Skip to main content

MCP Server Framework for MetaTrader 5. Build HTTP and stdio servers with automatic tool registration and MT5 socket communication

Project description

MCP Servers for MT5


Overview

McpServer es una libreria que proporciona la interfaz para MQL5, donde se definiran los tools funciones asicronas como sincronas ademas de propoarinar la parte de python la cual esta compuesta de un pauqeute facil de usar para definir tools


Main Features

Core Capabilities

  • Trade Operations: Open/close positions, manage orders, query trading history
  • Market Data: Real-time OHLC and tick data, symbol information and quotes
  • Chart Management: Create/modify graphic objects, control chart windows
  • Code Execution: Compile MQL5, run Expert Advisors, execute backtests
  • Terminal Data: Access account info, terminal settings, and logging

Repository Structure

McpServer/
├── Src/                    # MQL5 Backend Functions
├── mcp_mt5_conection/      # Python MCP Server Package
└── Configuration & metadata files

Requirements

  • For repo code
  • For user use:

Installation of repo code

cd "C:\Users\YOUR USER\AppData\Roaming\MetaQuotes\Terminal\YOUR ID\MQL5\Shared Projects"
tsndep install "https://forge.mql5.io/nique_372/McpServer.git"
  • For use tsndep command requerid tsndep pacakage (avaible in pypi).. This command automatically downloads all dependencies and installs all requirements from the repositories.
  • If any part of the system is private, then it will fail... contact me so I can give you access (if it's a product, you can buy it; if you have any questions, don't hesitate to contact me).

Quick Start (for final users)

1. Install Package

pip install mcp-mt5-conection

2. Create Configuration File

Create a JSON configuration file (e.g., mt5_mcp_config.json):

{
    "general_config": {
        "host": "localhost",
        "port": 9999,
        "mode": "fast_mcp"
    },
    "fast_mcp": {
        "name": "MT5McpServer"
    },
    "http": {
        "http_port": 8000,
        "name": "MT5 HTTP Server",
        "tools_namespace": "tools"
    }
}

3. Create Your Server Script

Create a Python file with your custom tools (based on mcp_mt5_conection/server_template.py):

from mcp_mt5_conection import CMt5McpConection, CToolRegisterMCP
import json
from typing import Dict, Any

# Load configuration
config : dict = None
with open("mt5_mcp_config.json", "r") as f:
    config = json.load(f)

# Initialize connection and server
mt5_conn = CMt5McpConection(
    config["general_config"]["host"],
    config["general_config"]["port"]
)
server = CToolRegisterMCP(config, mt5_conn)

# Register your custom tools using the decorator
@server.register_tool()
def open_trade(payload: Dict[str, Any]) -> str:
    """Open a new trade position"""
    pass

# Run the server
if __name__ == "__main__":
    server.run()

4. Part of MQL5

  • Functions include
#include <TSN\\Mcp\\Main.mqh>
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
class CMcpFuncTradeTrade : public CMcpFunction
 {
protected:
  CTrade*            m_trade;
public:
                     CMcpFuncTradeTrade(CTrade* tr)
    :                CMcpFunction(0, false, "open_trade"),
                     m_trade(tr)
   {}
                    ~CMcpFuncTradeTrade(void) {}
  //---
  void               Run(CJsonNode& param, string& res) override final;
 };
//+------------------------------------------------------------------+
void               CMcpFuncTradeTrade::Run(CJsonNode& param, string& res)
 {
  ::ResetLastError();
  res = "";
  m_trade.SetExpertMagicNumber(ulong(param["magic"].ToInt(0)));
  const bool result = (param["type"].ToString("") == "buy")
                      ? m_trade.Buy(param["lot_size"].ToDouble(0.00), param["symbol"].ToString(NULL), param["price"].ToDouble(0.000), param["sl"].ToDouble(0.000), param["tp"].ToDouble(0.0000), param["comment"].ToString(""))
                      : m_trade.Sell(param["lot_size"].ToDouble(0.00), param["symbol"].ToString(NULL), param["price"].ToDouble(0.000), param["sl"].ToDouble(0.000), param["tp"].ToDouble(0.0000), param["comment"].ToString(""));
  if(!result)
    res = StringFormat("{\"ok\":false,\"error\":\"trade_failed, last mt5 error = %d\"}", ::GetLastError());
  else
    res = StringFormat("{\"ok\":true,\"result\":%lu}", m_trade.ResultOrder());
 }
  • Main EA
