'How to implement a Super trend crossover

I am new to pine script. I am trying to create strategy with below condition.

  • if current price is greater than supertrend(5,1) and current price is greater than 20 EMA then "BUY"
  • if current price is less than supertrend(5,1) and current price is less than 20 EMA then "SELL".

In order to avoid the continuous buy sell signal I have included the code from the link How do I stop multiple BUY/SELL signals from printing in a row? (Pine, Script, Trading, View, PineScript, TradingView)

Now the signal is not working correctly. once the buy signal is reversed I am not getting sell signal (vice versa). Below is my code

//@version=5

indicator('EMA 1 min', shorttitle='EMA 1 min', overlay=true)
ema = ta.ema(close, 20)
[supertrend,direction] = ta.supertrend(5,1)
// Base condition
longentry = (close > supertrend) and (close > ema)
shortentry = (close < supertrend) and (close < ema)


// we create a variable that "saves" and doesn't calc on each bar 
var pos = 0

// we save it to a new number when long happens. Long can be 1 
if longentry and pos <= 0
    pos := 1
// we save it again when short happens. Short can be -1 
if shortentry and pos >= 0 
    pos := -1

// here we check if we have a newly detected change from another number to our 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]


plot(ema)

plotshape(longsignal, style=shape.triangleup, color=color.new(color.green, 0), text='BUY', editable=false, location=location.belowbar, size=size.small)
plotshape(shortsignal, style=shape.triangledown, color=color.new(color.black, 0), text='SELL', editable=false, location=location.abovebar, size=size.small)

See the below image where the signal is not reversing.

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source