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
MQL5 Expert Advisor Builder (Part 1): A Simple Static Template

MQL5 Expert Advisor Builder (Part 1): A Simple Static Template

The article examines an example of a multipurpose trading robot template that is suitable both for creating your own strategies and as a codebase for freelance work. A key feature of the solution is bar-based trading; the code already includes built-in modes for averaging, martingale, and holding positions for extended periods. This material will be most useful to beginners who want to develop their own simple strategies or learn about common trading techniques.
preview
Market Simulation: Unity Is Strength (III)

Market Simulation: Unity Is Strength (III)

In this article, I will present our system for simulating market operations. Although everything is practically finished, there are still a few things to implement and a few changes to make. However, I have to admit that, after everything we've already developed, I'm tired of still being stuck on implementing this system.
preview
Developing a Multi-Currency Expert Advisor (Part 32): Secrets of the Optimization Project Creation Step (II)

Developing a Multi-Currency Expert Advisor (Part 32): Secrets of the Optimization Project Creation Step (II)

The article discusses the parameters of the second stage of the automatic optimization pipeline for a multi-currency Expert Advisor. We analyze the criteria for filtering first-stage passes and the rules for forming groups of trading strategies. The article demonstrates how settings affect optimization results, discusses aspects of process reliability, and examines the balance between selection strictness and having enough candidates for the algorithm.
preview
Python-MetaTrader 5 Strategy Tester (Part 06): MQL5-Style Backtesting for Python Expert Advisors

Python-MetaTrader 5 Strategy Tester (Part 06): MQL5-Style Backtesting for Python Expert Advisors

Code and build Python-based trading robots just like MQL5 Expert Advisors (EAs). In this article, we develop a Python-based replica of the MetaTrader 5 Python package, providing methods that closely resemble those of MetaTrader 5 during simulation. This allows us to backtest Python EAs in a simplified environment, using an approach similar to developing and testing Expert Advisors in MQL5.
preview
Building an Adaptive Fibonacci Volatility Band Indicator in MQL5

Building an Adaptive Fibonacci Volatility Band Indicator in MQL5

We build an adaptive Fibonacci volatility band indicator in MQL5 that centers on a smoothed price (SMMA) and scales band width with a smoothed ATR. The article covers inputs, buffer mapping, ATR handling, and SMMA formulas, then projects configurable Fibonacci ratios with filled zones. Readers get a ready workflow for visualizing volatility expansion/contraction and outlining dynamic support and resistance.
preview
Building AI-Powered Trading Systems in MQL5 (Part 10): A Resolution-Independent Vector Icon System

Building AI-Powered Trading Systems in MQL5 (Part 10): A Resolution-Independent Vector Icon System

We replace the embedded bitmap icons in our MQL5 canvas interface with a resolution-independent vector icon system. A small set of anti-aliased primitives (strokes, discs, rings, rounded rectangles, and polygons) draws every logo and sidebar glyph procedurally, then plugs into the header, sidebar, and theme toggle. You get smaller builds, theme-aware recoloring, and icons that stay sharp at any size.
preview
From Basic to Intermediate: Operator Overloading (IV)

From Basic to Intermediate: Operator Overloading (IV)

In this article, we will take a first step toward showing how to implement operator overloading for the index operator and the assignment operator, while striving to offer a practical and interesting approach for everyone. What we will see here is only part of what I still intend to show, and it is directly related to the overloading of these operators.
preview
Market Replay: Unity Is Strength (II)

Market Replay: Unity Is Strength (II)

Until now, the application being developed as part of this series of articles has focused exclusively on simulating the graphical part. However, to obtain a more complete system in which we can test the Expert Advisor within the replay/simulation service, we also need to simulate the trading server. You'll notice that this simulation will include only the most essential elements. Nevertheless, you, dear reader, will be able to fill in the missing parts. Since these additional components don't affect what I want to show, we already have more than enough to implement what we have in mind.
preview
Neural Networks in Trading: The Adaptive Graph Diffusion Model (SAGDFN)

Neural Networks in Trading: The Adaptive Graph Diffusion Model (SAGDFN)

In this article, we explore the architecture of SAGDFN — a modern framework capable of transforming the approach to processing spatiotemporal data. It preserves key information even in complex graphs while reducing computational costs.
preview
How to Use Finite Differences for Price Forecasting

How to Use Finite Differences for Price Forecasting

The article examines the practical application of finite differences in trading: types of differences, their relationship to price dynamics, and the binomial transform for noise filtering. The rules for encoding patterns based on difference levels and the application of these patterns to forecasting are described. This section presents naive, adaptive, and probabilistic approaches that help smooth time series, identify recurring patterns, and estimate future movements.
preview
LLM-Based Trading Agent with Embedded Top Trader Philosophy

