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
Ebola Optimization Search Algorithm (EOSA)

Ebola Optimization Search Algorithm (EOSA)

The article examines the EOSA algorithm, which is inspired by the mechanisms of Ebola virus transmission: short-distance transmission through close contact (exploitation) and long-distance transmission through travel (exploration). An analysis of the original publication revealed critical issues in the mathematical formulas and an epidemiological model that was impractical to implement, which required a significant overhaul of the algorithm to produce a workable implementation.
preview
Neural Networks in Trading: Decomposition Instead of Scaling (SSCNN)

Neural Networks in Trading: Decomposition Instead of Scaling (SSCNN)

In this article, we begin our exploration of the SSCNN framework — a modern architectural solution for time series analysis that combines accuracy, a structured design, and high computational efficiency. We will systematically examine its theoretical aspects, highlight the key differences from its predecessors, and begin the practical implementation of its basic components in the MQL5 environment.
preview
Bidirectional LSTM and Quantum Computing for Predicting the Direction of Price Movement

Bidirectional LSTM and Quantum Computing for Predicting the Direction of Price Movement

The article presents a reproducible implementation of a hybrid quantum-neural network model for algorithmic trading on Forex without using real quantum hardware. A fixed three-qubit quantum circuit in IBM Qiskit converts sliding-window statistics (mean returns, volatility, and range) into a probability distribution, from which seven quantum metrics are calculated. These features are integrated into a bidirectional LSTM architecture with regularization and mechanisms to address class imbalance, including focal loss and a sampler.
preview
Defining your Edge (Part 3): Using HMM and GRU in an Expert Advisor

Defining your Edge (Part 3): Using HMM and GRU in an Expert Advisor

We examine how a Hidden Markov Model (HMM) estimates latent market regimes while basing on observable price and indicator sequences. This is done by estimating the probability of state transitions. A Gated Recurrent Unit (GRU) network models time dependencies and keeps important information over several observations. In an Expert Advisor, HMM-based regime probabilities, can be merged with GRU-based sequence learning to better classify increments in accumulation, distribution, and momentum prior to their showing up in regular price confirmations.
preview
Partial Information Decomposition: When Two Indicators Together Say More Than Either Alone

Partial Information Decomposition: When Two Indicators Together Say More Than Either Alone

We introduce a Partial Information Decomposition library for MQL5 that decomposes two sources about a target into four atoms: unique to each, shared, and synergy. The implementation uses quantile binning, tabulated logarithms, and a maximum-entropy fit (for I_ccs), and it pairs results with a block-permutation null because atoms sit above zero on finite samples. Use it to screen indicator pairs and judge significance, including family-wise correction.
preview
Neural Networks in Trading: Disentangling Structured Components (Conclusion)

Neural Networks in Trading: Disentangling Structured Components (Conclusion)

The article provides a detailed explanation of the SCNN architecture and one way to implement it using MQL5. We will show how time series decomposition can be combined with neural network methods and attention mechanisms.
preview
Combining 3D Bars, Quantum Computing, and Machine Learning into a Unified Trading System

Combining 3D Bars, Quantum Computing, and Machine Learning into a Unified Trading System

The article presents the full integration of the 3D-bar module into a quantum-enhanced trading system for forecasting the movement of currency pairs. The system combines stationary four-dimensional features, an 8-qubit quantum encoder, and CatBoost gradient boosting with 52+ features. The system is implemented in Python using MetaTrader 5, Qiskit, CatBoost, and optional integration with the Llama 3.2 LLM for interpreting forecasts.
preview
Ecological Cycle Optimizer (ECO)

Ecological Cycle Optimizer (ECO)

The ECO (Ecological Cycle Optimizer) algorithm offers an interesting metaphor for applying the concept of the ecological cycle to the field of metaheuristic optimization. The idea of dividing a population into trophic levels — producers, herbivores, carnivores, omnivores, and decomposers — creates a hierarchical search structure, in which each group contributes to the overall optimization process.
preview
Neural Networks in Trading: Disentangling Structured Components (Encoder)

