Content
# MTX — MT5 Trade eXecutor (MCP server for Claude Code)
```
███╗ ███╗████████╗██╗ ██╗
████╗ ████║╚══██╔══╝╚██╗██╔╝
██╔████╔██║ ██║ ╚███╔╝
██║╚██╔╝██║ ██║ ██╔██╗
██║ ╚═╝ ██║ ██║ ██╔╝ ██╗
╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝
MT5 Trade eXecutor · place, manage, and guard real trades
╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴
```
[](LICENSE)
[](https://www.python.org/)
[](https://www.metatrader5.com/)
[](https://modelcontextprotocol.io/)
[](#running-on-linux--macos-via-wine)
**Place, manage, and protect real MetaTrader 5 trades by talking to Claude — a Model
Context Protocol (MCP) server that turns natural language into broker-validated
`order_send` calls, with config-driven risk guardrails between you and a bad trade.**
**Requirements:** Python 3.9+ · MetaTrader 5 (Windows, or Linux/macOS via Wine) · Claude Code
MTX is the **execution sibling of [MBT](https://github.com/FXDavid-OffbeatForex/MBT)**:
MBT reads and backtests, MTX places and manages. Together they cover the whole loop —
verify a strategy on real broker data, then let Claude execute it on a real (or demo)
account, one confirmed trade at a time.
- **Open, modify, and close positions** — market orders, partial closes, SL/TP updates.
- **Place and manage pending orders** — `buy_limit`, `sell_limit`, `buy_stop`, `sell_stop`,
with optional expiration.
- **Risk-based position sizing** — tell it a risk % or amount and a stop distance; it
returns a broker-correct lot size.
- **Money-management guardrails** — max open positions, daily loss limits, equity stop,
margin-level protection — enforced in code, not left to the model's judgement.
- **Confirm-by-default** — every write tool previews a broker `order_check` first and
only trades when you say so (or when you explicitly opt into unattended `auto` mode).
---
## MTX never guesses — the broker always has the final word
The #1 source of bugs in hand-rolled MT5 automation is code that recalculates or
assumes broker constraints — a wrong filling mode, an unrounded lot size, a stop inside
the freeze level. MTX doesn't guess any of that:
- Every price and volume is normalized against the symbol's own `digits`, `volume_step`,
`volume_min/max`, and filling-mode bitmask, read fresh from `symbol_info` on every call.
- Every order runs through the broker's own `order_check` before anything is sent —
MTX previews what the broker would do, not what it thinks the broker will do.
- Guardrail failures **fail safe**: if a risk check can't be evaluated, new trades are
blocked rather than silently allowed through.
---
## How it works
```
You, in Claude Code MTX (this server)
┌───────────────────────┐ ┌──────────────────────────────┐
│ "buy 0.5 lots EURUSD, │ calls │ normalize price/volume │
│ sl 1.0950, tp 1.1100" ├──────────┤ pick_filling_mode │
└───────────────────────┘ │ mm.check_guardrails_block_new │
│ order_check → preview │
│ │ │
│ confirm=true or mode: auto │
│ ▼ │
│ order_send → your MT5 terminal │
└──────────────────────────────┘
```
In `confirm` mode (the default), every write tool returns a validated preview —
balance, equity, margin impact, and the broker's `order_check` verdict — and only
executes once you call it again with `confirm=true`. Flip `execution.mode` to `auto`
in `config.yaml` for unattended use (a cron-driven `mm_check` heartbeat, or a hands-off
Claude Desktop session), and every open still passes through the guardrails first.
---
## Install
```bash
git clone https://github.com/FXDavid-OffbeatForex/MTX.git
cd MTX
pip install -r requirements.txt
cp config.example.yaml config.yaml
```
Edit **config.yaml**:
```yaml
mt5_path: "C:/Path/To/Your/terminal64.exe" # the terminal to trade on
# Most setups run MT5 already logged in — leave this out entirely in that case.
login:
account: null
password: "${MTX_PASSWORD}" # keep secrets in .env, never in config.yaml
server: null
execution:
mode: confirm # confirm | auto
magic: 770077 # tags MTX's own orders
deviation: 20 # max slippage, in points
mm:
enforce: false # false = mm_check only reports; true = it also closes
max_open_positions: 5
max_daily_loss_pct: 5.0
min_margin_level_pct: 200.0
equity_stop_pct: 20.0
```
Register the server with Claude Code:
```bash
claude mcp add MTX python "/abs/path/to/MTX/mcp_server.py"
```
**Using Claude Desktop instead of Claude Code?** Open
**Settings → Developer → Edit Config** (this opens `claude_desktop_config.json`)
and add:
```json
{
"mcpServers": {
"mtx": {
"command": "python",
"args": ["/abs/path/to/MTX/mcp_server.py"]
}
}
}
```
Restart Claude Desktop to load it.
That's it — `ping` in a Claude Code session to confirm the terminal is reachable.
---
## Money-management guardrails
Guardrails are deterministic, config-driven code — never left to model judgement:
| Config key | What it does |
|---|---|
| `max_open_positions` | refuses new opens once you're at the cap |
| `max_daily_loss_pct` / `max_daily_loss_money` | halts new opens once today's realized + floating loss hits the limit |
| `min_margin_level_pct` | protective: flags/flattens when margin level drops too low |
| `equity_stop_pct` | protective: flattens everything if equity drops too far below balance |
| `close_position_loss_pct` / `close_position_loss_money` | protective: closes a single losing position past its limit |
Opening actions check these **before every send, in both `confirm` and `auto` mode.**
The protective side (`mm_check`) reports breaches by default; set `mm.enforce: true`
and it also executes the closes — the setting a cron heartbeat flips on for unattended
protection.
---
## Tools (MCP)
**Reads — safe, no confirmation needed:**
| Tool | Purpose |
|---|---|
| `ping` | check MT5 is running and reachable |
| `get_config` | active terminal, account, execution mode, mm summary (password redacted) |
| `get_account_info` | balance, equity, margin, margin level, leverage |
| `get_symbol_info` | digits, volume step, stops level, filling mode, live bid/ask |
| `get_positions` | open positions, optionally by symbol |
| `get_pending_orders` | working pending orders, optionally by symbol |
| `get_history` | closed deals over a date range |
| `calc_position_size` | risk-based lot sizing from a risk %/amount and stop distance |
| `mm_check` | evaluate guardrails; also acts if `mm.enforce: true` |
**Writes — gated by `confirm` / `execution.mode`:**
| Tool | Purpose |
|---|---|
| `open_position` | open a market position (buy/sell) |
| `place_pending_order` | place a `buy_limit` / `sell_limit` / `buy_stop` / `sell_stop` |
| `modify_position` | change SL/TP on an open position |
| `modify_pending_order` | change price/SL/TP/expiration on a pending order |
| `close_position` | close a position, in whole or in part |
| `cancel_pending_order` | cancel a working pending order |
---
## Examples
```
"What's my account balance and margin level?"
"Show me EURUSD's current spread and minimum stop distance."
"Size a position risking 1% of equity with a 200-point stop on GBPUSD."
"Buy 0.1 lots of XAUUSD with a stop at 2340 and target at 2380."
"Move the stop loss on ticket 65879650 to breakeven."
"Place a sell limit on USDJPY at 158.50, good till 2026-08-01."
"Check my guardrails — am I close to today's loss limit?"
"Close half my EURUSD position."
```
Every trading example above returns a preview first in the default `confirm` mode —
Claude shows you the broker's own validation before anything executes.
---
## Running on Linux / macOS (via Wine)
MetaTrader 5 and its Python package are Windows-only, but MTX runs fine on Linux and
macOS through [Wine](https://www.winehq.org/) — same approach as MBT:
1. Install MT5 under Wine (from your broker or MetaQuotes).
2. Install a Windows Python **into that same Wine prefix** and add MTX's dependencies:
```bash
wine /path/to/wine/python.exe -m pip install MetaTrader5 PyYAML mcp
```
3. Point `config.yaml` at the Wine-mapped terminal path, and register the server with
the Wine launcher:
```json
{ "mcpServers": { "MTX": { "command": "wine", "args": ["/path/to/wine-python.exe", "/abs/path/to/MTX/mcp_server.py"] } } }
```
The `MetaTrader5` Python package talks to the terminal through a Windows DLL, so it
must run under the same Wine prefix's Python as the terminal — not your system Python.
---
## Out of scope (for now)
OCO/bracket orders, server-side trailing stops, hedge-netting `close_by`, partial-fill
auto-retry, and multi-account routing aren't implemented yet. The tool surface above is
stable enough to add them later without breaking existing calls.
---
## A note on risk
MTX will place real orders on whatever account `config.yaml` points at. **Test on a
demo account first.** The `confirm`-by-default mode and the guardrails in `core/mm.py`
exist so that no trade — and no runaway loss — happens without either your explicit
approval or a limit you configured yourself. This software is provided as-is (see
[LICENSE](LICENSE)) with no warranty; trading carries real financial risk, and past
behavior is not a guarantee of future results.
---
## Related
- [MBT — MT5 Backtest Toolkit](https://github.com/FXDavid-OffbeatForex/MBT) — the
read/backtest sibling this project executes for.
## Built on YouTube
This toolkit was built live on [FX David](https://www.youtube.com/@fxdavid9392) — a
series on building, verifying, and trading MT5 strategies with Claude AI.