I have very simple SMA based strategy which is as follows:
//@version=5
//Initialization
strategy(title='SMA', shorttitle='SMA', overlay=true, initial_capital=100, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
//Inputs
src = input(close)
len = input(20, title='SMA Length')
smoothening = input.int(2, minval=1, maxval=10, title='1 = No Smoothing')
//Indicator
sma = ta.sma(src, len)
out = request.security(syminfo.tickerid, timeframe.period, sma)
//Strategy
ma_up = out >= out[smoothening]
ma_down = out < out[smoothening]
//Plot
col = ma_up ? color.lime : ma_down ? color.red : color.aqua
plot(out, title='Multi-Timeframe Moving Avg', style=plot.style_line, linewidth=4, color=col)
//Backtest
if ma_up
strategy.close('S', comment = "EXIT_SHORT")
strategy.entry('L', strategy.long, comment = "ENTER_LONG")
if ma_down
strategy.close('L', comment = "EXIT_LONG")
strategy.entry('S', strategy.short, comment = "ENTER_SHORT")
Now after implementing this strategy, I am getting quite an interesting result where the plotline seems to be correct but the entry and exits of the trades are occurring after a slight delay
That is, if we were to remove the bars then the offset becomes clearer
However, the ideal should be entries and exits at the point at which the plotline changes color like in the following picture
How can I eliminate this delay between the plotline transitions and the trade entries/exits so that they can be in sync? Any help would be greatly appreciated 🙏
Add process_orders_on_close=true in the strategy function
strategy(title='SMA', shorttitle='SMA', overlay=true, initial_capital=100, default_qty_type=strategy.percent_of_equity, default_qty_value=100, process_orders_on_close=true)