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
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.
preview
Developing Statistical Market Inflection Forecasting Indicator

Developing Statistical Market Inflection Forecasting Indicator

An MQL5 indicator forecasts where a movement is likely to terminate and how far the opposite leg has typically traveled, using statistics from completed moves on the same symbol and timeframe. It detects confirmed pivots, takes a single snapshot, selects similar historical observations, and reads entry, stop loss, and take profit from their distributions. Empirical hit rates come from a chronological replay without look‑ahead, and resolved forecasts leave the chart with an option to review them.
preview
Benford's Law for Trade Log and Quote Feed Integrity Auditing in Native MQL5

Benford's Law for Trade Log and Quote Feed Integrity Auditing in Native MQL5

This article presents a native MQL5 auditor for Benford's first- and second‑digit tests on trade logs and market data. It implements an eligibility gate (sample size and decade spread), a theory-based test (chi-square, MAD, per‑digit z‑scores), and a reference comparison calibrated by bootstrap quantiles. A timer-driven EA, include files, and a tamper simulator show detection of hand rounding and invented values, while padding and scaling remain measured near the false-alarm level.
preview
Chart Synchronization in MQL5 (Part 2): Building an Interactive Multi-Chart Tool

Chart Synchronization in MQL5 (Part 2): Building an Interactive Multi-Chart Tool

This article turns the Part 1 prototype into an interactive MetaTrader 5 indicator that synchronizes charts of the same symbol across different timeframes. It handles keyboard input and drag events via OnChartEvent, traverses charts with ChartFirst/ChartNext, and maps time using iBarShift and ChartNavigate. A draggable vertical line keeps the selected time near the chart center, while a horizontal line propagates a chosen price level. The result streamlines multi-timeframe comparison.
preview
Building a Prop Firm Compliance Monitor in MQL5 (Part 4): Economic Calendar and Account Exposure Monitoring

Building a Prop Firm Compliance Monitor in MQL5 (Part 4): Economic Calendar and Account Exposure Monitoring

This article explains exposure-aware economic news monitoring for Prop Firm Guard in MetaTrader 5. The EA builds a unique currency set from supported open positions, treats XAUUSD as USD exposure, filters Economic Calendar events by currency, minimum importance, specific scheduled datetime, and search horizon, and selects the nearest qualifying event. The resulting countdown and restriction window are integrated into the EA through OnInit() and OnTimer().
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
Neural Networks in Trading: A Spatio-Temporal State Model for Financial Data Analysis (Conclusion)

Neural Networks in Trading: A Spatio-Temporal State Model for Financial Data Analysis (Conclusion)

We present an adaptation of the E-STMFlow framework — a modern solution for building autonomous trading systems. In this article, we complete the implementation of the approaches proposed by the framework's authors. The test results demonstrate steady capital growth, minimal drawdowns, and a predictable distribution of risk, confirming the practical effectiveness of the approach and opening up opportunities for further optimization of the strategy.
preview
Neural Networks in Practice: A Question of Scale

Neural Networks in Practice: A Question of Scale

There is a common misconception among the general public that a neural network or artificial intelligence can, in a sense, comprehend the world in which we live. In some cases, this might even be true. However, if you want to achieve faster convergence of a neural network—or even a single neuron—you need to understand that the scale of the values used often affects the convergence rate. In addition, in this article I'll show you something strange that happens in neural networks. It will blow your mind and make you think about a lot of things related to this topic.
preview
From Basic to Intermediate: Objects and Subwindows (III)

From Basic to Intermediate: Objects and Subwindows (III)

This article describes a safe way to handle the deletion of graphical objects: event interception, object recreation, and restoration of a minimal set of properties. We'll show you how to avoid errors when working with pointers, prevent unwanted object recreation during shutdown, and preserve object positions and dimensions by updating them using DRAG/CHANGE. As a result, the indicator remains intact, and the user retains some of their settings.
preview
MLP (Multilayer Perceptron) Inside an MQL5 Expert Advisor: Training on Historical Data Without Python or Weight Files

MLP (Multilayer Perceptron) Inside an MQL5 Expert Advisor: Training on Historical Data Without Python or Weight Files

The article shows how to move the GridSurvivor Expert Advisor’s MLP filter from offline training in Python to fully embedded training in MQL5. The network is trained on the history of the current symbol and timeframe, is periodically retrained, and is used as the final signal filter. This approach eliminates external files and normalization mismatches, making the Expert Advisor self-contained and reproducible.
preview
The Chimp Optimization Algorithm: From ChOA to BChimp

The Chimp Optimization Algorithm: From ChOA to BChimp

The Chimp Optimization Algorithm (ChOA) mimics primate group hunting with a division of roles, and its binary variant, BChimp, applies this mechanism to feature selection problems. We implement a continuous core in C_AO; along the way, we identify and correct an inherited coefficient defect — one that is masked by binarization but disrupts the search in the continuous domain. The abstract provides a ready-made implementation and practical insights into the quality and robustness of the search.
preview
Distributed Tracing for Expert Advisors: A Native OpenTelemetry (OTLP) Exporter in MQL5

