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
Interactive Supply and Demand Zone Manager in MQL5: From Manual to Automated Lifecycle

Interactive Supply and Demand Zone Manager in MQL5: From Manual to Automated Lifecycle

Replace static drawings with automated, stateful zones controlled by a CZone wrapper. The system synchronizes user rectangles, sizes zones by ATR, validates breakouts using consecutive closes, applies ghost/deactivation rules, merges nearby structures by a 1.5×ATR threshold, and projects edges forward. Traders gain durable levels that update themselves and reduce repetitive chart management.
preview
Market Microstructure in MQL5 (Part 4): Volatility That Remembers

Market Microstructure in MQL5 (Part 4): Volatility That Remembers

This article adds eight volatility functions to MicroStructure_Foundation.mqh, including realized volatility, duration-adjusted volatility, fractional volatility, a FIGARCH-inspired proxy, a volatility clustering index, a GJR-GARCH asymmetry measure (using the Dube library), bipower-variation jump detection, and a wrapper function. The MFDFA implementation is revised to return the conventional Legendre-transform Δα with an R² confidence field, replacing the τ-spread proxy used in the original submission. Thresholds are derived from 514 NY sessions of NQ E-mini Nasdaq 100 futures (May 2024–May 2026); no new include file is created.
preview
From Basic to Intermediate: Objects (II)

From Basic to Intermediate: Objects (II)

In today's article, we will look at how to control some object properties in a simple way using code. We will also see how a custom application can place more than one object on the same chart. In addition, we will begin to understand the importance of assigning a short name to any indicator we plan to implement.
preview
Market Simulation (Part 24): Getting Started with SQL (VII)

Market Simulation (Part 24): Getting Started with SQL (VII)

In the previous article, we completed the necessary introduction to SQL. And, in my opinion, we properly clarified what we wanted to show and explain about SQL. This was done so that anyone who comes to look at the replication/simulation system being built can at least get an idea of what may be happening there. The point is that there is no sense in programming things that SQL handles perfectly.
preview
Analyzing Price Time Gaps in MQL5 (Part II): Creating a Heat Map of Liquidity Distribution Over Time

Analyzing Price Time Gaps in MQL5 (Part II): Creating a Heat Map of Liquidity Distribution Over Time

A detailed guide on how to create a heat map indicator for MetaTrader 5 that visualizes the price distribution over time. The article reveals the mathematical basis of time density analysis, where each price level is colored from red (minimum stay time) to blue (maximum stay time).
preview
From Basic to Intermediate: Function Pointers

From Basic to Intermediate: Function Pointers

You have probably already heard about pointers when it comes to programming. But did you know that we can use this kind of data here in MQL5? Of course, this must be done in a way that keeps us in control and avoids strange program behavior during execution. Still, because this is a resource with a very specific purpose and aimed at particular kinds of tasks, it is rare to hear anyone discuss what a pointer is and how to use it in MQL5.
preview
Market Simulation (Part 23): Getting Started with SQL (VI)

Market Simulation (Part 23): Getting Started with SQL (VI)

In this article, we will see how to visualize a database and, from that, understand how it is structured. This is done by analyzing the database’s internal structure. Although this may seem unnecessary at first, it is fully justified if we really want to become database administrators. After all, some people make a living maintaining and designing databases.
preview
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 3): A Regime-Adaptive Mean-Reversion Swing Trading System

Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 3): A Regime-Adaptive Mean-Reversion Swing Trading System

The article describes and codes MR Swing in MQL5, a mean‑reversion swing approach that combines a 200‑day hysteresis channel with Value Charts, DVO, and SVAPO. We document entry/exit rules for bull and bear regimes and show five‑year backtests on six high‑liquidity Nasdaq stocks. The complete EA code and backtest configurations are provided for reproducibility.
preview
MQL5 Trading Tools (Part 34): Replacing Native Chart Objects with an Interactive Canvas Drawing Layer

MQL5 Trading Tools (Part 34): Replacing Native Chart Objects with an Interactive Canvas Drawing Layer

