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 GARCH (Part III): Building the MMAR and the Verdict

Beyond GARCH (Part III): Building the MMAR and the Verdict

With the multifractal parameters from Part 2 in hand, this article builds the full MMAR process. We construct the multiplicative cascade for trading time, generate Fractional Brownian Motion via Davies-Harte FFT, and combine both into X(t) = B_H[theta(t)]. A 100-path Monte Carlo simulation produces the volatility forecast, which we then pit against GARCH on the same EURUSD M5 data. Does Mandelbrot's fractal architecture outforecast Engle's conditional variance framework? Part 3 of a eight-part series leading to a native MQL5 library and Expert Advisor.
preview
MetaTrader 5 Machine Learning Blueprint (Part 16): Nested CV for Unbiased Evaluation

MetaTrader 5 Machine Learning Blueprint (Part 16): Nested CV for Unbiased Evaluation

The article presents a V-in-V nested cross-validation pipeline for financial data that breaks leakage at three decision points: hyperparameter search, calibration, and final evaluation. A temporal three‑zone split isolates an inner walk‑forward search with the 1‑SE rule from an outer walk‑forward or CPCV evaluation, while OOF isotonic calibration is fitted independently. The resulting UnifiedValidationCalibrator delivers unbiased out‑of‑sample scores and well‑calibrated probabilities for deployment.
preview
MQL5 Wizard Techniques you should know (Part 90): Fenwick Tree Money Management with 1D CNN in MQL5

MQL5 Wizard Techniques you should know (Part 90): Fenwick Tree Money Management with 1D CNN in MQL5

This article implements a Fenwick Tree (Binary Indexed Tree) for volume-aware money management inside an MQL5 Wizard Expert Advisor. We structure cumulative volume in O(log n) and apply four scaling modes—linear, conservative, aggressive, and mean-reversion—optionally gated by a lightweight 1D CNN. Practical tests compare the algorithm alone versus the CNN‑filtered approach to illustrate adaptive lot sizing and risk control under varying volume topologies.
preview
Eagle Strategy (ES)

Eagle Strategy (ES)

Eagle Strategy is an algorithm that mimics the eagle's two-phase hunting strategy: global search via Levy flights using Mantegna method, alternating with intense local exploitation using the firefly algorithm, a mathematically sound approach to balancing exploration and exploitation, and a bioinspired concept that combines two natural phenomena into a single computational method.
preview
Beyond GARCH (Part II): Measuring the Fractal Dimension of Markets

Beyond GARCH (Part II): Measuring the Fractal Dimension of Markets

Building on the partition function analysis from Part 1, this article deepens the theoretical foundation before completing the analytical pipeline. We first give a full treatment of the Hurst exponent: what it measures, what it implies about market memory, and why it matters for the MMAR. This is followed by an intuitive exploration of multifractal spectra and what f(α) reveals about volatility heterogeneity. We then move to implementation: extracting the scaling function τ(q), estimating H via R/S analysis, and fitting the multifractal spectrum across four candidate distributions. By the end, we have the complete parameter set needed to construct the MMAR process in Part 3. Part 2 of an eight-part series.
preview
Determining Fair Exchange Rates Using PPP and IMF Data

Determining Fair Exchange Rates Using PPP and IMF Data

Building a purchasing power parity (PPP)-based exchange rate analysis system using Python. The author developed an algorithm with 5 methods for calculating fair exchange rates using IMF data. A practical guide to fundamental currency analysis, economic data processing, and integration with trading systems. Full code in open source.
preview
Building an Object-Oriented ONNX Inference Engine in MQL5

Building an Object-Oriented ONNX Inference Engine in MQL5

This article shows how to run Python-trained models natively in MetaTrader 5 via the terminal's ONNX functions. We build an MQL5 class that encapsulates session creation, fixes input/output tensor shapes, applies min-max feature normalization to mirror training, and executes OnnxRun once per bar to protect the CPU, the result is a reliable, maintainable inference path for live charts and the Strategy Tester without sockets or DLLs.
preview
Integrating MQL5 with Data Processing Packages (Part 9): Entropy-Based Adaptive Volatility

