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 a Modular Pre-Trade Execution Filter Engine in MQL5

Building a Modular Pre-Trade Execution Filter Engine in MQL5

The article presents a modular pre-trade execution filter for MQL5 as an object-oriented include class. It validates quote freshness, aligns order filling with broker capabilities, applies a rollover freeze window, and detects spread outliers using rolling statistics with a hard cap. An on-chart diagnostic indicator and an EA template with reproducible telemetry show integration and help reduce execution frictions in live trading.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 11): A Real Stroke Engine

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 11): A Real Stroke Engine

The engine learns to draw lines by stroking arbitrary paths with width, cap and join styles, miter limiting, and dashes. The stroker outputs overlapping geometry that the non-zero rule welds during fill, so no new raster code is required. In practice, you can render solid or dashed outlines with predictable caps and joins for chart series, widgets, and other UI shapes.
preview
Building a Daily OHLCV Aggregator from M1 Bars in MQL5

Building a Daily OHLCV Aggregator from M1 Bars in MQL5

Create session-aligned daily candles from M1 data by choosing the session close hour. A dedicated shift–truncate–restore day-key function prevents off-by-one errors at rollover and is easy to unit test. The script groups and aggregates M1 bars, writes a custom symbol for standard D1 charting, and reports results in the Experts tab, backed by synthetic tests.
preview
The Brunner-Munzel Test for MQL5: Comparing Trade Outcomes When the Variances Don't Agree

The Brunner-Munzel Test for MQL5: Comparing Trade Outcomes When the Variances Don't Agree

Mann–Whitney's usual normal-approximation reading relies on equal shape and variance, which trade outcomes often violate. We implement the Brunner–Munzel test natively in MQL5, validate it against SciPy, and quantify Mann–Whitney's type‑I mis-sizing under unequal variance. The test is integrated as a one‑sided regime gate inside a Donchian breakout EA with rolling logs, giving you a variance‑robust filter for live comparisons.
preview
Dirichlet Process Mixtures: How Many Market Regimes Are There, and Does the Answer Mean Anything?

Dirichlet Process Mixtures: How Many Market Regimes Are There, and Does the Answer Mean Anything?

Most regime tools ask for a fixed number of states. This article implements a Dirichlet process mixture for MQL5 with truncated stick-breaking and varying coordinate ascent, so the cluster count is inferred from data and the evidence bound is monitored each iteration. The package includes a nine-file library, an out-of-sample indicator that scores each bar, a six-level test suite, and a shuffle-based null control to judge how much the recovered count means.
preview
Self-Optimizing Expert Advisors in MQL5 (Part 21): Wavelet Denoising With Time-Lagged Independent Component Analysis (4)

Self-Optimizing Expert Advisors in MQL5 (Part 21): Wavelet Denoising With Time-Lagged Independent Component Analysis (4)

This article refines a multilayer market‑noise filter by sanitizing moving‑average inputs via Discrete Wavelet Transform and constructing a FastICA manifold on the denoised signals. We expand lag horizons (10–80 days), calibrate spectral clusters, and replace non-ONNX steps with surrogate models for MT5 deployment. The result is a reproducible MQL5 workflow that reduces forecasting error and integrates directly into an Expert Advisor.
preview
Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (ADM Module)

Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (ADM Module)

The article presents an implementation of the Adaptive Density Module (ADM), a key component of the EEMFlow framework, using MQL5. It examines the steps involved in building and combining the MDC and MDS submodules, as well as integrating ADM into the existing BAT trading model. Backtesting results on historical EURUSD data show robust growth in the account balance, controlled drawdowns, and a highly stable equity curve.
preview
Counting Breaches Is Not Backtesting: Six Tests for a Loss Limit

Counting Breaches Is Not Backtesting: Six Tests for a Loss Limit

We present a dependency-free MQL5 library that tests risk limits instead of simply using them. It grades any loss limit with six coverage tests, validates the battery on synthetic data, compares four standard forecasters on EURUSD daily history, and feeds the verdict back into position sizing.
preview
Native MQL5 to ClickHouse Integration via HTTP Interface and RowBinary

