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
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
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
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
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.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 4): Fully Automated Analytical Objects System

How to Detect and Normalize Chart Objects in MQL5 (Part 4): Fully Automated Analytical Objects System

This part extends the series with a modular, event-driven MQL5 pipeline: swing detection feeds an object placer for trendlines, SR, Fibonacci, channels, and pitchforks; evaluators monitor interactions and generate signals; adaptive logic executes trades with valid stops per instrument. The topology manager synchronizes placement, scanning, and processing. The code is structured into reusable components for easy reuse and scaling.
preview
Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Building Objects)

Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Building Objects)

Mantis is a versatile tool for in-depth time series analysis that can be flexibly scaled to accommodate any financial scenario. Learn how a combination of patching, local convolutions, and cross-attention enables a highly accurate interpretation of market patterns.
preview
Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Mantis)

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

Meet Mantis — a lightweight foundation model for time series classification based on a Transformer architecture, featuring contrastive pre-training and hybrid attention that deliver record-breaking accuracy and scalability.
preview
Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Core Model Modules)

Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Core Model Modules)

We continue our acquaintance with the Mamba4Cast framework. Today, we will delve into the practical implementation of the proposed approaches. Mamba4Cast was designed not for lengthy warm-up on every new time series, but for immediate deployment. Thanks to the concept of Zero-Shot Forecasting, the model can produce high-quality forecasts on real-world data without additional training or hyperparameter tuning.
preview
Trading Options Without Options (Part 3): Complex Option Strategies

Trading Options Without Options (Part 3): Complex Option Strategies

The article discusses flat (non-directional) and trend-following (directional) option strategies and their implementation in MQL5. The EA described in the previous article is updated. The display of option levels has been added. Now it is time to examine the strategies used by options traders in practice and put them into action.
preview
Price Action Analysis Toolkit Development (Part 76): One-Click Symbol Dashboard for Centralized Multi-Chart Management in MQL5

Price Action Analysis Toolkit Development (Part 76): One-Click Symbol Dashboard for Centralized Multi-Chart Management in MQL5

Learn to assemble an MT5 Expert Advisor that hosts a chart management dashboard written in MQL5. The guide walks through shared definitions, symbol acquisition and filtering, chart lifecycle functions, and a UI panel with search, scrolling, and state indicators, all driven by events and a timer. The result is a reproducible tool that reduces clicks and accelerates multi-symbol analysis.
preview
Automating Classic Market Methods in MQL5 (Part 5): The Original Turtle Trading Rules

Automating Classic Market Methods in MQL5 (Part 5): The Original Turtle Trading Rules

This article builds a complete MQL5 Expert Advisor that implements the original Turtle Trading rules from Curtis Faith. It covers both systems: 20/55-day breakouts, the System 1 skip rule, N (Wilder ATR) for volatility-adjusted sizing, a four‑unit pyramid with N/2 adds, a unified 2N stop, and 10/20-day exits. You will get compilable code, implementation details, and a backtesting procedure on EURUSD.
preview
Automating Classic Market Methods in MQL5 (Part 4): Mark Minervini's Trend Template

Automating Classic Market Methods in MQL5 (Part 4): Mark Minervini's Trend Template

This article presents TrendTemplateEA, an Expert Advisor implementing Mark Minervini's eight-condition trend template for daily forex charts. It evaluates all conditions on every bar and enters only when they are simultaneously satisfied, using RSI above 50 in place of the stock market RS rating. The entry trigger is a 20-bar high breakout on expanding volume, with all rules coded and testable in MQL5.
preview
How to Research a Trading Idea: A Range Breakout Strategy Case Study

How to Research a Trading Idea: A Range Breakout Strategy Case Study

This article demonstrates a practical approach to researching trading ideas using a range breakout strategy as an example. We will go through the entire process, from formalizing trading rules and building a baseline model to parameter optimization, forward testing, and evaluating the robustness of the results. The main goal of the article is to develop an understanding of how statistics and testing can be used to identify, validate, and evaluate trading hypotheses.
preview
Developing a Manual Backtesting Expert Advisor: Additional Features

