ta.sma in MQL5: iMA MODE_SMA or a windowed mean

Short answer

Use iMA with MODE_SMA for a price source, or the sum of the last length values divided by length for anything else. The SMA has no memory, so both platforms agree on every bar once the window is full.

ta.sma(source, length) is the arithmetic mean of the last length values of a series. In MQL5 the same number comes from iMA with MODE_SMA when the source is one of the applied prices, and from a short loop over the last length elements of an array when it is anything else. There is no seeding question: the SMA has no memory, so both platforms agree on every bar once the window is full.

What ta.sma computes

On bar i (bar_index counting), the value is (source[0] + source[1] + … + source[length-1]) / length, where source[k] is the value k bars ago. Until length bars exist the result is na, so the first length - 1 bars of the chart have no value. If a value inside the window is na, the mean is na on that bar too; the window is not shortened. length must be a positive integer, and in v6 it may change from bar to bar.

Because there is no recursion, the value on a given bar depends only on that bar and the length - 1 before it. A chart with 500 bars of history and a chart with 50,000 give identical SMAs for the bars they share. This is what makes the SMA the easiest average to verify after a conversion.

The MQL5 equivalent

Pine first. One input, one plot:

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

The MQL5 indicator below is a complete program that compiles as shown. It keeps the OnCalculate arrays in their default oldest-first order, so close[i - k] is the value k bars before bar i, and it writes EMPTY_VALUE where Pine has na:

//+------------------------------------------------------------------+
//| ta.sma(source, length) as a plain windowed mean                  |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "SMA (ta.sma)"

input int InpLength = 20;   // length

double SmaBuffer[];

int OnInit()
{
   SetIndexBuffer(0, SmaBuffer, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength - 1);
   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;
   // arrays are oldest-first here: index 0 is the first bar of history
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i < InpLength - 1)          // Pine: na until `length` bars exist
        {
         SmaBuffer[i] = EMPTY_VALUE;
         continue;
        }
      double sum = 0.0;
      for(int k = 0; k < InpLength; k++)
         sum += close[i - k];
      SmaBuffer[i] = sum / InpLength;
     }
   return rates_total;
}

When the source is a plain price, the native indicator does the same work without the loop. Create the handle once in OnInit and copy from buffer 0 in OnCalculate:

int maHandle = INVALID_HANDLE;

int OnInit()
{
   SetIndexBuffer(0, SmaBuffer, INDICATOR_DATA);
   maHandle = iMA(_Symbol, _Period, InpLength, 0, MODE_SMA, PRICE_CLOSE);
   return maHandle == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED;
}

// in OnCalculate: copy everything that is new, oldest-first like the buffer
int toCopy = prev_calculated == 0 ? rates_total : rates_total - prev_calculated + 1;
if(CopyBuffer(maHandle, 0, 0, toCopy, SmaBuffer) <= 0)
   return 0;   // data not ready yet, try again on the next tick

The two produce the same values. Choose the loop when the source is computed (a difference of two series, hlc3 times a factor, an RSI) or when you want the indicator to be a single self-contained file; choose iMA when the source is an applied price and you prefer to let the terminal cache the result.

Where the two differ

TopicPine ScriptMQL5
Missing valuesna on the first length - 1 barsEMPTY_VALUE written by you; iMA's values on those bars are not na; skip them
Index directionsource[1] is the previous barclose[i - 1] with oldest-first arrays; close[1] only after ArraySetAsSeries
SourceAny series, including computed onesiMA accepts applied prices only; a computed source needs the loop or a two-step iMA on a custom buffer via iCustom
ShiftDone with offset in plot() or [1] on the resultThe fourth iMA argument (ma_shift) moves the line sideways
Realtime barRecomputed on every tick with the current closeSame, as long as the loop starts at prev_calculated - 1 so the forming bar is redone
Integer length from inputinput.intinput int; divide by (double)length or write sum / InpLength with a double sum to avoid integer division

What the Stratlate converter emits

The Pine to MQL5 engine does not map ta.sma to iMA. It emits a call to its runtime helper pine_sma(src, bar, length), a windowed mean that returns na until length bars exist and na when any value inside the window is na, which is the Pine behaviour. When the source is a computed expression with no array behind it, the engine records the per-bar value into a window array of its own and calls pine_sma_step on it, so the result is identical to a named series. Both forms are reported as exact; the test script above converts CLEAN. Compile and backtest the output, and compare recent bars against TradingView.

Pitfalls

  • Averaging over the whole array when i < length - 1. close[i - k] with a negative index raises "array out of range" and the indicator stops drawing. Guard the first bars.
  • Mixing index directions. Calling ArraySetAsSeries(close, true) on one array and not the buffer makes the line appear mirrored or flat. Either set every array as series or none.
  • Trusting iMA on bar 0 to length - 2. There is no average yet, and the buffer does not hold a missing-value marker you can test like na. Skip the first length bars or a crossover test fires on garbage.
  • Copying one value per tick. CopyBuffer(handle, 0, 0, 1, …) fills only the newest slot; history stays empty after a timeframe switch. Copy rates_total values on the first call.
  • Different candles. The SMA can only match if the closes match. MT5 charts are usually bid-based; TradingView's depend on the selected feed. A constant offset of a spread or so is data, not code.

FAQ

Is iMA with MODE_SMA exactly ta.sma?

Yes, for an applied-price source and the same candles. The formula is the same windowed mean, and because there is no recursion the amount of loaded history does not matter. The only visible difference is the first length - 1 bars, where Pine returns na and iMA has no meaningful value.

How do I apply ta.sma to a computed series in MQL5?

Write the value into a buffer each bar and run the windowed loop over that buffer, as the complete indicator above does with close. Alternatively, publish the computed series as its own indicator and feed it to iMA through an iCustom handle; the loop is simpler and avoids a second file.

Why is my converted SMA shifted by one bar?

Usually one side is reading the previous bar: close[1] in Pine is close[i - 1] in an oldest-first MQL5 array, but close[i + 1] when the array has been set as series. Check which direction each array uses before comparing values.

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