Download MetaTrader 5

Construction of Fractal Lines

15 August 2007, 10:40
Shashev Sergei
2 679


Fractals are used by practically all traders. However, if you ask them what a fractal is, they will at best answer that it is an indicator in the Bill Williams' system. The more advanced traders will say that it is a sequence of 5 bars where, if the middle bar's High is higher than those of other bars in the sequence, it is an Up fractal and, if the middle bar's Low is lower than those of other bars, it is a Down fractal. As the phrase goes, "This is all I can tell about the war”.

A brief description of fractals, particularly of their nature and use, is given in the Bill Williams' book named New Trading Dimensions: How to Profit from Chaos in Stocks, Bonds, and Commodities. Something can also be found in the Chekulaev's article named Fractals (in Russian). Mathematical formulas are well described in Shiryaev's book named Fundamentals of Stochastic Mathematics (in Russian).

Use of Fractals

There are two kinds of fractal penetration to be marked – a simple one is where the price exceeds the Up fractal level (falls under the Down fractal level). In this case, it would be better to wait for the close price and open a position at opening the next bar.

The respective fractals Buy and Sell are marked with arrows in the figure above where we consider the simple fractal penetration. A complex penetration uses 2 fractals – the last and the last but one. They are joint by a straight line that is expected to be penetrated by the close price.

Entering points when the fractal line is penetrated are marked by blue and red arrows. The development environment MQL4 will help us to know the fractal ideology better.

Let us define a problem to test fractals:

  • draw fractals buy/sell;
  • draw horizontal penetrating levels;
  • draw fractal lines;
  • mark the expected entering points with arrows.

Fractals Buy/Sell

