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
How to Implement Metaprompting for Trading Signals in an MQL5 Expert Advisor

How to Implement Metaprompting for Trading Signals in an MQL5 Expert Advisor

Metaprompting is an approach in which the LLM itself optimizes trading instructions based on actual P&L and signal quality metrics. The article demonstrates a practical implementation in Python and MQL5: a prompt version registry, an execution agent, an evaluator for directional accuracy and profit factor, and a meta-LLM that generates improvements in a loop. The solution is integrated into the Expert Advisor without interrupting trading.
preview
Numerical Fidelity Under Fire: Benchmarking Native MQL5, ONNX Runtime, and ALGLIB

Numerical Fidelity Under Fire: Benchmarking Native MQL5, ONNX Runtime, and ALGLIB

This article benchmarks one MLP forward pass implemented three ways in MQL5: native code, ALGLIB, and ONNX Runtime. We quantify numerical fidelity versus a float64 ground truth and execution latency (mean/percentiles), then outline practical criteria and a ready‑to‑use harness to help you choose and integrate the right engine in an EA.
preview
Neural Networks in Trading: Iterative Forecast Refinement Models (RAFT)

Neural Networks in Trading: Iterative Forecast Refinement Models (RAFT)

The RAFT framework offers a fundamentally different approach to forecasting market dynamics — not as a one-time snapshot, but as an iterative refinement of the state in real time. It takes both local and global changes into account, maintaining a high degree of accuracy even with complex price structures.
preview
Buzzard Optimization Algorithm (BUZOA)

Buzzard Optimization Algorithm (BUZOA)

BUZOA is a population-based metaheuristic algorithm in which each agent randomly selects one of three hunting tactics at each iteration: a narrow search around its personal best, a classic PSO step toward the flock leader, or full teleportation to a random point in the search space. The article examines the implementation of the algorithm in MQL5, identifies a coefficient sign error in the original formulation, and presents benchmark results on a standard test bench.
preview
Offline Reinforcement Learning in MQL5: Conservative Q-Learning from Historical Trade Logs Without Live Exploration

Offline Reinforcement Learning in MQL5: Conservative Q-Learning from Historical Trade Logs Without Live Exploration

Build and deploy a conservative, offline‑trained policy entirely in MQL5. Logged trades become a fixed dataset for a two‑layer Q‑network trained with Conservative Q‑Learning, which pushes down Q‑values for poorly supported actions to limit extrapolation error. The EA loads the frozen weights and applies an out‑of‑distribution guard using saved feature statistics. This yields reproducible training and execution without live exploration.
preview
Online Portfolio Selection: A Provable Regret Bound, and the Cost That Eats It

Online Portfolio Selection: A Provable Regret Bound, and the Cost That Eats It

The article implements Online Portfolio Selection in MQL5: exact simplex projection, four allocators (EG, Universal Portfolio, PAMR, OLMAR), and a BCRP solver on a concave objective. We verify weight paths against the published Python reference and self-check the optimizer. A drift-aware transaction cost model measures turnover and net wealth on a multi-asset basket. Readers get a tested library and evidence on when regret-bounded methods lose to costs.
preview
Neural Networks in Trading: Adaptive Perception of Market Dynamics (Conclusion)

Neural Networks in Trading: Adaptive Perception of Market Dynamics (Conclusion)

The article continues the work on implementing the STE-FlowNet framework, which combines multi-stream processing with recurrent structures for accurate analysis of complex data. The tests conducted confirmed its stability and flexibility in various scenarios. This architecture speeds up computations and enables deeper modeling of dependencies in time series. This approach opens up new possibilities for practical application in trading and analytics.
preview
Using Renko-bar Regression with Error Correction

Using Renko-bar Regression with Error Correction

The article presents a regression-based approach to forecasting Renko bars using CatBoost: the model estimates the logarithmic return of the next bar and the uncertainty of the forecast. We will examine a cascade of residual models with OOF validation using TimeSeriesSplit, shrinkage, and overall early stopping, as well as conditional bias correction. On EURUSD D1, a reduction in OOF-MAE was achieved, along with approximately 65% directional accuracy. A working script for MetaTrader 5 is provided that generates a signal, position size, SL, and TP in brick units.
preview
Neural Networks in Trading: Adaptive Perception of Market Dynamics (Encoder)

