Metadata-Version: 2.4
Name: mcp-mt5-conection
Version: 1.0.1
Summary: MCP Server Framework for MetaTrader 5. Build HTTP and stdio servers with automatic tool registration and MT5 socket communication
Project-URL: Repository, https://forge.mql5.io/nique_372/McpServer
Project-URL: Documentation, https://forge.mql5.io/nique_372/McpServer
Project-URL: Issues, https://forge.mql5.io/nique_372/McpServer/issues
Author-email: Nique Mendoza <tradesystemsnique@gmail.com>, Leo <leo@example.com>
License: Copyright (c) 2026 Niquel and Leo.  
        
        This repository is governed by the Niquel & Leo NL-ND-P (No LLM, No Distribution, Private).  
        Full terms and conditions are available at:  
        https://forge.mql5.io/nique_372/TSNReposIndex/src/branch/main/Licenses/LICENSE-NL-ND-P.md
        
        By accessing, cloning, forking, or otherwise using this repository (including all repo code and all repo sections, issues, wiki, pull requesets, releases, packages, etc.), you agree to be bound by the terms of this license.
        If you do not agree to this repository's license, do not use any code from it for any purpose.
License-File: LICENSE
Keywords: mcp,metatrader5,mt5,server,trading
Requires-Python: >=3.10
Requires-Dist: fastapi>=0.136.1
Requires-Dist: mcp>=1.27.0
Requires-Dist: uvicorn>=0.46.0
Description-Content-Type: text/markdown

<!-- mcp-name: io.github.TradeSystemsNique/fullmt5mcp-by-leo -->
<p align="center">
  <img src="https://img.shields.io/badge/Language-Python-3776ab?style=flat-square"/>
  <img src="https://img.shields.io/badge/MQL5-Backend-13C7DE?style=flat-square"/>
  <img src="https://img.shields.io/badge/Protocol-MCP-1B6CA8?style=flat-square"/>
  <img src="https://img.shields.io/badge/Platform-MetaTrader%205-0D1B2A?style=flat-square"/>
  <img src="https://img.shields.io/badge/Author-Niquel%20Mendoza-C9D6DF?style=flat-square"/>
  <a href="./LICENSE">
    <img src="https://img.shields.io/badge/License-Nique%26Leo%20NL--ND--P-red.svg"/>
  </a>
</p>

<p align="center">
  <strong>MCP Servers for MT5</strong>
</p>

---

## Overview

**mcp-mt5-conection** is a Python library that bridges MetaTrader 5 (MT5) with the Model Context Protocol (MCP). It provides a simple and extensible framework to create tools that communicate between Python and MT5 via socket connections. Define your tools once in Python, and expose them through either FastMCP (for Claude and MCP clients) or HTTP (for custom integrations).

---

## Main Features

### Library Capabilities
- **Simple Tool Registration:** Use Python decorators to define MCP tools with minimal boilerplate
- **Dual Protocol Support:** Expose tools via FastMCP (for Claude) or HTTP API simultaneously
- **Socket-Based Communication:** Reliable TCP socket connection between Python and MT5 with JSON serialization
- **Extensible Architecture:** Abstract base classes allow custom implementations (MCP, HTTP, or custom protocols)
- **MT5 Function Access:** Call any MT5 function from Python through registered tools (trading, data, charts, etc.)

---

## Repository Structure

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

---

## Requirements
- Py requeriements and MQL5 Dependencies: [dependencies.json](./dependencies.json)
- McpServer requerid a EX5 Library, pucharse in: [TheBotPlace - McpServerByLeo](https://www.thebotplace.com/bot/mcpserverbyleo)

---

## Installation of repo code 

```bash
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](https://pypi.org/project/tsndep)).. 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

```bash
pip install mcp-mt5-conection
```

### 2. Create Configuration File

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

```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`):

```python
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
```cpp
#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
```cpp
#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: **Tools** → **Options** → **Allowed 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`:

```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](./LICENSE)**

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

---

## Documentation
- Wiki: [https://forge.mql5.io/nique_372/McpServer/wiki](https://forge.mql5.io/nique_372/McpServer/wiki)

---

## Contact
- **Platform:** [MQL5 Community](https://www.mql5.com/es/users/nique_372)
- **Profile:** https://www.mql5.com/es/users/nique_372/news

---

<p align="center">Copyright © 2026 Niquel Mendoza (nique_372).<br/>
TSN Trading Systems ecosystem.</p>