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
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.
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
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
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
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
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
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
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
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
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
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
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
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
Your Take Profit Is a Guess Until You Log MFE: Building an Excursion Recorder in MQL5

Your Take Profit Is a Guess Until You Log MFE: Building an Excursion Recorder in MQL5

A compact MFE/MAE recorder in pure MQL5 samples excursion while a position is open and writes one CSV row per closed position, measured in R and frozen at entry. A companion script prints a reach-rate table per asset class: the share of trades that ever reached each level. In a 226-position sample, three of the four classes never reached the 3R target the system was using. Use it to test whether a target is reachable before trusting it.
preview
Building a HalfTrend Channel Indicator in MQL5

Building a HalfTrend Channel Indicator in MQL5

This article builds a HalfTrend Channel indicator in MQL5 that combines rolling price extremes with a HalfTrend baseline and a Wilder‑smoothed ATR(100) to form adaptive channel boundaries. It explains the trend‑state machine, ATR smoothing, and the logic for detecting close‑price crossings of the bands. The result helps you study confirmed directional shifts and price behavior around a volatility‑adjusted reference line.
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
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 (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
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
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
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
Automating Trading Strategies in MQL5 (Part 54): Consolidation Breakout and Retest Entry Model

Automating Trading Strategies in MQL5 (Part 54): Consolidation Breakout and Retest Entry Model

We implement an MQL5 program that validates consolidations by counting edge switches, height capped to the typical candle, and net drift, then requires a buffered close beyond an edge and a move away before arming. Entry follows a return to the broken edge and a strong close back on the breakout side. The stop anchors beyond the retest extreme; the target is an R-multiple, and failed attempts can rearm the same range after a fresh breakout and retest.
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
Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (EDCFlow)

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

In the article, we explore the EDCFlow framework, which offers a new approach to analyzing market microstructure. It combines state correlation with a difference map, making it possible to identify subtle dynamic changes in the market. The model's architecture effectively aggregates multiscale features with minimal computational cost, making it suitable for real-time analysis.
preview
Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity

Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity

A complete, native MQL5 toolkit for Detrended Cross-Correlation Analysis: engine, validator, basket scanner, and a reference spread-trading EA. The engine produces a scale-by-scale rho_DCCA(s) curve and a band-mean score to rank pairs, contrasted with a standard Pearson correlation. The article details the box-detrending approach and shows real Strategy Tester results to illustrate how the gate integrates into trade decisions.
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
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
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: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (Conclusion)

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

The article presents an adaptation of the EEMFlow framework for building highly effective trading models using MQL5. MeshFlow estimation algorithms with advanced feature correlation are considered, allowing for accurate analysis of market dynamics and forecasting of price flows. Testing confirmed positive mathematical expectation, moderate drawdowns and high decision-making efficiency.
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.