Williams Fractals: TradingView (Pine Script) to MT5 (MQL5)

Short answer

An up fractal is a bar whose high is above the highs of the n bars on each side, and a down fractal the mirror with lows; MetaTrader's iFractals is the fixed n = 2 case. A fractal is confirmed only n bars later, and the two platforms express that lag differently.

A Williams fractal marks a bar whose high is above the highs of the n bars on each side (an up fractal) or whose low is below the lows on each side (a down fractal); Bill Williams used n = 2. MetaTrader 5 ships that fixed 2/2 case as iFractals. The versions below take n as an input, use the same tie rule as the terminal, and agree with iFractals when n = 2. The formula is a handful of comparisons; the part that trips people up is that a fractal can only be confirmed n bars after it happens, and the two platforms express that lag differently.

How Williams Fractals are calculated

With n = 2, bar c is an up fractal when

  • high[c] >= high[c-1] and high[c] >= high[c-2] (the two older bars), and
  • high[c] > high[c+1] and high[c] > high[c+2] (the two newer bars).

The down fractal mirrors this with lows. The asymmetric tie rule, at-least-equal towards older bars and strictly greater towards newer bars, is the one MetaTrader's bundled Fractals indicator applies; with it a flat double top produces one fractal, on the later bar, rather than none or two. Scripts that use strict comparisons on both sides mark fewer fractals, and this page uses the terminal's rule on both platforms so they agree.

Because the test needs n bars to the right, a fractal on bar c is first known when bar c + n exists. Until bar c + n closes, that bar's high is still moving and the fractal can appear and disappear within the bar. That is not repainting in the usual sense (nothing changes on closed bars), but a strategy that acts "on the fractal bar" is looking two bars into the future.

Pine Script v6 version

An original script. Pine evaluates on the newest bar, so the candidate is high[n], its older neighbours are high[n + k] and its newer neighbours high[n - k], down to high[0], the current bar. The marker is drawn n bars back with offset = -n.

//@version=6
indicator("Williams Fractals", shorttitle="Fractals", overlay=true)

n = input.int(2, "Bars on each side", minval=1)

// The candidate is the bar n bars back. Its high must be at least as high as
// the n bars before it and strictly higher than the n bars after it (the rule
// MetaTrader's Fractals uses), so a fractal is only known n bars later.
isUp   = true
isDown = true
for k = 1 to n
    isUp   := isUp   and high[n] >= high[n + k] and high[n] > high[n - k]
    isDown := isDown and low[n]  <= low[n + k]  and low[n]  < low[n - k]

plotshape(isUp,   "Up fractal",   shape.triangleup,   location.abovebar, color.teal,   offset=-n, size=size.tiny)
plotshape(isDown, "Down fractal", shape.triangledown, location.belowbar, color.maroon, offset=-n, size=size.tiny)

MQL5 version

Two DRAW_ARROW buffers. MQL5 indicators iterate bars oldest-first and can write to any index, so the natural approach is the reverse of Pine's: test bar i as the candidate, with high[i - k] older and high[i + k] newer, and write the marker directly at i. No plot shift is needed because the value already sits on the candidate bar. The price is stored in the buffer so the arrow is positioned at the fractal's high or low; PLOT_ARROW_SHIFT moves it a few pixels clear of the candle.

//+------------------------------------------------------------------+
//| Williams Fractals with n bars on each side (n = 2 is iFractals).  |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_label1  "Up fractal"
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrTeal
#property indicator_label2  "Down fractal"
#property indicator_type2   DRAW_ARROW
#property indicator_color2  clrMaroon

input int InpN = 2;  // Bars on each side

double UpBuf[], DownBuf[];

int OnInit()
  {
   if(InpN < 1)
      return INIT_PARAMETERS_INCORRECT;
   SetIndexBuffer(0, UpBuf,   INDICATOR_DATA);
   SetIndexBuffer(1, DownBuf, INDICATOR_DATA);
   PlotIndexSetInteger(0, PLOT_ARROW, 217);        // Wingdings up arrow
   PlotIndexSetInteger(1, PLOT_ARROW, 218);        // Wingdings down arrow
   PlotIndexSetInteger(0, PLOT_ARROW_SHIFT, -10);  // pixels above the high
   PlotIndexSetInteger(1, PLOT_ARROW_SHIFT, 10);   // pixels below the low
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   IndicatorSetString(INDICATOR_SHORTNAME, "Fractals(" + IntegerToString(InpN) + ")");
   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 < 2 * InpN + 1)
      return 0;
   if(prev_calculated == 0)
     {
      ArrayInitialize(UpBuf,   EMPTY_VALUE);
      ArrayInitialize(DownBuf, EMPTY_VALUE);
     }
   // A candidate at i is judged against the InpN bars after it, so the last
   // InpN + 1 candidates are re-examined on every tick until they are final.
   int start = (prev_calculated > 0) ? MathMax(prev_calculated - 1 - InpN, InpN) : InpN;
   for(int i = start; i < rates_total; i++)
     {
      UpBuf[i]   = EMPTY_VALUE;
      DownBuf[i] = EMPTY_VALUE;
      if(i + InpN >= rates_total)
         continue;                  // not enough bars to the right yet
      bool up = true, down = true;
      for(int k = 1; k <= InpN && (up || down); k++)
        {
         // >= / <= towards older bars, strict towards newer bars: the same
         // tie rule as the terminal's Fractals indicator.
         up   = up   && high[i] >= high[i - k] && high[i] > high[i + k];
         down = down && low[i]  <= low[i - k]  && low[i]  < low[i + k];
        }
      if(up)   UpBuf[i]   = high[i];
      if(down) DownBuf[i] = low[i];
     }
   return rates_total;
  }

