phgnomo

image.png

A few days ago i wrote about how to create a trading strategy in a structured way.

My main idea of writing that article was to start creating a trading bot for Metatrader 5.

I have created some bots for Metatrader 4 on the past, but this year i started using MT5, so it's now time to learn to create my own bots on this platform.

What is MQL5

Quoting from the official site:

MetaQuotes Language 5 (MQL5) is a high-level language designed for developing technical indicators, trading robots and utility applications, which automate financial trading. MQL5 has been developed by MetaQuotes Software Corp. for their trading platform. The language syntax is very close to C++ enabling programmers to develop applications in the object-oriented programming (OOP) style.

While it's similar to MQL4, the big change is that now it is a object-oriented programming, wich make things a bit more challenging for me, since i have a very limited coding knowledge (Went to some basic coding class while on college).

So, i will start to learn how to do it trying to implement the strategy i created

The good part is that there is a lot of articles about the language, so i think i will be able to code my robot.

First things First: How to start to code

When you install Metatrader 5 terminal, it already comes with the MetaEditor, wich is the interface to code your program.

Captura de tela 20200306 22.42.43.png

Personally, i always liked this interface, because on the left you have quick access to all the programs, and below you have a list of the articles related to MQL5 coding

There is 3 kinds of program you can code:

  • Expert Advisors - Trading bots, that execute orders according to the algorithim.
  • Indicators - Graphic representation of any data you want
  • Scripts - A program that execute a set of operations only one time per execution

Once you click 'New' you are greeted with the MQL5 Wizard, where you can choose wich kind of program you want to create.

Captura de tela 20200306 23.03.43.png

Since i am building a trading robot, i am only interested in two options at the moment

1 - Expert Advisor (template)
Create a template of an Expert Advisor allowing to fully automate analytical and trading activity for effective trading on financial markets.

2 - Expert Advisor (generate)
Generate ready-made Expert Advisor based on the standard library by selecting trading signals, money management and trailing stop algorithms for it.

While number 2 seems interesting, because it says it will create a EA ready to go, none of the indicators i am going to use (HMA and Ichimoku clouds) is aviable, and it seems you can't use custom indicators, i will go with No 1, to start from scratch.

Defining Parameters

After defining what kind of program will be created (Expert Advisor), on the next window, you are asked to register some basic information, EA name, and Author.

Captura de tela 20200313 17.56.14.png

The most important part of this step is to the define the Parameters. They are the inputs that will be used by the EA, and defining the parameters on this step will help on the first template configuration.

Notice that these are variables that will be used on the robot that can be edited whe you attach the EA to a graph.

Data Types

As any program language, every variable must have a type, that defines what kind of information can be stored on that variable.

You can see here all the data types that the MQL5 language uses, but here is the most important ones we will be using to build this robot:

int

The main data type to store integers(no fractions) values that will be used on calculations.

The size of the int type is 4 bytes (32 bits). The minimal value is -2.147.483.648, the maximal one is 2.147.483.647.

bool

Intended to store the logical values of true or false, numeric representation of them is 1 or 0, respectively.

string

The string type is used for storing text strings.

This type is where we save any text, that won't be used in calculations.

double

This is the float-point type, where we can store fractional numbers

datetime

The datetime type is intended for storing the date and time as the number of seconds elapsed since January 01, 1970

enum

This data type allow us to create a list. Will be useful to make it easier to setup the parameters choices.

Defining the EA parameters

We need to determine what we want to control/change on our robot, and using the strategy we are building, we will set these parameters:

Indicators

int FastHMA = 12    // Fast Hull Moving Average period
int SlowHMA = 120   // Slow Hull Moving Average period

Allowed trade types

enum TradeDirection // Define wich directions the bot will be allowed to trade
{
    buy,
    sell,
    buy&sell,
}
bool AllowHedge = 1 // Define if the bot will be allowed to do hedge operations

Trade Size

double LotSize = 0.01   // Define the size of the lot

Stop Loss & Take Profit

enum SL             // Chooses what kind of StopLoss will be used
{
    fixed,
    Ichimoku,
    FastHMA
    SlowHMA
}
int FixedSL = 100   // If a fixed stop loss is used, define how many points it will be
int TP = 1000       // Set how many points the take profit will be set

And here is what it looks like after we ser the parameters:

Captura de tela 20200313 23.42.15.png

Event handlers

The MQL programming language have some predefined functions called event handlers, that are executed when some specifics actions happen on the terminal.

These functions are the main structure of the MQL programs, because it sets a "moment" when part of the program will be executed.

After defining the parameters on the MQL Wizard, the next window you recieve is this one:

Captura de tela 20200313 23.45.28.png

You can check what each of these handlers do and when they are activated here. It's important to notice that some handlers are only used on certain types of programs (for example, OnStart() is only used for scripts).

For now, we won't be using any other handler than the main ones needed to run the Expert Advisor:

OnInit()

Execute once when the EA is attached of an graph

OnDeinit()

Execute once when the EA is removed

OnTick()

Execute everytime a tick is recieved by the terminal

Template set

Then that's it. Finishing the wizard will create a template to build the trading robot, where you can add all the functions and calculations that you want. So, that was the easy part.

And here is the finished template:


//+------------------------------------------------------------------+
//|                                              HMA Trend Trade.mq5 |
//|                                          Copyright 2020, phgnomo |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, phgnomo"
#property link      "https://www.mql5.com"
#property version   "1.00"
//--- input parameters
input int      FastHMA=12;
input int      SlowHMA=120;
input bool     AllowHedge=true;
input double   LotSize=0.01;
input int      FixedSL=100;
input int      TP=1000;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
  }
//+------------------------------------------------------------------+


See you on the next part, where the fun part will begin.