Forex Blog

First-hand Forex trading experience and information about foreign exchange market that will be useful to traders

Archives

Drawing Filled Rectangles in MQL4/MQL5

July 26, 2010 (Last updated on October 4, 2012) by

(This post will be interesting only to those who code in MQL4 or MQL5 languages.)

Drawing a rectangle in MQL-coded indicator or expert advisor is quite an easy task in both MetaTrader 4 and MetaTrader 5 platforms. All you have to do is to call the ObjectCreate() function with rather simple parameters. For example, in MQL4 it goes like this:

ObjectCreate("Rectangle", OBJ_RECTANGLE, 0, Time[0], price1, Time[1], price2);

And in MQL5 it would look almost the same:

ObjectCreate(0, "Rectangle", OBJ_RECTANGLE, 0, Time[0], price1, Time[1], price2);

But filling the rectangle in MQL5 or drawing it unfilled in MQL4 wasn’t so obvious to me. The rectangles come unfilled by default in MT5 and filled by default in MT4. OBJPROP_BACK is the property that responds for that. For example, to make a rectangle unfilled in MQL4 you can call this function:

ObjectSet("Rectangle", OBJPROP_BACK, false);

And to fill the rectangle in MQL5 you would change the property to true:

ObjectSetInteger(0, "Rectangle", OBJPROP_BACK, true);


If you have any questions or comments regarding drawing of the rectangles in MQL4 or MQL5, please, use the commentary form below.

