ta.hma in MQL5: Hull average from three weighted MAs

Short answer

MQL5 has no Hull average. Compute wma(2*wma(src, len/2) - wma(src, len), round(sqrt(len))), storing the inner difference in a calculation buffer. iMA MODE_LWMA can supply the two inner averages for a price source; the outer one needs your own loop.

ta.hma(source, length) is Alan Hull's moving average: a weighted average of the difference between a half-length WMA doubled and a full-length WMA, smoothed again over round(sqrt(length)) bars. MQL5 has no function for it. The equivalent is three linear weighted averages, with the intermediate difference stored in a calculation buffer so the outer WMA has a series to read. iMA MODE_LWMA can supply the two inner averages for a price source, but the outer one always needs your own loop.

What ta.hma computes

Written out in Pine terms:

half = length / 2                    // integer division: 16 / 2 = 8, 9 / 2 = 4
rt   = math.round(math.sqrt(length)) // 16 -> 4, 14 -> 4, 9 -> 3
diff = 2 * ta.wma(src, half) - ta.wma(src, length)
hma  = ta.wma(diff, rt)

Two details are easy to get wrong. length / 2 is integer division in Pine when length is an int, so odd lengths truncate. The outer length is the rounded square root, so for length = 14 it is 4 (sqrt is 3.74), not 3. The value is na until the inner full-length WMA has a window and the outer WMA has rt such values, which is length + rt - 2 bars after the first. Like the WMA it is built from, the HMA has no recursion: the amount of history does not change its values.

The MQL5 equivalent

//@version=6
indicator("HMA", overlay = true)
len = input.int(16, "Length")
plot(ta.hma(close, len), "HMA")

A complete MQL5 indicator. The second buffer is declared with INDICATOR_CALCULATIONS so it is not drawn, and the same Lwma helper serves all three averages; it treats EMPTY_VALUE inside the window as na, which matters for the outer pass over the difference buffer:

//+------------------------------------------------------------------+
//| ta.hma(source, length) =                                         |
//|   wma(2 * wma(src, length / 2) - wma(src, length), round(sqrt(length))) |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "HMA (ta.hma)"

input int InpLength = 16;   // length

double HmaBuffer[];
double DiffBuffer[];        // 2 * wma(half) - wma(full), the series the outer WMA smooths

int halfLen, sqrtLen;

// linear weighted mean of src[i - len + 1 .. i]; EMPTY_VALUE before the window is full
double Lwma(const double &src[], const int i, const int len)
{
   if(len <= 0 || i < len - 1)
      return EMPTY_VALUE;
   double sum = 0.0, norm = 0.0;
   for(int k = 0; k < len; k++)
     {
      if(src[i - k] == EMPTY_VALUE)
         return EMPTY_VALUE;
      sum  += src[i - k] * (len - k);
      norm += len - k;
     }
   return sum / norm;
}

int OnInit()
{
   SetIndexBuffer(0, HmaBuffer, INDICATOR_DATA);
   SetIndexBuffer(1, DiffBuffer, INDICATOR_CALCULATIONS);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   halfLen = InpLength / 2;                            // Pine int division truncates
   sqrtLen = (int)MathRound(MathSqrt((double)InpLength)); // math.round(math.sqrt(length))
   if(InpLength < 2 || sqrtLen < 1)
      return INIT_PARAMETERS_INCORRECT;
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength + sqrtLen - 2);
   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++)
     {
      const double wHalf = Lwma(close, i, halfLen);
      const double wFull = Lwma(close, i, InpLength);
      DiffBuffer[i] = (wHalf == EMPTY_VALUE || wFull == EMPTY_VALUE)
                      ? EMPTY_VALUE : 2.0 * wHalf - wFull;
      HmaBuffer[i] = Lwma(DiffBuffer, i, sqrtLen);
     }
   return rates_total;
}

If you prefer iMA for the inner averages, create two handles with MODE_LWMA and periods halfLen and InpLength, copy both into calculation buffers, fill DiffBuffer from them and keep the outer Lwma loop. The result is the same; the loop version avoids handle management and works for a computed source.

Where the two differ

TopicPine ScriptMQL5
Native supportta.hmaNone; three WMAs and a buffer
Half lengthlength / 2 truncates for int lengthInpLength / 2 also truncates; same result
Outer lengthmath.round(math.sqrt(length))(int)MathRound(MathSqrt((double)InpLength)); MathRound rounds half away from zero like Pine
First barsna for length + rt - 2 barsEMPTY_VALUE, if the helper propagates it through the difference buffer
Intermediate seriesImplicit; any expression is a seriesNeeds a buffer; the outer WMA cannot read an expression's history
Realtime barAll three stages recomputed each tickSame when the loop restarts at prev_calculated - 1, because the difference for the forming bar is rewritten first

What the Stratlate converter emits

The engine maps ta.hma to a single runtime call, pine_hma(close, __pineBar, (int)(len)), which has no computed-source variant, so the source must be a named series; a computed source is reported as unsupported. The helper does not keep a difference buffer: for each of the outer window's bars it recomputes 2 * wma(src, len / 2) - wma(src, len) from the source and applies the linear weights, which is exact but costs O(length^1.5) per bar. One current detail to know: the runtime takes floor(sqrt(length)) for the outer window where Pine rounds, so for lengths whose square root has a fractional part of .5 or more (13 to 15, 21 to 24, 31 to 35, 43 to 48) the outer smoothing is one bar shorter than TradingView's; for 9, 16, 20, 25, 30 or 50 the two agree. The script above converts CLEAN. Compile and backtest, and compare values against TradingView for your length.

Pitfalls

  • Outer length by truncation. (int)MathSqrt(14) is 3; Pine uses 4. The line is slightly faster than TradingView's and never matches.
  • Float half length. InpLength / 2.0 passed to a WMA of 4.5 bars is meaningless; the WMA length is an int and Pine truncates.
  • Smoothing the difference without a buffer. Recomputing 2 * wHalf - wFull only on the current bar and averaging it with stale values gives a jagged line. The outer WMA needs the last rt differences, each computed on its own bar.
  • Reversed weights in the helper. The HMA then lags instead of leading price. The newest bar must carry weight len.
  • Handle readiness. If the inner averages come from iMA, CopyBuffer can return fewer values than requested on the first ticks after attaching. Return 0 and wait for the next tick.

FAQ

Is there a Hull moving average in MetaTrader 5?

Not among the standard indicators or iMA modes. You build it from weighted averages as above, or use a custom indicator through iCustom. The arithmetic is short; the only state is one calculation buffer for the inner difference.

Why does my HMA of 14 differ from TradingView by a small amount on every bar?

Check the outer length. The square root of 14 is 3.74, which Pine rounds to 4. Any implementation that floors it to 3 smooths one bar less and produces a line that is close but never equal. Lengths with an exact square root (9, 16, 25) hide this mistake.

Can the HMA be built from iMA handles only?

The two inner averages can, with MODE_LWMA and PRICE_CLOSE. The outer one cannot, because iMA only averages applied prices, not another indicator's buffer; it needs either your own loop or a second custom indicator fed through iCustom.

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