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
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.
preview
Feature Neutralization in MQL5: Orthogonalizing Trading Signals Against Confound Factors

Feature Neutralization in MQL5: Orthogonalizing Trading Signals Against Confound Factors

We implement feature neutralization so your signal is evaluated without volatility/trend confounds. The core is a native MQL5 rolling OLS engine using Gauss-Jordan elimination and out-of-sample residual scoring, with no DLLs. An EA and indicator integrate the residual and log diagnostics, while a Python companion validates numerics and runs bar-replay tests. Use it to isolate linear exposure and assess true signal contribution.
preview
Neural Networks in Trading: Training Deep Spiking Models (Spike Integration)

Neural Networks in Trading: Training Deep Spiking Models (Spike Integration)

The article presents a practical implementation of the key components of the SEW-ResNet framework using MQL5. The use of dynamic arrays and spiking mechanisms enables flexible model architecture design and efficient processing of financial time series. The proposed solutions demonstrate how SEW-ResNet can optimize computations and improve the extraction of meaningful features.
preview
Harris Hawks Optimization (HHO)

Harris Hawks Optimization (HHO)

We implement the Harris Hawks Optimization algorithm in MQL5 and analyze five movement modes of agents controlled by a single parameter — the decaying escape energy E. The C_AO_HHO class is introduced; it is compatible with the unified test bench and features a reproducible implementation of Lévy flight. The algorithm was tested on the Hilly, Forest, and Megacity functions with 5, 25, and 500 coordinates — the results indicate anomalous behavior.
preview
Ollivier-Ricci Curvature: Reading the Shape of a Correlation Network, Not Its Level

Ollivier-Ricci Curvature: Reading the Shape of a Correlation Network, Not Its Level

The article builds an Ollivier–Ricci curvature library in MQL5 for multi‑symbol analysis. A basket becomes a correlation network, and the reading captures network geometry rather than correlation level. It includes an exact optimal transport solver with an internal certificate, a rolling fragility metric with two informative nulls, an indicator that plots the reading against its null band, and a demonstration expert that uses it as a risk gate.
preview
Price Action Analysis Toolkit Development (Part 84): Validating Recorded Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 84): Validating Recorded Double-Bottom Samples

This work adds an explainable validation module to the recording toolkit for double bottoms. It finds and filters swing lows, selects the neckline, quantifies depth, low similarity, symmetry and recovery, and assigns a rule-based status and scores accepted pairs. The settings are configurable, the process is reproducible, and the original sample data remains intact for comparison across rule sets.
preview
Neural Networks in Trading: Training Deep Spiking Models (SEW-ResNet)

Neural Networks in Trading: Training Deep Spiking Models (SEW-ResNet)

We invite you to explore the SEW-ResNet framework, which allows you to build deep spiking models without degradation issues and with effective gradient management. In this article, we demonstrate how to implement a basic spiking neuron and its algorithms using MQL5.
preview
Foundation Models for Trading (Part III): Running a Generative AI Forecaster Inside MetaTrader 5

Foundation Models for Trading (Part III): Running a Generative AI Forecaster Inside MetaTrader 5

We demonstrate live forecast charting with Kronos in MQL5 and an evaluation pipeline designed to be look‑ahead‑safe. Deterministic dumps are scored per horizon against a random‑walk baseline (15,113 predictions), then fed to a simple Strategy Tester rule on EURUSD H1. The findings show no edge, and illustrate how a high threshold can yield a persuasive but low‑information backtest with very few trades.
preview
Machine Learning Under Constraint (Part 3): De-Risking Near the Profit Target and the News-Window Rule

Machine Learning Under Constraint (Part 3): De-Risking Near the Profit Target and the News-Window Rule

Position sizing that ignores proximity to a profit target or the timing of high-impact news exposes banked progress to reversal risk and misstates simulated profit near funded-stage news releases. We implement derisking_factor, a piecewise-linear size reduction keyed to phase progress with a floor set by minimum-trading-days status, and news_window_factor, a phase-gated step function applying FundedNext's news reward-share haircut in a configurable window around correlated events. Both return bounded multipliers combined multiplicatively with the sizer's other modifiers.
preview
How to Test and Customize Built-in MQL5 Programs: Envelopes with Alligator Strategy

How to Test and Customize Built-in MQL5 Programs: Envelopes with Alligator Strategy

Envelopes define percentage boundaries around a moving average, but a boundary touch alone does not identify whether the market is trending or ranging. We build Envelope_Alligator_Strategy.mq5, a custom indicator that reads the built-in Envelopes and Alligator buffers. Ordered Alligator lines classify directional states; interwoven lines identify a neutral state. This context changes how envelope crossings are interpreted and produces testable, non-trading chart signals.
preview
Price Action Analysis Toolkit Development (Part 83): Building a Reusable Double-Bottom Pattern Library

Price Action Analysis Toolkit Development (Part 83): Building a Reusable Double-Bottom Pattern Library

This recorder bridges visual labeling and systematic research in MQL5. After you position a rectangle, the EA extracts the candles it spans, derives candle geometry, normalizes OHLC values, assigns an ID, and saves the sample for reuse across sessions. The current category is the double bottom, and the module records the chosen sequence without enforcing a predefined pattern definition.
preview
Certified Robustness Radius: Knowing How Much Noise Your ONNX Trading Model Can Survive

Certified Robustness Radius: Knowing How Much Noise Your ONNX Trading Model Can Survive

We introduce a certified-radius gate for ONNX signals implemented natively in MQL5. The system estimates per-prediction robustness via randomized smoothing and a one-sided Clopper–Pearson bound, then applies the radius to trade admission, lot scaling, and monitoring. This provides an actionable confidence margin that reflects input noise tolerance rather than softmax magnitude.
preview
Neural Networks in Trading: From Transformers to Spiking Neurons (Conclusion)

Neural Networks in Trading: From Transformers to Spiking Neurons (Conclusion)

Neural networks are already changing the way we analyze markets, and new architectures are opening up even more possibilities. In this article, we wrap up our work with the SpikingBrain framework, which opens up new possibilities for us.