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
MetaTrader 5 Machine Learning Blueprint (Part 16): Nested CV for Unbiased Evaluation

MetaTrader 5 Machine Learning Blueprint (Part 16): Nested CV for Unbiased Evaluation

The article presents a V-in-V nested cross-validation pipeline for financial data that breaks leakage at three decision points: hyperparameter search, calibration, and final evaluation. A temporal three‑zone split isolates an inner walk‑forward search with the 1‑SE rule from an outer walk‑forward or CPCV evaluation, while OOF isotonic calibration is fitted independently. The resulting UnifiedValidationCalibrator delivers unbiased out‑of‑sample scores and well‑calibrated probabilities for deployment.
preview
MQL5 Wizard Techniques you should know (Part 90): Fenwick Tree Money Management with 1D CNN in MQL5

MQL5 Wizard Techniques you should know (Part 90): Fenwick Tree Money Management with 1D CNN in MQL5

This article implements a Fenwick Tree (Binary Indexed Tree) for volume-aware money management inside an MQL5 Wizard Expert Advisor. We structure cumulative volume in O(log n) and apply four scaling modes—linear, conservative, aggressive, and mean-reversion—optionally gated by a lightweight 1D CNN. Practical tests compare the algorithm alone versus the CNN‑filtered approach to illustrate adaptive lot sizing and risk control under varying volume topologies.
preview
Eagle Strategy (ES)

Eagle Strategy (ES)

Eagle Strategy is an algorithm that mimics the eagle's two-phase hunting strategy: global search via Levy flights using Mantegna method, alternating with intense local exploitation using the firefly algorithm, a mathematically sound approach to balancing exploration and exploitation, and a bioinspired concept that combines two natural phenomena into a single computational method.
preview
The Power of MetaTrader 5: From Step-by-Step Debugging to EX5 Protection in a Unified Environment

The Power of MetaTrader 5: From Step-by-Step Debugging to EX5 Protection in a Unified Environment

This article examines a comprehensive approach to developing trading algorithms: from project setup and logic debugging to protecting the finished product. We will explore MetaEditor's built-in tools, including step-by-step debugging using real ticks, performance profiling, and direct integration with C++ DLLs to speed up calculations. The article also explains how to protect intellectual property using MQL5 Cloud Protector. The application of the described techniques will transform Expert Advisor development from a chaotic search for solutions into a systematic process, significantly reducing the time required to develop a strategy.
preview
Beyond GARCH (Part II): Measuring the Fractal Dimension of Markets

Beyond GARCH (Part II): Measuring the Fractal Dimension of Markets

Building on the partition function analysis from Part 1, this article deepens the theoretical foundation before completing the analytical pipeline. We first give a full treatment of the Hurst exponent: what it measures, what it implies about market memory, and why it matters for the MMAR. This is followed by an intuitive exploration of multifractal spectra and what f(α) reveals about volatility heterogeneity. We then move to implementation: extracting the scaling function τ(q), estimating H via R/S analysis, and fitting the multifractal spectrum across four candidate distributions. By the end, we have the complete parameter set needed to construct the MMAR process in Part 3. Part 2 of an eight-part series.
preview
Determining Fair Exchange Rates Using PPP and IMF Data

Determining Fair Exchange Rates Using PPP and IMF Data

Building a purchasing power parity (PPP)-based exchange rate analysis system using Python. The author developed an algorithm with 5 methods for calculating fair exchange rates using IMF data. A practical guide to fundamental currency analysis, economic data processing, and integration with trading systems. Full code in open source.
preview
RiskGate: Centralized Risk Management for Multiple EAs

RiskGate: Centralized Risk Management for Multiple EAs

Many MetaTrader 5 setups run several EAs on one account, so risk gets fragmented and correlated exposure slips through. The article introduces RiskGate, a centralized Service that evaluates EA intents account‑wide: EAs send a JSON signal, the Service returns approved, lot and reason. You will see the client/server wiring, example rules (daily loss, exposure and correlation caps), unit‑tested handler design, and an EA example. The result is consistent portfolio‑level risk with simpler EAs.
preview
Building an Object-Oriented ONNX Inference Engine in MQL5

Building an Object-Oriented ONNX Inference Engine in MQL5

