Check if crossover occurred in the period of last 10 candles in tradingview pinescript

Category > OTHERS || Published on : Sunday, December 13, 2020 || Views: 171 || Check if crossover occurred in the period of last 10 candles tradingview pinescript


Here Pawan Kumar will explain how to Check if crossover occurred in the period of last 10 candles in tradingview pinescript

//@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)