ta.ema in MQL5: iMA MODE_EMA, seeding and the first bars

Short answer

Use iMA with MODE_EMA for a price source, or the recursion ema = alpha * source + (1 - alpha) * ema_prev with alpha = 2 / (length + 1). The formula is the same on both platforms; visible differences come from where the recursion starts.

ta.ema(source, length) is the exponential moving average with smoothing constant alpha = 2 / (length + 1). In MQL5 the equivalent is iMA with MODE_EMA for a price source, or the one-line recursion ema = alpha * source + (1 - alpha) * ema_prev seeded with the first source value. The formula is the same on both platforms; the differences that show up on a chart come from where the recursion starts.

What ta.ema computes

On the first bar where source is not na, the EMA equals source. On every later bar, ema = alpha * source + (1 - alpha) * ema[1] with alpha = 2 / (length + 1). For length = 20 that is 0.0952. A bar whose source is na leaves the previous EMA in place rather than resetting it. Unlike ta.rma, there is no SMA seed and no na warm-up period: the plot starts on the first bar of the chart.

Because each value carries a fraction of every earlier value, the EMA on bar n depends on how many bars precede it. The weight of the starting value decays as (1 - alpha)^n, so after about five times length bars it is below one percent and the start no longer matters in practice. That is the number to remember when two charts disagree on the left edge.

The MQL5 equivalent

//@version=6
indicator("EMA", overlay = true)
len = input.int(20, "Length")
plot(ta.ema(close, len), "EMA")

A complete MQL5 indicator that reproduces the recursion. The arrays are oldest-first, so bar 0 is the first bar of history and seeds the average:

//+------------------------------------------------------------------+
//| ta.ema(source, length): alpha = 2 / (length + 1), seeded with    |
//| the first source value                                           |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "EMA (ta.ema)"

input int InpLength = 20;   // length

double EmaBuffer[];

int OnInit()
{
   SetIndexBuffer(0, EmaBuffer, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   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[])
{
   if(InpLength <= 0)
      return 0;
   const double alpha = 2.0 / (InpLength + 1.0);   // 2.0, not 2: int division gives 0
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i == 0)
         EmaBuffer[i] = close[i];                   // Pine seeds with the first value
      else
         EmaBuffer[i] = alpha * close[i] + (1.0 - alpha) * EmaBuffer[i - 1];
     }
   return rates_total;
}

With a price source you can hand the work to the terminal instead. Replace the loop with a handle and CopyBuffer:

// OnInit
maHandle = iMA(_Symbol, _Period, InpLength, 0, MODE_EMA, PRICE_CLOSE);

// OnCalculate
int toCopy = prev_calculated == 0 ? rates_total : rates_total - prev_calculated + 1;
if(CopyBuffer(maHandle, 0, 0, toCopy, EmaBuffer) <= 0)
   return 0;

The built-in uses the same 2 / (length + 1) constant and also starts from the first available price, so once both charts have the same candles and enough history the lines coincide.

Where the two differ

TopicPine ScriptMQL5
SeedFirst non-na source valueHand-written: whatever you write on bar 0; iMA: the first price of the loaded history
History depthDepends on plan and symbol; the EMA is computed from TradingView's first barDepends on the broker's data and "Max bars in chart"; the EMA is computed from MT5's first bar
na in the sourceSkipped; previous EMA keptYou decide: test for EMPTY_VALUE and carry EmaBuffer[i - 1]
Realtime barRecomputed each tick from ema[1], which is the closed barSame if you read EmaBuffer[i - 1]; a static double prev updated per tick compounds the update
Smoothing constant2 / (length + 1) is a float2 / (InpLength + 1) with an int input is 0; write 2.0
Non-price sourceAny seriesLoop over a buffer; iMA only takes applied prices

Since alpha and the recursion are identical, a hand-written EMA and iMA MODE_EMA on the same chart agree to floating-point precision on every bar. The remaining difference against TradingView is therefore almost always the start of the history or the candles themselves, not the code.

What the Stratlate converter emits

The engine treats ta.ema as a stateful call: each call site gets its own state array (__st0, __st1, …) sized to rates_total, and the emitted line is pine_ema(close, __st0, __pineBar, (int)(len)). The runtime seeds with the first non-na value, keeps the prior EMA when the source is na, and always reads the previous bar's slot, so a recomputed realtime bar does not compound. A computed source with no array behind it goes through pine_ema_step(value, state, …), which carries the same recursion from a single value per bar. The call is reported as exact, and the Pine script above converts CLEAN. Compile and backtest the output and compare recent bars, not the first ones.

Pitfalls

  • Integer division. 2 / (InpLength + 1) evaluates to 0 and the EMA becomes a flat copy of the seed. Use 2.0.
  • Keeping the previous EMA in a static variable. Every tick of the forming bar applies the update again, so the line drifts towards price within the bar and jumps at the open of the next. Store the state per bar and read [i - 1].
  • Judging by the first bars. A difference that shrinks to the right is the seed, not a bug. Compare after five to ten times length bars.
  • Seeding with an SMA. That is ta.rma's rule, not ta.ema's. Seeding the EMA with an SMA of the first length values changes early values and delays the plot by length - 1 bars.
  • Recomputing from bar 0 on every tick. Correct but slow on long histories. Start at prev_calculated - 1.

FAQ

Is iMA with MODE_EMA the same as ta.ema?

Same constant, same recursion, same seed rule (the first price). Given identical candles and the same amount of history the values coincide. In practice the two platforms start their history on different bars, so early values differ and converge later.

How much history does an EMA need before it matches TradingView?

The influence of the starting value decays as (1 - alpha) to the power of the bar count. After five times the length it is under one percent, after ten times it is negligible. Load at least that many bars before the range you compare.

Why does my EMA move within the current bar on MT5 but look stable on TradingView?

Both move: TradingView's realtime bar also recalculates on each tick with the current close. If your MT5 line moves more, you are probably compounding the update per tick instead of recomputing the bar from the previous bar's stored value.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related