Articles on machine learning in trading

icon

Creating AI-based trading robots: native integration with Python, matrices and vectors, math and statistics libraries and much more.

Find out how to use machine learning in trading. Neurons, perceptrons, convolutional and recurrent networks, predictive models — start with the basics and work your way up to developing your own AI. You will learn how to train and apply neural networks for algorithmic trading in financial markets.

Add a new article
latest | best
preview
MLP (Multilayer Perceptron) Inside an MQL5 Expert Advisor: Training on Historical Data Without Python or Weight Files

MLP (Multilayer Perceptron) Inside an MQL5 Expert Advisor: Training on Historical Data Without Python or Weight Files

The article shows how to move the GridSurvivor Expert Advisor’s MLP filter from offline training in Python to fully embedded training in MQL5. The network is trained on the history of the current symbol and timeframe, is periodically retrained, and is used as the final signal filter. This approach eliminates external files and normalization mismatches, making the Expert Advisor self-contained and reproducible.
preview
The Chimp Optimization Algorithm: From ChOA to BChimp

The Chimp Optimization Algorithm: From ChOA to BChimp

The Chimp Optimization Algorithm (ChOA) mimics primate group hunting with a division of roles, and its binary variant, BChimp, applies this mechanism to feature selection problems. We implement a continuous core in C_AO; along the way, we identify and correct an inherited coefficient defect — one that is masked by binarization but disrupts the search in the continuous domain. The abstract provides a ready-made implementation and practical insights into the quality and robustness of the search.
preview
Neural Networks in Trading: A Spatio-Temporal State Space Model for Financial Data Analysis (STSSM Block)

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

The article explains the internal mechanics of the STSSM block and demonstrates how modern SSM approaches can be adapted to the event-driven logic of spiking models while maintaining high speed and expressive representations. Step by step, we work our way through the architecture, transforming the rigorous theory behind the authors' approach into a practical financial instrument for analyzing financial time series.
preview
A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part III): A Living Feature Graph

A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part III): A Living Feature Graph

The third article in this series introduces a trainable feature graph in the Cellular10K architecture: the weights of the feature → feature connections are strengthened online after correct predictions and weakened after errors. The article covers soft initialization, the message-passing step, a local Hebbian learning rule, weight clipping, normalization, and decay. The article demonstrates integration with a cellular automaton and a binary predictor, along with diagnostics metrics and practical activation thresholds for controlling overfitting.
preview
Native AWS S3 Integration in MQL5: A Signature V4 Client for Model and Feature Artifact Storage

Native AWS S3 Integration in MQL5: A Signature V4 Client for Model and Feature Artifact Storage

This article builds an AWS SigV4 signer in pure MQL5 and wraps it in a small S3 client for PutObject, GetObject, and ListObjectsV2. It explains canonicalization, HMAC‑SHA256, and key derivation, and shows how to handle empty‑payload hashing and GMT timestamps to avoid SignatureDoesNotMatch. A script uploads a model and a CSV, downloads them back, and compares SHA‑256 checksums, providing a practical, DLL‑free path to centralized artifact storage.
preview
A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part II): A New Level of Online Adaptation

A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part II): A New Level of Online Adaptation

In the second part, the cellular automaton is transferred from a grid to a graph. The features become vertices in a graph with local and long-range small-world connections, and the cells become agents that interact not only with their geometric neighbors but also with their semantic neighbors. The article discusses graph-based feature filtering, the construction of a neighbor graph, updated coherence-based voting, and the Graph Coherence and Graph Health metrics. This reduces the impact of isolated outliers and accelerates the propagation of market regimes while maintaining full compatibility with MQL5.
preview
A Trade Request Preflight Class in MQL5: Checking Volume, Stops, Margin and Sessions Before OrderSend

A Trade Request Preflight Class in MQL5: Checking Volume, Stops, Margin and Sessions Before OrderSend