Neural Networks in Trading: Adaptive Perception of Market Dynamics (Encoder)

The article presents the comprehensive architecture of the STE-FlowNet encoder, which combines stack memory, recurrent processing, and a correlation mechanism to extract hidden market dependencies. The article demonstrates how these modules are sequentially integrated into a single computational chain capable of performing comprehensive time-series analysis.
preview
Machine Learning Under Constraint (Part 4): The Stop-Loss Ceiling Meets the Optimal Trading Rule Search

Machine Learning Under Constraint (Part 4): The Stop-Loss Ceiling Meets the Optimal Trading Rule Search

The article constrains the optimal trading rule by a prop-firm stop-loss ceiling and corrects OU fitting by pooling within-trade pairs per AFML eq. 13.6. We apply the ceiling as a feasibility mask on a shared PT–SL mesh, ensuring the constrained set is a subset of the baseline. Practical guidance covers when the ceiling binds, the Sharpe cost, and how exposure and live budget state affect the bound.
preview
Population-Based Optimization Algorithms: Building a Defense Against Cheaters

Population-Based Optimization Algorithms: Building a Defense Against Cheaters

The algorithms were rerun on the updated functions, and a method was proposed for quickly verifying their "honesty". The composite test combines five different landscapes and eliminates the possibility of gaining an advantage based on the geometry of individual problems, allowing for a quick assessment of the algorithm's actual search capability. A script is provided for preliminary validation of algorithms before they are applied to the optimization of trading strategies.
preview
Benchmark Champions vs. Real-World Optimization Problems

Benchmark Champions vs. Real-World Optimization Problems

We analyze why ratings may be inflated due to the alignment of algorithm trajectories with benchmark diagonals, and we supplement the testing methodology with a requirement to keep the global extremum away from the diagonals. We update Forest and Megacity, and perform RAW verification and calibration using VerifyExtremes.mq5. A drop in HHO and DOAm performance serves as a practical indicator of false leaders.
preview
Hyperdimensional Computing: Learning in One Integer Add, and the Nulls That Judge It

Hyperdimensional Computing: Learning in One Integer Add, and the Nulls That Judge It

A complete Hyperdimensional Computing library for MQL5 implements bind, bundle and permute over 4096‑bit hypervectors, graded level ladders for quantities, an encoder for bars and sequences, and a classifier trained by integer addition. It includes a purged, ordered validation split, online updates without refitting, a market scan with two nulls, and a Python reference that reproduces the MQL5 model bit for bit, so you can validate results and deploy a reproducible indicator and test suite.
preview
Diebold-Mariano Testing in MQL5: Validating Predictive Edge Across Instruments and Models

Diebold-Mariano Testing in MQL5: Validating Predictive Edge Across Instruments and Models

The article shows how to compare two trading forecasters in MQL5 using the Diebold–Mariano test with HAC‑corrected variance and the Harvey–Leybourne–Newbold adjustment. It explains implementation details, including loss choices, horizon‑dependent lag windows, rolling computation, verdict handling, and a manifest‑driven configuration, plus a Student‑t implementation without external libraries. An EA and an indicator provide a live dashboard and significance bands for practical, defensible model selection.
preview
Neural Networks in Trading: Adaptive Perception of Market Dynamics (STE-FlowNet)

Neural Networks in Trading: Adaptive Perception of Market Dynamics (STE-FlowNet)

The STE-FlowNet framework offers a new perspective on financial data analysis by responding to actual market events rather than fixed timeframes. Its architecture preserves local and temporal dependencies, making it possible to track even small impulses in price dynamics.
preview
Native Gaussian Process Regression in MQL5: Short-Horizon Price Forecasting with Uncertainty Bands

Native Gaussian Process Regression in MQL5: Short-Horizon Price Forecasting with Uncertainty Bands

The article rebuilds a Gaussian Process forecaster in native MQL5 around market-state inputs and direct horizon log-return targets. It employs a Matern 3/2 kernel, symmetric Cholesky with adaptive jitter, standardized targets, and a log‑space grid search that avoids state side effects. The EA trades only when az‑score over observed variance clears a threshold and the edge beats the live spread. Calibration is verified in Strategy Tester.
preview
How to Set Up an AI Hedge Fund in MetaTrader 5

How to Set Up an AI Hedge Fund in MetaTrader 5