Neural Networks in Trading: Disentangling Structured Components (Encoder)

We invite you to explore the next stage in implementing the SCNN framework, which combines flexibility and interpretability, allowing structural components of a time series to be identified precisely. The article provides a detailed explanation of the mechanisms of adaptive normalization and attention, which ensure the model's resilience to changing market conditions.
preview
Machine Learning Under Constraint (Part 2): Calibrating Position Size to the Remaining Drawdown Budget

Machine Learning Under Constraint (Part 2): Calibrating Position Size to the Remaining Drawdown Budget

We present a rule-set-aware calibration chain that turns the remaining risk budget into a calibrated sigmoid scale for position sizing. It computes a ceiling from stop loss pct and safety factor, back-solves w at a reference divergence, and flattens size progressively as the budget shrinks. The paper also clarifies where leverage caps must be applied in production: at the lots conversion, since risk-based sizing alone does not enforce max leverage.
preview
Self-Optimizing Expert Advisors in MQL5 (Part 19): Parameter Optimization For Time-Lagged Independent Components Analysis (2)

Self-Optimizing Expert Advisors in MQL5 (Part 19): Parameter Optimization For Time-Lagged Independent Components Analysis (2)

The article shows how to tune ICA hyperparameters with a supervised evaluation pipeline and apply spectral clustering to time-lagged indicators. Cross-validation identifies the optimal number of clusters, which are translated into expected return and risk measures. These signals drive dynamic position sizing and stop-loss control, with surrogate models converted to ONNX and integrated into an MQL5 Expert Advisor.
preview
Machine Learning Under Constraint (Part 1): A Configurable Rule Set for Prop-Firm Position Sizing

Machine Learning Under Constraint (Part 1): A Configurable Rule Set for Prop-Firm Position Sizing

Hardcoded prop-firm rules lock the sizer to one program. This article factors those rules into a PropFirmRuleSet and refactors PropFirmAccountState and the sizing modifiers to consume it, including dynamic versus fixed daily limits and the news-window profit-credit haircut. Parity against the original FundedNext behavior is validated on a simulated equity path, so you can retarget sizing by configuration instead of rewriting code.
preview
Markov Chain Monte Carlo Sampling Methods: The HMC Algorithm

Markov Chain Monte Carlo Sampling Methods: The HMC Algorithm

The article examines the Hamiltonian Monte Carlo (HMC) algorithm — the gold standard for sampling from complex multivariate distributions. A full-featured implementation of HMC in MQL5 is presented, including adaptive mass matrix tuning, MAP estimation using the L-BFGS optimization method, and comprehensive diagnostics.
preview
Neural Networks in Trading: Disentangling Structured Components (SCNN)

Neural Networks in Trading: Disentangling Structured Components (SCNN)

We invite you to explore the innovative SCNN framework, which takes time series analysis to a new level by clearly separating data into long-term, seasonal, short-term, and residual components. This approach significantly improves forecasting accuracy by allowing the model to adapt to complex and changing market dynamics.
preview
Reinforcement Learning Meets MetaTrader 5: A Complete Pipeline for Training, Validating and Honestly Evaluating a Gold Trading Bot

Reinforcement Learning Meets MetaTrader 5: A Complete Pipeline for Training, Validating and Honestly Evaluating a Gold Trading Bot

This article presents a complete RL trading pipeline for XAUUSD: a supervised signal baseline with triple-barrier labels, PPO training, purged walk-forward validation with embargo, multi-seed checks, and contract-guarded deployment with normalization. It includes runnable code for data validation, features, environment, training, and broker‑based reconciliation. The live demo over 763 closed trades showed no statistically significant edge, and the methods highlight where information and costs, not architecture, set performance limits.
preview
Dandelion Optimizer (DO)

Dandelion Optimizer (DO)

