bar_index in MQL5: rates_total, prev_calculated and the loop
Short answer
In an MQL5 indicator, bar_index is the loop index i of an oldest-first loop over OnCalculate's arrays, and last_bar_index is rates_total - 1. Start the loop at prev_calculated - 1, which tells you how many bars the previous call already handled.
bar_index is the zero-based number of the current bar counted from the oldest bar on the chart; last_bar_index is the index of the newest bar. In an MQL5 indicator those are the loop variable i of an oldest-first loop over OnCalculate's arrays and rates_total - 1. prev_calculated has no Pine counterpart: it tells you how many bars the previous call already handled, so you know where to restart.
What bar_index computes
Pine runs the script once per bar from the oldest bar forward, and bar_index is 0 on the first bar and increments by one per bar. It is an integer series, so bar_index[1] is bar_index - 1. last_bar_index is the same on every bar of one execution: the index of the realtime bar, or of the last historical bar if the market is closed. Typical uses are last_bar_index - bar_index < 100 to restrict drawings to recent bars, bar_index % n == 0 for periodic work, and label.new(bar_index, high, ...) to position objects by bar rather than by time.
The count depends on how much history TradingView loads, which depends on the plan and the timeframe. A script that stores absolute bar_index values is therefore not portable between charts; distances between bars are.
The MQL5 equivalent
OnCalculate receives rates_total, the number of bars, and prev_calculated, the value the previous call returned (0 on the first call and after a history reload). The standard loop runs from prev_calculated - 1 (the forming bar, recomputed) to rates_total - 1, and the loop index is Pine's bar_index.
//@version=6
indicator("bar index demo")
plot(bar_index, "bar_index")
plot(last_bar_index - bar_index, "bars to the right")
if barstate.islast
label.new(bar_index, 0, str.tostring(bar_index))#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 2
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_label1 "bar_index"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrOrangeRed
#property indicator_label2 "bars to the right"
double IndexBuf[];
double RemainBuf[];
int OnInit()
{
SetIndexBuffer(0, IndexBuf, INDICATOR_DATA);
SetIndexBuffer(1, RemainBuf, 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: last_bar_index
int lastBar = rates_total - 1;
// First call (prev_calculated == 0): every bar. Later calls: the
// forming bar again plus any new bars, which is what Pine does too.
int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
IndexBuf[i] = i; // Pine: bar_index
RemainBuf[i] = lastBar - i; // Pine: last_bar_index - bar_index
}
// Pine: if barstate.islast -> label.new(bar_index, ...)
if(start <= lastBar)
Comment("bar_index of the newest bar: ", lastBar,
" (rates_total=", rates_total, ", prev_calculated=", prev_calculated, ")");
return rates_total;
}
void OnDeinit(const int reason) { Comment(""); }Returning rates_total is what makes the next call's prev_calculated correct. Returning 0 forces a full recalculation on the next tick, which is the right response when a handle is not ready, but a bug if done unconditionally: the indicator then recomputes the whole chart on every tick.
Where the two differ
| Aspect | Pine | MQL5 |
|---|---|---|
| Current bar | bar_index | loop variable i in an oldest-first loop |
| Newest bar | last_bar_index | rates_total - 1 |
| Number of bars | last_bar_index + 1 | rates_total; also Bars(_Symbol, _Period) outside OnCalculate |
| Which bars run | all on load, then the realtime bar per tick | all when prev_calculated == 0, then from prev_calculated - 1; the program decides |
| History reload | script restarts, bar_index renumbered | prev_calculated arrives as 0; static state must be reset by the program |
| Series-indexed access | n/a | after ArraySetAsSeries(arr, true) the newest bar is index 0 and bar_index is rates_total - 1 - shift |
| Drawing position | by bar_index or by time | objects take a datetime; use time[i] |
What the Stratlate converter emits
The engine's OnCalculate computes const int start = (prev_calculated > 1) ? prev_calculated - 1 : 0; and loops __pineBar from there to rates_total - 1, calling a per-bar function; bar_index is emitted as __pineBar and last_bar_index as __pineLastBar, a global set to rates_total - 1 at the top of each call. Both are exact. The converted example wrote Buf0[__pineBar] = __pineBar and Buf1[__pineBar] = (__pineLastBar - __pineBar) with no notes in the report; the label.new went through the runtime's object helper and is positioned by the bar's time.
Pitfalls
- Starting the loop at
prev_calculated: the forming bar is written once at its first tick and never again, so the last value on the chart is frozen until a new bar opens. - Starting at 0 on every call: correct output, but the whole history is recomputed per tick. Symptom: CPU load grows with chart length and the terminal lags on fast markets.
- Reading
rates_totalas Pine'sbar_index: it is the count, so the newest index isrates_total - 1. Off by one in a loop condition reads past the array. - Storing
bar_indexvalues instaticvariables and not resetting them whenprev_calculated == 0: after a history reload the stored indices point at different bars. - Using
bar_indexas an object coordinate: MQL5 objects are anchored by time, so passtime[i], noti. Symptom: labels pile up in January 1970.
FAQ
What is bar_index in MQL5?
There is no built-in variable. In an indicator it is the index i of the bar being computed in an oldest-first loop over the OnCalculate arrays; the newest bar is rates_total - 1. In an Expert Advisor there is no bar loop, and a bar is identified by its shift (0 = current) or its open time.
What does prev_calculated correspond to in Pine?
Nothing. Pine decides itself which bars to run. prev_calculated is the value your OnCalculate returned last time, so prev_calculated - 1 is the index of the bar that was forming then and must be recomputed now.
Why does last_bar_index - bar_index not match "shift" in MQL5?
It does: both count bars back from the newest one. The difference is the direction of the arrays. With oldest-first arrays the newest bar is rates_total - 1 and shift is rates_total - 1 - i; after ArraySetAsSeries(arr, true) the shift is the index itself.
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