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
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.
preview
A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part II): A New Level of Online Adaptation

A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part II): A New Level of Online Adaptation

In the second part, the cellular automaton is transferred from a grid to a graph. The features become vertices in a graph with local and long-range small-world connections, and the cells become agents that interact not only with their geometric neighbors but also with their semantic neighbors. The article discusses graph-based feature filtering, the construction of a neighbor graph, updated coherence-based voting, and the Graph Coherence and Graph Health metrics. This reduces the impact of isolated outliers and accelerates the propagation of market regimes while maintaining full compatibility with MQL5.
preview
Temporal Causality Audit in MQL5: Validating Recorded Dependencies Against the Decision Time

Temporal Causality Audit in MQL5: Validating Recorded Dependencies Against the Decision Time

Look-ahead errors arise when a decision consumes values that did not yet exist, such as a partially formed higher-timeframe bar. This MQL5 library logs input timing metadata and validates declarations against the decision time with eight ordered rules, returning PASS, WARNING, or FAIL and a named violation. A demo EA plus twelve deterministic tests at a fixed timestamp illustrate correct and failing cases.
preview
A Trade Request Preflight Class in MQL5: Checking Volume, Stops, Margin and Sessions Before OrderSend

A Trade Request Preflight Class in MQL5: Checking Volume, Stops, Margin and Sessions Before OrderSend

CTradePreflight checks a trade request before OrderSend(), so an EA finds an off-step volume, a wrong-side stop, missing margin or a closed session instead of getting a server rejection. The class repairs only safe cases, reads the OrderCheck() retcode, and counts every refusal by reason. Unit tests and a random-delay stress EA show that levels placed very close to the price can still fail, and an optional delay buffer stops those rejections at the cost of blocking some valid requests.
preview
Neural Networks in Practice: The Perceptron

Neural Networks in Practice: The Perceptron

In this article, the perceptron is presented as the basis of a neural network, and its implementation in MQL5 is described in detail. We will explain what activation functions and their derivatives are, the difference between forward propagation and backpropagation, and how the least squares loss function and the gradient are used. You will learn how to train weights and biases, verify the results using test scripts, and adjust the learning rate to achieve stable convergence.
preview
Neural Networks in Practice: The Gradient

Neural Networks in Practice: The Gradient

This article explains why and how the gradient is used in training a perceptron, based on the least squares method and the chain rule for computing partial derivatives. We will demonstrate how to implement gradient calculation in the C_Neuron class using the MQL5 language and test it using examples with 1 and 2 inputs. You'll learn how to adjust the weights and bias using gradient descent and prepare for forward propagation and backpropagation.
preview
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Conclusion)

Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Conclusion)

The SDformerFlow framework transforms complex events in financial time series into structured representations, enabling the model to identify local fluctuations and global trends simultaneously. The multi-level U-structure ensures consistency between the forward pass and the backward pass, synchronization of gradients, and computational stability. Ultimately, SDformerFlow proves to be a powerful and flexible tool for building modern trading systems.
preview
Self-Learning SuperTrend: An Adaptive Machine Learning-Based Trend Indicator

Self-Learning SuperTrend: An Adaptive Machine Learning-Based Trend Indicator

The classic SuperTrend loses accuracy when the market regime changes because it uses fixed ATR parameters and a fixed multiplier. The article examines the architecture of ML SuperTrend Pro v2.00 written entirely in MQL5: a background test matrix with adaptive parameter updates, a regime grid as a context detector, an accuracy layer consisting of five filters, and Parabolic-style rendering with well-designed buffers. The article presents the principles of L1 regularization, the results of a comparison with the classic SuperTrend, and practical recommendations for deployment and integration via iCustom.
preview
Coyote Optimization Algorithm (COA)

Coyote Optimization Algorithm (COA)

Introducing an MQL5 implementation of the Coyote Optimization Algorithm: packs with local alphas, a median-based tendency, and built-in crossover enable parallel exploration of regions of the search space while keeping premature convergence in check. The algorithm is integrated into C_AO and has been tested on the standard test bench and in a composite anti-cheat test. The article includes code, pseudocode, and an analysis of the operators that enable the use of COA to optimize the parameters of a trading system.
preview
Measuring Spread Costs Before a Market Order in MQL5

Measuring Spread Costs Before a Market Order in MQL5

The article implements a MetaTrader 5 Expert Advisor that provides spread-only pre-trade estimates in points for a planned Buy or Sell. It compares a current-spread result with a historical scenario that uses the maximum of the live spread and a selected percentile from recent Bid/Ask ticks, and shows both on a collapsible panel. Manual market execution is available without SL/TP, with readiness checks kept separate from the estimates.
preview
Estimate the Probability of Large-range Sessions (Part 1): Build and Check EURUSD Forecasts

Estimate the Probability of Large-range Sessions (Part 1): Build and Check EURUSD Forecasts