CTradePreflight checks a trade request before OrderSend(), so an EA finds an off-step volume, a wrong-side stop, missing margin or a closed session instead of getting a server rejection. The class repairs only safe cases, reads the OrderCheck() retcode, and counts every refusal by reason. Unit tests and a random-delay stress EA show that levels placed very close to the price can still fail, and an optional delay buffer stops those rejections at the cost of blocking some valid requests.
preview
Neural Networks in Practice: The Perceptron

Neural Networks in Practice: The Perceptron

In this article, the perceptron is presented as the basis of a neural network, and its implementation in MQL5 is described in detail. We will explain what activation functions and their derivatives are, the difference between forward propagation and backpropagation, and how the least squares loss function and the gradient are used. You will learn how to train weights and biases, verify the results using test scripts, and adjust the learning rate to achieve stable convergence.
preview
Neural Networks in Practice: The Gradient

Neural Networks in Practice: The Gradient

This article explains why and how the gradient is used in training a perceptron, based on the least squares method and the chain rule for computing partial derivatives. We will demonstrate how to implement gradient calculation in the C_Neuron class using the MQL5 language and test it using examples with 1 and 2 inputs. You'll learn how to adjust the weights and bias using gradient descent and prepare for forward propagation and backpropagation.
preview
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Conclusion)

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

The SDformerFlow framework transforms complex events in financial time series into structured representations, enabling the model to identify local fluctuations and global trends simultaneously. The multi-level U-structure ensures consistency between the forward pass and the backward pass, synchronization of gradients, and computational stability. Ultimately, SDformerFlow proves to be a powerful and flexible tool for building modern trading systems.
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
Estimate the Probability of Large-range Sessions (Part 1): Build and Check EURUSD Forecasts

Estimate the Probability of Large-range Sessions (Part 1): Build and Check EURUSD Forecasts

We estimate the probability, at broker time 08:00, that EURUSD's 08:00–16:00 range exceeds 1.25 times the mean of the previous 20 complete, valid target ranges. A two-feature SPSS logistic regression model employs the completed 00:00–08:00 H1 window. Coefficients from 2020–2023 sessions are fixed for the 2024 holdout comparison against constant and 60-outcome rolling frequency baselines, using Brier scores and log losses. MQL5 scripts allow readers to extract broker data and recreate the probabilities in MetaTrader 5.
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
Why My MQL5 EA Passed Validation and Still Failed Under Execution Delay

Why My MQL5 EA Passed Validation and Still Failed Under Execution Delay

An EA that passes CodeBase validation can still fail under execution delay and a freeze level. Using a tick scalper, the article reproduces four such failures in the Strategy Tester and shows each fix with its limits. An ablation under a fixed delay measures each change on its own. The burst-based stop distance removes most rejected modifications, while the weekend case behind the session buffer did not recur in those runs.
preview
Model Drift Watchdog: PSI-Based Auto-Retrain Alerts via a Lightweight Webhook

Model Drift Watchdog: PSI-Based Auto-Retrain Alerts via a Lightweight Webhook

This article implements a PSI-based drift watchdog for MQL5 EAs. It compares a feature and the model's predicted probability against a quantile-based reference using a rolling window at a configurable cadence, applies hysteresis to avoid flapping, and raises a webhook on state transitions. You get tested math, an audit CSV and a plotting indicator, plus tuning guidance for thresholds, window size, and cooldown.
preview
Neural Networks in Practice: Activation Functions

Neural Networks in Practice: Activation Functions

This is, without a doubt, the article I've enjoyed writing the most so far. In it, I showed that we don't really need anything special to achieve a certain goal. We can achieve this in various ways, provided we have the necessary knowledge and are willing to learn and dedicate ourselves to the task. I would like to express my heartfelt thanks to everyone who helped me choose these functions. The material presented here is intended solely for educational purposes. Under no circumstances should this be viewed as intended for anything other than teaching and studying the concepts presented.
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 Practice: ReLU Function Graph

