Documentation

Home / Documentation

Documentation

×


This section describes every available function in detail. We recommend that you go over all functions to understand MT4GUI and use it in full range. You may also check Blog section for more examples. We do describe every function and prepare basic examples.

Installation & Configuration


Please refer Download page for details about Installation & Configuration

Key points





×

Cheat Sheet


We have prepared a cheat-sheet for you to get started rapidly. We regularly update this cheat-sheet, please update your file from time to time.



GUI General Functions


int guiCleanup(int hwnd)

This is very important function to cleanup, its a must to call this function from deinit() as last mt4gui function. It requires hwnd as parameter.

int deinit()
  {
   // Very important to cleanup and remove all gui items from chart   
   guiRemoveAll(hwnd); guiCleanup(hwnd);
   return(0);
  }

int guiVendor(string apikey)

You can tag your clients with your apikey. To register an apikey follow this link, once you have an apikey, call the guiVendor() function as first step before you call any other gui related mt4gui function. This will tag all new-registered clients as yours and you will be able to see them inside vendor panel

This function is optional but recommended, this way you can see all registrants and can contact them. Most of demos here dont have this function calling, simply because we have implemented this function few years later. We recommend you to use this function.

int guiRemove(int hwnd,int ObjectHandle)

int guiRemoveAll(int hwnd)

These functions are responsible to remove chart objects from chart. guiRemoveAll needs hwnd as parameter and removes all chart objects(such as buttons, labels etc) from chart. If you want to remove particular objects from chart then use guiRemove() function, it will need the handle of objects. Removed objects will be destroyed forever, you will need to re-create them if you want to have them back. We recommend to use guiRemoveAll(hwnd) in init() and deinit() functions to cleanup.

int guiAdd(int hwnd,string ObjectType,int X,int Y,int Width,int Height,string Label)

This is function is able to add different gui objects to chart. Right now MT4GUI Supports:

  • Button : Classic buttons
  • Radio Button : (*) Style radio button
  • Checkbox : [x] Style checkbox
  • Link : Underlined labels, clickable, upon click defined url will be opened
  • Label : Static fields
  • Textbox : User can type something, editable fields
  • Droplist box : Can contain multiple items to choose from


ObjectType parameter allows following inputs: “button”,”radio”,”checkbox”,”link”,”label”,”text”,”list”, this parameter is case-sensitive, so please use lower-case. The X and Y parameters define the location on chart and Width & Height are self-explanatory. Label is the caption of object, not every object needs a caption, for example “list” does not need a caption.

Every guiAdd call returns a object handle. Those handles are needed to react to Events, change color etc. This demonstration will show you how to add particular objects:

// mt4gui-guiDemo1.mq4
#include <mt4gui2.mqh>

// Global Variables
int hwnd = 0;
// GUI Object Handles
int Button1,Button2,Button3,Button4,Button5;
int Label1,Label2,Label3,List1,List2,Edit1,Edit2,Label4;
int CB1,CB2,R1,R2,R3,R4,L1,L2,L3,L4,Label5;


// Settings
int GUIX = 50;
int GUIY = 100;
int ButtonWidth = 150;
int ButtonHeight = 30;

int OnInit()
{
	ObjectsDeleteAll();
	hwnd = WindowHandle(Symbol(),Period());		
	// Lets remove all Objects from Chart before we start
	guiRemoveAll(hwnd);
	// Lets build the Interface
	BuildInterface();
  return(0);
}
//// Add new objects, Type:  "button","checkbox","list","label","text"
void BuildInterface()
{
	// Build Checkbox Panel
	Label3  = guiAdd(hwnd,"label",290,50,210,180,""); 
						guiSetBgColor(hwnd,Label3,LightGray);guiSetTextColor(hwnd,Label3,Black);

	// Build Options Panel
	Label4  = guiAdd(hwnd,"label",520,20,200,210,""); 	
	Label5  = guiAdd(hwnd,"label",520,20,200,20,"Options"); 	
						guiSetBgColor(hwnd,Label5,RoyalBlue);guiSetTextColor(hwnd,Label5,White);

	// Build Links Panel
	int tmp = guiAdd(hwnd,"label",740,20,200,210,""); guiSetBgColor(hwnd,tmp,RosyBrown);guiSetTextColor(hwnd,tmp,White);
	int tmp2=	guiAdd(hwnd,"label",740,20,200,20,"Useful Links"); guiSetBgColor(hwnd,tmp2,RoyalBlue);guiSetTextColor(hwnd,tmp2,White);


	Label2  = guiAdd(hwnd,"label",GUIX,20,ButtonWidth*3,48,"Another Label Object, Labels can be put to chart without any limits"); 
						guiSetBgColor(hwnd,Label2,DimGray);guiSetTextColor(hwnd,Label2,White);

	Label1  = guiAdd(hwnd,"label",GUIX,50,ButtonWidth*3,15,"Label Object"); 
						guiSetBgColor(hwnd,Label1,LightGreen);guiSetTextColor(hwnd,Label1,Black);
	
	Button1 = guiAdd(hwnd,"button",GUIX,GUIY+ButtonHeight*1+5,220,ButtonHeight,"Button");
	Button2 = guiAdd(hwnd,"button",GUIX,GUIY+ButtonHeight*2+10,220,ButtonHeight*2,"Another Button");
						guiSetBgColor(hwnd,Button2,SkyBlue);guiSetTextColor(hwnd,Button2,Black);
															
						
	// List Object						
	List1   = guiAdd(hwnd,"list",300,140,150,300,"List1"); 
			guiAddListItem(hwnd,List1,"First List Item");
			guiAddListItem(hwnd,List1,"Second List Item");
			guiAddListItem(hwnd,List1,"Third List Item");
			guiAddListItem(hwnd,List1,"Forth List Item");
			guiAddListItem(hwnd,List1,"Fifth List Item");
			guiSetListSel(hwnd,List1,0); 
			
	// Textfield Object
	Edit1 = guiAdd(hwnd,"text",GUIX,80,220,20,"Text Field");	
					guiSetBgColor(hwnd,Edit1,Gainsboro);guiSetTextColor(hwnd,Edit1,Black);
	Edit2 = guiAdd(hwnd,"text",GUIX,105,220,20,"Another Text Field");	
					guiSetBgColor(hwnd,Edit2,SkyBlue);guiSetTextColor(hwnd,Edit2,Black);
			
	// CheckBoxes
	CB1		= guiAdd(hwnd,"checkbox",300,80,150,30,"CheckBox1"); guiSetBgColor(hwnd,CB1,LightGray);guiSetTextColor(hwnd,CB1,Black);			
	CB2		= guiAdd(hwnd,"checkbox",300,105,180,30,"CheckBox2 - Checked"); guiSetBgColor(hwnd,CB2,LightGray);guiSetTextColor(hwnd,CB2,Blue);			
			
	// Radio Buttons
	R1    = guiAdd(hwnd,"radio",540,50,100,30,"Radio1"); 
	R2    = guiAdd(hwnd,"radio",540,80,100,30,"Radio2"); 
	R3    = guiAdd(hwnd,"radio",540,110,100,30,"Radio3");
	R4    = guiAdd(hwnd,"radio",540,140,100,30,"Radio4");
	
	// Links on "Useful Links" Panel
	L1   = guiAdd(hwnd,"link",750,50,180,20,"Search by google"); guiSetBgColor(hwnd,L1,RosyBrown);guiSetTextColor(hwnd,L1,White);				
	L2   = guiAdd(hwnd,"link",750,80,180,20,"Check Fx1.net"); guiSetBgColor(hwnd,L2,RosyBrown);guiSetTextColor(hwnd,L2,White);			
	L3   = guiAdd(hwnd,"link",750,110,180,20,"Visit ForexFactory"); guiSetBgColor(hwnd,L3,RosyBrown);guiSetTextColor(hwnd,L3,White);			
	// Define the links usign guiSetLink
	guiSetLink(hwnd,L1,"http://google.com");
	guiSetLink(hwnd,L2,"http://fx1.net");
	guiSetLink(hwnd,L3,"http://forexfactory.com");
}

