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
Building a Position Sizing Engine in MQL5 with Multiple Risk Models

Building a Position Sizing Engine in MQL5 with Multiple Risk Models

The article presents a position sizing engine for MQL5 Expert Advisors that separates risk policy from lot conversion. Four models—fixed fractional, fixed monetary, ATR-based volatility scaling, and equity-curve scaling—share a CLotConverter that uses OrderCalcProfit() to measure real money per point. A unified CPositionSizer interface exposes CalculateLots(), making model changes straightforward while producing broker-compliant volumes across symbols.
preview
From Novice to Expert: Weekend Gap Size Effect Research Using MQL5 and Python

From Novice to Expert: Weekend Gap Size Effect Research Using MQL5 and Python

The article provides a practical research setup for weekend gap analysis: MQL5 extracts precise pip‑based gaps and tracks fills, while Python performs statistical testing and visualization. You will compute fill rates by gap buckets, model fill probability with logistic regression, and assess time-to-fill via Kaplan–Meier curves. All steps are configurable and reproducible for EURUSD, GBPUSD, USDJPY and beyond.
preview
Building a Future Swing Projection Indicator in MQL5

Building a Future Swing Projection Indicator in MQL5

We implement a Future Swing Projection indicator in MQL5 that analyzes historical swing structure and estimates the next move from recent price behavior. It locates six alternating swing points, measures five completed legs, and uses their average distance to project a target five bars ahead. The indicator draws swing legs, a projection line, ATR‑based support and resistance zones, and a label with the projected price to keep the process rule‑based and reproducible.
preview
Interactive Supply and Demand Zone Manager in MQL5 (Part IV): Trading Supply and Demand Zones

Interactive Supply and Demand Zone Manager in MQL5 (Part IV): Trading Supply and Demand Zones

We extend the supply and demand framework with a strategy layer that converts zone interactions into decisions. Qualified zones pass sequential checks for interaction proximity, approach behavior, higher‑timeframe alignment, and price action before execution is handed to a dedicated trade manager. This architecture improves control, maintainability, and future extensibility without changing the underlying zone engine.
preview
Neural Networks in Trading: An Intelligent Forecast Pipeline (Sparse Mixture of experts)

Neural Networks in Trading: An Intelligent Forecast Pipeline (Sparse Mixture of experts)

We invite you to explore the practical implementation of a sparse mixture of experts block for time series in the OpenCL computing environment. This article provides a step-by-step explanation of how masked multi-window convolution works, as well as how gradient-based training is organized in the presence of multiple information streams.
preview
Elite Crystal Evolution Algorithm (CEO-inspired): Theory

Elite Crystal Evolution Algorithm (CEO-inspired): Theory

A new original population-based algorithm, ECEA, is presented. Inspired by the process of water freezing, it adapts ideas from the Crystal Energy Optimizer (CEO) algorithm, which uses graph-based search, for general optimization problems. The algorithm uses a dynamic elite group, three search strategies, and a periodic diversification mechanism.
preview
Unified Multi-Timeframe Renko: Synthesizing the Market's Temporal Dimensions

Unified Multi-Timeframe Renko: Synthesizing the Market's Temporal Dimensions

The article presents an innovative concept for a multi-timeframe Renko chart that combines signals from four timeframes (M5, M15, H1, H4) into a unified synthetic instrument. The system creates a virtual symbol in MetaTrader 5 by using the EMA of each timeframe to generate a composite signal through three methods: simple average, weighted average, and consensus. The implementation includes ATR-based adaptive brick sizing, real-time operation, and full integration with MetaTrader 5.
preview
Designing a Unified Order Execution Gateway Class in MQL5

Designing a Unified Order Execution Gateway Class in MQL5

This class provides one point of contact for trade operations in MQL5. It rounds and clamps lot sizes, validates SL/TP against the broker's minimum distance, resolves a compatible filling policy, and applies bounded retries for transient retcodes. Calls return a structured CGatewayResult instead of raw retcodes, simplifying error handling and maintenance across strategies.
preview
From Novice to Expert: Systematic Profit Conservation Using Candle Range Theory

