Content
# Tool List
<div align="center">



A modular quantitative trading system based on FastMCP and XTQuant, providing intelligent strategy generation, real-time trading execution, and backtesting analysis.
</div>
## 🌟 Project Features
- **🔗 MCP Protocol Integration**: Based on Model Context Protocol, seamlessly connected to AI assistants
- **📈 Intelligent Strategy Generation**: Automatically generate and optimize quantitative trading strategies
- **⚡ Real-time Trading Execution**: Supports XTQuant/QMT live trading 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 mechanism
## 🎬 Demo Video
> 📺 Click the cover or link to watch the full demo on Bilibili
>
> https://www.bilibili.com/video/BV1SFGjz6EKN/?vd_source=26053b834f0ddd4f57b22169d74b6f78
<!-- If you have a demo cover image, replace docs/demo_cover.png with your image path -->
[](https://www.bilibili.com/video/BV1SFGjz6EKN/?vd_source=26053b834f0ddd4f57b22169d74b6f78)
## 🏗️ System Architecture
```
QMT-MCP/
├── main.py # FastMCP server main entry
├── config.json # System configuration file
├── requirements.txt # Project dependencies
├── src/
│ ├── config.py # Configuration management module (supports environment variables)
│ ├── tools/ # MCP tool implementations
│ │ ├── trading_tool.py # Trading execution tool
│ │ └── qmt_tool.py # QMT strategy tool
│ ├── strategies/ # Strategy module
│ │ ├── ma_strategy.py # Dual moving average strategy
│ │ └── strategy_generator.py # Strategy generator
│ └── utils/ # Utility module
│ ├── xtquant_client.py # XTQuant client
│ └── data_handler.py # Data processor
└── logs/ # Log file directory
```
## 🚀 Quick Start
### Environment Requirements
- **Python 3.8+**
- **XTQuant/QMT Client** (Guosen/QMT quantitative trading client)
- **Windows System** (XTQuant only supports Windows)
### Installation Steps
1. **Clone the project**
```bash
git clone <repository-url>
cd QMT-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 Environment Configuration File
# Please modify the following configuration parameters according to your actual environment
# =====================================================
# Server configuration
QUANTMCP_HOST=127.0.0.1 # MCP server listening address, usually keep 127.0.0.1
QUANTMCP_PORT=8000 # MCP server port number, can be modified as needed
QUANTMCP_TRANSPORT=sse # Transport protocol, keep sse
# XTQuant/QMT trading client configuration
# Important: Please modify to your QMT installation path and account information
QMT_PATH=Your QMT installation path\userdata_mini # QMT client data directory, such as: D:\QMT\userdata_mini
QMT_SESSION_ID=Your session ID # QMT session ID, integer, such as: 12345
QMT_ACCOUNT_ID=Your trading account ID # Your simulated or live trading account ID
# QMT strategy save directory
QMT_STRATEGY_DIR=Your QMT strategy directory\mpython # QMT strategy file save directory, such as: D:\QMT\mpython
# Trading risk control configuration
MAX_ORDER_VALUE=100000.0 # Maximum single order amount (yuan), prevent accidental large orders
MAX_POSITION_VALUE=500000.0 # Maximum single stock position amount (yuan), control single stock risk
MIN_ORDER_QUANTITY=100 # Minimum order quantity (shares), usually a multiple of 100
MARKET_ORDER_SPREAD=0.1 # Market order price difference ratio (0.1=10%), avoid large price deviation
# Strategy default parameters configuration
DEFAULT_SYMBOL=000001.SZ # Default stock code, used for testing and demonstration
DEFAULT_START_DATE=20240101 # Default backtest start date, format YYYYMMDD
DEFAULT_END_DATE=20241201 # Default backtest end date, format YYYYMMDD
DEFAULT_SHORT_PERIOD=5 # Default short-term moving average days
DEFAULT_LONG_PERIOD=20 # Default long-term moving average days
# Log configuration
LOG_LEVEL=INFO # Log level: DEBUG/INFO/WARNING/ERROR
LOG_FILE=logs/quantmcp.log # Log file path
```
4. **Start XTQuant client**
- Open Guosen QMT or XTQuant quantitative trading client
- Ensure the client is logged in and connected
5. **Start QMT-MCP service**
```bash
python main.py
```
The service will provide MCP service at `http://127.0.0.1:8000`.
## 🔧 Function Introduction
### Trading Tool
#### Order placement
```python
# Call through MCP interface
place_order(
symbol="000001.SZ", # Stock code
quantity=100, # Buy shares
price=10.5, # Order price
direction="BUY" # Trading direction
)
```
#### Cancel order
```python
cancel_order(order_id="12345") # Cancel specified order
```
### Strategy Generation
#### Dual moving average strategy
```python
generate_ma_strategy(
symbol="000001.SZ", # Target stock
short_period=5, # Short-term moving average
long_period=20, # Long-term moving average
strategy_name="my_ma" # Strategy name
)
```
#### Custom strategy
```python
save_qmt_strategy(
strategy_name="custom_strategy",
code="""
def init(context):
# Strategy initialization
pass
def handle_bar(context, bar_dict):
# Strategy execution logic
pass
"""
)
```
## 📊 Strategy Backtesting
The system provides complete strategy backtesting, including:
- **Return indicators**: Total return, annualized return, Sharpe ratio
- **Risk indicators**: Maximum drawdown, volatility, VaR
- **Trading statistics**: Number of trades, win rate, average profit and loss
- **Performance evaluation**: Strategy rating and optimization suggestions
### Backtest report example
```
[OK] Dual moving average strategy generation successful!
[DATA] Stock information: 000001.SZ
[DATE] Data period: 20240101 to 20241201
[CHART] Data count: 242
[DATA] Trading days: 242 days
[TARGET] Dual moving average strategy parameters:
* Short-term moving average: 5 days
* Long-term moving average: 20 days
[CHART] Strategy performance:
* Total return: 15.23%
* Annualized return: 18.45%
* Maximum drawdown: -8.67%
* Annualized volatility: 22.15%
* Sharpe ratio: 0.845
* Number of trades: 24
* Win rate: 58.33%
[TIP] Strategy evaluation:
[OK] Annualized return is good, above 15%
[OK] Risk control is excellent, maximum drawdown less than 10%
[WARNING] Sharpe ratio is general, return-risk ratio needs to be improved
[OK] Win rate is good, above 50%
```
## 🛡️ Risk Control
The system has built-in multi-layer risk control mechanisms:
### Trading level
- Maximum single order amount limit
- Maximum single stock position limit
- 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 state control
- Connection state monitoring
- Exception handling mechanism
- Log record tracking
## 🔌 MCP Integration
QMT-MCP is fully compatible with Model Context Protocol and can be integrated with MCP-supported AI assistants:
### First choice: SSE direct connection configuration (recommended)
If you only need to **directly connect** to the already started 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 dependency**: The client does not need to execute Python/Node commands.
> - ⚡ **Ready to use**: The server can be discovered by any MCP-supported application after startup.
> - 🪶 **Minimal configuration**: Only `type` and `url` are required.
> - 🌐 **Remote-friendly**: Modify `url` to access in LAN/cloud server.
## 📋 Configuration Description
### Core configuration items
| Configuration item | Description | Default value |
|--------|------|--------|
| QMT_PATH | QMT client installation path | Your QMT installation path\userdata_mini |
| QMT_SESSION_ID | QMT session ID | Your session ID |
| QMT_ACCOUNT_ID | Trading account ID | Your trading account ID |
| MAX_ORDER_VALUE | Maximum single order amount | 100000.0 |
| MAX_POSITION_VALUE | Maximum single stock position | 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 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 new tool
1. Create a tool module in the `src/tools/` directory
2. Implement the tool class and related methods
3. Register the new tool 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 stock trading order
**Parameters:**
- `symbol` (str): Stock code, such as "000001.SZ"
- `quantity` (int): Trading quantity, must be a 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 dual 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
## 🔍 FAQ
### Q: XTQuant connection failed, what should I do?
A: Ensure the QMT client is started and logged in, and check if the `QMT_PATH` configuration is correct.
### Q: How to modify risk control parameters?
A: Modify `MAX_ORDER_VALUE`, `MAX_POSITION_VALUE` and other parameters in the `.env` file.
### Q: Strategy backtesting data is not accurate?
A: Check the data date range and ensure XTQuant has corresponding historical data permissions.
### Q: How to add new technical indicators?
A: Create a new strategy module in the `src/strategies/` directory, refer to the implementation of `ma_strategy.py`.
## 📄 License
This project uses the MIT License - see [LICENSE](LICENSE) file
## 🤝 Contribution
Welcome to submit issues and pull requests to improve the project!
## 📞 Contact
- 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! 🌟**
</div>
Connection Info
You Might Also Like
Vibe-Trading
Vibe-Trading: Your Personal Trading Agent
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.
mcp-linker
MCP Linker enables one-click addition and sync of MCP servers across AI clients.
mcp-store
add Model Context Protocol (MCP) server to your mcp client (claude cursor)...
computer-use-mcp
A local MCP server for Claude to control your computer easily.