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 Market Behavior Analyzer in MQL5

Building a Market Behavior Analyzer in MQL5

We outline a modular analyzer for MetaTrader 5 that separates detection, interpretation, and visualization. The engine identifies swing highs and lows, assigns structural labels, evaluates impulses and pullbacks, and stores results in a market state object. An on‑chart dashboard and interactive inspection tools make the latest structure and measurements immediately accessible.
preview
From Novice to Expert: Trading Multi-Symbol Basket

From Novice to Expert: Trading Multi-Symbol Basket

The article develops a multi-symbol basket EA that standardizes prices, derives PCA weights with native MQL5 matrices, forms a synthetic spread, and trades z-score deviations from a rolling mean. It validates symbols and synchronized history, stabilizes component orientation, maps signed weights to leg directions, and applies broker-aware volumes, stops, and netting rules. Basket entries run with rollback protection and chart status, with a reproducible testing procedure.
preview
Market Microstructure in MQL5 (Part 9): Pullback Quality

Market Microstructure in MQL5 (Part 9): Pullback Quality

Part 9 adds a second measurement layer to Part 8's micro‑trend signal: pullback quality. It maps Fibonacci retracement depth to a six‑level PULLBACK QUALITY label, adds an H1 range position from a 60‑bar rolling proxy, and uses lag‑1 momentum autocorrelation. These inputs form a single composite entry‑quality score in [0,1] for filtering setups and sizing trades within MicroStructure_Foundation.mqh.
preview
Intrinsic Time: From the Directional-Change Scaling Laws to the Alpha Engine

Intrinsic Time: From the Directional-Change Scaling Laws to the Alpha Engine

The article implements intrinsic-time analysis in MQL5: an event-based directional-change operator that splits ticks into directional-change and overshoot sections. We reproduce the core scaling laws on 17.8 million live EUR/USD ticks and compare them to a random-walk baseline. Finally, we build a hedging-account Expert Advisor that trades the Alpha Engine with limit orders, detailing thresholds, inventory skew, and liquidity control for practical reuse.
preview
Implementing and Comparing Five Historical Volatility Estimators in MQL5

Implementing and Comparing Five Historical Volatility Estimators in MQL5

The study implements five historical-variance estimators in MQL5 and evaluates their one-session-ahead persistence forecasts for EURUSD D1 sessions using an M1 realized-variance proxy. Deterministic tests cover formulas, chronological order, and target construction. A configurable indicator, comparison scripts, and CSV outputs provide reproducible losses, calibration diagnostics, a common‑target mask, and sensitivity to the estimation window.
preview
Money Management in MQL5 (Part 1): Kelly Position Sizing from the Strategy's Own Edge

Money Management in MQL5 (Part 1): Kelly Position Sizing from the Strategy's Own Edge

This article applies the Kelly criterion to position sizing in native MQL5. It presents a reusable CKelly class that estimates win rate and payoff from closed deals, derives the Kelly fraction, and sizes lots from a stop distance. A Monte Carlo sweep of the Kelly multiplier shows growth peaking at full Kelly while drawdown and ruin increase, motivating fractional Kelly such as half Kelly that preserves most growth with materially lower drawdown.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 5): Fill Rules, Holes and Borders

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 5): Fill Rules, Holes and Borders

Part 5 adds a fill rule to the rasterizer and a stroke helper to the path. The engine now supports both non-zero and even-odd fills via a single enum parameter, enabling rings, true borders that do not repaint interiors, and glyph counters. AddThickLine() builds strokes from fills in one path and one pass, preserving uniform opacity at joints and showing why strokes require the non-zero rule.
preview
How to Implement Competition Among LLM Agents in MetaTrader 5

How to Implement Competition Among LLM Agents in MetaTrader 5

The article describes a competitive architecture for MetaTrader 5 in which ten LLM agents, each with different trading rules, manage their own capital and open independent positions using unique magic numbers. The system prompt and the agent's trading aggressiveness are adjusted based on PnL results and the trade streak. A reproducible framework with operating modes and monitored metrics is presented, suitable for testing and further optimization.
preview
Neural Networks in Trading: A Unified View of Space and Time (Conclusion)

Neural Networks in Trading: A Unified View of Space and Time (Conclusion)

