🧠 Agentic AI · Sep 2026

MetaTrader 5 MCP: the AI That Runs Backtests and Optimizes Your EA

By Dan Machado · 10 min read

MetaTrader 5 MCP is what turns the AI Assistant from a chat into an agent: instead of just answering, it performs actions inside the platform. With build 6180, released in early September 2026, the AI can now read Strategy Tester reports, launch optimizations and read your Expert Advisor’s logs. In this guide you’ll see what’s already possible, a practical AI-driven optimization workflow and the precautions that keep you from falling into overfitting.

⚡ 30-second summary

  • MCP is an open standard that lets AI agents use an application’s functions.
  • MT5 has had native MCP since build 6060 (late Jul 2026).
  • In build 6180 the AI gained access to the Strategy Tester: reports, optimization, settings and logs.
  • MetaQuotes says external agents like Claude Code and OpenAI Codex can also connect.
  • Optimizing with AI is fast, but validating against overfitting is still your job.

What is MCP (in 1 minute)

MCP (Model Context Protocol) is an open standard that lets applications talk to AI agents. The application offers “tools” (read quotes, add an indicator, run a test) and the agent decides which ones to use and in what order.

Here’s the difference from a regular chatbot: the agent breaks a complex task into a sequence of actions and uses the connected application’s capabilities to carry them out. In MT5, that means asking “optimize this EA and compare the best results” and watching the AI set up the test, wait and read the report.

If you haven’t enabled the assistant yet, start with the MT5 AI Assistant guide.

What MetaTrader 5 MCP already does (build by build)

Build MCP tools
6060 (Jul 2026) Access to market data, analysis of charts and the trading environment, and trade execution through a standard interface. Support for external MCP-compatible agents.
6090 (Jul 2026) Add indicators to the chart and list the available indicators with their parameters.
6140 (Aug 2026) Optimized MCP tools and a new tool to stop the Strategy Tester.
6180 (Sep 2026) Read Strategy Tester reports, launch optimizations with defined criteria, read the tester’s current settings, read the tester log, add indicators with custom parameters and read the terminal and EA logs.

Practical workflow: optimizing an EA with AI

Let’s use a moving-average crossover EA as an example, like the one in the AI Assistant guide. The sequence of prompts below takes advantage of the build 6180 tools:

  1. Confirm the setup before burning hours of CPU:
    Read the current Strategy Tester settings and confirm:
    EA, symbol, timeframe, dates, modeling and initial deposit.
  2. Launch the optimization with clear ranges and criterion:
    Launch an optimization of the "EMACrossover" EA on EURUSD H1,
    from Jan 1, 2024 to Dec 31, 2025, varying:
    - Fast EMA from 10 to 30 (step 2)
    - Slow EMA from 40 to 100 (step 5)
    Criterion: recovery factor.
  3. Read and compare the results:
    When it finishes, read the report and compare the top 5 passes:
    net profit, maximum drawdown, profit factor and number of trades.
  4. Look for overfitting:
    Are these 5 passes in a stable parameter region
    or are they isolated peaks? Point out signs of overfitting.
  5. Check for errors:
    Read the tester log and the EA logs and list any errors or warnings.

⚠️ Important

The AI reads the numbers in the report, but the decision to trust them is yours. A pass with high profit and few trades is almost always overfitting.

Anti-overfitting checklist (use it with the AI)

  • Hold out an out-of-sample period: optimize on 2024–2025 and validate on 2026 without touching the parameters.
  • Run walk-forward analysis: optimize and validate on windows that roll forward in time.
  • Require a minimum sample: discard passes with few trades (use 100+ as a benchmark).
  • Prefer plateaus to peaks: if EMA 18 works and EMA 16 and 20 are a disaster, there’s no robustness.
  • Include real costs: your broker’s spread, commission and swap.
  • Forward test on demo before any live account.

When I tested 20 strategies on real data, most of them didn’t survive out of sample. The numbers are in The 70% win rate is a myth.

What about Claude Code, Codex and other external agents?

