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
Building a High-Volume Pivot Indicator in MQL5

Building a High-Volume Pivot Indicator in MQL5

This article presents a high-volume pivot indicator in MQL5 that identifies confirmed pivot highs and lows using surrounding price bars and normalized volume strength. It calculates rolling volume sums, determines a 95th-percentile volume reference, and filters pivot points based on their relative volume. The indicator uses ATR(500) to scale concentric rings around qualifying pivots and draws reaction levels, pivot markers, and formatted volume labels on the chart, helping you study high-volume pivot areas and their interaction with price structure and market volatility.
preview
Weak Supervision for Traders: Combining Several Noisy Labeling Heuristics into One Probabilistic Label (Snorkel-Style)

Weak Supervision for Traders: Combining Several Noisy Labeling Heuristics into One Probabilistic Label (Snorkel-Style)

The article builds an MQL5‑native weak‑labeling engine that infers per‑indicator trust from vote agreement, then fuses five noisy signals into P(Buy) using Expectation‑Maximization. We describe the EA architecture, rolling‑window refits, abstain handling, diagnostics, and a majority‑vote baseline used for comparison. Readers can reuse the EM library, swap in their own labeling functions, and obtain a transparent, probability‑based entry filter.
preview
Building AI-Powered Trading Systems in MQL5 (Part 13): Letting the Assistant Execute Trades Behind an Approval Card

Building AI-Powered Trading Systems in MQL5 (Part 13): Letting the Assistant Execute Trades Behind an Approval Card

We extend an MQL5 AI assistant from read-only tools to safe trade execution with a human-in-the-loop gate. The article defines action tools for placing, closing, modifying, and deleting trades and for drawing on the chart, validates each request, sizes volume to broker limits, and scopes ownership. We pause the tool loop behind an approval card, queue actions, and resume execution only after approval, which holds while auto-approval stays off, as it is by default.
preview
Which Economic Releases Actually Move Your Symbol, and by How Much?

Which Economic Releases Actually Move Your Symbol, and by How Much?

