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
Ollivier-Ricci Curvature: Reading the Shape of a Correlation Network, Not Its Level

Ollivier-Ricci Curvature: Reading the Shape of a Correlation Network, Not Its Level

The article builds an Ollivier–Ricci curvature library in MQL5 for multi‑symbol analysis. A basket becomes a correlation network, and the reading captures network geometry rather than correlation level. It includes an exact optimal transport solver with an internal certificate, a rolling fragility metric with two informative nulls, an indicator that plots the reading against its null band, and a demonstration expert that uses it as a risk gate.
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
The Maximal Information Coefficient: Detecting Any Relationship, and the Null That Decides Whether It Is Real

The Maximal Information Coefficient: Detecting Any Relationship, and the Null That Decides Whether It Is Real

This article implements the Maximal Information Coefficient (MINE) for MQL5, including the grid search with dynamic programming and the four MINE statistics. It explains why raw MIC has a nonzero noise floor and builds a permutation null to judge significance. The result is a verified library with a dependence scanner and a chart indicator, allowing you to test features and interpret scores consistently across relationship shapes.
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
Consecutive Loss Streak Analyzer and Risk-of-Ruin Calculator in MQL5

Consecutive Loss Streak Analyzer and Risk-of-Ruin Calculator in MQL5

This article presents an MQL5 script that extracts closed trade history, computes empirical win rate and payoff, and evaluates consecutive-loss probabilities using the geometric tail, plus risk of ruin from edge and position size. It plots a CCanvas ruin curve with a live marker at the chosen risk and prints a probability summary, including the account's worst historical streak in theoretical context.
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
Uncertainty as a Model (Part 5): The Basics of Regression

Uncertainty as a Model (Part 5): The Basics of Regression

A practical introduction to time series regression models: regression on a constant and simple regression with deterministic, exogenous, and endogenous regressors. It describes the key steps in the diagnostic process, including residual analysis and hypothesis testing, that are necessary for making informed trading decisions. MQL5 scripts for MetaTrader 5 are included; they implement tests and plots using real data.
preview
Recovering Option-Implied Probability Distributions Across Four Markets in MQL5

Recovering Option-Implied Probability Distributions Across Four Markets in MQL5

A practical route from the option chain to probability levels inside MetaTrader 5. For GLD, SLV, SPY, and USO, the risk-neutral density implied by each ETF's options is recovered with the Breeden-Litzenberger identity and checked for static arbitrage, after the method itself is validated against an analytic lognormal. A Python feed publishes the percentiles; an MQL5 service rescales them onto a related symbol, draws levels, and alerts when price leaves the risk-neutral 5 to 95 percent band. Every reading carries its own diagnostics, and full source is included.
preview
Monthly Profit and Loss Calendar Heatmap Renderer in MQL5

Monthly Profit and Loss Calendar Heatmap Renderer in MQL5

The article presents an MQL5 script that reads closed deals, groups them by date, and renders a calendar grid for daily P&L and trade count. It explains the data model, normalization to midnight, robust week/weekday mapping, diverging and single-hue color scales, and CCanvas-based drawing, plus a verification script and weekday summary. This helps you quickly locate clusters and quiet periods and cross-check findings with logged totals.
preview
Hyperdimensional Computing: Learning in One Integer Add, and the Nulls That Judge It

Hyperdimensional Computing: Learning in One Integer Add, and the Nulls That Judge It

A complete Hyperdimensional Computing library for MQL5 implements bind, bundle and permute over 4096‑bit hypervectors, graded level ladders for quantities, an encoder for bars and sequences, and a classifier trained by integer addition. It includes a purged, ordered validation split, online updates without refitting, a market scan with two nulls, and a Python reference that reproduces the MQL5 model bit for bit, so you can validate results and deploy a reproducible indicator and test suite.
preview
Online Portfolio Selection: A Provable Regret Bound, and the Cost That Eats It

Online Portfolio Selection: A Provable Regret Bound, and the Cost That Eats It

The article implements Online Portfolio Selection in MQL5: exact simplex projection, four allocators (EG, Universal Portfolio, PAMR, OLMAR), and a BCRP solver on a concave objective. We verify weight paths against the published Python reference and self-check the optimizer. A drift-aware transaction cost model measures turnover and net wealth on a multi-asset basket. Readers get a tested library and evidence on when regret-bounded methods lose to costs.
preview
The MQL5 Standard Library Explorer (Part 17): Building a Reusable Portfolio Manager with CArrayObj

The MQL5 Standard Library Explorer (Part 17): Building a Reusable Portfolio Manager with CArrayObj