This article shows how to run Python-trained models natively in MetaTrader 5 via the terminal's ONNX functions. We build an MQL5 class that encapsulates session creation, fixes input/output tensor shapes, applies min-max feature normalization to mirror training, and executes OnnxRun once per bar to protect the CPU, the result is a reliable, maintainable inference path for live charts and the Strategy Tester without sockets or DLLs.
preview
Cross Recurrence Quantification Analysis (CRQA) in MQL5: Building a Complete Analysis Library

Cross Recurrence Quantification Analysis (CRQA) in MQL5: Building a Complete Analysis Library

This article extends the MQL5 RQA library to Cross-Recurrence Quantification Analysis (CRQA) for comparing two time series. We implement dual‑series embedding, cross‑recurrence matrix construction, adapted metrics (CRR, CDET, CLAM, CENTR, and others), and rolling‑window analysis, with optional GPU acceleration via OpenCL. A ready-to-use indicator compares two symbols in real time, supporting timestamp alignment and normalization for practical inter-market analysis.
preview
Integrating MQL5 with Data Processing Packages (Part 9): Entropy-Based Adaptive Volatility

Integrating MQL5 with Data Processing Packages (Part 9): Entropy-Based Adaptive Volatility

This work presents an end-to-end pipeline: collect MetaTrader 5 data, engineer entropy/volatility/trend features, train a PyTorch classifier, and expose predictions through a Flask API. An MQL5 EA posts rolling prices each tick, receives probability and regime, and applies adaptive position sizing and stop distances. The result is a clear recipe for integrating ML inference with MetaTrader 5.
preview
MQL5 Wizard Techniques you should know (Part 89): Using Bitwise Vectorization with Perceptron Classifiers

MQL5 Wizard Techniques you should know (Part 89): Using Bitwise Vectorization with Perceptron Classifiers

This article presents a custom MQL5 signal class, CSignalBitwisePerceptron, for ultra-lightweight entry logic. It packs 64 bars into a single uint64 via bitwise vectorization and evaluates them with a perceptron that sums weights only for active bits. A two-gate flow (algorithmic hash map plus neural threshold) minimizes array iteration and heavy math. Readers get a practical template to cut latency and refine entry validation.
preview
Building AI-Powered Trading Systems in MQL5 (Part 9): Creating an AI Signal Dispatcher

Building AI-Powered Trading Systems in MQL5 (Part 9): Creating an AI Signal Dispatcher

We turn the MQL5 AI trading assistant into a dispatch-driven system that routes seven trading actions through a single central dispatcher. A line-based key-value protocol constrains AI output, while each action maps to market or pending orders and instrument-aware stop levels. A canvas-based UI with a custom prompt editor and pixel-accurate text fitting makes signals consistent, auditable, and ready to render on the chart
preview
Beyond GARCH (Part I): Mandelbrot's MMAR versus Engle's GARCH

Beyond GARCH (Part I): Mandelbrot's MMAR versus Engle's GARCH

This article starts the MMAR pipeline on EURUSD M5 data. We load market data via the MetaTrader5 Python API and run partition-function analysis with non-overlapping intervals to test for multifractal scaling. The result is an evidence-based decision on fractality, a prerequisite for building MMAR and for choosing whether to proceed beyond GARCH.
preview
Position Management: Safe Pyramiding with a Unified Stop in MQL5

Position Management: Safe Pyramiding with a Unified Stop in MQL5

This article presents CPyramidEngine, a reusable MQL5 class that adds disciplined pyramiding to any Expert Advisor with about six lines of integration. The engine enforces three constraints: strictly decreasing lot sizes, a single unified stop that advances after each add-on, and broker-level validation of every modification. It explains common failure modes in naive implementations and shows how to keep total account risk quantifiable and controlled as positions are added.
preview
Downloading International Monetary Fund Data Using Python

Downloading International Monetary Fund Data Using Python

Downloading international monetary fund data in Python: Mining IMF data for use in macroeconomic currency strategies. How can macroeconomics help an ordinary and an algorithmic trader?
preview
MQL5 Trading Tools (Part 31): Creating an Interactive Tools Palette in MQL5

MQL5 Trading Tools (Part 31): Creating an Interactive Tools Palette in MQL5

