Skip to main content
Glama
README.md
# MetaTrader 5 (MT5) MCP Server & Web GUI Workstation

[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![MCP](https://img.shields.io/badge/MCP-Protocol-orange.svg)](https://modelcontextprotocol.io)
[![MetaTrader 5](https://img.shields.io/badge/MetaTrader-5-green.svg)](https://www.metatrader5.com/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

A high-performance **Model Context Protocol (MCP)** Server and interactive **Web GUI Workstation** for MetaTrader 5 on Windows. This project connects AI assistants (Antigravity, Claude Desktop, Cursor, etc.) and quantitative traders directly to their local MT5 installation to:

1. **Pull historical market data** (OHLCV bars across timeframes M1–MN1 and millisecond-precision tick streams) with high-speed **Parquet** and **CSV** exports.
2. **Execute strategy backtests** via built-in Python quantitative engines and native MT5 Strategy Tester automation (`terminal64.exe /config:tester.ini`).
3. **Inspect demo account status**, equity curves, active symbols, market watch quotes, and open positions.
4. **Interactive Financial Web GUI**: Built with TradingView Lightweight Charts, real-time telemetry, Strategy Studio with equity curve visualizer, and account login manager.
5. **Strict Trading Safety Guard**: Ensures demo and live orders can only execute with explicit confirmation.

---

## Architecture Overview

```
 ┌────────────────────────────────────────────────────────┐
 │                      AI Client                         │
 │        (Antigravity / Claude Desktop / Cursor)         │
 └───────────────────────────┬────────────────────────────┘
                             │ MCP Protocol (stdio)
 ┌───────────────────────────▼────────────────────────────┐
 │                  MT5 MCP Server (Python)               │
 │   - FastMCP Server (`src/mt5_mcp/server.py`)           │
 │   - Data Caching & Parquet/CSV Export Engine           │
 │   - Quantitative Strategy Backtesting Engine           │
 └─────────────┬────────────────────────────┬─────────────┘
               │                            │
 ┌─────────────▼──────────────┐  ┌──────────▼─────────────┐
 │    MetaTrader5 Python API  │  │ MT5 Native Tester Auto │
 │  - copy_rates_range()      │  │  - tester.ini builder  │
 │  - copy_ticks_range()      │  │  - terminal64.exe CLI  │
 │  - account_info() / login()│  │  - Report XML/HTML     │
 └─────────────┬──────────────┘  └──────────┬─────────────┘
               │                            │
 ┌─────────────▼────────────────────────────▼─────────────┐
 │               MetaTrader 5 Windows Terminal            │
 │               (Demo Account Connected)                 │
 └────────────────────────────────────────────────────────┘
```

---

## Installation & Prerequisites

### 1. Requirements
* Windows 10 / 11 (64-bit)
* MetaTrader 5 desktop terminal installed
* Python 3.10, 3.11, or 3.12 (64-bit)
* `uv` (recommended) or standard `pip`

### 2. Enable Algorithmic Trading in MT5
In your MetaTrader 5 terminal:
* Navigate to **Tools** -> **Options** -> **Expert Advisors**.
* Check **Allow algorithmic trading**.
* Check **Allow DLL imports** (if required by custom indicators).

### 3. Setup Virtual Environment
```bash
# Clone the repository
git clone https://github.com/remomein05/mt5-mcp.git
cd mt5-mcp

# Create virtual environment and install dependencies
uv venv --python 3.12 .venv
.venv\Scripts\activate
uv pip install -e ".[dev]"
```

---

## Web GUI Workstation (Interactive Dashboard)

The repository includes a dedicated financial-grade **Web GUI Dashboard** with TradingView charting, real-time market watch, strategy backtesting studio, and account management:

```bash
# Launch via console script
mt5-mcp-gui

# Or launch via Python module
.venv\Scripts\python -m mt5_mcp.gui --port 8000
```
Then open **`http://127.0.0.1:8000`** in your browser.

### GUI Features:
- 📊 **TradingView Lightweight Charts**: Smooth candlestick and volume charting with interactive timeframe selector (`M1`, `M5`, `M15`, `M30`, `H1`, `H4`, `D1`).
- 📈 **Strategy Backtest Studio**: Configure strategy parameters (`SMA Crossover`, `RSI Reversal`, `Bollinger Bands`), run simulations, and inspect **Equity Growth Curves**, KPIs (Sharpe ratio, Max Drawdown %, Win Rate %), and closed trades logs.
- 📦 **Historical Data Exporter**: Instant one-click extraction of candlestick data to **Parquet** and **CSV** files.
- 🔍 **Market Watch**: Real-time symbol exploration with wildcard search (e.g. `*USD*`, `Crypto*`) and live floating spread indicators.
- ⚙️ **MT5 Connect & Account Login Modal**: Seamlessly connect to your active MT5 terminal or switch/log in to any demo account with custom Login ID, Password, Broker/Server, and optional executable path (with **Enter key** submission and **Esc key** dismissal).
- 📋 **Open Positions & Native MT5 Tester Panel**: View open trades and automate native MQL5 Expert Advisors headlessly with batch `.ini` configurations.

---

## MCP Client Configuration

### Claude Desktop / Antigravity / Cursor (`mcp_config.json`)
Add the MT5 MCP server to your MCP client configuration:

```json
{
  "mcpServers": {
    "mt5": {
      "command": "C:\\Users\\<USER>\\source\\repos\\mt5_mcp\\.venv\\Scripts\\python.exe",
      "args": [
        "-m",
        "mt5_mcp.server"
      ],
      "env": {
        "PYTHONUNBUFFERED": "1"
      }
    }
  }
}
```

---

## Available MCP Tools

### 1. Connection & Account Management
| Tool | Parameters | Description |
| :--- | :--- | :--- |
| `mt5_connect` | `path`, `login`, `password`, `server` | Initializes connection to MT5 terminal or logs in to a specific demo account. |
| `mt5_account_summary` | _None_ | Returns demo account balance, equity, leverage, free margin, and profit. |
| `mt5_terminal_info` | _None_ | Returns MT5 build version, connection state, ping, and data directories. |

### 2. Market Exploration & Historical Data
| Tool | Parameters | Description |
| :--- | :--- | :--- |
| `mt5_get_symbols` | `group` (e.g. `*USD*`) | Searches available symbols with wildcard filtering. |
| `mt5_symbol_details` | `symbol` (e.g. `EURUSD`) | Returns contract specifications (spread, point, digits, swap rates). |
| `mt5_symbol_current_tick` | `symbol` | Retrieves real-time bid, ask, and last price. |
| `mt5_fetch_historical_bars` | `symbol`, `timeframe`, `count`, `date_from`, `date_to`, `export_format` | Extracts historical OHLCV data across timeframes (`M1` to `MN1`) with optional Parquet/CSV export. |
| `mt5_fetch_ticks` | `symbol`, `count`, `date_from`, `date_to`, `export_format` | Extracts millisecond-precision tick streams with optional Parquet/CSV export. |

### 3. Strategy Testing & Simulation
| Tool | Parameters | Description |
| :--- | :--- | :--- |
| `mt5_list_backtest_strategies` | _None_ | Lists built-in backtest models (`sma_crossover`, `rsi_reversal`, `bollinger_bands`). |
| `mt5_run_strategy_backtest` | `symbol`, `timeframe`, `strategy_name`, `bars_count`, `initial_cash`, `lot_size`, `params` | Executes backtest on historical MT5 data and returns Sharpe ratio, Max Drawdown %, Win Rate %, Profit Factor, and trade log. |
| `mt5_run_native_tester` | `expert_name`, `symbol`, `period`, `deposit`, `currency`, `leverage`, `model`, `from_date`, `to_date`, `visual` | Automates native MT5 Strategy Tester using generated `.ini` configs and headless `terminal64.exe` execution. |

### 4. Positions & Trading (Guarded)
| Tool | Parameters | Description |
| :--- | :--- | :--- |
| `mt5_get_open_positions` | `symbol` (optional) | Lists open positions on the demo account. |
| `mt5_get_order_history` | `days`, `symbol` (optional) | Lists closed deals and historical order executions. |
| `mt5_place_demo_order` | `symbol`, `order_type`, `volume`, `sl`, `tp`, `explicit_user_approval` | Places demo orders with strict safety guard requiring `explicit_user_approval=True`. |

---

## Running Tests

Run the comprehensive pytest suite verifying connectivity, historical extraction, quantitative backtesters, and GUI REST APIs:
```bash
.venv\Scripts\pytest -v
```

---

## License
MIT License.