AI Agents For MT5 Trading
How-To Guide

AI Agents For MT5 Trading

by Michael Burney · 2026-08-02

Integrating AI agents and ML algorithms into MT5 EAs and indicators

40 chapters 75,397 words ~302 min read English 100 reads

Read the first chapter

The whole of chapter one, free. About 9 min. Turn the pages with the arrows, your keyboard, or a swipe.

Chapter 1

MT5 Trading Architecture Overview

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:

| Responsibility | Primary owner | Typical MT5 location | Output | |---|---|---|---| | Read bars, ticks, and indicator inputs | Indicator or data adapter | OnCalculate(), CopyRates() | Features and buffers | | Detect a signal | Indicator or signal module | OnCalculate() or EA-owned logic | Signal record | | Add account, spread, and session rules | EA | OnTick() or OnTimer() | Eligible or rejected decision | | Ask an AI model or agent | EA orchestration layer | OnTimer() or controlled OnTick() path | Score, action, or veto | | Calculate volume and protective levels | EA risk module | Before order submission | Validated trade plan | | Send and track orders | EA | CTrade, OrderSend(), OnTradeTransaction() | Request and execution state | | Display values | Indicator or chart layer | Indicator buffers and objects | Visual 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. An agent can combine that estimate with session status, open exposure, news blackout flags, and the current position. However, an agent should return a decision object rather than call OrderSend() directly. This separation gives the EA one execution gate and makes the agent replaceable. Ask yourself: if the agent process stops after returning BUY, can the EA safely reject the action, log the failure, and continue without corrupting account state? If not, the interface is too broad.

Choose the event handler according to timing. Use OnTick() when the strategy must react to every eligible price update, but add a bar-time guard when the model only evaluates completed bars. Use OnTimer() for expensive inference, polling an external Python service, or retrying a delayed response. Use OnTradeTransaction() to update actual position state; do not assume that a successful request means a completed fill. The practical takeaway is to keep the event loop short, deterministic, and ownership-driven: calculate, evaluate, validate, submit, then reconcile.

Putting the Map Into Practice

Daria applies the MT5 Responsibility Map to an EURUSD 15-minute system. A custom indicator calculates a 20-bar moving-average gap, 14-bar Average True Range (ATR), and a momentum feature. A gradient-boosted model returns an upward-move score. An AI agent then selects whether the EA should hold, open a position, or close an existing position. The EA enforces the desk’s limits: one EURUSD position, a maximum volume of 0.20 lots, a minimum stop distance of 80 points, and a spread limit of 18 points.

She implements the flow as follows:

1. Wait for a completed bar. On each tick, the EA reads the latest closed M15 bar time. If that time matches last_processed_bar, it exits without inference. This prevents five hundred ticks from producing five hundred identical decisions. The expected result is one model evaluation per completed bar. 2. Build the snapshot. The EA reads the indicator buffers, current bid and ask, spread, account equity, open position state, and session flag. It rejects the snapshot if any feature returns EMPTY_VALUE or if fewer than 50 bars exist. The expected result is a complete, timestamped input rather than a partially populated request. 3. Call the decision service. The agent receives the snapshot and returns action=BUY, confidence=0.81, stop_points=120, and decision_id=EURUSD-M15-20260802-1015. The EA applies a 300-millisecond timeout. A timeout produces HOLD, not an order retry, because an unknown model state cannot justify account risk. 4. Apply EA gates. The EA checks the 18-point spread limit, the one-position limit, the 0.20-lot cap, the 80-point stop minimum, and available margin. Suppose the agent requests 0.30 lots; the EA clamps or rejects it according to the configured policy. Daria chooses rejection with a logged reason so the model cannot silently change risk. 5. Submit the trade. The EA normalizes volume to the symbol’s volume step, calculates the stop price from the current ask, and sends the request through the configured trading class. It attaches the decision_id to the order comment where the broker permits it. The expected result is a request whose parameters match the validated trade plan. 6. Reconcile execution. OnTradeTransaction() records the request identifier, returned retcode, deal ticket, fill price, and actual volume. If the broker partially fills 0.12 lots, the EA updates its position state from the transaction rather than from the requested 0.20 lots. The expected result is an internal state that matches the account. 7. Render observability data. The indicator displays the model score and signal marker, while the EA logs the gate results and execution status. Daria can now see whether a signal existed, whether the agent selected an action, whether a risk rule rejected it, or whether execution failed.

The indicator never sends the order, and the agent never owns the position. That division also supports replay testing: Daria can feed historical snapshots to the decision layer without opening a chart trade context. She can then test the EA gates separately with synthetic actions such as BUY at 0.30 lots or SELL with a 20-point stop.

Quick checklist

• Assign every output to either the indicator, agent, EA, or execution-reconciliation layer. - Include symbol, timeframe, completed-bar time, feature version, and decision identifier in each signal. - Guard bar-based inference with a stored bar timestamp. - Keep OnTick() free of blocking external calls when possible; use OnTimer() for bounded polling. - Treat model output as a proposed action, not an authorized trade. - Recheck spread, volume, stops, margin, and position limits immediately before submission. - Use OnTradeTransaction() to update actual fills and position state. - Log rejected actions as carefully as accepted trades.

A successful implementation produces an auditable chain: one bar, one snapshot, one decision, one validation result, and one reconciled account outcome. That chain matters more than a visually impressive signal marker because it tells Daria exactly where a live result diverged from the tested path.

What to Watch For

The indicator becomes a hidden execution engine

Developers often add OrderSend() to OnCalculate() because the indicator already detects the signal. That shortcut creates duplicate execution paths when several charts load the same indicator, and it makes trade state difficult to reconcile.

Do this: let the indicator publish signal values and let one EA own authorization and order submission.

Not this: send an order from every indicator instance that detects the same crossover.

Use a unique signal key based on symbol, timeframe, and bar time. The EA should also maintain its own processed-signal state because indicator buffers can recalculate after history updates.

The agent blocks the event loop

A remote model call inside OnTick() can stall price processing while the service waits. During that delay, the spread may widen, the position may change, or the signal may become stale. Repeated ticks can also start overlapping requests.

Do this: queue one snapshot, call the service from OnTimer() or a controlled worker pattern, set a timeout, and discard responses whose bar time no longer matches the current decision window.

Not this: wait indefinitely inside OnTick() and submit the returned action without rechecking market conditions.

For a 15-minute strategy, a response that arrives after the next bar begins may still be useful for logging, but it should not automatically trade the new bar. The EA must define freshness explicitly.

The EA trusts requested state instead of broker state

A successful OrderSend() call indicates that MT5 accepted the request for processing; it does not guarantee the final fill, volume, or price. Partial fills, rejected stops, requotes, and position changes can invalidate the EA’s assumptions.

Do this: treat the trade transaction stream as the source of truth, update state from deal and order events, and log the broker return code.

Not this: set has_position=true immediately after the request and assume the requested volume reached the account.

This distinction becomes critical when an AI agent proposes a close action while a previous opening request remains pending. The EA needs a state machine that distinguishes FLAT, OPEN_REQUESTED, PARTIALLY_FILLED, OPEN, and CLOSE_REQUESTED. Clear states prevent the agent from issuing contradictory actions.

The MT5 Responsibility Map gives every decision a home and every trade a traceable path. Once those boundaries hold, model selection and agent orchestration become controlled engineering choices rather than repairs for execution ambiguity. The next layer of an AI-enhanced system can then focus on better inputs and better decisions without losing control of the terminal’s event loop or the trading account.

End of chapter one. 39 more chapters in the full book.

1 / 10

Swipe or use the arrows to turn the page

What's inside: 40 chapters

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