Neural Networks in Practice: ReLU Function Graph

We will create an indicator written entirely in MQL5 to display the activation function and its derivative on the chart, using ReLU as an example. We will explain how derivatives affect the choice of activation function and what precautions are needed at nondifferentiable points. Readers will be able to interactively visualize the curves and gain a practical foundation for deciding when to use certain activation functions and when not to.
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
Weak Supervision for Traders: Combining Several Noisy Labeling Heuristics into One Probabilistic Label (Snorkel-Style)

Weak Supervision for Traders: Combining Several Noisy Labeling Heuristics into One Probabilistic Label (Snorkel-Style)

The article builds an MQL5‑native weak‑labeling engine that infers per‑indicator trust from vote agreement, then fuses five noisy signals into P(Buy) using Expectation‑Maximization. We describe the EA architecture, rolling‑window refits, abstain handling, diagnostics, and a majority‑vote baseline used for comparison. Readers can reuse the EM library, swap in their own labeling functions, and obtain a transparent, probability‑based entry filter.
preview
Neural Networks in Practice: The Birth of C_Neuron

Neural Networks in Practice: The Birth of C_Neuron

This article demonstrates how to encapsulate a neuron in MQL5 using the C_Neuron class, with weights, a bias, and a parameter specifying the number of inputs. We will take a detailed look at how to compute the loss function based on the least squares method and how to organize training data in arrays. This makes it easy to change the inputs and repeat experiments without modifying the implementation.
preview
MetaTrader 5 Machine Learning Blueprint (Part 26): Process Permutation

MetaTrader 5 Machine Learning Blueprint (Part 26): Process Permutation

We introduce the permutation process for backtest validation: permute bars, rerun the complete development process, and compare the observed Sharpe to the null distribution it produces. Outputs include one-sided p-values, robust z, and quantile confidence intervals, plus a spurious performance curve that quantifies selection versus trial budget. A cache-isolation check prevents false passes. The EURUSD H1 case shows how to set a tolerance and assess whether performance is distinguishable from selection.
preview
A Categorical Hidden Markov Model in MQL5

A Categorical Hidden Markov Model in MQL5

The article provides a detailed examination of the theoretical foundations and practical implementation of the hidden Markov model with categorical emissions (Categorical HMM) in the MQL5 language. Specific examples are used to demonstrate the processes of inference, iterative parameter learning, and online filtering, as well as the methodology for selecting the optimal model architecture based on the AIC/BIC information criteria.
preview
Active Learning: An EA That Only Asks for Human Confirmation on Its Most Uncertain Trades

Active Learning: An EA That Only Asks for Human Confirmation on Its Most Uncertain Trades

This article builds an uncertainty-based routing layer for an EA: an online logistic regression scores P(up), Shannon entropy measures uncertainty, and a streaming P² quantile enforces a fixed review budget. Signals auto-trade, auto-skip or go to a human checkpoint, replaced by proxy modes in the Strategy Tester. It is judged on a held-out window against a trade-everything baseline, matched-frequency and seeded controls, and an exact profit split. No edge is claimed.
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
MetaTrader 5 Machine Learning Blueprint (Part 25): Live Monitoring

MetaTrader 5 Machine Learning Blueprint (Part 25): Live Monitoring

The article shows why a fixed posterior threshold, checked trade by trade, lacks error control and retires healthy strategies far too often on a real EURUSD case. It introduces WinRateSPRT (with Page's CUSUM for continuous use) and a permutation-tested profit factor trend to cover distinct failure modes. LiveStrategyMonitor integrates both and reports a normalized retirement-progress measure for operational decisions.
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
Self-Optimizing Expert Advisors in MQL5 (Part 20): Causality Regularization With Time-Lagged Independent Components Analysis (3)

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.
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
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
Andean Condor Algorithm (ACA)

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.
preview
MetaTrader 5 Machine Learning Blueprint (Part 24): Sequence Risk

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.