Trading Systems

MQL Programming: Complete Guide for 2021 - Build Powerful Trading Robot

Welcome to the MQL Programming Guide. We are going to start with basics and slowly continue to more advanced stuff. If you want to discover our Trading Applications you can sign up for a Free Trial and trade with FTMO account up to $400,000.

Automated trading systems

If you are interested in trading, you have surely already come across the term "automated trading system", abbreviated as ATS.

Thanks to these systems, traders have much broader trading options.

ATS can run continuously day and night and not get tired of it.

Equally, it can trade dozens of markets at the same time, has no emotions and does only what it is allowed to do.

It never fails, does not do anything beyond its settings, and does not miss any trade.

These properties may not always be an advantage but since you are reading these lines you may have already decided for ATS.

An automated trading system is an algorithm written in a particular programming language whose task it is to enter, close and manage trading positions under prescribed conditions or, where appropriate, to perform other tasks.

It is nothing else than tens, hundreds or even thousands of lines of text in code that the trading platform translates into its language and on the basis of which it does what the code says.

The good news is that if we have a platform for it, we can usually also create and test such systems without further installations and fees.

All you usually need is the knowledge of the programming language.

Every trading platform typically has its own, tailored language.

In this series, we are going to cover the most popular programming language of the trading software MetaTrader 4.

This language is called MetaQuotes Language, MQL for short.

What is the MetaQuotes Language and what is it used for?

MQL programming language was developed by the company MetaQuotes, which is also the operator of the popular trading platform MetaTrader used for trading CFD derivatives.

The module for the creation and editing of automated trading systems, but also of the indicators and other programs designed to run in MetaTrader, comes directly with the platform and is called the MetaEditor.

Therefore, if you have downloaded and installed MetaTrader, you automatically have MetaEditor as well.

The same is also true for versions 4 and 5.

You can run MetaEditor from the platform in the Tools menu – MetaQuotes Language Editor or directly from its icon on the top toolbar:


The individual components of the MetaEditor will be dealt with in the next episode.

Basic terms

From a programmer's point of view, the MQL language is derived from C++. Knowledge of C++ is, therefore, an advantage, however, it is certainly no problem to learn to program in MQL without any previous programming experience.

Now let's summarize some important basic concepts to be encountered down the line which is essential for its understanding.

Execution = implementation of the algorithm (program) by the MetaTrader Terminal. Performing the execution, the Terminal "reads" the code of the program and executes the actions in the MetaTrader Terminal.

Control = the part of the program that is being executed. In other words, the part of the code which is currently being read and performed by the Terminal.

Tick = new inbound price. Most of the programs are specifically executed upon each new tick.

Comment = the part of the program which is not there to be executed. In code, this is the part of the line that begins with two consecutive slashes.

For clarity, these parts are colored in gray in the code and they are skipped during execution. If we want to comment on multiple lines, we can mark the beginning of commentary as /* and the end as */.

It may not seem that way but describing parts of the code is critically important to make the code clear to understand not only to anyone else but also even to the author him or herself.


Terminal = the classic user interface of the MetaTrader in which we launch programs and which is able to execute the codes written in the MQL language.

Compilation = compilation is the last phase of the creation of the program.

During this action, the compiler in the MetaEditor checks the code for errors and then prepares the program for operation in the Terminal.

If there are errors in the code, the compiler lists them and the programmer is forced to correct them.

MQL vs. Metatrader 4 and 5

Now shortly something about the differences between the versions of MT4 and MT5 and their relation to the MQL.

MetaTrader 4 and MetaTrader 5 as such are different in many ways, however, the relevant programming languages only differ in parts.

Originally, each version had both its custom MetaEditor and language (the languages were based on the same basis, the MQL5 was only further developed).

Thus, the mutually incompatible MQL4 and MQL5 used to exist alongside each other.

But the popularity of the newer MT5 at the expense of MT4 did not rise and this even held true for the respective MQL versions.

However, programmers wanted to program the programs that were only possible in MQL5, also into MT4.

The creators of the languages, therefore, gave way to a so-called "grand unification" which came along with the MetaTrader build 600.

MQL4 underwent major updates towards MQL5, as well as its corresponding MetaEditor, which is now exactly the same in both versions.

Programs are written in MQL5, however, will only function in the MQL4 under certain conditions, as a lot of elements of MT4 were retained for compatibility with older programs.