LLM-Based Trading Agent with Embedded Top Trader Philosophy

The article provides a critical analysis of an LLM strategy in which forecasting the direction is separated from trading decisions, and demonstrates why this leads to a disconnect between metrics and PnL. We will describe procedures for dataset balancing, feature engineering, prompt and response preparation, fine-tuning configuration in Ollama, and reliable parsing. Backtesting and forward testing reveal systematic degradation. The practical conclusion is that the problem must be formulated as a direct optimization of trading outcomes.
preview
Developing a Reusable Dynamic Volatility Trailing Stop Engine in MQL5

Developing a Reusable Dynamic Volatility Trailing Stop Engine in MQL5

This article presents a modular, object-oriented volatility trailing stop engine for MQL5 packaged as a reusable include class, it calculates dynamic stop-loss levels using a True Range average filter on closed bars, supports step-based trailing, includes a visual diagnostic indicator, and provides an Expert Advisor execution template.
preview
From Basic to Intermediate: Operator Overloading (III)

From Basic to Intermediate: Operator Overloading (III)

In this article, we will examine how to implement overloading for both logical operators and comparison operators. This requires a certain amount of caution and a fair amount of attention. Even a minor oversight when implementing the overloading of these operators can render the entire code completely unusable. If any problems arise in the overloading, the entire database created from the results generated by the code will have to be either discarded completely or, at the very least, reviewed in full.
preview
Market Replay: Unity Is Strength (I)

Market Replay: Unity Is Strength (I)

We're entering the home stretch. The development of the replay/simulation system is nearly complete. Of course, we still have a few things left to finish, but compared to everything we've already done, completing what's left won't be difficult. However, it is essential to fully absorb and understand everything covered in this article. So I hope you enjoy reading this and, above all, that you enjoy this final stage of the journey.
preview
Building a Session Performance Analytics Dashboard in MQL5

Building a Session Performance Analytics Dashboard in MQL5

This article builds an MQL5 dashboard that classifies closed deals into Sydney, Tokyo, London, and New York trading sessions by UTC close time. It computes per-session P&L, win rate, and average hold time, then renders the results as a persistent CCanvas bar chart with an account-wide summary row, alongside an Experts tab summary table. A verification script confirms the classification and metrics logic behaves correctly.
preview
Defining your Edge (Part 6): Harnessing Fourier Transform and a Spiking Neural Network in an Expert Advisor

Defining your Edge (Part 6): Harnessing Fourier Transform and a Spiking Neural Network in an Expert Advisor

Article revisits Trading Robot that merged Discrete Fourier Transform with Leaky Integrate-and-Fire Spiking Neural Network. Evaluation is made over the seven operating modes with different symbols, timeframes, and test windows. We use two-thirds of the test window to optimize while the one-third does a forward walk run. This study tries to detail parameter interactions, input scaling, gating effects, and outlines practical checks that include rolling windows, frozen inputs, and others. The goal remains identifying settings worth further testing or paper trading.
preview
From Basic to Intermediate: Operator Overloading (II)

From Basic to Intermediate: Operator Overloading (II)

At first, this article may seem rather confusing because of the material I'm going to cover in it. Nevertheless, I've tried to explain everything as simply and clearly as possible. I hope you'll understand what I'm about to show you here, and that it will come in handy someday.
preview
Market Simulation: Position View (XIX)

Market Simulation: Position View (XIX)

One of the issues that bothered me the most was that the `C_ElementsTrade` class contains code for accessing positions. Don't take this as a mistake, because it really isn't one. However, this increases the risk of errors in some of the tasks we will need to handle later. All work on implementing the position indicator was carried out with a view to its use in the replay/simulation service. However, when running in this environment, we will have no access to actual positions. Consequently, any call to the MQL5 library intended to retrieve position data will have no effect in this environment.
preview
Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (Conclusion)

Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (Conclusion)

The article describes a practical implementation of the HimNet framework based on MQL5, ready for integration into automated trading. We demonstrate how heterogeneity-adapted meta-parameters transform the model into a universal tool capable of handling fluctuating volatility.
preview
How to Obtain Synchronized Arrays for Use in Portfolio Trading Algorithms

How to Obtain Synchronized Arrays for Use in Portfolio Trading Algorithms

The article describes a practical approach to synchronizing bars between instruments in a portfolio in MQL5. Classes are provided for loading, storing, and aligning OHLCV data, with options to use an empty bar or carry over values from the previous bar, select a synchronization symbol, and process new bars asynchronously. Examples of use in multi-chart and basket indicators are shown. Readers receive a ready-to-use API for reliable portfolio calculations.
preview
From Option Chain to Risk-Neutral Density: The Market's Own Probability Distribution

From Option Chain to Risk-Neutral Density: The Market's Own Probability Distribution

