In my script, I have both SL and TP calculations. When I change the slippage parameter in the strategy settings, the SL and TP levels are adapted accordingly. So far, so good.
But looking at the list of trades in the backtesting engine, I find that only the entry price has changed due to slippage but not the exit price. Thus, the backtest calculations are way too optimistic, of course.
This is how I calculate SL:
longPercStopPrice = 0.0
shortPercStopPrice = 0.0
if useSL
longPercStopPrice := strategy.position_avg_price * (1 - LossPerc)
shortPercStopPrice := strategy.position_avg_price * (1 + LossPerc)
else
longPercStopPrice := na
shortPercStopPrice := na
LongSLPrice = useSL ? longPercStopPrice : na
ShortSLPrice = useSL ? shortPercStopPrice : na
final_SL_Long := if use_SL_Percent
LongSLPrice
This is how I exit the trade using SL:
if longs_opened
strategy.exit(id='Exit SL', from_entry='Long', comment = CommentExitLong, stop=useSL ? final_SL_Long : na)
if shorts_opened
strategy.exit(id='Exit SL', from_entry='Short', comment = CommentExitShort, stop=useSL ? final_SL_Short : na)
This is how I calculate TP:
var float TPlongPrice = na
var float TPshortPrice = na
ProfitTrailPerc = input.float(title='TP %', minval=0.0, step=0.5, defval=5, inline="a", group='Exit Take Profit') * 0.01
TPlongPrice := use_TP_Percent ? strategy.position_avg_price * (1 + ProfitTrailPerc) : strategy.position_avg_price
TPshortPrice := use_TP_Percent ? strategy.position_avg_price * (1 - ProfitTrailPerc) : strategy.position_avg_price
This is how I exit the trade using TP:
var bool is_TP_reached = false
if FinalLongCondition or FinalShortCondition or strategy.position_size == 0
is_TP_reached := false
if longs_opened and ta.crossover(high, TPlongPrice) and use_TP_Percent and not is_TP_reached
is_TP_reached := true
strategy.close(id='Long', comment='L:Exit TP')
if shorts_opened and ta.crossunder(low, TPshortPrice) and use_TP_Percent and not is_TP_reached
is_TP_reached := true
strategy.close(id='Short', comment='S:Exit TP')
Your help is much appreciated!