miniqmt

GitHub 作者 LeoYeAI/openclaw-master-skills v1.2.0

miniQMT 极简量化交易终端 - 支持外接Python获取行情数据和程序化交易,基于xtquant SDK。

安装 / 下载方式

TotalClaw CLI推荐
totalclaw install github:LeoYeAI~openclaw-master-skills~miniqmt
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/github%3ALeoYeAI~openclaw-master-skills~miniqmt/file -o miniqmt.md
# miniQMT(迅投极简量化交易终端)

miniQMT 是迅投科技开发的轻量级量化交易终端,专为外接Python设计。它作为本地Windows服务运行,通过 [XtQuant](http://dict.thinktrader.net/nativeApi/start_now.html) Python SDK(`xtdata` + `xttrade`)提供行情数据和交易功能。

> ⚠️ **需要券商开通miniQMT权限**。联系您的证券公司开通。多家国内券商支持(国金、华鑫、中泰、东方财富、国信、方正等)。

## miniQMT 概述

- **轻量级QMT客户端**,在Windows上作为后台服务运行
- 为外部Python程序提供**行情数据服务** + **交易服务**
- Python脚本通过 `xtquant` SDK经本地TCP连接(xtdata获取行情,xttrade执行交易)
- 支持品种:A股、ETF、可转债、期货、期权、融资融券
- 部分券商提供免费的 **Level 2数据**

## 架构

```
Python脚本(任意IDE: VS Code, PyCharm, Jupyter等)
    ↓ xtquant SDK(pip install xtquant)
    ├── xtdata  ──TCP──→ miniQMT(行情数据服务)
    └── xttrade ──TCP──→ miniQMT(交易服务)
                              ↓
                    券商交易系统
```

## 如何获取 miniQMT

1. 在支持QMT的券商开立证券账户
2. 申请miniQMT权限(部分券商要求最低资产,如5万-10万元)
3. 从券商处下载安装QMT客户端
4. 以miniQMT模式(极简模式)启动并登录

## 使用流程

### 1. 启动 miniQMT

以极简模式启动QMT客户端并登录。miniQMT界面非常简洁——只有一个登录窗口。

### 2. 安装 xtquant

```bash
pip install xtquant
```

### 3. 使用Python连接行情数据

```python
from xtquant import xtdata

# 连接本地miniQMT行情数据服务
xtdata.connect()

# 下载历史数据(首次访问前必须下载)
xtdata.download_history_data('000001.SZ', '1d', start_time='20240101', end_time='20240630')

# 获取K线数据(返回以股票代码为键的DataFrame字典)
data = xtdata.get_market_data_ex(
    [], ['000001.SZ'], period='1d',
    start_time='20240101', end_time='20240630',
    dividend_type='front'  # 前复权
)
print(data['000001.SZ'].tail())
```

### 4. 使用Python连接交易服务

```python
from xtquant import xtconstant
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from xtquant.xttype import StockAccount

# path必须指向QMT安装目录下的userdata_mini文件夹
path = r'D:\券商QMT\userdata_mini'
# session_id对每个策略/脚本必须唯一
session_id = 123456
xt_trader = XtQuantTrader(path, session_id)

# 注册回调接收实时推送通知
class MyCallback(XtQuantTraderCallback):
    def on_disconnected(self):
        print('已断开连接 — 需要重新连接')
    def on_stock_order(self, order):
        print(f'Order update: {order.stock_code} status={order.order_status} msg={order.status_msg}')
    def on_stock_trade(self, trade):
        print(f'Trade filled: {trade.stock_code} {trade.traded_volume}@{trade.traded_price}')
    def on_order_error(self, order_error):
        print(f'Order error: {order_error.error_msg}')

xt_trader.register_callback(MyCallback())
xt_trader.start()
connect_result = xt_trader.connect()  # 收益率 0 on success, non-zero on failure

account = StockAccount('your_account')
xt_trader.subscribe(account)  # 订阅账户推送通知

# 下买入单
order_id = xt_trader.order_stock(
    account, '000001.SZ', xtconstant.STOCK_BUY, 100,
    xtconstant.FIX_PRICE, 11.50, 'my_strategy', 'test_order'
)
# order_id > 0 表示成功,-1 表示失败
```

---

## miniQMT 与完整版 QMT 对比

| 特性 | miniQMT | QMT(完整版) |
|---|---|---|
| **Python** | 外接Python(任意版本) | 内置Python(版本受限) |
| **IDE** | 任意(VS Code, PyCharm, Jupyter等) | 仅内置编辑器 |
| **第三方库** | 所有pip包(pandas, numpy等) | 仅内置库 |
| **界面** | 极简(仅登录窗口) | 完整交易UI + 图表 |
| **行情数据** | 通过xtdata API | 内置 + xtdata API |
| **交易** | 通过xttrade API | 内置 + xttrade API |
| **资源占用** | 轻量(~50 MB内存) | 较重(完整GUI,~500 MB+) |
| **调试** | 完整IDE调试支持 | 有限 |
| **使用场景** | 自动化策略、外部集成 | 可视化分析 + 手动交易 |
| **连接方式** | 一次性连接,无自动重连 | 持久连接 |

---

## 数据能力(通过xtdata)

| 类别 | 详情 |
|---|---|
| **K-line** | tick, 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1mon — supports adjustment (forward / backward / proportional) |
| **Tick** | Real-time tick data with 5-level bid/ask, volume, turnover, trade count |
| **Level 2** | l2quote (real-time snapshot), l2order (order-by-order), l2transaction (trade-by-trade), l2quoteaux (aggregate buy/sell), l2orderqueue (order queue), l2thousand (1000-level order book), fullspeedorderbook (full-speed 20-level) |
| **Financials** | Balance sheet, income statement, cash flow statement, per-share metrics, share structure, top 10 shareholders / free-float holders, shareholder count |
| **Reference** | Trading calendar, holidays, sector lists, index constituents & weights, ex-dividend data, contract info |
| **Real-time** | Single-stock subscription (`subscribe_quote`), market-wide push (`subscribe_whole_quote`) |
| **Special** | Convertible bond info, IPO subscription data, ETF creation/redemption lists, announcements & news, consecutive limit-up tracking, snapshot indicators (volume ratio / price velocity), high-frequency IOPV |

### 数据访问模式

```
download_history_data() → get_market_data_ex()  # Historical data: download to local cache first, then read from cache
subscribe_quote()       → callback               # Real-time data: subscribe and receive via callback
get_full_tick()                                   # Snapshot data: get latest tick for the entire market
```

## 交易能力(通过xttrade)

| 类别 | 操作 |
|---|---|
| **Stocks** | Buy/sell (sync and async), limit/market/best price orders |
| **ETF** | Buy/sell, creation/redemption |
| **Convertible bonds** | Buy/sell |
| **Futures** | Open long/close long/open short/close short |
| **Options** | Buy/sell open/close, covered open/close, exercise, lock/unlock |
| **Margin trading** | Margin buy, short sell, buy to cover, direct return, sell to repay, direct repayment, special margin/short |
| **IPO** | New share/bond subscription, query subscription quota |
| **Cancel** | Cancel by order_id or broker contract number (sync and async) |
| **Query** | Assets, orders, trades, positions, futures position summary |
| **Credit query** | Credit assets, liability contracts, margin-eligible securities, available-to-short data, collateral |
| **Bank-broker transfer** | Bank to securities, securities to bank (sync and async) |
| **Smart algorithms** | VWAP and other algorithmic execution |
| **Securities lending** | Query available securities, apply for lending, manage contracts |

### 账户类型

```python
StockAccount('id')            # 普通股票账户
StockAccount('id', 'CREDIT')  # 信用账户(融资融券)
StockAccount('id', 'FUTURE')  # 期货账户
```

### 关键交易回调

| 回调函数 | 触发时机 |
|---|---|
| `on_stock_order(order)` | Order status change (submitted, partially filled, fully filled, cancelled, rejected) |
| `on_stock_trade(trade)` | Trade execution report |
| `on_stock_position(position)` | Position change |
| `on_stock_asset(asset)` | Asset/fund change |
| `on_order_error(error)` | Order placement failure |
| `on_cancel_error(error)` | Order cancellation failure |
| `on_disconnected()` | Disconnected from miniQMT |

### 订单状态码

| 值 | 状态 |
|---|---|
| 48 | 未报 |
| 50 | 已报 |
| 54 | 已撤 |
| 55 | 部分成交 |
| 56 | 已成 |
| 57 | 废单 |

---

## 常见券商路径

```python
# 国金证券
path = r'D:\国金证券QMT交易端\userdata_mini'
# 华鑫证券
path = r'D:\华鑫证券\userdata_mini'
# 中泰证券
path = r'D:\中泰证券\userdata_mini'
# 东方财富
path = r'D:\东方财富证券QMT交易端\userdata_mini'
```

## 股票代码格式

| 市场 | 示例 |
|---|---|
| 上海A股 | `600000.SH` |
| 深圳A股 | `000001.SZ` |
| 北交所 | `430047.BJ` |
| 指数 | `000001.SH`(上证综指), `399001.SZ`(深证成指) |
| 中金所期货 | `IF2401.IF` |
| 上期所期货 | `ag2407.SF` |
| 期权 | `10004358.SHO` |
| ETF | `510300.SH` |
| 可转债 | `113050.SH` |

---

## 完整示例:行情数据 + 交易策略

```python
from xtquant import xtdata, xtconstant
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from xtquant.xttype import StockAccount

# === 回调类定义 ===
class MyCallback(XtQuantTraderCallback):
    def on_disconnected(self):
        print('已断开连接')
    def on_stock_trade(self, trade):
        print(f'Trade filled: {trade.stock_code} {trade.traded_volume}@{trade.traded_price}')
    def on_order_error(self, order_error):
        print(f'Error: {order_error.error_msg}')

# === 1. 连接行情数据服务 ===
xtdata.connect()

# === 2. 下载并获取历史数据 ===
stock = '000001.SZ'
xtdata.download_history_data(stock, '1d', start_time='20240101', end_time='20240630')
data = xtdata.get_market_data_ex(
    [], [stock], period='1d',
    start_time='20240101', end_time='20240630',
    dividend_type='front'  # 前复权
)
df = data[stock]

# === 3. 计算简单均线交叉信号 ===
df['ma5'] = df['close'].rolling(5).mean()    # 5日均线
df['ma20'] = df['close'].rolling(20).mean()  # 20日均线
latest = df.iloc[-1]   # 最新K线
prev = df.iloc[-2]     # 前一根K线

# === 4. 连接交易服务 ===
path = r'D:\券商QMT\userdata_mini'
xt_trader = XtQuantTrader(path, 123456)
xt_trader.register_callback(MyCallback())
xt_