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
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
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
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
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
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
Implementing Session Volume Profile in MQL5

Implementing Session Volume Profile in MQL5

Build a responsive session volume profile indicator in MQL5 from tick data with draggable session bounds and dual anchoring. The article details hash-based bucket aggregation for historical and live ticks, a timer-driven rendering loop with partial updates, automatic or custom bucket sizing, pixel-anchored proportional bars, POC highlighting, and multi‑instance safety—so you can implement, optimize, and run multiple profiles on one chart without UI lag.
preview
Buzzard Optimization Algorithm (BUZOA)

Buzzard Optimization Algorithm (BUZOA)

BUZOA is a population-based metaheuristic algorithm in which each agent randomly selects one of three hunting tactics at each iteration: a narrow search around its personal best, a classic PSO step toward the flock leader, or full teleportation to a random point in the search space. The article examines the implementation of the algorithm in MQL5, identifies a coefficient sign error in the original formulation, and presents benchmark results on a standard test bench.
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
Using Renko-bar Regression with Error Correction

Using Renko-bar Regression with Error Correction

The article presents a regression-based approach to forecasting Renko bars using CatBoost: the model estimates the logarithmic return of the next bar and the uncertainty of the forecast. We will examine a cascade of residual models with OOF validation using TimeSeriesSplit, shrinkage, and overall early stopping, as well as conditional bias correction. On EURUSD D1, a reduction in OOF-MAE was achieved, along with approximately 65% directional accuracy. A working script for MetaTrader 5 is provided that generates a signal, position size, SL, and TP in brick units.
preview
Real-Time Polynomial Regression: A Causal Savitzky-Golay Implementation for MQL5

Real-Time Polynomial Regression: A Causal Savitzky-Golay Implementation for MQL5

We adapt the Savitzky–Golay filter to a strictly causal, real-time form for MQL5 and derive the fixed coefficients for end-point evaluation. The article provides a full indicator and an Expert Advisor, explains the edge-evaluation noise sensitivity, and implements a multi-bar confirmation safeguard. Backtests on several symbols are shown without cherry-picking. You get ready-to-compile code, parameter guidance, and a reduced-lag alternative to moving averages.
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
Benchmark Champions vs. Real-World Optimization Problems

Benchmark Champions vs. Real-World Optimization Problems

We analyze why ratings may be inflated due to the alignment of algorithm trajectories with benchmark diagonals, and we supplement the testing methodology with a requirement to keep the global extremum away from the diagonals. We update Forest and Megacity, and perform RAW verification and calibration using VerifyExtremes.mq5. A drop in HHO and DOAm performance serves as a practical indicator of false leaders.
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
The Kalman Filter for Price Smoothing: An Exact Implementation in MQL5

The Kalman Filter for Price Smoothing: An Exact Implementation in MQL5

This article implements the scalar Kalman Filter for price smoothing in MQL5 using the standard local-level model and the exact prediction–update equations. It explains how process and measurement noise (Q, R) shape the Kalman gain, builds two independently configured filters into a fast/slow crossover, and provides a complete indicator and Expert Advisor that trade a stability-confirmed signal via iCustom, giving a reproducible baseline for testing and tuning.
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
How to Set Up an AI Hedge Fund in MetaTrader 5

How to Set Up an AI Hedge Fund in MetaTrader 5

The article examines the architecture of a committee consisting of 15 AI agents: ten analysts and four risk officers vote in three parallel phases, and the Chair records the final result. Isolated pair contexts with separate reputations are used for eight currency pairs. The dynamic vote threshold depends on the daily PnL targets. The Expert Advisor uses only the signal, SL and TP, which allows for evaluation pf the quality of its decisions without any additional mechanics.
preview
Where your backtest stops being real: Measuring the depth of your broker's tick history

Where your backtest stops being real: Measuring the depth of your broker's tick history

In the "Every tick based on real ticks" mode, the Strategy Tester's journal reports the minutes for which real ticks were absent or discarded and says that every tick generation was used for them. We show where the journal records this, measure how far back usable tick history goes on two demo servers, and check the ticks from inside an Expert Advisor, so a test range can be chosen by its real-tick share.
preview
The Hypothesis of Randomness: Searching for Hidden Patterns in Price Series

The Hypothesis of Randomness: Searching for Hidden Patterns in Price Series

The article describes a test of the hypothesis of randomness for quotes based on a chi-square statistic derived from the frequencies of overlapping s-chains. The article shows how to define discrete states and compare observed and expected frequencies in order to detect Markov memory in price increments. This approach helps distinguish structural dependence from noise and formalize the testing of trading hypotheses.
preview
Nonlinear OHLC Features Derived from Elliptic Curves

Nonlinear OHLC Features Derived from Elliptic Curves

