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
Rolling Sharpe Ratio with Statistical Significance Bands in MQL5

Rolling Sharpe Ratio with Statistical Significance Bands in MQL5

This article presents a custom MetaTrader 5 indicator that computes a rolling annualized Sharpe ratio and plots configurable z-score significance bands based on Lo's asymptotic standard error. It uses a circular return buffer with incremental variance to keep O(1) updates. We explain the n^(-1/2) uncertainty scaling, the inflation of intervals at high Sharpe values, and how to set per-instrument annualization for correct deployment.
preview
Beyond GARCH (Part VI): Fractional Brownian Motion And The Multiplicative Cascade in MQL5

Beyond GARCH (Part VI): Fractional Brownian Motion And The Multiplicative Cascade in MQL5

This article implements the MMAR Simulation Engine that turns fitted parameters (H, distribution, coefficients, sample volatility) into synthetic price paths. It builds multifractal trading time via a multiplicative cascade, synthesizes fractional Brownian motion with Davies–Harte or Cholesky, scales it to target volatility, and composes the process by time deformation. Readers get a reusable MQL5 class, method choices by path length, and validation steps for scenario testing and Monte Carlo use in the next part.
preview
Market Simulation: Getting Started with SQL in MQL5 (V)

Market Simulation: Getting Started with SQL in MQL5 (V)

In the previous article, I showed how to proceed in order to add a query mechanism. This was needed so that, inside MQL5 code, you could fully use SQL and retrieve results using an SQL SELECT query. But there is still one last function we need to implement. This is the DatabaseReadBind function. Since understanding it properly requires a slightly more detailed explanation, it was decided to cover it not in the previous article, but in today's article. So, since the topic will be fairly extensive, let us proceed directly to the next section.
preview
From Basic to Intermediate: Object Events (II)

From Basic to Intermediate: Object Events (II)

In this article, we will look at how the last three types of events generated by an object work. Understanding this will be very interesting, because in the end we will do something that may seem crazy to many people, but it is entirely possible and produces a very surprising result.
preview
CSV Data Analysis (Part 5): Real-Time CSV Streaming from Live MetaTrader 5 Sessions

CSV Data Analysis (Part 5): Real-Time CSV Streaming from Live MetaTrader 5 Sessions

This article describes a live data export framework for MetaTrader 5 built around a decoupled, three‑layer design. The MQL5 component batches bar and tick records via a write buffer and rotates CSV files daily; a Python daemon tails the stream, renders a live dashboard, and flags anomaly thresholds. The demo indicator illustrates integration points, enabling real‑time monitoring and auditability during trading sessions.
preview
Encoding Candlestick Patterns (Part 3): Frequency Analysis for Single Candlestick Type Structure

Encoding Candlestick Patterns (Part 3): Frequency Analysis for Single Candlestick Type Structure

This article introduces a frequency-analysis framework for encoded candlestick patterns in MQL5. By transforming candlesticks into alphabetic symbols, historical price action can be analyzed as a statistical sequence rather than a visual chart. Using GBPUSD and Gold across multiple timeframes, the study examines the occurrence frequency of individual candlestick types, identifies dominant market structures, and reveals the symmetry between bullish and bearish price movements. The results establish a quantitative foundation for pattern discovery and prepare the way for analyzing multi-candlestick sequences and their predictive potential in algorithmic trading systems.
preview
MQL5 Wizard Techniques you should know (Part 98): Using an Unscented Kalman Filter and a Capsule Network in a Custom Signal Class

MQL5 Wizard Techniques you should know (Part 98): Using an Unscented Kalman Filter and a Capsule Network in a Custom Signal Class

This article presents 'CSignalUKFCapsNet', as a custom class coded in MQL5. This class is meant to be used with the MQL5 Wizard when assembling an Expert Advisor and when selected in the Wizard it defines the Expert Advisor's entry signals. In building this custom class, we brought together the algorithm Unscented Kalman Filter and the Capsule Neural Network. Our algorithm is showcased with four operation modes, and the coding of this as a custom class for the MQL5 Wizard, allows testing with various Trailing Stop methods and Money Management systems.
preview
Quantum Neural Network in MQL5 (Part III): A Virtual Quantum Processor Based on Qubits

Quantum Neural Network in MQL5 (Part III): A Virtual Quantum Processor Based on Qubits

The article focuses on creating a trading system with a real quantum simulator instead of mathematical analogies. The system uses 3 virtual qubits, quantum gates and superposition principles to analyze markets. It is implemented as a trading EA for MetaTrader 5 in MQL5. The main achievement is the transition from simulation to real quantum principles of financial information processing.
preview
CSV Data Analysis (Part 5): Real-Time CSV Streaming from Live MetaTrader 5 Sessions

CSV Data Analysis (Part 5): Real-Time CSV Streaming from Live MetaTrader 5 Sessions

This article describes a live data export framework for MetaTrader 5 built around a decoupled, three‑layer design. The MQL5 component batches bar and tick records via a write buffer and rotates CSV files daily; a Python daemon tails the stream, renders a live dashboard, and flags anomaly thresholds. The demo indicator illustrates integration points, enabling real‑time monitoring and auditability during trading sessions.
preview
MQL5 Wizard Techniques you should know (Part 98): Using an Unscented Kalman Filter and a Capsule Network in a Custom Signal Class

