ta.mfi in MQL5: iMFI, tick volume and the one-bar offset
Short answer
For an hlc3 source use iMFI(symbol, timeframe, length, VOLUME_TICK or VOLUME_REAL), which has the same arithmetic; for other sources compute it by hand. The formula transfers cleanly, but a MetaTrader chart usually carries tick counts, not traded volume.
ta.mfi(source, length) is the Money Flow Index: a volume-weighted RSI that sums source * volume over the bars where the source rose and the bars where it fell, then scales the ratio to 0..100. MetaTrader 5 has iMFI(symbol, timeframe, length, applied_volume) with the same arithmetic on the typical price. The formula transfers cleanly; what does not transfer is the volume itself, because a MetaTrader chart usually carries tick counts rather than traded volume.
What ta.mfi computes
For each bar in the window of length bars, the raw money flow is source * volume. It is added to the positive sum when ta.change(source) > 0 and to the negative sum when the change is below 0; a bar whose source did not move contributes to neither. Then mfi = 100 - 100 / (1 + positive / negative), which is 100 when every bar in the window rose. The first value appears on bar index length - 1: on bar 0 the change is na, and because both na <= 0 and na >= 0 are false in Pine, TradingView's reference definition counts bar 0's money flow into both sums rather than making the result na. TradingView's MFI indicator uses hlc3 as the source and 14 as the length, and ta.mfi always reads the chart's volume.
The MQL5 equivalent
//@version=6
indicator("MFI ref")
m = ta.mfi(hlc3, 14)
plot(m, "MFI")The indicator below reproduces the Pine behaviour including the bar 0 rule. It picks real volume when the broker delivers it and tick volume otherwise, which is the test the Stratlate runtime also makes. Buffers are oldest-first.
//+------------------------------------------------------------------+
//| Money Flow Index matching ta.mfi(hlc3, length) |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 1
#property indicator_label1 "MFI"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_level1 20
#property indicator_level2 80
input int InpLength = 14; // Length
double MfiBuf[], TpBuf[];
int OnInit()
{
SetIndexBuffer(0, MfiBuf, INDICATOR_DATA);
SetIndexBuffer(1, TpBuf, INDICATOR_CALCULATIONS);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
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[])
{
// TradingView's "volume" is the feed's traded volume. Use real volume
// when the broker supplies it and tick volume otherwise.
const bool realVol = rates_total > 0 && volume[rates_total - 1] > 0;
int start = prev_calculated > 1 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
TpBuf[i] = (high[i] + low[i] + close[i]) / 3.0; // hlc3
if(i < InpLength - 1) { MfiBuf[i] = EMPTY_VALUE; continue; }
double up = 0.0, dn = 0.0;
for(int k = 0; k < InpLength; k++)
{
const int j = i - k;
const double mf = TpBuf[j] * (double)(realVol ? volume[j] : tick_volume[j]);
if(j == 0) { up += mf; dn += mf; continue; } // no previous bar: change is na
if(TpBuf[j] > TpBuf[j - 1]) up += mf;
else if(TpBuf[j] < TpBuf[j - 1]) dn += mf;
}
if(dn == 0.0) MfiBuf[i] = 100.0;
else if(up == 0.0) MfiBuf[i] = 0.0;
else MfiBuf[i] = 100.0 - 100.0 / (1.0 + up / dn);
}
return rates_total;
}For the standard hlc3 source the built-in indicator is one call:
// iMFI(symbol, timeframe, length, applied_volume): typical price only.
// VOLUME_TICK counts ticks per bar; VOLUME_REAL is traded volume, which
// many forex brokers do not supply (the array is all zeros).
int mfiHandle = iMFI(_Symbol, _Period, 14, VOLUME_TICK);Where the two differ
| Aspect | Pine ta.mfi | MQL5 iMFI |
|---|---|---|
| Source | Any series | Typical price only |
| Volume | The feed's traded volume | VOLUME_TICK (tick count) or VOLUME_REAL (often all zeros on forex) |
| First value | Bar index length - 1 | Bar index length; the window needs a bar before its oldest member |
| Bar 0 | Counted into both sums | Never inside a window |
| Window with no down bars | 100 | 100 |
| Window with no up bars | 0 | 0 |
| Flat bars | Ignored (neither sum) | Ignored |
The one-bar offset is real but harmless once the chart has history: from bar length on, both windows contain the same bars. The volume difference is the one that decides whether the lines look alike at all. On a stock or futures chart where the broker streams real volume, VOLUME_REAL gives values comparable with TradingView's. On a forex chart, tick volume is a proxy: it tracks activity but not size, and the MFI built on it will cross 20 and 80 on different bars than TradingView's, however exact the formula is. Whether TradingView's volume for the same forex pair is comparable depends on the feed you selected there; check it before judging the conversion.
What the Stratlate converter emits
The converter emits its runtime helper pine_mfi(src, volume, bar, length), not iMFI, so any source expression works (the hlc3 in the test script is materialised into an array first). The helper follows the Pine definition: first value on bar length - 1, bar 0 counted into both sums, na if any source value in the window is na, 100 when the negative sum is zero. The generated OnCalculate checks whether the newest bar has a non-zero real volume and passes volume[] if so, tick_volume[] otherwise. The mapping is reported as exact (CLEAN), and the volume question is left to you: compile the output, run it on a chart whose volume you trust, and compare with TradingView on the same bars.
Pitfalls
- Choosing
VOLUME_REALon a symbol whose broker does not supply it. Every money flow is zero, the sums are zero and the MFI is pinned at 100 or shows nothing. - Starting the window at bar
lengthasiMFIdoes when you want to match a Pine script bar for bar. The MFI itself is identical afterwards, but any EMA the script applies to it (ta.ema(mfi, 9)is common) seeds one bar later and stays slightly off for a long time. - Using a
>=comparison for the positive sum. Flat bars then count as positive, and the index is biased upward on quiet charts. - Comparing a tick-volume MFI against TradingView on a stock chart. The shapes diverge on high-volume bars; that is the data, not the code.
- Multiplying
longvolume by adoubleprice without a cast. MQL5 compiles it, but "possible loss of data" warnings follow when the product is stored back into a long. Cast the volume todoublefirst.
FAQ
Can iMFI reproduce ta.mfi exactly?
The formula yes, for the typical price source: both sum price times volume over up and down bars and scale the ratio to 0..100. The values only match if the volume series matches, which it does when the broker streams real volume and TradingView uses the same feed. iMFI's first value also appears one bar later than ta.mfi's.
Which applied volume should I pass to iMFI?
VOLUME_REAL when the symbol has traded volume (exchange-traded futures, stocks, some CFDs), VOLUME_TICK otherwise. Check Market Watch: if the Volume column is empty for the symbol, real volume is not available and only tick volume will produce an indicator.
Why does ta.mfi start a bar earlier than my MQL5 version?
Because Pine's definition does not require a bar before the oldest window member: on bar 0 the change is na and the bar's money flow is counted into both sums. A hand-written MQL5 loop that compares each bar with the one before it needs that extra bar and starts at index length instead of length - 1.
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