i didn't try this in a scan, but i think it will work. it works on a column and on a chart.
possible scan code , (not tested)
Code:
input avg1_len = 80;
input avg1_type = AverageType.EXPONENTIAL;
def ma1 = MovingAverage(avg1_type, close, avg1_len);
input barsback = 20;
plot abovexbars = ( Sum( (close > ma1), barsback ) == barsback );
a column study , that shows for how many bars, close has been above ema for x bars.
zclsaboveema1
http://tos.mx/3smi07W
Code:
# zclsaboveema1
# priceaboveEMA_xbars_01 - upper
def bn = barnumber();
input avg1_len = 80;
input avg1_type = AverageType.EXPONENTIAL;
def ma1 = MovingAverage(avg1_type, close, avg1_len);
input barsback = 20;
def abovexbars = ( Sum( (close > ma1), barsback ) == barsback );
def xbarscnt = if bn == 1 then 0 else if !abovexbars then 0 else if (abovexbars and !abovexbars[1] ) then 1 else if abovexbars then xbarscnt[1] + 1 else xbarscnt[1];
plot z = xbarscnt;
z.setdefaultcolor(color.dark_gray);
assignbackgroundcolor( if abovexbars then color.yellow else color.current);
#
a chart version for testing. draws a count of bar numbers when close is > ema. after x bars of being above, it draws yellow down arrows.
Code:
# priceaboveEMA_xbars_01
# https://usethinkscript.com/threads/scanning-for-price-above-ema-for-certain-number-of-price-bars.7000/
# How can I scan for the price bars closing above a certain EMA for a certain number of price bars in thinkorswim?
# EXAMPLE: scanning for price has closed above the 80 ema for 20 price bars.
#AddLabel(1, "stay above ema", Color.YELLOW);
# https://tlc.thinkorswim.com/center/reference/thinkScript/Constants/AverageType
# EXPONENTIAL
# HULL
# SIMPLE
# WEIGHTED
# WILDERS
# average line
def na = double.nan;
def bn = barnumber();
input avg1_len = 80;
input avg1_type = AverageType.EXPONENTIAL;
def ma1 = MovingAverage(avg1_type, close, avg1_len);
plot avg = ma1;
avg.SetDefaultColor(Color.cyan);
# plot down arrow when close > ema, for the past x bars
input barsback = 20;
def abovexbars = ( Sum( (close > ma1), barsback ) == barsback );
plot x = if abovexbars then high else na;
x.SetPaintingStrategy(PaintingStrategy.ARROW_down);
x.SetDefaultColor(Color.yellow);
# display bar counts
def clsabove = (close > ma1);
def cnt = if bn == 1 then 0 else if !clsabove then 0 else if (clsabove and !clsabove[1] ) then 1 else if clsabove then cnt[1] + 1 else cnt[1];
plot num = if (cnt >0) then cnt else na;
num.SetPaintingStrategy(PaintingStrategy.VALUES_below);
num.SetDefaultColor(Color.light_gray);
#