Therefore, to be safe, we need to make clear here that this series deals only with the MQL4 language which is, however, already very close to MQL5.

The series will be written in rather laymen terms so that really everyone can learn the basics of MQL.


How do I enter the MetaEditor? What are its parts and what can they do? Can I customize the different panels and toolbars? Can I close some of the windows completely?

As mentioned in the first part, the MetaEditor can be accessed either using the menu Tools – MetaQuotes Language Editor, or the appropriate icon in the top toolbar of the Terminal.

We have also mentioned that what you see then, is all the same, whether MetaEditor is opened in MetaTrader version 4 or 5.

MetaEditor is very simple, practical and effective. It does not contain any extra functionality. The MetaEditor work environment can be divided into five parts.

Top Toolbar


These toolbars contain the traditional program menu and menu related to the active program (active in the main editor).

The full menu is hidden in the drop-down menus File, Edit, etc., while the most used tools are “surfaced” in the form of icons.

On the left side, there are by default a block of tools for working with files, two icons to switch on/off the Navigator module and the Toolbox, while other icons apply to the active program you are working with.

The icon layout can be customized according to your preferences after right-clicking one of the icons and choosing Customize.

What a particular icon does will appear in a tool-tip upon hovering over it or at the same time in the status bar at the bottom of MetaEditor.

On the far right, then, there is a very important tool — the lookup field.

Under the geared wheel icon, you can choose whether you want the specified expression to be searched only in the current document and/or all files and/or the entire MQL community.

If you have checked the option to search in the MQL community, the appropriate web page will open after the search.

The rest of the search results can be found in the Toolbox on the Search tab.

You will undoubtedly find search useful in solving various programming tasks, especially at the onset.

The MQL community operates in English and Russian.



The Navigator is used for navigating through the file structure, which after the “grand unification” of MQL versions moved to a slightly more complex destination.

Generally for Windows, it is C:\Users\ “user” \AppData\Roaming\ MetaQuotes\Terminal\ “instance_code” \MQL4\.

Here you should be able to find all the source files of programs in MQL for the particular MetaTrader instance.

These can then be viewed and edited directly in the editor. The module can be turned off and on using the relevant icon or menu on the main toolbar.

Program-Writing Editor


This is, of course, the largest window.

The Editor itself does not offer too much.

It is, de facto, just a text editor in which you write and edit the active program.

To the left, there is a useful lines counter.

By clicking a particular line number, you can mark it to be easily located at a later time.

If you have multiple open programs, then you can switch between them using the tabs at the top part of the editor.



The Toolbox offers several useful tools, among which you can switch in the lower part.

The tab Errors is used for the overview and description of the errors in the program during its compilation.

Bug reports will be dealt with in one of the later parts of the series.

Search displays the results of the search in the document or in files.

Articles display the latest articles on the website of MQL community.

Upon double click, the relevant article will open on the site

In the Code Base tab, there is a list of new programs available from members of the MQL community have shared to their pages.

Once again, by clicking any of the items, the browser with the appropriate page will open.

The Journal section is used as the program log.

Status Bar

The status bar only occupies a single line at the very bottom of the MetaEditoru, but it provides very valuable information.

In its left part, it displays what an icon or menu item does upon hover over the icon or menu item.

In its right part, then, you can see what parts of the program your cursor is currently located in, i.e. in which row and column.

Still, the far right also shows the abbreviation of the type of writing. INS for classic paste, OVR for overwriting.

You can switch between these modes use the Insert key like in common text editors.

Since we already know everything about the MetaEditor, we can start creating our first program.

We will describe the program file wizard and the basic types of programs.

New MQL Program and Types of Programs in MQL4

How do I start creating my program in the MetaEditor? What are the types of programs and their specific features? Which program should I choose?

In the last part, we described the individual elements of the MetaEditor, which is why we are ready to embark on the creation of the first program. We begin the creation of a new program by clicking on the icon tomql4 the left in the toolbar, or clicking the same button in the File drop-down menu.

First, we have to select the type of program that we want to create.

The default pre-chosen option is Expert Advisor, other options include Custom Indicator or Script.

According to the selected type, MetaEditor prepares for us the code of the program, but this is not a non-reversible choice, we can then change the code as we like, even with the program type.

We can leave the last three types out as we will not need them in this series.

