MQL4 and 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
The Mathematics of Volatility: Why the GRI Indicator Deserves to Return to Your Trading Terminal

The Mathematics of Volatility: Why the GRI Indicator Deserves to Return to Your Trading Terminal

The article focuses on the Gopalakrishnan Range Index (GRI/ROCI), which quantitatively assesses the market's "degree of chaos" using the logarithm of the closing price range over a given period. The article shows how to implement GRI in MetaTrader 5, resolve the issue of negative values using a shifted logarithm, and convert the scale to convenient "points" by normalizing it by Point. Next, we examine practical scenarios for using GRI as a filter for volatility and market phases.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 2): Points, Contours and the Path

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 2): Points, Contours and the Path

This second part adds the geometry layer to a Cairo‑inspired graphics library for MetaTrader 5. It defines a path of double‑precision points grouped into contours, records open/closed intent, and stores vertices in a flat array with start indices. We implement MoveTo, LineTo, Close, provide basic shape helpers, and include a demo that visualizes the built geometry for inspection and reuse.
preview
Market Simulation: Position View (XIV)

Market Simulation: Position View (XIV)

Now we will implement this solution, since MQL5 is based on the same principles as event-driven programmingю Developers often use this model when creating DLLs. I know that at first, the event-driven model will seem confusing and illogical. But in this article, I will explain the principles of event-driven programming in a way that is easier to understand, so that if you are just getting started, you will have a clear grasp of how it works. Understanding what I am about to explain in this article will help you throughout your work as a programmer.
preview
From Basic to Intermediate: Classes (I)

From Basic to Intermediate: Classes (I)

In this article, we explain what a class is and why this concept came about. Although the topic is interesting, we will focus here on the principles underlying MQL5 programming. This article is just an introduction.
preview
Neural Networks in Trading: Decomposition Instead of Scaling (SSCNN)

Neural Networks in Trading: Decomposition Instead of Scaling (SSCNN)

In this article, we begin our exploration of the SSCNN framework — a modern architectural solution for time series analysis that combines accuracy, a structured design, and high computational efficiency. We will systematically examine its theoretical aspects, highlight the key differences from its predecessors, and begin the practical implementation of its basic components in the MQL5 environment.
preview
Market Simulation: Position View (XIII)

Market Simulation: Position View (XIII)

In this article, we will look at how to easily implement an indicator that shows whether a position is generating a profit or a loss. The procedure is simple and effective. Even without in-depth expertise, this indicator will allow you to easily recognize when to close a position. This way, you will avoid unexpected results, since the calculation reflects the actual outcome you would get if you closed the position.
preview
From Basic to Intermediate: Queues, Lists, and Trees (V)

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

In this article, we implemented the first components of a tree structure. Since I realize that this structure can be very complex at the beginning of the learning process, we will introduce it gradually, step by step. This way, everyone will be able to understand how a tree works and when it is best to use one.
preview
Bidirectional LSTM and Quantum Computing for Predicting the Direction of Price Movement

Bidirectional LSTM and Quantum Computing for Predicting the Direction of Price Movement

The article presents a reproducible implementation of a hybrid quantum-neural network model for algorithmic trading on Forex without using real quantum hardware. A fixed three-qubit quantum circuit in IBM Qiskit converts sliding-window statistics (mean returns, volatility, and range) into a probability distribution, from which seven quantum metrics are calculated. These features are integrated into a bidirectional LSTM architecture with regularization and mechanisms to address class imbalance, including focal loss and a sampler.
preview
Walsh Functions in Modern Trading

Walsh Functions in Modern Trading

The article discusses the application of Walsh functions in trading. We will explore the basic principles of using these functions to analyze financial markets, forecast prices, and make trading decisions. We will also discuss the advantages and disadvantages of these functions, as well as the prospects for their application in trading and technical analysis.
preview
Defining your Edge (Part 3): Using HMM and GRU in an Expert Advisor