From Novice to Expert: Systematic Profit Conservation Using Candle Range Theory

A hybrid exit engine for MQL5 replaces static TPs with CRT-derived structural levels. The CRT_ProfitConserve class secures a partial at the first level and then trails the remaining position by structural anchors rather than fixed pips. The article walks through the class API, essential methods, and example usage in EAs, providing a clear path to embed CRT-based exits into existing strategies.
preview
Automating Trading Strategies in MQL5 (Part 52): The tCISD Model with SSMT and Quarterly Theory

Automating Trading Strategies in MQL5 (Part 52): The tCISD Model with SSMT and Quarterly Theory

We build a tCISD program in MQL5 that pairs Quarterly Theory cycles anchored to New York time with a correlated-symbol SSMT divergence to time reversals. The article shows how to map cycles and quarters, detect the cross-symbol sweep disagreement, and derive the tCISD level whose break confirms the change in delivery. You will get a working entry logic that arms on divergence and executes on a confirmation close or a retest.
preview
Quick Integration of a Large Language Model into MetaTrader 5 (Part I): Building the Model

Quick Integration of a Large Language Model into MetaTrader 5 (Part I): Building the Model

The article explores the revolutionary integration of large language models (LLMs) with the MetaTrader 5 trading platform, where AI does not simply predict prices but makes autonomous trading decisions by analyzing market context much like an experienced trader. The author highlights a fundamental difference between LLMs and classical machine learning models such as CatBoost — the ability to engage in metacognition and self-reflection, which allows the system to learn from its own mistakes and improve its strategy.
preview
The Avellaneda-Stoikov Model: Inventory-Aware Quoting for Two-Sided Strategies

The Avellaneda-Stoikov Model: Inventory-Aware Quoting for Two-Sided Strategies

This article builds the Avellaneda–Stoikov formulas in MQL5, feeds them with rolling estimates of mid-price volatility and a proxy for order-flow intensity, and plots the reservation price with bid and ask in real time. A bar-by-bar simulation contrasts adaptive and fixed quoting under the same fill rules. The result is a tested class, an indicator, and a backtest to improve inventory control in two‑sided strategies.
preview
Price Action Analysis Toolkit Development (Part 77): Building a Searchable Indicator Panel for MetaTrader 5

Price Action Analysis Toolkit Development (Part 77): Building a Searchable Indicator Panel for MetaTrader 5

A modular indicator search system for MetaTrader 5 that replaces manual navigation through built-in indicator categories with a searchable interface. The application integrates an indicator catalog, search engine, chart launcher, and graphical panel, allowing indicators to be located, filtered, and attached to the appropriate chart window from a single interface.
preview
Neural Networks in Trading: An Intelligent Forecast Pipeline (Time-MoE)

Neural Networks in Trading: An Intelligent Forecast Pipeline (Time-MoE)

We invite you to explore the modern Time-MoE framework, which has been adapted for time series forecasting tasks. In this article, we will implement the key components of the architecture step by step, providing explanations and practical examples along the way. This approach will allow you not only to understand how the model works, but also to apply those principles to real-world trading scenarios.
preview
A Team of AI Agents with Profit-Based Rotation: The Evolution of a Living Trading System in MQL5

A Team of AI Agents with Profit-Based Rotation: The Evolution of a Living Trading System in MQL5

Financial management as an ecosystem: Seven AI traders with different personalities and strategies instead of a single algorithm. They compete for capital, learn from their mistakes, and make decisions collectively. The article explains the principles behind the Modern RL Trader system, in which the code possesses consciousness and emotions, creating a living, evolving trading mind.
preview
Feature Engineering for ML (Part 11): Fractal Features in Python

Feature Engineering for ML (Part 11): Fractal Features in Python