We replace native MetaTrader chart objects with a canvas-based drawing engine that renders tools pixel-by-pixel on a full-chart bitmap layer. The article implements persistent object storage with per-tool style memory, precise hit testing, selection, whole-object dragging, and handle manipulation. It also adds new line tools, a reorganized category system with a one-click delete action, and a rubber-band preview for multi-click placement.
preview
MetaTrader 5 Machine Learning Blueprint (Part 17): CPCV Backtesting — From Python Model to Tick-Level Evidence

MetaTrader 5 Machine Learning Blueprint (Part 17): CPCV Backtesting — From Python Model to Tick-Level Evidence

We bridge Python-native artifacts to MQL5 for tick-accurate CPCV backtesting. The export script converts the ONNX model, calibrator, feature spec, and path masks to flat files, while the expert advisor rebuilds features, performs ONNX inference with calibration, and trades on real ticks. The Strategy Tester runs each combinatorial path, and Python aggregates per-path equities into a path Sharpe distribution to assess robustness after spread, slippage, and commission.
preview
Automating Classic Market Methods in MQL5 (Part 1): Wyckoff Accumulation and Distribution

Automating Classic Market Methods in MQL5 (Part 1): Wyckoff Accumulation and Distribution

The article describes an MQL5 EA that automates Wyckoff accumulation and distribution via a finite state machine. It confirms spring to SOS and upthrust to SOW before placing LPS or LPSY entries, using relative tick volume as the confirmation metric. Readers get the state model, detection criteria, code organization, and MetaTrader 5 testing procedure.
preview
Seasonality Indicator by Hours, Days of the Week, and Days of the Month

Seasonality Indicator by Hours, Days of the Week, and Days of the Month

The article explains how to develop a tool for analyzing recurring price patterns in financial markets — by day of the month (1-31), day of the week (Monday-Sunday), or hour of the day (0-23). The indicator analyzes historical data, calculates the average return for each period, and displays the results as a histogram with a forecast. It includes customizable parameters: seasonality type, number of bars analyzed, display as percentages or absolute values, chart colors.
preview
Backtracking Search Algorithm (BSA)

Backtracking Search Algorithm (BSA)

What if an optimization algorithm could remember its past journeys and use that memory to find better solutions? BSA does just that – balancing exploration with revisiting the tried and true. In this article, we reveal the secrets of the algorithm. A simple idea, minimum parameters and a stable result.
preview
Market Simulation (Part 22): Getting Started with SQL (V)

Market Simulation (Part 22): Getting Started with SQL (V)

Before you give up and decide to abandon learning SQL, allow me to remind you, dear readers, that here we are still using only the most basic elements. We have not yet looked at some of SQL's capabilities. Once you understand them, you will see that SQL is far more practical than it seems. Although, most likely, we will eventually change the direction of what we are building, because the creation process is dynamic. We will show a little more about creating different things in SQL, because this is truly important and useful for you. Simply thinking that you are more capable than an entire community of programmers and developers will only lead to wasted time and opportunities. Do not worry, because what comes next will be even more interesting.
preview
From Basic to Intermediate: Objects (I)

From Basic to Intermediate: Objects (I)

In this article, we will begin looking at how to work with objects directly on the chart. This is done using code specially developed for demonstration purposes. Working with objects is very interesting and can be a lot of fun. Since this will be our first contact with the topic, we will start with something very simple.
preview
Analyzing Price Time Gaps in MQL5 (Part I): Building a Basic Indicator

Analyzing Price Time Gaps in MQL5 (Part I): Building a Basic Indicator

Time gap analysis helps traders identify potential market reversal points. The article discusses what a time gap is, how to interpret it, and how it can be used to detect large volume influxes into the market.
preview
Dolphin Echolocation Algorithm (DEA)

Dolphin Echolocation Algorithm (DEA)