A calendar release is not a category but a number against a consensus. In MQL5 we build a robust, standardized surprise (actual minus forecast scaled by each indicator's own dispersion), recover the broker's daylight saving schedule from price to anchor each release on the bar that moved, and regress price response by symbol and horizon. The result is a measurable profile in pips per sigma showing which events actually move your market.
preview
Local Outlier Factor: Density-Based Anomaly Detection in Native MQL5

Local Outlier Factor: Density-Based Anomaly Detection in Native MQL5

This article builds a native MQL5 LOF engine without DLLs, ALGLIB or ONNX. Bars are mapped to five standardized features; k‑NN reachability and density produce a scale‑free LOF score, and the alarm level is a moving quantile of the reference cloud. The score gates only new entries in an EMA‑cross EA, with an indicator for charting and a script for independent checks on XAUUSD, EURUSD and GBPUSD.
preview
Building A Candlestick Trend Constraint Model (Part 13): Normalizing and Scoring Lower-Timeframe Trigger Quality

Building A Candlestick Trend Constraint Model (Part 13): Normalizing and Scoring Lower-Timeframe Trigger Quality

The EA now computes an equal-weight score at M1 confirmation from normalized body fraction, breakout relative to C's range, and elapsed time, while excursions are measured only afterward. We refine processing of closed minutes and export a typed CSV that distinguishes completed observations from snapshots. The result is a clearer, reproducible basis for analyzing confirmed-signal behavior.
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
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (SDformerFlow)

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

The article presents an adaptation of the SDformerFlow spiking architecture for the task of dense analysis of price micro-movements. The spatio-temporal structure provides a high level of detail, while the spiking logic ensures computational efficiency and the ability to work with sparse, pulse-like data. As a result, traders gain access to a tool that detects even the slightest shifts in liquidity and provides the foundation for more accurate and consistent real-time decisions.
preview
Developing a Quantitative Session Analysis Tool (Part 2): Building Universal Sessions and Analysing Session Relationships

Developing a Quantitative Session Analysis Tool (Part 2): Building Universal Sessions and Analysing Session Relationships

The Session Analyzer is upgraded to define sessions by local market time and to translate those windows into broker/server time with date-aware DST logic. We describe the session model, broker offset treatment, and efficient bar selection, then add a relationship layer that measures temporal overlap, shared price range, range breaks, and size ratios. This provides a clear, reusable basis for session-based research and chart inspection
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
From Basic to Intermediate: Subwindows (III)

From Basic to Intermediate: Subwindows (III)

This article takes a detailed look at using subwindows in MQL5 indicators: creating them, detecting instances, and preventing duplication. It also covers INDICATOR_SHORTNAME, querying information about chart windows and indicators, and the difference between displaying indicators in the main chart window and in a separate window. The article also shows how to set the height and boundaries of a subwindow to standardize the interface and simplify the placement of objects.
preview
Neural Networks in Practice: ReLU Function Graph

Neural Networks in Practice: ReLU Function Graph

We will create an indicator written entirely in MQL5 to display the activation function and its derivative on the chart, using ReLU as an example. We will explain how derivatives affect the choice of activation function and what precautions are needed at nondifferentiable points. Readers will be able to interactively visualize the curves and gain a practical foundation for deciding when to use certain activation functions and when not to.
preview
Building A Candlestick Trend Constraint Model (Part 13): Normalizing and Scoring Lower-Timeframe Trigger Quality

Building A Candlestick Trend Constraint Model (Part 13): Normalizing and Scoring Lower-Timeframe Trigger Quality

The EA now computes an equal-weight score at M1 confirmation from normalized body fraction, breakout relative to C's range, and elapsed time, while excursions are measured only afterward. We refine processing of closed minutes and export a typed CSV that distinguishes completed observations from snapshots. The result is a clearer, reproducible basis for analyzing confirmed-signal behavior.
preview
Developing a Quantitative Session Analysis Tool (Part 2): Building Universal Sessions and Analysing Session Relationships

Developing a Quantitative Session Analysis Tool (Part 2): Building Universal Sessions and Analysing Session Relationships

The Session Analyzer is upgraded to define sessions by local market time and to translate those windows into broker/server time with date-aware DST logic. We describe the session model, broker offset treatment, and efficient bar selection, then add a relationship layer that measures temporal overlap, shared price range, range breaks, and size ratios. This provides a clear, reusable basis for session-based research and chart inspection
preview
James-Stein Shrinkage: Estimating Many Numbers at Once, and Testing What It Buys

James-Stein Shrinkage: Estimating Many Numbers at Once, and Testing What It Buys

This article implements a James–Stein and empirical Bayes shrinkage library in MQL5, validates it against hand-checked arithmetic and a Python reference, and applies it to ten years of H1 data across eight symbols. It covers fixed-target and grand-mean forms, unequal variances with a fitted between-group spread, and a proportions wrapper. You finish with a reusable header, a reproducible test script, a walk-forward study, and a chart indicator that shrinks an hour-of-day table.
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.
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
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
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
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
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
Integrating MQL5 with Data Processing Packages (Part 11): Multi-Timeframe Causality Detection using Granger Analysis

Integrating MQL5 with Data Processing Packages (Part 11): Multi-Timeframe Causality Detection using Granger Analysis

This article implements a multi‑timeframe Granger causality monitor for MetaTrader 5. A Jupyter notebook tests predefined timeframe pairs, selects lags, applies multiple‑testing control, and exports a calibration table. An MQL5 Expert Advisor reloads the setup, recomputes the F‑test live on rolling windows, and marks pairs VALID/INVALID to gate its vote‑based BUY/SELL generator. The workflow shows alignment rules, live/offline parity, and a filtered vs unfiltered comparison on EURUSD.
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 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
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
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
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
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
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
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
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
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
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
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
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
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 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
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
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
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.