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 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.
preview
News Filtering with MetaTrader 5 Economic Calendar and CSV Fallback

News Filtering with MetaTrader 5 Economic Calendar and CSV Fallback

This article presents a self-contained news filter module for MetaTrader 5 built on the platform's economic calendar API. It implements symbol-to-currency mapping, pre- and post-event trading pauses, and optional position size reduction on high-impact days, with a CSV-based fallback for the Strategy Tester. A demo EA and live chart dashboard show integration and verification in both live and backtest environments.
preview
Building the Market Structure Sentinel Indicator in MQL5

Building the Market Structure Sentinel Indicator in MQL5

This article builds a Market Structure Sentinel indicator in MQL5 that detects and visualizes Smart Money Concepts (SMC) events, including Break of Structure (BOS) and Change of Character (CHOCH), in real time. It explains swing detection, structural validation, and trend classification, and adds a compact dashboard to track bullish, bearish, or ranging states for faster on‑chart interpretation.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 1): Building a Chart Object Detection Engine

How to Detect and Normalize Chart Objects in MQL5 (Part 1): Building a Chart Object Detection Engine

This article addresses the interpretative gap between visual chart objects and algorithmic execution. You will build a systematic detector that iterates over all chart objects, identifies analytical types, and normalises their geometric data (time and price coordinates) into a structured SChartObjectInfo array. The implementation uses raw MQL5 functions, a filter‑extract‑store pipeline, and a timer‑driven test EA, resulting in a reusable framework for rule‑based trading inputs.
preview
Building a Megaphone Pattern Indicator in MQL5

Building a Megaphone Pattern Indicator in MQL5

Build a megaphone pattern indicator in MQL5 that detects expanding structures on the chart. The article walks through swing identification and refinement, trend line validation, breakout confirmation, and SL/TP projection, with chart objects for lines, labels, and signals. As a result, you get a rule-based implementation that automates pattern detection and produces actionable levels directly in MetaTrader 5.
preview
Market Microstructure in MQL5: Estimating ARFIMA d with GPH (Part 3)

Market Microstructure in MQL5: Estimating ARFIMA d with GPH (Part 3)

A GPH‑based estimator for d, the key ARFIMA parameter, is added to MicroStructure_Foundation.mqh. GPHEstimator() computes d via log‑periodogram regression, while PopulateARFIMAAnalysis() stores d with an R² confidence score and validates the theoretical relationship H = d + 0.5. An empirical study on 72 US100 M1 sessions confirms pooled d = −0.006, consistent with the random walk boundary established in Part 2.
preview
An Introduction to the Study of Fractal Market Structures Using Machine Learning

An Introduction to the Study of Fractal Market Structures Using Machine Learning

The article attempts to examine financial time series from the perspective of self-similar fractal structures. Since we have too many analogies that confirm the possibility of considering market quotes as self-similar fractals, this allows us to think about the forecasting horizons of such structures.
preview
Trading with the MQL5 Economic Calendar (Part 12): SQLite Storage and Deduplication

Trading with the MQL5 Economic Calendar (Part 12): SQLite Storage and Deduplication

In this article, we replace the embedded CSV snapshot with a SQLite layer that persists calendar events and triggered trade IDs across restarts. The database lives in the common terminal folder and is shared by live charts and the strategy tester, so both modes read the same data without recompiling. An on-demand downloader with a canvas progress bar fetches history from the calendar API and stores it for offline reuse.
preview
Price Action Analysis Toolkit Development (Part 70): Turning Flag Pattern Signals into Automated Trade Execution

Price Action Analysis Toolkit Development (Part 70): Turning Flag Pattern Signals into Automated Trade Execution

The article defines a buffer-based signal architecture for flag breakouts and an EA that consumes it. Breakout arrows and pole height are written to dedicated buffers only after confirmation, preventing repainting and ambiguity. The EA polls buffers with CopyBuffer(), validates signals using configurable filters, and executes trades with fixed or dynamic SL/TP.
preview
Publish Your Article Code to MQL5 Algo Forge in 10 Minutes: A Step-by-Step Guide

Publish Your Article Code to MQL5 Algo Forge in 10 Minutes: A Step-by-Step Guide

The article provides a step-by-step guide on how to migrate code from a published project into a fully-fledged MQL5 Algo Forge project. You will set up the environment and authentication in MetaEditor, create a project in Shared Projects, select the type, arrange the files, add README.md, check the encoding and build, commit the changes to Git, and open the repository publicly. The article helps to build a working structure and preserve version history for the convenience of readers.
preview
MQL5 Wizard Techniques you should know (Part 91): Using Skip Lists and a Hopfield Network in a Custom Trailing Class

MQL5 Wizard Techniques you should know (Part 91): Using Skip Lists and a Hopfield Network in a Custom Trailing Class

For our next Exploration on notions that are testable with the MQL5 Wizard we examine if Skip Lists and the Hopfield Network can give us a profit-guarding trailing strategy. Trailing Stop Management, as already argued, can be overlooked in most trading systems at the expense of Entry Signals or even Money Management. Trailing stops can make all the difference in certain situations such as trending markets, and thus we test this out with GBP USD.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part IV): Remote voice trading

