Skip to main content
Glama
edkdev

MetaTrader5 MCP Server

by edkdev
README.md
# MetaTrader5 MCP Server

A Model Context Protocol (MCP) server that provides trading interfaces for MetaTrader5 (MT5) platform.

## Features

- Account Management: Get account info, balance, equity, margin
- Position Management: View, modify, and close open positions
- Order Operations: Place market/pending orders, cancel orders
- Market Data: Get symbol info, current prices (ticks)
- Rates/Candles: Fetch OHLCV via start_pos/count or date range
- Indicators: Compute SMA, EMA, RSI, MACD, Bollinger Bands, ATR, Stochastic
- Bundle Indicators: Compute multiple indicators in a single call
- Signal Tools: EMA crossover regime flags and confluence scoring for entries

## Installation

Install dependencies with uv:
```bash
uv sync
```

## Configuration

Environment variables are now configured directly in your MCP client settings (no `.env` file needed).

### Claude Desktop / Kiro

Add to your `mcp.json` configuration file:

```json
{
  "mcpServers": {
    "mt5-trading": {
      "command": "uvx",
      "args": ["mt5-mcp"],
      "env": {
        "MT5_LOGIN": "your_account_number",
        "MT5_PASSWORD": "your_password",
        "MT5_SERVER": "your_broker_server",
        "MT5_PATH": "C:\\Program Files\\MetaTrader 5\\terminal64.exe",
        "MT5_TIMEOUT": "60000",
        "DEFAULT_DEVIATION": "20",
        "DEFAULT_MAGIC": "234000"
      }
    }
  }
}
```

**Required Environment Variables:**
- `MT5_LOGIN` - Your MT5 account number
- `MT5_PASSWORD` - Your MT5 account password
- `MT5_SERVER` - Your broker's server name
- `MT5_PATH` - Path to MT5 terminal executable

**Optional Environment Variables:**
- `MT5_TIMEOUT` - Connection timeout in milliseconds (default: 60000)
- `DEFAULT_DEVIATION` - Default price deviation in points (default: 20)
- `DEFAULT_MAGIC` - Default magic number for orders (default: 234000)

### Alternative: Local Development

For local development, you can also run directly:

```bash
# Set environment variables and run
MT5_LOGIN=your_account MT5_PASSWORD=your_pass MT5_SERVER=your_server MT5_PATH="C:\Program Files\MetaTrader 5\terminal64.exe" uv run python mt5_mcp/server.py
```

Or use the legacy method with uv directory:

```json
{
  "mcpServers": {
    "mt5-trading": {
      "command": "uv",
      "args": [
        "--directory",
        "D:\\path\\mt5-mcp",
        "run",
        "python",
        "mt5_mcp/server.py"
      ],
      "env": {
        "MT5_LOGIN": "your_account_number",
        "MT5_PASSWORD": "your_password",
        "MT5_SERVER": "your_broker_server",
        "MT5_PATH": "C:\\Program Files\\MetaTrader 5\\terminal64.exe"
      }
    }
  }
}
```

## Available Tools

### Account Information
- `mt5_get_account_info` - Get account balance, equity, margin, etc.
- `mt5_get_positions` - Get open positions (all or filtered by symbol)
- `mt5_get_orders` - Get pending orders

### Order Operations
- `mt5_place_order` - Place market or pending orders
  - Supports: buy, sell, buy_limit, sell_limit, buy_stop, sell_stop
  - Optional SL/TP
- `mt5_close_position` - Close an open position by ticket
- `mt5_cancel_order` - Cancel a pending order
- `mt5_modify_position` - Modify SL/TP of an open position

### Market Data
- `mt5_get_symbol_info` - Get contract specifications
- `mt5_get_tick` - Get current bid/ask prices

### Rates / Candles
- `mt5_get_rates_from_pos` - Get OHLCV starting from a position (0=current bar) with `start_pos` and `count`
- `mt5_get_rates_range` - Get OHLCV within an ISO date range `date_from` → `date_to`

### Indicators
All indicator tools support either direct data (closes/candles) or auto-fetch via `symbol` + `timeframe` plus either `date_from/date_to` or `start_pos/count`. Set `return_last_only=true` to return only the latest values.

