MQL4 and 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
Quantum Neural Network in MQL5 (Part I): Creating the Include File

Quantum Neural Network in MQL5 (Part I): Creating the Include File

The article presents a new approach to creating trading systems based on quantum principles and artificial intelligence. The author describes the development of a unique neural network that goes beyond classical machine learning by combining quantum mechanics with modern AI architectures.
preview
MQL5 Wizard Techniques you should know (Part 94): Using Reservoir Sampling and Linear Regression in a Custom Trailing Stop Class

MQL5 Wizard Techniques you should know (Part 94): Using Reservoir Sampling and Linear Regression in a Custom Trailing Stop Class

For this article we rotate to a custom MQL5 Wizard class implementation that explores Trailing Stops. Our custom class is ‘CTrailingReservoirLinReg’ that we derive by combining the Reservoir Sampling algorithm with a Linear Regression network. As has been the case throughout these series, this formulation is testable with MQL5 Wizard Assembled Expert Advisors that can be tuned with various entry signals and money management classes.
preview
Step-by-Step Implementation of a Local Stop Loss System in MQL5

Step-by-Step Implementation of a Local Stop Loss System in MQL5

This article shows how to build a local stop-loss system in an MQL5 Expert Advisor that keeps stop levels on the terminal side. It walks through the execution logic, event handlers, inputs, and an OOP design using CTrade, CPositionInfo, CHashMap/CHashSet, and chart objects. You will implement multi-position tracking, draggable stops, visual spacers and labels, plus cleanup and disconnection behavior to create a practical risk-control utility.
preview
CSV Data Analysis (Part 2): Building a Production-Grade CSV Export and Parsing Pipeline for Quantitative Strategy Analysis

CSV Data Analysis (Part 2): Building a Production-Grade CSV Export and Parsing Pipeline for Quantitative Strategy Analysis

MQL5's file system operates within a strict sandbox. Understanding its access flags and path resolution rules is the foundation of any reliable export pipeline. This article builds a CCSVExporter class that handles file creation, safe appending, and error recovery. It also covers CSV parsing, field tokenization, concurrent access conflicts, and write-buffering strategies for high-frequency optimization runs.
preview
MQL5 Custom Symbols: Creating a 3D Bars Symbol

MQL5 Custom Symbols: Creating a 3D Bars Symbol

The article provides a detailed guide to creating the innovative 3DBarCustomSymbol.mq5 indicator, which generates custom symbols in MetaTrader 5 that combine price, time, volume, and volatility into a single three-dimensional representation. The mathematical foundations, system architecture, practical aspects of implementation and application in trading strategies are considered.
preview
Position Management: A Reusable Trade Journal with Live Maximum Adverse Excursion, Maximum Favorable Excursion, and R-Multiple Tracking in MQL5

Position Management: A Reusable Trade Journal with Live Maximum Adverse Excursion, Maximum Favorable Excursion, and R-Multiple Tracking in MQL5

This article presents CTradeJournal, a self-contained MQL5 class for live tracking of open positions at tick frequency. It maintains MAE, MFE, and initial risk in money, calculates the R-multiple when a position closes, and writes a complete CSV record. The text explains the design choices, provides the implementation, and shows simple EA integration so you can analyze entries, stop placement, and outcome distribution.
preview
CSV Data Analysis (Part 1): CSV Export Engine for MQL5 Multi-Core Optimizations

CSV Data Analysis (Part 1): CSV Export Engine for MQL5 Multi-Core Optimizations

Multi-core optimization in MetaTrader 5 can silently drop results when parallel agents contend for the same CSV file. A reusable MQL5 export engine applies an iteration-based spin-lock to acquire the file handle reliably and append rows without loss. It persists custom metrics such as the Sortino Ratio, average trade duration, and signal-quality measures (lag and whipsaws) into a consolidated CSV for downstream analysis.
preview
Exploring Regression Models for Causal Inference and Trading

Exploring Regression Models for Causal Inference and Trading

The article explores the possibility of using regression models in algorithmic trading. Regression models, unlike binary classification, allow for the creation of more flexible trading strategies by quantifying predicted price changes.
preview
Recurrence Network Analysis (RNA) in MQL5: From Recurrence Matrices to Complex Networks

