OnTick in Pine Script: per-bar strategy evaluation
Short answer
A Pine strategy body already runs once per bar close, with orders filled at the next bar's open. Drop the new-bar gate and shift every history read by one bar: shift 1 becomes [0].
OnTick is called by MetaTrader for every incoming price change, and most Expert Advisors immediately filter that down to "once per new bar" by comparing iTime(_Symbol, _Period, 0) with the time they saw last. A Pine Script strategy already works that way: the script body is evaluated once when each bar closes and orders are filled at the next bar's open. The equivalent of an OnTick with a new-bar gate is a plain strategy() body with the gate removed, and a one-bar shift in every history read.
What OnTick computes
An EA has no price arrays handed to it. Inside OnTick you ask for data with iClose, iHigh, CopyBuffer and friends, where shift 0 is the bar that is forming right now and shift 1 is the last completed bar. A gated EA therefore runs on the first tick of a new bar, sees the just-closed bar at shift 1, and sends a market order that fills at (roughly) the new bar's open price. Without a gate it runs on every tick and must make its own decisions idempotent, typically by checking PositionSelect before trading again.
A Pine strategy evaluates on the close of each historical bar. At that moment close is the bar that has just completed, so it corresponds to the EA's shift 1, and close[1] to shift 2. An order placed by strategy.entry on that bar is filled at the open of the next bar, which is where the EA's market order filled too. On the realtime bar the strategy by default evaluates once, at the bar's close; with calc_on_every_tick = true it also runs on every tick of the realtime bar, with the bar's series values rolled back before each run.
The Pine Script equivalent
A breakout EA that buys when the last closed bar closes above the highest high of the twenty bars before it, and exits when it closes below the previous bar's low. Both versions act once per bar.
//@version=6
strategy("Breakout once per bar", overlay = true, pyramiding = 0, calc_on_every_tick = false)
lots = input.float(0.10, "Lots")
len = input.int(20, "Breakout lookback")
// The script runs on the close of each bar. "close" is the bar that has just
// completed, so it plays the role of iClose(_Symbol, _Period, 1) in an EA.
priorHigh = ta.highest(high, len)[1] // highest high of the len bars before this one
breakout = close > priorHigh
flat = strategy.position_size == 0
if breakout and flat
strategy.entry("breakout", strategy.long, qty = lots)
if not flat and close < low[1]
strategy.close("breakout")#include <Trade\Trade.mqh>
input double InpLots = 0.10; // Lots
input int InpLen = 20; // Breakout lookback
CTrade trade;
datetime lastBarTime = 0;
int OnInit()
{
trade.SetExpertMagicNumber(240601);
return(INIT_SUCCEEDED);
}
void OnTick()
{
// Act once per bar: the first tick of a new bar sees a new open time at shift 0.
datetime barTime = iTime(_Symbol, _Period, 0);
if(barTime == lastBarTime)
return;
lastBarTime = barTime;
// Shift 1 is the bar that has just closed; shift 2..InpLen+1 the bars before it.
double lastClose = iClose(_Symbol, _Period, 1);
int hiShift = iHighest(_Symbol, _Period, MODE_HIGH, InpLen, 2);
double priorHigh = iHigh(_Symbol, _Period, hiShift);
bool breakout = lastClose > priorHigh;
bool flat = !PositionSelect(_Symbol);
if(breakout && flat)
trade.Buy(InpLots, _Symbol, 0.0, 0.0, 0.0, "breakout");
if(!flat && lastClose < iLow(_Symbol, _Period, 2))
trade.PositionClose(_Symbol);
}Read the two side by side: iClose(…, 1) is close, iLow(…, 2) is low[1], iHighest(…, InpLen, 2) plus iHigh is ta.highest(high, len)[1], and the lastBarTime gate is gone. PositionSelect as a flat test is strategy.position_size == 0.
Where the two differ
| Topic | MQL5 OnTick | Pine strategy |
|---|---|---|
| Trigger | Every tick; you gate on a new bar yourself | Bar close; realtime bar also per tick only with calc_on_every_tick |
| Last closed bar | Shift 1 | Offset 0 (close) |
| Forming bar | Shift 0 (open known, close moving) | Not visible when the bar is processed at its close; on realtime, the same bar with barstate.isrealtime |
| Market fill | Current Ask/Bid on the first tick of the new bar | Next bar's open; process_orders_on_close = true fills at this bar's close |
| Confirmed bar test | Time gate on iTime(…, 0) | barstate.isconfirmed (true on the last tick of the bar) |
| Tick-level state | Globals persist between calls | varip persists between ticks; var is rolled back per tick |
| Spread | Real Bid/Ask | None in the data; model it with slippage and commission in strategy() |
The fill difference matters for backtests. The EA fills at the new bar's open plus spread; Pine fills at the new bar's open with no spread unless you set slippage in ticks. Results from the two testers agree only after you add an equivalent cost model.
What the Stratlate converter emits
The MQL5 to Pine engine lowers an EA to strategy("name", overlay=true, pyramiding=100) and moves the decisions onto the bar where Pine can make them: MQL shift s becomes Pine offset s - 1 (iClose(_Symbol, _Period, 1) is emitted as close[0], iLow(…, 2) as low[1]), and the EA's clock, TimeCurrent() or iTime(…, 0), is emitted as time_close / 1000; this is the EaBarAlignment pass in the engine source. The new-bar gate is kept literally as if (barTime == lastBarTime) … else, which is harmless because the strategy evaluates once per bar anyway. trade.Buy and trade.PositionClose go through the runtime helpers f_order_send (a strategy.entry with a generated id and, when SL/TP are given, a strategy.exit) and f_order_close (strategy.close_all()); PositionSelect is reported as an approximation. calc_on_every_tick is not set, so a tick-driven EA becomes a bar-driven strategy; compile the output and backtest it against the original on the same bars before trusting it.
Pitfalls
- Translating shift 1 as
close[1]. The EA sees the just-closed bar at shift 1; Pine sees it asclose. Keeping the shift makes every signal one bar late and the backtest will not match. Symptom: entries one bar after the EA's in the same history. - Keeping the time gate with
var lastBar = time. It compiles and works, but on the realtime bar withcalc_on_every_tickthe rolled-backvarre-opens the gate on every tick. Usebarstate.isconfirmedor leave the gate out. - Assuming tick-by-tick history. TradingView backtests on bar data; an EA that scalps inside the bar cannot be reproduced except with the Bar Magnifier (paid plans) and even then only at a lower-timeframe resolution, not per tick.
- Forgetting that
strategy.entryin the same direction while a position is open adds to it only up topyramiding. With the defaultpyramiding = 0repeated entries are ignored, so an EA that intentionally stacks positions needs the parameter raised. - Reading
strategy.position_sizeright afterstrategy.entryon the same bar. The order has not filled yet; the size changes on the next bar. The EA sees the position immediately aftertrade.Buyreturns.
FAQ
How do I make a Pine strategy react inside the bar like OnTick does?
Set calc_on_every_tick = true in strategy(). The realtime bar is then evaluated on every tick, but historical bars are still evaluated once at their close, so the backtest and the live behaviour differ. Use varip for anything that must survive between ticks.
What is the Pine equivalent of checking a new bar with iTime?
Usually nothing: the script runs once per bar. If you need an explicit flag, barstate.isnew is true on the first execution of a bar and barstate.isconfirmed on the last. ta.change(time) != 0 works as a hand-written test.
Does OnTick's return-early pattern map to anything in Pine?
Pine has no return at script level. Wrap the rest of the logic in an if with the inverted condition, or compute boolean conditions and pass them to strategy.entry and strategy.close directly.
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 converter