Hey Gaz! Welcome to the forum mate :)
What you're trying to achieve is definitely possible, I've done it with a couple of my scripts.
The easiest way I've found to do it is using "var" variables which are persistent across all the bars on your chart.
So some pseudo-code would look something like this:
Code: Select all
//@version=4
study(title="Stops & Targets", overlay=true)
// Detect long setup and get ATR
longSignal = close > open
atr = atr(14)
// Declare trade variables (eg. for longs)
var stopLossPrice = 0.0
var targetPrice = 0.0
var inLongTrade = false
// Declare trade management variables
stoppedOut = false
targetHit = false
initiatedLong = false
// Check if we have a valid long setup
if longSignal and not inLongTrade and not na(atr)
stopLossPrice := low - atr
targetPrice := close + atr
inLongTrade := true
initiatedLong := true
// Check if long stop has been hit
if inLongTrade and low <= stopLossPrice
stoppedOut := true
inLongTrade := false
// Check if long target has been hit
if inLongTrade and high >= targetPrice
targetHit := true
inLongTrade := false
// Draw stops & targets
plot(inLongTrade ? stopLossPrice : na, color=color.red, style=plot.style_linebr, title="Stop Loss")
plot(inLongTrade ? targetPrice : na, color=color.green, style=plot.style_linebr, title="Target")
// Trigger alerts
alertcondition(initiatedLong, title="Long trade was placed", message="Opened new long position")
alertcondition(stoppedOut, title="Long trade was stopped out", message="Stop loss hit for {{ticker}}")
alertcondition(targetHit, title="Long target was hit", message="Take profit hit for {{ticker}}")
That's how I usually store my stop loss & targets for trade management alerts and drawing onto the chart and whatnot.
Obviously it's not perfect as it doesn't account for spread etc., but it's the best we can do with Pine. You could add in a fixed spread amount to the entry price / SL / target checks if your broker uses a fixed spread, otherwise there's nothing that can be done about that.
I hope that helps man, unfortunately I don't have time to dive deep into your script but let me know if you have any further questions. I'll try to record a YouTube video on this subject when I get a spare couple of hours :)
Good luck with your coding!