MQL5 Lesson 1: Code Editor, Events, Structure of MQL Programs

Hello, friends! This series of lessons is aimed at beginners who have never programmed at all. For those who have tried, already know some language, especially C and mql4, many of these lessons will be simple.

In the first lesson, we will examine the differences between MQL5 and version 4, the structure of the MetaEditor 5 code editor, and the main functions of the structure of MQL programs.

What Is MQL5?

Mql5 is an object-oriented language; it can work with complex data types such as classes. It is very similar to C++. In mql5, compared with the old version 4, there are more event handlers and events themselves, so the possibilities for writing more complex algorithms are higher. Now version 4 has also gained the ability to use an object-oriented approach and many other features that are available in mql5 from the start, so mql4 is now very close to version 5, with the exception of a few things: mql4 has fewer events, slightly less functionality in the tester, and a few other minor details. I suspect this was done to make the transition to version 5 smoother. The fundamental difference between 4 and 5 is that only one active position can be open per instrument. Whereas in 4 we operate with orders, of which there can be many per instrument.

The mql language is a highly specialized language aimed at writing trading strategies, indicators and scripts for trading. The code itself is written in the special MetaTrader editor. You can get to it by clicking the editor icon in the terminal or by pressing F4.

The MetaEditor code editor allows you to edit and write program source code, create and use templates to speed up development, compile the written code, run debugging, and access built-in help. That is, the most important, basic things are present in the editor.

The text in the editor is highlighted in different colors, which is very convenient. The colors, background, and font size can be changed in the program settings.

After writing a program, it needs to be compiled, converted into machine code. To do this, you can click the button on the panel or press the F7 key. In the log, you can view compilation errors and warnings, which include files were included in the program, and other reference information.

The code editor also has debugging. This is a special mode that lets you go through the code line by line. For a very long time, mql4 did not have it, but in the end a debugger was still added. In mql5 it was there from the start. To debug, press the "play" button or F5. In the settings, you can choose the instrument and the timeframe. After pressing it, the EA settings window opens, and program control stops at the line we specified. You can move through the lines using F10 or the "step over" button. To stop debugging, simply press the "stop" button.

mql is an event-driven language. This means that when a certain event occurs, our program reacts to it in some way. Functions for handling these events must be defined in the MQL5 program: the function name, the return value type, the composition of parameters (if any), and their types must strictly match the description of the event handler function. The program receives events only from the chart on which it is running. All events are processed one after another in the order they arrive.

Function OnInit

This service function handles the start of the expert advisor on the chart. Here we write everything that should be executed when the EA is attached to the chart, for example, some checks, drawing panels, preparing data, and so on. It looks like this:

int  OnInit(void);

