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: Heterogeneity-Informed Meta-Parameter Learning (HimNet)

Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (HimNet)

We invite you to explore the HimNet framework, which combines the flexibility of spatio-temporal adaptation with high computational efficiency, enabling accurate and stable forecasts for financial time series. The article explains in detail how its key components interact with one another, transforming complex algorithms into a manageable architecture.
preview
Beetle Swarm Optimization (BSO)

Beetle Swarm Optimization (BSO)

We consider a BAS+PSO (BSO) hybrid, where BAS provides a local direction signal and PSO facilitates the exchange of best solutions within the swarm. The article presents a mathematical model, pseudocode, an implementation of the class in MQL5, and test results from a standard test bench. This material allows reproducing the algorithm, configuring its parameters, and understanding how three objective-function evaluations per iteration affect efficiency.
preview
Machine Learning in Pure MQL5 (Part 1): Logistic Regression from Scratch with SGD

Machine Learning in Pure MQL5 (Part 1): Logistic Regression from Scratch with SGD

The series develops machine learning in 100% native MQL5 with no external dependencies. Part 1 delivers logistic regression from first principles: a CLogReg class with standardization, a stable sigmoid, SGD training, and model persistence, plus a script that builds ATR-normalized features, labels the next bar, and tests out-of-sample against a baseline. Readers get a compact include file and a clear template for leakage-free evaluation.
preview
Defining your Edge (Part 5): Using GARCH Variance and Volatility-Scaled LSTM in an Expert Advisor

Defining your Edge (Part 5): Using GARCH Variance and Volatility-Scaled LSTM in an Expert Advisor

We merge GARCH(1,1) variance projections with ATR plus Bollinger-Bands patterns to form an algorithm that could optionally be used with volatility-scaled LSTM within LSTM Wizard-ready signal class. We cover feature scaling, mode scoring, thresholds, and safety checks. Readers can replicate backtest/forward test results to verify if the recurrent layer gives incremental discrimination over our deterministic baseline.
preview
Neural Networks in Trading: The Temporal Query Model (Conclusion)

Neural Networks in Trading: The Temporal Query Model (Conclusion)

We are pleased to present the final stage of the TQNet framework’s development and testing, where theory meets real-world trading practice. We will move from historical training to a stress test using recent market data, evaluating the model's robustness and accuracy. The final results are not just dry statistics, but also a clear demonstration of the practical value of the proposed approach.
preview
The ZeroMQ Message Transfer Protocol in MQL5: Implementing the REQ/REP pattern

The ZeroMQ Message Transfer Protocol in MQL5: Implementing the REQ/REP pattern

This article presents a native MQL5 implementation of the ZeroMQ Message Transfer Protocol (ZMTP) built on raw MQL5 sockets. It explains the REQ/REP pattern via the CZmqReqSocket class, including framing, handshake, and strict send/receive alternation. A practical pipeline shows an MQL5 script streaming returns to a Python/R server running MS‑GARCH and receiving regime probabilities, enabling integration without DLLs.
preview
Native Isolation Forest for Execution-Quality Anomaly Detection in MQL5

Native Isolation Forest for Execution-Quality Anomaly Detection in MQL5

A step-by-step guide to a native Isolation Forest in MQL5 focused on execution metrics rather than price. It details five features, tree construction and path‑length scoring, rolling‑window training, CSV logging, and FILE_COMMON persistence, all integrated into OnTradeTransaction(). The resulting circuit breaker flags unusual fills in real time and applies controlled responses to stabilize live trading under changing execution conditions.
preview
Development and Forward Testing of an Autonomous LLM Agent for Trading with SEAL

Development and Forward Testing of an Autonomous LLM Agent for Trading with SEAL

A hybrid architecture based on Llama 3.2 and SEAL is being tested on eight currency pairs (M15), with forward-period data isolation and information leakage control. The methodology combines adversarial self-play, curriculum learning, and class balancing to ensure stable training. The experiments confirm the gap between forecast accuracy and actual returns, providing readers with practical guidelines for testing strategies and accurately assessing their generalizability.
preview
Butterfly Optimization Algorithm (BOA)

Butterfly Optimization Algorithm (BOA)

The article discusses the Butterfly Optimization Algorithm, which is based on modeling foraging using the sense of smell. We will analyze the original formulas, identify and correct errors in motion equations, add a mechanism for maintaining population diversity, and present the test results.
preview
Neural Networks in Trading: The Temporal Query Model (TQNet)

Neural Networks in Trading: The Temporal Query Model (TQNet)

The TQNet framework opens up new possibilities for modeling and forecasting financial time series by combining modularity, flexibility, and high performance. The article explores the possibility of implementing complex mechanisms for handling global correlations, including advanced parameter initialization methods.
preview
Measuring What Matters (Part 4): Reading the Spectrum — What Eigenvalues Tell You About Risk

Measuring What Matters (Part 4): Reading the Spectrum — What Eigenvalues Tell You About Risk

