MT5 Confirmed EMA Crossover Indicator: Complete MQL5 Arrow Signals Using iMA and CopyBuffer

MetaTrader 5 indicator tutorial. A moving-average crossover can be visually simple but programmatically tricky. This tutorial builds a two-buffer MQL5 custom indicator that draws an up arrow only when a completed candle's fast EMA crosses above the slow EMA, and a down arrow for the opposite event. It does not trade or promise profitability.

What a confirmed EMA crossover actually means

An exponential moving average emphasizes newer closing prices. For period N, its smoothing multiplier is α = 2/(N+1); the recursive update is EMA(t) = α × Close(t) + (1−α) × EMA(t−1). The initial seed depends on the platform's implementation. A bullish cross occurs when fast EMA(t) > slow EMA(t) while fast EMA(t−1) ≤ slow EMA(t−1). A bearish cross reverses the inequalities. Here t is the most recent closed bar, not the still-forming candle.

Default inputs are 12 and 26 EMA periods, with arrow placement 30 symbol points beyond the bar high/low. A point is not necessarily a pip or tick; the visual offset will vary by instrument.

MT5 Confirmed EMA Crossover Indicator: Complete MQL5 Arrow Signals Using iMA and CopyBuffer
Conceptual illustration: blue fast EMA crosses green slow EMA; the arrow represents a confirmed signal after the bar closes. The diagram is schematic, not a backtest.

Why MT5 uses handles and CopyBuffer

Unlike MQL4's older direct-value iMA pattern, MQL5 iMA() returns an indicator handle. CopyBuffer() then retrieves its calculated values. This example checks BarsCalculated() and requires a full successful copy before comparing two completed bars. Arrays use series indexing: 0 is the live candle, 1 the latest completed candle, and 2 the preceding completed candle.

Complete MQL5 source code

Save as ConfirmedEMACrossArrows.mq5 under MQL5/Indicators and compile in MetaEditor.

//+------------------------------------------------------------------+ //| Confirmed EMA Crossover Arrows for MetaTrader 5                  | //| Educational custom indicator; signals only on closed candles.  | //+------------------------------------------------------------------+ #property copyright "PatternSmart educational example" #property version   "1.00" #property indicator_chart_window #property indicator_buffers 2 #property indicator_plots   2 #property indicator_label1  "Bullish EMA Cross" #property indicator_type1   DRAW_ARROW #property indicator_color1  clrLimeGreen #property indicator_width1  2 #property indicator_label2  "Bearish EMA Cross" #property indicator_type2   DRAW_ARROW #property indicator_color2  clrTomato #property indicator_width2  2
input int FastEMAPeriod = 12; input int SlowEMAPeriod = 26; input int ArrowOffsetPoints = 30;
double BullBuffer[]; double BearBuffer[]; int FastHandle = INVALID_HANDLE; int SlowHandle = INVALID_HANDLE;
int OnInit() {    if(FastEMAPeriod < 1 || SlowEMAPeriod < 2 ||       FastEMAPeriod >= SlowEMAPeriod || ArrowOffsetPoints < 0)    {       Print("Invalid parameters: require 1 <= fast < slow and offset >= 0.");       return INIT_PARAMETERS_INCORRECT;    }
   SetIndexBuffer(0, BullBuffer, INDICATOR_DATA);    SetIndexBuffer(1, BearBuffer, INDICATOR_DATA);    ArraySetAsSeries(BullBuffer, true);    ArraySetAsSeries(BearBuffer, true);    PlotIndexSetInteger(0, PLOT_ARROW, 233);    PlotIndexSetInteger(1, PLOT_ARROW, 234);    PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);    PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);    PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, SlowEMAPeriod + 1);    PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, SlowEMAPeriod + 1);
   FastHandle = iMA(_Symbol, PERIOD_CURRENT, FastEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);    SlowHandle = iMA(_Symbol, PERIOD_CURRENT, SlowEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);    if(FastHandle == INVALID_HANDLE || SlowHandle == INVALID_HANDLE)    {       Print("Could not create EMA handles. Error: ", GetLastError());       return INIT_FAILED;    }    IndicatorSetString(INDICATOR_SHORTNAME, "Confirmed EMA Cross (" +                       IntegerToString(FastEMAPeriod) + "," +                       IntegerToString(SlowEMAPeriod) + ")");    return INIT_SUCCEEDED; }