The Dandelion Optimizer (DO) turns the simple flight of a seed carried by the wind into a mathematical search strategy. The three phases — vortex rising, drift toward the center of the population, and landing along a Lévy-flight trajectory — form an elegant metaphor that yields interesting results in practice.
preview
Combining LLM, CatBoost, and Quantum Computing into a Unified Trading System

Combining LLM, CatBoost, and Quantum Computing into a Unified Trading System

The article proposes a synthesis of new technologies to overcome the limitations of classical indicators in market data analytics. It shows how language models and quantum encoding can reveal hidden market patterns that traditional methods overlook. The experiment confirms the value of new technologies and proposes an updated analysis methodology aligned with the current state of computational innovation.
preview
MetaTrader 5 Machine Learning Blueprint (Part 20): Denoising, Detoning, and Clustering the Feature Correlation Matrix

MetaTrader 5 Machine Learning Blueprint (Part 20): Denoising, Detoning, and Clustering the Feature Correlation Matrix

Raw feature correlations contain estimation noise and a shared market-mode component that distort clustering. We fit the Marcenko–Pastur noise ceiling (with an effective sample size correction), apply constant-residual denoising and market detonation, and run the Optimal Number of Clusters routine. The result is a cleaned correlation matrix and stable cluster labels that avoid substitution effects and feed clustered MDI/MDA in the next article.
preview
Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (Conclusion)

Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (Conclusion)

We are pleased to present the final part of our series on GinAR — a neural network framework for time series forecasting. In this article, we analyze the results of testing the model on new data and assess its robustness under real-market conditions.
preview
Dendritic Cell Algorithm (DCA)

Dendritic Cell Algorithm (DCA)

The Dendritic Cell Algorithm (DCA) is a metaheuristic inspired by the mechanisms of the innate immune system. Dendritic cells patrol the search space, accumulate signals about the quality of positions, and reach a collective decision: whether to exploit what they have found or to continue exploration. Let's take a look at how a biological model for detecting pathogens is transformed into an optimization algorithm.
preview
Isolation Forest: Unsupervised Anomaly Detection, and What It Actually Finds in Price Data

Isolation Forest: Unsupervised Anomaly Detection, and What It Actually Finds in Price Data

This article implements a self-contained Isolation Forest library for MetaTrader 5 with no labels, no distribution assumptions and no external dependencies. It details a reproducible 64‑bit generator, tree/forest construction, scoring and feature design, then verifies results against Python and market data with two null models. The package includes an indicator that plots the decision variable and a gate example. Readers get a validated library, clear limits of applicability and a practical way to calibrate thresholds.
preview
Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (Key Components)

Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (Key Components)

We invite you to explore a new implementation of the key components of the GinAR framework — an adaptive algorithm for working with graph-structured time series. This article provides a step-by-step breakdown of the architecture and the algorithms for the forward pass and error backpropagation.
preview
Deterministic Dendritic Cell Algorithm (dDCA)

Deterministic Dendritic Cell Algorithm (dDCA)

The article presents an adaptation of the Deterministic Dendritic Cell Algorithm (dDCA) for continuous optimization problems. The algorithm, inspired by the immune system's Danger Theory, uses a signal accumulation mechanism to automatically balance exploration and exploitation within the search space.
preview
Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (GinAR)

Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (GinAR)

We invite you to explore an innovative approach to forecasting time series with missing data using the GinAR framework. The article demonstrates the implementation of key components using OpenCL, which ensures high performance. In our next publication, we will take a detailed look at how to integrate these solutions into MQL5. This will help understand how to apply the method in practice in trading.
preview
Quantum Computing and Gradient Boosting in EURUSD Trading

Quantum Computing and Gradient Boosting in EURUSD Trading

The article describes the practical implementation of a hybrid algorithmic trading system that combines quantum computing (IBM Qiskit) and gradient boosting (CatBoost) to predict movements in the EURUSD pair on the hourly time frame. The system extracts four unique quantum features from a probability distribution across 256 states using eight qubits and, in combination with classical indicators and delta encoding of time categories, achieves 62% accuracy on 15,000 candlesticks.
preview
Motifs and Discords: Building a Matrix Profile from Scratch

Motifs and Discords: Building a Matrix Profile from Scratch

We build the Matrix Profile for MQL5 from the ground up and keep it numerically stable on real prices. The library includes rolling statistics, a radix-2 FFT powering MASS, and a STOMP self-join, with results matched to stumpy. A compact facade, an indicator that draws the profile and flags discords, and a demonstration Expert Advisor show how to read and use the signal in practice.
preview
Hypothesis Testing for Trading Strategies — Proving Whether Your Edge is Real

Hypothesis Testing for Trading Strategies — Proving Whether Your Edge is Real

Net profit and win rate do not tell you if a strategy's edge is statistically real. This MQL5 toolkit analyzes return series built from price data or deal history and reports t‑statistics, p‑values, and confidence intervals using one-sample and Welch t‑tests, the Mann–Whitney U test, and volatility‑regime analysis to support evidence‑based trading decisions.
preview
Neural Networks in Trading: Probabilistic Time Series Forecasting (Conclusion)

Neural Networks in Trading: Probabilistic Time Series Forecasting (Conclusion)

We invite you to learn about the K²VAE framework and how the proposed approaches can be integrated into a trading system. You will learn how the hybrid Koopman–Kalman–VAE approach helps build adaptive and interpretable models. The article concludes with practical results from using the implemented solutions.
preview
Distribution-Free Price Channels in MQL5: Quantile Regression by Iteratively Reweighted Least Squares

Distribution-Free Price Channels in MQL5: Quantile Regression by Iteratively Reweighted Least Squares

We build a rolling price channel by fitting the 0.1, 0.5 and 0.9 conditional quantile lines via IRLS with pinball loss, packaged as a reusable class and two MetaTrader 5 indicators. We verify in-sample coverage, examine quantile crossing, and compare the channel width with ATR, Bollinger and regression widths on matched horizons. Tests in the Strategy Tester show the edges are descriptive, while the normalized width works as a volatility/regime feature.
preview
Meta-Labeling the Classics (Part 3): Filtering and Sizing Bollinger Band Trades

Meta-Labeling the Classics (Part 3): Filtering and Sizing Bollinger Band Trades

Bollinger Band mean reversion degrades in trending regimes when ADX is high and bandwidth expands. We separate direction from trade selection with a two‑stage meta‑labeling pipeline: a gradient‑boosted secondary classifier trained with PurgedKFold on band‑specific features (BBP, BBB, bandwidth regime) outputs action probabilities that drive probability‑based bet sizing. The MQL5 implementation loads the ONNX model and applies position sizing within a two‑EA architecture to filter low‑quality band touches.
preview
Measuring Market Efficiency with Lempel-Ziv Complexity

Measuring Market Efficiency with Lempel-Ziv Complexity

This article presents a compact MQL5 library for market-complexity analysis: LZ76 complexity and Normalized Compression Distance built on a SAX symbolizer, exposed through a simple facade and an efficiency indicator. It explains the discretization choices, normalization, and distance formulation, and validates the code with unit checks and an independent cross-check. You get a ready-to-use library and indicator, plus a disciplined way to interpret readings with a shuffle null and a direction check.
preview
Online Machine Learning for Trade Signal Filtering in MQL5 (Part 1)

Online Machine Learning for Trade Signal Filtering in MQL5 (Part 1)

This article implements an online logistic‑regression trade filter in native MQL5 and integrates it into an EMA‑crossover EA with a closed‑trade feedback loop. It details the shared class, features, SGD update, persistence, and a read‑only probability view. Synthetic experiments cover multi‑seed separation, calibration, feature ablation, regime‑shift baselines, and hyperparameter sweeps. You get reproducible scripts and a walk‑forward protocol to validate the filter on your own instrument.
preview
Beyond the Mean and Standard Deviation: A Robust Statistics Library for MQL5 Indicators

Beyond the Mean and Standard Deviation: A Robust Statistics Library for MQL5 Indicators

