MT5 MCP Server

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.

Category
Visit Server

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.

FastMCP Python MT5 Tools Release

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:

  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.

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured