Articles on trading system automation in MQL5

icon

Read articles on the trading systems with a wide variety of ideas at the core. Learn how to use statistical methods and patterns on candlestick charts, how to filter signals and where to use semaphore indicators.

The MQL5 Wizard will help you create robots without programming to quickly check your trading ideas. Use the Wizard to learn about genetic algorithms.

Add a new article
latest | best
preview
Self-Learning SuperTrend: An Adaptive Machine Learning-Based Trend Indicator

Self-Learning SuperTrend: An Adaptive Machine Learning-Based Trend Indicator

The classic SuperTrend loses accuracy when the market regime changes because it uses fixed ATR parameters and a fixed multiplier. The article examines the architecture of ML SuperTrend Pro v2.00 written entirely in MQL5: a background test matrix with adaptive parameter updates, a regime grid as a context detector, an accuracy layer consisting of five filters, and Parabolic-style rendering with well-designed buffers. The article presents the principles of L1 regularization, the results of a comparison with the classic SuperTrend, and practical recommendations for deployment and integration via iCustom.
preview
Coyote Optimization Algorithm (COA)

Coyote Optimization Algorithm (COA)

Introducing an MQL5 implementation of the Coyote Optimization Algorithm: packs with local alphas, a median-based tendency, and built-in crossover enable parallel exploration of regions of the search space while keeping premature convergence in check. The algorithm is integrated into C_AO and has been tested on the standard test bench and in a composite anti-cheat test. The article includes code, pseudocode, and an analysis of the operators that enable the use of COA to optimize the parameters of a trading system.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part VIII): Building a Floating Risk Management Calculator Module for Any EA

Overcoming Accessibility Problems in MQL5 Trading Tools (Part VIII): Building a Floating Risk Management Calculator Module for Any EA

A reusable MQL5 component measures floating P/L with swap, gross loss, two stop‑loss quantities, equity gap, margin level, and stop coverage, then classifies results for selected positions and the whole account. The snapshot records validity and readable reasons, supporting a quote‑age policy and missing‑stop handling. Integrate it into an Expert Advisor and block new exposure when thresholds or data checks fail.
preview
From Evidence to Execution (Part 2): Turning MetaTrader 5 AI Strategy Logs into Robust Rule Based EA

From Evidence to Execution (Part 2): Turning MetaTrader 5 AI Strategy Logs into Robust Rule Based EA

This article turns the Part 1 evidence into a working MQL5 Expert Advisor. It formalizes entry conditions, designs direction-aware stop loss and take profit, and stress-tests the combined logic before coding, with every rule linked to measured features. Readers receive a reproducible implementation with configurable inputs and per-bar execution consistent with the study.
preview
Measuring What Matters (Part 5): The Risk Concentration Indicator — Plotting Eigenvalue Dominance Live

Measuring What Matters (Part 5): The Risk Concentration Indicator — Plotting Eigenvalue Dominance Live

This article presents a live MQL5 indicator for monitoring portfolio risk concentration through eigenvalue decomposition. The indicator calculates rolling covariance statistics for three instruments using persistent prefix sums, aligns price data by timestamp, handles missing observations, and plots the dominant eigenvalue as a percentage of total portfolio variance. The implementation provides a practical way to observe changes in portfolio risk concentration as the covariance structure evolves over time.
preview
Neural Networks in Trading: A Spatio-Temporal State-Space Model for Financial Data Analysis (E-STMFlow)

Neural Networks in Trading: A Spatio-Temporal State-Space Model for Financial Data Analysis (E-STMFlow)

We invite you to explore the E-STMFlow framework, which effectively processes event streams by extracting informative embeddings, filtering out noise, and identifying key movements. Its architecture makes it possible to identify complex relationships between features and provides scalability, accuracy, and high computational efficiency for intelligent analysis and forecasting.
preview
Corona Virus Optimization (CVO) Algorithm

Corona Virus Optimization (CVO) Algorithm

We describe and implement CVO: infection as candidate generation, coordinate-wise normal perturbation, and a dynamic population. The algorithm is integrated into C_AO and has been tested on a standard benchmark. The analysis identifies a scaling-related cause of stagnation and provides a practical solution — a shift to a relative step based on the range width. The code is ready for use.
preview
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Encoder)

Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Encoder)

The article presents an adaptation of the SDformerFlow framework that achieves high adaptability by integrating spiking attention with multi-window convolution and weighted summation of query elements. The architecture allows each attention head to learn its own parameters, which improves the model's accuracy and sensitivity to the structure of the data being analyzed.
preview
TradeMux as a Quant Backbone: Connecting Institutional Python Pipelines to Different Terminals and Brokers

TradeMux as a Quant Backbone: Connecting Institutional Python Pipelines to Different Terminals and Brokers

The article describes TradeMux as a bridge between a Python pipeline and the MetaTrader 5 terminal for the seamless transfer of trading decisions without duplicating logic. The article examines a four-layer production architecture and a complete Python execution service: connection setup, reading account and position data, signal generation (including CatBoost), pre-trade risk control, kill_switch, and a supervisor. Practical benefits include cross-broker normalization (RoboForex, IC Markets, Alpari, OANDA) and scaling from a single account to multi-account broadcasting without changing the trading logic.
preview
Beluga Whale Optimization (BWO) Algorithm