Native MQL5 to ClickHouse Integration via HTTP Interface and RowBinary

We implement a direct MT5→ClickHouse pipeline without intermediate services: RowBinary encoding at the byte level and an HTTP client that authenticates and posts inserts. The article details schema and field mapping, VarUInt and Float64 encoding, Nullable rules, and why POST is required for inserts and DDL. An EA streams live ticks and deals, and scripts verify round‑trip correctness and perform historical backfill, enabling consistent storage for downstream queries.
preview
Account-Wide Position Sizing in MQL5: Capping Each New Trade by the Risk Already Open

Account-Wide Position Sizing in MQL5: Capping Each New Trade by the Risk Already Open

When an EA trades several symbols, each new lot size must account for the risk already open. CRiskBudget returns the largest volume that five caps allow: risk per trade, open risk budget, free margin share, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_LIMIT, and it names the cap that decided. Unit tests, a tester EA, and a Python consistency check cover these decisions. In the tested runs, the budget did not reduce drawdown.
preview
Apache Arrow Flight from MQL5: A Native gRPC Client for Columnar Data Transport

Apache Arrow Flight from MQL5: A Native gRPC Client for Columnar Data Transport

This article implements a native Apache Arrow Flight client in pure MQL5: FlatBuffers-based Arrow IPC encoding/decoding, a raw HTTP/2 client with HPACK, and a thin gRPC/Flight framing layer, no external libraries. We detail the protocol stack, message formats, and the DoPut/DoGet/ListFlights calls, and verify interoperability against a live pyarrow server with round-trip checks and fault injection. You get a schema-carrying, columnar path out of MetaTrader 5 that is smaller than CSV and ready for Python/Arrow workflows.
preview
Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (MDC Module)

Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (MDC Module)

Here is an implementation of the key components of the EEMFlow framework using MQL5. The article demonstrates how multi-scale event processing, spiking FAM modules, and adaptive feature fusion in MDC form a structured representation that is adapted to market density. This enables the strategy to effectively identify significant signals, combine micro-impulses with broader trends, and improve the accuracy of forecasts, providing traders with a reliable tool for analysis and decision-making.
preview
Constructing Renko Bars from MQL5 Tick Streams in Real Time

Constructing Renko Bars from MQL5 Tick Streams in Real Time

We build a Renko aggregator that operates on the raw tick stream from OnTick, not M1 OHLC, to preserve the true crossing order. The engine writes each completed brick to a MetaTrader custom symbol, enabling standard indicators on the output chart. Continuation, reversal, and gap scenarios are covered and validated with a compact test script.
preview
Bland-Altman Analysis for MQL5: Agreement Between Strategy Tester Modes (Real Ticks vs 1 Minute OHLC).

Bland-Altman Analysis for MQL5: Agreement Between Strategy Tester Modes (Real Ticks vs 1 Minute OHLC).

The article builds a full MQL5 workflow for Bland-Altman agreement analysis between two Strategy Tester execution modes (real-tick vs 1-minute OHLC). A logging EA produces paired trades, a statistics core calculates bias, SD, 95% limits of agreement, confidence bands and proportional bias, and a dashboard reports the verdict. You get a concrete measure of execution-model sensitivity instead of relying on win rate alone.
preview
Implementing a DST-aware Trading Day Resolver in MQL5

Implementing a DST-aware Trading Day Resolver in MQL5

With CTradingDay, an EA can reset its daily loss limit at the time its rule names, such as the New York close, not at the end of the broker's feed. CServerClockFit finds the server time zone and its DST rule from hourly bars. On the tested server, the New York close falls one hour before server midnight between the US and EU clock changes. Unit tests and tester runs check these clock times for that server only.
preview
Building an ATR-Based Indicator for Potential Support and Resistance in MQL5

Building an ATR-Based Indicator for Potential Support and Resistance in MQL5

An adaptive MQL5 indicator builds potential support and resistance areas in advance using a smoothed ATR. It centers a volatility-based range on each bar's midpoint, draws upper and lower boundaries with midpoints, and visualizes zones and levels. The code detects boundary breaks, bullish/bearish midpoint conditions, and returns inside the range, and plots colored zones, horizontal lines, circles, triangles, and optional X markers.
preview
Volatility Sizing Under Controlled Stress in MQL5 (Part 1): From Known Variance to Auditable Position Sizes

