# period_bar_counter_template_00
#---------------------------------------
def na = double.nan;
def bn = barnumber();
#---------------------------------------
# test signals , 2 averages
# template_buy_sell_avgs_cross
# buy sell signals based on averages crossing
def price = close;
input ma1_len = 9;
input ma1_type = AverageType.EXPONENTIAL;
def ma1 = MovingAverage(ma1_type, price, ma1_len);
input ma2_len = 21;
input ma2_type = AverageType.EXPONENTIAL;
def ma2 = MovingAverage(ma2_type, price, ma2_len);
input show_ma1_line = yes;
plot z1 = if show_ma1_line then ma1 else na;
z1.setdefaultcolor(getcolor(1));
#z1.setlineweight(1);
z1.hidebubble();
input show_ma2_line = no;
plot z2 = if show_ma2_line then ma2 else na;
z2.setdefaultcolor(getcolor(2));
#z2.setlineweight(1);
z2.hidebubble();
#---------------------------------------
# conditions , start , stop
def start_pricexupma1 = (close crosses above ma1);
def stop_pricexdwnma1 = (close crosses below ma1);
#def start_ma1xup = (ma1 crosses above ma2);
#def stop_ma1xdwn = (ma1 crosses below ma2);
# time periods
def priceabovema1 = (close > ma1);
#def ma1above = (ma1 > ma2);
# count bars during each time period , priceabovema1. reset count on each new period.
def barcnt = if bn == 1 then 0
else if stop_pricexdwnma1 then 0
else if start_pricexupma1 then 1
else if priceabovema1 then barcnt[1] + 1
else barcnt[1];
# count bars during all the time periods
def totalcnt = if bn == 1 then 0
else if priceabovema1 then totalcnt[1] + 1
else totalcnt[1];
# count quantity of time periods
def qty = if bn == 1 then 0
else if start_pricexupma1 then qty[1] + 1
else qty[1];
def avg = round(totalcnt / qty, 2);
addchartbubble(1, low*0.997,
barcnt + " cnt\n" +
totalcnt + " ttl\n" +
qty + " qty\n" +
avg + " avg"
, (if barcnt > 0 then color.yellow else color.gray), no);
#