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
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
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
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
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
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
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
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
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
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
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
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
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 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
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
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
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
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
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
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
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
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
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
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
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
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.