RSI Divergence Grid Expert Advisor with Risk Manager in MQL5
A simple grid trading strategy becomes a resilient system thanks to three components: an entry filter based on RSI divergence, a strict limit on the number of grid levels, and an independent risk manager that monitors equity on every tick and blocks trading when the daily limit or maximum drawdown is reached. The article examines the mathematics behind the classic martingale trap, the implementation of pivot point and RSI divergence detection in MQL5, the complete code for the CRiskManager class with protection against floating losses, and the architecture of the grid itself, with TP based on the weighted average entry price.
Self-Optimizing Expert Advisors in MQL5 (Part 20): Causality Regularization With Time-Lagged Independent Components Analysis (3)
The article presents a piecewise workflow that forecasts growth in ICA components as surrogate targets and then reconstructs smoothed returns from these forecasts. We analyze dominant-component effects and apply Shapley Additive Explanations to assess feature importance. The approach is implemented end to end, from data preparation to ONNX export and MQL5 integration, providing a practical pipeline for noise reduction and model interpretability.
Markowitz Mean-Variance Optimization for MQL5: A Native Efficient-Frontier Portfolio Builder
This article shows how to implement a native MQL5 portfolio optimizer for multi-symbol baskets. It derives a covariance matrix from bar log-returns, inverts it via Gauss–Jordan, and solves the global minimum-variance, tangency, and target-return portfolios without external libraries. You will build an EA that rebalances positions long-only with clip-and-renormalize and a read‑only dashboard that tracks drift versus targets, plus learn Strategy Tester setup and common pitfalls.
Neural Networks in Trading: Recurrent Modeling of Market Micromovements (Encoder)
The article takes readers deep into the heart of the EV-MGRFlowNet framework, showing how its architecture is applied in a practical implementation for financial forecasting tasks. Step by step, we build a carefully designed combination of modules capable of detecting subtle temporal patterns and translating them into meaningful market signals.
From Basic to Intermediate: Subwindows (II)
This article examines the use of subwindows in MetaTrader 5 in detail and shows how the calculation direction in OnCalculate affects indicator buffers and the plotting of averages. Practical examples explain how indicators are linked using FIRST INDICATOR’S DATA and PREVIOUS INDICATOR’S DATA, the effect of cascading removal of dependent indicators, and how indicator_separate_window behaves. Readers will learn how to diagnose display issues and create indicators that work correctly in subwindows.
Testing Random Walk vs Mean Reversion in MQL5: Implementing the Lo-MacKinlay Variance Ratio Test
Implements the Lo–MacKinlay Variance Ratio Test in MQL5 to assess serial dependence via random‑walk variance scaling. Provides a reusable CVarianceRatio class with classical (homoskedasticity) and heteroskedasticity‑robust statistics, plus a script that scans multiple horizons and logs VR and Z‑values. Shows how to embed the test in an Expert Advisor as a statistical gate for mean‑reversion logic.
From Polling to Events: Building a Reactive MQL5 Trading System with Python and Redis Streams
An Expert Advisor that takes signals from an external process must know which messages were delivered, which were acknowledged, and which orders reached the broker. This article builds that confirmation protocol on Redis Streams: MQL5 publishes market events, Python suggests trades, and MQL5 alone decides what is executed. Live tests on a demo account show duplicate detection, guard refusals, and dead-lettering; crash recovery is verified with unit tests.
From Evidence to Execution (Part 1): How to Log, Measure, and Decode a Trading Strategy Inside MetaTrader 5 AI
An evidence-first workflow for Range Breakout in MQL5: a non-trading logger captures session/time windows and records 61 fields per breakout to CSV, with a strict split between entry features and hindsight labels. The MT5 AI Assistant processes the dataset in nine phases, helping validate data, quantify baselines, and locate stable, entry-usable thresholds for subsequent EA coding.
Archimedes Optimization Algorithm (AOA)
The article examines the Archimedes Optimization Algorithm — a metaheuristic in which an agent is represented as a physical object with density, volume, and acceleration, and the search itself is reinterpreted as the tendency of bodies submerged in a fluid to reach equilibrium. The balance between exploration and exploitation is not dictated by an external schedule here, but rather stems from the physics of decaying turbulence. We will implement the algorithm in MQL5, test it on a standard test bench, and analyze where this approach works.
Andean Condor Algorithm (ACA)
The article implements the Andean Condor Algorithm (ACA) for MQL5 — a compact optimizer with a multiscale intensification operator. A significant improvement in solution quality was observed with a small population: a single adjustment to the settings propels it into the top 45 — and behind this lies a distinctive feature of the algorithm worth knowing about. This resource provides ready-to-use code and practical guidelines for its application.
Entropy Pooling and Scenario Budgets for Expected-Shortfall Sizing
Rolling lookback windows implicitly fix a probability vector over past bars. We implement entropy pooling in MQL5 to keep all historical scenarios, reweight them by conditioning on today's volatility under an effective‑scenarios budget, and add views on volatility, tails and correlation. A walk‑forward test, a chart indicator and an ES‑based sizing EA demonstrate how to calibrate risk forecasts and position size to the current regime.
MetaTrader 5 Machine Learning Blueprint (Part 24): Sequence Risk
Realized backtests reflect a single ordering of trades, so their maximum drawdown and prop‑firm breach risk are often understated. We resequence trade returns via a stationary bootstrap with a derived block length to estimate the drawdown distribution and a sequence risk ratio, compute path‑dependent breach probabilities for drawdown and daily‑loss limits, and replace WFE with a paired IS–OOS degradation statistic. The tools are demonstrated on a real EURUSD RSI strategy to guide sizing and risk limits.
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 6): A Constant-Dollar Exposure FX Trading System Based on Fixed-Income Interest Rate Yield Differentials
We describe ANANTA, a rules-based FX portfolio model that measures deviations in Interest Rate Swap differentials via moving averages and rebalances constant-dollar exposure across G10 currencies. Designed for intraday operation, it complements or substitutes carry logic without relying on trade volume. Performance is examined from January 2020 to October 2026 for five of the most liquid currencies. Code and free data pipelines are included.
Neural Networks in Trading: Recurrent Modeling of Market Micromovements (EV-MGRFlowNet)
The article discusses the adaptation of the EV-MGRFlowNet architecture — originally developed for processing event-based video data — to the field of financial time series. The approach presented here offers a new perspective on the market as a stream of micro-movements, where price, volume, and liquidity form a dynamic structure that lends itself to recurrent analysis without explicit supervision.
Building a Two-Pole Momentum Oscillator in MQL5
We build a Two‑Pole Momentum Oscillator in MQL5 that measures deviation from a 25‑period SMA, normalizes it by its mean and standard deviation, and smooths the result with two EMA‑style passes. The code defines inputs, buffers, warm‑up and recalculation logic, signal rules, and colorized plots, and derives dynamic targets from the 100‑period average range. It helps detect momentum shifts around the zero line and display price levels tied to recent volatility.
Weibull Reliability Analysis for Strategy Lifespan: Estimating When an EA Is Likely to "Fail"
We implement a native Weibull maximum-likelihood fit in MQL5 and use it to model strategy wear-out from trade history. Failures are defined as the rolling profit factor dropping below a floor, producing lifetimes in trades. The article wires a survival-based governor into an EA and a companion indicator, so you can estimate conditional survival over the next N trades and apply explicit retirement thresholds with cooldown.
Building a FIFO-Compliant Position Management Layer for NFA-Regulated MQL5 Accounts
This article shows how to make EA close operations comply with broker-enforced FIFO (ACCOUNT FIFO CLOSE) on hedging accounts, so naive exits stop failing. It introduces CFifoPositionQueue to order an EA's own tickets by time and CFifoComplianceGuard to execute closes in two modes: strict reject or auto-cascade, with optional per-direction scope. The guard re-verifies eligibility before each step, normalizes volumes, and inspects real server retcodes. You get reusable code, tests, and clear limits.
Uncertainty as a Model (Part 6): Multiple Regression and Diagnostics
A practical introduction to multiple regression with deterministic factors for financial time series. Topics covered include the formulation and matrix form of ordinary least squares (OLS), residual diagnostics, EDA/CDA, R-squared and adjusted R-squared, the F-test, RESET, the Breusch–Pagan test, VIF, and Cook’s distance. Techniques for working with regressors are demonstrated: dummy variables, nonlinear transformations, and interaction terms. Examples involving trends, days of the week, and news help select factors and build models suitable for forecasting.
How to Implement R/S Analysis and the Hurst Indicator in MQL5
The Hurst exponent indicator for MQL5 is based on R/S analysis using OLS regression in log-log space. The theoretical basis is the findings of Gatheral–Jaisson–Rosenbaum (2014), according to which volatility follows fractional Brownian motion with H ≈ 0.10. The indicator estimates H within a moving window, identifies anti-persistent (H < 0.3), neutral, and trending (H > 0.5) market regimes, colors the line, and triggers an alert upon a regime change, helping you choose a strategy type and manage risk.
Per-Setup Trade Ledger in MQL5: Find Out Which of Your EA's Entries Is Losing Money
Most EAs trade more than one setup, yet the Strategy Tester judges them all by a single equity curve. CSetupLedger is a small MQL5 class that stores each trade's setup in its magic number and rebuilds the per-setup record from the account's deal history, so a restart never wipes it. It compares a Wilson interval of each setup's win rate with the breakeven rate implied by that setup's own average win and loss, and gives no verdict before 30 closed trades. Each setup ends up trusted, rejected or still undecided. In two backtests the per-setup totals match the tester exactly. Full source and two working EAs are attached.
Property-Based Testing for Trading Rules in MQL5 (Part 1): Generate Market Scenarios, Test Invariants, Find Edge Cases
Property-based tests exercise a sizing rule across thousands of generated scenarios instead of a few hand-picked cases. A deterministic MQL5 runner creates seeded symbol contracts, checks eight risk-volume properties, and writes text and CSV reports for reproducible evidence. A second script intentionally rounds volume the wrong way, replays the failing seed, and shrinks the counterexample to the half-step boundary, making the defect minimal and diagnosable.
Neural Networks in Practice: When to Use an Artificial Neuron and How It Works in MQL5
We implemented a neuron in MQL5 that was trained using stochastic gradient descent and compared its loss function to that of linear regression. Using code and graphs, we demonstrate how normalization, the choice of learning rate, and the structure of the problem affect convergence. This article provides guidance on debugging the training process, interpreting error behavior, and selecting the appropriate architecture or activation function.
From Basic to Intermediate: Subwindows (I)
In this article, we'll start exploring how to work with subwindows in MetaTrader 5 using MQL5. This is a broad topic with several practical aspects that may prove challenging, so we'll start with a brief introduction. And yet, dear reader, it’s important that you understand what we’re going to discuss here, because it could play an important role in your future.
Neural Networks in Practice: Stochastic Gradient Descent
This article uses practical examples to explain how to calculate and apply gradients of the weights and bias (intercept) in a linear neuron implemented in MQL5, and also discusses a stochastic variant of gradient descent. We analyze stopping criteria, iteration limits, and the effects of training on data subsets. The results are displayed in the MetaTrader 5 terminal, where a simple chart is also plotted. Readers are invited to modify the training set and analyze the model's behavior.
Neural Networks in Trading: Temporal Motion Aggregation (Conclusion)
Introducing the TMA framework — an intelligent system capable of forecasting market dynamics with sufficient accuracy. In this article, we have integrated all the components into a single architecture and transformed it into a fully-fledged trading agent that analyzes the market and makes decisions in real time.
Practical Modules from Other Languages in MQL5 (Part 09): MATPLOTLIB (II)
Learn how to create advanced visualizations in MetaTrader 5 using a Matplotlib-like API from MQL5 while Python handles rendering. We implement key chart types—scatter, bar, horizontal bar, histogram, pie, and hexbin—and show how to control axes, legends, colorbars, and styles. The result is a consistent workflow for exploring trading and financial datasets.
Confident Learning: Finding Mislabeled Trades Before They Poison Your Classifier
The article focuses on label-auditing for meta-labeling, not on a new entry signal. It presents a native MQL5 implementation of confident learning with out-of-fold scoring and calibrated pruning, plus an EA switch that trains the meta-filter on raw or cleaned datasets. A controlled Strategy Tester comparison helps you quantify noise and choose a pruning level that preserves generalization.
How to Replace a WebSocket EA with TradeMux REST in MetaTrader 5
The article continues the series on AI Hedge Fund and addresses three limitations of v4: analysts' reputation scores are now stored persistently in SQLite, the EA has been removed from the critical execution path, and signals from the council of fifteen are distributed to multiple brokers via the TradeMux REST API. The logic behind the council and risk management has remained the same: Python retrieves data via the MetaTrader 5 SDK and executes orders directly. The result is resilience to restarts and scalability across multiple terminals.
Crypto Exchange Integration with MQL5 (Part 1): Connecting to MEXC Futures
This article introduces the foundations of connecting MetaTrader 5 to a cryptocurrency exchange using MQL5 and the MEXC Futures API. It covers terminal configuration, JSON response processing, WebRequest() execution and validation, and conversion of API data into native MQL5 types. Practical examples demonstrate retrieving and processing exchange data. These components establish the basis for a reusable MEXC Futures client, developed progressively throughout the series. The series focuses exclusively on exchange integration; how readers use the retrieved data remains outside its scope.
Creating Custom Indicators in MQL5 (Part 12): Mapping Liquidity with a Volume Profile Heatmap
We build a volume profile heatmap indicator in MQL5 that bins window volume into uniform price levels and paints each bar as a column of colored cells behind the candles. We cover binning, heat coloring, the side profile, the point-of-control and value-area lines, and the liquidity readouts, with every level published to buffers. The result is a map of dense bands and thin gaps, showing how much traded volume sits above and below the current price.
Constant Proportion Portfolio Insurance (CPPI) for MQL5: A Floor-Protected Capital Allocation Strategy
Build Constant Proportion Portfolio Insurance natively in MQL5. The article details the floor and cushion formulas, a rebalance engine that operates safely on both netting and hedging accounts, and a price‑only reference indicator that reuses the same math. A real Strategy Tester run on XAUUSD M5 demonstrates configuration, order sizing, and stability under a rebalance band.
Neural Additive Models for Fully Interpretable Signal Attribution in MQL5
Build and deploy a Neural Additive Model natively in MQL5: one small network per feature, additive output, and no post-hoc explainability. The article provides a PyTorch trainer, two‑output ONNX export (signal and contributions), an include wrapper using OnnxCreateFromBuffer/OnnxRun, and an EA that prints real per‑feature contributions each bar. It covers identical feature math for training/export, threshold measurement, Strategy Tester results, and edge cases such as NaNs and out‑of‑distribution inputs.
Neural Networks in Trading: Temporal Motion Aggregation (Key Components)
In this article, theory meets practice. We implement the key modules of the TMA framework — MPE and MPA. Here, data takes on meaning, and cross-attention becomes a tool for precise analysis of market dynamics. Minimal unnecessary operations, maximum efficiency — a step toward next-generation intelligent trading.
A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part I): Continuous Adaptation of the Trading Model on Each Bar
The article examines the architecture of an Expert Advisor based on a cellular automaton with 10,000 adaptive parameters and an independent binary predictor with a 10-bar prediction horizon. The article demonstrates a three-level online learning process, the evolution of strategies, and validation using a ring buffer and a confusion matrix. The input parameters are reduced to Magic Number, while trading settings are calculated from ATR and five genomes. The EURUSD H1 test yielded an approximate hit rate of 58%, compared to roughly 51% for the fixed MLP.
From Basic to Intermediate: Technical Indicators (II)
In this article, we'll show you how to create an MQL5 indicator that plots multiple moving averages on a single chart, reducing the amount of duplicate code. This uses iMA, indicator buffers, CopyBuffer, PlotIndexSetInteger/String, and a const array of structures that brings together periods, methods, and colors. The sizes of `indicatorbuffers` and `indicatorplots` are determined based on `Averange.Size()`. This approach simplifies maintenance and allows you to add or remove moving averages by modifying just one list.
Building a Trade Replay Tool in MQL5
This article presents a Trade Replay Tool for MetaTrader 5 implemented as an MQL5 indicator. It replays historical candles within an anchor-defined range and automatically reconstructs historical trades as paper positions with entry, SL, and TP. Users control start/end anchors and playback speed via UI buttons and hotkeys, enabling focused study of price evolution and trade lifecycle in a precise, event-driven environment.
Neural Networks in Practice: Gradient Descent
In this article, I will try to explain as simply and clearly as possible one of the most controversial issues that arises when discussing neural networks: how to find the best possible point, or the minimum of the loss function. I'll show you the difference between linear regression and gradient descent. Both methods are fairly simple and serve as examples of how the path that seems obvious isn't always the best one.
From Basic to Intermediate: Technical Indicators (I)
In this article, we will examine the basic principles of using the technical indicators built into MetaTrader 5 and supported by this platform. Knowing and understanding these indicators can make implementing a solution much simpler, faster, and more efficient, since you won't have to worry about the necessary calculations. The platform handles them for us automatically.
Using the MQL5 Economic Calendar for News Filter (Part 5): The Tier the Calendar Does Not Have
This part extends the news filter with an ordered tier scale that adds a special tier above the broker's High, per‑event time windows, and one classifier shared by live calendar data and historical CSV. A rule table (with optional CSV overrides) promotes or demotes specific releases and can set custom windows. A diagnostic script prints your broker's calendar, event codes, and server time so your rules match what the terminal actually reports.
Building a PDF Creation Library in MQL5 (Part 3): The Byte-Exact Writer
The article presents CPdfBuffer and CPdfWriter, a minimal MQL5 pair that derives all offsets from the output buffer instead of hand-maintaining numbers. CPdfWriter records object starts, writes a fixed-width cross-reference table and trailer, and ensures structural consistency. The result passes Part 2's validator, and a ready-to-use script converts arbitrary text to a paginated PDF.