int OnDeinit()
  {
   // Very important to cleanup and remove all gui items from chart      
   if (hwnd>0) { guiRemoveAll(hwnd);   	guiCleanup(hwnd ); }
   return(0);
  }

void OnTick() { }

int guiSetTextColor(int hwnd,int ObjectHandle,color Color)

int guiSetBgColor(int hwnd,int ObjectHandle,color Color)

int guiSetBorderColor(int hwnd,int ObjectHandle,color Color)

You can adjust Textcolor, Background color and BorderColor (only for Buttons). Simply call this function with hwnd, objecthandle and color. Please check demonstration code from guiAdd() function to see how it can be used.

int guiSetLink(int hwnd,int LinkObjectHandle,string Link)

This function is only for “link” object and sets the target. By creating the “link” object you can use guiAdd(…”link”….”label”), the label is the caption and guiSetLink() sets the target to be opened in default browser once clicked.

	
	// Howto add a link object to chart and set its Link property
	int Link1;
	Link1 = guiAdd(hwnd,"link",10,10,100,25,"Open Google");
	guiSetLink(hwnd,Link1,"http://google.com");

bool guiIsClicked(int hwnd,int ObjectHandle)

This function can capture events from any Chart Object. Returns TRUE if this object has been clicked. Once any object has been clicked, MT4GUI sends a Tick to chart automatically, this makes a fluent response from events possible. Every Click to every GUI Object will call start() MQL function and you can capture the events from there using guiIsClicked() function. guiIsClicked has been demonstrated on almost every demonstration file, refer them. For advanced level check guiSetText() function demonstration.

bool guiIsChecked(int hwnd,int CheckboxHandle)

int guiSetChecked(int hwnd,int CheckboxHandle, bool State)

These functions are dedicated for Checkbox chart objects. guiIsChecked() returns TRUE if the State if checkbox is checked, FALSE if not. guiSetChecked sets the State via True(check) or False(uncheck).

int guiGroupRadio(int hwnd)

This function indicates a new Radio Group. You simply call this function with hwnd and all following “radio” objects will be grouped together. To start new group you call this function one more time. Here is a demonstration:

	
#property version   "1.00"
#property strict
#include <mt4gui2.mqh>

// global variables
int hwnd = 0; 
int radioA1,radioA2,radioA3;
int radioB1,radioB2,radioB3;
int radioC1,radioC2,radioC3;

int OnInit()
  {
  hwnd = WindowHandle(Symbol(),Period());
  guiRemoveAll(hwnd);
  
  BuildInterface();


  return(INIT_SUCCEEDED);
  }


void BuildInterface()
   {
   // Lets add a panel
   int panel1 = guiAdd(hwnd,"label",100,50,650,100,"Radio Group Demonstration"); 
   guiSetTextColor(hwnd,panel1,Red);
   // Lets group A
   guiGroupRadio(hwnd);
   radioA1 = guiAdd(hwnd,"radio",120,80,150,20,"Radio Group A - #1");
   radioA2 = guiAdd(hwnd,"radio",120,100,150,20,"Radio Group A - #2");
   radioA3 = guiAdd(hwnd,"radio",120,120,150,20,"Radio Group A - #3");
   guiGroupRadio(hwnd);
   radioB1 = guiAdd(hwnd,"radio",320,80,150,20,"Radio Group B - #1"); guiSetTextColor(hwnd,radioB1,Green);
   radioB2 = guiAdd(hwnd,"radio",320,100,150,20,"Radio Group B - #2"); guiSetTextColor(hwnd,radioB2,Green);
   radioB3 = guiAdd(hwnd,"radio",320,120,150,20,"Radio Group B - #3"); guiSetTextColor(hwnd,radioB3,Green);
   guiGroupRadio(hwnd);
   radioC1 = guiAdd(hwnd,"radio",520,80,150,20,"Radio Group C - #1"); guiSetTextColor(hwnd,radioC1,Blue);
   radioC2 = guiAdd(hwnd,"radio",520,100,150,20,"Radio Group C - #2"); guiSetTextColor(hwnd,radioC2,Blue);
   radioC3 = guiAdd(hwnd,"radio",520,120,150,20,"Radio Group C - #3"); guiSetTextColor(hwnd,radioC3,Blue);

   
   }