Developing a Manual Backtesting Expert Advisor: Additional Features

We enhance the manual backtesting EA with real-time lot adjustment, an order module for buy/sell stops and limits, and a Trade Manager to modify TP/SL and close positions individually. The article explains control setup with CButton/CBmpButton/CEdit, logic in OnTick, and workarounds for Strategy Tester input constraints. Readers can reuse these components to speed up testing workflows and implement robust trade management.
preview
How to Test and Customize Built-in MQL5 Programs:  Custom BullishBearish MeetingLines Stoch Expert Advisor

How to Test and Customize Built-in MQL5 Programs: Custom BullishBearish MeetingLines Stoch Expert Advisor

We demonstrate a practical customization path for a built-in MetaTrader 5 EA using BullishBearish MeetingLines Stoch. The workflow covers baseline testing in the Strategy Tester, parameter optimization, and code-level changes. Two modifications are implemented: exposing Stochastic thresholds as inputs and adding an optional Moving Average filter to limit counter‑trend signals. The article includes the full modified code for replication.
preview
The MQL5 Standard Library Explorer (Part 14): Building a Dynamic Hedge EA with the ALGLIB Port (ap.mqh)

The MQL5 Standard Library Explorer (Part 14): Building a Dynamic Hedge EA with the ALGLIB Port (ap.mqh)

This article introduces ap.mqh, the ALGLIB port for MQL5, and demonstrates its use in multi‑asset workflows that require robust linear algebra. It covers why built-in indicators fall short, then implements polynomial regression, a rolling correlation matrix indicator, and an adaptive hedge ratio estimator using ridge regression with Cholesky. Practical code shows how to compute spread z‑scores and execute coordinated pairs trades entirely within MetaTrader 5.
preview
Algorithmic Arbitrage Trading Using Graph Theory

Algorithmic Arbitrage Trading Using Graph Theory

In this article, triangular arbitrage is presented as a problem of finding cycles in a directed graph, where the vertices are currencies and the edges are currency pairs with weight rates. Profitable cycle: product of weights >1. Our Floyd-Warshall and DFS algorithms find optimal currency exchange paths that return to the starting point with a profit.
preview
Monochronic Trading (Part 1): How to Detect Broker Timezone and DST in MQL5

Monochronic Trading (Part 1): How to Detect Broker Timezone and DST in MQL5

We describe an MQL5 framework that aligns entries with session rhythms and scheduled clock events. A script identifies the broker's time zone and DST by detecting NFP spikes on EURUSD and matching them to EU/US/AU transition dates, producing EA‑ready settings. Session-to-broker time conversion and 15-minute marks constrain execution. A multi‑timeframe AMA signal aggregates trends for strategy selection and optimization.
preview
Building a Synthetic Custom Symbol in MQL5 Using Multi-Symbol Price Averaging

Building a Synthetic Custom Symbol in MQL5 Using Multi-Symbol Price Averaging

This article shows how to build a synthetic custom symbol in MQL5 by averaging OHLC data from multiple instruments into a single derived price series. It covers symbol collection and validation, custom symbol creation and configuration, timestamp alignment, historical reconstruction, and lightweight live updates. The result is a reusable method for creating synthetic instruments suitable for correlation analysis, index-style modeling, indicator development, and strategy testing.
preview
Trading Robot Based on a GPT Language Model

Trading Robot Based on a GPT Language Model

The article presents a complete implementation of TimeGPT, a specialized Transformer-based architecture for forecasting financial time series on the MetaTrader 5 platform. Adaptation of the attention mechanism to financial data, selective tokenization of price changes, hardware-aware optimizations, and advanced learning techniques are discussed. Included are practical testing results showing 87% forecast accuracy over a 24-bar horizon with a training time of 15 minutes on the CPU. We also present a ready-made trading EA with automatic retraining.
preview
Custom Indicator Workshop (Part 4) : Automating UT Bot Alerts into a Trading Expert Advisor