Price outliers distort indicators based on the mean and standard deviation. This article delivers a robust MQL5 library (RobustStats.mqh) implementing the median, 1.4826-scaled MAD, and Theil–Sen slope, plus three drop‑in indicators that replace Bollinger Bands, the linear regression channel, and the z‑score oscillator. A comparison overlay and a breakdown‑point measurement on EURUSD show how the robust instruments hold their shape when a single spike moves the classical ones.
preview
Python + LLM API + MetaTrader 5: Real-World Experience Building an Autonomous Trading Bot

Python + LLM API + MetaTrader 5: Real-World Experience Building an Autonomous Trading Bot

The article describes the development of an MVP prototype for an autonomous trading bot for MetaTrader 5 that uses large language models (LLMs) via the OpenRouter API to analyze the market and make trading decisions. A Python script retrieves historical OHLCV data, sends it to an LLM for technical analysis based on support/resistance levels and Price Action patterns, and then automatically places orders with specified stop loss and take profit levels.
preview
Neural Networks in Trading: Probabilistic Time Series Forecasting (Encoder)

Neural Networks in Trading: Probabilistic Time Series Forecasting (Encoder)

We invite you to explore a new approach that combines classical methods and modern neural networks for time series analysis. The article provides a detailed explanation of the architecture and operating principles of the K²VAE model.
preview
Fast Integration of a Large Language Model with MetaTrader 5 (Part II): Fine-Tuning on Real Data, Backtesting, and Live Trading by the Model

Fast Integration of a Large Language Model with MetaTrader 5 (Part II): Fine-Tuning on Real Data, Backtesting, and Live Trading by the Model

The article describes the process of fine-tuning a language model for trading based on real historical data from MetaTrader 5. The base model, which has only theoretical knowledge of technical analysis, is trained on a thousand examples of the real behavior of currency pairs (EURUSD, GBPUSD, USDCHF, USDCAD) over 180 days. After being trained using Ollama, the model begins to understand the specific characteristics of each instrument.
preview
Self Optimizing Expert Advisors in MQL5 (Part 18): Time Lagged Independent Components Analysis

Self Optimizing Expert Advisors in MQL5 (Part 18): Time Lagged Independent Components Analysis

We evaluate blind source separation for market noise control using FastICA applied to SMA-filtered, time-lagged OHLC features. The study compares classical and surrogate targets, measures accuracy across lags, tunes KNN models, and inspects residual structure with clustering. Models are exported to ONNX and integrated into an MQL5 Expert Advisor for testing. The result is a reproducible pipeline from data extraction to deployment.
preview
Differential Search Algorithm (DSA)

Differential Search Algorithm (DSA)

The article discusses the Differential Search Algorithm (DSA), which simulates the migration of a superorganism in search of optimal living conditions. The algorithm uses a Gamma distribution to generate a pseudo-stable random walk and offers four strategies for selecting the direction of movement, along with three coordinate mutation mechanisms. How will this method perform?
preview
Neural Networks in Trading: Probabilistic Time Series Forecasting (K2VAE)

Neural Networks in Trading: Probabilistic Time Series Forecasting (K2VAE)

We invite you to explore the original implementation of the K²VAE framework — a flexible model capable of linearly approximating complex dynamics in latent space. This article demonstrates how to implement key components in MQL5, including parameterized matrices and how to manage them outside standard neural network layers. This material will be useful for anyone looking for a practical approach to building interpretable time-series models.
preview
Foundation Models for Trading (Part II): Decoding, Autoregression, and an Exact KV-Cache

Foundation Models for Trading (Part II): Decoding, Autoregression, and an Exact KV-Cache

We complete the native MQL5 port of Kronos: the decoder, the predictor's decode_s1 and decode_s2 stages with their cross-attention traps, and the autoregressive loop that produces a multi-bar forecast. Then we profile and make it roughly 4.5x faster with an exact KV-cache and pre-transposed weights, verifying every stage against PyTorch.