The article discusses the projection of EURUSD daily candlesticks onto the secp256k1 elliptic curve and the extraction of 96 features (EC+TA) to predict the direction of the next candlestick in CatBoost. The price mapping to the curve and the training pipeline on 2,000 D1 bars are shown; the full model achieves a test AUC of 0.6508, with EC features contributing 60.6%. The materials are suitable for reproduction in Python/MetaTrader 5.
preview
Agent Based Market Simulation: Growing a Market From Rules, and Using It to Catch an Overfitted Strategy

Agent Based Market Simulation: Growing a Market From Rules, and Using It to Catch an Overfitted Strategy

A compact MetaTrader 5 library builds a synthetic market from agents: a minority game, a zero‑intelligence double auction, a stylized‑facts analyzer, and a parameter scanner. The result is a testbed with known answers, providing the control real price backtests lack. Each result is cross‑checked by the model's phase transition, a matching Python implementation, and detection of a planted edge.
preview
Adaptive Trade Management in MQL5: Building a Broker-Aware, Deterministic, and Explainable Exit Engine

Adaptive Trade Management in MQL5: Building a Broker-Aware, Deterministic, and Explainable Exit Engine

This article presents an MQL5 trade-management engine that converts exit rules into proposal generators. A policy engine ranks all proposals by a configurable reason priority with documented tie-breakers. A broker-aware validator checks the candidates in that order and falls back to the next one on rejection, and an execution adapter sends the first accepted request. Reconciliation confirms the result on the position before the internal state changes. The engine uses R-multiples for thresholds, persists intratrade state, and records a decision trace for each managed position on every tick.
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
Price Action Analysis Toolkit Development (Part 87): Searching Chart History with Recorded Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 87): Searching Chart History with Recorded Double-Bottom Samples

This stage connects structural validation with reference matching for double bottoms. The Expert Advisor scans completed history, filters pairs by the current structural rules, and compares normalized close and low profiles against validated samples from the library. Results that meet the similarity requirement appear in the panel for chart review and are saved to REFERENCE_MATCHES.csv.
preview
Beyond Tick Volume: Measuring Market Activity from the Waits Between Quotes

Beyond Tick Volume: Measuring Market Activity from the Waits Between Quotes

Tick volume mostly reflects the time of day and is only complete when a bar closes. We build a per‑quote, live activity gauge from the waits between quote changes, remove the intraday rhythm, and model the remainder with the autoregressive conditional duration (ACD) model. We then test whether this activity measure improves short‑horizon volatility forecasts once live price volatility is already in the model.
preview
MetaTrader 5 Machine Learning Blueprint (Part 23): Feature Screening

MetaTrader 5 Machine Learning Blueprint (Part 23): Feature Screening

Permutation tests that assume exchangeable observations miscalibrate feature screens for overlapping financial labels, yielding a tenfold false‑positive inflation on EURUSD. This article implements a calibrated three‑gate pipeline: ADF+KPSS for stationarity, uniform‑grid entropy with modal occupancy, and mutual information corrected via a joint permutation null and Westfall–Young max‑T. The ScreeningReport summarizes gate outcomes and effective test count so you can filter features reliably before fitting models.
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
Implementing an LLM Agent with SQL Memory in MetaTrader 5

Implementing an LLM Agent with SQL Memory in MetaTrader 5

An LLM agent with SQL memory in MetaTrader 5 — an architecture that eliminates the main limitation of traditional LLM Expert Advisors (EAs): the loss of context between queries. Each agent decision is recorded in SQLite along with the market conditions at the time of the signal — RSI, MA alignment, volatility — and after the position is closed, the outcome is written to the database. When the next request comes in, the agent reviews its own history — similar past RSI conditions and the last three agent decisions — and only then analyzes the current market. The result is a system that remembers its errors between restarts and adapts its behavior based on accumulated statistics, rather than starting from scratch with each new bar.
preview
Uncertainty as a Model (Part 4): Random Processes — The Dynamics of Uncertainty

Uncertainty as a Model (Part 4): Random Processes — The Dynamics of Uncertainty

The article introduces the concepts and tools for working with random processes in trading: definitions, characteristics, autocorrelation functions, and a practical classification. The article covers white noise, random walks, Wiener and Poisson processes, as well as Markov chains and martingales. MQL5 scripts demonstrate the generation of sample paths and allow you to simulate equity, highlighting the mathematical limitations of strategies.
preview
Variational Mode Decomposition: Building the Solver, and Measuring What Hindsight Buys

Variational Mode Decomposition: Building the Solver, and Measuring What Hindsight Buys

A from‑scratch VMD library for MetaTrader 5: radix‑2 transform, ADMM updates, mirrored windows, and a result type that reports solve quality and mode separation. We verify the solver to full double precision against a reference and test causality by sabotage. The article quantifies repaint from batch versus causal runs and compares it to volatility‑matched random walks. You get a causal indicator, usable diagnostics, and settings that avoid common pitfalls.
preview
Price Action Analysis Toolkit Development (Part 86): Validating the Entire Sample Library