Recurrence Network Analysis (RNA) in MQL5: From Recurrence Matrices to Complex Networks

The article extends the MQL5 recurrence library to Recurrence Network Analysis (RNA) by treating recurrence matrices as adjacency matrices of undirected graphs. It implements core network metrics—clustering, transitivity, average path length, betweenness, assortativity, and density—and applies them in rolling windows for single-series RNA and Joint RNA (JRNA). A modular metrics engine and two indicators visualize the evolving network structure on MetaTrader 5 charts for practical time-series analysis.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 2): Collecting and Structuring Data from Complex Analytical Objects

How to Detect and Normalize Chart Objects in MQL5 (Part 2): Collecting and Structuring Data from Complex Analytical Objects

Manually drawn analytical object tools like Fibonacci tools, and Andrews Pitchforks are invisible to automated trading logic. This article extends a base detector to extract anchor points, level arrays, and geometric offsets from complex objects. You will implement a reusable collector that normalizes the raw chart data into structured memory arrays, ready for strategy decisions.
preview
MQL5 Trading Tools (Part 35): Adding Channel, Pitchfork, Gann, and Fibonacci Tools to the Canvas Drawing Layer

MQL5 Trading Tools (Part 35): Adding Channel, Pitchfork, Gann, and Fibonacci Tools to the Canvas Drawing Layer

We extend the canvas drawing layer from the previous part with seven new categories of multi-anchor analytical drawing tools, covering three channel variants, three pitchfork variants, three Gann tools, and the six Fibonacci tools. We work through how each tool encodes its geometry on the canvas, how derived handles let users reshape compound shapes coherently, and how shared helpers handle ray clipping, scanline filling, and anti-aliased arc rendering. By the end, we will have a full set of analytical drawing tools that live on the same interactive canvas alongside the basic line tools from the previous part.
preview
Feature Engineering for ML (Part 5): Microstructural Features in Python

Feature Engineering for ML (Part 5): Microstructural Features in Python

This article implements the Chapter 19 microstructure suite in afml.features.microstructure and explains a two-layer design for OHLCV-only and tick-augmented workflows. We cover Roll and Corwin–Schultz spread/volatility, Kyle's, Amihud's, and Hasbrouck's lambdas, VPIN, and bar‑level imbalance features, all in Numba‑accelerated kernels. A single np.searchsorted pass resolves bar boundaries, enabling prange parallelization and producing a bar‑indexed feature matrix ready for downstream ML models.
preview
Engineering Trading Discipline into Code (Part 7): Automating Equity Protection Through Governance Logic

Engineering Trading Discipline into Code (Part 7): Automating Equity Protection Through Governance Logic

Automated trading systems often focus heavily on signal generation while neglecting the mechanisms required to protect capital during periods of stress. This article presents an Equity Governance Framework in MQL5 that monitors drawdown conditions, evaluates equity pressure, and dynamically controls trading activity through a state-driven risk management model. By combining drawdown analysis, cooldown logic, trade authorization, and execution restrictions, the framework demonstrates how trading discipline can be engineered directly into code using a modular and extensible architecture.
preview
Neural Networks in Trading: Hierarchical Skill Discovery for Adaptive Agent Behavior (HiSSD)

Neural Networks in Trading: Hierarchical Skill Discovery for Adaptive Agent Behavior (HiSSD)

In this article, we explore the HiSSD framework, which combines hierarchical learning and multi-agent approaches to create adaptive systems. We examine in detail how this innovative methodology helps uncover hidden patterns in financial markets and optimize trading strategies in decentralized environments.
preview
Beyond GARCH (Part V): Fitting the Multifractal Spectrum in MQL5

Beyond GARCH (Part V): Fitting the Multifractal Spectrum in MQL5

This article builds the Spectrum Fitter: from tau(q) we compute f(alpha) with a discrete Legendre transform, then fit Normal, Binomial, Poisson, and Gamma spectra under box constraints using BLEIC. The best model by SSE is selected, and its parameters (eg, alpha min, alpha max or alpha_0, gamma) become the cascade inputs for multifractal simulation.
preview
Carry Trade Logic in MQL5: Building an EA That Factors Swap Rates Into Position Sizing and Holding Decisions

