QF Trading Workshop
Current location: Home > Workshops > QF Trading Workshop

Workshop #3 MQL4 Basics

Posted:2021-03-26 11:52:22 Click:6058

Workshop - MQL Basics




1. What is MQL?



  • MetaQuotes Language 4 (MQL4) is a built-in language for programming trading strategies.
  • This language is developed by MetaQuotes Software Corp. based on their long experience in the creation of online trading platforms.
  • Using this language, you can create your own Expert Advisors that make trading management automated and are perfectly suitable for implementing your own trading strategies.
  • Besides, using MQL4 you can create your own technical indicators (custom indicators), scripts and libraries.
  • MQL4 contains a large number of functions necessary for analyzing current and previously received quotes, and has built-in basic indicators and functions for managing trade orders and controlling them.
  • The MetaEditor  that highlights different constructions of MQL4 is used for writing the program code. It helps users to orientate themselves in the expert system text quite easily.
  • Although MQL5 have been launch for years, however, most traders and brokers are still using MQL4 over MT4 platform.
  • As any MQL4 program can be compiled and run in MT4/MT5 platforms (but no the other way round).
  • In this course, we focus on MT4 programming.

2. Main Features of MQL



Programs written in MQL4 have different features and purposes.

  • Expert Advisor (EA) - is a mechanical trading system linked up to a certain chart. An Expert Advisor starts to run when an event happens that can be handled by it: events of initialization and deinitialization, event of a new tick receipt, a timer event, depth of market changing event, chart event and custom events.
    (We will focus on EA programming techniques in this course.)
  • Custom Indicator - is a technical indicator written independently in addition to those already integrated into the client terminal. Like built-in indicators, they cannot trade automatically and are intended for implementing of analytical functions only.
  • Scripts -  is a program intended for a single execution of some actions. Unlike Expert Advisors, scripts do not process any actions, except for the start event.
  • Library -  is a set of custom functions intended for storing and distributing frequently used blocks of custom programs. Libraries cannot start executing by themselves.
  • Include File -  is a source text of the most frequently used blocks of custom programs like C++.


3. Visit MQ4 Documentation Official Site


For detail documentation of MQL4, please visit https://docs.mql4.com/



4. MQL 4 Programming Basics


