MT5 MCP Server
by Boschi404
README.md
# 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.
[](https://gofastmcp.com)
[](https://python.org)
[](https://www.metatrader5.com)
[]()
[](https://github.com/Boschi404/mt5-mcp-server/releases)
## 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
```bash
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:**
```bash
hermes mcp add mt5-backtest --command "C:/Python311/python" --args "/path/to/server.py" --timeout 600
```
**Claude Desktop** (`claude_desktop_config.json`):
```json
{"mcpServers": {"mt5-backtest": {"command": "python", "args": ["/path/to/server.py"]}}}
```
## Autonomous Pipeline
One command to run 9 phases:
```python
run_autonomous_pipeline(
strategy_name="GoldBreakout",
strategy_description="Channel breakout M15, EMA50 H4 trend filter, SL 700pts, TP 3000pts"
)
```
**Phases:**
1. **Create** β Generate MQL5 code with all parameters
2. **Compile** β Compile to .ex5 + error check
3. **Screen** β Test on 15+ major symbols (1M OHLC)
4. **Correlate** β Find uncorrelated candidates (0-100 diversification score)
5. **Optimize** β Genetic optimization on tick data with fixed risk
6. **Monte Carlo** β 1000 simulations, skip 10% random trades
7. **Kelly** β Position sizing from real trade stats (max 15% DD)
8. **Robustness** β 100 random 6-month backtests
9. **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.
This server cannot be deployed
Maintenance
ActivitySlowing
ResponsivenessNo issues