void OnDeinit(const int reason)
  {   }

void OnTick()
  {  }

int guiGetWidth(int hwnd,int ObjectHandle)

int guiGetHeight(int hwnd,int ObjectHandle)

int guiSetPos(int hwnd,int ObjectHandle,int X,int Y)

int guiSetSize(int hwnd,int ObjectHandle,int Width,int Height)

Those functions can manage and retrieve Position and Dimension information about every chart object. You can retrieve Dimension and, set Dimension(Width, Height) and Positition (X,Y).

	
// mt4gui-PosDemo.mq4
#include <mt4gui2.mqh>

// global Variable
int hwnd = 0;
int panel1,list1,buttonLEFT,buttonRIGHT,buttonUP;
int buttonDOWN,buttonGROW,buttonSHRINK;
// Panel Coordinated & Dimentions
int PanelX = 250,PanelY = 25;
int PanelW = 300, PanelH = 300;

int OnInit()
  {  
	hwnd = WindowHandle(Symbol(),Period());		
	guiRemoveAll(hwnd);	
	// Build a panel
	panel1 = guiAdd(hwnd,"label",PanelX,PanelY,PanelW,PanelH,"Move it baby");
	guiSetBgColor(hwnd,panel1,Tomato);
	// Left Button
	buttonLEFT = guiAdd(hwnd,"button",102,65,40,25,"<<<"); guiSetBorderColor(hwnd,buttonLEFT,SteelBlue);
		guiSetText(hwnd,buttonLEFT,CharToStr(223),18,"Wingdings");
	// Right Button
	buttonRIGHT = guiAdd(hwnd,"button",168,65,40,25,">>>"); guiSetBorderColor(hwnd,buttonRIGHT,SteelBlue);
		guiSetText(hwnd,buttonRIGHT,CharToStr(224),18,"Wingdings");

  // UP Button
	buttonUP = guiAdd(hwnd,"button",142,25,26,40,"^^"); 
	guiSetText(hwnd,buttonUP,CharToStr(225),18,"Wingdings");
	guiSetBorderColor(hwnd,buttonUP,SteelBlue);
	 
	// DOWN Button
	buttonDOWN = guiAdd(hwnd,"button",142,90,26,40,""); 
	guiSetText(hwnd,buttonDOWN,CharToStr(226),18,"Wingdings");
	guiSetBorderColor(hwnd,buttonDOWN,SteelBlue);
	
	// Grow Button
	buttonGROW = guiAdd(hwnd,"button",183,105,25,25,"");
	guiSetText(hwnd,buttonGROW,CharToStr(248),18,"Wingdings");
	guiSetBorderColor(hwnd,buttonGROW,Silver);
	guiSetBgColor(hwnd,buttonGROW,Silver);

	// Shrink Button
	buttonSHRINK = guiAdd(hwnd,"button",100,25,25,25,"");
	guiSetText(hwnd,buttonSHRINK,CharToStr(245),18,"Wingdings");
	guiSetBorderColor(hwnd,buttonSHRINK,Silver);	
	guiSetBgColor(hwnd,buttonSHRINK,Silver);
	UpdatePanelLabels();
		
  return(0);
  }

void OnDeinit(const int reason)
{   
   if (hwnd>0) guiRemoveAll(hwnd); 
   // Call this as last mt4gui function
   guiCleanup(hwnd);    
}

void OnTick()
{         
  // Lets remember the Panel Height & Weight
  string PanelWH = guiMD5((DoubleToStr(PanelX*PanelY)));	
  // Manage the buttons and their Events	
  if (guiIsClicked(hwnd,buttonRIGHT)) PanelX+=15;   	
  if (guiIsClicked(hwnd,buttonLEFT)) PanelX-=15;
  if (guiIsClicked(hwnd,buttonUP))  PanelY-=15;  	
  if (guiIsClicked(hwnd,buttonDOWN))  PanelY+=15;   	  	  
	// Detect Change in PanelX, PanelY using MD5! (hint)	
	if (guiMD5((DoubleToStr(PanelX*PanelY)))!=PanelWH) { guiSetPos(hwnd,panel1,PanelX,PanelY); UpdatePanelLabels(); }
	
	// Shrink & Grow Buttons
	if (guiIsClicked(hwnd,buttonSHRINK)) { PanelW-=15; PanelH-=15; guiSetSize(hwnd,panel1,PanelW,PanelH);  UpdatePanelLabels(); }
	if (guiIsClicked(hwnd,buttonGROW)) { PanelW+=15; PanelH+=15; guiSetSize(hwnd,panel1,PanelW,PanelH); UpdatePanelLabels(); }	
}

void UpdatePanelLabels()
{
	// Change Label of Panel with coordinate and size information
	guiSetText(hwnd,panel1,"X:"+DoubleToStr(PanelX,0)+" Y:"+DoubleToStr(PanelY,0)+" Width:"
			+DoubleToStr(guiGetWidth(hwnd,panel1),0)+" Height:"+DoubleToStr(guiGetHeight(hwnd,panel1),0)
			,18,"Terminal");
}

int guiSetText(int hwnd,int ObjectHandle,string NewText,int FontSize,string Fontname)

string guiGetText(int hwnd,int ObjectHandle)

You can retrieve and set Text for all objects using those two functions. For example if you have a “text” object, you can set the content with guiSetText and retrieve typed information using guiGetText. For List object it retrieves the selected items caption etc. By buttons you can set the caption. Its possible to define any font by guiSetText. Important: try to use common fonts they are available in every system, otherwise non-existing fonts may cause problems on other computers. Hint: you may use “Wingdings” font to display different objects ob buttons.

	
// mt4gui-setTextDemo.mq4
#include <mt4gui2.mqh>

// global Variables
int hwnd = 0;
int ButtonHeight = 30; 
int ButtonWidth = 150;
int ButtonDistance = 20; 
int X = 50, Y = 100;
// Advanced Level
int GUIHandles[100];
int GUITotal=0;

