metatrader5-mcp
The metatrader5-mcp server bridges AI clients like Claude to a MetaTrader 5 terminal for read-only data, market analysis, MQL5 development, and backtesting preparation — never executing live trades.
Read-Only Market & Account Data
Account balance, equity, margin, leverage, and trade mode
Terminal connection state, build version, and data paths
Symbol specifications, latest ticks, and OHLCV bar data
Open positions, pending orders, and historical deals
MT5 terminal/expert logs and Strategy Tester HTML reports
Performance & Market Analysis
Summarize open positions by symbol and side (long/short)
Compute peak-to-trough drawdown with optional equity curve
Analyze trade history: win rate, profit factor, trade averages
Calculate basic risk/reward ratios from entry, SL, and TP prices
Hypothetical Order Planning (requires explicit human approval, demo accounts only, never sent to market)
Calculate required margin and estimated profit/loss
Run MT5's server-side
order_checkvalidationBuild full order plans including margin, P&L, and validation results
MQL5 Code Development
Read, diff, draft, backup, restore, and review MQL5 source files
Generate EA, indicator, and script templates
Create, update, patch, rename, and delete files (with approval, backups, and rollback)
Fix compile errors and manage file mutations
MetaEditor & Strategy Tester
Prepare and run compilation; parse errors/warnings; generate fix plans
Prepare signal-only backtests, validate tester configurations
Import, collect, compare, and generate backtest reports
Environment & Workspace Management
Detect terminal path, MetaEditor, data folders, and MQL5 folder
Sync workspace files to the MT5 Data Folder (with approval and backup)
Audit & Introspection
List and inspect tool policies and permission levels
Read the server's audit log of all executed actions
What it cannot do: No order execution, modification, or cancellation. All trading-related tools are planning-only, restricted to demo accounts, and blocked on real/contest accounts. Chart, EA runtime, and live account tools are strictly disabled.
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., "@metatrader5-mcp show my current positions"
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.
metatrader5-mcp
A local MCP (Model Context Protocol) server that connects Claude (or any MCP client) to a running MetaTrader 5 terminal.
A user-directed bridge between you, Claude, and MetaTrader 5. You can ask for
read-only market/account data, performance analysis, MQL5 development (read /
draft / diff / backup / approved file changes), compile and backtest preparation,
and report review. The design principle is user authority broad, model autonomy
narrow: every tool is governed by a ToolPolicy (permission level 0–5), the
model never auto-initiates a risky action, and file/runtime changes require
explicit human approval with a diff, a backup, a rollback point, and an audit
entry. No tool sends, modifies, or cancels an order; live trading is never
implemented. Chart/EA-runtime and live-account tools are declared in the policy
model but disabled by default. This is a tool-rich development bridge, not a
trading bot.
Naming
The two names below differ intentionally:
Repository / project identity:
metatrader5-mcpInstallable package / command:
mt5-mcp(the Python import package ismt5_mcp, andpip install -e .also exposes anmt5-mcpconsole command)
Related MCP server: metatrader-mcp
Requirements
Windows, with a running MetaTrader 5 terminal (the
MetaTrader5Python package only works on Windows, next to the terminal). On other platforms the server still runs and lists its tools, but every tool that touches MT5 will raise a clearMT5NotAvailableError.Python 3.10+
New to this on Windows? Follow
docs/QUICKSTART_WINDOWS.mdfor a step-by-step setup, first tool calls, and a smoke-test checklist.
Install
python -m venv .venv
.venv\Scripts\activate # Windows
pip install -e .Configure
Copy .env.example to .env and adjust as needed. Nothing here is a secret
that gets committed - .env is gitignored, and the server never logs your
password.
cp .env.example .envKey settings:
Variable | Default | Purpose |
| unset | Optional explicit terminal/account to connect to. If unset, attaches to the terminal already running on the machine. |
|
|
|
|
| In |
|
| Order-planning tools are disabled even on a demo account unless this is |
|
| Where |
|
| Directory that |
|
| MQL5 source root the file/code tools are confined to. Point at the terminal's |
|
| Where file mutations write backups + rollback metadata, and where snapshots go. |
|
| Where |
| unset | Full path to |
| unset | The terminal's Data Folder. |
|
| Where tester |
Run the server locally
python -m mt5_mcp.serverThis starts the MCP server over stdio. Point any MCP client (Claude Desktop,
Claude Code, the mcp Python client, etc.) at this command. Example Claude
Desktop / Claude Code config:
{
"mcpServers": {
"metatrader5": {
"command": "python",
"args": ["-m", "mt5_mcp.server"],
"cwd": "/path/to/metatrader5-mcp"
}
}
}See examples/example_client.py for a minimal standalone client that lists
tools and calls one tool per permission tier (read, analysis, and a
planning-only call that is never sent). examples/claude_desktop_config.example.json
and examples/claude_code_config.example.json show client wiring with the
venv's python.exe and an absolute cwd. docs/EXAMPLES.md walks through
usage by tool group.
Before pointing a client at the server, you can run the read-only readiness helper to confirm your environment (it never plans or sends orders):
python scripts/mt5_readiness_check.pyWhat's implemented
SAFE_READ (always allowed, logged, no approval needed):
get_account_info, get_terminal_info, get_symbol_info, get_tick,
get_rates, get_positions, get_orders, get_history_deals, read_log,
read_strategy_report.
SAFE_ANALYSIS (pure computation over data you already read, no approval
needed): summarize_positions, analyze_drawdown, analyze_trade_history,
calculate_profit_risk_basic.
REQUIRES_APPROVAL (order planning - margin/profit math and MT5's own
dry-run order_check; a human must approve every call, and the risk guard
still requires a demo account with MT5_MCP_ENABLE_DEMO_TRADING=true):
calculate_margin, calculate_profit, check_order, prepare_order_plan.
Bridge tools (governed by ToolPolicy; see list_tool_policies):
Workspace/code, Level 0/1 — workspace status & listing,
mql5_file_read,mql5_file_diff,mql5_file_write_draft,mql5_file_backup,mql5_code_review,mql5_code_generate_ea/indicator/script,mql5_code_fix_compile_error. No approval; never mutate a real source file.File mutations, Level 2 —
mql5_file_create/update/apply_patch/rename/delete/ restore/revert_patch,workspace_restore_snapshot. Approval required, with backup + diff + rollback id.Environment, Level 0 —
mt5_env_detect(terminal path, MetaEditor, Data Folder(s), MQL5 folder, reports/logs; env-var-honoring, Windows auto-detect, never raises).Data Folder sync —
workspace_plan_sync(L1 preview) andworkspace_sync_to_data_folder(L2; approval + backup + rollback; requires explicitMT5_MCP_DATA_FOLDER).MetaEditor/Tester, Level 0/1 + gated Level 3 —
metaeditor_prepare_compile,metaeditor_parse_errors/warnings,metaeditor_generate_fix_plan,tester_prepare_signal_only_test,tester_validate_config,tester_import_csv/html,tester_collect_reports,tester_review_results,tester_compare_runs,tester_generate_backtest_report; plus the gatedmetaeditor_run_compile/tester_run_backtest_if_supported(Windows only; tester run is validated-[Tester]-only).Audit/introspection, Level 0 —
list_tool_policies,get_tool_policy,read_audit_log.
Declared but disabled (Level 4/5) — mt5_chart_*, mt5_ea_*, mt5_live_*
are in the policy model but not registered as tools in this phase.
BLOCKED (not implemented at all - no tool by these names exists, and the router refuses them by name as a safety net): sending, modifying, or cancelling any order; live trading in general.
See docs/TOOLS.md for full parameter reference, docs/EXAMPLES.md for usage
examples by tool group, docs/TROUBLESHOOTING.md for a symptom → cause → fix
guide, docs/SECURITY_MODEL.md for the canonical safety model (how the approval
gate and risk guard work, and what is intentionally excluded), and
docs/ARCHITECTURE.md for the module layout and request flow. docs/SAFETY.md
is a short summary that points to docs/SECURITY_MODEL.md. See
docs/RELEASE_CHECKLIST.md for the maintainer checklist used before tagging a
release.
Run the tests
pip install -e ".[dev]"
pytestTests run against a fake in-memory MT5 module (see tests/conftest.py), so
they pass on any platform without a real terminal.
Known limitations
No order execution (
order_send) - intentionally not implemented.No VPS/remote mode, no plugin system, no multi-strategy framework.
get_ratesonly supports the "most recent N bars" mode (copy_rates_from_pos), not arbitrary date ranges.read_strategy_reportuses a generic HTML table parser (label/value cell pairing); unusual report layouts may need raw row inspection.The file-based approval mode polls the filesystem; it is not push-based.
No persistence/database - approvals and logs are plain files.
Available Tools
18 toolsanalyze_drawdownA
Compute basic peak-to-trough drawdown from history deals (fetched live if deals is omitted).
Inputs: deals, date_to, date_from, include_curve, +1 more.
analyze_trade_historyB
Compute win rate / profit factor / averages from history deals (fetched live if deals is omitted).
Inputs: deals, date_to, date_from.
calculate_marginA
Calculate required margin for a hypothetical order. Requires approval; demo accounts only; never sent.
Inputs: price (required), symbol (required), volume (required), order_type (required).
calculate_profitB
Calculate hypothetical profit/loss between two prices. Requires approval; demo accounts only; never sent.
Inputs: symbol (required), volume (required), order_type (required), price_open (required), +1 more.
calculate_profit_risk_basicA
Pure price-math risk/reward ratio calculation. No MT5 connection or symbol lookup needed.
Inputs: stop_loss (required), entry_price (required), take_profit (required), volume, +1 more.
check_orderB
Run MT5's server-side order_check validation for a hypothetical order. Requires approval; demo only; never sent.
Inputs: price (required), symbol (required), volume (required), order_type (required), +5 more.
get_account_infoA
Get the connected MT5 account's balance, equity, margin, leverage, and trade mode.
Inputs: no named parameters.
get_history_dealsB
List historical deals between date_from/date_to (ISO dates), or by ticket/position.
Inputs: group, ticket, date_to, position, +1 more. Returns: result
get_ordersB
List active pending orders, optionally filtered by symbol or ticket.
Inputs: symbol, ticket. Returns: result
get_positionsC
List open positions, optionally filtered by symbol or ticket.
Inputs: symbol, ticket. Returns: result
get_ratesB
Get OHLCV bars for symbol on timeframe (e.g. M1, M15, H1, H4, D1).
Inputs: symbol (required), timeframe (required), count, start_pos. Returns: result
get_symbol_infoA
Get full symbol specification (point, digits, contract size, spread, limits) for symbol.
Inputs: symbol (required).
get_terminal_infoA
Get MT5 terminal status: connection state, data path, build, trade-allowed flags.
Inputs: no named parameters.
get_tickB
Get the latest bid/ask/last tick for symbol.
Inputs: symbol (required).
prepare_order_planB
Build a full order plan (request + margin + estimated P/L + order_check). Requires approval; demo only; NEVER sent.
Inputs: price (required), symbol (required), volume (required), order_type (required), +5 more.
read_logA
Read the tail of an MT5 log file for date (YYYYMMDD, default today). kind: 'terminal' or 'experts'.
Inputs: date, kind, lines.
read_strategy_reportA
Parse an MT5 Strategy Tester HTML report into a summary dict and raw table rows.
Inputs: path (required).
summarize_positionsB
Summarize open positions by total, symbol, and side. Fetches live positions if positions is omitted.
Inputs: positions.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 18 tools
Each tool has a distinct purpose. Analysis tools are differentiated (drawdown vs. trade history vs. profit calculation variants). Data retrieval tools are separate (rates, ticks, symbols, account, terminal). No overlapping functionality.
All tools follow a consistent verb_noun snake_case pattern: get_*, analyze_*, calculate_*, check_*, prepare_*, read_*, summarize_*. No mixing of conventions.
18 tools are well-scoped for a MetaTrader 5 assistant covering account info, market data, position/order status, trade analysis, risk calculation, and logging. Not overwhelming or insufficient.
The tool surface covers core functionalities (data retrieval, analysis, planning) but lacks order execution (place, modify, close). Since several tools explicitly state 'never sent' (demo only), this appears intentional, leaving a minor gap for an analytical MCP.
Related MCP Connectors
Read-only access to your MetaTrader 4 and 5 accounts for AI agents: balances, open positions, trade history with win rate, live quotes, symbol specs and candles. It cannot place, modify or close orders.
Read-only MetaTrader 5 for AI agents: balances, positions, history and prices. Sign in with OAuth.
Connect any MCP client to MetaTrader 4/5 to read prices, manage positions, and place trades.
Read and trade MT5 accounts, read-only unless you allow, plus MarketLabs calendar, COT and research.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceProvides read-only access to MetaTrader 5 market data, trading history, and technical analysis through Python execution. Supports querying price data, calculating indicators, creating charts, and generating forecasts with Prophet and ML models.64 PyPI3MIT
- AlicenseNot gradedqualityDmaintenanceEnables users to capture real MetaTrader 5 chart snapshots with custom indicators and fetch market data through natural language in Claude Desktop.3MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI assistants to connect to MetaTrader 5 for trading, market data access, and account management through the Model Context Protocol.107 PyPI245MIT
- AlicenseNot gradedqualityDmaintenanceEnables interaction with MetaTrader 5 for market data, technical analysis, Fibonacci calculations, and trading via MCP clients such as Claude.MIT