void OnDeinit(const int reason) {    if(FastHandle != INVALID_HANDLE) IndicatorRelease(FastHandle);    if(SlowHandle != INVALID_HANDLE) IndicatorRelease(SlowHandle); }
int OnCalculate(const int rates_total, const int prev_calculated,                 const datetime &time[], const double &open[],                 const double &high[], const double &low[],                 const double &close[], const long &tick_volume[],                 const long &volume[], const int &spread[]) {    if(rates_total < SlowEMAPeriod + 3) return 0;    if(BarsCalculated(FastHandle) < rates_total ||       BarsCalculated(SlowHandle) < rates_total) return prev_calculated;
   double fast[], slow[];    ArraySetAsSeries(fast, true);    ArraySetAsSeries(slow, true);    if(CopyBuffer(FastHandle, 0, 0, rates_total, fast) != rates_total ||       CopyBuffer(SlowHandle, 0, 0, rates_total, slow) != rates_total)       return prev_calculated;
   ArraySetAsSeries(high, true);    ArraySetAsSeries(low, true);    BullBuffer[0] = EMPTY_VALUE; // current, unfinished bar is never signaled    BearBuffer[0] = EMPTY_VALUE;
   int oldest = rates_total - SlowEMAPeriod - 2;    int start = (prev_calculated == 0) ? oldest : MathMin(oldest, 2);    for(int i = start; i >= 1; --i)    {       BullBuffer[i] = EMPTY_VALUE;       BearBuffer[i] = EMPTY_VALUE;       if(fast[i] == EMPTY_VALUE || slow[i] == EMPTY_VALUE ||          fast[i+1] == EMPTY_VALUE || slow[i+1] == EMPTY_VALUE)          continue;       bool bullish = (fast[i] > slow[i] && fast[i+1] <= slow[i+1]);       bool bearish = (fast[i] < slow[i] && fast[i+1] >= slow[i+1]);       if(bullish) BullBuffer[i] = low[i] - ArrowOffsetPoints * _Point;       if(bearish) BearBuffer[i] = high[i] + ArrowOffsetPoints * _Point;    }    return rates_total; }

Signal logic and numerical example

Bar Fast EMA Slow EMA Interpretation
Previous completed (index 2) 1.0840 1.0843 Fast is below slow
Latest completed (index 1) 1.0851 1.0848 Fast moves above slow: bullish cross
Current forming (index 0) Changing Changing Excluded from signal calculation

These numbers are hypothetical and illustrate the comparison, not real EUR/USD prices or verified trading performance. For the bearish condition, reverse the two comparisons.

Installation and validation

  1. Open MetaTrader 5 → File → Open Data Folder → MQL5 → Indicators.
  2. Create ConfirmedEMACrossArrows.mq5, paste the complete source, then compile in MetaEditor.
  3. Attach it to a chart with enough history for the slow EMA and review the Journal for handle or data-loading errors.
  4. Compare arrow timestamps with a separately plotted 12/26 EMA pair, checking the crossover only after a candle has closed.
  5. Test different symbols, timeframes, price gaps, history reloads, and arrow offsets. Verify arrows do not appear on index 0.

Limits and common implementation mistakes

Crossovers are lagging, and sideways markets can produce repeated whipsaws. Confirmed-bar logic avoids intrabar signal flicker but does not prevent future losses, price gaps, or changes caused by corrected historical data. The code intentionally does not send orders, manage stops, or include trading costs. Do not confuse points with pips. In MQL5, failing to check CopyBuffer(), treating a handle as an EMA value, or mixing series and chronological array indexing can silently misplace signals. The full-history copy is easy to audit but may be less efficient on extremely large charts; production code can copy only the changed window with careful indexing.

Extending the concept responsibly

Potential extensions include a minimum EMA separation, an ATR-based volatility filter, trend confirmation from a higher timeframe, and alerts triggered once per closed bar. Each additional filter should be tested out of sample rather than optimized solely for historical profit. For tailored indicators or platform integrations, see Custom Trading Software Development Services.

Risk disclosure: This is educational software, not investment advice. Indicator signals can fail, and leveraged trading can cause substantial losses. Verify code in your own MT5 installation and use appropriate risk limits before any live deployment. This source has not been compiled or backtested in a live MT5 terminal during this publication workflow.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.