ta.barssince in MQL5: a stateful counter that survives ticks

Short answer

MQL5 has no equivalent function. Keep the index of the most recent true bar per bar, Last[i] = cond ? i : Last[i-1], and return i - Last[i], with EMPTY_VALUE until the condition has been true once.

ta.barssince(condition) returns the number of bars since condition was last true: 0 on the bar it is true, 1 on the next, and so on, and na until it has been true at least once. MQL5 has no equivalent function; the faithful translation keeps one piece of state per bar, the index of the most recent true bar, and derives the count from it.

What ta.barssince computes

Conceptually a counter: reset to 0 when the condition holds, otherwise the previous bar's value plus one. Before the first true the value is na, not 0 and not a large number, which matters when the result feeds a comparison: ta.barssince(x) < 5 is false while the result is na, and ta.barssince(x) > 5 is also false. The condition is evaluated on the current bar first, so on the realtime bar the count can fall to 0 mid-bar and come back when the condition stops holding before the close.

Unlike -ta.highestbars, the count is unbounded: it keeps growing for as long as the condition stays false. Scripts combine it with ta.valuewhen to describe "the last signal was n bars ago at price p".

The MQL5 equivalent

Pine: bars since a close above the previous bar's high.

//@version=6
indicator("Bars since breakout")
cond = close > high[1]
since = ta.barssince(cond)
plot(since, "Bars since")

MQL5. The state is a calculation buffer holding, for every bar, the index of the latest true bar (-1 for never). The displayed value is the difference. Because the state of bar i is derived only from bar i - 1 and bar i's own condition, recomputing the forming bar on every tick gives the same answer each time.

//+------------------------------------------------------------------+
//| Bars since a breakout close: Pine's ta.barssince(cond) in MQL5    |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   1
#property indicator_label1  "bars since"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue

double Since[];     // what ta.barssince returns
double LastTrue[];  // index of the latest bar where the condition held, -1 if never

int OnInit()
{
   SetIndexBuffer(0, Since,    INDICATOR_DATA);
   SetIndexBuffer(1, LastTrue, 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 > 1) ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      // The condition: a close above the previous bar's high.
      bool cond = (i > 0) && close[i] > high[i - 1];

      // The counter lives in a buffer, not a static int, so recalculating
      // the forming bar on every tick reads the state of bar i-1 and never
      // double-counts.
      double prev = (i > 0) ? LastTrue[i - 1] : -1.0;
      LastTrue[i] = cond ? (double)i : prev;

      // na until the condition has been true once; 0 on the bar it is true.
      Since[i] = (LastTrue[i] < 0) ? EMPTY_VALUE : i - LastTrue[i];
   }
   return rates_total;
}

A static int counter incremented in the loop is the tempting shortcut. It fails in two ways: OnCalculate re-runs the forming bar on every tick, so the counter advances once per tick instead of once per bar, and a history reload (prev_calculated == 0) does not reset it. Per-bar state in a buffer has neither problem.

Where the two differ

TopicPine ScriptMQL5
Before the first truenaEMPTY_VALUE in the buffer; comparisons must test for it explicitly, as EMPTY_VALUE < 5 is simply false and EMPTY_VALUE > 5 is true
StateImplicit per-bar seriesA buffer (INDICATOR_CALCULATIONS) or any array indexed by bar; not a scalar
Realtime barRecomputed each tick from the previous bar's stateSame, if the state is read from i - 1; wrong if a scalar is mutated
Typeint seriesdouble in buffers; cast when indexing with it
Index directionCount grows toward the presentOldest-first: i - LastTrue[i]; series order needs the mirror arithmetic

What the Stratlate converter emits

The emitter gives every ta.barssince call site its own state array and emits pine_barssince((cond), __stN, __pineBar). The runtime stores in state[i] the bar index of the most recent true as of bar i, taken from state[i-1] unless the condition holds now, and returns na while that index is negative or unwritten, otherwise i - state[i] as a double. The comment in PineRuntime.mqh states the reason for the design: a recomputed newest bar cannot advance the count twice. The example above converts CLEAN to since = pine_barssince((cond), __st0, __pineBar); the mapping is exact.

Pitfalls

  • A static or global counter. Symptom: the value climbs by dozens within a single bar on a live chart, and differs between a fresh attach and a running chart.
  • Starting at 0 instead of na. Symptom: logic such as barssince < 3 is true on the first bars of the chart, where TradingView's is false, producing early signals in the Strategy Tester.
  • Comparing the buffer value without an EMPTY_VALUE test. Symptom: since > 20 is true on every bar before the first occurrence, because EMPTY_VALUE is a huge double.
  • Evaluating the condition with series-ordered arrays while writing the state oldest-first. Symptom: the count resets on the wrong bars by a fixed offset.
  • Resetting the state only in OnInit. Symptom: stale counts after a history reload or a timeframe change; derive bar 0 from -1 inside the loop instead.

FAQ

What does ta.barssince return before the condition has ever been true?

na. In MQL5 write EMPTY_VALUE and test for it before any comparison, since EMPTY_VALUE itself compares as a very large positive number.

Why not use a static int counter in OnCalculate?

Because OnCalculate recomputes the forming bar on every tick, so the counter would advance once per tick, and because it survives a history reload. Per-bar state indexed by bar is recomputed correctly in both cases.

How does the Stratlate engine implement it?

With a per-call-site state array that holds the index of the last true bar; the runtime helper pine_barssince returns i minus that index, or na while the condition has never held.

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