Distributed Tracing for Expert Advisors: A Native OpenTelemetry (OTLP) Exporter in MQL5

This article builds a four-layer MQL5 tracer that works without gRPC or protobufs: OTLP/HTTP JSON via WebRequest, SHA-256–backed ID generation, a nanosecond-formatted clock, and a ratio sampler. Finished spans go to a bounded queue and flush in batches with exponential backoff. A W3C traceparent header links the EA's spans to a Python service for end-to-end visibility.
preview
Diebold-Mariano Test in MQL5: Does Your Indicator Actually Forecast Better Than a Random Walk?

Diebold-Mariano Test in MQL5: Does Your Indicator Actually Forecast Better Than a Random Walk?

The article implements the Diebold–Mariano test in pure MQL5 with HAC long‑run variance and the Harvey–Leybourne–Newbold small-sample correction, and adds the Clark–West adjustment for nested models. Forecasts are scored without look‑ahead over a rolling window while accounting for overlapping horizons. An EA and indicator use these tests as a live gate so trades occur only when a model outperforms a random walk at the chosen right‑tail threshold.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 8): Paint, from Solid Colors to Gradients

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 8): Paint, from Solid Colors to Gradients

Gradients are introduced by making the source a polymorphic paint: the rasterizer calls ColorAt(x, y) for each pixel. This enables solid, linear and radial fills on any path with a single inner‑loop change, keeping Path.mqh untouched. The article details color stops and padding, corner‑based normalization for linear gradients, normalized centers/radii for radial ones, a CCairoFillStyle handle, and compatibility with the legacy uint Fill().
preview
Why Backtested Scalpers Diverge in Live Trading (Part 1): Building an Intelligent Friction Guard for Dynamic Spread and Micro-Volatility Filtering

Why Backtested Scalpers Diverge in Live Trading (Part 1): Building an Intelligent Friction Guard for Dynamic Spread and Micro-Volatility Filtering

The article addresses the backtest–live gap in scalping by formalizing market friction and screening trades at quote time. It estimates tick velocity and arrival frequency, detects spread anomalies with a hybrid Welford–EWMA variance model, and evaluates a Friction Ratio against a configurable execution horizon. The MQL5 gatekeeper and diagnostic terminal radar classify market conditions into four regimes and gate order initiation when spreads widen or projected movement is insufficient.
preview
From Basic to Intermediate: Objects and Subwindows (II)

From Basic to Intermediate: Objects and Subwindows (II)

This article explains how to track and handle the removal of objects from the chart in MQL5 using MetaTrader 5 events. When the code detects that an object created by an indicator has been deleted, it deletes the corresponding instance to avoid inconsistencies and prevent subwindows from being left behind. This approach uses unique names and a header file, prioritizing simplicity and predictable behavior.
preview
Neural Networks in Trading: A Spatio-Temporal State Space Model for Financial Data Analysis (STSSM Block)

Neural Networks in Trading: A Spatio-Temporal State Space Model for Financial Data Analysis (STSSM Block)

The article explains the internal mechanics of the STSSM block and demonstrates how modern SSM approaches can be adapted to the event-driven logic of spiking models while maintaining high speed and expressive representations. Step by step, we work our way through the architecture, transforming the rigorous theory behind the authors' approach into a practical financial instrument for analyzing financial time series.
preview
A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part III): A Living Feature Graph

A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part III): A Living Feature Graph

The third article in this series introduces a trainable feature graph in the Cellular10K architecture: the weights of the feature → feature connections are strengthened online after correct predictions and weakened after errors. The article covers soft initialization, the message-passing step, a local Hebbian learning rule, weight clipping, normalization, and decay. The article demonstrates integration with a cellular automaton and a binary predictor, along with diagnostics metrics and practical activation thresholds for controlling overfitting.
preview
L-Moments for Robust Return Profiling in MQL5: A Distribution-Shape Regime Validator

L-Moments for Robust Return Profiling in MQL5: A Distribution-Shape Regime Validator

A native MQL5 pipeline computes L-moments from probability‑weighted moments and compares their shape ratios to conventional Pearson estimators on the same rolling window. A single-pass walk-forward validator flags L‑kurtosis (tau4) and excess kurtosis spikes against adaptive baselines and scores them with precision, recall and F1 on real FX history. The script is diagnostic, input-driven, and avoids the Strategy Tester to provide reproducible, data-first results.
preview
Native AWS S3 Integration in MQL5: A Signature V4 Client for Model and Feature Artifact Storage

Native AWS S3 Integration in MQL5: A Signature V4 Client for Model and Feature Artifact Storage

This article builds an AWS SigV4 signer in pure MQL5 and wraps it in a small S3 client for PutObject, GetObject, and ListObjectsV2. It explains canonicalization, HMAC‑SHA256, and key derivation, and shows how to handle empty‑payload hashing and GMT timestamps to avoid SignatureDoesNotMatch. A script uploads a model and a CSV, downloads them back, and compares SHA‑256 checksums, providing a practical, DLL‑free path to centralized artifact storage.