Integrating MQL5 with Data Processing Packages (Part 9): Entropy-Based Adaptive Volatility

This work presents an end-to-end pipeline: collect MetaTrader 5 data, engineer entropy/volatility/trend features, train a PyTorch classifier, and expose predictions through a Flask API. An MQL5 EA posts rolling prices each tick, receives probability and regime, and applies adaptive position sizing and stop distances. The result is a clear recipe for integrating ML inference with MetaTrader 5.
preview
MQL5 Wizard Techniques you should know (Part 89): Using Bitwise Vectorization with Perceptron Classifiers

MQL5 Wizard Techniques you should know (Part 89): Using Bitwise Vectorization with Perceptron Classifiers

This article presents a custom MQL5 signal class, CSignalBitwisePerceptron, for ultra-lightweight entry logic. It packs 64 bars into a single uint64 via bitwise vectorization and evaluates them with a perceptron that sums weights only for active bits. A two-gate flow (algorithmic hash map plus neural threshold) minimizes array iteration and heavy math. Readers get a practical template to cut latency and refine entry validation.
preview
Beyond GARCH (Part I): Mandelbrot's MMAR versus Engle's GARCH

Beyond GARCH (Part I): Mandelbrot's MMAR versus Engle's GARCH

This article starts the MMAR pipeline on EURUSD M5 data. We load market data via the MetaTrader5 Python API and run partition-function analysis with non-overlapping intervals to test for multifractal scaling. The result is an evidence-based decision on fractality, a prerequisite for building MMAR and for choosing whether to proceed beyond GARCH.
preview
Downloading International Monetary Fund Data Using Python

Downloading International Monetary Fund Data Using Python

Downloading international monetary fund data in Python: Mining IMF data for use in macroeconomic currency strategies. How can macroeconomics help an ordinary and an algorithmic trader?
preview
Biogeography-Based Optimization (BBO)

Biogeography-Based Optimization (BBO)

Biogeography-Based Optimization (BBO) is an elegant global optimization method inspired by natural processes of species migration between islands within archipelagos. The algorithm is based on a simple yet powerful idea: high-quality solutions actively share their characteristics, while low-quality ones actively adopt new features, creating a natural flow of information from the best solutions to the worst. A unique adaptive mutation operator provides an excellent balance between exploration and exploitation. BBO demonstrates high efficiency on a variety of tasks.
preview
From Matrices to Models: How to Build an ML Pipeline in MQL5 and Export It to ONNX

From Matrices to Models: How to Build an ML Pipeline in MQL5 and Export It to ONNX

The article describes the arrangement of a coordinated ML pipeline in MetaTrader 5 with separation of roles: Python trains and exports the model to ONNX, MQL5 reproduces normalization and PCA via matrix/vector and performs inference. This approach makes the model's inputs stable and verifiable, and the MetaTrader 5 strategy tester provides metrics for analyzing the system behavior.
preview
Exploring Conformal Forecasting of Financial Time Series

Exploring Conformal Forecasting of Financial Time Series

In this article, we will consider conformal predictions and the MAPIE library that implements them. This approach is one of the most modern ones in machine learning and allows us to focus on risk management for existing diverse machine learning models. Conformal predictions, by themselves, are not a way to find patterns in data. They only determine the degree of confidence of existing models in predicting specific examples and allow filtering for reliable predictions.
preview
MetaTrader 5 Machine Learning Blueprint (Part 15): How to Calibrate Profit-Taking and Stop-Loss Targets from Synthetic Data

MetaTrader 5 Machine Learning Blueprint (Part 15): How to Calibrate Profit-Taking and Stop-Loss Targets from Synthetic Data

This article applies the Optimal Trading Rule from AFML Chapter 13 to set profit targets and stop-losses without in-sample calibration. We model post-entry P&L with a discrete Ornstein–Uhlenbeck process, run a 100,000-path search, and implement Python, multiprocessing, and a Numba @njit parallel kernel (242× faster). The result is an optimal (PT, SL) under three forecast specifications, constrained by the prop-firm daily loss limit.
preview
Market Microstructure in MQL5: Robust Foundation (Part 1)