int init()
  {  
	hwnd = WindowHandle(Symbol(),Period());		
	ArrayInitialize(GUIHandles,-1);
	guiRemoveAll(hwnd);	
	
  // Add Buttons
	AddButton("Button #1 - Default");
	AddButton("Button #2",10,"Tahoma");
	BGColor(AddButton("Button #3",12,"Terminal"),Gold);
	TextColor(AddButton("Button #4",16,"Arial"),Blue);
	// Add Checkboxes
	Y=100; X=250;
	AddCB("Checkbox-Default");
	TextColor(BGColor(AddCB("Checkbox#2",10,"Terminal"),White),Blue);
	TextColor(BGColor(AddCB("xxx "+CharToStr(139)+CharToStr(140)+CharToStr(141),18,"Wingdings"),White),Red);
	TextColor(BGColor(AddCB("Checkbox#4",18,"Arial"),Gold),Black);

	// Add more Buttons
	Y=100; X=450;
	BGColor(AddButton("xxx "+CharToStr(139)+CharToStr(140)+CharToStr(141),18,"Wingdings"),Red);	
	BorderColor(AddButton("Button #6",10,"Tahoma"),Green);
	BGColor(BorderColor(AddButton("Button #7",28,"Tahoma"),Red),Lime);		
	TextColor(BGColor(BorderColor(AddButton("Button #8",28,"Tahoma"),White),White),Blue);

	
  return(0);
  }

int deinit()
  {   
   if (hwnd>0) guiRemoveAll(hwnd); 
   // Call this as last mt4gui function
   guiCleanup(hwnd); 
   return(0);
  }

int start()
{
	// Advanced level of event capturing
	for(int i=0;i<GUITotal;i++)
			{
				if (guiIsClicked(hwnd,GUIHandles))
						{
							
							string ClickedLabel = guiGetText(hwnd,GUIHandles);
							guiPrintXY("Clicked : "+ClickedLabel,Tomato,50,50,18);
						}
			}
return(0);
}

int AddButton(string ButtonLabel,int FontSize=0,string Font="")
{
	int Handle = guiAdd(hwnd,"button",X,Y,ButtonWidth,ButtonHeight,ButtonLabel);
	if (FontSize>0) guiSetText(hwnd,Handle,ButtonLabel,FontSize,Font);
	Y=Y+ButtonHeight+ButtonDistance;	
	AddHandle(Handle);
	return(Handle);
}

int AddCB(string Label,int FontSize=0,string Font="")
{
	int Handle = guiAdd(hwnd,"checkbox",X,Y,ButtonWidth,ButtonHeight,Label);
	if (FontSize>0) guiSetText(hwnd,Handle,Label,FontSize,Font);
	Y=Y+ButtonHeight+ButtonDistance;	
	AddHandle(Handle);
	return(Handle);
}

int AddHandle(int Handle) {	GUIHandles[GUITotal]=Handle;GUITotal++; return(0); }

int BGColor(int Handle,color BgColor) { guiSetBgColor(hwnd,Handle,BgColor); return(Handle);}
int TextColor(int Handle,color FrontColor) { guiSetTextColor(hwnd,Handle,FrontColor); return(Handle);}
int BorderColor(int Handle,color BColor) { guiSetBorderColor(hwnd,Handle,BColor); return(Handle);}

Default system fonts for objects is “system” if nothing in user profile is defined

int guiEnable(int hwnd,int ObjectHandle, bool State)

bool guiIsEnabled(int hwnd,int ObjectHandle)

You can enable, disable every chart object such as buttons, checkboxes, listboxes via guiEnable() function. If you set the State as TRUE then this object gets enabled, if you define the state FALSE then this chart object will get disabled. Second function guiIsEnabled() is able to ask for current State.

Enumerating Functions


int guiObjectsCount(int hwnd)

int guiGetByNum(int hwnd,int Index)

int guiGetByName(int hwnd,string Alias)

int guiGetType(int hwnd,int ObjectHandle)

int guiSetName(int hwnd,int ObjectHandle,string Alias)

string guiGetName(int hwnd,int ObjectHandle)

Its possible to enumerate the objects using MT4GUI Functions. The enum functions makes you possible to retrieve information about all objects on chart. Roughly: you can retrieve the number of all MT4GUI Objects on chart using guiObjectsCount() function, then you can use for(…) function to go over all objects and retrieve their handle using guiGetByNum(hwnd,index) function. This function returns the handle. Use guiGetType(hwnd,handle) function to retrieve the Type of object. This is anonymous way to enumerate over all available objects. Its also possible to enumerate named. Every MT4GUI object can have a unique name, this name is an alias which can be set from you individually. You should set unique name to every object using guiSetName(hwnd,ObjectHandle,Alias) function. Second way to enumerate is then to use guiGetByName(hwnd,Alias) function which will return a handle to that object and you can again use guiGetText(hwnd,handle) function to retrieve the Type of object. As soon you have handle and type you can use every described function to get caption,position,dimensions.

GUI List Functions


int guiAddListItem(int hwnd,int ListObjectHandle,string ItemToAdd)

This function adds a new item to existing ListBox Chart Object.

	
// mt4gui-ListDemo.mq4
#include <mt4gui2.mqh>

// global Variable
int hwnd = 0; 
int panel1,list1,button1,button2;

int init()
  {  
  hwnd = WindowHandle(Symbol(),Period());		
  guiRemoveAll(hwnd);	
  // Build the panel
  panel1 = guiAdd(hwnd,"label",100,50,250,150," Select Trade to Close"); guiSetTextColor(hwnd,panel1,Black);
  guiSetBgColor(hwnd,panel1,MediumPurple);
  // Add buttons to panel
  button1 = guiAdd(hwnd,"button",105,100,240,25,"Close Selected Trade"); guiSetBorderColor(hwnd,button1,Moccasin);
  button2 = guiAdd(hwnd,"button",105,130,240,25,"Refresh Trades"); guiSetBorderColor(hwnd,button2,Chocolate);
  // Add ListBox
  list1 = guiAdd(hwnd,"list",105,70,240,150,"");
  RefreshListBox();
  return(0);
  }

