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
Native Gaussian Process Regression in MQL5: Short-Horizon Price Forecasting with Uncertainty Bands

Native Gaussian Process Regression in MQL5: Short-Horizon Price Forecasting with Uncertainty Bands

The article rebuilds a Gaussian Process forecaster in native MQL5 around market-state inputs and direct horizon log-return targets. It employs a Matern 3/2 kernel, symmetric Cholesky with adaptive jitter, standardized targets, and a log‑space grid search that avoids state side effects. The EA trades only when az‑score over observed variance clears a threshold and the edge beats the live spread. Calibration is verified in Strategy Tester.
preview
The Kalman Filter for Price Smoothing: An Exact Implementation in MQL5

The Kalman Filter for Price Smoothing: An Exact Implementation in MQL5

This article implements the scalar Kalman Filter for price smoothing in MQL5 using the standard local-level model and the exact prediction–update equations. It explains how process and measurement noise (Q, R) shape the Kalman gain, builds two independently configured filters into a fast/slow crossover, and provides a complete indicator and Expert Advisor that trade a stability-confirmed signal via iCustom, giving a reproducible baseline for testing and tuning.
preview
Building a Position Lifecycle Manager in MQL5 (Part 2): Managing Manual and Multi-Symbol Positions

Building a Position Lifecycle Manager in MQL5 (Part 2): Managing Manual and Multi-Symbol Positions

This update adds manual position adoption and multi-symbol lifecycle management. The manager detects and tracks positions regardless of the chart, applies initial protection, transitions to break-even under fixed or ATR triggers, and validates broker constraints per symbol. Using the MACD sample for context, it demonstrates reusable management across instruments and manually opened trades.
preview
Uncertainty as a Model (Part 5): The Basics of Regression

Uncertainty as a Model (Part 5): The Basics of Regression

A practical introduction to time series regression models: regression on a constant and simple regression with deterministic, exogenous, and endogenous regressors. It describes the key steps in the diagnostic process, including residual analysis and hypothesis testing, that are necessary for making informed trading decisions. MQL5 scripts for MetaTrader 5 are included; they implement tests and plots using real data.
preview
How to Set Up an AI Hedge Fund in MetaTrader 5

How to Set Up an AI Hedge Fund in MetaTrader 5

The article examines the architecture of a committee consisting of 15 AI agents: ten analysts and four risk officers vote in three parallel phases, and the Chair records the final result. Isolated pair contexts with separate reputations are used for eight currency pairs. The dynamic vote threshold depends on the daily PnL targets. The Expert Advisor uses only the signal, SL and TP, which allows for evaluation pf the quality of its decisions without any additional mechanics.
preview
Chart Synchronization in MQL5 (Part 1): From a Simple Script to an Interactive Indicator

Chart Synchronization in MQL5 (Part 1): From a Simple Script to an Interactive Indicator

The article develops a practical MetaTrader 5 tool that synchronizes charts of the same symbol across timeframes, starting from a script and moving to an interactive indicator. It uses time as a common reference, converts it to bar indices with iBarShift(), and navigates charts with ChartNavigate(). The result is a synchronized workspace for efficient MTF analysis. This is Part 1 of a three-part development series.
preview
Where your backtest stops being real: Measuring the depth of your broker's tick history

Where your backtest stops being real: Measuring the depth of your broker's tick history

In the "Every tick based on real ticks" mode, the Strategy Tester's journal reports the minutes for which real ticks were absent or discarded and says that every tick generation was used for them. We show where the journal records this, measure how far back usable tick history goes on two demo servers, and check the ticks from inside an Expert Advisor, so a test range can be chosen by its real-tick share.
preview
Building a PDF Creation Library in MQL5 (Part 2): Why PDFs Break

Building a PDF Creation Library in MQL5 (Part 2): Why PDFs Break

Learn how a viewer opens a PDF backwards, why xref entries must be exactly 20 bytes, and how a two-character change falsifies multiple offsets. We reproduce three typical failures, compare results in PDFium and pypdf, and extract four strict checks a generator must pass. The included PdfValidate.mqh class for MQL5 applies these checks and returns actionable offsets and object numbers for reliable testing beyond “it opens”.
preview
Controlling MetaTrader 5 from Telegram with Hermes and MCP

Controlling MetaTrader 5 from Telegram with Hermes and MCP