Beluga Whale Optimization (BWO) Algorithm

A candidate for our ranking table is Beluga Whale Optimization, a metaheuristic based on three behavioral patterns of the beluga whale: pair swimming, hunting using Lévy flight, and population renewal through whale fall. During implementation, we discovered that the algorithm does not so much optimize as read the geometry of the test bench; we examine how this works and develop an honest, promising modification called BWOm.
preview
Integrating MQL5 with Data Processing Packages (Part 11): Multi-Timeframe Causality Detection using Granger Analysis

Integrating MQL5 with Data Processing Packages (Part 11): Multi-Timeframe Causality Detection using Granger Analysis

This article implements a multi‑timeframe Granger causality monitor for MetaTrader 5. A Jupyter notebook tests predefined timeframe pairs, selects lags, applies multiple‑testing control, and exports a calibration table. An MQL5 Expert Advisor reloads the setup, recomputes the F‑test live on rolling windows, and marks pairs VALID/INVALID to gate its vote‑based BUY/SELL generator. The workflow shows alignment rules, live/offline parity, and a filtered vs unfiltered comparison on EURUSD.
preview
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (SDformerFlow)

Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (SDformerFlow)

The article presents an adaptation of the SDformerFlow spiking architecture for the task of dense analysis of price micro-movements. The spatio-temporal structure provides a high level of detail, while the spiking logic ensures computational efficiency and the ability to work with sparse, pulse-like data. As a result, traders gain access to a tool that detects even the slightest shifts in liquidity and provides the foundation for more accurate and consistent real-time decisions.
preview
Local Outlier Factor: Density-Based Anomaly Detection in Native MQL5

Local Outlier Factor: Density-Based Anomaly Detection in Native MQL5

This article builds a native MQL5 LOF engine without DLLs, ALGLIB or ONNX. Bars are mapped to five standardized features; k‑NN reachability and density produce a scale‑free LOF score, and the alarm level is a moving quantile of the reference cloud. The score gates only new entries in an EMA‑cross EA, with an indicator for charting and a script for independent checks on XAUUSD, EURUSD and GBPUSD.
preview
Building a Divergence System (Part V): Adaptive Parabolic SAR Trailing Stop Utility

Building a Divergence System (Part V): Adaptive Parabolic SAR Trailing Stop Utility

The article delivers AdaptivePSARTrail.mqh: a reusable header that lets an EA trail positions (its own or external, by symbol/magic) with an adaptive Parabolic SAR. The utility adapts the step from divergence, guards flips with a side check, and orders broker and improvement gates (stops/freeze, tick grid, break‑even, start and step thresholds). A calculation‑only build serves indicators, result codes aid logging, and a demo EA verifies the integration.
preview
How to Build a 29-Pair Portfolio with an L1 Filter and VaR-based Allocation of Lots

How to Build a 29-Pair Portfolio with an L1 Filter and VaR-based Allocation of Lots

The article explores the practical application of the L1 Trend Filter for noise reduction and the construction of structural features suitable for live trading. The full workflow is presented: H1 data for 29 instruments from MetaTrader 5, causal filtering, CatBoost with a horizon of three L1 bars, rigorous walk-forward testing, and VaR-based allocation of lots. The reader is provided with a reproducible code pipeline and a portfolio evaluation methodology.
preview
Neural Networks in Trading: Recurrent Modeling of Market Micromovements (Conclusion)

Neural Networks in Trading: Recurrent Modeling of Market Micromovements (Conclusion)

The implementation of the EV-MGRFlowNet framework demonstrates its key advantages: modularity, resilience to market fluctuations, and the ability to develop strategies independently. These features make the framework a powerful tool for analysis, forecasting, and the development of autonomous trading strategies.
preview
Neural Networks in Trading: Recurrent Modeling of Market Micromovements (Encoder)

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.
preview
Testing Random Walk vs Mean Reversion in MQL5: Implementing the Lo-MacKinlay Variance Ratio Test

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.
preview
From Polling to Events: Building a Reactive MQL5 Trading System with Python and Redis Streams

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.
preview
From Evidence to Execution (Part 1): How to Log, Measure, and Decode a Trading Strategy Inside MetaTrader 5 AI

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.
preview
Archimedes Optimization Algorithm (AOA)

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.
preview
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 6): A Constant-Dollar Exposure FX Trading System Based on Fixed-Income Interest Rate Yield Differentials

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.
preview
Neural Networks in Trading: Recurrent Modeling of Market Micromovements (EV-MGRFlowNet)

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.
preview
Building a FIFO-Compliant Position Management Layer for NFA-Regulated MQL5 Accounts

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.
preview
How to Implement R/S Analysis and the Hurst Indicator in MQL5

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.
preview
Property-Based Testing for Trading Rules in MQL5 (Part 1): Generate Market Scenarios, Test Invariants, Find Edge Cases

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.
preview
Neural Networks in Trading: Temporal Motion Aggregation (Conclusion)

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.
preview
How to Replace a WebSocket EA with TradeMux REST in MetaTrader 5

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.
preview
Constant Proportion Portfolio Insurance (CPPI) for MQL5: A Floor-Protected Capital Allocation Strategy

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.
preview
Neural Networks in Trading: Temporal Motion Aggregation (Key Components)

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.
preview
Using the MQL5 Economic Calendar for News Filter (Part 5): The Tier the Calendar Does Not Have

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.
preview
Neural Networks in Trading: Temporal Motion Aggregation (TMA)

