How to account for Exponential MA movement in backtesting strategy?



New member
I have put together a strategy that relies on fast (5 period) exponential moving averages. The problem I'm running into in backtesting is that many times the moving average changes so much throughout a candle that, after the candle is fully formed, it triggers a buy/sell signal that would not have been possible if actively trading the strategy. This is because the price never actually hit the MA in real time, but, for example, the high of the candle is greater than the exponential MA after the candle is formed only because the CLOSE of the candle was far below the EMA (dragging the EMA down long after the high was formed). I hope this makes sense.

Anyone know how to fully account for this error in backtesting? I've tried using the following, and it works most of the time, but it would only work perfectly for an SMA, rather than an EMA.

def maoffsetl = (high - close) / EMALength;
def maoffsets = (close - low) / EMALength;

AddOrder(OrderType.SELL_TO_CLOSE, high[-1] >= EMA[-1] + maoffsetl[-1], EMA[-1], name = "Profit", tickcolor = Color.DARK_GREEN, arrowcolor = Color.DARK_GREEN);

AddOrder(OrderType.BUY_TO_CLOSE, low[-1] <= EMA[-1] - maoffsets[-1], EMA[-1], name = "Profit", tickcolor = Color.DARK_GREEN, arrowcolor = Color.DARK_GREEN);
Thanks in advance for any help!

Similar threads