This is the most elementary part. We should also consider indicator iFractal available in MQL4 (in Omega, I had to write this indicator myself, and it was rather difficult due to Omega's properties). The examples of how to write this indicator can be found in Code Base.

Horizontal Levels of Penetration

Let us use standard horizontal lines. We will specify the the price of a fractal as a price coordinate, the date of forming the fractal and the current time will be given as time coordinates.


Fractal Lines

The simplest way seems to be drawing of trend lines through 2 points. We make a ray of the line and wait for penetration. However, indeed, it does not seem to be possible to compare the close price and value of the price on the fractal line since function ObjectGet can return only values of points that have formed the fractal line. So what are we to do?

We should remember analytic geometry. We have 2 points, so we have a straight-line equation. And, since we know the time coordinate, we can easily obtain the price value from the straight-line equation. The canonical straight-line equation looks like this:

We will substitute price and time instead of х and у. The realization thereof is given in function LevelCalculate that calculates the penetration level and, along with this, defines new coordinates of the fractal line to be set using function ObjectSet.


Placing Arrows

We build all necessary lines in the loop and then comapre them to the current prices. If it penetrates a simple line, we put a yellow arrow. If it penetrates a fractal line, arrow for Buy will be blue, for Sell – red.

All this is realized as indicator FractalLines.mq4.

//|                                                 FractalLines.mq4 |
//|                      Copyright © 2006, MetaQuotes Software Corp. |
//|                               |
#property copyright "Copyright © 2006, MetaQuotes Software Corp."
#property link      ""
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 Blue
#property indicator_color2 Red
//---- input parameters
extern int       lines=5;  //The amount of visible fractal lines
extern int       MaxFractals=10000; // :)
extern bool       ShowHorisontalLines=true;
extern bool       ShowFractalLines=true; 
//---- buffers
double ExtMapBuffer1[];
double ExtMapBuffer2[];
//--- my variables
double bufUpPrice[10000];  //price array of Up fractals
double bufUpDate[10000];   //date array of Up fractals
double bufDownPrice[10000];   //price array of Down fractals
double bufDownDate[10000]; //date array of Down fractals
int Up = 0; //counter of Up fractals
int Down = 0;  //counter of Down fractals
//The function calculates the price value of penetration of the fractal line by the simplest
//equations of analytic geometry
double LevelCalculate(double Price1, double Time1, double Price2, 
                     double Time2, double NewTime)
   double level;
   if (Time2!=Time1)// Just in case, to avoid zero divide.
//| Custom indicator initialization function                         |
int init()
//---- indicators
//| Custom indicator deinitialization function                       |
int deinit()
//| Custom indicator iteration function                              |
int start()
   int    counted_bars=IndicatorCounted();
//---- the last calculated bar will be recalculated   
   if(counted_bars > 0) 
   int limit = Bars - counted_bars;
// We will rather place arrows at the moment of penetration of fractal lines, 
// estimate efficiency
 // The idea was borrowed from Rosh, hopefully he will not be offended by this :)    
  string arrowName; // here, we will give the arrow a unique name
  //The number of the penetrated fractal
  //Penetration of the fractal line
  int FractalUp = 0;
  int FractalDown = 0;
  //Simple penetration of a fractal
  int SimpleFractalUp = 0;
  int SimpleFractalDown = 0;
  double BuyFractalLevel = 0;  //penetration level of the Up fractal line
  double SellFractalLevel = 0; //penetration level of the Down fractal line
  double buf = 0; // buffer value of fractal being available; if it is 0, there is no fractal at all
//---- the main loop       
   for(int i = limit; i>0; i--)
       //Draw simple fractal levels
       //Define the current fractal levels 
         //Move the second coordinate of the Up fractal line                              
         //Move the second coordinate of the Down fractal line                               
      //Search for a simple penetration
         if (Close[i]>ObjectGet("SimpleUp"+Up,OBJPROP_PRICE1)&&
         if (Close[i]<ObjectGet("SimpleDown"+Down,OBJPROP_PRICE1)&&
      //Search for a complex penetration
        if ((Close[i]>BuyFractalLevel)&&(Up>FractalUp)) 
            //Put an up-arrow
        if ((Close[i]<SellFractalLevel)&&(Down>FractalDown))
            //Put a down-arrow
        //Draw the Up fractal itself
        ExtMapBuffer1[i] = iFractals(NULL, 0, MODE_UPPER, i);
        //If it is available, place it in the array of fractals
        buf = iFractals(NULL, 0, MODE_UPPER, i);
        if (buf!=0)
            bufUpPrice[Up]=iFractals(NULL, 0, MODE_UPPER, i);
            //The current fractal penetration level - fractal itself
            if (Up>1)
               //Simple fractal
               //Draw fractal lines on 2 coordinates
               //Remove the outdated lines
               if (Up>lines+1)
         //A similar block, but for Down fractals
        ExtMapBuffer2[i] = iFractals(NULL, 0, MODE_LOWER, i);
        buf = iFractals(NULL, 0, MODE_LOWER, i);    
        if (buf!=0)
            bufDownPrice[Down]=iFractals(NULL, 0, MODE_LOWER, i);
            if (Down>1)
               if (Down>lines+1)
        if (!ShowHorisontalLines)
        if (!ShowFractalLines)

Old lines must be removed, otherwise the chart will look like a palette. There is a couple of additional settings provided in the indicator, such as visibility of lines or their amount. The result of the indicator's activities is given below.

This touches the spot for those who love fractals!

Translated from Russian by MetaQuotes Software Corp.
Original article:

Attached files |
FractalLines.mq4 (9.4 KB)
Last comments | Go to discussion (6)
MQL4 Comments
MQL4 Comments | 15 Dec 2007 at 08:14

Bravo !

You are the best.

I like the russian people, because they are excellent fighters,excellent thinkers ,excellent writers ,excellent programmers,excellent chess-players,excellent mathematicians .

The russians don't deserve to live in poverty.

Bravo Sashev Sergei

----I'm not russian

MQL4 Comments
MQL4 Comments | 8 Aug 2008 at 10:07

How do I run this program thru a debugger? I mean to understand it better. I have understanding of making fractals, but this is a more complex program.

The math behind is easy. The coding of the OBJECTSET without OBJECTCREATE etc in this is really intriguing.

Or can someone please edit the program with comments so as to explain it. It will be very helpful in that way.

Best regards,


MQL4 Comments
MQL4 Comments | 13 Oct 2008 at 20:24

Great thinker.........just made love

MQL4 Comments
MQL4 Comments | 26 Sep 2009 at 19:30

This is an interesting indicator but can alert be added to it? And if yes how?

Larry | 4 May 2010 at 04:20

I agree that this is an excellent EA, granted there are redundant arrows, which I know can be cleaned up. While running this in a back test on EURUSD I found situations where there were red arrows pointing down and red arrows pointing up. Is this because the program is confused? Are these areas of where the strategy fails or was this a programming error? Was this the case that the tool was outputing arrows for both attempts of lines and failed to seperate which ones fired on which? I tried it with setting the two line sets false at different times and it looks like this might be the case. So, would a user benefit from running both and requiring a confirmation signal from both before considering a trigger on a trade? OR would it be best to seperate the two strategies and firing on each according to it's strategy?

Step on New Rails: Custom Indicators in MQL5 Step on New Rails: Custom Indicators in MQL5

I will not list all of the new possibilities and features of the new terminal and language. They are numerous, and some novelties are worth the discussion in a separate article. Also there is no code here, written with object-oriented programming, it is a too serous topic to be simply mentioned in a context as additional advantages for developers. In this article we will consider the indicators, their structure, drawing, types and their programming details, as compared to MQL4. I hope that this article will be useful both for beginners and experienced developers, maybe some of them will find something new.

Here Comes the New MetaTrader 5 and MQL5 Here Comes the New MetaTrader 5 and MQL5

This is just a brief review of MetaTrader 5. I can't describe all the system's new features for such a short time period - the testing started on 2009.09.09. This is a symbolical date, and I am sure it will be a lucky number. A few days have passed since I got the beta version of the MetaTrader 5 terminal and MQL5. I haven't managed to try all its features, but I am already impressed.

Portfolio trading in MetaTrader 4 Portfolio trading in MetaTrader 4

The article reveals the portfolio trading principles and their application to Forex market. A few simple mathematical portfolio arrangement models are considered. The article contains examples of practical implementation of the portfolio trading in MetaTrader 4: portfolio indicator and Expert Advisor for semi-automated trading. The elements of trading strategies, as well as their advantages and pitfalls are described.

False trigger protection for Trading Robot False trigger protection for Trading Robot

Profitability of trading systems is defined not only by logic and precision of analyzing the financial instrument dynamics, but also by the quality of the performance algorithm of this logic. False trigger is typical for low quality performance of the main logic of a trading robot. Ways of solving the specified problem are considered in this article.