fixnan in MQL5: carrying the last valid value forward

Short answer

MQL5 has no fixnan; it is one line inside the bar loop: buf[i] = isNaN(x) ? buf[i-1] : x. Keep the carried value in the buffer itself, not in a scalar.

fixnan(x) returns x on bars where it is defined and the most recent defined value on bars where x is na. It turns a sparse series such as ta.pivothigh into a step line. MQL5 has no equivalent function; the translation is one line inside the bar loop, buf[i] = isNaN(x) ? buf[i-1] : x, with the carried value kept in the buffer itself rather than in a scalar.

What fixnan computes

On each bar: if x is not na, the result is x; otherwise the result is the previous bar's result. Until the first non-na value appears the result is na. The function is stateful: its output on bar n depends on every earlier bar, and like every stateful Pine function it keeps that state per call site, so two fixnan calls on different series do not interfere. On the realtime bar Pine rolls the state back to the committed value at the start of each tick, so if the input flips between na and a value intrabar, the output follows it without "remembering" the intrabar values.

Compare nz, which replaces na with a constant and carries nothing, and ta.valuewhen(not na(x), x, 0), which gives the same result as fixnan(x) but scans backwards each bar.

The MQL5 equivalent

The example carries the last 5/5 pivot high forward as a dotted level. The raw pivot is NaN on most bars and goes into a calculation buffer; the plotted buffer holds the carried value. The important detail is LevelBuf[i - 1]: the carry is read from the previous bar, so recomputing bar i any number of times gives the same answer.

//@version=6
indicator("fixnan demo", overlay=true)
int left = input.int(5, "Left")
int right = input.int(5, "Right")
float level = fixnan(ta.pivothigh(left, right))
plot(level, "level", color=color.orange, style=plot.style_linebr)
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrOrangeRed
#property indicator_style1  STYLE_DOT

input int Left  = 5;
input int Right = 5;

double LevelBuf[];   // plotted: fixnan(pivot high)
double PivotBuf[];   // calculation only: the raw pivot, NaN on most bars

const double NA = MathLog(-1.0);

bool IsNa(const double v) { return !MathIsValidNumber(v); }

// Pine: ta.pivothigh(Left, Right) -- the high Right bars back, if it
// is the highest of the Left bars before it and the Right bars after.
double PivotHigh(const double &high[], const int i, const int left, const int right)
{
   int c = i - right;
   if(c - left < 0) return NA;
   for(int k = c - left; k <= i; k++)
      if(k != c && high[k] >= high[c]) return NA;
   return high[c];
}

int OnInit()
{
   SetIndexBuffer(0, LevelBuf, INDICATOR_DATA);
   SetIndexBuffer(1, PivotBuf, INDICATOR_CALCULATIONS);
   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++)
   {
      PivotBuf[i] = PivotHigh(high, i, Left, Right);
      // Pine: float level = fixnan(ta.pivothigh(Left, Right))
      // The carried value is read from the previous BAR, not from a
      // scalar, so recomputing the forming bar on every tick is safe.
      double prev = i > 0 ? LevelBuf[i - 1] : EMPTY_VALUE;
      LevelBuf[i] = IsNa(PivotBuf[i]) ? prev : PivotBuf[i];
   }
   return rates_total;
}

Because the plotted buffer must never hold NaN, the "nothing yet" value is EMPTY_VALUE rather than NaN, and the plot's PLOT_EMPTY_VALUE is set to match. Pine's plot.style_linebr leaves a gap before the first pivot; MT5 does the same for an EMPTY_VALUE slot in a DRAW_LINE plot.

Where the two differ

AspectPineMQL5 hand version
State storagehidden per call sitea buffer slot per bar (shown), or a static scalar only in an EA that evaluates each bar once
Before the first valuenaNaN in a calculation buffer, EMPTY_VALUE in a plotted one
Realtime barstate rolled back every tickautomatic when the carry is buf[i-1]; broken if the carry is a scalar
Recalculationwhole history on every script changeonly from prev_calculated - 1; bar i-1 must already be correct
Pivot offsetta.pivothigh(5, 5) is confirmed 5 bars late, value at the pivot bar's highsame: the level changes on bar i to high[i-5]

What the Stratlate converter emits

fixnan(x) is emitted as pine_fixnan(x, __stN, __pineBar) with one state array per call site. The runtime function reads state[i-1], stores pine_na(v) ? prev : v in state[i] and returns it, so the state array is the carried series and recomputing the newest bar is idempotent, exactly as in the hand version above. The report marks it exact; converting the pivot example above produced a CLEAN result with pine_fixnan(pine_pivothigh(high, __pineBar, left, right), __st0, __pineBar).

Pitfalls

  • Carrying in a scalar inside an indicator: static double last updated in OnCalculate is advanced on every tick of the forming bar and is not rolled back. Symptom: the level is right on history and wrong, or stuck, on the live bar.
  • Reading buf[i-1] on bar 0: MQL5 raises "array out of range". Guard with i > 0.
  • Initialising the plotted buffer with 0 instead of EMPTY_VALUE: the step line starts at zero and the chart autoscale collapses. Symptom: price looks like a flat line at the top of the window.
  • Mixing NaN into the plotted buffer: the carry logic works but the chart has no rule for NaN. Keep NaN in calculation buffers and translate on the way out.
  • Starting the loop at prev_calculated instead of prev_calculated - 1: the forming bar is computed once and never updated, so a pivot confirmed by the current bar does not appear until the next bar opens.

FAQ

Is fixnan the same as nz?

No. nz(x) replaces na with 0 (or a given constant) and has no memory; fixnan(x) replaces na with the last non-na value of the same series, so it needs state from the previous bar. In MQL5 that state lives naturally in the previous slot of the indicator buffer.

Can I write fixnan with a static variable in MQL5?

In an Expert Advisor that evaluates each bar once on bar close, yes. In an indicator, no: OnCalculate recomputes the last bar on every tick, so a static carry drifts. Read the previous bar's buffer value instead.

What does fixnan return before the first valid value?

na, on both platforms. In the MQL5 indicator above those bars hold EMPTY_VALUE in the plotted buffer, which draws as a gap, and NaN in the calculation 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