Hermes Agent links a private Telegram bot to the MetaTrader 5 MCP interface, so natural-language requests call terminal tools under controlled permissions. The article shows how to install Hermes on Windows, configure an AI service and the Telegram gateway, authorize users, and add the MCP settings generated by the terminal. Readers learn to run read‑only checks, perform bounded MQL5 edits and compilation, launch Strategy Tester runs, inspect market and account data, and enable trading tools deliberately.
preview
The MQL5 Standard Library Explorer (Part 18): Building a Multi-Symbol Indicator Cache

The MQL5 Standard Library Explorer (Part 18): Building a Multi-Symbol Indicator Cache

The article introduces a centralized cache that serves indicators to multiple strategy nodes. It encodes full indicator identity in keys, stores Standard Library objects in CArrayObj entries, reuses matching instances, verifies readiness, refreshes data, and deletes each indicator on final release. Readers gain a predictable resource lifecycle and reduced duplication in multi‑symbol Expert Advisors.
preview
Neural Networks in Trading: A Spike-Semantic Approach to Spatiotemporal Identification (Conclusion)

Neural Networks in Trading: A Spike-Semantic Approach to Spatiotemporal Identification (Conclusion)

In our interpretation, S3CE-Net skillfully translates the market into the language of events and captures early impulses that traditional indicators simply average out. STFS ensures robust training — the model sees the data from different perspectives and does not overfit to local anomalies. SSAM blocks and the OpenCL implementation deliver practical speed and accuracy, while the separation between training and deployment modes saves resources in production.
preview
The Hypothesis of Randomness: Searching for Hidden Patterns in Price Series

The Hypothesis of Randomness: Searching for Hidden Patterns in Price Series

The article describes a test of the hypothesis of randomness for quotes based on a chi-square statistic derived from the frequencies of overlapping s-chains. The article shows how to define discrete states and compare observed and expected frequencies in order to detect Markov memory in price increments. This approach helps distinguish structural dependence from noise and formalize the testing of trading hypotheses.
preview
Nonlinear OHLC Features Derived from Elliptic Curves

Nonlinear OHLC Features Derived from Elliptic Curves

The article discusses the projection of EURUSD daily candlesticks onto the secp256k1 elliptic curve and the extraction of 96 features (EC+TA) to predict the direction of the next candlestick in CatBoost. The price mapping to the curve and the training pipeline on 2,000 D1 bars are shown; the full model achieves a test AUC of 0.6508, with EC features contributing 60.6%. The materials are suitable for reproduction in Python/MetaTrader 5.
preview
Try/Catch style in MQL5: Bringing Modern Error Management to Algorithmic Trading

Try/Catch style in MQL5: Bringing Modern Error Management to Algorithmic Trading

This article presents an exception-like model for MQL5 that prevents VM faults through defensive guards and cooperative TRY/CATCH/FINALLY macros. It introduces structured error objects (CException), result propagation (CResult), manual stack tracing, and integrated logging for clear diagnostics. Readers learn how to validate risky operations, propagate failures predictably, and keep EAs stable when facing zero‑divide, null access, invalid handles, and array‑bounds conditions.
preview
Agent Based Market Simulation: Growing a Market From Rules, and Using It to Catch an Overfitted Strategy

Agent Based Market Simulation: Growing a Market From Rules, and Using It to Catch an Overfitted Strategy

A compact MetaTrader 5 library builds a synthetic market from agents: a minority game, a zero‑intelligence double auction, a stylized‑facts analyzer, and a parameter scanner. The result is a testbed with known answers, providing the control real price backtests lack. Each result is cross‑checked by the model's phase transition, a matching Python implementation, and detection of a planted edge.
preview
Adaptive Trade Management in MQL5: Building a Broker-Aware, Deterministic, and Explainable Exit Engine

Adaptive Trade Management in MQL5: Building a Broker-Aware, Deterministic, and Explainable Exit Engine

This article presents an MQL5 trade-management engine that converts exit rules into proposal generators. A policy engine ranks all proposals by a configurable reason priority with documented tie-breakers. A broker-aware validator checks the candidates in that order and falls back to the next one on rejection, and an execution adapter sends the first accepted request. Reconciliation confirms the result on the position before the internal state changes. The engine uses R-multiples for thresholds, persists intratrade state, and records a decision trace for each managed position on every tick.
preview
The MQL5 Standard Library Explorer (Part 17): Building a Reusable Portfolio Manager with CArrayObj

The MQL5 Standard Library Explorer (Part 17): Building a Reusable Portfolio Manager with CArrayObj