Market Microstructure in MQL5: Robust Foundation (Part 1)

This article builds the foundation layer of a twelve-part MQL5 market microstructure toolkit. It implements guarded math helpers (SafeDivide, SafeLog, SafeSqrt, SafeExp, SafeTanh), robust data validation (ValidateSymbolV2, SafeCopyClose), trimmed statistical estimators (robust mean var), a linear regression slope, shared structs, and an FFT. You compile a single include file that hardens indicators and expert advisors against silent numerical failures and standardizes data flow for later parts.
preview
MQL5 Wizard Techniques you should know (Part 88): Using Blooms Filter with a Custom Trailing Class

MQL5 Wizard Techniques you should know (Part 88): Using Blooms Filter with a Custom Trailing Class

Our next focus in these series on ideas that can be rapidly prototyped with the MQL5 Wizard, is a Custom Trailing class that uses the Blooming Filter. Trailing Stop systems are an optional but very resourceful part to any trading system that we want to explore more in these series besides the traditional Entry Signals.
preview
Feature Engineering for ML (Part 2): Implementing Fixed-Width Fractional Differentiation in MQL5

Feature Engineering for ML (Part 2): Implementing Fixed-Width Fractional Differentiation in MQL5

This article delivers a production-grade MQL5 implementation of fixed-width fractional differentiation for live MetaTrader 5 feeds. We introduce a header-only CFFDEngine that precomputes weights without a fixed cap, performs O(width) per-bar updates, and avoids per-tick allocations. The FFD.mq5 indicator supports all ENUM_APPLIED_PRICE types and prev_calculated optimization. Validation scripts confirm numerical equivalence with the standard Python frac diff_ffd pipeline.
preview
Python + MetaTrader 5: Fast Research Framework for Data, Features, and Prototypes

Python + MetaTrader 5: Fast Research Framework for Data, Features, and Prototypes

The article demonstrates how Python and MetaTrader 5 integration combines research flexibility and trade execution into a single workflow. Python is used for data analysis, feature selection and model training, while MetaTrader 5 is used for testing and trading automation. This approach simplifies the transfer of solutions into practice, increases reproducibility, and makes the development of trading systems faster and more structured.
preview
CFTC Data Mining in Python and Building an AI Model

CFTC Data Mining in Python and Building an AI Model

Let's try mining CFTC data, downloading COT and TFF reports via Python, connecting all this with MetaTrader 5 quotes and an AI model, and get forecasts. What are COT reports in the Forex market? How to use COT and TFF reports for forecasting?
preview
Mining Central Bank Balance Sheet Data to Get a Picture of Global Liquidity

Mining Central Bank Balance Sheet Data to Get a Picture of Global Liquidity

Mining central bank balance sheet data provides a picture of global liquidity in the Forex market and key currencies. We combine data from the Fed, ECB, BOJ and PBoC into a composite index and use machine learning to uncover hidden patterns. This approach turns raw data into real trading signals by combining fundamental and technical analysis.
preview
MQL5 Wizard Techniques you should know (Part 87): Volatility-Scaled Money Management with Monotonic Queue in MQL5

MQL5 Wizard Techniques you should know (Part 87): Volatility-Scaled Money Management with Monotonic Queue in MQL5

This article presents a custom MQL5 money management class that adapts position sizing to real-time volatility using a monotonic queue for O(N) sliding-window extremes. The class applies inverse volatility scaling and optionally validates risk with an RBF network. We show implementation details in the Optimize method and compare results with the inbuilt Size-Optimized class to assess latency and risk control benefits.
preview
CAPM Model Indicator for the Forex Market

CAPM Model Indicator for the Forex Market

