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
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.
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
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
Per-Setup Trade Ledger in MQL5: Find Out Which of Your EA's Entries Is Losing Money

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.
preview
Neural Networks in Practice: When to Use an Artificial Neuron and How It Works in MQL5

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.
preview
Neural Networks in Practice: Stochastic Gradient Descent

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.
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
Practical Modules from Other Languages in MQL5 (Part 09): MATPLOTLIB (II)

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.
preview
Confident Learning: Finding Mislabeled Trades Before They Poison Your Classifier

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.
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
Neural Additive Models for Fully Interpretable Signal Attribution in MQL5

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.
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
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

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.
preview
Neural Networks in Practice: Gradient Descent

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.
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.