Articles on data analysis and statistics in MQL5

icon

Articles on mathematical models and laws of probability are interesting for many traders. Mathematics is the basis of technical indicators, and statistics is required to analyze trading results and develop strategies.

Read about the fuzzy logic, digital filters, market profile, Kohonen maps, neural gas and many other tools that can be used for trading.

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
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
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
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
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
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
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
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
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
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
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
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
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.
preview
Dolphin Echolocation Algorithm (DEA)

Dolphin Echolocation Algorithm (DEA)

In this article, we take a closer look at the DEA algorithm, a metaheuristic optimization method inspired by dolphins' unique ability to find prey using echolocation. From mathematical foundations to practical implementation in MQL5, from analysis to comparison with classical algorithms, we will examine in detail why this relatively new method deserves a place in the arsenal of researchers facing optimization problems.
preview
Market Simulation (Part 21): First Steps with SQL (IV)

Market Simulation (Part 21): First Steps with SQL (IV)

Many of you may have far more experience working with databases than I do, and therefore may have a different opinion. Since it was necessary to explain why databases are designed the way they are, and why SQL has the form it does—especially why primary and foreign keys emerged—some things had to remain somewhat abstract.
preview
MQL5 Wizard Techniques you should know (Part 92): Using B-Tree Indexing and a Bayesian NN in a Custom Signal Class

MQL5 Wizard Techniques you should know (Part 92): Using B-Tree Indexing and a Bayesian NN in a Custom Signal Class

In this article we present yet another custom MQL5 Signal Class that we are labelling ‘CSignalBTreeBayesian’. We are marrying the algorithm of a balanced tree with a neural network that is built on Bayesian principles to formulate yet another custom signal testable independently or with other signals thanks to the MQL5 Wizard.
preview
Beyond GARCH (Part IV): Partition Analysis in MQL5

Beyond GARCH (Part IV): Partition Analysis in MQL5

In this article, we shift from Python research to native MQL5 engineering. We build the first module of the MMAR library: a shared constants header, an SVD-based OLS regression class, a Generalized Hurst Exponent estimator, and the partition analysis engine that computes the partition function, extracts tau(q), estimates H via zero-crossing interpolation, and scores multifractality through three diagnostic tests. Tested on 500,000 bars of EURUSD M10, the engine correctly classifies the data as multifractal in under four seconds. Part 4 of an eight-part series. Part 5 fits the tau(q) curve to four candidate distributions via the Legendre transform.
preview
Building Volatility Models in MQL5 (Part III): Implementing the SLSQP Algorithm for Model Estimation

Building Volatility Models in MQL5 (Part III): Implementing the SLSQP Algorithm for Model Estimation

An SLSQP optimizer is implemented in MQL5 to resolve parameter discrepancies between a volatility library and Python's ARCH module. The article details constraint handling, gradient options, configuration, and convergence controls and shows how to integrate the solver into existing code. Practical examples and comparisons demonstrate matched log‑likelihoods and parameters on shared datasets.
preview
Application of the Grey Model in Technical Analysis of Financial Time Series

Application of the Grey Model in Technical Analysis of Financial Time Series

This article explores the grey model, a promising tool that can expand trader's capabilities. We will look at some options for applying this model to technical analysis and building trading strategies.
preview
Joint Recurrence Quantification Analysis (JRQA) in MQL5: Detecting Simultaneous Recurrence in Two Series

Joint Recurrence Quantification Analysis (JRQA) in MQL5: Detecting Simultaneous Recurrence in Two Series

We extend the RQA library for MetaTrader 5 with JRQA, which detects when two series simultaneously revisit their own past states. The article covers the joint recurrence matrix, twelve JRQA metrics (including TREND and COMPLEXITY), dual-epsilon configuration, and a rolling-window engine with OpenCL acceleration and automatic CPU fallback. A practical indicator plots JRR, JDET, JLAM, JENTR, and JTREND for any symbol pair with timestamp alignment and normalization.
preview
Covariance Matrix Adaptation Evolution Strategy (CMA-ES)

Covariance Matrix Adaptation Evolution Strategy (CMA-ES)

The article explores one of the most interesting non-gradient optimization algorithms, which learns to understand the geometry of the objective function. We will focus on the classical implementation of CMA-ES with a slight modification - replacing the normal distribution with the power one. We will thoroughly examine the math behind the algorithm, as well as practical implementation, and check where CMA-ES is unbeatable and where it should be avoided.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 1): Building a Chart Object Detection Engine

How to Detect and Normalize Chart Objects in MQL5 (Part 1): Building a Chart Object Detection Engine

This article addresses the interpretative gap between visual chart objects and algorithmic execution. You will build a systematic detector that iterates over all chart objects, identifies analytical types, and normalises their geometric data (time and price coordinates) into a structured SChartObjectInfo array. The implementation uses raw MQL5 functions, a filter‑extract‑store pipeline, and a timer‑driven test EA, resulting in a reusable framework for rule‑based trading inputs.
preview
Market Microstructure in MQL5 (Part 3): Estimating ARFIMA d with GPH

Market Microstructure in MQL5 (Part 3): Estimating ARFIMA d with GPH

A GPH‑based estimator for d, the key ARFIMA parameter, is added to MicroStructure_Foundation.mqh. GPHEstimator() computes d via log‑periodogram regression, while PopulateARFIMAAnalysis() stores d with an R² confidence score and validates the theoretical relationship H = d + 0.5. An empirical study on 72 US100 M1 sessions confirms pooled d = −0.006, consistent with the random walk boundary established in Part 2.
preview
An Introduction to the Study of Fractal Market Structures Using Machine Learning

An Introduction to the Study of Fractal Market Structures Using Machine Learning

The article attempts to examine financial time series from the perspective of self-similar fractal structures. Since we have too many analogies that confirm the possibility of considering market quotes as self-similar fractals, this allows us to think about the forecasting horizons of such structures.