Skip to main content
Glama
Boschi404

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.

[![FastMCP](https://img.shields.io/badge/FastMCP-3.1.1-blue)](https://gofastmcp.com)
[![Python](https://img.shields.io/badge/Python-3.9+-green)](https://python.org)
[![MT5](https://img.shields.io/badge/MetaTrader-5-orange)](https://www.metatrader5.com)
[![Tools](https://img.shields.io/badge/tools-37-purple)]()
[![Release](https://img.shields.io/badge/release-v2.1-brightgreen)](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.