In this article, we take a closer look at the DEA algorithm, a metaheuristic optimization method inspired by dolphins' unique ability to find prey using echolocation. From mathematical foundations to practical implementation in MQL5, from analysis to comparison with classical algorithms, we will examine in detail why this relatively new method deserves a place in the arsenal of researchers facing optimization problems.
preview
Market Simulation (Part 21): First Steps with SQL (IV)

Market Simulation (Part 21): First Steps with SQL (IV)

Many of you may have far more experience working with databases than I do, and therefore may have a different opinion. Since it was necessary to explain why databases are designed the way they are, and why SQL has the form it does—especially why primary and foreign keys emerged—some things had to remain somewhat abstract.
preview
From Basic to Intermediate: Indicator (V)

From Basic to Intermediate: Indicator (V)

In this article, we will look at how to handle user requests to change the chart plotting mode. This is necessary so that an indicator designed for the current chart plotting mode does not look strange or differ from what a MetaTrader 5 user expects.
preview
Building an EquiVolume Indicator in MQL5

Building an EquiVolume Indicator in MQL5

We implement an EquiVolume indicator in MQL5 that converts standard candlesticks into volume-weighted boxes. The workflow includes selecting volume type, detecting the maximum volume within a lookback range, normalizing all values against it, and mapping them into proportional box widths. The result is a chart-based structure that visualizes trading activity intensity alongside price movement in MetaTrader 5.
preview
Formulating Dynamic Multi-Pair EA (Part 9): Market Microstructure Execution Noise Filtering

Formulating Dynamic Multi-Pair EA (Part 9): Market Microstructure Execution Noise Filtering

This article presents a multi-symbol execution filter that scores real-time market quality before any trade is allowed. It measures spread behavior, tick velocity, quote gaps, micro-volatility, and a slippage estimate, then classifies the state to block degraded conditions. Once noise settles, a liquidity sweep continuation model evaluates structure shifts so entries occur only when execution is mechanically stable.
preview
Custom Debugging and Profiling Tools for MQL5 Development (Part II): Profiling EAs and Testing Trading Logic

Custom Debugging and Profiling Tools for MQL5 Development (Part II): Profiling EAs and Testing Trading Logic

We build a compact profiler that records calls, min/max/average times, and slow-call counts to CSV, and a simple test runner that writes deterministic pass/fail reports. The article explains where to place measurements in an EA, how to sample ticks, and how to keep pure calculations testable. Running the script first and the profiling EA second provides repeatable evidence for regression analysis.
preview
Position Management: Scaling Into Winners With A Falling-Risk Pyramid

Position Management: Scaling Into Winners With A Falling-Risk Pyramid

We introduce CPyramidBridge, a thin MQL5 layer that maps bet-sizing results to CPyramidEngine. The bridge applies probability to initial lot sizing, enforces a capacity-aware entry gate, promotes add-ons from dynamic divergence, adapts the trailing stop to reserve estimates, and syncs signals on close, allowing an Expert Advisor to convert model confidence and concurrency into a structured, decreasing-risk pyramid.
preview
MQL5 Wizard Techniques you should know (Part 92): Using B-Tree Indexing and a Bayesian NN in a Custom Signal Class

MQL5 Wizard Techniques you should know (Part 92): Using B-Tree Indexing and a Bayesian NN in a Custom Signal Class

In this article we present yet another custom MQL5 Signal Class that we are labelling ‘CSignalBTreeBayesian’. We are marrying the algorithm of a balanced tree with a neural network that is built on Bayesian principles to formulate yet another custom signal testable independently or with other signals thanks to the MQL5 Wizard.
preview
MQL5 Bootstrap (I): Reusable Functions for Working with Positions and Orders

MQL5 Bootstrap (I): Reusable Functions for Working with Positions and Orders

This article presents a compact MQL5 utility layer for routine trade operations. It includes position existence checkers, position counters, bulk close helpers, and functions to retrieve the most recent or oldest position by symbol, magic, or type. A simple SMA crossover Expert Advisor demonstrates integration. The result is cleaner EAs, fewer inconsistencies across projects, and faster maintenance.
preview
Modular Indicator Architecture in MQL5 (Part 1): Stop Copy-Pasting and Start Writing Scalable, Reusable Code

