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
Auditing an Expert Advisor From Its Trade History (Part 1): Rebuilding Positions From Deals

Auditing an Expert Advisor From Its Trade History (Part 1): Rebuilding Positions From Deals

This article introduces TradeAudit, an MQL5 include library that rebuilds closed trades from raw deal history to produce one consistent record per trade. It handles partial closes, scale-ins on netting accounts, netting reversals, close-by pairs, and positions spanning the date range. A script exports the records to CSV, and a self-test script runs synthetic netting and close-by sequences. The result is a clean per-trade dataset for reliable EA statistics and verification.
preview
Backtesting Indicator Signals in MQL5 Using Buffers and Chart Objects

Backtesting Indicator Signals in MQL5 Using Buffers and Chart Objects

The EA evaluates indicator signals from buffers or dated chart objects on historical closed bars, keeping execution separate from account reports. It models virtual positions with user-defined entry timing, stop loss, staged targets, partial exits, break-even, and optional reversal on opposite signals, and renders exit paths and statistics on the chart. EURUSD examples compare SMA buffer/object sources and test confirmed RSI divergence, illustrating a practical way to judge signals before building a dedicated EA.
preview
Automatic Differentiation: Exact Gradients Without a Step Size

Automatic Differentiation: Exact Gradients Without a Step Size

We implement a compact automatic differentiation library for MQL5 in forward and reverse modes and use it to supply exact Jacobians to ALGLIB's Levenberg–Marquardt solver. The article details dual numbers, a tape with local partials, validation against closed forms and jax, and timing versus finite differences. You will learn when forward mode fills least‑squares Jacobians faster, where finite differences still win at small parameter counts, and how AD behaves on real price data.
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
From Basic to Intermediate: Objects and Subwindows (I)

From Basic to Intermediate: Objects and Subwindows (I)

This article provides a detailed look at creating and positioning the OBJ_CHART object in subwindows, with a particular focus on the differences between the main window and the subwindows. It shows how to integrate indicators using resources (#resource, ChartIndicatorAdd) and identify the desired subwindow by the indicator short name. As a result, the code becomes more stable, portable, and reusable.
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
Implementing a Zone-Aware Rollover Window Gate in MQL5

Implementing a Zone-Aware Rollover Window Gate in MQL5

CTradeWindows blocks EA entries during the daily rollover spread spike. Each window is a clock time in a zone such as New York, so it follows that zone through DST. CSpreadProfile learns the windows from tick spreads and saves them to a file that an EA can load. Unit tests and Strategy Tester runs on one server show that a window fixed in server time misses the spike in weeks when the US and EU DST dates differ.
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
Using the MQL5 Economic Calendar for News Filter (Part 6): A Filter an EA Can Hold Two Of

Using the MQL5 Economic Calendar for News Filter (Part 6): A Filter an EA Can Hold Two Of

This article describes refactoring an EA‑scoped news filter into a reusable MQL5 class. Inputs move into a configuration struct, while events, currency mapping, saved stops, a suspension flag, and a private CTrade object become per‑instance state. The class lets one EA run multiple filters with different thresholds and responses, share one rule table, and reduce duplicated code while keeping each filter independently configurable.
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
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
Multi-Timeframe Bar Aggregator with Conflict Detection in MQL5

Multi-Timeframe Bar Aggregator with Conflict Detection in MQL5

We implement a multi‑timeframe aggregator that prevents mixing bars from different moments. It validates grid alignment, recency to the forming base bar, and closed‑bar end times, and returns either a complete bundle or a structured error. A re‑read guards against races with a new base bar, while a fake bar source powers fifteen reproducible tests and a demo indicator that plots on valid data only.
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
A Thin gRPC Inference Client: Serving a Live Python Model to MetaTrader 5 Without ONNX

A Thin gRPC Inference Client: Serving a Live Python Model to MetaTrader 5 Without ONNX

Learn how to connect a LightGBM pipeline with a custom feature transformer to an MQL5 Expert Advisor without converting it to ONNX. The article covers the gRPC service, REST gateway, WebRequest() client, signal and risk logic, and probability indicator. An offline replay approximates the EA’s decisions and compares confidence thresholds across in-sample and out-of-sample data, since WebRequest() fails in the Strategy Tester.
preview
Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Difference Block)

Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Difference Block)

