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
Trading with the MQL5 Economic Calendar (Part 12): SQLite Storage and Deduplication

Trading with the MQL5 Economic Calendar (Part 12): SQLite Storage and Deduplication

In this article, we replace the embedded CSV snapshot with a SQLite layer that persists calendar events and triggered trade IDs across restarts. The database lives in the common terminal folder and is shared by live charts and the strategy tester, so both modes read the same data without recompiling. An on-demand downloader with a canvas progress bar fetches history from the calendar API and stores it for offline reuse.
preview
Price Action Analysis Toolkit Development (Part 70): Turning Flag Pattern Signals into Automated Trade Execution

Price Action Analysis Toolkit Development (Part 70): Turning Flag Pattern Signals into Automated Trade Execution

The article defines a buffer-based signal architecture for flag breakouts and an EA that consumes it. Breakout arrows and pole height are written to dedicated buffers only after confirmation, preventing repainting and ambiguity. The EA polls buffers with CopyBuffer(), validates signals using configurable filters, and executes trades with fixed or dynamic SL/TP.
preview
Publish Your Article Code to MQL5 Algo Forge in 10 Minutes: A Step-by-Step Guide

Publish Your Article Code to MQL5 Algo Forge in 10 Minutes: A Step-by-Step Guide

The article provides a step-by-step guide on how to migrate code from a published project into a fully-fledged MQL5 Algo Forge project. You will set up the environment and authentication in MetaEditor, create a project in Shared Projects, select the type, arrange the files, add README.md, check the encoding and build, commit the changes to Git, and open the repository publicly. The article helps to build a working structure and preserve version history for the convenience of readers.
preview
MQL5 Wizard Techniques you should know (Part 91): Using Skip Lists and a Hopfield Network in a Custom Trailing Class

MQL5 Wizard Techniques you should know (Part 91): Using Skip Lists and a Hopfield Network in a Custom Trailing Class

For our next Exploration on notions that are testable with the MQL5 Wizard we examine if Skip Lists and the Hopfield Network can give us a profit-guarding trailing strategy. Trailing Stop Management, as already argued, can be overlooked in most trading systems at the expense of Entry Signals or even Money Management. Trailing stops can make all the difference in certain situations such as trending markets, and thus we test this out with GBP USD.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part IV): Remote voice trading

Overcoming Accessibility Problems in MQL5 Trading Tools (Part IV): Remote voice trading

Learn a practical way to execute MetaTrader 5 trades from Telegram voice notes using a Python middleware and an MQL5 EA acting as an HTTP client. The article covers architecture, WebRequest polling, in-memory queuing, JSON parsing with null-terminator stripping, and a constrained command grammar with a 0.001-lot default. You will configure the environment and validate round‑trip latency suitable for mobile data connections.
preview
Trading with the MQL5 Economic Calendar (Part 11): Modular Canvas News Dashboard

Trading with the MQL5 Economic Calendar (Part 11): Modular Canvas News Dashboard

We rebuild the MQL5 Economic Calendar dashboard from a monolithic object-based panel into a modular canvas-based system split across four files. The update adds a dual light and dark theme, collapsible day groups, a resizable layout with pixel-based scrolling, revised value markers, and a live countdown with toast notifications. A candidate event cache and a fast-path timer that repaints only changed cells improve responsiveness and make the codebase easier to extend.
preview
Feature Engineering for ML (Part 4): Implementing Time Features in MQL5

Feature Engineering for ML (Part 4): Implementing Time Features in MQL5

Applying Python session boundaries to MQL5 broker timestamps misclassifies session membership by two to three hours on any non-UTC broker, corrupting session flags across the full backtest history. We implement CTimeFeatures.mqh, containing CRingBuffer and CTimeFeatures, with three EA-facing methods: Initialize (UTC offset capture and frequency gate configuration), Update (log return push to session-conditional ring buffers), and Calculate (cyclical encoding, session flags, and session volatility). The output is a flat double array drop-compatible with Python's get_time_features for sub-hourly, hourly, and daily timeframes.
preview
3D Visualization Without External Libraries: How MetaTrader 5 Reveals Optimization Results via MQL5 + DX11

3D Visualization Without External Libraries: How MetaTrader 5 Reveals Optimization Results via MQL5 + DX11

The article describes the practical application of DirectX 11 and built-in MQL5 tools for creating 3D visualizations and interactive interfaces in MetaTrader 5. The focus is on cognitive efficiency - the ability of 3D charts and guided scenes to help in understanding optimization data, liquidity clusters, and multi-dimensional trading scenarios. The basics of the DX pipeline, working with shaders, binding mouse and keyboard events, and objective technological limitations are discussed in detail. The article is intended for MQL5 developers and algorithmic traders who are ready to transform strategy metrics into understandable 3D analytical landscapes, where the visual layer accelerates decision-making.
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.