pine-scripttrailing

How to "Fix" the ATR trailing stop in Pine Script


I would love your help.

I'm coding a trading strategy that goes **long** on the break of a 40-day high, and closes that long position when a trailing stop is hit. That trailing stop is 3*ATR which begins under the low of the entry candle and trails upwards.

My current problem is that I don't know how to 'fix' the ATR level when it trails up, to stop it going back down when the price goes down. Currently, when the price goes down, *the trailing stop also goes down with it*, meaning the stop is never hit! (please see the black lines on the uploaded image)

Screenshot of current plots

Do you know how I could code this so the trailing stop moves higher when the price goes higher, *but stays fixed when the price goes down* so the stop level can be hit to close the position?

Many thanks in advance for your help - Dave.

//@version=5 

strategy("Donchian Breakout - Trading",overlay=true, initial_capital=100000,currency=currency.GBP)

//Inputs
DonchHighLength=input.int(title="DonchHighLength",defval=20,step=10)
DonchLowLength=input.int(title="DonchLowLength",defval=20,step=10)
ATRLength=input.int(title="ATRLength", defval=20, step=1)
ATRx=input.int(title="ATRMultiple", defval=4, step=1)

//Variables
DonchHigh=ta.highest(close[1],DonchHighLength)
DonchLow=ta.lowest(close[1],DonchLowLength)
ATR=ta.atr(ATRLength)
ATRLongStop=low-(ATR*ATRx)
ATRShortStop=high+(ATR*ATRx)

//Plot
plot(DonchHigh,"Long", color.green)
plot(DonchLow,"Short", color.red)
plot(ATRLongStop, "LongStop", color.black)
plot(ATRShortStop, "ShortStop", color.black)

//Entry
EnterLong=close>DonchHigh  
EnterShort=close<DonchLow 

// Calculate position size
RiskEquity=0.02*strategy.equity
RiskPerTrade=EnterLong?((strategy.position_avg_price-ATRLongStop)*syminfo.pointvalue):((ATRShortStop-strategy.position_avg_price)*syminfo.pointvalue)
PosSize=RiskEquity/RiskPerTrade

//Entry orders
if strategy.position_size==0
    if EnterLong 
        strategy.entry("Long",strategy.long,qty=PosSize)
    
if strategy.position_size==0
    if EnterShort 
        strategy.entry("Short",strategy.short,qty=PosSize)

//Close strategy.position_size

strategy.close(id="Long", when=close<ATRLongStop[1])
strategy.close(id="Short", when=close>ATRShortStop[1])

Solution

  • You should record your ATRLongStop value and modify your strategy.close only if the new Stop Loss value is greater than the actual one.

    var StopLoss = 0.0
    if strategy.position_size==0
        if EnterLong 
            strategy.entry("Long",strategy.long,qty=PosSize)
            StopLoss := 0.0
    if ATRLongStop[1] > StopLoss
        StopLoss := ATRLongStop[1]
        strategy.close(id="Long", when=close<ATRLongStop[1])