Learning MQL5 - Building a trade robot from scratch #1

in Project HOPE5 years ago

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.

Sort:  

I'm a programmer and it's hard for me to understand your post, it's necessary to have a level of programming to be able to assimilate what you explain.

I imagine it's an excellent idea to program a kind of robot that does the task of trading for you. Especially when you are not near a computer.

Especially at times like these, that situation surprisingly affected all crypto coins and made the value of the BTC go down an awful lot.

Perhaps a robot that is constantly monitoring the events would have acted quickly, watching the trend and thus avoiding losing the money, investing or keeping the money in stable crypto such as USDT, TUSD, etc.

I wonder if these robots have the ability to have artificial intelligence or machine learning?

Thanks for sharing! :D

Metatrader programming language (MQL5) is based on C++ but aimed to build specific application to the trading terminal.

While learning C++ isn't a pre-requisite to learn MQL5, a basic understanding about programming logic is definetly needed.

The thing about trading robots is that they don't do any miracle, and they are as good as the trader using them.

To make a good use of one, the trader must understand how it works, and even when to turn it off.

I wonder if these robots have the ability to have artificial intelligence or machine learning?

It's a bit advanced to me, but i have seen some articles about these kinds of robots.

I will check more about MQL5 anytime soon :)

As a follower of @followforupvotes this post has been randomly selected and upvoted! Enjoy your upvote and have a great day!

Hi @phgnomo

image.png
Source
What will happen if we choose order 3 and 4 of 1?


Custom Indicator - You will create a indicator that draw what you want on the graph, but don't do the trades
Script - It's a program that run only one, and don't do trades.

ok, thank's to your respon.

Quite difficult topic. Resteemed already. Hopefully it will help you get some exposure.

Upvote on the way

Indeed. I started studying Metatrader programming again, so i thought, why not create a tutorial on the proccess, so i can learn better, and as colateral, maybe help other people that are looking to learn the same thing?

 5 years ago 

@tipu curate

Wow, very nice article! Awesome work man!

Thanks! there is more to come.

I am really looking forward to it! :-)

 5 years ago 

Greetings friend @phgnomo.

I hope you have made the right choice with this tool.
I wish you the best of luck in this new project that you are undertaking.

I really can not make a comment more related to the topic because I do not feel in the domain of the necessary knowledge.

Thanks for posting to Project Hope.

Your friend, Juan.

Metatrader is a really powerful platform for traders, and the ability to build your own robot or indicator, no matter how complex it is, it is really awesome.

This post was upvoted by SteeveBot!

SteeveBot regularly upvotes stories that are appreciated by the community around Steeve, an AI-powered Steem interface.

Awesome job and a great idea. Your publication is very educational and I appreciate the contribution, your idea of the robot is magnificent, I am already eager to see what the result is when you have it ready. I hope it can be used as an app for Android phones.
Great work, I congratulate you and I will consider this article for my selection of the best community posts 👍

Metatrader have a mobile version, but unfortunately, you can't add robots or custom indicators to it.

The programs can only run on desktop version o Metatrader.

This is such an intelligent job buddy, I wish you all the best.

Creating a trade robot on your own, you must be a genius bro, nice job. Reesteemed