preview
From Novice to Expert: The Essential Journey Through MQL5 Trading

From Novice to Expert: The Essential Journey Through MQL5 Trading

MetaTrader 5Tester | 30 July 2024, 14:56
1 355 0
Clemence Benjamin
Clemence Benjamin

Key Sections:

  1. Introduction: A Brief Walk Through My Journey to MQL5
  2. Uncovering the Secrets to a Thriving MQL5 Trader
  3. Implementation of Artificial Intelligence in Algorithm Development
  4. Conclusion

 

Introduction: A Brief Walk Through My Journey to MQL5

When I joined the MQL5 community in 2019, I was a beginner with only manual trading skills on my phone and limited knowledge of algorithmic trading, despite a solid Computer Science background. I wish I had grasped the concepts of algorithmic trading earlier. Initially, I dismissed it and continued manual trading. However, three years later, while working as an electronic technician, I sought to continue trading despite my demanding job. This desire prompted me to learn about algorithmic trading to develop systems that would automate my trading or at least provide actionable signals.

Returning to the MQL5 community felt like finding a home of possibilities. The articles I encountered motivated me to read more, each enriched with valuable skills. Many articles guide readers through algorithm projects, evolving from basic to complex stages. Over the past two years, I have sharpened my MQL5 skills through various custom projects. Learning has become faster with the rapid improvement of technology and resources. I recommend reading this article thoroughly to avoid missing any crucial information.

 

Who Is This Article For?

  1. Absolute beginners to get started.
  2. Medium and advanced developers to unlock new potentials.

I will guide you through the creation of a working program customized to your needs and inspire you to get started. The goal of this article is to make the MQL5 community user-friendly by simplifying algorithm development with emerging technologies.

The algorithmic trading environment has become much friendlier compared to a few years ago, thanks to accessible educational resources. Here are some questions that guided my focus, and I hope they inspire you too:

  • How can beginners efficiently learn and master the basics of MQL5?
  • What resources are available for MQL5 learners to quickly overcome specific coding challenges?
  • How can traders invent new strategies, optimize, and automate using MQL5?

I will discuss three areas to kickstart your MQL5 journey as an absolute beginner or to advance your skills as a senior developer. One piece of advice I want to give you is: “Fall in love with text; there are hidden gems in reading.” Many miss opportunities because they dislike reading. The internet, especially the MQL5 community, offers countless opportunities for careers, authorship, development, and freelancing. I visit mql5.com at least three times a day, and I have integrated it with my mobile terminal ID, called MetaQuotes ID, to receive crucial notifications on my mobile device. As William Shakespeare said, “All that glitters is not gold.” True wealth lies in reading text, which may not be as appealing as images, yet even algorithm is composed of valuable text.

  •  Secret 1: MQL5 Community
  •  Secret 2: Desktop MetaTrader 5 Platform
  •  Secret 3: Artificial Intelligence

These three elements can be used together to make you a better MQL5 algorithm developer. While the goal of this article is to motivate you to get started, I will also ensure we build a basic program to implement these three secrets.

 

Uncovering the Secrets to a Thriving MQL5 Trader

Secret 1: MQL5 Community

MQL5 is a comprehensive resource for everything related to algorithmic trading. It contains everything you need to get started and continue developing as a trader. Here are some key components of the MQL5 community that are essential for developers:

  mql5.com

    • Documentation: Comprehensive resource providing detailed information about MQL5 programming, including functions, classes, and development guidelines.
    • 'AlgoBook': A collection of algorithmic books to help develop your own algorithms.
    • 'NeuroBook': Specialized books focusing on neural networks and machine learning techniques in algorithmic trading using MQL5.
    • 'CodeBase': A repository of free MQL5 scripts, indicators, and expert advisors (EAs) contributed by the MQL5 community for traders to download, use, and modify.
    • Forum: An interactive platform for discussing trading strategies, programming issues, and sharing experiences and solutions related to MQL5 development.
    • Articles: A library of articles offering tutorials, trading strategies, programming tips, and insights into various aspects of algorithmic trading with MQL5.
    • Market: An online store where traders can buy and sell MQL5 trading applications, including EAs, indicators, and scripts.
    • Signals: A service allowing traders to subscribe to trading signals provided by experienced traders, enabling automated copying of their trades.
    • VPS: Virtual Private Server service provided by MetaTrader, enabling traders to run their trading robots and signals 24/7 without interruptions.
    • Freelance: A platform where traders can hire freelance developers to create custom trading applications, indicators, or scripts in MQL5.
    • Quotes: Real-time quotes of financial instruments, providing traders with up-to-date market prices necessary for making informed trading decisions.
    •  Calendar: An economic calendar listing significant economic events and news that can impact financial markets and trading strategies.
    • 'WebTerminal': An online version of the MetaTrader trading platform, allowing traders to access their accounts and trade directly from a web browser without installing any software.
    • Search Box: A tool enabling users to quickly find specific information, resources, or content within the MQL5 community and its extensive library of documentation, articles, and forum discussions.

 

