ta.tr in MQL5: true range, handle_na and the first bar

Short answer

The true range is one line: max(high - low, |high - close[i-1]|, |low - close[i-1]|). On the first bar, ta.tr(true) is high - low while plain ta.tr is na, and that value seeds everything smoothed from it, including ta.atr.

ta.tr is the true range: the largest of the bar's own range and its two gaps from the previous close. It is one line in MQL5 and needs no indicator handle. The only decision is the first bar of the chart, where there is no previous close: ta.tr(true) falls back to high - low, while the bare ta.tr (and ta.tr(false)) is na. That one value matters because everything smoothed from the true range, including ta.atr, is seeded by it.

What ta.tr computes

On every bar after the first, tr = max(high - low, abs(high - close[1]), abs(low - close[1])). The two absolute terms only win when the bar gaps: if the previous close lies inside the bar's range, high - low is already the largest. On the first bar, close[1] is na; ta.tr(true) returns high - low, and ta.tr without the argument, which is the same as handle_na = false, returns na.

ta.atr is defined on ta.tr(true), so an ATR's seed includes the first bar's range. A hand-rolled ta.rma(ta.tr, length) in Pine instead sees na on bar 0, so the RMA's first full window arrives one bar later and its seed averages different bars. Two Pine scripts that look identical can therefore have ATRs that differ for a few hundred bars, and the same happens in a port that mixes the two conventions. ta.tr is a series without parameters other than the flag; it takes no length and has no state.

The MQL5 equivalent

//@version=6
indicator("True range", overlay = false)
plot(ta.tr(true), "TR, first bar = high - low")
plot(ta.tr, "TR, first bar = na", color = color.orange)

A complete MQL5 indicator with the handle_na choice as an input. Arrays are oldest-first, so the previous close is close[i - 1] and bar 0 is the first bar of history:

//+------------------------------------------------------------------+
//| ta.tr(handle_na): max(high - low, |high - close[1]|, |low - close[1]|) |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_label1  "True range (ta.tr)"

input bool InpHandleNa = true;   // handle_na: first bar = high - low instead of na

double TrBuffer[];

int OnInit()
{
   SetIndexBuffer(0, TrBuffer, INDICATOR_DATA);
   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[])
{
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      if(i == 0)
        {
         TrBuffer[i] = InpHandleNa ? high[i] - low[i] : EMPTY_VALUE;
         continue;
        }
      const double prevClose = close[i - 1];
      TrBuffer[i] = MathMax(high[i] - low[i],
                            MathMax(MathAbs(high[i] - prevClose), MathAbs(low[i] - prevClose)));
     }
   return rates_total;
}

An equivalent and shorter form for bars after the first is MathMax(high[i], close[i - 1]) - MathMin(low[i], close[i - 1]); it is the same number, since extending the bar's range to include the previous close is exactly the max of the three terms. MetaTrader has no true range function, and iATR does not expose its range buffer, so this is the whole implementation.

Where the two differ

TopicPine ScriptMQL5
First barta.tr(true): high - low; ta.tr: naclose[i - 1] does not exist at i = 0; you must branch, or the read is out of range
Missing valuesnaEMPTY_VALUE; any smoothing you apply must treat it as missing
Previous closeclose[1]close[i - 1] oldest-first, close[1] after ArraySetAsSeries
Realtime barRange grows as new highs and lows printSame when the forming bar is recomputed each tick
Gaps across sessionsCaptured by the two absolute termsSame; the weekend gap in forex shows up as a large Monday true range on both
Native functionta.trNone; three MathMax/MathAbs calls

What the Stratlate converter emits

The engine distinguishes the two forms. ta.tr(true) (or any non-false argument) becomes pine_tr_na(high, low, close, __pineBar, true), which returns high - low on the first bar; ta.tr, ta.tr() and ta.tr(false) become pine_tr(high, low, close, __pineBar). In the current runtime, however, pine_tr also returns high - low on bar 0 rather than na, a deliberate choice documented in the runtime source so that RMA and EMA seeds fed by a bare ta.tr start on the same bar as the engine's own ATR; the effect is confined to the seeding of averages at the very start of the history and is not reported as a note. On every later bar both helpers compute the standard three-term maximum. The script above converts CLEAN. Compile and backtest the output, and compare bars well past the start of the chart.

Pitfalls

  • Reading close[i - 1] at i = 0. Array out of range; the indicator stops. Branch on the first bar.
  • Leaving the first bar as EMPTY_VALUE and then averaging it. The seed of an ATR picks up 1.797e308 and the whole line is garbage until the seed fades, or forever with an SMA.
  • Using the previous bar's range instead of the previous close. high[i] - low[i - 1] is not a true range; gaps are measured against the prior close only.
  • Forgetting the absolute values. A gap down makes high - close[1] negative and the max silently ignores it.
  • Different candles. Daily bars that close at different session boundaries on the two platforms produce different gaps, and therefore different true ranges on those bars.

FAQ

Is there a true range function in MQL5?

No. iATR computes one internally but exposes only the averaged result. Write the three-term maximum yourself; it is one line per bar plus a branch for the first bar of the history.

Should I port ta.tr as na or as high - low on the first bar?

Match what the Pine script used. ta.tr(true) and ta.atr use high - low; bare ta.tr and ta.tr(false) use na. Mixing them changes the seed of any average built on the range and shifts early ATR values.

Why is the first bar of my converted ATR different from TradingView?

Besides the first-bar convention, the two charts rarely start on the same candle, so the first true range and the SMA seed are computed from different bars. The difference fades with Wilder smoothing after a few multiples of the length.

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