void RefreshListBox()
{
	guiRemoveListAll(hwnd,list1);
	
	for(int i=0;i<OrdersTotal();i++)
		{
		if (OrderSelect(i,SELECT_BY_POS))
				{
					string lbl = "#"+DoubleToStr(OrderTicket(),0)+" - "+OrderSymbol()+" x "+DoubleToStr(OrderLots(),2);
					guiAddListItem(hwnd,list1,lbl);
				}		
		}
}

int deinit()
  {   
   if (hwnd>0) guiRemoveAll(hwnd); 
   // Call this as last mt4gui function
   guiCleanup(hwnd); 
   return(0);
  }

int start()
{

	// Button "Close Selected Trade"
	if (guiIsClicked(hwnd,button1))
			{
				// We require that at least one item has been selected
				if (guiGetListSel(hwnd,list1)>-1)
					{
						// We can read the selected items index by guiGetListSel
						// and Selected Item using guiGetText() function
						// Lets extract the OrderID from "#" prefix
						int SelectedTrade = ExtractOrderID(guiGetText(hwnd,list1));
						Comment("Selected ID:"+DoubleToStr(SelectedTrade,0));
						if (_CloseByTicket(20,SelectedTrade))
								{
									PlaySound("ok.wav");
									// We can remove this item from list after close
									guiRemoveListItem(hwnd,list1,guiGetListSel(hwnd,list1));
								}
								else PlaySound("error.wav");												
					}
				
			}

	// Button "Refresh"
	if (guiIsClicked(hwnd,button2)) RefreshListBox();						
return(0);
}

int guiGetListSel(int hwnd,int ListObjectHandle)

int guiSetListSel(int hwnd,int ListObjectHandle,int ItemIndex)

Get function is to read selected index from ListBox. Get returns -1 if nothing is selected. Set function sets the selected item index. If index does not exists then Set will return an error. Refer guiAddListItem() demonstration file to example.

int guiRemoveListItem(int hwnd, int ListObjectHandle, int ItemIndex )

int guiRemoveListAll(int hwnd,int ListObjectHandle )

These functions are responsible to remove either one particular or all items in existing List Chart Object.

GUI Menu Functions


int guiAddMenu(int hwnd,string Caption,int ParentHandle,int Flags)

Did you ever wanted add menu to MT4 Terminal? This function allows you doing this.

Parameters :
  • hwnd : WindowHandle from Chart
  • Caption: This is the Label of Menu
  • ParentHandle: MT4GUI supports MultiLevel menus. If you specify 0 then your menu gets TopParent, if you want to add a submenu to TopParent, you must specifiy here the handle of TopMenu etc. Its possible to generate multiple sub menus.
  • Flags: 1 indicates checkbox menu, 0 indicates normal menu. Flags shall be only specified by SubMenus

Here is an Example & Output demonstrated:


Of course there are functions to capture Events, Change Look&Feel, Check Checkbox state, Change Labels. Check other Menu Functions

int guiSetMenuTextColor(int hwnd,int menuHandle,color Color)

int guiSetMenuBgColor(int hwnd,int menuHandle,color Color)

Those two functions adjust colors to created menu objects. By default MT4GUI Creates all menus in windows default menu color.

Demonstration & Output