We present a multi‑symbol EA structure that moves symbol‑specific state into independently initialized CStrategyNode objects and manages them with CPortfolioManager. Using CArrayObj with FreeMode, Add(), At(), Delete(), Total(), and Clear(), the manager ensures safe ownership and isolation, while timer‑driven routing and completed‑bar gates keep processing deterministic. This lets you scale portfolios, control risk per node, and avoid duplicated event handling.
preview
Online False Discovery Rate Control: Putting an Error Budget on a Live Signal Stream

Online False Discovery Rate Control: Putting an Error Budget on a Live Signal Stream

The article addresses online false discovery rate control for streaming signals, where fixed thresholds inflate noise discoveries. We port LORD3, LORD++ and SAFFRON into MQL5, construct a causal bootstrap p‑value source without a resolution floor, and verify correctness before market data. Dependence stress tests, a budget/level indicator and a two-arm Strategy Tester show how to configure, monitor and throttle streams to keep the acted-on noise fraction within target.
preview
Neural Networks in Trading: A Spiking-Semantic Approach to Spatiotemporal Identification (Key Components)

Neural Networks in Trading: A Spiking-Semantic Approach to Spatiotemporal Identification (Key Components)

In this article, we took a detailed look at the integration of the SSAM module into the SEW-ResNeXt block, demonstrating how the S3CE-Net framework enables the effective combination of spiking attention with residual blocks. This architecture ensures accurate processing of temporal and spatial data streams and high training stability. The modularity and flexibility of the components make it easier to extend the model and reuse proven methods.
preview
Building a Prop Firm Compliance Monitor in MQL5 (Part 2): Daily Sessions and Restart-Safe Starting Balances

Building a Prop Firm Compliance Monitor in MQL5 (Part 2): Daily Sessions and Restart-Safe Starting Balances

Establishes persistent daily-session management for Prop Firm Guard in MetaTrader 5. The EA derives the session identity from the trading-server date, account login, and server, persists state in SQLite, and adds a confirmation step for the daily starting balance. A timer detects trading-day changes and restores the confirmed baseline after EA removal or terminal restarts, ensuring a stable reference for daily risk checks.
preview
Building Your Personal Expert Advisor (Part 7): Risk Management VI (Final)—Consolidating the Risk Framework

Building Your Personal Expert Advisor (Part 7): Risk Management VI (Final)—Consolidating the Risk Framework

The article consolidates trade, basket, and account risk into a modular framework for MQL5 EAs. Risk logic moves into reusable classes and shared types, leaving the EA with its inputs, signal, configuration, and call sequence. The result is a shorter strategy file and a second EA that reuses the basket tier and the shared conversions.
preview
Beyond Clone and Commit: The Advanced Side of MQL5 Algo Forge

Beyond Clone and Commit: The Advanced Side of MQL5 Algo Forge

We map the parts of Algo Forge that impact day-to-day MQL5 work: opening repos in MetaEditor, README translation, Units, branch/tag protection, browser patching, packages, and CI on a Windows host. The article shows exact settings, required runner labels, and how to gate merges on builds. You leave with reproducible steps to protect code, automate compiles, and ship artifacts.
preview
Neural Networks in Trading: A Spiking-Semantic Approach to Spatiotemporal Identification (S3CE-Net)

Neural Networks in Trading: A Spiking-Semantic Approach to Spatiotemporal Identification (S3CE-Net)

We invite you to explore the S3CE-Net framework and its SSAM and STFS mechanisms, which accurately process spiking events while taking causality into account. The model is lightweight, parallel, and capable of identifying complex relationships across time and space.
preview
Price Action Analysis Toolkit Development (Part 87): Searching Chart History with Recorded Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 87): Searching Chart History with Recorded Double-Bottom Samples

This stage connects structural validation with reference matching for double bottoms. The Expert Advisor scans completed history, filters pairs by the current structural rules, and compares normalized close and low profiles against validated samples from the library. Results that meet the similarity requirement appear in the panel for chart review and are saved to REFERENCE_MATCHES.csv.
preview
Beyond Tick Volume: Measuring Market Activity from the Waits Between Quotes

Beyond Tick Volume: Measuring Market Activity from the Waits Between Quotes

