ta.pivothigh in MQL5: confirmed right bars late, vs iFractals

Short answer

Loop over left + right + 1 cells: the pivot is src[i-right] when no left bar is higher and no right bar is as high, returned right bars late on the confirming bar. MetaTrader's iFractals is the special case left = right = 2, stored on the pivot bar itself.

ta.pivothigh(source, leftbars, rightbars) finds swing highs: a bar whose source is higher than the leftbars bars before it and the rightbars bars after it. The two-argument form uses high. The point that trips up almost everyone: the function returns the pivot's value on the bar that confirms it, rightbars bars after the pivot bar, and na on every other bar. In MQL5 the same test is a loop over left + right + 1 cells, and MetaTrader's own iFractals is the special case left = right = 2, stored on the pivot bar.

What ta.pivothigh computes

On bar n, the candidate is the bar rightbars back, source[rightbars]. It is a pivot high when none of the leftbars bars before it is higher and none of the rightbars bars after it (up to and including bar n) is as high or higher. If so, the function returns the candidate's value on bar n; otherwise na. A pivot can only be known once the rightbars bars after it have printed, so the value appears late by design. Plotting with offset = -rightbars moves the marker back onto the pivot bar; the delay in knowing does not go away.

This is the source of the "repainting" complaint around pivots. A script that reads ta.pivothigh and draws it with a negative offset looks, on history, as if it knew the pivot on the pivot bar. Live, nothing appears until rightbars bars later. Neither TradingView nor any faithful MQL5 port can do otherwise. A strategy that enters on the pivot bar at the pivot price is looking into the future; the engine's differential verifier runs both versions bar by bar, which is exactly where such look-ahead shows up as a mismatch.

Ties: the Stratlate runtime, and MetaTrader's iFractals, allow a left bar to equal the candidate but disqualify the candidate if a right bar equals it, so a plateau of equal highs produces one pivot, at its last bar. Verify TradingView's behaviour on your own chart if a script depends on exact ties; real prices make them rare.

The MQL5 equivalent

Pine: 5/5 swing highs drawn on the pivot bar.

//@version=6
indicator("Pivot highs", overlay=true)
left = input.int(5, "Left")
right = input.int(5, "Right")
ph = ta.pivothigh(left, right)
plot(ph, "Pivot high", style=plot.style_circles, offset=-right)

MQL5. PivotHighAt returns what ta.pivothigh returns on bar i; the buffer therefore holds the value on the confirmation bar, and PLOT_SHIFT set to -Right draws it on the pivot bar exactly as Pine's offset=-right does.

//+------------------------------------------------------------------+
//| Swing highs: Pine's ta.pivothigh(left, right) in MQL5             |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "pivot high"
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrOrangeRed
#property indicator_width1  2

input int Left  = 5;
input int Right = 5;

double Pivot[];

// ta.pivothigh(src, left, right) evaluated on bar i: the candidate is the
// bar `right` bars back. It is a pivot when no bar among the `left` older
// ones is higher and no bar among the `right` newer ones is as high. The
// result belongs to bar i (the confirmation bar), not to the pivot bar.
double PivotHighAt(const double &src[], const int i, const int left, const int right)
{
   if(i < left + right) return EMPTY_VALUE;
   int    p    = i - right;
   double cand = src[p];
   for(int k = p - left; k < p; k++)  if(src[k] > cand)  return EMPTY_VALUE;  // left: ties allowed
   for(int k = p + 1; k <= i; k++)    if(src[k] >= cand) return EMPTY_VALUE;  // right: ties disqualify
   return cand;
}

int OnInit()
{
   SetIndexBuffer(0, Pivot, INDICATOR_DATA);
   PlotIndexSetInteger(0, PLOT_ARROW, 234);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   // Same as plot(ph, offset=-right): the value is stored on the
   // confirmation bar and drawn `Right` bars to the left, on the pivot bar.
   PlotIndexSetInteger(0, PLOT_SHIFT, -Right);
   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++)
      Pivot[i] = PivotHighAt(high, i, Left, Right);
   return rates_total;
}

iFractals compares to this as follows: MetaTrader's Fractals example indicator marks bar i an upper fractal when high[i] is strictly greater than the two newer bars and greater than or equal to the two older bars, writes the value into the buffer at bar i, and stops its loop three bars before the newest bar, so both confirming bars are closed bars and the forming bar is never used. That is ta.pivothigh(2, 2) with the value moved back by two bars and the same tie rule; the only difference is timing at the right edge, where Pine also lets the forming bar act as a confirming bar, so a fractal can show in TradingView one bar before MetaTrader marks it (and can vanish again before that bar closes).

Where the two differ

TopicPine ScriptMQL5 (hand-written) and iFractals
Where the value landsOn the confirmation bar; offset=-right moves the drawingYour choice: confirmation bar plus PLOT_SHIFT, or write Buf[i - right] directly as iFractals does
Delayrightbars barsIdentical in a custom loop; iFractals waits for two closed bars, one bar more than Pine on the live edge
ParametersAny left and rightiFractals is fixed at 2 and 2; a custom loop takes any
Non-pivot barsnaEMPTY_VALUE with PLOT_EMPTY_VALUE set
Realtime barThe newest bar can break a pending candidate, so a candidate is not a pivot until right bars closeRecompute bar i each tick; write EMPTY_VALUE as well as values so a withdrawn pivot is erased

What the Stratlate converter emits

Both arities are handled: ta.pivothigh(left, right) converts to pine_pivothigh(high, __pineBar, (int)(left), (int)(right)) and the three-argument form passes the named source array. The runtime returns na while i < left + right, takes src[i - right] as the candidate, returns na if any value in the window is na, disqualifies the candidate on a strictly higher left bar or an equal-or-higher right bar, and otherwise returns the candidate on the confirmation bar, which is Pine's timing. A plot(..., offset=-right) becomes PlotIndexSetInteger(n, PLOT_SHIFT, (int)((-right))). The mapping is exact.

Pitfalls

  • Writing the pivot on the pivot bar and then reading it on that bar in trading logic. Symptom: a backtest that buys the exact top; live, the signal arrives right bars later or not at all.
  • Not erasing a withdrawn candidate. Symptom: a pivot marker that TradingView does not show, left behind after the forming bar made a higher high.
  • Letting the loop run to the newest bar with Buf[i - right] writes but no guard for i < left + right. Symptom: array out of range on the first bars.
  • Assuming iFractals equals ta.pivothigh(2, 2) on the same bar. Symptom: markers two bars apart; the values agree, the placement does not, until you apply the shift.
  • Using >= on the left side or > on the right side. Symptom: on a plateau of equal highs, the pivot moves to a different bar than the runtime's, or two pivots appear.

FAQ

Why does ta.pivothigh show up several bars after the high?

Because a swing high is defined by the bars after it. The function cannot confirm the pivot until rightbars bars have closed, so it returns the value on that later bar and na before.

Is iFractals the same as ta.pivothigh?

It is the fixed 2-left, 2-right case with the value stored on the fractal bar instead of the confirmation bar. The comparison rule in MetaTrader's Fractals example matches the Stratlate runtime: strict against the newer bars, non-strict against the older ones.

How do I draw the marker on the pivot bar in MQL5?

Either store the value on the confirmation bar and set PLOT_SHIFT to -right, as the example does, or write the buffer at index i - right directly. Both display the same; the first keeps the buffer identical to what ta.pivothigh returns.

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

Related