int guiSetMenuText(int hwnd,int MenuHandle,string NewLabel

You can also modify labels of menu objects using this function. Simply pass hwnd and MenuHandle and NewLabel and it will be modified on GUI.

bool guiIsMenuClicked(int hwnd,int menuHandle)

This function captures the Clicked Event to Menu Objects.

// Partial Code
// Responsible to build menu
void BuildMenus()
{
	// Lets add "Operations" Menu as PARENT Node
	menuPARENT1 = guiAddMenu(hwnd,"Trade Menu",0,0);
  // Lets Add Sub menu to "Demo" parent
			menuSUB1 = guiAddMenu(hwnd,"Buy @ Market",menuPARENT1,0);
			menuSUB2 = guiAddMenu(hwnd,"Sell @ Market",menuPARENT1,0);

	// Adjust Colors of all Menus
	guiSetMenuTextColor(hwnd,menuPARENT1,White); guiSetMenuBgColor(hwnd,menuPARENT1,Red);
	guiSetMenuTextColor(hwnd,menuSUB1,White); guiSetMenuBgColor(hwnd,menuSUB1,Green);
	guiSetMenuTextColor(hwnd,menuSUB2,White); guiSetMenuBgColor(hwnd,menuSUB2,Tomato);		
}

// Functions to capture Menu Events
void ManageEvents()
{	
	if (guiIsMenuClicked(hwnd,menuSUB1)) 
				guiPrint("Buy @ Market - Menu Clicked. BUYING NOW",Green);
	if (guiIsMenuClicked(hwnd,menuSUB2)) 
				guiPrint("Sell @ Market - Menu Clicked. SELLING NOW.",Tomato);				
}

bool guiIsMenuChecked(int hwnd,int menuHandle)

int guiCheckMenu(int hwnd,int menuHandle,bool State)

First function retrieves CheckBox state from menu objects, second one sets the state to true(check) or false(uncheck). Demonstration code explains those functions in detail:

// mt4gui-MenuDemo1.mq4
#include <mt4gui2.mqh>

// Global Variables
int hwnd = 0;
int menuPARENT1,menuPARENT2,menuSUB1,menuSUB2,menuSUBSUB2;
int menuSUBSUB1,menuSUB3,menuSUB4,button1,button2;

int init()
{
	ObjectsDeleteAll();
	hwnd = WindowHandle(Symbol(),Period());	
	// Lets remove all gui Objects from chart
	guiRemoveAll(hwnd);	
	// Lets Build the Menus
	BuildMenus();
  return(0);
}

int deinit()
  {
   // Very important to cleanup and remove all gui items from chart   
   if (hwnd>0) { guiRemoveAll(hwnd);   	guiCleanup(hwnd ); }
   return(0);
  }

// Responsible to build menu
void BuildMenus()
{
	button1 = guiAdd(hwnd,"button",100,50,150,30,"Enable Trading");
	button2 = guiAdd(hwnd,"button",100,80,150,30,"Disable Trading");
		
	// Lets add "Options" Menu as PARENT Node
	menuPARENT2 = guiAddMenu(hwnd,"Options",0,0);
			menuSUB3 = guiAddMenu(hwnd,"Allow Trading",menuPARENT2,1);
			menuSUB4 = guiAddMenu(hwnd,"Sound",menuPARENT2,1);									
	
}

// Functions to capture Menu Events
void ManageEvents()
{		
	// Event Handling for buttons
	if (guiIsClicked(hwnd,button1)) guiCheckMenu(hwnd,menuSUB3,true);
	if (guiIsClicked(hwnd,button2)) guiCheckMenu(hwnd,menuSUB3,false);
	// Read MENU Checkbox State
	bool TradingEnabled = guiIsMenuChecked(hwnd,menuSUB3);
	bool SoundEnabled = guiIsMenuChecked(hwnd,menuSUB4);
	
	// Display Information on Chart
	if (TradingEnabled) guiPrintXY("Trades are Allowed",Gold,300,50,14,"Terminal"); 
			else guiPrintXY("Trades are Disallowed",Tomato,300,50,14,"Terminal");
	if (SoundEnabled)guiPrintXY("Sound is Enabled",Gold,300,80,14,"Terminal"); 
			else guiPrintXY("Sound is muted",Tomato,300,80,14,"Terminal");
			
}

int start()
{
	ManageEvents();			
	return(0);
}

int guiEnableMenu(int hwnd,int menuHandle,bool Status)

Enabling and Disabling any menu object is possible using this function. Simply pass menuHandle along Status to Enable or Disable any menu. Disabled menus are not clickable but they will still be displayed.

int guiRemoveMenu(int hwnd,int menuHandle)

guiRemoveMenu removes any menu from Chart. For menu always use guiRemoveMenu() function. Removed menu items are removed from chart permanently and you need to create them again if you want to restore. All other GUI Objects use guiRemove() function to be removed.

Link Functions


int guiLinkAdd(int hwnd,int ParentHandle,string Label,string Link)

Links will be added to terminal “Navigator” Panel. They are powerful tool for you to link to your services. If you specify ParentHandle as 0 then this Link will be a Parent Link. All Sub links shall have handle from any parent handle which was already created.Link should start with http:,https: or mailto: prefix. We dont recommend anything else. Please see video demonstration to see how links work in MT4 Terminal. Maximum number of sublinks is 10. Root link captions are unique and if some EA or Indicator has a Root link yet, its not possible to create it again from another chart or Study. If you add a sub link with same caption, it will be overwritten to same link which same caption (its like overwriting).

int guiLinkRemove(int hwnd)

This function removes all Links from Terminal. Call this function inside init() and deinit() to cleanup all links and re-add them. If you pass hwnd to this function it will delete all links from navigator window, if you pass handle of a parent link, then it will remove only that particular link and all its sublinks. So this function is able to remove all or specific, all-in-one-solution.

Error Handling


Very important to capture Errors

int guiGetLastError(int hwnd)

Call this function after every MT4GUI call will return you error code which was caused by last function call. You should expect 0 as result, 0 is SUCCESS. Refer this table for all possible error codes and explanations:

Alias Value Description
GUI_OK 0 Success
GUI_INVALID_HANDLE -1 Invalid Handle, call guiAdd() at least once
GUI_DATA_LIMIT -2 Some functions have limits, for example guiLinkAdd can add maximum 10 Sublinks. Limit exceed
GUI_DUPLICATE_DATA -3 In case you use guiLinkAdd function with same caption, this error will be thrown
GUI_NO_DATA -4 Hwnd passed to function does not exists
GUI_OPEN_REQUEST -5 Internet API Error
GUI_CONNECT -6 Internet API Error
GUI_INTERNET_OPEN -7 Internet API Error
GUI_SEND_REQUEST -8 Internet API Error
GUI_INVALID_PARAM -9 Invalid parameter, for example guiStartTicker requires minimum 500 as Period
GUI_CANT_WORK -99 MT4GUI is too old and needs update
GUI_UNKNOWN -100 Some unknown error

Ticker Functions


int guiTickerStart(int hwnd,int TickPeriod)

int guiTickerStop(int hwnd,int TickerHandle)

If you want to send ticks to your projects you can use these functions. Minimum TickPeriod is 500ms for security reasons, sending more frequent ticks may cause problems. Important: You can start only one Ticker per hwnd/chart. If you start multiple ticker instances to same hwnd, then fastest one will be applied. If you stop that one then second fastest will be applied etc..

guiTickerStart returns a handle which will be needed to stop the ticker with guiTickerStop. Demonstration code explains many details. Please use Ticker functions with care. Starting multiple tickers from same Study is advanced topic. But its still important to understand how ticker threads are working because you may not know about other studies applied to chart, if you dont have source code you will not know how the ticker has been handled in that study.

// mt4gui-TickerDemo.mq4
#include <mt4gui2.mqh>

// TickerHandle needs to be global
int TickerHandle=0;
int ticks=0;
int hwnd=0;

int init()
  {
     ObjectsDeleteAll();
     hwnd = WindowHandle(Symbol(),Period());          
     // Lets Start Ticker, Period 1000ms = 1second
     TickerHandle=guiTickerStart(hwnd,1000);  
     if (TickerHandle>0) Print("Ticker has been started successfully"); 
     else Print("Ticker could not be started. Returned error: "+DoubleToStr(TickerHandle,0));
     return(0);
  }
  
int deinit()
  {
   // We must stop the Ticker at the end of EA!!
   if (TickerHandle>0)  guiTickerStop(hwnd,TickerHandle);   
   return(0);
  }


int start()
  {
   ticks++;    
   // We count the ticks per Tick and show them on Chart
   Comment("Tick Count :",ticks,"\n Day Of Week:",TimeDayOfWeek(TimeCurrent()));         
   guiPrint(TimeToStr(TimeLocal(),TIME_SECONDS)+" - Tick Count: "+DoubleToStr(ticks,0),Gold);
   return(0);
  }




Other Functions


string guiVersion()

Returns MT4GUI Library version. You may compare version in your code to require a minimum version. mt4gui.dll is shared among all Expert Advisor and Indicators, so its possible that another developer deploys old version of mt4gui to libraries folder. In such case your Project will also try to load old version. We recommend to compare version inside init(). We recommend to compare only Revision, which is last digit part after last “.”. Example output is 2.0.033 and 033 is the revision. All new versions of Library will follow same standard.

//Simple example
string mt4guiVersion = guiVersion();

string guiMD5(string StringToHash)

You may need to calculate MD5 Hash sometimes do determine differences. Use this function

// Howto calculate MD5 using MQL
string toHash="MT4GUI Rox";
string theMD5 = guiMD5(toHash);
Print("MD5 of '"+toHash+" is '"+theMD5);
// Result : MD5 of 'MT4GUI Rox is '6C835FC9DA418F7C9B23A8E8C5520DA7

int guiCRC32(string ToHash)

This function calculated CRC32 Summary from given String. You can use CRC32 value for different purphoses. As example: you may need to calculate MAGIC Number automatically based on different conditions. See example code to get inspired how to use this function effectively:

	
	int MAGICNUMBER = 123;
	string EAName="myEA";
	// Based on Symbol  	
	MAGICNUMBER = guiCRC32(Symbol());
	// Based on Symbol + Period
	MAGICNUMBER = guiCRC32(Symbol()+"-"+Period());
	// Based on EAName + Symbol - So we get different MAGIC Number 
	MAGICNUMBER = guiCRC32(EAName+"-"+Symbol());
	// Based on EAName + Symbol + Period
    MAGICNUMBER = guiCRC32(EAName+"-"+Symbol()+"-"+Period());

As you see thi example demonstrates how you can use to determine the MAGIC numbers automatically based on different conditions.

string guiCID()

This function returns ComputerID from running computer. CID is a unique stamp which will be used per computer to identify them uniquely. Every computer in the world should (theoretically) have unique CID. CID is developed by Fx1.net and is beeing used in many different products such as MQLLock, Guardian. This function may be useful also for you to uniform your clients. It returns a string. CID is 32 byte/char hex number. Example CID: B824B3020ACC168BC79FFD005A8BE145 . You can use CID for example to tie projects to some given computers (for licencing purphoses). Here is small demonstration how to use it:

// Determine ComputerID 
	string CID = guiCID(); 
	Print("Your CID is "+CID);

int guiOpenBrowser(string url)

This function opens users default browser with given url. Sometimes you may want to send user to some internet page. To send client to google, call guiOpenBrowser(“http://google.com”);

int GetFocusedChart()

returns hwnd of current active & focused chart

int guiTimeGMT()

Unfortunetly there is no native way to calculate GMT Time using MQL. Function guiTimeGMT returns you GMT Time in MQL Format(which is UnixTime format). Important: GMT will be calcualted based on local time, if local time is wrong then also GMT time will be delivered off because its relative to local clock.

	// Load Local, Gmt, Broker Time   
	int Time_Local  = TimeLocal();
	int Time_Gmt    = guiTimeGMT();
	int Time_Broker = Timecurrent();

int guiTimeHTTPGMT(string URL)

This function reads the GMT Time from external HTTP Calls. Almost every HTTP Server serves the time in HTTP HEADER. HTTP Time can be retrieved using this function. This function connects to internet and returns the GMT Time in MQL/UnixTime Format. Please do not call this function on every tick! This function would cause a big flood/DDoS towards given URL. As URL you can use almost every trusted site like google.com.

This function can be used if you dont trust users/local computer time or if you wish to detect offtime. Attached demonstration detects time discrepancy between local- and realtime and warns user per Alert() call in case there is a discrepancy over 10 seconds.

Important detail: Asking HTTP header for GMT is working very good to determine time but its important to know that HTTP Request also takes time to be finished, so depending on internet speed of user the Remote GMT and Local GMT may have several seconds difference and this may be normal due to HTTP Request and internet speed.

The URL parameter needs to define the protocoll as mandatory part. So you must either define http:// or https:// as prefix, else function will return a negative value. We recommend to use http:// protocoll because its faster then https://.

You also need to check for return value, a return value >0 is success and it contains the GMT Time from HTTP Header, everything else is ERROR and needs to be captured from your code to avoid wrong interpretations. You or your clients may have no internet or may be offline during your call, in such cases the return value will be an error-code and not a GMT Time. Its essential to cover this case.

// mt4gui-OffTimeDetection.mq4
#include <mt4gui2.mqh>

// global Variable
int hwnd = 0;
int button1,button2,button3,button4;

int init()
  {
  hwnd = WindowHandle(Symbol(),Period());	
  return(0);
  }

int deinit()
  {  
   // Very important to cleanup and remove all gui items from chart
   guiCleanup(hwnd);
   return(0);
  }
  
int start()
{  
	int guiX = 100;
	int guiY = 50;
	int FontSize = 12;

	// Load Local, Gmt, Broker Time   
	int Time_Local  = TimeLocal();
	int Time_Gmt    = guiTimeGMT();
	int Time_Broker = TimeCurrent();
	
	// Print Local Time
	guiPrintXY("LocalTime:",Red,guiX,guiY,FontSize); 
	guiPrintXY(TimeToStr(Time_Local,TIME_DATE|TIME_SECONDS),Gold,guiX+200,guiY,FontSize); guiY+=20;
	// Print Broker Time
	guiPrintXY("BrokerTime:",Red,guiX,guiY,FontSize); guiPrintXY(TimeToStr(Time_Broker,TIME_DATE|TIME_SECONDS),Blue,guiX+200,guiY,FontSize); guiY+=20;
	
	// Print GMT Time based on Local Clock
	guiPrintXY("GMTTime(local):"+DoubleToStr(Time_Gmt,0),Red,guiX,guiY,FontSize); 
	guiPrintXY(TimeToStr(Time_Gmt,TIME_DATE|TIME_SECONDS),Lime,guiX+200,guiY,FontSize); 
	
	// Call This function to determine time discrepancy
	// Time discrepancy may cause big trouble if there is huge difference between local gmt and real gmt
	OffTimeDetection();
return(0);
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//  |O|f|f|t|i|m|e| |D|e|t|e|c|t|i|o|n|
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//  Keep calling this routine inside start()
//  If Offtime has been detected, it shows an alert on screen
//  returns difference in seconds from function
//  threshold defines tolerated seconds of offtime
int  lastOffTimeDetection=0;
int OffTimeDetection(string url="http://google.com",int interval=600, int threshold=10)
{	
	int GMTTimeNow = guiTimeGMT();
	if (GMTTimeNow-lastOffTimeDetection>=interval)
			{							   		
   		int got = guiTimeHTTPGMT(url);
   		int diff=0;
   		// Check return code to make sure there is no error by fetching http gmt time
   		if (got>0)
   		{
		   		int x   = guiTimeGMT();
		   		diff = MathAbs(x-got);
		   		Print("OffTimeDetection Checked : LocalGMT:"+DoubleToStr(x,0)+" RemoteGMT:"+DoubleToStr(got,0)+" Difference:"+DoubleToStr(diff,0)+" seconds");
		   		Print("Google GMT Time:"+TimeToStr(got,TIME_DATE|TIME_SECONDS));
		   		Print("Local GMT Time:"+TimeToStr(x,TIME_DATE|TIME_SECONDS));
		   		if (diff>=threshold)
		   			{
		   				Alert("Your local time possibly off. This may cause trouble in trading. Please check your local time and fix it");
		   			}
		   }
		   		lastOffTimeDetection=GMTTimeNow;				   		
		   		return(diff);   	  
			}		
return(0);			
}





Terminal Functions


int guiFocusChart(hwnd)

Function is used to set chart focus to the chart where EA/Indicator is running. Calling this function will simply change visible/focused chart. Use this function to indicate or inform about important actions.

// Focus to chart if spread is less then 10 points
int Spread = MarketInfo(Symbol(),MODE_SPREAD);
if (Spread<10) 
  		{ 
  		Print("Focusing chart due to important action"); 
  		guiFocusChart(hwnd); 
  		}

int guiCloseTerminal()

int guiMinimizeTerminal()

int guiMaximizeTerminal()

int guiCloseChart(int hwnd)

You may need to close, minimize, maximize the terminal from your code. Those functions are responsible for that. Demonstration says a lot:

// mt4gui-TerminalFunctions.mq4
#include <mt4gui2.mqh>

// global Variable
int hwnd = 0;
int button1,button2,button3,button4;

int init()
  {
	hwnd = WindowHandle(Symbol(),Period());	
	guiRemoveAll(hwnd);	
	button2 = guiAdd(hwnd,"button",100,50,150,30,"Close Terminal");
	button1 = guiAdd(hwnd,"button",100,80,150,30,"Minimize Terminal");
	button3 = guiAdd(hwnd,"button",100,110,150,30,"Maximize Terminal");		
	button4 = guiAdd(hwnd,"button",100,140,150,30,"Close "+Symbol()+" Chart");		
  return(0);
  }

int deinit()
  {
   // Very important to cleanup and remove all gui items from chart   
   if (hwnd>0) { guiRemoveAll(hwnd);   	guiCleanup(hwnd ); }
   return(0);
  }

int start()
{
  // button2 is "Close Terminal" Button, we will close the terminal  
  if (guiIsClicked(hwnd,button2)) 
  		{	
  			Print("Bye Bye");
  			guiCloseTerminal(); 		
  		}
	// button1 is "Minimize Terminal" Button
	if (guiIsClicked(hwnd,button1)) guiMinimizeTerminal();
	// button3 is "Minimize Terminal" Button
	if (guiIsClicked(hwnd,button3)) guiMaximizeTerminal();			  		  		  		
	// button4 is "Close Current Chart" Button
	if (guiIsClicked(hwnd,button4)) guiCloseChart(hwnd);			  		  		  		
return(0);
}

int guiGetChartWidth(int hwnd)

int guiGetChartHeight(int hwnd)

You may need to determine Width & Height of actual chart window. There is no native solution in MQL to do this. Use those 2 functions to determine the chart Width & Height. You can use this functions to align some objects exactly to corners. Important: if chart has indicator applied which creates seperate window, this function returns the height in full range, not only the part with coordinates.

int guiChangeSymbol(int hwnd, string SymbolAndPeriod)

You may need to change symbol on current chart. You can do this using this function. This function can be used in different ways. General syntax is to pass “[,]”. If you want to switch to “EURUSD M15” then you will need to pass “EURUSD,15”. You may also use “EURUSD,”+PERIOD_M15 to switch to M15. Of course daily bars are represented as “,1440″ or “,”+PERIOD_D1.


Period part is optional in parameter but Symbol is mandatory. If you want to chanage current symbol to H1 then you must call guiChangeSymbol(hwnd,Symbol()+”,”+PERIOD_H1); Here is a small demonstration:

// mt4gui-ChangeSymbol.mq4
#include <mt4gui2.mqh>

// global Variable
int hwnd = 0;
int button1,button2,button3,button4;

int init()
  {
	hwnd = WindowHandle(Symbol(),Period());	
	guiRemoveAll(hwnd);	
	button1 = guiAdd(hwnd,"button",100,50,150,30,"Switch to USDJPY");
	button2 = guiAdd(hwnd,"button",100,80,150,30,"Switch to GBPUSD");	
	button3 = guiAdd(hwnd,"button",100,110,150,30,"Switch to DAILY Bars");		
	button4 = guiAdd(hwnd,"button",100,140,150,30,"Switch to M1 Bars");
  return(0);
  }

int deinit()
  {
   // Very important to cleanup and remove all gui items from chart   
   if (hwnd>0) { guiRemoveAll(hwnd);  guiCleanup(hwnd); }
   return(0);
  }
  
int start()
{  
  if (guiIsClicked(hwnd,button1)) guiChangeSymbol(hwnd,"USDJPY");
  if (guiIsClicked(hwnd,button2)) guiChangeSymbol(hwnd,"GBPUSD");
  if (guiIsClicked(hwnd,button3)) guiChangeSymbol(hwnd,Symbol()+","+DoubleToStr(PERIOD_D1,0));  
  if (guiIsClicked(hwnd,button4)) guiChangeSymbol(hwnd,Symbol()+","+DoubleToStr(PERIOD_M1,0));   		
  return(0);
}