Tick volume mostly reflects the time of day and is only complete when a bar closes. We build a per‑quote, live activity gauge from the waits between quote changes, remove the intraday rhythm, and model the remainder with the autoregressive conditional duration (ACD) model. We then test whether this activity measure improves short‑horizon volatility forecasts once live price volatility is already in the model.
preview
MetaTrader 5 Machine Learning Blueprint (Part 23): Feature Screening

MetaTrader 5 Machine Learning Blueprint (Part 23): Feature Screening

Permutation tests that assume exchangeable observations miscalibrate feature screens for overlapping financial labels, yielding a tenfold false‑positive inflation on EURUSD. This article implements a calibrated three‑gate pipeline: ADF+KPSS for stationarity, uniform‑grid entropy with modal occupancy, and mutual information corrected via a joint permutation null and Westfall–Young max‑T. The ScreeningReport summarizes gate outcomes and effective test count so you can filter features reliably before fitting models.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 6): Manipulating Chart Objects with MetaTrader 5 Agentic AI Assistant

How to Detect and Normalize Chart Objects in MQL5 (Part 6): Manipulating Chart Objects with MetaTrader 5 Agentic AI Assistant

This article demonstrates how natural-language prompts generate MQL5 producer programs that place native chart objects, and how a deterministic Expert Advisor (AIObjectTrader) reads them through a structured naming and geometry contract. We compare indicator and script routes, using three cases: horizontal resistance, a persistent Andrews' Pitchfork, and Fibonacci Time Zones. Readers gain a reproducible workflow to connect AI-built objects to TOUCH/BREAK/ZONE evaluation and optional execution.
preview
Recovering Option-Implied Probability Distributions Across Four Markets in MQL5

Recovering Option-Implied Probability Distributions Across Four Markets in MQL5

A practical route from the option chain to probability levels inside MetaTrader 5. For GLD, SLV, SPY, and USO, the risk-neutral density implied by each ETF's options is recovered with the Breeden-Litzenberger identity and checked for static arbitrage, after the method itself is validated against an analytic lognormal. A Python feed publishes the percentiles; an MQL5 service rescales them onto a related symbol, draws levels, and alerts when price leaves the risk-neutral 5 to 95 percent band. Every reading carries its own diagnostics, and full source is included.
preview
Implementing an LLM Agent with SQL Memory in MetaTrader 5

Implementing an LLM Agent with SQL Memory in MetaTrader 5

An LLM agent with SQL memory in MetaTrader 5 — an architecture that eliminates the main limitation of traditional LLM Expert Advisors (EAs): the loss of context between queries. Each agent decision is recorded in SQLite along with the market conditions at the time of the signal — RSI, MA alignment, volatility — and after the position is closed, the outcome is written to the database. When the next request comes in, the agent reviews its own history — similar past RSI conditions and the last three agent decisions — and only then analyzes the current market. The result is a system that remembers its errors between restarts and adapts its behavior based on accumulated statistics, rather than starting from scratch with each new bar.
preview
Uncertainty as a Model (Part 4): Random Processes — The Dynamics of Uncertainty

Uncertainty as a Model (Part 4): Random Processes — The Dynamics of Uncertainty

The article introduces the concepts and tools for working with random processes in trading: definitions, characteristics, autocorrelation functions, and a practical classification. The article covers white noise, random walks, Wiener and Poisson processes, as well as Markov chains and martingales. MQL5 scripts demonstrate the generation of sample paths and allow you to simulate equity, highlighting the mathematical limitations of strategies.
preview
Variational Mode Decomposition: Building the Solver, and Measuring What Hindsight Buys

Variational Mode Decomposition: Building the Solver, and Measuring What Hindsight Buys

A from‑scratch VMD library for MetaTrader 5: radix‑2 transform, ADMM updates, mirrored windows, and a result type that reports solve quality and mode separation. We verify the solver to full double precision against a reference and test causality by sabotage. The article quantifies repaint from batch versus causal runs and compares it to volatility‑matched random walks. You get a causal indicator, usable diagnostics, and settings that avoid common pitfalls.
preview
Price Action Analysis Toolkit Development (Part 86): Validating the Entire Sample Library

Price Action Analysis Toolkit Development (Part 86): Validating the Entire Sample Library

This part adds library-wide validation to the double-bottom toolkit. VALIDATE ALL applies the single-sample rule engine to the stored collection, counts its four outcomes and exports a separate CSV report. The report includes settings, sample context and detailed results. Source samples remain unchanged, and export errors are reported separately from completed validation.
preview
Interactive Supply and Demand Zone Manager in MQL5 (Part V): Persisting Zones Across Terminal and EA Restarts

