Friday, September 11, 2015

How to properly check if 2 MAs (or any 2 indicator buffers) have just intersected

When building an EA, it is a very common thing to check if a faster MA has just crossed above or below a slower MA.
In other cases, you may be interested to know if the main line of an oscillator has crossed above or below its signal line. In other cases, there are different buffers and you just want to know if they crossed and take a certain action as a result to that.

Here's an example with 2 MAs:

int candleIdx=0;
double fasterMA = iMA(Symbol(), Period(), 50, 0, MODE_EMA, PRICE_CLOSE,candleIdx);
double slowerMA = iMA(Symbol(), Period(), 100, 0, MODE_EMA, PRICE_CLOSE,candleIdx);

Above we have selected the values of the 50 EMA and 100 EMA on the current symbol, current timeframe, at the most recent candle (index=0).
However, we cannot just check whether the faster MA is above the slower MA and determine that the trend has changed bullish based on that. Perhaps the faster MA has been above the slower MA for a long time already. We also need to know where the faster MA was one candle back, relative to the slower MA. If it was below, and now it's above, there's a bullish cross right there. 

So here's the MQL4 code for selecting the values of the MAs for the previous candles:

int candleIdx=0;
double fasterMA = iMA(Symbol(), Period(), 50, 0, MODE_EMA, PRICE_CLOSE,candleIdx+1);
double slowerMA = iMA(Symbol(), Period(), 100, 0, MODE_EMA, PRICE_CLOSE,candleIdx+1);

Now you just need to make the checks and perform the right action in case of a MA crossover.

if (fasterMA>slowerMA && fasterMA_lastBar<=slowerMA_lastBar){
// bullish crossover - do something
}
if (fasterMA<slowerMA && fasterMA_lastBar>=slowerMA_lastBar){
// bearish crossover - do something
}

Additional notes:
- if you want the crossover to be confirmed by the end of the candle (no "repainting" such to speak), then you need to look at the candles with indexes 1 and 2 instead of 0 and 1 - so initializing the candleIdx with value 1 will do just that
- this kind of verification can be applied on any 2 indicator buffers to check the trigger for opening or  closing an opened order

Don't hesitate to send me suggestions for topics you want covered.
Keep on learning MT4 programming, you're doing great!

Nick.

No comments:

Post a Comment