Carry Trade Logic in MQL5: Building an EA That Factors Swap Rates Into Position Sizing and Holding Decisions

Most retail traders ignore overnight swap rates, but for long-term positions, these interest payments can make or break your strategy. This article shows you how to build a dynamic MQL5 module that retrieves real-time swap data and converts it into actual profit or loss in your account currency. You will learn how to program an Expert Advisor that automatically calculates if a trade is worth holding based on carry income and adjusts your position size to account for expected interest. It is a practical guide to turning a hidden cost into a mathematical advantage for your trading systems.
preview
Exchange Market Algorithm (EMA)

Exchange Market Algorithm (EMA)

The article presents a detailed analysis of the Exchange Market Algorithm (EMA) inspired by the behavior of stock market traders. The algorithm simulates stock trading, where market participants with varying levels of success employ different strategies to maximize profits.
preview
Developing a Multi-Currency Expert Advisor (Part 28): Adding a Position Closing Manager

Developing a Multi-Currency Expert Advisor (Part 28): Adding a Position Closing Manager

When running multiple strategies in parallel, you may want to periodically close all open positions and start the strategies over again. The existing code only allows this behavior to be implemented through manual intervention. Let's try to automate this part.
preview
MQL5 Wizard Techniques you should know (Part 93): Using Suffix Automation and an Auto Encoder in a Custom Money Management Class

MQL5 Wizard Techniques you should know (Part 93): Using Suffix Automation and an Auto Encoder in a Custom Money Management Class

For this article we switch to a custom MQL5 Wizard class implementation that explores Money Management. We are labelling our custom class ‘CMoneySuffixAE’ that we derive by combining the Suffix Automaton algorithm with an Autoencoder neural network. As always, this formulation is testable with MQL5 Wizard Assembled Expert Advisors that can be tuned with various entry signals and trailing stop approaches.
preview
Price Action Analysis Toolkit Development (Part 71): Weekend Gap Structure Mapping in MQL5

Price Action Analysis Toolkit Development (Part 71): Weekend Gap Structure Mapping in MQL5

The article delivers an object-based MQL5 implementation that detects weekend gaps from time discontinuities and renders them directly on the chart. It manages graphical objects, tracks state transitions (fresh, partial, reaction, filled), and preserves completed gaps as historical zones. The result is a reproducible framework for monitoring how price revisits and fills weekend gap structures.
preview
Building an Object-Oriented Z-Score Statistical Arbitrage Engine in MQL5

Building an Object-Oriented Z-Score Statistical Arbitrage Engine in MQL5

This article shows how to implement a production Z-Score engine in MQL5 using an object-oriented include file, the library computes a rolling mean and population standard deviation, exposes a shift parameter for historical queries, and avoids redundant tick work by running on bar close. An Expert Advisor executes rule-based entries at positive/negative sigma thresholds and closes on mean reversion; a custom indicator provides visual verification.
preview
Neural Networks in Trading: Anomaly Detection in the Frequency Domain (Final Part)

Neural Networks in Trading: Anomaly Detection in the Frequency Domain (Final Part)

We continue to work on implementing the CATCH framework, which combines the Fourier transform and frequency patching mechanisms, ensuring accurate detection of market anomalies. In this article, we complete the implementation of our own vision of the proposed approaches and test the new models on real historical data.
preview
Market Simulation: Getting started with SQL in MQL5 (I)

Market Simulation: Getting started with SQL in MQL5 (I)

In today's article we will begin studying the use of SQL in MQL5 code. We will also look at how to create a database. Or, more precisely, how to create a SQLite database file using the features built into MQL5. We will also see how to create a table, and then how to establish a relationship between tables by using primary and foreign keys. All of this, once again, will be done with MQL5. We will see how easy it is to create code that can later be migrated to other SQL implementations by using a class that helps hide the implementation being created. And, most importantly, we will see that at various points we may face the risk that something will go wrong when using SQL. This happens because, in MQL5 code, SQL code will always be placed inside a string.
preview
Implementing a Breakeven Mechanism in MQL5 (Part 2): ATR- and RRR-Based Breakeven

