Build an EMA Distance Percentage Indicator in MT4 with MQL4

Beginner Trading Tutorial | MetaTrader 4 | Custom indicator

A moving average is often plotted directly over price, making it easy to see whether a market is above or below its average. But the chart does not immediately tell you whether the separation is large or small relative to the instrument's price. A two-dollar gap is substantial for a stock trading at $20 and much less significant for one trading at $200. A percentage-based distance indicator makes that distinction explicit.

This tutorial builds a separate-window MQL4 indicator that measures the signed percentage difference between the closing price and its exponential moving average (EMA). Rather than guessing from the visual gap on a zoomed chart, the trader can read a consistent numerical value. We also provide a setting that hides the developing candle so the display can focus on completed observations.

From a price difference to a percentage

The exponential moving average assigns greater weight to recent prices. Its conventional smoothing factor is 2 / (N + 1), where N is the averaging period. The platform's built-in EMA implementation supplies the moving average, so our indicator does not need to recreate the recursive smoothing calculation.

Distance (%) = 100 × (Close − EMA) / EMA. A positive result means the close is above the EMA; a negative result means it is below. Zero means they coincide. Dividing by the EMA, rather than by the close, expresses the difference as a percentage of the reference average. This choice should stay consistent when comparing observations.

Build an EMA Distance Percentage Indicator in MT4 with MQL4
Figure 1. Hypothetical closes of 102, 100 and 98 against an EMA of 100 produce distances of +2%, 0% and −2%.
Close EMA Raw difference Distance
102 100 2 +2.00%
100 100 0 0.00%
98 100 −2 −2.00%
51 50 1 +2.00%
204 200 4 +2.00%

All examples use hypothetical prices. The last two rows illustrate why percentages are useful: different nominal prices and absolute gaps can represent the same relative separation. The result is not a return since entry, nor a forecast of the size of the next move. It simply measures the location of a close relative to a moving reference.

What the indicator actually displays

The separate panel contains one blue line and a horizontal zero reference. When the line is above zero, the bar's close exceeds its EMA; below zero, it is beneath the EMA. The height of the line represents the percentage difference, not the number of points, ticks or pips. The Data Window shows the numeric value to two decimal places, while the calculation retains full double precision.

The indicator deliberately does not color a high reading as a sell signal or a low reading as a buy signal. Both trend-following and mean-reversion research can use distance, but these approaches attach different interpretations to the same observation. Keeping the calculation independent of any order rule helps users evaluate the feature without implicitly assuming a trading strategy.

Complete MQL4 source code

// PatternSmart EMA Distance Percent - MetaTrader 4
#property strict
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 clrRoyalBlue
#property indicator_width1 2
#property indicator_level1 0.0
#property indicator_levelcolor clrSilver

input int EmaPeriod = 20;
input bool ClosedBarsOnly = true;
double Distance[];

int OnInit()
{
   if(EmaPeriod < 1)
      return(INIT_PARAMETERS_INCORRECT);

   if(!SetIndexBuffer(0, Distance))
      return(INIT_FAILED);

   ArraySetAsSeries(Distance, true);
   SetIndexStyle(0, DRAW_LINE);
   SetIndexLabel(0, "EMA distance (%)");
   SetIndexEmptyValue(0, EMPTY_VALUE);
   SetIndexDrawBegin(0, EmaPeriod - 1);
   IndicatorDigits(2);
   IndicatorShortName("EMA Distance % (" +
                      IntegerToString(EmaPeriod) + ")");
   return(INIT_SUCCEEDED);
}

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[])
{
   ArraySetAsSeries(close, true);
   if(prev_calculated <= 0 || prev_calculated > rates_total)
      ArrayInitialize(Distance, EMPTY_VALUE);

   if(rates_total < EmaPeriod)
      return(0);

   // Largest valid shift with enough history.
   int oldest = rates_total - EmaPeriod;
   int start = oldest;
   if(prev_calculated > 0 && prev_calculated <= rates_total)
      start = MathMin(oldest, rates_total - prev_calculated + 1);

   // Recalculate the latest closed bar and live bar.
   for(int i = start; i >= 0; i--)
   {
      Distance[i] = EMPTY_VALUE;
      if(ClosedBarsOnly && i == 0)
         continue;

      double ema = iMA(NULL, 0, EmaPeriod, 0,
                       MODE_EMA, PRICE_CLOSE, i);

      // Reject invalid denominators and unavailable prices.
      if(!MathIsValidNumber(ema) || ema <= 0.0 ||
         !MathIsValidNumber(close[i]) || close[i] <= 0.0)
         continue;

      Distance[i] = 100.0 * (close[i] - ema) / ema;
   }
   return(rates_total);
}

