Search code examples
mql4metatrader4mt4

How to get price of Chart HLine objects and calculate Fibonacci levels


Three part question:

  1. How to find 2 user created horizontal lines on a chart by name and return the price of each.
  2. Then determine which HLine was crossed by the price most recently to determine trend direction.
  3. Calculate Fibonacci levels based on prices and direction

Solution

  • Working example of Fibonacci object that can be edited by the user and printing of fibonacci levels.

    #include <ChartObjects/ChartObjectsFibo.mqh>
    CChartObjectFibo *Fibo;
    
    int OnInit()
        {
         Fibo = new CChartObjectFibo();
         #Create object and set some defaults
         if(!Fibo.Create(0,"Fibonacci",0,Time[5],Open[5],Time[0],Open[0]))
         {
                return(INIT_FAILED);
         }
         # Allow user to drag object
         Fibo.Selectable(true);
         return(INIT_SUCCEEDED);
        }
    
    void OnDeinit(const int reason)
        {
         delete Fibo;
        }
    
    void OnTick()
        {
         string level_description;
         double level_value;
         string printString="Fibonacci Levels - ";
         # Get the two anchor prices
         double p1 = Fibo.GetDouble(OBJPROP_PRICE,0);
         double p2 = Fibo.GetDouble(OBJPROP_PRICE,1);
         # Calculate range
         double range=MathAbs(p1-p2);
         for(int i=0;i<Fibo.LevelsCount();i++)
         {
                level_description=Fibo.LevelDescription(i);
                # Calculate price of level
                level_value=(p2>p1)?p2-range*Fibo.LevelValue(i):p2+range*Fibo.LevelValue(i);
                printString=StringFormat("%s %s:%.5f",printString,level_description,level_value);
         }
         Print(printString);
        }