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
Building a Neural Loss-Pattern Auditor in MQL5

Building a Neural Loss-Pattern Auditor in MQL5

Aggregate metrics like win rate or profit factor miss sequence-dependent behavior, such as sizing up right after a loss. This MQL5 script trains a small native neural network on closed-deal history to estimate loss probability from behavioral and market-context features. It reports accuracy uplift over a baseline, probability calibration, and permutation feature importance, then combines them into a configurable A-F grade with concise, plain-language recommendations.
preview
Market Simulation: Position View (XVI)

Market Simulation: Position View (XVI)

In this article, we will make the necessary changes so that the position indicator displays the financial result. This way, the trader will be able to get an idea of the financial result of an open position. In addition, I will tell you something that many people do not know, even those who have been using MQL5 for a long time: how to use static variables to share memory and avoid declaring a global variable in the main code.
preview
Market Replay: Unity Is Strength (II)

Market Replay: Unity Is Strength (II)

Until now, the application being developed as part of this series of articles has focused exclusively on simulating the graphical part. However, to obtain a more complete system in which we can test the Expert Advisor within the replay/simulation service, we also need to simulate the trading server. You'll notice that this simulation will include only the most essential elements. Nevertheless, you, dear reader, will be able to fill in the missing parts. Since these additional components don't affect what I want to show, we already have more than enough to implement what we have in mind.
preview
Measuring What Matters (Part 4): Reading the Spectrum — What Eigenvalues Tell You About Risk

Measuring What Matters (Part 4): Reading the Spectrum — What Eigenvalues Tell You About Risk

We turn eigenvalues from a covariance matrix into a normalized spectral‑entropy score that measures how evenly variance is spread across factors. SpectralEntropyCalculator.mq5 compares two portfolios in one run, using native vector summation, ArraySort()-based ordering, element‑wise division, and the Shannon entropy formula. The report makes dominant factors visible and enables quick, repeatable checks of diversification quality.
preview
Market Simulation: Position View (XIX)

Market Simulation: Position View (XIX)

One of the issues that bothered me the most was that the `C_ElementsTrade` class contains code for accessing positions. Don't take this as a mistake, because it really isn't one. However, this increases the risk of errors in some of the tasks we will need to handle later. All work on implementing the position indicator was carried out with a view to its use in the replay/simulation service. However, when running in this environment, we will have no access to actual positions. Consequently, any call to the MQL5 library intended to retrieve position data will have no effect in this environment.
preview
Market Simulation: Unity Is Strength (III)

Market Simulation: Unity Is Strength (III)

In this article, I will present our system for simulating market operations. Although everything is practically finished, there are still a few things to implement and a few changes to make. However, I have to admit that, after everything we've already developed, I'm tired of still being stuck on implementing this system.
preview
Testing for Residual Autocorrelation with the Ljung-Box Portmanteau Test in MQL5

Testing for Residual Autocorrelation with the Ljung-Box Portmanteau Test in MQL5

A complete MQL5 implementation of the Ljung-Box test helps verify independence in trading data and fitted-model residuals. It computes sample autocorrelations, the Q statistic over selected horizons, degrees of freedom with user-controlled adjustments, and right-tail p-values via the regularized incomplete gamma function. Run it on returns, deal outcomes, or external residuals and review decisions directly in the Experts tab.
preview
From Deal History to Hazard Curves: Survival Analysis Applied To Strategies

From Deal History to Hazard Curves: Survival Analysis Applied To Strategies

This article reframes performance from unconditional win rate to conditional probability given survival time. It introduces an MQL5 library, an on‑chart indicator, and a demo Expert Advisor that read deal history, fit Kaplan–Meier and Aalen–Johansen curves with competing risks, and report forward probabilities over a bar‑based horizon. Readers gain a reproducible way to quantify the chance that the current position reaches its target or stop, and to see the bias of the naive censoring approach.
preview
Profit Factor Stability Chart Across Rolling Windows in MQL5

Profit Factor Stability Chart Across Rolling Windows in MQL5

A modular MQL5 toolkit computes and visualizes rolling Profit Factor over fixed trade-count windows. It presents the statistical motivation, an incremental algorithm that avoids recomputation, and a dedicated CCanvas rendering pipeline. The dashboard adds reference lines, shading for weak periods, and summary metrics, while a separate test suite validates the math, giving a practical way to monitor stability and detect deterioration in strategy behavior.
preview
Market Replay: Unity Is Strength (I)

Market Replay: Unity Is Strength (I)

We're entering the home stretch. The development of the replay/simulation system is nearly complete. Of course, we still have a few things left to finish, but compared to everything we've already done, completing what's left won't be difficult. However, it is essential to fully absorb and understand everything covered in this article. So I hope you enjoy reading this and, above all, that you enjoy this final stage of the journey.
preview
Market Microstructure in MQL5 (Part 9): Pullback Quality

Market Microstructure in MQL5 (Part 9): Pullback Quality

Part 9 adds a second measurement layer to Part 8's micro‑trend signal: pullback quality. It maps Fibonacci retracement depth to a six‑level PULLBACK QUALITY label, adds an H1 range position from a 60‑bar rolling proxy, and uses lag‑1 momentum autocorrelation. These inputs form a single composite entry‑quality score in [0,1] for filtering setups and sizing trades within MicroStructure_Foundation.mqh.
preview
Did Your Scale Outs Actually Help? A Scale Out Value Analyzer in MQL5

Did Your Scale Outs Actually Help? A Scale Out Value Analyzer in MQL5

