ta.dmi in MQL5: iADX vs iADXWilder and the DI smoothing

Short answer

For an exact match, compute it by hand: Wilder-smoothed +DM, -DM and true range, then one more Wilder average for the ADX. iADXWilder is close but takes one period for both, and iADX smooths with exponential averages and differs visibly.

ta.dmi(diLength, adxSmoothing) returns Wilder's Directional Movement System as a tuple: [diPlus, diMinus, adx]. MetaTrader 5 has two built-ins with similar names and different arithmetic. iADXWilder follows Wilder's construction, the same one Pine uses, but takes a single period for both the DI and the ADX smoothing. iADX smooths the directional ratios with exponential averages and gives visibly different lines. For an exact match with separate lengths, write it out: three Wilder averages and one more for the ADX.

What ta.dmi computes

Per bar: up = high - high[1], down = low[1] - low. +DM = up if up > down and up > 0, else 0; -DM = down if down > up and down > 0, else 0. Then, all with ta.rma (Wilder, alpha = 1 / length, seeded with the simple mean of the first length values):

  • trur = ta.rma(ta.tr, diLength)
  • diPlus = fixnan(100 * ta.rma(+DM, diLength) / trur), and likewise diMinus
  • adx = 100 * ta.rma(|diPlus - diMinus| / (diPlus + diMinus, or 1 if that sum is 0), adxSmoothing)

fixnan carries the last valid DI forward when the division is undefined. The DIs start once the true-range average has a value (around bar diLength), and the ADX needs another adxSmoothing - 1 bars of DX on top, so with 14/14 the first ADX appears near bar 27. All three move with the realtime bar's high and low.

The MQL5 equivalent

//@version=6
indicator("DMI ref")
[diPlus, diMinus, adx] = ta.dmi(14, 14)
plot(diPlus, "+DI", color=color.green)
plot(diMinus, "-DI", color=color.red)
plot(adx, "ADX", color=color.blue)

The indicator below keeps the raw +DM, -DM, true range and DX in calculation buffers and smooths each with a small Rma helper that reproduces ta.rma's SMA seed. The plot order follows Pine's tuple (+DI, -DI, ADX), not MetaTrader's buffer order.

//+------------------------------------------------------------------+
//| +DI, -DI and ADX matching ta.dmi(diLength, adxSmoothing)          |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 10
#property indicator_plots   3
#property indicator_label1  "+DI"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrGreen
#property indicator_label2  "-DI"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrRed
#property indicator_label3  "ADX"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrDodgerBlue
#property indicator_width3  2

input int InpDiLength  = 14;   // DI length
input int InpAdxLength = 14;   // ADX smoothing

double PlusDI[], MinusDI[], Adx[];
double TrRaw[], PdmRaw[], MdmRaw[], DxRaw[], TrS[], PdmS[], MdmS[];

int OnInit()
{
   SetIndexBuffer(0, PlusDI,  INDICATOR_DATA);
   SetIndexBuffer(1, MinusDI, INDICATOR_DATA);
   SetIndexBuffer(2, Adx,     INDICATOR_DATA);
   SetIndexBuffer(3, TrRaw,   INDICATOR_CALCULATIONS);
   SetIndexBuffer(4, PdmRaw,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(5, MdmRaw,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(6, DxRaw,   INDICATOR_CALCULATIONS);
   SetIndexBuffer(7, TrS,     INDICATOR_CALCULATIONS);
   SetIndexBuffer(8, PdmS,    INDICATOR_CALCULATIONS);
   SetIndexBuffer(9, MdmS,    INDICATOR_CALCULATIONS);
   for(int p = 0; p < 3; p++) PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   return INIT_SUCCEEDED;
}

// ta.rma over raw[], which is valid from index `first`: na until len values
// exist, the plain mean of the first len values as the seed, then Wilder.
double Rma(const double &raw[], const double &sm[], const int i, const int len, const int first)
{
   if(i < first + len - 1) return EMPTY_VALUE;
   if(i == first + len - 1 || sm[i - 1] == EMPTY_VALUE)
   {
      double s = 0.0;
      for(int k = 0; k < len; k++) s += raw[i - k];
      return s / len;
   }
   return (sm[i - 1] * (len - 1) + raw[i]) / len;
}

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[])
{
   const int len = InpDiLength;
   int start = prev_calculated > 1 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      if(i == 0)   // ta.change and ta.tr are na on the first bar
      {
         TrRaw[0] = 0.0; PdmRaw[0] = 0.0; MdmRaw[0] = 0.0; DxRaw[0] = 0.0;
         TrS[0] = EMPTY_VALUE;
         PdmS[0] = Rma(PdmRaw, PdmS, 0, len, 0); MdmS[0] = Rma(MdmRaw, MdmS, 0, len, 0);
         PlusDI[0] = EMPTY_VALUE; MinusDI[0] = EMPTY_VALUE; Adx[0] = EMPTY_VALUE;
         continue;
      }
      const double up   = high[i] - high[i - 1];
      const double down = low[i - 1] - low[i];
      PdmRaw[i] = (up > down && up > 0.0)   ? up   : 0.0;
      MdmRaw[i] = (down > up && down > 0.0) ? down : 0.0;
      TrRaw[i]  = MathMax(high[i] - low[i],
                  MathMax(MathAbs(high[i] - close[i - 1]), MathAbs(low[i] - close[i - 1])));
      TrS[i]  = Rma(TrRaw,  TrS,  i, len, 1);   // true range is na on bar 0
      PdmS[i] = Rma(PdmRaw, PdmS, i, len, 0);   // +DM/-DM are 0 (not na) on bar 0
      MdmS[i] = Rma(MdmRaw, MdmS, i, len, 0);
      if(TrS[i] == EMPTY_VALUE)
      {
         PlusDI[i] = EMPTY_VALUE; MinusDI[i] = EMPTY_VALUE; DxRaw[i] = 0.0; Adx[i] = EMPTY_VALUE;
         continue;
      }
      // fixnan(): a zero true range keeps the previous DI instead of dividing
      PlusDI[i]  = TrS[i] == 0.0 ? PlusDI[i - 1]  : 100.0 * PdmS[i] / TrS[i];
      MinusDI[i] = TrS[i] == 0.0 ? MinusDI[i - 1] : 100.0 * MdmS[i] / TrS[i];
      const double sum = PlusDI[i] + MinusDI[i];
      DxRaw[i] = 100.0 * MathAbs(PlusDI[i] - MinusDI[i]) / (sum == 0.0 ? 1.0 : sum);
      Adx[i]   = Rma(DxRaw, Adx, i, InpAdxLength, len);   // DX exists from bar `len`
   }
   return rates_total;
}

If one period for both stages is acceptable, the built-in is closer than its name suggests:

// Closest built-in: iADXWilder smooths TR, +DM and -DM with Wilder's average,
// as ta.dmi does, but uses ONE period for the DI and the ADX smoothing.
int adxw = iADXWilder(_Symbol, _Period, 14);
// Buffer order differs from Pine's tuple: 0 = ADX, 1 = +DI, 2 = -DI.
// iADX(_Symbol, _Period, 14) is a different calculation (EMA of per-bar DM/TR ratios).

Where the two differ

AspectPine ta.dmiMQL5 iADXWilderMQL5 iADX
DI smoothingWilder average of TR, +DM, -DM separatelyWilder average of TR, +DM, -DM separatelyEMA of the per-bar ratios 100 * DM / TR
ADX smoothingWilder, own lengthWilder, same period as DIEMA, same period
LengthsdiLength and adxSmoothingOne periodOne period
Output order+DI, -DI, ADXBuffer 0 ADX, 1 +DI, 2 -DIBuffer 0 ADX, 1 +DI, 2 -DI
Zero true rangefixnan keeps the previous DIDI set to 0Ratio set to 0 for that bar
Early barsna until each average is seeded0 written, own seedingEMA from the first bar

The iADX row is the one that produces support questions. Averaging the ratio DM / TR bar by bar is not the same as dividing the averaged DM by the averaged TR, and an EMA with alpha = 2 / 15 reacts almost twice as fast as Wilder's 1 / 14. The result is an ADX that peaks higher and earlier, so a filter like adx > 25 passes on different bars. iADXWilder has the right structure; with equal lengths it should agree with ta.dmi once the averages have forgotten their different starting points, but verify that on your own data before relying on it.

What the Stratlate converter emits

The converter does not use iADX or iADXWilder. Its lowering pass expands the tuple into Pine's own definition: pine_change for the up and down moves, a ternary for each DM, pine_rma over a materialised true-range series for trur, pine_rma and pine_fixnan for each DI, and a final pine_rma with the ADX length, every average with its own state array. One detail: the runtime's true range uses high - low on the very first bar rather than na, which can move the seed of the first averages slightly; it does not affect later bars once the averages have converged. The mapping is reported as exact (the test script converts CLEAN). Compile and backtest the output, and compare recent bars with TradingView.

Pitfalls

  • Using iADX because the name matches. The ADX runs hotter than TradingView's and ADX-threshold filters let trades through on the wrong bars.
  • Reading buffer 0 as +DI. In MetaTrader buffer 0 is the ADX; a DI cross built on buffers 0 and 1 compares the ADX with +DI and fires at random.
  • Passing different DI and ADX lengths and expecting iADXWilder to honour both. It has one period; with 14/20 in Pine the ADX smoothing is wrong.
  • Averaging the DI ratios instead of DM and TR separately. That is the iADX construction and gives the same mismatch.
  • Replacing fixnan with 0 when the true-range average is zero. The DI drops to zero for a bar and creates a false cross.
  • Smoothing with alpha = 2 / (len + 1). That is an EMA, not Wilder; every line becomes faster.

FAQ

Which MetaTrader indicator matches TradingView's ADX?

iADXWilder, the "Average Directional Movement Index Wilder", is built the same way as ta.dmi: Wilder averages of the true range and both directional movements. Its single period has to equal both Pine lengths. The standard iADX is a different calculation and will not match.

What is the buffer order of iADX and iADXWilder?

Buffer 0 is the ADX (MAIN_LINE), buffer 1 is +DI (PLUSDI_LINE) and buffer 2 is -DI (MINUSDI_LINE). Pine's tuple is ordered +DI, -DI, ADX, so the indices do not line up.

Why does the ADX appear so late on the chart?

It is an average of an average. The DIs need about diLength bars before their averages are seeded, and the ADX then needs adxSmoothing values of DX for its own seed, so with 14 and 14 the first ADX value arrives near bar 27 in both platforms.

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