These are additional codes for more complex programs.

Now, when we are to choose the type of program, it is time to explain basic differences between strategy, indicator, and script.

After that, we will finish the creation of the program.



The script is the simplest type of program that is used for one-time execution of a task.

When initiated, it only executes once and turns off.

The entire code to be executed as part of the special function OnStart(), other functions have no purpose in the script.

Do not panic, we will talk about special functions in other episodes.

Examples of the script may be programs that perform a one-time rendition of a graphical element into a chart, programs that open or closed positions with specific characteristics, and so on.

Therefore, the script itself cannot contain trading functions that can open or close or modify positions.

Most importantly, however, the entire code is only executed once.

As soon as the code is executed to the end, the program ends.

Automated Trading System (Expert Advisor)

A program of this type is primarily used for creating automated trading systems, but it can also be used to create other supporting programs that are executed repeatedly, for example, information ones.

Unlike in the case of a script, the code is executed on a regular basis, usually upon every incoming tick, i.e. upon each new incoming price (with the only exception of ticks which came at a time when the previous execution of the program had not finished).

The main part of the program is usually a part of the special function OnTick(), and there are usually also the functions OnInit() and OnDeinit() which contain the piece of code that is executed when starting or switch-off a strategy.

It is possible to add even more special functions to the program which we will be talking about in further installments.

However, you might not need these, especially if you are only just starting with MQL.

A strategy may of course also include trading functions.

When switched on, the strategy runs until it is turned off.

Custom Indicator

A program of the indicator type is used for creating custom graphical indicators.

The main special function of this type is the function OnCalculate() which is also executed upon each incoming price.

Here, too, the functions OnInit() and OnDeinit() are commonly used, along with some of the other special functions. Unlike the strategy, this type cannot contain trading functions.

Although they may be there, they will be ignored.

Once we know which type of program we want to create, we can move to the next options.

In the next window, we will need to name the program.

This is the only mandatory field.

We can also add authorship and link to a web page.

The already known parameters (variables) that will be active in the program can be added to the largest field.

Even here, it holds true that all (non-)specified values apart from the name can then be edited, deleted or added in the code without any problem.

If we chose the script at the beginning, the wizard to a new program will be finished at this stage.

If our plan is to create another program, the wizard will require us to give more information about the special functions.

If you are only starting with MQL, these offers do not need to distract you and you can click through them as they are with peace of mind.

They will first come in handy for the more complex programs.

If you are creating an indicator, at the end of the wizard, you can specify the planned lines of the indicator with their style, color and name.

You can also define whether they will be in a separate window or directly in the chart, and, where appropriate, if they will have a minimum and a maximum.

Once again, this is not anything that could not be changed directly in the code.

After you complete the wizard, the pre-designed code pops up in the code editor.

Its syntax is based on what you entered in the wizard.

In order for you to start getting to know certain parts of the code which are identical to all programs and start organizing your program code, we are going to focus on program structure in the fourth episode.

MQL4 Structure of the Programme

What are the parts of the program? Do these parts vary according to program type? Why is it important to divide codes into logical parts? How does the program control move among program parts?

Each program can be divided into several logical parts.

Their number and use depend on the type and purpose of the program.

The following diagram offers a basic schematic of the parts contained in most programs.

Below the diagram, there is an explanation of the progress of program execution as performed by the computer.

Then, individual main parts of the program are discussed.

It may seem to be an excessive theory but you will learn for yourself that the knowledge of what is being executed is very important.


Structure of the program. Source:

The progress of program execution

The usual progress of program execution among individual parts is marked in the diagram by a yellow line.

As evident from the last episode already, the program first reads the header and then executes the function OnInit() if it is present.

Then, it moves to the main special function which differs according to the type of program, as we have seen in the last episode.


If the program is a script, the special function OnStart() is executed only once.

In other cases, the main special function is executed over and over again until an instruction is given to exit the program.

This may come either from any part of the code or from the program user.

Once that happens, the function OnDeinit() is in turn for the execution, if present, and then the program ends.

Smaller yellow lines indicate the possibility to summon the execution of custom functions from the main functions.

We will deal with user functions closer at a later time.

They are parts of the code which are to execute a specific task.

In the code, they are located outside of the other functions, usually below the whole code.

As seen here, these functions can be initiated to execution from all of the special functions, not only from the main function but also from other custom functions as well.

