quant-broker-ai-connector
A Python framework engineered to bridge advanced Large Language Models (LLMs) with the MetaTrader 5 (MT5) environment, enabling automated, natural-language-driven algorithmic trading operations and execution control.
Author

ariadng
Quick Info
Actions
Tags
Algorithmic Trading Bridge for MT5 via AI
🌟 System Overview
Quant Broker AI Connector functions as a communication layer, linking sophisticated artificial intelligence agents (such as those powered by large language models) directly to your installed MetaTrader 5 instance. This eliminates manual intervention; users issue directives in plain speech, and the system translates them into actionable trade commands.
"What is my current account leverage?" "Initiate a long position for 0.05 standard units of Gold (XAUUSD)" "Liquidate all positions showing a floating loss."
The AI interprets this natural language input and orchestrates execution via the MT5 infrastructure.
Operational Flow Diagram
You \u2192 Conversational Agent \u2192 Connector Server \u2192 MetaTrader 5 \u2192 Trade Execution
✨ Capabilities Overview
- 🗣️ Conversational Instruction - Execute complex trading logic using everyday language.
- 🤖 Heterogeneous AI Compatibility - Seamless integration with various LLM frontends (e.g., Claude ecosystem, Open WebUI/ChatGPT).
- 📊 Comprehensive Market Data Access - Retrieve live quotes, historical time-series, and instrument metadata.
- 💼 Full Account Telemetry - Query financial metrics: capital base, current equity, required margin, and performance aggregates.
- ⚡ Transaction Control - Submit, revise, or terminate pending and active orders.
- 🔒 Localized Security - All proprietary credentials remain strictly local to the host machine.
- 🌐 Dual Interface Modes - Operates interchangeably as a high-performance MCP service or a standard RESTful API gateway.
- 📖 Extensive Documentation - Detailed guides covering deployment and integration methodologies.
🎯 Target Audience
- Quant Traders seeking to automate decision-making via AI proxies.
- Software Engineers developing proprietary automated trading systems.
- Financial Analysts requiring programmatic, rapid data retrieval.
- Innovators merging generative AI capabilities with real-time financial markets.
⚠️ Critical Risk Disclosure
Mandatory Review:
Engaging in the trading of leveraged financial instruments carries an inherent, substantial risk of capital depletion. This software utility is supplied strictly "as-is"; the maintainers expressly disclaim any accountability for financial outcomes, including but not limited to realized profits or accrued losses, resulting from the use of this tool.
By deploying this utility, the user affirms: - Full comprehension of global financial market volatility and risk. - Acceptance of total fiduciary responsibility for all transactions processed herein. - Agreement to hold developers harmless against all consequential damages. - Acknowledgment that this solution does not constitute formalized financial counsel.
Trade with Prudence and Responsibility.
📋 Prerequisites for Deployment
Ensure the following dependencies are satisfied prior to activation:
- Python Interpreter - Version 3.10 or newer is required.
- MetaTrader 5 Client - The terminal application must be installed.
- MT5 Broker Credentials - Active credentials (Demo or Live):
- Account Identifier (Login)
- Access Password
- Broker Server Designation (e.g., "BrokerName-Demo")
🚀 Initial Setup Guide
Stage 1: Package Installation
Execute the following command in your shell environment:
bash pip install metatrader-mcp-server
Stage 2: Enabling Automation in MT5
Configure the MetaTrader 5 application:
1. Launch MT5.
2. Navigate to the main menu: Tools \u2192 Options.
3. Select the Expert Advisors pane.
4. Activate the checkbox labeled Allow algorithmic trading.
5. Confirm by clicking OK.
Stage 3: Interface Selection
Choose the connection method matching your desired AI integration:
Pathway A: Native Integration with Claude Desktop (Recommended for Simplicity)
- Locate the configuration file path for Claude Desktop:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json -
macOS:
~/Library/Application Support/Claude/claude_desktop_config.json -
Insert or augment the configuration data within this JSON file:
{ "mcpServers": { "metatrader": { "command": "metatrader-mcp-server", "args": [ "--login", "YOUR_ACCOUNT_ID", "--password", "YOUR_SECRET_KEY", "--server", "YOUR_BROKER_ENDPOINT" ] } } }
-
Substitute placeholders with your actual credentials.
-
Reinitialize the Claude Desktop application.
-
Begin interaction! Prompt example: *"Summarize my open profit/loss."
Pathway B: REST API Mode via Open WebUI (For general LLM Tool Use)
- Start the HTTP endpoint service:
bash metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 0.0.0.0 --port 8000
-
Access the live documentation in your web browser at
http://localhost:8000/docs. -
Within your Open WebUI environment:
- Navigate to Configuration \u2192 Tool Orchestration.
- Select Register New Service Endpoint.
- Provide the endpoint URL:
http://localhost:8000. -
Save the configuration.
-
You can now invoke trading functions directly within your chat sessions.
💡 Operation Demos
Using the Claude Integration
Conversational exchange examples:
Account Query:
User: "Provide a summary of my account status."
Claude: Outputs leverage, equity, margin call level, etc.
Data Retrieval:
User: "What is the current bid price for the EUR/USD currency pair?"
Claude: Returns real-time pricing data.
Order Placement:
User: "Execute a sell order for 0.5 lots of USD/JPY, setting a protective stop loss at 150.55."
Claude: Confirms trade submission.
Position Management:
User: "Immediately terminate all positions currently yielding negative returns."
Claude: Reports on closed trades.
HTTP API Interaction Examples
bash
Retrieve current account metrics
curl http://localhost:8000/api/v1/account/info
Fetch the latest candle data for EURUSD
curl "http://localhost:8000/api/v1/market/candles?symbol_name=EURUSD&limit=10"
Submit a limit buy order
curl -X POST http://localhost:8000/api/v1/order/pending \ -H "Content-Type: application/json" \ -d '{ "symbol": "XAUUSD", "volume": 0.1, "type": "BUY_LIMIT", "price": 2350.50 }'
Request closure of a specific ticket ID
curl -X DELETE http://localhost:8000/api/v1/positions/98765
Python Library Usage
python from metatrader_client import MT5Client
Initialization parameters
credentials = { "login": 98765432, "password": "secure_token", "server": "BrokerCorp-Live" } connector = MT5Client(credentials) connector.establish_connection()
Query statistics
summary = connector.account.get_trade_statistics() print(f"Current Equity: {summary['equity']:.2f}")
Fetch live tick data
price_data = connector.market.get_symbol_price("AUDCAD") print(f"AUDCAD Ask: {price_data['ask']}")
Modify an existing trade parameter
connector.order.update_stop_loss( ticket_id=54321, new_sl=1.0550 )
connector.terminate_connection()
📚 Available Operational Modules
Account Metrics Retrieval
fetch_account_data- Gathers balance, margin usage, leverage factor, and trade currency.
Market Intelligence
list_available_instruments- Enumerates all tradable tickers.retrieve_current_quotes- Fetches prevailing bid/ask quote levels.get_ohlcv_time_series- Retrieves recent Open-High-Low-Close-Volume bars.query_instrument_specifications- Details configuration parameters per symbol.
Transaction Submission
execute_instant_trade- Submits immediate market entries (Buy/Sell).schedule_contingent_order- Places deferred limit or stop orders.recalibrate_position_levels- Adjusts associated stop loss or take profit values.recalibrate_scheduled_order- Modifies parameters of a pending order.
Active Position Oversight
enumerate_open_transactions- Lists all currently active trades.filter_positions_by_ticker- Isolates trades for a specific financial instrument.isolate_transaction_details- Retrieves data for one specific transaction ticket.settle_single_transaction- Closes one specific active trade.liquidate_all_trades- Closes every open position.settle_out_of_favor_trades- Closes positions recording a net loss.settle_winning_trades_only- Closes positions recording a net gain.
Contingent Order Administration
list_all_scheduled_orders- Shows pending order queue.filter_scheduled_by_ticker- Views pending orders relevant to one symbol.void_scheduled_order- Cancels a specific pending instruction.void_all_scheduled_orders- Clears the entire pending queue.void_scheduled_by_ticker- Cancels pending orders associated with a symbol.
Historical Record Access
fetch_deal_settlements- Retrieves records of completed trades.fetch_order_log- Retrieves historical order submission records.
🔧 Advanced Configuration Parameters
Utilizing Environment Variables for Credentials
For enhanced security, avoid command-line arguments by preparing a .env configuration file:
env LOGIN=98765432 PASSWORD=secure_token SERVER=BrokerCorp-Live
Then launch the server without explicit parameters:
bash metatrader-http-server
Custom Network Bindings
Specifying alternative network interfaces or ports:
bash metatrader-http-server --host 192.168.1.10 --port 9090
Fine-Tuning Connection Behavior
The underlying MT5 client allows granular control over the connection lifecycle:
python connection_settings = { "login": 98765432, "password": "secure_token", "server": "BrokerCorp-Live", "timeout": 120000, # Connection timeout in milliseconds "max_retries": 5, # Maximum reconnection attempts "backoff_factor": 2.0, # Exponential backoff multiplier "cooldown_time": 5.0, # Wait time (seconds) between reconnection tries "verbose_logging": True # Activate detailed debug output }
🗺️ Development Trajectory
| Milestone | Current Status |
|---|---|
| MT5 Connectivity Core | \u2705 Achieved |
| Python Client Interface | \u2705 Achieved |
| MCP Service Layer | \u2705 Achieved |
| Native LLM Integration (Claude) | \u2705 Achieved |
| HTTP Gateway Implementation | \u2705 Achieved |
| Automated API Specification Generation | \u2705 Achieved |
| Public Package Release (PyPI) | \u2705 Published |
| Google ADK Protocol Support | \u231B In Active Development |
| Bi-directional WebSocket Streaming | \u2318 Scheduled |
| Containerization (Docker) | \u2318 Scheduled |
🛠️ Repository Contribution
We encourage community involvement in advancing this platform:
- Bug Reporting - Log defects via GitHub Issues.
- Feature Proposal - Discuss desired enhancements in the issues tracker.
- Code Submissions - Submit Pull Requests for fixes or new features.
- Documentation Enhancement - Improve clarity and accuracy of existing guides.
- Sharing Use Cases - Showcase how you leverage this tool.
Contribution Protocol
- Fork the primary repository.
- Establish a dedicated feature branch (e.g.,
git checkout -b enhancement/new-feature). - Implement modifications.
- Verify test coverage (
pytest). - Commit changes with descriptive messages.
- Push the branch to your fork.
- Initiate a Pull Request targeting the main branch.
🆘 Support & Troubleshooting
- Reporting Problems: Utilize the GitHub Issues Portal.
- Community Discussion: Engage in GitHub Discussions.
- Developer Contact: Reach out via LinkedIn.
Common Fault Resolution
Error: "Connection handshake timed out" - Ensure the MT5 desktop client application is active and responsive. - Verify that the MT5 'Allow algorithmic trading' setting is switched on. - Double-check the fidelity of the provided account credentials.
Error: "Dependency Resolution Failure"
- Confirm installation: pip install metatrader-mcp-server.
- Validate Python interpreter version (must be \u2265 3.10).
Error: "Order Rejected: Invalid Parameters" - Confirm the market is currently open for the requested symbol. - Check that the specified trading instrument is listed by your broker. - Verify account margin availability is adequate for the requested trade size.
📝 Licensing Details
This software is distributed under the permissive MIT License (refer to the LICENSE file).
🙏 Special Thanks
- Recognition to the contributors of FastMCP for the protocol implementation.
- Utilization of the official MetaTrader5 Python binding.
- Built upon the robust foundation of FastAPI for API serving.
📊 Project Metrics
- Current Release: 0.2.8
- Compatibility: Python \u2265 3.10
- License: MIT
- Status: Actively Maintained
