MetaQuotes Language MQL4/MQL5
First appeared | 2005 |
---|---|
Filename extensions | .ex4, .mq4, .mqh |
MQL4 (MetaQuotes Language 4) and MQL5 (MetaQuotes Language 5) are integrated programming languages designed for developing trading robots, technical market indicators, scripts and function libraries within the MetaTrader software.
The primary objective of MQL4 and MQL5 is automation of trading and facilitation of operational analysis. MQL4 and MQL5 comprises an extensive codebase source code library used for developing trading robots.
History
On July 1, 2005 MetaQuotes Software released MetaTrader 4 - a platform for trading on financial markets. MQL4 - an object-oriented programming language, was written specifically for work on this platform. Initially, its syntax was based on C. Another platform, MetaTrader 5, was released in 2010 together with MQL5 - a new language created for it. Both trading platforms are independent of one another. Writing trading robots and indicators for each platform requires the corresponding language.
The release of MetaTrader 4 600 build in 2014 was a major update of the language. That brought it to the level of the faster and more modern MQL5. The development environment MetaEditor became unified for both languages. Although MQL4 and MQL5 are very similar to C++, there are several fundamental differences, which will be considered in a separate section below.
The updated MQL4 features new graphical objects and new functions borrowed from MQL5 and used for analyzing charts. The protection system was completely modified for the executable files EX4, which made decompiling impossible. The MQL5 Standard libraries was transferred almost entirely with the only exception of the trade subsystem, which required adaptation. New data types were added and the micro substitution system expanded (conditional compiling #ifdef, #ifndef, #else, #endif), allowing the use of code from other languages based on С/C++. Structures, classes and object pointers were added as well (it should be noted that object pointers in MQL4/MQL5 are not similar in every way to the ones in С++).
Both languages support nearly all standards of object-oriented programming except multiple inheritance: encapsulation and extensibility of types, inheritance, polymorphism, overload, virtual functions.
Using classes when writing programs enhances debugging and development of large applications.The updated MQL4 features the mode of strict compiling, has higher standards of the coding, which prevents a lot of potential programming errors. In MQL5 this mode is default and cannot be disabled.
General principles of MQL4/MQL5
- Compatibility of code written in MQL4 and MQL5 among themselves and other highly developed programming languages based on Java/C/С++. It allows transferring programs over between high level languages.
- As MQL4/MQL5 syntax is closely related to today's most popular languages Java/C/C++ and C#, it does not take long to master it.
- Object orientation of the MQL language family meets the contemporary programming standards.
- Both MQL4 and MQL5 were developed for the corresponding platforms and they handle all challenges of automatic trading.
- Maximum protection of executable code from decompiling and reliable autonomous work of trading robots.
Compiler
To develop programs in MQL4 and MQL5, MetaEditor - a compiler embedded in the development environment was created. It is integrated in the MetaTrader 4/MetaTrader5 trading terminals. MetaEditor allows convenient editing of program source code, automatic generating projects by a template, profiling code and remotely developing joint applications in conjunction with other people. For maximum convenience of programming, MetaEditor features intelligent tools for working with code. Among them are autosubstitution of function names:
Differences between MQL4 and MQL5
One of the fundamental differences is the trading system setup. MQL4 is used for developing trading programs based on the order system and MQL5 is utilized to implement a positional system. In the MetaTrader 5 trading terminal there are strict delimitations between the concepts of position, order and deal. An order is a request to execute a trading operation, which may result in a trading deal. A position is the aggregate deals on a certain financial instrument. Each financial instrument can have only one position.
There are differences in work with the indicators too. MQL4 contains only 6 styles of drawing indicators whereas in MQL5 there are 18 of them. After creating a custom indicator instance in MQL5, its handle can be obtained for getting values of indicator buffers and setting up properties of the indicator itself. MQL4 does not provide this opportunity. These differences are insignificant for technical analysis and creating automatic trading systems. However, fragments of code for work with technical indicators cannot be used directly between the MQL4 and MQL5 languages.
MQL5 comprises a significantly expanded list of trading functions for work with open orders, a list of open positions, order history and deal history. In MQL4, different functions such as OrderSend(), OrderClose(), OrderCloseBy(), OrderModify(), OrderDelete() were initially incorporated for performing each trade operation. These functions can be used to open/close and delete pending orders.
In MQL5 all trading operations are carried out by sending trade requests using only one function - OrderSend(). As a parameter, a function gets passed a request either to place a pending order, or to open by the market, or to cancel a previously placed order. Introducing the new function OrderSendAsync() to MQL5 enabled asynchronous trading operations. That allowed to create a new class of high-speed robots.
An important novelty in MQL5 is Depth of Market and a new event type of handling Depth of Market information.
New event types added to MQL5 represent another significant difference between the languages. These event types allow flexible management of testing and optimization of trading robots in the MetaTrader 5 strategy tester - TesterInit, TesterPass and TesterDeinit. Detailed information on the difference between the two languages can be found in the documentation on the developer's website.
Capabilities
Capabilities of MQL4/MQL5 directly address traders' needs and requirements. It was developed for writing trading programs and is used only for that purpose. Functions for performing trade operations OrderSend(), OrderClose(), OrderCloseBy(), OrderModify(), OrderDelete() have been initially incorporated in the language and are used for changing the state of a trading account.
Hundreds of programs for automated trading reflecting personal preferences and diversity of trading strategies are written every day. Today more than 10 000 sellers of homegrown programs written in MQL 4 and MQL5 are officially registered. The total number of Meta Trader 4 and Meta Trader 5 users counts in millions.
There are four program types that can be written in MQL4/MQL5.
- Expert Advisors — automatic systems trading by specified parameters and following a coded algorithm. Occurrence of a previously specified event like receiving a new tick, an alert about a new trading operation or even pressing a button or clicking a mouse, triggers the Expert Advisor to perform a programmed action.
- Example of the Expert Advisor: program Three Moving Averages. The Expert Advisor opens and closes positions according to the trend strategy based on the location of three exponentially smoothed moving averages: fast, slow and medium:
- Custom Indicators. Written by users, they are used along the ready-made indicators integrated in the terminals. Their function is purely analytical. Indicators do not perform trading nor carry out operations that slow down the interface stream such as sending emails or performing a random delay. The main task of indicators is to monitor a situation, reflect and interpret it and then submit to a trader for analysis.
- Scripts. A script is a program intended for a single execution of an action. The start event is the only event type processed by the script.
- Custom Functions Libraries.In addition, there is an opportunity to create 'include files' (#include). 'Include files' allows you to include most frequently used functions and classes without directly pasting their source code into its program. Using functions and classes simplifies creating, debugging and compiling because when using dynamic libraries, functions load only when they are called directly.
MQL4/MQL5 are specialized languages developed specifically for the MetaTrader 4 and MetaTrader 5 platforms. They allow traders to implement and automate their strategies. Clearly it is a specific tool for automated trading. The functionality of MQL4 and MQL5 is enriched by the opportunity to easily transfer code from the languages similar to C++.
The MQL4 and MQL5 Syntax and their Difference from С++
The syntax of the languages is similar to the one of C++, however there are exceptions. MQL4 and MQL5 do not feature pointer arithmetic. The developers discarded it as they wanted to avoid computer security threats at direct access to RAM. The goto operator is also missing in the MQL languages as well as a possibility to declare anonymous enumeration and multiple inheritance.
Text formatting - any number of space symbols such as spaces, tabs, empty strings can be used to make the code more readable and convenient to work with. There are exceptions, however. A line break symbol must not be used immediately after a hash and space symbols cannot be used inside constants, identifiers and key words.
Comments - as with the C/C++, MQL4/MQL5 comments can be both single-line and multi-line. A single-line comment starts with the // symbols and ends with the new line character. Multi-line comments start with the /* symbols and end with */ ones. They cannot be nested.
Identifiers - identifiers are used as names for variables and functions. The length of an identifier cannot exceed 63 characters. The following characters can be used in writing an identifier: numbers 0-9, Latin upper and lower case letters Z, recognized as different characters and the underscore character (_). A number can not be used as the first character.
Data types
Main data types used in MQL4/MQL5:
- integers (char, short, int, long, uchar, ushort, uint, ulong);
- Boolean or logical (bool) ;
- literals (ushort);
- strings (string);
- floating point (double, float);
- color (color);
- date and time (datetime) ;
- enumeration (enum).
Structures and classes are a complex (abstract) data type that can be operated in MQL4. Classes differ from structures in the following characteristics:
- the key word class at declaration;
- all class members have private access by default whereas structure members have public access;
- class objects always have a table of virtual functions when structures cannot have it;
- the new operator can be applied only to class objects. It cannot be applied to structures;
- inheritance: a class inherit from a class only and a structure derives only from a structure.
Operations and expressions
All common operations - arithmetic, bool, binary etc. are present in MQL4/MQL5. The precedence of operations corresponds to that adopted in С++.
Client terminal events in the event model of the Language
The MQL4 and MQL5 languages allow writing programs handling client terminal events. Unlike procedural languages using the flat functional model, MQL uses an event model. It allows writing of simple and easy to understand code, which saves development costs and makes the language efficient. There are several event types in MQL4 and MQL5.
- Init (event of a program loading, or beginning of work after a financial instrument has been changed, or input parameters have been altered, or the account has been switched);
- DeInit (event generated when the terminal has finished work, before a change of a financial instrument, a chart timeframe, an account or input parameters);
- Start (event starting a script after the latter has been loaded);
- NewTick (event generated upon receiving new quotes);
- Calculate (generated only for indicators when price data gets changed or immediately after the Init event has been generated);
- Timer (generated periodically if the user has activated the timer with a specific function);
- Tester (generated immediately after testing of an Expert Advisor on historical data has finished);
- Chart Event (generated when a user is working with a chart, namely, when graphical objects are created and deleted, when a graphical object gets clicked on or moved with a mouse or when text on a chart gets edited etc.);
- BookEvent (only in MQL5).
Each of the above functions is handled by the functions provided in the language.
Criticism
The major disadvantage of the languages of the MQL family is the impossibility of creating independent applications as each language is attached to its corresponding platform (MetaTrader 4/MetaTrader 5), and the programs EX4/EX5 only work in them.
References
Bibliography
- "MetaTrader - investiˇcná platforma pre obchodovanie" (PDF). Is.muni.cz. Retrieved 14 November 2014.
- "Evaluating the Effectiveness and Sensitivity of Forex Trading Robots" (PDF). Unitec.researchbank.ac.nz. Retrieved 14 November 2014.
- "Forex Analysis and Money Management : Interactive Qualifying Project" (PDF). Wpi.edu. Retrieved 14 November 2014.
- "INVESTMENT AND TRADING : An Interactive Qualifying Project Report Submitted to the Faculty of WORCESTER POLYTECHNIC INSTITUTE" (PDF). Wpi.edu. Retrieved 14 November 2014.
External links
- "MQL4 documentation". Docs.mql4.com. Retrieved 14 November 2014.
- "MQL5 documentation". Docs.mql5.com.