Secret 2: Desktop MetaTrader 5 Platform

This platform is another rich resource essential for mastering algorithmic trading. It features many of the resources found in the MQL5 community and serves as the starting point for writing algorithms. When strategizing, I start by viewing charts to identify repeating patterns in past market data, then I develop the logic on paper before coding my algorithm. MetaTrader 5 comes with the MetaQuotes Language Editor and the Strategy Tester, among other features, making it a fantastic tool set for development and studying.

Let me briefly show you an example:

I open the chart to analyze what has been happening. Here is an image of GBP/USD before any indicator is applied. I then add EMA 50 and EMA 21 on the chart to see how they interact with price changes. I observe potential crossovers and mark them with rectangle tools. From this image, I can start strategizing for automation.

GBPUSD 


Setting MA21



Setting MA 50


GBPUSD MA crossover strategy


MetaQuotes Language Editor (MetaEditor):

Templates: MetaEditor comes with pre-made templates for scripts, Expert Advisors (EAs), and indicators, providing a solid starting point for projects and helping users understand the structure and key components of MQL5 programs.

Learning by Doing: Educational theorist John Dewey emphasized the importance of "learning by doing" in the early 20th century. Start by creating simple projects using these templates. Modify and experiment with them to get a feel for how different elements interact. This practical approach solidifies your foundational knowledge and aligns with Dewey's philosophy that active involvement in learning enhances understanding and retention.

 

Secret 3: Artificial Intelligence

There are many AI models being invented every day, but let's briefly talk about ChatGPT. It is a conversational AI model designed to assist users by providing answers, inspiration, and productivity help. It is free to use and can aid in writing, learning, brainstorming, and more. ChatGPT was created by OpenAI, a company founded in 2015.

AI models like ChatGPT are trained on vast amounts of data, including programming languages and documentation. This training process involves analyzing patterns, understanding syntax, and learning best practices from numerous code examples across various languages. As a result, ChatGPT can offer expert-level guidance, helping you understand complex programming concepts and solve coding problems efficiently.

 

Implementation of Artificial Intelligence in Algorithm Development

Here, I will guide you through how the collaboration of tools can simplify your learning and break the limitations caused by not knowing these resources. To get started with ChatGPT, I will split activities into two:

  1. Understanding the MetaEditor templates with ChatGPT
  2. Developing a script with AI assistance, called "My First MQL5 Program"

 

Understanding the MetaEditor templates with ChatGPT

In MetaTrader 5 desktop, go to Tools and select MetaQuotes Language Editor, or press F4 on your keyboard. A new window for the MetaEditor will open. Go to File and select New. Below is an animated image showing the process:

MetaEditor: MyFirstIndicator

I have named the file "MyFirstIndicator," but this is optional; you can name it as you like. When you do this, you will get a code template shown in the snippet below.

//+------------------------------------------------------------------+
//|                                             MyFirstIndicator.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_chart_window
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

As a beginner, you might ask yourself, "What on earth is this?" Well, let me show you how to easily understand everything as part of our secret unlocking goal.

  1. Go to chat.openai.com and initiate a chat.
  2. Copy the program code from MetaEditor.
  3. Type a prompt in ChatGPT: "Explain this MQL5 code in parts:" (paste the code you copied) and click send.

ChatGPT will reply with a detailed explanation of what is going on. Continue reading to discover more.