The number of custom functions in the program is not restricted.

Blue arrows indicate the communications of individual functions with the terminal.

This can be done for instance to get the current instrument price, volumes and other information.

In some cases, the program may even ensure communication outside the terminal, indicated by black arrows.

This involves, for example, the execution of orders where the program communicates with the broker’s server or the work with files where information is exchanged directly with the operating system.


The header usually provides basic information about the program first, such as the version, authorship, description, etc.

This is the information displayed upon program startup in Metatrader.

In order for them to be displayed to the user, the code has to always start with the modifier #property and the name of the specific information type (e.g. copyright, description, version, etc.).

Furthermore, we define the global variables in the header.

These variables will be available to all functions in the program.

Of course, we will talk about variables closer in further episodes of this series.

If the name of the variable is preceded by the modifier “input”, we define a variable whose value can be entered by the program user him or herself (in the case of a script, it is necessary to enter the modifier #property show_inputs to display the window with parameters).

In the header, it is also, for instance, possible to import functions from other file libraries and other activities. mql4


Special function OnInit()

This function contains the code to be executed as first. It is, therefore, a sum of actions to be performed before starting the main part of the program.

It may involve the preparation of graphics, the definition of indicator lines, preparation of calculations etc. With an indicator the function is almost always present, otherwise, it is not necessarily needed and we can leave it blank or delete it completely. In that case, the control switches from the header straight to the main special function.

Although MetaEditor always generates it in the first place, it is in practice completely arbitrary wherein the program it is located.

The control always heads to it first, if it is present in the code.


Main special function

Each program must include a special function that will contain the main part of the program for execution.

That is the part that defines the main mission of our program.

Specific main special functions vary according to the program type.

In the case of a script, it has the name OnStart(), in case of a strategy it is OnTick(), and finally, in case of an indicator, it is OnCalculate().

Several further special functions can be added to the programs.

There will be a special article dealing with them after the completion of the basics series as they will not be needed for the basics.

The name of the special function suggests what kind of events it will be performed.

The OnInit() is executed upon initialization, OnTick() upon receiving a new incoming tick, etc.

This part of the program usually contains the largest part of the code and the execution of this part also employs the control the longest.

In the case of a strategy or an indicator, this section repeats over and over again, until the program is ended.

User-defined functions

Most of the more complex codes will contain user-defined functions for the sake of clear arrangement.

These are all the non-predefined functions which the programmer defines him or herself in the code.

They will be dealt with in detail later. Also, it does not matter where in the code they will be placed.

Normally, they are placed at the very end for the sake of clarity.

They are executed at the moment when they are initiated from other parts of the code that is currently being executed.

The principle of initiation and construction of custom functions will be shown in further episodes, however, it certainly will do no harm to have a look at what they can look like now.


Special functions OnDeinit()

As the name of this special function suggests, it is responsible for the execution of the code upon deinitialization, i.e. end of the program.

Thus, it is a set of actions that are performed once the user or the terminal give the command to end the program. It may involve for example deleting graphics features of the program, parting with the user, etc.

Once again, the position in the code does not matter.

Once the execution of the function is finished, the program ends. If the function is missing, the program will end directly upon the signal to exit, like in the case of OnInit().


In further episodes, we will finally have a look at the specific characteristics of the MQL language. We will start with the division of data into individual types.

MQL4 Data Types

Why is it important to distinguish data according to their type? What data types are there and what are they good for? How does a computer work with data?

Every program has to process certain data.

However, not all data are mutually intelligible.

We will be using numbers, texts, often times also colors or enumerations, and performing various operations with such data – arithmetic, such as addition, multiplication, etc., assigning (assigning values to variables), comparing, and other.

However, we may only perform these operations with data of the same type.

In other words, we must not mix apples and oranges.

A text cannot be added to a number and a color can in no way be compared to a date.

Therefore, it is necessary to strictly differentiate what type of data we are working with.

To communicate to the computer what type of data for a specific variable or function we are working with, we use so-called datatype identifiers in the code.

We insert these identifiers in front of a variable or function when declaring it.

The introduction or declaration of variables and functions can be found in further episodes.

The data in the code can be divided into the types listed in the following table.

Listed here are only the basic types sufficient for the creation of common programs.

There also are derived types which, however, mostly have the sole function of saving your computer’s memory, or conversely, enabling you to insert extreme values. Information about these is available in English at

Identifier Data Type
int integer
bool logical
string string
double floating-point number
color color
DateTime date and time
enum enumeration

It is also interesting that of all of them, the program only uses three types, i.e. integers, decimals, and strings. The difference from other types is only in the size of memory the computer allocates to each value, and in the form, the data are presented to the user. You can get to the bottom of this reading the following lines.

Integers (int)

This type of data is useful for variables and functions which by their nature can only be integers. It may be the number of positions, the number of chart candles, the difference between the prices in pips, and the like. The value of the variables of this type is limited to the number 2 147 483 647 in both the positive and negative spectrum. If we need a higher number, we need to use a derived data type, such as int or long. An example of the introduction of an integer variable and assignment of a specific value is shown in the following line.

int Number = 5;

Logical value (bool)

Logical value, or Bool value, is a data type represented by one of the values TRUE or FALSE. In the code, it can be written as true and false or as 1 and 0. This means that the computer understands this type as an integer.

bool Error = true;

bool Error = 1;

String (string)

We use the string data type for data in which we want to insert text or a string of any characters. The beginning and end of the string have to be always enclosed in quotation marks.

string Adv = „Get up to 40 000 USD for trading CFDs“;

Decimal number (double)

We use a decimal number where the value is not inherently an integer but can also have decimal places (up to 15).

double Decimal = 15.958645;

double Average_profit = Profit/Trading_days;

Colour (color)

If we determine a variable or function as the data type color, the value we input in it will be understood by the computer as a specific color code according to its internal color palette. We have three options for informing it which color we want. The easiest option is to write it in words. However, the color name must be one of the web colors the MQL is able to distinguish. A table with the names can be found at

color Colour = Red;

Another option is an integer number notation. On the Internet, it is usually used in the form of the so-called hexadecimal code. The color hexadecimal code can be retrieved from any simple text or graphics editor. The code is based on RGB values, therefore, on the ratio of red, green and blue color in the formula 0xRRGGBB.

color White = 0xFFFFFF;

We may also use the same value converted to decimal degrees.

color Green = 32768;

There are more options to enter the color code, however, they may be considered as less practical. This is why we will only point you to the appropriate web page for more information:

Date and time (DateTime)

This data type is, of course, used to write dates and, if need be, time as well. A specific data entry will always start with the identifier D´ followed by the date and time code. The formats and which we are used to from our latitudes is also accepted. Seconds, minutes and hours are facultative. However, if the day, month or year are missing, the compiler will notify us of error.

DateTime NewYear1 = D’2017.31.12 23:59:59′;

DateTime NewYear2 = D’31.12.2017′;

Even in this case, the date is converted to an integer number, for the purposes of the processing unit computations as the number of seconds that have passed since 01. 01. 1970 00:00:00. The date and time 29.08. 2015 15:44 may, therefore, be also written this way:

DateTime Now = 1440863081;

You will most likely never enter the number in this format, but it may happen that where you expect the date, a fantastical number like this one pops up due to some kind of error. The cause will then be known to you.

In practice, a date is seldom explicitly entered into variables. Typically, variables which bear time in them are in some way derived for example from the current time, for which we have the functions TimeCurrent() and TimeLocal() functions. Here, too, the above-mentioned conversion to an integer code will come handy, as, for example, current time + two days will simply be calculated as follows:

DateTime TheDayAfterTomorrow = TimeLocal() + 2*24*60*60;

In other words, the day after tomorrow = now + 2(days)*24(hours)*60(minutes)*60(seconds). Now you already know why this is this way, which will make your work with data considerably easier.

Enumeration (enum)

Enumeration is one of the data types which only came into existence in MQL4 after the “grand unification”. This data type is used to create groups of data of the same type. We may assign values to the data, but we do not have to, as they will be assigned automatically. Enumeration must be declared inside curly brackets. In this basic series, we more than likely will not need enumerations. We will be able to read about them in articles beyond the scope of this series.

Already in this episode, we have come across the important concept of a “variable”. It is precisely variables that will be discussed in the next episode.


What is a variable and what does it do in the program? How do I create a variable? How do I assign it a value? Into what types of variables can they be divided?

Work with variables is absolutely unavoidable in any program. A variable acts as the holder of a certain value we assign to it. The value of the variable is stored in computer memory until changed again by another operation.

Using variables, the program can store and present information in various forms. However, you will also be using auxiliary variables which will only operate within the code so their use will not be apparent to the user from outside. You might not feel much informed by these definitions but you will find them clear soon enough from practical examples.

Variables can be divided based on various criteria but first, we will learn how to “produce” such a variable that the computer understands it and assigns a value to it.


The introduction of variables into the program is called declaration. It is very easy. To introduce a variable one has to only know the name and data type we wish to input.

We explained data types in the previous episode. The introduction will be performed by writing the data type identifier and then the name of the variable. The name can only contain English characters. Special characters, including the dot, for example, may not be used.

A declaration is an operation, it is necessary to write a semicolon at the end of it. We will learn why in the next episode dealing with operations.

The introduction of the variable named “Challenge” which should contain integer values, will, therefore, appear in the code as follows:

int Challenge;

There can even be more variables of the same type at the same time, their names only have to be separated by a comma:

double Profit, Loss, Win_Rate, RiskRewardRatio;

This way, we have declared six variables to which we are planning to input decimal numbers. If any of the variables were of a different type, we need to declare them separately. The first value assigned to a variable is called initialization.

MQL4 Initialization

Initialization, i.e. the first assignment of a value to a variable, is simply performed by an assigning operation where we use the symbol =. The options are numerous. Initialization can be performed by direct assignation:

Deposit = 100 000;

Or as the result of an equation in which other variables occur:

A = B + C

Or perhaps as the result of a function or a combination of functions:

Today = TimeToString(TimeCurrent(),TIME_DATE);

This way, we have for example inserted the current date of the broker’s server converted to text into the variable Today. However, the variable Today must be declared as a string type. Once again, do not forget the semicolon at the end.

Declaration and initialization can be combined into a single operation on a single line, like this:

int A = 3;

color Yell = Yellow, Lemon = Lime;

On the previous two lines, we have introduced an integer variable of the value 3 and the color Yell with the value Yellow and Lemon with the value Lime.

Custom vs predefined variables

Above, we have seen the creation and work with custom variables. In the MQL framework, however, there is also a number of predefined variables we do not need to declare or initialize. If we use them in the code, they turn pink and automatically contain the appropriate value.

These variables contain specific data about the market, the chart on which the program is running, and other characteristics of the Terminal.

Below, you will find a table with these variables and the values they contain. You will probably never use some of them while others are used in almost every program.

Variable Value
_Digits The number of decimal places in the price of the market on which the program is running.
_Point The point size of the market on which the program is running.
_LastError Code of the last error.
_Period The timeframe of the chart on which the program is running.
_RandomSeed Status of the generator of pseudorandom numbers.
_StopFlag Program stop flag.
_Symbol The name of the symbol on which the program is running.
_UninitReason The reason for deinitialization.
Ask The last known Ask price of the market on which the program is running.
Bars The number of bars on the chart on which the program is running.
Bid The last known Bid price of the market on which the program is running.
Close[] The array type variable containing closing prices of all of the chart candles.
Digits See _Digits.
High[] The array type variable containing the highest prices of all of the chart candles.
Low[] The array type variable containing the lowest prices of all of the chart candles.
Open[] The array type variable containing opening prices of all of the chart candles.
Point See _Point.
Time[] The array type variable containing opening times of all of the chart candles.
Volume[] The array type variable containing all chart candle volumes.

By clicking on the variable name, you will open its detailed description at

Maybe you paused at the array type variables and looked for them in this episode. However, they deserve their own chapter so we will go through them in the next episode. Now, just briefly on the division of variables to global and local.

Global vs. local variables

Whether a variable is global or local depends on the part of the program in which it is declared. If the variable is declared in the code header outside the body of all functions (we talked about program structure in the fourth episode), it is a global variable.

Such a variable is available to all of the functions of the program – both main and custom ones. In other words, it can be used with the same name and current value in all parts of the program.

However, this type of the global variable must not be confused with global variables which are available even for the entire terminal and all its other programs.

Those are operated using a set of functions. This special type of variables will be discussed in a separate article.

Conversely, any local variable is a variable defined inside one of the functions. This is then available only for that function alone. If it is used in another function, it will not be detected, or the compiler will mark it as an error and force you to repair it.

This other function can also have a variable declared with the same name but its value will depend only on the operations within this function.

If you need to convert the value of a variable from one function to another, it can be done using the parameters of the function call. However, we will only talk about those in the episode of functions.

As mentioned above, the next episode will expand on the issue of variables by the arrays which are used with the very important predefined variables, such as Open, High, Low, Close, Time and Volume.

MQL4 Array variables

What is an array variable? How to index its value? How are its declaration and initialization different from the normal variables? How do you find a specific value from a set of values? Why such variables exist and how will they make my work easier?

As we said last time, we need to allocate a part of the series to a piece on array variables, especially on the predefined ones which fortunately are their simplest instances.

This is because these variables are used to initiate the characteristic values of candlesticks in the graph which are necessary for the formation of most trading systems and indicators.

Arrays in general

A normal variable can only bear a single value at a time. In contrast, an array variable carries the whole indexed set of values which can be up to four-dimensional. Thanks to the indexes, we can then initiate a specific value from the set we currently need.

At a given time, it is only possible to have access to one of the values in the set. The more dimensions the set has, the more coordinates the index has. It is the same as when we are looking for a point on a two-dimensional plane, e.g. a map.

We, too, need to enter the longitude and latitude. But when we are looking for a point in a three-dimensional space, we already need to have three coordinates.

Unlike the geographical coordinates, it could also be needed for example to know the floor of the building. This is nicely illustrated in an image from the website


Figure a) illustrates a one-dimensional set of values of an array variable, figure b) a two-dimensional one and figure c) a three-dimensional one. Fortunately, it will suffice for the purposes of this series to work with one-dimensional sets.

