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
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.
preview
Causal Savitzky-Golay Kinematics in MQL5: Non-Repainting Velocity and Acceleration from Local Polynomial Fits

Causal Savitzky-Golay Kinematics in MQL5: Non-Repainting Velocity and Acceleration from Local Polynomial Fits

We present CSavGolFilter, a causal Savitzky–Golay implementation for MQL5 that evaluates a local polynomial at the most recent closed bar. It delivers smoothed price, velocity, and acceleration via precomputed convolution kernels, avoiding per-tick matrix work. The package includes an indicator, a simple EA, and a self-test that proves the non-repainting property and validates kernel identities.
preview
Hedge (Multiplicative Weights): Blending a Handful of Simple Trading Rules Online

Hedge (Multiplicative Weights): Blending a Handful of Simple Trading Rules Online

We implement a Hedge (multiplicative-weights) ensemble in MQL5 that combines five simple experts: MA cross, RSI reversion, Bollinger and Donchian breakouts, and a MACD histogram flip. The EA updates weights bar by bar from realized direction, with an optional regret-based learning rate. We wire it into trade logic, logging weights and enforcing risk controls, then compare Hedge to equal-weight and single-expert modes across multiple symbols and timeframes to show how to tune η and evaluate impact.
preview
Do My EA's Losses Come in Clusters? A Wald-Wolfowitz Runs Test for Trade Outcomes in MQL5

Do My EA's Losses Come in Clusters? A Wald-Wolfowitz Runs Test for Trade Outcomes in MQL5

A pause after a losing streak assumes that losses come in clusters. CRunsTest turns the closed trades of an account or a tester run into a sequence of wins and losses and checks it with the Wald-Wolfowitz runs test, streak checks against shuffled orders, and a drift test. No dependence was detected on the tested EAs. A power simulation shows which effects each check could see, and on the shorter test runs a "not detected" result carries little weight.
preview
Hjorth Parameters for MQL5: Activity, Mobility, and Complexity as a Volatility-Momentum-Shape Dashboard

Hjorth Parameters for MQL5: Activity, Mobility, and Complexity as a Volatility-Momentum-Shape Dashboard

Implements Hjorth's Activity, Mobility and Complexity in MQL5 as an O(1) rolling engine, a regime-colored dashboard indicator, and an Expert Advisor. Explains how volatility, lag-1 autocorrelation and path shape arise from three variances, how null bands classify regimes, and how the indicator feeds the EA. Tests a Donchian breakout with and without a Trend gate on real ticks, with checks and limitations
preview
Is Your Expert Advisor Still the One You Backtested? An Edge Drift Detector in MQL5

Is Your Expert Advisor Still the One You Backtested? An Edge Drift Detector in MQL5

An equity curve cannot tell whether a live Expert Advisor still matches its backtest. This MQL5 tool compares live closing deals to a backtest baseline using a bootstrap-calibrated CUSUM shortfall detector, a change-point estimate, short and long window checks, and an expectancy decomposition. It summarizes the evidence as a configurable A+–F score and a rule-based verdict: CONTINUE, WATCH, REDUCE, or SUSPEND.
preview
Neural Networks in Trading: Bidirectional Adaptive Temporal Correlation (BAT)

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

The article presents the BAT framework, which enables accurate and adaptive modeling of temporal dynamics. Using bidirectional temporal correlation, BAT transforms sequential changes in market data into structured, informative representations. The model combines high computational efficiency with the ability to integrate deeply into trading systems, enabling the identification of both short-term and long-term price movement patterns.
preview
Implementation of the Gaussian Mixture Model in MQL5

Implementation of the Gaussian Mixture Model in MQL5

The article examines the theoretical foundations and practical implementation of the Gaussian mixture model in the MQL5 language. It introduces the CGMM class and provides examples of its use, as well as a methodology for selecting the optimal number of model components using the AIC and BIC information criteria. Considerable attention is paid to how the EM algorithm works — a recognized standard for training probabilistic models with hidden (latent) variables. Support for MAP training and parameter initialization using K-Means++ has been implemented. A ready-to-use tool for clustering, multivariate density estimation, and data generation is now available in MetaTrader 5 as well.