MetaTrader MCP Server

MetaTrader MCP Server

Let AI assistants trade for you using natural language.

120
Stars
34
Forks
120
Watchers
8
Issues
MetaTrader MCP Server is a bridge that connects AI assistants such as Claude and ChatGPT to the MetaTrader 5 trading platform via the Model Context Protocol (MCP). It enables users to perform trading actions on MetaTrader 5 through natural language instructions. The system supports real-time data access, full account management, and secure local credential handling, offering both MCP and REST API interfaces.

Key Features

Natural language trading execution
Multi-AI assistant compatibility (Claude, ChatGPT, etc.)
Real-time market data retrieval
Comprehensive order and account management
Secure credential management on user machine
MCP and REST API interfaces
Historical data access
Support for Python 3.10+
Well-documented with guides and examples
Full control over positions and trading statistics

Use Cases

Automating trades using voice or text with an AI assistant
Building AI-driven trading bots for MetaTrader 5
Developing financial dashboards integrating real-time account data
Implementing natural language queries for trading analytics
Monitoring portfolio performance through AI interfaces
Simplifying complex trading operations with conversational commands
Enabling analysts to retrieve market data quickly via AI
Integrating MetaTrader 5 with custom AI workflows
Managing orders and positions programmatically using NLP
Providing a bridge between AI services and trading platforms for research or production

README

PyPI version Python 3.10+ License: MIT

Let AI assistants trade for you using natural language

Features β€’ Quick Start β€’ Documentation β€’ Examples β€’ Support

MetaTrader MCP Server


🌟 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

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 or REST API
  • πŸ“– 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.


πŸ“‹ Prerequisites

Before you begin, make sure you have:

  1. Python 3.10 or higher - Download here
  2. MetaTrader 5 terminal - Download here
  3. MT5 Trading Account - Demo or live account credentials
    • Login number
    • Password
    • Server name (e.g., "MetaQuotes-Demo")

πŸš€ Quick Start

Step 1: Install the Package

Open your terminal or command prompt and run:

bash
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 (Recommended for beginners)

  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:

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

Optional: Specify Custom MT5 Terminal Path

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

json
{
  "mcpServers": {
    "metatrader": {
      "command": "metatrader-mcp-server",
      "args": [
        "--login",    "YOUR_MT5_LOGIN",
        "--password", "YOUR_MT5_PASSWORD",
        "--server",   "YOUR_MT5_SERVER",
        "--path",     "C:\\Program Files\\MetaTrader 5\\terminal64.exe"
      ]
    }
  }
}
  1. Replace YOUR_MT5_LOGIN, YOUR_MT5_PASSWORD, and YOUR_MT5_SERVER with your actual credentials

  2. Restart Claude Desktop

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

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

  1. Start the HTTP server:
bash
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:

bash
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
  1. Open your browser to http://localhost:8000/docs to see the API documentation

  2. In Open WebUI:

    • Go to Settings β†’ Tools
    • Click Add Tool Server
    • Enter http://localhost:8000
    • Save
  3. Now you can use trading tools in your Open WebUI chats!


πŸ’‘ Usage Examples

With Claude Desktop

Once configured, you can chat naturally:

Check Your Account:

You: "Show me my account information"

Claude: Returns balance, equity, margin, leverage, etc.

Get Market Data:

You: "What's the current price of EUR/USD?"

Claude: Shows bid, ask, and spread

Place a Trade:

You: "Buy 0.01 lots of GBP/USD with stop loss at 1.2500 and take profit at 1.2700"

Claude: Executes the trade and confirms

Manage Positions:

You: "Close all my losing positions"

Claude: Closes positions and reports results

Analyze History:

You: "Show me all my trades from last week for EUR/USD"

Claude: Returns trade history as a table

With HTTP API

bash
# Get account info
curl http://localhost:8000/api/v1/account/info

# Get current price
curl "http://localhost:8000/api/v1/market/price?symbol_name=EURUSD"

# Place a market order
curl -X POST http://localhost:8000/api/v1/order/market \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "EURUSD",
    "volume": 0.01,
    "type": "BUY",
    "stop_loss": 1.0990,
    "take_profit": 1.1010
  }'

