This book was created with Inkfluence AI · Create your own book in minutes. Start Writing Your Book
AI Agents For MT5 Trading
How-To Guide

AI Agents For MT5 Trading

by Michael Burney · Published 2026-08-02

Created with Inkfluence AI

40 chapters 75,397 words ~302 min read English

Integrating AI agents and ML algorithms into MT5 EAs and indicators

Table of Contents

  1. 1. MT5 Trading Architecture Overview
  2. 2. Designing an Agent Message Bus
  3. 3. Defining Agent Roles and Contracts
  4. 4. Feature Store for MT5 Indicators
  5. 5. Historical Data Ingestion Pipeline
  6. 6. Labeling Trades for Supervised Learning
  7. 7. Walk-Forward Splits Without Leakage
  8. 8. Online Feature Updates in Real Time
  9. 9. Model Selection for Trading Policies
  10. 10. Baseline Heuristics as ML Priors
  11. 11. XGBoost for Tabular Market Features
  12. 12. LSTM/GRU Sequence Models for Bars
  13. 13. Temporal Convolution for Fast Inference
  14. 14. Transformer Encoders for Regime Detection
  15. 15. Uncertainty Estimation with Ensembles
  16. 16. Reinforcement Learning for Execution
  17. 17. Offline RL with Conservative Q
  18. 18. Agent Orchestration with State Machines
  19. 19. Hierarchical Orchestration for Multi-Models
  20. 20. Risk Agent for Position Sizing
  21. 21. Execution Agent with Order Lifecycle
  22. 22. Slippage and Spread-Aware Backtesting
  23. 23. Reward Shaping for Trading Objectives
  24. 24. Calibration with Platt/Isotonic Scaling
  25. 25. Threshold Optimization for Trade Triggers
  26. 26. Hyperparameter Search with MT5 Runs
  27. 27. Bayesian Optimization for EA Parameters
  28. 28. Genetic Algorithms for Strategy Discovery
  29. 29. Walk-Forward Retraining Schedules
  30. 30. Model Versioning and Rollback Plans
  31. 31. Exporting Models to MT5-Friendly Formats
  32. 32. Implementing Inference in MQL5
  33. 33. Custom Indicator as Feature Generator
  34. 34. Agent Logging, Telemetry, and Traces
  35. 35. Live Monitoring with Drift Metrics
  36. 36. Safety Constraints and Kill Switches
  37. 37. Optimization Against Overfitting Traps
  38. 38. Latency Budgeting for Tick-Level Decisions
  39. 39. Deployment Workflow for MT5 Agents
  40. 40. Post-Trade Learning and Continuous Improvement

Preview: MT5 Trading Architecture Overview

A short excerpt from “MT5 Trading Architecture Overview”. The full book contains 40 chapters and 75,397 words.

Why the MT5 Responsibility Map Matters


Daria, a 31-year-old fintech engineer at a prop desk, found a trade signal in a backtest that looked reliable. The signal came from a custom indicator, but the indicator also checked spread, calculated position size, and sent orders. When Daria attached it to two charts, both instances could submit the same trade. A second problem appeared during a terminal restart: the indicator had no clear way to reconstruct its trade state. The model was not the main failure. The boundary between the indicator and the Expert Advisor (EA) was.


The MT5 Responsibility Map fixes that boundary. An indicator answers, “What does the market data say?” An EA answers, “What should the account do?” An Artificial Intelligence (AI) agent can evaluate context, select a permitted action, or coordinate several models, but it should not quietly bypass the EA’s execution controls. Keeping these responsibilities explicit prevents duplicate orders, inconsistent state, and expensive model calls in the wrong event handler.


After applying the map, you can place each operation in the correct part of the MetaTrader 5 (MT5) event loop, define the data passed between components, and trace a model decision from a new price bar to an accepted or rejected trade request. You will also know which work belongs inside MQL5 and which work should run in an external service. The practical takeaway is simple: make the indicator descriptive, make the EA authoritative, and make the agent advisory unless you deliberately grant it a narrow, tested action interface.


How the MT5 Responsibility Map Works