The article builds an MQL5 indicator that recovers the risk-neutral density from an option chain via the Breeden–Litzenberger identity. Quotes are inverted to implied volatilities, the smile is smoothed and priced back to arbitrage‑free calls, and the second derivative yields the density. The tool reports probabilities above any level, the expected move, skew and kurtosis, and overlays the realized-return distribution for comparison.
preview
Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (Key Components)

Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (Key Components)

In this article, we take a detailed look at the algorithms used to implement the key components of the HimNet framework. We demonstrate how, with a minimal number of trainable components, a high degree of consistency and controllability can be achieved throughout the entire system. The presented implementation is compact and transparent, which makes it easier to adapt to real-world market tasks.
preview
Building a News Filter Engine in MQL5 Using a Local Economic Calendar File

Building a News Filter Engine in MQL5 Using a Local Economic Calendar File

A file-based news filter for MQL5 reads a pre-downloaded Forex Factory CSV from MQL5/Files, avoiding fragile web scraping and paid APIs. It provides a modular CNewsFilter with a quote-aware CSV parser, suffix-robust currency extraction, an inclusive time-window checker with clear block reasons, and chart zones for today's events. A demo EA and assertion tests help you integrate and verify offline filtering around scheduled releases.
preview
Automating Classic Market Methods in MQL5 (Part 8): Ed Seykota's Trend Following System

Automating Classic Market Methods in MQL5 (Part 8): Ed Seykota's Trend Following System

The article presents a full MQL5 implementation of a multi-symbol trend system: dual EMA crossovers for entries, ADX to avoid ranges, ATR to normalize position size, and a heat monitor to cap total portfolio risk. We explain the architecture, calculation details, and entry/exit logic on daily bars. The result is a practical EA template for systematic, risk-aware portfolio trading.
preview
Developing a Multi-Currency Expert Advisor (Part 31): Secrets of the Optimization Project Creation Step (I)

Developing a Multi-Currency Expert Advisor (Part 31): Secrets of the Optimization Project Creation Step (I)

The article examines two practical aspects of the Adwizard-based optimization pipeline: diagnostics and recovery after failures when generating the final Expert Advisor database, as well as preliminary selection of strategy parameter ranges before project creation. It is shown how analyzing the stages/jobs/tasks tables in SQLite and restarting stages based on their statuses help restore the process, while trial optimization narrows the search space, eliminates redundant parameters, and reduces the risk of getting stuck at local maxima.
preview
From Basic to Intermediate: Queues, Lists, and Trees (VIII)

From Basic to Intermediate: Queues, Lists, and Trees (VIII)

In this article, we will examine how to implement a tree balancing algorithm. Here, I will present my own version of an implementation of this algorithm. There are many other algorithms that serve the same purpose. Nevertheless, each of them has its own advantages and disadvantages. You, my dear reader, will need to explore them and find the one that best suits your needs.
preview
Market Simulation: Position View (XVIII)

Market Simulation: Position View (XVIII)

In this article, I have shown—in the clearest possible way—how to modify and improve code capable of handling specific tasks while making as few changes as possible to the existing code. We will add a volume display and, at the same time, ensure that users or traders cannot effectively remove objects created by the position indicator.
preview
Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (HimNet)

Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (HimNet)

We invite you to explore the HimNet framework, which combines the flexibility of spatio-temporal adaptation with high computational efficiency, enabling accurate and stable forecasts for financial time series. The article explains in detail how its key components interact with one another, transforming complex algorithms into a manageable architecture.
preview
Beetle Swarm Optimization (BSO)

Beetle Swarm Optimization (BSO)

We consider a BAS+PSO (BSO) hybrid, where BAS provides a local direction signal and PSO facilitates the exchange of best solutions within the swarm. The article presents a mathematical model, pseudocode, an implementation of the class in MQL5, and test results from a standard test bench. This material allows reproducing the algorithm, configuring its parameters, and understanding how three objective-function evaluations per iteration affect efficiency.
preview
Machine Learning in Pure MQL5 (Part 1): Logistic Regression from Scratch with SGD

Machine Learning in Pure MQL5 (Part 1): Logistic Regression from Scratch with SGD

The series develops machine learning in 100% native MQL5 with no external dependencies. Part 1 delivers logistic regression from first principles: a CLogReg class with standardization, a stable sigmoid, SGD training, and model persistence, plus a script that builds ATR-normalized features, labels the next bar, and tests out-of-sample against a baseline. Readers get a compact include file and a clear template for leakage-free evaluation.
preview
Automating Classic Market Methods in MQL5 (Part 7): The Nicolas Darvas Box System

Automating Classic Market Methods in MQL5 (Part 7): The Nicolas Darvas Box System

