MQL5 Programming Articles

icon

Study the MQL5 language for programming trading strategies in numerous published articles mostly written by you - the community members. The articles are grouped into categories to help you quicker find answers to any questions related to programming: Integration, Tester, Trading Strategies, etc.

Follow our new publications and discuss them on the Forum!

Add a new article
latest | best
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
Generating a Per-Symbol Trade Analytics PDF Report from MQL5

Generating a Per-Symbol Trade Analytics PDF Report from MQL5

This article shows how to generate a dependency-free, single-page PDF report in MQL5 using only string assembly and the FILE_BIN API. The script computes per-symbol trade statistics, then renders a labeled table and an equity curve with explicit PDF color and drawing operators. Statistics are calculated in a standalone module, so every value can be verified against synthetic data without relying on a live trading account.
preview
Path Signatures for Lead-Lag Detection

Path Signatures for Lead-Lag Detection

Build a level-2 path-signature engine in pure MQL5 to read the lead-lag ordering between two data streams without choosing a lag and without a linear model. The article delivers a reusable library, an indicator that plots the Levy‑area oscillator, and a simple rule‑based Expert Advisor. Code is cross‑checked against closed‑form cases, and the components are ready to plug into your projects.
preview
Measuring broker execution quality in MQL5: Why your live account doesn't match the backtest

Measuring broker execution quality in MQL5: Why your live account doesn't match the backtest

Live performance often drifts from backtests because of execution friction. We introduce an MQL5 diagnostic EA that records entry and exit slippage, asymmetry, observed spread, requotes, and per-leg latency, using a precise probe mode and an approximate passive mode, and writes every sample to CSV. Use the results to distinguish strategy issues from execution effects across your terminal, network, broker, and liquidity.
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
How We Built the Most Powerful Machine Learning-Powered Trading Platform: The Evolution of MQL and MetaTrader Through Archives, Forums, and Releases

How We Built the Most Powerful Machine Learning-Powered Trading Platform: The Evolution of MQL and MetaTrader Through Archives, Forums, and Releases

A technical history of MQL evolution: from the limited MQL and MQL II languages, through procedural MQL4, to object-oriented MQL5 with native compilation, rich APIs, and a full-fledged engineering environment. We show here the key capabilities of the language and its integrations with Python, OpenCL, ONNX, OpenBLAS, databases, DirectX, the agentic AI Assistant, and the Model Context Protocol (MCP), which connects AI systems with the terminal, MetaEditor, market data, trading operations, and development tools. This article examines archival materials on the origins of MetaQuotes and MetaTrader, the launch of MQL4.COM and MQL5.COM, the championships, Algo Forge, and their impact on the ecosystem.
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
Exporting Custom Indicator Buffers to CSV for Python Backtesting Pipelines

Exporting Custom Indicator Buffers to CSV for Python Backtesting Pipelines

We build a CSV exporter for MQL5 custom indicators that preserves the exact values seen on the chart. The script creates the indicator handle with iCustom, waits for BarsCalculated, aligns buffers to CopyRates, and writes a locale-safe CSV that pandas loads with parsed dates and NaN for warm-up bars. It addresses compile-time argument limits, jagged-array workarounds, and EMPTY_VALUE handling, enabling reliable Python backtests without re-coding the indicator.
preview
Building a Volume-Based Liquidity Heatmap Indicator in MQL5

Building a Volume-Based Liquidity Heatmap Indicator in MQL5

This article implements an MQL5 Liquidity Heatmap that infers likely liquidation zones from price and volume. It qualifies bars with a rolling volume SMA, computes leverage-based liquidation levels from candle extremes, ranks signals across two volume modes, and manages chart objects (lines and bubbles) that extend until price crosses them, allowing you to highlight potential stop-hunt areas and strengthen structural analysis.
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
Building a Divergence System (Part III): The Adaptive SuperTrend EA

Building a Divergence System (Part III): The Adaptive SuperTrend EA

The article implements a self-sufficient Adaptive SuperTrend EA with internal calculations on a selectable timeframe, avoiding external buffers and indicator files. It includes risk-based lot sizing, ATR stops, stepwise RR trailing, optional anti-repainting confirmation, and session control. Practitioners can reuse the structure for consistent new‑bar signal handling and broker‑compliant order validation.
preview
Streaming MetaTrader 5 Trade Events to a Local HTTP Server Using WinINet in MQL5

