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
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
Self-Exciting Markets: Building a Hawkes Process from Scratch

Self-Exciting Markets: Building a Hawkes Process from Scratch

Volatility arrives in clusters: one large move makes the next large move more likely, and quiet spells stay quiet. This article builds a Hawkes self-exciting point process in pure MQL5 to measure that effect directly, ending in a single number, the branching ratio, that says how reflexive a market currently is. You get a small, tested library, an indicator that plots the fitted intensity live, and a demonstration Expert Advisor, along with the honest limits of all three.
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.
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
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
Swarm Optimizer with Hierarchical Sub-Flocks — Flock by Leader

Swarm Optimizer with Hierarchical Sub-Flocks — Flock by Leader

We are developing and implementing the Flock by Leader algorithm in MQL5: sub-flocks are formed based on the ARF metric, and the leader is determined by the highest personal best rather than by the centroid's position. We present the update formulas for the swarm roles and the separation mechanism. The C_AO_FBL class is compatible with the test bench and has been tested on the Hilly, Forest, and Megacity functions with dimensionalities from 10 to 1000 coordinates, which simplifies reproduction and comparison.
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
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
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
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
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
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
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
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
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 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.