Declaration and initialization

The declaration of an array variable compared to the normal declaration only differs in one thing. Apart from the data type and name of the variable, the number of values in the set have to be stated as well in square brackets. Initialization also only runs slightly differently. If we want to insert the set of values manually, we can do so by listing them in the brackets.

int Serie[4] = {9,8,7,6};

This way, we have declared the one-dimensional variable Serie of the integral type which contains the values 1, 2, 3 and 4. Indexing is performed from left to right starting with zero. The specific value is later initiated in the program by the series name and the index in square brackets.

Result = Serie[1];

After you perform this assignment, the variable Result acquires the value 8, since the index 1 value of the variable Serie is 8 (the first value, that is 9, has index 0).

However, the manual declaration is not very practical mainly due to the enormous sets of values and it is not used much.

A handier method of initializing an array variable presents itself in loops. These will be first dealt with in the upcoming piece on operators but for illustration, let us see what such initialization might look like.

for (x = 0; x < Bars; x++)

{Serie[x] = (High[x]+Low[x])/2}

In this case, the for loop will serve us an example which functions so that the first expression (x = 0) in the header (in the parentheses) is executed, then an iteration of the loop (the code in composite parentheses) is executed, then, the third expression in parentheses (x ++, which is x +1) is executed, then the next iteration of the loop and the loop continues this way over and over again, until the condition in the second expression in parentheses (x < Bars) is met.