We turn eigenvalues from a covariance matrix into a normalized spectral‑entropy score that measures how evenly variance is spread across factors. SpectralEntropyCalculator.mq5 compares two portfolios in one run, using native vector summation, ArraySort()-based ordering, element‑wise division, and the Shannon entropy formula. The report makes dominant factors visible and enables quick, repeatable checks of diversification quality.
preview
Defining your Edge (Part 4): Applying Isotonic Regression and PNN Price-Forecasting in an Expert Advisor

Defining your Edge (Part 4): Applying Isotonic Regression and PNN Price-Forecasting in an Expert Advisor

We consider the methods with which Isotonic Regression calibrates raw RSI, Stochastic and price-action signal scores into probabilities that are sorted, while a separate Probability based Neural Network evaluates similar historical market states. This article uses both approaches in a ready-made MQL5 custom signal class that is compatible with MQL5 Wizard and provides up to 7 selectable entry modes. Reproducible tests compare isotonic-only signals with the combined Isotonic-PNN model to assess whether the network adds useful information beyond the simpler baseline.
preview
Enhanced Colliding Bodies Optimization (ECBO)

Enhanced Colliding Bodies Optimization (ECBO)

The article discusses the Colliding Bodies Optimization (CBO) algorithm, which is based on the physics of one-dimensional collisions between bodies. The basic version of the algorithm does not include any configurable parameters, which makes it simple. Therefore, the enhanced ECBO version — supplemented with Colliding Memory and a crossover mechanism — was used as the basis for the implementation, allowing the algorithm to achieve respectable results and earn a place in the ranking table.
preview
How to Create and Adapt an RL Agent with an LLM and Quantum Encoding for Algorithmic Trading in MQL5

How to Create and Adapt an RL Agent with an LLM and Quantum Encoding for Algorithmic Trading in MQL5

The article proposes a hybrid approach to algorithmic trading based on quantum encoding of market states, Double DQN with a prioritized experience replay buffer, and an LLM acting as a contextual EA. The SEAL methodology enables asynchronous continued training of the agent without halting trading. A lightweight Q-learning filter (USE/SKIP/REDUCE) controls signal execution at the meta-level. Practical details are provided on integrating the system with the MetaTrader 5 trading platform, along with a scheme for adapting it to market regime shifts.
preview
Neural Networks in Trading: Decomposition Instead of Scaling (Conclusion)

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

We invite you to learn about an algorithm for decomposing a time series into meaningful layers and using them to build a parsimonious model. We systematically present the architecture, the practical implementation in MQL5/OpenCL, and real-world tests using historical market data.
preview
Cricket Algorithm (CA)

Cricket Algorithm (CA)

The article discusses the Cricket Algorithm, a metaheuristic optimization method that combines elements of the Bat Algorithm and the Firefly Algorithm with the physical laws governing the propagation of sound in the atmosphere. The algorithm simulates the behavior of crickets that navigate by the chirping of their conspecifics, using Dolbear's law and acoustic formulas to guide the search for best solutions.
preview
Neural Networks in Trading: Decomposition Instead of Scaling — Building Modules

Neural Networks in Trading: Decomposition Instead of Scaling — Building Modules

In this article, we continue our hands-on exploration of SSCNN — a next-generation architectural solution capable of processing fragmented time series. Instead of blind scaling — smart modularity, attention to detail, and targeted normalization. Step by step, we are creating computational blocks in the MQL5 environment and laying the foundation for reliable predictive analysis.
preview
Working with ONNX Models in MQL5 (Part 1): Decoding the Model File with a Protobuf Parser

Working with ONNX Models in MQL5 (Part 1): Decoding the Model File with a Protobuf Parser

We decode ONNX files in pure MQL5 by implementing a Protocol Buffers reader from scratch. We generate a sample network in Python, verify it in Netron, and then parse the same binary to recover graph nodes, connections, weight tensors, and input/output shapes. The result is a MetaTrader 5 program that inspects a trained model's structure before inference, without any external libraries.
preview
Implementing a Continuous LLM Adaptation System for Algorithmic Trading

Implementing a Continuous LLM Adaptation System for Algorithmic Trading

SEAL (Self-Evolving Adaptive Learning) is a system for the continuous adaptation of large language models (LLMs) for algorithmic trading, designed to address the problem of rapid model degradation in changing markets. Instead of periodic retraining, which takes hours and erases old patterns, SEAL learns from every closed trade, maintains priority memory for important examples, and automatically initiates incremental fine-tuning when accuracy drops or a market regime change occurs.
preview
Eco-inspired Evolutionary Algorithm (ECO)

Eco-inspired Evolutionary Algorithm (ECO)

The article discusses the ECO optimization algorithm, which is based on ecological concepts: populations are grouped into habitats based on territorial proximity, exchange genetic material within habitats, and migrate between them. Despite its wide range of operators and elegant biological metaphor, the algorithm produced a certain result discussed below.
preview
Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Conclusion)

Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Conclusion)

The article will show you how Mamba4Cast turns theory into a working trading algorithm and lays the groundwork for your own experiments. Do not miss this opportunity to gain a full range of knowledge and inspiration for developing your own strategy.
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.