'Trailing stop loss at previous bar low / high after target profit reached
I have a working strategy with SL at the recent swing low (for longs) and profit target at RR 1:2. I've been struggling for few days to find a way to add a trailing stop loss, so that once the profit target is reached, the strategy does not exit the position, but starts trailing stop loss at previous bar low (for longs).
I've tried modifying Stepped trailing strategy example by adolgov on TradingView for my case, although with no luck as it uses a predefined stop loss size, while in my case it differs for each entry.
Below current code with dummy entry logic - would be super grateful if somebody has an idea how I can add this trailing last bar low stop.
// Trading parameters for SL and TP
var float TP = na
var float SL = na
var bool LS = na
var bool SS = na
LookBackPeriod = 15
//Stop Loss and take profit criteria
longstoploss = ta.lowest(low, LookBackPeriod)
shortstoploss = ta.highest(high, LookBackPeriod)
RR = 2
longtakeprofit = close + RR * (close - longstoploss)
shorttakeprofit = close - RR * (shortstoploss - close)
// Buy & sell conditions
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
// Set TP and SL
if (longCondition and strategy.position_size == 0) or (shortCondition and strategy.position_size == 0)
SL := longCondition ? longstoploss : shortstoploss
TP := longCondition ? longtakeprofit : shorttakeprofit
// Current trade direction
LS := longCondition or strategy.position_size > 0
SS := shortCondition or strategy.position_size < 0
// Buy
strategy.entry("Long entry", strategy.long, when = longCondition and not SS)
strategy.exit ("Long exit", from_entry="Long entry", stop=SL, limit=TP)
// Sell
strategy.entry("Short entry", strategy.short, when = shortCondition and not LS)
strategy.exit ("Short exit", from_entry="Short entry", stop=SL, limit=TP)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
