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
Ecological Cycle Optimizer (ECO)

Ecological Cycle Optimizer (ECO)

The ECO (Ecological Cycle Optimizer) algorithm offers an interesting metaphor for applying the concept of the ecological cycle to the field of metaheuristic optimization. The idea of dividing a population into trophic levels — producers, herbivores, carnivores, omnivores, and decomposers — creates a hierarchical search structure, in which each group contributes to the overall optimization process.
preview
Neural Networks in Trading: Unraveling Structural Components (Encoder)

Neural Networks in Trading: Unraveling Structural Components (Encoder)

We invite you to explore the next stage in implementing the SCNN framework, which combines flexibility and interpretability, allowing structural components of a time series to be identified precisely. The article provides a detailed explanation of the mechanisms of adaptive normalization and attention, which ensure the model's resilience to changing market conditions.
preview
Tables in the MVC Paradigm in MQL5: Symbol Correlation Table

Tables in the MVC Paradigm in MQL5: Symbol Correlation Table

In this article, we will refine the graphics library classes by adding a vertical header to the table and use the table classes to create an indicator that displays the correlation between the symbols specified in the settings.
preview
Machine Learning Under Constraint (Part 2): Calibrating Position Size to the Remaining Drawdown Budget

Machine Learning Under Constraint (Part 2): Calibrating Position Size to the Remaining Drawdown Budget

We present a rule-set-aware calibration chain that turns the remaining risk budget into a calibrated sigmoid scale for position sizing. It computes a ceiling from stop loss pct and safety factor, back-solves w at a reference divergence, and flattens size progressively as the budget shrinks. The paper also clarifies where leverage caps must be applied in production: at the lots conversion, since risk-based sizing alone does not enforce max leverage.
preview
Self-Optimizing Expert Advisors in MQL5 (Part 19): Parameter Optimization For Time-Lagged Independent Components Analysis (2)

Self-Optimizing Expert Advisors in MQL5 (Part 19): Parameter Optimization For Time-Lagged Independent Components Analysis (2)

The article shows how to tune ICA hyperparameters with a supervised evaluation pipeline and apply spectral clustering to time-lagged indicators. Cross-validation identifies the optimal number of clusters, which are translated into expected return and risk measures. These signals drive dynamic position sizing and stop-loss control, with surrogate models converted to ONNX and integrated into an MQL5 Expert Advisor.
preview
Zero-Copy Tick Streaming (Part 1): Bridging MetaTrader 5 to Shared Memory with the Arrow C Data Interface

Zero-Copy Tick Streaming (Part 1): Bridging MetaTrader 5 to Shared Memory with the Arrow C Data Interface

This article implements a lock-free shared-memory bridge in MetaTrader 5 that writes ticks in Apache Arrow’s columnar layout via the C Data Interface. It details the column layout, double buffering with a seqlock, and a batching strategy. You get full source for a writer class, a streaming Expert Advisor, and a self-test script that validates correctness before any Python reader is involved.
preview
First Fractal Breakout — Intraday Strategy, Expert Advisor and Backtesting

First Fractal Breakout — Intraday Strategy, Expert Advisor and Backtesting

This article develops a market‑structure‑driven intraday breakout system based on Bill Williams fractals. We define session bounds, derive volatility‑scaled stops, use fixed risk and take‑profit multipliers, and limit trades to one per direction. An MQL5 Expert Advisor, visualization and statistics, tick-level backtests, an ORB comparison, and a cross-asset forward test provide a complete, replicable workflow.
preview
Market Simulation: Position View (XI)

Market Simulation: Position View (XI)

In this article, I will show you, dear reader, how to select the objects we create on the chart and modify the position indicator so that it can perform many more functions than originally intended. We will look at how to implement the ability to move price levels and create price lines directly on the chart. Many people may find this difficult. However, you will see that we'll do this with minimal effort. You just need to give it a little thought.
preview
From Basic to Intermediate: Queues, Lists, and Trees (III)

From Basic to Intermediate: Queues, Lists, and Trees (III)

In this article, we will take the next step in understanding what a linked list is and how it works. Although the content of this article may seem rather complex and confusing to beginners, I will try to explain it in the simplest terms possible. This will help you understand why and when to use linked lists.
preview
Machine Learning Under Constraint (Part 1): A Configurable Rule Set for Prop-Firm Position Sizing

Machine Learning Under Constraint (Part 1): A Configurable Rule Set for Prop-Firm Position Sizing

Hardcoded prop-firm rules lock the sizer to one program. This article factors those rules into a PropFirmRuleSet and refactors PropFirmAccountState and the sizing modifiers to consume it, including dynamic versus fixed daily limits and the news-window profit-credit haircut. Parity against the original FundedNext behavior is validated on a simulated equity path, so you can retarget sizing by configuration instead of rewriting code.
preview
Market Simulation: Position View (X)

