Articles with examples of trading robots developed in MQL5

icon

An Expert Advisor is the 'pinnacle' of programming and the desired goal of every automated trading developer. Read the articles in this section to create your own trading robot. By following the described steps you will learn how to create, debug and test automated trading systems.

The articles not only teach MQL5 programming, but also show how to implement trading ideas and techniques. You will learn how to program a trailing stop, how to apply money management, how to get the indicator values, and much more.

Add a new article
latest | best
preview
MQL5 Trading Tools (Part 29): Step-by-Step Butterfly Animation on Canvas

MQL5 Trading Tools (Part 29): Step-by-Step Butterfly Animation on Canvas

In this article, we expand our butterfly animation program with a four-stage animation pipeline: sequential curve drawing, smooth wing fill fading, detailed body rendering, and continuous flight. We implement a timer-driven state machine, four oscillators for wing flapping, vertical bobbing, horizontal sway, and tilt, as well as a neon glow around the wing outlines and a cyclical color change based on hue. You will learn how to structure these effects on the MetaTrader 5 canvas for clean and controlled playback.
preview
CAPM Model Indicator for the Forex Market

CAPM Model Indicator for the Forex Market

Adaptation of the classical CAPM model for the Forex currency market in MQL5. The indicator calculates expected return and risk premium based on historical volatility. The indicators rise at peaks and bottoms, reflecting the fundamental principles of pricing. Practical application for counter-trend and trend-following strategies, taking into account the dynamics of the risk-reward ratio in real time. The article includes mathematical apparatus and technical implementation.
preview
Trading Options Without Options (Part 1): Basic Theory and Emulation Through Underlying Assets

Trading Options Without Options (Part 1): Basic Theory and Emulation Through Underlying Assets

The article describes a variant of options emulation through an underlying asset implemented in the MQL5 programming language. The pros and cons of the chosen approach are compared with real exchange options using the example of the FORTS futures market of the MOEX Moscow exchange and the Bybit crypto exchange.
preview
File-Based Versioning of EA Parameters in MQL5

File-Based Versioning of EA Parameters in MQL5

This article explains how to implement parameter versioning in MQL5 using binary files and packed structures. It shows how to write and read fixed-size records with FileWriteStruct and FileReadStruct in FILE_BIN mode, including version numbers, timestamps, and a checksum. You will also see how to detect changes via checksums, append records safely, and load the latest configuration without overwriting prior settings.
preview
Building a Trade Analytics System (Part 2): How to Capture Closed Trades and Send JSON in MQL5

Building a Trade Analytics System (Part 2): How to Capture Closed Trades and Send JSON in MQL5

We build a lightweight bridge that captures closed trades in MetaTrader 5 and sends them to an external backend over HTTP as JSON. It uses OnTradeTransaction for event detection, reads details from deal history, assembles a JSON payload, and posts it via WebRequest. A local Flask API is used to test the flow, delivering a working path to move trade data outside the terminal.
preview
Automating Trading Strategies in MQL5 (Part 48): Order Blocks, Inducement, Break of Structure

Automating Trading Strategies in MQL5 (Part 48): Order Blocks, Inducement, Break of Structure

We implement an MQL5 expert advisor that detects order blocks formed after consolidation breakouts and confirms them with fair value gaps. Each zone is validated by a break of structure and a preceding inducement, then filtered by the higher-timeframe trend. The program adds mitigation tracking, risk-based lot sizing, and two trailing stop modes, providing clear on-chart visuals and backtest-ready trade execution logic.
preview
Neural Networks in Trading: Detecting Anomalies in the Frequency Domain (CATCH)

Neural Networks in Trading: Detecting Anomalies in the Frequency Domain (CATCH)

The CATCH framework combines Fourier transform and frequency patching to accurately identify market anomalies beyond the reach of traditional methods. Let us examine how this approach reveals hidden patterns in financial data.
preview
Neural Networks in Trading: Adaptive Detection of Market Anomalies (Final Part)

Neural Networks in Trading: Adaptive Detection of Market Anomalies (Final Part)