Streaming MetaTrader 5 Trade Events to a Local HTTP Server Using WinINet in MQL5

An MQL5 implementation sends trade lifecycle events to a local HTTP service through WinINet with a reusable session and per-request handles. The trade callback only enqueues JSON and returns, while a 500 ms timer drains the queue and retries failed posts, preserving order. A three-stage log policy keeps the Experts tab clear during downtime and summarizes recovery.
preview
Mathematical Models in Grid Strategies

Mathematical Models in Grid Strategies

In this article, we will examine the application of mathematics to grid strategies. We will consider the basic principles of the strategy, as well as its advantages and disadvantages. You will learn how to build a trading grid, set optimal parameters, and manage risks effectively.
preview
Building a Modular Fair Value Gap (FVG) Detection Engine in MQL5

Building a Modular Fair Value Gap (FVG) Detection Engine in MQL5

This article introduces a modular Fair Value Gap (FVG) detection engine for MQL5 packaged as a reusable include class, it evaluates imbalance zones on closed bars, applies a Simple True Range average filter to eliminate low-volatility noise, and supports wick-touch and close-through mitigation. A companion diagnostic indicator plots active gaps, and an Expert Advisor template demonstrates automated pullback entries with new-bar execution controls.
preview
Automating Trading Strategies in MQL5 (Part 51): The Bread and Butter Judas Swing Model with Premium and Discount

Automating Trading Strategies in MQL5 (Part 51): The Bread and Butter Judas Swing Model with Premium and Discount

We build a session-based reversal program in MQL5 using the Bread and Butter Judas Swing model. It derives a higher-timeframe daily bias, defines New York kill zones, maps each session's premium and discount from the live range, and requires a sweep before a market structure shift confirms entry. Readers get a ready approach to arm setups only during active sessions and execute in the bias direction with clear, testable rules.
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
Hierarchical Risk Parity: A Robust Portfolio Allocator and Expert Advisor

Hierarchical Risk Parity: A Robust Portfolio Allocator and Expert Advisor

We implement a Hierarchical Risk Parity allocator in MQL5 as a single class, validate each stage against an independent Python reference, and package it in a rebalancing Expert Advisor. The pipeline covers returns, covariance/correlation, clustering, quasi-diagonalization, and recursive bisection, and contrasts HRP with Markowitz on stressed data. You finish with a verified allocator and an EA ready for basket-level testing.
preview
Exporting Symbol Tick Data to Binary Files in MQL5 for Offline Analysis

Exporting Symbol Tick Data to Binary Files in MQL5 for Offline Analysis

The article delivers a complete, verifiable tick export path from MQL5 to a binary file and into Python. It defines a 64‑byte header, 48‑byte records with millisecond time and flags, an export pipeline using CopyTicksRange(), and a single‑call NumPy loader. Users obtain compact, precision‑preserving files and a reproducible workflow for vectorized analysis.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 4): Fully Automated Analytical Objects System

How to Detect and Normalize Chart Objects in MQL5 (Part 4): Fully Automated Analytical Objects System

This part extends the series with a modular, event-driven MQL5 pipeline: swing detection feeds an object placer for trendlines, SR, Fibonacci, channels, and pitchforks; evaluators monitor interactions and generate signals; adaptive logic executes trades with valid stops per instrument. The topology manager synchronizes placement, scanning, and processing. The code is structured into reusable components for easy reuse and scaling.
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
Real-Time Trade Event Logger to SQLite via MQL5 DLL Bridge

Real-Time Trade Event Logger to SQLite via MQL5 DLL Bridge

The article shows how to build an MQL5 EA that writes every deal to an SQLite database the moment it appears, using the built-in Database API as the SQLite bridge. It implements an event data model, a prepared INSERT workflow reused across calls, session-safe recovery after restarts, and deal detection via OnTrade(). You can open the resulting file with any SQLite client to run queries for analysis and reporting.
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.
preview
From One Price to Four: Range-Based Volatility Estimators for MetaTrader 5

From One Price to Four: Range-Based Volatility Estimators for MetaTrader 5

Close-to-close volatility ignores the high, the low, and overnight gaps. We build a reusable MQL5 library implementing four range-based estimators from Parkinson to the gap-robust Yang-Zhang, and put it to work in a comparison indicator and a set of adaptive volatility bands.
preview
Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Core Model Modules)

Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Core Model Modules)