We turn the Tools Palette sidebar from a static shell into an interactive MQL5 system. The article implements flyout menus per category, a chart event handler, a multi-click drawing engine (one-, two-, and three-click tools), and mouse interactions including drag, bottom-edge resize, scrolling, hover states, and live theme toggling. You will be able to select a tool and place chart objects directly from the palette for analysis
preview
Adaptive Malaysian Engulfing Indicator (Part 2): Optimized Retest Bar Range

Adaptive Malaysian Engulfing Indicator (Part 2): Optimized Retest Bar Range

The article adds a self-adaptive layer to the Malaysian Engulfing indicator by optimizing the retest bar range with a constrained brute-force search scored by MFE and MAE. It details the data model, helper routines, and an MQL5 implementation that gathers historical setups, computes excursions, and selects the best parameter. Readers learn how to remove manual tuning and run the indicator with context-appropriate settings across symbols and timeframes.
preview
Building a Trade Analytics System (Part 3): Storing MetaTrader 5 Trades in SQLite

Building a Trade Analytics System (Part 3): Storing MetaTrader 5 Trades in SQLite

This article extends a Flask backend to reliably receive, validate, and store closed trade data from MetaTrader 5 using SQLite and Flask‑SQLAlchemy. It implements required‑field checks, timestamp conversion, transaction‑safe persistence, and working retrieval endpoints for all trades and single records, plus a basic summary. The result is a complete data pipeline with local testing that records trades and exposes them through a structured API for further analysis.
preview
Manual Backtesting with On-Chart Buttons in the MetaTrader 5 Strategy Tester

Manual Backtesting with On-Chart Buttons in the MetaTrader 5 Strategy Tester

Learn how to build a manual backtesting EA for MetaTrader 5's visual tester by adding chart buttons with CButton, executing orders through CTrade, and filtering positions with a magic number. The article implements Buy/Sell and Close All controls, configurable lot size and initial SL, and a trailing stop via CPositionInfo. You will also see how to load indicators with tester.tpl to validate ideas faster before automation and narrow optimization ranges.
preview
Biogeography-Based Optimization (BBO)

Biogeography-Based Optimization (BBO)

Biogeography-Based Optimization (BBO) is an elegant global optimization method inspired by natural processes of species migration between islands within archipelagos. The algorithm is based on a simple yet powerful idea: high-quality solutions actively share their characteristics, while low-quality ones actively adopt new features, creating a natural flow of information from the best solutions to the worst. A unique adaptive mutation operator provides an excellent balance between exploration and exploitation. BBO demonstrates high efficiency on a variety of tasks.
preview
Leak-Free Multi-Timeframe Engine with Closed-Bar Reads in MQL5

Leak-Free Multi-Timeframe Engine with Closed-Bar Reads in MQL5

The article presents two systematic pitfalls in MQL5 multi‑timeframe work: indicator handle leaks that exhausted resources and repainting from reading the forming bar (index 0). It introduces MTFEngine.mqh, a unified include that creates and tracks handles in one place and defaults all reads to closed bars (index 1). A D1–H4–H1 example shows how this approach keeps signals technically correct and consistent with charts.
preview
From Matrices to Models: How to Build an ML Pipeline in MQL5 and Export It to ONNX

From Matrices to Models: How to Build an ML Pipeline in MQL5 and Export It to ONNX

The article describes the arrangement of a coordinated ML pipeline in MetaTrader 5 with separation of roles: Python trains and exports the model to ONNX, MQL5 reproduces normalization and PCA via matrix/vector and performs inference. This approach makes the model's inputs stable and verifiable, and the MetaTrader 5 strategy tester provides metrics for analyzing the system behavior.
preview
Gaussian Processes in Machine Learning: Regression Model in MQL5

Gaussian Processes in Machine Learning: Regression Model in MQL5

We will review the basics of Gaussian processes (GP) as a probabilistic machine learning model and demonstrate its application to regression problems using synthetic data.
preview
Feature Engineering for ML (Part 3): Session-Aware Time Features for Forex Machine Learning

Feature Engineering for ML (Part 3): Session-Aware Time Features for Forex Machine Learning

The article addresses the loss of temporal information in ML pipelines by encoding periodic time variables with Fourier harmonics and adding forex session structure. It implements session and overlap flags, lagged session volatility, and calendar effects, then prunes features by timeframe. The get time features function returns an index‑aligned, ML‑ready set of time features suitable for integration with price‑based signals.
preview
Creating an EMA Crossover Forward Simulation Indicator in MQL5