Adaptation of the classical CAPM model for the Forex currency market in MQL5. The indicator calculates expected return and risk premium based on historical volatility. The indicators rise at peaks and bottoms, reflecting the fundamental principles of pricing. Practical application for counter-trend and trend-following strategies, taking into account the dynamics of the risk-reward ratio in real time. The article includes mathematical apparatus and technical implementation.
preview
Neural Networks in Trading: Detecting Anomalies in the Frequency Domain (CATCH)

Neural Networks in Trading: Detecting Anomalies in the Frequency Domain (CATCH)

The CATCH framework combines Fourier transform and frequency patching to accurately identify market anomalies beyond the reach of traditional methods. Let us examine how this approach reveals hidden patterns in financial data.
preview
Neural Networks in Trading: Adaptive Detection of Market Anomalies (Final Part)

Neural Networks in Trading: Adaptive Detection of Market Anomalies (Final Part)

We continue to build the algorithms that form the basis of the DADA framework, which is an advanced tool for detecting anomalies in time series. This approach enables effective distinguishing random fluctuations from significant deviations. Unlike classical methods, DADA dynamically adapts to different data types, choosing the optimal compression level in each specific case.
preview
Deterministic Oscillatory Search (DOS)

Deterministic Oscillatory Search (DOS)

Deterministic Oscillatory Search (DOS) algorithm is an innovative global optimization method that combines the advantages of gradient and swarm algorithms without the use of random numbers. The fitness oscillation and slope mechanism allows DOS to explore complex search spaces in a deterministic manner.
preview
MetaTrader 5 Machine Learning Blueprint (Part 13):  Implementing Bet Sizing in MQL5

MetaTrader 5 Machine Learning Blueprint (Part 13): Implementing Bet Sizing in MQL5

We build a production MQL5 bet‑sizing toolkit: utilities, snippets, and user‑level functions that mirror the Python originals. The methods cover probability‑to‑size mapping with overlap correction, dynamic forecast‑price sizing (calibrated sigmoid/power with limit price), occupancy‑based budgeting, and mixture‑model reserve sizing (EF3M). The result is a signed [−1, ..., 1] position plus diagnostics you can plug directly into order logic.
preview
Self-Learning Expert Advisor with a Neural Network Based on a Markov State-Transition Matrix

Self-Learning Expert Advisor with a Neural Network Based on a Markov State-Transition Matrix

Self-training EA with a neural network based on a state matrix. We combine Markov chains with a multilayer neural network MLP developed using the ALGLIB MQL5 library. How can Markov chains and neural networks be combined for Forex forecasting?
preview
Markov Chain-Based Matrix Forecasting Model

Markov Chain-Based Matrix Forecasting Model

We are going to create a matrix forecasting model based on a Markov chain. What are Markov chains, and how can we use a Markov chain for Forex trading?
preview
Integrating Computer Vision into Trading in MQL5 (Part 2): Extending the Architecture to 2D RGB Image Analysis

Integrating Computer Vision into Trading in MQL5 (Part 2): Extending the Architecture to 2D RGB Image Analysis

Computer vision for trading: how it works and how to develop it step by step. We create an algorithm for recognition of RGB images of price charts using the attention mechanism and a bidirectional LSTM layer. As a result, we obtain a working model for forecasting the EURUSD price with the accuracy of up to 55% in the validation section.
preview
Camel Algorithm (CA)

Camel Algorithm (CA)

The Camel Algorithm, developed in 2016, simulates the behavior of camels in the desert to solve optimization problems, taking into account temperature, supply, and endurance. This article also presents a modified version of the algorithm (CAm) with key improvements: the use of a Gaussian distribution in generating solutions and the optimization of the oasis effect parameters.
preview
Foundation Models in Trading: Time Series Forecasting with Google's TimesFM 2.5 in MetaTrader 5

Foundation Models in Trading: Time Series Forecasting with Google's TimesFM 2.5 in MetaTrader 5

Time series forecasting in trading has evolved from traditional statistical models (like ARIMA) to deep learning approaches, but both require heavy tuning and training. Inspired by advances in NLP, Google’s TimesFM introduces a pretrained “foundation model” for time series that can perform strong forecasts even without task-specific training. For traders, this is powerful because it can be efficiently fine-tuned on their own data using lightweight methods like LoRA, reducing overfitting while adapting to changing market conditions.
preview
Hidden Markov Models in Machine Learning-Based Trading Systems

