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
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.
preview
Feature Engineering for ML (Part 13): Trend-Scanning Features in Python

Feature Engineering for ML (Part 13): Trend-Scanning Features in Python

Trend-scanning supports both forward and backward windows, and the labeling default is unsafe for features: it looks ahead and boosts next-bar agreement well above chance on random walks. We provide a dedicated wrapper, get trend scanning features, that forces computational causal and returns only window, slope, t value, and rsquared. A second analysis quantifies errors introduced by the default log transform on signed series.
preview
Neural Networks in Trading: Adaptive Periodic Segmentation (Conclusion)

Neural Networks in Trading: Adaptive Periodic Segmentation (Conclusion)

We invite you to dive into the exciting world of LightGTS — a lightweight yet powerful framework for time-series forecasting, where adaptive convolution and RoPE encoding are combined with innovative attention mechanisms. In our article, you will find a detailed description of all components — from creating patches to the complex mixture of experts in the decoder — ready for integration into MQL5 projects. Discover how LightGTS takes automated trading to a whole new level!
preview
Bonobo Optimizer (BO)

Bonobo Optimizer (BO)

The article presents the implementation and analysis of the Bonobo Optimizer algorithm, which is based on the unique behavioral characteristics of bonobos — their dynamic fission-fusion social structure and three mating strategies. What interesting features does this method have?
preview
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 5): Pre-Backtest Evaluation of Machine-Learning-Generated Signals Through Formulaic Alphas

Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 5): Pre-Backtest Evaluation of Machine-Learning-Generated Signals Through Formulaic Alphas

The article shows how to evaluate machine-learning alphas before a full backtest by expressing them as formulaic alphas. We compute Information Coefficient (IC), Rank IC, Information Ratio (ICIR), and t-statistics to quantify forecasting strength and stability. A MetaTrader 5 backtest illustrates differences versus execution-dependent tests, and a Python parser facilitates reproducible calculations and bulk screening.
preview
Neural Networks in Trading: Adaptive Periodic Segmentation (Creating Tokens)

Neural Networks in Trading: Adaptive Periodic Segmentation (Creating Tokens)

We invite you to embark on an exciting journey through the world of adaptive analysis of financial time series and learn how to turn complex spectral analysis and flexible convolution into real trading signals. You will see how LightGTS listens to the market rhythm, adapting to its changes through a variable-window stride, and how OpenCL acceleration can turn computation into a fast track to profitable decisions.
preview
Learnable Curves, Not Weights: A Kolmogorov-Arnold Network from Scratch

Learnable Curves, Not Weights: A Kolmogorov-Arnold Network from Scratch

This article builds a Kolmogorov–Arnold Network (KAN) in MQL5, where every edge carries a learnable B‑spline curve rather than a scalar weight. We construct the spline basis, assemble edges and a layer, and fit all coefficients by ridge‑regularized least‑squares in a single solve. The model is delivered as an indicator that visualizes the learned curves and an Expert Advisor that acts on the prediction, providing an interpretable, reusable codebase.
preview
Neural Networks in Trading: Adaptive Periodic Segmentation (LightGTS)

Neural Networks in Trading: Adaptive Periodic Segmentation (LightGTS)

We invite you to learn about the innovative technique of adaptive patching — a method for flexibly segmenting time series while taking their internal periodicity into account. We will also look at an efficient encoding technique that preserves important semantic characteristics when working with data at different scales. These methods open up new possibilities for the accurate processing of complex, multiscale data characteristic of financial markets and significantly improve the stability and reliability of forecasts.
preview
Elite Crystal Evolution Algorithm (CEO-inspired): Practical Implementation

Elite Crystal Evolution Algorithm (CEO-inspired): Practical Implementation

Experimental evaluation on standard benchmark functions reveals the advantages and limitations of directly adapting combinatorial algorithms. The article provides a detailed description of the ECEA algorithm's mechanisms and test results.
preview
Measuring What Matters (Part 3): The Reconstruction Engine — Validating Risk Footprints with Matrix Algebra

Measuring What Matters (Part 3): The Reconstruction Engine — Validating Risk Footprints with Matrix Algebra

This article performs a numerical verification of MQL5 eigendecomposition for a covariance matrix using the spectral theorem A = V Λ Vᵀ. It reconstructs the matrix with Diag(), Transpose(), and MatMul(), computes the residual and its Frobenius norm, and shows that deviations remain at floating‑point precision, with results printed to the Experts journal.
preview
Neural Networks in Trading: An Intelligent Forecast Pipeline (Conclusion)

Neural Networks in Trading: An Intelligent Forecast Pipeline (Conclusion)

The article provides a fascinating look at how SwiGLU embedding reveals hidden market patterns, and how a sparse Mixture of Experts within a Decoder-Only Transformer makes forecasts more accurate at reasonable computational cost. We take an in-depth look at the integration of Time‑MoE into MQL5 and OpenCL, and provide a step-by-step guide to configuring and training the model.
preview
Machine Learning Without the Black Box: The Tsetlin Machine for Trading

