Introduction To MetaTrader 5 An - Rafael F. V. C. Santos
Introduction To MetaTrader 5 An - Rafael F. V. C. Santos
MQL5
All rights reserved. This e-book or any part thereof may not be
reproduced or used in any way without the express written permission
of the author or publisher, except for the use of short quotations in a
review of the e-book.
Investors and speculators in the financial market know that the main
enemy to make money in this world is precisely the emotional factor.
Human beings have desires, wants, greed, fears and fears that make
the activity decide the best time to buy and / or sell a real challenge.
When we are working with Investment Robots, we are discussing a
strategy that has been previously defined and structured so that it can
be executed in a timely manner. Fortunately, robots do not get tired,
stress or have any feelings that allow misunderstandings and / or
biases when buying or selling.
Optical fibers allowed for a revolution in communication. In the
investment world, for example, every thousandth of a second can cost
millions of dollars. So-called High Frequency Traders (HFTs)
operating on the world's top stock exchanges makes decisions at
infinitesimal speeds and thus are threatening many professional
brokers and traders.
The HFTs' decision to buy and / or sell is taken in milliseconds, up to
ten to fifty times faster than a simple wink of the human eye (lasting
approximately 300 milliseconds). It is practically unfeasible and unfair
the operational comparison of any computational system of this
category with a normal human being.
Recent data (year 2018) show that more than 50% of US financial
operations are carried out by investment robots. And the results show
that these robots can increase financial returns by up to 15%. There
are some stock exchanges where more than 90% of operations are
carried out by investment robots.
1.4. Computer Programming
So to achieve the goal of creating our first Expert Advisor, this e-book
organizes and simplifies in a didactic way the necessary steps with
the knowledge and usage information of MetaTrader 5 and its MQL5
programming language.
Here's a summary of what you will learn from reading this e-book:
- Learn how to install MetaTrader 5;
- Know the main benefits of the MetaTrader online portal;
- Understand the main features and differences between MetaTrader
and MQL5:
- Learn to add indicators and EA;
- Know MetaEditor and some of the main shortcuts to facilitate
programming;
- Learn the programming syntax of MQL5;
- Understand the main functions of the MQL5 development libraries.
- Create a strategy using trend indicators (moving averages) and
consolidated market indicators (Relative Strength Index - RSI);
- Program step-by-step a Multistrategy EA;
- Make backtests of the created EA;
- Know the backtest statistics;
- And much more.
Just go ahead until the end of the installation. At the end you will be
asked for an account with login and password. It is necessary for us
to use the pricing data for financial assets. In this e-book we will use a
demo account from XP Investimentos.
See below the open program requesting the login, password and
type of server (if real or demo).
2.2. Main elements of the MetaTrader 5
In the figure above, we can see that the indicators are separated by
trend indicators, oscillators, volumes, Bill Williams and Custom. Trend
indicators, as the name implies, are more apt to warn when the
market is within some well-defined directional behavior. On the other
hand, the Oscillator indicators are more adequate to warn of
opportunities within a lateralized market, a market in consolidation.
Bill Williams[2] is a very popular trader who has developed several
important and widely used indicators. Therefore, a specific section
was created for the indicators created by it.
It is interesting the possibility that we have to use indicators and
native EA of MetaTrader itself and indicators and EA created by us or
even offered in the Market tab of the field Toolbox.
2.4. Field Toolbox
In the Experts tab, we can view the main information logs regarding
the operation of our robots. In this place, we are informed about the
sending and execution of orders, problems with variables, errors of
execution and operations.
Now that we already know, in general, the main fields of MetaTrader
5, we go to the main graphic field, which is the window of visualization
of the price candles.
2.5. Looking for Candels
So, just load the saved template, to a new graphic, so that the
settings are immediately applied. That way, we have a lot of flexibility
to be able to configure visualization templates for setups of different
strategies.
2.7. Drawing Objects
You can draw several objects in price charts. We can add channels,
support lines and resistance, Fibonacci, up/down arrows etc.
In this way, it is possible to make a visual technical analysis very
complete with the main graphic objects present in the platform.
Right-click on the graphic you can see the list of objects and make
different types of edits like modify subtitles, colors etc.
It is worth spending some time familiarizing yourself with the use of
graphics and objects.
2.8. Transition between Graph Times
We can also change the candle time from the shortcut bar, as shown
below:
2.9. Adding Indicators
The indicators, for many traders, are the main guiding factors for
decision making. These are the indicators that often alert us to enter
and exit an operation in timely situations. And when you talk about
indicators, MetaTrader does not leave you wanting.
Currently, the platform has more than 2,000 indicators available for
free download. This download can be done either by the site itself or
by the platform in the Toolbox field on the Code Base tab.
Let's, for example, add moving averages to the chart. We can do this
either through the menu Insert -> Indicators or directly clicking in the
field Navigator -> indicators, click and hold the chosen indicator and
drag to the graphic window.
As an example, let's insert a Moving Average indicator:
Now let's add two moving averages. Our averages should have
periods of 72 and 32 with zero shift, exponential methods and
applied to closing prices:
After clicking on ‘ok’, we have the immediate addition to the selected
asset graph.
Let's now add the Relative Strength Index (RSI). This indicator is
interesting as it is drawn in a separate window from the main candle
price window (see figures below).
Let's leave a period of 9 applied to the closing price:
This action will open, for us, a new field: Data Window. Now we can
position the mouse cursor over any candle of the graph to obtain
detailed information of prices and indicators in the place chosen.
See the example below, where we place the mouse on the highlighted
candle in green and the Data Window gives us the detailed
information:
Chapter 3
3. MQL5 Community
Oscillations in the energy and internet network are problems that can
compromise the proper functioning of our investment robots. An
alternative to solving this problem is by hiring a Virtual Private Server
(VPS) virtual machine. The MQL5 portal itself provides this kind of
service.
There is the possibility of contracting the VPS virtual machine service
by other companies, such as Amazon AWS
(https://aws.amazon.com/en/vpc/) that even offers a free year of use.
We have the Forum field which is where we will probably spend a
good part of our learning journey answering and putting our doubts
about the MQL5 codes. This is a good place to exchange
experiences, make friendships and partnerships.
Chapter 4
4. MetaEditor MQL5
Let's click the New icon and then choose from the MQL5 wizard the
type of project that we want to create.
We can notice that we have several design options. This Wizard even
allows us to create investment robots without programming
knowledge. Of course in this case we will be blind to most of the steps
and we will hardly do anything with confidence and due security.
As this ebook intends to provide the first steps with the MQL5 tool we
will only have the first option Expert Advisor (model). There are
two[3] other e-books from the same author that show you how to
develop Indicator and Scripts codes.
Let's first name our investment robot (Expert Advisor). We'll call it
EA_MA_Cros_RSI (Expert Advisor of Moving Moving Crosses with
the RSI Dindicator). This is just a temporary name for MetaEditor
presentation.
After clicking Finish the MQL5 Wizard creates for us the basic body
required for the development of any investment robot. Therefore, we
already have a divided structure with the main methods for the
operation of an EA.
The structure of an EA, for its proper functioning, will always contain
at least these three functions or methods: OnInit (), OnDeinit () and
OnTick ().
4.3. OnInit()
4.6.1.Comments
This type of structure (//) causes the compiler not to interpret the
characters they saw immediately. So we can make small reminders
and explanatory comments to make the code clear and readable for
editing by other developers and even us.
The second type of comment / * * / allows you to write entire
paragraphs between them.
We have some shortcuts to the comments. For example, if we want to
comment several lines we can make the selection of them and press
(Ctrl + ~). To remove the comments, simply select and press (Ctrl +
Ç).
The shortcut (Ctrl +.) Lets you create the following annotated string.
This is useful for separating large sections of code.
The shortcut (Ctrl +;) lets you create a small separation with the
following strings:
4.7. EA Properties
We note that in the Toolbox field on the Errors tab the compiler did
not raise any problems.
So automatically in the MetaTrader Platform in the field Navigator ->
clicking on the more of Expert consultant we can find our EA
compiled (.exe5). You can now click, hold and drag to the candle
chart and observe the #property information present.
The file type generated with MetaEditor has the extension '.mql'. We
can verify this in the MetaEditor Navigator field where we have our
robot edition file called EA_MA_Cros_RSI.mql5.
After clicking on the button Compile a file with the extension
'EA_MA_Cros_RSI.exe5' is automatically created in the field
Navigator -> Expert Advisor of MetaTrader.
It is important to note the difference between MetaTrader and
MetaEditor. In MetaEditor we have files with extension '.mql5' and in
MetaTrader we have '.exe5' files.
4.9. Adding Libraries
We can add special libraries provided by MQL5. For this we just need
to know the name of the library with the following code structure:
Every MQL5 variable must have a type and a name. The type of this
variable must always be specified before the name. Then we can
assign values corresponding to the variable type. Let's study the most
used and that will be part of the structure of our EA.
5.2.1.Integer Type
char - uses only 1 byte of memory. You can allow values in the range
of -128 to 127.
short - uses 2 bytes of memory. Can support values in the range of
-32,768 to 32,767.
int - uses 4 bytes of memory. You can allow values in the range of
-2,147,48,648 through 2,147,483,647.
uchar - uses 1 byte of memory. The range of values is 0 to 255.
ushort - uses 2 bytes of memory. The range of values is 0 to 65,535.
uint - uses 4 bytes of memory. The range of values is 0 to
4,294,967,295.
5.2.2.Type Double
5.2.3.Type String
Textual character variables are typed with string. The MQL5 language
allows string concatenation in a very simplified way as shown below.
5.2.4.Type bool
It should be noted that in the case the variable 'bool response' was
declared without initial value, so the value of (false) is immediately
assigned. Only then, see figure above, that we have a value change
to true, because x is less than y.
5.2.5.Type Datetime
This is one of the most widely used types, since asset price data are
collected over some time scale. We will always be able to make
evaluations of times and days for operations. Therefore, we should be
well aware of the use of this type of variable.
The date and time format for MQL5 is defined as follows:
{D'yyyy.mm.dd hh: mm: ss'} ie {year.mon.day hours: minutes:
seconds}
The capitalized D letter placed at the beginning of the date causes the
variable to have the datetime constant.
5.3. Declaring Constants
We will often use variable arrays to store mainly financial asset price
information and indicator variables.
Here is an example of a three-position array declaration for storing
integer numbers:
If we try to do:
When we press Tab, the editor will autocomplete the whole structure
of the for loop.
This structure means that we will iterate from the integer 0 (zero) to
the integer (total-1) with an iteration increment ‘i’ of a unit (i ++ is the
same as i = i + 1, as well as i-- is the same as i = i-1).
So if we want to make a scan inside the elements of an array we can
do from the for loop as follows:
5.6. Enum
Another Tab, we have autocomplete. Our enum should look like this:
Input variables are the only ones that allow the user of the indicators
or EA to assign values to them. These variables are used to provide
the user with the possibility of changing the setups of the indicators,
stop loss, take profit, number of lots etc.
Input variables can be of any type including enum types. Let's take an
example to make it easier to understand.
5.8.1.Local variables
5.8.2.Global Variables
See the use of the if conditional plus the logical connectives &&
(AND) and || (OR):
Let's now go to the conditional structure of the else type. The else is
activated if the ‘if’ conditional is not true. Therefore, if the ‘if’ is false
automatically the else becomes true and everything inside the keys of
this structure is executed.
The else if structure is very useful in many cases. When the chain of
conditions is extensive we can use this structure. If no else if is true,
else executes automatically.
5.12. Ternary Operator
The MQL5 language has a set of libraries prepared to work with the
acquisition and manipulation of candle prices. We have the
MqlRates structure that stores the price information of opening,
closing, maximum, minimum, volume, spread and time.
Tick information refers to those collected from the book of offers such
as ask (bid), bid (sale), last business etc. This information can be
accessed from the MqlTick structure.
Let's see how to declare a candle variable and tick. We must beware,
because we must first declare the variable after doing the proper
loading of the data in the variable declared from other specific
functions.
In order to load, we must specify the financial asset (which can be the
current one of the graph using _Symbol) and the period of the
candles (to use the current chart we put _Period).
For an example, we will create a new Expert Advisor with the name of
Study_Var (study of variables). In the wizard now we will add the
OnTimer option.
We decided to add the OnTimer() function, because with it we can
work and view our debug codes outside the trading hours. As we saw
in Chapter 4, the OnTick() function is called every time a new trading
operation is performed, and as we are probably making the codes
outside trading hours no call to this function will be made.
So we'll use the OnTimer() function to make timed calls and be able
to see the development of our codes. Let's ask it to be called every 2
seconds from the EventSetTimer(2) function (see example below).
We are taking the prices of the candle in position '0', that is, collecting
the values of the most current candle. The candle can represent any
time chart, what really matters is your position. We can choose any
desired position, all we need is to understand the ordering of the
vector. Below is an illustration to facilitate this understanding (it is
worth noting that this illustration is valid only after using the
ArraySetAsSeries() that orders the vector as shown).
Our candle vector has only 10 positions, because we use the function
CopyRates(_Symbo, _Period, 0,10, candles).
We can make our code more easily able to choose the position of the
candles and, in addition, add tick information, see below:
Let's now test the case of the variable (pos = 10). We chose for
candles a vector with only 10 price positions, but we are trying to
access the position of number 11 (remembering that the count starts
with zero). So the code will compile normally, however when
executed in MetaTrader we will get the following error message:
We have an array out of range error. MetaTrader also informs the line
of code in the .mql file where we find the violation (line 59). We must
be alert because this type of error is quite frequent in our robot
creations. So be very careful with the sizes and tracking positions of
the arrays.
5.15. Functions Comment () and Alert ()
5.15.2. Alert()
The Alert() function displays an alert box in the center of the screen
with the requested information. Those who are interested can search
for audible alerts, because it is also possible to add them to our EAs.
5.16. Adding MQL5 Indicators
Let us now turn to one of the most common and important practices
when the goal is to plan an investment strategy. It is very likely that
your investment strategy will make use of some indicator, so let's
learn how to call indicators from the MQL5 language.
Initially, we need to declare the variables for our indicator. How we will
declare variables will depend greatly on the type and functioning of
the indicator.
There are indicators that provide only one output of information, such
as a moving average. From the moving average we have only one
output of information which is the value of the moving average
calculated for a specific point in the graph. In this case we say that
the moving average has only one memory buffer. Every indicator
needs at least one Handle and it must be an integer type.
Now let's add the RSI oscillator indicator. This indicator also has only
a single Buffer. If you are in doubt regarding the number of buffers of
each indicator simply go to the documentation from the F1 key and
look for #property indicator_buffers:
It follows the code with the addition of the two indicators (moving
average and RSI). Note that the (iRSI ()) function of the RSI indicator
has input parameters that are very different from the iMA () function:
Finally, we are fully equipped with the minimum information necessary
to start programming our investment robot. Let's go to the next
chapter!
Chapter 6
6. Programming the EA
Our EA will have two moving averages and the RSI indicator. The
crossing of two Moving Averages works well when the market is in a
trend. On the other hand, in parallel markets or in consolidation, the
RSI indicator performs better.
There are several indicators that offer indicative when the market is in
trend as the ADX indicator. We decided to choose the RSI for reasons
of making an alternative between the possibility of choosing the
market in the trend and/or lateralized market.
For the buy or sell operations, our EA will have the possibility to
choose only one of the indicators (crossing of averages or RSI) or
both at the same time. Thus, we will have an EA that will track the
input triggers based on two indicators: moving averages and RSI.
Let us understand how the input triggers in operations will be given
for each of these indicators.
6.1.1.Moving Averages
Let us, therefore, to a summary of the strategy with the elements that
we will need to program for our EA:
1 - We must add two moving averages (fast and slow) both with the
possibility of choosing the period, the average application price and
the average method used.
3 - The user can choose among the options to enter the traders if they
come from the moving averages plus the RSI, only moving averages
or only the RSI.
Now that we know the operation to buy and sell for our two indicators
(crossing of averages and RSI) we are ready to start developing the
algorithm with the presented strategy.
6.2. Creating EA
Let's open MetaEditor and ask the wizard to create a new Expert
Advisor. Let's give it the following name: MM_CROS_RSI.mql5.
If you want to obtain the complete source code of the robot you can
access the following page in github https://github.com/rafaelfvcs or
send an email to [email protected]. However, it is strongly
recommended that you enter the codes presented to gradually
memorize the use of MetaEditor functions and features.
Here we have the skeleton of our EA:
6.3. Declaration of Global Variables
6.3.2.Global Variables
We must now declare the global variables that will be used by the
functions of our algorithm. See below:
6.4. OnInit () Function
Let's create some useful and important functions for the operation of
our EA. We can use the shortcut (Ctrl +.) To create sections for a set
of functions that we will create for our EA.
From these structures we can delimit the type of order that we are
interested in, specifying details of it. The request and response
variables must be used in an order send function called OrderSend().
Below is a function created to send an order to buy to market with
type of fill FOK (fill or kill - or fills the lot size of the order or does not
execute). This order, executed to market, already enters with the stop
loss and target of gains (take profit) defined.
In every market there are offers from the best buyers and best sellers.
Therefore, we need to access the book of offers to know these prices.
As we have seen, in Chapter 5, we can access book information from
the MqlTick structure. So we created a variable called 'tick' to store
this information. With it we can access the best seller 'tick.bid' and the
best buyer 'tick.ask'.
We have the bid = (sell, offer) and ask = (buy, demand).
The goal now is to create the whole strategy logic for our EA. We
already have the necessary functions ready for its operation. It is
within the OnTick() function, called each new business carried out on
the stock exchange, that we will write the strategic body.
First, we must feed our candle, tick, and indicator variables with data.
Also, let's not forget to sort them appropriately with the
ArraySetAsSeries() function:
After this we can make use of these variables to build the logic of the
buy and sell action of our EA. Follow the conditions of crossings:
In the MQL5 language it is:
With these features we will be able to choose the financial asset for
the backtest:
The graphical time:
We have the option to choose how the formation of our candles are
simulated by MetaTrader.
After setting the parameters correctly for the backtest, simply go back
to the Settings tab and hit the Start button.
7.2. Analyzing the Backtest
As soon as you press the Start button, the following window appears:
During the backtest or after the end we can follow the evolution of our
capital in the Graph tab that appears in the Strategy Tester.
However, after the end of the backtest, a new tab called Backtest
appears. This tab provides a summary of the operational statistics of
our strategy. In it we can see the profit Factor of the operation (ratio
between gross profit and gross loss), recovery factor, drawdown or
retraction, total trading, number of short positions and bought with
gains and losses, sharp index among others.
We can visualize bar charts informing about the schedules, the days
of the week and the month where we have more entries in the
traders.
You can track the frequency of profits and losses: by EA operating
hours, days of the week, and months of the year. We also have
information regarding the maximum time set and the minimum
duration of a position.
However, as we can see, MetaTrader 5 gives us a very thorough
review of our backtest.
--==*__*==--
Congratulations on getting here!! Thank you for your confidence in
reading this e-book. Sorry for the problems with the translation. Feel
free to submit suggestions, criticisms and errors in the texts and
subjects covered in the e-book.
Now that you've been able to create your first EA and make the
backtests, it means you have a new journey of study towards more
sophisticated strategies. It is worth remembering that the EA taught in
this book is purely demonstrative and offers no means to use as a
suggestion of real investments.
If you want to know other books, with similar didactics, it is worth
checking the following:
How to create indicators and scripts in MQL5 (step by step).
How to Properly Optimize Investment Robots in MetaTrader 5
[1] Obs: The information contained in this e-book does not represent or offer
any suggestion and / or expectation of investment.
[2] https://en.wikipedia.org/wiki/Bill_Williams_(trader)