MQL5 Wizard Techniques you should know (Part 98): Using an Unscented Kalman Filter and a Capsule Network in a Custom Signal Class

This article presents 'CSignalUKFCapsNet', as a custom class coded in MQL5. This class is meant to be used with the MQL5 Wizard when assembling an Expert Advisor and when selected in the Wizard it defines the Expert Advisor's entry signals. In building this custom class, we brought together the algorithm Unscented Kalman Filter and the Capsule Neural Network. Our algorithm is showcased with four operation modes, and the coding of this as a custom class for the MQL5 Wizard, allows testing with various Trailing Stop methods and Money Management systems.
preview
Artificial Atom Algorithm (A3)

Artificial Atom Algorithm (A3)

The article describes implementation of the A3 algorithm - a metaheuristic optimization method inspired by chemical processes - in MQL5. Only two adjustable parameters, compactness and a small population, ensure high operating speed with sufficient quality of solutions.
preview
Interactive Supply and Demand Zone Manager in MQL5 (Part II): Event-Driven Architecture and Persistent Lifecycle Logging

Interactive Supply and Demand Zone Manager in MQL5 (Part II): Event-Driven Architecture and Persistent Lifecycle Logging

This article advances the stateful supply and demand zone framework for MetaTrader 5 by replacing polling with an event-driven model based on OnChartEvent(). We split synchronization into dedicated handlers for creation, modification, and deletion, and separate market logic in OnTick() from user interactions in OnChartEvent(). A persistent, append-only CSV logger records all lifecycle events, improving responsiveness, state consistency, and recoverable history for downstream analysis.
preview
MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties

MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties

We add a tabbed settings window opened from the ribbon and bound to the selected object. The tabs — Style, Text, Coordinates, and Visibility — are built from the same descriptor system, with scrolling, per-level rows, and shared color/width/style popovers. The article covers layout, rendering, interaction, and inline price/time and numeric editing. You get one place to edit every property with live preview and commit-or-discard on close.
preview
Designing a Strategy State Machine in MQL5: Replacing Nested If-Else Logic with Formal States

Designing a Strategy State Machine in MQL5: Replacing Nested If-Else Logic with Formal States

Nested if-else logic inside OnTick() creates implicit states that are hard to isolate, debug, and extend without regressions. A formal finite state machine in MQL5 uses an IState interface, a CStrategyContext mediator, and four concrete states to separate detection from behavior. A three-file include structure resolves circular dependencies and keeps declarations, definitions, and instantiation clean, making changes safer and debugging faster.
preview
From Cloud to Complex: The Vietoris-Rips Filtration in MQL5

From Cloud to Complex: The Vietoris-Rips Filtration in MQL5

We turn a price-embedded point cloud into a Vietoris–Rips filtration and its boundary matrix. The article enumerates vertices, edges, and triangles with filtration values, sorts them in entry order, and builds O(1) vertex/edge lookups. You get MQL5 classes CTDARips and CTDABoundary and a sparse Z/2 boundary suitable for the next-step persistence reduction.
preview
Meta-Labeling the Classics (Part 2): Filtering and Sizing ADX Trades

Meta-Labeling the Classics (Part 2): Filtering and Sizing ADX Trades

The DI crossover often triggers in ranges where +DI and -DI oscillate without persistence. We build a two-layer hybrid: Optuna's TPE optimizes a regime gate over ADXR threshold, DI lookback, and minimum DI separation to maximize signal precision on a held-out window, then a Random Forest uses eleven ADX-derived features to accept or scale entries via afml.bet_sizing. The result filters ranging-market bursts and calibrates position size on EURUSD H1.
preview
The MQL5 Standard Library Explorer (Part 13): Implementing the Math Solvers Library in Trading

The MQL5 Standard Library Explorer (Part 13): Implementing the Math Solvers Library in Trading

We present a complete workflow for adaptive filtering in MQL5 using the CNlEq Levenberg–Marquardt–like solver. The EA fits a VAMAC model—two EWMAs with an ATR‑based scaling—by supplying residuals and a Jacobian through CNlEq's reverse‑communication loop, with optional numerical or analytical derivatives. Code, setup instructions, and GBPUSD H1 tests show how to replace static thresholds with on‑bar re‑estimation.
preview
Linear Regression Prediction Channels in MQL5: Constructing Statistically Grounded Confidence and Prediction Bands

Linear Regression Prediction Channels in MQL5: Constructing Statistically Grounded Confidence and Prediction Bands

The article implements rolling OLS regression channels in MQL5 and computes confidence and prediction bands with Student's t critical values instead of a fixed standard-deviation multiplier. It explains the leverage-driven widening at window edges, contrasts the result with Bollinger and Donchian channels, and reviews OLS assumptions on price data. A five-line rendering is documented to ensure reliable display in MetaTrader 5.
preview
Gaussian Processes in Machine Learning (Part 2): Implementing and Testing a Classification Model in MQL5

Gaussian Processes in Machine Learning (Part 2): Implementing and Testing a Classification Model in MQL5

In this section, we will look at the implementation of the key interfaces of the library of Gaussian processes in MQL5: IKernel, ILikelihood, and IInference. We will also demonstrate its operation on synthetic data and implement indicators for classification and regression, demonstrating its operation in online mode - with retraining of the model on each new bar.