Extreme Value Theory in MQL5: Building a Tail-Risk Crash Gauge Beyond Monte Carlo VaR
Standard MQL5 risk tools read risk from recent history and miss how heavy the downside tail can be. We implement Extreme Value Theory in MetaTrader 5: a Peaks‑Over‑Threshold fit of the Generalized Pareto Distribution via ALGLIB, a live indicator that reports EVT VaR/ES and tail shape, and an EA that sizes positions from the tail estimate. A controlled backtest illustrates reduced drawdown for unchanged entries.
Market Simulation (Part 23): Position View (I)
The content we will cover from this point on is much more complex in terms of theory and concepts. I will try to make the material as simple as possible. The programming part itself is quite simple and straightforward. But if you do not understand the theory behind it, you will be left with no practical basis at all for refining or adapting the replay/simulation system to tasks different from the ones I am going to show. I do not want you merely to compile and use the code I present. I want you to learn, understand and, if possible, be able to create something even better.
MQL5 Bootstrap (II): Essential Validators for Robust Trading Systems
The article builds a reusable validation layer for Expert Advisors in MQL5. It implements lot-size rules and normalization, SL/TP and freeze-level guards, price digit normalization, margin sufficiency checks, unchanged-level filtering on modifications, account order-limit control, new-bar detection, symbol tradability checks, economic-calendar news windows, and session detectors. The result is cleaner code and fewer terminal errors in live trading.
MQL5 Trading Tools (Part 39): Adding a Pinned-Tools Ribbon for Quick Access to Favorite Tools
We add a pinned-tools ribbon: a floating bar that exposes frequently used tools for one-click access without reopening the sidebar. The article implements the ordered pin set and its API, an anti-aliased pushpin control in the flyout, and the ribbon with offscreen clipping, user-resizable width, and horizontal scrolling. The result is faster activation of favorite tools from a draggable, resizable ribbon on the chart.
Implementing Walk-Forward Efficiency Ratio Scoring in MQL5 to Detect Over-Optimized Strategies
Parameter optimization inside MetaTrader 5's Strategy Tester routinely produces strategies that perform well in-sample and collapse on forward data. This article builds a native MQL5 Walk-Forward Efficiency scoring engine that quantifies how much of a strategy's in-sample Sharpe ratio transfers to each out-of-sample window. The distribution is rendered as a CCanvas histogram and validated against real EURUSD Daily backtest data.
Building a Broker-Agnostic Symbol Resolution Layer in MQL5
We implement a symbol resolution framework that abstracts broker naming differences in MetaTrader 5. Using a persistent mapping store, layered resolution with validation, a hash-indexed registry, and a cache, it returns selectable symbols with live market data and logs unresolved cases. Practically, you can deploy the same EA across brokers and keep symbol access consistent at low runtime cost.
Persistent Homology in MQL5: The Reduction Algorithm and the Persistence Diagram
We complete persistent homology for MQL5 by reducing the Vietoris–Rips boundary matrix to a persistence diagram. The article implements Z/2 column reduction (CTDAReduction), a diagram container with analytics (CTDADiagram), and a facade that runs the six-stage pipeline in one call (CTDA). Outputs are cross-checked against Ripser to numerical agreement, enabling reliable diagram-based metrics.
Detecting and Visualizing Outlier Bars in MQL5 Using Modified Z-Score on OHLCV Features
Abnormal bars inflate mean and standard deviation estimates, distorting ATR, Bollinger Bands, and moving averages. We implement a native MQL5 indicator that detects such bars with the Modified Z-Score applied to four features: body, upper wick, lower wick, and tick volume. The indicator marks flagged bars on the chart and plots a composite score in a separate subwindow, helping you diagnose contamination in rolling-window indicators.
CSV Data Analysis (Part 6): Multi-Broker Result Normalization and Cross-Platform CSV Reconciliation
This article presents a multi‑broker CSV normalization framework. An MQL5 include file enriches exports with broker metadata. A Python module resolves schema divergences — pip conventions, symbol aliases, time offsets, commission models, and currency denomination — producing a unified canonical dataset. Comparative visualizations of slippage distributions and net‑of‑cost performance enable reliable cross‑platform strategy analysis without silent data corruption.
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 4): A Volatility-Adjusted Momentum-Based Intraday System
We present a timer-based MQL5 EA for Opening Range Breakout aligned to NYSE hours. It screens “Stocks in Play” via opening-range relative volume, enforces price/volume/ATR minimums, sizes positions by risk, and exits at 16:00 ET. A Sharpe-ranked optimization across 30 liquid Nasdaq stocks and a single-symbol test are provided, together with backtest settings and an Excel report for verification.
Training a nonlinear U-Transformer on the residuals of a linear autoregressive model
The article presents an innovative hybrid system for forecasting exchange rates that combines a linear autoregressive model with a U-Transformer architecture for residual analysis. The system automatically switches between signal sources depending on their quality and includes complete trading logic with averaging/pyramiding strategies. The key advantage of this approach is that the neural network is trained on the residuals of the linear model, which simplifies the task and reduces the risk of overfitting. The implementation is done entirely in MQL5 and is ready for use in real trading with automatic adaptation to changing market conditions.
Beyond Maximum Drawdown: Building a Drawdown DNA Analyzer in MQL5
Maximum drawdown is one number that hides what really matters: how often an equity curve declines, how long it stays below a previous peak, and how quickly it recovers. This article builds a native MQL5 tool that reconstructs the underwater curve, breaks it into individual drawdown episodes (depth, duration, recovery time), computes the Ulcer Index, Pain Index, and Recovery Factor, and combines them into a single resilience grade with practical recommendations. No external libraries, no Python, no AI.
Building Volatility Models in MQL5 (Part IV): Implementing Long Memory Volatility Processes, FIGARCH, and HARCH
The article delivers MQL5 implementations of FIGARCH and HARCH and updates the volatility library for long‑memory processes. It provides code for Hurst and GPH testing, parameter setup (truncation and horizons), and scripts for fitting, forecasting, and simulations. Readers learn how to apply and compare the models on market data to select an appropriate specification.
Dream Optimization Algorithm (DOA)
A population-based optimization algorithm inspired by a controversial and little-studied phenomenon - the mechanism of human dreams. Agent groups with different "memory", cosine-wave modulation of motion, and an unusual 99/1 phase distribution — learn how these features affect the optimization efficiency of your trading strategies.
MQL5 Wizard Techniques you should know (Part 100): Sliding Window Median and Bidirectional LSTM for a Custom Trailing Stop
CTrailingSlidingMedianBiLSTM is a custom MQL5 Wizard trailing module that combines robust median/MAD outlier filtering with a BiLSTM context score in the range [-1, 1]. Four algorithm modes (standard, bands, RSI, adaptive) target noise, mean-reverting bursts and liquidity spikes, reducing premature stop adjustments. This module is intended for side-by-side evaluation with diverse entry signals and money management settings.
Automatic Session Volume Profile Builder in MQL5: Rendering POC and Value Area Without Third-Party Tools
Implement a session-focused volume profile in MQL5: acquire ticks with CopyTicksRange(), bin prices, and compute POC, VAH, and VAL by the 70% approach. The indicator renders directly on the chart as native objects, supports fixed-width scaling for consistent geometry across timeframes, and refreshes on each new session. This provides objective reference levels without external dependencies.
Duelist Algorithm
What if your trading strategies could learn from each other, like real fighters? Duelist Algorithm is a new optimization method where trading system parameters literally duel for the right to be called the best.
Implementation of the Quantum Reservoir Computing (QRC) circuit
A revolutionary approach to machine learning in trading through quantum computing. The article demonstrates a practical implementation of an adaptive QRC system with continuous retraining for predicting market movements in real time.
Beyond GARCH (Part VII): Monte Carlo Volatility Forecasting in MQL5
We implement the CMonteCarlo module that turns the fitted MMAR parameters into a volatility forecast via Monte Carlo. It runs N independent simulations over a chosen horizon and reports mean, median, standard deviation, and a percentile-based 95% confidence interval, with access to per-run values if needed. Adaptive cascade depth selects the minimal k such that b^k covers the horizon, keeping the run fast and consistent.
Heatmap Visualization of Intraday Return Patterns in MQL5 Using CCanvas
MetaTrader 5 provides no native tool for visualizing intraday return patterns across time dimensions simultaneously. This article implements a custom indicator that aggregates historical bar returns into a 5×24 matrix indexed by weekday and hour of day, then renders the result as a color-interpolated heatmap inside an indicator subwindow using CCanvas. Green cells represent positive average returns, red cells negative, with color intensity encoding return magnitude.
Market Microstructure in MQL5 (Part 7): Regime Classification
We integrate eleven one-minute microstructure measurements from Parts 2–6 into a composite regime label with confidence and direction. A rule-based RegimeClassifier() assigns one of six regimes—Normal, Stressed, Noisy, Informed, Trending, Mean-Reverting—using empirically derived thresholds from 514 NQ M1 sessions (May 2024–May 2026). The deliverable includes MARKET_REGIME, RegimeAnalysis, and PopulateRegimeAnalysis(), enabling position sizing, stop placement, and signal filtering from a single call.
Developing a Neural Network Trading Robot Based on Mamba with Selective State Space Models
The article explores the revolutionary Mamba/SSM neural network architecture for financial time series forecasting. We will consider a complete MQL5 implementation of a modern alternative to Transformer with linear complexity O(N) instead of quadratic O(N²). Selective State Space Models, hardware-aware optimizations, patching techniques, and advanced AdamW training methods are covered in detail. Practical test results showing an increase in accuracy from 62% to 71% while reducing training time from 45 to 8 minutes are included. A ready-made trading EA with auto learning and adaptive risk management for MetaTrader 5 is presented.
Measuring What Matters (Part 1) : Portfolio Risk Decomposition in MQL5
The article establishes a reproducible method to measure portfolio risk for multiple symbols using MQL5 matrices and OpenBLAS. It covers computing log returns, building a covariance matrix, and evaluating wᵀΣw instead of summing individual variances. A complete script prints naive versus true volatility and the cross‑term contribution, enabling you to detect when correlated instruments inflate exposure beyond single‑asset estimates.
Persistent Key-Value Store in MQL5: Using Flat Files as a Lightweight Database for EA State
A lightweight persistence design lets EAs retain counters, flags, and timestamps between terminal restarts. Using only MQL5, CPersistentStore writes a human-readable key=value file in MQL5/Files and serves reads from a CHashMap write-through cache via a typed API. The article analyzes O(1)/O(n) operations, partial‑write risks, and lack of locking, compares with GlobalVariables/SQLite, and provides a demo that reloads state deterministically.
Risk Manager for Trading Robots (Part I): Risk Control Include File for Expert Advisors
Trading is characterized by high demands on risk management discipline. The article presents an analysis of the main reasons for traders' failures and proposes a technical solution in the form of the CEnhancedRiskManager class for the MQL5 platform. It includes practical testing on an aggressive grid EA.
MQL5 Wizard Techniques you should know (Part 99): Using a KD-Tree and an Echo State Network in a Custom Money Management Class
This article lays out 'CMoneyKDTreeESN' custom money management class usable with the MQL5 Wizard, that combines the KD-Tree algorithm and the Echo State Network. We use the KD-Tree on log returns and ATR to give us a risk score, while the ESN tracks recent flow to give us a bounded lot size multiplier. Our class is usable in a variety of Wizard assembled Expert Advisors as shown here with the Envelopes and RSI signals, with a broad objective of modulating exposure in high-volatility and tail-risk environments.
Creating an HTML Dashboard for Strategy Tester and Prop Firm Challenge Analysis in MQL5
This article demonstrates how to build a reusable prop‑firm evaluation module for MQL5 Expert Advisors and export results to an HTML dashboard. The module monitors balance and equity during backtests, simulates single or rolling challenges, checks profit target, daily and overall drawdown, and minimum trading days, then outputs both a terminal summary and a browser‑readable report.
Gaussian Processes in Machine Learning (Part 2): Implementing and Testing a Classification Model in MQL5
In this section, we will look at the implementation of the key interfaces of the library of Gaussian processes in MQL5: IKernel, ILikelihood, and IInference. We will also demonstrate its operation on synthetic data and implement indicators for classification and regression, demonstrating its operation in online mode - with retraining of the model on each new bar.
Linear Regression Prediction Channels in MQL5: Constructing Statistically Grounded Confidence and Prediction Bands
The article implements rolling OLS regression channels in MQL5 and computes confidence and prediction bands with Student's t critical values instead of a fixed standard-deviation multiplier. It explains the leverage-driven widening at window edges, contrasts the result with Bollinger and Donchian channels, and reviews OLS assumptions on price data. A five-line rendering is documented to ensure reliable display in MetaTrader 5.
MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties
We add a tabbed settings window opened from the ribbon and bound to the selected object. The tabs — Style, Text, Coordinates, and Visibility — are built from the same descriptor system, with scrolling, per-level rows, and shared color/width/style popovers. The article covers layout, rendering, interaction, and inline price/time and numeric editing. You get one place to edit every property with live preview and commit-or-discard on close.
From Cloud to Complex: The Vietoris-Rips Filtration in MQL5
We turn a price-embedded point cloud into a Vietoris–Rips filtration and its boundary matrix. The article enumerates vertices, edges, and triangles with filtration values, sorts them in entry order, and builds O(1) vertex/edge lookups. You get MQL5 classes CTDARips and CTDABoundary and a sparse Z/2 boundary suitable for the next-step persistence reduction.
Artificial Atom Algorithm (A3)
The article describes implementation of the A3 algorithm - a metaheuristic optimization method inspired by chemical processes - in MQL5. Only two adjustable parameters, compactness and a small population, ensure high operating speed with sufficient quality of solutions.
Quantum Neural Network in MQL5 (Part III): A Virtual Quantum Processor Based on Qubits
The article focuses on creating a trading system with a real quantum simulator instead of mathematical analogies. The system uses 3 virtual qubits, quantum gates and superposition principles to analyze markets. It is implemented as a trading EA for MetaTrader 5 in MQL5. The main achievement is the transition from simulation to real quantum principles of financial information processing.
MQL5 Wizard Techniques you should know (Part 98): Using an Unscented Kalman Filter and a Capsule Network in a Custom Signal Class
This article presents 'CSignalUKFCapsNet', as a custom class coded in MQL5. This class is meant to be used with the MQL5 Wizard when assembling an Expert Advisor and when selected in the Wizard it defines the Expert Advisor's entry signals. In building this custom class, we brought together the algorithm Unscented Kalman Filter and the Capsule Neural Network. Our algorithm is showcased with four operation modes, and the coding of this as a custom class for the MQL5 Wizard, allows testing with various Trailing Stop methods and Money Management systems.
Encoding Candlestick Patterns (Part 3): Frequency Analysis for Single Candlestick Type Structure
This article introduces a frequency-analysis framework for encoded candlestick patterns in MQL5. By transforming candlesticks into alphabetic symbols, historical price action can be analyzed as a statistical sequence rather than a visual chart. Using GBPUSD and Gold across multiple timeframes, the study examines the occurrence frequency of individual candlestick types, identifies dominant market structures, and reveals the symmetry between bullish and bearish price movements. The results establish a quantitative foundation for pattern discovery and prepare the way for analyzing multi-candlestick sequences and their predictive potential in algorithmic trading systems.
CSV Data Analysis (Part 5): Real-Time CSV Streaming from Live MetaTrader 5 Sessions
This article describes a live data export framework for MetaTrader 5 built around a decoupled, three‑layer design. The MQL5 component batches bar and tick records via a write buffer and rotates CSV files daily; a Python daemon tails the stream, renders a live dashboard, and flags anomaly thresholds. The demo indicator illustrates integration points, enabling real‑time monitoring and auditability during trading sessions.
Market Simulation: Getting Started with SQL in MQL5 (V)
In the previous article, I showed how to proceed in order to add a query mechanism. This was needed so that, inside MQL5 code, you could fully use SQL and retrieve results using an SQL SELECT query. But there is still one last function we need to implement. This is the DatabaseReadBind function. Since understanding it properly requires a slightly more detailed explanation, it was decided to cover it not in the previous article, but in today's article. So, since the topic will be fairly extensive, let us proceed directly to the next section.
Community of Scientists Optimization (CoSO): Practice
We resume the topic of optimization by the scientific community. CoSO should not be viewed as a ready-made solution, but as a promising research platform. With proper development, CoSO can find its niche in tasks where adaptability and resilience to change are important, and computation time is not critical.
Market Microstructure in MQL5 (Part 6): Order Flow
This article adds six order-flow functions and a new OrderFlowAnalysis struct to MicroStructureFoundation.mqh: VPINOHLC, signed flow imbalance, trade intensity versus a 20-session baseline, a late-minus-early smart-money index, flow momentum, and a wrapper that outputs a confidence weight. Flow confidence is gated by noise and jump intensity from Parts 5 and 4. Calibrated on 602 NQ M1 NY sessions, it provides ready-to-use intraday flow signals with documented thresholds.
How to Detect and Normalize Chart Objects in MQL5 (Part 3): Alerting and Automated Trading from Manually Drawn Objects
This article extends the chart‑object detector into a modular monitoring and execution layer. It defines objective interaction rules (touch, cross, breakout) for trendlines, Fibonacci levels, channels, rectangles, and pitchforks, then routes events through an interaction detector, alert manager, and optional trade executor. Orders use object geometry for stop‑loss and take‑profit. The result is a reproducible pipeline that converts static drawings into actionable alerts and, if enabled, trades.