The Extralonger framework demonstrates a unique ability to integrate spatial and temporal factors into a single model, ensuring high forecast accuracy. Its architecture allows it to adapt to different planning horizons and financial instruments while maintaining the system's transparency and manageability.
preview
Profit Factor Stability Chart Across Rolling Windows in MQL5

Profit Factor Stability Chart Across Rolling Windows in MQL5

A modular MQL5 toolkit computes and visualizes rolling Profit Factor over fixed trade-count windows. It presents the statistical motivation, an incremental algorithm that avoids recomputation, and a dedicated CCanvas rendering pipeline. The dashboard adds reference lines, shading for weak periods, and summary metrics, while a separate test suite validates the math, giving a practical way to monitor stability and detect deterioration in strategy behavior.
preview
Beyond REST and ZeroMQ: Building a gRPC/Protocol Buffers Bridge for Real-Time MetaTrader 5–Python Inference

Beyond REST and ZeroMQ: Building a gRPC/Protocol Buffers Bridge for Real-Time MetaTrader 5–Python Inference

This article defines a Protocol Buffers contract for the MetaTrader 5-Python boundary and implements a length-prefixed Protobuf-over-TCP client in MQL5, since MQL5 cannot speak real gRPC natively. A small Python shim relays those frames to a genuine grpc.aio server, unary today, with streaming already live on the backend. You get schema-enforced, strongly-typed messages, explicit errors, retry/backoff, and a Strategy Tester cache for reproducible backtests where sockets don't run.
preview
Self-Exciting Markets: Building a Hawkes Process from Scratch

Self-Exciting Markets: Building a Hawkes Process from Scratch

Volatility arrives in clusters: one large move makes the next large move more likely, and quiet spells stay quiet. This article builds a Hawkes self-exciting point process in pure MQL5 to measure that effect directly, ending in a single number, the branching ratio, that says how reflexive a market currently is. You get a small, tested library, an indicator that plots the fitted intensity live, and a demonstration Expert Advisor, along with the honest limits of all three.
preview
Architecture for Collective Trading Decisions by AI Agents

Architecture for Collective Trading Decisions by AI Agents

The article describes the architecture of a multi-agent trading system based on the grok-4-fast language model, in which, instead of a single system prompt, four independent analysts with fundamentally different roles operate: a bull, a bear, a risk manager, and an arbiter. Three analysts run in parallel using a ThreadPoolExecutor and, within 3–5 seconds, formulate well-reasoned positions based on the same market data; after that, a deterministic judge renders a final verdict according to strict rules.
preview
From Deal History to Hazard Curves: Survival Analysis Applied To Strategies

From Deal History to Hazard Curves: Survival Analysis Applied To Strategies

This article reframes performance from unconditional win rate to conditional probability given survival time. It introduces an MQL5 library, an on‑chart indicator, and a demo Expert Advisor that read deal history, fit Kaplan–Meier and Aalen–Johansen curves with competing risks, and report forward probabilities over a bar‑based horizon. Readers gain a reproducible way to quantify the chance that the current position reaches its target or stop, and to see the bias of the naive censoring approach.
preview
Encoding Candlestick Patterns (Part 5): Expanding Taxonomy of Candlestick for General Pattern Frequency Analysis

Encoding Candlestick Patterns (Part 5): Expanding Taxonomy of Candlestick for General Pattern Frequency Analysis

This article extends the candlestick encoding framework by separating previously unclassified bullish and bearish candlesticks into distinct symbols. Using an MQL5 script, historical data were automatically encoded, sequential patterns were extracted, and frequency statistics were generated. The results show that these newly identified candles represent a significant portion of market activity, revealing structural information previously hidden by the generic underscore notation. The expanded taxonomy improves the completeness of the symbolic representation while preserving an objective, quantitative framework for large-scale market structure analysis.
preview
Neural Networks in Trading: A Unified View of Space and Time (Global-Local Attention)

Neural Networks in Trading: A Unified View of Space and Time (Global-Local Attention)

We are continuing our work on implementing the approaches proposed by the authors of the Extralonger framework. This time, we will focus on building a Global-Local Spatial Attention module using MQL5, examining both its structure and its practical integration into the overall computational process.
preview
Competitive Swarm Optimizer (CSO)

Competitive Swarm Optimizer (CSO)