This article implements the Darvas Box method as a complete MQL5 Expert Advisor. We code box detection with a three-session hold, volume contraction during consolidation, and volume-confirmed breakouts, plus a staircase pyramid with a shared, rolling stop at the latest box floor. The EA uses a state machine to run box scanning and trade management in parallel, providing a ready-to-compile system with configurable inputs and clear on-chart diagnostics.
preview
From Basic to Intermediate: Queues, Lists, and Trees (VII)

From Basic to Intermediate: Queues, Lists, and Trees (VII)

In this article, we will clearly and simply demonstrate and explain how to remove a node from a tree. This process usually confuses beginners rather than helping them understand how it's done and why it needs to be done that way.
preview
Market Simulation: Position View (XVII)

Market Simulation: Position View (XVII)

In the previous article, we configured the indicator to display the financial result. However, not everyone likes using this display mode. The reasons differ from one trader to another, although in some cases they seem quite reasonable and justified to me. Adapting the code to provide this capability is by no means one of the most difficult tasks. It's actually pretty simple. In this article, we'll look at how to do this.
preview
Designing a Multi-EA Communication Bus Using Named Pipes in MQL5

Designing a Multi-EA Communication Bus Using Named Pipes in MQL5

This article implements a typed message bus over Windows named pipes to replace MetaTrader's untyped GlobalVariables for inter‑EA communication. A broker EA manages the server and registry, serves multiple slave EAs, and responds with a live, per‑symbol‑attributed portfolio risk measure. It also explains the non-blocking accept pattern that preserves terminal responsiveness, and includes a dashboard and a test script.
preview
Defining your Edge (Part 5): Using GARCH Variance and Volatility-Scaled LSTM in an Expert Advisor

Defining your Edge (Part 5): Using GARCH Variance and Volatility-Scaled LSTM in an Expert Advisor

We merge GARCH(1,1) variance projections with ATR plus Bollinger-Bands patterns to form an algorithm that could optionally be used with volatility-scaled LSTM within LSTM Wizard-ready signal class. We cover feature scaling, mode scoring, thresholds, and safety checks. Readers can replicate backtest/forward test results to verify if the recurrent layer gives incremental discrimination over our deterministic baseline.
preview
Neural Networks in Trading: The Temporal Query Model (Conclusion)

Neural Networks in Trading: The Temporal Query Model (Conclusion)

We are pleased to present the final stage of the TQNet framework’s development and testing, where theory meets real-world trading practice. We will move from historical training to a stress test using recent market data, evaluating the model's robustness and accuracy. The final results are not just dry statistics, but also a clear demonstration of the practical value of the proposed approach.
preview
The ZeroMQ Message Transfer Protocol in MQL5: Implementing the REQ/REP pattern

The ZeroMQ Message Transfer Protocol in MQL5: Implementing the REQ/REP pattern

This article presents a native MQL5 implementation of the ZeroMQ Message Transfer Protocol (ZMTP) built on raw MQL5 sockets. It explains the REQ/REP pattern via the CZmqReqSocket class, including framing, handshake, and strict send/receive alternation. A practical pipeline shows an MQL5 script streaming returns to a Python/R server running MS‑GARCH and receiving regime probabilities, enabling integration without DLLs.
preview
Native Isolation Forest for Execution-Quality Anomaly Detection in MQL5

Native Isolation Forest for Execution-Quality Anomaly Detection in MQL5

A step-by-step guide to a native Isolation Forest in MQL5 focused on execution metrics rather than price. It details five features, tree construction and path‑length scoring, rolling‑window training, CSV logging, and FILE_COMMON persistence, all integrated into OnTradeTransaction(). The resulting circuit breaker flags unusual fills in real time and applies controlled responses to stabilize live trading under changing execution conditions.
preview
The MQL5 Standard Library Explorer (Part 16): Building a Regime-Adaptive Expert Advisor

The MQL5 Standard Library Explorer (Part 16): Building a Regime-Adaptive Expert Advisor

We convert the Part 15 decision‑forest classifier into a regime‑adaptive Expert Advisor that decouples statistical inference from trading authority. The EA trains on completed bars, scores each new completed bar, and confirms stable bullish, neutral, or bearish regimes before acting. It then applies spread, ownership, risk, and execution checks to authorize opening, holding, closing, or blocking a position.
preview
MetaTrader 5 as a Kafka Producer: Event-Bus Architecture for Multi-Terminal Signal Fan-Out

MetaTrader 5 as a Kafka Producer: Event-Bus Architecture for Multi-Terminal Signal Fan-Out

The article details a native MQL5 Kafka producer that speaks the wire protocol over raw TCP. It implements RecordBatch v2 encoding, varints, and CRC32C, and adds batching, acks, and retry logic, all without a sidecar or DLL. Use it to publish JSON-structured trading signals from a single terminal to Kafka, where dashboards and other services subscribe independently.