MT5 MCP Server
A 34-tool MCP server that bridges LLMs to MetaTrader 5, enabling EA development, backtesting, optimization, advanced analytics, live trading, and portfolio management.
README
MT5 MCP Server v2.1
37-tool MCP server for MetaTrader 5 — the most complete LLM-to-MT5 bridge. Full autonomous pipeline from strategy description to PDF report, with proper risk metrics (Sharpe, Sortino, Calmar) and validation checks. Write EAs, compile, backtest, optimize, Monte Carlo, Kelly sizing, live trade, monitor portfolio — all through MCP.
Highlights
- 🤖 Autonomous Pipeline — Describe a strategy → get a complete PDF report with Monte Carlo, Kelly, risk metrics
- 📊 37 MCP tools — every MT5 operation available to LLMs
- 📈 Proper Risk Metrics — Annualized Sharpe, Sortino, Calmar with sanity checks
- 🔴 Live Trading — Place orders, manage positions, monitor portfolio from any LLM
Tools Overview (37)
📊 Backtest & Optimization (5)
| Tool | Description |
|---|---|
run_mt5_backtest |
Single backtest with full parameter control |
run_mt5_optimization |
Genetic/complete parameter optimization |
run_multi_backtest |
Test EA on multiple symbols, aggregate results |
get_backtest_results |
Parse tester log into structured trade data |
get_optimization_results |
Read .opt files with best passes |
✏️ EA Development (6)
| Tool | Description |
|---|---|
write_expert |
Write/update .mq5 source (auto-compile) |
compile_expert_file |
Compile .mq5 → .ex5 via MetaEditor |
read_expert_code |
Read full MQL5 source |
get_ea_parameters |
Extract all input params with types/defaults |
list_experts |
List all installed EAs |
get_backtest_log |
Raw tester log for debugging |
📈 Advanced Analytics (6)
| Tool | Description |
|---|---|
run_monte_carlo |
1000-sim robustness with P5/P95 confidence |
run_walk_forward |
Rolling OOS validation, overfitting detection |
calc_position_size |
Kelly Criterion, Optimal F, Risk of Ruin |
get_trade_stats |
Expectancy, Z-score, streaks |
get_risk_metrics |
v2.1 Sharpe, Sortino, Calmar + validation |
export_trades |
Export results to CSV |
🔴 Live Trading (6)
| Tool | Description |
|---|---|
place_order |
Market & pending orders (buy/sell/limit/stop) |
get_positions |
Open positions with real-time P&L |
close_position |
Close by ticket or close all |
modify_position |
Modify SL/TP on open positions |
get_account |
Balance, equity, margin, leverage |
get_order_history |
Historical deals with P&L |
📊 Portfolio Management (7)
| Tool | Description |
|---|---|
analyze_portfolio_diversification |
0-100 score + verdict + recommendations |
calc_correlation |
Correlation matrix, diversification score |
calc_efficient_frontier |
Markowitz optimal weights, max Sharpe |
calc_risk_allocation |
Equal risk, Kelly, inverse-DD allocation |
get_portfolio_health |
Live P&L, concentration, margin |
backtest_to_returns |
Convert results to returns series |
get_mt5_status |
Connection and account status |
🤖 Autonomous Pipeline (2)
| Tool | Description |
|---|---|
build_strategy_code |
v2.0 Generate MQL5 EA from natural language |
run_autonomous_pipeline |
v2.0 Full auto: Create→Compile→Screen→Correlate→Optimize→MC→Kelly→Robustness→Report |
📡 Data Access (5)
| Tool | Description |
|---|---|
get_bars |
OHLC bar data for any symbol/timeframe |
get_ticks |
Raw tick data with spread stats |
list_symbols |
All available trading symbols |
get_latest_price |
Real-time bid/ask for multiple symbols |
get_symbol_info |
Spread, swap, margin, tick value |
Quick Start
git clone https://github.com/Boschi404/mt5-mcp-server.git
cd mt5-mcp-server
pip install -r requirements.txt
Register with MCP Client
Hermes Agent:
hermes mcp add mt5-backtest --command "C:/Python311/python" --args "/path/to/server.py" --timeout 600
Claude Desktop (claude_desktop_config.json):
{"mcpServers": {"mt5-backtest": {"command": "python", "args": ["/path/to/server.py"]}}}
Autonomous Pipeline
One command to run 9 phases:
run_autonomous_pipeline(
strategy_name="GoldBreakout",
strategy_description="Channel breakout M15, EMA50 H4 trend filter, SL 700pts, TP 3000pts"
)
Phases:
- Create — Generate MQL5 code with all parameters
- Compile — Compile to .ex5 + error check
- Screen — Test on 15+ major symbols (1M OHLC)
- Correlate — Find uncorrelated candidates (0-100 diversification score)
- Optimize — Genetic optimization on tick data with fixed risk
- Monte Carlo — 1000 simulations, skip 10% random trades
- Kelly — Position sizing from real trade stats (max 15% DD)
- Robustness — 100 random 6-month backtests
- Report — Full HTML report with Sharpe, Sortino, Calmar + validation
Output: Desktop/pipelines/StrategyName_TIMESTAMP/ with organized subfolders per phase.
Risk Metrics (v2.1)
get_risk_metrics computes proper risk-adjusted returns:
| Metric | Formula |
|---|---|
| Sharpe | (Return − RiskFree) / StdDev × √Periods |
| Sortino | (Return − RiskFree) / DownsideStdDev × √Periods |
| Calmar | AnnualizedReturn / MaxDrawdown |
Automatic validation checks:
- Sharpe > 10? → ⚠️ WARNING: suspiciously high
- Sortino >> Sharpe? → ✅ Positive skew confirmed
- Profit Factor > 100? → ⚠️ WARNING: likely look-ahead bias
- Win Rate > 95%? → ⚠️ WARNING: survivorship bias
Example Workflows
Full Pipeline (EA → Live)
1. build_strategy_code("Channel breakout, SL 700, TP 3000") → get MQL5 code
2. write_expert("GoldScalper", code) → save + compile
3. run_multi_backtest("GoldScalper", ["XAUUSD","DAXEUR","NDQUSDc"]) → screen
4. analyze_portfolio_diversification(returns) → score: 72/100 ✅
5. run_autonomous_pipeline("GoldScalper") → full auto
6. place_order("XAUUSD", "buy_stop", volume=0.05, ...) → go live
7. get_portfolio_health() → monitor
Risk Check
LLM → get_risk_metrics()
→ Sharpe: 1.85 (institutional quality)
→ Sortino: 3.12 (positive skew)
→ Max DD: 8.4%
→ Data Quality: GOOD
→ Validation: 3 checks passed, 0 warnings
Architecture
mt5-mcp-server/
├── server.py # MCP server (37 tools)
├── backtest.py # MT5 tester orchestrator
├── analytics.py # Monte Carlo, Walk-Forward, Kelly
├── risk_metrics.py # v2.1 Proper Sharpe/Sortino/Calmar
├── trading.py # Live order execution
├── portfolio.py # Correlation, efficient frontier
├── data.py # Bar/tick data, symbols, prices
├── batch.py # Multi-symbol testing
├── pipeline.py # v2.0 Autonomous pipeline orchestrator
├── strategy_builder.py # v2.0 MQL5 code generator
├── report_generator.py # v2.0 HTML/PDF report generator
└── requirements.txt
Version History
| Version | Tools | Highlights |
|---|---|---|
| v1.0 | 5 | Basic backtest + log parsing |
| v1.1 | 11 | Optimization, EA dev, compilation |
| v1.2 | 17 | Monte Carlo, Walk-Forward, Kelly, CSV |
| v1.3 | 30 | Live trading, portfolio, data access |
| v1.4 | 34 | Batch testing, diversification scoring |
| v2.0 | 36 | Autonomous pipeline, strategy builder, PDF reports |
| v2.1 | 37 | Proper Sharpe/Sortino/Calmar + validation checks |
License
MIT — use it, fork it, ship it.
推荐服务器
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 模型以安全和受控的方式获取实时的网络信息。