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 Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer

Building a Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer

An MQL5 prop-firm guard must evaluate account rules before it acts and verify that protective actions have completed. This article examines eight rules, two-phase directive resolution, position closing, Algo Trading state checks and restart recovery. A demo and synthetic tests show how to use the guard and verify its rule logic.
preview
The MQL5 Standard Library Explorer (Part 19): Developing a Reusable Portfolio Risk Manager

The MQL5 Standard Library Explorer (Part 19): Developing a Reusable Portfolio Risk Manager

This article explores CAccountInfo through a shared risk authority for a multi-symbol Expert Advisor. We model requests, decisions, and reservations, then apply portfolio, symbol, position, direction, and margin checks before submitting trades. The example also explains the limits of its reservation and execution handling.
preview
Automating Chart Patterns in MQL5 (Part 4): The Flag and Pennant

Automating Chart Patterns in MQL5 (Part 4): The Flag and Pennant

This article implements a flag and pennant detector in MQL5 using swing-structure data from a higher timeframe. The pole is validated by ATR-based height and a maximum bar duration, and the subsequent consolidation is replayed bar by bar on the chart timeframe with limits on minimum length, lifetime, and retracement. A three-state machine trades a fresh breakout once and projects a measured-move target from the pole's height.
preview
Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown

Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown

We show how to attribute realized portfolio drawdown to individual configurations inside MetaTrader 5. Using daily results grouped by magic (optionally magic and symbol), the tool rebuilds the portfolio curve and quantifies three contributions: leave-one-out drawdown, shares of the deepest drawdown episodes, and Euler variance share. Flags are checked for stability across sample halves and rolled up into a heuristic A+–F score for practical diagnostics.
preview
Interactive Supply and Demand Zone Manager in MQL5 (Part VI): Dual-Timeframe Zone Detection and Lifecycle Management

Interactive Supply and Demand Zone Manager in MQL5 (Part VI): Dual-Timeframe Zone Detection and Lifecycle Management

This installation implements source‑aware processing: select a lower source or a lower/higher pair, then run detection and lifecycle per source with dedicated ATR, history checks, and bar stamps. Zones store their source timeframe for logging and snapshot persistence, and only that source's chart displays and permits edits. The result is predictable chart switching, reproducible restoration, and clearer separation of signals across timeframes.
preview
Connecting MQL5 to Apache Cassandra: A Native CQL Binary Protocol (v4) Client for Tick-Level Feature Archival

Connecting MQL5 to Apache Cassandra: A Native CQL Binary Protocol (v4) Client for Tick-Level Feature Archival

This article builds a driverless MQL5 client for Cassandra's CQL binary protocol v4 using outbound TCP sockets. It explains frame headers and primitives, SASL PLAIN, prepared statements, and UNLOGGED batches, then demonstrates an EA that writes per‑tick feature vectors with batched throughput and a reconnect‑and‑retry flush path verified on a real node.
preview
Aggregating Order Flow Delta from Tick Data in MQL5

Aggregating Order Flow Delta from Tick Data in MQL5

Compute and visualize order flow delta in MQL5 from raw ticks, either per bar or cumulatively. The implementation applies the tick rule, threads state through bars, and annotates price–cumulative delta divergences closed on bars. Pure classes isolate logic for testing, and a synthetic tick script confirms behavior, improving robustness and clarity of the output.
preview
MQL5 Developer Gotchas (Part 2): A Multi-Line Text Block for Chart Labels Beyond the 63-Character Limit

MQL5 Developer Gotchas (Part 2): A Multi-Line Text Block for Chart Labels Beyond the 63-Character Limit

CLabelBlock lets an EA show a long text as labels wrapped by pixel width and detect a truncated label. On the tested builds, native text objects and object names keep only the first 63 UTF-16 code units without an error. CCanvasBlock draws wider lines on one bitmap without that cap but cannot read its text back. Unit tests and screenshot checks cover one system and a few fonts.
preview
Reading Parquet Natively in MQL5: Thrift, Snappy and Dictionary Decoding into matrix Without CSV

Reading Parquet Natively in MQL5: Thrift, Snappy and Dictionary Decoding into matrix Without CSV

This article shows how to read Apache Parquet files directly in MQL5 without DLLs: a native Thrift Compact Protocol decoder for footer metadata, a native Snappy block decompressor, and a hybrid RLE/bit‑packing decoder for definition levels and dictionary indices. We assemble numeric columns into a matrix with an optional null mask. Scope: flat schemas, INT32/INT64/FLOAT/DOUBLE, UNCOMPRESSED/SNAPPY, DataPageV1, first row group. The result avoids CSV conversions and preserves nulls and types.
preview
Building Your Own Expert Advisor (Part 8): ATR and R-Multiple Trailing Stops

Building Your Own Expert Advisor (Part 8): ATR and R-Multiple Trailing Stops

We add TrailingStop.mqh: a trailing engine plus pluggable methods for the Series EA. Each method proposes a level; the engine decides if and when to send it, enforcing protective direction, minimum step, stops level and freeze level. Included methods are ATR trailing and an R‑multiple ladder, with optional break‑even as a floor. The result is per‑tick, safer stop management under broker constraints.
preview
Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (CDC Module)

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

The article presents an interim stage in the implementation of the EEMFlow framework using MQL5. The focus is on the design and integration of a CDC module that includes a Self-Corrector, a Self-Attention mechanism for the corrected flow, and weighted signal aggregation via a confidence mask. The article examines architectural principles, the sequence of forward and backward passes, and the specifics of working with local and global motion features.
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().