### Quick Installation of MT5 MCP Server Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/getting_started.md This snippet shows the commands to quickly clone the repository and install dependencies using 'uv'. This is the fastest way to get the server up and running. ```bash git clone https://github.com/Qoyyuum/mcp-metatrader5-server cd mcp-metatrader5-server uv sync ``` -------------------------------- ### Install MCP Server from PyPI using uvx Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Installs the mcp-metatrader5-server package using uvx for quick execution. This is a convenient way to get the server running without a full local installation. ```bash uvx --from mcp-metatrader5-server mt5mcp ``` -------------------------------- ### Python Example: Connect and Get Market Data Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md A Python script demonstrating how to initialize the MT5 connection, log in to a trading account, and retrieve a list of available trading symbols using the mcp-metatrader5-server library. ```python # Initialize MT5 initialize() # Log in to your trading account login(account=123456, password="your_password", server="your_server") # Get available symbols symbols = get_symbols() ``` -------------------------------- ### Install MetaTrader 5 MCP Server Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/index.md Methods to install the server either from the source repository using uv or via the PyPI package manager. ```bash git clone https://github.com/Qoyyuum/mcp-metatrader5-server.git cd mcp-metatrader5-server uv sync ``` ```bash uv pip install mcp-metatrader5-server ``` -------------------------------- ### Place a Buy Order in MT5 Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/getting_started.md This example demonstrates how to place a buy order. It involves getting the current ask price, constructing an order request with specified parameters (volume, stop loss, take profit, deviation), and sending the order using the `order_send` tool. The `order_filling_types` constant `ORDER_FILLING_IOC` is used for immediate or cancel execution. ```python # Get current ask price for EURUSD current_ask_price = get_symbol_info_tick("EURUSD")['ask'] # Define order request parameters request = { "action": TRADE_ACTION_DEAL, # 0 "symbol": "EURUSD", "volume": 0.1, "type": ORDER_TYPE_BUY, # 0 "price": current_ask_price, "sl": 1.0950, "tp": 1.1050, "deviation": 20, "type_filling": ORDER_FILLING_IOC # 2 } # Send the order order_send(request) ``` -------------------------------- ### Install MCP Server from Source using uv sync Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Clones the repository and installs dependencies using uv sync, then runs the server. This method is suitable for development or when needing the latest code directly from the repository. ```bash git clone https://github.com/Qoyyuum/mcp-metatrader5-server.git cd mcp-metatrader5-server uv sync uv run mt5mcp ``` -------------------------------- ### Troubleshoot MCP Server Startup (Bash) Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md Provides a command-line instruction to verify the installation and basic functionality of the MCP MetaTrader 5 server. It uses `uvx` to run the `mt5mcp` command with the `--help` flag, which should display usage information if the server is correctly installed and accessible. ```bash uvx --from mcp-metatrader5-server mt5mcp --help ``` -------------------------------- ### Install Project Dependencies with uv Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md Installs all project dependencies, including development and documentation extras, using the 'uv' package manager. This command ensures all necessary libraries are available for development. ```bash uv sync --all-extras ``` -------------------------------- ### Example Unit Test Structure Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/tests/README.md Demonstrates the structure of a unit test using 'pytest' and 'unittest.mock'. It includes the use of the '@pytest.mark.unit' decorator, setup (Arrange), action (Act), and assertion (Assert) phases. ```python import pytest from unittest.mock import patch @pytest.mark.unit def test_my_function(): """Test description.""" # Arrange expected = "result" # Act result = my_function() # Assert assert result == expected ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md Copies the example environment file to be used for local configuration. Users should then edit the '.env' file with their specific MetaTrader 5 (MT5) configuration details. ```bash # Copy the example environment file cp .env.example .env # Edit .env with your MT5 configuration ``` -------------------------------- ### Install MCP Server for Clients using fastmcp Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Installs the MetaTrader 5 MCP server for various AI clients using the fastmcp command. This simplifies the integration process for different platforms like Claude Desktop, Cursor, and Gemini CLI. ```bash git clone https://github.com/Qoyyuum/mcp-metatrader5-server cd mcp-metatrader5-server uv run fastmcp install mcp-json src/mcp_mt5/main.py uv run fastmcp install claude-desktop src/mcp_mt5/main.py uv run fastmcp install claude-code src/mcp_mt5/main.py uv run fastmcp install cursor src/mcp_mt5/main.py uv run fastmcp install gemini-cli src/mcp_mt5/main.py ``` -------------------------------- ### Python Unit Test Example Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md An example of a unit test written in Python using pytest and the 'fastmcp' library. It demonstrates how to instantiate a client, call a tool, and assert the result. ```python import pytest from fastmcp import Client from mcp_mt5.main import mcp @pytest.mark.unit async def test_my_feature(): """Test description.""" async with Client(mcp) as client: result = await client.call_tool("my_tool", {"param": "value"}) assert result.data == expected_value ``` -------------------------------- ### Install dependencies for MT5 MCP and Pydantic AI Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md Commands to install the necessary Python packages and the MCP MetaTrader 5 server using pip or uv. ```bash pip install pydantic-ai pip install 'pydantic-ai[openai]' pip install 'pydantic-ai[anthropic]' pip install 'pydantic-ai[gemini]' pip install mcp-metatrader5-server git clone https://github.com/Qoyyuum/mcp-metatrader5-server cd mcp-metatrader5-server uv sync ``` -------------------------------- ### Install Test Dependencies with uv Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/tests/README.md Installs development dependencies required for testing the MCP MetaTrader 5 Server using the 'uv' package manager. This command ensures all necessary libraries for running tests are available. ```bash uv sync --extra dev ``` -------------------------------- ### Get Recent Price Data for EURUSD (Python) Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Retrieves the most recent price data for a specified currency pair and timeframe. It uses the `copy_rates_from_pos` function, which requires the symbol, timeframe, starting position, and the number of data points to fetch. The connection is then shut down. ```python # Get recent price data for EURUSD rates = copy_rates_from_pos(symbol="EURUSD", timeframe=15, start_pos=0, count=100) # Shut down the connection shutdown() ``` -------------------------------- ### Configure Claude Desktop for MCP Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/index.md Instructions for integrating the server with Claude Desktop, either via CLI installation or manual configuration file updates. ```bash uv run fastmcp install src/mcp_mt5/main.py ``` ```json { "mcpServers": { "mcp-metatrader5-server": { "command": "uv", "args": [ "--directory", "C:\\path\\to\\mcp-metatrader5-server", "run", "mt5mcp" ] } } } ``` -------------------------------- ### Run MCP Server in stdio mode Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Starts the MetaTrader 5 MCP server in standard input/output mode, which is the default and suitable for MCP clients like Claude Desktop. ```bash uv run mt5mcp ``` -------------------------------- ### Configure and Run MCP Server in HTTP Development Mode Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Sets up the server to run in HTTP development mode by creating a .env file with transport and host/port configurations, then starting the server using uv run. ```env MT5_MCP_TRANSPORT=http MT5_MCP_HOST=127.0.0.1 MT5_MCP_PORT=8000 ``` ```bash uv run mt5mcp ``` -------------------------------- ### Get MT5 Version Information Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Returns the version and build information for the MetaTrader 5 terminal. ```python # Get MT5 version version = get_version() # Returns: # { # "version": 500, # "build": 3950, # "date": "01 Jan 2024" # } ``` -------------------------------- ### Manual Package Upload to PyPI using uv Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/publishing.md This snippet demonstrates how to manually build and publish a Python package to PyPI using the 'uv' tool. It first shows how to install 'uv' and then proceeds with building and publishing the package. Ensure you have a PyPI token ready for the '--password' argument. ```bash # Install uv if you don't have it already curl -LsSf https://astral.sh/uv/install.sh | sh # Build the package uv build # Upload to PyPI uv publish --username __token__ --password YOUR_PYPI_TOKEN ``` -------------------------------- ### Manual Package Upload to PyPI using Python build and twine Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/publishing.md This snippet shows the standard Python method for manually building and publishing a package to PyPI. It utilizes the 'build' module to create the distribution files and 'twine' to upload them. Ensure you have 'build' and 'twine' installed and your PyPI credentials configured or provided. ```bash # Build the package python -m build # Upload to PyPI python -m twine upload dist/* ``` -------------------------------- ### Example Integration Test for MT5 Connection Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/tests/README.md Illustrates an integration test for establishing an MT5 connection using 'pytest'. This test requires a running MT5 terminal and uses the 'initialize' function, marked with '@pytest.mark.integration'. ```python import pytest @pytest.mark.integration def test_mt5_connection(): """Test actual MT5 connection.""" # This test requires MT5 to be running result = initialize(path="C:\\Program Files\\MetaTrader 5\\terminal64.exe") assert result is True ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md Examples of Git commit messages following the Conventional Commits specification. This standard helps in automating changelog generation and semantic versioning. ```bash git commit -m "feat: add support for custom timeframes" git commit -m "fix: handle MT5 connection timeout" git commit -m "docs: update installation instructions" git commit -m "test: add tests for order validation" ``` -------------------------------- ### Run Unit Tests with pytest Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md Executes unit tests using pytest, filtered by the 'unit' marker. This command is used to verify the development setup and ensure basic functionality is working correctly. ```bash uv run pytest -m unit ``` -------------------------------- ### Analyze Market Data with Pandas and NumPy Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/market_data_guide.md Demonstrates how to transform raw market data into a pandas DataFrame and perform technical analysis, including SMA, RSI, and MACD calculations. ```python 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() # Calculate RSI def calculate_rsi(series, period=14): delta = series.diff() gain = delta.where(delta > 0, 0).rolling(window=period).mean() loss = -delta.where(delta < 0, 0).rolling(window=period).mean() rs = gain / loss return 100 - (100 / (1 + rs)) df['rsi'] = calculate_rsi(df['close']) # Calculate MACD def calculate_macd(series, fast=12, slow=26, signal=9): ema_fast = series.ewm(span=fast, adjust=False).mean() ema_slow = series.ewm(span=slow, adjust=False).mean() macd = ema_fast - ema_slow signal_line = macd.ewm(span=signal, adjust=False).mean() histogram = macd - signal_line return macd, signal_line, histogram df['macd'], df['signal'], df['histogram'] = calculate_macd(df['close']) ``` -------------------------------- ### Get MT5 Account Information Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves comprehensive information about the currently logged-in trading account, including balance, equity, margin, and leverage. ```python # Get account information account = get_account_info() # Returns AccountInfo with fields: # { # "login": 12345678, # "balance": 10000.00, # "equity": 10250.50, # "margin": 500.00, # "margin_free": 9750.50, # "margin_level": 2050.10, # "profit": 250.50, # "leverage": 100, # "currency": "USD", # "name": "John Doe", # "server": "YourBroker-Demo", # "company": "Your Broker Ltd" # } ``` -------------------------------- ### Troubleshoot MT5 Connection (Python) Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md Attempts to initialize a connection to the MetaTrader 5 terminal by trying common installation paths for `terminal64.exe`. It iterates through a list of predefined paths and uses the `initialize` tool, breaking the loop once a successful connection is established. ```python # Try different common paths paths = [ r"C:\\Program Files\\MetaTrader 5\\terminal64.exe", r"C:\\Program Files (x86)\\MetaTrader 5\\terminal64.exe", ] for path in paths: result = await session.call_tool("initialize", arguments={"path": path}) if not result.isError: break ``` -------------------------------- ### Get All Trading Symbols Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves a list of all available trading symbols (financial instruments) from the MetaTrader 5 terminal. ```python # Get all available symbols symbols = get_symbols() # Returns list of symbol names: # ["EURUSD", "GBPUSD", "USDJPY", "XAUUSD", "BTCUSD", ...] ``` -------------------------------- ### Manage MCP Session Lifecycle Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md Illustrates proper management of the MCP session, ensuring it is initialized at the start and always shut down, even if errors occur. This pattern uses nested 'async with' statements for the client and session, with a 'finally' block for cleanup. ```python async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: # Initialize at start await session.initialize() try: # Your trading logic here pass finally: # Always shutdown MT5 await session.call_tool("shutdown", arguments={}) ``` -------------------------------- ### Place Market Buy Order using MetaTrader 5 API Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/trading_guide.md Demonstrates how to place a market buy order using the MetaTrader 5 API. It utilizes the OrderRequest object to define order parameters like symbol, volume, and type, then sends the request via the order_send function. Requires the mt5_server library and access to current tick data. ```python from mt5_server import OrderRequest # Create an order request request = OrderRequest( action=mt5.TRADE_ACTION_DEAL, symbol="EURUSD", volume=0.1, type=mt5.ORDER_TYPE_BUY, price=mt5.symbol_info_tick("EURUSD").ask, deviation=20, magic=123456, comment="Buy order", type_time=mt5.ORDER_TIME_GTC, type_filling=mt5.ORDER_FILLING_IOC ) # Send the order result = order_send(request) ``` -------------------------------- ### Place Pending Buy Limit Order using MetaTrader 5 API Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/trading_guide.md Illustrates how to place a pending buy limit order with the MetaTrader 5 API. This involves creating an OrderRequest with specific parameters for pending orders, including the desired price, stop loss, and take profit levels. The order is then submitted using the order_send function. ```python from mt5_server import OrderRequest # Create a pending order request request = OrderRequest( action=mt5.TRADE_ACTION_PENDING, symbol="EURUSD", volume=0.1, type=mt5.ORDER_TYPE_BUY_LIMIT, price=1.08, # Price to buy at sl=1.07, # Stop loss tp=1.09, # Take profit deviation=20, magic=123456, comment="Buy limit order", type_time=mt5.ORDER_TIME_GTC, type_filling=mt5.ORDER_FILLING_IOC ) # Send the order result = order_send(request) ``` -------------------------------- ### Close Position using MetaTrader 5 API Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/trading_guide.md Provides an example of how to close an existing trading position via the MetaTrader 5 API. It involves fetching the position details, constructing an OrderRequest with the appropriate closing action (TRADE_ACTION_DEAL) and opposite order type, and then sending the request to close the position. ```python from mt5_server import OrderRequest # Get the position position = positions_get_by_ticket(ticket=123456) # Create a request to close the position request = OrderRequest( action=mt5.TRADE_ACTION_DEAL, symbol=position.symbol, volume=position.volume, type=mt5.ORDER_TYPE_SELL if position.type == mt5.ORDER_TYPE_BUY else mt5.ORDER_TYPE_BUY, price=mt5.symbol_info_tick(position.symbol).bid if position.type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(position.symbol).ask, position=position.ticket, deviation=20, magic=123456, comment="Close position", type_time=mt5.ORDER_TIME_GTC, type_filling=mt5.ORDER_FILLING_IOC ) # Send the order result = order_send(request) ``` -------------------------------- ### Publish Package to PyPI with uv (Bash) Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Commands for publishing the Python package to the Python Package Index (PyPI) using `uv`. It first requires building the package, then uses `uv publish` to upload the distributions. An option to publish to TestPyPI first is also provided for testing. ```bash # Build first uv build # Publish to PyPI uv publish # Or publish to TestPyPI first uv publish --publish-url https://test.pypi.org/legacy/ ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md This snippet shows how to clone the project repository and navigate into the project directory using Git. It's the first step in setting up the development environment. ```bash git clone https://github.com/YOUR_USERNAME/mcp-metatrader5-server.git cd mcp-metatrader5-server ``` -------------------------------- ### Build Package with uv (Bash) Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Instructions for building the Python package using the `uv` build tool. This command generates wheel and source distributions of the package, which are typically placed in the `dist/` directory. ```bash uv build ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md Builds and serves the project's documentation locally using MkDocs. This allows developers to preview documentation changes before deploying them. ```bash uv run mkdocs serve # Visit http://127.0.0.1:8000 ``` -------------------------------- ### Retrieve Historical Bars from Date (Python) Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves historical OHLCV bar data starting from a specific date. Requires the datetime module for specifying the start date. Returns a list of bar dictionaries. ```python from datetime import datetime # Get 100 bars starting from a specific date rates = copy_rates_from_date( symbol="EURUSD", timeframe=60, # H1 timeframe date_from=datetime(2024, 1, 15, 0, 0), count=100 ) # Returns list of bars with same structure as copy_rates_from_pos ``` -------------------------------- ### Initialize MT5 Connection and Login Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/getting_started.md These are the initial steps to establish a connection with the MetaTrader 5 terminal and log in to a trading account. The `initialize` tool requires the path to the MT5 terminal executable, and the `login` tool requires account credentials and server information. ```python # Initialize the MT5 terminal initialize(path="C:\\Program Files\\MetaTrader 5\\terminal64.exe") # Log in to your trading account login(login=123456, password="your_password", server="your_server") ``` -------------------------------- ### Get Specific Symbol Information Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves detailed information about a specific trading symbol, including its pricing, trading conditions, and contract specifications. ```python # Get detailed symbol information info = get_symbol_info(symbol="EURUSD") # Returns SymbolInfo with fields: # { # "name": "EURUSD", # "description": "Euro vs US Dollar", # "path": "Forex\\EURUSD", # "bid": 1.08521, # "ask": 1.08523, # "spread": 2, # "digits": 5, # "point": 0.00001, # "volume_min": 0.01, # "volume_max": 100.0, # "volume_step": 0.01, # "contract_size": 100000.0, # "tick_value": 1.0, # "tick_size": 0.00001, # "swap_long": -0.5, # } ``` -------------------------------- ### Place a Buy Trade Order (Python) Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Demonstrates how to place a buy trade order using the MetaTrader 5 API. This involves initializing and logging into the MT5 account, creating an `OrderRequest` object with trade parameters, sending the order, and finally shutting down the connection. It utilizes various constants from the `mt5` library for order configuration. ```python # Initialize and log in initialize() login(account=123456, password="your_password", server="your_server") # Create an order request request = OrderRequest( action=mt5.TRADE_ACTION_DEAL, symbol="EURUSD", volume=0.1, type=mt5.ORDER_TYPE_BUY, price=mt5.symbol_info_tick("EURUSD").ask, deviation=20, magic=123456, comment="Buy order", type_time=mt5.ORDER_TIME_GTC, type_filling=mt5.ORDER_FILLING_IOC ) # Send the order result = order_send(request) # Shut down the connection shutdown() ``` -------------------------------- ### Get MT5 Terminal Information Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Returns information about the MetaTrader 5 terminal, including its build number, file paths, and connection status. ```python # Get terminal information terminal = get_terminal_info() # Returns dict with terminal details: # { # "community_account": False, # "community_connection": False, # "connected": True, # "dlls_allowed": False, # "trade_allowed": True, # "tradeapi_disabled": False, # "email_enabled": False, # "ftp_enabled": False, # "notifications_enabled": False, # "mqid": False, # "build": 3950, # "maxbars": 100000, # "codepage": 0, # "ping_last": 42, # "company": "Your Broker", # "name": "MetaTrader 5", # "language": "English", # "path": "C:\\Program Files\\MetaTrader 5", # "data_path": "C:\\Users\\User\\AppData\\Roaming\\MetaQuotes\\Terminal\\...", # "commondata_path": "C:\\Users\\User\\AppData\\Roaming\\MetaQuotes\\Terminal\\Common" # } ``` -------------------------------- ### Configure Claude Desktop for MCP Server using uvx Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Adds configuration to Claude Desktop's settings to use the mcp-metatrader5-server via uvx. This allows Claude Desktop to automatically fetch and run the server when needed. ```json { "mcpServers": { "mcp-metatrader5-server": { "command": "uvx", "args": [ "--from", "git+https://github.com/Qoyyuum/mcp-metatrader5-server", "mt5mcp" ] } } } ``` -------------------------------- ### Manual Configuration for MCP Server in LLM Config Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/README.md Provides a manual configuration snippet for LLM client configuration files, such as `claude_desktop_config.json`, to specify the command and arguments for running the mcp-metatrader5-server. ```json { "mcpServers": { "mcp-metatrader5-server": { "command": "uvx", "args": [ "--from", "mcp-metatrader5-server", "mt5mcp" ] } } } ``` -------------------------------- ### Query Symbol Information Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/market_data_guide.md Methods to retrieve available trading symbols, filter symbols by group, and fetch detailed specifications or current tick data for a specific instrument. ```python # Get all available symbols symbols = get_symbols() # Get symbols by group forex_symbols = get_symbols_by_group("*USD*") # Get information about a specific symbol symbol_info = get_symbol_info("EURUSD") # Get the latest tick for a symbol tick = get_symbol_info_tick("EURUSD") ``` -------------------------------- ### Retrieve Historical Ticks from Date (Python) Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves tick data starting from a specific date. Requires the datetime module and allows filtering by flags. Returns a list of tick dictionaries. ```python from datetime import datetime # Get 500 ticks from a specific date ticks = copy_ticks_from_date( symbol="EURUSD", date_from=datetime(2024, 1, 22, 10, 0), count=500, flags=0 ) ``` -------------------------------- ### Run MetaTrader 5 MCP Server Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/index.md Commands to execute the server in Stdio mode for local clients or HTTP mode for development environments. ```bash uv run mt5mcp ``` ```env MT5_MCP_TRANSPORT=http MT5_MCP_HOST=127.0.0.1 MT5_MCP_PORT=8000 ``` -------------------------------- ### Run All Tests with pytest Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/tests/README.md Executes all unit and integration tests defined in the project using the 'pytest' framework, managed by 'uv'. This provides a comprehensive check of the server's functionality. ```bash uv run pytest ``` -------------------------------- ### Initialize MT5 MCP Session with Pydantic AI Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md A basic implementation showing how to connect to the MT5 MCP server via stdio and initialize the connection within a Pydantic AI agent workflow. ```python import asyncio from datetime import datetime from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIModel from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client model = OpenAIModel('gpt-4o', api_key='your-api-key-here') agent = Agent( model, system_prompt="You are a trading assistant with access to MetaTrader 5. You can help analyze markets, retrieve data, and execute trades safely." ) async def use_mt5_with_pydantic_ai(): server_params = StdioServerParameters( command="uvx", args=["--from", "mcp-metatrader5-server", "mt5mcp"] ) async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() tools_result = await session.list_tools() init_result = await session.call_tool( "initialize", arguments={"path": r"C:\Program Files\MetaTrader 5\terminal64.exe"} ) result = await agent.run( "Get my account information and summarize the balance and equity.", message_history=[] ) print(f"Agent response: {result.data}") asyncio.run(use_mt5_with_pydantic_ai()) ``` -------------------------------- ### Get Trading Symbols by Group Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves trading symbols that match a specific group pattern using wildcard filtering. This allows for fetching symbols based on categories like currency pairs or commodities. ```python # Get symbols by group pattern eur_symbols = get_symbols_by_group(group="EUR*") # Returns: ["EURUSD", "EURJPY", "EURGBP", "EURCAD", ...] forex_symbols = get_symbols_by_group(group="*USD*") # Returns: ["EURUSD", "GBPUSD", "USDJPY", "AUDUSD", ...] all_symbols = get_symbols_by_group(group="*") # Returns all symbols ``` -------------------------------- ### Troubleshoot Tool Call Failures (Python) Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md Lists all available tools and their details, including name, description, and input schema. This is useful for debugging issues with tool calls by verifying that the intended tool exists and understanding its required parameters. ```python # List all available tools tools = await session.list_tools() for tool in tools.tools: print(f"Tool: {tool.name}") print(f"Description: {tool.description}") print(f"Parameters: {tool.inputSchema}") ``` -------------------------------- ### Retrieve Historical Ticks from Position (Python) Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves tick data starting from a specific time. Allows filtering ticks by flags (ALL, INFO, TRADE). Requires the datetime module. Returns a list of tick dictionaries. ```python from datetime import datetime # Get 1000 ticks starting from a specific time ticks = copy_ticks_from_pos( symbol="EURUSD", start_time=datetime(2024, 1, 22, 10, 0), count=1000, flags=0 # 0=ALL, 1=INFO (bid/ask changes), 2=TRADE (last/volume changes) ) # Returns list of ticks: # [ # { # "time": "2024-01-22T10:00:00Z", # "time_msc": "2024-01-22T10:00:00.123Z", # "bid": 1.08521, # "ask": 1.08523, # "last": 0.0, # "volume": 0, # "flags": 6 # }, # ... # ] ``` -------------------------------- ### Format Code with Ruff Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md Automatically formats the code in the 'src/' and 'tests/' directories according to project style guidelines using Ruff. This ensures consistent code style across the project. ```bash uvx ruff format src/ tests/ ``` -------------------------------- ### Retrieve Historical Bars from Position (Python) Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves historical OHLCV bar data starting from a specific position (0 represents the most recent bar). Supports various timeframes. Returns a list of bar dictionaries. ```python # Get last 100 bars on 15-minute timeframe rates = copy_rates_from_pos( symbol="EURUSD", timeframe=15, # Minutes: 1, 5, 15, 30, 60, 240, 1440, 10080, 43200 start_pos=0, # 0 = most recent bar count=100 ) # Returns list of bars with ISO 8601 timestamps: # [ # { # "time": "2024-01-22T10:00:00Z", # "open": 1.08500, # "high": 1.08550, # "low": 1.08480, # "close": 1.08520, # "tick_volume": 1234, # "spread": 2, # "real_volume": 0 # }, # ... # ] # Timeframe values (in minutes): # 1=M1, 5=M5, 15=M15, 30=M30, 60=H1, 240=H4 # 1440=D1, 10080=W1, 43200=MN1 ``` -------------------------------- ### Execute Market and Pending Orders Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Demonstrates how to place market sell orders and pending buy limit orders using the order_send function. It highlights the required dictionary structure for request parameters. ```python result = order_send(request={ "action": 1, "symbol": "EURUSD", "volume": 0.1, "type": 1, "price": 1.08518, "sl": 1.08718, "tp": 1.08118 }) result = order_send(request={ "action": 2, "symbol": "EURUSD", "volume": 0.1, "type": 2, "price": 1.08000, "sl": 1.07800, "tp": 1.08400 }) ``` -------------------------------- ### Query Market Data and Symbol Information Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/api_reference.md Functions to list available financial instruments, retrieve detailed symbol specifications, and get the latest tick data. Useful for market analysis and instrument discovery. ```python symbols = get_symbols() symbol_info = get_symbol_info("EURUSD") tick_data = get_symbol_info_tick("EURUSD") ``` -------------------------------- ### Retrieve Historical Price Data with MetaTrader 5 Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/market_data_guide.md Functions to fetch historical candlestick bars and tick data using various time-based criteria. These methods require a valid connection to the MetaTrader 5 terminal. ```python # Get the last 100 bars for EURUSD on the H1 timeframe rates = copy_rates_from_pos(symbol="EURUSD", timeframe=60, start_pos=0, count=100) # Get bars for EURUSD on the D1 timeframe from a specific date from datetime import datetime rates = copy_rates_from_date( symbol="EURUSD", timeframe=1440, date_from=datetime(2023, 1, 1), count=100 ) # Get bars for EURUSD on the M15 timeframe within a date range rates = copy_rates_range( symbol="EURUSD", timeframe=15, date_from=datetime(2023, 1, 1), date_to=datetime(2023, 1, 31) ) ``` ```python # Get the last 1000 ticks for EURUSD ticks = copy_ticks_from_pos(symbol="EURUSD", start_pos=0, count=1000) # Get ticks for EURUSD from a specific date ticks = copy_ticks_from_date( symbol="EURUSD", date_from=datetime(2023, 1, 1), count=1000 ) # Get ticks for EURUSD within a date range ticks = copy_ticks_range( symbol="EURUSD", date_from=datetime(2023, 1, 1), date_to=datetime(2023, 1, 2) ) ``` -------------------------------- ### Retrieve Historical Ticks by Date Range (Python) Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves tick data within a specified date range. Requires the datetime module for start and end dates, and allows filtering by flags. Returns a list of tick dictionaries. ```python from datetime import datetime # Get all ticks within a time range ticks = copy_ticks_range( symbol="EURUSD", date_from=datetime(2024, 1, 22, 10, 0), date_to=datetime(2024, 1, 22, 10, 30), flags=0 ) ``` -------------------------------- ### Retrieve Account and Terminal Information Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/api_reference.md Tools to fetch current account statistics, terminal configuration, and version details. Returns structured data objects containing balance, equity, and build information. ```python account = get_account_info() terminal = get_terminal_info() version = get_version() ``` -------------------------------- ### Retrieve Historical Bars by Date Range (Python) Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Retrieves OHLCV bar data within a specified date range. Requires the datetime module for specifying start and end dates. Returns all bars within the given period. ```python from datetime import datetime # Get all bars between two dates rates = copy_rates_range( symbol="EURUSD", timeframe=1440, # D1 timeframe date_from=datetime(2024, 1, 1), date_to=datetime(2024, 1, 31) ) # Returns all daily bars for January 2024 ``` -------------------------------- ### Initialize and Authenticate MT5 Connection Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/api_reference.md Functions to establish a connection with the MetaTrader 5 terminal and authenticate a trading account. Requires the path to the terminal executable and valid account credentials. ```python initialize(path="C:\\Program Files\\MetaTrader 5\\terminal64.exe") login(login=123456, password="your_password", server="YourBroker-Demo") ``` -------------------------------- ### Run Specific Test Files with pytest Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/tests/README.md Allows running specific test files using 'pytest' via 'uv'. This is useful for isolating and testing particular modules like timeframes, connection management, account info, or Pydantic models. ```bash # Test timeframe validation uv run pytest tests/test_timeframes.py # Test connection management uv run pytest tests/test_connection.py # Test account info uv run pytest tests/test_account_info.py # Test Pydantic models uv run pytest tests/test_models.py ``` -------------------------------- ### Main Function to Run Trading Bot Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md The main entry point for the trading bot application. It initializes the 'TradingBot' with necessary API keys and MT5 path, then calls the 'run' method with trading symbols, login credentials, and server details. It uses 'asyncio.run' to execute the asynchronous main function. ```python async def main(): bot = TradingBot( api_key="your-anthropic-api-key", mt5_path=r"C:\\Program Files\\MetaTrader 5\\terminal64.exe" ) await bot.run( symbols=["EURUSD", "GBPUSD", "USDJPY"], login=123456, password="your-password", server="your-server" ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Run Linting with Ruff Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md Checks the code style and potential errors in the 'src/' and 'tests/' directories using Ruff. This command helps maintain code consistency and quality. ```bash uvx ruff check src/ tests/ ``` -------------------------------- ### Initialize MCP Server for MetaTrader 5 Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md Initializes the MCPServerStdio for MetaTrader 5. This server acts as a bridge to interact with the MT5 terminal. It requires specifying the server name, arguments for the connection, and a timeout duration. ```python mt5_server = MCPServerStdio( 'uvx', args=['--from', 'mcp-metatrader5-server', 'mt5mcp'], timeout=30 ) ``` -------------------------------- ### Modify Stop Loss and Take Profit for Position using MetaTrader 5 API Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/trading_guide.md Shows how to modify the stop loss (SL) and take profit (TP) levels for an existing position using the MetaTrader 5 API. It retrieves the position details, creates an OrderRequest with the TRADE_ACTION_SLTP action, and specifies the new SL and TP values before sending the request. ```python from mt5_server import OrderRequest # Get the position position = positions_get_by_ticket(ticket=123456) # Create a request to modify stop loss and take profit request = OrderRequest( action=mt5.TRADE_ACTION_SLTP, symbol=position.symbol, sl=1.07, # New stop loss tp=1.09, # New take profit position=position.ticket ) # Send the order result = order_send(request) ``` -------------------------------- ### Run a Specific Test Case Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/tests/README.md Executes a single, specific test case using 'pytest' via 'uv'. This command targets a particular test method within a test file, useful for focused debugging. ```bash uv run pytest tests/test_timeframes.py::TestTimeframeValidation::test_valid_timeframe_conversion ``` -------------------------------- ### Run Tests with Verbose Output Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/tests/README.md Executes all tests using 'pytest' via 'uv' with verbose output enabled. This provides detailed information about each test case being run, which can be helpful for debugging. ```bash uv run pytest -v ``` -------------------------------- ### Initialize MT5 Connection Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Initializes the connection to the MetaTrader 5 terminal. This function must be called before any other MT5 operations. It requires the path to the terminal executable. ```python # Initialize MT5 terminal connection result = initialize(path="C:\\Program Files\\MetaTrader 5\\terminal64.exe") # Returns: True if successful, False otherwise # Common paths: # - "C:\\Program Files\\MetaTrader 5\\terminal64.exe" # - "C:\\Program Files (x86)\\MetaTrader 5\\terminal64.exe" ``` -------------------------------- ### Manage Open Positions in MT5 Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/getting_started.md This snippet shows how to retrieve information about currently open positions in the MT5 terminal. The `positions_get()` tool returns a list of all open positions associated with the logged-in account. ```python # Get all open positions positions_get() ``` -------------------------------- ### Run Tests with Coverage Report Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/CONTRIBUTING.md Runs all tests and generates an HTML coverage report for the 'mcp_mt5' module. This helps identify areas of the code that are not adequately tested. ```bash uv run pytest --cov=mcp_mt5 --cov-report=html ``` -------------------------------- ### Send Trading Orders (Python) Source: https://context7.com/qoyyuum/mcp-metatrader5-server/llms.txt Sends a trading order to the server, supporting market orders, pending orders, and position modifications. Requires a request dictionary with order details like action, symbol, volume, type, price, and optional parameters like stop loss, take profit, and deviation. ```python # Market Buy Order (minimal required fields) result = order_send(request={ "action": 1, # 1=TRADE_ACTION_DEAL (market order) "symbol": "EURUSD", "volume": 0.1, # Lots (0.01=micro, 0.1=mini, 1.0=standard) "type": 0, # 0=BUY, 1=SELL "price": 1.08520 # Current ask price for buy }) # Market Buy Order with Stop Loss and Take Profit result = order_send(request={ "action": 1, "symbol": "EURUSD", "volume": 0.1, "type": 0, # ORDER_TYPE_BUY "price": 1.08520, "sl": 1.08320, # Stop loss 20 pips below "tp": 1.08920, # Take profit 40 pips above "deviation": 20, # Max slippage in points "magic": 123456, # EA identifier "comment": "Buy EURUSD", "type_filling": 2 # 0=FOK, 1=IOC, 2=RETURN }) ``` -------------------------------- ### Create Trading Agent with MT5 Tools Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/docs/pydantic_ai_integration.md Constructs an AI trading agent using the initialized model and MT5 MCP server as its toolset. The agent is configured with a system prompt defining its role, responsibilities, and available MT5 tools. It also specifies the output type and the number of retries for operations. ```python trading_agent = Agent( model, output_type=MarketAnalysis, system_prompt="""You are an expert trading analyst with access to MetaTrader 5 market data. Your responsibilities: 1. Initialize MetaTrader 5 first using the initialize tool 2. Analyze market data using technical indicators 3. Identify key support and resistance levels 4. Determine market trends (bullish, bearish, sideways) 5. Provide clear trading recommendations 6. Assess risk levels for each recommendation Always consider: - Multiple timeframe analysis - Risk management principles - Market volatility - Recent price action Available tools from MT5: - initialize: Initialize MT5 connection - copy_rates_from_pos: Get historical price data - get_symbol_info_tick: Get current price tick - get_account_info: Get account balance and info - positions_get: Get open positions - shutdown: Shutdown MT5 connection Be conservative with recommendations and always prioritize capital preservation.""", toolsets=[mt5_server], # Register MT5 MCP server as a toolset retries=2 ) ``` -------------------------------- ### Run Tests with Coverage Report Generation Source: https://github.com/qoyyuum/mcp-metatrader5-server/blob/main/tests/README.md Executes tests using 'pytest' via 'uv' and generates a code coverage report, specifically focusing on the 'mcp_mt5' module. The report is output in HTML format for easy viewing. ```bash # Generate coverage report uv run pytest --cov=mcp_mt5 --cov-report=html # View HTML report open htmlcov/index.html # macOS/Linux start htmlcov/index.html # Windows ```