ta.macd in MQL5: why iMACD's signal line does not match
Short answer
Don't use iMACD to match TradingView: its MACD line is the same, but its signal line is a simple moving average, while Pine's is an EMA. Write the three EMAs yourself: fast EMA minus slow EMA, an EMA of that as the signal, and their difference as the histogram.
ta.macd(source, fastlen, slowlen, siglen) returns three series at once: the MACD line (fast EMA minus slow EMA), the signal line (an EMA of the MACD line) and the histogram (their difference). MetaTrader 5 has iMACD, and its MACD line is the same, but its signal line is a simple moving average of the MACD line, not an exponential one. The honest MQL5 equivalent of ta.macd is therefore three EMAs written by hand, which is short, and it is what the code below does.
What ta.macd computes
The tuple is defined as macd = ta.ema(source, fastlen) - ta.ema(source, slowlen), signal = ta.ema(macd, siglen), hist = macd - signal. ta.ema uses alpha = 2 / (length + 1) and starts from the first value of its source, so none of the three lines is ever na on a chart whose source has no gaps; the MACD line is exactly 0 on the first bar because both EMAs equal the first price there, and the signal line starts at 0 for the same reason. The result is destructured in Pine: [macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9). All three move with the realtime bar and settle at the close.
The MQL5 equivalent
//@version=6
indicator("MACD ref")
[macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9)
plot(macdLine, "MACD", color=color.blue)
plot(signalLine, "Signal", color=color.orange)
plot(hist, "Histogram", style=plot.style_histogram)The MQL5 indicator keeps the two EMAs in calculation buffers so the realtime bar can be recomputed from the previous bar's slot on every tick. Plot order is chosen so the histogram is drawn behind the lines. Everything is oldest-first, which is how OnCalculate hands the arrays over.
//+------------------------------------------------------------------+
//| MACD with an EMA signal line, as ta.macd computes it |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 5
#property indicator_plots 3
#property indicator_label1 "Histogram"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrSilver
#property indicator_width1 2
#property indicator_label2 "MACD"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrDodgerBlue
#property indicator_label3 "Signal"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrOrange
input int InpFast = 12; // Fast length
input int InpSlow = 26; // Slow length
input int InpSignal = 9; // Signal length
double HistBuf[], MacdBuf[], SignalBuf[], FastBuf[], SlowBuf[];
int OnInit()
{
SetIndexBuffer(0, HistBuf, INDICATOR_DATA);
SetIndexBuffer(1, MacdBuf, INDICATOR_DATA);
SetIndexBuffer(2, SignalBuf, INDICATOR_DATA);
SetIndexBuffer(3, FastBuf, INDICATOR_CALCULATIONS);
SetIndexBuffer(4, SlowBuf, INDICATOR_CALCULATIONS);
IndicatorSetString(INDICATOR_SHORTNAME, "MACD EMA signal");
return INIT_SUCCEEDED;
}
int OnCalculate(const int rates_total, const int prev_calculated,
const int begin, const double &price[])
{
// 2.0, not 2: an int division here turns every EMA into a flat line.
const double aF = 2.0 / (InpFast + 1.0);
const double aS = 2.0 / (InpSlow + 1.0);
const double aG = 2.0 / (InpSignal + 1.0);
int start = prev_calculated > 1 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
if(i == 0) // ta.ema starts from the first value of its source
{
FastBuf[0] = price[0]; SlowBuf[0] = price[0];
MacdBuf[0] = 0.0; SignalBuf[0] = 0.0; HistBuf[0] = 0.0;
continue;
}
FastBuf[i] = aF * price[i] + (1.0 - aF) * FastBuf[i - 1];
SlowBuf[i] = aS * price[i] + (1.0 - aS) * SlowBuf[i - 1];
MacdBuf[i] = FastBuf[i] - SlowBuf[i];
SignalBuf[i] = aG * MacdBuf[i] + (1.0 - aG) * SignalBuf[i - 1]; // EMA, not SMA
HistBuf[i] = MacdBuf[i] - SignalBuf[i];
}
return rates_total;
}The built-in indicator is still useful when you only need the MACD line, for example for a zero-line cross. For a signal-line cross or the histogram, keep in mind what you are getting:
// iMACD: fast EMA, slow EMA, signal period, applied price.
// Buffer 0 is the MACD line, buffer 1 the signal line.
// The signal line is a SIMPLE moving average of the MACD line here,
// so it is not ta.macd's EMA signal line and the histogram differs too.
int macdHandle = iMACD(_Symbol, _Period, 12, 26, 9, PRICE_CLOSE);The MetaTrader standard MACD also draws the MACD line itself as the histogram and the signal as a line; there is no third buffer holding macd - signal. If a Pine script plots the TradingView-style histogram and you reproduce it from iMACD, you must compute buffer0 - buffer1 yourself, and the result will still be the SMA-based histogram.
Where the two differ
| Aspect | Pine ta.macd | MQL5 iMACD |
|---|---|---|
| MACD line | EMA(fast) - EMA(slow), both seeded with the first price | Same formula; the EMAs come from iMA MODE_EMA |
| Signal line | EMA of the MACD line | SMA of the MACD line |
| Histogram | Third tuple element, macd - signal | No buffer; the MACD line is drawn as the histogram |
| Return shape | Tuple, destructured into three variables | Handle with two buffers, read with CopyBuffer |
| First bars | Values from bar 0; MACD line is 0 there | Signal line only once siglen MACD values exist (SMA window) |
| Source | Any series | Applied-price constant only |
How large is the signal-line difference? An EMA with siglen = 9 weights the newest MACD value at 20% and decays from there; a 9-bar SMA weights each of the last nine values at 11%. The EMA signal line therefore turns earlier and the histogram changes sign one to three bars before the SMA version does on most swings. If a strategy trades the signal cross, the two versions produce different trade lists. The MACD-line zero cross is unaffected.
What the Stratlate converter emits
The converter does not map ta.macd to iMACD. Its lowering pass expands the tuple into the exact three definitions above: two pine_ema calls on the source for the MACD line, a third pine_ema over a materialised buffer of that line for the signal, and a subtraction for the histogram, each EMA with its own state array. The destructured names (macdLine, signalLine, hist) survive as ordinary MQL5 variables, and a plot(..., style=plot.style_histogram) becomes a DRAW_HISTOGRAM buffer. The mapping is reported as exact: the test script above converts CLEAN with no notes. Compile the output and backtest it before trading on it.
Pitfalls
- Reading the signal line from
iMACDbuffer 1. The line lags TradingView's and the histogram flips sign on different bars. Symptom: signal-cross entries one to three bars late in the Strategy Tester. - Expecting a histogram buffer from
iMACD. Buffer 2 does not exist, soCopyBufferfails and the indicator shows nothing. - Integer alphas:
2 / (InpFast + 1)is 0 with anintinput, so each EMA stays at the first price and the MACD line is a flat zero. - Seeding the signal EMA from an SMA of the first
siglenMACD values. That is theta.rmaseed, not theta.emaone, and the first few dozen bars will not match. - Keeping the EMAs in scalar variables updated on every tick. The realtime bar compounds its own updates; use the previous bar's buffer slot.
- Different source: a Pine script with
input.sourceset tohlc3compared against aniMACDonPRICE_CLOSE.
FAQ
Does the MetaTrader MACD really use an SMA for the signal line?
Yes. The standard MACD indicator that ships with MetaTrader 5 builds the MACD line from two exponential iMA handles and smooths the signal line with a simple moving average of that line. TradingView's ta.macd uses an exponential average for the signal, so the two signal lines and histograms differ by design.
Can I make iMACD match TradingView by changing a parameter?
No. iMACD has no moving-average-method parameter for the signal line. To match ta.macd you compute the signal line yourself as an EMA of the MACD line, either from iMACD's buffer 0 or from two EMAs you compute as in the code on this page.
Why is the MACD line exactly zero on the first bar in both my Pine and MQL5 versions?
Because ta.ema starts each EMA from the first value of its source, both the fast and the slow EMA equal the first price on bar 0, so their difference is 0. The hand-written MQL5 version reproduces that seed on purpose; it is not an error.
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