Modular Indicator Architecture in MQL5 (Part 1): Stop Copy-Pasting and Start Writing Scalable, Reusable Code

This article develops an object-oriented framework for MQL5 indicators by evolving a primitive example into reusable modules. It formalizes partial buffer recalculation in OnCalculate, moves logic into header-based classes (CAppliedPrice, CSma), and introduces CSubIndiBase, CIndicatorBase, and a registry to centralize requirements. You get portable components, isolated inputs, and clean buffers with minimal boilerplate, making new indicators faster to assemble and easier to maintain.
preview
Encoding Candlestick Patterns (Part 2): Modeling Price Action as an Ordered Sequence

Encoding Candlestick Patterns (Part 2): Modeling Price Action as an Ordered Sequence

Developing permutation-based tools in MQL5 provides a systematic way to analyze candlestick pattern combinations for trading strategies. This article introduces a permutation calculator and generator designed to compute and enumerate all possible ordered candlestick sequences from bullish and bearish sets, with or without repetition. By generating exhaustive pattern combinations, traders can perform data-driven analysis to identify high-probability market patterns and improve decision-making in automated trading systems.
preview
Beyond GARCH (Part IV): Partition Analysis in MQL5

Beyond GARCH (Part IV): Partition Analysis in MQL5

In this article, we shift from Python research to native MQL5 engineering. We build the first module of the MMAR library: a shared constants header, an SVD-based OLS regression class, a Generalized Hurst Exponent estimator, and the partition analysis engine that computes the partition function, extracts tau(q), estimates H via zero-crossing interpolation, and scores multifractality through three diagnostic tests. Tested on 500,000 bars of EURUSD M10, the engine correctly classifies the data as multifractal in under four seconds. Part 4 of an eight-part series. Part 5 fits the tau(q) curve to four candidate distributions via the Legendre transform.
preview
Building Volatility Models in MQL5 (Part III): Implementing the SLSQP Algorithm for Model Estimation

Building Volatility Models in MQL5 (Part III): Implementing the SLSQP Algorithm for Model Estimation

An SLSQP optimizer is implemented in MQL5 to resolve parameter discrepancies between a volatility library and Python's ARCH module. The article details constraint handling, gradient options, configuration, and convergence controls and shows how to integrate the solver into existing code. Practical examples and comparisons demonstrate matched log‑likelihoods and parameters on shared datasets.
preview
MQL5 Trading Tools (Part 33): Building a Rich Content Markup Documentation System for MQL5 Programs

MQL5 Trading Tools (Part 33): Building a Rich Content Markup Documentation System for MQL5 Programs

We extend the Part 9 setup wizard to build a canvas-based, in-chart documentation system for MetaTrader 5. The panel is tabbed and scrollable, supports inline styling, images, and interactive controls, and renders with supersampled anti-aliasing. The result is a reusable engine that any MQL5 program can embed to deliver self-contained documentation directly on the chart.
preview
Beyond the Clock (Part 2): Building Runs Bars in MQL5

Beyond the Clock (Part 2): Building Runs Bars in MQL5

We implement tick-, volume-, and dollar-runs bars in Python and MQL5 and align them with the existing bar‑building framework. The article details the dual‑accumulator update, offline calibration with per‑side seeds, state persistence for EAs, and parity verification to match Python and MQL5 outputs. Runs bars expose one‑sided bursts that net imbalance can hide, improving coverage during quiet sessions and for mean‑reversion models.
preview
Application of the Grey Model in Technical Analysis of Financial Time Series

Application of the Grey Model in Technical Analysis of Financial Time Series

This article explores the grey model, a promising tool that can expand trader's capabilities. We will look at some options for applying this model to technical analysis and building trading strategies.
preview
Keeping Memory Across Restarts: EA State Persistence Using Binary Files in MQL5

Keeping Memory Across Restarts: EA State Persistence Using Binary Files in MQL5