Neural Networks in Trading: Temporal Motion Aggregation (TMA)

The TMA framework offers a new perspective on market dynamics, enabling models to capture not only the state of the market but also the passage of time itself. Its ability to identify patterns in a continuous stream of data makes the analysis more in-depth and accurate than with traditional approaches. Recurrent adaptation turns this method into a practical tool for working with real-world quotes.
preview
Trading Strategy Beyond Raw Volume: Using Transformed Volume Change for Trading

Trading Strategy Beyond Raw Volume: Using Transformed Volume Change for Trading

The article develops a volume-change strategy that transforms tick or real volume with Ln(volume+1), differences it bar to bar, and applies arctan to produce a bounded, scale‑independent signal. A threshold drives entries, with selectable gates for positive, negative, or bi‑directional signals and candle‑based confirmation. An MQL5 Expert Advisor implements the logic and supports fixed TP/SL, N‑candle exits, or both, enabling straightforward testing and deployment.
preview
How to Train an MLP Using Markov Chain Features in MQL5

How to Train an MLP Using Markov Chain Features in MQL5

The article describes the two-level MarkovMLPOscillator indicator: a three-state Markov chain uses historical data to construct a transition matrix and generate 15 probabilistic features for each bar, and an MLP is trained on these features to predict price direction at a specified forecast horizon. The article covers feature generation, the validation procedure using a holdout set, and parameter settings. The result is an interpretable oscillator with a color histogram, a smoothed signal, and a display of the current transition matrix.
preview
Building a Prop-Firm Rule Guard in MQL5 (Part 1): The Observation Layer

Building a Prop-Firm Rule Guard in MQL5 (Part 1): The Observation Layer

Prop-firm accounts operate under a second rulebook that MetaTrader 5 does not model. This first part builds the observation layer: a per-pass frozen account snapshot read by every rule, a verdict record that reports without acting, explicit enable flags in the profile, and a session clock aligned to the firm's reset time. The result is a reproducible pass that prevents cascading effects and prepares the ground for safe decisions in Part 2.
preview
Neural Networks in Trading: Iterative Forecast Refinement Models (Conclusion)

Neural Networks in Trading: Iterative Forecast Refinement Models (Conclusion)

Introducing the RAFT framework — a powerful tool for analyzing and forecasting financial time series. Its flexible and optimized architecture ensures accurate forecasts, stable performance, and faster data processing. RAFT reduces the risk of errors and makes it easier to create effective trading strategies.
preview
Bull Optimization Algorithm (BOA)

Bull Optimization Algorithm (BOA)

We present an evolutionary algorithm without a selection operator: the best individual becomes the sole mating partner for the entire population, and classical mutation is replaced by multiplicative mutation with a self-adjusting step size. In this article, we examine three key ideas, implement the algorithm in MQL5 using the C_AO framework, and test it on the standard benchmark suite and in an anti-cheat test — where BOA comes very close to the cutoff for the top 45 but does not make the ranking.
preview
Behavioural Cloning in a Live Trading System: What Live Experience Can and Cannot Teach

Behavioural Cloning in a Live Trading System: What Live Experience Can and Cannot Teach

This article measures a live-to-train behavioral-cloning loop for an RL trading system across 83 models. Outcome-weighted imitation shifted the policy toward Hold (48% → 82%), with 12 final models not trading at all. Live records were instead used to fit spread and slippage to broker fills, revealing execution costs ~85× higher than in simulation. We describe the loop, the failure mechanism, the calibration, and a protocol to apply.
preview
Broker Time vs Real Market Time — Building a DST-Aware Session Clock in MQL5

Broker Time vs Real Market Time — Building a DST-Aware Session Clock in MQL5

Session filters can run an hour off when a broker and a market change their clocks on different dates. This article presents an MQL5 include file, SessionClock.mqh, that converts London, New York, and Tokyo sessions to broker hours for a stated daylight saving time (DST) schedule (EU, US, or fixed) and winter offset. A second script estimates the schedule from server history. It uses calendar arithmetic, so it also works in the Strategy Tester.
preview
Neural Networks in Trading: Iterative Forecast Refinement Models (Key Components)

Neural Networks in Trading: Iterative Forecast Refinement Models (Key Components)

In this article, we explore the inner workings of the RAFT framework — one of the most precise and elegant approaches to analyzing dynamic processes. Step by step, we adapt its idea of iterative refinement to financial time series, laying a solid foundation for a future model. Readers can look forward to an engaging exploration of the architecture, where every component has its own purpose and function.