Search code examples
mql5metatrader5

How to draw a trend line on the chart?


I want to draw a trend line on the chart in MQL5. I tried it with this method:

ChartIndicatorAdd(0,0,handle);

However, it did not work and getting below error:-

runtime error (4107)


Solution

  • Do you want to attach an indicator to the chart or do you want to draw a (trend) line?

    If you want to draw a line, use the ObjectCreate function to create line objects.

    For instance: ObjectCreate(chart_id,"bullish",OBJ_TREND,sub_window,time1,price1,time2,price2);

    If you want to draw the trend line on the current chart, use 0 for chart_id. In addition, sub_window refers to the chart sub-window (i.e. 0 for the main chart window).

    The ObjectCreate method returns false in case of an error, as a result you may want to add a check like this:

    if(!ObjectCreate(chart_ID,"bullish",OBJ_TREND,sub_window,time1,price1,time2,price2))
         {
            Print(__FUNCTION__,": failed to draw trend line! Error code: ",GetLastError());
         }
    

    Make sure to reset the error code with ResetLastError();.

    Last but not least, object properties like color can be set with the ObjectSetInteger function.

    Read more: ObjectCreate, ObjectSetInteger.