Market Simulation: Position View (X)

We need a way to handle the graphical objects we create. The approach presented in the previous article works very well for certain scenarios. In this case, we will need something more complex, given the specific nature of the problem at hand. Therefore, we will not attempt to replace the ZOrder management mechanisms already present in MetaTrader 5, nor, of course, will we check which object is in the foreground or covered by another object. We are going to do something completely different. Here, I will show you what changes need to be made to the code in order to use part of what MetaTrader 5 already does for us.
preview
From Basic to Intermediate: Queues, Lists, and Trees (II)

From Basic to Intermediate: Queues, Lists, and Trees (II)

This is an article that you, dear reader, should study carefully. That is due to the nature of the material presented here. Although we have tried to present the material as simply and informatively as possible, the information provided here can certainly seem quite complex to those who are just beginning to learn programming. Nevertheless, this is no reason to lose heart or ignore what is explained here, as this article will establish a link between two completely different, though closely related, topics.
preview
Building a Bar Replay Tool in MQL5

Building a Bar Replay Tool in MQL5

This article shows how to build an interactive bar replay tool in MQL5 for MetaTrader 5 that reveals historical candles one by one without exposing future data. You will implement custom candles with DRAW COLOR CANDLES, an event-driven engine with OnChartEvent and OnTimer, a dashboard with Play/Pause, a draggable replay anchor, and Buy/Sell paper trading with SL/TP lines, while keeping the active bar in view to practice discretionary analysis and execution.
preview
Price Action Analysis Toolkit Development (Part 81): Adding Persistent Historical Bookmarks to an MQL5 Navigator

Price Action Analysis Toolkit Development (Part 81): Adding Persistent Historical Bookmarks to an MQL5 Navigator

We introduce a persistent bookmark layer for the MetaTrader 5 History Navigator. Bookmarks capture a chart's symbol, timeframe, and historical position with a name and notes, write them to a CSV file, and reload them later without manual date entry. The implementation integrates bookmark management into the current navigation engine, enabling quick creation, selection, navigation, and deletion for efficient historical study.
preview
Market Simulation: Position View (IX)

Market Simulation: Position View (IX)

In this turning-point article, we will begin to explore in greater depth the interaction between the applications we are developing to ensure full support for the replay/simulation system. Here we will analyze a problem that, on the one hand, is quite unpleasant, but on the other hand, is very interesting to explain and solve. The problem is this: how can we restore the take-profit and stop-loss lines after they have been deleted, and do so without using the terminal by performing the operation directly on the chart? At first glance, it seems simple. However, there are several obstacles that must be overcome.
preview
From Basic to Intermediate: Queues, Lists, and Trees (I)

From Basic to Intermediate: Queues, Lists, and Trees (I)

In this article, we'll begin exploring a short series of concepts that are of immense importance to anyone who truly wants to learn how to program properly. Since this may seem very complicated at first—even though it is based on simple elements—we will go through the material step by step. So, let's start by figuring out what queues are.
preview
Markov Chain Monte Carlo Sampling Methods: The HMC Algorithm

Markov Chain Monte Carlo Sampling Methods: The HMC Algorithm

The article examines the Hamiltonian Monte Carlo (HMC) algorithm — the gold standard for sampling from complex multivariate distributions. A full-featured implementation of HMC in MQL5 is presented, including adaptive mass matrix tuning, MAP estimation using the L-BFGS optimization method, and comprehensive diagnostics.
preview
Market Simulation: Position View (VIII)

Market Simulation: Position View (VIII)

In the previous article, we considered how to implement a position indicator that allows you to close an open position directly from the chart by interacting with an object available on the chart. After completing and testing the first mechanism, we began making changes to ensure that take-profit and stop-loss levels could be removed for an open position. However, since the necessary changes required detailed explanations, in that same article I showed only the changes that needed to be made to the expert advisor; I still needed to show the changes that needed to be made to the position indicator.
preview
Neural Networks in Trading: Unraveling Structural Components (SCNN)

Neural Networks in Trading: Unraveling Structural Components (SCNN)

We invite you to explore the innovative SCNN framework, which takes time series analysis to a new level by clearly separating data into long-term, seasonal, short-term, and residual components. This approach significantly improves forecasting accuracy by allowing the model to adapt to complex and changing market dynamics.
preview
From Basic to Intermediate: Like Bubbles

From Basic to Intermediate: Like Bubbles

This article will explain a very simple and easy-to-understand mechanism whose purpose is to sort any array. In it, we will see that the result obtained does not always meet expectations, so the implementation itself will need to be adapted to achieve the desired results.
preview
Survival Analysis for Trade Exits: A Discrete-Time Competing-Risks Model in MQL5

