MQL5 Programming Articles

icon

Study the MQL5 language for programming trading strategies in numerous published articles mostly written by you - the community members. The articles are grouped into categories to help you quicker find answers to any questions related to programming: Integration, Tester, Trading Strategies, etc.

Follow our new publications and discuss them on the Forum!

Add a new article
latest | best
preview
Self Optimizing Expert Advisors in MQL5 (Part 8): Multiple Strategy Analysis (Part 2)

Self Optimizing Expert Advisors in MQL5 (Part 8): Multiple Strategy Analysis (Part 2)

Join us for our follow-up discussion, where we will merge our first two trading strategies into an ensemble trading strategy. We shall demonstrate the different schemes possible for combining multiple strategies and also how to exercise control over the parameter space, to ensure that effective optimization remains possible even as our parameter size grows.
preview
Developing an MQTT client for Metatrader 5: a TDD approach — Part 5

Developing an MQTT client for Metatrader 5: a TDD approach — Part 5

This article is the fifth part of a series describing our development steps of a native MQL5 client for the MQTT 5.0 protocol. In this part we describe the structure of PUBLISH packets, how we are setting their Publish Flags, encoding Topic Name(s) strings, and setting Packet Identifier(s) when required.
preview
MQL5 Trading Toolkit (Part 6): Expanding the History Management EX5 Library with the Last Filled Pending Order Functions

MQL5 Trading Toolkit (Part 6): Expanding the History Management EX5 Library with the Last Filled Pending Order Functions

Learn how to create an EX5 module of exportable functions that seamlessly query and save data for the most recently filled pending order. In this comprehensive step-by-step guide, we will enhance the History Management EX5 library by developing dedicated and compartmentalized functions to retrieve essential properties of the last filled pending order. These properties include the order type, setup time, execution time, filling type, and other critical details necessary for effective pending orders trade history management and analysis.
preview
Population optimization algorithms: Bacterial Foraging Optimization - Genetic Algorithm (BFO-GA)

Population optimization algorithms: Bacterial Foraging Optimization - Genetic Algorithm (BFO-GA)

The article presents a new approach to solving optimization problems by combining ideas from bacterial foraging optimization (BFO) algorithms and techniques used in the genetic algorithm (GA) into a hybrid BFO-GA algorithm. It uses bacterial swarming to globally search for an optimal solution and genetic operators to refine local optima. Unlike the original BFO, bacteria can now mutate and inherit genes.
preview
Feature selection and dimensionality reduction using principal components

Feature selection and dimensionality reduction using principal components

The article delves into the implementation of a modified Forward Selection Component Analysis algorithm, drawing inspiration from the research presented in “Forward Selection Component Analysis: Algorithms and Applications” by Luca Puggini and Sean McLoone.
preview
Overcoming The Limitation of Machine Learning (Part 1): Lack of Interoperable Metrics

Overcoming The Limitation of Machine Learning (Part 1): Lack of Interoperable Metrics

There is a powerful and pervasive force quietly corrupting the collective efforts of our community to build reliable trading strategies that employ AI in any shape or form. This article establishes that part of the problems we face, are rooted in blind adherence to "best practices". By furnishing the reader with simple real-world market-based evidence, we will reason to the reader why we must refrain from such conduct, and rather adopt domain-bound best practices if our community should stand any chance of recovering the latent potential of AI.
preview
Mastering Log Records (Part 6): Saving logs to database

Mastering Log Records (Part 6): Saving logs to database

This article explores the use of databases to store logs in a structured and scalable way. It covers fundamental concepts, essential operations, configuration and implementation of a database handler in MQL5. Finally, it validates the results and highlights the benefits of this approach for optimization and efficient monitoring.
preview
Creating a Trading Administrator Panel in MQL5 (Part XI): Modern feature communications interface (I)

Creating a Trading Administrator Panel in MQL5 (Part XI): Modern feature communications interface (I)

Today, we are focusing on the enhancement of the Communications Panel messaging interface to align with the standards of modern, high-performing communication applications. This improvement will be achieved by updating the CommunicationsDialog class. Join us in this article and discussion as we explore key insights and outline the next steps in advancing interface programming using MQL5.
preview
Developing a Replay System (Part 56): Adapting the Modules

Developing a Replay System (Part 56): Adapting the Modules

