What is MQL4 and MQL5
MQL is a programming language built into the MetaTrader platform. To write your own trading robots, indicators or other applications in MQL, as well as to compile and debug them, the MetaQuotes Language Editor development environment is used, which, along with all the reference information, is supplied with the MetaTrader Client Terminal installation.

If you have at least once invested in certain assets, maybe you just bought dollars to keep in the bank, then you understand that the investment requires tireless control. I bet youve asked yourself questions like these more than once:
Isn't it time to exit the trade while the price is at its peak?
How to determine if the price of an asset will continue to rise or the market will reverse?
Maybe this time a false signal was received and there is no need to take risks and rush to open a position?
You need to keep up with the market - make trading decisions in a timely manner. It is advisable to do this around the clock during the most active sessions. When work is carried out with several assets at the same time, the situation is even more aggravated.
MQL allows you to implement any trading strategy or algorithm in the form of a computer program. Then this program is launched and runs on a workstation in the MetaTrader Client Terminal all the time. In addition, the delivery set includes a number of trading robots, indicators and scripts from the platform developer in the form of source codes, which greatly facilitates the development of the language and its inherent techniques. Also, MQL is provided with detailed online and offline reference information. There is a huge community around the language.
Let's say you come up with some cool indicator or tricky trading algorithm that you want to use in your work. Or maybe you want to analyze the market using neural networks? There are no restrictions. With MQL, you can implement any idea in the form of an indicator, expert or other application. Compile, debug, check on historical data in the strategy tester - without involving financial risks, and use it in trading.

History of the MQL4 and MQL5 Languages
MQL emerged as an evolutionary development of the platform - a tool for the automatic management of trading accounts in MetaTrader. I will not dwell on this point in detail, I will go over it superficially.
MetaQuotes released the MetaQuotes Language along with the MetaTrader platform, which was previously the FXCharts application. MQL grew to the second version along with the MetaTrader 3 update. Here MetaQuotes rolled out the API, which was provided to clients as an additional layer between MetaTrader Client and MetaTrader Server.
The release of the fourth generation of the platform took place on July 01, 2005. Together with it, MQL4 was released. Backward compatibility with the previous version of the language has been lost. MetaQuotes also stopped supporting the client terminal API, but expanded the capabilities of the language itself and provided ways to integrate custom dll libraries into MQL applications. The API remained available only to brokers at the server, administration and management levels.

See also: Wide range of InstaForex technical indicators.


Name: 01-MQL4-Wizard-File.png Views: 46 Size: 73.1 KB

In June 2010, after numerous releases, MetaTrader 5 was launched. MetaQuotes reworked the trading logic, removing most of the restrictions imposed by the internal structure of the platform. But until now MT5 is not competing with the fourth generation in terms of popularity.
In February 2014, MQL4 was updated along with the 600th build of the MT4 client terminal. MetaQuotes improved the language, introduced most of the features from MQL5, and at the same time accelerated it to the level of a successor.

Possibilities of MQL4 and MQL5 Languages
MQL is used to create automated trading strategies. The MQL code is preliminarily interpreted into C ++ code, which is then compiled into an executable code that works inside the terminal as an included dynamic library. If we draw a parallel with the ancestor, then it will be similar to including the dll library in the executable code of the main program. This approach contributes to ease of development and a low threshold for entry into the field of automated trading. The language is popular among traders, despite its narrow specialization and dependence of the language on the platform.
MetaQuotes took care of their users and provided all their applications with detailed help information. References for MQL4 and MQL5 in the form of htm files are supplied with MetaEditor in several languages. Therefore, you always have a detailed manual with code examples on how to implement the required behavior.
A large community of traders and programmers has formed around MQL. There are tools to facilitate communication between programmers and traders. A layer of ready-made applications has already formed to simplify the trading process. On the resource https://mql5.com there is a market for exchanging applications on a paid or free basis. The trading terminal integrates: application store, code base, articles and signals from other traders. The app store offers hundreds of both paid and free solutions: indicators, advisors, scripts and all kinds of utilities. This is in case it is easier to purchase a ready-made program than to reinvent your own wheel.
But, if you have firmly decided to master MQL on your own and plunge into the world of creating your own applications, in this article I will try to highlight the main nuances that a beginner encounters when taking the first steps in this direction. The advanced reader is unlikely to learn something new from the material below.
Developers provide informational support to the MQL community by regularly publishing tutorials in the form of articles on various topics from the world of trading. The authors of the articles consider new programming techniques, for example, the creation of neural networks, the analysis and solution of problems and limitations of the language, the analysis and testing of trading strategies, the search and implementation of new algorithms.