Survival Analysis for Trade Exits: A Discrete-Time Competing-Risks Model in MQL5

Fixed exits ignore state changes while a trade is open. We implement a discrete-time competing-risks model entirely in MQL5, estimate cause-specific hazards for take-profit and stop-loss via Newton–Raphson on a person-period dataset with time-varying features, and turn cumulative incidence into a bar-by-bar hold-or-close rule, then test it against fixed take-profit/stop-loss with identical entry logic.
preview
Reinforcement Learning Meets MetaTrader 5: A Complete Pipeline for Training, Validating and Honestly Evaluating a Gold Trading Bot

Reinforcement Learning Meets MetaTrader 5: A Complete Pipeline for Training, Validating and Honestly Evaluating a Gold Trading Bot

This article presents a complete RL trading pipeline for XAUUSD: a supervised signal baseline with triple-barrier labels, PPO training, purged walk-forward validation with embargo, multi-seed checks, and contract-guarded deployment with normalization. It includes runnable code for data validation, features, environment, training, and broker‑based reconciliation. The live demo over 763 closed trades showed no statistically significant edge, and the methods highlight where information and costs, not architecture, set performance limits.
preview
Dandelion Optimizer (DO)

Dandelion Optimizer (DO)

The Dandelion Optimizer (DO) turns the simple flight of a seed carried by the wind into a mathematical search strategy. The three phases — vortex rising, drift toward the center of the population, and landing along a Lévy-flight trajectory — form an elegant metaphor that yields interesting results in practice.
preview
Market Simulation: Position View (VII)

Market Simulation: Position View (VII)

In this article, we'll start making some improvements to the position indicator so that we can interact with it and modify price lines or close a position directly through the position indicator. Before we move on to the implementation, there are a few things worth clarifying, especially for those who aren't familiar with this. The indicator cannot be used in any way to change anything on the trading server. This is because MetaTrader 5 has a security system in place that allows only Expert Advisors to modify orders and positions. No application other than an Expert Advisor can manipulate orders or positions.
preview
Combining LLM, CatBoost, and Quantum Computing into a Unified Trading System

Combining LLM, CatBoost, and Quantum Computing into a Unified Trading System

The article proposes a synthesis of new technologies to overcome the limitations of classical indicators in market data analytics. It shows how language models and quantum encoding can reveal hidden market patterns that traditional methods overlook. The experiment confirms the value of new technologies and proposes an updated analysis methodology aligned with the current state of computational innovation.
preview
From Basic to Intermediate: Navigating the Sandbox

From Basic to Intermediate: Navigating the Sandbox

In this article, we'll look at two ways to inspect the contents of the sandbox and even interact with it, using MetaTrader 5 as the base platform. Understanding the material in this article is essential to understanding what will be covered in subsequent articles.
preview
MetaTrader 5 Machine Learning Blueprint (Part 20): Denoising, Detoning, and Clustering the Feature Correlation Matrix

MetaTrader 5 Machine Learning Blueprint (Part 20): Denoising, Detoning, and Clustering the Feature Correlation Matrix

Raw feature correlations contain estimation noise and a shared market-mode component that distort clustering. We fit the Marcenko–Pastur noise ceiling (with an effective sample size correction), apply constant-residual denoising and market detonation, and run the Optimal Number of Clusters routine. The result is a cleaned correlation matrix and stable cluster labels that avoid substitution effects and feed clustered MDI/MDA in the next article.
preview
Building a Hull Moving Average Momentum Oscillator in MQL5

Building a Hull Moving Average Momentum Oscillator in MQL5

This article builds a Hull Moving Average Momentum indicator in MQL5 by combining raw price momentum with Hull MA smoothing. We compute momentum as the close-to-close difference over a user-defined length, form 2×Fast WMA − Slow WMA, then apply a final WMA with a square‑root period. The implementation covers inputs, buffers, warm-up/recalculation, and visualization with a color-coded line and zero-line filling, helping interpret positive/negative momentum without treating zero crossings as signals.
preview
Price Action Analysis Toolkit Development (Part 80): Building a History Navigator for MetaTrader 5

Price Action Analysis Toolkit Development (Part 80): Building a History Navigator for MetaTrader 5

We implement a History Navigator for MetaTrader 5 that jumps the chart to an exact historical period by date and time. The dialog validates inputs, converts them to datetime, and searches bar times with a binary-search routine before centering the selected candle. The navigation logic is separated from chart control, improving testability and maintenance, and a one-click return restores the live market view.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 1): Why the terminal needs its own 2D-renderer Contents

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 1): Why the terminal needs its own 2D-renderer Contents