We continue to build the algorithms that form the basis of the DADA framework, which is an advanced tool for detecting anomalies in time series. This approach enables effective distinguishing random fluctuations from significant deviations. Unlike classical methods, DADA dynamically adapts to different data types, choosing the optimal compression level in each specific case.
preview
MQL5 Trading Tools (Part 28): Filling Sweep Polygons for Butterfly Curve in MQL5

MQL5 Trading Tools (Part 28): Filling Sweep Polygons for Butterfly Curve in MQL5

We expand the capabilities of the MetaTrader 5 butterfly curve canvas by adding multi-layered wing fills, vein lines, scale dots, and a full body (abdomen, thorax, head, eyes, antennae). This article implements polygon fills with vertical and radial gradients, as well as filled circles and ellipses, all using supersampling antialiasing. You will also receive reusable MQL5 helper functions and a rendering order that transforms a simple curve into a customizable, detailed chart illustration.
preview
Self-Learning Expert Advisor with a Neural Network Based on a Markov State-Transition Matrix

Self-Learning Expert Advisor with a Neural Network Based on a Markov State-Transition Matrix

Self-training EA with a neural network based on a state matrix. We combine Markov chains with a multilayer neural network MLP developed using the ALGLIB MQL5 library. How can Markov chains and neural networks be combined for Forex forecasting?
preview
Markov Chain-Based Matrix Forecasting Model

Markov Chain-Based Matrix Forecasting Model

We are going to create a matrix forecasting model based on a Markov chain. What are Markov chains, and how can we use a Markov chain for Forex trading?
preview
MQL5 Trading Tools (Part 27): Rendering Parametric Butterfly Curve on Canvas

MQL5 Trading Tools (Part 27): Rendering Parametric Butterfly Curve on Canvas

In this article, we explore the butterfly curve, a parametric mathematical equation, and render it visually on a MQL5 canvas. We build an interactive display with a draggable, resizable canvas window, supersampled curve rendering, gradient backgrounds, and a color-segmented legend. By the end, we have a fully functional visual tool that plots the butterfly curve directly on the MetaTrader 5 chart.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part III): Bidirectional Speech Communication Between a Trader and an Expert Advisor

Overcoming Accessibility Problems in MQL5 Trading Tools (Part III): Bidirectional Speech Communication Between a Trader and an Expert Advisor

Build a local, bidirectional voice interface for MetaTrader 5 using MQL5 WebRequest and two Python services. The article implements offline speech recognition with Vosk, wake‑word detection, an HTTP command endpoint, and a text‑to‑speech server on localhost. You will wire an Expert Advisor that fetches commands, executes trades, and returns spoken confirmations for hands‑free operation.
preview
Applying L1 Trend Filtering in MetaTrader 5

Applying L1 Trend Filtering in MetaTrader 5

This article explores the practical application of L1 trend filtering in MetaTrader 5, covering both its mathematical foundations and usage in MQL5 programs. The L1 filter enables extraction of piecewise-linear trends that preserve essential market structure while reducing price noise. The study analyzes parameter scaling, trend estimation behavior, and integration of the method into algorithmic trading strategies. Experimental results demonstrate how L1 trend filtering can enhance signal stability, trade timing, and overall robustness of trading systems.
preview
Forex Arbitrage Trading: A Matrix Trading System for Return to Fair Value with Risk Control

Forex Arbitrage Trading: A Matrix Trading System for Return to Fair Value with Risk Control

The article contains a detailed description of the cross-rate calculation algorithm, a visualization of the imbalance matrix, and recommendations for optimally setting the MinDiscrepancy and MaxRisk parameters for efficient trading. The system automatically calculates the "fair value" of each currency pair using cross rates, generating buy signals in case of negative deviations and sell signals in case of positive ones.
preview
Building a Volume Bubble Indicator in MQL5 Using Standard Deviation

Building a Volume Bubble Indicator in MQL5 Using Standard Deviation

The article demonstrates how to build a Volume Bubble Indicator in MQL5 that visualizes market activity using statistical normalization. It covers how to work with tick and real volume, compute the mean and standard deviation over a rolling window, and normalize volume values to identify relative strength. You will implement chart objects to display bubbles with dynamic size and color, providing a clear representation of volume intensity directly on the chart.
preview
Predicting Renko Bars with CatBoost AI

Predicting Renko Bars with CatBoost AI