In response, ChatGPT split the program into snippets and explained it in a more engaging way, making it easy to understand the template. Here is the program explained by ChatGPT in italic text:

//+------------------------------------------------------------------+
//|                                             MyFirstIndicator.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+

  • This section is a header comment that includes the name of the file, the copyright information, and a link to the MetaQuotes website. This is typical in MQL5 code to give context and attribution.

#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_chart_window

These #property directives provide metadata about the indicator:

  • #property copyright: Indicates the copyright holder and year.
  • #property link: Provides a link to a website (typically where more information can be found).
  • #property version: Specifies the version of the indicator.
  • #property indicator_chart_window: Indicates that the indicator will be drawn in the main chart window (as opposed to a separate window).
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   
//---
   return(INIT_SUCCEEDED);
  }

This section defines the OnInit function, which is called when the indicator is initialized:

  • OnInit(): The function is responsible for setting up the indicator, such as allocating buffers and initializing variables.
  • return'(INIT_SUCCEEDED);': Indicates that the initialization was successful. INIT_SUCCEEDED is a predefined constant in MQL5.
  • Currently, the function does not perform any actions because the main body between the comments (//---) is empty.

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

This section defines the OnCalculate function, which is called to calculate the indicator values on each tick:

  • OnCalculate: This is where the main logic of the indicator is implemented. It processes the price data and computes the indicator values.
  • Rates_total: Total number of bars in the chart.
  • 'Prev_calculated': Number of bars calculated during the previous call.
  • Time[], open[], high[], low[], close[], tick_volume[], volume[], spread[]: Arrays containing the time, open, high, low, close prices, tick volume, real volume, and spread for each bar.

The function currently does not perform any calculations, as the main body is empty. It simply returns rates_total, indicating the total number of bars that have been processed. This is important for keeping track of the bars processed in subsequent calls. In summary, this is a skeleton code for a custom indicator in MQL5. It sets up the basic structure and metadata but does not perform any specific actions or calculations yet.


Developing a script with AI assistance, called "My First MQL5 Program"

First, we need to know the purpose of the program we are developing. In this case, I will suggest a script program to tell me whether the D1 candle is a Bull or a Bear. Next, go to ChatGPT and send a prompt. This time, we want to provide the script program template for storage in AI memory and then ask to modify it for the conditions.

Create a Script


Set the name of the Script

First, we need to know the purpose of the program we are developing. In this case, I will suggest a script program to tell me whether the D1 candle is a Bull or a Bear. After pressing "Finish," we get this program template, and we copy it to ChatGPT to accomplish our plan according to this context:

//+------------------------------------------------------------------+
//|                                          MyFirstMQL5 Program.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   
  }
//+------------------------------------------------------------------+
Below is a code snippet as prompted it on ChatGPT:
Create an MQL5 script from this template that tells day candle status on screen: //+------------------------------------------------------------------+
//|                                          MyFirstMQL5 Program.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   
  }
//+------------------------------------------------------------------+

 ChatGPT response:

//+------------------------------------------------------------------+
//|                                          MyFirstMQL5 Program.mq5 |
//|                                  Copyright 2024, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

// Input parameters for customizing the text display
input color TextColor = clrRed;               // Color of the text
input int FontSize = 20;                      // Font size
input ENUM_ANCHOR_POINT AnchorCorner = ANCHOR_LEFT_UPPER; // Text anchor point
input int X_Offset = 10;                      // X offset
input int Y_Offset = 10;                      // Y offset

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   // Get the opening price of the current day
   double openPrice = iOpen(_Symbol, PERIOD_D1, 0);
   
   // Get the closing price of the current day
   double closePrice = iClose(_Symbol, PERIOD_D1, 0);
   
   // Determine the candle status
   string candleStatus = (closePrice >= openPrice) ? "Bullish" : "Bearish";
   
   // Display the candle status on the screen
   DisplayCandleStatus(candleStatus);
  }