Although the modules already interact with each other properly, an error occurs when trying to use the mouse pointer in the replay service. We need to fix this before moving on to the next step. Additionally, we will fix an issue in the mouse indicator code. So this version will be finally stable and properly polished.
preview
Stepwise feature selection in MQL5

Stepwise feature selection in MQL5

In this article, we introduce a modified version of stepwise feature selection, implemented in MQL5. This approach is based on the techniques outlined in Modern Data Mining Algorithms in C++ and CUDA C by Timothy Masters.
preview
Population optimization algorithms: Resistance to getting stuck in local extrema (Part I)

Population optimization algorithms: Resistance to getting stuck in local extrema (Part I)

This article presents a unique experiment that aims to examine the behavior of population optimization algorithms in the context of their ability to efficiently escape local minima when population diversity is low and reach global maxima. Working in this direction will provide further insight into which specific algorithms can successfully continue their search using coordinates set by the user as a starting point, and what factors influence their success.
preview
MQL5 Wizard Techniques you should know (Part 29): Continuation on Learning Rates with MLPs

MQL5 Wizard Techniques you should know (Part 29): Continuation on Learning Rates with MLPs

We wrap up our look at learning rate sensitivity to the performance of Expert Advisors by primarily examining the Adaptive Learning Rates. These learning rates aim to be customized for each parameter in a layer during the training process and so we assess potential benefits vs the expected performance toll.
preview
Price-Driven CGI Model: Advanced Data Post-Processing and Implementation

Price-Driven CGI Model: Advanced Data Post-Processing and Implementation

In this article, we will explore the development of a fully customizable Price Data export script using MQL5, marking new advancements in the simulation of the Price Man CGI Model. We have implemented advanced refinement techniques to ensure that the data is user-friendly and optimized for animation purposes. Additionally, we will uncover the capabilities of Blender 3D in effectively working with and visualizing price data, demonstrating its potential for creating dynamic and engaging animations.
preview
MQL5 Wizard Techniques you should know (Part 40): Parabolic SAR

MQL5 Wizard Techniques you should know (Part 40): Parabolic SAR

The Parabolic Stop-and-Reversal (SAR) is an indicator for trend confirmation and trend termination points. Because it is a laggard in identifying trends its primary purpose has been in positioning trailing stop losses on open positions. We, however, explore if indeed it could be used as an Expert Advisor signal, thanks to custom signal classes of wizard assembled Expert Advisors.
preview
Data Science and ML (Part 44): Forex OHLC Time series Forecasting using Vector Autoregression (VAR)

Data Science and ML (Part 44): Forex OHLC Time series Forecasting using Vector Autoregression (VAR)

Explore how Vector Autoregression (VAR) models can forecast Forex OHLC (Open, High, Low, and Close) time series data. This article covers VAR implementation, model training, and real-time forecasting in MetaTrader 5, helping traders analyze interdependent currency movements and improve their trading strategies.
preview
Developing an MQTT client for Metatrader 5: a TDD approach — Part 6

Developing an MQTT client for Metatrader 5: a TDD approach — Part 6

This article is the sixth part of a series describing our development steps of a native MQL5 client for the MQTT 5.0 protocol. In this part we comment on the main changes in our first refactoring, how we arrived at a viable blueprint for our packet-building classes, how we are building PUBLISH and PUBACK packets, and the semantics behind the PUBACK Reason Codes.
preview
MQL5 Wizard Techniques you should know (Part 72): Using Patterns of MACD and the OBV with Supervised Learning

MQL5 Wizard Techniques you should know (Part 72): Using Patterns of MACD and the OBV with Supervised Learning

We follow up on our last article, where we introduced the indicator pair of the MACD and the OBV, by looking at how this pairing could be enhanced with Machine Learning. MACD and OBV are a trend and volume complimentary pairing. Our machine learning approach uses a convolution neural network that engages the Exponential kernel in sizing its kernels and channels, when fine-tuning the forecasts of this indicator pairing. As always, this is done in a custom signal class file that works with the MQL5 wizard to assemble an Expert Advisor.
preview
Mastering Log Records (Part 2): Formatting Logs

Mastering Log Records (Part 2): Formatting Logs

In this article, we will explore how to create and apply log formatters in the library. We will see everything from the basic structure of a formatter to practical implementation examples. By the end, you will have the necessary knowledge to format logs within the library, and understand how everything works behind the scenes.
preview
Header in the Connexus (Part 3): Mastering the Use of HTTP Headers for Requests

Header in the Connexus (Part 3): Mastering the Use of HTTP Headers for Requests