Volatility Sizing Under Controlled Stress in MQL5 (Part 1): From Known Variance to Auditable Position Sizes

We provide a controlled MQL5 test that sizes exposure from variance, applies a cap, and checks the implied next-bar standard deviation against a 0.75% target. Rolling-20 and EWMA-0.94 are audited against a fixed-exposure control using a generator with known next-bar variance. All sizing requests, caps, and conditional-risk deviations are recorded to CSV for detailed review.
preview
Practical Modules from Other Languages in MQL5 (Part 10): The configparser module from Python

Practical Modules from Other Languages in MQL5 (Part 10): The configparser module from Python

Configuration is an essential part of almost every software application. Instead of hardcoding settings directly into the source code, developers can store them in configuration files, making programs easier to customize, maintain, and reuse. In this article, we will see how INI files work and implement an MQL5-friendly interface for reading, accessing, modifying, and writing configuration data similarly to Python's builtin module called configparser.
preview
Aggregating Multi-Broker Tick Feeds into a Synthetic Mid-Price in MQL5

Aggregating Multi-Broker Tick Feeds into a Synthetic Mid-Price in MQL5

This article shows how to aggregate quotes from multiple brokers in MQL5 via a simple file‑based bridge. Publisher EAs write bid, ask, and volume per tick; a timer-driven master EA validates inputs, excludes stale feeds, and produces a volume-weighted synthetic mid-price. The EA publishes the series to a custom symbol you can chart and test; the design was exercised on three broker demo accounts.
preview
Embedding a WebSocket Server in an MQL5 Expert Advisor: Live Push to Browsers and Scripts Without a Middleman

Embedding a WebSocket Server in an MQL5 Expert Advisor: Live Push to Browsers and Scripts Without a Middleman

We build a WebSocket server inside an MQL5 Expert Advisor to stream ticks, positions and deal events to a browser or a Python client in real time. The article implements RFC 6455 (handshake, framing, masking and ping/pong) in pure MQL5 with Winsock, drives non-blocking sockets from a timer, wires the server into OnTick/OnTimer/OnTradeTransaction, and measures latency, throughput and trading overhead.
preview
Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (EEMFlow)

Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (EEMFlow)

The article provides an overview of the architecture of the EEMFlow framework, which is designed to work with event streams. Particular attention is paid to adaptive and multi-level modules, which enable flexible handling of both global and local changes. The framework's architecture preserves key information, minimizes the impact of noise, and efficiently generates features for further analysis, making EEMFlow a promising tool for forecasting financial market dynamics.
preview
Does the Terminal Run the Model You Trained? ONNX Contract and Golden-File Checks in MQL5

Does the Terminal Run the Model You Trained? ONNX Contract and Golden-File Checks in MQL5

An EA can detect a wrong ONNX model in OnInit, before its first prediction, instead of failing or returning other probabilities in OnTick. COnnxContract checks the model's signature, features, class labels, and SHA-256 hash against a contract file. COnnxParity compares the terminal's probabilities with onnxruntime on a golden file of reference rows, and a Python tool builds both files from your data. The tool also audits the EA's prediction log, because a golden pass covers only its own rows.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 10): Transforms and the Graphics Context

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 10): Transforms and the Graphics Context

We add the missing pieces: an affine transform and a context layer for the Cairo-style engine in MQL5. The six-number matrix is applied as paths are built, turning user coordinates into pixels and enabling reusable widgets by translation, scale, and rotation. CCairoContext stores transform, clip, source, and fill rule, with Save/Restore to manage state safely.
preview
Change Point Detection for Financial Time Series in MQL5

Change Point Detection for Financial Time Series in MQL5

Financial markets can shift between regimes, so detecting when the statistical behavior of returns changes is valuable for analysis. An MQL5 change point detector segments historical returns into periods with different mean and volatility using optimal partitioning with PELT pruning and a BIC-style default penalty. A sensitivity scan tests robustness by showing which detected breaks persist as settings vary.
preview
Building a Volume Profile Aggregator from Tick Data in MQL5