We estimate the probability, at broker time 08:00, that EURUSD's 08:00–16:00 range exceeds 1.25 times the mean of the previous 20 complete, valid target ranges. A two-feature SPSS logistic regression model employs the completed 00:00–08:00 H1 window. Coefficients from 2020–2023 sessions are fixed for the 2024 holdout comparison against constant and 60-outcome rolling frequency baselines, using Brier scores and log losses. MQL5 scripts allow readers to extract broker data and recreate the probabilities in MetaTrader 5.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part VIII): Building a Floating Risk Management Calculator Module for Any EA

Overcoming Accessibility Problems in MQL5 Trading Tools (Part VIII): Building a Floating Risk Management Calculator Module for Any EA

A reusable MQL5 component measures floating P/L with swap, gross loss, two stop‑loss quantities, equity gap, margin level, and stop coverage, then classifies results for selected positions and the whole account. The snapshot records validity and readable reasons, supporting a quote‑age policy and missing‑stop handling. Integrate it into an Expert Advisor and block new exposure when thresholds or data checks fail.
preview
From Evidence to Execution (Part 2): Turning MetaTrader 5 AI Strategy Logs into Robust Rule Based EA

From Evidence to Execution (Part 2): Turning MetaTrader 5 AI Strategy Logs into Robust Rule Based EA

This article turns the Part 1 evidence into a working MQL5 Expert Advisor. It formalizes entry conditions, designs direction-aware stop loss and take profit, and stress-tests the combined logic before coding, with every rule linked to measured features. Readers receive a reproducible implementation with configurable inputs and per-bar execution consistent with the study.
preview
Measuring What Matters (Part 5): The Risk Concentration Indicator — Plotting Eigenvalue Dominance Live

Measuring What Matters (Part 5): The Risk Concentration Indicator — Plotting Eigenvalue Dominance Live

This article presents a live MQL5 indicator for monitoring portfolio risk concentration through eigenvalue decomposition. The indicator calculates rolling covariance statistics for three instruments using persistent prefix sums, aligns price data by timestamp, handles missing observations, and plots the dominant eigenvalue as a percentage of total portfolio variance. The implementation provides a practical way to observe changes in portfolio risk concentration as the covariance structure evolves over time.
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
From Basic to Intermediate: Resources

From Basic to Intermediate: Resources

In this article, you'll learn about a concept that can prove extremely useful in many situations and significantly simplify the sharing of your apps and projects. Although it is not easy to fully explain this concept in a single article, what will be presented and explained here will be enough to enable us to accomplish a great deal in the future—including things that would otherwise be impossible. That is exactly why this article has not been published until now: to give you supporting material and a starting point for your studies.
preview
Neural Networks in Trading: A Spatio-Temporal State-Space Model for Financial Data Analysis (E-STMFlow)

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

We invite you to explore the E-STMFlow framework, which effectively processes event streams by extracting informative embeddings, filtering out noise, and identifying key movements. Its architecture makes it possible to identify complex relationships between features and provides scalability, accuracy, and high computational efficiency for intelligent analysis and forecasting.
preview
Corona Virus Optimization (CVO) Algorithm

Corona Virus Optimization (CVO) Algorithm

We describe and implement CVO: infection as candidate generation, coordinate-wise normal perturbation, and a dynamic population. The algorithm is integrated into C_AO and has been tested on a standard benchmark. The analysis identifies a scaling-related cause of stagnation and provides a practical solution — a shift to a relative step based on the range width. The code is ready for use.
preview
Why My MQL5 EA Passed Validation and Still Failed Under Execution Delay

Why My MQL5 EA Passed Validation and Still Failed Under Execution Delay

An EA that passes CodeBase validation can still fail under execution delay and a freeze level. Using a tick scalper, the article reproduces four such failures in the Strategy Tester and shows each fix with its limits. An ablation under a fixed delay measures each change on its own. The burst-based stop distance removes most rejected modifications, while the weekend case behind the session buffer did not recur in those runs.
preview
Working with ONNX Models in MQL5 (Part 3): Drawing the Neurons and the Weights Between Them

Working with ONNX Models in MQL5 (Part 3): Drawing the Neurons and the Weights Between Them

We build a neuron-level view for MQL5 models: count neurons per row, compute ranks, and render one line per stored weight from dense layers. The implementation reads matrix orientation from attributes, colors connections by sign and relative strength, and keeps activations on the same row. You can toggle between the layer graph and neurons, or see why the neuron view is unavailable, to analyze how weights connect inputs to outputs.
preview
Creating Three-Dimensional Bars in MQL5

Creating Three-Dimensional Bars in MQL5