How to use Renko bars with AI? Let's look at Renko trading on Forex with forecast accuracy of up to 59.27%. We will explore the benefits of Renko bars for filtering market noise, learn why volume is more important than price patterns, and how to set the optimal Renko block size for EURUSD. This is a step-by-step guide on integrating CatBoost, Python, and MetaTrader 5 to create your own Renko Forex forecasting system. It is ideal for traders looking to go beyond traditional technical analysis.
preview
Pair Trading: Algorithmic Trading with Auto Optimization Based on Z-Score Differences

Pair Trading: Algorithmic Trading with Auto Optimization Based on Z-Score Differences

In this article, we will explore what pair trading is and how correlation trading works. We will also create an EA for automating pair trading and add the ability to automatically optimize this trading algorithm based on historical data. In addition, as part of the project, we will learn how to calculate the differences between two pairs using the z-score.
preview
Using the MQL5 Economic Calendar for News Filter (Part 3): Surviving Terminal Restarts During News Window

Using the MQL5 Economic Calendar for News Filter (Part 3): Surviving Terminal Restarts During News Window

The article introduces a restart-safe storage model for news-time stop removal. Suspension state and original SL/TP per position are written to terminal global variables, reconstructed on OnInit, and cleaned after restoration. This lets the EA resume an active suspension window after recompiles or restarts and restore stops only when the news window ends.
preview
MQL5 Trading Tools (Part 26): Integrating Frequency Binning, Entropy, and Chi-Square in Visual Analyzer

MQL5 Trading Tools (Part 26): Integrating Frequency Binning, Entropy, and Chi-Square in Visual Analyzer

In this article, we develop a frequency analysis tool in MQL5 that bins price data into histograms, computes entropy for information content, and applies chi-square tests for distribution goodness-of-fit, with interactive logs and statistical panels for market insights. We integrate per-bar or per-tick computation modes, supersampled rendering for smooth visuals, and draggable/resizable canvases with auto-scrolling logs to enhance usability in trading analysis.
preview
Neuro-Structural Trading Engine — NSTE (Part II): Jardine's Gate Six-Gate Quantum Filter

Neuro-Structural Trading Engine — NSTE (Part II): Jardine's Gate Six-Gate Quantum Filter

This article introduces Jardine's Gate, a six-gate orthogonal signal filter for MetaTrader 5 that validates LSTM predictions across entropy, expert interference, confidence, regime-adjusted probability, trend direction, and consecutive-loss kill switch dimensions. Out of 43,200 raw signals per month, only 127 pass all six gates. Readers get the complete QuantumEdgeFilter MQL5 class, threshold calibration logic, and gate performance analytics.
preview
Trend Criteria. Conclusion

Trend Criteria. Conclusion

In this article, we will consider the specifics of applying some trend criteria in practice. We will also try to develop several new criteria. The focus will be on the efficiency of applying these criteria to market data analysis and trading.
preview
Introduction to MQL5 (Part 43): Beginner Guide to File Handling in MQL5 (V)

Introduction to MQL5 (Part 43): Beginner Guide to File Handling in MQL5 (V)

The article explains how to use MQL5 structures with binary files to persist Expert Advisor parameters. It covers defining structures, accessing members, and distinguishing simple from complex layouts, then writing and reading entire records using FileWriteStruct and FileReadStruct in FILE BIN mode. You will learn safe patterns for fixed-size data and how shared storage (FILE COMMON) enables reuse across sessions and terminals.
preview
Neural Networks in Trading: Adaptive Detection of Market Anomalies (DADA)

Neural Networks in Trading: Adaptive Detection of Market Anomalies (DADA)

We invite you to get acquainted with the DADA framework, which is an innovative method for detecting anomalies in time series. It helps distinguish random fluctuations from suspicious deviations. Unlike traditional methods, DADA is flexible and adapts to different data. Instead of a fixed compression level, it uses several options and chooses the most appropriate one for each case.
preview
MQL5 Trading Tools (Part 25): Expanding to Multiple Distributions with Interactive Switching

MQL5 Trading Tools (Part 25): Expanding to Multiple Distributions with Interactive Switching