In this Lab, we will study the MQL 4 Programming Environment and Basic Operation.

  • The MetaQuotes Language 4 (MQL4) is an OO-programming language intended for writing automated trading strategies, custom technical indicators for the analysis of various financial markets.
  • It allows not only to write a variety of expert systems, designed to operate in real time, but also create their own graphical tools to help you make trade decisions.
  • MQL4 is based on the concept of the popular programming language C++
  • Like C++, MQL4 provides the OO-programming basics include:-
    • Syntax
    • Data Types
    • Operations and Expressions
    • Operators
    • Functions
    • Variables
    • Preprocessor
    • Object-Oriented Programming
      (Details please refers to https://docs.mql4.com/basis)


5. Core Features of MQL4 Programming


In additional to all C++-style programming fundamental tools and function, MQL4 provides pre-defined variables, classes & functions which tailored for program trading, including:

  • Account Information
  • Checkup
  • Market Info
  • Timeseries and Indicators Access
  • Chart Operations
  • Trade Functions
  • Global Variables of the Terminal
  • Technical Indicators


6 MQL Basics - Predefined Variables


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

_Digits

Number of decimal places

_Point

Size of the current symbol point in the quote currency

_LastError

The last error code

_Period

Timeframe of the current chart

_RandomSeed

Current status of the generator of pseudo-random integers

_StopFlag

Program stop flag

_Symbol

Symbol name of the current chart

_UninitReason

Uninitialization reason code

Ask

The latest known seller's price (ask price) of the current symbol

Bars

Number of bars in the current chart

Bid

The latest known buyer's price (offer price, bid price) of the current symbol

Close

Series array that contains close prices for each bar of the current chart

Digits

Number of digits after decimal point for the current symbol prices

High

Series array that contains the highest prices of each bar of the current chart

Low

Series array that contains the lowest prices of each bar of the current chart

Open

Series array that contains open prices of each bar of the current chart

Point

The current symbol point value in the quote currency

Time

Series array that contains open time of each bar of the current chart

Volume

Series array that contains tick volumes of each bar of the current chart


7. Lab 7.0 Your First MT4 Program - A Simple MT4 Example to print predefined variables


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".


8. Lab 7_0_1 Different between init() and start()


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.


9 MQL Basics - Checkup (State Checking)


Functions that return parameters of the current state of the client terminal
Commonly used Checkup functions include:


terminal

Function

Action

GetLastError

Returns the last error

IsStopped

Returns true, if an mql4 program has been commanded to stop its operation

UninitializeReason

Returns the code of the reason for deinitialization

MQLInfoInteger

Returns an integer value of a corresponding property of a running mql4 program

MQLInfoString

Returns a string value of a corresponding property of a running mql4 program

MQLSetInteger

Sets the value of the MQL_CODEPAGE property in an MQL4 program environment

TerminalInfoInteger

Returns an integer value of a corresponding property of a running mql4 program

TerminalInfoDouble

Returns a double value of a corresponding property of a running mql4 program

TerminalInfoString

Returns a string value of a corresponding property of a running mql4 program

Symbol

Returns the name of a symbol of the current chart

Period

Returns the current chart timeframe

Digits

Returns the number of decimal digits determining the accuracy of the price value of the current chart symbol

Point

Returns the point size of the current symbol in the quote currency

IsConnected

Checks connection between client terminal and server

IsDemo

Checks if the Expert Advisor runs on a demo account

IsDllsAllowed

Checks if the DLL function call is allowed for the Expert Advisor

IsExpertEnabled

Checks if Expert Advisors are enabled for running

IsLibrariesAllowed

Checks if the Expert Advisor can call library function

IsOptimization

Checks if Expert Advisor runs in the Strategy Tester optimization mode

IsTesting

Checks if the Expert Advisor runs in the testing mode

IsTradeAllowed

Checks if the Expert Advisor is allowed to trade and trading context is not busy

IsTradeContextBusy

Returns the information about trade context

IsVisualMode

Checks if the Expert Advisor is tested in visual mode

TerminalCompany

Returns the name of company owning the client terminal

TerminalName

Returns client terminal name

TerminalPath

Returns the directory, from which the client terminal was launched


10 MQL Basics - Timeseries and Indicators Access Functions


  • These are functions for working with timeseries and indicators.
  • A timeseries differs from the usual data array by its reverse ordering - elements of timeseries are indexed from the end of an array to its begin (from the most recent data to the oldest ones).
  • To copy the time-series values and indicator data, it's recommended to use dynamic arrays only, because copying functions are designed to allocate the necessary size of arrays that receive values.
  • Commonly used functions include: iOpen, iHigh, iLow, iClose, iVolume, iTime.
iOpen() Returns Open price value for the bar of specified symbol with timeframe and shift.


11 MQL Basics - Chart Time Frame


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.


12 MQL Basics - Trade Functions


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()


13 MQL Basics - Technical  Indicators


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);


14 Lab7_1 : MQL EA Programming Basics


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:

  1. Read the current product Symbol
  2. Set the product symbol code and magic number
  3. Set an alert message to the client window to show the current status
  4. Create a data file in the COMMON file directory “DATA”
  5. In the Start() process, start the timer
  6. Get the current Ask price
  7. Calculate the time difference dtime between the current and previous time step
  8. Calculate the price difference dprice between the current and previous time step
  9. Write the product symbol, dtime and dprice into the data file namely Symbol.csv (where Symbol is the product code)
  10. Wait (Sleep) for 1 sec and Loop Again
  11. Stop when counter to 20

Let's see how it works.



14.1 Program Declaration:


- #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;


14.2 Program Initialization


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);


14.3 Program Main Body - start()


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();

if(file_handle!=INVALID_HANDLE)
{

FileWrite(file_handle,TimeToString(TimeLocal(),TIME_SECONDS),Symbol(),count,dtime,DoubleToString(cprice,5),DoubleToString(dprice,5));

}else
{
Print("Count = 20, Stop writing ");
}


Using sleep(1000) to pause the system for 1000 msec.


Sleep(1000); // Sleep for 1 secs

pprice = cprice;
ptime = ctime;
count++;


14.4 Put it all together into Lab7_1.mq4 and compile it


It should be like this:





到价提醒[关闭]