The article examines a Williams five‑bar fractal feature pipeline and shows how a centered rolling window creates a true look‑ahead leak. It identifies two additional silent bugs—a hardcoded shift tied to the default n and a volatility threshold that ignores its input—and consolidates fixes under a single leak_safe flag. Readers get leak‑free fractal, level, trend, and signal features, plus guidance on when unshifted columns remain valid for labeling.
preview
Integrating MQL5 with Data Processing Packages (Part 10): Deploying Python AutoML Pipelines for Strategy Testing

Integrating MQL5 with Data Processing Packages (Part 10): Deploying Python AutoML Pipelines for Strategy Testing

This article presents a reproducible MetaTrader 5 workflow: collect history, engineer nine context features, label simulated EMA crossover trades, train with FLAML, and export to ONNX with fixed opset and plain probabilities. The Expert Advisor loads the model natively, mirrors the Python feature contract, and uses a tunable confidence threshold as a trade filter. Readers can swap signals and features to reuse the same pipeline.
preview
Implementing Anchored VWAP Indicator in MQL5: A Step-by-Step Guide

Implementing Anchored VWAP Indicator in MQL5: A Step-by-Step Guide

A step-by-step guide to building an anchored VWAP indicator with an interactive draggable anchor line in MQL5. The article covers the complete implementation, including calculation methodology, session resets, standard deviation bands, and custom visualization. Learn the architectural design decisions behind stateless boundary detection, multi-instance support, and cross-asset volume handling to build a versatile indicator with benchmarking, technical, and analytical capabilities.
preview
Neural Networks in Trading: A Cross-Domain Time Series Forecasting Framework (Conclusion)

Neural Networks in Trading: A Cross-Domain Time Series Forecasting Framework (Conclusion)

The article focuses on the practical implementation of the TimeFound model for time series forecasting. The key stages of implementing the framework's main approaches using MQL5 are examined.
preview
Generating a Per-Symbol Trade Analytics PDF Report from MQL5

Generating a Per-Symbol Trade Analytics PDF Report from MQL5

This article shows how to generate a dependency-free, single-page PDF report in MQL5 using only string assembly and the FILE_BIN API. The script computes per-symbol trade statistics, then renders a labeled table and an equity curve with explicit PDF color and drawing operators. Statistics are calculated in a standalone module, so every value can be verified against synthetic data without relying on a live trading account.
preview
Path Signatures for Lead-Lag Detection

Path Signatures for Lead-Lag Detection

Build a level-2 path-signature engine in pure MQL5 to read the lead-lag ordering between two data streams without choosing a lag and without a linear model. The article delivers a reusable library, an indicator that plots the Levy‑area oscillator, and a simple rule‑based Expert Advisor. Code is cross‑checked against closed‑form cases, and the components are ready to plug into your projects.
preview
Measuring broker execution quality in MQL5: Why your live account doesn't match the backtest

Measuring broker execution quality in MQL5: Why your live account doesn't match the backtest

Live performance often drifts from backtests because of execution friction. We introduce an MQL5 diagnostic EA that records entry and exit slippage, asymmetry, observed spread, requotes, and per-leg latency, using a precise probe mode and an approximate passive mode, and writes every sample to CSV. Use the results to distinguish strategy issues from execution effects across your terminal, network, broker, and liquidity.
preview
MCMC Sampling Methods: The Slice Sampling Algorithm

MCMC Sampling Methods: The Slice Sampling Algorithm

The article examines slice sampling — an adaptive MCMC algorithm that automatically adjusts its sampling parameters. Its effectiveness is demonstrated using Bayesian linear and logistic regression models, and the results are compared with classical frequentist methods.
preview
A Reinforcement Learning System for Algorithmic Trading in MQL5

A Reinforcement Learning System for Algorithmic Trading in MQL5

The article describes the development of a multi-agent machine learning system for algorithmic trading on MetaTrader 5 based on reinforcement learning. The system has a three-tier architecture: memory neurons store experience, agents make independent decisions, and the collective mind combines them through weighted voting. The system is continuously improved through Q-learning, pruning of ineffective neurons, and evolutionary reduction of exploration.
preview
How We Built the Most Powerful Machine Learning-Powered Trading Platform: The Evolution of MQL and MetaTrader Through Archives, Forums, and Releases