Custom Indicator Workshop (Part 4) : Automating UT Bot Alerts into a Trading Expert Advisor

This article shows how to build an MQL5 Expert Advisor around the UT Bot Alerts indicator. The EA reads custom indicator signals via iCustom() and CopyBuffer(), evaluates entries only on new bars, using the last closed candle at index 1, and enforces a one-direction-at-a-time model by closing opposite positions before taking new entries. It also adds optional ATR-based stop-losses, reward-to-risk take-profits, dedicated buy/sell execution functions, magic-number tracking, and basic backtesting for repeatable evaluation.
preview
N-BEATS Network-Based Forex EA

N-BEATS Network-Based Forex EA

Implementation of the N-BEATS architecture for Forex trading in MetaTrader 5 with quantile forecasting and adaptive risk management. The architecture is adapted through bilinear normalization and specialized loss functions for financial data. Backtesting on 2025 data shows inability to generate profits, confirming the gap between theoretical achievements and practical trading performance.
preview
Neural network trading EA based on PatchTST

Neural network trading EA based on PatchTST

The article presents the revolutionary architecture of PatchTST, a tailored transformer for financial time series analysis that breaks market data into 16-bar patches for efficient processing. We will discuss the full implementation of a trading robot in MQL5 covering everything from mathematical fundamentals and data structures to a ready-made EA with risk management and continuous learning systems.
preview
Automating Trading Strategies in MQL5 (Part 50): Turtle Soup Liquidity Sweeps

Automating Trading Strategies in MQL5 (Part 50): Turtle Soup Liquidity Sweeps

We build an automated MQL5 program that trades Turtle Soup by fading false breakouts of the N-bar high and low. The article implements liquidity-sweep detection, confirmation closes back inside the level, sweep-depth and extreme-age filters, and an optional reversal-candle body check. It adds configurable dynamic or static stops, two take-profit modes, points-based trailing, and clear chart visuals, providing a ready baseline for backtesting and further customization.
preview
MQL5 Trading Tools (Part 39): Adding a Pinned-Tools Ribbon for Quick Access to Favorite Tools

MQL5 Trading Tools (Part 39): Adding a Pinned-Tools Ribbon for Quick Access to Favorite Tools

We add a pinned-tools ribbon: a floating bar that exposes frequently used tools for one-click access without reopening the sidebar. The article implements the ordered pin set and its API, an anti-aliased pushpin control in the flyout, and the ribbon with offscreen clipping, user-resizable width, and horizontal scrolling. The result is faster activation of favorite tools from a draggable, resizable ribbon on the chart.
preview
Building a Broker-Agnostic Symbol Resolution Layer in MQL5

Building a Broker-Agnostic Symbol Resolution Layer in MQL5

We implement a symbol resolution framework that abstracts broker naming differences in MetaTrader 5. Using a persistent mapping store, layered resolution with validation, a hash-indexed registry, and a cache, it returns selectable symbols with live market data and logs unresolved cases. Practically, you can deploy the same EA across brokers and keep symbol access consistent at low runtime cost.
preview
Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Mamba4Cast)

Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Mamba4Cast)

In this article, we introduce the Mamba4Cast framework and take a closer look at one of its key components: timestamp-based positional encoding. The article shows shows how time embedding is formed taking into account the calendar structure of the data.
preview
Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (Final Part)

Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (Final Part)

The article discusses the adaptation and practical implementation of the ACEFormer framework using MQL5 in the context of algorithmic trading. It presents key architectural decisions, training features, and model testing results on real data.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 5): Real-Time Recovery Dashboard (Final Part)

Engineering a Self-Healing Expert Advisor in MQL5 (Part 5): Real-Time Recovery Dashboard (Final Part)

This article implements a real-time monitoring dashboard for a self-healing MetaTrader 5 Expert Advisor. The dashboard displays the current EA state, virtual stop-loss and take-profit levels, breakeven and trailing status, recovery state, synchronization status, and heartbeat information directly on the chart. By exposing the internal recovery state visually, the Expert Advisor becomes easier to monitor, verify, and troubleshoot while managing active trades.
preview
Building Automated Daily Trading Reports with the SendMail Function

