Search code examples
signalspine-scriptalert

Prevent alert triggering on consecutive signal


I set up these two alerts:

alertcondition(bar_close > bar_open, 'BUY/LONG', 'BUY_ALERT')
alertcondition(bar_close < bar_open, 'SELL/SHORT', 'SELL_ALERT')

They work as a trigger on confirmed closed bars, but they trigger on each consecutive bar that's the same color. I wanted to change the code so they don't trigger if the previous color was the same as the current.

I found this answer and I copied what was shown in that answer and applied it to my script, so now my alerts look like this:

alertcondition(bar_close > bar_open and not bar_close > bar_open[1], 'BUY/LONG', 'BUY_ALERT')
alertcondition(bar_close < bar_open and not bar_close < bar_open[1], 'SELL/SHORT', 'SELL_ALERT')

The behavior is the same, with the alert still triggering on each consecutive bar that's the same color as the last.

I wondered if perhaps it's because it works on a confirming closed candle, so I changed those [1] to [2] but that doesn't work, the alert still triggers on each consecutive color:

bar_close > bar_open and not bar_close > bar_open[2]
bar_close < bar_open and not bar_close < bar_open[2]

I then tried adding those [1] to the end of each like this, but this also keeps the same behavior:

bar_close > bar_open and not bar_close[1] > bar_open[1]
bar_close < bar_open and not bar_close[1] < bar_open[1]

That only leaves one other thing to try, but again the behavior is the same with [2] there:

bar_close > bar_open and not bar_close[2] > bar_open[2]
bar_close < bar_open and not bar_close[2] < bar_open[2]

After trying all of the above I just couldn't get it to work.


Solution

  • Here is the answer, for Pine v5.

    // -----------------------------------------------------------
    // Code to stop repeating buy/sell signals...
    
    // Create variable that saves and doesn't calculate on each bar
    var pos = 0
    
    // Save that to a new number when long happens. Long can be 1
    if bar_close > bar_open and pos <= 0
        pos := 1
    // we save it again when short happens. Short can be -1
    if bar_close < bar_open and pos >= 0
        pos := -1
    
    // Check new change from another number to pos number this bar
    // Is pos equal to 1 and was it not equal to 1 one bar ago?
    longsignal = pos ==  1 and (pos !=  1)[1]
    shortsignal = pos == -1 and (pos != -1)[1]
    
    // -----------------------------------------------------------
    // Alerts
    alertcondition(longsignal, 'BUY/LONG', 'BUY_ALERT')
    alertcondition(shortsignal, 'SELL/SHORT', 'SELL_ALERT')