I'm trying to add a trigger for my percentage trailing stop and at the same time having an ATR stop, for the times when the trailing stop isn't triggered. Bear in mind, that I'm pretty new to coding.
The trigger for trailing is a fast MA above a slow MA and the initial stop an ATR stop. The type of trigger and initial stop isn't that important. The problem is that I can't figure out how to implement them at the same time. Can it be done as simple as I'm trying to here? The stops work on there own, but when used at the same time, it's only using the ATR stop (never trailing stop) and only when fast MA is below slow MA (trigger condition not met). When fast MA is above slow MA it never triggers a stop, but it works fine if I remove the else statement with the ATR stop. Doesn't make sense to me right now.
Some guidance would be much appreciated!
//Moving Average calculation and plotting
Not important
//ATR input
ATR = input(14, step=1, title='ATR periode')
LongstopMult = input(3, step=0.1, title='ATR Long Stop Multiplier')
//Trailing stop inputs
longTrailPerc = input(title="Trail Long Loss (%)",
type=float, minval=0.0, step=0.1, defval=4.6) * 0.01
// Determine trail stop loss prices
longStopPrice = 0.0
longStopPrice := if (strategy.position_size > 0)
stopValue = close * (1 - longTrailPerc)
max(stopValue, longStopPrice[1])
else
0
//Strategy entry conditions
XXX
// Submit exit orders for trail stop loss price
if (fastSMMA > slowSMMAlong)
strategy.exit(id="XL TRL STP1", stop=longStopPrice)
else
stop_level = low - (ATR * LongstopMult)
strategy.exit("TP/SL", stop=stop_level)
You can switch the longStopPrice value and use only 1 strategy.exit function as shown below.
fastSMMA = sma(close, 20)
slowSMMAlong = sma(close, 200)
//ATR input
ATR = input(14, step=1, title='ATR periode')
LongstopMult = input(3, step=0.1, title='ATR Long Stop Multiplier')
//Trailing stop inputs
longTrailPerc = input(title="Trail Long Loss (%)",
type=float, minval=0.0, step=0.1, defval=4.6) * 0.01
// Determine trail stop loss prices
longStopPrice = 0.0
if fastSMMA > slowSMMAlong
longStopPrice := if (strategy.position_size > 0)
stopValue = close * (1 - longTrailPerc)
max(stopValue, longStopPrice[1])
else
0
else
longStopPrice := low - (ATR * LongstopMult)
// debug
bgcolor(fastSMMA > slowSMMAlong ? red : na) // highlight the type of trigger
plot(longStopPrice, style = stepline, offset = 1) // print the exit line on the chart
//Strategy entry conditions // example entry
strategy.entry("enter long", true, 1, when = open > high[20])
// Submit exit orders for trail stop loss price
strategy.exit(id="XL TRL STP1", stop=longStopPrice)