We continue developing the Connexus library. In this chapter, we explore the concept of headers in the HTTP protocol, explaining what they are, what they are for, and how to use them in requests. We cover the main headers used in communications with APIs, and show practical examples of how to configure them in the library.
preview
Custom Debugging and Profiling Tools for MQL5 Development (Part I): Advanced Logging

Custom Debugging and Profiling Tools for MQL5 Development (Part I): Advanced Logging

Learn how to implement a powerful custom logging framework for MQL5 that goes beyond simple Print() statements by supporting severity levels, multiple output handlers, and automated file rotation—all configurable on‐the‐fly. Integrate the singleton CLogger with ConsoleLogHandler and FileLogHandler to capture contextual, timestamped logs in both the Experts tab and persistent files. Streamline debugging and performance tracing in your Expert Advisors with clear, customizable log formats and centralized control.
preview
Body in Connexus (Part 4): Adding HTTP body support

Body in Connexus (Part 4): Adding HTTP body support

In this article, we explored the concept of body in HTTP requests, which is essential for sending data such as JSON and plain text. We discussed and explained how to use it correctly with the appropriate headers. We also introduced the ChttpBody class, part of the Connexus library, which will simplify working with the body of requests.
preview
Mastering Log Records (Part 4): Saving logs to files

Mastering Log Records (Part 4): Saving logs to files

In this article, I will teach you basic file operations and how to configure a flexible handler for customization. We will update the CLogifyHandlerFile class to write logs directly to the file. We will conduct a performance test by simulating a strategy on EURUSD for a week, generating logs at each tick, with a total time of 5 minutes and 11 seconds. The result will be compared in a future article, where we will implement a caching system to improve performance.
preview
Developing a Replay System (Part 63): Playing the service (IV)

Developing a Replay System (Part 63): Playing the service (IV)

In this article, we will finally solve the problems with the simulation of ticks on a one-minute bar so that they can coexist with real ticks. This will help us avoid problems in the future. The material presented here is for educational purposes only. Under no circumstances should the application be viewed for any purpose other than to learn and master the concepts presented.
preview
Developing a Replay System (Part 58): Returning to Work on the Service

Developing a Replay System (Part 58): Returning to Work on the Service

After a break in development and improvement of the service used for replay/simulator, we are resuming work on it. Now that we've abandoned the use of resources like terminal globals, we'll have to completely restructure some parts of it. Don't worry, this process will be explained in detail so that everyone can follow the development of our service.
preview
MQL5 Wizard Techniques you should know (Part 30): Spotlight on Batch-Normalization in Machine Learning

MQL5 Wizard Techniques you should know (Part 30): Spotlight on Batch-Normalization in Machine Learning

Batch normalization is the pre-processing of data before it is fed into a machine learning algorithm, like a neural network. This is always done while being mindful of the type of Activation to be used by the algorithm. We therefore explore the different approaches that one can take in reaping the benefits of this, with the help of a wizard assembled Expert Advisor.
preview
MQL5 Trading Toolkit (Part 7): Expanding the History Management EX5 Library with the Last Canceled Pending Order Functions

MQL5 Trading Toolkit (Part 7): Expanding the History Management EX5 Library with the Last Canceled Pending Order Functions

Learn how to complete the creation of the final module in the History Manager EX5 library, focusing on the functions responsible for handling the most recently canceled pending order. This will provide you with the tools to efficiently retrieve and store key details related to canceled pending orders with MQL5.
preview
Connexus Observer (Part 8): Adding a Request Observer

Connexus Observer (Part 8): Adding a Request Observer

In this final installment of our Connexus library series, we explored the implementation of the Observer pattern, as well as essential refactorings to file paths and method names. This series covered the entire development of Connexus, designed to simplify HTTP communication in complex applications.
preview
Sending Messages from MQL5 to Discord, Creating a Discord-MetaTrader 5 Bot

Sending Messages from MQL5 to Discord, Creating a Discord-MetaTrader 5 Bot

Similar to Telegram, Discord is capable of receiving information and messages in JSON format using it's communication API's, In this article, we are going to explore how you can use discord API's to send trading signals and updates from MetaTrader 5 to your Discord trading community.
preview
Developing a multi-currency Expert Advisor (Part 20): Putting in order the conveyor of automatic project optimization stages (I)

Developing a multi-currency Expert Advisor (Part 20): Putting in order the conveyor of automatic project optimization stages (I)

