iClose, iHigh, iLow, iTime in Pine Script: close[shift]

Short answer

On the chart's own symbol and timeframe, iClose(_Symbol, _Period, n) is close[n]. For another timeframe or symbol use request.security; the last completed bar without repainting is request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on).

iClose(symbol, timeframe, shift) and its siblings iOpen, iHigh, iLow, iVolume, iTickVolume and iTime return one value of a bar counted back from the newest bar of any symbol and timeframe. In Pine Script the answer depends on what the arguments are. For the chart's own symbol and timeframe it is the history operator: iClose(_Symbol, _Period, n) is close[n]. For another timeframe or symbol it is request.security, and to read the last completed bar of that timeframe without repainting the form is request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on).

What iClose computes

The shift counts from the newest bar of the requested series at the moment of the call, newest-first, regardless of any ArraySetAsSeries setting: shift 0 is the forming bar, shift 1 the last completed one. The symbol argument accepts _Symbol or NULL for the chart symbol, the timeframe _Period, PERIOD_CURRENT or 0 for the chart timeframe. If the requested history is not loaded yet the function returns 0 (and iTime returns 0), and the terminal starts downloading it in the background, which is why careful MQL5 code checks for zero and retries on the next tick. iTime returns a datetime, seconds since 1970, of the bar's open.

The important consequence is that the shift is relative to now, not to the bar you are calculating. Inside an OnCalculate loop over history, iClose(_Symbol, PERIOD_D1, 1) is yesterday relative to today for every bar of the loop, which is a classic repainting bug. The correct per-bar form maps the chart bar's time to a daily shift with iBarShift(_Symbol, PERIOD_D1, time[i]) and reads shift + 1.

Pine's history operator has the per-bar meaning built in: close[1] on each historical bar is the bar before that bar. And request.security evaluates its expression on the other timeframe and aligns the result to each chart bar, so the iBarShift step disappears too.

The Pine Script equivalent

Previous day's close and high on an intraday chart, the textbook use of iBarShift plus iClose.

//@version=6
indicator("Previous higher-timeframe bar", overlay = true)

// Same chart, same symbol: iClose(_Symbol, _Period, n) is just close[n].
lastClose = close[1]

// Other timeframe: the last COMPLETED daily bar, on history and realtime alike,
// is expr[1] with lookahead on. This is iClose(_Symbol, PERIOD_D1, shift + 1) in MQL5.
[htfClose, htfHigh] = request.security(syminfo.tickerid, "D", [close[1], high[1]], lookahead = barmerge.lookahead_on)

// Bar open time of the previous chart bar, in milliseconds (MQL5 iTime gives seconds).
prevBarTime = time[1]

plot(htfClose, "Previous day close", color = color.rgb(255, 69, 0))
plot(htfHigh,  "Previous day high",  color = color.rgb(70, 130, 180))
plot(lastClose, "Previous close", color = color.new(color.gray, 60))
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrOrangeRed
#property indicator_label1  "Previous day close"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrSteelBlue
#property indicator_label2  "Previous day high"

double HtfClose[];
double HtfHigh[];

int OnInit()
{
   SetIndexBuffer(0, HtfClose, INDICATOR_DATA);
   SetIndexBuffer(1, HtfHigh,  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[])
{
   int start = (prev_calculated == 0) ? 0 : prev_calculated - 1;
   for(int i = start; i < rates_total; i++)
   {
      // Which daily bar contains this chart bar? Shift + 1 is the day before it,
      // i.e. the last daily bar that had closed when this chart bar was forming.
      int shift = iBarShift(_Symbol, PERIOD_D1, time[i], false);
      if(shift < 0)
      {
         HtfClose[i] = EMPTY_VALUE;
         HtfHigh[i]  = EMPTY_VALUE;
         continue;
      }
      HtfClose[i] = iClose(_Symbol, PERIOD_D1, shift + 1);
      HtfHigh[i]  = iHigh(_Symbol, PERIOD_D1, shift + 1);
   }
   return(rates_total);
}
MQL5Pine
iClose(_Symbol, _Period, n)close[n] (in an EA, see the shift note below)
iHigh / iLow / iOpen(_Symbol, _Period, n)high[n], low[n], open[n]
iVolume / iTickVolume(_Symbol, _Period, n)volume[n]
iTime(_Symbol, _Period, n)time[n] / 1000 (Pine is milliseconds)
iClose(_Symbol, PERIOD_D1, iBarShift(...) + 1)request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on)
iClose("EURUSD", _Period, n)request.security("FX:EURUSD", timeframe.period, close[n])
iBars(_Symbol, _Period)bar_index + 1
iBarShift(sym, tf, t)No function; request.security does the alignment

