How Old Is this Bull Run Getting? Check MA Test Bars Since
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradeStation
//@version=4
//MA test bars since plots how many bars since price touched or crossed a given moving. It's color coded green (last price above MA) or red (last price under MA)

//MA types are:
// 1 - simple
// 2 - exponential
// 3 - Hull
// 4 - weighted
// 5 - volume weighted

study(title="MA test bars since")
length = input(50, minval=1, title="Length")
src = input(close, title="Source")
matype = input(1, minval=1, maxval=5, title="AvgType")

simplema = sma(src,length)
exponentialma = ema(src,length)
hullma = wma(2*wma(src, length/2)-wma(src, length), round(sqrt(length)))
weightedma = wma(src, length)
volweightedma = vwma(src, length)

avgval = matype==1 ? simplema : matype==2 ? exponentialma : matype==3 ? hullma : matype==4 ? weightedma : matype==5 ? volweightedma : na

var counter = 0
var Pcolor = color.gray

// this counts bars
if (( low>avgval ) or (high < avgval ))
    counter := counter + 1

// these next expressions set counter to 0 because the condition has been met
// this detects price touching but not crossing
if (( high > avgval) and (low< avgval) )
    counter :=0
// these detects price gapping under
if ((close<avgval) and (close[1]>avgval[1]))
    counter :=0
// these detects price gapping above
if ((close>avgval) and (close[1]<avgval[1]))
    counter :=0

// set the line color based on above/below MA
if ( close<avgval)
    Pcolor := color.red
if ( close>avgval)
    Pcolor := color.green

plot(counter, color=Pcolor, style=plot.style_histogram, linewidth=3)