I have a trailing stop loss and take profit that works when in a long position, however I’m unsure how to adapt it when the strategy is shorting. Here’s my code so far:
bullish = tk_cross_bull and cs_cross_bull and price_above_kumo and ta.crossover(lower, close)
bearish = tk_cross_bear and cs_cross_bear and price_below_kumo and ta.crossover(close,lower)
// Configure trail stop level with input options
longTrailPerc = input.float(title='Trail Long Loss (%)', minval=0.0, step=0.1, defval=5) * 0.01
shortTrailPerc = input.float(title='Trail Short Loss (%)', minval=0.0, step=0.1, defval=5) * 0.01
// Determine trail stop loss prices
longStopPrice = 0.0
shortStopPrice = 0.0
longStopPrice := if strategy.position_size > 0
stopValue = close * (1 - longTrailPerc)
math.max(stopValue, longStopPrice[1])
else
0
shortStopPrice := if strategy.position_size < 0
stopValue = close * (1 + shortTrailPerc)
math.min(stopValue, shortStopPrice[1])
else
999999
strategy.entry('Short', strategy.short, when=bearish and short_entry and timePeriod)
//strategy.exit('Exit', stop = longStopPrice, limit = shortStopPrice)
//strategy.close('Short', when=bullish and not long_entry)
if (bullish and timePeriod)
strategy.exit(id='Exit', limit = shortStopPrice)
>Solution :
You already calculate your short stop loss price which seems to be correct. Then use this value in your strategy.exit() call.
strategy.entry('Short', strategy.short, when=bearish and short_entry and timePeriod)
if (strategy.position_size < 0)
strategy.exit("Short Exit", "Short", stop=shortStopPrice