Tuesday, December 8, 2015

How to detect fractals in MT4 (+code sample)

When your DIY MT4 programing project requires you to implement swing detection or breakout levels, it's almost impossible not to think about working with fractals.

However, the MT4 fractals don't allow you to change the 2-bar lookback period that the Bill Williams indicator uses to find where the market made a swing lower or higher.
In some cases, you may want to have this period adjustable, so you can validate a fractal only if 5 or more bars are swinging lower and lower before a low fractal is formed.

As you know, the default behavior of the default fractal indicator uses repainting. So it prints the lower fractal as soon as the market steps 2 consecutive candles lower, before waiting for the next 2 candles to be closed and the swing confirmed. Later, if the middle candle was broken below, price went lower and lower, the fractal will be repainted.

You may also want to configure this confirmation period to 1 full candle or even more with a '5-bar fractal'. So how do you implement a custom fractal checking function in MQL4? Here're a few lines of code that will guide you, the sample is pretty straightfoward.


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool fractal_lower(int idx)
  {
   for(int i=1; i<=CANDLES; i++)
     {
      if(Low[idx+i]<=Low[idx]) return false;
     }

   for(int i=1; i<=CANDLES; i++)
     {
      if(idx-i>=0 && Low[idx-i]<=Low[idx]) return false;
     }
   return true;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool fractal_upper(int idx)
  {
   for(int i=1; i<=CANDLES; i++)
     {
      if(High[idx+i]>=High[idx]) return false;
     }

   for(int i=1; i<=CANDLES; i++)
     {
      if(idx-i>=0 && High[idx-i]>=High[idx]) return false;
     }
   return true;
  }

No comments:

Post a Comment