Implementing a Breakeven Mechanism in MQL5 (Part 2): ATR- and RRR-Based Breakeven

This article completes the implementation of ATR- and RRRR-based breakeven mechanisms in MQL5 and develops, from scratch, a class that makes it easy to switch breakeven modes without having to enter the parameters again. To evaluate the effectiveness of each breakeven type, several backtests are run, analyzing their advantages and disadvantages in the context of algorithmic trading.
preview
Interactive Supply and Demand Zone Manager in MQL5: From Manual to Automated Lifecycle

Interactive Supply and Demand Zone Manager in MQL5: From Manual to Automated Lifecycle

Replace static drawings with automated, stateful zones controlled by a CZone wrapper. The system synchronizes user rectangles, sizes zones by ATR, validates breakouts using consecutive closes, applies ghost/deactivation rules, merges nearby structures by a 1.5×ATR threshold, and projects edges forward. Traders gain durable levels that update themselves and reduce repetitive chart management.
preview
Market Microstructure in MQL5 (Part 4): Volatility That Remembers

Market Microstructure in MQL5 (Part 4): Volatility That Remembers

This article adds eight volatility functions to MicroStructure_Foundation.mqh, including realized volatility, duration-adjusted volatility, fractional volatility, a FIGARCH-inspired proxy, a volatility clustering index, a GJR-GARCH asymmetry measure (using the Dube library), bipower-variation jump detection, and a wrapper function. The MFDFA implementation is revised to return the conventional Legendre-transform Δα with an R² confidence field, replacing the τ-spread proxy used in the original submission. Thresholds are derived from 514 NY sessions of NQ E-mini Nasdaq 100 futures (May 2024–May 2026); no new include file is created.
preview
From Basic to Intermediate: Objects (II)

From Basic to Intermediate: Objects (II)

In today's article, we will look at how to control some object properties in a simple way using code. We will also see how a custom application can place more than one object on the same chart. In addition, we will begin to understand the importance of assigning a short name to any indicator we plan to implement.
preview
Market Simulation (Part 24): Getting Started with SQL (VII)

Market Simulation (Part 24): Getting Started with SQL (VII)

In the previous article, we completed the necessary introduction to SQL. And, in my opinion, we properly clarified what we wanted to show and explain about SQL. This was done so that anyone who comes to look at the market replay/simulation system being built can at least get an idea of what may be happening there. The point is that there is no sense in programming things that SQL handles perfectly.
preview
Analyzing Price Time Gaps in MQL5 (Part II): Creating a Heat Map of Liquidity Distribution Over Time

Analyzing Price Time Gaps in MQL5 (Part II): Creating a Heat Map of Liquidity Distribution Over Time

A detailed guide on how to create a heat map indicator for MetaTrader 5 that visualizes the price distribution over time. The article reveals the mathematical basis of time density analysis, where each price level is colored from red (minimum stay time) to blue (maximum stay time).
preview
From Basic to Intermediate: Function Pointers

From Basic to Intermediate: Function Pointers

You have probably already heard about pointers when it comes to programming. But did you know that we can use this kind of data here in MQL5? Of course, this must be done in a way that keeps us in control and avoids strange program behavior during execution. Still, because this is a feature with a very specific purpose and aimed at particular kinds of tasks, it is rare to hear anyone discuss what a pointer is and how to use it in MQL5.
preview
Market Simulation (Part 23): Getting Started with SQL (VI)

Market Simulation (Part 23): Getting Started with SQL (VI)

In this article, we will see how to visualize a database and, from that, understand how it is structured. This is done by analyzing the database’s internal structure. Although this may seem unnecessary at first, it is fully justified if we really want to become database administrators. After all, some people make a living maintaining and designing databases.
preview
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 3): A Regime-Adaptive Mean-Reversion Swing Trading System

Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 3): A Regime-Adaptive Mean-Reversion Swing Trading System