How the buffer and calculation work

OnInit binds the dynamic Distance array to indicator buffer zero. In MQL4, a buffer is managed by the terminal after binding. Setting its series indexing after SetIndexBuffer makes shift zero correspond to the newest bar. OnCalculate similarly sets the close array's indexing explicitly. Matching these directions is essential: the close and EMA must refer to the same historical shift.

The call to iMA retrieves the EMA directly as a numeric value in MT4. Its arguments select the current symbol and chart timeframe, the user-defined period, zero visual displacement, exponential smoothing, closing prices and the current loop shift. This is not the MT5 handle-and-CopyBuffer interface.

On the first calculation or after a history reset, the code initializes the buffer to EMPTY_VALUE and computes all bars with sufficient history. Subsequent updates use prev_calculated to limit the loop to recent bars, including the most recent completed bar. Returning rates_total lets the platform supply the previous calculation count on the next event. The initial history cutoff prevents plotting readings before there are enough available bars for the selected period. EMA values may still depend on the amount of history used to initialize the platform's calculation.

Settings and trade-offs

Input Default Interpretation
EmaPeriod 20 Number of bars used for the EMA
ClosedBarsOnly true Hide the developing bar at shift zero

A shorter period, such as 10, makes the EMA more responsive to price changes. A longer period, such as 50, reacts more slowly and may produce larger persistent distances in trending markets. Neither setting is universally better. Comparing the same symbol and timeframe with several periods is a useful way to observe how the reference changes.

ClosedBarsOnly defaults to true because a developing candle can move above and below the average repeatedly. In this mode the most recent plotted observation is shift one. Turning the setting off displays shift zero, which changes as the current closing price and EMA update. This is normal live behavior rather than future-data leakage. Historical values can nevertheless change if the broker revises its data or loads more history.

Installation in MetaTrader 4

  1. Open MT4 and select File → Open Data Folder.
  2. Open MQL4/Indicators and create a file named PS_EMADistancePercent.mq4 in MetaEditor.
  3. Paste the complete source and compile it. Review any compiler diagnostics rather than ignoring them.
  4. Refresh the Navigator or restart the terminal, then attach the indicator to a chart.
  5. Add the built-in EMA with the same period, zero shift and Close price for comparison. Open the Data Window and compare values on completed bars.

This example uses the current chart's symbol and timeframe. Switching the chart timeframe changes the input bars and therefore the EMA and distance. A 20-period EMA on a five-minute chart is not equivalent to a 20-period EMA on a daily chart.

A practical verification routine

Start with a liquid instrument and a chart containing more than 20 bars. For a selected completed bar, read its close and the reference EMA from the Data Window. Calculate the percentage manually and compare it with the custom indicator. Allow for rounding in displayed prices. Repeat with a bar above the EMA, one below it, and a bar close to zero. Switch ClosedBarsOnly off and confirm that the developing bar appears; switch it back on and verify that only the current bar is hidden. Change EmaPeriod and confirm that both the built-in reference and distance respond consistently.

Check a symbol with limited history as well. Empty values should not be interpreted as zero-distance readings. If the reference EMA is unavailable or nonpositive, the indicator leaves the output empty to avoid division by zero or inappropriate percentage calculations. It is intended for instruments with positive prices.

Research limitations

Percentage normalization helps compare different price levels, but it does not normalize volatility. A 2% separation may be unusual in one instrument and routine in another. A large distance can persist during a trend rather than predicting immediate reversion. Spread, trading costs and execution risk are not captured by this feature. Consider volatility, market regime and liquidity independently before incorporating it into a trading model.

Interested in extending this free indicator with alerts, volatility-adjusted bands or an EA integration? Contact us through our Custom Trading Software Development Services.

The example was reviewed against MQL4 documentation but has not been compiled or run in MT4. Test it on your own installation before relying on it. Trading involves risk; no indicator guarantees performance.

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.