The article discusses the Competitive Swarm Optimizer — a swarm optimization algorithm based on an extremely simple idea: agents are randomly paired, and the loser learns from the winner and is drawn toward the center of the swarm. In addition to analyzing CSO, the article describes the modernization of the test bench: visualization of the algorithms’ operation has been moved into 3D space, making it possible to clearly observe the movement of the population on the surface of the test function.
preview
Working with ONNX Models in MQL5 (Part 2): Drawing the Model Graph on an Interactive Chart Panel

Working with ONNX Models in MQL5 (Part 2): Drawing the Model Graph on an Interactive Chart Panel

We turn the ONNX reader into an interactive graph viewer on a MetaTrader 5 chart. The parser is extended to carry tensor shapes and node attributes, and a canvas with anti-aliased drawing renders nodes and labeled connections. The layout arranges layers by depth, while zoom, pan, and clicks let you inspect operators and the tensors they read. This makes a model's structure and data flow visible directly in MQL5.
preview
Wasserstein Distance for Live Feature-Drift Detection in MQL5: Monitoring ONNX Model Inputs with Optimal Transport

Wasserstein Distance for Live Feature-Drift Detection in MQL5: Monitoring ONNX Model Inputs with Optimal Transport

This article implements a lightweight feature-space drift guard in MQL5 using 1D Wasserstein‑1: sort-and-pair scoring on equal windows, IQR normalization per feature, and gating via both a weighted composite and a max-statistic. Configuration comes from a JSON manifest (window sizes, weights, warn/critical thresholds, actions). It runs next to an ONNX classifier and is validated with Strategy Tester results and explicit caveats.
preview
Position Management: Deriving a Self-Calibrating Exit Ladder From Historical MFE in MQL5

Position Management: Deriving a Self-Calibrating Exit Ladder From Historical MFE in MQL5

We implement three MQL5 classes that replace fixed 1R/2R/3R targets with data-driven scale-out levels. CExcursionTracker records each closed trade's maximum favorable excursion in R, CExitLadderCalibrator derives runs from distribution percentiles with lookback and minimum-sample controls, and CLadderExecutor executes them on open positions. The ladder recalibrates as trades accumulate and uses a fallback until enough samples exist.
preview
Rough Volatility: Building a Roughness Index Feature from the RFSV Model for ML Trade Filtering

Rough Volatility: Building a Roughness Index Feature from the RFSV Model for ML Trade Filtering

This article builds a usable roughness index from rough volatility theory by fitting local H via a structure-function regression on blocked returns, all in native MQL5. We combine it with vol-of-vol features, train a gradient-boosted classifier in Python, export to ONNX, and call it from an EA. You will be able to compute H on every bar and use the model as a regime-aware entry filter.
preview
Hidden Semi-Markov Models for Duration-Aware Regime Detection in MQL5

Hidden Semi-Markov Models for Duration-Aware Regime Detection in MQL5

Standard HMMs assume geometric, memoryless state durations, which poorly match real market phases. This piece implements a duration‑explicit Hidden Semi‑Markov Model natively in MQL5, with per‑state sojourn distributions and a residual‑time forward filter. Parameters are fit offline via EM and loaded through a compact JSON manifest. The EA for XAUUSD M5 uses expected remaining duration to gate entries and exits, helping hold trends while avoiding late entries near regime exhaustion.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 4): Anti-Aliasing, Coverage and Compositing

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 4): Anti-Aliasing, Coverage and Compositing

The rasterizer now accumulates exact span coverage in X and sampled coverage in Y, and blends it via CairoBlendOver on straight ARGB. CairoAaSamples sets the number of vertical samples at runtime, making the cost nearly linear and localized to edges. Readers get smoother boundaries, correct compositing of translucent shapes, and controllable performance.
preview
Neural Networks in Trading: A Unified View of Space and Time (Extralonger)

Neural Networks in Trading: A Unified View of Space and Time (Extralonger)

The Extralonger framework demonstrates an approach to integrating spatial and temporal factors into a single model, which makes it possible to account for both local patterns and long-term cycles simultaneously. This architecture makes time series forecasting more resilient to market noise and enables data analysis across different time horizons. The article takes a detailed look at how these ideas are put into practice using OpenCL and MQL5.
preview
Artificial Searching Swarm Algorithm (ASSA)

