Skip to content
Back to search

metatrader-mcp-server

Model Context Protocol (MCP) to enable AI LLMs to trade using MetaTrader platform

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/ariadng--metatrader-mcp-server/badge.svg)](/listings/ariadng--metatrader-mcp-server)

HTML

<a href="/listings/ariadng--metatrader-mcp-server"><img src="/api/listings/ariadng--metatrader-mcp-server/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Step 1: Install the Package

Open your terminal or command prompt and run:

pip install metatrader-mcp-server

Step 2: Enable Algorithmic Trading

1. Open MetaTrader 5 2. Go to `Tools` → `Options` 3. Click the `Expert Advisors` tab 4. Check the box for `Allow algorithmic trading` 5. Click `OK`

Step 3: Choose Your Interface

Pick one based on how you want to use it:

Option A: Use with Claude Desktop (Local STDIO)

1. Find your Claude Desktop config file: - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` - **Mac**: `~/Library/Application Support/Claude/claude_desktop_config.json`

2. Open the file and add this configuration:

{
  "mcpServers": {
    "metatrader": {
      "command": "metatrader-mcp-server",
      "args": [
        "--login",     "YOUR_MT5_LOGIN",
        "--password",  "YOUR_MT5_PASSWORD",
        "--server",    "YOUR_MT5_SERVER",
        "--transport", "stdio"
      ]
    }
  }
}

**Optional: Specify Custom MT5 Terminal Path**

If your MT5 terminal is installed in a non-standard location, add the `--path` argument:

{
  "mcpServers": {
    "metatrader": {
      "command": "metatrader-mcp-server",
      "args": [
        "--login",     "YOUR_MT5_LOGIN",
        "--password",  "YOUR_MT5_PASSWORD",
        "--server",    "YOUR_MT5_SERVER",
        "--transport", "stdio",
        "--path",      "C:\\Program Files\\MetaTrader 5\\terminal64.exe"
      ]
    }
  }
}

3. Replace `YOUR_MT5_LOGIN`, `YOUR_MT5_PASSWORD`, and `YOUR_MT5_SERVER` with your actual credentials

4. Restart Claude Desktop

5. Start chatting! Try: *"What's my account balance?"*

Option B: Use with Open WebUI (For ChatGPT and other LLMs)

1. Start the HTTP server:

metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 0.0.0.0 --port 8000

**Optional: Specify Custom MT5 Terminal Path**

If your MT5 terminal is installed in a non-standard location, add the `--path` argument:

metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --path "C:\Program Files\MetaTrader 5\terminal64.exe" --host 0.0.0.0 --port 8000

2. Open your browser to `http://localhost:8000/docs` to see the API documentation

3. In Open WebUI: - Go to **Settings** → **Tools** - Click **Add Tool Server** - Enter `http://localhost:8000` - Save

4. Now you can use trading tools in your Open WebUI chats!

Option C: Real-Time Quotes via WebSocket

Stream live tick data (bid, ask, spread, volume) over WebSocket for dashboards, bots, or monitoring:

metatrader-quote-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER

Connect with any WebSocket client:

websocat ws://localhost:8765

You'll receive a `connected` message followed by continuous tick updates as JSON. See [WebSocket Quote Server](#-websocket-quote-server) for full details.

Option D: Remote MCP Server (SSE)

Run the MCP server on a Windows VPS (where MT5 is installed) and connect to it remotely from Claude Desktop or Claude Code.

**Server-side** (on the Windows VPS):

metatrader-mcp-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER

This starts the SSE server on `0.0.0.0:8080` by default. Customize with `--host` and `--port`:

metatrader-mcp-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 127.0.0.1 --port 9000

**Client-side** (Claude Desktop config on your local machine):

{
  "mcpServers": {
    "metatrader": {
      "url": "http://VPS_IP:8080/sse"
    }
  }
}

Replace `VPS_IP` with your server's IP address.

