OnCalculate in Pine Script: the bar loop becomes one line
Short answer
There is no handler: the Pine script body runs once per bar, oldest first. Keep the loop body, drop the loop and the index, and the rates_total and prev_calculated bookkeeping disappears.
OnCalculate is the MQL5 indicator entry point: MetaTrader calls it on every tick with the whole price history as arrays and expects your code to loop over the bars that still need computing. Pine Script has no such handler. The whole script body is run once for every bar, oldest first, and the current bar is implicit. The Pine equivalent of an OnCalculate loop is the loop body with the index removed, and the rates_total / prev_calculated bookkeeping disappears entirely.
What OnCalculate computes
The signature with ten parameters gives you rates_total (bars on the chart), prev_calculated (what the previous call returned, 0 on the first call and after a history reload) and the arrays time[], open[], high[], low[], close[], tick_volume[], volume[], spread[]. The arrays are oldest-first unless you call ArraySetAsSeries, so bar i uses close[i] and the bar before it is close[i-1]. The return value becomes the next call's prev_calculated. The usual idiom is a for loop from prev_calculated - 1 (recompute the forming bar) to rates_total - 1, with a guard that returns 0 while there are too few bars, which makes MetaTrader call again from scratch.
Pine's model: every bar is a function call of the whole script. Built-ins like close are the value on the current bar, close[1] the bar before, and anything you assign is itself a series whose past values you can read with []. Pine keeps the history for you, so there is no buffer array to fill and no "where did I stop last time" to track. On the realtime bar the script re-runs on every tick and the bar's values are rolled back before each run, which is the same effect as recomputing index prev_calculated - 1.
The Pine Script equivalent
Ten-bar momentum, written both ways. The MQL5 indicator is complete and compiles; the Pine script is complete and parses.
//@version=6
indicator("Momentum (close minus close n bars ago)", overlay = false)
len = input.int(10, "Lookback")
// No loop: this line runs once per bar, oldest bar first.
// close[len] is na on the first len bars, so mom is na there and the plot leaves a gap.
mom = close - close[len]
plot(mom, "Momentum", color = color.rgb(30, 144, 255))#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
input int InpLen = 10; // Lookback
double MomBuffer[];
int OnInit()
{
SetIndexBuffer(0, MomBuffer, INDICATOR_DATA);
PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpLen);
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[])
{
if(rates_total <= InpLen)
return(0); // not enough bars yet: ask to be called again
// First call (or history reload): start at the first bar that has InpLen bars behind it.
// Later calls: recompute only the bar that is still forming (prev_calculated - 1).
int start = (prev_calculated == 0) ? InpLen : prev_calculated - 1;
for(int i = start; i < rates_total; i++)
MomBuffer[i] = close[i] - close[i - InpLen];
return(rates_total); // becomes prev_calculated on the next tick
}Everything inside the MQL5 loop body maps one-to-one: close[i] is close, close[i - InpLen] is close[len], and the assignment to MomBuffer[i] is a plain variable declaration. The three lines that compute start and the early return have no counterpart because Pine never needs to know which bars are already done.
Where the two differ
| Topic | MQL5 OnCalculate | Pine Script |
|---|---|---|
| Execution unit | One call per tick, loop over bars inside | One run per bar; the realtime bar re-runs per tick |
| Index direction | Oldest-first unless ArraySetAsSeries | Always newest-first: [0] is now, [1] one bar back |
| Warm-up | return(0) or guard on i < period; buffer holds EMPTY_VALUE | Past values that do not exist are na; the plot leaves a gap |
| Bar count | rates_total | bar_index + 1 so far, last_bar_index + 1 in total |
| Incremental state | prev_calculated, static or global variables | var keeps a value across bars; varip across ticks |
| Output | Buffers bound with SetIndexBuffer | plot() of any series |
| Multiple passes | Allowed: a second loop can re-read the first buffer | Not possible; a value can only read its own past, never future bars |
The last row is the one that breaks hand conversions. An OnCalculate that fills a buffer forward and then smooths it backward (or reads Buf[i+1]) is doing something Pine cannot do on a per-bar basis; you need to restate the algorithm so each bar depends only on bars before it. Anything that reads the future repaints by definition, so the restatement is usually an improvement.
What the Stratlate converter emits
The MQL5 to Pine engine recognises the per-bar sweep in OnCalculate (ascending for (i = prev_calculated...; i < rates_total; i++) or the descending limit form) and lowers it to one per-bar reassignment of each buffer, so the program above comes out as MomBuffer := close - close[InpLen] with a plot() per buffer. rates_total is rendered as bar_index + 1 and prev_calculated as bar_index (catalog entries, reported as clean), and the warm-up guard if (rates_total <= InpLen) return(0) is kept as a harmless statement while the real warm-up comes from na history and a bar_index < drawBegin ? na : … wrapper on the plot. An inner loop whose shape the lowering does not fold (a running highest/lowest over high[i + k], for example) is kept as a Pine for loop over history reads, and the report lists every identifier and call that was not mapped cleanly so you know what to review. Compile the result in TradingView and compare it on the same bars; the report lists every call that was approximated.
Pitfalls
- Translating
close[i-1]asclose[-1]or keepingclose[i]. In Pine the offset is relative to now and positive means the past:close[i-1]inside an oldest-first loop isclose[1]. Symptom: compile error "negative index" or a plot that lags by one bar. - Keeping the loop.
for i = 0 to bar_indexin Pine recomputes the whole history on every bar, which is quadratic and hits the execution time limit on long charts. Symptom: "Script execution timeout" or "loop takes too long". - Rebuilding
prev_calculatedlogic withvarcounters. It is not needed and usually ends up wrong on the realtime bar, where Pine re-runs the bar from scratch each tick. Symptom: values drift on the live bar and snap back when a new bar opens. - Expecting
return(0)to blank the output. In MQL5 it makes the next call recompute from zero; in Pine the equivalent is doing nothing, because missing history is alreadyna. - Reading the forming bar as if it were closed.
OnCalculateand Pine both see the forming bar, but Pine's realtime bar re-evaluates every tick; usebarstate.isconfirmedif a value must only be taken once per bar.
FAQ
Is there any Pine function that runs once per tick like OnCalculate?
No. The script body runs once per historical bar and once per tick on the realtime bar. Indicators recalculate on every realtime tick; strategies do so only when calc_on_every_tick=true is set in the declaration. There is no separate handler to register.
What replaces prev_calculated when I need to carry state between bars?
Declare the variable with var, which initialises once and keeps its value from bar to bar, and update it with :=. For state that must survive between ticks on the realtime bar use varip. Everything else is a normal series whose past you read with [n].
How do I handle the short form OnCalculate(rates_total, prev_calculated, begin, price[])?
The price[] array is whatever the user applied the indicator to (close by default, or another indicator's buffer). In Pine use input.source(close, "Source") and read that variable where the MQL5 code reads price[i]. The begin parameter has no equivalent and can be dropped.
Convert the whole program
Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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 converterRelated
- Pine close[1] vs MQL5 arrays: indexing and ArraySetAsSeries
- How to Convert an MQL4 or MQL5 Indicator to Pine Script
- ArraySetAsSeries in Pine Script: index direction and []
- bar_index in MQL5: rates_total, prev_calculated and the loop
- Convert MQL5 to Pine Script (v6) — online MT5 to TradingView converter