This article provides a structured MQL5 framework for serializing an Expert Advisor's internal state into local binary files. It prevents data resets during platform restarts by safely storing volatile tracking metrics, such as trade counts and multipliers, directly to disk. This architecture offers a more robust state continuity alternative to terminal Global Variables.
preview
Detecting and Classifying Fractal Patterns Using Machine Learning

Detecting and Classifying Fractal Patterns Using Machine Learning

In this article, we will touch upon the intriguing topic of fractal analysis and market forecasting using machine learning. These are just the first steps towards exploring the diverse fractal structures that form on financial price charts. We will use the correlation to find patterns and the CatBoost algorithm to classify these patterns.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 1): Persistent Trade State Architecture

Engineering a Self-Healing Expert Advisor in MQL5 (Part 1): Persistent Trade State Architecture

This article demonstrates how to build the persistence foundation of a self-healing Expert Advisor in MQL5 using SQLite. Readers will learn how to create a permanent trade-state storage layer capable of surviving terminal restarts, shutdowns, and unexpected interruptions. The article covers SQLite integration in MetaTrader 5, database lifecycle management, persistent trade-state structures, and runtime state recovery using practical MQL5 implementations.
preview
Joint Recurrence Quantification Analysis (JRQA) in MQL5: Detecting Simultaneous Recurrence in Two Series

Joint Recurrence Quantification Analysis (JRQA) in MQL5: Detecting Simultaneous Recurrence in Two Series

We extend the RQA library for MetaTrader 5 with JRQA, which detects when two series simultaneously revisit their own past states. The article covers the joint recurrence matrix, twelve JRQA metrics (including TREND and COMPLEXITY), dual-epsilon configuration, and a rolling-window engine with OpenCL acceleration and automatic CPU fallback. A practical indicator plots JRR, JDET, JLAM, JENTR, and JTREND for any symbol pair with timestamp alignment and normalization.
preview
Meta-Labeling the Classics (Part 1): Filtering and Sizing RSI Trades

Meta-Labeling the Classics (Part 1): Filtering and Sizing RSI Trades

RSI accumulates losses in trending conditions by firing at every threshold crossing regardless of market regime. A Random Forest secondary classifier trained on 12 contextual features — RSI momentum slope, EMA50 trend velocity, ATR-normalised trend stretch, and nine others — filters raw signals and scales position size by classifier confidence on EURUSD H1. Results compare plain RSI, meta-filtered RSI, and bet-sized RSI across a 16-month out-of-sample period with per-trade metrics and drawdown diagnostics.
preview
Covariance Matrix Adaptation Evolution Strategy (CMA-ES)

Covariance Matrix Adaptation Evolution Strategy (CMA-ES)

The article explores one of the most interesting non-gradient optimization algorithms, which learns to understand the geometry of the objective function. We will focus on the classical implementation of CMA-ES with a slight modification - replacing the normal distribution with the power one. We will thoroughly examine the math behind the algorithm, as well as practical implementation, and check where CMA-ES is unbeatable and where it should be avoided.
preview
Building a Dynamic STF Liquidity Sweep Indicator in MQL5

Building a Dynamic STF Liquidity Sweep Indicator in MQL5

The article delivers a dynamic MetaTrader 5 indicator that detects liquidity sweeps via swing‑point logic, wick‑ratio thresholds, and engulfing confirmation. It recognizes single‑wick and dual‑candle patterns without a fixed window, updates buy‑/sell‑side targets as price evolves, and invalidates broken levels to maintain a reliable liquidity map.
preview
Integrating AI into 3 Smart Money Concepts (SMC): OB, BOS, and FVG

Integrating AI into 3 Smart Money Concepts (SMC): OB, BOS, and FVG

This guide integrates a trained XGBoost model (ONNX) into an SMC EA to evaluate trade setups before execution. The Python pipeline labels historical XAUUSD events and produces a 12-feature representation aligned with the EA. The result is a reproducible method to train, export, and embed the model so the EA can filter OB, FVG, and BOS signals programmatically.