Zac Vaughn
Zac Vaughn

Reputation: 7

How do I stop multiple BUY/SELL signals from printing in a row?

I am trying to achieve a few things with my script...

  1. I only want to print a "BUY" signal if the previous signal was "SELL" (and vice-versa)
  2. I only want to print a "BUY" signal if it is less than the previous "SELL" signal. (and vice-versa)

I have been trying to find a solution to this issue all day. I don't understand how I can use "valuewhen" or "barssince" to achieve this.

//Long
emalong = out1 > out2
macdlong = macd > signal and ((macd[1] < signal[1]) or (macd[2] < 
    signal[2]))
psarlong = psar < close and ((psar[1] > close[1]) or (psar[2] > 
    close[2]))

//Short
emashort = out1 < out2
macdshort = macd < signal and ((macd[1] > signal[1]) or (macd[2] 
    > signal[2]))
psarshort = psar > close and ((psar[1] < close[1]) or (psar[2] < 
    close[2]))

//Collect
longentry = emalong and macdlong and psarlong
shortentry = emashort and macdshort and psarshort

//Plot
plotshape(longentry, style=shape.circle, color=#26a69a, text="⬆", 
    textcolor=#ffffff, location=location.belowbar, 
    size=size.tiny)
plotshape(shortentry, style=shape.circle, color=#ef5350, 
    text="⬇", textcolor=#ffffff, location=location.abovebar, 
    size=size.tiny)

Upvotes: 0

Views: 3157

Answers (1)

Bjorgum
Bjorgum

Reputation: 2310

For this to occur we need to create a variable that wont recalculate on each bar. "var" lets us do this as it will hold whatever value we give it at run time. We can then conditionally assign it a new variable. In this case we will use your long and short signals to assign the number to 1 or -1 for a long or a short. I have included notes below:

// we create a variable that "saves" and doesnt 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 detetected 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
// we change our plot shape to coincide with the change detection 
plotshape(longsignal,  style=shape.circle, color=#26a69a, text="⬆", textcolor=#ffffff, location=location.belowbar, size=size.tiny)
plotshape(shortsignal, style=shape.circle, color=#ef5350, text="⬇", textcolor=#ffffff, location=location.abovebar, size=size.tiny)

in this sense we could even create an exit variable where our position goes to zero. We would have to make an exit condition and assign our pos to 0 in the same manner.

Cheers and best of luck in your coding and trading

Upvotes: 2

Related Questions