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
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.
preview
Color Harmony Algorithm (CHA)

Color Harmony Algorithm (CHA)

We take a closer look at the Color Harmony Algorithm (CHA) — a meta-heuristic optimization method based on Munsell's theory of color harmony. We explore the structure of the hue circle, harmony templates, the alternation between the concentration and dispersion phases, and the role of solution memory. From a theoretical framework to a working implementation in MQL5 and unbiased testing on a standard benchmark.
preview
Neural Networks in Practice: An Example of Implementing an XOR Gate

Neural Networks in Practice: An Example of Implementing an XOR Gate

In this article, I will try to show you, dear reader, that things are not always what they seem. We often tend to think that everything is arranged in a certain way, even though we may end up believing something that isn't necessarily true. Neural networks are undoubtedly one of the most interesting topics, whether viewed from the perspectives of mathematics, electronics, or software. Contrary to what many people believe or claim, neural networks are neither a problem nor a definitive solution. This is just one area of research where we should continue to delve deeper and explore what goes on behind the scenes.
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
Optimal Trade Exit in MQL5: Longstaff-Schwartz Least-Squares Monte Carlo for Continuation-Value Estimation

Optimal Trade Exit in MQL5: Longstaff-Schwartz Least-Squares Monte Carlo for Continuation-Value Estimation

This article models position exits as an American option and implements the Longstaff–Schwartz least‑squares Monte Carlo in native MQL5. The engine calibrates drift and volatility from recent returns, simulates forward price paths, and uses backward induction to compare immediate exercise to continuation. It integrates into an EA with hard time and price backstops and a live indicator, and is tested on four symbol/timeframe combinations with mixed, reproducible Strategy Tester results.
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
Beyond Squared Returns: Path-Dependent Volatility

Beyond Squared Returns: Path-Dependent Volatility

This article implements a path-dependent volatility model in MQL5 that keeps the sign of returns. The engine uses two-timescale EWMA kernels (four accumulators) to form activity and trend features, with closed-form coefficients and a lightweight kernel search. We provide a calibration workflow and an indicator that plots the decomposition, then test out of sample against EWMA and GARCH on multiple symbols. Results show clear gains on equity indicators and minimal gains on FX.
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
Fundamentals of Bayesian Inference in Discrete and Continuous Settings: From Theory to Practical Model Implementation

Fundamentals of Bayesian Inference in Discrete and Continuous Settings: From Theory to Practical Model Implementation

The article discusses the fundamentals of Bayesian statistics in both discrete and continuous settings. We will progress from classical Bayes’ theorem and simple examples involving coin flips to conjugate distributions and dynamic Bayesian updating, which enables real-time analysis of market quotes. Using the beta-binomial model as an example, a simple change-point detection indicator has been implemented to help identify shifts in market regimes.
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.
preview
From Signal to Trade via a Chain of Agents: LangChain Architecture on Top of MQL5

From Signal to Trade via a Chain of Agents: LangChain Architecture on Top of MQL5

The article describes an architecture in which the MQL5 Expert Advisor (EA) handles only data collection and execution, while the logic is moved to a Python server with three LangChain agents: a signal agent, a news agent, and a risk manager. Agents process the WebSocket request sequentially; if any agent rejects it, "hold" is returned. Decisions and actual PnL are stored in SQLite, forming memory and statistics. The reader will receive an interaction diagram, a command protocol, and a feedback approach.