Hull Moving Average: TradingView (Pine Script) to MT5 (MQL5)
Short answer
HMA is a WMA over sqrt(length) of 2 × WMA(half length) minus WMA(full length). Every step is a finite window with no recursion, so a hand-written MQL5 port returns exactly TradingView's values from the first bar both platforms draw.
The Hull Moving Average (HMA) is a weighted moving average of a de-lagged series: twice the WMA over half the length minus the WMA over the full length, smoothed again with a WMA over the square root of the length. Because every step is a finite window with no recursion, a hand-written MQL5 port returns exactly TradingView's values from the first bar on which both platforms draw it.
How the Hull Moving Average is calculated
With len (default 16) and a source src (default close):
halfLen = len / 2using integer division (16 → 8, 9 → 4), andsqrtLen = round(sqrt(len))(16 → 4, 10 → 3).raw = 2 * WMA(src, halfLen) - WMA(src, len). Subtracting the slower average from twice the faster one pushes the series ahead of price and roughly cancels the lag.HMA = WMA(raw, sqrtLen), which smooths the noise that the subtraction amplified.
A WMA over n values gives the newest value weight n, the next n - 1 and so on down to 1, then divides by n (n + 1) / 2. It needs n values and nothing else: no previous output, no seed. This is what makes HMA the easy case when moving between platforms. The first bar that has a value is len + sqrtLen - 2 (18 for the defaults), because raw needs len bars and the outer WMA needs sqrtLen of those.
The colour rule used below is the common one: green when the HMA is above its previous value, red otherwise.
Pine Script v6 version
The script builds the HMA from ta.wma instead of calling ta.hma, so each line has an MQL5 counterpart. len / 2 is integer division because both operands are int; math.round(math.sqrt(len)) returns an int.
//@version=6
indicator("Hull Moving Average, written out", "HMA", overlay = true)
len = input.int(16, "Length", minval = 2)
src = input.source(close, "Source")
int halfLen = len / 2 // integer division, like ta.hma
int sqrtLen = math.round(math.sqrt(len))
float wmaHalf = ta.wma(src, halfLen)
float wmaFull = ta.wma(src, len)
float raw = 2 * wmaHalf - wmaFull // de-lagged series
float hma = ta.wma(raw, sqrtLen) // smoothed over sqrt(len)
bool rising = hma > hma[1]
plot(hma, "HMA", rising ? color.green : color.red, 2)
alertcondition(rising and not rising[1], "HMA turned up", "Hull MA started rising")
alertcondition(not rising and rising[1], "HMA turned down", "Hull MA started falling")ta.hma(src, len) computes exactly this, so the two forms can be swapped in Pine. The written-out form is only there so that the port is line by line.
MQL5 version
Two calculation buffers hold the source price and the raw series; the drawn buffer is a DRAW_COLOR_LINE with a colour-index buffer (0 = green, 1 = red). Wma() is written once and used three times. Arrays stay oldest-first, so i - k looks back k bars exactly like Pine's [k].
//+------------------------------------------------------------------+
//| HullMA_TV.mq5 - Hull Moving Average built from three WMAs |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots 1
#property indicator_label1 "HMA"
#property indicator_type1 DRAW_COLOR_LINE
#property indicator_color1 clrGreen, clrRed
#property indicator_width1 2
input int InpLen = 16; // Length
input ENUM_APPLIED_PRICE InpPrice = PRICE_CLOSE; // Source
double Hma[], HmaColor[]; // drawn: value and colour index (0 rising, 1 falling)
double Src[], Raw[]; // per-bar state: source price, 2*WMA(n/2) - WMA(n)
int OnInit()
{
if(InpLen < 2)
return INIT_PARAMETERS_INCORRECT;
SetIndexBuffer(0, Hma, INDICATOR_DATA);
SetIndexBuffer(1, HmaColor, INDICATOR_COLOR_INDEX);
SetIndexBuffer(2, Src, INDICATOR_CALCULATIONS);
SetIndexBuffer(3, Raw, INDICATOR_CALCULATIONS);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
IndicatorSetString(INDICATOR_SHORTNAME, "HMA(" + (string)InpLen + ")");
return INIT_SUCCEEDED;
}
// Applied price for one bar, like Pine's input.source choices
double Price(const int i, const double &open[], const double &high[],
const double &low[], const double &close[])
{
switch(InpPrice)
{
case PRICE_OPEN: return open[i];
case PRICE_HIGH: return high[i];
case PRICE_LOW: return low[i];
case PRICE_MEDIAN: return (high[i] + low[i]) / 2.0; // hl2
case PRICE_TYPICAL: return (high[i] + low[i] + close[i]) / 3.0; // hlc3
case PRICE_WEIGHTED: return (high[i] + low[i] + 2.0 * close[i]) / 4.0; // hlcc4
default: return close[i];
}
}
// Linearly weighted mean of the last len values ending at bar i (ta.wma).
// EMPTY_VALUE until the window is full or if any value inside is empty.
double Wma(const double &src[], const int i, const int len)
{
if(len < 1 || i < len - 1)
return EMPTY_VALUE;
double num = 0.0, den = 0.0;
for(int k = 0; k < len; k++)
{
if(src[i - k] == EMPTY_VALUE)
return EMPTY_VALUE;
double w = len - k; // newest value carries weight len
num += src[i - k] * w;
den += w;
}
return num / den;
}
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 half = InpLen / 2; // integer division, as in Pine
int root = (int)MathRound(MathSqrt((double)InpLen));
int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
Src[i] = Price(i, open, high, low, close);
double wHalf = Wma(Src, i, half);
double wFull = Wma(Src, i, InpLen);
Raw[i] = (wHalf == EMPTY_VALUE || wFull == EMPTY_VALUE) ? EMPTY_VALUE : 2.0 * wHalf - wFull;
Hma[i] = Wma(Raw, i, root);
bool rising = (i > 0 && Hma[i] != EMPTY_VALUE && Hma[i - 1] != EMPTY_VALUE && Hma[i] > Hma[i - 1]);
HmaColor[i] = rising ? 0 : 1;
}
return rates_total;
}The Price() helper stands in for input.source: MQL5 has no series-typed input, so the usual replacement is an ENUM_APPLIED_PRICE input and a switch. If the Pine script fed the HMA with another indicator's output, that output would have to be computed into a buffer first and passed to Wma() in place of Src.
Differences you will see on the chart
| Topic | TradingView | MetaTrader 5 |
|---|---|---|
| Warm-up | na until bar len + sqrtLen - 2. | EMPTY_VALUE until the same bar; the line simply starts later. |
| Values | Identical to floating-point precision once both are drawn. There is no seed and no recursion, so the history depth does not matter, unlike EMA- or RMA-based indicators. | |
| Colour | One plot whose colour is a per-bar expression. | One DRAW_COLOR_LINE plot with two colours in indicator_color1 and a colour-index buffer. |
| First coloured bar | Red on the first drawn bar (hma[1] is na, so "rising" is false). | Red as well; the code checks that Hma[i - 1] exists before comparing. |
| Realtime bar | Recomputed every tick; the colour of the last segment can change until the bar closes. | Same: the loop restarts at prev_calculated - 1. |
HMA does not repaint closed bars on either platform.
What the Stratlate converter does with this script
Converted with the Stratlate engine, the script above is graded CLEAN. Each ta.wma becomes the runtime helper pine_wma; the computed raw series is written into a per-call-site window buffer so that the outer pine_wma can read its history; input.source becomes an ENUM_APPLIED_PRICE input read through pine_source; and the coloured plot becomes a DRAW_COLOR_LINE with a colour-index buffer. A script that calls ta.hma directly is mapped to pine_hma, which recomputes the inner WMAs for the last round(sqrt(len)) bars and is exact. The report notes (PM221) that input options such as minval have no field on an MQL input; the emitted OnInit rejects out-of-range values instead. Compile and backtest the output as you would any port.
Using it in MetaTrader 5
- Save the code as
HullMA_TV.mq5inMQL5\Indicators, compile with F7 (no warnings) and attach it from the Navigator. - The Source input offers the standard applied prices.
PRICE_MEDIANis Pine'shl2,PRICE_TYPICALishlc3,PRICE_WEIGHTEDishlcc4; Pine'sohlc4has no enum value and would need one more case. - From an EA,
iCustom(_Symbol, _Period, "HullMA_TV", 16, PRICE_CLOSE)andCopyBuffer(handle, 0, ...)read the line; buffer 1 holds the colour index (0 rising, 1 falling), which is a cheap way to read the slope. - For an alert when the colour changes, compare
HmaColor[rates_total - 2]withHmaColor[rates_total - 3]on a new bar; the closed bar is the one TradingView'salertconditionfires on when the alert is set to "once per bar close".
Pitfalls
- Using
iMAwithMODE_LWMAfor the outer step. The standard MA cannot take a computed series as input, so people feed it the price and get a plain WMA, not an HMA. Computerawinto a buffer and smooth that. - Floating-point half length.
len / 2.0gives 4.5 forlen = 9; Pine truncates to 4. Keep the division in integers or the two WMAs use different windows. - Rounding the root. For
len = 15the root is 3.87:(int)MathSqrt(15)truncates to 3 while Pine'smath.roundgives 4, so the outer window differs. UseMathRound. - Reading the previous value after
ArraySetAsSeries. If the buffers are flipped to series order,Hma[i - 1]is the newer bar and every slope colour inverts. - Ignoring empty values inside the window. A WMA that treats
EMPTY_VALUE(about 1.8e308) as a number produces a huge spike on the first bars. TheWma()above returnsEMPTY_VALUEif any input is empty.
FAQ
Why do the HMA values match exactly while EMA-based indicators differ on early bars?
A WMA is a weighted sum over a fixed window and uses no previous output, so once the window is full the value depends only on those bars. EMA and RMA carry a seed from the first bar of the loaded history, and the two platforms load different histories.
Can I build the HMA from iMA handles instead of the loop?
Partly. Two iMA handles with MODE_LWMA give the half and full WMAs of a price, but the outer WMA runs over the computed difference, which iMA cannot consume. You would still need the loop for the last step, so the single Wma() function is simpler.
Does the MQL5 version need ArraySetAsSeries?
No. OnCalculate hands over oldest-first arrays and the indicator buffers are oldest-first as well, so i - 1 is the previous bar. Leave the ordering alone unless you have a reason to flip every array consistently.
Convert your own version
Have a variant of this indicator, or any other TradingView script? Paste it and get MQL5 that is checked against the original on the same price history, with every construct that could not be carried over reported.
Open the converter