Search code examples
pine-scriptcandlestick-chartpine-script-v4candlesticks

pinescript v4 Do not enter if there are six green candles before entering the position


I'd like to make a code that won't entering the position in a situation like in the picture.

enter image description here

    greenCandle = barstate.isconfirmed and (close > open)
    
    sixGreenCandles = greenCandle[6] and greenCandle[5] and greenCandle[4] and greenCandle[3] and greenCandle[2] and greenCandle[1]

I don't know the code to count the candle before entering the position

(Except for the candles at the signal)


Solution

  • You can use the ta.barssince() function to figure out when the last red candle was. Then add a check whether this was less than 6 before the current bar. Use this condition together with your other buy conditions.

    //@version=5
    indicator("My script")
    
    red_candle = (close < open)
    since_last_red = ta.barssince(red_candle)
    can_buy = (since_last_red[1] < 6)
    
    plot(since_last_red)