After compilation, these applications in the form of executable code are placed in the appropriate directory of the MetaTrader Client Terminal (File -> Open Data Folder): Experts, Indicators, Scripts, etc. And then, after initialization on the chart, they are launched in response to events generated by the MetaTrader Client Terminal during operation. Events are a trigger for launching custom programs and allow you to track initialization and deinitialization, receipt of a new quote, custom event on the chart, and so on.
In addition, now there is an opportunity to create applications in Python, respectively, Python tools have become available in the trading terminal.

Trading robot or advisor
It is also often referred to as an expert in the trader community. The Expert Advisor is attached to the chart in the MetaTrader Client Terminal and works continuously as long as the trading terminal is running and a connection to the trading server is available. EAs are used to implement absolutely any trading strategies, control the account status, conduct trading operations under certain conditions, and manage graphical objects. A trading robot is launched for execution every time it receives a new tick for an instrument. The Expert Advisor can also be launched in response to a number of other events: OnTimer, OnChartEvent, OnTesterTimer, etc.
Expert Advisors are used to create user interfaces. Robots, like indicators, have access to graphical objects.

Try Forex indicators in MT4 with $1000 No Deposit Bonus now!

Below is the code for a simple trading robot. Every new tick for the symbol on the chart of which the EA is working, market deals are checked. If there is already a trade for a symbol, the EA waits for it to close. If there is no deal, then a deal is opened in the direction opposite to the previous deal. The EA parameters: volume, stop loss and take profit levels are set by the user. At the time of the first launch, the purchase of currency will be made. After it closes, the next one will open for sale, then again for purchase, and so on. In case of an unsuccessful attempt to open a deal, the advisor writes an error message to the log and falls asleep for 60 seconds, then the attempt is repeated. The Expert Advisor does not check the parameters entered by the user for correctness, therefore, carefully monitor their correctness. Potential problems that are immediately visible at a glance:
The possibility of trading is not checked in general. It can be disabled by the user in the terminal or specifically for this advisor. The trading server may also have restrictions on automated trading.
The volume may be less than the smaller or larger than the larger, and may not be suitable if the server has a limit on the volume step. For example, a user enters 0.23 lots, and the server has a minimum change of 0.05 lots. As a result, the deal will not be opened and the OrderSend function will return an error.
Stop levels for a trade are also not checked for correctness. They may not fit within the minimum / maximum allowable values or not fit within the limits set by the freeze levels.

Indicator
Used to display information about price data that has been transformed in some way. All kinds of oscillators, trend lines, fractals - these are all indicators. The indicators have access to tools for working with graphics. There are 6 of them in MQL4, while in MQL5 there are already 18. For example, Moving Average displays some averaged and / or smoothed price value for a price period in the past and indirectly indicates the future direction of the price for an instrument. Works on the chart all the time. The indicator is updated and recalculated every time a tick is received for the instrument on the chart of which the indicator is working, or when events are received from the user.
With any indicator inside the MetaTrader Client Terminal, one or more buffers are associated with numeric data. MQL4 provides 32 buffers for one indicator, while in MQL5 it allows you to operate with 512.

Name: 04-MQL5-Events.png Views: 51 Size: 26.5 KB

Mqh included library
It is used, as the name implies, for inclusion in other types of programs for the MetaTrader Client Terminal. An experienced developer has a set of their own tools that can be reused many times in various applications.
In the MetaQuotes Language Editor, you only need to specify the path to the included header file relative to the location of the file into which the inclusion is taking place. When compiling the program, MetaEditor will find this file and include the code from it instead of the #include directive. Now all the library code can be used in the application.
Likewise, C and C ++ programmers reuse code by including header files in their projects and linking with binaries.
The example below presents the most simplified interpretation of a dynamic array aka std :: vector from the standard C ++ library. This code compiles and works with MetaEditor version: 5.00 build 2375 on 31 March 2020.

