na in MQL5: NaN, EMPTY_VALUE and MathIsValidNumber

Short answer

MQL5 has no na. Store a quiet NaN in a double, test it with !MathIsValidNumber(x), and swap it for EMPTY_VALUE only when the number is written to an indicator buffer.

In Pine Script na is the "no value" marker: a series is na on bars where it is undefined, arithmetic on na yields na, and na(x) tests for it. MQL5 has no such value in the language. The closest equivalent is an IEEE quiet NaN stored in a double, tested with MathIsValidNumber, and swapped for EMPTY_VALUE only when the number is written to an indicator buffer.

What na computes

na is a value of every Pine type, and in v6 it must be typed when used as an initialiser (float x = na). Three rules describe its behaviour:

  • Propagation: na + 1, na * close and math.max(na, 3) are na. A window function such as ta.sma returns na until it has length real values.
  • Comparison: na > 0, na == 0 and na == na are all false; a condition that depends on an na value is false, so the branch guarded by it does not run.
  • Testing: na(x) is the only reliable test. x == na does not compile in v6.

Plotting na leaves a gap in the line, which is how plot.style_linebr draws discontinuous levels.

The MQL5 equivalent

MQL5 doubles can hold NaN, and NaN follows the same propagation and comparison rules as Pine's na: every arithmetic operator returns NaN, every comparison returns false. There is no NaN literal, so one is made once: MathLog(-1.0) produces a quiet NaN. Testing uses MathIsValidNumber, which returns false for NaN and for infinities. What MQL5 does not have is a chart that understands NaN as "no value": plot buffers mark gaps with EMPTY_VALUE (DBL_MAX), an ordinary finite number. So the rule is: compute with NaN, publish with EMPTY_VALUE.

//@version=6
indicator("na demo", overlay=true)
float gap = close > open ? close - open : na
float doubled = gap * 2
plot(doubled, "doubled")
plotshape(na(gap), "missing", style=shape.circle, location=location.belowbar)
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue

double GapBuf[];

// Pine's na as a value: a quiet NaN. MQL5 has no NaN literal.
const double NA = MathLog(-1.0);

// Pine's na(x) as a test. NaN is never == to anything, so compare
// with MathIsValidNumber, not with ==.
bool IsNa(const double v) { return !MathIsValidNumber(v); }

int OnInit()
{
   SetIndexBuffer(0, GapBuf, 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++)
   {
      // Pine: float gap = close > open ? close - open : na
      double gap = close[i] > open[i] ? close[i] - open[i] : NA;
      // Pine: float doubled = gap * 2   (na in, na out)
      double doubled = gap * 2.0;
      // Pine: plot(doubled)  -- the buffer wants EMPTY_VALUE, not NaN
      GapBuf[i] = IsNa(doubled) ? EMPTY_VALUE : doubled;
   }
   return rates_total;
}

The PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE) call is what makes the buffer value a gap rather than a point at 1.8e308. The default depends on the drawing style, so writing it out removes doubt and keeps the intent visible.

Where the two differ

AspectPine naMQL5
Literalna, typed by contextnone; MathLog(-1.0) or a divide such as 0.0/0.0 at run time
Testna(x)!MathIsValidNumber(x); x != x also works for NaN
Arithmeticna propagatesNaN propagates; EMPTY_VALUE does not (EMPTY_VALUE * 2 is inf, EMPTY_VALUE - 1 is still DBL_MAX)
In a plotgap in the linegap only if the buffer holds the plot's PLOT_EMPTY_VALUE
Uninitialised seriesna on bars before the first assignmentbuffers hold garbage until written; initialise with ArrayInitialize or write every bar
Integersint x = na is legalno NaN for int; use a sentinel such as INT_MIN or a double
Strings, boolsstring s = na, bool b = na are legalno missing value; use "" / NULL or a separate flag

What the Stratlate converter emits

The engine represents na as PINE_NA, a constant in its runtime defined as MathLog(-1.0), so propagation and comparison work by IEEE rule without extra guards; na(x) becomes pine_na(x), which is v == PINE_NA || !MathIsValidNumber(v). The NaN is written straight into the plot buffer and each plot's PLOT_EMPTY_VALUE is set to EMPTY_VALUE; na(arr) on an array is emitted as false, since an MQL array always exists. This mapping is reported as exact and carries no note in the conversion report.

Pitfalls

  • Testing with ==: if(x == NA) is never true because NaN compares unequal to itself. Symptom: the "missing" branch never runs and downstream values turn NaN for the whole chart.
  • Doing arithmetic on EMPTY_VALUE: a buffer read of EMPTY_VALUE fed into a moving average gives a value around 1e305 or inf. Convert buffer reads back to NaN (or skip them) before computing.
  • Reading an unwritten buffer slot: unlike Pine, MQL5 does not fill it with na. Symptom: a random spike on the first bars after attaching, or after a history reload.
  • Treating na as zero in a condition: Pine's close > prev with prev na is false; a hand-translation that replaced na with 0 makes it true on every bar.
  • Using NaN for an int: MQL5 integers cannot hold NaN; (int)NaN is an implementation-defined large negative number. Keep such values as double or pick an explicit sentinel.

FAQ

Is EMPTY_VALUE the MQL5 equivalent of na?

Only for indicator buffers. EMPTY_VALUE is DBL_MAX, a finite number that participates in arithmetic, so it is wrong as a general missing-value marker. Use NaN inside the calculation and EMPTY_VALUE only when writing to a buffer whose PLOT_EMPTY_VALUE is EMPTY_VALUE.

How do I write na in MQL5 without a NaN literal?

Define one global: const double NA = MathLog(-1.0); MathLog of a negative number returns a quiet NaN, and MathIsValidNumber(NA) is false. Some code uses 0.0/0.0 at run time, but the constant is clearer and does not rely on the division being evaluated at run time.

Does MathIsValidNumber match Pine's na() exactly?

It returns false for NaN and for positive and negative infinity, so it is slightly wider than na(): Pine does not produce infinities from finite inputs, but MQL5 does on division by zero. That is usually what you want, since an infinite value in a buffer is as useless as a missing one.

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