The article examines the architecture of a committee consisting of 15 AI agents: ten analysts and four risk officers vote in three parallel phases, and the Chair records the final result. Isolated pair contexts with separate reputations are used for eight currency pairs. The dynamic vote threshold depends on the daily PnL targets. The Expert Advisor uses only the signal, SL and TP, which allows for evaluation pf the quality of its decisions without any additional mechanics.
preview
Neural Networks in Trading: A Spike-Semantic Approach to Spatiotemporal Identification (Conclusion)

Neural Networks in Trading: A Spike-Semantic Approach to Spatiotemporal Identification (Conclusion)

In our interpretation, S3CE-Net skillfully translates the market into the language of events and captures early impulses that traditional indicators simply average out. STFS ensures robust training — the model sees the data from different perspectives and does not overfit to local anomalies. SSAM blocks and the OpenCL implementation deliver practical speed and accuracy, while the separation between training and deployment modes saves resources in production.
preview
Nonlinear OHLC Features Derived from Elliptic Curves

Nonlinear OHLC Features Derived from Elliptic Curves

The article discusses the projection of EURUSD daily candlesticks onto the secp256k1 elliptic curve and the extraction of 96 features (EC+TA) to predict the direction of the next candlestick in CatBoost. The price mapping to the curve and the training pipeline on 2,000 D1 bars are shown; the full model achieves a test AUC of 0.6508, with EC features contributing 60.6%. The materials are suitable for reproduction in Python/MetaTrader 5.
preview
Online False Discovery Rate Control: Putting an Error Budget on a Live Signal Stream

Online False Discovery Rate Control: Putting an Error Budget on a Live Signal Stream

The article addresses online false discovery rate control for streaming signals, where fixed thresholds inflate noise discoveries. We port LORD3, LORD++ and SAFFRON into MQL5, construct a causal bootstrap p‑value source without a resolution floor, and verify correctness before market data. Dependence stress tests, a budget/level indicator and a two-arm Strategy Tester show how to configure, monitor and throttle streams to keep the acted-on noise fraction within target.
preview
Neural Networks in Trading: A Spiking-Semantic Approach to Spatiotemporal Identification (Key Components)

Neural Networks in Trading: A Spiking-Semantic Approach to Spatiotemporal Identification (Key Components)

In this article, we took a detailed look at the integration of the SSAM module into the SEW-ResNeXt block, demonstrating how the S3CE-Net framework enables the effective combination of spiking attention with residual blocks. This architecture ensures accurate processing of temporal and spatial data streams and high training stability. The modularity and flexibility of the components make it easier to extend the model and reuse proven methods.
preview
Neural Networks in Trading: A Spiking-Semantic Approach to Spatiotemporal Identification (S3CE-Net)

Neural Networks in Trading: A Spiking-Semantic Approach to Spatiotemporal Identification (S3CE-Net)

We invite you to explore the S3CE-Net framework and its SSAM and STFS mechanisms, which accurately process spiking events while taking causality into account. The model is lightweight, parallel, and capable of identifying complex relationships across time and space.
preview
MetaTrader 5 Machine Learning Blueprint (Part 23): Feature Screening

MetaTrader 5 Machine Learning Blueprint (Part 23): Feature Screening

Permutation tests that assume exchangeable observations miscalibrate feature screens for overlapping financial labels, yielding a tenfold false‑positive inflation on EURUSD. This article implements a calibrated three‑gate pipeline: ADF+KPSS for stationarity, uniform‑grid entropy with modal occupancy, and mutual information corrected via a joint permutation null and Westfall–Young max‑T. The ScreeningReport summarizes gate outcomes and effective test count so you can filter features reliably before fitting models.
preview
Implementing an LLM Agent with SQL Memory in MetaTrader 5

Implementing an LLM Agent with SQL Memory in MetaTrader 5

An LLM agent with SQL memory in MetaTrader 5 — an architecture that eliminates the main limitation of traditional LLM Expert Advisors (EAs): the loss of context between queries. Each agent decision is recorded in SQLite along with the market conditions at the time of the signal — RSI, MA alignment, volatility — and after the position is closed, the outcome is written to the database. When the next request comes in, the agent reviews its own history — similar past RSI conditions and the last three agent decisions — and only then analyzes the current market. The result is a system that remembers its errors between restarts and adapts its behavior based on accumulated statistics, rather than starting from scratch with each new bar.
preview
Variational Mode Decomposition: Building the Solver, and Measuring What Hindsight Buys

