I am trying to backtest a "Long" strategy in tradingview using trailing stops. For example I want to be able to open a long with a 2% target above price, a stop loss of 1% below price, and a trailing stop activation of 1% once it reaches the 2% target price. Please help, thanks very much.
So far I've managed to backtest with fixed Targets (% above price) and Fixed stops (% below price).
tp_inp = input(2, title='Take Profit %', type=float,step=.1)/100
sl_inp = input(1, title='Stop Loss %', type=float,step=.1)/100
trail_inp = input(1, title='Trailing %', type=float,step=.1)/100
stop_level = strategy.position_avg_price * (1 - sl_inp)
take_level = strategy.position_avg_price * (1 + tp_inp)
trail_level = strategy.position_avg_price * (1 - trail_inp)
strategy.entry("Long", true, when = buysignal == 1)
strategy.exit("Exit","Long", stop=stop_level, trail_price=take_level, trail_offset=trail_level)
I just can't wrap around my head to get the trailing stop work in the backtest. I am just able to do it with fixed stops.