Defining your Edge (Part 3): Using HMM and GRU in an Expert Advisor

We examine how a Hidden Markov Model (HMM) estimates latent market regimes while basing on observable price and indicator sequences. This is done by estimating the probability of state transitions. A Gated Recurrent Unit (GRU) network models time dependencies and keeps important information over several observations. In an Expert Advisor, HMM-based regime probabilities, can be merged with GRU-based sequence learning to better classify increments in accumulation, distribution, and momentum prior to their showing up in regular price confirmations.
preview
Partial Information Decomposition: When Two Indicators Together Say More Than Either Alone

Partial Information Decomposition: When Two Indicators Together Say More Than Either Alone

We introduce a Partial Information Decomposition library for MQL5 that decomposes two sources about a target into four atoms: unique to each, shared, and synergy. The implementation uses quantile binning, tabulated logarithms, and a maximum-entropy fit (for I_ccs), and it pairs results with a block-permutation null because atoms sit above zero on finite samples. Use it to screen indicator pairs and judge significance, including family-wise correction.
preview
Neural Networks in Trading: Disentangling Structured Components (Conclusion)

Neural Networks in Trading: Disentangling Structured Components (Conclusion)

The article provides a detailed explanation of the SCNN architecture and one way to implement it using MQL5. We will show how time series decomposition can be combined with neural network methods and attention mechanisms.
preview
Combining 3D Bars, Quantum Computing, and Machine Learning into a Unified Trading System

Combining 3D Bars, Quantum Computing, and Machine Learning into a Unified Trading System

The article presents the full integration of the 3D-bar module into a quantum-enhanced trading system for forecasting the movement of currency pairs. The system combines stationary four-dimensional features, an 8-qubit quantum encoder, and CatBoost gradient boosting with 52+ features. The system is implemented in Python using MetaTrader 5, Qiskit, CatBoost, and optional integration with the Llama 3.2 LLM for interpreting forecasts.
preview
Decoding Market Intent: Reading Structure, Liquidity, and Price Behavior

Decoding Market Intent: Reading Structure, Liquidity, and Price Behavior

We implement a five-stage MQL5 pipeline that quantifies market structure, liquidity interaction, and price behavior on four timeframes, then resolves them into a 0–100 Market Intent Score. Decision states (WAIT/WATCH/ACTION) are driven by explicit weights plus hard gates. The analytical core feeds a concise dashboard and, when AutoTrade is on, an execution layer with entry zones, invalidation and liquidity‑based targets.
preview
Building Your Personal Expert Advisor (Part 2): Risk Management and Dynamic Lot Sizing

Building Your Personal Expert Advisor (Part 2): Risk Management and Dynamic Lot Sizing

This part implements risk-based position sizing for the EA. Lot size is derived from account balance, a chosen risk percent, and ATR-based stop distance, then confined and rounded to the broker's volume rules and minimum stop levels. An optional drawdown-aware layer reduces risk during equity declines. Readers get a reproducible sizing function that keeps per-trade risk consistent and orders acceptable to the server.
preview
Market Simulation: Position View (XII)

Market Simulation: Position View (XII)

In this article, you will learn how to create a visual signal on your trading platform so you can determine directly on the chart whether a position is long or short, without having to open the Terminal. In addition, the article also explains how to implement a feature that improves the display when moving Take Profit and Stop Loss lines by hiding the horizontal line that follows the mouse cursor while these lines are being moved, to avoid confusion. The article provides practical insight into setting up market simulation systems.
preview
From Basic to Intermediate: Queues, Lists, and Trees (IV)

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

In this article, we will conclude the section on the implementation and explanation of the linked list. However, the implementation presented here omits one detail that can be implemented in a linked list. We will discuss this later, in another article.
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: Disentangling Structured Components (Encoder)

Neural Networks in Trading: Disentangling Structured 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: Disentangling Structured Components (SCNN)

Neural Networks in Trading: Disentangling Structured 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.