How We Built the Most Powerful Machine Learning-Powered Trading Platform: The Evolution of MQL and MetaTrader Through Archives, Forums, and Releases

A technical history of MQL evolution: from the limited MQL and MQL II languages, through procedural MQL4, to object-oriented MQL5 with native compilation, rich APIs, and a full-fledged engineering environment. We show here the key capabilities of the language and its integrations with Python, OpenCL, ONNX, OpenBLAS, databases, DirectX, the agentic AI Assistant, and the Model Context Protocol (MCP), which connects AI systems with the terminal, MetaEditor, market data, trading operations, and development tools. This article examines archival materials on the origins of MetaQuotes and MetaTrader, the launch of MQL4.COM and MQL5.COM, the championships, Algo Forge, and their impact on the ecosystem.
preview
Neural Networks in Trading: A Cross-Domain Time Series Forecasting Framework (TimeFound)

Neural Networks in Trading: A Cross-Domain Time Series Forecasting Framework (TimeFound)

In this article, we build the core of the TimeFound intelligent model step by step, adapting it to real-world time series forecasting tasks. If you are interested in the practical implementation of neural network patching algorithms in MQL5, you have come to the right place.
preview
Exporting Custom Indicator Buffers to CSV for Python Backtesting Pipelines

Exporting Custom Indicator Buffers to CSV for Python Backtesting Pipelines

We build a CSV exporter for MQL5 custom indicators that preserves the exact values seen on the chart. The script creates the indicator handle with iCustom, waits for BarsCalculated, aligns buffers to CopyRates, and writes a locale-safe CSV that pandas loads with parsed dates and NaN for warm-up bars. It addresses compile-time argument limits, jagged-array workarounds, and EMPTY_VALUE handling, enabling reliable Python backtests without re-coding the indicator.
preview
Building a Volume-Based Liquidity Heatmap Indicator in MQL5

Building a Volume-Based Liquidity Heatmap Indicator in MQL5

This article implements an MQL5 Liquidity Heatmap that infers likely liquidation zones from price and volume. It qualifies bars with a rolling volume SMA, computes leverage-based liquidation levels from candle extremes, ranks signals across two volume modes, and manages chart objects (lines and bubbles) that extend until price crosses them, allowing you to highlight potential stop-hunt areas and strengthen structural analysis.
preview
Implementing and Benchmarking Bag-of-SFA-Symbols (BOSS) Against Dynamic Time Warping (DTW)

Implementing and Benchmarking Bag-of-SFA-Symbols (BOSS) Against Dynamic Time Warping (DTW)

This article implements BOSS from scratch in MQL5 and applies it to regime classification: SFA turns windows into words, bags record word frequencies, and an ensemble over window lengths votes on labels. We cover the encoding steps, the BOSS distance, training with auto-generated regime labels, and practical parameters. A BTCUSD benchmark versus DTW shows higher macro accuracy on clean data and markedly faster inference.
preview
Crystal Structure Algorithm (CryStAl)

Crystal Structure Algorithm (CryStAl)

This article presents two versions of the Crystal Structure Algorithm: the original and the modified version. The Crystal Structure Algorithm (CryStAl), published in 2021 and inspired by the physics of crystal structures, was positioned as a parameter-free metaheuristic for global optimization. However, testing revealed a critical problem with the algorithm. A modified version, CryStAlm, is also presented; it addresses the original's key shortcomings.
preview
Building a Divergence System (Part III): The Adaptive SuperTrend EA

Building a Divergence System (Part III): The Adaptive SuperTrend EA

The article implements a self-sufficient Adaptive SuperTrend EA with internal calculations on a selectable timeframe, avoiding external buffers and indicator files. It includes risk-based lot sizing, ATR stops, stepwise RR trailing, optional anti-repainting confirmation, and session control. Practitioners can reuse the structure for consistent new‑bar signal handling and broker‑compliant order validation.
preview
Streaming MetaTrader 5 Trade Events to a Local HTTP Server Using WinINet in MQL5

Streaming MetaTrader 5 Trade Events to a Local HTTP Server Using WinINet in MQL5

An MQL5 implementation sends trade lifecycle events to a local HTTP service through WinINet with a reusable session and per-request handles. The trade callback only enqueues JSON and returns, while a 500 ms timer drains the queue and retries failed posts, preserving order. A three-stage log policy keeps the Experts tab clear during downtime and summarizes recovery.
preview
Mathematical Models in Grid Strategies

Mathematical Models in Grid Strategies

In this article, we will examine the application of mathematics to grid strategies. We will consider the basic principles of the strategy, as well as its advantages and disadvantages. You will learn how to build a trading grid, set optimal parameters, and manage risks effectively.
preview
Building a Modular Fair Value Gap (FVG) Detection Engine in MQL5

Building a Modular Fair Value Gap (FVG) Detection Engine in MQL5

This article introduces a modular Fair Value Gap (FVG) detection engine for MQL5 packaged as a reusable include class, it evaluates imbalance zones on closed bars, applies a Simple True Range average filter to eliminate low-volatility noise, and supports wick-touch and close-through mitigation. A companion diagnostic indicator plots active gaps, and an Expert Advisor template demonstrates automated pullback entries with new-bar execution controls.
preview
Automating Trading Strategies in MQL5 (Part 51): The Bread and Butter Judas Swing Model with Premium and Discount

Automating Trading Strategies in MQL5 (Part 51): The Bread and Butter Judas Swing Model with Premium and Discount

We build a session-based reversal program in MQL5 using the Bread and Butter Judas Swing model. It derives a higher-timeframe daily bias, defines New York kill zones, maps each session's premium and discount from the live range, and requires a sweep before a market structure shift confirms entry. Readers get a ready approach to arm setups only during active sessions and execute in the bias direction with clear, testable rules.
preview
MCMC Sampling Methods — The Metropolis-Hastings Algorithm

MCMC Sampling Methods — The Metropolis-Hastings Algorithm

The Metropolis-Hastings algorithm is a fundamental Markov chain Monte Carlo (MCMC) method that is widely used to approximate posterior distributions in Bayesian inference. This article describes the theoretical foundations of the algorithm, the implementation of the MHSampler class in MQL5, and examples of its application, including an analysis of the resulting samples.
preview
Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Final Part)

Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Final Part)

The Mantis framework transforms complex time series into informative tokens and serves as a reliable foundation for an intelligent trading agent capable of operating in real time.
preview
Kohonen Self-Organizing Maps in an MQL5 Expert Advisor

Kohonen Self-Organizing Maps in an MQL5 Expert Advisor

Kohonen's self-organizing maps transform the chaos of market data into an ordered two-dimensional map, where similar patterns are grouped together. The article demonstrates a complete implementation of a SOM in an MQL5 Expert Advisor with 400 neurons and continuous learning. We break down the Best Matching Unit search algorithm, weight updates using a Gaussian neighborhood function, integration with quantum effects, and the generation of trading signals. The code is open-source, the math is clear, and the results are verifiable.
preview
Artificial Coronary Circulation Algorithm (ACCS)

Artificial Coronary Circulation Algorithm (ACCS)

A metaheuristic algorithm that simulates the growth of coronary arteries in the human heart for optimization problems. It uses the principles of angiogenesis (the growth of new blood vessels), bifurcation (branching), and pruning of weak branches to find optimal solutions in a multidimensional space. Testing its effectiveness across a wide range of tasks yielded unexpected results.
preview
Hierarchical Risk Parity: A Robust Portfolio Allocator and Expert Advisor

Hierarchical Risk Parity: A Robust Portfolio Allocator and Expert Advisor

We implement a Hierarchical Risk Parity allocator in MQL5 as a single class, validate each stage against an independent Python reference, and package it in a rebalancing Expert Advisor. The pipeline covers returns, covariance/correlation, clustering, quasi-diagonalization, and recursive bisection, and contrasts HRP with Markowitz on stressed data. You finish with a verified allocator and an EA ready for basket-level testing.