Overcoming Accessibility Problems in MQL5 Trading Tools (Part IV): Remote voice trading

Learn a practical way to execute MetaTrader 5 trades from Telegram voice notes using a Python middleware and an MQL5 EA acting as an HTTP client. The article covers architecture, WebRequest polling, in-memory queuing, JSON parsing with null-terminator stripping, and a constrained command grammar with a 0.001-lot default. You will configure the environment and validate round‑trip latency suitable for mobile data connections.
preview
Trading with the MQL5 Economic Calendar (Part 11): Modular Canvas News Dashboard

Trading with the MQL5 Economic Calendar (Part 11): Modular Canvas News Dashboard

We rebuild the MQL5 Economic Calendar dashboard from a monolithic object-based panel into a modular canvas-based system split across four files. The update adds a dual light and dark theme, collapsible day groups, a resizable layout with pixel-based scrolling, revised value markers, and a live countdown with toast notifications. A candidate event cache and a fast-path timer that repaints only changed cells improve responsiveness and make the codebase easier to extend.
preview
Feature Engineering for ML (Part 4): Implementing Time Features in MQL5

Feature Engineering for ML (Part 4): Implementing Time Features in MQL5

Applying Python session boundaries to MQL5 broker timestamps misclassifies session membership by two to three hours on any non-UTC broker, corrupting session flags across the full backtest history. We implement CTimeFeatures.mqh, containing CRingBuffer and CTimeFeatures, with three EA-facing methods: Initialize (UTC offset capture and frequency gate configuration), Update (log return push to session-conditional ring buffers), and Calculate (cyclical encoding, session flags, and session volatility). The output is a flat double array drop-compatible with Python's get_time_features for sub-hourly, hourly, and daily timeframes.
preview
3D Visualization Without External Libraries: How MetaTrader 5 Reveals Optimization Results via MQL5 + DX11

3D Visualization Without External Libraries: How MetaTrader 5 Reveals Optimization Results via MQL5 + DX11

The article describes the practical application of DirectX 11 and built-in MQL5 tools for creating 3D visualizations and interactive interfaces in MetaTrader 5. The focus is on cognitive efficiency - the ability of 3D charts and guided scenes to help in understanding optimization data, liquidity clusters, and multi-dimensional trading scenarios. The basics of the DX pipeline, working with shaders, binding mouse and keyboard events, and objective technological limitations are discussed in detail. The article is intended for MQL5 developers and algorithmic traders who are ready to transform strategy metrics into understandable 3D analytical landscapes, where the visual layer accelerates decision-making.
preview
Engineering Trading Discipline into Code (Part 6): Building a Unified Discipline Framework in MQL5

Engineering Trading Discipline into Code (Part 6): Building a Unified Discipline Framework in MQL5

The article introduces a unified MQL5 discipline framework that consolidates the symbol whitelist, trading‑hours and news filters, and daily trade‑limit modules under CDisciplineEngine.mqh. It explains centralized trade validation and state synchronization shared by a chart dashboard and an enforcement Expert Advisor. Readers learn how to authorize orders through a single gate, monitor permissions in real time, and automatically enforce rules across the terminal.
preview
Market Microstructure in MQL5: Measuring long memory in MQL5 with Hurst estimators (Part 2)

Market Microstructure in MQL5: Measuring long memory in MQL5 with Hurst estimators (Part 2)

Part 2 focuses on practical long-memory detection for intraday data. Three complementary Hurst estimators are implemented and combined into a confidence‑weighted composite, with confidence tied to valid regression scales. The final H and confidence populate the shared analysis struct, enabling indicators to act only when H departs from the neutral 0.40–0.60 band and to select trend‑following above 0.60 or mean‑reversion below 0.40.
preview
Building a Trade Analytics System (Part 4): Summary Metrics and Dashboard

Building a Trade Analytics System (Part 4): Summary Metrics and Dashboard

This article extends the existing Flask backend to compute performance analytics from stored MetaTrader 5 closed trades and deliver them as both JSON and a simple web view. It calculates total trades, total profit, win rate, average profit, and trade duration metrics, returning JSON at /api/v1/analytics/summary and rendering a dashboard at /api/v1. The result provides a quick, consistent way to review trading performance from persisted SQLite records.
preview
Evaluating the Quality of Forex Spread Trading Based on Seasonal Factors in MetaTrader 5

Evaluating the Quality of Forex Spread Trading Based on Seasonal Factors in MetaTrader 5

The article examines the quality of a seasonal trading approach on a daily timeframe, both for individual symbols and for spreads. Particular attention is paid to identifying recurring monthly cycles and the possibilities of their application in trading within the current year.
preview
From "Best Pass" to Robust Solutions: Exploring the Optimization Surface in MetaTrader 5

From "Best Pass" to Robust Solutions: Exploring the Optimization Surface in MetaTrader 5

The article examines an engineering approach to optimizing an Expert Advisor in MetaTrader 5: from collecting custom metrics through Optimization Frames to parameter surface analysis. A simple event-driven EMA/RSI model demonstrates CSV export, smoothing, and local stability assessment in Python. The goal is to find stable areas of configurations and validate them with forward optimization for reliable implementation.