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
Engineering Trading Discipline into Code (Part 6): Building a Unified Discipline Framework in MQL5

Engineering Trading Discipline into Code (Part 6): Building a Unified Discipline Framework in MQL5

The article introduces a unified MQL5 discipline framework that consolidates the symbol whitelist, trading‑hours and news filters, and daily trade‑limit modules under CDisciplineEngine.mqh. It explains centralized trade validation and state synchronization shared by a chart dashboard and an enforcement Expert Advisor. Readers learn how to authorize orders through a single gate, monitor permissions in real time, and automatically enforce rules across the terminal.
preview
Market Microstructure in MQL5: Measuring long memory in MQL5 with Hurst estimators (Part 2)

Market Microstructure in MQL5: Measuring long memory in MQL5 with Hurst estimators (Part 2)

Part 2 focuses on practical long-memory detection for intraday data. Three complementary Hurst estimators are implemented and combined into a confidence‑weighted composite, with confidence tied to valid regression scales. The final H and confidence populate the shared analysis struct, enabling indicators to act only when H departs from the neutral 0.40–0.60 band and to select trend‑following above 0.60 or mean‑reversion below 0.40.
preview
Building a Trade Analytics System (Part 4): Summary Metrics and Dashboard

Building a Trade Analytics System (Part 4): Summary Metrics and Dashboard

This article extends the existing Flask backend to compute performance analytics from stored MetaTrader 5 closed trades and deliver them as both JSON and a simple web view. It calculates total trades, total profit, win rate, average profit, and trade duration metrics, returning JSON at /api/v1/analytics/summary and rendering a dashboard at /api/v1. The result provides a quick, consistent way to review trading performance from persisted SQLite records.
preview
Evaluating the Quality of Forex Spread Trading Based on Seasonal Factors in MetaTrader 5

Evaluating the Quality of Forex Spread Trading Based on Seasonal Factors in MetaTrader 5

The article examines the quality of a seasonal trading approach on a daily timeframe, both for individual symbols and for spreads. Particular attention is paid to identifying recurring monthly cycles and the possibilities of their application in trading within the current year.
preview
From "Best Pass" to Robust Solutions: Exploring the Optimization Surface in MetaTrader 5

From "Best Pass" to Robust Solutions: Exploring the Optimization Surface in MetaTrader 5

The article examines an engineering approach to optimizing an Expert Advisor in MetaTrader 5: from collecting custom metrics through Optimization Frames to parameter surface analysis. A simple event-driven EMA/RSI model demonstrates CSV export, smoothing, and local stability assessment in Python. The goal is to find stable areas of configurations and validate them with forward optimization for reliable implementation.
preview
MetaTrader 5: Build a Market to Suit Your Strategy — Renko/Range/Volume, Synthetics, and Stress Tests on Custom Symbols

MetaTrader 5: Build a Market to Suit Your Strategy — Renko/Range/Volume, Synthetics, and Stress Tests on Custom Symbols

In this article, we demonstrate how to use API of the MetaTrader 5 custom symbols to transform your terminal into a data constructor for generating timeless Renko, Range, and Equal-Volume charts and assembling synthetic instruments. We will analyze tick aggregation and history modification for stress tests (spread widening, stop level changes) taking into account platform limitations. Besides, you will get some practice of handling CiCustomSymbol and routing orders to a real symbol through the CustomOrder wrapper with ready-made code fragments.
preview
MQL5 Trading Tools (Part 32): Crosshair, Magnifier, and Measure Mode

MQL5 Trading Tools (Part 32): Crosshair, Magnifier, and Measure Mode

In this article, we extend the Tools Palette with a precision crosshair for MQL5 charts: reticle tick marks, full-width and full-height lines with axis labels, and a circular magnifier that renders zoomed candles. A double-click measure mode adds anchor markers, a diagonal connector, and a floating label with bars, pips, and price difference. Implementation details include a crosshair manager, eleven canvas layers, Bresenham line drawing, and theme-aware behavior that hides near the sidebar and fly out.
preview
The MQL5 Standard Library Explorer (Part 12): Multi-Timeframe Composite-Score Dashboard

The MQL5 Standard Library Explorer (Part 12): Multi-Timeframe Composite-Score Dashboard

The article implements CMultiTimeframeMatrix, a reusable dashboard that maps symbols vs. timeframes and displays a numeric, colour‑coded score. The score combines trend, momentum, and volatility, updates by timer, and respects performance constraints. You will learn how to build the UI with CAppDialog/CLabel, compute metrics via CMatrixDouble, and embed the component into a thin EA for a consistent, real-time overview.
preview
Beyond GARCH (Part III): Building the MMAR and the Verdict

Beyond GARCH (Part III): Building the MMAR and the Verdict

With the multifractal parameters from Part 2 in hand, this article builds the full MMAR process. We construct the multiplicative cascade for trading time, generate Fractional Brownian Motion via Davies-Harte FFT, and combine both into X(t) = B_H[theta(t)]. A 100-path Monte Carlo simulation produces the volatility forecast, which we then pit against GARCH on the same EURUSD M5 data. Does Mandelbrot's fractal architecture outforecast Engle's conditional variance framework? Part 3 of a eight-part series leading to a native MQL5 library and Expert Advisor.
preview
Price Action Analysis Toolkit Development (Part 69): Flag Pattern Detection in MQL5

Price Action Analysis Toolkit Development (Part 69): Flag Pattern Detection in MQL5

This article shows how to convert subjective flag recognition into reproducible MQL5 logic for live charts. It combines ATR-normalized pole strength, retracement limits, consolidation structure checks, breakout confirmation, and overlap control. Readers gain a workable approach that renders adaptive channels and zones, updates active setups efficiently, and provides optional alerts for newly confirmed patterns.
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.