We have already created quite a few components that help arrange auto optimization. During the creation, we followed the traditional cyclical structure: from creating minimal working code to refactoring and obtaining improved code. It is time to start clearing up our database, which is also a key component in the system we are creating.
preview
Mastering Log Records (Part 3): Exploring Handlers to Save Logs

Mastering Log Records (Part 3): Exploring Handlers to Save Logs

In this article, we will explore the concept of handlers in the logging library, understand how they work, and create three initial implementations: Console, Database, and File. We will cover everything from the basic structure of handlers to practical testing, preparing the ground for their full functionality in future articles.
preview
Mastering Log Records (Part 5): Optimizing the Handler with Cache and Rotation

Mastering Log Records (Part 5): Optimizing the Handler with Cache and Rotation

This article improves the logging library by adding formatters in handlers, the CIntervalWatcher class to manage execution cycles, optimization with caching and file rotation, performance tests and practical examples. With these improvements, we ensure an efficient, scalable and adaptable logging system to different development scenarios.
preview
Data Science and ML (Part 45): Forex Time series forecasting using PROPHET by Facebook Model

Data Science and ML (Part 45): Forex Time series forecasting using PROPHET by Facebook Model

The Prophet model, developed by Facebook, is a robust time series forecasting tool designed to capture trends, seasonality, and holiday effects with minimal manual tuning. It has been widely adopted for demand forecasting and business planning. In this article, we explore the effectiveness of Prophet in forecasting volatility in forex instruments, showcasing how it can be applied beyond traditional business use cases.
preview
Mastering Log Records (Part 9): Implementing the builder pattern and adding default configurations

Mastering Log Records (Part 9): Implementing the builder pattern and adding default configurations

This article shows how to drastically simplify the use of the Logify library with the Builder pattern and automatic default configurations. It explains the structure of the specialized builders, how to use them with smart auto-completion, and how to ensure a functional log even without manual configuration. It also covers tweaks for MetaTrader 5 build 5100.
preview
Mastering Log Records (Part 8): Error Records That Translate Themselves

Mastering Log Records (Part 8): Error Records That Translate Themselves

In this eighth installment of the Mastering Log Records series, we explore the implementation of multilingual error messages in Logify, a powerful logging library for MQL5. You’ll learn how to structure errors with context, translate messages into multiple languages, and dynamically format logs by severity level. All of this with a clean, extensible, and production-ready design.
preview
Implementing Practical Modules from Other Languages in MQL5 (Part 01): Building the SQLite3 Library, Inspired by Python

Implementing Practical Modules from Other Languages in MQL5 (Part 01): Building the SQLite3 Library, Inspired by Python

The sqlite3 module in Python offers a straightforward approach for working with SQLite databases, it is fast and convenient. In this article, we are going to build a similar module on top of built-in MQL5 functions for working with databases to make it easier to work with SQLite3 databases in MQL5 as in Python.
preview
Using association rules in Forex data analysis

Using association rules in Forex data analysis

How to apply predictive rules of supermarket retail analytics to the real Forex market? How are purchases of cookies, milk and bread related to stock exchange transactions? The article discusses an innovative approach to algorithmic trading based on the use of association rules.
preview
Statistical Arbitrage Through Cointegrated Stocks (Part 1): Engle-Granger and Johansen Cointegration Tests

Statistical Arbitrage Through Cointegrated Stocks (Part 1): Engle-Granger and Johansen Cointegration Tests

This article aims to provide a trader-friendly, gentle introduction to the most common cointegration tests, along with a simple guide to understanding their results. The Engle-Granger and Johansen cointegration tests can reveal statistically significant pairs or groups of assets that share long-term dynamics. The Johansen test is especially useful for portfolios with three or more assets, as it calculates the strength of cointegrating vectors all at once.
preview
MQL5 Wizard Techniques you should know (Part 73): Using Patterns of Ichimoku and the ADX-Wilder

MQL5 Wizard Techniques you should know (Part 73): Using Patterns of Ichimoku and the ADX-Wilder

The Ichimoku-Kinko-Hyo Indicator and the ADX-Wilder oscillator are a pairing that could be used in complimentarily within an MQL5 Expert Advisor. The Ichimoku is multi-faceted, however for this article, we are relying on it primarily for its ability to define support and resistance levels. Meanwhile, we also use the ADX to define our trend. As usual, we use the MQL5 wizard to build and test any potential these two may possess.