var and varip in MQL5: persistent state and tick rollback

Short answer

MQL5 globals already persist, so the issue is the reverse: the forming bar is recomputed on every tick and a var value must be rolled back first. Store a var value per bar in a buffer; a varip value is a plain static reset when a new bar opens.

var declares a Pine variable that is initialised once and keeps its value from bar to bar instead of being re-initialised on every bar. varip does the same and additionally keeps changes made between ticks of the realtime bar. In MQL5 every global and static variable already persists, so the problem is the reverse: an indicator recomputes the forming bar on every tick, and a var value must be rolled back to its committed state first. The reliable pattern is to store a var value per bar in a buffer; a varip value is a plain static reset when a new bar opens.

What var and varip compute

Without a modifier, float x = 0.0 runs on every bar and x starts at 0 each time. var float x = 0.0 runs the initialiser on the first bar only; later bars see the value left by the previous bar, so x := x + 1 counts bars. On the realtime bar Pine executes the script on every tick, but before each run it restores every variable to the value it had when the bar opened. A var counter incremented on the live bar therefore goes to n + 1 on every tick, not n + ticks. varip ("intrabar persist") skips that rollback: its value carries from tick to tick, which is how tick counters and intrabar volume deltas are written. On historical bars, where there is one execution per bar, var and varip behave identically.

The MQL5 equivalent

A var value that depends on the bar sequence is best kept in a buffer slot per bar: bar i starts from buf[i - 1], so recomputing bar i on every tick gives the same answer, exactly as Pine's rollback does. A varip value is a static that is reset when the newest bar's open time changes.

//@version=6
indicator("var and varip demo")
var int ups = 0
varip int ticks = 0
if barstate.isnew
    ticks := 0
ticks += 1
if close > open
    ups += 1
plot(ups, "up bars (var)")
plot(barstate.islast ? ticks : 0, "ticks this bar (varip)")
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_label1  "up bars (var)"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrOrangeRed
#property indicator_label2  "ticks this bar (varip)"

double UpsBuf[];     // the `var` counter, one committed value per bar
double TicksBuf[];

int OnInit()
{
   SetIndexBuffer(0, UpsBuf, INDICATOR_DATA);
   SetIndexBuffer(1, TicksBuf, INDICATOR_DATA);
   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[])
{
   // Pine: varip int ticks = 0  -- survives every tick, never rolled back
   static int      ticks = 0;
   static datetime barTime = 0;
   int lastBar = rates_total - 1;
   if(time[lastBar] != barTime) { barTime = time[lastBar]; ticks = 0; }
   ticks++;

   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      // Pine: var int ups = 0
      //       if close > open
      //           ups += 1
      // The previous bar's committed value is the starting point, so
      // re-running the forming bar does not count it twice.
      double prevUps = i > 0 ? UpsBuf[i - 1] : 0.0;
      UpsBuf[i] = prevUps + (close[i] > open[i] ? 1.0 : 0.0);
      TicksBuf[i] = (i == lastBar) ? ticks : 0.0;
   }
   return rates_total;
}

The buffer approach also survives prev_calculated == 0: a history reload recomputes every slot from bar 0. A static counter does not know about reloads and has to be reset by hand when prev_calculated is 0. In an Expert Advisor that runs once per closed bar, a global variable behaves like var without any extra work, because there is no re-execution to roll back.

Where the two differ

AspectPine varPine varipMQL5
Initialisedfirst barfirst barglobal: at load; static: first call; buffer: bar 0 of the loop
Across barskeptkeptkept
Across ticks of the forming barrolled back to bar openkeptkept, unless the code reads the previous bar's slot
History reloadscript restartsscript restartsprev_calculated == 0; statics keep stale values
Backtest / Strategy Testervarip sees one tick per bar on historysametester feeds generated ticks, so a tick counter gives tester-specific numbers
Scopeglobal or inside a function (per call site)samestatic inside a function is one slot for all calls

What the Stratlate converter emits

The engine keeps every script-level variable as an MQL global and reproduces Pine's rollback itself: before the forming bar is computed for the first time it snapshots all globals (__pineSaveState), and on each later tick it restores them (__pineRestoreState) before re-running the bar, so var semantics are exact. varip is parsed but treated as var: the same snapshot and restore apply, so a varip tick counter in a converted indicator reads the same on every tick instead of accumulating, and the report does not note it (the example above converted CLEAN). If intrabar persistence matters, replace the restored variable with a static as shown here.

Pitfalls

  • Translating var to a global and incrementing it in the bar loop: the forming bar adds one per tick. Symptom: the count on the last bar climbs while you watch, then drops back when the next bar opens and the history pass is not repeated.
  • Translating varip to a buffer slot: the per-bar read rolls it back, which is var behaviour. Symptom: a tick counter stuck at 1.
  • Forgetting the prev_calculated == 0 reset for statics: after a reconnect the indicator continues from stale values. Symptom: a running total that disagrees with a freshly attached copy.
  • Reading an uninitialised buffer slot as "the previous value" on bar 0: MQL5 does not zero buffers. Guard with i > 0 and supply the initial value explicitly.
  • Expecting varip results to match in a backtest: TradingView's historical bars have one execution each, so intrabar counters only mean something on live bars; the Strategy Tester's generated ticks make the numbers different again.

FAQ

Is a Pine var the same as an MQL5 static variable?

Only in an Expert Advisor that runs each bar once. In an indicator the forming bar is recomputed on every tick, and a static is not rolled back, so it drifts. Keep the committed value in the previous bar's buffer slot and recompute the forming bar from there.

How do I translate varip to MQL5?

Use a static or global variable and reset it when the newest bar's open time changes. That reproduces intrabar persistence on a live chart; there is nothing to reproduce on history, where Pine runs each bar once anyway.

Why does my converted counter show one more than TradingView on the live bar?

Because the MQL5 code increments a persistent variable on every tick while Pine rolls it back before each tick. Either read the previous bar's committed value from a buffer, or snapshot the variable at the start of the forming bar and restore it before each recalculation.

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