# valueWhen_convert_01
input nth_previous_condition = 3;
input show_vertical_lines_on_condition = yes;
def bn = barnumber();
def na = double.nan;
def lastbarbn = HighestAll(If(IsNaN(close), 0, bn));
def lastbar = if (bn == lastbarbn) then 1 else 0;
#=================================
#=================================
# test data , condition is when 2 emas cross
input avg1_len = 10;
input avg1_type = AverageType.simple;
def ma1 = MovingAverage(avg1_type, close, avg1_len);
input avg2_len = 80;
input avg2_type = AverageType.simple;
def ma2 = MovingAverage(avg2_type, close, avg2_len);
input show_ma_lines = yes;
plot z1 = if show_ma_lines then ma1 else na;
z1.setdefaultcolor(color.cyan);
plot z2 = if show_ma_lines then ma2 else na;
z2.setdefaultcolor(color.yellow);
def ma_cross = if ma1 crosses ma2 then 1 else 0;
plot x1 = if ma_cross then min(min(z1,z2),low)*0.997 else na;
x1.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
x1.SetDefaultColor(Color.cyan);
x1.setlineweight(3);
x1.hidebubble();
#=================================
#=================================
def cond1 = ma_cross;
# count conditions, create reverse count
def cntx = if bn == 1 then 0 else if cond1 then cntx[1] + 1 else cntx[1];
def cntx_max = highestall(cntx);
def revcntx = if cond1 then cntx_max - cntx + 1 else cntx_max - cntx + 0;
# --------------------------------
# check if desired condition number is valid
def prevnum = if nth_previous_condition > cntx_max then cntx_max else if nth_previous_condition < 1 then 1 else nth_previous_condition;
addlabel(1, "find the nth previous condition " + prevnum, color.yellow);
# --------------------------------
# find offset to desired condition
def t = GetMaxValueOffset(( if revcntx == prevnum then revcntx else 0) , 400);
def cond_cls = getvalue(close, t);
addlabel(1, "close of signal, " + t + " bars back " + cond_cls, color.yellow);
# vertical lines around condition bar
def x = if (revcntx[0] == prevnum and revcntx[-1] <> prevnum ) then 1 else 0;
# vertical lines around desired condition
addverticalline(show_vertical_lines_on_condition and (x or x[1]), "-", color.cyan);
# --------------------------------
# test stuff
input test1_cond_counts = no;
addchartbubble(test1_cond_counts, low*0.998,
cntx + "\n" +
revcntx
, color.cyan, no);
input test2_cond_bubbles = no;
addchartbubble(test2_cond_bubbles and cond1, high,
bn + "\n" +
cntx + "\n" +
revcntx
, color.cyan, yes);
input test3_cond_cls = no;
addchartbubble(test3_cond_cls, low*0.998,
t + "\n" +
cond_cls
, color.yellow, no);
#