MetaTrader5 & MQL5 Community
Introduction
Digital Age
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.
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.
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.
Computer Programming
Most people have the following objections when it comes to programming: it's very difficult, needs a lot of practice, has to know a lot of math, I've never been good with numbers. However, many of these objections are nothing more than a misunderstanding of this programming activity, which is as trivial as telling a brief story with beginning middle and end.
The interesting thing is that anyone able to write the steps of running a cake recipe on a sheet of paper is able to create a computer program. To program is to communicate with the outside, with the other, in order to conduct actions. For our case, this other is the machine.
We have a structure of activities to be followed and we need, for a good realization of it, an adequate sequence of order of execution. Programming is to master a language the machine understands and know how to position our deliberative needs in time and space, so that they are executed correctly.
Therefore, it is up to every curious investor and with the patience to learn something new to look at in the world of programming. This is because scheduling computers is a much simpler activity than many imagine.
What will we learn?
In this e-book we will learn how to create, step by step, an automated investment strategy. We will create an Investment Robot (Expert Advisor - EA) from scratch using the MetaTrader 5 and MQL5 programming language.
Thus, having a program written in a high-level language (MQL5) (those closest to the understanding of humans, low-level languages are closer to the understanding of machines) we will be able to leave the arduous and exhausting work of monitoring purchase and sale of a financial asset on the stock exchange for the robot.
We will spend a few hours to program a robot known as Expert Advisor and spend the rest of the time monitoring the execution of the strategy in a much quieter and safer way. That leaves more time for a contemplative and pleasurable life.
Why MetaTrader 5?
MetaTrader 5 is a powerful platform for visualizing, operating and scheduling investment strategies for various types of financial markets.
It was created in the year 2005 and continues to be improved and distributed by MetaQuotes (https://www.metaquotes.net). We can use MetaTrader 5 to operate in the stock markets, futures, options, currency pairs (FOREX) among others.
MetaTrader 5 was chosen to build our first EA, as it is a 'free' tool, quite powerful and complete from the point of view of the main functionalities that a trader platform should have.
Inside MetaTrader 5 we have the option to create scripts, indicators and, of course, investment robots using the MQL5 programming language. This language is very similar to C ++, Java and C #. So anyone who already knows any of them will feel extremely comfortable learning MQL5.
EA Strategy
We will develop from scratch a strategy of crossing two moving averages (one fast and one slow) with the possibility of an input filter in operations with the rather popular indicator RSI (relative strength index).
Our robot will be multi-strategy. It will be able to work, using as input triggers in the operations, only the crossing of the moving averages, only the RSI or both (crossing of averages plus RSI).
We will also learn how to make backtests of the created robot. Thus we will be able to test various setups on historical data of various financial assets. The book is full of guidelines, with screenshots, using the key parts of MetaTrader 5 and MetaEditor.
We will learn the programming syntax in MetaEditor. We have several features when programming with MQL5. It already presents a very significant set of libraries to work with graphical manipulation, mathematical operations, statistics, with price structures and control of the sending of trading orders.
Advantages of Using EA
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.
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.
Now we are moving towards the future of investments. Congratulations on your decision to enter this grand and fascinating world of automated investments.
MetaTrader 5
MetaTrader is a platform developed to assist in the visualization of prices of financial assets and execution of buy and sell orders on the stock exchange. It is also possible to create scripts (algorithms for specific actions), indicators and investment robots.
It is a free tool developed and distributed by MetaQuotes Softwares (https://www.metaquotes.net/). Initially, it was developed thinking about the Forex market. However, several brokerages have been allowing for the use in the stock market, options and futures.
We need a company (investment broker) to provide routing pricing data for the platform. Many investment brokers offer this service for free. Some even offer a demo account where we can simulate buy and sell operations in the financial market with dummy money. Also, in the demo account, we can put our robots to test in real time before using them in a real account.
MetaTrader 4 was created in 2005 and since then has been undergoing major transformation of improvements in its system and security features. It is currently in its second major release called MetaTrader 5 which was released in 2010.
We can use MetaTrader on both desktop and smartphones. It is available to work on the Web, on Mac, Linux, Windows and Android systems. The leading Internet browsers on the market support MetaTrader 5 online.
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).
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)
.
Main elements of the MetaTrader 5
One of our main interests is to visualize asset prices from candles (candlesticks). So, let's get to know the main visualization features of the MetaTrader 5 platform.
In the menu: View -> Symbols, we have the option to choose the financial assets that we wish to work.
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 addition of a symbol that represents a company, which is being consulted in the prices, can be executed in the Market Watch.
In this Market Observation field we can add the assets related to the companies traded on the stock exchange in which the brokerage firm is released to operate.
Still within the Market Watch field we have the Details tab that offers additional information regarding the financial asset being evaluated. Below, for example, we can see the information on this tab for Petrobras shares. In the Trading tab we have several options where we can make purchases and sales with just one click.
Navigator Field
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 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.
Field Toolbox
In the Toolbox field we can find several importants informations regarding the sale of the main indicators and investment robots developed for MetaTrader platform. We can also download those provided for free (tab Libraries). We can view the main news (tab News) in real time of trading as market in auction and output of news relevant to the market.
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.
Looking for Candels
The MetaTrader 5 platform allows us to customize the way we visualize prices in different ways. For example, we can change the background of the screen, the colors of the contours and fill of the high/low/doji candles, the separation lines of periods, grids, among several other properties.
We can switch between three types of price visualization of financial assets. These visual types are given through Bar Chart, Candlestick or Line Chart.0
Saving Templates
It is important to note that each time a new chart is requested to be opened in MetaTrader it will appear on the screen with the default settings. However, there is a way to save our screen preview customization from creating a template.
For example, let's set up a template. For this we must make our customizations. With a right click on the graphic field we can choose Properties and make the appropriate color settings to our liking.
Let's consider the following changes:
Then right click on the graphic screen and go to Template -> Save Templates. We chose a name and that's it.
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.
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.
Transition between Graph Times
The transition between the graphical scales of candle formation observation is quite simple and fast. Just right click on top of the chart, go to Timeframes and choose the time of candles.
We can also change the candle time from the shortcut bar, as shown below:
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:
The result is:
The RSI is an indicator used to warn about overbought and/or oversold. Basically, we have two reference levels that we must choose for the activation trigger of the overbought or oversold. We can choose the levels of 30 (oversold) and 70 (overbought).
For example, RSI values above 70 are indicating that the price is overbought, that is, at any moment in a consolidated market, we can begin to see a drop in prices. On the other hand, if the value of the IFR is below 30 we can say that the price is oversold and a sudden high in prices is eminent.
These two indicators were presented, since they will be used to create our investment robot. Going forward, we will use three strategies: one with the crossing of moving averages, another with only the RSI and one with both indicators.
Data Window
A very important field, which greatly facilitates the visualization of prices and values of indicators, is the Data Window.
To open it we can: go to the View menu -> Data Window or use the keyboard shortcut Ctrl + D.
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:
MQL5 Community
As discussed earlier, MQL5 is a programming language offered within MetaTrader 5. Programmers often share codes and questions around specific problems in a programming language.
It is very important to participate in communities of developers, because with this our learning and the motivational side are enhanced. The sharing of knowledge and doubts generates sustainability in our development and growth as a programmer and user of the language.
It is always good to have a place to exchange knowledge, ask questions and discuss project ideas. The more widely used and documented a programming language, the better the learning curve for first-time sailors. Therefore, a common environment where all are destined to the same end is quite valid.
In this sense, for the MQL5 language we are well covered, because we are facing a mature tool, with a lot of developers and a very active and generous community that offers articles and doubts with agility in the forums.
We can access the community from the site: https://www.mql5.com/en.
After reading this e-book and/or even now, the reader is invited to make an account and start adding their knowledge and ask questions from the portal.
Soon after the registration we will have access to a very interesting set of functionalities. For example, we can access the MetaTrader 5 web terminal, documentation that is extensive and up-to-date, key information on the global financial market, and other benefits.
Something very important for anyone who is starting with the MQL5 language are the open source code samples available in CodeBase. In this location we will have access to codes for both the MQL4 and MQL5 languages. It is extremely valuable to spend time researching and studying these codes.
We also have the section of Articles where tutorials with excellent didactics are added. This is one of the indispensable fields for anyone with the pretense of mastering the MQL5 language.
Anyone who wants to build an EA with a more robust and complex strategy can hire MQL5 programmers from orders on the Freelance portal. Also, for those who have begun to master the tool and want extra income, they can accept projects and offer their robot production services, indicators and investment scripts.
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.
Sumber : Rafael F. V. C. Santos