Building Automated Daily Trading Reports with the SendMail Function

We build an MQL5 Expert Advisor that emails a structured daily trading report. The article shows how to configure SMTP in MetaTrader 5, collect and filter closed trades for the previous day, compute totals for profit, wins, losses, and trade count, and assemble account details into the subject and body. You also schedule one send per day and prevent duplicates using daily candle detection.
preview
Training a nonlinear U-Transformer on the residuals of a linear autoregressive model

Training a nonlinear U-Transformer on the residuals of a linear autoregressive model

The article presents an innovative hybrid system for forecasting exchange rates that combines a linear autoregressive model with a U-Transformer architecture for residual analysis. The system automatically switches between signal sources depending on their quality and includes complete trading logic with averaging/pyramiding strategies. The key advantage of this approach is that the neural network is trained on the residuals of the linear model, which simplifies the task and reduces the risk of overfitting. The implementation is done entirely in MQL5 and is ready for use in real trading with automatic adaptation to changing market conditions.
preview
Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (ACEFormer)

Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (ACEFormer)

We invite you to explore the ACEFormer architecture — a modern solution that combines the effectiveness of probabilistic attention with adaptive time series decomposition. This article will be useful for those seeking a balance between computational performance and forecast accuracy in financial markets.
preview
Implementation of the Quantum Reservoir Computing (QRC) circuit

Implementation of the Quantum Reservoir Computing (QRC) circuit

A revolutionary approach to machine learning in trading through quantum computing. The article demonstrates a practical implementation of an adaptive QRC system with continuous retraining for predicting market movements in real time.
preview
Automating Trading Strategies in MQL5 (Part 49): The Quasimodo (QM) Reversal Pattern

Automating Trading Strategies in MQL5 (Part 49): The Quasimodo (QM) Reversal Pattern

In this article, we build an automated trading program in MQL5 that detects the Quasimodo reversal pattern from a zig-zag of confirmed swing pivots. We work through swing detection, pattern arming, retrace entries at the QM line, and structural stop placement with risk-based sizing. We also add trade management with breakeven, trailing, and partial closing to handle open positions.
preview
Developing a Neural Network Trading Robot Based on Mamba with Selective State Space Models

Developing a Neural Network Trading Robot Based on Mamba with Selective State Space Models

The article explores the revolutionary Mamba/SSM neural network architecture for financial time series forecasting. We will consider a complete MQL5 implementation of a modern alternative to Transformer with linear complexity O(N) instead of quadratic O(N²). Selective State Space Models, hardware-aware optimizations, patching techniques, and advanced AdamW training methods are covered in detail. Practical test results showing an increase in accuracy from 62% to 71% while reducing training time from 45 to 8 minutes are included. A ready-made trading EA with auto learning and adaptive risk management for MetaTrader 5 is presented.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 4): Trade-State Reconciliation and Safe Mode Recovery

Engineering a Self-Healing Expert Advisor in MQL5 (Part 4): Trade-State Reconciliation and Safe Mode Recovery

This article adds trade-state reconciliation and Safe Mode recovery to a MetaTrader 5 Expert Advisor. The EA continuously validates recovery integrity by comparing the live broker position with the persisted SQLite state and the in-memory runtime state. Detected inconsistencies trigger an automatic transition to Safe Mode, suspending virtual protection, breakeven, and trailing management until the recovery state can be trusted again.
preview
Risk Manager for Trading Robots (Part I): Risk Control Include File for Expert Advisors

Risk Manager for Trading Robots (Part I): Risk Control Include File for Expert Advisors

Trading is characterized by high demands on risk management discipline. The article presents an analysis of the main reasons for traders' failures and proposes a technical solution in the form of the CEnhancedRiskManager class for the MQL5 platform. It includes practical testing on an aggressive grid EA.