ta.wma in MQL5: iMA MODE_LWMA and the weight order

Short answer

Use iMA with MODE_LWMA, or for a non-price source sum(src[k] * (len - k)) / (len * (len + 1) / 2), with the newest value weighted most. It has no memory, so the platforms agree on every bar with a full window.

ta.wma(source, length) is the linearly weighted moving average: the newest value counts length times, the one before it length - 1 times, down to 1 for the oldest, and the sum is divided by the sum of the weights. MQL5 has it natively as iMA with MODE_LWMA, and it is a six-line loop when the source is not a price. Like the SMA it has no memory, so there is nothing to seed and the two platforms agree on every bar with a full window.

What ta.wma computes

With source[k] the value k bars ago, wma = sum(source[k] * (length - k), k = 0 … length - 1) / (length * (length + 1) / 2). The denominator is just 1 + 2 + … + length; for length = 20 it is 210. The result is na until length bars exist and na on a bar whose own source is na. The weights make the WMA lag about a third as much as an SMA of the same length, which is why it is the building block of ta.hma.

The weight order is the thing to get right. "Weight k for the value k bars back" is reversed: it gives the oldest bar the largest weight and produces a line that lags more than the SMA. Pine's definition gives the largest weight to the current bar.

The MQL5 equivalent

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

A complete MQL5 indicator with oldest-first arrays. close[i - k] is the value k bars before bar i, and it is multiplied by InpLength - k, so the current bar gets the full weight:

//+------------------------------------------------------------------+
//| ta.wma(source, length): linear weights, newest bar weighted most |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "WMA (ta.wma)"

input int InpLength = 20;   // length

double WmaBuffer[];

int OnInit()
{
   SetIndexBuffer(0, WmaBuffer, 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;
   const double norm = InpLength * (InpLength + 1) / 2.0;   // 1 + 2 + ... + length
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i < InpLength - 1)
        {
         WmaBuffer[i] = EMPTY_VALUE;
         continue;
        }
      double sum = 0.0;
      for(int k = 0; k < InpLength; k++)
         sum += close[i - k] * (InpLength - k);     // weight length for the newest bar, 1 for the oldest
      WmaBuffer[i] = sum / norm;
     }
   return rates_total;
}

With a price source, iMA does the same:

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

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

MetaTrader's LWMA uses exactly these linear weights, so the native handle and the loop give the same number. The loop is the one to use for a computed series, for the inner stages of a Hull average, or when the WMA length is itself a series that changes per bar, which iMA cannot do without a new handle.

Where the two differ

TopicPine ScriptMQL5
First barsna for length - 1 barsEMPTY_VALUE written by you; iMA's values before the first full window are not na; skip them
Weight directionCurrent bar has weight lengthSame with close[i - k] * (length - k) oldest-first, or close[k] * (length - k) after ArraySetAsSeries
DenominatorImplicitlength * (length + 1) / 2; compute it as a double, 20 * 21 / 2 is fine as an int but divide the sum as a double
Variable lengthSeries int allowedLoop only; an iMA handle has a fixed period
na in the windowA na source on the current bar gives naTest for EMPTY_VALUE yourself when the source is a buffer
SourceAny seriesiMA: applied prices; loop: any buffer

What the Stratlate converter emits

The engine does not use iMA. ta.wma is a windowed call and becomes pine_wma(close, __pineBar, (int)(len)); a computed source without an array behind it is recorded into a per-call-site window array and read back through pine_wma_step. The runtime returns na before length bars and when the current source value is na; a na inside the window at an older slot is filled with the preceding finite value rather than making the whole result na. The mapping is reported as exact, and the test script above converts CLEAN. ta.hma is built on the same helper. Compile and backtest the output and compare recent bars against TradingView.

Pitfalls

  • Reversed weights. close[i - k] * (k + 1) weights the oldest bar most. The symptom is a line that lags behind the SMA instead of leading it.
  • Integer denominator in integer division. If sum is accumulated in an int or the division is written as (int)sum / (len * (len + 1) / 2) the result is truncated. Keep the sum and denominator as doubles.
  • Index out of range on early bars. close[i - k] with i < length - 1 reads before the array start. Guard, as the indicator above does.
  • Mixing series and non-series arrays. After ArraySetAsSeries(close, true) the weight expression must become close[k]; the buffer must be set as series too or the line is mirrored.
  • Different candles. As with every average, a constant offset of a spread between the platforms is the data, not the formula.

FAQ

Is iMA MODE_LWMA identical to ta.wma?

Yes, for an applied-price source: both apply linear weights with the newest bar weighted most and divide by the sum of the weights. There is no recursion, so history depth does not matter, and only the first length - 1 bars differ (0.0 in MT5 versus na in Pine).

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

Write the series into a buffer each bar and run the loop above over that buffer instead of close. That is also how the Hull moving average is built: two WMAs of price, their difference stored in a buffer, and a third WMA of that buffer.

Why does the WMA react faster than the SMA with the same length?

Its effective lag is (length - 1) / 3 bars against (length - 1) / 2 for the SMA because recent values carry more weight. That is expected, not a sign that the weights are wrong; a WMA slower than the SMA is the sign of reversed weights.

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