MetaTrader MCP Server

repository·main·Indexed 20 days ago

https://github.com/ariadng/metatrader-mcp-server

A Model Context Protocol (MCP) server built with Python (v0.5.1) that connects AI assistants like Claude and ChatGPT to the MetaTrader 5 trading platform. It provides a unified Python interface via the MT5Client class for account, market, order, and history management, alongside a WebSocket Quote Server for real-time tick data and an HTTP REST API for programmatic trading operations.

Tokens
30.9K
Snippets
92
Records
150
Agent score
70%

What's inside metatrader-mcp-server

  1. Overview of MetaTrader MCP Server modules

    main

    The project is split into two primary functional areas:

    Client Module

    Provides a unified Python interface via the MT5Client class for MetaTrader 5 automation. It is used for direct programmatic control, including account info, market data, trading/order management, and historical data.

    Server Module

    Implements the Model Context Protocol (MCP) using the FastMCP SDK. This module exposes trading operations as tools that AI assistants (like Claude Desktop) can call.

    Current MCP Tools:

    • get_balance: Returns the account balance (currently returns demo/random values).
  2. Use MT5Client submodules for trading operations

    main

    The MT5Client object exposes specialized submodules to handle different domains of MetaTrader 5 operations:

    • client.account: Manage account info and status (balance, equity, margin).
    • client.market: Access market data (symbols, prices, candles).
    • client.order: Handle trading and order management (positions, orders).
    • client.history: Retrieve historical deals, orders, and statistics.
    • client.connection: Manage terminal connection settings.
  3. Workflow: How to place a Market Order with Stop Loss and Take Profit

    main

    The place_market_order tool does not accept stop_loss or take_profit parameters directly. To execute a market order with protection, follow this two-step workflow:

    1. Execute Order: Call place_market_order with the required symbol, volume, and type (BUY/SELL).
    2. Extract ID: From the returned trade result, extract the position ID from data.order or data.deal.
    3. Modify Position: Call modify_position using that position ID to set the desired stop_loss and take_profit values.
  4. Use the MT5History class to analyze historical data

    main

    The MT5History class provides a high-level Pythonic interface for retrieving and analyzing historical account activity (deals, orders, and statistics) from MetaTrader 5. It wraps the MetaTrader5 Python API and supports exporting data directly to pandas DataFrames for analysis.

    Dependencies:

    • MetaTrader5 Python package
    • pandas

    Core Methods:

    • get_deals(...): Retrieve historical deals as a list of dictionaries.
    • get_orders(...): Retrieve historical orders as a list of dictionaries.
    • get_total_deals(...): Get the total number of deals in a specific period.
    • get_total_orders(...): Get the total number of orders in a specific period.
    • get_deals_as_dataframe(...): Get deals as a pandas.DataFrame.
    • get_orders_as_dataframe(...): Get orders as a pandas.DataFrame.

    All methods support filtering by parameters such as date, group, and ticket.

    from metatrader_client.client_history import MT5History
    
    # history is an instance of MT5History initialized with an active MT5Connection
    deals = history.get_deals(from_date=datetime.now() - timedelta(days=7))
    df = history.get_deals_as_dataframe(from_date=datetime.now() - timedelta(days=30))
  5. MetaTrader 5 Domain Knowledge: Timeframes and Order Types

    main

    When using the trading tools, adhere to the following domain constraints:

    Valid Timeframes

    Use these exact strings for the timeframe parameter: M1, M2, M3, M4, M5, M6, M10, M12, M15, M20, M30, H1, H2, H3, H4, H6, H8, H12, D1, W1, MN1.

    Order Types

    • Market Orders: Use BUY or SELL in the type parameter for place_market_order.
    • Pending Orders: Use BUY or SELL in the type parameter for place_pending_order. The server automatically determines the specific type (e.g., BUY_LIMIT, SELL_STOP) based on the relationship between the current market price and your specified price.

    Symbol and Volume

    • Symbols: Formats are broker-dependent (e.g., EURUSD, EURUSD.m). Always verify the exact name using get_symbols before trading.
    • Volume: Expressed in lots. Minimum is typically 0.01 (broker-dependent).
  6. Configure Claude Desktop (Local STDIO)

    main

    To use the server with Claude Desktop via local standard input/output (STDIO), add the following configuration to your claude_desktop_config.json file.

    Config Locations:

    • Windows: %APPDATA%\Claude\claude_desktop_config.json
    • Mac: ~/Library/Application Support/Claude/claude_desktop_config.json

    Configuration Template: Replace YOUR_MT5_LOGIN, YOUR_MT5_PASSWORD, and YOUR_MT5_SERVER with your actual credentials. If your MT5 terminal is in a non-standard location, include the --path argument.

    {
      "mcpServers": {
        "metatrader": {
          "command": "metatrader-mcp-server",
          "args": [
            "--login",     "YOUR_MT5_LOGIN",
            "--password",  "YOUR_MT5_PASSWORD",
            "--server",    "YOUR_MT5_SERVER",
            "--transport", "stdio",
            "--path",      "C:\\Program Files\\MetaTrader 5\\terminal64.exe"
          ]
        }
      }
    }
  7. Install the MetaTrader MCP Server

    main

    Install the package using pip to enable the bridge between AI assistants and MetaTrader 5.

    Prerequisites:

    • Python 3.10 or higher
    • MetaTrader 5 terminal installed
    • MT5 Trading Account credentials (Login, Password, and Server name)
    pip install metatrader-mcp-server
  8. Initialize MT5History with an active connection

    main

    To use MT5History, you must first establish an active connection using MT5Connection. You pass the connection instance into the MT5History constructor.

    from metatrader_client.client_connection import MT5Connection
    from metatrader_client.client_history import MT5History
    
    conn = MT5Connection(config)
    if conn.connect():
        history = MT5History(conn)
  9. Set up the Development Environment

    main

    To develop on this project, clone the repository and install the package in editable mode.

    # 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/
  10. Configure Remote MCP Server (SSE)

    main

    To run the MCP server on a remote Windows VPS and connect to it from a local Claude Desktop or Claude Code instance, use the Server-Sent Events (SSE) transport.

    1. Server-side (on the Windows VPS): Start the server. It defaults to 0.0.0.0:8080. You can customize the host and port using --host and --port.

    metatrader-mcp-server --login YOUR_LOGIN --password YOUR_PASSWORD --server YOUR_SERVER

    2. Client-side (Local Claude Desktop config): Add the remote URL to your claude_desktop_config.json:

    {
      "mcpServers": {
        "metatrader": {
          "url": "http://VPS_IP:8080/sse"
        }
      }
    }

    ⚠️ Security Warning: The MCP protocol does not include authentication. When exposing the SSE server over a network, use a firewall to restrict access by IP, use a reverse proxy with authentication, or use an SSH tunnel.

  11. Enable Algorithmic Trading in MetaTrader 5

    main

    For the MCP server to execute trades, you must enable algorithmic trading within the MetaTrader 5 terminal:

    1. Open MetaTrader 5.
    2. Navigate to ToolsOptions.
    3. Select the Expert Advisors tab.
    4. Check the box for Allow algorithmic trading.
    5. Click OK.
  12. How to use MetaTrader tools with Claude Desktop

    main

    Once the server is installed in Claude Desktop, you can interact with MetaTrader using natural language.

    1. Open Claude Desktop.
    2. Start a new conversation.
    3. Ask Claude to perform trading tasks or retrieve information, such as: "What's my account balance?"