We continue our acquaintance with the Mamba4Cast framework. Today, we will delve into the practical implementation of the proposed approaches. Mamba4Cast was designed not for lengthy warm-up on every new time series, but for immediate deployment. Thanks to the concept of Zero-Shot Forecasting, the model can produce high-quality forecasts on real-world data without additional training or hyperparameter tuning.
preview
Developing a Terminal Manager (Part 2): Running Multiple Terminal Instances

Developing a Terminal Manager (Part 2): Running Multiple Terminal Instances

Let's move on to using multiple terminal instances on the server by setting up a simple control panel for starting and stopping them. Now it is time to expand the functionality and move on to the next stages — implementing more complex features, such as managing multiple terminal instances, state persistence, integration with the MetaTrader 5 API, and a web interface with comprehensive information about the terminals.
preview
Developing a Terminal Manager (Part 1): Problem Statement

Developing a Terminal Manager (Part 1): Problem Statement

How can we conveniently monitor multiple terminals running Expert Advisors, especially when they are on different computers? Let's try to create a web interface for managing the launch of MetaTrader 5 trading terminals and viewing detailed information about the operation of each instance.
preview
The Blue Monkey (BM) Algorithm

The Blue Monkey (BM) Algorithm

The article presents an implementation of the Blue Monkey metaheuristic algorithm, which is based on a model of the social behavior of blue monkeys. The article examines the key mechanisms of the algorithm — the group structure of the population, following local leaders, and generational renewal through the replacement of the worst adults with the best offspring — and analyzes the test results.
preview
Building Your Personal Expert Advisor (Part 1): From Fragile Script to Working EA

Building Your Personal Expert Advisor (Part 1): From Fragile Script to Working EA

This article focuses on EA architecture rather than signal design. Starting with a flawed Moving Average crossover EA, we add new‑bar detection to prevent duplicate entries, Magic Number and position awareness, ATR‑based risk levels, and data and trade result validation, along with basic safeguards. You obtain a practical base to build and test advanced systems.
preview
Automated Trade Statement Exporter to Excel-Compatible XLSX in MQL5

Automated Trade Statement Exporter to Excel-Compatible XLSX in MQL5

An MQL5 script reconstructs closed trades from deal history using a two-pass SL/TP lookup and exports them to an Excel-compatible XLSX file without third-party libraries. Four cooperating classes handle trade data, history reconstruction, SpreadsheetML XML generation, and ZIP assembly via .NET's ZipFile class through a direct ShellExecuteW call with marker-file polling. The output opens in Excel and Google Sheets with correct numeric types, formatted date columns, and a bold header row.
preview
Bayesian Online Change-Point Detection (BOCPD) in MQL5: One Regime-Break Signal, Three Ways to Use It

Bayesian Online Change-Point Detection (BOCPD) in MQL5: One Regime-Break Signal, Three Ways to Use It

This article delivers Bayesian Online Change-Point Detection as a single, dependency-free MQL5 class that maintains a per-bar, causal probability of a regime break. We use it three ways: a live monitor, a moving average that flushes on breaks, and a risk overlay with a matched-frequency random control. Readers get a reusable primitive to watch structural change, adapt indicators, and gate exposure after detected shifts.
preview
Creating a Probabilistic Market-Neutral Trading Robot Based on a Return Distribution

Creating a Probabilistic Market-Neutral Trading Robot Based on a Return Distribution

A market-neutral trading strategy based on the empirical return distribution offers an alternative to traditional technical analysis methods, replacing price direction forecasting with the statistical placement of orders at levels the price is likely to reach. This article provides a detailed analysis of the mathematical framework for calculating percentiles, algorithms for weighting position sizes based on the probability of an order being triggered, and mechanisms for adapting to changing market conditions through grid expiration. A complete implementation in MQL5 is provided.
preview
Crow Search Algorithm (CSA)

Crow Search Algorithm (CSA)

The Crow Search Algorithm (CSA) is an elegant metaheuristic inspired by crows’ ability to hide food and find other crows' caches, solving optimization problems by balancing following successful solutions with random exploration of the search space. Let's find out how well the algorithm performs.
preview
Trading Options Without Options (Part 3): Complex Option Strategies

Trading Options Without Options (Part 3): Complex Option Strategies

The article discusses flat (non-directional) and trend-following (directional) option strategies and their implementation in MQL5. The EA described in the previous article is updated. The display of option levels has been added. Now it is time to examine the strategies used by options traders in practice and put them into action.