mt5-mcp
This server exposes MetaTrader 5 account, market-data, and trading tools over MCP.
Health-check MT5 terminal reachability (
ping) and read terminal/broker connection details.Read account balance, equity, margin, leverage, margin mode, and trade permission.
Get symbol quotes, list tradeable instruments with contract/tick/margin/swap metadata, and check market open status.
Fetch OHLC bars for standard timeframes and calculate broker-authoritative margin for hypothetical orders.
List open positions and pending orders.
Place market or pending orders with optional SL/TP/deviation/comment.
Modify SL/TP on positions or price/expiration on pending orders.
Cancel pending orders.
Close positions fully or partially by ticket.
Retrieve closed-deal/trade history within a time range.
Mutating calls support idempotency keys and optional human-approval confirmation fields.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mt5-mcp show my current positions and account equity"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MetaTrader 5 MCP Bridge
Let an AI agent manage your MetaTrader 5 account over Model Context Protocol - with configurable human approval gate.
โ ๏ธ This software places real trades through your MetaTrader 5 terminal with real orders and irreversible fills. Read DISCLAIMER.md and SECURITY.md before connecting it to a live account. Always test using your demo account first.
Runs locally - in the same process tree as your agent, no cloud, no telemetry. Windows (native) or Linux (via Docker); Python 3.10+.
๐ The story behind this: this project is built step by step in Wiring AI agent into MetaTrader 5, Part 1 of the Trade with AI agent series on the Fintrix engineering blog.
What it is
mt5-mcp lets an AI agent read your MetaTrader 5 account and place trades
through it, over the Model Context Protocol.
12 read-only tools: account, quotes, positions, orders, history, OHLC bars, broker-authoritative margin estimates, and native chart screenshots (Windows). No consent gate.
4 mutating tools:
place_order,modify_order,cancel_order,close_position, each behind a preflight + human-consent + idempotency + audit layer.3 subscribable resources: live
account://,positions://, andquotes://{symbol}snapshots that push change notifications.3 ready-to-use Claude Code skills ship in
.claude/skills/:mt5-market-dataandmt5-tradingteach an agent how to read the account and run the consent flow safely;mt5-mql5-buildteaches the MQL5 compile loop.
Full catalogue and the consent flow: docs/tools.md.
Related MCP server: MetaAPI MCP Server
Why mt5-mcp
A safety layer, not just an API wrapper. Every mutating call routes through preflight checks -> an opt-in human-consent gate (arm it to require approval) -> idempotency -> an append-only audit log, so you can put a human in the loop on trades and always keep a replayable record of what the agent did.
An honest threat model. It treats an LLM wired to
place_orderas a live attack surface and says so plainly - the MCP is explicitly not the security boundary (see SECURITY.md).Verifiable proof, not a mock-up. The demo above is a real round-trip; the tickets and balance match MetaTrader 5's own History tab.
Local-first. No cloud, no telemetry; runs beside your agent. Windows-native or Linux via an all-in-one Docker image (no
rpycversion-matching).
Quickstart (Windows, native)
pip install mt5-trading-mcpLaunch MetaTrader 5 and log into your broker. Enable AlgoTrading (toolbar button green).
Verify the terminal is reachable:
python -m mt5_mcp doctor: expect[INFO] backend: nativeand[PASS]lines.Run it:
python -m mt5_mcp serve.
Wire it to OpenClaw in one command (registers the mcp.servers entry):
openclaw mcp set mt5-mcp '{"command":"python","args":["-m","mt5_mcp","serve"]}'Quickstart (Linux, Docker)
The MT5 terminal + the MCP run headless in an all-in-one image; your agent talks MCP over HTTP. No host Python, no bridge.
cp deploy/.env.example deploy/.env # add MT5_LOGIN / MT5_PASSWORD / MT5_SERVER
docker compose -f deploy/docker-compose.yml up -dLog the terminal in once via the KasmVNC web UI at http://127.0.0.1:3001
(File -> Login to Trade Account; persists across restarts), then point your
agent at http://127.0.0.1:8765/mcp. Wire it to OpenClaw in one command:
openclaw mcp set mt5-mcp '{"url":"http://127.0.0.1:8765/mcp","transport":"streamable-http"}'The image runs Wine 11.10 staging, which runs current MT5 builds (Wine 10 could
not run builds newer than 28 Sep 2026). The terminal is no longer pinned, so
MT5's LiveUpdate keeps it current. To build and backtest EAs on Linux, use the
backtest container in deploy/docker-compose.backtest.yml (see
docs/agents.md).
Known issue: fresh volumes. A new terminal does not know your broker's server, and its Login dialog can draw as a black box under Wine, so it never logs in (the MCP server then reports IPC timeouts). Workaround, once per volume:
Copy
servers.dat(server addresses only) from a terminal that knows the broker, e.g. a Windows install's%APPDATA%\MetaQuotes\Terminal\<id>\config\, into/config/.wine/drive_c/Program Files/MetaTrader 5/Config/(ownerabc).Log in with a one-off start config: stop the terminal and run
terminal64.exe "/config:C:\autologin.ini"asabc, where the ini has[Common]Login=,Password=,Server=andKeepPrivate=1. Delete the ini once the journal saysauthorized.So the login survives restarts, add
Login=andServer=(no password) under[Common]inConfig/common.ini(UTF-16) while the terminal is stopped.
Full walkthrough: docs/installation.md.
Chart screenshots
get_chart_screenshot(symbol, timeframe, annotations?) returns a PNG of the
native MT5 chart, optionally annotated, so an LLM can read it visually
(candles, support/resistance, patterns). Because the MetaTrader5 Python API
cannot capture charts, this uses a small MQL5 Expert Advisor that runs inside
a GUI terminal and calls ChartScreenShot().
See Chart annotations for marking up support/resistance lines, trendlines and notes before capture.
Setup (one time):
Install and attach the
AgentScreenshotEA - seemql5/README.md.Optionally set a template so your indicators/drawings appear in the shot:
[screenshot]template = "agent.tpl"in your config, or leave it unset for the default chart.
Config knobs ([screenshot] section): width (default 1600), height
(default 900), template (default none), timeout_s (default 10).
Docker: the image preinstalls the EA, the light template and a startup ini on
every boot, so no manual setup is needed. Set MT5_EA_SYMBOL (default
BTCUSD) to a symbol your account has, otherwise screenshots time out. The
light template is wired in only when the first boot seeds config.toml; on a
volume that already has one, add [screenshot] template = "agent_light.tpl"
by hand (an existing config.toml also ignores MT5_MCP_AUTH_TOKEN).
Elsewhere (macOS, native Linux) the tool returns SCREENSHOT_NOT_SUPPORTED.
Build MQL5 with an agent
mt5-mcp compile <file.mq5> compiles an Expert Advisor, indicator or script
with your local MetaEditor (Windows) and prints one line per problem
(src/MyEA.mq5:42:7: error 256: ...). An agent with a shell runs it, fixes
the errors and reruns until it exits 0. Clean builds install to
MQL5\<Kind>\Agent\ in the terminal's data folder; you attach them
yourself. Reinstalling an EA that is attached to a live chart reloads the new
code on that chart. Agents get the loop from the mt5-mql5-build skill.
Exit codes: 0 built, 1 compile errors, 2 could not run. On Linux both
commands run in the backtest container (deploy/docker-compose.backtest.yml)
via docker exec mt5-backtest mt5-mcp ....
mt5-mcp backtest <ea.ex5> then runs the Strategy Tester on that build
(single run, or --optimize full|genetic with a forward test on by default)
and prints a short summary or a ranked table of input sets. It runs on a
separate copy of MT5 made once with mt5-mcp backtest --setup, so your live
terminal is never touched. Windows (from a logged-in desktop session) or the
Linux backtest container.
For AI agents
If you've been handed this repository to install and run, follow the runbook in docs/agents.md. It covers platform detection, install, verification, registering the server, and the hard safety rules for trades - read it before calling any mutating tool.
Documentation
Guide | What's in it |
Requirements, Windows + Linux/Docker setup, wiring to an agent. | |
Step-by-step runbook for an agent installing and running the server. | |
| |
Read tools, mutating tools + consent flow, subscribable resources. | |
Per-client config snippets and Claude Code usage. | |
stdio/HTTP transports and Windows VPS patterns. | |
How to contribute and run the tests. | |
Release history and known limitations. |
Safety
mt5-mcp is not the security boundary, the broker's MT5 server enforces
the hard limits (margin, max-lot, symbol permissions). Pre-flight checks in the
policy engine are UX guardrails to catch agent mistakes early, not security
controls.
The human-consent gate is opt-in and off by default: auto_approve_notional
defaults to 0, so mutating calls auto-execute (full-open) - intended for trusted
or unattended agents. Arm the gate by setting auto_approve_notional > 0:
orders/closes whose notional is at or above it then return an ApprovalPreview
you must confirm, and modifying a stop to widen or remove it also requires
approval. The pre-flight limits (max_*) and symbol allow/deny lists are likewise
opt-in (0 / empty = off). Every mutating call is recorded in an append-only audit
JSONL log regardless. For vulnerability disclosure, see
SECURITY.md.
Architecture
mt5-mcp wraps the MetaTrader 5 Python library behind a FastMCP server. A single MT5Client (src/mt5_mcp/adapter/) owns the terminal connection, broker-timezone inference, and type conversions; everything else sits on top of it. The Pydantic models in src/mt5_mcp/types.py / src/mt5_mcp/config.py are the source of truth for the data and config schemas.
Agent / MCP client (Hermes, OpenClaw, Claude Code, Claude Desktop, โฆ)
โ
โ stdio ยท loopback HTTP
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FastMCP server โ
โ โ
โ tools/ resources/ policy/ โ
โ read + subscribable consent ยท idempotency โ
โ mutating account/quotes ยท audit (JSONL) โ
โ โ
โ streaming/ - change-detection poller + dispatcher โ
โ types.py ยท config.py - Pydantic schemas: source of โ
โ truth for data + config โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ adapter/ MT5Client โ
โ one terminal connection ยท broker-TZ inference ยท โ
โ type conversions ยท transparent reinit โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
MetaTrader 5 Python library -> broker terminal -> broker serverThe module paths shown (tools/, resources/, policy/, streaming/,
adapter/, types.py, config.py) all live under src/mt5_mcp/.
Contributing
Contributions are welcome, see CONTRIBUTING.md for the dev setup, test workflow, and project principles.
License
MIT - see LICENSE.
Available Tools
15 toolscalc_marginA
Broker-authoritative margin for a hypothetical order.
Wraps mt5.order_calc_margin. If price is omitted, uses the
current ask (buy) / bid (sell). Returned margin is in deposit
currency.
Inputs: symbol (required), side (required), volume (required), price. Returns: Broker-authoritative margin computation for a hypothetical order.
cancel_orderA
Cancel a pending order by ticket. No consent gate (reduces exposure).
Inputs: ticket (required), idempotency_key.
close_positionB
Close an open position in full or part by ticket.
Inputs: ticket (required), volume, idempotency_key, approval_confirmed, +1 more.
get_account_infoC
Balance, equity, margin, leverage, currency, margin mode.
Inputs: no named parameters. Returns: login, name, server, currency, +8 more
get_historyB
Closed deals (trades) within [from_ts, to_ts]. Timestamps must be ISO 8601 UTC.
Inputs: from_ts (required), to_ts (required), symbol. Returns: result
get_market_hoursA
Whether the given symbol's session is open right now.
v1 limitation: is_open is derived from trade_mode (open
when non-zero). next_open and next_close are always
None in v1 - parsing symbol_info().sessions_quotes is
scheduled for a later release. Agents needing precise session
boundaries should consult their broker's published schedule.
Inputs: symbol (required). Returns: symbol, is_open, next_open, next_close
get_ordersB
Pending orders, optionally filtered to a single symbol.
Inputs: symbol. Returns: result
get_positionsC
Open positions, optionally filtered to a single symbol.
Inputs: symbol. Returns: result
get_quoteA
Current bid/ask for a symbol. Prepares the symbol in Market Watch if needed.
Inputs: symbol (required). Returns: symbol, bid, ask, time
get_ratesA
OHLC bars for symbol at timeframe, most recent first.
timeframe: one of M1, M5, M15, M30, H1,
H4, D1, W1, MN1. count is clamped to
[1, 5000].
Inputs: symbol (required), timeframe (required), count (required). Returns: result
get_symbolsA
List tradeable instruments, optionally filtered by category (e.g. 'Forex', 'Metals').
Inputs: category. Returns: result
get_terminal_infoB
MT5 terminal connection state and broker TZ offset.
Inputs: no named parameters. Returns: connected, build, name, company, +4 more
modify_orderA
Modify SL/TP on a position or price/expiration on a pending order.
When the consent gate is armed (policy.auto_approve_notional > 0),
widening or removing an existing SL/TP requires approval; tightening
always auto-approves. At the default of 0 the gate is off and every
modify auto-executes.
Inputs: ticket (required), sl, tp, price, +4 more.
pingA
Health check - verifies the MT5 terminal is reachable.
Returns {"ok": bool, "latency_ms": int, "via": str | None}.
via names the layer that answered (terminal_info,
account_info, or tick_probe) and is omitted when ok
is false. Cheap; agents should call this after idle periods or
errors that smell like disconnection.
Inputs: no named parameters. Returns: object
place_orderA
Place a market or pending order. Optional SL / TP / deviation.
When policy.auto_approve_notional is set > 0, orders whose notional is
at or above it return an ApprovalPreview; retry with
approval_confirmed=true and the same request fields to proceed. At the
default of 0 the gate is off and orders auto-execute. Pass
idempotency_key (UUIDv4 recommended) to dedupe retries within
idempotency.ttl_seconds.
Inputs: symbol (required), side (required), type (required), volume (required), +9 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 15 tools
Each tool targets a distinct trading operation: margin calculation, order management, position closing, account info, market data retrieval, health check, etc. There is no functional overlap between tools.
Tool names consistently follow a verb_noun pattern (e.g., get_quote, place_order, close_position). The only exception is 'ping', which is a standard minimal verb for health checks, maintaining overall consistency.
15 tools is well-suited for an MT5 server, covering essential operations like account info, market data, order lifecycle, and positions. It is neither too sparse nor overly heavy.
The tool set covers the core trading lifecycle (market data, order placement/cancellation/modification, position closing, history) and account info. Minor gaps exist (e.g., trailing stops or news), but the essential functionality is present.
Maintenance
Related MCP Connectors
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
MCP server for OpenMM โ exposes market data, account, trading, and strategy tools to AI agents
Hosted MCP server for MT4 and MT5: read accounts, prices and candles, and place or close orders.
Deterministic pre-trade risk firewall and portfolio MCP server for AI agents (IBKR, Alpaca).
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceAn open-source AI trading agent for MetaTrader 5 with MCP support, connecting AI clients to MT5 for market data, analysis, and risk-gated trading.MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol (MCP) server that provides AI assistants like Claude with direct access to MetaAPI trading platform. Trade forex, stocks, and commodities through natural language conversations.1MIT
- AlicenseNot gradedqualityCmaintenanceA local-first MCP server that bridges AI coding agents with MetaTrader 5 for inspection, market data, MQL5 development, compiling, Strategy Tester review, workspace sync, logs, audit trails, demo trading, and carefully gated live trading.MIT
- AlicenseNot gradedqualityCmaintenanceMCP server for AI agents to inspect and trade against a MetaTrader 4 terminal, with an offline mock mode for CI and demos.3MIT