The start index deserves a look. A normal indicator recomputes only the forming bar, but here the forming bar is one of the right-hand neighbours of the last n candidates, so those candidates are re-examined on every tick and cleared or set accordingly. Candidates nearer the right edge than n bars are left at EMPTY_VALUE until enough bars exist.

Differences you will see on the chart

TradingViewMetaTrader 5
Where the marker livesCondition is true on bar c + n; offset = -n moves the shape back to cWritten straight into buffer index c
Reading it in codeisUp is true on bar c + n; the fractal's price is high[n]UpBuf[c] holds the price on the fractal bar itself; with CopyBuffer, indexes 0 to n - 1 are always empty
Last n barsNo shapes (they would need future bars)EMPTY_VALUE for the same reason
Forming barCandidate n bars back can flicker until the bar closesSame bars flicker
Marker styleshape.triangleup above the barWingdings arrow 217/218 with a pixel offset
Native alternativeta.pivothigh(n, n) gives the price of a confirmed pivot (check its tie rule before mixing)iFractals, buffers 0 (upper) and 1 (lower), fixed n = 2

Using it in MetaTrader 5

Save as FractalsN.mq5 under MQL5\Indicators, compile with F7, attach and set Bars on each side. From an EA, create the handle with iCustom(_Symbol, _Period, "FractalsN", 2) or, for the classic case, iFractals(_Symbol, _Period), and look for the most recent non-empty value starting at index n:

double up[];
ArraySetAsSeries(up, true);
if(CopyBuffer(handle, 0, 0, 50, up) > 0)
   for(int k = 2; k < 50; k++)
      if(up[k] != EMPTY_VALUE) { lastUpFractal = up[k]; break; }

For a breakout entry, compare the current price with that stored level; do not read indexes 0 and 1, they are empty by construction.

What the Stratlate converter emits

The Pine version converts CLEAN. The for loop becomes a plain MQL5 for, the history references high[n + k] and high[n - k] become pine_hist(high, bar, n + k) reads on the oldest-first arrays, and the two boolean accumulators are ordinary globals. Each plotshape becomes a DRAW_ARROW plot whose buffer holds high[n] or low[n] when the condition is true and EMPTY_VALUE otherwise, with Wingdings arrow codes (241 and 242) set in OnInit; the offset = -n becomes PlotIndexSetInteger(plot, PLOT_SHIFT, -n), so the converted indicator keeps Pine's shape: the condition is evaluated n bars late and the plot is shifted back, rather than written at the candidate as the hand-written port does. Both draw the same markers on the same bars. The only notes are the informational drop of minval. Compile the output and compare with the chart before trading on it.

Pitfalls

  • Treating the bar where a fractal appears as the bar to trade. In the MQL5 port the marker is on bar c but did not exist until bar c + n; a backtest that reads UpBuf[c] while simulating bar c + 1 uses future data and looks far too good.
  • Recomputing only the forming bar. The last n candidates need the forming bar's high and low. If start is prev_calculated - 1 the newest fractals never appear until a full recalculation.
  • Strict comparisons on both sides. Flat tops produce no fractal in your version and one in iFractals; the two disagree on exactly the bars that matter most in ranging markets.
  • Reading CopyBuffer index 0 for "the current fractal". It is always EMPTY_VALUE; search from index n.
  • Not initialising the buffers on the first run. Bars 0 to n - 1 are never visited by the loop and hold whatever was in memory; ArrayInitialize(..., EMPTY_VALUE) when prev_calculated == 0 fixes it.

FAQ

Does iFractals give the same result as this indicator with n = 2?

Yes. Both apply at-least-equal to the two older bars and strictly greater to the two newer bars, both leave the two newest bars empty, and both store the fractal's high or low in the buffer. The only difference is cosmetic: arrow codes and pixel offsets.

Why does the fractal appear two bars after the high on TradingView?

It does not; it appears on the high itself, because offset = -n moves the shape back. What arrives two bars later is the knowledge that the bar is a fractal. On a live chart you see the marker pop into existence two bars behind the current price.

Can I use ta.pivothigh instead of the loop?

You can; ta.pivothigh(n, n) returns the pivot's price on the confirming bar and na otherwise. Check how it treats equal highs before comparing with iFractals, since the tie rule is the only point where fractal implementations differ.

Convert your own version

Have a variant of this indicator, or any other TradingView script? Paste it and get MQL5 that is checked against the original on the same price history, with every construct that could not be carried over reported.

Open the converter

Related