Introduction To MetaTrader 5 and Programming With MQL5 (Rafael - F. - v. - C. - Santos)
Introduction To MetaTrader 5 and Programming With MQL5 (Rafael - F. - v. - C. - Santos)
MQL5
Create your 1st Investment Robot with MQL5 step by step from
ZERO.
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.
We are living in the digital age. Nowadays, information and knowledge travel
through the optical fibers. Everything is in constant development and
accelerated growth. This evolutionary dynamic is unprecedented in the
history of mankind.
Devices and objects are becoming increasingly intelligent and independent.
Nowadays, it is possible to find, for sale, smart phones and watches that
recharge the battery with even the temperature of the human body. Research
shows that by 2025, at least half of the US fleet will be traveling completely
autonomously. That's right, the profession of driver, taxi driver and many
others, are counting their days. And for the financial market this is no
different. Professional traders are being replaced by algorithms.
These are just small examples of the avalanche of modifications and benefits
brought in from the world shouting for change. We are changing the world
and the world forcing us to change into a virtuous circle of prosperity.
1.2. Artificial Intelligence
Embedded systems are gradually dominating our daily lives. People and
things are becoming more and more connected to the internet. A new
intelligence is created from this new cosmos. We are opening the doors to
Artificial Intelligence (AI). Practically everyone benefits (or will benefit) in
some way from the wonders brought by AI.
Many say that this new generation may bring us problems, but we must be
optimistic about the uncertainties, as we are on the way to an inevitable and
non-return path.
Several companies and investment funds are currently working heavily on the
use of artificial intelligence to make their investment decisions. From AI, we
can filter and group information and knowledge hidden in apparently
meaningless numeric data and connection.
In this race, it is advantageous to dominate subjects and knowledge related to
mathematics, statistics and computer programming.
1.3. High Frequency Trading - HFT
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
Let's go to the advantages behind using investment robots. They are many,
but we go to the main ones:
- Eliminates all emotional side;
- Test ready strategies with backtests;
- Simulate adverse market situations;
- EA are free from fatigue, stress, lose attention, or fail to execute the
strategy;
- We can optimize the strategy from a Robot;
- EA are infinitely disciplined and speedy compared to us;
- Statistical validations can be made. EA statistically validated are
winners and consistent in the medium and long term.
- EA has a single mindset that is to execute the scheduled strategy;
- EA operate from the first second of market opening to the last second
before closing, without truce and misconduct.
1.9. E-book Summary
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.
MetaTrader 5 is not only a tool for visualizing and routing orders (buy/sell)
of financial assets, but also an excellent platform for developing investment
strategies from scripts, indicators and robots (Expert Advisors). For this it
counts on the environment of development for the language MQL5
(MetaQuotes Language) that presents/displays great similarities with C ++,
Java and C #. Therefore, those who have had some knowledge in any of these
programming languages will feel comfortable with the MQL5 syntax.
In comparison to MetaTrader 4, MetaTrader 5 allows developing strategies
using the object-oriented programming paradigm (OOP).
2.1. Downloading and installing MetaTrader 5
In the world several brokerages offer free use of MetaTrader 5. All we need
is that we are a client of the investment broker. We need, after downloading
the platform, to request a release of a demo and / or real account so that we
can have access to the routing of the data of the financial assets.
The direct download of the platform can be done by the site:
https://www.metaquotes.net/en/metatrader5/.
As said before, several brokers around the world offer free routing, but many
for the Forex market. Some Forex brokers only need a valid phone number to
release a demo account. In this e-book we will use the systems with the prices
of financial assets present in the São Paulo (Brazil) BM&FBovespa stock
exchange.
However, to follow the studies in the book, you do not necessarily need to
have an account with a Brazilian investment broker.
The installation process is very simple and straightforward. After two clicks
on the file an installation wizard will guide us with the necessary steps.
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
We can choose between Bovespa and BMF Assets (continuous series). In the
assets of Bovespa we have the OPTIONS (calls and puts), the shares in A
VISTA and the INDICES (futures market) traded in the Brazilian market.
It is important to note that each brokerage will provide distinct data routing.
Some with more data and some with less. For example, if we were with some
brokerage that works with the Forex market, the options that would appear in
this window of Assets would be completely different.
The field Navigator is where it contains the information regarding the type
of account of the user if demo or real, as well as the indicators and robots of
investments available by the platform and those that were developed by
ourselves.
In this field, we can choose the type of indicator, script or EA and drag it
directly to the financial asset chart of interest.
Another way to add indicators or EA is from the menu Insert -> Indicators,
Insert -> Expert (Robots).
Let's add an indicator from the menu:
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
In the field Market we can buy indicators and EA offered by individuals and
specialized companies.
We have a very interesting field that is Investment Signals. Through it we
can follow the entry and exit of trader operations. We have the evolution of
yields, the level of reliability, maximum profit, among other information, for
each one of the traders who were willing to provide the signals of their
operations. Some signal services can be contracted (paid for) and automatic
execution can be synchronized with our accounts.
After finding a strategy and consistent setups and prove validity through
testing the demo account, an important step is to hire a virtual machine
service. This type of service will leave us more secure and protected with
regard to lack of energy and internet.
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()
One of the most important is the OnTick() function because it is where a lot
of our programming logic is running. This function is one of the most
requested by our robot, since it is called every time a market operation
happens. At each new sell, buy, release and order cancellation this function is
called.
It is worth mentioning that this function is only called when we have EA
within trading hours. That's because only with the trading in progress is that
we have changes in the market.
If we are working on the development of a robot and we are not in the trading
hours we will not see any call of this function. Alternatively, we can use the
OnTimer() function to minimize these problems and to make tests and
debugs through it (using the Print() function). Later in Chapter 5 we will see
an example of using the OnTimer() function.
It is worth highlighting that there are several other predefined functions like
OnChartEvent(), OnTrader(), OnTester(), and others. However, we will only
study the main ones. Further details regarding these other functions can be
found in the MetaTrader 5 documentation.
4.6. Programming Accessories
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.
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:
The above example adds a set of classes and methods ready to generate
Fibonacci figures in the first include <ChartObjects/ChartObjectsFibo.mqh>,
and work with sending and managing sales orders in the second include
<Trade/Trade.mqh>.
Note that the extension of these include files is of type '.mqh'. MetaEditor
also allows you to create this type of file. From this we can create complex
algorithms that work with the graphic part and even visual animations.
We can research and study the main MQL5 libraries from the site:
In Chapter 5 we will know and study better MetaEditor functionality from the
study of the MQL5 syntax.
Chapter 5
5. Basic Programming Logic with MQL5
As mentioned before, the MQL5 language has great similarities with the C
++, Java, and C # languages. Therefore, anyone who has any knowledge of
these languages will have great ease in understanding the MQL5 operating
syntax.
Every algorithm, every recipe for cake, begins with the description of the
ingredients. So let's make an analogy and start studying the ingredients of our
EA, our cake.
Let's first understand the main types of variables present in MQL5. We also
need to know how this language declares and assigns values to variables.
5.1. Types of Variables
The variable is the basic unit of data storage in any programming language.
Almost every algorithm needs variables. In MQL5 we need to declare a
variable always with some type.
The main types of variables used to create robots are: Integer (int), floating
point - decimal values (float and double), alphanumeric characters (string),
logical (bool) and dates (datetime).
Unlike MQL5 there are some languages that have automatic typing with, for
example, Python.
Having to explicitly declare the variable type has practical security
advantages and makes it easy to find compilation errors. When we are
limiting the type of the variable, we protect it from possible arithmetic errors,
assignment errors, and programming logic errors.
5.2. Declaration of Variables
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
When we are interested in storing variables with decimal numbers the most
appropriate is to use the double type. The double type consumes 8 bytes of
memory. More economical, we have the float type that consumes half, 4
bytes.
The main difference between these two types (float and double) is that the
accuracy of significant digits is larger for the double type (15 significant
digits) while the float has only 7 significant digits. As the difference in
memory consumption for our robots will be irrelevant we will use only the
double type that is more accurate.
For example, the division, in the figure below, does not involve many
numeric digits. Therefore, the double or float type makes no difference. On
the other hand, if we had a problem where the result was some periodic
tithing multiplied by some number or other decimal, cumulative rounding
errors could interfere with the accuracy of the results.
To the present moment do not worry about not observing the results of
operations. We will do this later with the use of the Print() function. For the
time being, let's take a look at the structure of the statement of variables.
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
When the interest is to have a variable with boolean characteristics, that is,
that only allow true values (true) or false (false) we can use the 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
Of course, the values of the constants can not be changed. If there is any
attempt to change the value, we will have a compilation error.
It is standard to consider the names of constants with upper-case characters.
5.4. Vector Variables: Arrays
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:
We will now study a very important repetition loop used in the development
of investment robots. When we want the computer to perform repetitive
activities within certain predetermined limits, a practical way of informing
the machine is through the for loop.
When we type the word for in MetaEditor we will have a small set as shown
below:
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
The enum structure is a special type of integer where we can define, through
a list, assignment constants. With enum we can customize the types of
variables that best suit our problem.
For example, let's create an enum to represent the seasons of the year. We
know that there are only 4 seasons of the year: spring, summer, autumn and
winter.
When you type the word enum we have a small arrow pointing to the right,
as shown below:
Another Tab, we have autocomplete. Our enum should look like this:
The value of output was 1 (one) because enum considers the ordering of
integers from zero. In our case we have spring (0), summer (1), fall (2),
winter (3). Interesting and quite useful the enum, right?
5.7. Input Type Variables
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.
After compiling the above code we will have in MetaTrader the following
possibility of setting the EA:
Therefore, the input directive allows us to dialogue with the user on the
Input tab of our EA.
5.8. Local and Global Variables
5.8.1.Local variables
5.8.2.Global Variables
The MQL5 language has several predefined routinely used variables for
strategy development. These variables have their own notation and are
preceded by an underscore (_).
The main variables most used and that we will apply to create our first EA
are:
_Symbol: represents the financial asset symbol present on the current chart
shown on the screen.
_Period: refers to the period, in minutes, of the current candle chart.
_Point: represents the size of points that characterize the financial asset.
_Digits: represents the number of decimal point digits of the current asset.
The use of these variables will become clearer when we are developing our
EA.
5.10. Math Operations
The language itself already comes with a set of mathematical and statistical
functions to work connected with the most diverse operations. We have the
functions with radical MathXXX quite useful:
5.11. Logical and Conditional Relationships
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
In the place where we use the conditional variable we could do any structure
using the logical evaluators (> =, <=, &&, ||).
5.13. Methods or Functions
In a function we can have several types of returns and input parameters. The
processing performed depends on the logic of the problem.
Let's take another example where we have functions used to calculate the
sum, multiplication, and division of two numbers:
Functions that do not return values have a void type declaration. However, if
the function has some kind of return we are required to return something
relative to the return type.
5.14. Candles and Tick Variables
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 ()
By using some useful functions we can create warning elements and alerts to
provide greater security of use and better understanding of what is happening
with our EAs.
5.15.1. Comment()
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
First we go to the trigger for the crossing of moving averages. We have two
moving averages and the type, whether exponential or arithmetic, of these
averages can be changed as we will see next.
One of the moving averages will be called the fast average and the other
slow average. The fast average is the one that has the shortest period, on the
other hand the slow average should always have the longest period.
We give these names to averages because fast averages are those with a
shorter period of time and are more adherent to price, so they move faster
than those of longer periods where they have slower directional behavior.
Let's look at an illustrative diagram of how these triggers work in trading:
6.1.2.Relative Strength Index (RSI)
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.
2 - We must add the RSI indicator with possibility of period choice, applied
price, and oversold and oversold levels.
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
Let's start by declaring our global variables. We will separate those variables
that the user will have access to modify and those that will be used for the
structure of the EA algorithm.
We will provide the following options (input parameters): profit targets, stop
loss, number of traded lots, chart time, average periods, RSI period,
application of methods in prices (opening, closing, max, min) for both the
averages and the RSI, possibility of choice in the strategy of entry triggers in
operations (Moving averages plus RSI, only crosses, RSI only) and time limit
to close the open operations.
Below is the code of all this:
For the 'strategy' variable it was chosen to create an enum (this should be
declared at the top of the algorithm above the Input 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.
First, we will need a function that informs the appearance of a new candle
regardless of the graphical time. Still, we do not have a native function in
MQL5 that allows us to accurately assess changing candle and so we must
create it.
The function should return true if a new candle appears on the chart. Here is
the code used in the tutorials in the MetaTrader article portal:
Let's do a function to help you visualize the entry points of our strategies.
This function basically will construct a graphical object (vertical line). Every
time our robot presents logical conditions (the trigger is activated) a vertical
line will be drawn on the graph with a name and color referring to the type of
warning.
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 type of action to be chosen is the first requisition that we should assign:
We have several types of orders. We can choose from the structure type:
The NormalizeDouble() function is used for rounding variables. We need to
use it because some financial assets have the number of different price digits
of others. We have assets that are quantified by points (as is the case of index
and dollar futures contracts), others are quantified by price and even pips
(Forex market). In Chapter 5 we discussed the use of _Point and _Digits.
The values of the SL and TK variables should be chosen by the user in the
form of points. Notice that for the stop loss price we did:
NormalizeDouble(tick.ask - SL * _Point, _Digits) as we are buying and our
stop loss point needs to be below the (ask). Already the target of the take
(take profit) naturally for a purchase should be above TK ask points.
It is with the request request.type_filling = ORDER_FILLING_FOK' that we
choose the order fulfillment type. We basically have three types of order
fulfillment:
Let's see the function to sell:
In this case, we have the stop loss level above the bid price
NormalizeDouble(tick.bid + SL * _Point, _Digits) and the gain target
naturally below NormalizeDouble (tick.bid - TK * _Point, _Digits).
We also need to create two functions to close open orders if arrive at the time
limit chosen by the user. That's because our robot is daytrader, we do not
want to sleep positioned. Remembering that to guarantee the closing of open
orders we have the variable 'Limit Closing Closing Position' chosen by the
user.
So to close a sale we must buy and to close a purchase we must sell.
It is always good to treat the returns of the orders sent. This is because we can
minimize problems and evaluate execution errors. In our functions we did
this from answer.retcode which returns a code (with 5 digits) coming from
the brokerage server. Below is a window showing details of these codes. You
can get to this window by pressing the F1 key on code number 10008 or
10009.
6.7. Function: OnTick()
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:
Our main interest with Expert Advisor (EA) is to have a winning strategy
over the long term. There is that famous phrase: that nobody in the financial
market has a crystal ball. It is no use trying to predict the future of the market,
because unfortunately, it is impossible until the present moment.
We need to be realistic to accept that our strategy will have ups and downs
regarding financial returns. The 100% winning strategy is a utopia. However,
it is important to know how good our strategy is. There is nothing better than
using past data to gauge how it performed under various market conditions.
So testing our strategy at past time periods is called a backtest.
Fortunately, when it comes to backtesting MetaTrader 5 provides a collection
of simple and useful features to extract as much information as possible from
the performance of our EA.
Now that we already have an EA (MM_CROS_RSI.exe5) multi-strategy
programmed and working properly, let's do the backtests.
7.1. Backtest in MetaTrader 5
Let's open MetaTrader and go to the field Navigator -> Expert Advisor
consultant and look for our newest EA. Once found we should right click on
it and then on Test.
This will give us a new field in MetaTrader called Strategy Tester, in the
settings tab we have the following panel of possibilities:
With these features we will be able to choose the financial asset for the
backtest:
We have the option to choose how the formation of our candles are
simulated by MetaTrader.
For this way of generating prices in candles, let’s go to the main options most
used:
Every tick or Every tick based on real ticks: MetaTrader tries to simulate
real price ticks in the formation of candles. This option leaves the backtest
more accurate, but requires more computational resources once inside a
candle the MetaTrader tries to reproduce the formation of real ticks. It is
worth noting that ticks are not real are just a simulation (a possible
representation of reality). This article clarifies the functioning of this
simulation:https://www.mql5.com/en/articles/75.
1 minute OHLC: In this type of candle formation MetaTrader generates only
4 price values: O - open, H - High, L - Low, C - Close. This option requires
much fewer computational resources compared to the tick option.
Open price only: This is the least costly option computationally, because it
only uses a price to represent a candle.
In our backtests we will always leave the option Forward marked No (see
the figure below). This option is useful when we are doing strategy
optimizations and want to use optimization methods such as Walk Forward
Analysis (WFA). This type of study is beyond the scope of this book. If you
want to know more about it, you can buy the other e-book (How to Properly
Optimize Investment Robots in MetaTrader 5[4]).
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:
Finally, the Operation tab shows the progress of each particular negotiation.
We have the information regarding the entry price, our available financial
margin and how the trade is progressing, whether with gain or loss.
7.3. Performance Charts
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
If you are interested in any of these books please contact me by e-
mail:[email protected]
This material was written thinking of you dear reader. It is good to remember
that we are all motivated by criticism or praise. If this book was helpful to
you in any way, whether or not you liked the didactics, please leave a
comment on the Amazon store. This kind of attitude is of extreme
importance so that future editions are even better.
[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)