We have talked about the variable Bars already – it is the number of candlesticks on the chart.

As we can see, each iteration is done with x higher by one value and the last iteration is done for x = Bars – 1, as the next step no longer meets the condition of the second expression.

With each loop iteration, the variable Serie with the index x is assigned the value resulting from the equation (High[x] + Low[x])/2, which is nothing more than the average of the High and Low of the candlestick with the index x.

The result will be a single-dimensional array variable “Serie” which will contain a set of averages of highs and lows of all the candlesticks on the chart.

This brings us neatly to the very important issue of so-called time series and their indexing.

Predefined arrays

As we said in the past, the MQL language includes several predefined variables that do not need to be declared or initialized. Some of them are of the array type and this part of the series was created about them predominately. Just to make sure, I will repeat which variables these are in the following table.

Variable Values
Time Series array that contains an open time of each bar of the current chart
Open Series array that contains open prices of each bar of the current chart
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
Close Series array that contains close prices for each bar of the current chart
Volume Series array that contains tick volumes of each bar of the current chart

The list is quite possibly familiar to you. This is because when you hover over a specific candlestick in Metatrader, a tooltip will show displaying exactly these details. At the same time, you can see the same details on the status bar to the right.

Thanks to these variables, we can easily retrieve the value of any of these specific features of any candlestick in the graph the program is running in. We already know how to initiate a value, now we just need to know based on what key the values of candlesticks are indexed.

