MetaTrader 5 MCP Server
Provides 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.
README
MetaTrader 5 MCP Server
MetaTrader 5 integration for Model Context Protocol (MCP). Provides read-only access to MT5 market data through Python commands.
⚡ What's New in v0.5.1
- Standardized error taxonomy – New helpers define 12 error classes, safe JSON parsing, enum conversion, and field validation so every tool returns consistent, timestamped diagnostics.
- Tool-level guardrails –
mt5_query,mt5_analyze, andexecute_mt5now enforce payload size limits, reject dangerous operations, validate MT5 connectivity up front, and catch-all exceptions without crashing the server. - Handler resilience – Request objects, enums, and MT5 parameters are validated before execution, with wrapped exceptions that include operation context for easier debugging.
- Connection + executor hardening – MT5 initialization retries, namespace fallback messaging, and result-format safety nets keep stdio/HTTP transports stable even when inputs misbehave.
- Expanded regression tests – 30+ new cases cover malformed JSON, invalid enums, missing fields, MT5 connection failures, and rate-limit handling for production readiness.
# Default behavior (stdio only, backward compatible)
python -m mt5_mcp
# or simply:
mt5-mcp
# Streamable HTTP with rate limiting and a custom port
python -m mt5_mcp --transport http --host 0.0.0.0 --port 7860 --rate-limit 30
# or:
mt5-mcp --transport http --host 0.0.0.0 --port 7860 --rate-limit 30
# Dual mode (stdio + HTTP)
python -m mt5_mcp --transport both
# or:
mt5-mcp --transport both
📖 Documentation:
- USAGE.md - Comprehensive instructions, tool reference, and troubleshooting
- CHANGELOG.md - Release history and migration notes
Key Capabilities
- Read-only MT5 bridge – Safe namespace exposes only data-retrieval APIs and blocks all trading calls.
- Transaction history access – Retrieve and analyze trading history with
history_deals_get,history_orders_get, andpositions_get. - Multiple interaction models – Write Python (
execute_mt5), submit structured MT5 queries (mt5_query), or run full analyses with indicators, charts, and forecasts (mt5_analyze). - Technical analysis toolkit –
ta,numpy, andmatplotlibship in the namespace for RSI, MACD, Bollinger Bands, multi-panel charts, and more. - Interactive charting – Optional Plotly support (
px,go) for creating interactive HTML charts from market data and trading history. - Forecasting + ML signals – Prophet forecasting and optional XGBoost buy/sell predictions with confidence scoring.
- LLM-friendly guardrails – Clear tool descriptions, runtime validation, and result-assignment reminders keep assistant output predictable.
Available Tools
execute_mt5
Free-form Python execution inside a curated namespace. Ideal for quick calculations, prototyping, and bespoke formatting.
rates = mt5.copy_rates_from_pos('BTCUSD', mt5.TIMEFRAME_H1, 0, 100)
df = pd.DataFrame(rates)
df['RSI'] = ta.momentum.rsi(df['close'], window=14)
result = df[['time', 'close', 'RSI']].tail(10)
mt5_query
Structured JSON interface that maps directly to MT5 read-only operations with automatic validation, timeframe conversion, and friendly error messages.
{
"operation": "copy_rates_from_pos",
"symbol": "BTCUSD",
"parameters": {"timeframe": "H1", "count": 100}
}
mt5_analyze
Pipeline tool that chains a query → optional indicators → charts and/or Prophet forecasts (with optional ML signals) in one request.
{
"query": {
"operation": "copy_rates_from_pos",
"symbol": "BTCUSD",
"parameters": {"timeframe": "D1", "count": 180}
},
"indicators": [
{"function": "ta.trend.sma_indicator", "params": {"window": 50}},
{"function": "ta.momentum.rsi", "params": {"window": 14}}
],
"forecast": {"periods": 30, "plot": true, "enable_ml_prediction": true}
}
Prerequisites
- Windows OS (MetaTrader5 library is Windows-only)
- MetaTrader 5 terminal installed and running
- Python 3.10+
Installation
- Clone this repository:
git clone <repository-url>
cd MT5-MCP
- Install the package:
pip install -e .
Optional features (HTTP transport and interactive charting):
# Install with HTTP/Gradio support
pip install -e .[ui]
# Install with Plotly for interactive charts
pip install -e .[charting]
# Install everything
pip install -e .[all]
# From PyPI:
pip install "mt5-mcp[all]"
Package naming: The package is named mt5-mcp (with hyphen) on PyPI, but the Python module uses mt5_mcp (with underscore). This is standard Python convention.
This will install all required dependencies:
mcp- Model Context Protocol SDKMetaTrader5- Official MT5 Python librarypandas- Data manipulation and formattingprophet- Time series forecastingxgboost- Machine learning for trading signals (NEW!)scikit-learn- ML utilities and preprocessing (NEW!)ta- Technical analysis indicators
Configuration
Claude Desktop
Add to your Claude Desktop configuration file:
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"mt5": {
"command": "python",
"args": ["-m", "mt5_mcp"]
}
}
}
Alternatively, if the mt5-mcp CLI script is in your PATH:
{
"mcpServers": {
"mt5": {
"command": "mt5-mcp",
"args": []
}
}
}
With Logging (for troubleshooting)
{
"mcpServers": {
"mt5": {
"command": "python",
"args": ["-m", "mt5_mcp", "--log-file", "C:\\path\\to\\mt5_mcp.log"]
}
}
}
Transport Modes (CLI)
Choose how the server exposes MCP transports directly from the command line:
# Default behavior (run only stdio like previous version)
python -m mt5_mcp
# or:
mt5-mcp
# Run both transports
python -m mt5_mcp --transport both
# or:
mt5-mcp --transport both
# Run only streamable HTTP
python -m mt5_mcp --transport http --host 0.0.0.0 --port 7860
# or:
mt5-mcp --transport http --host 0.0.0.0 --port 7860
Additional flags:
--rate-limit <value>– Requests per IP each minute (set to0to disable; keep enabled for public servers).--log-level/--log-file– Tailored diagnostics across transports.
HTTP MCP Clients
- Install the optional extras:
pip install "mt5-mcp[ui]"(orpip install -e .[ui]while developing). - Launch the HTTP transport:
python -m mt5_mcp --transport http --host 0.0.0.0 --port 7860(ormt5-mcp --transport http). - Point any MCP client to the new endpoint:
{
"mcpServers": {
"mt5-http": {
"url": "http://localhost:7860/gradio_api/mcp/"
}
}
}
Note: Use python -m mt5_mcp (module name with underscore) or the mt5-mcp CLI command (package name with hyphen) interchangeably.
This endpoint works with MCP Inspector, Claude Desktop (when configured for HTTP), VS Code extensions, or remote deployments (Hugging Face Spaces, Windows VPS, etc.).
Usage Overview
Refer to USAGE.md for a complete walkthrough that covers prerequisites, configuration screens, troubleshooting tips, and in-depth per-tool examples. Below is a quick multi-line example using execute_mt5:
from datetime import datetime, timedelta
end_date = datetime.now()
start_date = end_date - timedelta(days=30)
rates = mt5.copy_rates_range('EURUSD', mt5.TIMEFRAME_D1, start_date, end_date)
df = pd.DataFrame(rates)
df['time'] = pd.to_datetime(df['time'], unit='s')
df['return'] = df['close'].pct_change()
result = df[['time', 'close', 'return']].tail(10)
Note: Always assign the final output to result (or another variable noted in USAGE.md) so the MCP response can be formatted correctly.
Architecture & Compliance
- Built on
mcp.server.lowlevel.Serverfor stdio clients and Gradio v6 for streamable HTTP/SSE, both sharing the same MT5-safe namespace. - Safe execution namespace exposes vetted objects (
mt5,datetime,pd,ta,numpy,matplotlib) while blocking trading calls and disallowed modules. - Runtime validation catches
mt5.initialize()/mt5.shutdown()attempts, highlights the correct workflow, and enforces result assignment. - Thread-safe MT5 connection management plus IP-scoped rate limiting protect terminals from abusive HTTP workloads.
- Documentation, tool signatures, and CLI examples match MCP SDK and Gradio MCP guidance for predictable LLM behavior.
Troubleshooting
MT5 Connection Issues
- Ensure MT5 terminal is running before starting the MCP server
- Enable algo trading in MT5: Tools → Options → Expert Advisors → Check "Allow automated trading"
- Check MT5 terminal logs for any errors
Enable Logging
Run the server with logging enabled:
python -m mt5_mcp --log-file mt5_debug.log
# or:
mt5-mcp --log-file mt5_debug.log
Or configure it in Claude Desktop config (see Configuration section above).
Common Errors
"MT5 connection error: initialize() failed"
- MT5 terminal is not running
- MT5 is not installed
- Algo trading is disabled in MT5
"Symbol not found"
- Check symbol name spelling (case-sensitive)
- Symbol may not be available in your MT5 account
- Use
mt5.symbols_get()to see available symbols
"No data returned"
- Symbol may not have historical data for requested period
- Check date range validity
- Some symbols may have limited history
Security
This server provides read-only access to MT5 data. Trading functions are explicitly excluded from the safe namespace:
Blocked Functions
order_send()- Place ordersorder_check()- Check orderpositions_get()- Get positions (read-only but blocked to prevent confusion)positions_total()- Position count- All order/position modification functions
Only market data and information retrieval functions are available.
License
MIT License
Contributing
Contributions are welcome! Please ensure:
- All code follows the read-only philosophy
- Tests pass (when test suite is added)
- Documentation is updated
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。