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.
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.
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.
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.
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.
Price Action Analysis Toolkit Development (Part 83): Building a Reusable Double-Bottom Pattern Library
This recorder bridges visual labeling and systematic research in MQL5. After you position a rectangle, the EA extracts the candles it spans, derives candle geometry, normalizes OHLC values, assigns an ID, and saves the sample for reuse across sessions. The current category is the double bottom, and the module records the chosen sequence without enforcing a predefined pattern definition.
MiniRocket: A Deterministic Time-Series Classifier and What It Finds in Seven Classic Setups
This article delivers a native MQL5 MiniRocket: 84 fixed convolution kernels yield 9,996 features quickly and deterministically, requiring no training loop and no external runtime. We verify the port against sktime and a float64 reimplementation, then run a reproducible audit of seven classic setups; planted and coin‑flip controls confirm correctness, and a 25%‑flipped control sets the detection threshold.
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.
Symbol Correlation Monitor with Live Heatmap in MQL5
This work delivers an MQL5 Expert Advisor that reads open-position symbols, builds return series, and computes a rolling Pearson correlation matrix, displayed as a CCanvas heatmap. Off-diagonal pairs that meet a warning threshold are bordered for quick scanning. The code details return processing, correlation arithmetic, and matrix indexing, with a verification script, helping you track shifting co-movements across your active book.
Practical Modules from Other Languages in MQL5 (Part 08): MATPLOTLIB
Learn how to bring advanced plotting and data visualization to the MetaTrader 5 terminal by leveraging Matplotlib, one of Python's most powerful and widely used visualization libraries.
Master the Z-Score: Building Mean-Reverting MQL5 Trading Systems
This article explains how to use the Z-Score to quantify price deviations in standard deviations and apply the concept in MQL5. We cover the calculation, interpretation across market regimes, and the implementation of a custom indicator and three trading strategies as Expert Advisors. Readers get complete code examples and a testing workflow, plus practical notes on lookback selection, fat tails, execution timing, and risk controls.
MetaTrader 5 Machine Learning Blueprint (Part 22): Auditing the Selection Criterion — Measuring Overfit in Hyperparameter Search
We show that nested cross-validation removes optimistic evaluation bias but does not stop hyperparameter search from overfitting a finite sample, and we add a diagnostic for when the criterion cannot resolve candidates from noise. We implement OffsetPurgedKFold (boundary-shifted repartitioning), a criterion variance audit (resolution ratio and selection stability), a selection optimization curve, a corrected one-standard-error rule, noise-floor early stopping, and an effective trial count for correlated trials. The result is a dispersion report per candidate and an effective count for the Deflated Sharpe Ratio.
Trade Entry Timing Accuracy Analyzer in MQL5
This article builds an MQL5 dashboard that evaluates entry timing for closed positions using tick‑based Maximum Adverse Excursion (MAE) and Maximum Favorable Excursion (MFE). It computes an entry efficiency ratio, renders an MAE/MFE scatter plot and an efficiency histogram, and prints a concise summary to the Experts tab. Deal grouping, tick‑level excursion logic, and a standalone verification script are included so you can diagnose entry quality across many trades.
Building AI-Powered Trading Systems in MQL5 (Part 12): Giving the Assistant Chart Vision and Tool Access
We give our AI chat assistant two new abilities in MQL5: sight and tool access. It can now capture the chart as a screenshot, attach it to a message, and view it in the panel, and it can call tools that read live positions, trade history, indicator values, chart objects, and the economic calendar. The assistant reasons from what it sees and queries rather than text alone.
Encoding Candlestick Pattern (Part 6): Developing the Encoded Sequence Indicator
An on-chart MQL5 indicator generates a live stream of encoded candlestick symbols and a frequency report for the last N bars. It supports color customization and type filtering, and uses A/a, H/h, E/e, G/g, D, and N/n classifications. Traders can quickly review occurrences and common sequences directly on the chart.
Regime Discovery by Structure: Implementing Toeplitz Inverse Covariance Clustering (TICC)
This article presents a full MQL5 pipeline for Toeplitz Inverse Covariance Clustering: stacked observations, ADMM‑based graphical lasso with block‑Toeplitz constraints, and dynamic‑programming regime assignment. It separates structure from volatility and conditions away the shared USD leg. The fitted regimes are displayed causally as a non-repainting ribbon with a dependency graph for the active state.
Uncertainty as a Model (Part 3): Mathematical Statistics — How to Extract Knowledge from Data
This part of the series examines the mechanisms of the Law of Large Numbers (LLN) and the Central Limit Theorem (CLT) as the theoretical foundation for understanding market patterns. This section describes the tools of descriptive statistics and methods for finding point and interval estimates of distribution parameters. Particular attention is paid to the methodology for testing statistical hypotheses, which makes it possible to objectively distinguish genuine market anomalies from random noise. Each theoretical concept is accompanied by a practical example in the appendix, which helps reinforce the material using specific data.
Time Series Shapelets: Learning a Price Shape, and Testing Whether It Means Anything
We implement a Time Series Shapelet library for MQL5 that finds the subsequence of price history whose z-normalized shape best separates two labels and derives the decision threshold from information gain. Because candidate searches on prices always return a winner, the fit includes a purged hold-out and a calibrated block permutation null. You get a reusable facade and rules you can plot and evaluate against an explicit noise floor.
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.
Swarm Optimizer with Hierarchical Sub-Flocks — Flock by Leader
We are developing and implementing the Flock by Leader algorithm in MQL5: sub-flocks are formed based on the ARF metric, and the leader is determined by the highest personal best rather than by the centroid's position. We present the update formulas for the swarm roles and the separation mechanism. The C_AO_FBL class is compatible with the test bench and has been tested on the Hilly, Forest, and Megacity functions with dimensionalities from 10 to 1000 coordinates, which simplifies reproduction and comparison.
Developing Smart Chart Objects in MQL5 (Part 2): Automating Trendline Discovery and Lifecycle Management
Learn how Smart Trendline Manager separates creation from lifecycle control while handling both manual and auto-generated trendlines. It demonstrates discovery, registration, proximity and touch handling, bounce/break confirmation, post-break resurrection, expiration, and state-driven visualization. This gives you a consistent, configurable way to manage multiple lines through one orchestrated update process.
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.
The Deflated Sharpe Ratio in MQL5: Telling a Real Edge from a Lucky Backtest
A Sharpe ratio read off the best of many optimization runs is not the number it looks like. This article ships a reusable native CDeflatedSharpe class that turns a raw Sharpe into an honest confidence statement. The Probabilistic Sharpe Ratio corrects it for sample length and for skew and kurtosis; the Deflated Sharpe Ratio adds the correction almost nobody applies, for the number of variants you tried before keeping the best. Everything is from scratch, the sample moments, the normal CDF and its inverse included, so there is no Python, no DLL and no library. On a real sweep of 56 moving-average variants on XAUUSD the winner looked significant at 98.5 percent by PSR, then fell to 90.6 percent once the 56 trials were admitted, below the usual bar. That gap is the selection bias, made measurable.
Developing a Quantitative Session Analysis Tool (Part 1): Building a Data-Driven View of Market Sessions
The article presents a session analysis workflow in MQL5 that standardizes sessions as structured data with timing, OHLC, range, net move, and the sequence of extremes. It measures how range builds at 25%, 50%, 75%, and 100% of session duration. The chart shows session markers, a compact comparison panel, and an interactive inspector to review individual occurrences.
Creating and Testing a Council of 15 Models in MetaTrader 5
The article describes the transition from four-voice debates to the Council of Fifteen: ten analysts, four independent risk managers, and a Chair, with strict voting rules. It examines the roles of the participants, the three-phase architecture, and the parallel execution of a full cycle in 10–15 seconds. It shows the operational log, the risk-gate rules, and backward compatibility so you can quickly connect the system to an Expert Advisor.
Markov Chains in Trading and Price Forecasting
In this article, we will examine how to build and apply Markov chains in market conditions: from selecting states and counting transitions to generating forecasts of trajectories and levels. We will also see how Markov chains can be applied to qualitative and quantitative data, ways to account for rare events, and the impact of the forecast horizon. Examples are provided using prices and indicators, as well as an option for evaluating a sequence of trades, with ready-to-use implementations in MQL5.
Win Rate and Edge Ratio Heatmap by Hour and Symbol in MQL5
This MQL5 dashboard aggregates closed deals by symbol and UTC hour, calculates win rate and average reward‑to‑risk, and displays the results as two color‑coded heatmaps. A companion table in the Experts tab highlights the strongest and weakest symbol/hour cells, with an option to require a minimum trade count to reduce noise.
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.
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.
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.
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.
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.
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.
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.
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.
How to Implement Competition Among LLM Agents in MetaTrader 5
The article describes a competitive architecture for MetaTrader 5 in which ten LLM agents, each with different trading rules, manage their own capital and open independent positions using unique magic numbers. The system prompt and the agent's trading aggressiveness are adjusted based on PnL results and the trade streak. A reproducible framework with operating modes and monitored metrics is presented, suitable for testing and further optimization.
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.
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.
Architecture for Collective Trading Decisions by AI Agents
The article describes the architecture of a multi-agent trading system based on the grok-4-fast language model, in which, instead of a single system prompt, four independent analysts with fundamentally different roles operate: a bull, a bear, a risk manager, and an arbiter. Three analysts run in parallel using a ThreadPoolExecutor and, within 3–5 seconds, formulate well-reasoned positions based on the same market data; after that, a deterministic judge renders a final verdict according to strict rules.
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.