Migrating 3D bars from Python to native MQL5: instead of Plotly and a bridge to the terminal — a scene using CCanvas3D and DirectX 11 directly on the chart. Price, time, and tick volume are plotted along three axes; the geometry is assembled manually from vertices and triangles; and a mouse-controlled orbit camera allows interactive exploration without external dependencies.
preview
Forecasting Realized Volatility with Option-Implied Variance for Multiple Instruments in MQL5

Forecasting Realized Volatility with Option-Implied Variance for Multiple Instruments in MQL5

A published daily history of option-implied variance is combined with a broker symbol's daily bars to fit a HAR model of realized volatility in MQL5; the implied term enters the regression as a predictor, not as a ready-made forecast. Out-of-sample tests on four funds paired with their Cboe indices, ten US equities, and two broker symbols show where it improves the forecast. A background service refits on the broker's bars and draws a five-session price range on the chart, and a self-test matches independent C++ and Python implementations.
preview
Model Drift Watchdog: PSI-Based Auto-Retrain Alerts via a Lightweight Webhook

Model Drift Watchdog: PSI-Based Auto-Retrain Alerts via a Lightweight Webhook

This article implements a PSI-based drift watchdog for MQL5 EAs. It compares a feature and the model's predicted probability against a quantile-based reference using a rolling window at a configurable cadence, applies hysteresis to avoid flapping, and raises a webhook on state transitions. You get tested math, an audit CSV and a plotting indicator, plus tuning guidance for thresholds, window size, and cooldown.
preview
Neural Networks in Practice: Activation Functions

Neural Networks in Practice: Activation Functions

This is, without a doubt, the article I've enjoyed writing the most so far. In it, I showed that we don't really need anything special to achieve a certain goal. We can achieve this in various ways, provided we have the necessary knowledge and are willing to learn and dedicate ourselves to the task. I would like to express my heartfelt thanks to everyone who helped me choose these functions. The material presented here is intended solely for educational purposes. Under no circumstances should this be viewed as intended for anything other than teaching and studying the concepts presented.
preview
From Basic to Intermediate: Subwindows (IV)

From Basic to Intermediate: Subwindows (IV)

In this article, we'll see that things aren't quite what many people initially think they are. One of the most interesting aspects of programming is that we can guarantee that everything will always turn out exactly as we planned. So please read this article carefully to understand some of the most confusing concepts related to the use of subwindows. If you understand what is explained here, you'll be able to understand much of what we'll be doing next.
preview
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Encoder)

Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Encoder)

The article presents an adaptation of the SDformerFlow framework that achieves high adaptability by integrating spiking attention with multi-window convolution and weighted summation of query elements. The architecture allows each attention head to learn its own parameters, which improves the model's accuracy and sensitivity to the structure of the data being analyzed.
preview
Native MQL5 Prometheus Exporter: Real-Time Observability for Live Trading Models

Native MQL5 Prometheus Exporter: Real-Time Observability for Live Trading Models

This article shows how to build a fully native MQL5 metrics pipeline for a live EA without DLLs or sidecar processes. It implements counters, gauges, and histograms, safe text/label encoding, and an HTTP client that pushes one exposition payload to a Prometheus Pushgateway on a timer. You will wire metrics into OnTick/OnTimer, export equity, drawdown, trade P&L, and latency, and learn configuration, testing, and limitations for reliable observability.
preview
Probabilistic Sharpe Ratio and Minimum Track Record Length from Deal History

Probabilistic Sharpe Ratio and Minimum Track Record Length from Deal History

The article delivers a practical PSR/MinTRL workflow in MQL5: construct returns from deal history, compute SR/skew/kurtosis, and evaluate normal CDF/quantile via rational approximations with runtime self-tests. We apply it in an EA and a script and validate across 12 Strategy Tester runs on three symbols. This lets you verify a Sharpe ratio against a benchmark and quantify how many trades your strategy still needs.
preview
TradeMux as a Quant Backbone: Connecting Institutional Python Pipelines to Different Terminals and Brokers

TradeMux as a Quant Backbone: Connecting Institutional Python Pipelines to Different Terminals and Brokers

The article describes TradeMux as a bridge between a Python pipeline and the MetaTrader 5 terminal for the seamless transfer of trading decisions without duplicating logic. The article examines a four-layer production architecture and a complete Python execution service: connection setup, reading account and position data, signal generation (including CatBoost), pre-trade risk control, kill_switch, and a supervisor. Practical benefits include cross-broker normalization (RoboForex, IC Markets, Alpari, OANDA) and scaling from a single account to multi-account broadcasting without changing the trading logic.
preview
Beluga Whale Optimization (BWO) Algorithm

Beluga Whale Optimization (BWO) Algorithm

A candidate for our ranking table is Beluga Whale Optimization, a metaheuristic based on three behavioral patterns of the beluga whale: pair swimming, hunting using Lévy flight, and population renewal through whale fall. During implementation, we discovered that the algorithm does not so much optimize as read the geometry of the test bench; we examine how this works and develop an honest, promising modification called BWOm.