Labsco
ariadng logo

MetaTrader MCP Server

β˜… 600

from ariadng

A Python-based MCP server that allows AI LLMs to execute trades on the MetaTrader 5 platform.

πŸ”₯πŸ”₯πŸ”₯βœ“ VerifiedFreeAdvanced setup
<div align="center"> <h1>MetaTrader MCP Server</h1> </div> <br /> <div align="center">

PyPI version Python 3.10+ License: MIT

Let AI assistants trade for you using natural language

MetaTrader MCP Server

</div> <br />

πŸ“‘ Table of Contents


🌟 What is This?

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:

"Show me my account balance" "Buy 0.01 lots of EUR/USD" "Close all profitable positions"

The AI understands your request and executes it on MetaTrader 5 automatically.

How It Works

Copy & paste β€” that's it
You β†’ AI Assistant β†’ MCP Server β†’ MetaTrader 5 β†’ Your Trades

✨ Features

  • πŸ—£οΈ Natural Language Trading - Talk to AI in plain English to execute trades
  • πŸ€– Multi-AI Support - Works with Claude Desktop, ChatGPT (via Open WebUI), and more
  • πŸ“Š Full Market Access - Get real-time prices, historical data, and symbol information
  • πŸ’Ό Complete Account Control - Check balance, equity, margin, and trading statistics
  • ⚑ Order Management - Place, modify, and close orders with simple commands
  • πŸ”’ Secure - All credentials stay on your machine
  • 🌐 Flexible Interfaces - Use as MCP server, REST API, or WebSocket stream
  • πŸ“– Well Documented - Comprehensive guides and examples

🎯 Who Is This For?

  • Traders who want to automate their trading using AI
  • Developers building trading bots or analysis tools
  • Analysts who need quick access to market data
  • Anyone interested in combining AI with financial markets

⚠️ Important Disclaimer

Please read this carefully:

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.

By using this software, you acknowledge that:

  • You understand the risks of financial trading
  • You are responsible for all trades executed through this system
  • You will not hold the developers liable for any outcomes
  • You are using this software at your own risk

This is not financial advice. Always trade responsibly.


πŸ€– Trading Assistant Skill (Claude Code / Claude Desktop)

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.

Installing for Claude Code

Option 1: Symlink (recommended)

Create a symlink from the standard Claude Code skills directory to claude-skill/:

Copy & paste β€” that's it
cd metatrader-mcp-server
mkdir -p .claude
ln -s ../claude-skill .claude/skills

The skill will be auto-discovered and available as /trading.

Option 2: Copy

Copy the skill files into the Claude Code skills directory:

Copy & paste β€” that's it
cd metatrader-mcp-server
mkdir -p .claude/skills
cp -r claude-skill/trading .claude/skills/trading

Installing for Claude Desktop

For Claude Desktop, copy the skill to the global Claude skills directory:

Copy & paste β€” that's it
# macOS
mkdir -p ~/Library/Application\ Support/Claude/skills
cp -r claude-skill/trading ~/Library/Application\ Support/Claude/skills/trading

# Windows
mkdir "%APPDATA%\Claude\skills"
xcopy /E claude-skill\trading "%APPDATA%\Claude\skills\trading\"

What the Skill Does

  • Direct Execution: Executes trades immediately when requested, no extra confirmation needed
  • Workflows: Knows how to chain tools for complex operations (e.g., place market order then set SL/TP)
  • Formatting: Presents account data, positions, orders, and prices in clean terminal-style tables
  • Domain Knowledge: Understands MT5 order types, timeframes, symbol formats, and filling modes

Usage

Once installed, invoke with /trading or just ask trading-related questions naturally:

Copy & paste β€” that's it
/trading
> Show me my account dashboard
> Buy 0.1 lots of EURUSD with SL at 1.0800
> Close all profitable positions
> Show me GBPUSD H4 candles

πŸ“‘ WebSocket Quote Server

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.

Starting the Server

Copy & paste β€” that's it
metatrader-quote-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER

The server starts on ws://0.0.0.0:8765 by default.

Customization

Copy & paste β€” that's it
metatrader-quote-server \
  --login YOUR_LOGIN \
  --password YOUR_PASSWORD \
  --server YOUR_SERVER \
  --host 127.0.0.1 \
  --port 9000 \
  --symbols "EURUSD,GBPUSD,XAUUSD" \
  --poll-interval 200

Configuration

FlagEnv VarDefaultDescription
--hostQUOTE_HOST0.0.0.0Host to bind
--portQUOTE_PORT8765Port to bind
--symbolsQUOTE_SYMBOLSXAUUSD,USOIL,GBPUSD,USDJPY,EURUSD,BTCUSDComma-separated symbols to stream
--poll-intervalQUOTE_POLL_INTERVAL_MS100Tick polling interval in milliseconds

CLI flags take precedence over environment variables, which take precedence over defaults.

Message Format

On connect β€” server sends a connected message with the symbol list, followed by any cached ticks:

Copy & paste β€” that's it
{"type": "connected", "symbols": ["XAUUSD", "EURUSD", "GBPUSD"], "poll_interval_ms": 100}

Tick updates β€” sent whenever bid, ask, or volume changes:

Copy & paste β€” that's it
{"type": "tick", "symbol": "XAUUSD", "bid": 2345.67, "ask": 2345.89, "spread": 0.22, "volume": 1234, "time": "2026-03-14T10:30:45+00:00"}

Errors β€” sent if a symbol cannot be fetched:

Copy & paste β€” that's it
{"type": "error", "symbol": "INVALID", "message": "Symbol not found or data unavailable"}