The function returns one of the predefined values:

    Function OnDeinit

    The OnDeinit function starts when the expert advisor is removed from the chart, that is, it stops working. Procedures for cleaning the chart, saving some statistics, and so on are usually placed here. Here is what it looks like:

    void  OnDeinit(const int  reason);

    where reason is the deinitialization reason code, which can take the following values:

      Function OnTick

      The OnTick function starts when the terminal receives a new quote. It looks like this:

      void  OnTick(void);

      The NewTick event is generated only for experts when a new tick arrives for the symbol whose chart the expert is attached to. It is useless to define the OnTick() function in a custom indicator or script, because the NewTick event is not generated for them.

      The Tick event is generated only for experts, but this does not mean that experts must have the OnTick() function. The point is that not only NewTick events are generated for experts, but also Timer, BookEvent, and ChartEvent events, which will be discussed below.

      The NewTick event is generated regardless of whether auto trading is disabled or enabled (the "Auto Trading" button). Disabling auto trading means only a ban on sending trade requests from the expert; the expert itself does not stop working.

      Function OnTimer

      Called in expert advisors when the Timer event occurs, generated by the terminal at an interval set by the programmer:

      void  OnTimer(void);

      The Timer event is periodically generated by the client terminal for an expert advisor that activated the timer using the EventSetTimer() function. Usually this function is called in the OnInit() function. When the expert advisor finishes working, the created timer must be destroyed using EventKillTimer(), which is usually called in the OnDeinit() function. Each expert advisor and each indicator work with their own timer and receive events only from it.

      If it is necessary to receive timer events more often than once per second, you can use EventSetMillisecondTimer() to create a timer in milliseconds. In the strategy tester, a minimum interval of 1000 milliseconds is used. In the general case, reducing the timer period increases testing time, since the number of timer event handler calls grows. When working in real time, timer events are generated no more often than once every 10-16 milliseconds, which is related to hardware limitations.

      Only one timer can be started for each program. Each MQL5 program and each chart have their own event queue, where all newly arriving events are placed. If the queue already contains a Timer event or this event is in the processing state, then a new Timer event is not placed in the MQL5 program queue.

      OnTrade Function

      Called in expert advisors when the Trade event occurs. The function is intended to process changes in the lists of orders, positions, and trades:

      void  OnTrade(void);

      OnTrade() is called only for expert advisors; in indicators and scripts it is ignored, even if you add a function with this name and type to them. With any trading action (placing a pending order, opening/closing a position, setting stops, triggering pending orders, and so on), the history of orders and trades or the list of positions and current orders changes.

      OnTradeTransaction Function

      The OnTradeTransaction function is called in expert advisors when the TradeTransaction event occurs and is intended to process the results of executing a trading request:

      void  OnTradeTransaction(const MqlTradeTransaction& trans, const MqlTradeRequest& request, const MqlTradeResult& result);

      where trans is the structure of the trade transaction, request is the request structure, and result is the response structure.

      Sending a trading request, for example, to buy leads to a whole chain of trade transactions that are performed on the trading account: first the request is accepted for processing, then a corresponding buy order is created for the account, then the order is executed, the executed order is removed from the active list, added to the order history, then a corresponding trade is added to the history and a new position is created. All these actions are trade transactions. The arrival of each such transaction in the terminal is the TradeTransaction event. At the same time, the order in which these transactions arrive in the terminal is not guaranteed, so you cannot build your trading algorithm on expecting some trade transactions to arrive after others.

      OnBookEvent Function

      The OnBookEvent function is called in indicators and expert advisors when the BookEvent event occurs and is intended to process changes in the order book:

      void  OnBookEvent(const string&  symbol);

      To receive BookEvent events for any symbol, you first need to subscribe to receiving these events for that symbol using the MarketBookAdd() function. To unsubscribe from receiving the BookEvent event for a specific symbol, you need to call the MarketBookRelease() function.

      OnChartEvent Function

      The OnChartEvent function is called in expert advisors and indicators when the ChartEvent event occurs and is intended to process chart changes caused by user actions or the operation of MQL5 programs:

      void  OnChartEvent(const int id, const long& lparam, const double& dparam, const string& sparam);

      where id is the event identifier, lparam is an event parameter of type long, dparam is an event parameter of type double, sparam - an event parameter of type string. We will talk about types in the next lesson.

      OnTester Function

      The OnTester function is called in expert advisors when the Tester event occurs to perform the necessary actions at the end of testing:

      double OnTester(void);

      The OnTester() function can be used only in expert advisors during testing and is intended primarily to calculate some value used as the "Custom max" criterion when optimizing input parameters. Nevertheless, nothing prevents you from writing some other operations in it as well, for example, saving testing results to a file.

      The OnTesterInit Function

      The OnTesterInit function is called in expert advisors when the TesterInit event occurs to perform the necessary actions before optimization starts in the strategy tester:

      int OnTesterInit(void);

      The OnTesterInit() function is intended to initialize the expert advisor before optimization starts for the subsequent processing of optimization results. It is always used together with the OnTesterDeinit() handler.

      The OnTesterDeinit Function

      The OnTesterDeinit function is called in expert advisors when the TesterDeinit event occurs to perform the necessary actions when expert advisor optimization ends:

      void OnTesterDeinit(void);

      The OnTesterPass Function

      The OnTesterPass function is called in expert advisors when the TesterPass event occurs to process a new data frame during expert advisor optimization:

      void OnTesterPass(void);

      The OnStart Function

      The OnStart function is used only in scripts. In it we write everything we want from the script. After being attached to a chart, the OnStart function immediately begins to execute. As soon as it finishes, the script is removed from the chart.

      The OnCalculate Function

      It is called only in indicators when the Calculate event occurs to process changes in price data. This is, in fact, where the entire indicator logic is contained.

      That is all for today, bye everyone!

      Best regards, Dmitry aka Silentspec
      Tlap.io

      This series of video lessons on the MQL5 language is aimed at beginners who have never even tried to learn programming. In the first lesson, we examine the MetaEditor 5 code editor and learn to understand the structure of MQL5 programs.