In this article, we expand the MQL5 graphing tool to support seventeen statistical distributions with interactive cycling via a header switch icon. We add type-specific data loading, discrete and continuous histogram computation, and theoretical density functions for each model, with dynamic titles, axis labels, and parameter panels that adapt automatically. The result lets you overlay distribution models on the same sample and compare fit across families without reloading the tool.
preview
Neural Networks in Trading: Dual Clustering of Multivariate Time Series (Final Part)

Neural Networks in Trading: Dual Clustering of Multivariate Time Series (Final Part)

We continue to implement approaches proposed vy the authors of the DUET framework, which offers an innovative approach to time series analysis, combining temporal and channel clustering to uncover hidden patterns in the analyzed data.
preview
MQL5 Trading Tools (Part 24): Depth-Perception Upgrades with 3D Curves, Pan Mode, and ViewCube Navigation

MQL5 Trading Tools (Part 24): Depth-Perception Upgrades with 3D Curves, Pan Mode, and ViewCube Navigation

In this article, we enhance the 3D binomial distribution graphing tool in MQL5 by adding a segmented 3D curve for improved depth perception of the probability mass function, integrating pan mode for view target shifting, and implementing an interactive view cube with hover zones and animations for quick orientation changes. We incorporate clickable sub-zones on the view cube for faces, edges, and corners to animate camera transitions to standard views, while maintaining switchable 2D/3D modes, real-time updates, and customizable parameters for immersive probabilistic analysis in trading.
preview
Larry Williams Market Secrets (Part 15): Trading Hidden Smash Day Reversals with Market Context

Larry Williams Market Secrets (Part 15): Trading Hidden Smash Day Reversals with Market Context

Build an MQL5 Expert Advisor that automates Larry Williams Hidden Smash Day reversals. It reads confirmed signals from a custom indicator, applies context filters (Supertrend alignment and optional trading‑day rules), and manages risk with stop‑loss models based on smash‑bar structure or ATR and a fixed or risk‑based position size. The result is a reproducible framework ready for testing and extension.
preview
Neural Networks in Trading: Dual Clustering of Multivariate Time Series (DUET)

Neural Networks in Trading: Dual Clustering of Multivariate Time Series (DUET)

The DUET framework offers an innovative approach to time series analysis, combining temporal and channel clustering to uncover hidden patterns in the analyzed data. This allows models to adapt to changes over time and improve forecasting quality by eliminating noise.
preview
Using the MQL5 Economic Calendar for News Filtering (Part 2): Stop Management Positions During News Releases

Using the MQL5 Economic Calendar for News Filtering (Part 2): Stop Management Positions During News Releases

In part 2, we extend the news filter to protect existing positions during news events. Instead of closing trades, we temporarily remove stop-loss and take-profit levels, storing them safely in memory. When the news window ends, stops are deterministically restored, adjusted if price has already crossed the original levels, while respecting broker minimum distance rules. The result is a mechanism that preserves trade integrity without interfering with entry logic, keeping the EA in control through volatility.
preview
MQL5 Trading Tools (Part 23): Camera-Controlled, DirectX-Enabled 3D Graphs for Distribution Insights

MQL5 Trading Tools (Part 23): Camera-Controlled, DirectX-Enabled 3D Graphs for Distribution Insights

In this article, we advance the binomial distribution graphing tool in MQL5 by integrating DirectX for 3D visualization, enabling switchable 2D/3D modes with camera-controlled rotation, zoom, and auto-fitting for immersive analysis. We render 3D histogram bars, ground planes, and axes alongside the theoretical probability mass function curve, while preserving 2D elements like statistics panels, legends, and customizable themes, gradients, and labels
preview
Mastering PD Arrays: Optimizing Trading from Imbalances in PD Arrays

Mastering PD Arrays: Optimizing Trading from Imbalances in PD Arrays

This is an article about a specialized trend-following EA that aims to clearly elaborate how to frame and utilize trading setups that occur from imbalances found in PD arrays. This article will explore in detail an EA that is specifically designed for traders who are keen on optimizing and utilizing PD arrays and imbalances as entry criteria for their trades and trading decisions. It will also explore how to correctly determine and profile premium and discount arrays and how to validate and utilize each of them when they occur in their respective market conditions, thus trying to maximize opportunities that occur from such scenarios.
preview
Package-based approach with KnitPkg for MQL5 development

