Programs written in MQL4 have different features and purposes.
For detail documentation of MQL4, please visit https://docs.mql4.com/
In this Lab, we will study the MQL 4 Programming Environment and Basic Operation.
In additional to all C++-style programming fundamental tools and function, MQL4 provides pre-defined variables, classes & functions which tailored for program trading, including:
For each executable mql4-program a set of predefined variables is supported, which reflect the state of the current price chart by the moment a mql4-program (Expert Advisor, script or custom indicator) is started.
Variable |
Value |
Number of decimal places |
|
Size of the current symbol point in the quote currency |
|
The last error code |
|
Timeframe of the current chart |
|
Current status of the generator of pseudo-random integers |
|
Program stop flag |
|
Symbol name of the current chart |
|
Uninitialization reason code |
|
The latest known seller's price (ask price) of the current symbol |
|
Number of bars in the current chart |
|
The latest known buyer's price (offer price, bid price) of the current symbol |
|
Series array that contains close prices for each bar of the current chart |
|
Number of digits after decimal point for the current symbol prices |
|
Series array that contains the highest prices of each bar of the current chart |
|
Series array that contains the lowest prices of each bar of the current chart |
|
Series array that contains open prices of each bar of the current chart |
|
The current symbol point value in the quote currency |
|
Series array that contains open time of each bar of the current chart |
|
Series array that contains tick volumes of each bar of the current chart |
7.1 MT4 Programming Environment (so-called "MetaEditor") can be started independently or via MT4 program.
It should be installed into your PC when you install your MT4 system.
To start MetaEditor via MT4 program.
7.2 First, start your MT4 application.
7.3 Second, from menu, click "Tools-MetaQuotes Language Editor" (or press F4) to launch MetaEditor. Like this
7.4 The MetaEditor should be launched automatically. Like this
Basically, the MetaEditor is both a MT4 program/script editor and compiler.
It consists of THREE main sub-window:-
1. Navigator Window - Should the directory structure of all the scripts and programs stored in your PC.
Where "Experts" is the main sub-directory of MQL4 used to store all the Expert Advisor (EA) MT4 program.
You can open the directory by right-click your mouse on top of the Expert / MQL4 folder icon to view the file structure.
2. Program Editor Window - A Multi-window for you to edit your MT4 program(s). Actually you can edit and compile a batch of MT4 program by using the batch compilation functions. (Useful when you have to make changes to a batch of EA programs of different products at the same time).
3. Message Window (Bottom) - It shows several message groups. The most important one is the
"Error Message" Tag which shows all the compilation Errors and Warnings.
Note: All MT4 EA source codes are ASCII file with extension .mq4 and compiled file with extension .ex4 .
Like C++, MT4 programs with Errors will not generate .ex4 until all Errors are fixed.
7.5 To write a New EA program, you can 1) use any editor to create a .mq4 extension file; 2) use "New" button to create a new MT program/script/library. Like this:
7.6. Name the EA Program as Lab7_0, update the Author and Link HTTP accordingly. Like this:
7.7 A New EA program Window will be opened some basic structures OnStart() (same as start()), OnInit() (same as init())
Edit the following code into Editor window:
//+------------------------------------------------------------------+
//| Script program start function | //+------------------------------------------------------------------+ int init() { Print("Symbol name of the current chart=",_Symbol); Print("Timeframe of the current chart=",_Period); Print("The latest known seller's price (ask price) for the current symbol=",Ask); Print("The latest known buyer's price (bid price) of the current symbol=",Bid); Print("Number of decimal places=",Digits); Print("Number of decimal places=",_Digits); Print("Size of the current symbol point in the quote currency=",_Point); Print("Size of the current symbol point in the quote currency=",Point); Print("Number of bars in the current chart=",Bars); Print("Open price of the current bar of the current chart=",Open[0]); Print("Close price of the current bar of the current chart=",Close[0]); Print("High price of the current bar of the current chart=",High[0]); Print("Low price of the current bar of the current chart=",Low[0]); Print("Time of the current bar of the current chart=",Time[0]); Print("Tick volume of the current bar of the current chart=",Volume[0]); Print("Last error code=",_LastError); Print("Random seed=",_RandomSeed); Print("Stop flag=",_StopFlag); Print("Uninitialization reason code=",_UninitReason); return(0); }
int deinit()
{ return(0); } int start() { return(0); } |
Note: One can also use OnStart() instead of start() or OnInit() instead of init().
7.8. Compile Lab7_0.mq4 program by clicking the "Compile" button.
If everything is fine, it will be error free, like this:
7.9 If you check the file directory of Expert, there should be two MT4 files. Lab7_0.mq4 (EA source code) & Lab7_0.ex4 (EA executable file).
7.10. Save the Lab7_0.mq4 program file.
7.11 As the main function of MT4 EA program are used for automatic trading purpose, so they are all "attached"("added") to a product chart window for execution purpose.
To run your Lab7_0.ex4 program:
- Go back to your MT4 application
- Choose any Chart Window e.g. EURUSD H4 Chart Windows
- From the Navigator Window, there should a new Lab7_0 icon under the "Experts" directory
- Choose "Attach to a chart" or "double-click" the Lab7_0 icon to run this EA onto EURUSD Chart Window.
Like this
- The EA program results will be shown on the "Experts" Tag of the "Message Window" at the bottom.
Like this:
Note: Remember to press the "AutoTrading" button to invoke the auto trading function.
Note:
1) Although every EA program MUST "attached" to a product Chart Window for execution, it doesn't mean that the product information (e.g. price) are related to the EA program (they can be totally unrelated). Which means, you can run a EA program to read the current and historical prices of HSI with a EA program attached to the EURUSD chart window.
2) Actually it is the flexibility of EA program in the sense that you can write a "Universal" Trading Strategy EA program that can be used on ANY financial product, or in the other extreme to write a EA program that can only be used on a particular product instead (if you try to sole your EA .ex4 program to your client).
3) To stop the EA program. right-click mouse on Chart Window, Select "Expert Advisor - Remove".
Obviously, the meaning of init() should be for program initialization and start() is for program execution.
One might wonder, technically speaking, what will happen if we put the program statements from the init() module to start(). In other words, what is the guidelines for us to put the program/assignment statements into init() or start() module.
8.1. To check for it, why NOT to a simple experiment by moving the all the program statements in Lab7_0 from init() module to start() module and rename the EA program into Lab7_0_1.
Like this:
8.2. When you compile the program, it should be also Error Free. But when you run the program, you will see the difference. Like this. What is IT?
8.3 The truth is: As said before, the main function of MT EA program is used for automatic trading which involve continuously monitoring the market movement. In order to do this, the core function of the start() module is not only served for the core program execution logic, but also served for the continuously monitoring of the market movement using a continuously looping (when "automatic trading" function is ON).
So as a critical guideline, for ALL the program "one-off" task such as variables initialization, program initialization, parameter and global function initialization and settings should be put into the init() module. All the other program statement which need continuously monitoring, e.g. monitoring the RSI and MACD values and MA-crossing, continuously chart pattern matching, should be all put into the start() module.
Functions that return parameters of the current state of the client terminal
Commonly used Checkup functions include:
terminal
Function |
Action |
Returns the last error |
|
Returns true, if an mql4 program has been commanded to stop its operation |
|
Returns the code of the reason for deinitialization |
|
Returns an integer value of a corresponding property of a running mql4 program |
|
Returns a string value of a corresponding property of a running mql4 program |
|
Sets the value of the MQL_CODEPAGE property in an MQL4 program environment |
|
Returns an integer value of a corresponding property of a running mql4 program |
|
Returns a double value of a corresponding property of a running mql4 program |
|
Returns a string value of a corresponding property of a running mql4 program |
|
Returns the name of a symbol of the current chart |
|
Returns the current chart timeframe |
|
Returns the number of decimal digits determining the accuracy of the price value of the current chart symbol |
|
Returns the point size of the current symbol in the quote currency |
|
Checks connection between client terminal and server |
|
Checks if the Expert Advisor runs on a demo account |
|
Checks if the DLL function call is allowed for the Expert Advisor |
|
Checks if Expert Advisors are enabled for running |
|
Checks if the Expert Advisor can call library function |
|
Checks if Expert Advisor runs in the Strategy Tester optimization mode |
|
Checks if the Expert Advisor runs in the testing mode |
|
Checks if the Expert Advisor is allowed to trade and trading context is not busy |
|
Returns the information about trade context |
|
Checks if the Expert Advisor is tested in visual mode |
|
Returns the name of company owning the client terminal |
|
Returns client terminal name |
|
Returns the directory, from which the client terminal was launched |
iOpen() Returns Open price value for the bar of specified symbol with timeframe and shift.
All predefined timeframes of charts have unique identifiers. The PERIOD_CURRENT identifier means the current period of a chart, at which a mql4-program is running.
This is the group of functions intended for managing trading activities.
Major Trade Functions need to be used in EA are:
- OrderSend()
- OrderClose()
- OrderModify()
- OrderDelete()
A complete list of function can be found at https://docs.mql4.com/trading
Example: OrderSend()
A group of functions intended for calculation of standard and custom indicators.
Totally 39 technical indicator functions are provided.
Commonly used technical indicators include:
- iBands - Bollinger Bands
- iMomentum – Momentum
- iMA - Moving Average
- iMACD - Moving Averages Convergence-Divergence
- iRSI - Relative Strength Index
- iStochastic - Stochastic Oscillator
- iFractals - Fractals
Example: iMA - Moving Averages
iMA - Calculates the Moving Average indicator and returns its value.
Program Example of iMA()
MA_13 = iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i); |
In this Lab, we use a simple EA program to demonstrate the basic programming structure and style of EA programming using MQL4.
This program will do the following tasks:
Let's see how it works.
- #property is used to declare program properties
- Declare all variables such as:
- TPSymbol – product symbol code
- FileName – Data file
- Counter
- Magic number
extern double TPLot=10; //Transaction Volume extern int TPn=0; //Current Product No extern int pHour=0; //Previous Server Hour extern string TPSymbol=""; //Product Symbol, Forex.com add "pro" extern int TPMagic=0; //Product Magic No extern int nPeriod=PERIOD_M1; //PERIOD_M1 or PERIOD_M5 extern uint ctime=0; extern uint ptime=0; extern uint dtime=0; extern double cprice=0; extern double pprice=0; extern double dprice=0; extern string FileName="Labv1.csv"; // File name extern string DirectoryName="DATA"; extern int file_handle; extern int count=0; |
Using Init() – check for the product symbol in the current active window. This process is useful when the client is not familiar with EA trading system to prevent them trigger the EA program in the wrong product window.
if (Symbol()=="AUDCAD") { TPn=0; TPSymbol ="AUDCAD"; TPMagic =888000; } else if (Symbol()=="CADJPY") { TPn=1; TPSymbol="CADJPY"; TPMagic =888001; } else if (Symbol()=="CHFJPY") { TPn=2; TPSymbol="CHFJPY"; TPMagic =888002; } else if (Symbol()=="EURCHF") { TPn=3; TPSymbol="EURCHF"; TPMagic =888003; } |
Once the initialization is completed, using alert() to show a Pop Up windows on the client windows to show the current status.
Alert(TPSymbol,"Initialization : TPn=",TPn," TPSymbol=",TPSymbol," TPMagic=",TPMagic," nPeriod=",nPeriod); |
Also, the initialization of the data file handle is done in the init() section as well:
FileName=Symbol()+".csv"; file_handle=FileOpen(DirectoryName+"//"+FileName,FILE_COMMON|FILE_READ|FILE_WRITE|FILE_CSV); |
We use GetTickCount() returns the number of milliseconds that elapsed since the system start.
if (count<20) { ctime = GetTickCount(); |
Using Ask to get the current Ask price (Similar for “Bid”)
dtime=ctime-ptime; cprice=Ask; dprice=cprice-pprice; string str_cprice=DoubleToString(cprice,5); string str_dprice=DoubleToString(dprice,5); |
Using Print() to printout the current status onto the Expert Window of the system.
Print("Count=",count," ",TimeToString(TimeLocal(),TIME_SECONDS)," ",Symbol()," : time elapse= ",dtime, " msec Price= ",str_cprice," Diff= ",str_dprice); |
Using FileWrite() to printout the data into the designated datafile.
ResetLastError(); |
Using sleep(1000) to pause the system for 1000 msec.
Sleep(1000); // Sleep for 1 secs |
It should be like this: