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 8): Building an SQLite Strategy Registry from Accumulated CSV Exports

CSV Data Analysis (Part 8): Building an SQLite Strategy Registry from Accumulated CSV Exports

Flat files work well at the start of an MQL5 research pipeline, but they hinder cross-run queries and provenance once the archive grows. We build a Python-based SQLite registry that ingests CSV exports with SHA-1 deduplication, records EA version and run timestamps, applies forward-only schema migrations, and indexes common filters. You get a structured query layer for fast lookups, robustness checks, and version comparisons across all campaigns.
preview
The MQL5 Standard Library Explorer (Part 15): Building a Market-Regime Classifier with dataanalysis.mqh

The MQL5 Standard Library Explorer (Part 15): Building a Market-Regime Classifier with dataanalysis.mqh

This part focuses on practical data analysis in MQL5 with dataanalysis.mqh. We prepare a labeled dataset from bars, apply normalization, explore redundancy with PCA, and train a decision forest to classify future bar regimes. The article shows how to obtain out-of-bag estimates and permutation importance, helping you validate the model and understand which inputs matter most.
preview
Market Simulation: Position View (XI)

Market Simulation: Position View (XI)

In this article, I will show you, dear reader, how to select the objects we create on the chart and modify the position indicator so that it can perform many more functions than originally intended. We will look at how to implement the ability to move price levels and create price lines directly on the chart. Many people may find this difficult. However, you will see that we'll do this with minimal effort. You just need to give it a little thought.
preview
Market Simulation: Position View (VI)

Market Simulation: Position View (VI)

In this article, we will implement a number of improvements to ensure that the position indicator accurately reflects the actual state on the trading server in terms of open positions and their current state. I should point out that the applications shown here are in no way intended to replace any of the elements available in MetaTrader 5. They should also not be used without due caution and a balanced approach, since their purpose is to provide educational code—that is, code intended solely for learning how the system works. The reason I call this code “educational” is that, in some cases, using messages is not the best way to implement certain functions.
preview
Partial Information Decomposition: When Two Indicators Together Say More Than Either Alone

Partial Information Decomposition: When Two Indicators Together Say More Than Either Alone

We introduce a Partial Information Decomposition library for MQL5 that decomposes two sources about a target into four atoms: unique to each, shared, and synergy. The implementation uses quantile binning, tabulated logarithms, and a maximum-entropy fit (for I_ccs), and it pairs results with a block-permutation null because atoms sit above zero on finite samples. Use it to screen indicator pairs and judge significance, including family-wise correction.
preview
Adaptive Position Sizing in MQL5: A Prototype Risk Engine with Generalized Kelly and Bootstrap Calibration

Adaptive Position Sizing in MQL5: A Prototype Risk Engine with Generalized Kelly and Bootstrap Calibration

This article presents a modular position sizing engine for MetaTrader 5 that operates on normalized R-multiples. A layered pipeline combines enriched trade statistics, a generalized Kelly edge estimate, volatility-aware adjustment, Monte Carlo calibration under ruin and drawdown limits, a continuous risk policy, an exposure guard, and a broker-aware lot calculator. The output is a broker-valid lot size with an optional CSV audit trail, providing a transparent prototype for implementing modern risk controls in native MQL5.
preview
Honest Backtesting of Swing Strategies on Index CFDs: Financing Costs, Swap Modes, and What the Strategy Tester Cannot Model

Honest Backtesting of Swing Strategies on Index CFDs: Financing Costs, Swap Modes, and What the Strategy Tester Cannot Model

Financing drives multi‑day index‑CFD results: in one full‑history test, swap consumed 44% of gross profit and all profit on one symbol. We convert swaps to annualized rates, contrast four brokers and two financing models with a read‑only script, and quantify a Strategy Tester issue where a single current swap is used for all history, inflating implied rates by up to seven times. The piece provides a repeatable cost‑audit method.
preview
Expectancy and Trade Quality Score Dashboard in MQL5

Expectancy and Trade Quality Score Dashboard in MQL5

We present an MQL5 script that converts closed trade history into comparable metrics: expectancy in currency, pips, and R-multiples, plus a sample-aware win rate via the Wilson interval. These inputs form a conservative, dimensionless Trade Quality Score. The tool draws a CCanvas panel, prints an Experts-tab report, and supports an hour-based session filter to analyze a defined trading window alongside full-history results.
preview
Defining your Edge (Part 4): Applying Isotonic Regression and PNN Price-Forecasting in an Expert Advisor

Defining your Edge (Part 4): Applying Isotonic Regression and PNN Price-Forecasting in an Expert Advisor

We consider the methods with which Isotonic Regression calibrates raw RSI, Stochastic and price-action signal scores into probabilities that are sorted, while a separate Probability based Neural Network evaluates similar historical market states. This article uses both approaches in a ready-made MQL5 custom signal class that is compatible with MQL5 Wizard and provides up to 7 selectable entry modes. Reproducible tests compare isotonic-only signals with the combined Isotonic-PNN model to assess whether the network adds useful information beyond the simpler baseline.
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
Monte Carlo Simulation and Analysis for MetaTrader 5 Backtest Reports

Monte Carlo Simulation and Analysis for MetaTrader 5 Backtest Reports

This article explains Monte Carlo simulation and analysis for trading and guides you through a Python tool that ingests MetaTrader 5 HTML reports. It generates many randomized equity paths, then summarizes them with max drawdown, bust/profit rates, and percentile envelopes around the mean curve. The workflow helps you assess uncertainty, separate normal behavior from outliers, and size positions accordingly.
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
Development and Forward Testing of an Autonomous LLM Agent for Trading with SEAL

Development and Forward Testing of an Autonomous LLM Agent for Trading with SEAL

A hybrid architecture based on Llama 3.2 and SEAL is being tested on eight currency pairs (M15), with forward-period data isolation and information leakage control. The methodology combines adversarial self-play, curriculum learning, and class balancing to ensure stable training. The experiments confirm the gap between forecast accuracy and actual returns, providing readers with practical guidelines for testing strategies and accurately assessing their generalizability.
preview
The MQL5 Standard Library Explorer (Part 16): Building a Regime-Adaptive Expert Advisor

The MQL5 Standard Library Explorer (Part 16): Building a Regime-Adaptive Expert Advisor

We convert the Part 15 decision‑forest classifier into a regime‑adaptive Expert Advisor that decouples statistical inference from trading authority. The EA trains on completed bars, scores each new completed bar, and confirms stable bullish, neutral, or bearish regimes before acting. It then applies spread, ownership, risk, and execution checks to authorize opening, holding, closing, or blocking a position.
preview
Monte Carlo Simulation and Analysis for MetaTrader 5 Backtest Reports

Monte Carlo Simulation and Analysis for MetaTrader 5 Backtest Reports

This article explains Monte Carlo simulation and analysis for trading and guides you through a Python tool that ingests MetaTrader 5 HTML reports. It generates many randomized equity paths, then summarizes them with max drawdown, bust/profit rates, and percentile envelopes around the mean curve. The workflow helps you assess uncertainty, separate normal behavior from outliers, and size positions accordingly.
preview
The ZeroMQ Message Transfer Protocol in MQL5: Implementing the REQ/REP pattern

The ZeroMQ Message Transfer Protocol in MQL5: Implementing the REQ/REP pattern

This article presents a native MQL5 implementation of the ZeroMQ Message Transfer Protocol (ZMTP) built on raw MQL5 sockets. It explains the REQ/REP pattern via the CZmqReqSocket class, including framing, handshake, and strict send/receive alternation. A practical pipeline shows an MQL5 script streaming returns to a Python/R server running MS‑GARCH and receiving regime probabilities, enabling integration without DLLs.
preview
Defining your Edge (Part 5): Using GARCH Variance and Volatility-Scaled LSTM in an Expert Advisor

Defining your Edge (Part 5): Using GARCH Variance and Volatility-Scaled LSTM in an Expert Advisor

We merge GARCH(1,1) variance projections with ATR plus Bollinger-Bands patterns to form an algorithm that could optionally be used with volatility-scaled LSTM within LSTM Wizard-ready signal class. We cover feature scaling, mode scoring, thresholds, and safety checks. Readers can replicate backtest/forward test results to verify if the recurrent layer gives incremental discrimination over our deterministic baseline.
preview
Market Simulation: Position View (XVII)

Market Simulation: Position View (XVII)

In the previous article, we configured the indicator to display the financial result. However, not everyone likes using this display mode. The reasons differ from one trader to another, although in some cases they seem quite reasonable and justified to me. Adapting the code to provide this capability is by no means one of the most difficult tasks. It's actually pretty simple. In this article, we'll look at how to do this.
preview
Beetle Swarm Optimization (BSO)

Beetle Swarm Optimization (BSO)

We consider a BAS+PSO (BSO) hybrid, where BAS provides a local direction signal and PSO facilitates the exchange of best solutions within the swarm. The article presents a mathematical model, pseudocode, an implementation of the class in MQL5, and test results from a standard test bench. This material allows reproducing the algorithm, configuring its parameters, and understanding how three objective-function evaluations per iteration affect efficiency.