Artificial Searching Swarm Algorithm (ASSA)

The article discusses the implementation of the Artificial Searching Swarm Algorithm (ASSA) in MQL5 as part of a unified test bench. The article examines three behavioral movement rules, the signal and global bulletin board mechanisms, space normalization, and the stepRatio and Pc parameters. Readers will receive a ready-made foundation for integrating ASSA, as well as an answer to the question of how successful the tactical metaphor proved to be as a basis for the competitiveness of the optimization algorithm.
preview
Building a Neural Loss-Pattern Auditor in MQL5

Building a Neural Loss-Pattern Auditor in MQL5

Aggregate metrics like win rate or profit factor miss sequence-dependent behavior, such as sizing up right after a loss. This MQL5 script trains a small native neural network on closed-deal history to estimate loss probability from behavioral and market-context features. It reports accuracy uplift over a baseline, probability calibration, and permutation feature importance, then combines them into a configurable A-F grade with concise, plain-language recommendations.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 3): Edges and the First Filled Shape

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 3): Edges and the First Filled Shape

Part 3 implements a scanline rasterizer in pure MQL5. We convert path segments into top‑down edges, sweep each row, sort crossings, and apply the non‑zero winding rule to decide which pixels are inside. The result is a single Fill(path, color, buffer, w, h) routine that draws rectangles, stars, glyphs, or 2000‑edge shapes without per‑shape code, ready to integrate into your MQL5 projects.
preview
Random Matrix Theory: Denoising the Correlation Matrix for Multi-Symbol EAs

Random Matrix Theory: Denoising the Correlation Matrix for Multi-Symbol EAs

Sample correlation matrices can look precise yet be mostly noise. This article implements a dependency-free RMT cleaner in MQL5: Jacobi eigendecomposition, Marchenko–Pastur eigenvalue screening, and average-noise reconstruction that preserves the matrix trace and unit diagonal. It explains integration into a basket EA so the denoised matrix improves stability of hedge ratios and weights between rebalances, while keeping the code portable and auditable.
preview
Drawdown Duration Analysis Indicator in MQL5

Drawdown Duration Analysis Indicator in MQL5

We build a drawdown analytics dashboard that derives the equity curve from deals and finds every episode's depth and recovery duration. Results appear on a CCanvas timeline spaced by point index with alternating bold annotations, and in a terminal table sorted by duration, allowing you to prioritize risk by time spent underwater rather than depth alone.
preview
Testing for Residual Autocorrelation with the Ljung-Box Portmanteau Test in MQL5

Testing for Residual Autocorrelation with the Ljung-Box Portmanteau Test in MQL5

A complete MQL5 implementation of the Ljung-Box test helps verify independence in trading data and fitted-model residuals. It computes sample autocorrelations, the Q statistic over selected horizons, degrees of freedom with user-controlled adjustments, and right-tail p-values via the regularized incomplete gamma function. Run it on returns, deal outcomes, or external residuals and review decisions directly in the Experts tab.
preview
Neural Networks in Trading: The Adaptive Graph Diffusion Model (Conclusion)

Neural Networks in Trading: The Adaptive Graph Diffusion Model (Conclusion)

In this article, we conclude our work on building the SAGDFN framework using MQL5, summarizing the development process and presenting the results of its practical testing. Let's combine the modules we've already implemented into a single system, highlight the strengths of this approach, point out its weaknesses, and discuss possible ways to improve it.
preview
Building a Dynamic and Customizable Table in MQL5

Building a Dynamic and Customizable Table in MQL5

This article presents a reusable CTable class for building chart-based tables in MQL5. It covers table architecture, creation and destruction of objects, coordinates and sizing, cell properties, horizontal/vertical headers, dynamic row/column edits, object naming, index conversion, and efficient refreshing. You will be able to assemble consistent, aligned on-chart dashboards for market data, indicators, and signals with minimal boilerplate.
preview
Building AI-Powered Trading Systems in MQL5 (Part 11): Optimizing the UI with Frame Throttling and Partial Rendering

Building AI-Powered Trading Systems in MQL5 (Part 11): Optimizing the UI with Frame Throttling and Partial Rendering

