Skip to main content
Glama

MetaTrader 5 (MT5) MCP 服务器 & Web GUI 工作站

Python 3.10+ MCP MetaTrader 5 License: MIT

一个高性能的 Model Context Protocol (MCP) 服务器和交互式 Web GUI 工作站,适用于 Windows 上的 MetaTrader 5。本项目将 AI 助手(Antigravity、Claude Desktop、Cursor 等)和量化交易者直接连接到本地 MT5 安装,以:

  1. 拉取历史市场数据(跨时间周期 M1–MN1 的 OHLCV K 线,以及毫秒级精度的 tick 数据流),并支持高速 Parquet 和 CSV 导出。

  2. 执行策略回测,通过内置 Python 量化引擎和原生 MT5 策略测试器自动化(terminal64.exe /config:tester.ini)。

  3. 查看模拟账户状态、权益曲线、活跃交易品种、市场报价和未平仓头寸。

  4. 交互式金融 Web GUI:基于 TradingView Lightweight Charts 构建,具备实时遥测、带权益曲线可视化器的策略工作室,以及账户登录管理器。

  5. 严格的交易安全防护:确保模拟盘和实盘订单只能在明确确认后执行。


架构概述

 ┌────────────────────────────────────────────────────────┐
 │                      AI Client                         │
 │        (Antigravity / Claude Desktop / Cursor)         │
 └───────────────────────────┬────────────────────────────┘
                             │ MCP Protocol (stdio)
 ┌───────────────────────────▼────────────────────────────┐
 │                  MT5 MCP Server (Python)               │
 │   - FastMCP Server (`src/mt5_mcp/server.py`)           │
 │   - Data Caching & Parquet/CSV Export Engine           │
 │   - Quantitative Strategy Backtesting Engine           │
 └─────────────┬────────────────────────────┬─────────────┘
               │                            │
 ┌─────────────▼──────────────┐  ┌──────────▼─────────────┐
 │    MetaTrader5 Python API  │  │ MT5 Native Tester Auto │
 │  - copy_rates_range()      │  │  - tester.ini builder  │
 │  - copy_ticks_range()      │  │  - terminal64.exe CLI  │
 │  - account_info() / login()│  │  - Report XML/HTML     │
 └─────────────┬──────────────┘  └──────────┬─────────────┘
               │                            │
 ┌─────────────▼────────────────────────────▼─────────────┐
 │               MetaTrader 5 Windows Terminal            │
 │               (Demo Account Connected)                 │
 └────────────────────────────────────────────────────────┘

Related MCP server: MetaTrader MCP Server

安装与前提条件

1. 环境要求

  • Windows 10 / 11 (64 位)

  • 已安装 MetaTrader 5 桌面终端

  • Python 3.10、3.11 或 3.12 (64 位)

  • uv(推荐)或标准 pip

2. 在 MT5 中启用算法交易

在您的 MetaTrader 5 终端中:

  • 导航至 工具 -> 选项 -> 智能交易系统。

  • 勾选 允许算法交易。

  • 勾选 允许 DLL 导入(如果自定义指标需要)。

3. 设置虚拟环境

# Clone the repository
git clone https://github.com/remomein05/mt5-mcp.git
cd mt5-mcp

# Create virtual environment and install dependencies
uv venv --python 3.12 .venv
.venv\Scripts\activate
uv pip install -e ".[dev]"

Web GUI 工作站(交互式仪表盘)

该仓库包含一个专门的金融级 Web GUI 仪表盘,具备 TradingView 图表、实时市场行情、策略回测工作室和账户管理功能:

# Launch via console script
mt5-mcp-gui

# Or launch via Python module
.venv\Scripts\python -m mt5_mcp.gui --port 8000

然后在浏览器中打开 http://127.0.0.1:8000。

GUI 功能:

  • 📊 TradingView Lightweight Charts:流畅的蜡烛图和成交量图表,带有交互式时间周期选择器(M1、M5、M15、M30、H1、H4、D1)。

  • 📈 策略回测工作室:配置策略参数(SMA Crossover、RSI Reversal、Bollinger Bands),运行模拟,并检查权益增长曲线、KPI(夏普比率、最大回撤 %、胜率 %)及已平仓交易日志。

  • 📦 历史数据导出器:一键即时提取蜡烛图数据到 Parquet 和 CSV 文件。

  • 🔍 市场报价:通过通配符搜索(例如 *USD*、Crypto*)实时探索交易品种,并提供实时浮动点差指标。

  • ⚙️ MT5 连接与账户登录弹窗:无缝连接到您当前活跃的 MT5 终端,或通过自定义登录 ID、密码、经纪商/服务器以及可选的执行文件路径切换/登录任何模拟账户(支持 Enter 键提交和 Esc 键关闭)。

  • 📋 未平仓头寸与原生 MT5 测试器面板:查看未平仓交易,并通过批量的 .ini 配置以无头模式自动化运行原生 MQL5 智能交易系统。


