nz in MQL5: replacing na with zero or a default value

Short answer

MQL5 has no nz, but once missing values are NaN it is a two-line function: MathIsValidNumber(x) ? x : r, with r defaulting to 0. Guard EMPTY_VALUE separately.

nz(x) returns x unless it is na, in which case it returns 0; nz(x, r) returns r instead. MQL5 has no built-in for this because it has no na, but once missing values are represented as NaN (see na in MQL5) the equivalent is a two-line function: MathIsValidNumber(x) ? x : r.

What nz computes

nz is the standard way to seed a recurrence in Pine. On the first bar x[1] is na, so x := x[1] + 1 would stay na for ever; x := nz(x[1]) + 1 starts at 1. The function is overloaded for every numeric type and for colours and booleans: nz(int) returns an int, nz(bool) returns false for na, nz(color) returns the replacement colour. The replacement is evaluated on every bar whether or not it is used, which matters only when it has side effects.

Two things nz does not do: it does not carry the last valid value forward (that is fixnan), and it does not make a window function start earlier. nz(ta.sma(close, 20)) is 0 for the first 19 bars, not a shorter average.

The MQL5 equivalent

The example sums the bar-to-bar change of close from the start of the chart. The change is na on bar 0 and the running total has no previous value there, so both reads go through nz. In MQL5 the previous total is read from the buffer's previous slot, and the change is computed into a calculation buffer so the NaN on bar 0 is explicit.

//@version=6
indicator("nz demo")
float chg = ta.change(close)
var float net = 0.0
net := nz(net[1]) + nz(chg)
plot(net, "net")
plot(nz(ta.highest(high, 20)[1], high), "prevHigh")
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue

double NetBuf[];      // plotted: running net change
double ChangeBuf[];   // calculation only: close - close[1], NaN on bar 0

const double NA = MathLog(-1.0);

// nz(x) and nz(x, replacement) in one function
double Nz(const double v, const double replacement = 0.0)
{
   return MathIsValidNumber(v) ? v : replacement;
}

int OnInit()
{
   SetIndexBuffer(0, NetBuf, INDICATOR_DATA);
   SetIndexBuffer(1, ChangeBuf, INDICATOR_CALCULATIONS);
   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 chg = ta.change(close)      (na on the first bar)
      ChangeBuf[i] = i > 0 ? close[i] - close[i - 1] : NA;
      // Pine: var float net = 0.0
      //       net := nz(net[1]) + nz(chg)
      double prevNet = i > 0 ? NetBuf[i - 1] : NA;
      NetBuf[i] = Nz(prevNet) + Nz(ChangeBuf[i]);
   }
   return rates_total;
}

The default argument on Nz gives both Pine forms in one function. Because NetBuf is a plotted buffer and every slot is written with a finite number, it never needs EMPTY_VALUE. If a plotted buffer can contain gaps, read it back with a check for both NaN and EMPTY_VALUE before applying Nz, because MathIsValidNumber(EMPTY_VALUE) is true.

Where the two differ

AspectPine nzMQL5 hand version
What counts as missingnaNaN and infinities fail MathIsValidNumber; EMPTY_VALUE passes and must be checked separately
Return typesame as the argument (int stays int)one double overload is enough; add an int overload with your own sentinel if needed
Previous-bar readx[1] is na on bar 0 automaticallyi > 0 ? buf[i-1] : NA must be written out; buf[-1] is an array-out-of-range error
Realtime barthe recurrence restarts from the committed x[1] on every ticksame, provided the previous value is read from buf[i-1] and not from a scalar updated on every call
Booleans and coloursoverloads existMQL5 bool and color cannot be missing; nothing to replace

What the Stratlate converter emits

nz(x) is emitted as pine_nz(x) and nz(x, r) as pine_nz(x, r); the runtime function is pine_na(v) ? replacement : v with a default replacement of 0.0, and pine_na is v == PINE_NA || !MathIsValidNumber(v). A history read inside it, such as nz(net[1]), becomes pine_nz(pine_hist(net, __pineBar, 1)), where pine_hist returns PINE_NA for an index before the first bar. The mapping is exact and adds no note to the report.

Pitfalls

  • Forgetting nz on the seed of a recurrence: total[i] = total[i-1] + x with an unwritten total[i-1] on bar 0 reads garbage (MQL5 does not zero buffers). Symptom: a huge or NaN value on every bar.
  • Applying nz to a buffer that holds EMPTY_VALUE: the check passes and DBL_MAX enters the sum. Symptom: the line jumps to 1e308 or inf after the first gap.
  • Replacing na with 0 inside a division: nz(a) / nz(b) divides by zero, which in MQL5 is inf or NaN and in Pine is na; either way guard the divisor.
  • Using a static or global scalar as the "previous value" in an indicator: OnCalculate re-runs the forming bar on every tick, so the scalar is advanced once per tick instead of once per bar. Symptom: the value on the last bar grows while you watch it.
  • Expecting nz(ta.sma(...)) to shorten the warm-up: it only replaces the early na with 0, so the first bars show 0 rather than a partial average, on both platforms.

FAQ

Is there a built-in nz in MQL5?

No. MQL5 has no missing value, so there is nothing to replace. If you represent missing values as NaN, the equivalent is MathIsValidNumber(x) ? x : 0.0, which is short enough to inline or wrap in a two-line function with a default argument for the replacement.

What does nz return for an integer or a boolean in Pine?

The same type as its argument: nz(int) is an int, nz(bool) is false when the argument is na, and nz(color, c) returns c. In MQL5 those types cannot hold a missing value, so only the double case needs translating.

Can I use EMPTY_VALUE as the "na" that nz replaces?

Only if you also test for it, since MathIsValidNumber(EMPTY_VALUE) is true. A buffer that is read back into a calculation should be checked with both tests, or the gap should be stored as NaN in a calculation buffer and converted to EMPTY_VALUE only in the plotted buffer.

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