# hull_avg_cross_00b
#https://usethinkscript.com/threads/how-to-hold-a-value-for-few-candles.15158/
#how to hold a value for few candles.
#rengagopal 4/12
#long,
#close crosses above hullmovingavg(close,16)
# calculate the average price by (close / short buyprice) / short hold count.
#count number of candles,
#while close > hullmovingavg(close,16)
#short,
#close crosses below hullmovingavg(close,16)
# calculate the average price by (close / long buyprice) / long hold count.
# count bars while close < hull
def na = Double.NaN;
def bn = BarNumber();
def avg1_price = close;
input avg1_len = 16;
#input avg1_type = AverageType.EXPONENTIAL;
input avg1_type = AverageType.hull;
def ma1 = MovingAverage(avg1_type, avg1_price, avg1_len);
plot z1 = ma1;
z1.SetDefaultColor(Color.CYAN);
z1.HideBubble();
def dir;
def longpr;
def longcnt;
def shortpr;
def shortcnt;
def diffavg;
def avg;
if bn == 1 then {
dir = 0;
longpr = 0;
longcnt = 0;
shortpr = 0;
shortcnt = 0;
avg = 0;
diffavg = 0;
} else if close crosses above ma1 then {
dir = 1;
longpr = close;
longcnt = 1;
shortpr = 0;
shortcnt = 0;
avg = close;
diffavg = 0;
} else if close crosses below ma1 then {
dir = -1;
longpr = 0;
longcnt = 0;
shortpr = close;
shortcnt = 1;
avg = close;
diffavg = 0;
} else if dir[1] > 0 then {
dir = dir[1];
longpr = longpr[1];
longcnt = longcnt[1] + 1;
shortpr = 0;
shortcnt = 0;
avg = (fold j1 = 0 to longcnt
with q1
do q1 + getvalue(close,j1)) / longcnt;
diffavg = (fold i1 = 0 to longcnt
with p1
do p1 + (getvalue(close,i1) - getvalue(longpr,i1))) / longcnt;
} else if dir[1] < 0 then {
dir = dir[1];
longpr = 0;
longcnt = 0;;
shortpr = shortpr[1];
shortcnt = shortcnt[1] + 1;
avg = (fold j2 = 0 to shortcnt
with q2
do q2 + getvalue(close,j2)) / shortcnt;
diffavg = (fold i2 = 0 to shortcnt
with p2
do p2 + (getvalue(close,i2) - getvalue(shortpr,i2))) / shortcnt;
} else {
dir = 0;
longpr = longpr[1];
longcnt = longcnt[1];
shortpr = shortpr[1];
shortcnt = shortcnt[1];
avg = 0;
diffavg = 0;
}
def ravg = round(avg,2);
def rdiffavg = round(diffavg,2);
input avg_bubble = yes;
addchartbubble(avg_bubble, low*0.999,
ravg
, (if dir > 0 then color.green else if dir < 0 then color.red else color.gray), no);
input diffavg_bubble = no;
addchartbubble(diffavg_bubble, low*0.999,
rdiffavg
, (if dir > 0 then color.green else if dir < 0 then color.red else color.gray), no);
input test1 = no;
addchartbubble(test1, low*0.999,
dir + "\n" +
close + "\n" +
longpr + "\n" +
longcnt + "\n" +
shortpr + "\n" +
shortcnt + "\n" +
ravg + "\n" +
rdiffavg
, (if dir > 0 then color.green else if dir < 0 then color.red else color.gray), no);
#