Indexation of the candlesticks takes place from zero in ascending order from the right. This means that the current bar which is just being created has the index of 0. The last finished bar has an index of 1, etc. Everything is illustrated in the following figure and table:



The image shows a minute chart where numbers above candlesticks correspond to their indices. In the table, there are concrete features of the candlesticks with their respective indexes. It follows from the table that if we want to obtain, for example, the opening price of the current candlestick, we need the value Open[0] which is currently 1.54370.

The volume of the candlestick with index 19 – Volume[19] has the current value of 82, and so on. If we return to the example above with the variable Serie and apply it to this particular situation, then after executing this expression,

the value of (1,54352 + 1,54324)/2 = 1,54338 will be saved in the Serie variable with index 2.

We will encounter this type of variable times and times over in this series, so it does not matter if you have not understood the issue completely – everything is clearer in practice. In the next part, we will be dealing with a quite relaxing issue, namely operations.


What is the operation? What types of operations are there? What operations can we use in the code? How come the operation X = X + 2 is ok?

To most of you, this article should be rather relaxing. We need to clarify what operations we can use in the MQL code and how. We will also talk about some of the details that are not completely intuitive if you are new to programming.

The creators of the MQL language divide operations into seven categories; we will now go through the four major ones.

These are the operations you will mostly know from primary and secondary school. However, it is necessary to clarify some of its properties.