The article describes and codes MR Swing in MQL5, a mean‑reversion swing approach that combines a 200‑day hysteresis channel with Value Charts, DVO, and SVAPO. We document entry/exit rules for bull and bear regimes and show five‑year backtests on six high‑liquidity Nasdaq stocks. The complete EA code and backtest configurations are provided for reproducibility.
preview
MQL5 Trading Tools (Part 34): Replacing Native Chart Objects with an Interactive Canvas Drawing Layer

MQL5 Trading Tools (Part 34): Replacing Native Chart Objects with an Interactive Canvas Drawing Layer

We replace native MetaTrader chart objects with a canvas-based drawing engine that renders tools pixel-by-pixel on a full-chart bitmap layer. The article implements persistent object storage with per-tool style memory, precise hit testing, selection, whole-object dragging, and handle manipulation. It also adds new line tools, a reorganized category system with a one-click delete action, and a rubber-band preview for multi-click placement.
preview
MetaTrader 5 Machine Learning Blueprint (Part 17): CPCV Backtesting — From Python Model to Tick-Level Evidence

MetaTrader 5 Machine Learning Blueprint (Part 17): CPCV Backtesting — From Python Model to Tick-Level Evidence

We bridge Python-native artifacts to MQL5 for tick-accurate CPCV backtesting. The export script converts the ONNX model, calibrator, feature spec, and path masks to flat files, while the expert advisor rebuilds features, performs ONNX inference with calibration, and trades on real ticks. The Strategy Tester runs each combinatorial path, and Python aggregates per-path equities into a path Sharpe distribution to assess robustness after spread, slippage, and commission.
preview
Automating Classic Market Methods in MQL5 (Part 1): Wyckoff Accumulation and Distribution

Automating Classic Market Methods in MQL5 (Part 1): Wyckoff Accumulation and Distribution

The article describes an MQL5 EA that automates Wyckoff accumulation and distribution via a finite state machine. It confirms spring to SOS and upthrust to SOW before placing LPS or LPSY entries, using relative tick volume as the confirmation metric. Readers get the state model, detection criteria, code organization, and MetaTrader 5 testing procedure.
preview
Seasonality Indicator by Hours, Days of the Week, and Days of the Month

Seasonality Indicator by Hours, Days of the Week, and Days of the Month

The article explains how to develop a tool for analyzing recurring price patterns in financial markets — by day of the month (1-31), day of the week (Monday-Sunday), or hour of the day (0-23). The indicator analyzes historical data, calculates the average return for each period, and displays the results as a histogram with a forecast. It includes customizable parameters: seasonality type, number of bars analyzed, display as percentages or absolute values, chart colors.
preview
Backtracking Search Algorithm (BSA)

Backtracking Search Algorithm (BSA)

What if an optimization algorithm could remember its past journeys and use that memory to find better solutions? BSA does just that – balancing exploration with revisiting the tried and true. In this article, we reveal the secrets of the algorithm. A simple idea, minimum parameters and a stable result.
preview
Market Simulation (Part 22): Getting Started with SQL (V)

Market Simulation (Part 22): Getting Started with SQL (V)

Before you give up and decide to abandon learning SQL, allow me to remind you, dear readers, that here we are still using only the most basic elements. We have not yet looked at some of SQL's capabilities. Once you understand them, you will see that SQL is far more practical than it seems. Although, most likely, we will eventually change the direction of what we are building, because the creation process is dynamic. We will show a little more about creating different things in SQL, because this is truly important and useful for you. Simply thinking that you are more capable than an entire community of programmers and developers will only lead to wasted time and opportunities. Do not worry, because what comes next will be even more interesting.
preview
From Basic to Intermediate: Objects (I)

From Basic to Intermediate: Objects (I)

In this article, we will begin looking at how to work with objects directly on the chart. This is done using code specially developed for demonstration purposes. Working with objects is very interesting and can be a lot of fun. Since this will be our first contact with the topic, we will start with something very simple.
preview
Analyzing Price Time Gaps in MQL5 (Part I): Building a Basic Indicator

Analyzing Price Time Gaps in MQL5 (Part I): Building a Basic Indicator

Time gap analysis helps traders identify potential market reversal points. The article discusses what a time gap is, how to interpret it, and how it can be used to detect large volume influxes into the market.