#include "Functions.mqh"
//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input string InpSoketAdres = "127.0.0.1";
input uint InpSoketPort = 9999;
input int InpMsPool = 100;
input int InpMsTimeoutReadNoTls = 10000;
//+------------------------------------------------------------------+
//| Global variables                                                 |
//+------------------------------------------------------------------+
IMcpBase* g_mcp_server;
CTrade g_trade;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
 {
//---
#ifdef TSN_MCPSERVER_FUNC_CTS
  g_mcp_server = TSN_MCPSERVER_FUNC_CTS(THE_BOT_PLACE_USER_ID);
#else
  g_mcp_server = McpServerByLeo_Create(THE_BOT_PLACE_USER_ID); 
#endif // TSN_MCPSERVER_FUNC_CTS
//---
  ::EventSetMillisecondTimer(InpMsPool);
  g_mcp_server.AddLogFlags(LOG_ALL);
//--- Graphics / Objects
  g_mcp_server.AddItemFast(new CMcpFuncObjectCreate());
  g_mcp_server.AddItemFast(new CMcpFuncObjectCreate());
//---
  g_mcp_server.Set(InpMsPool, InpMsTimeoutReadNoTls);
  if(!g_mcp_server.Conectar(InpSoketAdres, InpSoketPort, (10 * 1000))) // 10 segundos de espera para conectarse
    return INIT_FAILED;
//---
  return(INIT_SUCCEEDED);
 }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
 {
//---
  if(CheckPointer(g_mcp_server) == POINTER_DYNAMIC)
    delete g_mcp_server;
//---
 }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
 {
//---
 }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer(void)
 {
  g_mcp_server.TimerEvent();
 }
//+------------------------------------------------------------------+

5. Configure MetaTrader 5

In MT5: ToolsOptionsAllowed URLs for WebRequest

  • Add 127.0.0.1 (or your configured host)
  • Enable AutoTrading and DLL imports

6. Run Server and Connect EA

  • Start your Python server: python your_server.py --config mt5_mcp_config.json
  • In MetaTrader 5, compile and attach the McpServer EA to your chart
  • Configure EA parameters to match your host/port settings

7. Use in Claude Desktop

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "mt5_mcp": {
      "command": "python",
      "args": ["your_server.py", "--config", "mt5_mcp_config.json"]
    }
  }
}

Now you can use Claude to interact with MT5 through natural language.


License

Read Full License

By downloading or using this repository, you accept the license terms.


Documentation


Contact


Copyright © 2026 Niquel Mendoza (nique_372).
TSN Trading Systems ecosystem.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mcp_mt5_conection-1.0.0.tar.gz (9.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcp_mt5_conection-1.0.0-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

Details for the file mcp_mt5_conection-1.0.0.tar.gz.

File metadata

  • Download URL: mcp_mt5_conection-1.0.0.tar.gz
  • Upload date:
  • Size: 9.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.9

File hashes

Hashes for mcp_mt5_conection-1.0.0.tar.gz
Algorithm Hash digest
SHA256 d3be326051d089ec91b00c002b6a8073b7788a0bf600cb6eb607bbe5aa8935f2
MD5 71975e862f3bf0647c78ed407241d624
BLAKE2b-256 e427f383087a7e24cddea7f8be92badfe5203f93a7e55bdc9281f5c2faf7beeb

See more details on using hashes here.

File details

Details for the file mcp_mt5_conection-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for mcp_mt5_conection-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2a598f8877d2c925b821cc8a3776c57ac1f7b523cac1db40e7e59c44dabe843c
MD5 5beaabfb05d6af12b1b0918308c50b7e
BLAKE2b-256 82d4ac5638302693d3e5972b89296184cfc9f7c06779e5ccb2b63860589a12b2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page