MetaTrader 5 MCP Server

repository·main·Indexed 41 days ago

https://github.com/qoyyuum/mcp-metatrader5-server

A Model Context Protocol (MCP) server version 0.1.8 that allows AI assistants to interact with the MetaTrader 5 platform. It provides standardized tools for automated trading, market data analysis, and history retrieval, including APIs for connection management, symbol discovery, OHLCV historical bar data, and order execution.

Tokens
17.9K
Snippets
39
Records
73
Agent score
51%

What's inside MetaTrader 5 MCP Server

  1. Common patterns for MT5 trading logic

    main

    Multi-Timeframe Analysis

    Retrieve market data across different timeframes (e.g., 15m, 1h, 4h, 1d) using copy_rates_from_pos to provide the agent with broader context.

    Risk Management

    Calculate position sizes by combining account balance with risk percentages and stop loss distances. Use get_symbol_info to retrieve necessary symbol data for accurate calculations.

    Monitoring Loop

    Implement a continuous loop using asyncio.sleep that periodically calls positions_get to monitor open trades and adjust stop losses or take profits.

  2. Important Usage Notes and Best Practices

    main

    When using the MetaTrader 5 MCP Server, adhere to these rules:

    • Initialization: Always call initialize() before attempting to use any other tools.
    • Authentication: You must login() to access account-specific data or execute trades.
    • Cleanup: Always use shutdown() when finished to ensure the connection to the MT5 terminal is closed properly.
    • Verification: Always check the results of order_send() to confirm if a trade was successful or failed.
    • Safety: It is highly recommended to use Demo accounts for testing your workflows before using real capital.
  3. How Pydantic AI and MT5 MCP Server integrate

    main

    The integration follows a layered architecture where the AI agent orchestrates logic by communicating through an MCP Client to the MT5 MCP Server, which in turn controls the MetaTrader 5 Terminal.

    Architecture Flow:

    1. Pydantic AI Agent: Orchestrates AI logic and tool calls.
    2. MCP Client: Communicates with the MCP server via stdio or http using the Model Context Protocol.
    3. MT5 MCP Server (FastMCP): Provides tools to interact with MetaTrader 5.
    4. MetaTrader 5 Terminal: The actual trading platform being controlled.
  4. Analyzing Price Data with Pandas and Numpy

    main

    Once market data is retrieved, it is common practice to convert the raw rates into a pandas.DataFrame for technical analysis.

    Key steps:

    1. Convert the rates list to a DataFrame.
    2. Convert the time column (which is in seconds) to a datetime object using pd.to_datetime(df['time'], unit='s').
    3. Apply technical indicators like SMA, RSI, or MACD using pandas rolling windows or custom functions.
    import pandas as pd
    import numpy as np
    
    # Convert rates to a pandas DataFrame
    df = pd.DataFrame(rates)
    
    # Convert time to datetime
    df['time'] = pd.to_datetime(df['time'], unit='s')
    
    # Calculate moving averages
    df['sma_20'] = df['close'].rolling(window=20).mean()
    df['sma_50'] = df['close'].rolling(window=50).mean()
  5. Configure for Claude Desktop

    main

    To use the server with Claude Desktop, you can use the fastmcp install command or manually edit your claude_desktop_config.json file.

    Using fastmcp

    uv run fastmcp install src/mcp_mt5/main.py

    Manual Configuration

    Add the following entry to your claude_desktop_config.json. Ensure the C:\path\to\mcp-metatrader5-server is replaced with the actual absolute path to the cloned repository.

    {
      "mcpServers": {
        "mcp-metatrader5-server": {
          "command": "uv",
          "args": [
            "--directory",
            "C:\\path\\to\\mcp-metatrader5-server",
            "run",
            "mt5mcp"
          ]
        }
      }
    }
  6. Configure MetaTrader 5 MCP Server for Claude Desktop

    main

    To use the server with Claude Desktop, add the following configuration to your claude_desktop_config.json file.

    Method 1: Using uvx (Simplest)

    This method does not require a local installation of the repository.

    {
      "mcpServers": {
        "mcp-metatrader5-server": {
          "command": "uvx",
          "args": [
            "--from",
            "git+https://github.com/Qoyyuum/mcp-metatrader5-server",
            "mt5mcp"
          ]
        }
      }
    }

    Method 2: Using FastMCP Install

    If you have cloned the repository locally, you can use fastmcp to automatically configure your environment.

    # For Claude Desktop
    uv run fastmcp install claude-desktop src/mcp_mt5/main.py
    
    # For Cursor
    uv run fastmcp install cursor src/mcp_mt5/main.py
    
    # For Claude Code
    uv run fastmcp install claude-code src/mcp_mt5/main.py
    
    # For Gemini CLI
    uv run fastmcp install gemini-cli src/mcp_mt5/main.py
  7. Best practices for MCP and Pydantic AI integration

    main

    When building integrations between Pydantic AI and the MT5 MCP server, follow these patterns:

    Error Handling

    Always check result.isError when calling MCP tools to prevent the agent from proceeding with invalid data.

    try:
        result = await session.call_tool("get_account_info", arguments={})
        if result.isError:
            print(f"Error: {result.content}")
        else:
            account_info = result.content[0].text
    except Exception as e:
        print(f"MCP call failed: {e}")

    Connection Management

    Use async with blocks for both the stdio_client and ClientSession to ensure resources are cleaned up. Always call the shutdown tool in a finally block to properly close the MT5 connection.

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            try:
                # logic
                pass
            finally:
                await session.call_tool("shutdown", arguments={})

    Type Safety and Dependency Injection

    • Structured Outputs: Use Pydantic models as the result_type for agents to ensure the AI returns data in a format your code can reliably use.
    • Dependency Injection: Pass the MCP session and other configuration (like max_risk_per_trade) into the agent using the deps parameter. This allows tools to access the active session via RunContext.
  8. Install the MetaTrader 5 MCP Server

    main

    You can install the server using uvx for a quick run without permanent installation, or by cloning the source code.

    uvx --from mcp-metatrader5-server mt5mcp

    From Source

    git clone https://github.com/Qoyyuum/mcp-metatrader5-server.git
    cd mcp-metatrader5-server
    uv sync
    uv run mt5mcp
  9. Configure Claude Desktop for MetaTrader 5 MCP

    main

    You can install the server for Claude Desktop automatically using fastmcp, or manually edit your configuration file.

    Automatic Installation

    uv run fastmcp install src/mcp_mt5/main.py

    Manual Configuration

    Add the following entry to your claude_desktop_config.json. Ensure you replace C:\path\to\mcp-metatrader5-server with the actual absolute path to the repository on your machine.

    {
      "mcpServers": {
        "mcp-metatrader5-server": {
          "command": "uv",
          "args": [
            "--directory",
            "C:\\path\\to\\mcp-metatrader5-server",
            "run",
            "mt5mcp"
          ]
        }
      }
    }
  10. Configure automatic PyPI publishing via GitHub Actions

    main

    The project is configured to automatically publish to PyPI whenever a new GitHub release is created. To enable this, you must provide a PyPI API token as a GitHub secret.

    1. Create a PyPI API token

    • Log in to pypi.org
    • Navigate to Account Settings $\rightarrow$ API tokens
    • Create a new token with the scope "Entire account (all projects)"
    • Copy the token value immediately.

    2. Add the token to GitHub secrets

    • In your GitHub repository, go to Settings $\rightarrow$ Secrets and variables $\rightarrow$ Actions.
    • Click "New repository secret".
    • Set the Name to PYPI_API_TOKEN.
    • Paste your token into the Value field and click "Add secret".
  11. Trigger a PyPI release via GitHub

    main

    To trigger the automatic publishing workflow, create a new release in the GitHub repository:

    1. Navigate to the Releases section of your GitHub repository.
    2. Click "Create a new release".
    3. Select a tag version (e.g., v0.1.3).
    4. Provide a title and description.
    5. Click "Publish release".

    The GitHub Actions workflow will then automatically build and upload the package to PyPI.

  12. Install Pydantic AI and MCP MetaTrader 5 Server

    main

    To integrate MetaTrader 5 with Pydantic AI, you must install both the agent framework and the MCP server. You can install Pydantic AI with specific model support (OpenAI, Anthropic, or Gemini) using extras.

    Prerequisites

    • Python 3.11 or higher
    • MetaTrader 5 terminal installed on Windows
    • MCP MetaTrader 5 Server installed
    • Pydantic AI installed
    # Install Pydantic AI
    pip install pydantic-ai
    
    # Or with specific model support
    pip install 'pydantic-ai[openai]'  # For OpenAI
    pip install 'pydantic-ai[anthropic]'  # For Anthropic Claude
    pip install 'pydantic-ai[gemini]'  # For Google Gemini
    
    # Install the MCP MetaTrader 5 Server
    pip install mcp-metatrader5-server
    
    # Or install from source
    git clone https://github.com/Qoyyuum/mcp-metatrader5-server
    cd mcp-metatrader5-server
    uv sync