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
CSV Data Analysis (Part 3): Engineering a Python Analytics Pipeline for MetaTrader 5 CSV Exports

CSV Data Analysis (Part 3): Engineering a Python Analytics Pipeline for MetaTrader 5 CSV Exports

MetaTrader 5 provides rich performance data but limited structural analysis. This article shows how to export results to CSV from MQL5 and build five Python visualizations that expose cross-asset parameter consistency, the lag‑versus‑noise trade-off, walk‑forward decay, drawdown depth and duration, and intraday hour‑by‑day clusters. A unified automation module runs the full pipeline on any new export to deliver repeatable diagnostics.
preview
MQL5 Wizard Techniques you should know (Part 95): Using Disjoint Set Union and Deep Belief Network in a Custom Signal Class

MQL5 Wizard Techniques you should know (Part 95): Using Disjoint Set Union and Deep Belief Network in a Custom Signal Class

For this article we switch to a custom MQL5 Wizard class that examines entry Signals. Our custom class is ‘CSignalDSUDBN’ this time around, and is coded by combining the Disjoint Set Union algorithm with a Deep Belief network. As has been the case throughout these series, our model is testable with MQL5 Wizard-Assembled Expert Advisors that can be tuned with different trailing stops and money management classes.
preview
Implementing a Fluent Interface Builder Pattern for MQL5 Order Construction

Implementing a Fluent Interface Builder Pattern for MQL5 Order Construction

Manual population of MqlTradeRequest leaves cross-field rules unchecked, creating silent misconfigurations at execution time. A fluent COrderBuilder for MQL5 adds pointer-based method chaining, per-field validation, and directional SL/TP checks against broker stop‑level constraints. Its Send() method runs a four-stage gate—flag completeness, cross-field consistency, OrderCheck(), then OrderSend()—so configuration errors are caught early and order code stays clear and reusable.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 2): Restart-Safe Virtual Trade Protection

Engineering a Self-Healing Expert Advisor in MQL5 (Part 2): Restart-Safe Virtual Trade Protection

Build a restart-aware virtual protection layer on top of the SQLite persistence from Part 1. The EA reconstructs hidden stop-loss and take-profit after restart, verifies current price against recovered exits, and closes or continues positions accordingly. The result is a consistent recovery path that detects managed positions and sustains safe runtime management.
preview
Building a Type-Safe Event Bus in MQL5: Decoupling EA Components Without Global Variables

Building a Type-Safe Event Bus in MQL5: Decoupling EA Components Without Global Variables

A typed publish-subscribe event bus in MQL5 replaces global variables and direct cross-references. Using an abstract listener interface and an enum-indexed subscription table, a signal engine, order manager, and drawdown monitor communicate only through the bus, with no shared state. The article analyzes dispatch overhead, pointer validation, and recursive publish risks, helping you design decoupled, testable EAs.
preview
Extremal Optimization (EO)

Extremal Optimization (EO)

The article discusses the Extremal Optimization (EO) algorithm, an optimization method inspired by the Bak-Sneppen self-organized criticality model, where evolution occurs through the elimination of the worst-case components of the system. The modified population version of the algorithm demonstrates a shift away from theoretical principles in favor of practical efficiency, leading to the creation of powerful computational tools.
preview
Neural Networks in Trading: Actor—Director—Critic

Neural Networks in Trading: Actor—Director—Critic

We invite you to explore the Actor-Director-Critic framework, which combines hierarchical learning and a multi-component architecture for creating adaptive trading strategies. In this article, we take a detailed look at how using the Director to classify the Actor's actions helps to effectively optimize trading decisions and improve the robustness of models in financial market conditions.
preview
Implementing Partial Position Closing in MQL5

Implementing Partial Position Closing in MQL5

This article develops a class for managing partial position closing in MQL5 and then integrates it into an Order Blocks Expert Advisor. It also presents test results comparing the strategy with and without partial position closing, and analyzes the conditions under which this approach can help provide and maximize profit. In conclusion, partial position closing can be highly beneficial in trading strategies, especially those focused on wider price movements.
preview
Neural Networks in Trading: Skill Hierarchy for Adaptive Agent Behavior (Final Part)

Neural Networks in Trading: Skill Hierarchy for Adaptive Agent Behavior (Final Part)

The article discusses the practical implementation of the HiSSD framework in algorithmic trading tasks. It explains how the skill hierarchy and adaptive architecture can be used to build sustainable trading strategies.
preview
Custom Debugging and Profiling Tools for MQL5 Development (Part III): Regression Gates for Performance and Trading Rules

Custom Debugging and Profiling Tools for MQL5 Development (Part III): Regression Gates for Performance and Trading Rules

This article adds a regression gate to the MQL5 debugging and profiling workflow. It keeps the Part II profiler, TestLite runner, and trading math helper as contracts, then compares current profiler evidence with an accepted baseline. The workflow also adds symbol-aware assertions, compact status files, and report tables so performance drift, missing tests, and broker-assumption problems are visible before a build is accepted.
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.