ta.alma in MQL5: Gaussian weights, offset and sigma

Short answer

MQL5 has no ALMA built-in. Compute a Gaussian weight table once, exp(-(j-m)^2/(2s^2)) with m = offset*(len-1) and s = len/sigma, then take a dot product over the last length values each bar, with the weight index running from the oldest bar of the window.

ta.alma(source, length, offset, sigma) is the Arnaud Legoux moving average: a weighted mean whose weights follow a Gaussian curve across the window, positioned by offset and widened or narrowed by sigma. MQL5 has no built-in for it. The equivalent is a weight table computed once from the three parameters and a dot product over the last length values on every bar. The only subtlety is pairing each weight with the right bar: the index runs from the oldest bar of the window, not from the current one.

What ta.alma computes

With j = 0 the oldest bar in the window and j = length - 1 the current bar:

m = offset * (length - 1)             // centre of the curve; 0.85 * 8 = 6.8 for length 9
s = length / sigma                    // width; 9 / 6 = 1.5
w[j] = exp(-(j - m)^2 / (2 * s^2))
alma = sum(src[length - 1 - j] * w[j]) / sum(w[j])

An offset of 1 puts the centre on the current bar (fast, little smoothing); 0 puts it on the oldest bar (smooth, lagging); the usual 0.85 sits near the recent end. A larger sigma makes the curve narrower, so fewer bars carry real weight. The result is na until length bars exist, and the weights do not depend on price, so they can be computed once. In Pine v3 the centre m was floored to an integer; from v4 it is not, and ta.alma has an optional fifth boolean argument, floor, to request the old behaviour. Since there is no recursion, history depth does not affect the values.

The MQL5 equivalent

//@version=6
indicator("ALMA", overlay = true)
len    = input.int(9, "Length")
offset = input.float(0.85, "Offset")
sigma  = input.float(6.0, "Sigma")
plot(ta.alma(close, len, offset, sigma), "ALMA")

A complete MQL5 indicator. The weights are built in OnInit because inputs cannot change while the indicator runs; OnCalculate only does the weighted sum. Note the index close[i - (InpLength - 1 - j)]: j = 0 reaches the oldest bar of the window:

//+------------------------------------------------------------------+
//| ta.alma(source, length, offset, sigma): Gaussian-weighted mean   |
//| centred at m = offset * (length - 1), width s = length / sigma   |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "ALMA (ta.alma)"

input int    InpLength = 9;     // length
input double InpOffset = 0.85;  // offset (0 = smooth, 1 = responsive)
input double InpSigma  = 6.0;   // sigma

double AlmaBuffer[];
double Weight[];                // weight[j], j = 0 is the OLDEST bar of the window
double WeightSum = 0.0;

int OnInit()
{
   SetIndexBuffer(0, AlmaBuffer, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength - 1);
   if(InpLength <= 0 || InpSigma == 0.0)
      return INIT_PARAMETERS_INCORRECT;
   ArrayResize(Weight, InpLength);
   const double m = InpOffset * (InpLength - 1);     // v4+: not floored
   const double s = InpLength / InpSigma;
   WeightSum = 0.0;
   for(int j = 0; j < InpLength; j++)
     {
      Weight[j] = MathExp(-((j - m) * (j - m)) / (2.0 * s * s));
      WeightSum += Weight[j];
     }
   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[])
{
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i < InpLength - 1)
        {
         AlmaBuffer[i] = EMPTY_VALUE;
         continue;
        }
      double sum = 0.0;
      for(int j = 0; j < InpLength; j++)              // j = 0 pairs with the oldest bar
         sum += close[i - (InpLength - 1 - j)] * Weight[j];
      AlmaBuffer[i] = sum / WeightSum;
     }
   return rates_total;
}

To reproduce a v3 script, floor m with MathFloor before computing the weights. Everything else stays the same.

Where the two differ

TopicPine ScriptMQL5
Native supportta.almaNone; weight table plus loop
Parameter typeslength int, offset and sigma float (simple in v6: they cannot vary per bar)int and double inputs; weights computed once in OnInit
CentreNot floored (v4+); floor = true restores v3Your choice; floor explicitly for v3 scripts
Weight directionj = 0 is the oldest barclose[i - (len - 1 - j)] oldest-first; close[len - 1 - j] after ArraySetAsSeries
sigma = 0Division by zero inside the formula gives naRuntime error; reject the parameter in OnInit
First barsna for length - 1 barsEMPTY_VALUE written by you

Because the weights are a fixed table, the ALMA is cheap: one multiply-add per bar in the window. It is also one of the easiest averages to verify after a conversion, since there is no seed, no state and no volume.

What the Stratlate converter emits

The engine maps ta.alma to pine_alma(close, __pineBar, (int)(len), (offset), (sigma)), and passes the fifth floor argument through when the script gives one. The runtime builds the Gaussian weights with m = offset * (length - 1) (floored only when asked), s = length / sigma, pairs weight j with the bar length - 1 - j bars back and divides by the weight sum; it returns na before length bars, when any value in the window is na, or when sigma is zero. The source must be a named series; a computed expression as the first argument is reported as unsupported for this call. The call itself is reported as exact, and the script above converts CLEAN. Compile and backtest the output and compare recent bars against TradingView.

Pitfalls

  • Weights applied in the wrong direction. Pairing w[0] with the current bar flips the curve: an offset of 0.85 then behaves like 0.15 and the line lags badly.
  • Flooring the centre for a v5 or v6 script. For length 9 and offset 0.85, m is 6.8, not 6. The floored version is visibly smoother. Floor only for v3 code or when the script passes floor = true.
  • Integer length / sigma. If both are ints in MQL5 the width truncates; keep sigma a double or cast.
  • Recomputing weights every bar. Harmless to the result but wasteful; the parameters are constant for the life of the indicator.
  • Forgetting the normalisation. Dividing by length instead of the weight sum scales the line away from price.

FAQ

Does MetaTrader 5 have an ALMA indicator?

Not as a standard indicator or an iMA mode. The implementation above is the whole thing: a weight table from length, offset and sigma, and a weighted sum per bar. Custom ALMA indicators exist in the Market and Code Base, but they vary on whether the centre is floored.

What do offset and sigma actually change?

offset moves the peak of the weight curve across the window: 1 weights the newest bar most, 0 the oldest. sigma controls the width: a larger sigma gives a narrower curve, so fewer bars matter. The defaults 0.85 and 6 give a responsive line with mild smoothing.

Why does a converted ALMA differ slightly from the TradingView one?

The usual causes are a floored centre (v3 behaviour), reversed weight order, or different candles. The ALMA has no seed and no state, so a difference that does not fade with more history is one of those three, not a warm-up effect.

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