Fen1xTrading
Pine Script Rookie
Pine Script Rookie
Posts: 2
Joined: December 24th, 2020
Contact: TradingView Profile

Check if condition is true in the last n bars

Hi everyone i'm actually programming a really simple script that plots 1 column if close > BollingerBandBasis

Actually is working for all bars.
Now i just want to start plotting columns only if i get 20 consecutive close > BBbasis

How should i code this condition?

Thanks in advance.

kmarryat
Pine Script Rookie
Pine Script Rookie
Posts: 20
Joined: December 21st, 2020
Contact: TradingView Profile

Re: Check if condition is true in the last n bars

There's probably a better way to do it but I would use a for loop to count the times the condition was true in the past 20 bars , then check to see if it was true 20 times. Something like this.

Code: Select all

// Count candles above Boolinger Bands Basis
barsAboveBBbasis = 0

for i = 0 to 19
    if close[i] > BollingerBandBasis[i]
        barsAboveBBbasis := barsAboveBBbasis + 1

bgcolor(barsAboveBBbasis == 20 ? color.green : na , transp=80, title="Past 20 Bars Above BBbasis")

You could also check for the opposite condition using barssince:

Code: Select all

barsAboveBBbasis = barssince(close <= BoolingerBandsBasis)
bgcolor(barsAboveBBbasis >= 20 ? color.green : na , transp=80, title="Past 20 Bars Above BBbasis")
You could also use sum to accomplish this

Code: Select all

barAboveBBbasis = close > BollingerBandBasis
barsAboveBBbasis = sum(barAboveBBbasis ? 1 : 0, 20) == 20
bgcolor(barsAboveBBbasis ? color.green : na , transp=80, title="Past 20 Bars Above BBbasis")

User avatar
Matthew
Site Admin
Site Admin
Posts: 92
Joined: July 1st, 2020
Location: Australia
Contact: Website Facebook Twitter TradingView Profile

Re: Check if condition is true in the last n bars

^ this is a great solution! As kmarryat said, maybe there's a better way to do it but my personal philosophy in coding is don't try to fix something that isn't broken (unless you're certain you've found a better way to do it haha)

If it works, it works! Give it a try and let us know how you go :)

Return to “Pine Script Q&A”