### Development Environment Setup Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Instructions for setting up the development environment, installing dependencies, and running tests. ```APIDOC ## 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/ ``` ``` -------------------------------- ### Example Usage Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/README.md A comprehensive example demonstrating the usage of MT5Client for connecting, retrieving data, placing orders, and disconnecting. ```APIDOC ## Example Usage ### Description This example illustrates a typical workflow using the `MT5Client`. ### Request Example ```python from metatrader_client.client import MT5Client config = { "login": 12345678, "password": "your_password", "server": "Broker-Server" } client = MT5Client(config) if client.connect(): print("Connected! ๐ŸŽ‰") # Account Information print("Balance:", client.account.get_balance()) # Market Data print("EURUSD price:", client.market.get_symbol_price("EURUSD")) # Placing an Order client.order.place_market_order(type="buy", symbol="EURUSD", volume=0.1) # Historical Data print("Recent deals:", client.history.get_deals()) client.disconnect() else: print("Failed to connect. ๐Ÿšจ") ``` ``` -------------------------------- ### Install metatrader-mcp-server Package Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Install the package using pip. Ensure you have Python 3.10 or higher. ```bash pip install metatrader-mcp-server ``` -------------------------------- ### Install MetaTrader MCP Server Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/README.md Commands to clone the repository, install dependencies, and register the MCP server with Claude Desktop. ```bash # Install from source git clone https://github.com/ariadng/metatrader-mcp-server.git cd metatrader-mcp-server pip install -e . # Install MCP CLI tools (if not already installed) pip install mcp[cli] # Install the MCP server in Claude Desktop mcp install src/mcp/main.py ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Commands to clone the Metatrader MCP Server repository, navigate into the directory, and install the project in development mode along with testing dependencies. ```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/ ``` -------------------------------- ### Start Quote Server Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Commands to launch the WebSocket quote server with default or custom configurations. ```bash metatrader-quote-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER ``` ```bash 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 ``` -------------------------------- ### REST API Usage Examples Source: https://context7.com/ariadng/metatrader-mcp-server/llms.txt Example curl commands to interact with the running HTTP REST API. ```bash # REST API Examples using curl # Get account info curl http://localhost:8000/api/v1/account/info # Get current price curl "http://localhost:8000/api/v1/market/price/EURUSD" # Or using query parameter: curl "http://localhost:8000/api/v1/market/price?symbol_name=EURUSD" # Get all symbols curl http://localhost:8000/api/v1/market/symbols # Filter symbols curl "http://localhost:8000/api/v1/market/symbols/filter?group=*USD*" # Get symbol info curl http://localhost:8000/api/v1/market/symbol/info/EURUSD # Get latest candles curl "http://localhost:8000/api/v1/market/candles/latest?symbol_name=EURUSD&timeframe=H1&count=50" # Get candles by date range curl "http://localhost:8000/api/v1/market/candles/date?symbol_name=EURUSD&timeframe=D1&date_from=2024-01-01T00:00:00&date_to=2024-12-31T23:59:59" ``` -------------------------------- ### Start Server with Default Configuration Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Starts the MetaTrader MCP Server using default transport (sse), host (0.0.0.0), and port (8080). It automatically loads credentials from a .env file if present. ```bash metatrader-http-server ``` -------------------------------- ### Start HTTP REST Server Source: https://context7.com/ariadng/metatrader-mcp-server/llms.txt Commands to launch the FastAPI-based HTTP server for MetaTrader 5. ```bash # Start HTTP server with credentials metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 0.0.0.0 --port 8000 # With custom MT5 terminal path metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --path "C:\Program Files\MetaTrader 5\terminal64.exe" # Using environment variables (.env file) # LOGIN=12345678 # PASSWORD=your_password # SERVER=MetaQuotes-Demo metatrader-http-server --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Start MetaTrader HTTP Server Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Launch the HTTP server for Open WebUI integration. Specify a custom path if necessary. ```bash metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 0.0.0.0 --port 8000 ``` ```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 ``` -------------------------------- ### Example Usage of get_total_deals Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/history/get_total_deals.md Demonstrates how to import and call the get_total_deals function with an existing connection object. ```python from metatrader_client.history import get_total_deals total = get_total_deals(conn) ``` -------------------------------- ### Install Trading Assistant Skill for Claude Code Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Install the trading skill via symlink or direct copy into the Claude Code directory. ```bash cd metatrader-mcp-server mkdir -p .claude ln -s ../claude-skill .claude/skills ``` ```bash cd metatrader-mcp-server mkdir -p .claude/skills cp -r claude-skill/trading .claude/skills/trading ``` -------------------------------- ### Start Server with Custom Port and Host Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Launches the MetaTrader HTTP server, binding it to a specific IP address and port for API access. ```bash metatrader-http-server --host 127.0.0.1 --port 9000 ``` -------------------------------- ### Start and configure WebSocket quote server Source: https://context7.com/ariadng/metatrader-mcp-server/llms.txt Launch the quote server with custom host, port, symbol list, and polling intervals. ```bash metatrader-quote-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER ``` ```bash metatrader-quote-server \ --login YOUR_LOGIN \ --password YOUR_PASSWORD \ --server YOUR_SERVER \ --host 127.0.0.1 \ --port 9000 \ --symbols "EURUSD,GBPUSD,XAUUSD,BTCUSD" \ --poll-interval 200 ``` -------------------------------- ### Example Usage of MT5Account Methods Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_account.md Demonstrates connecting to MetaTrader 5, initializing MT5Account, and retrieving various account details like info, balance, equity, and margin level. Remember to disconnect the connection when done. ```python from metatrader_client.client_connection import MT5Connection from metatrader_client.client_account import MT5Account config = {"login": 12345678, "password": "your_password", "server": "Broker-Server"} conn = MT5Connection(config) if conn.connect(): account = MT5Account(conn) info = account.get_account_info() print("Account Info:", info) print("Balance:", account.get_balance()) print("Equity:", account.get_equity()) print("Margin Level:", account.get_margin_level()) conn.disconnect() else: print("Failed to connect. ๐Ÿšจ") ``` -------------------------------- ### Invoke Trading Commands Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Examples of natural language commands for the trading MCP server. ```text /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 ``` -------------------------------- ### Connect to WebSocket with Python Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Example client implementation to receive and parse tick data from the WebSocket server. ```python 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()) ``` -------------------------------- ### Execute get_orders function Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/history/get_orders.md Basic usage example for fetching orders using a connection object and date range. ```python from metatrader_client.history import get_orders orders = get_orders(conn, from_date, to_date) ``` -------------------------------- ### Perform Market Data Operations Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_market.md Example demonstrating connection, symbol retrieval, price fetching, and candle data extraction. ```python from metatrader_client.client_connection import MT5Connection from metatrader_client.client_market import MT5Market config = {"login": 12345678, "password": "your_password", "server": "Broker-Server"} conn = MT5Connection(config) if conn.connect(): market = MT5Market(conn) symbols = market.get_symbols() print("Available symbols:", symbols) price = market.get_symbol_price("EURUSD") print("EURUSD price:", price) candles = market.get_candles_latest("EURUSD", timeframe="M1", count=10) print(candles) conn.disconnect() else: print("Failed to connect. ๐Ÿšจ") ``` -------------------------------- ### Execute Trading Operations Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_order.md Example demonstrating connection, position retrieval, market order placement, and closing profitable positions. ```python from metatrader_client.client_connection import MT5Connection from metatrader_client.client_order import MT5Order config = {"login": 12345678, "password": "your_password", "server": "Broker-Server"} conn = MT5Connection(config) if conn.connect(): order = MT5Order(conn) print(order.get_all_positions()) order.place_market_order(type="buy", symbol="EURUSD", volume=0.1) order.close_all_profitable_positions() conn.disconnect() else: print("Failed to connect. ๐Ÿšจ") ``` -------------------------------- ### Stream Real-Time Quotes via WebSocket Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Start the quote server and connect using a WebSocket client. ```bash metatrader-quote-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER ``` ```bash websocat ws://localhost:8765 ``` -------------------------------- ### Calculate Spread and Get Symbol Info Source: https://context7.com/ariadng/metatrader-mcp-server/llms.txt Demonstrates how to calculate the spread from price data and retrieve detailed symbol specifications. ```python # Calculate spread spread = price['ask'] - price['bid'] # 0.00002 (2 pips) # Get detailed symbol information symbol_info = client.market.get_symbol_info("EURUSD") # Returns: { # 'name': 'EURUSD', # 'description': 'Euro vs US Dollar', # 'digits': 5, # 'point': 0.00001, # 'trade_tick_size': 0.00001, # 'trade_contract_size': 100000, # 'volume_min': 0.01, # 'volume_max': 500.0, # 'volume_step': 0.01, # 'spread': 2, # 'trade_mode': 4, # Full trading allowed # 'margin_initial': 0.0, # 'margin_maintenance': 0.0, # ... # } client.disconnect() ``` -------------------------------- ### Install Trading Assistant Skill for Claude Desktop Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Copy the trading skill files to the global Claude Desktop skills directory for macOS or Windows. ```bash # 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\" ``` -------------------------------- ### HTTP REST API Server Source: https://context7.com/ariadng/metatrader-mcp-server/llms.txt Start and interact with the FastAPI-based HTTP server for REST API access. ```APIDOC ## HTTP REST API Server ### Description Provides a RESTful API interface to interact with MetaTrader trading operations. ### Starting the Server #### Basic Usage ```bash metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 0.0.0.0 --port 8000 ``` #### With Custom MT5 Terminal Path ```bash metatrader-http-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --path "C:\Program Files\MetaTrader 5\terminal64.exe" ``` #### Using Environment Variables (e.g., from a .env file) ```bash # .env file content: # LOGIN=12345678 # PASSWORD=your_password # SERVER=MetaQuotes-Demo metatrader-http-server --host 0.0.0.0 --port 8000 ``` ### REST API Examples (using curl) #### Get account info ```bash curl http://localhost:8000/api/v1/account/info ``` #### Get current price for a symbol ```bash # Using path parameter curl "http://localhost:8000/api/v1/market/price/EURUSD" # Using query parameter curl "http://localhost:8000/api/v1/market/price?symbol_name=EURUSD" ``` #### Get all symbols ```bash curl http://localhost:8000/api/v1/market/symbols ``` #### Filter symbols by group ```bash curl "http://localhost:8000/api/v1/market/symbols/filter?group=*USD*" ``` #### Get symbol information ```bash curl http://localhost:8000/api/v1/market/symbol/info/EURUSD ``` #### Get latest candles ```bash curl "http://localhost:8000/api/v1/market/candles/latest?symbol_name=EURUSD&timeframe=H1&count=50" ``` #### Get candles by date range ```bash curl "http://localhost:8000/api/v1/market/candles/date?symbol_name=EURUSD&timeframe=D1&date_from=2024-01-01T00:00:00&date_to=2024-12-31T23:59:59" ``` ``` -------------------------------- ### Connect to MetaTrader 5 Terminal Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/connection/connect.md Establishes a connection to the MetaTrader 5 terminal and initiates a session. This is the primary function to start interacting with the terminal. ```APIDOC ## connect(connection) ### Description Connects to the MetaTrader 5 terminal and establishes a session. ### Method POST (Assumed, as it establishes a connection) ### Endpoint /ariadng/metatrader-mcp-server/connect ### Parameters #### Request Body - **connection** (object) - Required - The connection object containing credentials and configuration. - **login** (string) - Required - The MetaTrader account login. - **password** (string) - Required - The MetaTrader account password. - **server** (string) - Required - The MetaTrader server address. - **port** (integer) - Optional - The MetaTrader server port (defaults to 443). ### Response #### Success Response (200) - **success** (bool) - `True` if the connection was successful, `False` otherwise. #### Error Response (400) - **error** (string) - A descriptive message if connection fails. ### Request Example ```json { "connection": { "login": "YOUR_LOGIN", "password": "YOUR_PASSWORD", "server": "YOUR_SERVER.com" } } ``` ### Response Example ```json { "success": true } ``` ### Exceptions - **ConnectionError**: If connection fails for any reason (initialization or login issues). ``` -------------------------------- ### Server Configuration using Environment Variables Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Configures the MetaTrader MCP Server by loading credentials and optional paths from a .env file. The server automatically detects and uses these variables when started without arguments. ```env LOGIN=12345678 PASSWORD=your_password SERVER=MetaQuotes-Demo # Optional: Specify custom MT5 terminal path (auto-detected if not provided) # MT5_PATH=C:\Program Files\MetaTrader 5\terminal64.exe ``` -------------------------------- ### MT5Client Initialization Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/README.md Demonstrates how to initialize the MT5Client with minimal and full configuration options. ```APIDOC ## MT5Client Initialization ### Description Initialize the `MT5Client` with your MetaTrader 5 account credentials and server information. Optional parameters allow for customization of connection behavior and debugging. ### Configuration Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `login` | int | Yes | - | Your MT5 account login number | | `password` | str | Yes | - | Your MT5 account password | | `server` | str | Yes | - | MT5 server name (e.g., "MetaQuotes-Demo") | | `path` | str | No | None | Full path to MT5 terminal executable (auto-detected if not provided) | | `timeout` | int | No | 60000 | Connection timeout in milliseconds | | `portable` | bool | No | False | Enable portable mode for MT5 terminal | | `max_retries` | int | No | 3 | Maximum number of connection retry attempts | | `backoff_factor` | float | No | 1.5 | Exponential backoff factor for retry delays | | `cooldown_time` | float | No | 2.0 | Minimum time in seconds between connection attempts | | `debug` | bool | No | False | Enable detailed debug logging for troubleshooting | ### Request Example (Minimal Configuration) ```python from metatrader_client.client import MT5Client config = { "login": 12345678, "password": "your_password", "server": "Broker-Server" } client = MT5Client(config) ``` ### Request Example (Full Configuration) ```python from metatrader_client.client import MT5Client config = { "login": 12345678, "password": "your_password", "server": "Broker-Server", "path": None, "timeout": 60000, "portable": False, "max_retries": 3, "backoff_factor": 1.5, "cooldown_time": 2.0, "debug": False } client = MT5Client(config) ``` ``` -------------------------------- ### GET /api/v1/positions Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Retrieves all currently open positions. ```APIDOC ## GET /api/v1/positions ### Description Retrieves all currently open positions. ### Method GET ### Endpoint /api/v1/positions ``` -------------------------------- ### Initialize MT5Client Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/README.md Configure and instantiate the MT5Client with account credentials and optional terminal settings. ```python from metatrader_client.client import MT5Client # Minimal configuration config = { "login": 12345678, "password": "your_password", "server": "Broker-Server" } # Full configuration with all available options config = { "login": 12345678, # Required: MT5 account login number "password": "your_password", # Required: MT5 account password "server": "Broker-Server", # Required: MT5 server name "path": None, # Optional: Path to terminal executable (auto-detect if None) "timeout": 60000, # Optional: Connection timeout in ms (default: 60000) "portable": False, # Optional: Use portable mode (default: False) "max_retries": 3, # Optional: Max connection retries (default: 3) "backoff_factor": 1.5, # Optional: Retry delay multiplier (default: 1.5) "cooldown_time": 2.0, # Optional: Seconds between connections (default: 2.0) "debug": False # Optional: Enable debug logging (default: False) } client = MT5Client(config) ``` -------------------------------- ### Get All Positions API Source: https://context7.com/ariadng/metatrader-mcp-server/llms.txt Retrieve a list of all open positions. ```APIDOC ## GET /api/v1/positions ### Description Retrieves a list of all currently open trading positions. ### Method GET ### Endpoint /api/v1/positions ### Response #### Success Response (200) An array of open position objects. #### Response Example ```json [ { "position_id": "123456789", "symbol": "EURUSD", "volume": 0.01, "type": "BUY", "open_price": 1.08500, "current_price": 1.08550, "stop_loss": 1.08000, "take_profit": 1.09000 } ] ``` ``` -------------------------------- ### GET /symbol_info Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/market/get_symbol_info.md Retrieve all available information about a trading symbol. ```APIDOC ## GET /symbol_info ### Description Retrieve all available information about a trading symbol. Perfect for exploring symbol properties and metadata! ### Method GET ### Endpoint /symbol_info ### Parameters #### Query Parameters - **connection** (object) - Required - The MetaTrader connection/session object. - **symbol_name** (string) - Required - The symbol (e.g., 'EURUSD') you want info for. ### Response #### Success Response (200) - **Dict[str, Any]** - Dictionary containing all symbol attributes (tick size, margin, etc). #### Response Example ```json { "tick_size": 0.00001, "spread": 15, "trade_mode": 0, "digits": 5 } ``` ### Error Handling - **SymbolNotFoundError**: If the symbol doesn't exist. ``` -------------------------------- ### GET /api/v1/market/price Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Fetches the current market price for a specific symbol. ```APIDOC ## GET /api/v1/market/price ### Description Fetches the current market price for a specific symbol. ### Method GET ### Endpoint /api/v1/market/price ### Parameters #### Query Parameters - **symbol_name** (string) - Required - The symbol to query (e.g., EURUSD) ``` -------------------------------- ### Get Account Currency Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/account/get_currency.md Retrieves the deposit currency of the MetaTrader account. ```APIDOC ## GET /api/account/currency ### Description Returns the account's deposit currency (e.g., USD, EUR). ### Method GET ### Endpoint /api/account/currency ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **currency** (str) - Account currency code. #### Response Example { "currency": "USD" } ### Error Handling - **AccountInfoError**: If currency can't be retrieved. - **ConnectionError**: If not connected to the terminal. ``` -------------------------------- ### Get Margin Level Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/account/get_margin_level.md Retrieves the current margin level percentage for the account. ```APIDOC ## GET /api/account/margin_level ### Description Returns the current margin level (in %), a key risk metric for your account. ### Method GET ### Endpoint /api/account/margin_level ### Parameters #### Query Parameters - **connection** (object) - Required - The MetaTrader connection object (must be connected!). ### Response #### Success Response (200) - **margin_level** (float) - Current margin level percentage. #### Response Example ```json { "margin_level": 150.5 } ``` ### Errors - **AccountInfoError**: If margin level can't be retrieved. - **ConnectionError**: If not connected to the terminal. ``` -------------------------------- ### Build the Package Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/README.md Commands to build the project from source using the build module. ```bash pip install build python -m build ``` -------------------------------- ### GET /get_orders Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/history/get_orders.md Fetches historical orders from MetaTrader 5 with optional filtering capabilities. ```APIDOC ## GET /get_orders ### Description Fetches historical orders from MetaTrader 5. You can filter by date, group, or ticket. Returns a list of order dictionaries. ### Parameters #### Query Parameters - **from_date** (datetime) - Optional - Start date for history (default: 30 days ago) - **to_date** (datetime) - Optional - End date for history (default: now) - **group** (string) - Optional - Filter by group - **ticket** (integer) - Optional - Filter by ticket number ### Response #### Success Response (200) - **List[Dict[str, Any]]** - List of orders as dictionaries. ### Errors - **ConnectionError**: Raised if not connected. - **OrdersHistoryError**: Raised if MetaTrader 5 errors occur. ``` -------------------------------- ### Minimal MT5Client Configuration Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/CLAUDE.md Shows the essential configuration parameters required to initialize the MT5Client for establishing a connection. ```python from metatrader_client import MT5Client # Minimal configuration config = {"login": int(login), "password": password, "server": server} ``` -------------------------------- ### Initialize MT5Market Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_market.md Establish a connection using MT5Connection before instantiating the MT5Market class. ```python from metatrader_client.client_connection import MT5Connection from metatrader_client.client_market import MT5Market conn = MT5Connection(config) if conn.connect(): market = MT5Market(conn) ``` -------------------------------- ### GET /get_orders_as_dataframe Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/history/get_orders_as_dataframe.md Fetches historical orders from MetaTrader 5 and returns them as a pandas DataFrame. ```APIDOC ## GET get_orders_as_dataframe ### Description Fetches historical orders and returns them as a pandas DataFrame for analysis and reporting. ### Parameters #### Arguments - **connection** (object) - Required - The active MetaTrader 5 connection object. - **from_date** (datetime) - Optional - Start date for history (default: 30 days ago). - **to_date** (datetime) - Optional - End date for history (default: now). - **group** (string) - Optional - Filter by group. - **ticket** (integer) - Optional - Filter by ticket number. ### Returns - **pd.DataFrame** - Orders as a DataFrame, indexed by setup time if available. ### Raises - **OrdersHistoryError** - Raised if DataFrame creation fails. ### Request Example ```python from metatrader_client.history import get_orders_as_dataframe df = get_orders_as_dataframe(conn) ``` ``` -------------------------------- ### GET /get_deals Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/history/get_deals.md Fetches historical deals from MetaTrader 5 based on optional filters. ```APIDOC ## GET /get_deals ### Description Fetches historical deals from MetaTrader 5. You can filter by date, group, ticket, or position. ### Parameters #### Query Parameters - **from_date** (datetime) - Optional - Start date for history (default: 30 days ago) - **to_date** (datetime) - Optional - End date for history (default: now) - **group** (string) - Optional - Filter by group - **ticket** (integer) - Optional - Filter by ticket number - **position** (integer) - Optional - Filter by position ID ### Response #### Success Response (200) - **List[Dict[str, Any]]** - List of deals as dictionaries. ### Request Example ```python from metatrader_client.history import get_deals deals = get_deals(conn, from_date=from_date, to_date=to_date) ``` ``` -------------------------------- ### Use as Python Library Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Basic initialization and connection to the MT5 client library. ```python from metatrader_client import MT5Client # Connect to MT5 config = { "login": 12345678, "password": "your_password", "server": "MetaQuotes-Demo" } client = MT5Client(config) client.connect() ``` -------------------------------- ### Initialize and Connect to MT5 Terminal Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_connection.md Instantiate MT5Connection with configuration and establish a connection. Ensure your login, password, and server details are correct. Optional parameters like path and debug can be provided. ```python from metatrader_client.client_connection import MT5Connection config = { "login": 12345678, "password": "your_password", "server": "Broker-Server", # Optional: # "path": "C:/Program Files/MetaTrader 5/terminal64.exe", # "timeout": 60000, # "debug": True, } mt5_conn = MT5Connection(config) if mt5_conn.connect(): print("Connected! ๐ŸŽ‰") info = mt5_conn.get_terminal_info() print("Terminal Info:", info) mt5_conn.disconnect() else: print("Failed to connect. ๐Ÿšจ") ``` -------------------------------- ### Initialize MT5Account with MT5Connection Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_account.md Establish a connection using MT5Connection and then instantiate the MT5Account class with the active connection object. Ensure the connection is successful before proceeding. ```python from metatrader_client.client_connection import MT5Connection from metatrader_client.client_account import MT5Account conn = MT5Connection(config) if conn.connect(): account = MT5Account(conn) ``` -------------------------------- ### GET /api/v1/account/info Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Retrieves the current account information including balance, equity, margin, and leverage. ```APIDOC ## GET /api/v1/account/info ### Description Retrieves the current account information. ### Method GET ### Endpoint /api/v1/account/info ### Response #### Success Response (200) - **balance** (float) - Account balance - **equity** (float) - Account equity - **margin** (float) - Used margin - **leverage** (int) - Account leverage ``` -------------------------------- ### Configure Remote MCP Server (SSE) Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Run the server on a remote VPS and configure the client to connect via URL. ```bash metatrader-mcp-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER ``` ```bash metatrader-mcp-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER --host 127.0.0.1 --port 9000 ``` ```json { "mcpServers": { "metatrader": { "url": "http://VPS_IP:8080/sse" } } } ``` -------------------------------- ### Manage MCP Server CLI options Source: https://context7.com/ariadng/metatrader-mcp-server/llms.txt View help documentation and configure transport modes or network settings via CLI arguments. ```bash metatrader-mcp-server --help ``` -------------------------------- ### Get Symbol Price Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/market/get_symbol_price.md Retrieves the latest price and tick data for a given symbol from MetaTrader. ```APIDOC ## GET /api/symbol/price ### Description Get the latest price and tick data for a symbol. Perfect for live quotes, trading bots, or just checking the price! ### Method GET ### Endpoint /api/symbol/price ### Parameters #### Query Parameters - **connection** (object) - Required - The MetaTrader connection/session object. - **symbol_name** (str) - Required - The symbol (e.g., 'EURUSD') you want the price for. ### Response #### Success Response (200) - **bid** (float) - The current bid price. - **ask** (float) - The current ask price. - **last** (float) - The last traded price. - **volume** (int) - The volume of the last trade. - **time** (datetime) - The timestamp of the tick data. #### Response Example ```json { "bid": 1.12345, "ask": 1.12350, "last": 1.12348, "volume": 100, "time": "2023-10-27T10:30:00Z" } ``` ### Raises - `SymbolNotFoundError`: If the symbol doesn't exist. ``` -------------------------------- ### GET /get_symbols Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/market/get_symbols.md Retrieves a list of available market symbols from MetaTrader, with optional filtering by group. ```APIDOC ## GET get_symbols ### Description Get a list of all available market symbols, optionally filtered by group. ### Parameters #### Path Parameters - **connection** (object) - Required - The MetaTrader connection/session object. #### Query Parameters - **group** (string) - Optional - Filter symbols by group (e.g., '*USD*' for all USD pairs). ### Response #### Success Response (200) - **List[str]** - List of symbol names matching the filter. ### Request Example ```python symbols = get_symbols(conn, '*JPY*') print(symbols) ``` ``` -------------------------------- ### Get Last Error Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/connection/_get_last_error.md Fetches the last error code and message from the MetaTrader 5 terminal. ```APIDOC ## _get_last_error(connection) ### Description Fetches the last error code and message from the MetaTrader 5 terminal. ### Method GET ### Endpoint /api/metatrader/last_error ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **error_code** (int) - The last error code. - **error_message** (str) - The last error message. #### Response Example { "error_code": 10001, "error_message": "Connection lost" } ``` -------------------------------- ### Initialize MT5Order Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_order.md Create an instance of MT5Order using an active MT5Connection. ```python from metatrader_client.client_connection import MT5Connection from metatrader_client.client_order import MT5Order conn = MT5Connection(config) if conn.connect(): order = MT5Order(conn) ``` -------------------------------- ### Initialize MT5Client Source: https://context7.com/ariadng/metatrader-mcp-server/llms.txt Configure and connect to the MetaTrader 5 terminal using the MT5Client class. ```python from metatrader_client import MT5Client # Basic configuration config = { "login": 12345678, "password": "your_password", "server": "MetaQuotes-Demo" } # Advanced configuration with all options config = { "login": 12345678, "password": "your_password", "server": "MetaQuotes-Demo", "path": "C:\\Program Files\\MetaTrader 5\\terminal64.exe", # Optional: auto-detected if not provided "timeout": 60000, # Connection timeout in milliseconds "portable": False, # Use portable mode "max_retries": 3, # Maximum connection retry attempts "backoff_factor": 1.5, # Delay multiplier between retries "cooldown_time": 2.0, # Seconds to wait between connections "debug": True # Enable debug logging } client = MT5Client(config) # Connect to terminal success = client.connect() # Returns True if successful # Check connection status if client.is_connected(): print("Connected to MT5") # Get terminal information terminal_info = client.get_terminal_info() # Returns: {'name': 'MetaTrader 5', 'path': '...', 'data_path': '...', 'company': '...', ...} # Get terminal version version = client.get_version() # Returns: (5, 0, 3650, 0) # Disconnect when done client.disconnect() ``` -------------------------------- ### Import MT5Client Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/README.md Import the main client class from the library. ```python from metatrader_client.client import MT5Client ``` -------------------------------- ### GET /get_trade_statistics Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/account/get_trade_statistics.md Retrieves basic trade statistics including balance, equity, profit, and account details. ```APIDOC ## GET /get_trade_statistics ### Description Returns a dictionary with basic trade statistics: balance, equity, profit, margin level, free margin, account type, leverage, and currency. ### Parameters #### Request Body - **connection** (object) - Required - The MetaTrader connection object (must be connected). ### Response #### Success Response (200) - **stats** (Dict[str, Any]) - Dictionary containing account statistics. ### Request Example { "connection": "active_connection_object" } ### Response Example { "balance": 10000.0, "equity": 10050.0, "profit": 50.0, "margin_level": 500.0, "free_margin": 9000.0, "account_type": "demo", "leverage": 100, "currency": "USD" } ``` -------------------------------- ### Import MT5Market Class Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_market.md Import the MT5Market class from the client_market module. ```python from metatrader_client.client_market import MT5Market ``` -------------------------------- ### GET /get_total_deals Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/history/get_total_deals.md Retrieves the total number of deals from the MetaTrader 5 history within a specified date range. ```APIDOC ## GET /get_total_deals ### Description Counts the total number of deals in your MetaTrader 5 history. Useful for stats and sanity checks. ### Parameters #### Query Parameters - **connection** (object) - Required - Your MetaTrader 5 connection object. - **from_date** (datetime) - Optional - Start date for history (default: 30 days ago). - **to_date** (datetime) - Optional - End date for history (default: now). ### Response #### Success Response (200) - **total** (int) - Total number of deals. ### Request Example ```python from metatrader_client.history import get_total_deals total = get_total_deals(conn) ``` ``` -------------------------------- ### Initialize Terminal Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/connection/_initialize_terminal.md Initializes the MetaTrader 5 terminal for a new session. ```APIDOC ## initialize_terminal(connection) ### Description Initializes the MetaTrader 5 terminal for a new session. ### Parameters #### Path Parameters - **connection** (object) - Required - The connection object with initialization details. ### Returns - **bool** - `True` if initialization is successful, `False` otherwise. ### Raises - **InitializationError**: If initialization fails after retries. ### How it works 1. Ensures cooldown before initializing. 2. Attempts initialization with retries and jitter. 3. Handles errors gracefully. ### Fun Fact This function gets your MetaTrader engine runningโ€”start your trading engines! ``` -------------------------------- ### Get Account Statistics Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Retrieves and prints the current balance and equity of the trading account. Ensure the client is connected before calling. ```python stats = client.account.get_trade_statistics() print(f"Balance: ${stats['balance']}") print(f"Equity: ${stats['equity']}") ``` -------------------------------- ### GET /api/candles/latest Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/market/get_candles_latest.md Fetches the latest N candles for a given symbol and timeframe. Useful for live dashboards and quick analyses. ```APIDOC ## GET /api/candles/latest ### Description Fetch the latest N candles for a given symbol and timeframe. Great for live dashboards, quick analyses, or just keeping your finger on the market pulse! ### Method GET ### Endpoint /api/candles/latest ### Parameters #### Query Parameters - **symbol_name** (str) - Required - The symbol (e.g., 'EURUSD') you want candles for. - **timeframe** (str) - Required - Timeframe string (e.g., 'M1', 'H1', 'D1'). - **count** (int) - Optional - Number of latest candles to fetch. Defaults to 100. ### Response #### Success Response (200) - **candles** (pd.DataFrame) - DataFrame with the latest candle data (open, high, low, close, volume, time, etc). #### Response Example ```json { "candles": [ { "open": 1.12345, "high": 1.12350, "low": 1.12300, "close": 1.12320, "volume": 1000, "time": "2023-10-27T10:00:00Z" } // ... more candle data ] } ``` ### Error Handling - **SymbolNotFoundError**: If the symbol doesn't exist. - **InvalidTimeframeError**: If the timeframe is invalid. - **MarketDataError**: If data retrieval fails. ``` -------------------------------- ### Connection Parameters Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/README.md Configuration options for establishing a connection to the MT5 client. ```APIDOC ## 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 ``` -------------------------------- ### Client-Level Error Handling Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/CLAUDE.md Example of basic input validation for trade types before executing an operation, returning a structured error response. ```python # Client level if type.upper() not in ["BUY", "SELL"]: return {"error": True, "message": "Invalid type", "data": None} ``` -------------------------------- ### Import MT5History class Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/_history.md Import the MT5History class from the client_history module. ```python from metatrader_client.client_history import MT5History ``` -------------------------------- ### Full MT5Client Configuration Options Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/CLAUDE.md Details all available configuration options for the MT5Client, including connection parameters, retry logic, and debug settings. ```python # Full configuration with all available options config = { "login": int(login), # Required: MT5 account login "password": password, # Required: MT5 account password "server": server, # Required: MT5 server name "path": None, # Optional: Path to terminal executable (auto-detect if None) "timeout": 60000, # Optional: Connection timeout in ms (default: 60000) "portable": False, # Optional: Use portable mode (default: False) "max_retries": 3, # Optional: Max connection retries (default: 3) "backoff_factor": 1.5, # Optional: Retry delay multiplier (default: 1.5) "cooldown_time": 2.0, # Optional: Seconds between connections (default: 2.0) "debug": False # Optional: Enable debug logging (default: False) } client = MT5Client(config) client.connect() # operations... client.disconnect() ``` -------------------------------- ### Get Account Currency Source: https://github.com/ariadng/metatrader-mcp-server/blob/main/docs/metatrader_client/account/get_currency.md Use this function to retrieve the account's deposit currency. Ensure the MetaTrader connection is established before calling. ```python currency = get_currency(connection) print(f"Account currency: {currency} ๐Ÿ’ต") ```