ITMScript
Count bars since a cross
Count the bars since the close last crossed its average, restarting the count on each cross with scan.
Count the bars since the close last crossed its average, and start the count again on each cross.
//@itmscript 2
study("Bars since cross", overlay=false)
len = input.int(20, "Length", min=2, max=300)
limit = input.int(10, "Age limit", min=1, max=500)
avg = ta.sma(close, len)
cross = ta.crossover(close, avg) or ta.crossunder(close, avg)
age(acc, x) => nz(acc, -1) + 1
count = scan(close, na, age, reset=cross)
plot(count, "Bars since cross", color=count >= limit ? color.red : color.gray, width=1, style=columns)
hline(limit, "Limit", color=color.gray, style=dashed)What you see
Columns in their own pane show the age of the latest cross. The count is 0 on the bar of the cross and grows by one on each bar after it. A column is grey until the count reaches the age limit and red from then on. A dashed line marks the limit.
The count restarts on a cross in either direction. Before the first cross it runs from the first bar. The reset condition is read before the function runs, so the bar of the cross counts as 0.
Change these inputs
- Length. The window of the average, from 2 to 300 bars.
- Age limit. The count at which a column turns red, from 1 to 500 bars. It is also where the dashed line sits.