The article presents a practical implementation of the EDCFlow framework's approaches, with a focus on the Multi-Scale Difference module. It demonstrates how sequential feature compression, the computation of differences across multiple scales, and adaptive multiscale attention enable the formation of a structured and informative representation of streaming data.
preview
Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color

Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color

The article turns drawing primitives into PDF output: one cm flip installs a top‑left, y‑down system, while CPdfPage writes m/l/c/h/re, S/f/B, W n, and transforms from calls on CPdfSurface. PdfColor keeps RGB bytes and fixes MQL5 byte order when writing fractions. It also covers caps, joins, dashes, clipping, and Bezier circles. Demos include a printable ruler, a feature sampler, and a ready letterhead script.
preview
Aggregating Economic Calendar Events into a Structured MQL5 Data Feed

Aggregating Economic Calendar Events into a Structured MQL5 Data Feed

The package builds a news feed from CalendarValueHistory(): it filters by impact and currency, maps events to a symbol universe, and stores them in a time‑sorted array with minutes to event. You can query GetNextEvent() and IsInNewsWindow() to implement deterministic news filtering in an EA. An abstract source and clock, plus terminal and fake implementations, enable testing when calendar functions are unavailable in the Strategy Tester.
preview
Native Apache Cassandra Client in MQL5: Writing Trade and Market Data via the CQL Binary Protocol

Native Apache Cassandra Client in MQL5: Writing Trade and Market Data via the CQL Binary Protocol

This article shows how to build a native Cassandra CQL v4 client in MQL5 over a raw socket, without a REST or gRPC proxy. It details CQL frame encoding, correct handling of prepared-statement ids as short bytes, and a lot-sizing error found in the Strategy Tester, with targeted guards. You get a reusable client class, an EA that batches closed-trade inserts, and a script that reads rows back and cross-checks them with terminal history.
preview
Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Conclusion)

Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Conclusion)

The article provides a detailed analysis of the practical implementation of the EDCFlow framework's concepts using MQL5 and their validation using real historical data. It demonstrates how a neural network model forms an internal representation of the market environment, processes correlations among features, and makes trading decisions without hand-crafted rules. The test results reveal not only the approach's potential but also its weaknesses, honestly identifying its limitations and areas for further development.
preview
Implementing Golden-File Regression Tests for Expert Advisors in MQL5

Implementing Golden-File Regression Tests for Expert Advisors in MQL5

Golden-file testing compares the trade decisions of a modified Expert Advisor with an accepted run, so an unintended logic change appears as changed decisions. CDecisionRecorder writes each recorded request with run context and a tick hash, and CGfFile refuses truncated or malformed files. CGoldenCompare pairs rows by time and returns a verdict that separates changed decisions from different settings or ticks. Random execution delay made the tested runs differ, so compare runs with the same fixed delay or none.
preview
Building a Price Ladder Aggregator for Depth-of-Market Analysis in MQL5

Building a Price Ladder Aggregator for Depth-of-Market Analysis in MQL5

The article presents a live‑only MQL5 indicator that converts MarketBook data into a price ladder with tick‑based bucketing, per‑level aggregation, outward cumulative columns, and top‑3 cluster marking per side. A canvas panel renders the ladder, spread, and diagnostics, avoiding empty or misleading displays when DOM is missing. Logic is isolated in tested classes, providing a clear, reusable structure for DOM visualization.
preview
Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction

Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction

A rolling Wald–Wolfowitz runs-test engine classifies recent bar direction as persistent, alternating, or indistinguishable from noise before any entry logic is applied. The package includes full MQL5 source, a chart indicator, a three-mode Expert Advisor (Gated, No gate, Placebo), validation scripts, and an audit log. An 18‑run Strategy Tester matrix with fixed window and critical value, plus a null‑rate calibration on real history, shows how a regime gate changes trade frequency and drawdown.
preview
Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction

Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction

A rolling Wald–Wolfowitz runs-test engine classifies recent bar direction as persistent, alternating, or indistinguishable from noise before any entry logic is applied. The package includes full MQL5 source, a chart indicator, a three-mode Expert Advisor (Gated, No gate, Placebo), validation scripts, and an audit log. An 18‑run Strategy Tester matrix with fixed window and critical value, plus a null‑rate calibration on real history, shows how a regime gate changes trade frequency and drawdown.
preview
Beginner to Intermediate: Operator Overloading (I)

Beginner to Intermediate: Operator Overloading (I)

In this article, we will begin exploring how so-called operator overloading is implemented. First, we will take a look at the fundamentals of this implementation. In addition, we will see that things are not always as complicated as they seem.
preview
Volatility Sizing Under Controlled Stress in MQL5 (Part 2): Heavy Tails, Outliers, and Risk Recovery

Volatility Sizing Under Controlled Stress in MQL5 (Part 2): Heavy Tails, Outliers, and Risk Recovery

We study how additive, transient outliers affect volatility estimates and next‑bar sizing when the Part 1 rules remain fixed. Using standardized Student‑t returns and paired stress paths, we evaluate capped exposure under both base and complete‑return conditional risk. The article provides an MQL5 script and a CSV audit to reproduce decisions and verify results.
preview
Market Simulation: Position View (XX)

Market Simulation: Position View (XX)

In this article, we will look at how to modify the position indicator's code to create a sort of shadow that lets us see the price level still in effect on the trading server. This mechanism is designed to simplify the planning of trades in which we adjust our stop-loss or take-profit levels. Adding this feature — that is, price shadows — may seem like an extremely difficult task. Here, I will show you that this can be implemented very easily in practice.
preview
Building Your Own Expert Advisor (Part 9): Point-Based and Indicator Trailing Stops

Building Your Own Expert Advisor (Part 9): Point-Based and Indicator Trailing Stops

This part extends the MQL5 risk management framework with two trailing stop methods: fixed points and an indicator line. A base class converts chart levels on Bid-built charts into stop prices and adds the current spread to sell stops so they align with Ask-triggered execution. The Series EA integrates these trails alongside the existing ATR and R-ladder options.
preview
Streaming Percentiles in MQL5: Testing the P-Square Algorithm on Real Tick Data

Streaming Percentiles in MQL5: Testing the P-Square Algorithm on Real Tick Data

An EA can set spread and tick-gap thresholds by percentile without storing every tick. CPSquare implements the P-Square algorithm, and two order-independent classes serve as alternatives: CCountQuantile returns exact percentiles of rounded spreads, and CLogQuantile keeps a chosen relative error within a set range. Unit tests, mutation runs, and a Python consistency check cover the code. On EURUSD and XAUUSD ticks in time order, the P-Square estimates of high percentiles stayed far from the exact values.
preview
Neural Networks in Trading: Spatially Guided Aggregation of Market Events (STFlow)

Neural Networks in Trading: Spatially Guided Aggregation of Market Events (STFlow)

The article introduces the STFlow framework, which can generate a robust joint representation of the current market state and the dynamics of recent events, ensuring high sensitivity to micro-impulses while maintaining stable processing. The core ICE module has been implemented; it accumulates price and event streams, creating a reliable foundation for further aggregation and analysis.
preview
Practical MQL5 Utilities (Part 1): Trade Journal Analytics Panel

Practical MQL5 Utilities (Part 1): Trade Journal Analytics Panel

This article presents a read-only trade journal for MetaTrader 5 that groups account deals into positions and calculates closed-trade statistics, including profit factor, expectancy, drawdown, and win and loss streaks. It breaks the results down by entry hour and weekday, shows them in a chart panel, and exports the closed positions to a CSV file. The implementation covers HistorySelect, deal and position identifiers, closed-trade sorting, and object-based panel rendering.
preview
Adaptive Bar Replay Tool in MQL5: Using MFE and MAE Percentile Analysis

Adaptive Bar Replay Tool in MQL5: Using MFE and MAE Percentile Analysis

We implement a bar replay indicator in MQL5 that uses historical MFE and MAE percentiles to compute adaptive Stop Loss and Take Profit levels. The article covers data collection, excursion calculation, percentile interpolation, and an event-driven engine that replays candles and manages multiple simulated positions. Readers can test decisions against statistically derived risk thresholds rather than fixed offsets.
preview
CandleCode Indicator: Formalization of Candlestick Patterns in MQL5

CandleCode Indicator: Formalization of Candlestick Patterns in MQL5

The article demonstrates the practical implementation of CandleCode for MetaTrader 5: calculating candlestick codes using the Likhovidov method with thresholds adapted to volatility (Bollinger Bands) and histogram visualization. An Expert Advisor is also presented that builds a database of historical patterns using ZigZag, compares them with the current "snapshot" using ATR, and displays match statistics on a panel.