Page 1 of 1

Check if condition is true in the last n bars

Posted: Thu Dec 24, 2020 11:32 am
by Fen1xTrading
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.

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

Posted: Mon Jan 11, 2021 5:49 pm
by kmarryat
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")

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

Posted: Fri Jan 15, 2021 1:21 am
by Matthew
^ 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 :)