25 Responses to “Drawing Filled Rectangles in MQL4/MQL5”

  1. Guillermo

    I am having problems building the rectangle because I am unable to convert the dates correctly.It has to do with the StringToTime and TimeTo String Functions. This indicator was developed correctly on MQ4 but I cant get it to work on MQ5..
    Could somebody please help here? I am including the source,and THE PROBLEM IS DEBUGGED WITH A COMMENT. thanks:

    //+------------------------------------------------------------------+
    //|                                                             Sessions.mq4 |
    //+------------------------------------------------------------------+
    #property indicator_chart_window
     
     
    //:::::::::::::::::::::::::::::::::::::::::::::
    #include 
    #include 
    #include 
    //#include 
    #include 
    #include 
    //Etc.
    //:::::::::::::::::::::::::::::::::::::::::::::::
     
    input			int			eiNumberOfDays		=	02;    // Number Of Days to Draw rectancle(history)
    input			int			eiBrokerHHOffset	=	03;    // Broker Offset (FXDD)
    input			color		ecSydneyColor		=	Khaki;
    input			color		ecTokyoColor		=	Magenta;
    input			color		ecLondonColor		=	Orange;
    input			color		ecNewYorkColor		=	Blue;
    input			bool		ebShowPrice			=	true;    // Show min/max session prices
    input			color		ecColorFont			=	Black;   // Text font Color
    input			int			eiSizeFont			=	8;     // Text Font Size
    input			int			eiOffSet			=	10;    // Text Font Adjustment
    input			bool		ebTesting			=	false;
     
    				int			iCountedBars		=	0;
    				datetime	tClockTime;
    				datetime	tStart;
    				string		sSessionName[]		=	{"      Sydney", "     Tokyo", "      London", "         New York"};
    				int			iSessionBegin[4]	=	{    00,      02,     10,       15};
    				color		cSessionColor[]		=	{    Khaki,     Magenta,    Orange,      Blue};
     
    //+------------------------------------------------------------------+
    //| Custom indicator initialization function                         |
    //+------------------------------------------------------------------+ing
     
    void OnInit()
    	{
    		//:::::::::::::::::::::::::::::::::::::::::::::
    		double	dAsk=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
    		double	dBid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
    		int		iBars=Bars(Symbol(),PERIOD_CURRENT);
    		double	dPoint=Point();
    		//Etc.
    		//:::::::::::::::::::::::::::::::::::::::::::::::
     
    		for(int o=0;o<4;o++)
    			iSessionBegin[o]+=eiBrokerHHOffset-3;
    		DeleteSessionObjects();
    		cSessionColor[0] = ecSydneyColor;
    		cSessionColor[1] = ecTokyoColor;
    		cSessionColor[2] = ecLondonColor;
    		cSessionColor[3] = ecNewYorkColor;
    		for (int i=0; i<eiNumberOfDays; i++)
    			for(int s=0; s=0;i--)
    			if(StringSubstr(ObjectName(i),0,8)=="Session.")
    				ObjectDelete(ObjectName (i)); 
    	}
     
    //+------------------------------------------------------------------+
    //| Custom indicator iteration function                              |
    //+------------------------------------------------------------------+
    int OnCalculate(const int RatesTotal,
                    const int PrevCalculated,
                    const datetime& time[],
                    const double& open[],
                    const double& high[],
                    const double& low[],
                    const double& close[],
                    const long& tickVolume[],
                    const long& volume[],
                    const int& spread[])
    	{
    		ArraySetAsSeries(open,true);
    		ArraySetAsSeries(high,true);
    		ArraySetAsSeries(low,true);
    		ArraySetAsSeries(close,true);
    		ArraySetAsSeries(time,true);
    		ArraySetAsSeries(volume,true);
    		ArraySetAsSeries(spread,true);
     
    		//:::::::::::::::::::::::::::::::::::::::::::::
    		double	dAsk=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
    		double	dBid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
    		int		iBars=Bars(Symbol(),PERIOD_CURRENT);
    		double	dPoint=Point();
    		//Etc.
    		//:::::::::::::::::::::::::::::::::::::::::::::::
     
    		if(ebTesting)
    			tClockTime = GlobalVariableGet("CurrentTime");
    		if(tClockTime ==0)
    			tClockTime = TimeCurrent();
    		datetime	dt=tClockTime+(60*60*24);
    		if(iBars==iCountedBars)
    			return(0);
    		iCountedBars = iBars;
    		for (int i=0; i<eiNumberOfDays; i++)
    			{
    				for(int s=0; s<4; s++)
    					{
    						if (ebShowPrice && i==0)
    							DrawSessionHiLo(dt, s);
    						DrawSession(dt, s,i);
    					}
    				dt-=60*60*24;
    			}
    		return(0);
    	}
     
    void DrawSession(datetime st, int iSession, int iNoOfDays)
    	{
    		datetime t1, t2;
    		double   p1, p2;
    		int      b1, b2;
     
    		t1=StringToTime(TimeToString(st,TIME_DATE))+iSessionBegin[iSession]*(60*60);
    		t2=t1+(9*60*60);
    		if(TimeDayOfWeek(st)==1&&iSession==0)
    			tStart=t1;
    		//if(TimeDayOfWeek(dt)==5&&iSession==3)
    		// t2=tStart;
    		b1=iBarShift(NULL, 0, t1);
    		b2=iBarShift(NULL, 0, t2);
    		p1=iHighest(NULL, 0, MODE_HIGH, b1-b2, b2);
    		p2=iLowest (NULL, 0, MODE_LOW , b1-b2, b2);
    		//p2	=	1.3948;
    		//p1	=	1.3893;
    		p1	=	ChartGetDouble(0,CHART_PRICE_MAX,0);
    		p2	=	ChartGetDouble(0,CHART_PRICE_MIN,0);
     
     
    		string sObjectName = "Session."+(iSession)+"."+iNoOfDays;
     
    		ObjectSet(sObjectName, OBJPROP_TIME1 , t1);
    		ObjectSet(sObjectName, OBJPROP_PRICE1, p1);
     
    		ObjectSet(sObjectName, OBJPROP_TIME2 , t2);
    		ObjectSet(sObjectName, OBJPROP_PRICE2, p2);
     
    		ObjectSet(sObjectName+".Name",OBJPROP_TIME1,t1);
    		ObjectSet(sObjectName+".Name",OBJPROP_PRICE1,p1);
    		//t1	=	5000;
    		//t2	=	t1+(9*60*60);
    		t1=StringToTime(TimeToString(st,TIME_DATE));//+iSessionBegin[iSession]*(60*60);
    		t2=t1+(40*60*60);
     
    		Comment("<<<<<t1:"+t1+",p1:"+ p1+"....t2:"+ t2+",p2:"+ p2+"   T1^T2 "+
    		TimeToString(t1,TIME_DATE)+TimeToString(t1,TIME_SECONDS)+",,,"+TimeToString(t2,TIME_DATE)+TimeToString(t2,TIME_SECONDS));
    	}
     
    void DrawSessionHiLo(datetime st, int iSession)
    	{
    		datetime t1, t2;
    		double   p1, p2;
    		int      b1, b2;      
     
    		t1=StringToTime(TimeToString(st,TIME_DATE))+iSessionBegin[iSession]*60*60;
    		t2=t1+(9*60*60);
     
    		b1=iBarShift(NULL, 0, t1);
    		b2=iBarShift(NULL, 0, t2);
    		p1=iHighest(NULL, 0, MODE_HIGH, b1-b2, b2);
    		p2=iLowest (NULL, 0, MODE_LOW , b1-b2, b2);
    		p1	=	ChartGetDouble(0,CHART_PRICE_MAX,0);
    		p2	=	ChartGetDouble(0,CHART_PRICE_MIN,0);
     
    	}
    //+------------------------------------------------------------------+

    Reply

    admin Reply:

    1. Never (and I mean NEVER) insert the code as a commentary. WP messes up code and it’s a pain in the ass to copy it into MQL. Host the file somewhere and give a link to it in the comment.

    2. You have a lot of improperly converted functions here (dozens!). Please, see other MQL5 indicators to see how the Object, i* and other functions are converted from MQL4 to MQL5.

    3. Why do you have those empty #include directives in the beginning?

    Reply

  2. Guillermo

    I apologize, sorry.. Was a typecasting problem…

    Reply

  3. German

    Hello: How can I put “style transparent red” ,for example, in a rectangle?. Thanks.

    Best Regards.

    Reply

  4. kenbob

    I want to create a rectangle on a 2 candle candlestick pattern using the Highest High and the Lowest Low of the 2 candles, and beginning with the Open (or Close) of the first and ending with the Close (or Open) of the second.
    I am a newbie, so any help will be greatly appreciated.

    Reply

    admin Reply:

    If we are talking MQL4, then it is quite simple.
    This will draw a rectangle on the two latest candles from Low to High:

    ObjectCreate("Rectangle", OBJ_RECTANGLE, 0, Time[0], Low[0], Time[1], High[1]);

    This will do the same for Open/Close:

    ObjectCreate("Rectangle", OBJ_RECTANGLE, 0, Time[0], Open[0], Time[1], Close[1]);

    You can substitute 0 and 1 in the indexes for the specific number of bars you want to draw on. If you want to draw from highest high to lowest low of the two candles, you can use the following code:

    ObjectCreate("Rectangle", OBJ_RECTANGLE, 0, Time[0], MathMin(Low[0], Low[1]), Time[1], MathMax(High[1], High[0]));

    Reply

    kenbob Reply:

    Thanks for the quick reply.
    I tried all three; couldn’t make any of them work. They all compile without problem but don’t plot. Tried changing background colors, still no luck.
    Any other suggestions?
    kenbob

    Reply

    admin Reply:

    It would really help to see the full source code of your program. Can you upload it somewhere and share a link here?

    Reply

  5. kenbob

    Be glad to do that, but I don’t know how. Can you tell me how?
    (Told ya I was a newbie)

    Reply

    admin Reply:

    You can share a file using Google Drive – drive.google.com/start and then post a link here.

    Reply

  6. Jobin John

    how to create rectangular boxes in mt4

    Reply

    Andriy Moraru Reply:

    If you want to add them manually, you can use the menu Insert->Shapes->Rectangle.
    If you want your EA or indicator to add boxes, you can use MQL4 function ObjectCreate(). See the post above for examples.

    Reply

  7. Andrew

    Hey,

    Thanks for this post. I’m a coding newb (zero experience) but have been looking around for an mt4 indicator to simply draw a rectangle of the opening range at Frankfurt, New York & Tokyo.

    In addition to the code lines above, any other advice of where I can find “the beginner’s guide to….” (I’ve googled around a fair bit).

    Cheers,

    Andrew

    Reply

    Andriy Moraru Reply:

    You may want to start by finding a code for an indicator that just marks the trading sessions on chart. There are plenty of such indicators. You would then have to modify it to draw the desired rectangles instead of the usual vertical lines it is done with.

    Reply

  8. Andrew

    Thanks for the speedy response. I’ve got this box indicator that I’m having a play with the code (butchering!).

    I’ve managed to make it draw my required box at the Frankfurt Open, I thought I’d rename the indi and change the parametres for NY and Tokyo, but applying a second indi seems to remove the first one from the chart, which is a bit odd.

    The code looks a bit much for “drawing a box”?

    https://dl.dropboxusercontent.com/u/4358891/BentoBox.mq4

    Reply

  9. Andrew

    Have managed to clean up the indi quite a bit and only using the pieces I need. I like the functionality that this one prints boxes in the past also.

    Still can’t figure out why the indi removes all boxes/shapes that are currently on the chart though?

    Reply

  10. Andrew

    (Sorry, third comment in a row, feel free to delete the two above)

    Here’s the cleaned up indi I’ve got so far… but still stuck as to why it’s deleting any of it’s predecessors on the chart… (Or any rectangles drawn for that matter)

    https://dl.dropboxusercontent.com/u/4358891/FrankenBox.mq4

    Reply

    Andriy Moraru Reply:

    That code shouldn’t delete anything from the chart. How do you apply it to a chart?

    Reply

  11. Andrew

    Ah my mistake, (possibly). I realised that the code refers to say.. “periodA_begin”.. I thought each indicator is sort of *insulated* from another, but I’m guessing that if you call an argument up within one indi, it’s universal?

    I just changed each “periodA_begin” to “tokyoperiodA_begin” etc… so each indi has it’s own variable prefix. Seems to have fixed the problem.

    My only (only, ha!) thing now, is say right now for example, I have the New York (half an hour’s time) box on as an indi, and it’s plotting the past ones no problem, but is also plotting tonights just as a giant box. I’m trying to figure out where (and how) to put an “if” statement in there, to only display the range box once it’s the appropriate time.

    This is a screen of what it’s doing at the moment: https://dl.dropboxusercontent.com/u/4358891/Screen%20Shot%202014-04-09%20at%207.07.51%20pm%20(2).png

    (Thanks again for your help too)

    Reply

  12. Oscar

    Hi there…
    where should I exactly write this code: ObjectSet(“Rectangle”, OBJPROP_BACK, false);
    to make all my rectangles unfilled in mt4?
    thnx for consideration…

    Reply

    Andriy Moraru Reply:

    If you want to change that for all the rectangles that already have drawn in your MT4, then there is no easy way to do it. However, if you want some indicator/EA/script to start drawing unfilled rectangles, then you would need to open the source code of the particular indicator/EA/script and find the line where the rectangle object is created. You may want search for something similar to this: ObjectCreate(“Rectangle”, OBJ_RECTANGLE

    Of course, “Rectangle” can be anything because it is just a name of the object. You can insert ObjectSet(“Rectangle”, OBJPROP_BACK, false); after that creation line unless the code does not use something like ObjectSet(“Rectangle”, OBJPROP_BACK, true); explicitly farther in the code. In which case, you would just need to change ‘true’ to ‘false’ there.

    Reply

  13. Fadil

    How do I create a rectangle that marks the open and close price of a candle on certain time, and the box has to be long until the end of the chart.
    for example like this: http://dominantforex.com/wp-content/uploads/2016/05/how-to-draw-supply-and-demand-le.jpg
    but I just want to take one candle and have the length of the rectangle until the end of the chart

    Reply

    Andriy Moraru Reply:

    You just need to do the following:
    1. Add rectangle to the chart (Insert->Shape->Rectangle).
    2. Draw from the candle’s open to its close and with any width.
    3. Double click the rectangle to select it.
    4. Right-click and select “Rectangle properties…”
    5. Set the second date to some 2018 date or later – it will spread out beyond the right edge of the chart.

    Reply

  14. Michal

    Hello.

    This article is a little bit low quality. Next time add info about all parameters, which You use in function caller please.
    Parameters ‘0’ – what are they? what are they doing?

    Best regards,
    Michal.

    Reply

    Andriy Moraru Reply:

    This article concerns a single topic – filling a rectangle when creating it from within the MQL4 or MQL5 code. Other parameters are irrelevant for that. Moreover, each parameter is explained in detail in the MetaEditor’s built-in help.

    The zero, when it is the first parameter in the MQL5 object functions, means that the object is created/referenced on the current chart.

    When you see a zero as the third parameter in MQL4 (or fourth in MQL5) in ObjectCreate() function, it means that the object is being created in the main chart window (not subwindow).

    I hope this helps.

    Reply

Leave a Reply

required
required (will not be published)