Pine na, nz() and MQL5 EMPTY_VALUE: missing values
Short answer
MQL5 has no built-in no-value: a double always holds a number. Choose a representation for missing values and check for it wherever Pine handled na silently; that is what fixes huge numbers, phantom signals on the first bars, and lines where TradingView shows gaps.
Pine Script has a built-in "no value", na. MQL5 does not: a double always holds a number. Converting a script therefore means choosing how to represent a missing value and checking for it wherever Pine would have handled it silently. This guide is for anyone whose converted indicator shows huge numbers, phantom signals on the first bars, or lines where TradingView shows gaps.
What na does in Pine
- It appears on its own. History before the first bar (
close[1]on bar 0),ta.*functions during their warm-up, and anything you assignnato. - It propagates. Any arithmetic with
nagivesna:na + 1,close - na,na * 2. - Comparisons with it are false.
x > 0is false whenxisna, and so ista.crossoverwhile either side is still warming up. To test for it, usena(x), neverx == na. - It plots as a gap.
plot()draws nothing on bars where the value isna. - It has helpers.
nz(x, y)replacesnawithy(default 0);fixnan(x)repeats the last non-navalue.
In Pine v6, int, float, color and string can be na; bool cannot. A small example that uses most of this:
//@version=6
indicator("Missing values")
minVol = input.int(100, "Minimum volume")
chg = close - close[1] // na on the first bar
w = volume >= minVol ? chg : na // na on thin bars
plot(nz(w), "nz(w)") // 0 where w is na
plot(fixnan(w), "fixnan(w)") // last valid w carried forwardRepresenting na in MQL5: EMPTY_VALUE or NaN
There are two reasonable choices, and most converted indicators use both.
EMPTY_VALUE is MetaTrader's sentinel for "nothing to draw". In MQL5 it equals DBL_MAX; in MQL4 it is 2147483647. It is an ordinary number, so it does not propagate: EMPTY_VALUE - 1.1 is still about 1.8e308, EMPTY_VALUE * 2 overflows to infinity, and EMPTY_VALUE > 0 is true. Every use has to be guarded.
NaN behaves like Pine's na: it propagates through every arithmetic operator, and every comparison with it is false. MQL5 has no NaN literal, so code typically creates one once, for example with MathLog(-1.0), and tests for it with !MathIsValidNumber(x), which is also true for infinities.
A workable rule: write EMPTY_VALUE into plot buffers, and either use NaN internally or test with a helper like IsNa() below before every calculation. For types that have no spare value, pick an explicit representation: clrNONE for a Pine na colour, a separate bool flag for a missing int, an empty string for text.
| Pine | MQL5 |
|---|---|
na (float) | EMPTY_VALUE in buffers, NaN or EMPTY_VALUE internally |
na(x) | x == EMPTY_VALUE || !MathIsValidNumber(x) |
nz(x, y) | IsNa(x) ? y : x |
fixnan(x) | IsNa(x) ? Buf[i - 1] : x, stored per bar |
na colour | clrNONE |
nz() and fixnan() in MQL5
The indicator below is the MQL5 version of the Pine example, using tick_volume for volume. The intermediate series w lives in an INDICATOR_CALCULATIONS buffer because fixnan needs the previous bar's result.
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots 2
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_label1 "nz(w)"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrOrange
#property indicator_label2 "fixnan(w)"
input long InpMinVolume = 100; // Minimum tick volume
double NzBuf[], FixBuf[], WBuf[];
bool IsNa(const double v) { return v == EMPTY_VALUE || !MathIsValidNumber(v); }
double Nz(const double v, const double r = 0.0) { return IsNa(v) ? r : v; }
int OnInit()
{
SetIndexBuffer(0, NzBuf, INDICATOR_DATA);
SetIndexBuffer(1, FixBuf, INDICATOR_DATA);
SetIndexBuffer(2, WBuf, INDICATOR_CALCULATIONS);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetDouble(1, 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++)
{
// chg = close - close[1] -> na on the first bar
double chg = (i > 0) ? close[i] - close[i - 1] : EMPTY_VALUE;
// w = tick volume >= min ? chg : na
WBuf[i] = (!IsNa(chg) && tick_volume[i] >= InpMinVolume) ? chg : EMPTY_VALUE;
NzBuf[i] = Nz(WBuf[i]); // nz(w)
FixBuf[i] = !IsNa(WBuf[i]) ? WBuf[i] // fixnan(w)
: (i > 0 ? FixBuf[i - 1] : EMPTY_VALUE);
}
return rates_total;
}The !IsNa(chg) test in the w line is the habit to build. Here the first bar would come out right without it, because w is only a copy of chg, but in a longer formula an unchecked EMPTY_VALUE flows into the arithmetic and comes out as a finite, very wrong number.
Plotting gaps: PLOT_EMPTY_VALUE
PlotIndexSetDouble(plot, PLOT_EMPTY_VALUE, EMPTY_VALUE) tells the terminal which value means "do not draw this bar"; such bars are also left blank in the Data Window. Set it explicitly for every plot. Some MetaTrader code uses 0.0 as the empty value instead, which works for prices but silently hides genuine zeros in an oscillator.
Watch line styles as well. Pine's default plot.style_line joins the points on either side of an na gap, while plot.style_linebr leaves the gap open. MetaTrader's DRAW_LINE does not draw through empty values, so it looks like style_linebr. If the Pine plot relies on bridging, carry the last value forward (as fixnan does) or accept the visual difference.
When you read another indicator with CopyBuffer, find out which empty value that indicator uses before treating its output as data.
Signals and comparisons
Because EMPTY_VALUE compares as a very large number, a warm-up bar can look like a crossover. Pine's ta.crossover is false until both inputs exist; the MQL5 version must say so explicitly:
// Pine: ta.crossover(fast, slow) is false while either side is na
bool crossUp = i > 0
&& !IsNa(FastBuf[i]) && !IsNa(SlowBuf[i])
&& !IsNa(FastBuf[i - 1]) && !IsNa(SlowBuf[i - 1])
&& FastBuf[i] > SlowBuf[i] && FastBuf[i - 1] <= SlowBuf[i - 1];The same applies to every if that tests a value which can be missing. In Pine the condition is simply false; in MQL5 it can be true.
What Stratlate's converter does
From Pine to MQL5, the converter's runtime represents na internally as a quiet NaN created with MathLog(-1.0), so arithmetic propagates it and comparisons with it are false, as in Pine. Its na() check uses MathIsValidNumber, and every plot declares EMPTY_VALUE as its PLOT_EMPTY_VALUE. From MQL to Pine, EMPTY_VALUE becomes na, and a guard such as buf[i] != EMPTY_VALUE is rewritten as an na() test, because a direct comparison with na is never true in Pine. Compile and backtest the output either way.
Pitfalls
- Arithmetic on EMPTY_VALUE. Symptom: values around 1.8e308 or
infin the Data Window, and a separate-window plot squashed flat by the autoscale. - Zero as na. Averages are pulled toward zero during warm-up, and real zero values disappear from the plot.
- Testing too late.
x == EMPTY_VALUEstops working oncexhas been through arithmetic. Test inputs, not results. - Unwritten slots.
ArrayResizedoes not initialise new elements. Write every bar, or callArrayInitialize(buf, EMPTY_VALUE)whenprev_calculated == 0, or an uninitialised slot reads as a tiny valid-looking number. - Warm-up signals. Crossovers or alerts firing on the first bars of the chart where Pine shows none.
- Hard-coded sentinels. Writing 2147483647 instead of
EMPTY_VALUEworks in MQL4 and breaks in MQL5, where the value isDBL_MAX.
FAQ
What is the MQL5 equivalent of na in Pine Script?
There is no direct equivalent. Use EMPTY_VALUE in plot buffers, and set it as PLOT_EMPTY_VALUE, so the bar is not drawn. In calculations, use NaN or test for missing values explicitly so a missing value never turns into a large number.
How do I write nz() in MQL5?
Write a small helper that returns the replacement when the value is missing and the value otherwise, for example IsNa(v) ? r : v, where IsNa tests v == EMPTY_VALUE || !MathIsValidNumber(v).
Why does my converted indicator show huge numbers?
A value that was na in Pine became EMPTY_VALUE in MQL5 and was then used in arithmetic. EMPTY_VALUE is DBL_MAX in MQL5, so the result is a huge number or infinity instead of a missing value. Check for missing values before calculating.
Let the converter handle na for you
Stratlate carries Pine's na semantics into MQL5 and maps EMPTY_VALUE back to na in the other direction. Compile and backtest the result before you trade on it.