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
Building Your Personal Expert Advisor (Part 4): Risk Management III—Risk Models and Order Execution

Building Your Personal Expert Advisor (Part 4): Risk Management III—Risk Models and Order Execution

The EA now defines risk by percentage, fixed cash, or fixed lot and can measure percentage against balance or equity. It supports market, limit, and stop orders, sizes from the planned entry, and enforces spread‑aware stop minima. Additional safeguards include downward volume rounding, explicit handling when the minimum lot exceeds target risk, and pending‑order distance/expiry checks, organized under a Plan–Validate–Execute structure.
preview
Automating Classic Market Methods in MQL5 (Part 6): Jesse Livermore's Pivotal Point System

Automating Classic Market Methods in MQL5 (Part 6): Jesse Livermore's Pivotal Point System

This article presents a complete MQL5 Expert Advisor that implements Jesse Livermore's market key as a deterministic state machine. It detects pivotal levels from consolidations using ATR and volume expansion, scales in across four tranches, and exits on abnormal behavior defined by range and volume. The EA validates inputs in OnInit, requires a hedging account, and compiles out of the box for testing Livermore's rules on daily data.
preview
MQL5 Bootstrap (IV): Trailing and Break-even Stop Helpers

MQL5 Bootstrap (IV): Trailing and Break-even Stop Helpers

This article presents reusable MQL5 utilities for managing trailing and break-even stops. It covers fixed-point, moving average, ATR, Parabolic SAR, money-based, and time-periodic trailing, plus break-even by points and by money, with activation thresholds, step logic, reverse-move protection, and broker-level validation. Code examples and Bootstrap classes show how to integrate these helpers into Expert Advisors to standardize position control and reduce duplicate code.
preview
Implementing a Continuous LLM Adaptation System for Algorithmic Trading

Implementing a Continuous LLM Adaptation System for Algorithmic Trading

SEAL (Self-Evolving Adaptive Learning) is a system for the continuous adaptation of large language models (LLMs) for algorithmic trading, designed to address the problem of rapid model degradation in changing markets. Instead of periodic retraining, which takes hours and erases old patterns, SEAL learns from every closed trade, maintains priority memory for important examples, and automatically initiates incremental fine-tuning when accuracy drops or a market regime change occurs.
preview
Building Your Personal Expert Advisor (Part 3): Risk Management II—Margin and Allowable Risk

Building Your Personal Expert Advisor (Part 3): Risk Management II—Margin and Allowable Risk

Risk-based lot sizing can still exceed what free margin allows. The article adds a margin-aware cap using OrderCalcMargin(), an optional adaptive cap that scales with ACCOUNT MARGIN LEVEL, and a single pre-trade validation gate that unifies position limits, risk sizing, and margin checks. Readers get concrete code to prevent order rejections and over-committing margin, with clear logs when a trade is reduced or skipped.
preview
Eco-inspired Evolutionary Algorithm (ECO)

Eco-inspired Evolutionary Algorithm (ECO)

The article discusses the ECO optimization algorithm, which is based on ecological concepts: populations are grouped into habitats based on territorial proximity, exchange genetic material within habitats, and migrate between them. Despite its wide range of operators and elegant biological metaphor, the algorithm produced a certain result discussed below.
preview
From Basic to Intermediate: Classes (II)

From Basic to Intermediate: Classes (II)

This article is intended to be as educational as possible, since the topic we will be discussing often causes considerable confusion in itself. Therefore, dear reader, please try to put what is explained here into practice. If you have any questions, be sure to leave a comment—after all, understanding destructors is no easy task.
preview
Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Conclusion)

Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Conclusion)

The article will show you how Mamba4Cast turns theory into a working trading algorithm and lays the groundwork for your own experiments. Do not miss this opportunity to gain a full range of knowledge and inspiration for developing your own strategy.
preview
Building Your Personal Expert Advisor (Part 5): Risk Management IV—Basket Risk and Strategy-Specific Sizing

Building Your Personal Expert Advisor (Part 5): Risk Management IV—Basket Risk and Strategy-Specific Sizing

Part 5 moves risk control from single trades to a basket-level framework. The EA aggregates its own positions, computes volume‑weighted entry, floating P/L including swap, and used margin, then enforces limits on combined loss, margin, position count, and time underwater, while logging maximum adverse excursion. A companion mean‑reversion EA demonstrates target‑based sizing and caps on implied risk that remains hidden when trades are evaluated in isolation.
preview
Automating Chart Patterns in MQL5 (Part 2): The Double Top and Double Bottom

Automating Chart Patterns in MQL5 (Part 2): The Double Top and Double Bottom

We build a robust MQL5 detector for double tops and double bottoms that first confirms the H4 trend, then validates six conditions (point equality, neckline placement, ordering, width, height, and ATR‑based tolerances). The neckline break is timed on the chart's timeframe, and a three-state machine ensures each pattern trades once. The measured‑move target translates structure into clear exits.
preview
Making Custom Indicators for Beginners (Part 2): Fisher-style Indicator

Making Custom Indicators for Beginners (Part 2): Fisher-style Indicator

This article develops a Fisher‑style Indicator in MQL5 from first principles: normalize price within a recent high/low window, smooth and clamp the value, then apply a logarithmic transform. We cover buffer wiring, calculation‑buffer state management across bars, and seeding for stable starts. An accompanying EA implements threshold and reversal confirmation to show how to act on the signal.
preview
Master MQL5 — From Beginner to Pro (Part VII): Principles of Debugging MQL Applications

Master MQL5 — From Beginner to Pro (Part VII): Principles of Debugging MQL Applications

Debugging is an integral part of the programming cycle. This article discusses common techniques for debugging any application running in the MetaTrader 5 environment.
preview
Ebola Optimization Search Algorithm (EOSA)

Ebola Optimization Search Algorithm (EOSA)

The article examines the EOSA algorithm, which is inspired by the mechanisms of Ebola virus transmission: short-distance transmission through close contact (exploitation) and long-distance transmission through travel (exploration). An analysis of the original publication revealed critical issues in the mathematical formulas and an epidemiological model that was impractical to implement, which required a significant overhaul of the algorithm to produce a workable implementation.
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.