Creating an EMA Crossover Forward Simulation Indicator in MQL5

A custom forward simulation engine detects fast/slow EMA crossovers and immediately projects synthetic candles ahead of the signal bar. It generates bodies and wicks using controlled logic, draws them with chart objects, and refreshes on every new signal or anchor change. You get a clear forward-looking view to test timing, visualize scenarios, and manage invalidation on the chart.
preview
Encoding Candlestick Patterns (Part 1): An Alphabetical System for Signal Detection

Encoding Candlestick Patterns (Part 1): An Alphabetical System for Signal Detection

We present a rule‑based alphabet for candlestick price action that maps measurable shape and direction to letter codes (A/a, H/h, E/e, G/g, D). The article shows an MQL5 implementation: classifying candles, building two‑bar sequences via permutations, and scanning charts with an indicator and alerts. Readers gain a practical template for objective pattern detection and systematic testing.
preview
Exploring Conformal Forecasting of Financial Time Series

Exploring Conformal Forecasting of Financial Time Series

In this article, we will consider conformal predictions and the MAPIE library that implements them. This approach is one of the most modern ones in machine learning and allows us to focus on risk management for existing diverse machine learning models. Conformal predictions, by themselves, are not a way to find patterns in data. They only determine the degree of confidence of existing models in predicting specific examples and allow filtering for reliable predictions.
preview
Adaptive Malaysian Engulfing Indicator (Part 1): Pattern Detection and Retest Validation

Adaptive Malaysian Engulfing Indicator (Part 1): Pattern Detection and Retest Validation

Implement the Malaysian Engulfing concept in MQL5 with two coordinated indicators. One applies strict, body‑based engulfing rules for precise pattern detection; the other uses a state-driven model to monitor what follows—pullbacks and timed retests—directly on the chart. The result is a repeatable, rule-based workflow that replaces visual guesswork with programmable logic.
preview
Creating a Custom Tick Chart in MQL5

Creating a Custom Tick Chart in MQL5

Learn how to implement a tick-based chart in MQL5 where each bar is built from a fixed number of ticks instead of time. The article covers creating and configuring a custom symbol, capturing real-time ticks, forming OHLC values, and pushing data with CustomRatesUpdate. This approach produces activity-driven candles that better reflect market intensity and short-term momentum for precise intraday analysis.
preview
The MQL5 Standard Library Explorer (Part 11): How to Build a Matrix-Based Market Structure Indicator in MQL5

The MQL5 Standard Library Explorer (Part 11): How to Build a Matrix-Based Market Structure Indicator in MQL5

Learn to engineer an MQL5 indicator that converts trend, momentum, and volatility into a single raw score using a matrix.mqh (ALGLIB). The article covers a separate‑window oscillator to validate the core mathematics, then a main‑chart indicator that plots non‑repainting buy/sell arrows when the score crosses user‑defined thresholds. An optional long‑term EMA filter, a minimum‑bar cooldown, and built‑in alerts make the tool practical for live trading.
preview
MetaTrader 5 Machine Learning Blueprint (Part 15): How to Calibrate Profit-Taking and Stop-Loss Targets from Synthetic Data

MetaTrader 5 Machine Learning Blueprint (Part 15): How to Calibrate Profit-Taking and Stop-Loss Targets from Synthetic Data

This article applies the Optimal Trading Rule from AFML Chapter 13 to set profit targets and stop-losses without in-sample calibration. We model post-entry P&L with a discrete Ornstein–Uhlenbeck process, run a 100,000-path search, and implement Python, multiprocessing, and a Numba @njit parallel kernel (242× faster). The result is an optimal (PT, SL) under three forecast specifications, constrained by the prop-firm daily loss limit.
preview
Event-Driven Architecture in MQL5: How to Turn an Expert Advisor into a Full-Fledged Trading System

Event-Driven Architecture in MQL5: How to Turn an Expert Advisor into a Full-Fledged Trading System

The article is dedicated to the event-driven architecture in MQL5 and describes the transition from the monolithic OnTick model to distributed processing. We will consider predefined and custom events, services and messaging between programs, as well as common architectural errors. A practical example demonstrates how to organize interactions between indicators and an EA to reduce load, improve readability, and simplify maintenance.
preview
MetaTrader 5 and the MQL5 Economic Calendar: How to Turn News into a Reproducible Trading System