MCP 客户端配置

Claude Desktop / Antigravity / Cursor (mcp_config.json)

将 MT5 MCP 服务器添加到您的 MCP 客户端配置中:

{
  "mcpServers": {
    "mt5": {
      "command": "C:\\Users\\<USER>\\source\\repos\\mt5_mcp\\.venv\\Scripts\\python.exe",
      "args": [
        "-m",
        "mt5_mcp.server"
      ],
      "env": {
        "PYTHONUNBUFFERED": "1"
      }
    }
  }
}

可用的 MCP 工具

1. 连接与账户管理

工具

参数

描述

mt5_connect

path, login, password, server

初始化到 MT5 终端的连接,或登录到特定的模拟账户。

mt5_account_summary

None

返回模拟账户余额、权益、杠杆、可用保证金和利润。

mt5_terminal_info

None

返回 MT5 构建版本、连接状态、ping 和数据目录。

2. 市场探索与历史数据

工具

参数

描述

mt5_get_symbols

group (例如 *USD*)

使用通配符过滤搜索可用交易品种。

mt5_symbol_details

symbol (例如 EURUSD)

返回合约规格(点差、点、小数位数、隔夜利息)。

mt5_symbol_current_tick

symbol

获取实时的买价、卖价和最新价。

mt5_fetch_historical_bars

symbol, timeframe, count, date_from, date_to, export_format

提取跨时间周期(M1 到 MN1)的历史 OHLCV 数据,可选择导出为 Parquet/CSV。

mt5_fetch_ticks

symbol, count, date_from, date_to, export_format

提取毫秒级精度的 tick 数据流,可选择导出为 Parquet/CSV。

3. 策略测试与模拟

工具

参数

描述

mt5_list_backtest_strategies

None

列出内置回测模型(sma_crossover、rsi_reversal、bollinger_bands)。

mt5_run_strategy_backtest

symbol, timeframe, strategy_name, bars_count, initial_cash, lot_size, params

在历史 MT5 数据上执行回测,并返回夏普比率、最大回撤 %、胜率 %、盈利因子和交易日志。

mt5_run_native_tester

expert_name, symbol, period, deposit, currency, leverage, model, from_date, to_date, visual

使用生成的 .ini 配置和无头 terminal64.exe 执行来自动化原生 MT5 策略测试器。

4. 持仓与交易(安全防护)

工具

参数

描述

mt5_get_open_positions

symbol (可选)

列出模拟账户上的未平仓头寸。

mt5_get_order_history

days, symbol (可选)

列出已平仓交易和历史上的订单执行记录。

mt5_place_demo_order

symbol, order_type, volume, sl, tp, explicit_user_approval

使用严格的安全防护下达模拟订单,要求 explicit_user_approval=True。


运行测试

运行全面的 pytest 测试套件,验证连接性、历史数据提取、量化回测器和 GUI REST API:

.venv\Scripts\pytest -v

许可证

MIT 许可证。

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    • Trader.AI turns trading ideas into strategies you can trade. Describe an idea, paste a strategy, or share the source of an MT5 Expert Advisor, and Trader.AI makes the rules exact (entries, exits, stops and position sizing), then backtests them on historical MT5 data for EURUSD, GBPUSD, AUDUSD, XAUUSD, XAGUSD, NAS100, SP500, USOIL, BTCUSD or ETHUSD. Results come back in the chat: return, max drawdown, win rate, Sharpe and every trade, with the rule that opened it and why it closed, plus a report link. Change the rules and backtest again; every version is saved so you can compare runs. Start from a starter strategy or see how Trader.AI's own AI traders perform in live trading. When a version backtests the way you want, export it as an MT5 Expert Advisor. Backtest results are hypothetical and don't guarantee future returns. Trader.AI doesn't place trades on your account or give investment advice. Connecting requires signing in with a Trader.AI account.

      https://trader.ai/api/mcp
    • Read-only MetaTrader 5 for AI agents: balances, positions, history and prices. Sign in with OAuth.

    • 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.

      https://mcp.fxsocket.com/mcp
    • MCP server for OpenMM — exposes market data, account, trading, and strategy tools to AI agents

      https://mcp.openmm.io/mcp

    Related MCP Servers

    • A
      license
      Not graded
      quality
      A
      maintenance
      Exposes a unified AI interface to MetaTrader 5 over the Model Context Protocol, enabling live quotes, historical data, technical indicators, order execution, position management, and headless backtests.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI assistants to trade on MetaTrader 5 using natural language, supporting account management, order placement, and real-time market data.
      1
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      A 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
    • F
      license
      Not graded
      quality
      D
      maintenance
      Universal MCP server that enables AI assistants to control MetaTrader 5 directly, executing trades, managing data, and automating MT5 operations through natural language.
      4
      -