### CLI Example: Get Rates Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/INDEX.md This is an example of how to use the MT5 Bridge CLI to get currency rates. Ensure the server is running and accessible at the specified URL. ```bash mt5-bridge client --url http://server:8000 rates XAUUSD ``` -------------------------------- ### Start the MT5 Bridge Server Source: https://github.com/akivajp/mt5-bridge/blob/main/README.md Launch the server on a Windows machine with MetaTrader 5 installed. ```powershell # Default (localhost:8000) uv run mt5-bridge server # Custom host/port uv run mt5-bridge server --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Install mt5-bridge Source: https://github.com/akivajp/mt5-bridge/blob/main/README.md Install the package from PyPI or sync dependencies from source. ```bash pip install mt5-bridge ``` ```bash # Install dependencies uv sync ``` -------------------------------- ### Server Initialization and Startup Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/MANIFEST.txt Details on how to initialize and start the MT5 Bridge server. ```APIDOC ## Server Initialization and Startup ### Description Provides instructions and details for initializing and starting the MT5 Bridge server. This includes any necessary configurations or prerequisites. ### Method N/A (Server Startup) ### Endpoint N/A (Server Startup) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Ticks From Output Example Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Example output for historical ticks fetched using ticks_from, showing retrieved count and tick data. ```text Retrieved 1000 ticks [ { "time": 1704067200, "time_msc": 1704067200100, "bid": 2046.20, "ask": 2046.30, "last": 2046.25, "volume": 100, "flags": 2 }, ... ] ... and 990 more ticks ``` -------------------------------- ### Apply CLI Arguments to MT5Handler Instance Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Shows how command-line arguments are used to update the global `mt5_handler` instance before the server starts. ```python if args.mt5_path: mt5_handler.program_path = args.mt5_path if args.mt5_login: mt5_handler.login = args.mt5_login if args.mt5_password: mt5_handler.password = args.mt5_password if args.mt5_server: mt5_handler.server = args.mt5_server mt5_handler.use_utc = not args.no_utc ``` -------------------------------- ### Get Account Information Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Fetches detailed information about the trading account. ```bash mt5-bridge client account ``` -------------------------------- ### Run MT5 Bridge Server with Custom Host and Port Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Starts the MT5 Bridge server, binding to a specified host and listening on a custom port. ```bash mt5-bridge server --host 0.0.0.0 --port 9000 ``` -------------------------------- ### CLI Commands for MT5 Bridge Server and Client Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/README.md This section shows how to start the MT5 Bridge server and use the CLI client for various operations including fetching data and placing orders. ```bash # Server (Windows only) mt5-bridge server --host 0.0.0.0 --port 8000 # Client queries mt5-bridge client --url http://server:8000 rates XAUUSD --timeframe H1 --count 50 mt5-bridge client --url http://server:8000 account mt5-bridge client --url http://server:8000 positions --symbols XAUUSD # Client orders mt5-bridge client --url http://server:8000 order XAUUSD BUY 0.1 --sl 2040 --tp 2050 mt5-bridge client --url http://server:8000 close 123456789 ``` -------------------------------- ### Display Version Information Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Use the --version flag to display the installed MT5 Bridge version and the Python version. ```bash mt5-bridge --version ``` -------------------------------- ### Run MT5 Bridge Server (Default) Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Starts the MT5 Bridge server using default settings, attempting to auto-detect the MT5 terminal and listening on localhost:8000. ```bash mt5-bridge server ``` -------------------------------- ### Run MT5 Bridge Server with Auto-Login Credentials Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Starts the MT5 Bridge server and configures it to auto-login to a specified MT5 account using provided credentials. ```bash mt5-bridge server --mt5-login 12345678 --mt5-password "mypassword" --mt5-server "MetaQuotes-Demo" ``` -------------------------------- ### Initialize MT5 Connection on Server Startup Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/endpoints.md This Python snippet shows how to initialize the MT5 connection when the FastAPI server starts. It includes platform-specific checks for Windows and initiates a background connection monitor. ```python import sys import asyncio # Assuming app and mt5_handler are defined elsewhere # from your_module import app, mt5_handler @app.on_event("startup") async def startup_event(): """Initialize MT5 connection on startup.""" # Only try to initialize if we are on Windows if sys.platform == "win32": if not mt5_handler.initialize(): print("WARNING: Failed to initialize MT5 on startup. Will retry in background.") # Start connection monitor asyncio.create_task(monitor_connection()) # monitor_connection needs to be defined else: print("Non-Windows platform detected: MT5 connection disabled.") ``` -------------------------------- ### Fetch Historical Ticks from Start Timestamp Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Fetch historical ticks starting from a given timestamp, with options for count and tick flags. ```bash mt5-bridge client ticks_from --start [OPTIONS] ``` ```bash # Get 1000 ticks from 2026-01-01 mt5-bridge client ticks_from XAUUSD --start 2026-01-01 ``` ```bash # Get 500 trade ticks from specific date mt5-bridge client ticks_from XAUUSD --start "2026-01-01 10:00:00" --count 500 --flags TRADE ``` ```bash # Get info ticks only mt5-bridge client ticks_from BTCUSD --start 2026-01-15 --flags INFO ``` -------------------------------- ### Run Uvicorn ASGI Server Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Starts the uvicorn server to run the FastAPI application on the specified host and port. ```python uvicorn.run(app, host=args.host, port=args.port) ``` -------------------------------- ### Run MT5 Bridge Server with Combined Options Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Starts the MT5 Bridge server with a combination of custom host, port, MT5 login credentials, and UTC conversion disabled. ```bash mt5-bridge server --host 192.168.1.100 --port 8000 --mt5-login 12345 --mt5-password "pass" --mt5-server "MetaQuotes-Demo" --no-utc ``` -------------------------------- ### GET /positions Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/types.md Retrieves a list of all open trading positions. ```APIDOC ## GET /positions ### Description Retrieves a list of all open trading positions. ### Method GET ### Endpoint /positions ### Response #### Success Response (200) An array of Position objects, where each object contains: - **ticket** (int) - Position ticket (unique identifier) - **symbol** (str) - Symbol traded (e.g., "XAUUSD") - **type** (str) - "BUY" or "SELL" - **volume** (float) - Position size (lots) - **price_open** (float) - Entry price - **comment** (str) - Position comment (set at order time or later) - **magic** (int) - Magic number (for position tracking/identification) - **sl** (float) - Stop loss price (0 = no stop loss) - **tp** (float) - Take profit price (0 = no take profit) - **price_current** (float) - Current market price for the symbol - **profit** (float) - Unrealized profit/loss (in account currency) - **time** (int) - Position open time (Unix timestamp, seconds, UTC) - **time_msc** (int) - Position open time (milliseconds precision) #### Response Example [ { "ticket": 123456789, "symbol": "XAUUSD", "type": "BUY", "volume": 0.1, "price_open": 1850.50, "comment": "My trade", "magic": 12345, "sl": 1840.00, "tp": 1900.00, "price_current": 1855.20, "profit": 47.00, "time": 1678886400, "time_msc": 1678886400123 } ] ``` -------------------------------- ### Run MT5 Bridge Server with Custom MT5 Path Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Starts the MT5 Bridge server, specifying the exact path to the MetaTrader 5 terminal executable. ```bash mt5-bridge server --mt5-path "C:\\Program Files\\MetaTrader 5\\terminal64.exe" ``` -------------------------------- ### Get Account Information Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md The expected JSON output format for account information. ```json { "login": 12345678, "balance": 10000.00, "equity": 10500.00, "margin": 2000.00, "margin_free": 8000.00, "margin_level": 525.0, "leverage": 100, "currency": "USD", "server": "MetaQuotes-Demo" } ``` -------------------------------- ### Configure MT5 Bridge Server via CLI Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/README.md Start the mt5-bridge server using command-line arguments for configuration. Use '--no-utc' to disable UTC conversion. ```bash mt5-bridge server \ --host 0.0.0.0 \ --port 8000 \ --mt5-path "/path/to/terminal64.exe" \ --mt5-login 12345678 \ --mt5-password "password" \ --mt5-server "MetaQuotes-Demo" \ --no-utc # Disable UTC conversion ``` -------------------------------- ### Close Position Success Output Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Example JSON output for a successfully closed position. ```json { "status": "ok" } ``` -------------------------------- ### Example: MCP Server HTTP Mode Configuration Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Configure the MCP server to run in HTTP mode with a custom API base URL and port. This allows for network-based communication. ```bash # HTTP mode python mt5_bridge/mcp_server.py --http --api-base http://server:8000 --port 8001 ``` -------------------------------- ### Run MT5 Bridge Server Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Starts the MT5 Bridge server. Press Ctrl+C to stop. On non-Windows systems, this command exits with an error code as the server is not supported. ```bash mt5-bridge server # Runs server indefinitely; press Ctrl+C to stop (exit code 0) mt5-bridge server # on non-Windows # Exits with code 1 (server not supported on non-Windows) ``` -------------------------------- ### Get Account Information Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/api-reference.md Fetches current account details including balance, equity, and margin. Use this to monitor account status. ```python def get_account_info(self) -> Optional[Dict[str, Any]] account = client.get_account_info() if account: print(f"Balance: {account['balance']} {account['currency']}") print(f"Equity: {account['equity']}") print(f"Free margin: {account['margin_free']}") ``` -------------------------------- ### Example Copilot CLI Interaction Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/mcp-server-reference.md Demonstrates a typical user interaction with Copilot CLI when calling MT5 Bridge tools. This shows how Claude Code can invoke bridge functionalities. ```text user: What's the latest price for XAUUSD? claude: I'll fetch the latest tick for you. → [calls health() → ok, then get_tick("XAUUSD")] → "The current price for XAUUSD is $2046.25 (bid: $2046.20, ask: $2046.30)" ``` -------------------------------- ### Market Order Success Output Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Example JSON output for a successfully submitted market order. ```json { "status": "ok", "ticket": 123456789 } ``` -------------------------------- ### Run MCP Server Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/INDEX.md To use MT5 Bridge with Claude/Copilot, you need to run the MCP server. This command starts the server using Python. ```bash python mt5_bridge/mcp_server.py ``` -------------------------------- ### HTTP Requests with curl Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/MANIFEST.txt Examples and guidance on making requests to the MT5 Bridge API using the `curl` command-line tool. ```APIDOC ## HTTP Requests with curl ### Description Provides examples of how to interact with the MT5 Bridge API endpoints using the `curl` command-line utility. This is useful for testing and scripting. ### Method All HTTP Methods (GET, POST, PUT, DELETE) ### Endpoint Examples will use placeholder endpoints like `/orders/market`. ### Parameters N/A ### Request Example ```bash # Example: Placing a market order curl -X POST \ http://localhost:8080/orders/market \ -H 'Content-Type: application/json' \ -d '{ "symbol": "EURUSD", "type": "buy", "volume": 0.1 }' ``` ### Response N/A ``` -------------------------------- ### GET /account Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/endpoints.md Fetches the current account information from the MT5 server. This includes details like balance, equity, margin, and leverage. ```APIDOC ## GET /account ### Description Fetch current account information. ### Method GET ### Endpoint /account ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **login** (int) - Account login number - **balance** (float) - Account balance (base currency) - **equity** (float) - Total equity (balance + profit/loss) - **margin** (float) - Margin used (in account currency) - **margin_free** (float) - Free margin available - **margin_level** (float) - Margin level percentage - **leverage** (int) - Account leverage ratio - **currency** (str) - Account base currency code - **server** (str) - MT5 server name #### Response Example ```json { "login": 12345678, "balance": 10000.00, "equity": 10500.00, "margin": 2000.00, "margin_free": 8000.00, "margin_level": 525.0, "leverage": 100, "currency": "USD", "server": "MetaQuotes-Demo" } ``` ``` -------------------------------- ### Handle Connection Errors Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Example of a client command failing due to an invalid URL, resulting in a connection error message. This demonstrates how HTTP errors are reported. ```bash mt5-bridge client --url http://invalid:9999 health # Error: Failed to reach MT5 Bridge ``` -------------------------------- ### GET /positions Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/endpoints.md Fetches open positions from the MT5 server. Supports filtering by symbols and magic number. ```APIDOC ## GET /positions ### Description Fetch open positions with optional filtering. ### Method GET ### Endpoint /positions ### Parameters #### Query Parameters - **symbols** (str) - Optional - Comma-separated list of symbols (e.g., "XAUUSD,BTCUSD"). If provided, only positions for these symbols are returned. - **magic** (int) - Optional - Magic number filter. If provided, only positions with this magic number are returned. #### Request Body None ### Response #### Success Response (200) - **ticket** (int) - Position ticket (unique identifier) - **symbol** (str) - Symbol name - **type** (str) - "BUY" or "SELL" - **volume** (float) - Position size (in lots) - **price_open** (float) - Entry price - **comment** (str) - Position comment - **magic** (int) - Magic number (for tracking) - **sl** (float) - Stop loss price - **tp** (float) - Take profit price - **price_current** (float) - Current market price - **profit** (float) - Unrealized P&L in account currency - **time** (int) - Position open time (Unix timestamp, seconds) - **time_msc** (int) - Position open time (milliseconds precision) #### Response Example ```json [ { "ticket": 123456789, "symbol": "XAUUSD", "type": "BUY", "volume": 0.1, "price_open": 2045.00, "comment": "Scalp trade", "magic": 123456, "sl": 2040.00, "tp": 2050.00, "price_current": 2046.30, "profit": 13.00, "time": 1704067200, "time_msc": 1704067200500 } ] ``` ``` -------------------------------- ### Get Open Positions Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Retrieves a list of currently open trading positions. Can be filtered by symbols or magic number. ```bash mt5-bridge client positions [--symbols ] [--magic ] ``` ```bash mt5-bridge client positions ``` ```bash mt5-bridge client positions --symbols XAUUSD,BTCUSD ``` ```bash mt5-bridge client positions --magic 123456 ``` -------------------------------- ### Run MCP Server in HTTP Mode on Custom Port Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/mcp-server-reference.md Start the MCP server in HTTP mode, listening on a non-default port. The server will be accessible at http://0.0.0.0:. ```bash python mt5_bridge/mcp_server.py --http --port 9000 ``` -------------------------------- ### Get Ticks from Start Date Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Retrieves tick data starting from a specified date or timestamp. You can limit the count and filter tick types. ```bash mt5-bridge client ticks_from --start [--count ] [--flags ] ``` ```bash mt5-bridge client ticks_from XAUUSD --start 2026-01-01 --count 500 --flags TRADE ``` -------------------------------- ### Run MT5 Bridge Server with UTC Conversion Disabled Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Starts the MT5 Bridge server without performing UTC conversion, using raw server time. ```bash mt5-bridge server --no-utc ``` -------------------------------- ### ticks_from Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Get tick data for a symbol starting from a specific date or timestamp. ```APIDOC ## ticks_from ### Description Get ticks from a specified start date or timestamp. ### Method GET ### Endpoint /client/ticks_from ### Parameters #### Query Parameters - **SYMBOL** (string) - Required - Symbol name. - **--start** (string) - Required - Start date or Unix timestamp. - **--count** (integer) - Optional - Number of ticks to retrieve. Defaults to 1000. - **--flags** (string) - Optional - Tick type filter: "ALL", "INFO", or "TRADE". Defaults to "ALL". ### Response #### Success Response (200) - **ticks** (array of objects) - Tick data from the specified start point. ``` -------------------------------- ### Get Ticks within Date Range Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Fetches tick data within a specified start and end date/timestamp. Allows filtering by tick type. ```bash mt5-bridge client ticks_range --start --end [--flags ] ``` ```bash mt5-bridge client ticks_range XAUUSD --start "2026-01-01 10:00:00" --end "2026-01-01 10:05:00" ``` -------------------------------- ### Configure Bridge Client via Constructor Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/README.md Initialize BridgeClient with the base URL of the MT5 Bridge server. ```python client = BridgeClient(base_url="http://192.168.1.10:8000") ``` -------------------------------- ### GET /ticks_from/{symbol} Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/endpoints.md Fetches historical tick data for a given symbol starting from a specified timestamp. Supports filtering by tick type and retrieving a specific count of ticks. ```APIDOC ## GET /ticks_from/{symbol} ### Description Fetch historical tick data from a starting timestamp (count-based). ### Method GET ### Endpoint `/ticks_from/{symbol}` ### Parameters #### Path Parameters - **symbol** (str) - Required - Symbol name #### Query Parameters - **start** (str) - Required - Start timestamp or datetime string (UTC) - **count** (int) - Optional - Number of ticks to retrieve (default: 1000) - **flags** (str) - Optional - Tick type: "ALL", "INFO" (bid/ask changes), "TRADE" (last/volume changes) (default: "ALL") ### Request Body None ### Response #### Success Response (200) Array of HistoricalTick objects. #### Response Example ```json [ { "time": 1704067200, "time_msc": 1704067200100, "bid": 2046.20, "ask": 2046.30, "last": 2046.25, "volume": 100, "flags": 2 } ] ``` #### Response Fields - **time** (int) - Tick time (seconds) - **time_msc** (int) - Tick time (milliseconds) - **bid** (float) - Bid price - **ask** (float) - Ask price - **last** (float) - Last traded price - **volume** (int) - Volume at tick - **flags** (int) - Tick change flags (bit mask from MT5) #### Error Responses - **400** - Invalid date format - **500** - Failed to fetch ticks ``` -------------------------------- ### initialize() Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/MT5Handler-reference.md Initializes the connection to the MetaTrader 5 terminal. ```APIDOC ## initialize() ### Description Initializes the connection to the MetaTrader 5 terminal. ### Method `initialize()` ### Returns - **bool**: True if initialization succeeded, False otherwise. ### Behavior - If `program_path` is set, passes it to MT5's `initialize()`. - If `login`, `password`, and `server` are set, attempts auto-login. - Sets `self.connected` to True on success, False on failure. - Returns False on Windows if MT5 package is unavailable. ### Example ```python handler = MT5Handler( login=12345678, password="mypassword", server="MetaQuotes-Demo" ) if handler.initialize(): print("Connected!") else: print("Connection failed") ``` ``` -------------------------------- ### GET /rates_range/{symbol} Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/endpoints.md Fetches historical OHLCV bars for a given symbol within a specified date range. Supports flexible date parsing for start and end times. ```APIDOC ## GET /rates_range/{symbol} ### Description Fetch historical OHLCV bars within a specific date range. ### Method GET ### Endpoint `/rates_range/{symbol}` ### Parameters #### Path Parameters - **symbol** (str) - Description: Symbol name #### Query Parameters - **timeframe** (str) - Required - Description: Timeframe code (M1, H1, etc.) - **start** (str) - Required - Description: Start timestamp or datetime string (UTC). Formats: Unix seconds (e.g., "1704067200") or ISO/natural date strings (e.g., "2026-01-01", "2026-01-01 10:30:00") - **end** (str) - Required - Description: End timestamp or datetime string (UTC) ### Response #### Success Response (200) Array of Rate objects (same as `/rates/{symbol}`). #### Error Response - **400** - Invalid date format - **500** - MT5 fetch failed ### Example Query ``` GET /rates_range/XAUUSD?timeframe=H1&start=2026-01-01&end=2026-01-15 ``` ``` -------------------------------- ### Get Historical Tick Data Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/api-reference.md Retrieves historical tick data for a symbol starting from a specified timestamp. Supports configurable count and flags for tick types (ALL, INFO, TRADE). The timeout is 60 seconds due to potentially large data volumes. ```python import time start = int(time.time()) - 3600 # 1 hour ago ticks = client.get_ticks_from("XAUUSD", start, count=500, flags="TRADE") print(f"Got {len(ticks)} trade ticks") ``` -------------------------------- ### Run MCP Server Source: https://github.com/akivajp/mt5-bridge/blob/main/README.md Expose the MT5 Bridge API to the Copilot CLI. ```bash python mt5_bridge/mcp_server.py --api-base http://localhost:8000 ``` -------------------------------- ### GET /account Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/types.md Retrieves information and status of the account. ```APIDOC ## GET /account ### Description Retrieves information and status of the account. ### Method GET ### Endpoint /account ### Response #### Success Response (200) - **login** (int) - Account login number - **balance** (float) - Account balance (base currency) - **equity** (float) - Total equity (balance + unrealized P&L) - **margin** (float) - Margin used (account currency) - **margin_free** (float) - Free margin available - **margin_level** (float) - Margin level as percentage - **leverage** (int) - Account leverage ratio (e.g., 100, 500) - **currency** (str) - Base currency code (e.g., "USD", "EUR") - **server** (str) - MT5 server name #### Response Example { "login": 12345678, "balance": 10000.50, "equity": 10500.75, "margin": 500.00, "margin_free": 10000.75, "margin_level": 2100.15, "leverage": 500, "currency": "USD", "server": "MT5Server1" } ``` -------------------------------- ### tick Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Get the latest tick data for a given symbol. ```APIDOC ## tick ### Description Get the latest tick data for a specified symbol. ### Method GET ### Endpoint /client/tick ### Parameters #### Query Parameters - **SYMBOL** (string) - Required - Symbol name (e.g., XAUUSD). ### Response #### Success Response (200) - **tick** (object) - The latest tick data, including bid, ask, and time. ``` -------------------------------- ### Launch MCP Server with Custom Configuration Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Launch the MCP server with custom API base URL and listen address using command-line arguments. Supports stdio or HTTP modes. ```bash python mt5_bridge/mcp_server.py [--http] [--api-base ] [--host ] [--port ] ``` -------------------------------- ### book Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Get the market depth (order book) for a given symbol. ```APIDOC ## book ### Description Get market depth. ### Method GET ### Endpoint /client/book ### Parameters #### Query Parameters - **SYMBOL** (string) - Required - Symbol name (e.g., XAUUSD). ### Response #### Success Response (200) - **market_depth** (object) - The market depth information, including bid and ask levels. ``` -------------------------------- ### GET /health Source: https://github.com/akivajp/mt5-bridge/blob/main/README.md Check the connection health of the MT5 bridge server. ```APIDOC ## GET /health ### Description Checks if the MT5 bridge server is running and connected to the terminal. ### Method GET ### Endpoint /health ``` -------------------------------- ### Initialize MT5Handler Connection Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/MT5Handler-reference.md Establishes a connection to the MetaTrader 5 terminal using provided account credentials. Returns True on successful connection, False otherwise. ```python handler = MT5Handler( login=12345678, password="mypassword", server="MetaQuotes-Demo" ) if handler.initialize(): print("Connected!") else: print("Connection failed") ``` -------------------------------- ### Initialize FastMCP Server Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/mcp-server-reference.md Initializes the FastMCP server with a specific name and Japanese instructions for the client. This sets up the server to act as an interface for MT5 functionalities. ```python from fastmcp import FastMCP mcp = FastMCP( "mt5-bridge", instructions=( "MT5を用いたチャートデータやポジション情報の取得、実際の取引注文を行います。" "レートの取得やチャート分析が求められた場合などは必ずこのツールを使用してください。" ), ) ``` -------------------------------- ### GET /symbols Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/endpoints.md Retrieve a list of all trading symbols supported by the MT5 Bridge. ```APIDOC ## GET /symbols ### Description Retrieve the list of all available trading symbols. ### Method GET ### Endpoint /symbols ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) List of symbol name strings. #### Response Example ```json [ "XAUUSD", "BTCUSD", "EURUSD" ] ``` ``` -------------------------------- ### Initialize FastAPI Application and MT5Handler Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Initializes the FastAPI application with a title and creates an instance of the MT5Handler. ```python app = FastAPI(title="MT5 Bridge API") mt5_handler = MT5Handler() ``` -------------------------------- ### GET /rates/{symbol} Source: https://github.com/akivajp/mt5-bridge/blob/main/README.md Retrieve historical bar data for a specific symbol. ```APIDOC ## GET /rates/{symbol} ### Description Fetches historical rates for the specified symbol. ### Method GET ### Endpoint /rates/{symbol} ### Parameters #### Path Parameters - **symbol** (string) - Required - The trading symbol (e.g., XAUUSD) #### Query Parameters - **timeframe** (string) - Optional - Timeframe (e.g., M1) - **count** (integer) - Optional - Number of bars to retrieve ``` -------------------------------- ### Close Position Error Output Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Example JSON output for an error when closing a position. ```json { "status": "error", "detail": "Position not found" } ``` -------------------------------- ### ticks_range Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Get tick data for a symbol within a specified date and time range. ```APIDOC ## ticks_range ### Description Get ticks within a specified date range. ### Method GET ### Endpoint /client/ticks_range ### Parameters #### Query Parameters - **SYMBOL** (string) - Required - Symbol name. - **--start** (string) - Required - Start date/timestamp (e.g., "2026-01-01 10:00:00"). - **--end** (string) - Required - End date/timestamp. - **--flags** (string) - Optional - Tick type filter. ### Response #### Success Response (200) - **ticks** (array of objects) - Tick data within the specified range. ``` -------------------------------- ### Get Latest Tick Data Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md The expected JSON output format for tick data. ```json { "time": 1704067200, "time_msc": 1704067200500, "bid": 2046.20, "ask": 2046.30, "last": 2046.25, "volume": 1000 } ``` -------------------------------- ### Get List of Trading Symbols Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md The expected JSON output when listing trading symbols. ```json [ "XAUUSD", "BTCUSD", "EURUSD" ] ``` -------------------------------- ### Initialize BridgeClient Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/api-reference.md Instantiate the BridgeClient with the server's base URL. The default is http://localhost:8000. Trailing slashes in the URL are automatically removed. ```python from mt5_bridge.client import BridgeClient client = BridgeClient("http://192.168.1.10:8000") ``` -------------------------------- ### Get Market Depth Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Retrieves the market depth (order book) for a given symbol. ```bash mt5-bridge client book ``` ```bash mt5-bridge client book XAUUSD ``` -------------------------------- ### Example: MCP Server Stdio Mode Configuration Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Configure the MCP server to run in stdio mode with a custom API base URL. This is the default mode, often used for integration with CLI tools. ```bash # Stdio mode (default, for integration with Copilot CLI) python mt5_bridge/mcp_server.py --api-base http://192.168.1.10:8000 ``` -------------------------------- ### Get Latest Tick Data Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Retrieves the most recent tick data for a specified symbol. ```bash mt5-bridge client tick ``` ```bash mt5-bridge client tick XAUUSD ``` -------------------------------- ### Market Order Error Output Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Example JSON output for an error during market order submission. ```json { "status": "error", "detail": "Invalid stops (10016)" } ``` -------------------------------- ### Interact with MT5 Bridge Client Source: https://github.com/akivajp/mt5-bridge/blob/main/README.md Use the CLI client to fetch market data, account info, or execute trades against a running server. ```bash # Check connection health uv run mt5-bridge client --url http://192.168.1.10:8000 health # Get historical rates (M1, last 1000 bars) for XAUUSD uv run mt5-bridge client --url http://192.168.1.10:8000 rates XAUUSD # Get historical rates by date range (M1, 2026-01-01 to 2026-01-15) uv run mt5-bridge client --url http://192.168.1.10:8000 rates_range XAUUSD --timeframe M1 --start 2026-01-01 --end 2026-01-15 # Get historical tick data from a specific date (count-based) uv run mt5-bridge client --url http://192.168.1.10:8000 ticks_from XAUUSD --start 2026-01-01 --count 1000 --flags ALL # Get historical tick data within a date range uv run mt5-bridge client --url http://192.168.1.10:8000 ticks_range XAUUSD --start "2026-01-01 10:00:00" --end "2026-01-01 10:05:00" --flags TRADE # Get latest tick uv run mt5-bridge client --url http://192.168.1.10:8000 tick XAUUSD # Get market depth (Level 2) uv run mt5-bridge client --url http://192.168.1.10:8000 book XAUUSD # Get account information uv run mt5-bridge client --url http://192.168.1.10:8000 account # List open positions (optional filters: --symbols XAUUSD,BTCUSD --magic 123456) uv run mt5-bridge client --url http://192.168.1.10:8000 positions # Send order uv run mt5-bridge client --url http://192.168.1.10:8000 order XAUUSD BUY 0.01 --sl 2000.0 --tp 2050.0 # Close position uv run mt5-bridge client --url http://192.168.1.10:8000 close 12345678 # Modify position uv run mt5-bridge client --url http://192.168.1.10:8000 modify 12345678 --sl 2005.0 ``` -------------------------------- ### Configure MCP Server via CLI Arguments Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/README.md Run the MCP server script with command-line arguments to specify the API base URL and port. ```bash python mt5_bridge/mcp_server.py --api-base http://server:8000 --http --port 8001 ``` -------------------------------- ### Get Open Positions Data Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md The expected JSON output format for open trading positions. ```json [ { "ticket": 123456789, "symbol": "XAUUSD", "type": "BUY", "volume": 0.1, "price_open": 2045.00, "comment": "Scalp trade", "magic": 123456, "sl": 2040.00, "tp": 2050.00, "price_current": 2046.30, "profit": 13.00, "time": 1704067200, "time_msc": 1704067200500 } ] ``` -------------------------------- ### Configure Client Connection via CLI Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Configure the MT5 Bridge client connection using command-line arguments. Specify the server URL with the --url flag. ```bash # Default server mt5-bridge client health # Remote server mt5-bridge client --url http://192.168.1.10:8000 rates XAUUSD # Remote with auth (if applicable) mt5-bridge client --url http://server:8000 account ``` -------------------------------- ### Parse Account Balance from JSON Output Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md Demonstrates how to pipe the output of the 'account' command to 'jq' to extract the balance. Assumes the MT5 Bridge is running and accessible. ```bash # Parse balance from account info mt5-bridge client account | jq '.balance' # Output: 10000.00 ``` -------------------------------- ### positions Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/configuration.md Get a list of currently open positions, with optional filtering by symbols or magic number. ```APIDOC ## positions ### Description Get open positions. Can be filtered by symbols or magic number. ### Method GET ### Endpoint /client/positions ### Parameters #### Query Parameters - **--symbols** (string) - Optional - Comma-separated list of symbols (e.g., "XAUUSD,BTCUSD"). - **--magic** (integer) - Optional - Magic number to filter positions. ### Response #### Success Response (200) - **positions** (array of objects) - A list of open positions. Each object contains details like ticket, symbol, volume, open price, etc. ``` -------------------------------- ### Configure MCP Server via Environment Variable Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/README.md Set the MT5_BRIDGE_BASE_URL environment variable to configure the MCP server. Then run the MCP server script. ```bash export MT5_BRIDGE_BASE_URL=http://server:8000 python mt5_bridge/mcp_server.py ``` -------------------------------- ### Get Historical OHLCV Bars Data Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md The expected JSON output format for historical OHLCV bars. ```json [ { "time": 1704067200, "open": 2045.50, "high": 2047.00, "low": 2044.50, "close": 2046.30, "tick_volume": 1500, "spread": 2, "real_volume": 8000 } ] ``` -------------------------------- ### Get MT5 Bridge Server Health Status Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/CLI-reference.md The expected JSON output when checking the server health. ```json { "status": "ok", "mt5_connected": true } ``` -------------------------------- ### Configure MT5 Handler via Constructor Source: https://github.com/akivajp/mt5-bridge/blob/main/_autodocs/README.md Instantiate MT5Handler with server connection details. Use 'use_utc=True' to convert timestamps to UTC. ```python handler = MT5Handler( program_path="/path/to/terminal64.exe", login=12345678, password="password", server="MetaQuotes-Demo", use_utc=True # Convert to UTC ) ```