- `mt5_calc_sma` - Simple Moving Average
  - Params: `period` (default 20)
- `mt5_calc_ema` - Exponential Moving Average
  - Params: `period` (default 20)
- `mt5_calc_rsi` - Relative Strength Index
  - Params: `period` (default 14)
- `mt5_calc_macd` - MACD line, signal, histogram
  - Params: `fast` (12), `slow` (26), `signal` (9)
- `mt5_calc_bbands` - Bollinger Bands (upper/middle/lower)
  - Params: `period` (20), `stddev` (2.0)
- `mt5_calc_atr` - Average True Range (requires candles)
  - Params: `period` (14)
- `mt5_calc_stochastic` - Stochastic Oscillator %K/%D (requires candles)
  - Params: `k_period` (14), `d_period` (3), `smooth_k` (1)

### Bundle Indicators
- `mt5_calc_bundle` - Compute multiple indicators in one call using the same fetched candles
  - Args:
    - `indicators`: array of names from ["sma","ema","rsi","macd","bbands","atr","stochastic"]
    - Optional `params` object for per-indicator overrides (e.g., `{ "sma": {"period": 50}, "bbands": {"stddev": 2.5} }`)
    - Supports `symbol/timeframe` with range/count or direct `candles/closes`
    - `return_last_only`: if true, returns only the latest values

### Signal Tools
- `mt5_signal_crossover` - EMA crossover and regime flags
  - Params: `fast` (default 50), `slow` (200), `lookback_bars` (200)
  - Returns: `state` (above/below/equal), `crossed_up`, `crossed_down`, `age_bars`, `slope_fast`, `slope_slow`, `spread`, `spread_pct`, `price_above_both`, `price_below_both`, `price`
- `mt5_signal_confluence` - Confluence scoring for entries
  - Indicator params: `ema_fast` (50), `ema_slow` (200), `ema_near` (20), `rsi_period` (14), `macd_fast` (12), `macd_slow` (26), `macd_signal` (9), `bb_period` (20), `bb_stddev` (2.0), `atr_period` (14)
  - Thresholds: `near_k_atr` (0.5), `atr_expansion_ratio` (1.0), `score_threshold` (3)
  - Control: `direction` (auto|long|short), optional `weights` for trend/momentum/volatility/location/trigger
  - Returns component flags and scores for long/short plus a suggested direction

## Example Usage

```python
# In Claude Desktop, you can now ask:

"What's my MT5 account balance?"
"Show me my open positions on EURUSD"
"Place a buy order for 0.1 lot EURUSD at market"
"Close position with ticket 12345"
"Get current price for XAUUSD"

# Indicators (auto-fetch candles)
"Compute RSI(14) on EURUSD H1 using the last 300 bars (latest value only)"
"Compute MACD and Bollinger Bands on EURUSD H4 for September"

# Bundle
"Compute RSI+MACD+BBands (latest values) on EURUSD H1 using last 300 bars"

# Signals
"Give me EMA(50/200) crossover regime info on EURUSD H1"
"Compute confluence score on EURUSD H1 (defaults) and tell me if entry is ready"
```

## Requirements

- Windows OS (MT5 only runs on Windows)
- MetaTrader5 terminal installed and running
- Python >=3.11
- Active MT5 trading account

## Architecture

```
mt5-mcp/
├── mt5_mcp/
│   ├── __init__.py          # Package init
│   ├── server.py            # MCP server with tool definitions
│   ├── mt5_service.py       # MT5 SDK wrapper
│   └── indicators.py        # Pure-Python technical indicators
├── pyproject.toml           # Project dependencies (uv)
├── .env.example             # Environment template
└── README.md
```

## Development

Run in development mode:
```bash
uv run python mt5_mcp/server.py
```

## License

MIT

## Notes
- Software is provided as is, the writer of the software will not be liable for any losses from trading. Trading forex is highly volatile and risky, proceed with extreme caution.
- The MT5 terminal must be running when using this MCP
- Ensure your account has trading permissions enabled
- Test on a demo account first before using with real money