### Install and Configure Environment Source: https://github.com/chymian/metatrader-mcp/blob/main/docs/To programmatically run strategy optimiz.md Commands to install Wine, MT5, and the necessary Python environment within a Linux system. ```bash sudo apt install wine wine mt5setup.exe wine python-3.x.x.exe wine pip install MetaTrader5 ``` -------------------------------- ### Distrobox Container Configuration Source: https://context7.com/chymian/metatrader-mcp/llms.txt Configuration file for setting up the MetaTrader environment in a Distrobox container, including dependency installation and API auto-start. ```ini [mt5] name=mt5 image=quay.io/toolbx/ubuntu-toolbox:24.04 additional_flags="-p 5000:5000" additional_packages="git vim tmux python3 python3-pip wine-stable winetricks" pull=true log_dir=~/mt5-dev/logs data_dir=~/mt5-dev/data result_dir=~/mt5-dev/result/manual/tuning init_hooks="pip3 install flask flask-restful MetaTrader5 pandas jinja2" init_hooks="mkdir -p ~/mt5-dev/result/manual/tuning" init_hooks="nohup python3 ~/mt5-dev/src/mt5_flask_api.py &" ``` ```bash distrobox-assemble create --file src/mt5.ini -R distrobox-enter mt5 curl http://localhost:5000/optimization_status/test ``` -------------------------------- ### GET get_account_info Source: https://context7.com/chymian/metatrader-mcp/llms.txt Retrieves account information from MetaTrader 5 including balance, equity, margin, and leverage details. ```APIDOC ## GET get_account_info ### Description Retrieves account information from MetaTrader 5 including balance, equity, margin, and leverage details. Optionally accepts an account number parameter; otherwise uses the default connected account. ### Method GET ### Endpoint get_account_info ### Parameters #### Query Parameters - **account** (number) - Optional - The specific account number to query. ### Request Example { "account": 12345678 } ### Response #### Success Response (200) - **login** (number) - Account login ID - **name** (string) - Account holder name - **balance** (number) - Current account balance - **equity** (number) - Current account equity #### Response Example { "login": 12345678, "name": "John Doe", "balance": 10000.00, "equity": 10250.50 } ``` -------------------------------- ### GET get_symbol_price Source: https://context7.com/chymian/metatrader-mcp/llms.txt Fetches the current bid/ask prices and spread for a specified trading symbol. ```APIDOC ## GET get_symbol_price ### Description Fetches the current bid/ask prices and spread for a specified trading symbol. Essential for monitoring market conditions before placing orders. ### Method GET ### Endpoint get_symbol_price ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., EURUSD). ### Request Example { "symbol": "EURUSD" } ### Response #### Success Response (200) - **symbol** (string) - The trading symbol - **bid** (number) - Current bid price - **ask** (number) - Current ask price - **spread** (number) - Current spread #### Response Example { "symbol": "EURUSD", "bid": 1.08542, "ask": 1.08545, "spread": 3 } ``` -------------------------------- ### Get Open Positions (TypeScript) Source: https://context7.com/chymian/metatrader-mcp/llms.txt Retrieves a list of all currently open trading positions in MetaTrader 5. Each position includes details such as ticket number, symbol, volume, profit/loss, and stop loss/take profit levels. ```typescript // MCP Tool Call const result = await mcpClient.callTool('get_open_positions', {}); // Expected Response [ { "ticket": 123456789, "symbol": "EURUSD", "type": "BUY", "volume": 0.1, "openPrice": 1.08500, "openTime": "2024-01-15T10:00:00Z", "sl": 1.08300, "tp": 1.08800, "profit": 42.50, "comment": "MCP automated trade" } ] ``` -------------------------------- ### Get Account Info (TypeScript) Source: https://context7.com/chymian/metatrader-mcp/llms.txt Retrieves detailed information about a MetaTrader 5 trading account, including balance, equity, margin, and leverage. This function can target a specific account or use the default connected account. ```typescript // MCP Tool Call const result = await mcpClient.callTool('get_account_info', { account: 12345678 // Optional: specific account number }); // Expected Response { "login": 12345678, "name": "John Doe", "server": "MetaQuotes-Demo", "currency": "USD", "balance": 10000.00, "equity": 10250.50, "margin": 500.00, "freeMargin": 9750.50, "leverage": 100 } ``` -------------------------------- ### Get Pending Orders (TypeScript) Source: https://context7.com/chymian/metatrader-mcp/llms.txt Fetches all pending orders (limit and stop orders) that are currently active in MetaTrader 5. This allows for monitoring and management of the order flow. ```typescript // MCP Tool Call const result = await mcpClient.callTool('get_pending_orders', {}); // Expected Response [ { "ticket": 987654321, "symbol": "GBPUSD", "type": "BUYLIMIT", "volume": 0.5, "openPrice": 1.26000, "openTime": "2024-01-15T12:00:00Z", "sl": 1.25800, "tp": 1.26500, "comment": "Support level entry" } ] ``` -------------------------------- ### Optimization Request Payload Source: https://github.com/chymian/metatrader-mcp/blob/main/docs/To programmatically run strategy optimiz.md Example JSON structure required for the /optimize POST request to define strategy parameters. ```json { "symbol": "EURUSD", "timeframe": "H1", "start_pos": 0, "count": 1000 } ``` -------------------------------- ### Get Symbol Price (TypeScript) Source: https://context7.com/chymian/metatrader-mcp/llms.txt Fetches the current bid, ask prices, and spread for a specified trading symbol from MetaTrader 5. This is crucial for monitoring market conditions before executing trades. ```typescript // MCP Tool Call const result = await mcpClient.callTool('get_symbol_price', { symbol: 'EURUSD' }); // Expected Response { "symbol": "EURUSD", "bid": 1.08542, "ask": 1.08545, "spread": 3, "time": "2024-01-15T14:30:00Z" } ``` -------------------------------- ### POST run_optimization Source: https://context7.com/chymian/metatrader-mcp/llms.txt Initiates a strategy optimization run for an Expert Advisor. ```APIDOC ## POST run_optimization ### Description Initiates a strategy optimization run for an Expert Advisor through the Flask API bridge. Supports genetic and exhaustive optimization modes. ### Method POST ### Endpoint run_optimization ### Parameters #### Request Body - **symbol** (string) - Required - Trading symbol. - **ea** (string) - Required - Expert Advisor filename. - **params** (object) - Required - Parameter ranges for optimization. - **optimization_mode** (string) - Optional - 'genetic' or 'exhaustive'. ### Request Example { "symbol": "EURUSD", "ea": "MyExpert.ex5", "params": { "TakeProfit": { "min": 50, "max": 200, "step": 10 } } } ### Response #### Success Response (200) - **optimization_id** (string) - Unique ID for the optimization task. ### Response Example { "optimization_id": "550e8400-e29b-41d4-a716-446655440000" } ``` -------------------------------- ### POST create_order Source: https://context7.com/chymian/metatrader-mcp/llms.txt Creates a new trading order with support for market orders and pending orders. ```APIDOC ## POST create_order ### Description Creates a new trading order with support for market orders (BUY/SELL) and pending orders (BUYLIMIT, SELLLIMIT, BUYSTOP, SELLSTOP). ### Method POST ### Endpoint create_order ### Parameters #### Request Body - **symbol** (string) - Required - Trading symbol - **type** (string) - Required - Order type (BUY, SELL, BUYLIMIT, etc.) - **volume** (number) - Required - Trade volume - **sl** (number) - Optional - Stop Loss - **tp** (number) - Optional - Take Profit ### Request Example { "symbol": "EURUSD", "type": "BUY", "volume": 0.1 } ### Response #### Success Response (200) - **ticket** (number) - Order ticket number - **status** (string) - Order status #### Response Example { "ticket": 123456790, "status": "filled" } ``` -------------------------------- ### Run Strategy Optimization Source: https://context7.com/chymian/metatrader-mcp/llms.txt Initiates an Expert Advisor optimization run. Supports genetic and exhaustive modes with configurable parameter ranges. ```typescript const result = await mcpClient.callTool('run_optimization', { symbol: 'EURUSD', ea: 'MyExpert.ex5', period: 'H1', date_from: '2023-01-01', date_to: '2023-12-31', deposit: 10000, params: { TakeProfit: { min: 50, max: 200, step: 10 }, StopLoss: { min: 30, max: 100, step: 10 } }, optimization_mode: 'genetic' }); ``` ```bash curl -X POST http://localhost:5000/optimize \ -H "Content-Type: application/json" \ -d '{ "symbol": "EURUSD", "ea": "MyExpert.ex5", "period": "H1", "date_from": "2023-01-01", "date_to": "2023-12-31", "deposit": 10000, "params": { "TakeProfit": {"min": 50, "max": 200, "step": 10}, "StopLoss": {"min": 30, "max": 100, "step": 10} } }' ``` -------------------------------- ### Create Order (TypeScript) Source: https://context7.com/chymian/metatrader-mcp/llms.txt Creates a new trading order in MetaTrader 5, supporting both market orders (BUY/SELL) and various pending order types. Optional parameters include stop loss, take profit, and a comment. ```typescript // Market Order Example const marketOrder = await mcpClient.callTool('create_order', { symbol: 'EURUSD', type: 'BUY', volume: 0.1, sl: 1.08300, tp: 1.08800, comment: 'Trend following entry' }); // Pending Limit Order Example const limitOrder = await mcpClient.callTool('create_order', { symbol: 'GBPUSD', type: 'BUYLIMIT', volume: 0.5, price: 1.26000, sl: 1.25800, tp: 1.26500, comment: 'Support level entry' }); // Expected Response { "ticket": 123456790, "status": "filled", "symbol": "EURUSD", "type": "BUY", "volume": 0.1, "price": 1.08545 } ``` -------------------------------- ### Retrieve Optimization Results Source: https://context7.com/chymian/metatrader-mcp/llms.txt Fetches the full results of a completed optimization run, including the best-performing parameter configuration. ```typescript const result = await mcpClient.callTool('get_optimization_results', { optimization_id: '550e8400-e29b-41d4-a716-446655440000' }); ``` ```bash curl http://localhost:5000/optimization_results/550e8400-e29b-41d4-a716-446655440000 ``` -------------------------------- ### Initialize MetaTrader 5 API Source: https://github.com/chymian/metatrader-mcp/blob/main/docs/To programmatically run strategy optimiz.md A Python snippet to verify the connection to the MetaTrader 5 terminal using the MetaTrader5 library. ```python import MetaTrader5 as mt5 if not mt5.initialize(): print("Failed to initialize MT5") mt5.shutdown() ``` -------------------------------- ### Save Optimization Results Source: https://context7.com/chymian/metatrader-mcp/llms.txt Exports optimization results to persistent storage in various formats like HTML, Markdown, or JSON. ```typescript const result = await mcpClient.callTool('save_optimization_results', { optimization_id: '550e8400-e29b-41d4-a716-446655440000', format: 'json', path: '~/mt5-dev/result/manual/tuning' }); ``` ```bash curl -X POST http://localhost:5000/save_results \ -H "Content-Type: application/json" \ -d '{ "optimization_id": "550e8400-e29b-41d4-a716-446655440000", "ea_name": "MyExpert", "format": "csv" }' ``` -------------------------------- ### MCP Server Configuration (JSON) Source: https://context7.com/chymian/metatrader-mcp/llms.txt Configuration for the MCP server, specifying connection details to MetaTrader 5 HTTP API and the Flask optimization API via environment variables. This JSON object defines how the server connects and operates. ```json { "mcpServers": { "metatrader5": { "command": "node", "args": ["server.js"], "env": { "MT5_API_ENDPOINT": "http://localhost:5555", "MT5_API_KEY": "", "MT5_FLASK_API": "http://localhost:5000" }, "disabled": false, "autoApprove": [] } } } ``` -------------------------------- ### Create Flask REST API for MT5 Source: https://github.com/chymian/metatrader-mcp/blob/main/docs/To programmatically run strategy optimiz.md A Flask application that exposes MT5 data retrieval and optimization tasks via a POST endpoint. It handles initialization, data fetching, and resource cleanup. ```python from flask import Flask, request, jsonify import MetaTrader5 as mt5 app = Flask(__name__) @app.route('/optimize', methods=['POST']) def optimize_strategy(): params = request.json symbol = params.get('symbol') timeframe = params.get('timeframe') start_pos = params.get('start_pos', 0) count = params.get('count', 1000) if not mt5.initialize(): return jsonify({"error": "Failed to initialize MT5"}), 500 rates = mt5.copy_rates_from_pos(symbol, timeframe, start_pos, count) mt5.shutdown() return jsonify({"rates": rates.tolist()}) if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### POST delete_order Source: https://context7.com/chymian/metatrader-mcp/llms.txt Deletes a pending limit or stop order. ```APIDOC ## POST delete_order ### Description Deletes a pending order (limit or stop order) that has not yet been executed. ### Method POST ### Endpoint delete_order ### Parameters #### Request Body - **ticket** (integer) - Required - The unique identifier of the pending order. ### Request Example { "ticket": 987654321 } ### Response #### Success Response (200) - **ticket** (integer) - The deleted order ticket. - **status** (string) - The status of the operation. ### Response Example { "ticket": 987654321, "status": "deleted" } ``` -------------------------------- ### Query Optimization Status Source: https://context7.com/chymian/metatrader-mcp/llms.txt Checks the current progress of an optimization task using its unique ID. ```typescript const result = await mcpClient.callTool('get_optimization_status', { optimization_id: '550e8400-e29b-41d4-a716-446655440000' }); ``` ```bash curl http://localhost:5000/optimization_status/550e8400-e29b-41d4-a716-446655440000 ``` -------------------------------- ### POST close_position Source: https://context7.com/chymian/metatrader-mcp/llms.txt Closes an open trading position by its unique ticket number. ```APIDOC ## POST close_position ### Description Closes an open position by its ticket number, realizing any profit or loss at current market prices. ### Method POST ### Endpoint close_position ### Parameters #### Request Body - **ticket** (integer) - Required - The unique identifier of the position to close. ### Request Example { "ticket": 123456789 } ### Response #### Success Response (200) - **ticket** (integer) - The closed position ticket. - **status** (string) - The status of the operation. - **profit** (float) - Realized profit or loss. - **closePrice** (float) - The price at which the position was closed. ### Response Example { "ticket": 123456789, "status": "closed", "profit": 45.00, "closePrice": 1.08590 } ``` -------------------------------- ### Modify Order (TypeScript) Source: https://context7.com/chymian/metatrader-mcp/llms.txt Modifies the stop loss and/or take profit levels for an existing order or position in MetaTrader 5, identified by its ticket number. This allows for dynamic risk management. ```typescript // MCP Tool Call const result = await mcpClient.callTool('modify_order', { ticket: 123456789, sl: 1.08400, // New stop loss tp: 1.09000 // New take profit }); // Expected Response { "ticket": 123456789, "status": "modified", "sl": 1.08400, "tp": 1.09000 } ``` -------------------------------- ### Delete Pending Order via MCP Source: https://context7.com/chymian/metatrader-mcp/llms.txt Removes a pending limit or stop order that has not yet been executed by the broker. ```typescript const result = await mcpClient.callTool('delete_order', { ticket: 987654321 }); ``` -------------------------------- ### Close Trading Position via MCP Source: https://context7.com/chymian/metatrader-mcp/llms.txt Closes an open trading position by its unique ticket number. This tool realizes any profit or loss at current market prices. ```typescript const result = await mcpClient.callTool('close_position', { ticket: 123456789 }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.