The first category of operations is all well known. When performing calculations, we can use the arithmetic symbols as we know them from school, i.e., + for addition, – for subtraction, * for multiplication and / for a division. There are only three features we do not know from school.

The symbol % as a symbol of operation retrieves the remainder after division, and also frequently used are the ++ and – – symbols which reduce or increase a variable by 1. A little table for the sake of clarity:

% Residue of division minutes = time % 60
++ Addition of 1 to the value of the variable y++ y = y + 1
Subtraction of 1 from the value of the variable y– y = y – 1


We change the value of a variable using an assigning operation, i.e. using the symbol =. Now I need to point out a counter-intuitive feature of programming some beginners sometimes cannot accept.

The expression A = B + C in code is not identified as an equation. If that had been the case, the expression X = X + 2 would have been pointless. However, that is not the case. Since the symbol = indicates an assignment operation rather than a symbol of equality, the program’s statement as “the variable X is to be assigned the expression X + 2”.

Therefore, if X equals 2 before the execution of this operation, it will be 4 afterward. If the operation is carried out again, then the new X will be 6. And so on.

This rule applies in the following table of assignment operations.

= Assignment of the value x to the variable y у = x
+= An increase of the variable y by x у += x y = y + x
-= Reduction of the variable y by x y -= x y = y – x
*= Multiplication of the variable y by x y *= x y = y * x
/= Division of the variable y by x y /= x y = y / x
%= The residue of the division of the variable y by x y %= x y = y % x


Relational operations are used to compare the values of two or more variables. They find use especially in the headers of composite operators which we will be dealing with in the next piece. We know most of the symbols from school again, other symbols come purely from the programming realm.

In the table, you can see that the symbol for equality is == instead of the expected = which symbolizes the assignment operation.

Make sure not to confuse these two symbols, as this is a very common mistake which is, nevertheless, not always easy to reveal.

== True, if x is equal to y x == y
!= True, if x is not equal to y x != y
< True, if x is less than y x < y
> True, if x is more than y x > y
<= True, if x is equal to or less than y x <= y
>= True, if x is equal to or more than y x >= y


You have probably heard about logical or boolean operations at the secondary school. Once again, they will be used mainly for composite operators. These are the following three:

! NOT (logical negation) х!=0 True, if x does not equal 0
|| OR (logical disjunction) x < 5 || x > 7 True if x equals 5 OR 7
&& AND (logical conjunction) x == 3 && y < 5 True, if x equals 3 AND y is less than 5

Enumeration of basic operations is finished for us. We should add that a function initiation is also an operation, but we will discuss that when we are through with functions. In the next part, we will open the core issue of operators.


We hope that you have found this article helpful and you are already looking forward to build your trading robot.
We plan for regular updates in the future, so don't forget to keep an eye on our blog.

About FTMO

FTMO developed a 2-step Evaluation Process to find trading talents. Upon successful completion you can get an FTMO Account with a balance of up to $200,000. How does it work?.