Interactive Supply and Demand Zone Manager in MQL5 (Part V): Persisting Zones Across Terminal and EA Restarts

We introduce a versioned persistence layer that saves and restores the zone engine's logical state across sessions. The snapshot preserves lifecycle status, interaction history, scores, blacklist prices, and the geometry and time anchors of user‑drawn rectangles, and it is reconstructed and reconciled with chart objects on startup. User zones enter with the minimum score so they integrate into the same lifecycle and trading pipeline.
preview
Neural Networks in Trading: Training Deep Spiking Models (Conclusion)

Neural Networks in Trading: Training Deep Spiking Models (Conclusion)

The article demonstrates a practical implementation of the SEW ResNet framework using MQL5, with a focus on its applied use in trading. The Double Bottleneck makes it possible to simultaneously analyze univariate streams and inter-channel dependencies without losing gradients during training. Spiking activations with adaptive thresholds and gates improve robustness to noise and sensitivity to market novelty. The text provides details on the implementation and test results.
preview
Forecast Reconciliation (MinT): One Engine for Timeframe Hierarchies and Currency Graphs

Forecast Reconciliation (MinT): One Engine for Timeframe Hierarchies and Currency Graphs

This article builds forecast reconciliation in pure MQL5 and applies it to two structures: timeframe aggregation on one symbol and a currency graph linked by no‑arbitrage. The engine projects base forecasts onto linear constraints to make them coherent. We benchmark OLS/WLS and MinT with and without shrinkage on long walk‑forward runs, show when total squared error decreases, and measure the cost that may concentrate in a single node.
preview
Surrogate Data Testing: A Null Model for Any Statistic, and Why Shuffling Bars Is Not One

Surrogate Data Testing: A Null Model for Any Statistic, and Why Shuffling Bars Is Not One

We implement surrogate testing for indicators in MQL5: generate synthetic series that match your data's distribution and spectrum, score any statistic, and locate the observation within its null distribution. The library provides four null models, an FFT that handles arbitrary lengths, and a plug‑in interface for custom measures. An indicator visualizes the statistical alongside its chance band for direct interpretation.
preview
Evolutionary Selection of LLM Agents in MetaTrader 5

Evolutionary Selection of LLM Agents in MetaTrader 5

The article describes the architecture of a trading system consisting of 20 Grok (xAI)-based LLM agents, each of which embodies a unique trading philosophy — from pure momentum to a statistical z-score. The system applies a genetic algorithm directly during trading: every 20 trades, it automatically eliminates weak agents, clones strong ones with a prompt mutation, and publishes a leaderboard on the MetaTrader 5 chart — without interrupting trading and without using any SDK.
preview
Price Action Analysis Toolkit Development (Part 85): Visualizing and Reviewing Validated Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 85): Visualizing and Reviewing Validated Double-Bottom Samples

This part adds a visual review layer to the double-bottom workflow. It checks the chart context, moves to the recorded period, and renders the range, two qualifying lows, neckline, classification, score, and the first decisive close. The annotations mirror the validator's indices and prices, helping you audit outcomes without changing sample data.
preview
Institutional-Grade Multi-Currency Portfolio Engine in MQL5 (Part 2): Instrument Universe Management and Symbol Metadata

Institutional-Grade Multi-Currency Portfolio Engine in MQL5 (Part 2): Instrument Universe Management and Symbol Metadata

This article adds a symbol metadata layer to the MQL5 portfolio framework, normalizing contract specifications across instruments with different tick sizes and profit currencies. A CSymbolRegistry class loads a symbol universe from file, queries broker data, and converts tick values into account currency, including cross-rate and CFD tick/point cases. The Portfolio Controller publishes per-symbol lot limits from this metadata, and Instrument Agents recover automatically once the controller becomes available.
preview
Does Your EA Depend on Candle Boundaries? A Shifted-Bar Stress Test in MQL5

Does Your EA Depend on Candle Boundaries? A Shifted-Bar Stress Test in MQL5

The framework evaluates boundary sensitivity by rebuilding shifted target-timeframe bars from completed M1 sources and running one Strategy Tester pass for each boundary offset. It includes a ShiftedBarBuilder, a demonstration EA, and a deterministic self-test. An XAUUSD M15 case study reports net profit, Profit Factor, maximum relative equity drawdown, and total trades across all 15 offsets to quantify dependence on the bar grid.