Building a Volume Profile Aggregator from Tick Data in MQL5

The article presents an MQL5 volume profile built with O(1)-per-tick binning, replacing O(n×m) nested comparisons by direct index arithmetic on a preallocated, tick-size-aligned bin grid. An EA-driven pipeline resolves the session, loads ticks with retries and pre-sizing, aggregates, computes POC/VA, and renders bars in the chart's right margin. A test script verifies arithmetic on controlled datasets.
preview
Dead-Man's Switch for MetaTrader 5: An EA Heartbeat That Reports Health, and a Guardian That Acts When It Goes Silent

Dead-Man's Switch for MetaTrader 5: An EA Heartbeat That Reports Health, and a Guardian That Acts When It Goes Silent

This article builds a dead man's switch for EAs: a host emits a timer-driven heartbeat with real health flags (connection, trading permissions, tick age, margin) to an external relay with its own clock. A guardian EA polls that relay and, once silence is confirmed, can alert, move stops to breakeven, or flatten positions by magic number.
preview
Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (Conclusion)

Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (Conclusion)

The BAT framework transforms a chaotic stream of market data into accurate forecasts and well-informed trading decisions. Backtesting shows steady capital growth with controlled risks. The model's architecture is simple, scalable, and ready for further optimization.
preview
Native SFTP Client in MQL5: Uploading Trade Reports over SSH Without External Tools

Native SFTP Client in MQL5: Uploading Trade Reports over SSH Without External Tools

Send MetaTrader 5 trade reports to an SFTP server without WinSCP or external scripts. A pure-MQL5 SSH/SFTP client uses host-key pinning, safe packet handling and a temporary “.part” swap to avoid partial files, while an EA writes daily CSV reports and a service uploads them. The article also explains a Strategy Tester case where the final closing deal misses OnTradeTransaction and how to capture it
preview
How Far Away Is the Stop-Out? A Stop-Out Threshold Finder and Pre-Trade Guard in MQL5

How Far Away Is the Stop-Out? A Stop-Out Threshold Finder and Pre-Trade Guard in MQL5

CStopOutGuard shows how far a symbol's price can move before the modeled margin level reaches stop-out, and how much closer a planned order would bring that threshold. Positions are valued with OrderCalcProfit() and OrderCalcMargin() at each tested price instead of a fixed tick value, so volume margin tiers are included. Unit tests, test EAs, and a Python consistency check cover the search. The model keeps the spread and swaps at their current values, and CanAdd() does not replace OrderCheck().
preview
Building a Dynamic Drop List in MQL5

Building a Dynamic Drop List in MQL5

This article describes CDropList, a composite class that implements an interactive drop-down list from standard MQL5 chart objects. It details creation/destruction, coordinates and sizes, color configuration, item management, and a Refresh method that keeps objects in sync. Event handling covers opening/closing, hover highlight, item clicks, and scrolling, helping you embed consistent selection controls in indicators, dashboards, and trading panels.
preview
Developing Smart Chart Objects in MQL5 (Part 3): Integrating Lifecycle Alerts into Managed Trendlines

Developing Smart Chart Objects in MQL5 (Part 3): Integrating Lifecycle Alerts into Managed Trendlines

This article adds a lifecycle-driven alert layer to the Smart Trendline Manager. Alerts originate from state transitions (touch, bounce, break, resurrection), pass configurable event and source filters, and are delivered via terminal popups and push notifications. You will see how to wire the alert engine through the manager, configure inputs in the indicator, and receive timely notifications without constant chart monitoring.
preview
How to Develop a Multi-Currency Expert Advisor with the AI Assistant in MetaTrader 5

How to Develop a Multi-Currency Expert Advisor with the AI Assistant in MetaTrader 5

Building a multi-symbol Expert Advisor — one that also trades using different strategies — is a real challenge even for an algorithmic trader with many years of experience. But with the introduction of a full-fledged built-in AI Assistant in the MetaTrader 5 terminal, this is now within the reach of developers of any skill level. You do not even need to be an expert in math or risk management — the language model will explain everything to you in the chat and write all the code for you.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 9):  Clipping, Bounds and Hit Testing

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 9): Clipping, Bounds and Hit Testing