This article opens a step-by-step 2D graphics engine for MetaTrader. It standardizes ARGB colors and implements a reusable surface: a uint pixel buffer uploaded as a dynamic resource and shown via one OBJ_BITMAP_LABEL. You will draw rectangles and a vertical gradient, check real transparency, and learn an efficient update path with a single Flush call.
preview
Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (Conclusion)

Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (Conclusion)

We are pleased to present the final part of our series on GinAR — a neural network framework for time series forecasting. In this article, we analyze the results of testing the model on new data and assess its robustness under real-market conditions.
preview
Dendritic Cell Algorithm (DCA)

Dendritic Cell Algorithm (DCA)

The Dendritic Cell Algorithm (DCA) is a metaheuristic inspired by the mechanisms of the innate immune system. Dendritic cells patrol the search space, accumulate signals about the quality of positions, and reach a collective decision: whether to exploit what they have found or to continue exploration. Let's take a look at how a biological model for detecting pathogens is transformed into an optimization algorithm.
preview
Isolation Forest: Unsupervised Anomaly Detection, and What It Actually Finds in Price Data

Isolation Forest: Unsupervised Anomaly Detection, and What It Actually Finds in Price Data

This article implements a self-contained Isolation Forest library for MetaTrader 5 with no labels, no distribution assumptions and no external dependencies. It details a reproducible 64‑bit generator, tree/forest construction, scoring and feature design, then verifies results against Python and market data with two null models. The package includes an indicator that plots the decision variable and a gate example. Readers get a validated library, clear limits of applicability and a practical way to calibrate thresholds.
preview
Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (Key Components)

Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (Key Components)

We invite you to explore a new implementation of the key components of the GinAR framework — an adaptive algorithm for working with graph-structured time series. This article provides a step-by-step breakdown of the architecture and the algorithms for the forward pass and error backpropagation.
preview
Building a Visual Position Planning Tool for MetaTrader 5

Building a Visual Position Planning Tool for MetaTrader 5

This article develops a visual position planning tool in MQL5 for evaluating trade setups before execution. The tool utilizes interactive Entry, Stop-Loss, and Take-Profit lines to calculate the stop distance, risk amount, estimated position size, potential reward, and risk-to-reward ratio directly on the chart. It supports market, limit, and stop order scenarios while keeping the focus strictly on planning and analysis rather than trade execution.
preview
Building a Position Lifecycle Manager in MQL5 (Part 1): The Foundation of Reusable Position Management

Building a Position Lifecycle Manager in MQL5 (Part 1): The Foundation of Reusable Position Management

A state-driven Position Lifecycle Manager brings structure to post-entry trade handling in MetaTrader 5. It discovers open positions, tracks them via managed objects, applies ATR-based protection, executes break-even transitions, and removes completed trades, with a clear NEW → PROTECTED → BREAKEVEN → CLOSED flow. The article shows integration with the standard MACD EA to enable reuse across strategies.
preview
Deterministic Dendritic Cell Algorithm (dDCA)

Deterministic Dendritic Cell Algorithm (dDCA)

The article presents an adaptation of the Deterministic Dendritic Cell Algorithm (dDCA) for continuous optimization problems. The algorithm, inspired by the immune system's Danger Theory, uses a signal accumulation mechanism to automatically balance exploration and exploitation within the search space.
preview
Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (GinAR)

Neural Networks in Trading: An End-to-End Multivariate Time Series Forecasting Model (GinAR)

We invite you to explore an innovative approach to forecasting time series with missing data using the GinAR framework. The article demonstrates the implementation of key components using OpenCL, which ensures high performance. In our next publication, we will take a detailed look at how to integrate these solutions into MQL5. This will help understand how to apply the method in practice in trading.
preview
Network Momentum for MetaTrader5: Trading the Lead-Lag Graph Between Markets

Network Momentum for MetaTrader5: Trading the Lead-Lag Graph Between Markets

This article builds a trend-following Expert Advisor that trades momentum spillover across markets, implemented fully in MQL5 without external solvers. It detects leaders with Derivative Dynamic Time Warping, learns a sparse weighted network by convex optimization, and propagates momentum through it with a reverting response. Readers get a step-by-step, reproducible pipeline and a working EA ready to run in the Strategy Tester.
preview
A Reusable Breakeven Manager in MQL5 with Spread Compensation

A Reusable Breakeven Manager in MQL5 with Spread Compensation

A robust breakeven implementation for MQL5 is built around live spread sampling and correct pip-to-price conversion by symbol digits. CBreakevenManager moves SL to open_price ± spread ± buffer once a real‑pip activation threshold is reached and prevents duplicate modifications. A demo EA shows the behavioral difference versus a naive breakeven, and a script verifies core calculations.