MetaQuotes states that, in addition to the built-in assistant, external MCP-compatible systems such as OpenAI Codex and Claude Code can connect to MT5. As of this article’s date, however, the release notes don’t include an official step-by-step for that connection. Before building anything, check the MetaQuotes documentation and your terminal’s AI settings.

An alternative that already works is your own MCP server in Python, using the official MetaTrader5 library. The MQL5 community published an article on this approach in April 2026. Below is a minimal, read-only example:

# pip install mcp MetaTrader5
from mcp.server.fastmcp import FastMCP
import MetaTrader5 as mt5

mcp = FastMCP("mt5-readonly")

def connect():
    # uses the MT5 terminal already open and logged in on this machine
    if not mt5.initialize():
        raise RuntimeError(f"Failed to connect: {mt5.last_error()}")

@mcp.tool()
def account() -> dict:
    """Account balance, equity, free margin and leverage."""
    connect()
    info = mt5.account_info()
    return {"balance": info.balance, "equity": info.equity,
            "free_margin": info.margin_free, "leverage": info.leverage}

@mcp.tool()
def candles(symbol: str, count: int = 100) -> list:
    """Latest H1 candles for the symbol."""
    connect()
    rates = mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_H1, 0, count)
    if rates is None:
        return []
    return [{"time": int(r["time"]), "open": float(r["open"]),
             "high": float(r["high"]), "low": float(r["low"]),
             "close": float(r["close"])} for r in rates]

@mcp.tool()
def positions() -> list:
    """Open positions (read-only)."""
    connect()
    return [p._asdict() for p in (mt5.positions_get() or [])]

if __name__ == "__main__":
    mcp.run()  # stdio transport

To use it in Claude Desktop, add the server to the claude_desktop_config.json file (on Windows, in %APPDATA%\Claude\):

{
  "mcpServers": {
    "mt5": {
      "command": "C:\\Python312\\python.exe",
      "args": ["C:\\mt5-mcp\\server.py"]
    }
  }
}

In Claude Code, the equivalent is claude mcp add mt5 -- python C:\mt5-mcp\server.py. Adjust the paths to match your machine.

⚠️ Limitations of this alternative

  • The MetaTrader5 library only runs on Windows, on the same machine as the terminal.
  • It’s single-threaded: simultaneous calls can cause problems.
  • Start read-only. If you add order tools, require confirmation and test on demo.

Security: what I wouldn’t do

  • I wouldn’t give an agent permission to trade on a live account. In the AI Assistant, keep trading prohibited or under manual confirmation.
  • I wouldn’t paste the account password into the chat or into files the agent reads.
  • I’d use the build 6060 access levels, if your broker offers them: the “Trader” password allows trading, but not withdrawals or password changes.
  • I’d keep network and command line access off for the AI, unless I needed them.
  • I’d review the terminal and EA logs after every session with the agent.

Frequently asked questions

What is MetaTrader 5 MCP?

It’s MT5’s native support for the Model Context Protocol, which lets AI agents access market data, charts, the trading environment and, since build 6180, the Strategy Tester.

Can the AI optimize my EA on its own?

Since build 6180 it launches optimizations and reads the reports. You still define the parameter ranges and the criterion, and you decide whether the result is robust.

Do I need to know how to code?

To use MCP through the built-in AI Assistant, no. To build your own MCP server in Python, basic Python knowledge helps a lot.

Is it safe?

It depends on the permissions. With trading prohibited or under confirmation, and testing on demo, the risk stays under control.

Sources: build 6060 release notes · build 6180 announcement · MT5 release history · MQL5 article on a Python MCP server. Checked in September 2026.

🚀 To test optimizations and agents without risking money, free Deriv MT5 demo ($10,000 virtual):

Open Deriv MT5 Demo →

DM

Dan Machado

Founder IA Trader Pro · AI-for-trading specialist

⚠️ Disclaimer: Educational content, not investment advice. Trading involves substantial risk. AI tools do not guarantee profit and can make mistakes. Always test on demo before trading with real capital. This article contains a Deriv affiliate link.

Similar Posts