This article extends a Cairo-style vector engine in MQL5 with anti-aliased clipping. We build rectangular and path-based clipping regions, combine their coverage in the rasterizer, and discuss the limitations of mask multiplication. We also implement path bounds and point containment for sizing masks and testing interface interactions.
preview
Modular Indicator Architecture in MQL5 (Part 2): Standard Smoothing Methods as Interchangeable Modules

Modular Indicator Architecture in MQL5 (Part 2): Standard Smoothing Methods as Interchangeable Modules

EMA, SMMA, and LWMA join SMA as modules of the indicator framework from Part 1, all four derived from a new base class, CSmoothingBase. The root object, CIndicator, dynamically creates the module of the chosen smoothing method and works with it through a base-class pointer. Besides the code, the article explains the smoothing methods themselves, with formulas and worked examples, and compares the four: how they weight the bars, what they need to start, and what their calculation costs.
preview
Association Rules and Probability Theory in Forex: A Signal Filter Without Neural Networks or Magic

Association Rules and Probability Theory in Forex: A Signal Filter Without Neural Networks or Magic

We explore an alternative to neural network signal filters: association rules and basic probability theory in MQL5, without Python or external libraries. This guide demonstrates how to discretize market conditions (RSI, EMA, ATR, momentum, session), compile statistics on support, confidence, lift, and edge using Laplace smoothing, and apply the result as a transparent entry filter before placing a trade.
preview
Pesaran–Timmermann Test in MQL5: Separating Real Directional Skill from a Lucky Hit Rate

Pesaran–Timmermann Test in MQL5: Separating Real Directional Skill from a Lucky Hit Rate

This article implements the Pesaran–Timmermann directional accuracy test in pure MQL5 and applies its rolling right-tail p-value as a gate to enable or disable an Expert Advisor. Forecasts are scored without look-ahead, and the framework includes an EA, a rolling statistical display, and a self-test. The method is evaluated on XAUUSD, EURUSD and GBPUSD, with a coin-flip control to quantify false alarms.
preview
MQL5 Developer Gotchas (Part 1): A Parameter Mapper for Calling Indicators with Input Groups

MQL5 Developer Gotchas (Part 1): A Parameter Mapper for Calling Indicators with Input Groups

Group lines in a custom indicator take parameter slots in iCustom() and IndicatorCreate(), so numbers passed without placeholders silently shift to the wrong inputs. CIndicatorInputs reads the live slot layout, fills the group slots, rejects values the terminal would change, and verifies the handle on a chart, so an EA gets the requested settings or an error. In the Strategy Tester it builds the handle from a saved layout without verification. Unit tests and a tester EA show both modes.
preview
Building a Divergence System (Part VI): A Scoring Divergence Engine

Building a Divergence System (Part VI): A Scoring Divergence Engine

A reusable MQL5 divergence engine that stores all confirmed pivots, selects clean pivot pairs, and measures price extension in ATR, oscillator disagreement, and bar spacing into a 0–100 score. It logs named rejection reasons for filtered pairs and exposes per‑bar queries. Integration is reduced to four steps, and the score can drive an adaptive trailing system that scales its SAR step by divergence strength.
preview
Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (Main Components)

Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (Main Components)

We continue implementing the BAT framework in MQL5, showing how bidirectional correlation and the SATMA module enable the analysis of market dynamics in the context of the current state. Key architectural solutions that enable the framework to be adapted for financial data analysis are presented.
preview
Bacterial Evolutionary Algorithm (BEA)

Bacterial Evolutionary Algorithm (BEA)

The article focuses on the Nawa–Furuhashi Bacterial Evolutionary Algorithm (BEA) and its two key operators: segmental bacterial mutation for local optimization and horizontal gene transfer for the exchange of successful solution fragments. We implement BEA within the C_AO framework as a finite-state machine with a fixed evaluation budget, test it on Hilly, Forest, and Megacity, and explain the terminological distinction from the Numaoka model.