Search code examples
pine-scripttrading

How to get the second occurrence of a condition on pine script


I have a strategy in tradingview that enters every time this condition is true, but I only need to enter the second occurrence of this condition

LongCondition = (wasOverSold and crossoverBull) and up_trend == false

enter image description here

the LongCondition gets true only on the exact candle where the blue cross appears (macd crossover), after that it is gets false all the time.

I already have tried using the history-referencing operator enter = LongCondition[1] ? true : false but it just delays the buy entry.

how can i find that second occurrence every time after an enter exit?


Solution

  • You can use a counter for that. Increase it when your condition becomes true, check if it is 2, enter position and reset your counter for next order.

    Here is an example that enters and exits position whenever a MACD cross takes place the second time.

    //@version=5
    strategy("My strategy", overlay=true, margin_long=100, margin_short=100)
    
    n = input.int(2, "Number of occurences")
    
    var bullCrossCnt = 0
    var bearCrossCnt = 0
    
    [macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9)
    
    bullCross = ta.crossover(macdLine, signalLine)
    bearCross = ta.crossunder(macdLine, signalLine)
    bullCrossCnt := bullCross ? bullCrossCnt + 1 : bullCrossCnt
    bearCrossCnt := bearCross ? bearCrossCnt + 1 : bearCrossCnt
    
    if (bullCross and bullCrossCnt == n)
        strategy.entry("Long", strategy.long)
        bullCrossCnt := 0  // Reset variable
    
    if (bearCross and bearCrossCnt == n)
        strategy.close("Long")
        bearCrossCnt := 0  // Reset variable
    

    enter image description here