MT5 drives an EA through event handlers. `OnInit()` runs when the EA loads, `OnTick()` runs when a market tick arrives, `OnTimer()` runs on a timer schedule, and `OnTradeTransaction()` reports changes related to trade requests and account state. A custom indicator normally uses `OnInit()` for setup and `OnCalculate()` for recalculating indicator buffers. These handlers do not provide equal-purpose execution slots. `OnCalculate()` should transform market history into values; `OnTick()` or `OnTimer()` should coordinate decisions and execution.


The MT5 Responsibility Map assigns each responsibility to one owner:


ResponsibilityPrimary ownerTypical MT5 locationOutput
Read bars, ticks, and indicator inputsIndicator or data adapter`OnCalculate()`, `CopyRates()`Features and buffers
Detect a signalIndicator or signal module`OnCalculate()` or EA-owned logicSignal record
Add account, spread, and session rulesEA`OnTick()` or `OnTimer()`Eligible or rejected decision
Ask an AI model or agentEA orchestration layer`OnTimer()` or controlled `OnTick()` pathScore, action, or veto
Calculate volume and protective levelsEA risk moduleBefore order submissionValidated trade plan
Send and track ordersEA`CTrade`, `OrderSend()`, `OnTradeTransaction()`Request and execution state
Display valuesIndicator or chart layerIndicator buffers and objectsVisual output

Use the following numbered sequence when mapping a new feature:


1. Classify the output. If the output describes price structure, volatility, or a model score, place it in the indicator or feature layer. If it changes account state, place it in the EA. This rule prevents a chart component from becoming an untracked trading engine.

2. Create a typed signal record. Pass fields such as symbol, timeframe, bar time, direction, confidence, and model version instead of passing a loose Boolean. The EA needs enough context to reject stale or duplicated signals.

3. Run agent reasoning behind a bounded interface. Give the agent a structured market snapshot and a fixed set of allowed actions, such as `HOLD`, `BUY`, `SELL`, or `CLOSE`. The EA remains responsible for checking whether the selected action fits account and strategy rules.

4. Validate before execution. Check spread, trading session, position limits, volume step, stop distance, margin, and current position state immediately before sending the request. Earlier checks can become invalid after a new tick.

5. Record the result. Store the decision identifier, request result, retcode, fill details, and reason for rejection. Without this record, you cannot distinguish a weak model decision from a broker or execution problem.


A useful signal record might contain `bar_time=2026.08.02 10:15`, `symbol=EURUSD`, `direction=BUY`, `confidence=0.78`, `feature_version=12`, and `decision_id=EURUSD-M15-20260802-1015`. The indicator can publish this record through buffers, global variables, files, or an in-process EA module. For production execution, an EA-owned feature calculation often reduces synchronization risk because the EA can read the same snapshot that it validates.


AI agents fit between signal creation and trade authorization. A classification model might estimate the probability of an upward move....

About this book

"AI Agents For MT5 Trading" is a how-to guide book by Michael Burney with 40 chapters and approximately 75,397 words. Integrating AI agents and ML algorithms into MT5 EAs and indicators.

This book was created using Inkfluence AI, an AI-powered book generation platform that helps authors write, design, and publish complete books. It was made with the AI Ebook Generator.

Frequently Asked Questions

What is "AI Agents For MT5 Trading" about?

Integrating AI agents and ML algorithms into MT5 EAs and indicators

How many chapters are in "AI Agents For MT5 Trading"?

The book contains 40 chapters and approximately 75,397 words. Topics covered include MT5 Trading Architecture Overview, Designing an Agent Message Bus, Defining Agent Roles and Contracts, Feature Store for MT5 Indicators, and more.

Who wrote "AI Agents For MT5 Trading"?

This book was written by Michael Burney and created using Inkfluence AI, an AI book generation platform that helps authors write, design, and publish books.

How can I create a similar how-to guide book?

You can create your own how-to guide book using Inkfluence AI. Describe your idea, choose your style, and the AI writes the full book for you. It's free to start.

Write your own how-to guide book with AI

Describe your idea and Inkfluence writes the whole thing. Free to start.

Start writing

Created with Inkfluence AI