We present a multi‑symbol EA structure that moves symbol‑specific state into independently initialized CStrategyNode objects and manages them with CPortfolioManager. Using CArrayObj with FreeMode, Add(), At(), Delete(), Total(), and Clear(), the manager ensures safe ownership and isolation, while timer‑driven routing and completed‑bar gates keep processing deterministic. This lets you scale portfolios, control risk per node, and avoid duplicated event handling.
preview
Online False Discovery Rate Control: Putting an Error Budget on a Live Signal Stream

Online False Discovery Rate Control: Putting an Error Budget on a Live Signal Stream

The article addresses online false discovery rate control for streaming signals, where fixed thresholds inflate noise discoveries. We port LORD3, LORD++ and SAFFRON into MQL5, construct a causal bootstrap p‑value source without a resolution floor, and verify correctness before market data. Dependence stress tests, a budget/level indicator and a two-arm Strategy Tester show how to configure, monitor and throttle streams to keep the acted-on noise fraction within target.
preview
Population-Based Optimization Algorithms: Building a Defense Against Cheaters

Population-Based Optimization Algorithms: Building a Defense Against Cheaters

The algorithms were rerun on the updated functions, and a method was proposed for quickly verifying their "honesty". The composite test combines five different landscapes and eliminates the possibility of gaining an advantage based on the geometry of individual problems, allowing for a quick assessment of the algorithm's actual search capability. A script is provided for preliminary validation of algorithms before they are applied to the optimization of trading strategies.
preview
From Signal to Trade via a Chain of Agents: LangChain Architecture on Top of MQL5

From Signal to Trade via a Chain of Agents: LangChain Architecture on Top of MQL5

The article describes an architecture in which the MQL5 Expert Advisor (EA) handles only data collection and execution, while the logic is moved to a Python server with three LangChain agents: a signal agent, a news agent, and a risk manager. Agents process the WebSocket request sequentially; if any agent rejects it, "hold" is returned. Decisions and actual PnL are stored in SQLite, forming memory and statistics. The reader will receive an interaction diagram, a command protocol, and a feedback approach.
preview
Measuring the Probability of Backtest Overfitting of Your MetaTrader 5 Optimization (Part 1): The CSCV Engine in MQL5

Measuring the Probability of Backtest Overfitting of Your MetaTrader 5 Optimization (Part 1): The CSCV Engine in MQL5

This article implements the Probability of Backtest Overfitting in MQL5 with Combinatorially Symmetric Cross-Validation. It shows how to build the bar-by-bar returns matrix of a parameter grid, aggregate it by blocks and rank the in-sample winner out-of-sample across every split of the history. You get a single probability that this winner ends up in the lower half of the grid out-of-sample, along with the MQL5 code to compute it on your own optimizations.
preview
Fundamentals of Bayesian Inference in Discrete and Continuous Settings: From Theory to Practical Model Implementation

Fundamentals of Bayesian Inference in Discrete and Continuous Settings: From Theory to Practical Model Implementation

The article discusses the fundamentals of Bayesian statistics in both discrete and continuous settings. We will progress from classical Bayes’ theorem and simple examples involving coin flips to conjugate distributions and dynamic Bayesian updating, which enables real-time analysis of market quotes. Using the beta-binomial model as an example, a simple change-point detection indicator has been implemented to help identify shifts in market regimes.
preview
Behavioural Cloning in a Live Trading System: What Live Experience Can and Cannot Teach

Behavioural Cloning in a Live Trading System: What Live Experience Can and Cannot Teach

This article measures a live-to-train behavioral-cloning loop for an RL trading system across 83 models. Outcome-weighted imitation shifted the policy toward Hold (48% → 82%), with 12 final models not trading at all. Live records were instead used to fit spread and slippage to broker fills, revealing execution costs ~85× higher than in simulation. We describe the loop, the failure mechanism, the calibration, and a protocol to apply.
preview
Beyond Squared Returns: Path-Dependent Volatility

Beyond Squared Returns: Path-Dependent Volatility

This article implements a path-dependent volatility model in MQL5 that keeps the sign of returns. The engine uses two-timescale EWMA kernels (four accumulators) to form activity and trend features, with closed-form coefficients and a lightweight kernel search. We provide a calibration workflow and an indicator that plots the decomposition, then test out of sample against EWMA and GARCH on multiple symbols. Results show clear gains on equity indicators and minimal gains on FX.
preview
Bull Optimization Algorithm (BOA)

Bull Optimization Algorithm (BOA)

We present an evolutionary algorithm without a selection operator: the best individual becomes the sole mating partner for the entire population, and classical mutation is replaced by multiplicative mutation with a self-adjusting step size. In this article, we examine three key ideas, implement the algorithm in MQL5 using the C_AO framework, and test it on the standard benchmark suite and in an anti-cheat test — where BOA comes very close to the cutoff for the top 45 but does not make the ranking.