MetaTrader 5 Machine Learning Blueprint (Part 19): Bagging Regimes
MetaTrader 5 Machine Learning Blueprint (Part 19): Bagging Regimes
We test AFML's claim that the sequential bootstrap decorrelates bagged trees on overlapping triple‑barrier labels by isolating two levers: draw count and draw rule. One decision identical tree is bagged under four row‑sampling regimes and evaluated on EURUSD 2022–2023 for draw uniqueness, between‑tree correlation, AUC, and calibration. Decorrelation comes almost entirely from throttling max_samples to average uniqueness; the sequential draw adds little. Out-of-bag inflation is largest under full-count sequential sampling.
Monochronic Trading (Part 1): How to Detect Broker Timezone and DST in MQL5
Monochronic Trading (Part 1): How to Detect Broker Timezone and DST in MQL5
We describe an MQL5 framework that aligns entries with session rhythms and scheduled clock events. A script identifies the broker's time zone and DST by detecting NFP spikes on EURUSD and matching them to EU/US/AU transition dates, producing EA‑ready settings. Session-to-broker time conversion and 15-minute marks constrain execution. A multi‑timeframe AMA signal aggregates trends for strategy selection and optimization.
Foundation Models for Trading (Part I): Porting Kronos to Native MQL5
Foundation Models for Trading (Part I): Porting Kronos to Native MQL5
Kronos is a pretrained transformer that models OHLCV bars the way a language model predicts words. We reimplement its tokenizer/encoder and transformer block in native MQL5, export weights to flat .bin files, and remove Python from runtime entirely. Part 1 delivers preprocessing and BSQ tokenization plus a bit-for-bit verification harness against PyTorch, so you can run the encoder inside MetaTrader 5 with confidence.
Trading Robot Based on a GPT Language Model
Trading Robot Based on a GPT Language Model
The article presents a complete implementation of TimeGPT, a specialized Transformer-based architecture for forecasting financial time series on the MetaTrader 5 platform. Adaptation of the attention mechanism to financial data, selective tokenization of price changes, hardware-aware optimizations, and advanced learning techniques are discussed. Included are practical testing results showing 87% forecast accuracy over a 24-bar horizon with a training time of 15 minutes on the CPU. We also present a ready-made trading EA with automatic retraining.
Exponentially Weighted Covariance Matrix in MQL5: Building an Adaptive Correlation Monitor for Multi-Symbol EAs
Exponentially Weighted Covariance Matrix in MQL5: Building an Adaptive Correlation Monitor for Multi-Symbol EAs
This article builds a constant-memory EW covariance engine and a chart heatmap for monitoring cross-symbol correlations in MQL5. CEWCovariance updates in O(N²) time per bar and exposes covariance/correlation accessors; CHeatmapRenderer shows a five‑symbol matrix with values and colors. You will learn λ-to‑window mapping, how to set a meaningful min_obs warm‑up, and how to size the variance guard epsilon for real FX M1 data.
N-BEATS Network-Based Forex EA
N-BEATS Network-Based Forex EA
Implementation of the N-BEATS architecture for Forex trading in MetaTrader 5 with quantile forecasting and adaptive risk management. The architecture is adapted through bilinear normalization and specialized loss functions for financial data. Backtesting on 2025 data shows inability to generate profits, confirming the gap between theoretical achievements and practical trading performance.
Building an Object-Oriented Order Block Engine in MQL5
Building an Object-Oriented Order Block Engine in MQL5
The article presents a production-oriented Order Block engine for MQL5 packaged as an include class, it validates zones via displacement and market structure break, maintains mitigation state only on closed bars, and avoids heavy copies by passing data by reference. A diagnostic indicator plots zones, and an EA gates logic to new bars for stable performance and reproducible tests.
Encoding Candlestick Patterns (Part 4): Frequency Analysis for Double-Candlestick Structures
Encoding Candlestick Patterns (Part 4): Frequency Analysis for Double-Candlestick Structures
This article extends single-candlestick analysis to ordered double-candlestick patterns using an MQL5 script. The script encodes candles into symbols, extracts every consecutive two-symbol sequence (treating Aa and aA as different), counts occurrences and percentages, and writes sorted frequency tables to a text file. Readers can quickly identify the most recurrent transitions by symbol, timeframe, and lookback for further statistical testing.
Neural network trading EA based on PatchTST
Neural network trading EA based on PatchTST
The article presents the revolutionary architecture of PatchTST, a tailored transformer for financial time series analysis that breaks market data into 16-bar patches for efficient processing. We will discuss the full implementation of a trading robot in MQL5 covering everything from mathematical fundamentals and data structures to a ready-made EA with risk management and continuous learning systems.
Analyzing the Hourly Movement of Trading Symbols and Their Spreads in MetaTrader 5
Analyzing the Hourly Movement of Trading Symbols and Their Spreads in MetaTrader 5
The ProSpread seasonality index indicator with a Moving Average is a technical analysis tool that identifies seasonal patterns in price movements, analyzes price behavior during specific trading hours and is able to work with either a single instrument or a spread between two assets. It also visualizes the statistical probability of directional movements.
MQL5 Trading Tools (Part 40): Adding SQLite Persistence and Per-Timeframe Visibility to the Canvas Drawing Layer
MQL5 Trading Tools (Part 40): Adding SQLite Persistence and Per-Timeframe Visibility to the Canvas Drawing Layer
We add SQLite persistence to the canvas tools, saving every drawing and the entire UI session per symbol, then restoring them on startup so the workspace resumes exactly where you left it. The article builds versioned object serialization, a load/save lifecycle with dirty writes, and a timeframe-visibility editor that drives render-time filtering. The toolkit also runs as an indicator, so it can sit alongside other indicators or an Expert Advisor.
Measuring What Matters (Part 2): Building the Covariance Matrix: Eigenvalue Decomposition and Risk Factor Analysis in MQL5
Measuring What Matters (Part 2): Building the Covariance Matrix: Eigenvalue Decomposition and Risk Factor Analysis in MQL5
In Part 2, we introduce a reusable CCovarianceMatrix class that computes and stores a covariance matrix from raw return series using MQL5's native Cov() method. We verify symmetry, print a labeled matrix grid, and call Eig() to obtain eigenvalues and eigenvectors. Readers see how symbols co-move and which factors drive variance, enabling clearer portfolio diagnostics and reuse in scripts or EAs.
Strategy Configuration via External JSON Files in MQL5: Replacing Input Parameters with a Runtime Config Loader
Strategy Configuration via External JSON Files in MQL5: Replacing Input Parameters with a Runtime Config Loader
The article presents CJsonConfigLoader and a typed SStrategyConfig that move EA inputs to a shared JSON file. A hand-written, quote-aware tokenizer parses a flat object without any DLLs. A hotkey triggers reload so all instances can pick up new lot size, SL/TP, and spread limits without reattaching the EA. On malformed input, the loader falls back to safe defaults and keeps the previous configuration.
OrderSend retries and circuit breaker in MQL5
OrderSend retries and circuit breaker in MQL5
Volatile-market failures such as requotes, connection drops, and partial fills expose a common weakness in EAs: unclassified retries and no cumulative failure control. This article introduces CRetryExecutor with exponential backoff and explicit error classification, plus a three-state CCircuitBreaker with cooldown and half-open probes, unified in CExecutionGateway. You can plug it into an EA to stop futile retries, prevent duplicate submissions, and improve diagnostics.
Beyond GARCH (Part VIII): The MMAR Library And Putting it to Work in an Expert Advisor
Beyond GARCH (Part VIII): The MMAR Library And Putting it to Work in an Expert Advisor
This article finalizes the MMAR project with a CMMAR facade class and a demo Expert Advisor for MetaTrader 5. The facade exposes a compact API—configure, Fit(), Forecast()—that wraps partition analysis, spectrum fitting and Monte Carlo simulation. You will learn how to load data, fit the model and obtain a volatility forecast, with diagnostics and status handling for robust use in EAs.
Building a Divergence System (Part II): Adaptive SuperTrend Custom Indicator
Building a Divergence System (Part II): Adaptive SuperTrend Custom Indicator
The article upgrades SuperTrend by integrating a divergence engine (MPO4 or RSI) the dynamically reduces the ATR multiplier during weakening momentum. It covers the shrinking formula, non-repainting state propagation with dedicated buffers, and a step-by-step MQL5 implementation on the price chart. You will learn how to interpret arrows and line flips, adjust inputs, and apply the indicator for disciplined trailing and earlier confirmations.
Automating Trading Strategies in MQL5 (Part 50): Turtle Soup Liquidity Sweeps
Automating Trading Strategies in MQL5 (Part 50): Turtle Soup Liquidity Sweeps
We build an automated MQL5 program that trades Turtle Soup by fading false breakouts of the N-bar high and low. The article implements liquidity-sweep detection, confirmation closes back inside the level, sweep-depth and extreme-age filters, and an optional reversal-candle body check. It adds configurable dynamic or static stops, two take-profit modes, points-based trailing, and clear chart visuals, providing a ready baseline for backtesting and further customization.
Reimagining Classic Strategies (Part 22): Ensemble Mean Reverting Strategy
Reimagining Classic Strategies (Part 22): Ensemble Mean Reverting Strategy
This article will illustrate to the reader how to implement a mean-reverting strategy for the EURUSD pair. The strategy follows contrarian trading rules. Our strategy implements a weekly moving average channel, with one moving average on the high-price feed and the latter on the low-price feed. We enter short positions when the price falls beneath the low moving average and long positions when the price rises above the high moving average. Additionally, we will export daily market data to build a simple ONNX model of the market to provide an additional filter for our entries. This provides the reader with a reproducible template for strategy development and backtesting.
MQL5 Bootstrap (II): Essential Validators for Robust Trading Systems
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
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.
Building a Broker-Agnostic Symbol Resolution Layer in MQL5
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.
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 4): A Volatility-Adjusted Momentum-Based Intraday System
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.
Feature Engineering for ML (Part 10): Structural Break Tests in MQL5
Feature Engineering for ML (Part 10): Structural Break Tests in MQL5
We port AFML Chapter 17 structural break tests to MQL5 as a single include, CStructuralBreaks, delivering six bar-indexed features for EAs: CSW statistic and critical value, Chow-Type DFC, SADF with a rolling lookback (default 252), SM-Exp, and SM-Power. SADF uses O(L²) rolling windows for real-time viability. A companion StructuralBreaksViewer indicator plots all series with per‑series visibility and optional z‑score normalization. SB_EMPTY marks invalid values for safe integration.
Feature Engineering for ML (Part 9): Structural Break Tests in Python
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.
Creating an EMA Crossover Forward Simulation (Culmination): Interactive Synthetic Candles
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
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.
Beyond GARCH (Part VII): Monte Carlo Volatility Forecasting in MQL5
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
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.
Automating Trading Strategies in MQL5 (Part 49): The Quasimodo (QM) Reversal Pattern
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
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
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.
Feature Engineering for ML (Part 8): Entropy Features in MQL5
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.
Persistent Key-Value Store in MQL5: Using Flat Files as a Lightweight Database for EA State
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.
MQL5 Wizard Techniques you should know (Part 99): Using a KD-Tree and an Echo State Network in a Custom Money Management Class
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.
Lazy-Loading Indicator Handles in MQL5: A Resource Manager Pattern for Multi-Timeframe EAs
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.