//+------------------------------------------------------------------+
//| Function to display the candle status on the screen              |
//+------------------------------------------------------------------+
void DisplayCandleStatus(string status)
  {
   string objName = "CandleStatusText";
   
   if(ObjectFind(0, objName) < 0)
     {
      // Create the text object if it doesn't exist
      ObjectCreate(0, objName, OBJ_LABEL, 0, 0, 0);
      ObjectSetInteger(0, objName, OBJPROP_CORNER, AnchorCorner);
      ObjectSetInteger(0, objName, OBJPROP_XDISTANCE, X_Offset);
      ObjectSetInteger(0, objName, OBJPROP_YDISTANCE, Y_Offset);
      ObjectSetInteger(0, objName, OBJPROP_FONTSIZE, FontSize);
      ObjectSetInteger(0, objName, OBJPROP_COLOR, TextColor);
     }
   
   // Update the text
   ObjectSetString(0, objName, OBJPROP_TEXT, "Day Candle: " + status);
  }
//+------------------------------------------------------------------+


Testing

Here is the procedure that I followed during testing.

  • Copy the Code: After receiving the modified script from ChatGPT, copy the code.
  • Open MetaEditor: Launch MetaEditor on your computer.
  • Create a New Script:
    • Go to File > New > Script.
    • Enter a name for your script, then click Next and Finish.
  • Paste the Code: Replace the auto-generated code in the new script file with the modified code you received from ChatGPT.
  • Compile the Script:
    • Click the Compile button on the MetaEditor toolbar.
    • If there are no errors, your script will be compiled successfully.
  • Check the Output:
    • In the Navigator tab, look under the Scripts section to find your compiled script file.
    • Drag and drop the script onto a chart in MetaTrader 5 to see the results.

  • Review the Results: Monitor the chart to verify if the script correctly identifies whether the D1 candle is a Bull or a Bear.

Compiling in MetaEditor


The program compiled successfully without any further editing. The D1 candle was confirmed to be Bullish by the script.

The script is now added in the scripts folder Boom 500 Index D1



Conclusion

Mastering MQL5 is a journey that combines learning, experimentation, and leveraging advanced tools like AI. By mastering the basics, engaging with community resources, overcoming dynamic challenges with AI assistance, optimizing strategies, and embracing automation, you can unlock your full potential as a trader. These three secrets are just the beginning; continuous learning and adaptation will ensure you stay ahead in the dynamic world of algorithmic trading. Embrace the opportunities that MQL5 offers, and watch your trading success soar.

Much can be done with AI, and the limit is your mind and the skill of communicating your idea with it. Not all programs created by AI will execute efficiently every time; sometimes, you need to go the extra mile in debugging and revisiting community documentation and MQL5 Books for in-depth research. There is a lot to share, but let's save that for next time. At least you now have a companion. Happy developing further!
File Name Description
'MyFirstIndicator.mq5' MQL5 indicator Template.
MyFirstMQL5 Program.mq5 Script algorithm.
MyFirstMQL5 Program.ex5 Compile scrip program ready for use.


Developing a multi-currency Expert Advisor (Part 5): Variable position sizes Developing a multi-currency Expert Advisor (Part 5): Variable position sizes
In the previous parts, the Expert Advisor (EA) under development was able to use only a fixed position size for trading. This is acceptable for testing, but is not advisable when trading on a real account. Let's make it possible to trade using variable position sizes.
Creating a Dynamic Multi-Symbol, Multi-Period Relative Strength Indicator (RSI) Indicator Dashboard in MQL5 Creating a Dynamic Multi-Symbol, Multi-Period Relative Strength Indicator (RSI) Indicator Dashboard in MQL5
In this article, we develop a dynamic multi-symbol, multi-period RSI indicator dashboard in MQL5, providing traders real-time RSI values across various symbols and timeframes. The dashboard features interactive buttons, real-time updates, and color-coded indicators to help traders make informed decisions.
Reimagining Classic Strategies (Part III): Forecasting Higher Highs And Lower Lows Reimagining Classic Strategies (Part III): Forecasting Higher Highs And Lower Lows
In this series article, we will empirically analyze classic trading strategies to see if we can improve them using AI. In today's discussion, we tried to predict higher highs and lower lows using the Linear Discriminant Analysis model.
Practicing the development of trading strategies Practicing the development of trading strategies
In this article, we will make an attempt to develop our own trading strategy. Any trading strategy must be based on some kind of statistical advantage. Moreover, this advantage should exist for a long time.