ta.highestbars in MQL5: the negative offset of the window high
Short answer
Find the index of the window maximum and subtract the current index; on oldest-first arrays that is already Pine's offset, from 0 down to -(length - 1). It is na until the window is full.
ta.highestbars(source, length) does not return the highest value; it returns where it is, as an offset from the current bar. The result is 0 when the current bar holds the window high, -1 when the previous bar does, down to -(length - 1). The one-argument form ta.highestbars(length) uses high. In MQL5 you find the index of the window maximum and subtract the current index; with oldest-first arrays that difference is already the negative offset Pine returns.
What ta.highestbars computes
Scan the length values ending on the current bar, locate the maximum, and report its position as -k where k is the number of bars back. The window includes the current bar, so 0 is a possible answer and means a fresh high. The result is na until length bars exist. Typical uses are "bars since the 20-bar high" (-ta.highestbars(high, 20)) and reading another series at that bar, close[-ta.highestbars(high, 20)], which is how the Aroon indicator and some divergence detectors are written.
Two exactly equal highs inside one window are a tie. Real prices rarely tie, but an indicator source with few distinct values (a rounded oscillator, a step function) ties constantly, and which bar is reported then depends on the implementation. See the pitfalls.
The MQL5 equivalent
Pine: plot the offset itself, which draws as a staircase from 0 down to -19 and jumps back to 0 on each new high.
//@version=6
indicator("highestbars")
len = input.int(20, "Length")
hb = ta.highestbars(high, len)
plot(hb, "Offset", style=plot.style_histogram)MQL5. Oldest-first arrays make the arithmetic direct: the index of the maximum minus the current index is 0 or negative, exactly Pine's value.
//+------------------------------------------------------------------+
//| Offset of the window high: Pine's ta.highestbars(high, len) |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_label1 "highestbars"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrDodgerBlue
#property indicator_maximum 0
input int Length = 20;
double Offset[];
// ta.highestbars(src, len): 0 when the current bar is the window high,
// -1 when the previous bar is, down to -(len-1). The scan runs from the
// oldest cell to the newest; with a strict '>' an exact tie keeps the
// older bar (equal highs on real prices are rare, see Pitfalls).
double HighestBarsAt(const double &src[], const int i, const int len)
{
if(len <= 0 || i < len - 1) return EMPTY_VALUE;
int best = i - len + 1;
for(int k = best + 1; k <= i; k++)
if(src[k] > src[best]) best = k;
return (double)(best - i);
}
int OnInit()
{
SetIndexBuffer(0, Offset, INDICATOR_DATA);
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++)
Offset[i] = HighestBarsAt(high, i, Length);
return rates_total;
}ArrayMaximum(high, i - Length + 1, Length) - i gives the same answer in one line; the explicit loop is shown because it makes the tie rule visible. In series order the sign flips: ArrayMaximum(high, i, Length) returns an index at or above i, and the Pine offset is i - idx.
Where the two differ
| Topic | Pine Script | MQL5 |
|---|---|---|
| Sign | 0 or negative | Oldest-first: idx - i is already negative. Series: i - idx |
| Early bars | na | Guard i < len - 1; the Stratlate runtime answers 0 there, see below |
| Reading another series at that bar | close[-hb] | close[i + hb] oldest-first (hb is negative), close[i - hb] in series order |
| Ties | Implementation-defined; verify on your chart | Whatever your comparison does: > keeps the older bar, >= keeps the newer |
| Type | int-like series | Store as double in a buffer; cast with (int) before indexing |
What the Stratlate converter emits
The emitter handles ta.highestbars as a windowed builtin and emits pine_highestbars(src, bar, len); the one-argument form is rewritten to high, so ta.highestbars(len) becomes pine_highestbars(high, __pineBar, (int)(len)), and a long source such as volume uses an overload for that array type. The runtime scans the window from oldest to newest with a strict >, so on an exact tie it reports the older bar, and it returns (best - i) as a double. One difference from Pine is real and worth knowing: on the first len - 1 bars, where Pine gives na, the helper returns 0 rather than na. The call is not flagged as an approximation in the report, so check early-bar output if your script reads it.
Pitfalls
- Returning the index instead of the offset. Symptom: values in the thousands that grow with the chart instead of a 0 to -19 staircase.
- Wrong sign in series order. Symptom: positive numbers where TradingView shows negatives; any
close[-hb]read then points into the future and reads the current bar. - Using
-ta.highestbarsas an age and forgetting that it saturates atlen - 1. Symptom: "bars since high" never exceeds 19 for a 20-bar window; useta.barssincefor an unbounded age. - Ties on a low-resolution source. Symptom: offsets that disagree with TradingView by several bars on flat stretches while the highest value itself matches.
- Indexing with the double returned from a buffer without a cast. Symptom: a compile error about implicit conversion, or truncation surprises if the value is not integral.
FAQ
Why is ta.highestbars negative?
Pine expresses positions relative to the current bar, and earlier bars are negative offsets. The current bar is 0, the previous bar -1, and the oldest bar of a 20-bar window -19.
How do I get bars since the highest high in MQL5?
Negate the offset: -(idx - i) on oldest-first arrays. It is capped at len - 1 by construction; for an uncapped count track the bar index of the last new high, as ta.barssince does.
Does ta.highestbars return na before the window is full?
In Pine yes. The Stratlate runtime helper returns 0 on those bars instead, which is one of the few early-bar differences in the ta.* family and is worth checking if a script reads the value in its first bars.
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