"hello this strategy that takes profit when ATR bands from trade entry either upper or lower band is crossed, it works but sometimes tp or sl is skipped or position randomly closed."
This what happen when runs somewhat correct [1]:https://i.sstatic.net/Ek8GF.png
this what happens when completely wrong [2]: https://i.sstatic.net/xDWR9.png [3]: https://i.sstatic.net/wpS8A.png [4]: https://i.sstatic.net/JvSXV.png
//@version=5
strategy("2Ma cross ATR Bands strategy", overlay = true)
// Inputs
atrPeriod = input(3, "ATR Period")
srcUpper = input(defval = close, title = "Source Upper")
srcLower = input(defval = close, title = "Source Lower")
atrMultiplierUpper = input(title = "ATR Multiplier Upper", defval = 4.0, tooltip ="3.8" )
atrMultiplierLower = input(title = "ATR Multiplier Lower", defval = 3.0, tooltip = "2.5")
// ATR
atr = ta.atr(atrPeriod)
// Plotting
plot(srcUpper + atr * atrMultiplierUpper, color = color.green)
plot(srcLower - atr * atrMultiplierLower, color = color.red)
plot(ta.sma(close,10))
// Entry condition
buysign= ta.crossover(close, ta.sma(close,10))
// Trading session
// session = input.session("0200-1600", "Session")
// t = time(timeframe.period, session)
// bgcolor(time == t ? color.rgb(76, 175, 79, 80) : na)
// Define take profit and stop loss
tp = srcUpper + atr * atrMultiplierUpper
sl = srcLower - atr * atrMultiplierLower
//place trade
if buysign
strategy.entry("long", strategy.long)
//exit trade
if buysign
strategy.exit("TP/SL", stop = sl, limit = tp)
With
atr = ta.atr(atrPeriod)
you are always updating the value of atr.
If you look closely, your exits use the last atr value and not the one at the time of entry.
You need to use a var
variable to store the atr value at the entry and then use it for your exits.
You can do something like this:
var float atr_at_entry = na
is_new_position = ((strategy.position_size[1] == 0) and (strategy.position_size !=0)) // Assuming you only go long
atr_at_entry := is_new_position ? atr : atr_at_entry // Store the atr value if it is a new position. Otherwise, keep its old value
And then later use atr_at_entry
in your TP and SL calculations.