Machine Learning Without the Black Box: The Tsetlin Machine for Trading

This article builds a white-box classifier in MQL5 using the Tsetlin Machine. It learns human-readable AND-rules instead of weights, trains with integer state updates, and requires no external dependencies. You will assemble the automaton, clause, and multi-class voter, verify on XOR and other boolean tasks, booleanize indicators, label by forward ATR-scaled return, save the model to CSV, and view active rules on a live chart.
preview
Neural Networks in Trading: An Intelligent Forecast Pipeline (Sparse Mixture of Experts)

Neural Networks in Trading: An Intelligent Forecast Pipeline (Sparse Mixture of Experts)

We invite you to explore the practical implementation of a sparse mixture of experts block for time series in the OpenCL computing environment. This article provides a step-by-step explanation of how masked multi-window convolution works, as well as how gradient-based training is organized in the presence of multiple information streams.
preview
Elite Crystal Evolution Algorithm (CEO-inspired): Theory

Elite Crystal Evolution Algorithm (CEO-inspired): Theory

A new original population-based algorithm, ECEA, is presented. Inspired by the process of water freezing, it adapts ideas from the Crystal Energy Optimizer (CEO) algorithm, which uses graph-based search, for general optimization problems. The algorithm uses a dynamic elite group, three search strategies, and a periodic diversification mechanism.
preview
Quick Integration of a Large Language Model into MetaTrader 5 (Part I): Building the Model

Quick Integration of a Large Language Model into MetaTrader 5 (Part I): Building the Model

The article explores the revolutionary integration of large language models (LLMs) with the MetaTrader 5 trading platform, where AI does not simply predict prices but makes autonomous trading decisions by analyzing market context much like an experienced trader. The author highlights a fundamental difference between LLMs and classical machine learning models such as CatBoost — the ability to engage in metacognition and self-reflection, which allows the system to learn from its own mistakes and improve its strategy.
preview
Neural Networks in Trading: An Intelligent Forecast Pipeline (Time-MoE)

Neural Networks in Trading: An Intelligent Forecast Pipeline (Time-MoE)

We invite you to explore the modern Time-MoE framework, which has been adapted for time series forecasting tasks. In this article, we will implement the key components of the architecture step by step, providing explanations and practical examples along the way. This approach will allow you not only to understand how the model works, but also to apply those principles to real-world trading scenarios.
preview
A Team of AI Agents with Profit-Based Rotation: The Evolution of a Living Trading System in MQL5

A Team of AI Agents with Profit-Based Rotation: The Evolution of a Living Trading System in MQL5

Financial management as an ecosystem: Seven AI traders with different personalities and strategies instead of a single algorithm. They compete for capital, learn from their mistakes, and make decisions collectively. The article explains the principles behind the Modern RL Trader system, in which the code possesses consciousness and emotions, creating a living, evolving trading mind.
preview
Feature Engineering for ML (Part 11): Fractal Features in Python

Feature Engineering for ML (Part 11): Fractal Features in Python

The article examines a Williams five‑bar fractal feature pipeline and shows how a centered rolling window creates a true look‑ahead leak. It identifies two additional silent bugs—a hardcoded shift tied to the default n and a volatility threshold that ignores its input—and consolidates fixes under a single leak_safe flag. Readers get leak‑free fractal, level, trend, and signal features, plus guidance on when unshifted columns remain valid for labeling.
preview
Integrating MQL5 with Data Processing Packages (Part 10): Deploying Python AutoML Pipelines for Strategy Testing

Integrating MQL5 with Data Processing Packages (Part 10): Deploying Python AutoML Pipelines for Strategy Testing

This article presents a reproducible MetaTrader 5 workflow: collect history, engineer nine context features, label simulated EMA crossover trades, train with FLAML, and export to ONNX with fixed opset and plain probabilities. The Expert Advisor loads the model natively, mirrors the Python feature contract, and uses a tunable confidence threshold as a trade filter. Readers can swap signals and features to reuse the same pipeline.
preview
Neural Networks in Trading: A Cross-Domain Time Series Forecasting Framework (Conclusion)

Neural Networks in Trading: A Cross-Domain Time Series Forecasting Framework (Conclusion)

The article focuses on the practical implementation of the TimeFound model for time series forecasting. The key stages of implementing the framework's main approaches using MQL5 are examined.
preview
MCMC Sampling Methods: The Slice Sampling Algorithm

MCMC Sampling Methods: The Slice Sampling Algorithm

The article examines slice sampling — an adaptive MCMC algorithm that automatically adjusts its sampling parameters. Its effectiveness is demonstrated using Bayesian linear and logistic regression models, and the results are compared with classical frequentist methods.
preview
A Reinforcement Learning System for Algorithmic Trading in MQL5

A Reinforcement Learning System for Algorithmic Trading in MQL5

