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
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.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 3): Restart-Aware Breakeven and Trailing Systems

Engineering a Self-Healing Expert Advisor in MQL5 (Part 3): Restart-Aware Breakeven and Trailing Systems

Building on Part 2, the implementation introduces restart-aware breakeven and trailing-stop systems for MetaTrader 5. The EA persists the state, such as breakeven activation, last trailing price, and virtual SL in SQLite, then restores them on startup. This preserves dynamic protection flow and prevents lost progress after terminal interruptions.
preview
Building an Object-Oriented Session VWAP Engine in MQL5

Building an Object-Oriented Session VWAP Engine in MQL5

This article shows how to implement a session vwap in MQL5 as a reusable include class with a strict daily reset at broker midnight. The engine computes VWAP and volume‑weighted deviation bands only on closed bars and anchors accumulation with MqlDateTime to avoid distortions from missing candles. A companion indicator plots the baseline and bands, while an Expert Advisor reads signals once per bar for consistent, CPU‑efficient execution and reliable testing.
preview
The MQL5 Standard Library Explorer (Part 13): Implementing the Math Solvers Library in Trading

The MQL5 Standard Library Explorer (Part 13): Implementing the Math Solvers Library in Trading

We present a complete workflow for adaptive filtering in MQL5 using the CNlEq Levenberg–Marquardt–like solver. The EA fits a VAMAC model—two EWMAs with an ATR‑based scaling—by supplying residuals and a Jacobian through CNlEq's reverse‑communication loop, with optional numerical or analytical derivatives. Code, setup instructions, and GBPUSD H1 tests show how to replace static thresholds with on‑bar re‑estimation.
preview
MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties

MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties

We add a tabbed settings window opened from the ribbon and bound to the selected object. The tabs — Style, Text, Coordinates, and Visibility — are built from the same descriptor system, with scrolling, per-level rows, and shared color/width/style popovers. The article covers layout, rendering, interaction, and inline price/time and numeric editing. You get one place to edit every property with live preview and commit-or-discard on close.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 3): Alerting and Automated Trading from Manually Drawn Objects

How to Detect and Normalize Chart Objects in MQL5 (Part 3): Alerting and Automated Trading from Manually Drawn Objects

This article extends the chart‑object detector into a modular monitoring and execution layer. It defines objective interaction rules (touch, cross, breakout) for trendlines, Fibonacci levels, channels, rectangles, and pitchforks, then routes events through an interaction detector, alert manager, and optional trade executor. Orders use object geometry for stop‑loss and take‑profit. The result is a reproducible pipeline that converts static drawings into actionable alerts and, if enabled, trades.
preview
Price Action Analysis Toolkit Development (Part 74): Building an MQL5 Expert Advisor from Indicator Buffers

Price Action Analysis Toolkit Development (Part 74): Building an MQL5 Expert Advisor from Indicator Buffers

This article implements an MQL5 Expert Advisor that connects to a weekend gap indicator via iCustom and CopyBuffer, reading six buffers for buy/sell signals and SL/TP. It validates broker stop-distance rules, handles closed-bar confirmation and duplicate-signal control, and executes orders with a configurable magic number. The EA also includes midpoint stop-loss management and a backtesting procedure so you can verify behavior and adapt parameters to your setup.
preview
Neural Networks in Trading: LSTM Optimization for Multivariate Time Series Forecasting (Final Part)

Neural Networks in Trading: LSTM Optimization for Multivariate Time Series Forecasting (Final Part)

We continue to implement the DA-CG-LSTM framework, which offers innovative methods for time series analysis and forecasting. The use of CG-LSTM and dual attention allows for more accurate detection of both long-term and short-term dependencies in data, which is particularly useful for working with financial markets.
preview
MQL5 Trading Tools (Part 37): Adding a Per-Object Property-Editing Ribbon to the Canvas Drawing Layer

MQL5 Trading Tools (Part 37): Adding a Per-Object Property-Editing Ribbon to the Canvas Drawing Layer

We add a descriptor-driven property stack and a floating ribbon that binds to the current selection on the drawing layer. The article covers the descriptor list for each tool, the engine get/set API with snapshot-and-restore live preview, and widget renderers for color, opacity, line width, line style, fonts, and level visibility. You get in-place, real-time editing of object appearance via a compact, draggable panel.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part V): Gesture-Based Trading With Computer Vision

Overcoming Accessibility Problems in MQL5 Trading Tools (Part V): Gesture-Based Trading With Computer Vision

This article shows how to build a hands-free trading workflow for MetaTrader 5 by translating webcam-tracked hand gestures into MQL5 trade commands. We cover the architecture (MediaPipe/OpenCV in Python plus an MQL5 EA), gesture-to-action mapping, and interprocess communication via Global Variables or HTTP polling. You will implement the EA, execute BUY/SELL/CLOSE actions, and validate latency and reliability under real‑time conditions.
preview
Neural Networks in Trading: LSTM Optimization for Multivariate Time Series Forecasting (DA-CG-LSTM)

Neural Networks in Trading: LSTM Optimization for Multivariate Time Series Forecasting (DA-CG-LSTM)

This article introduces the DA-CG-LSTM algorithm, which offers new approaches to time series analysis and forecasting. It explains how innovative attention mechanisms and model flexibility can improve forecast accuracy.
preview
Neural Networks in Trading: Actor—Director—Critic (Final Part)

Neural Networks in Trading: Actor—Director—Critic (Final Part)

The Actor–Director–Critic framework is an evolution of the classic agent learning architecture. The article presents practical experience of its implementation and adaptation to financial market conditions.