Package-based approach with KnitPkg for MQL5 development

For maximum reliability and productivity in MetaTrader products built with MQL, this article advocates a development approach based on reusable “packages” managed by KnitPkg, a project manager for MQL5/MQL4. A package can be used as a building block for other packages or as the foundation for final artifacts that run directly on the MetaTrader platform, such as EAs, indicators, and more.
preview
MQL5 Trading Tools (Part 22): Graphing the Histogram and Probability Mass Function (PMF) of the Binomial Distribution

MQL5 Trading Tools (Part 22): Graphing the Histogram and Probability Mass Function (PMF) of the Binomial Distribution

This article develops an interactive MQL5 plot for the binomial distribution, combining a histogram of simulated outcomes with the theoretical probability mass function. It implements mean, standard deviation, skewness, kurtosis, percentiles, and confidence intervals, along with configurable themes and labels, and supports dragging, resizing, and live parameter changes. Use it to assess expected wins, likely drawdowns, and confidence ranges when validating trading strategies.
preview
Larry Williams Market Secrets (Part 13): Automating Hidden Smash Day Reversal Patterns

Larry Williams Market Secrets (Part 13): Automating Hidden Smash Day Reversal Patterns

The article builds a transparent MQL5 Expert Advisor for Larry Williams’ hidden smash day reversals. Signals are generated only on new bars: a setup bar is validated, then confirmed when the next session trades beyond its extreme. Risk is managed via ATR or structural stops with a defined risk-to-reward, position sizing can be fixed or balance-based, and direction filters plus a one-position policy ensure reproducible tests.
preview
Neural Networks in Trading: Integrating Chaos Theory into Time Series Forecasting (Final Part)

Neural Networks in Trading: Integrating Chaos Theory into Time Series Forecasting (Final Part)

We continue to integrate methods proposed by the authors of the Attraos framework into trading models. Let me remind you that this framework uses concepts of chaos theory to solve time series forecasting problems, interpreting them as projections of multidimensional chaotic dynamic systems.
preview
The MQL5 Standard Library Explorer (Part 9): Using ALGLIB to Filter Excessive MA Crossover Signals

The MQL5 Standard Library Explorer (Part 9): Using ALGLIB to Filter Excessive MA Crossover Signals

During sideways price movements, traders face excessive signals from multiple moving average crossovers. Today, we discuss how ALGLIB preprocesses raw price data to produce filtered crossover layers, which can also generate alerts when they occur. Join this discussion to learn how a mathematical library can be leveraged in MQL5 programs.
preview
Formulating Dynamic Multi-Pair EA (Part 7): Cross-Pair Correlation Mapping for Real-Time Trade Filtering

Formulating Dynamic Multi-Pair EA (Part 7): Cross-Pair Correlation Mapping for Real-Time Trade Filtering

In this part, we will integrate a real-time correlation matrix into a multi-symbol Expert Advisor to prevent redundant or risk-stacked trades. By dynamically measuring cross-pair relationships, the EA will filter entries that conflict with existing exposure, improving portfolio balance, reducing systemic risk, and enhancing overall trade quality.
preview
Neural Networks in Trading: Integrating Chaos Theory into Time Series Forecasting (Attraos)

Neural Networks in Trading: Integrating Chaos Theory into Time Series Forecasting (Attraos)

The Attraos framework integrates chaos theory into long-term time series forecasting, treating them as projections of multidimensional chaotic dynamic systems. Exploiting attractor invariance, the model uses phase space reconstruction and dynamic multi-resolution memory to preserve historical structures.
preview
Overcoming Accessibility Challenges in MQL5 Trading Tools (Part II): Enabling EA Voice Using a Python Text-to-Speech Engine

Overcoming Accessibility Challenges in MQL5 Trading Tools (Part II): Enabling EA Voice Using a Python Text-to-Speech Engine

Let's discuss how we can make our Expert Advisors speech‑capable using text‑to‑speech technology, partnering Python and MQL5. After reading this article, you will walk away with a working example of an EA that speaks dynamic market information. You will master the application of TTS, the WebRequest function, and learn how Python libraries integrate with the MQL5 language to create a truly voice‑aware trading tool.