iMACD in Pine Script: the signal line is an SMA, not ta.macd

Short answer

Don't use ta.macd: MetaTrader smooths the signal line with a simple moving average, Pine with an EMA. The exact port is macd = ta.ema(src, fast) - ta.ema(src, slow), then signal = ta.sma(macd, signalPeriod).

iMACD returns a handle to MetaTrader's MACD, whose two buffers are MAIN_LINE (fast EMA minus slow EMA) and SIGNAL_LINE. The trap when porting is the signal line: MetaTrader smooths it with a simple moving average, while Pine's ta.macd smooths it with an EMA. The exact Pine equivalent is macd = ta.ema(src, fast) − ta.ema(src, slow) followed by signal = ta.sma(macd, signalPeriod).

What iMACD computes

The signature is iMACD(symbol, timeframe, fast_ema_period, slow_ema_period, signal_period, applied_price). The stock indicator (Indicators\Examples\MACD.mq5) creates two internal iMA handles with MODE_EMA on the applied price, subtracts slow from fast into the main buffer, and then calls SimpleMAOnBuffer with signal_period to produce the signal buffer. The variable in the source is even named InpSignalSMA. Both EMAs are seeded with the first price in the loaded history and use α = 2/(n+1). The MACD line is drawn as a histogram in MetaTrader's default template and the signal as a line; there is no third "histogram" buffer, so iMACD has only buffer 0 and buffer 1. The difference main − signal is what MetaTrader's separate iOsMA indicator provides.

The Pine Script equivalent

Write the three lines yourself instead of calling ta.macd. The two EMAs are identical to MetaTrader's; the signal SMA is a window of signal_period bars with no seed effect, so once the EMAs have converged the two platforms print the same signal value.

//@version=6
indicator("iMACD port", overlay = false)
fastLen = input.int(12, "Fast EMA", minval = 1)
slowLen = input.int(26, "Slow EMA", minval = 1)
sigLen  = input.int(9, "Signal SMA", minval = 1)
src     = input.source(close, "Applied price")

macd   = ta.ema(src, fastLen) - ta.ema(src, slowLen)
signal = ta.sma(macd, sigLen)   // MetaTrader smooths the signal line with an SMA, not an EMA

plot(macd, "MACD (MAIN_LINE)", color.silver, style = plot.style_histogram)
plot(signal, "Signal (SIGNAL_LINE)", color.red)

The MQL5 indicator being replaced. Note the buffer indices used with CopyBuffer: 0 for the main line and 1 for the signal.

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_type1   DRAW_HISTOGRAM
#property indicator_color1  clrSilver
#property indicator_width1  2
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrRed

input int                InpFast   = 12;          // fast_ema_period
input int                InpSlow   = 26;          // slow_ema_period
input int                InpSignal = 9;           // signal_period (SMA)
input ENUM_APPLIED_PRICE InpPrice  = PRICE_CLOSE; // applied_price

double MacdBuffer[];
double SignalBuffer[];
int    macdHandle;

int OnInit()
  {
   SetIndexBuffer(0, MacdBuffer,   INDICATOR_DATA);
   SetIndexBuffer(1, SignalBuffer, INDICATOR_DATA);
   macdHandle = iMACD(_Symbol, _Period, InpFast, InpSlow, InpSignal, InpPrice);
   if(macdHandle == INVALID_HANDLE)
      return(INIT_FAILED);
   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(BarsCalculated(macdHandle) < rates_total)
      return(0);
   int to_copy = (prev_calculated == 0) ? rates_total : rates_total - prev_calculated + 1;
   if(CopyBuffer(macdHandle, MAIN_LINE,   0, to_copy, MacdBuffer)   <= 0) return(0);
   if(CopyBuffer(macdHandle, SIGNAL_LINE, 0, to_copy, SignalBuffer) <= 0) return(0);
   return(rates_total);
  }

Where the two differ

TopicMQL5 iMACDPine ta.macdHand-written Pine above
MACD lineEMA(fast) − EMA(slow)SameSame
Signal lineSMA of the MACD lineEMA of the MACD lineSMA, matches MT5
HistogramNot a buffer; use iOsMAThird tuple elementmacd − signal if you want it
Warm-upBuffer values exist from bar 0 because the EMAs are seeded immediately; the signal is 0.0 for the first signal−1 barsna until each EMA and the signal have datana for the first signal−1 bars
EMA seedsFirst bar of the terminal's historyFirst bar TradingView loadsSame as ta.macd
ReturnHandle; values via CopyBuffer(handle, 0|1, …)Tuple [macd, signal, hist]Two plain series

With the default 12/26/9 the EMA-signal and SMA-signal lines cross the MACD line on different bars several times per hundred bars, so a converted strategy that keeps ta.macd will not reproduce the MetaTrader trade list.

What the Stratlate converter emits

The MQL5 → Pine engine does not emit ta.macd. It dispatches iMACD on the line selector and emits prelude helpers f_macd_main(src, fast, slow, sig), which returns ta.ema(src, fast) − ta.ema(src, slow), and f_macd_signal, which returns ta.sma of that difference over sig; the helper's source comment states that MetaTrader's signal is a simple average and that this is closer to MetaTrader than the built-in. In the MQL5 handle form the line is chosen from the CopyBuffer buffer index: our probe produced MacdBuffer := f_macd_main(close, InpFast, InpSlow, InpSignal) and SignalBuffer := f_macd_signal(…), with an approximation warning (MQLW0501) noting that the mode was resolved from the buffer index rather than a constant. Compile the result and compare the signal crosses with the MT5 chart.

Pitfalls

  • Porting with [m, s, h] = ta.macd(close, 12, 26, 9). The MACD line matches; the signal line and every signal crossover do not.
  • Expecting a histogram buffer from iMACD. Buffer 2 does not exist; CopyBuffer fails and the indicator shows nothing. Compute main − signal or use iOsMA.
  • Comparing the first hundred bars. Both EMAs carry their seed for a long time, so the MACD line differs at the start of the chart even though the formulas are identical; compare later bars.
  • Treating MetaTrader's early 0.0 signal values as real. For the first signal−1 bars the buffer holds 0.0, which Pine shows as na.
  • Switching the applied price in MT5 but leaving close in Pine. PRICE_TYPICAL is hlc3, PRICE_WEIGHTED is hlcc4.

FAQ

Is MetaTrader's MACD signal line really an SMA?

Yes. The stock MACD.mq5 computes the signal with SimpleMAOnBuffer over the main line, and the input is named InpSignalSMA. MetaTrader 4's built-in MACD behaves the same way.

How do I get TradingView's MACD in MetaTrader instead?

Do not use iMACD. Build the main line from two iMA EMA handles and smooth it with ExponentialMAOnBuffer (or your own EMA loop) using the signal period.

What does iOsMA correspond to in Pine?

To main − signal with the SMA signal, in other words the histogram of the hand-written version above. It is not the third element of ta.macd, which uses the EMA signal.

Convert the whole program

Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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