The article presents an MQL5 tool that tests whether scaling out improved results rather than only appearing disciplined. It reconstructs positions from closing-deal history and reprices the full volume at the first, last, and best exit rates actually achieved, producing a Value-Add Ratio, a Scale-Out Win Rate, and an Efficiency measure. A single-trade dependence check and a configurable A+ to F grade turn these into clear, decision-ready feedback.
preview
Money Management in MQL5 (Part 1): Kelly Position Sizing from the Strategy's Own Edge

Money Management in MQL5 (Part 1): Kelly Position Sizing from the Strategy's Own Edge

This article applies the Kelly criterion to position sizing in native MQL5. It presents a reusable CKelly class that estimates win rate and payoff from closed deals, derives the Kelly fraction, and sizes lots from a stop distance. A Monte Carlo sweep of the Kelly multiplier shows growth peaking at full Kelly while drawdown and ruin increase, motivating fractional Kelly such as half Kelly that preserves most growth with materially lower drawdown.
preview
Building Volatility Models in MQL5: Implementing the APARCH Volatility Process

Building Volatility Models in MQL5: Implementing the APARCH Volatility Process

The article introduces the APARCH volatility process to the MQL5 library via the CAparchProcess class, estimating the power exponent (delta) jointly with other parameters. It details the recursion, parameter bounds, stationarity constraints, and starting values and reports SLSQP solver updates that streamline optimization. Implementation correctness is partially validated by reproducing approximations of GARCH and GJR-GARCH conditional volatility under parameter restrictions. A companion APARCH indicator visualizes conditional volatility, standardized residuals, and delta to track volatility dynamics and parameter drift.
preview
Self-Exciting Markets: Building a Hawkes Process from Scratch

Self-Exciting Markets: Building a Hawkes Process from Scratch

Volatility arrives in clusters: one large move makes the next large move more likely, and quiet spells stay quiet. This article builds a Hawkes self-exciting point process in pure MQL5 to measure that effect directly, ending in a single number, the branching ratio, that says how reflexive a market currently is. You get a small, tested library, an indicator that plots the fitted intensity live, and a demonstration Expert Advisor, along with the honest limits of all three.
preview
Intrinsic Time: From the Directional-Change Scaling Laws to the Alpha Engine

Intrinsic Time: From the Directional-Change Scaling Laws to the Alpha Engine

The article implements intrinsic-time analysis in MQL5: an event-based directional-change operator that splits ticks into directional-change and overshoot sections. We reproduce the core scaling laws on 17.8 million live EUR/USD ticks and compare them to a random-walk baseline. Finally, we build a hedging-account Expert Advisor that trades the Alpha Engine with limit orders, detailing thresholds, inventory skew, and liquidity control for practical reuse.
preview
Building Volatility Models in MQL5: Implementing the APARCH Volatility Process

Building Volatility Models in MQL5: Implementing the APARCH Volatility Process

The article introduces the APARCH volatility process to the MQL5 library via the CAparchProcess class, estimating the power exponent (delta) jointly with other parameters. It details the recursion, parameter bounds, stationarity constraints, and starting values and reports SLSQP solver updates that streamline optimization. Implementation correctness is partially validated by reproducing approximations of GARCH and GJR-GARCH conditional volatility under parameter restrictions. A companion APARCH indicator visualizes conditional volatility, standardized residuals, and delta to track volatility dynamics and parameter drift.
preview
Implementing and Comparing Five Historical Volatility Estimators in MQL5

Implementing and Comparing Five Historical Volatility Estimators in MQL5

The study implements five historical-variance estimators in MQL5 and evaluates their one-session-ahead persistence forecasts for EURUSD D1 sessions using an M1 realized-variance proxy. Deterministic tests cover formulas, chronological order, and target construction. A configurable indicator, comparison scripts, and CSV outputs provide reproducible losses, calibration diagnostics, a common‑target mask, and sensitivity to the estimation window.
preview
Uncertainty as a Model (Part 2): Dependence Among Random Variables — From Correlation to Copulas

Uncertainty as a Model (Part 2): Dependence Among Random Variables — From Correlation to Copulas

The second part of the series examines the mathematical framework for multivariate random variables, which is necessary for analyzing the dependence and joint behavior of market assets. This section describes joint distribution functions, the concepts of marginal and conditional distributions, and the conditions for dependence and independence of variables. The theoretical material is based on extending the analogy between probability and mass to multidimensional space. Particular attention is given to measures of association: from classical linear covariance and correlation to modern tools such as copulas and Shannon mutual information.
preview
Symbolic Fourier Approximation in MQL5: Benchmarking SFA Against SAX

Symbolic Fourier Approximation in MQL5: Benchmarking SFA Against SAX

We implement Symbolic Fourier Approximation in MQL5 and compare it to SAX under a shared harness on identical price windows. SFA keeps low‑frequency Fourier coefficients and learns per‑position bins (MCB), with a proven, sound lower bound. The measurements show how the same bit budget behaves under different splits of word length and alphabet, and give a practical rule for choosing settings for your symbol.
preview
Trade Duration vs Profitability Scatter Plot Indicator in MQL5

Trade Duration vs Profitability Scatter Plot Indicator in MQL5

The article presents a compact dashboard that relates trade duration to net profit using MQL5 and CCanvas. It pulls closed deals, derives duration in minutes, and renders a log‑scaled scatter by symbol, with an overlaid least‑squares line and R². A bucketed duration view identifies which hold‑time range produced the highest average result, helping assess exit timing.