Price Action Analysis Toolkit Development (Part 86): Validating the Entire Sample Library

This part adds library-wide validation to the double-bottom toolkit. VALIDATE ALL applies the single-sample rule engine to the stored collection, counts its four outcomes and exports a separate CSV report. The report includes settings, sample context and detailed results. Source samples remain unchanged, and export errors are reported separately from completed validation.
preview
Forecast Reconciliation (MinT): One Engine for Timeframe Hierarchies and Currency Graphs

Forecast Reconciliation (MinT): One Engine for Timeframe Hierarchies and Currency Graphs

This article builds forecast reconciliation in pure MQL5 and applies it to two structures: timeframe aggregation on one symbol and a currency graph linked by no‑arbitrage. The engine projects base forecasts onto linear constraints to make them coherent. We benchmark OLS/WLS and MinT with and without shrinkage on long walk‑forward runs, show when total squared error decreases, and measure the cost that may concentrate in a single node.
preview
Surrogate Data Testing: A Null Model for Any Statistic, and Why Shuffling Bars Is Not One

Surrogate Data Testing: A Null Model for Any Statistic, and Why Shuffling Bars Is Not One

We implement surrogate testing for indicators in MQL5: generate synthetic series that match your data's distribution and spectrum, score any statistic, and locate the observation within its null distribution. The library provides four null models, an FFT that handles arbitrary lengths, and a plug‑in interface for custom measures. An indicator visualizes the statistical alongside its chance band for direct interpretation.
preview
Evolutionary Selection of LLM Agents in MetaTrader 5

Evolutionary Selection of LLM Agents in MetaTrader 5

The article describes the architecture of a trading system consisting of 20 Grok (xAI)-based LLM agents, each of which embodies a unique trading philosophy — from pure momentum to a statistical z-score. The system applies a genetic algorithm directly during trading: every 20 trades, it automatically eliminates weak agents, clones strong ones with a prompt mutation, and publishes a leaderboard on the MetaTrader 5 chart — without interrupting trading and without using any SDK.
preview
Price Action Analysis Toolkit Development (Part 85): Visualizing and Reviewing Validated Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 85): Visualizing and Reviewing Validated Double-Bottom Samples

This part adds a visual review layer to the double-bottom workflow. It checks the chart context, moves to the recorded period, and renders the range, two qualifying lows, neckline, classification, score, and the first decisive close. The annotations mirror the validator's indices and prices, helping you audit outcomes without changing sample data.
preview
Does Your EA Depend on Candle Boundaries? A Shifted-Bar Stress Test in MQL5

Does Your EA Depend on Candle Boundaries? A Shifted-Bar Stress Test in MQL5

The framework evaluates boundary sensitivity by rebuilding shifted target-timeframe bars from completed M1 sources and running one Strategy Tester pass for each boundary offset. It includes a ShiftedBarBuilder, a demonstration EA, and a deterministic self-test. An XAUUSD M15 case study reports net profit, Profit Factor, maximum relative equity drawdown, and total trades across all 15 offsets to quantify dependence on the bar grid.
preview
Harris Hawks Optimization (HHO)

Harris Hawks Optimization (HHO)

We implement the Harris Hawks Optimization algorithm in MQL5 and analyze five movement modes of agents controlled by a single parameter — the decaying escape energy E. The C_AO_HHO class is introduced; it is compatible with the unified test bench and features a reproducible implementation of Lévy flight. The algorithm was tested on the Hilly, Forest, and Megacity functions with 5, 25, and 500 coordinates — the results indicate anomalous behavior.
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
Price Action Analysis Toolkit Development (Part 84): Validating Recorded Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 84): Validating Recorded Double-Bottom Samples

This work adds an explainable validation module to the recording toolkit for double bottoms. It finds and filters swing lows, selects the neckline, quantifies depth, low similarity, symmetry and recovery, and assigns a rule-based status and scores accepted pairs. The settings are configurable, the process is reproducible, and the original sample data remains intact for comparison across rule sets.
preview
Foundation Models for Trading (Part III): Running a Generative AI Forecaster Inside MetaTrader 5

Foundation Models for Trading (Part III): Running a Generative AI Forecaster Inside MetaTrader 5

We demonstrate live forecast charting with Kronos in MQL5 and an evaluation pipeline designed to be look‑ahead‑safe. Deterministic dumps are scored per horizon against a random‑walk baseline (15,113 predictions), then fed to a simple Strategy Tester rule on EURUSD H1. The findings show no edge, and illustrate how a high threshold can yield a persuasive but low‑information backtest with very few trades.