We optimize an MQL5 canvas interface to stay responsive under rapid input without changing its appearance. The article adds a direct-buffer canvas for block region copies, caches text widths and glyph coverage, caps repaints at 60 fps (16 ms), and limits drawing to panes and regions that actually changed. As a result, hover, scroll, and popups render smoothly without full-panel redraws.
preview
Practical Modules from Other Languages in MQL5 (Part 07): The OS Module from Python

Practical Modules from Other Languages in MQL5 (Part 07): The OS Module from Python

This article introduces a lightweight OS-like helper for MQL5 that streamlines file and path operations using a Python-inspired interface. We implement getcwd, listdir, scandir with DirEntry, remove, rmdir, rename, mkdir, stat, and an os.path subset (exists, isfile, isdir, join, split, pardir). You will learn how to work consistently within the terminal Files/common sandbox and simplify everyday filesystem tasks.
preview
From Delta-Space Quotes to the FX Volatility Smile: Garman-Kohlhagen and the Convention Problem

From Delta-Space Quotes to the FX Volatility Smile: Garman-Kohlhagen and the Convention Problem

FX options are quoted in delta space, not by strike. This article implements an FX-native smile tool for MetaTrader 5: it converts ATM, risk reversal and butterfly quotes into strike-space pillars, prices with the Garman–Kohlhagen model, handles spot/forward and premium-adjusted delta conventions per pair, and draws the smile with a reconstructed strike ladder and Greeks.
preview
Uncertainty as a Model (Part 1): Random Variables — The Language of Uncertainty

Uncertainty as a Model (Part 1): Random Variables — The Language of Uncertainty

The article provides a systematic overview of the theory of random variables, which serves as the basis for analyzing and modeling uncertainty in financial markets. The article covers the definitions and properties of univariate random variables, cumulative distribution functions (CDFs) and probability density functions (PDFs), as well as the differences between discrete, continuous, and mixed models. The theoretical material is based on intuitive analogies with mass and density. The appendix to this article contains practical examples of using the standard MQL5 library to calculate probabilities, quantiles, and moments of distributions. It also demonstrates the graphical capabilities of the MetaTrader 5 platform for visual data analysis by plotting PDF and CDF curves and QQ plots.
preview
Building a Swing-Based Volume Profile Indicator in MQL5

Building a Swing-Based Volume Profile Indicator in MQL5

This article presents a swing-based volume profile indicator in MQL5 that analyzes platform tick volume within completed high-to-low and low-to-high legs. It confirms swing points, partitions each leg's range into ATR(200)‑adaptive price bins, distributes tick volume, and marks the Point of Control. The indicator draws a ZigZag and renders the profile on chart rectangles, helping you study volume concentration within each swing relative to price structure.
preview
Automating Trading Strategies in MQL5 (Part 53): Double Top and Double Bottom Reversal Model

Automating Trading Strategies in MQL5 (Part 53): Double Top and Double Bottom Reversal Model

We build an MQL5 program that detects and trades Double Top and Double Bottom patterns from confirmed swing pivots with rule-based logic. The detector matches peaks within a tolerance, derives the neckline, and applies leg-balance and spacing filters to reject weak shapes. It supports entry on a neckline break or an optional pullback, with a stop beyond the extreme and targets by measured move or reward-to-risk.
preview
Did Your Scale Outs Actually Help? A Scale Out Value Analyzer in MQL5

Did Your Scale Outs Actually Help? A Scale Out Value Analyzer in MQL5

The article presents an MQL5 tool that tests whether scaling out improved results rather than only appearing disciplined. It reconstructs positions from closing-deal history and reprices the full volume at the first, last, and best exit rates actually achieved, producing a Value-Add Ratio, a Scale-Out Win Rate, and an Efficiency measure. A single-trade dependence check and a configurable A+ to F grade turn these into clear, decision-ready feedback.
preview
MetaTrader 5 Machine Learning Blueprint (Part 21): Feature Importance Analysis

MetaTrader 5 Machine Learning Blueprint (Part 21): Feature Importance Analysis

Feature importance often understates correlated predictors by spreading one signal across many engineered copies, while unrelated noise can appear higher. We measure this effect against a known ground truth and compare four remedies: permutation importance with purged cross-validation, single-feature models, and clustered impurity versus clustered accuracy. The results include per-method rankings and a per-cluster dilution ratio that help identify true signals and avoid deleting valuable features.