'Check if crossover occurred in the period of last 10 candles

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?



Solution 1:[1]

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)

Solution 2:[2]

Or you can just use this condition:

if ta.valuewhen(crossover(sma20, sma50), bar_index, 0) <= 10

//do whatever it is you want to do after the if condition

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 e2e4
Solution 2 Suraj Rao