Let AI assistants trade for you using natural language
Features β’ Quick Start β’ Documentation β’ Examples β’ Support
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.
You β AI Assistant β MCP Server β MetaTrader 5 β Your Trades
- π£οΈ 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
- π― Atomic SL/TP - Set stop loss and take profit at order open time β no two-step modify needed
- π Secure - All credentials stay on your machine
- π Flexible Interfaces - Use as MCP server or REST API
- π Well Documented - Comprehensive guides and examples
- 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
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.
Before you begin, make sure you have:
- Python 3.13 or higher - Download here
- MetaTrader 5 terminal - Download here
- MT5 Trading Account - Demo or live account credentials
- Login number (integer)
- Password
- Server name (e.g.,
"Deriv-Demo")
Open your terminal or command prompt and run:
pip install metatrader-mcp-server- Open MetaTrader 5
- Go to
ToolsβOptions - Click the
Expert Advisorstab - Check the box for
Allow algorithmic trading - Click
OK
Pick one based on how you want to use it:
-
Find your Claude Desktop config file:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json - Mac:
~/Library/Application Support/Claude/claude_desktop_config.json
- Windows:
-
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"
]
}
}
}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",
"--path", "C:\\Program Files\\MetaTrader 5\\terminal64.exe"
]
}
}
}-
Replace
YOUR_MT5_LOGIN,YOUR_MT5_PASSWORD, andYOUR_MT5_SERVERwith your actual credentials -
Restart Claude Desktop
-
Start chatting! Try: "What's my account balance?"
- Start the HTTP server:
metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 0.0.0.0 --port 8000Optional: Specify Custom MT5 Terminal Path
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-
Open your browser to
http://localhost:8000/docsto see the API documentation -
In Open WebUI:
- Go to Settings β Tools
- Click Add Tool Server
- Enter
http://localhost:8000 - Save
-
Now you can use trading tools in your Open WebUI chats!
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
# 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/12345from metatrader_client import MT5Client
# Connect to MT5
config = {
"login": 40931844, # Must be an integer
"password": "your_password",
"server": "Deriv-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()get_account_info- Get balance, equity, profit, margin level, leverage, currency
get_symbols- List all available trading symbolsget_symbol_price- Get current bid/ask price for a symbolget_candles_latest- Get recent price candles (OHLCV data)get_candles_by_date- Get historical candles for a date rangeget_symbol_info- Get detailed symbol information
place_market_order- Execute instant BUY/SELL orders with stop loss and take profit at open timeplace_pending_order- Place limit/stop orders with optional SL/TPmodify_position- Update stop loss or take profit on an existing positionmodify_pending_order- Modify pending order parameters
get_all_positions- View all open positionsget_positions_by_symbol- Filter positions by trading pairget_positions_by_id- Get specific position detailsclose_position- Close a specific positionclose_all_positions- Close all open positionsclose_all_positions_by_symbol- Close all positions for a symbolclose_all_profitable_positions- Close only winning tradesclose_all_losing_positions- Close only losing trades
get_all_pending_orders- List all pending ordersget_pending_orders_by_symbol- Filter pending orders by symbolcancel_pending_order- Cancel a specific pending ordercancel_all_pending_orders- Cancel all pending orderscancel_pending_orders_by_symbol- Cancel pending orders for a symbol
get_deals- Get historical completed tradesget_orders- Get historical order records
Instead of putting credentials in the command line, create a .env file:
LOGIN=40931844
PASSWORD=your_password
SERVER=Deriv-Demo
# Optional: Specify custom MT5 terminal path (auto-detected if not provided)
# PATH=C:\Program Files\MetaTrader 5 Terminal\terminal64.exeThen start the server without arguments:
metatrader-http-server
β οΈ Important:LOGINmust be an integer (no quotes). The Python client casts it withint()before passing to the MT5 API.
metatrader-http-server --host 127.0.0.1 --port 9000config = {
"login": 40931844, # integer β required
"password": "your_password",
"server": "Deriv-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)
}| 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 |
| Atomic SL/TP on Market Orders | β Complete |
| Google ADK Integration | π§ In Progress |
| WebSocket Support | π Planned |
| Docker Container | π Planned |
# Clone the repository
git clone https://github.com/leeroyanesu/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/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
Contributions are welcome! Here's how you can help:
- Report Bugs - Open an issue
- Suggest Features - Share your ideas in issues
- Submit Pull Requests - Fix bugs or add features
- Improve Documentation - Help make docs clearer
- Share Examples - Show how you're using it
- 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
- Developer Documentation - Detailed technical docs
- API Reference - Complete API documentation
- Examples - Code examples and tutorials
- Roadmap - Feature development timeline
- Issues: GitHub Issues
- Discussions: GitHub Discussions
(-2, 'Invalid "login" argument')
- The
loginmust be an integer, not a string. EnsureMT5_LOGINin.envhas no quotes and the code casts it withint().
"Connection failed"
- Ensure MT5 terminal is running
- Check that algorithmic trading is enabled (
Tools β Options β Expert Advisors) - 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
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with FastMCP for MCP protocol support
- Uses MetaTrader5 Python package
- Powered by FastAPI for the REST API
- Version: 0.3.0
- Python: 3.13+
- License: MIT
- Status: Active Development
- β
place_market_ordernow acceptsstop_lossandtake_profitat open time - β
AI is instructed to always set SL/TP atomically β no post-open
modify_positioncalls - β
Fixed parameter pass-through bug in
MT5Orderwrapper (client_order.py) - β Python 3.13+ minimum requirement
- π Updated GitHub URLs and author to
leeroyanesu
- Initial public release with MCP server, HTTP/REST API, Open WebUI support
Made with β€οΈ by leeroyanesu
β Star this repo if you find it useful!