Data types and syntax of MQL4 and MQL5 languages
The data types and syntax of the language are inherited from C ++. Before compilation, the MQL code is preprocessing and interpreted into the corresponding C ++ code, therefore, language constructs that are valid in the ancestor will most likely be compiled and will work in MQL. A programmer familiar with C, C ++ or C # can easily figure out how to write MQL code.
Data types
The following fundamental data types exist in MQL:
boolean values;
single and double precision floating point numbers;
integers, also single and double precision, signed and unsigned;
char for storing character data;
enum enumerations, but the enum class is not supported;
structures, classes and class templates.
At the same time, there is additionally support for color, string and datetime as built-in types, which, of course, somewhat simplifies the developer's life. Working with these types is organized in the C style - using global functions. The behavior of an MQL string is fundamentally different from the std :: string family of templates for C ++ 03, you should not confuse them.

Syntax of MetaQuotes languages
MQL has a syntax similar to C ++. The semantics of the ancestor of the C ++ 03 standard has been transferred to MQL with minor changes. Currently, MQL complies with the C ++ 03 standard in terms of its capabilities.
The main difference between MQL and C ++ is the different semantics of pointers. If in C ++ it is a virtual address at which data is located, then in MQL it is a descriptor, an analogue of a POSIX standard descriptor, a numeric identifier, a kind of wrapper over a "raw" pointer, at which there are objects created in dynamic memory and associated with this identifier. The arrow -> operator is not supported for MQL pointers, dereferencing is performed using the dot . Operator. The descriptor, just like the pointer, must be deleted after the program finishes. However, if you forget to destroy the object that this handle refers to, the runtime will do it for you when the program is uninitialized.
The MQL language lacks the concept of a temporary variable and data movement. Passing variables by reference and by value differs from C ++. and is implemented in MQL in its own manner. Any complex object or custom class will be passed to the function by reference, regardless of whether you use the ampersand operator or not.
There are a number of restrictions on the parent. You cannot write functions and templates with a variable number of arguments. But, what is noteworthy, a number of built-in functions: iCustom, which we will analyze later in this article, printf, StringFormat, PrintFormat - take a variable number of arguments. Paradox!
Working with data and object references differs in nuances compared to C ++, but they are all easily eliminated using messages from the compiler. There are differences in the signatures of the copy constructor and the copy assignment operator due to the different semantics of passing variables by reference. Also, there is no move semantics for moving variables and object instances in MQL.

Differences between MQL4 and MQL5

The differences between the fourth and fifth generation MQL languages are due to the differences between the MetaTrader4 and MetaTrader5 platforms themselves. A lot will be said for me that since the release of the 600 MT4 build, only the fifth version of MetaQuotes Language Editor has been used to write and compile programs in MQL4 and MQL5. In particular, languages operate in different ways with trading operations, since the fifth platform has more trading modes and the concepts of order, deal and position are separated.

How to write an Expert Advisor in MQL4 or MQL5
Before you start writing an Expert Advisor, you need to understand that you must already have a trading strategy. Only then can we start implementing the idea in the form of a formal algorithm. By itself, the code only provides language tools for the implementation of a certain idea.
So, the first thing you need is a working trading strategy. The question of developing this is outside the scope of this article, so let's take something simple for an example. Let's assume the following. During periods of low activity of the instrument on a flat, it is possible to open deals in opposite directions with small levels of limits. This will allow you to take advantage of small sideways market movements and profit from these movements.
Initially, the procedure is the same regardless of the language version. To write programs in MQL, you need to install the MetaTrader Client Terminal, the delivery package of which includes MetaEditor. Now we can launch MetaEditor directly from the working directory of the terminal, or through the main menu in the trading terminal: Tools and then MetaQuotes Language Editor (F4). In the MetaEditor window, in the main menu, click on File -> New. The New button in the graphical menu does the same.