The article describes the development of a multi-agent machine learning system for algorithmic trading on MetaTrader 5 based on reinforcement learning. The system has a three-tier architecture: memory neurons store experience, agents make independent decisions, and the collective mind combines them through weighted voting. The system is continuously improved through Q-learning, pruning of ineffective neurons, and evolutionary reduction of exploration.
preview
Neural Networks in Trading: A Cross-Domain Time Series Forecasting Framework (TimeFound)

Neural Networks in Trading: A Cross-Domain Time Series Forecasting Framework (TimeFound)

In this article, we build the core of the TimeFound intelligent model step by step, adapting it to real-world time series forecasting tasks. If you are interested in the practical implementation of neural network patching algorithms in MQL5, you have come to the right place.
preview
Implementing and Benchmarking Bag-of-SFA-Symbols (BOSS) Against Dynamic Time Warping (DTW)

Implementing and Benchmarking Bag-of-SFA-Symbols (BOSS) Against Dynamic Time Warping (DTW)

This article implements BOSS from scratch in MQL5 and applies it to regime classification: SFA turns windows into words, bags record word frequencies, and an ensemble over window lengths votes on labels. We cover the encoding steps, the BOSS distance, training with auto-generated regime labels, and practical parameters. A BTCUSD benchmark versus DTW shows higher macro accuracy on clean data and markedly faster inference.
preview
Crystal Structure Algorithm (CryStAl)

Crystal Structure Algorithm (CryStAl)

This article presents two versions of the Crystal Structure Algorithm: the original and the modified version. The Crystal Structure Algorithm (CryStAl), published in 2021 and inspired by the physics of crystal structures, was positioned as a parameter-free metaheuristic for global optimization. However, testing revealed a critical problem with the algorithm. A modified version, CryStAlm, is also presented; it addresses the original's key shortcomings.
preview
MCMC Sampling Methods — The Metropolis-Hastings Algorithm

MCMC Sampling Methods — The Metropolis-Hastings Algorithm

The Metropolis-Hastings algorithm is a fundamental Markov chain Monte Carlo (MCMC) method that is widely used to approximate posterior distributions in Bayesian inference. This article describes the theoretical foundations of the algorithm, the implementation of the MHSampler class in MQL5, and examples of its application, including an analysis of the resulting samples.
preview
Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Final Part)

Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Final Part)

The Mantis framework transforms complex time series into informative tokens and serves as a reliable foundation for an intelligent trading agent capable of operating in real time.
preview
Kohonen Self-Organizing Maps in an MQL5 Expert Advisor

Kohonen Self-Organizing Maps in an MQL5 Expert Advisor

Kohonen's self-organizing maps transform the chaos of market data into an ordered two-dimensional map, where similar patterns are grouped together. The article demonstrates a complete implementation of a SOM in an MQL5 Expert Advisor with 400 neurons and continuous learning. We break down the Best Matching Unit search algorithm, weight updates using a Gaussian neighborhood function, integration with quantum effects, and the generation of trading signals. The code is open-source, the math is clear, and the results are verifiable.
preview
Artificial Coronary Circulation Algorithm (ACCS)

Artificial Coronary Circulation Algorithm (ACCS)

A metaheuristic algorithm that simulates the growth of coronary arteries in the human heart for optimization problems. It uses the principles of angiogenesis (the growth of new blood vessels), bifurcation (branching), and pruning of weak branches to find optimal solutions in a multidimensional space. Testing its effectiveness across a wide range of tasks yielded unexpected results.
preview
Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Building Objects)

Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Building Objects)

Mantis is a versatile tool for in-depth time series analysis that can be flexibly scaled to accommodate any financial scenario. Learn how a combination of patching, local convolutions, and cross-attention enables a highly accurate interpretation of market patterns.
preview
Analysis of the Impact of Solar and Lunar Cycles on Currency Exchange Rates

Analysis of the Impact of Solar and Lunar Cycles on Currency Exchange Rates

What if lunar cycles and seasonal patterns influence the foreign exchange markets? This article shows how to translate astrological concepts into the language of mathematics and machine learning. I built a Python system with 88 features based on astronomical cycles, trained CatBoost on 15 years of EURUSD data, and obtained some intriguing results. The code is open-source, the methods are verifiable, and the conclusions are unexpected — ancient wisdom meets gradient boosting.
preview
Porting the Canonical Catch22 Time-Series Feature Set and Testing It on Volatility Regimes

Porting the Canonical Catch22 Time-Series Feature Set and Testing It on Volatility Regimes

We present a native MQL5 implementation of the catch22 feature set: all 22 canonical time-series characteristics in a reusable class validated against pycatch22. Using a leak-free pipeline (chronological split, purging, embargo), we run a three-arm ablation—classic indicators, catch22, and combined—for volatility-regime classification. Finally, we deploy the combined model as a Strategy Tester regime filter to quantify its impact on a simple baseline strategy.
preview
Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Mantis)

Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Mantis)

Meet Mantis — a lightweight foundation model for time series classification based on a Transformer architecture, featuring contrastive pre-training and hybrid attention that deliver record-breaking accuracy and scalability.