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.
Building a Viewport SnR Volume Profile Indicator in MQL5
We build a Support and Resistance Volume Profile indicator that adapts to the current viewport in MetaTrader 5. You will learn viewport detection, dynamic SnR identification, zoom‑driven bin sizing, min‑max volume scaling, and fast on‑chart rendering controlled by OnChartEvent. This approach expresses the relative strength of SnR levels with volume, keeping the chart focused on actionable reaction zones.
Feature Engineering for ML (Part 9): Structural Break Tests in Python
We present a production‑ready implementation of AFML Chapter 17 structural break tests. The module includes Chu-Stinchcombe-White (one-/two-sided), Chow-type DFC, SADF across six models (linear, quadratic, sm poly 1, sm poly 2, sm exp, sm power), plus QADF (q, v) and CADF (q), returning bar-indexed scalar features. We address the book snippets' scaling issues and argument‑order pitfall, and show how a fixed lookback (L=504) bounds SADF cost to O(L²) per bar for regime detection.
Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (ACEFormer)
We invite you to explore the ACEFormer architecture — a modern solution that combines the effectiveness of probabilistic attention with adaptive time series decomposition. This article will be useful for those seeking a balance between computational performance and forecast accuracy in financial markets.
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.
Building an Internal and External Market Structure Indicator
The article presents a structured approach to external and internal market structure in MQL5, from swing identification to CHoCH/BoS validation within an established trend. It explains refining true highs/lows, enforcing “first internal signal” logic, and rendering lines, labels, and markers on the chart. The outcome is a consistent indicator that converts price structure into defined entries, stop losses, and 1.5R targets.
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.
Creating an EMA Crossover Forward Simulation (Culmination): Interactive Synthetic Candles
This article finalizes the Forward Simulation Engine for MetaTrader 5 by calibrating synthetic candles to recent market volatility instead of using slope-only sizing. It samples average body, upper wick, and lower wick from closed bars, applies a sine-envelope with decay, proportional wicks, gaps between candles, and periodic counter-trend injections. The result is a live projection that advances one bar ahead, with code you can reuse for calibrated, anchor-based forward rendering and automatic cleanup.
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.
Code, Tears, and Algo Forge
This article discusses the transition to MQL5 Algo Forge as a modern and convenient format for publishing program code and article attachments. Using repositories instead of traditional ZIP archives and source code allows you to keep projects up-to-date, make edits quickly, and professionally interact with your readers. Recommendations are provided for quickly migrating developments to the cloud environment via the MetaEditor interface.
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.
Digital Signal Processing for Traders: Building Ehlers' Filter Library in MQL5
We implement Ehlers-style DSP filters in a single reusable MQL5 library and use it to build two indicators. The Roofing Filter applies a 2‑pole high‑pass followed by a Super Smoother to isolate the tradeable 10–48‑bar band. The Even Better Sinewave normalizes the wave to about ±1, oscillating in cycle regimes and railing in trends, so you can read cycles and detect regime shifts in charts and EAs.
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.
Automating Trading Strategies in MQL5 (Part 49): The Quasimodo (QM) Reversal Pattern
In this article, we build an automated trading program in MQL5 that detects the Quasimodo reversal pattern from a zig-zag of confirmed swing pivots. We work through swing detection, pattern arming, retrace entries at the QM line, and structural stop placement with risk-based sizing. We also add trade management with breakeven, trailing, and partial closing to handle open positions.
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.
Engineering Trading Discipline into Code (Part 8): Building a Setup Confirmation and Trade Authorization Layer in MQL5
This article introduces an MQL5 trade authorization framework built around CDisciplineLayer, CDisciplineGuardian, and CDisciplinePanel. The framework manages setup lifecycles, signal freshness, session restrictions, setup expiry, and global trading locks through a centralized authorization layer. It also provides automated enforcement of violations and a real-time dashboard, enabling consistent trade validation and monitoring before and after execution.
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.
Feature Engineering for ML (Part 8): Entropy Features in MQL5
An MQL5 port of four entropy estimators — Shannon, Plug-In, Lempel-Ziv, and Kontoyiannis — operating on the intrabar tick-rule sequence. CopyTicksRange() limits data to the broker's cached tick window, so features apply to recent bars only. The implementation encodes bid-direction ticks from MqlTick, replaces NumPy-dependent steps with array-based methods, and ships CEntropyFeatures.mqh and EntropyViewer.mq5 for EA and indicator use.
Engineering a Self-Healing Expert Advisor in MQL5 (Part 4): Trade-State Reconciliation and Safe Mode Recovery
This article adds trade-state reconciliation and Safe Mode recovery to a MetaTrader 5 Expert Advisor. The EA continuously validates recovery integrity by comparing the live broker position with the persisted SQLite state and the in-memory runtime state. Detected inconsistencies trigger an automatic transition to Safe Mode, suspending virtual protection, breakeven, and trailing management until the recovery state can be trusted again.
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.
Automating Classic Market Methods in MQL5 (Part 2): Wyckoff Cause and Effect—Point and Figure Price Targets
This article builds a self-contained MQL5 Expert Advisor that completes the Wyckoff cycle: it detects accumulation/distribution with a finite state machine, enters at the last point of support/supply, and calculates exit point-and-figure counts under Wyckoff's Cause and Effect. We detail the box size from range ATR, a 1-box reversal, target validation, and a 2R fallback. Readers get runnable code without external dependencies.
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.
Lazy-Loading Indicator Handles in MQL5: A Resource Manager Pattern for Multi-Timeframe EAs
Multi‑timeframe EAs that initialize every indicator handle in OnInit() pay a fixed startup cost even when most handles are never used. CIndicatorCache applies lazy loading with composite‑key lookup, reference‑counted Acquire/Release, and a deterministic FlushAll() for cleanup. Handles are created on first request and reused across ticks, reducing startup latency, avoiding repeated heap allocation, and preventing terminal resource leaks through centralized ownership.
MetaTrader 5 Machine Learning Blueprint (Part 18): Sequential Bootstrap, Corrected — Clone, Class Erasure, and the Comparison Toolkit
The article diagnoses two defects that neutralize sequential bootstrap during cross‑validation: type erasure of SequentiallyBootstrappedBaggingClassifier and a fold‑level shape mismatch from cloning full samples info sets. It retains the classifier's identity, adds find seq bagging to re‑inject fold‑sliced t1 in CalibratorCV.fit, and resets state per split. A new bootstrap_comparison module reports OOF and OOB metrics and memory, letting you verify that sequential sampling is applied correctly and quantify its impact.
Engineering a Self-Healing Expert Advisor in MQL5 (Part 3): Restart-Aware Breakeven and Trailing Systems
Building on Part 2, the implementation introduces restart-aware breakeven and trailing-stop systems for MetaTrader 5. The EA persists the state, such as breakeven activation, last trailing price, and virtual SL in SQLite, then restores them on startup. This preserves dynamic protection flow and prevents lost progress after terminal interruptions.
Building an Object-Oriented Session VWAP Engine in MQL5
This article shows how to implement a session vwap in MQL5 as a reusable include class with a strict daily reset at broker midnight. The engine computes VWAP and volume‑weighted deviation bands only on closed bars and anchors accumulation with MqlDateTime to avoid distortions from missing candles. A companion indicator plots the baseline and bands, while an Expert Advisor reads signals once per bar for consistent, CPU‑efficient execution and reliable testing.
Feature Engineering for ML (Part 7): Entropy Features in Python
The article provides production-ready entropy estimators (Shannon, plug-in, Lempel–Ziv, Kontoyiannis) operating on tick-rule–encoded sequences. It resolves three correctness and performance issues in the original code, verifies outputs against chapter references, and extends encoding with quantile and sigma options. Users gain reproducible results and markedly improved computation speed for large bar sets.
Forecasting in Trading Using Grey Models
The article discusses the application of Grey models to forecasting financial time series. We will consider the operating principles of Grey models and the specifics of their application to financial series. We will also discuss the advantages and limitations of using these models in trading.
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.
The MQL5 Standard Library Explorer (Part 13): Implementing the Math Solvers Library in Trading
We present a complete workflow for adaptive filtering in MQL5 using the CNlEq Levenberg–Marquardt–like solver. The EA fits a VAMAC model—two EWMAs with an ATR‑based scaling—by supplying residuals and a Jacobian through CNlEq's reverse‑communication loop, with optional numerical or analytical derivatives. Code, setup instructions, and GBPUSD H1 tests show how to replace static thresholds with on‑bar re‑estimation.
Meta-Labeling the Classics (Part 2): Filtering and Sizing ADX Trades
The DI crossover often triggers in ranges where +DI and -DI oscillate without persistence. We build a two-layer hybrid: Optuna's TPE optimizes a regime gate over ADXR threshold, DI lookback, and minimum DI separation to maximize signal precision on a held-out window, then a Random Forest uses eleven ADX-derived features to accept or scale entries via afml.bet_sizing. The result filters ranging-market bursts and calibrates position size on EURUSD H1.
Designing a Strategy State Machine in MQL5: Replacing Nested If-Else Logic with Formal States
Nested if-else logic inside OnTick() creates implicit states that are hard to isolate, debug, and extend without regressions. A formal finite state machine in MQL5 uses an IState interface, a CStrategyContext mediator, and four concrete states to separate detection from behavior. A three-file include structure resolves circular dependencies and keeps declarations, definitions, and instantiation clean, making changes safer and debugging faster.