Content
# QMT-MCP - Modular Quantitative Trading Assistant
<div align="center">



A modular quantitative trading system based on FastMCP and XTQuant, providing intelligent strategy generation, real-time trade execution, and backtesting analysis.
</div>
## 🌟 Project Features
- **🔗 MCP Protocol Integration**: Seamlessly connects with AI assistants based on Model Context Protocol
- **📈 Intelligent Strategy Generation**: Automatically generates and optimizes quantitative trading strategies
- **⚡ Real-time Trade Execution**: Supports XTQuant/QMT live and simulated trading
- **🧠 Modular Architecture**: Clear code structure, easy to extend and maintain
- **📊 Backtesting Analysis**: Complete strategy backtesting and performance evaluation
- **🛡️ Risk Control**: Built-in multi-layer risk control mechanisms
## 🎬 Demo Video
> 📺 Click the cover image or link to watch the full demo on Bilibili
>
> https://www.bilibili.com/video/BV1SFGjz6EKN/?vd_source=26053b834f0ddd4f57b22169d74b6f78
<!-- 如果你准备了演示封面图,可以把下面这行的 docs/demo_cover.png 换成你的图片路径 -->
[](https://www.bilibili.com/video/BV1SFGjz6EKN/?vd_source=26053b834f0ddd4f57b22169d74b6f78)
## 🏗️ System Architecture
```
国金QMT-MCP/
├── main.py # FastMCP服务器主入口
├── config.json # 系统配置文件
├── requirements.txt # 项目依赖
├── src/
│ ├── config.py # 配置管理模块(支持环境变量)
│ ├── tools/ # MCP工具实现
│ │ ├── trading_tool.py # 交易执行工具
│ │ └── qmt_tool.py # QMT策略工具
│ ├── strategies/ # 策略模块
│ │ ├── ma_strategy.py # 双均线策略
│ │ └── strategy_generator.py # 策略生成器
│ └── utils/ # 工具模块
│ ├── xtquant_client.py # XTQuant客户端
│ └── data_handler.py # 数据处理器
└── logs/ # 日志文件目录
```
## 🚀 Quick Start
### Environment Requirements
- **Python 3.8+**
- **XTQuant/QMT Client** (Guojin/Xuntou Quantitative Trading Client)
- **Windows System** (XTQuant only supports Windows)
### Installation Steps
1. **Clone the project**
```bash
git clone <repository-url>
cd Nondescript-MCP
```
2. **Install dependencies**
```bash
pip install -r requirements.txt
```
3. **Configure environment**
Create a `.env` file and configure the following parameters:
```env
# =====================================================
# 国金QMT-MCP 环境配置文件
# 请根据你的实际环境修改下面的配置参数
# =====================================================
# 服务器配置
QUANTMCP_HOST=127.0.0.1 # MCP服务器监听地址,通常保持127.0.0.1
QUANTMCP_PORT=8000 # MCP服务器端口号,可根据需要修改
QUANTMCP_TRANSPORT=sse # 传输协议,保持sse即可
# XTQuant/QMT 交易客户端配置
# 重要:请修改为你的QMT安装路径和账户信息
QMT_PATH=你的QMT安装路径\userdata_mini # QMT客户端数据目录,如: D:\QMT\userdata_mini
QMT_SESSION_ID=你的会话ID # QMT会话ID,整数,如: 12345
QMT_ACCOUNT_ID=你的交易账户ID # 你的模拟或实盘交易账户ID
# QMT策略保存目录
QMT_STRATEGY_DIR=你的QMT策略目录\mpython # QMT策略文件保存目录,如: D:\QMT\mpython
# 交易风险控制配置
MAX_ORDER_VALUE=100000.0 # 单笔订单最大金额(元),防止误操作大额下单
MAX_POSITION_VALUE=500000.0 # 单只股票最大持仓金额(元),控制单股风险
MIN_ORDER_QUANTITY=100 # 最小下单数量(股),通常为100的整数倍
MARKET_ORDER_SPREAD=0.1 # 市价单价差比例(0.1=10%),避免成交价偏离过大
# 策略默认参数配置
DEFAULT_SYMBOL=000001.SZ # 默认股票代码,用于测试和演示
DEFAULT_START_DATE=20240101 # 默认回测开始日期,格式YYYYMMDD
DEFAULT_END_DATE=20241201 # 默认回测结束日期,格式YYYYMMDD
DEFAULT_SHORT_PERIOD=5 # 默认短期均线天数
DEFAULT_LONG_PERIOD=20 # 默认长期均线天数
# 日志配置
LOG_LEVEL=INFO # 日志级别: DEBUG/INFO/WARNING/ERROR
LOG_FILE=logs/quantmcp.log # 日志文件路径
```
4. **Start the XTQuant Client**
- Open the Guojin QMT or Xuntou Quantitative Client
- Ensure the client is logged in and connected
5. **Start the Guojin QMT-MCP service**
```bash
python main.py
```
After the service starts, it will provide MCP services at `http://127.0.0.1:8000`.
## 🔧 Function Introduction
### Trading Tools
#### Place Order Function
```python
# Through MCP interface call
place_order(
symbol="000001.SZ", # 股票代码
quantity=100, # 买入股数
price=10.5, # 下单价格
direction="BUY" # 交易方向
)
```
#### Cancel Order Function
```python
cancel_order(order_id="12345") # 撤销指定订单
```
### Strategy Generation
#### Double Moving Average Strategy
```python
generate_ma_strategy(
symbol="000001.SZ", # 目标股票
short_period=5, # 短期均线
long_period=20, # 长期均线
strategy_name="my_ma" # 策略名称
)
```
#### Custom Strategy
```python
save_qmt_strategy(
strategy_name="custom_strategy",
code="""
def init(context):
# 策略初始化
pass
def handle_bar(context, bar_dict):
# 策略执行逻辑
pass
"""
)
```
## 📊 Strategy Backtesting
The system provides complete strategy backtesting functions, including:
- **Return Metrics**: Total return, annualized return, Sharpe ratio
- **Risk Metrics**: Maximum drawdown, volatility, VaR
- **Trading Statistics**: Number of trades, win rate, average profit/loss
- **Performance Evaluation**: Strategy rating and optimization suggestions
### Backtesting Report Example
```
[OK] 双均线策略生成成功!
[DATA] 股票信息: 000001.SZ
[DATE] 数据期间: 20240101 至 20241201
[CHART] 数据条数: 242 条
[DATA] 交易天数: 242 天
[TARGET] 双均线策略参数:
* 短期均线: 5日
* 长期均线: 20日
[CHART] 策略表现:
* 总收益率: 15.23%
* 年化收益率: 18.45%
* 最大回撤: -8.67%
* 年化波动率: 22.15%
* 夏普比率: 0.845
* 交易次数: 24
* 胜率: 58.33%
[TIP] 策略评价:
[OK] 年化收益良好,超过15%
[OK] 风险控制优秀,最大回撤小于10%
[WARNING] 夏普比率一般,收益风险比有待提升
[OK] 胜率良好,超过50%
```
## 🛡️ Risk Control
The system has built-in multi-layer risk control mechanisms:
### Trading Level
- Maximum amount limit per order
- Maximum position limit per target
- Minimum order quantity control
- Market order price difference protection
### Strategy Level
- Maximum drawdown limit
- Minimum Sharpe ratio requirement
- Leverage ratio control
- Stop loss ratio setting
### System Level
- Trading status control
- Connection status monitoring
- Exception handling mechanism
- Log recording tracking
## 🔌 MCP Integration
Guojin QMT-MCP is fully compatible with the Model Context Protocol and can be integrated with AI assistants that support MCP:
### Preferred: SSE Direct Connection Configuration (Recommended)
If you only need to **directly connect** to an already running Guojin QMT-MCP server, the simplest and most reliable way is to use **SSE (Server-Sent Events) direct connection**.
```json
{
"mcpServers": {
"qmt-mcp": {
"type": "sse",
"url": "http://127.0.0.1:8000/sse",
"timeout": 60,
"autoApprove": []
}
}
}
```
> 📌 **Why recommend SSE?**
> - 🛠️ **Zero dependencies**: The client no longer needs to execute Python/Node commands.
> - ⚡ **Plug and play**: The server can be discovered by any MCP-enabled application after it is started.
> - 🪶 **Minimum configuration**: Only two key fields `type` and `url` are required.
> - 🌐 **Remote friendly**: Modify the `url` to access it on a LAN/cloud server.
The following shows complete configuration examples for different tools (Claude Desktop / VS Code Cline / Cursor). If you need to automatically start the server, you can also use the `command/args` mode.
### Claude Desktop Integration
Add to the Claude Desktop configuration file:
```json
{
"mcpServers": {
"quantmcp": {
"command": "python",
"args": ["path/to/Nondescript-MCP/main.py"],
"env": {
"QMT_PATH": "你的QMT安装路径\\userdata_mini"
}
}
}
}
```
### Available Tools
- `place_order`: Execute stock trades
- `cancel_order`: Cancel orders
- `save_qmt_strategy`: Save custom strategies
- `generate_ma_strategy`: Generate double moving average strategies
## 📋 Configuration Instructions
### Core Configuration Items
| Configuration Item | Description | Default Value |
|--------|------|--------|
| QMT_PATH | QMT client installation path | 你的QMT安装路径\userdata_mini |
| QMT_SESSION_ID | QMT session ID | 你的会话ID |
| QMT_ACCOUNT_ID | Trading account ID | 你的交易账户ID |
| MAX_ORDER_VALUE | Maximum amount per order | 100000.0 |
| MAX_POSITION_VALUE | Maximum position per target | 500000.0 |
### Strategy Configuration Items
| Configuration Item | Description | Default Value |
|--------|------|--------|
| DEFAULT_SYMBOL | Default stock code | 000001.SZ |
| DEFAULT_SHORT_PERIOD | Default short-term moving average | 5 |
| DEFAULT_LONG_PERIOD | Default long-term moving average | 20 |
## 🧪 Development Guide
### Add a New Strategy
1. Create a strategy module in the `src/strategies/` directory
2. Implement the strategy class, including signal calculation and backtesting methods
3. Register the new strategy in `strategy_generator.py`
4. Update the configuration file to add strategy parameters
### Add a New Tool
1. Create a tool module in the `src/tools/` directory
2. Implement the tool class and related methods
3. Register using the `@mcp.tool()` decorator in `main.py`
4. Update the `__init__.py` file to export the new tool
### Testing
```bash
# Run tests
pytest tests/
# Code formatting
black src/
# Code inspection
flake8 src/
```
## 📚 API Documentation
### place_order(symbol, quantity, price, direction)
Execute a stock trading order
**Parameters:**
- `symbol` (str): Stock code, such as "000001.SZ"
- `quantity` (int): Trading quantity, must be an integer multiple of 100
- `price` (float): Order price
- `direction` (str): Trading direction, "BUY" or "SELL"
**Returns:**
- `str`: Order result information
### generate_ma_strategy(symbol, short_period, long_period, strategy_name)
Generate a double moving average strategy
**Parameters:**
- `symbol` (str): Target stock code
- `short_period` (int): Short-term moving average period
- `long_period` (int): Long-term moving average period
- `strategy_name` (str, optional): Strategy name
**Returns:**
- `str`: Strategy generation and backtesting results
## 🔍 Common Issues
### Q: What if the XTQuant connection fails?
A: Make sure the QMT client is started and logged in, and check whether the `QMT_PATH` configuration is correct.
### Q: How to modify risk control parameters?
A: Modify parameters such as `MAX_ORDER_VALUE` and `MAX_POSITION_VALUE` in the `.env` file.
### Q: Inaccurate strategy backtesting data?
A: Check the data date range and ensure that XTQuant has the corresponding historical data permissions.
### Q: How to add new technical indicators?
A: Create a new strategy module in the `src/strategies/` directory, referring to the implementation of `ma_strategy.py`.
## 📄 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
## 🤝 Contribution
Welcome to submit Issues and Pull Requests to improve the project!
## 📞 Contact Information
- Project Address: https://github.com/guangxiangdebizi/QMT-MCP
- Issue Feedback: https://github.com/guangxiangdebizi/QMT-MCP/issues
- Documentation: https://github.com/guangxiangdebizi/QMT-MCP/wiki
- Email: guangxiangdebizi@gmail.com
- LinkedIn: https://www.linkedin.com/in/%E6%98%9F%E5%AE%87-%E9%99%88-b5b3b0313/
---
<div align="center">
**🌟 If this project helps you, please give it a Star to support it! 🌟**
</div>
Connection Info
You Might Also Like
valuecell
Valuecell is a Python project for efficient data management.
hexstrike-ai
HexStrike AI is an AI-powered MCP cybersecurity automation platform with 150+ tools.
AP2
AP2 provides code samples and demos for the Agent Payments Protocol.
YC-Killer
YC-Killer is an AI agents library by Singularity Research, open-sourcing...
solana-agent-kit
An open-source toolkit for AI agents to interact with Solana protocols.
mcp-server
MCP Server provides access to stock market data and financial statements.