I am working on a strategy that requires me to check if there was a certain crossover few candles back in time when I get my signal on current candle close.
Right now I am basically creating 10 variables for each candle, because I want to check back 10 candles and see if crossover happened (any kind of crossover works for this example).
This works, but leads to a bit of a messy and verbose code, so I was wondering if I can somehow create a "one liner" solution to check this for the whole period?
This might help
//@version=4
study("Sma cross during last n candles", overlay=true)
sma20 = sma(close, 20)
sma50 = sma(close, 50)
plot(sma20)
plot(sma50)
cross = cross(sma20, sma50)
// Highligh cross on the chart
bgcolor(cross ? color.red : na)
// Function looking for a happened condition during lookback period
f_somethingHappened(_cond, _lookback) =>
bool _crossed = false
for i = 1 to _lookback
if _cond[i]
_crossed := true
_crossed
// The function could be called multiple times on different conditions, that should reduce the code
crossed10 = f_somethingHappened(cross, 10)
// Highligh background if cross happened during last 10 bars
bgcolor(crossed10 ? color.green : na)