Variational Mode Decomposition: Building the Solver, and Measuring What Hindsight Buys

A from‑scratch VMD library for MetaTrader 5: radix‑2 transform, ADMM updates, mirrored windows, and a result type that reports solve quality and mode separation. We verify the solver to full double precision against a reference and test causality by sabotage. The article quantifies repaint from batch versus causal runs and compares it to volatility‑matched random walks. You get a causal indicator, usable diagnostics, and settings that avoid common pitfalls.
preview
Neural Networks in Trading: Training Deep Spiking Models (Conclusion)

Neural Networks in Trading: Training Deep Spiking Models (Conclusion)

The article demonstrates a practical implementation of the SEW ResNet framework using MQL5, with a focus on its applied use in trading. The Double Bottleneck makes it possible to simultaneously analyze univariate streams and inter-channel dependencies without losing gradients during training. Spiking activations with adaptive thresholds and gates improve robustness to noise and sensitivity to market novelty. The text provides details on the implementation and test results.
preview
Forecast Reconciliation (MinT): One Engine for Timeframe Hierarchies and Currency Graphs

Forecast Reconciliation (MinT): One Engine for Timeframe Hierarchies and Currency Graphs

This article builds forecast reconciliation in pure MQL5 and applies it to two structures: timeframe aggregation on one symbol and a currency graph linked by no‑arbitrage. The engine projects base forecasts onto linear constraints to make them coherent. We benchmark OLS/WLS and MinT with and without shrinkage on long walk‑forward runs, show when total squared error decreases, and measure the cost that may concentrate in a single node.
preview
Evolutionary Selection of LLM Agents in MetaTrader 5

Evolutionary Selection of LLM Agents in MetaTrader 5

The article describes the architecture of a trading system consisting of 20 Grok (xAI)-based LLM agents, each of which embodies a unique trading philosophy — from pure momentum to a statistical z-score. The system applies a genetic algorithm directly during trading: every 20 trades, it automatically eliminates weak agents, clones strong ones with a prompt mutation, and publishes a leaderboard on the MetaTrader 5 chart — without interrupting trading and without using any SDK.
preview
Feature Neutralization in MQL5: Orthogonalizing Trading Signals Against Confound Factors

Feature Neutralization in MQL5: Orthogonalizing Trading Signals Against Confound Factors

We implement feature neutralization so your signal is evaluated without volatility/trend confounds. The core is a native MQL5 rolling OLS engine using Gauss-Jordan elimination and out-of-sample residual scoring, with no DLLs. An EA and indicator integrate the residual and log diagnostics, while a Python companion validates numerics and runs bar-replay tests. Use it to isolate linear exposure and assess true signal contribution.
preview
Neural Networks in Trading: Training Deep Spiking Models (Spike Integration)

Neural Networks in Trading: Training Deep Spiking Models (Spike Integration)

The article presents a practical implementation of the key components of the SEW-ResNet framework using MQL5. The use of dynamic arrays and spiking mechanisms enables flexible model architecture design and efficient processing of financial time series. The proposed solutions demonstrate how SEW-ResNet can optimize computations and improve the extraction of meaningful features.
preview
Harris Hawks Optimization (HHO)

Harris Hawks Optimization (HHO)

We implement the Harris Hawks Optimization algorithm in MQL5 and analyze five movement modes of agents controlled by a single parameter — the decaying escape energy E. The C_AO_HHO class is introduced; it is compatible with the unified test bench and features a reproducible implementation of Lévy flight. The algorithm was tested on the Hilly, Forest, and Megacity functions with 5, 25, and 500 coordinates — the results indicate anomalous behavior.
preview
Ollivier-Ricci Curvature: Reading the Shape of a Correlation Network, Not Its Level

Ollivier-Ricci Curvature: Reading the Shape of a Correlation Network, Not Its Level

The article builds an Ollivier–Ricci curvature library in MQL5 for multi‑symbol analysis. A basket becomes a correlation network, and the reading captures network geometry rather than correlation level. It includes an exact optimal transport solver with an internal certificate, a rolling fragility metric with two informative nulls, an indicator that plots the reading against its null band, and a demonstration expert that uses it as a risk gate.
preview
Neural Networks in Trading: Training Deep Spiking Models (SEW-ResNet)

