mt5-mcp
by alikhande70
README.md
# mt5-mcp
<p align="center">
<img src="docs/assets/banner.svg" alt="MT5 MCP — a safe MetaTrader 5 bridge for Claude and ChatGPT" width="100%">
</p>
<p align="center"><b>A local-first <a href="https://modelcontextprotocol.io">MCP</a> server that bridges Claude and ChatGPT with MetaTrader 5 — safely.</b></p>
<p align="center">
<a href="https://github.com/alikhande70/Mt5_mcp/actions/workflows/tests.yml"><img src="https://github.com/alikhande70/Mt5_mcp/actions/workflows/tests.yml/badge.svg" alt="CI"></a>
<img src="https://img.shields.io/badge/license-MIT-22d3ee?style=flat-square" alt="License: MIT">
<img src="https://img.shields.io/badge/python-3.11%2B-38bdf8?style=flat-square" alt="Python 3.11+">
<img src="https://img.shields.io/badge/protocol-MCP-67e8f9?style=flat-square" alt="MCP">
<img src="https://img.shields.io/badge/tools-70-a78bfa?style=flat-square" alt="70 tools">
<img src="https://img.shields.io/badge/local--first-yes-fbbf24?style=flat-square" alt="Local-first">
</p>
MetaTrader 5 automation today means bouncing between the terminal, MetaEditor,
the file explorer, and the Strategy Tester by hand. `mt5-mcp` puts all of that
behind **one MCP server** so an AI agent can read your account, write and
compile MQL5 code, sync a local workspace with your MT5 data folder, and analyze
backtests — as a normal part of a coding session, with everything it does
audited for you to review afterwards.
**Claude** connects over stdio; **ChatGPT** connects over Streamable HTTP at a
`/mcp` endpoint. Both drive the *same* engine, with the *same* safety gates —
so when Claude is unavailable, ChatGPT can pick up the exact same workflow.
## Quick start
Requires Python 3.11+.
```bash
git clone https://github.com/alikhande70/Mt5_mcp.git
cd Mt5_mcp
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\Activate.ps1
pip install -e ".[dev]"
# Claude (stdio) — the default:
mt5-mcp
# ChatGPT (HTTP /mcp) — full parity, token required:
MT5_MCP_PROFILE=chatgpt_full \
MT5_MCP_TRANSPORT=streamable-http \
MT5_MCP_HTTP_TOKEN="$(openssl rand -hex 24)" \
mt5-mcp
```
The full suite runs **without** MetaTrader5 installed, so you can develop and
test the toolkit on any platform. Real MT5 tools activate on Windows where the
terminal lives. See [Setup & configuration](#setup--configuration) for details.
## Architecture overview
<p align="center">
<img src="docs/assets/overview.svg" alt="Architecture: Claude and ChatGPT connect through the MCP bridge to a MetaTrader 5 terminal and its domains" width="100%">
</p>
There is exactly **one engine**: `tool_registry.py` (what tools exist),
`action_router.py` (audit → execute), and the `mt5_mcp.*_tools` domain modules
(the actual MT5 / filesystem logic). Claude and ChatGPT are two *doors* into
that same engine — nothing is duplicated or forked per client. A single module,
`mt5_bridge.py`, is the only file that imports the `MetaTrader5` package, which
is why everything else — including the entire test suite — runs anywhere.
Every dispatched tool call is appended to `logs/audit.jsonl` before and after it
runs, so there is always a record of what happened. See
[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the module-by-module
breakdown.
## What it can do
<p align="center">
<img src="docs/assets/capabilities.svg" alt="Capabilities: account, market data, symbol tools, MQL5 files, compile, backtests, reports, workspace sync, demo trading, guarded live execution" width="100%">
</p>
**70 MCP tools** across the whole MetaTrader 5 workflow:
- **Read & inspect** — account/balance/margin, symbols, ticks and OHLC candles,
open positions, orders, and trade history.
- **MQL5 development** — read, search, diff, write, update, and generate
Experts / indicators / scripts (every overwrite and delete is backed up
first), then compile with the MetaEditor CLI.
- **Strategy Tester** — discover, import, parse, and `compare_backtests` on
Strategy Tester reports (net profit, drawdown, profit factor, recovery
factor, win rate, and more).
- **Workspace** — snapshot/restore/clean a local workspace and sync it both
ways with the MT5 `MQL5` folder.
- **Trading** — pure-Python position sizing / risk math, order planning and
validation, demo-only order submission, and consent-gated live execution.
Every tool works — or fails with a clear message — even when MetaTrader5 isn't
installed, MT5 isn't running, or MetaEditor can't be found. Full reference:
[`docs/TOOLS.md`](docs/TOOLS.md).
## Profiles
<p align="center">
<img src="docs/assets/profiles.svg" alt="Profiles: full and chatgpt_full are 70-tool parity profiles; chatgpt_safe is an optional 37-tool restricted profile" width="100%">
</p>
The active tool set is chosen by `MT5_MCP_PROFILE`:
| Profile | Tools | Transport | Purpose |
|---|---|---|---|
| `full` | 70 | stdio | **Default.** Claude Desktop / Claude Code — unchanged original behavior. |
| `chatgpt_full` | 70 | HTTP `/mcp` | **Recommended for ChatGPT.** Full parity with `full` — same tools, same safety gates, so ChatGPT can continue Claude's exact workflow. |
| `chatgpt_safe` | 37 | HTTP `/mcp` | **Optional, restricted.** Read / inspect / analyze only — no trading, no file writes, no compile, no broker credentials. |
`resolve_profile_specs("chatgpt_full")` returns the *identical* tool list as
`full` — parity is deliberate, not a filtered subset. `chatgpt_safe` is the one
profile that actually narrows the door, via an explicit allowlist. Full details:
[`docs/CHATGPT_MCP.md`](docs/CHATGPT_MCP.md).
## Workflow
<p align="center">
<img src="docs/assets/workflow.svg" alt="Workflow: inspect, analyze, apply approved changes, compile, backtest, inspect report, compare backtests" width="100%">
</p>
A typical development loop drives the tools end to end: **inspect** an EA or
files, **analyze** them, **apply** approved changes (backed up on write),
**compile**, **run a backtest**, **inspect the report**, and **compare
backtests** — then iterate. The same loop is available to Claude and to ChatGPT
under `chatgpt_full`. See
[`docs/BACKTEST_WORKFLOW.md`](docs/BACKTEST_WORKFLOW.md) and
[`docs/COMMAND_PLAYBOOK.md`](docs/COMMAND_PLAYBOOK.md).
## Safety model
<p align="center">
<img src="docs/assets/safety.svg" alt="Safety model: HTTP token and fail-closed auth; path confinement, backup before write, approval flow; demo-only guard and live-trade consent gate" width="100%">
</p>
The principle is **audit everything, block what matters** — defense in depth,
not a reflexive permission prompt on every call:
- **Transport perimeter** — the HTTP transports require a bearer token
(`MT5_MCP_HTTP_TOKEN`) checked in constant time, and **fail closed**: with no
token set, the server refuses to start rather than listen unauthenticated.
- **File & path guards** — every user-supplied path is confined to the
workspace or the detected MQL5 folder (no traversal escape), and every
overwrite or delete is backed up first.
- **Trading guards** — `order_send_demo_only` runs only on a confirmed demo
account (ambiguity fails closed), and the **only** tool call that can be
refused anywhere in the project — real-money execution — passes through the
live-trade consent gate: a short-lived consent record, an exact order-hash
match, and a human confirmation phrase, all before `mt5_bridge.order_send` is
ever reached.
See [`docs/ACCESS_MODEL.md`](docs/ACCESS_MODEL.md) for the reasoning and
[`docs/LIVE_TRADING_CONSENT.md`](docs/LIVE_TRADING_CONSENT.md) for the exact
consent flow.
## Setup & configuration
### Installation
Use a virtual environment — many Linux distros (and any "externally managed"
Python) refuse a bare `pip install -e ".[dev]"` outside one.
- `pip install -e .` — core server, works anywhere, no MT5 required.
- `pip install -e ".[mt5]"` — adds the `MetaTrader5` package (Windows only).
- `pip install -e ".[process]"` — adds `psutil` for process tools.
- `pip install -e ".[dev]"` — everything above plus pytest / ruff for development.
This registers the `mt5-mcp` console command.
### Windows quickstart
See [`docs/QUICKSTART_WINDOWS.md`](docs/QUICKSTART_WINDOWS.md) for the full
walkthrough. The short version:
```powershell
git clone https://github.com/alikhande70/Mt5_mcp.git
cd Mt5_mcp
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -e ".[dev]"
copy .env.example .env
python scripts\mt5_readiness_check.py
```
### MT5 & environment variables
`mt5-mcp` auto-detects the terminal, data folder, and MetaEditor from common
Windows install locations, or you can set them explicitly in `.env` (see
[`.env.example`](.env.example)). Run `mt5_readiness_check` (or
`python scripts/mt5_readiness_check.py`) any time to see exactly what was
detected and what's missing.
| Variable | Purpose |
|---|---|
| `MT5_TERMINAL_PATH` / `MT5_DATA_PATH` / `MT5_METAEDITOR_PATH` | Explicit MT5 paths (auto-detected if unset). |
| `MT5_MCP_PROFILE` | `full` (default), `chatgpt_full`, or `chatgpt_safe`. |
| `MT5_MCP_TRANSPORT` | `stdio` (default) or `streamable-http` / `sse`. |
| `MT5_MCP_HTTP_TOKEN` | **Required** for HTTP transports — bearer token. |
| `MT5_MCP_HTTP_ALLOW_NO_AUTH` | Local-dev-only override to run HTTP without a token (never for tunnels). |
| `MT5_MCP_LIVE_CONFIRM_PHRASE` | Human confirmation phrase for live-trade consent. |
## Claude usage
Copy [`examples/claude_desktop_config.example.json`](examples/claude_desktop_config.example.json)
into your Claude Desktop `claude_desktop_config.json`, adjusting the `env`
paths for your machine:
```json
{
"mcpServers": {
"mt5-mcp": {
"command": "mt5-mcp",
"env": { "MT5_TERMINAL_PATH": "C:\\Program Files\\MetaTrader 5\\terminal64.exe" }
}
}
}
```
For **Claude Code**, add the server the same way via
[`examples/claude_code_config.example.json`](examples/claude_code_config.example.json),
or run `mt5-mcp` directly and point Claude Code's MCP client at the stdio
process. Once connected, ask Claude to read your account summary, list open
positions, generate an EA draft, or summarize a Strategy Tester report — it
calls the matching tool and shows you the audited result.
## ChatGPT usage
ChatGPT connects over **Streamable HTTP** at `/mcp`. The main, recommended
profile is `chatgpt_full` — full parity with Claude's `full` profile, same
tools and same safety gates:
```bash
MT5_MCP_PROFILE=chatgpt_full
MT5_MCP_TRANSPORT=streamable-http
MT5_MCP_HTTP_TOKEN=<a long random string>
mt5-mcp
```
**HTTP auth is required by default.** If `MT5_MCP_HTTP_TOKEN` is unset the
server refuses to start (a `MT5_MCP_HTTP_ALLOW_NO_AUTH=true` override exists for
local-only development; never set it on anything reachable through a tunnel).
The token controls *who* can reach the server; once authenticated,
`chatgpt_full` grants the same capabilities Claude already has.
For a deliberately narrower connection, set `MT5_MCP_PROFILE=chatgpt_safe` — a
read / inspect / analyze-only profile with no trading, no writes, and no way to
submit broker credentials. It is optional, not the default. ChatGPT's custom
connectors need an HTTPS URL, so put a tunnel (cloudflared / ngrok) in front of
the local server — the full walkthrough, tunnel setup, and safety notes are in
[`docs/CHATGPT_MCP.md`](docs/CHATGPT_MCP.md).
### Broker symbol resolution
Every symbol in this project's docs and examples — `EURUSD`, `XAUUSD`,
`GBPUSD`, or any other ticker — is an **example, not a limitation**. Any symbol
your connected broker supports can be requested (in any name or language); the
agent resolves it dynamically against the real broker symbol list
(`mt5_symbols_list`) before use. Full rule and alias table:
[`docs/CLAUDE_CODE_AUTOMATION.md`](docs/CLAUDE_CODE_AUTOMATION.md#broker-symbol-resolution).
## Documentation
| Doc | What's inside |
|---|---|
| [`ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Module-by-module breakdown, layering, the audit flow. |
| [`ACCESS_MODEL.md`](docs/ACCESS_MODEL.md) | Why "audit everything, block what matters", and profiles. |
| [`LIVE_TRADING_CONSENT.md`](docs/LIVE_TRADING_CONSENT.md) | The exact real-money consent gate, with a worked example. |
| [`CHATGPT_MCP.md`](docs/CHATGPT_MCP.md) | ChatGPT setup: profiles, HTTP transport, auth, tunnel/HTTPS. |
| [`TOOLS.md`](docs/TOOLS.md) | Full reference for all 70 tools. |
| [`CLAUDE_CODE_AUTOMATION.md`](docs/CLAUDE_CODE_AUTOMATION.md) | Automation model + broker symbol resolution. |
| [`COMMAND_PLAYBOOK.md`](docs/COMMAND_PLAYBOOK.md) | Request → tool-call patterns. |
| [`BACKTEST_WORKFLOW.md`](docs/BACKTEST_WORKFLOW.md) | Symbol / timeframe / EA resolution for backtests. |
| [`OPERATIONAL_RUNBOOK.md`](docs/OPERATIONAL_RUNBOOK.md) | Day-to-day operation and incident response. |
| [`QUICKSTART_WINDOWS.md`](docs/QUICKSTART_WINDOWS.md) | Windows walkthrough. |
| [`USER_REQUESTS_FA.md`](docs/USER_REQUESTS_FA.md) | Persian-language request reference. |
## Project structure
```
src/mt5_mcp/ server, profiles, tool registry, action router, all tool modules
tests/ one test file per module, mocked mt5_bridge
docs/ architecture, access model, consent flow, tool reference,
automation model, command playbook, backtest workflow,
ChatGPT connector setup
docs/assets/ README graphics (banner, overview, profiles, workflow,
safety, capabilities — original self-contained SVGs)
examples/ Claude config examples + a minimal MCP client
scripts/ readiness check, open-access self-check
backups/ consents/ drafts/ logs/ workspace/ runtime data (gitignored contents)
```
## Testing
```bash
pytest # 222 tests
ruff check .
```
The suite runs fully without MetaTrader5 or psutil installed and never calls a
real `order_send`. See `tests/conftest.py` for the isolation fixtures that keep
every test off the real filesystem.
## Roadmap
- ~~Streamable-HTTP transport alongside stdio.~~ **Done** — see [`docs/CHATGPT_MCP.md`](docs/CHATGPT_MCP.md).
- ~~`compare_backtests` to diff two `summarize_backtest` outputs.~~ **Done.**
- OAuth / per-user auth for the HTTP transport (today: a single shared bearer token).
- Strategy Tester automation via `.ini` launch configs (currently: report discovery/parsing only).
- Multi-account profile switching.
- Richer market depth / DOM support where brokers allow it.
## License
Released under the [MIT License](LICENSE) — © 2026 Mt5_mcp contributors.