MetaTrader 5 and the MQL5 Economic Calendar: How to Turn News into a Reproducible Trading System

The article presents a systematic approach to news trading in MetaTrader 5 using the built-in economic calendar: data structure, API functions, time synchronization rules, and event filtering. Methods of caching and incremental updating without overloading the server are described. The article also provides a working mechanism for exporting history to an .EX5 resource for deterministic testing using the same algorithm.
preview
MetaTrader 5 Machine Learning Blueprint (Part 14): Transaction Cost Modeling for Triple-Barrier Labels in MQL5

MetaTrader 5 Machine Learning Blueprint (Part 14): Transaction Cost Modeling for Triple-Barrier Labels in MQL5

The article replaces hardcoded cost assumptions in triple-barrier labeling with measured inputs. An MQL5 script captures spread distribution, swap rates, and symbol metadata from your broker, and a Python model converts them into a broker-calibrated min ret you can pass to get events. Labels then reflect the actual round-trip friction for your instrument and holding period.
preview
MQL5 Trading Tools (Part 30): Class-Based Tool Palette Sidebar

MQL5 Trading Tools (Part 30): Class-Based Tool Palette Sidebar

We refactor the Tools Palette from a flat, function-based panel into a modular, class-driven sidebar in MQL5. The design introduces supersampled canvas rendering for anti-aliased shapes, theme control, a category registry, snap alignment, and selective corner rounding. The result is a reusable, scalable sidebar foundation that you can extend with tool selection, dragging, and fly-out menus in future steps.
preview
Market Microstructure in MQL5: Robust Foundation (Part 1)

Market Microstructure in MQL5: Robust Foundation (Part 1)

This article builds the foundation layer of a twelve-part MQL5 market microstructure toolkit. It implements guarded math helpers (SafeDivide, SafeLog, SafeSqrt, SafeExp, SafeTanh), robust data validation (ValidateSymbolV2, SafeCopyClose), trimmed statistical estimators (robust mean var), a linear regression slope, shared structs, and an FFT. You compile a single include file that hardens indicators and expert advisors against silent numerical failures and standardizes data flow for later parts.
preview
Three MACD Filters on US_TECH100: Five Years of Broker Data

Three MACD Filters on US_TECH100: Five Years of Broker Data

This article tests three common filters on a standard MACD crossover for US_TECH100 H1 using five years of broker-native data. Filters are layered incrementally: regime, higher timeframe (HTF) alignment, and US session timing, to isolate each one's marginal impact. Results show session timing contributes far more than indicator refinements, while regime and HTF add little on their own. Includes a reproducible MQL5 regime classifier.
preview
Beyond the Clock (Part 1): Building Activity and Imbalance Bars in Python and MQL5

Beyond the Clock (Part 1): Building Activity and Imbalance Bars in Python and MQL5

The article replaces clock-based sampling with López de Prado's alternative bar types and provides two aligned implementations: a unified Python module for batch tick histories and an object‑oriented MQL5 library for live EAs. It covers Parquet/Dask infrastructure, data cleaning, and a single API. Practical issues are solved explicitly: zero‑tick time‑bar filtering, imbalance threshold initialization, EWM state persistence, and parity between Python and MQL5 outputs.
preview
From Novice to Expert: Creating an MTF CRT Overlay Indicator in MQL5

From Novice to Expert: Creating an MTF CRT Overlay Indicator in MQL5

Higher-timeframe CRT ranges are informative, yet traders often execute on lower timeframes without that context. We implement an MQL5 indicator that reads higher-timeframe OHLC, projects the full candle range, body, and wicks onto the active lower-timeframe chart, and marks entries, stops, and targets. This improves situational awareness and removes the need to switch windows.
preview
Engineering Trading Discipline into Code (Part 5): Account-Level Risk Enforcement in MQL5

Engineering Trading Discipline into Code (Part 5): Account-Level Risk Enforcement in MQL5

We introduce an MQL5 discipline engine that enforces risk consistently at the account level. It continuously scans positions from any source, validates SL/TP, equity-based exposure, and target R:R, and automatically corrects deviations by setting levels or adjusting volume. The result is uniform risk structure across manual and EA trades, supported by on-chart feedback and mode-based control.