Where the two differ

EA shifts. In an Expert Advisor's OnTick, shift 1 is the bar that just closed. A Pine strategy evaluates at a bar's close, where that bar is offset 0. So in strategy code iClose(_Symbol, _Period, 1) becomes close, not close[1]. In an indicator loop that indexes by bar, the shift is relative to the bar and the plain close[n] mapping holds.

Time units. MQL5 datetime is seconds; Pine time is milliseconds since 1970 UTC. Multiply or divide by 1000 at every boundary, including timestamp() and str.format_time().

Session boundaries. MetaTrader's daily bar follows the broker's server time; TradingView's follows the exchange session of the data feed. On forex a "previous day high" can differ between the platforms by the hours of the time-zone offset. This is a data difference, not a code bug.

Missing data. MQL5 returns 0 for unavailable history; Pine returns na. Code that tests if(iClose(...) == 0) becomes if na(x).

Limits. Pine caps the number of unique request.* calls per script (40 by default); an MQL5 program that calls iClose for dozens of symbols has no such cap, so in Pine fetch several values per call as a tuple, as the example does.

What the Stratlate converter emits

The MQL5 to Pine engine maps iClose, iOpen, iHigh, iLow and iVolume to close[shift] and the like, and iTime to (time[shift] / 1000) so datetime arithmetic stays in seconds (PineCatalog bar-history accessors). The symbol and timeframe arguments are dropped on that path, which is correct only for the chart's own series. A fixed timeframe above H1 that is a whole number of hours, days or weeks takes a different path (ExprLowering.lowerHtfSeriesRead): iClose(_Symbol, PERIOD_D1, iBarShift(_Symbol, PERIOD_D1, time[i]) + 1) in the program above came out as request.security(syminfo.tickerid, "D", close[1], lookahead=barmerge.lookahead_on), the same as the hand-written version, with the iBarShift folded into it. A timeframe taken from an input, or a timeframe at or below H1, is not routed through request.security; it reads the chart's series, and a standalone iBarShift is reported as unsupported ("Pine has no time-keyed bar lookup"). In an EA the engine also moves shifts one bar (MQL shift s becomes Pine offset s - 1). Check the report for those lines and convert input-driven timeframes by hand.

Pitfalls

  • Writing request.security(..., close) with lookahead_on and no [1]. On history this reads the final close of a daily bar that had not finished yet: a backtest that looks perfect and cannot be traded.
  • Translating iClose(_Symbol, PERIOD_D1, 1) from inside a history loop literally. If the MQL5 code itself had the "relative to now" bug, the Pine version with proper alignment will look different on history; that is the original being wrong, not the conversion.
  • Comparing iTime values with Pine time without the factor 1000. Symptom: conditions that are never true, or dates in 1970.
  • Using the broker symbol name in Pine. "EURUSD.m" does not exist on TradingView; use an exchange-prefixed ticker like "FX:EURUSD" or "OANDA:EURUSD".
  • Requesting a lower timeframe with request.security. It returns only the last intrabar value per chart bar; use request.security_lower_tf to get all of them as an array.

FAQ

Is close[1] in Pine exactly iClose(_Symbol, _Period, 1)?

In an indicator evaluated per bar, yes: one bar before the current one. In an EA's OnTick versus a Pine strategy, no: the EA's shift 1 is the strategy's close, because the strategy runs when that bar closes.

How do I get the current day's high so far, like iHigh(_Symbol, PERIOD_D1, 0)?

request.security(syminfo.tickerid, "D", high, lookahead = barmerge.lookahead_on) gives it on the realtime bar but leaks the day's final high into historical bars. For a non-repainting running high, track it yourself: reset a var on timeframe.change("D") and take math.max with high on each bar.

What replaces iBarShift?

Usually nothing, because request.security already aligns the other timeframe's bar to each chart bar. To find how many chart bars ago something happened, use ta.barssince(condition) or store bar_index in a var when it happens.

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

Related