Example: Connecting with Python

Copy & paste β€” that's it
import asyncio
import json
from websockets.asyncio.client import connect

async def main():
    async with connect("ws://localhost:8765") as ws:
        async for message in ws:
            tick = json.loads(message)
            if tick["type"] == "tick":
                print(f"{tick['symbol']}: {tick['bid']}/{tick['ask']} (spread: {tick['spread']})")

asyncio.run(main())

Design Notes

  • Change detection: Only broadcasts when bid, ask, or volume actually changes, reducing unnecessary traffic.
  • Late joiners: New clients receive cached ticks immediately on connect, so they don't have to wait for the next change.
  • MT5 thread safety: All MT5 SDK calls are serialized through a single-thread executor to prevent concurrent access issues.
  • Multiple clients: Any number of WebSocket clients can connect simultaneously.

πŸ“š Available Operations

Account Management

  • get_account_info - Get balance, equity, profit, margin level, leverage, currency

Market Data

  • get_symbols - List all available trading symbols
  • get_symbol_price - Get current bid/ask price for a symbol
  • get_candles_latest - Get recent price candles (OHLCV data)
  • get_candles_by_date - Get historical candles for a date range
  • get_symbol_info - Get detailed symbol information

Order Execution

  • place_market_order - Execute instant BUY/SELL orders
  • place_pending_order - Place limit/stop orders for future execution
  • modify_position - Update stop loss or take profit
  • modify_pending_order - Modify pending order parameters

Position Management

  • get_all_positions - View all open positions
  • get_positions_by_symbol - Filter positions by trading pair
  • get_positions_by_id - Get specific position details
  • close_position - Close a specific position
  • close_all_positions - Close all open positions
  • close_all_positions_by_symbol - Close all positions for a symbol
  • close_all_profitable_positions - Close only winning trades
  • close_all_losing_positions - Close only losing trades

Pending Orders

  • get_all_pending_orders - List all pending orders
  • get_pending_orders_by_symbol - Filter pending orders by symbol
  • cancel_pending_order - Cancel a specific pending order
  • cancel_all_pending_orders - Cancel all pending orders
  • cancel_pending_orders_by_symbol - Cancel pending orders for a symbol

Trading History

  • get_deals - Get historical completed trades
  • get_orders - Get historical order records

πŸ—ΊοΈ Roadmap

FeatureStatus
MetaTrader 5 Connectionβœ… Complete
Python Client Libraryβœ… Complete
MCP Serverβœ… Complete
Claude Desktop Integrationβœ… Complete
HTTP/REST API Serverβœ… Complete
Open WebUI Integrationβœ… Complete
OpenAPI Documentationβœ… Complete
PyPI Packageβœ… Published
SSE Transport Supportβœ… Complete
Google ADK Integration🚧 In Progress
WebSocket Quote Serverβœ… Complete
Docker ContainerπŸ“‹ Planned

πŸ› οΈ Development

Setting Up Development Environment

Copy & paste β€” that's it
# Clone the repository
git clone https://github.com/ariadng/metatrader-mcp-server.git
cd metatrader-mcp-server

# Install in development mode
pip install -e .

# Install development dependencies
pip install pytest python-dotenv

# Run tests
pytest tests/

Project Structure

Copy & paste β€” that's it
metatrader-mcp-server/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ metatrader_client/      # Core MT5 client library
β”‚   β”‚   β”œβ”€β”€ account/            # Account operations
β”‚   β”‚   β”œβ”€β”€ connection/         # Connection management
β”‚   β”‚   β”œβ”€β”€ history/            # Historical data
β”‚   β”‚   β”œβ”€β”€ market/             # Market data
β”‚   β”‚   β”œβ”€β”€ order/              # Order execution
β”‚   β”‚   └── types/              # Type definitions
β”‚   β”œβ”€β”€ metatrader_mcp/         # MCP server implementation
β”‚   β”œβ”€β”€ metatrader_openapi/     # HTTP/REST API server
β”‚   └── metatrader_quote/       # WebSocket quote streamer
β”œβ”€β”€ tests/                      # Test suite
β”œβ”€β”€ docs/                       # Documentation
└── pyproject.toml             # Project configuration

🀝 Contributing

Contributions are welcome! Here's how you can help:

  1. Report Bugs - Open an issue
  2. Suggest Features - Share your ideas in issues
  3. Submit Pull Requests - Fix bugs or add features
  4. Improve Documentation - Help make docs clearer
  5. Share Examples - Show how you're using it

Contribution Guidelines

  • Fork the repository
  • Create a feature branch (git checkout -b feature/amazing-feature)
  • Make your changes
  • Write or update tests
  • Ensure tests pass (pytest)
  • Commit your changes (git commit -m 'Add amazing feature')
  • Push to the branch (git push origin feature/amazing-feature)
  • Open a Pull Request

πŸ“– Documentation


πŸ†˜ Getting Help

Common Issues

"Connection failed"

  • Ensure MT5 terminal is running
  • Check that algorithmic trading is enabled
  • Verify your login credentials are correct

"Module not found"

  • Make sure you've installed the package: pip install metatrader-mcp-server
  • Check your Python version is 3.10 or higher

"Order execution failed"

  • Verify the symbol exists on your broker
  • Check that the market is open
  • Ensure you have sufficient margin

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments


πŸ“Š Project Stats

  • Version: 0.5.1
  • Python: 3.10+
  • License: MIT
  • Status: Active Development

<div align="center">

Made with ❀️ by Aria Dhanang

⭐ Star this repo if you find it useful!

PyPI β€’ GitHub β€’ Issues

</div>