# Get all open positions
curl http://localhost:8000/api/v1/positions

# Close a specific position
curl -X DELETE http://localhost:8000/api/v1/positions/12345

As a Python Library

python
from metatrader_client import MT5Client

# Connect to MT5
config = {
    "login": 12345678,
    "password": "your_password",
    "server": "MetaQuotes-Demo"
}
client = MT5Client(config)
client.connect()

# Get account statistics
stats = client.account.get_trade_statistics()
print(f"Balance: ${stats['balance']}")
print(f"Equity: ${stats['equity']}")

# Get current price
price = client.market.get_symbol_price("EURUSD")
print(f"EUR/USD Bid: {price['bid']}, Ask: {price['ask']}")

# Place a market order
result = client.order.place_market_order(
    type="BUY",
    symbol="EURUSD",
    volume=0.01,
    stop_loss=1.0990,
    take_profit=1.1010
)
print(result['message'])

# Close all positions
client.order.close_all_positions()

# Disconnect
client.disconnect()

πŸ“š 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

πŸ”§ Advanced Configuration

Using Environment Variables

Instead of putting credentials in the command line, create a .env file:

env
LOGIN=12345678
PASSWORD=your_password
SERVER=MetaQuotes-Demo

# Optional: Specify custom MT5 terminal path (auto-detected if not provided)
# PATH=C:\Program Files\MetaTrader 5\terminal64.exe

Then start the server without arguments:

bash
metatrader-http-server

The server will automatically load credentials from the .env file.

Custom Port and Host

bash
metatrader-http-server --host 127.0.0.1 --port 9000

Connection Parameters

The MT5 client supports additional configuration:

python
config = {
    "login": 12345678,
    "password": "your_password",
    "server": "MetaQuotes-Demo",
    "path": None,               # Path to MT5 terminal executable (default: auto-detect)
    "timeout": 60000,           # Connection timeout in milliseconds (default: 60000)
    "portable": False,          # Use portable mode (default: False)
    "max_retries": 3,           # Maximum connection retry attempts (default: 3)
    "backoff_factor": 1.5,      # Delay multiplier between retries (default: 1.5)
    "cooldown_time": 2.0,       # Seconds to wait between connections (default: 2.0)
    "debug": True               # Enable debug logging (default: False)
}

Configuration Options:

  • login (int, required): Your MT5 account login number
  • password (str, required): Your MT5 account password
  • server (str, required): MT5 server name (e.g., "MetaQuotes-Demo")
  • path (str, optional): Full path to the MT5 terminal executable. If not specified, the client will automatically search standard installation directories
  • timeout (int, optional): Connection timeout in milliseconds. Default: 60000 (60 seconds)
  • portable (bool, optional): Enable portable mode for the MT5 terminal. Default: False
  • max_retries (int, optional): Maximum number of connection retry attempts. Default: 3
  • backoff_factor (float, optional): Exponential backoff factor for retry delays. Default: 1.5
  • cooldown_time (float, optional): Minimum time in seconds between connection attempts. Default: 2.0
  • debug (bool, optional): Enable detailed debug logging for troubleshooting. Default: False

πŸ—ΊοΈ Roadmap

Feature Status
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
Google ADK Integration 🚧 In Progress
WebSocket Support πŸ“‹ Planned
Docker Container πŸ“‹ Planned

πŸ› οΈ Development

Setting Up Development Environment

bash
# 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

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
β”œβ”€β”€ 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.2.9
  • Python: 3.10+
  • License: MIT
  • Status: Active Development

Made with ❀️ by Aria Dhanang

⭐ Star this repo if you find it useful!

PyPI β€’ GitHub β€’ Issues

Star History

Star History Chart

Repository Owner

ariadng
ariadng

User

Repository Details

Language Python
Default Branch main
Size 1,660 KB
Contributors 2
License MIT License
MCP Verified Nov 12, 2025

Programming Languages

Python
100%

Tags

Topics

ai finance investment llm mcp metatrader quantitative-finance trading

Join Our Newsletter