> **Security Warning**: The MCP protocol does not include authentication. When exposing the SSE server over a network, use a firewall to restrict access by IP, or place it behind a reverse proxy with authentication, or use an SSH tunnel.

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 760 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <div align="center">
  2. <h1>MetaTrader MCP Server</h1>
  3. </div>
  4. <br />
  5. <div align="center">
  6. [![PyPI version](https://img.shields.io/pypi/v/metatrader-mcp-server.svg?style=flat&color=blue)](https://pypi.org/project/metatrader-mcp-server/)
  7. [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
  8. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  9. **Let AI assistants trade for you using natural language**
  10. ![MetaTrader MCP Server](docs/media/hero.webp)
  11. </div>
  12. <br />
  13. ---
  14. ## 📑 Table of Contents
  15. - [What is This?](#-what-is-this)
  16. - [Features](#-features)
  17. - [Who Is This For?](#-who-is-this-for)
  18. - [Important Disclaimer](#%EF%B8%8F-important-disclaimer)
  19. - [Prerequisites](#-prerequisites)
  20. - [Quick Start](#-quick-start)
  21. - [Trading Assistant Skill](#-trading-assistant-skill-claude-code--claude-desktop)
  22. - [Usage Examples](#-usage-examples)
  23. - [Available Operations](#-available-operations)
  24. - [WebSocket Quote Server](#-websocket-quote-server)
  25. - [Advanced Configuration](#-advanced-configuration)
  26. - [Roadmap](#%EF%B8%8F-roadmap)
  27. - [Development](#%EF%B8%8F-development)
  28. - [Contributing](#-contributing)
  29. - [Documentation](#-documentation)
  30. - [Getting Help](#-getting-help)
  31. - [License](#-license)
  32. ---
  33. ## 🌟 What is This?
  34. **MetaTrader MCP Server** is a bridge that connects AI assistants (like Claude, ChatGPT) to the MetaTrader 5 trading platform. Instead of clicking buttons, you can simply tell your AI assistant what to do:
  35. > "Show me my account balance"
  36. > "Buy 0.01 lots of EUR/USD"
  37. > "Close all profitable positions"
  38. The AI understands your request and executes it on MetaTrader 5 automatically.
  39. ### How It Works
  40. ```
  41. You → AI Assistant → MCP Server → MetaTrader 5 → Your Trades
  42. ```
  43. ## ✨ Features
  44. - **🗣️ Natural Language Trading** - Talk to AI in plain English to execute trades
  45. - **🤖 Multi-AI Support** - Works with Claude Desktop, ChatGPT (via Open WebUI), and more
  46. - **📊 Full Market Access** - Get real-time prices, historical data, and symbol information
  47. - **💼 Complete Account Control** - Check balance, equity, margin, and trading statistics
  48. - **⚡ Order Management** - Place, modify, and close orders with simple commands
  49. - **🔒 Secure** - All credentials stay on your machine
  50. - **🌐 Flexible Interfaces** - Use as MCP server, REST API, or WebSocket stream
  51. - **📖 Well Documented** - Comprehensive guides and examples
  52. ## 🎯 Who Is This For?
  53. - **Traders** who want to automate their trading using AI
  54. - **Developers** building trading bots or analysis tools
  55. - **Analysts** who need quick access to market data
  56. - **Anyone** interested in combining AI with financial markets
  57. ## ⚠️ Important Disclaimer
  58. **Please read this carefully:**
  59. Trading financial instruments involves significant risk of loss. This software is provided as-is, and the developers accept **no liability** for any trading losses, gains, or consequences of using this software.
  60. By using this software, you acknowledge that:
  61. - You understand the risks of financial trading
  62. - You are responsible for all trades executed through this system
  63. - You will not hold the developers liable for any outcomes
  64. - You are using this software at your own risk
  65. **This is not financial advice. Always trade responsibly.**
  66. ---
  67. ## 📋 Prerequisites
  68. Before you begin, make sure you have:
  69. 1. **Python 3.10 or higher** - [Download here](https://www.python.org/downloads/)
  70. 2. **MetaTrader 5 terminal** - [Download here](https://www.metatrader5.com/en/download)
  71. 3. **MT5 Trading Account** - Demo or live account credentials
  72. - Login number
  73. - Password
  74. - Server name (e.g., "MetaQuotes-Demo")
  75. ## 🚀 Quick Start
  76. ### Step 1: Install the Package
  77. Open your terminal or command prompt and run:
  78. ```bash
  79. pip install metatrader-mcp-server
  80. ```
  81. ### Step 2: Enable Algorithmic Trading
  82. 1. Open MetaTrader 5
  83. 2. Go to `Tools` → `Options`
  84. 3. Click the `Expert Advisors` tab
  85. 4. Check the box for `Allow algorithmic trading`
  86. 5. Click `OK`
  87. ### Step 3: Choose Your Interface
  88. Pick one based on how you want to use it:
  89. #### Option A: Use with Claude Desktop (Local STDIO)
  90. 1. Find your Claude Desktop config file:
  91. - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
  92. - **Mac**: `~/Library/Application Support/Claude/claude_desktop_config.json`
  93. 2. Open the file and add this configuration:
  94. ```json
  95. {
  96. "mcpServers": {
  97. "metatrader": {
  98. "command": "metatrader-mcp-server",
  99. "args": [
  100. "--login", "YOUR_MT5_LOGIN",
  101. "--password", "YOUR_MT5_PASSWORD",
  102. "--server", "YOUR_MT5_SERVER",
  103. "--transport", "stdio"
  104. ]
  105. }
  106. }
  107. }
  108. ```
  109. **Optional: Specify Custom MT5 Terminal Path**
  110. If your MT5 terminal is installed in a non-standard location, add the `--path` argument:
  111. ```json
  112. {
  113. "mcpServers": {
  114. "metatrader": {
  115. "command": "metatrader-mcp-server",
  116. "args": [
  117. "--login", "YOUR_MT5_LOGIN",
  118. "--password", "YOUR_MT5_PASSWORD",
  119. "--server", "YOUR_MT5_SERVER",
  120. "--transport", "stdio",
  121. "--path", "C:\\Program Files\\MetaTrader 5\\terminal64.exe"
  122. ]
  123. }
  124. }
  125. }
  126. ```
  127. 3. Replace `YOUR_MT5_LOGIN`, `YOUR_MT5_PASSWORD`, and `YOUR_MT5_SERVER` with your actual credentials
  128. 4. Restart Claude Desktop
  129. 5. Start chatting! Try: *"What's my account balance?"*
  130. #### Option B: Use with Open WebUI (For ChatGPT and other LLMs)
  131. 1. Start the HTTP server:
  132. ```bash
  133. metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 0.0.0.0 --port 8000
  134. ```
  135. **Optional: Specify Custom MT5 Terminal Path**
  136. If your MT5 terminal is installed in a non-standard location, add the `--path` argument:
  137. ```bash
  138. metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --path "C:\Program Files\MetaTrader 5\terminal64.exe" --host 0.0.0.0 --port 8000
  139. ```
  140. 2. Open your browser to `http://localhost:8000/docs` to see the API documentation
  141. 3. In Open WebUI:
  142. - Go to **Settings** → **Tools**
  143. - Click **Add Tool Server**
  144. - Enter `http://localhost:8000`
  145. - Save
  146. 4. Now you can use trading tools in your Open WebUI chats!
  147. #### Option C: Real-Time Quotes via WebSocket
  148. Stream live tick data (bid, ask, spread, volume) over WebSocket for dashboards, bots, or monitoring:
  149. ```bash
  150. metatrader-quote-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER
  151. ```
  152. Connect with any WebSocket client:
  153. ```bash
  154. websocat ws://localhost:8765
  155. ```
  156. You'll receive a `connected` message followed by continuous tick updates as JSON. See [WebSocket Quote Server](#-websocket-quote-server) for full details.
  157. #### Option D: Remote MCP Server (SSE)
  158. Run the MCP server on a Windows VPS (where MT5 is installed) and connect to it remotely from Claude Desktop or Claude Code.
  159. **Server-side** (on the Windows VPS):
  160. ```bash
  161. metatrader-mcp-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER
  162. ```
  163. This starts the SSE server on `0.0.0.0:8080` by default. Customize with `--host` and `--port`:
  164. ```bash
  165. metatrader-mcp-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 127.0.0.1 --port 9000
  166. ```
  167. **Client-side** (Claude Desktop config on your local machine):
  168. ```json
  169. {
  170. "mcpServers": {
  171. "metatrader": {
  172. "url": "http://VPS_IP:8080/sse"
  173. }
  174. }
  175. }
  176. ```
  177. Replace `VPS_IP` with your server's IP address.
  178. > **Security Warning**: The MCP protocol does not include authentication. When exposing the SSE server over a network, use a firewall to restrict access by IP, or place it behind a reverse proxy with authentication, or use an SSH tunnel.
  179. ---
  180. ## 🤖 Trading Assistant Skill (Claude Code / Claude Desktop)
  181. A pre-built **Trading Terminal Assistant** skill is included in the `claude-skill/` directory. It provides Claude with structured knowledge about all 32 trading tools, output formatting, and MetaTrader 5 domain expertise.
  182. ### Installing for Claude Code
  183. **Option 1: Symlink (recommended)**
  184. Create a symlink from the standard Claude Code skills directory to `claude-skill/`:
  185. ```bash
  186. cd metatrader-mcp-server
  187. mkdir -p .claude
  188. ln -s ../claude-skill .claude/skills
  189. ```
  190. The skill will be auto-discovered and available as `/trading`.
  191. **Option 2: Copy**
  192. Copy the skill files into the Claude Code skills directory:
  193. ```bash
  194. cd metatrader-mcp-server
  195. mkdir -p .claude/skills
  196. cp -r claude-skill/trading .claude/skills/trading
  197. ```
  198. ### Installing for Claude Desktop
  199. For Claude Desktop, copy the skill to the global Claude skills directory:
  200. ```bash
  201. # macOS
  202. mkdir -p ~/Library/Application\ Support/Claude/skills
  203. cp -r claude-skill/trading ~/Library/Application\ Support/Claude/skills/trading
  204. # Windows
  205. mkdir "%APPDATA%\Claude\skills"
  206. xcopy /E claude-skill\trading "%APPDATA%\Claude\skills\trading\"
  207. ```
  208. ### What the Skill Does
  209. - **Direct Execution**: Executes trades immediately when requested, no extra confirmation needed
  210. - **Workflows**: Knows how to chain tools for complex operations (e.g., place market order then set SL/TP)
  211. - **Formatting**: Presents account data, positions, orders, and prices in clean terminal-style tables
  212. - **Domain Knowledge**: Understands MT5 order types, timeframes, symbol formats, and filling modes
  213. ### Usage
  214. Once installed, invoke with `/trading` or just ask trading-related questions naturally:
  215. ```
  216. /trading
  217. > Show me my account dashboard
  218. > Buy 0.1 lots of EURUSD with SL at 1.0800
  219. > Close all profitable positions
  220. > Show me GBPUSD H4 candles
  221. ```
  222. ---
  223. ## 📡 WebSocket Quote Server
  224. The WebSocket Quote Server streams real-time tick data from MetaTrader 5 to any WebSocket client. It's ideal for live dashboards, algorithmic trading frontends, and real-time monitoring.
  225. ### Starting the Server
  226. ```bash
  227. metatrader-quote-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER
  228. ```
  229. The server starts on `ws://0.0.0.0:8765` by default.
  230. ### Customization
  231. ```bash
  232. metatrader-quote-server \
  233. --login YOUR_LOGIN \
  234. --password YOUR_PASSWORD \
  235. --server YOUR_SERVER \
  236. --host 127.0.0.1 \
  237. --port 9000 \
  238. --symbols "EURUSD,GBPUSD,XAUUSD" \
  239. --poll-interval 200
  240. ```
  241. ### Configuration
  242. | Flag | Env Var | Default | Description |
  243. |------|---------|---------|-------------|
  244. | `--host` | `QUOTE_HOST` | `0.0.0.0` | Host to bind |
  245. | `--port` | `QUOTE_PORT` | `8765` | Port to bind |
  246. | `--symbols` | `QUOTE_SYMBOLS` | `XAUUSD,USOIL,GBPUSD,USDJPY,EURUSD,BTCUSD` | Comma-separated symbols to stream |
  247. | `--poll-interval` | `QUOTE_POLL_INTERVAL_MS` | `100` | Tick polling interval in milliseconds |
  248. CLI flags take precedence over environment variables, which take precedence over defaults.
  249. ### Message Format
  250. **On connect** — server sends a `connected` message with the symbol list, followed by any cached ticks:
  251. ```json
  252. {"type": "connected", "symbols": ["XAUUSD", "EURUSD", "GBPUSD"], "poll_interval_ms": 100}
  253. ```
  254. **Tick updates** — sent whenever bid, ask, or volume changes:
  255. ```json
  256. {"type": "tick", "symbol": "XAUUSD", "bid": 2345.67, "ask": 2345.89, "spread": 0.22, "volume": 1234, "time": "2026-03-14T10:30:45+00:00"}
  257. ```
  258. **Errors** — sent if a symbol cannot be fetched:
  259. ```json
  260. {"type": "error", "symbol": "INVALID", "message": "Symbol not found or data unavailable"}
  261. ```
  262. ### Example: Connecting with Python
  263. ```python
  264. import asyncio
  265. import json
  266. from websockets.asyncio.client import connect
  267. async def main():
  268. async with connect("ws://localhost:8765") as ws:
  269. async for message in ws:
  270. tick = json.loads(message)
  271. if tick["type"] == "tick":
  272. print(f"{tick['symbol']}: {tick['bid']}/{tick['ask']} (spread: {tick['spread']})")
  273. asyncio.run(main())
  274. ```
  275. ### Design Notes
  276. - **Change detection**: Only broadcasts when bid, ask, or volume actually changes, reducing unnecessary traffic.
  277. - **Late joiners**: New clients receive cached ticks immediately on connect, so they don't have to wait for the next change.
  278. - **MT5 thread safety**: All MT5 SDK calls are serialized through a single-thread executor to prevent concurrent access issues.
  279. - **Multiple clients**: Any number of WebSocket clients can connect simultaneously.
  280. ---
  281. ## 💡 Usage Examples
  282. ### With Claude Desktop
  283. Once configured, you can chat naturally:
  284. **Check Your Account:**
  285. > You: "Show me my account information"
  286. >
  287. > Claude: *Returns balance, equity, margin, leverage, etc.*
  288. **Get Market Data:**
  289. > You: "What's the current price of EUR/USD?"
  290. >
  291. > Claude: *Shows bid, ask, and spread*
  292. **Place a Trade:**
  293. > You: "Buy 0.01 lots of GBP/USD with stop loss at 1.2500 and take profit at 1.2700"
  294. >
  295. > Claude: *Executes the trade and confirms*
  296. **Manage Positions:**
  297. > You: "Close all my losing positions"
  298. >
  299. > Claude: *Closes positions and reports results*
  300. **Analyze History:**
  301. > You: "Show me all my trades from last week for EUR/USD"
  302. >
  303. > Claude: *Returns trade history as a table*
  304. ### With HTTP API
  305. ```bash
  306. # Get account info
  307. curl http://localhost:8000/api/v1/account/info
  308. # Get current price
  309. curl "http://localhost:8000/api/v1/market/price?symbol_name=EURUSD"
  310. # Place a market order
  311. curl -X POST http://localhost:8000/api/v1/order/market \
  312. -H "Content-Type: application/json" \
  313. -d '{
  314. "symbol": "EURUSD",
  315. "volume": 0.01,
  316. "type": "BUY",
  317. "stop_loss": 1.0990,
  318. "take_profit": 1.1010
  319. }'
  320. # Get all open positions
  321. curl http://localhost:8000/api/v1/positions
  322. # Close a specific position
  323. curl -X DELETE http://localhost:8000/api/v1/positions/12345
  324. ```
  325. ### As a Python Library
  326. ```python
  327. from metatrader_client import MT5Client
  328. # Connect to MT5
  329. config = {
  330. "login": 12345678,
  331. "password": "your_password",
  332. "server": "MetaQuotes-Demo"
  333. }
  334. client = MT5Client(config)
  335. client.connect()
  336. # Get account statistics
  337. stats = client.account.get_trade_statistics()
  338. print(f"Balance: ${stats['balance']}")
  339. print(f"Equity: ${stats['equity']}")
  340. # Get current price
  341. price = client.market.get_symbol_price("EURUSD")
  342. print(f"EUR/USD Bid: {price['bid']}, Ask: {price['ask']}")
  343. # Place a market order
  344. result = client.order.place_market_order(
  345. type="BUY",
  346. symbol="EURUSD",
  347. volume=0.01,
  348. stop_loss=1.0990,
  349. take_profit=1.1010
  350. )
  351. print(result['message'])
  352. # Close all positions
  353. client.order.close_all_positions()
  354. # Disconnect
  355. client.disconnect()
  356. ```
  357. ---
  358. ## 📚 Available Operations
  359. ### Account Management
  360. - `get_account_info` - Get balance, equity, profit, margin level, leverage, currency
  361. ### Market Data
  362. - `get_symbols` - List all available trading symbols
  363. - `get_symbol_price` - Get current bid/ask price for a symbol
  364. - `get_candles_latest` - Get recent price candles (OHLCV data)
  365. - `get_candles_by_date` - Get historical candles for a date range
  366. - `get_symbol_info` - Get detailed symbol information
  367. ### Order Execution
  368. - `place_market_order` - Execute instant BUY/SELL orders
  369. - `place_pending_order` - Place limit/stop orders for future execution
  370. - `modify_position` - Update stop loss or take profit
  371. - `modify_pending_order` - Modify pending order parameters
  372. ### Position Management
  373. - `get_all_positions` - View all open positions
  374. - `get_positions_by_symbol` - Filter positions by trading pair
  375. - `get_positions_by_id` - Get specific position details
  376. - `close_position` - Close a specific position
  377. - `close_all_positions` - Close all open positions
  378. - `close_all_positions_by_symbol` - Close all positions for a symbol
  379. - `close_all_profitable_positions` - Close only winning trades
  380. - `close_all_losing_positions` - Close only losing trades
  381. ### Pending Orders
  382. - `get_all_pending_orders` - List all pending orders
  383. - `get_pending_orders_by_symbol` - Filter pending orders by symbol
  384. - `cancel_pending_order` - Cancel a specific pending order
  385. - `cancel_all_pending_orders` - Cancel all pending orders
  386. - `cancel_pending_orders_by_symbol` - Cancel pending orders for a symbol
  387. ### Trading History
  388. - `get_deals` - Get historical completed trades
  389. - `get_orders` - Get historical order records
  390. ---
  391. ## 🔧 Advanced Configuration
  392. ### Using Environment Variables
  393. Instead of putting credentials in the command line, create a `.env` file:
  394. ```env
  395. LOGIN=12345678
  396. PASSWORD=your_password
  397. SERVER=MetaQuotes-Demo
  398. # Optional: Specify custom MT5 terminal path (auto-detected if not provided)
  399. # MT5_PATH=C:\Program Files\MetaTrader 5\terminal64.exe
  400. ```
  401. Then start the server without arguments:
  402. ```bash
  403. metatrader-http-server
  404. ```
  405. The server will automatically load credentials from the `.env` file.
  406. ### MCP Transport Configuration
  407. The MCP server supports multiple transport modes:
  408. | Flag | Env Var | Default | Description |
  409. |------|---------|---------|-------------|
  410. | `--transport` | `MCP_TRANSPORT` | `sse` | Transport type: `sse`, `stdio`, `streamable-http` |
  411. | `--host` | `MCP_HOST` | `0.0.0.0` | Host to bind (SSE/HTTP only) |
  412. | `--port` | `MCP_PORT` | `8080` | Port to bind (SSE/HTTP only) |
  413. CLI flags take precedence over environment variables, which take precedence over defaults.
  414. ### Custom Port and Host (HTTP API)
  415. ```bash
  416. metatrader-http-server --host 127.0.0.1 --port 9000
  417. ```
  418. ### Connection Parameters
  419. The MT5 client supports additional configuration:
  420. ```python
  421. config = {
  422. "login": 12345678,
  423. "password": "your_password",
  424. "server": "MetaQuotes-Demo",
  425. "path": None, # Path to MT5 terminal executable (default: auto-detect)
  426. "timeout": 60000, # Connection timeout in milliseconds (default: 60000)
  427. "portable": False, # Use portable mode (default: False)
  428. "max_retries": 3, # Maximum connection retry attempts (default: 3)
  429. "backoff_factor": 1.5, # Delay multiplier between retries (default: 1.5)
  430. "cooldown_time": 2.0, # Seconds to wait between connections (default: 2.0)
  431. "debug": True # Enable debug logging (default: False)
  432. }
  433. ```
  434. **Configuration Options:**
  435. - **login** (int, required): Your MT5 account login number
  436. - **password** (str, required): Your MT5 account password
  437. - **server** (str, required): MT5 server name (e.g., "MetaQuotes-Demo")
  438. - **path** (str, optional): Full path to the MT5 terminal executable. If not specified, the client will automatically search standard installation directories
  439. - **timeout** (int, optional): Connection timeout in milliseconds. Default: 60000 (60 seconds)
  440. - **portable** (bool, optional): Enable portable mode for the MT5 terminal. Default: False
  441. - **max_retries** (int, optional): Maximum number of connection retry attempts. Default: 3
  442. - **backoff_factor** (float, optional): Exponential backoff factor for retry delays. Default: 1.5
  443. - **cooldown_time** (float, optional): Minimum time in seconds between connection attempts. Default: 2.0
  444. - **debug** (bool, optional): Enable detailed debug logging for troubleshooting. Default: False
  445. ---
  446. ## 🗺️ Roadmap
  447. | Feature | Status |
  448. |---------|--------|
  449. | MetaTrader 5 Connection | ✅ Complete |
  450. | Python Client Library | ✅ Complete |
  451. | MCP Server | ✅ Complete |
  452. | Claude Desktop Integration | ✅ Complete |
  453. | HTTP/REST API Server | ✅ Complete |
  454. | Open WebUI Integration | ✅ Complete |
  455. | OpenAPI Documentation | ✅ Complete |
  456. | PyPI Package | ✅ Published |
  457. | SSE Transport Support | ✅ Complete |
  458. | Google ADK Integration | 🚧 In Progress |
  459. | WebSocket Quote Server | ✅ Complete |
  460. | Docker Container | 📋 Planned |
  461. ---
  462. ## 🛠️ Development
  463. ### Setting Up Development Environment
  464. ```bash
  465. # Clone the repository
  466. git clone https://github.com/ariadng/metatrader-mcp-server.git
  467. cd metatrader-mcp-server
  468. # Install in development mode
  469. pip install -e .
  470. # Install development dependencies
  471. pip install pytest python-dotenv
  472. # Run tests
  473. pytest tests/
  474. ```
  475. ### Project Structure
  476. ```
  477. metatrader-mcp-server/
  478. ├── src/
  479. │ ├── metatrader_client/ # Core MT5 client library
  480. │ │ ├── account/ # Account operations
  481. │ │ ├── connection/ # Connection management
  482. │ │ ├── history/ # Historical data
  483. │ │ ├── market/ # Market data
  484. │ │ ├── order/ # Order execution
  485. │ │ └── types/ # Type definitions
  486. │ ├── metatrader_mcp/ # MCP server implementation
  487. │ ├── metatrader_openapi/ # HTTP/REST API server
  488. │ └── metatrader_quote/ # WebSocket quote streamer
  489. ├── tests/ # Test suite
  490. ├── docs/ # Documentation
  491. └── pyproject.toml # Project configuration
  492. ```
  493. ---
  494. ## 🤝 Contributing
  495. Contributions are welcome! Here's how you can help:
  496. 1. **Report Bugs** - [Open an issue](https://github.com/ariadng/metatrader-mcp-server/issues)
  497. 2. **Suggest Features** - Share your ideas in issues
  498. 3. **Submit Pull Requests** - Fix bugs or add features
  499. 4. **Improve Documentation** - Help make docs clearer
  500. 5. **Share Examples** - Show how you're using it
  501. ### Contribution Guidelines
  502. - Fork the repository
  503. - Create a feature branch (`git checkout -b feature/amazing-feature`)
  504. - Make your changes
  505. - Write or update tests
  506. - Ensure tests pass (`pytest`)
  507. - Commit your changes (`git commit -m 'Add amazing feature'`)
  508. - Push to the branch (`git push origin feature/amazing-feature`)
  509. - Open a Pull Request
  510. ---
  511. ## 📖 Documentation
  512. - **[Developer Documentation](docs/README.md)** - Detailed technical docs
  513. - **[API Reference](docs/api-reference.md)** - Complete API documentation
  514. - **[Examples](docs/examples/)** - Code examples and tutorials
  515. - **[Roadmap](docs/roadmap/version-checklist.md)** - Feature development timeline
  516. ---
  517. ## 🆘 Getting Help
  518. - **Issues**: [GitHub Issues](https://github.com/ariadng/metatrader-mcp-server/issues)
  519. - **Discussions**: [GitHub Discussions](https://github.com/ariadng/metatrader-mcp-server/discussions)
  520. - **LinkedIn**: [Connect with me](https://linkedin.com/in/ariadhanang)
  521. ### Common Issues
  522. **"Connection failed"**
  523. - Ensure MT5 terminal is running
  524. - Check that algorithmic trading is enabled
  525. - Verify your login credentials are correct
  526. **"Module not found"**
  527. - Make sure you've installed the package: `pip install metatrader-mcp-server`
  528. - Check your Python version is 3.10 or higher
  529. **"Order execution failed"**
  530. - Verify the symbol exists on your broker
  531. - Check that the market is open
  532. - Ensure you have sufficient margin
  533. ---
  534. ## 📝 License
  535. This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
  536. ---
  537. ## 🙏 Acknowledgments
  538. - Built with [FastMCP](https://github.com/jlowin/fastmcp) for MCP protocol support
  539. - Uses [MetaTrader5](https://pypi.org/project/MetaTrader5/) Python package
  540. - Powered by [FastAPI](https://fastapi.tiangolo.com/) for the REST API
  541. ---
  542. ## 📊 Project Stats
  543. - **Version**: 0.5.1
  544. - **Python**: 3.10+
  545. - **License**: MIT
  546. - **Status**: Active Development
  547. ---
  548. <div align="center">
  549. **Made with ❤️ by [Aria Dhanang](https://github.com/ariadng)**
  550. ⭐ Star this repo if you find it useful!
  551. [PyPI](https://pypi.org/project/metatrader-mcp-server/) • [GitHub](https://github.com/ariadng/metatrader-mcp-server) • [Issues](https://github.com/ariadng/metatrader-mcp-server/issues)
  552. </div>

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.