ta.atr in MQL5: why iATR differs and the exact Wilder ATR
Short answer
Not iATR: MetaTrader's ATR averages true range with a simple moving average, and the difference does not fade with more history. Pine's ta.atr is Wilder's RMA of true range, seeded with the simple average of the first length ranges, so compute that RMA yourself.
ta.atr(length) is the average true range as Welles Wilder defined it: the true range smoothed with ta.rma, alpha 1 / length, seeded with a simple average of the first length ranges. MetaTrader's iATR is not that. The standard MT5 ATR averages the true range with a simple moving average, so it has the same scale as TradingView's ATR but a different shape, and the difference does not fade with more history. The exact equivalent is a true range buffer smoothed with the RMA recursion, which is what the indicator below does.
What ta.atr computes
Two steps. First the true range, ta.tr(true): max(high - low, |high - close[1]|, |low - close[1]|), with the first bar of the chart using high - low because there is no previous close. Then ta.rma(tr, length): na for the first length - 1 bars, the SMA of the first length true ranges on bar length - 1, and atr = (tr + (length - 1) * atr[1]) / length after that.
The recursion is what gives Wilder's ATR its memory: a single wide bar lifts the ATR and then decays out of it geometrically over several multiples of length, instead of dropping out abruptly after length bars as it does from a simple average. Stops and position sizes derived from the two are therefore different numbers, often by ten percent or more right after a volatility spike. As with every RMA, the first bars depend on where the history starts, and the seed's weight fades roughly as (1 - 1/length)^n.
The MQL5 equivalent
//@version=6
indicator("ATR", overlay = false)
len = input.int(14, "Length")
plot(ta.atr(len), "ATR")A complete MQL5 indicator that reproduces ta.atr. The true range lives in a calculation buffer so the seed can average it; arrays are oldest-first:
//+------------------------------------------------------------------+
//| ta.atr(length) = ta.rma(ta.tr(true), length): Wilder-smoothed |
//| true range, seeded with the SMA of the first `length` ranges |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_label1 "ATR (ta.atr)"
input int InpLength = 14; // length
double AtrBuffer[];
double TrBuffer[]; // true range per bar, not drawn
int OnInit()
{
SetIndexBuffer(0, AtrBuffer, INDICATOR_DATA);
SetIndexBuffer(1, TrBuffer, INDICATOR_CALCULATIONS);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLength - 1);
return InpLength > 0 ? INIT_SUCCEEDED : INIT_PARAMETERS_INCORRECT;
}
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 double alpha = 1.0 / InpLength;
int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
// ta.tr(true): the first bar has no previous close, so its range is high - low
if(i == 0)
TrBuffer[i] = high[i] - low[i];
else
TrBuffer[i] = MathMax(high[i], close[i - 1]) - MathMin(low[i], close[i - 1]);
if(i < InpLength - 1)
{
AtrBuffer[i] = EMPTY_VALUE; // na before the seed
continue;
}
if(i == InpLength - 1)
{
double sum = 0.0; // seed: SMA of the first `length` true ranges
for(int k = 0; k < InpLength; k++)
sum += TrBuffer[i - k];
AtrBuffer[i] = sum / InpLength;
continue;
}
AtrBuffer[i] = alpha * TrBuffer[i] + (1.0 - alpha) * AtrBuffer[i - 1];
}
return rates_total;
}If you already have a true range buffer in a custom indicator, iMA cannot smooth it directly (it only takes applied prices), so the loop stays. The only way to get Wilder smoothing from built-ins alone is to publish the true range as its own indicator and run iMA with MODE_SMMA on it through iCustom, which is more code than the loop.
Where the two differ
| Topic | Pine ta.atr | MQL5 iATR | Indicator above |
|---|---|---|---|
| Smoothing | Wilder RMA, alpha 1 / length | Simple moving average of the true range | Wilder RMA |
| Seed | SMA of the first length ranges | Not applicable; every value is a window mean | Same as Pine |
| First bar's range | high - low (handle_na) | Computed by the terminal; no handle_na choice | high - low |
| Warm-up | na for length - 1 bars | Values before the first full window are not meaningful; skip them | EMPTY_VALUE |
| After a spike | Decays geometrically | Drops out after length bars | Decays geometrically |
| History depth | Affects early values through the seed | Does not matter | Same as Pine |
So iATR and ta.atr agree only by coincidence, usually in quiet stretches where the true range is roughly constant. Any logic that depends on the ATR's level, such as a trailing stop or a Keltner band, inherits the difference.
What the Stratlate converter emits
The engine does not use iATR. ta.atr becomes pine_atr_hlc(high, low, close, __st0, __stb0, __pineBar, (int)(len)), with two arrays per call site: __stb0 receives the true range (computed as ta.tr(true), so the first bar is high - low) and __st0 carries the Wilder average, produced by the same pine_rma helper the engine uses for ta.rma and ta.rsi: na until length bars, SMA seed, then alpha 1 / length, reading the previous bar's slot so a recomputed realtime bar is idempotent. When the length is omitted the engine uses 14. The call is reported as exact, and the script above converts CLEAN. Compile and backtest the output and compare bars well past the warm-up, not the first ones.
Pitfalls
- Dropping in
iATR. Values differ on every bar, by the most right after volatility changes. Trailing stops are placed at different distances and a backtest diverges from TradingView's. - Using
MODE_EMAor2 / (length + 1)on the true range. Nearly twice the intended alpha; the ATR reacts too fast and the gap never closes. - Forgetting the first bar's range. If
TrBuffer[0]is left atEMPTY_VALUE, the SMA seed includes a huge number and the ATR starts far too high. - Integer alpha.
1 / InpLengthis 0; write1.0 / InpLength. - Comparing the first few dozen bars. The seed differs because the two platforms' histories start on different candles; look several hundred bars in.
FAQ
Is iATR the same as ta.atr?
No. MetaTrader's standard ATR is a simple moving average of the true range, while ta.atr is Wilder's exponentially smoothed version. They share a scale and a period but respond differently to volatility changes. To match TradingView, compute the true range yourself and smooth it with the RMA recursion.
How much history does the ATR need before it matches TradingView?
The seed's influence fades as (1 - 1/length) to the power of the bars elapsed, so for length 14 it is below one percent after roughly 65 bars and negligible after 150. Load several hundred bars before the range you compare.
Can I feed iMA MODE_SMMA with the true range?
Not directly: iMA accepts applied prices only. You would have to publish the true range as a separate indicator and call iMA on it through iCustom. The loop in the indicator above is shorter and keeps the logic in one file.
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