Hidden Markov Models in Machine Learning-Based Trading Systems

Hidden Markov Models (HMMs) are a powerful class of probabilistic models designed to analyze sequential data, where observed events depend on some sequence of unobserved (hidden) states that form a Markov process. The main assumptions of HMM include the Markov property for hidden states, meaning that the probability of transition to the next state depends only on the current state, and the independence of observations given knowledge of the current hidden state.
preview
Fractal-Based Algorithm (FBA)

Fractal-Based Algorithm (FBA)

The article presents a new metaheuristic method based on a fractal approach to partitioning the search space for solving optimization problems. The algorithm sequentially identifies and separates promising areas, creating a self-similar fractal structure that concentrates computing resources on the most promising areas. A unique mutation mechanism aimed at better solutions ensures an optimal balance between exploration and exploitation of the search space, significantly increasing the efficiency of the algorithm.
preview
Feature Engineering for ML (Part 1): Fractional Differentiation — Stationarity Without Memory Loss

Feature Engineering for ML (Part 1): Fractional Differentiation — Stationarity Without Memory Loss

Integer differentiation forces a binary choice between stationarity and memory: returns (d=1) are stationary but discard all price-level information; raw prices (d=0) preserve memory but violate ML stationarity assumptions. We implement the fixed-width fractional differentiation (FFD) method from AFML Chapter 5, covering get_weights_ffd (iterative recurrence with threshold cutoff), frac_diff_ffd (bounded dot product per bar), and fracdiff_optimal (binary search for minimum stationary d*).
preview
MetaTrader 5 Machine Learning Blueprint (Part 12): Probability Calibration for Financial Machine Learning

MetaTrader 5 Machine Learning Blueprint (Part 12): Probability Calibration for Financial Machine Learning

Tree-based classifiers are typically overconfident: true win rates near 0.55 appear as 0.65–0.80 and inflate position sizes and Kelly fractions. This article presents afml.calibration and CalibratorCV, which generate out-of-fold predictions via PurgedKFold and fit isotonic regression or Platt scaling. We define Brier score, ECE, and MCE, and show diagnostics that trace miscalibration into position sizes, realized P&L, and CPCV path Sharpe distributions to support leakage-free, correctly sized trading.
preview
Forex Arbitrage Trading: A Matrix Trading System for Return to Fair Value with Risk Control

Forex Arbitrage Trading: A Matrix Trading System for Return to Fair Value with Risk Control

The article contains a detailed description of the cross-rate calculation algorithm, a visualization of the imbalance matrix, and recommendations for optimally setting the MinDiscrepancy and MaxRisk parameters for efficient trading. The system automatically calculates the "fair value" of each currency pair using cross rates, generating buy signals in case of negative deviations and sell signals in case of positive ones.
preview
Chaos optimization algorithm (COA): Continued

Chaos optimization algorithm (COA): Continued

We continue studying the chaotic optimization algorithm. The second part of the article deals with the practical aspects of the algorithm implementation, its testing and conclusions.
preview
Chaos optimization algorithm (COA)

Chaos optimization algorithm (COA)

This is an improved chaotic optimization algorithm (COA) that combines the effects of chaos with adaptive search mechanisms. The algorithm uses a set of chaotic maps and inertial components to explore the search space. The article reveals the theoretical foundations of chaotic methods of financial optimization.
preview
Predicting Renko Bars with CatBoost AI

Predicting Renko Bars with CatBoost AI

How to use Renko bars with AI? Let's look at Renko trading on Forex with forecast accuracy of up to 59.27%. We will explore the benefits of Renko bars for filtering market noise, learn why volume is more important than price patterns, and how to set the optimal Renko block size for EURUSD. This is a step-by-step guide on integrating CatBoost, Python, and MetaTrader 5 to create your own Renko Forex forecasting system. It is ideal for traders looking to go beyond traditional technical analysis.