Stay updated with the latest AI tools, news, and offers by subscribing to our weekly newsletter.

We respect your privacy. Unsubscribe at any time.

Related MCPs

Discover similar Model Context Protocol servers

  • CipherTrust Manager MCP Server

    CipherTrust Manager MCP Server

    Enables AI assistants to access CipherTrust Manager securely via the Model Context Protocol.

    CipherTrust Manager MCP Server provides an implementation of the Model Context Protocol (MCP), offering AI assistants such as Claude and Cursor a unified interface to interact with CipherTrust Manager resources. Communication is facilitated through JSON-RPC over stdin/stdout, enabling key management, CTE client management, user management, and connection management functionalities. The tool is configurable via environment variables and integrates with existing CipherTrust Manager instances using the ksctl CLI for secure resource access.

    • ⭐ 7
    • MCP
    • sanyambassi/ciphertrust-manager-mcp-server
  • Meta Ads MCP

    Meta Ads MCP

    AI-powered Meta Ads campaign analysis and management via MCP

    Meta Ads MCP is a Model Context Protocol (MCP) server for managing, analyzing, and optimizing Meta advertising campaigns. It enables AI interfaces, such as LLMs, to retrieve ad performance data, visualize creatives, and provide strategic insights across Facebook, Instagram, and related platforms. The solution supports integration with platforms like Claude and Cursor, leveraging Meta's public APIs to deliver actionable insights and campaign management capabilities. Authentication options include interactive login and token-based flows for various MCP clients.

    • ⭐ 342
    • MCP
    • pipeboard-co/meta-ads-mcp
  • QuantConnect MCP Server

    QuantConnect MCP Server

    Official bridge for secure AI access to QuantConnect's algorithmic trading cloud platform

    QuantConnect MCP Server enables artificial intelligence systems such as Claude and OpenAI to interface with QuantConnect's cloud platform through an official, secure, and dockerized implementation of the Model Context Protocol (MCP). It facilitates automated project management, strategy writing, backtesting, and live deployment by exposing a comprehensive suite of API tools for users with valid access credentials. As the maintained official version, it ensures security, easy deployment, and cross-platform compatibility for advanced algorithmic trading automation.

    • ⭐ 50
    • MCP
    • QuantConnect/mcp-server
  • Freqtrade-MCP

    Freqtrade-MCP

    MCP server bridge for Freqtrade automated crypto trading bots

    Freqtrade-MCP acts as a Model Context Protocol (MCP) server that connects AI agents to the Freqtrade cryptocurrency trading bot via its REST API. It exposes Freqtrade operations as standardized MCP tools, enabling automated trading workflows through programmatic access. The system ensures AI agents can manage market data, trigger trades, and monitor performance in a uniform context protocol environment. It supports secure and configurable deployment with support for relevant API endpoints.

    • ⭐ 92
    • MCP
    • kukapay/freqtrade-mcp
  • Make MCP Server (legacy)

    Make MCP Server (legacy)

    Enable AI assistants to utilize Make automation workflows as callable tools.

    Make MCP Server (legacy) provides a Model Context Protocol (MCP) server that connects AI assistants with Make scenarios configured for on-demand execution. It parses and exposes scenario parameters, allowing AI systems to invoke automation workflows and receive structured JSON outputs. The server supports secure integration through API keys and facilitates seamless communication between AI and Make's automation platform.

    • ⭐ 142
    • MCP
    • integromat/make-mcp-server
  • Taskade MCP

    Taskade MCP

    Tools and server for Model Context Protocol workflows and agent integration

    Taskade MCP provides an official server and tools to implement and interact with the Model Context Protocol (MCP), enabling seamless connectivity between Taskade’s API and MCP-compatible clients such as Claude or Cursor. It includes utilities for generating MCP tools from any OpenAPI schema and supports the deployment of autonomous agents, workflow automation, and real-time collaboration. The platform promotes extensibility by supporting integration via API, OpenAPI, and MCP, making it easier to build and connect agentic systems.

    • ⭐ 90
    • MCP
    • taskade/mcp
  • Didn't find tool you were looking for?

    Be as detailed as possible for better results