Neural Networks in Trading: Training Deep Spiking Models (SEW-ResNet)

We invite you to explore the SEW-ResNet framework, which allows you to build deep spiking models without degradation issues and with effective gradient management. In this article, we demonstrate how to implement a basic spiking neuron and its algorithms using MQL5.
preview
Foundation Models for Trading (Part III): Running a Generative AI Forecaster Inside MetaTrader 5

Foundation Models for Trading (Part III): Running a Generative AI Forecaster Inside MetaTrader 5

We demonstrate live forecast charting with Kronos in MQL5 and an evaluation pipeline designed to be look‑ahead‑safe. Deterministic dumps are scored per horizon against a random‑walk baseline (15,113 predictions), then fed to a simple Strategy Tester rule on EURUSD H1. The findings show no edge, and illustrate how a high threshold can yield a persuasive but low‑information backtest with very few trades.
preview
Machine Learning Under Constraint (Part 3): De-Risking Near the Profit Target and the News-Window Rule

Machine Learning Under Constraint (Part 3): De-Risking Near the Profit Target and the News-Window Rule

Position sizing that ignores proximity to a profit target or the timing of high-impact news exposes banked progress to reversal risk and misstates simulated profit near funded-stage news releases. We implement derisking_factor, a piecewise-linear size reduction keyed to phase progress with a floor set by minimum-trading-days status, and news_window_factor, a phase-gated step function applying FundedNext's news reward-share haircut in a configurable window around correlated events. Both return bounded multipliers combined multiplicatively with the sizer's other modifiers.
preview
Certified Robustness Radius: Knowing How Much Noise Your ONNX Trading Model Can Survive

Certified Robustness Radius: Knowing How Much Noise Your ONNX Trading Model Can Survive

We introduce a certified-radius gate for ONNX signals implemented natively in MQL5. The system estimates per-prediction robustness via randomized smoothing and a one-sided Clopper–Pearson bound, then applies the radius to trade admission, lot scaling, and monitoring. This provides an actionable confidence margin that reflects input noise tolerance rather than softmax magnitude.
preview
Neural Networks in Trading: From Transformers to Spiking Neurons (Conclusion)

Neural Networks in Trading: From Transformers to Spiking Neurons (Conclusion)

Neural networks are already changing the way we analyze markets, and new architectures are opening up even more possibilities. In this article, we wrap up our work with the SpikingBrain framework, which opens up new possibilities for us.
preview
MiniRocket: A Deterministic Time-Series Classifier and What It Finds in Seven Classic Setups

MiniRocket: A Deterministic Time-Series Classifier and What It Finds in Seven Classic Setups

This article delivers a native MQL5 MiniRocket: 84 fixed convolution kernels yield 9,996 features quickly and deterministically, requiring no training loop and no external runtime. We verify the port against sktime and a float64 reimplementation, then run a reproducible audit of seven classic setups; planted and coin‑flip controls confirm correctness, and a 25%‑flipped control sets the detection threshold.
preview
Practical Modules from Other Languages in MQL5 (Part 08): MATPLOTLIB

Practical Modules from Other Languages in MQL5 (Part 08): MATPLOTLIB

Learn how to bring advanced plotting and data visualization to the MetaTrader 5 terminal by leveraging Matplotlib, one of Python's most powerful and widely used visualization libraries.
preview
MetaTrader 5 Machine Learning Blueprint (Part 22): Auditing the Selection Criterion — Measuring Overfit in Hyperparameter Search

MetaTrader 5 Machine Learning Blueprint (Part 22): Auditing the Selection Criterion — Measuring Overfit in Hyperparameter Search

We show that nested cross-validation removes optimistic evaluation bias but does not stop hyperparameter search from overfitting a finite sample, and we add a diagnostic for when the criterion cannot resolve candidates from noise. We implement OffsetPurgedKFold (boundary-shifted repartitioning), a criterion variance audit (resolution ratio and selection stability), a selection optimization curve, a corrected one-standard-error rule, noise-floor early stopping, and an effective trial count for correlated trials. The result is a dispersion report per candidate and an effective count for the Deflated Sharpe Ratio.