chore: init qmt_bridge repo (HTTP+WS bridge, MCP endpoint, docs, references)
This commit is contained in:
@@ -0,0 +1,346 @@
|
||||
---
|
||||
name: qmt-trader
|
||||
description: "通过统一 CLI 脚本驱动大 QMT 迅投量化交易端的全部能力,含实时行情查询、K线历史数据、账户资产与持仓查询、委托与成交查询、买入卖出下单、撤单、板块龙虎榜北向资金财务数据等,并内置 xtquant_big_convert 桥接服务的安装部署引导(装包/同步 QMT 端文件/配置/启动验证/排错)。适用于大模型辅助量化交易分析、行情研判、持仓监控、半自动下单等场景。当用户需要查看股票行情、分析K线、查询持仓资产、查看今日委托成交、下单买卖、撤单、查询北向资金龙虎榜财务数据,或需要安装部署 QMT RPC 桥接服务时触发此 skill。"
|
||||
---
|
||||
|
||||
# QMT Trader — 大模型驱动的 QMT 交易/行情工具
|
||||
|
||||
## 概述
|
||||
|
||||
本 skill 提供一个确定性 CLI 脚本 `scripts/qmt.py`,让大模型通过命令行调用大 QMT 的全部
|
||||
交易与行情能力,避免每次现场写 Python 代码。所有命令默认输出 JSON(便于解析),加 `--table`
|
||||
切换人类可读表格。
|
||||
|
||||
**前置条件**:本 skill 依赖 xtquant_big_convert 桥接服务已部署运行。若 `ping` 失败或用户尚未部署,
|
||||
先按下文「首次部署」引导完成:装包 → 同步 QMT 端文件 → 写配置 → QMT 里运行入口 → 验证。
|
||||
|
||||
## 首次部署(只需一次,AI 逐步引导用户完成)
|
||||
|
||||
部署分两端:**客户端**(跑本 skill/策略的开发机)和**服务端**(大 QMT 客户端内置 Python)。
|
||||
|
||||
### 第 1 步:客户端安装包
|
||||
|
||||
```bash
|
||||
pip install "xtquant-big-convert[redis]" # redis 传输(默认,推荐)
|
||||
# 或 zmq 同机低延迟:pip install xtquant-big-convert(基础版已含 pyzmq)
|
||||
```
|
||||
|
||||
> 没发布到 PyPI 的私有 fork 用源码安装:`git clone <repo> && cd xtquant_big_convert && pip install -e .[redis]`
|
||||
|
||||
### 第 2 步:把服务端文件同步到 QMT 的 python 目录
|
||||
|
||||
需要拷 4 项到大 QMT 的 `python` 目录(如 `D:\国金证券QMT交易端\python\`):
|
||||
|
||||
```
|
||||
bigqmt_signal_trader/ (整个包,pip 装的在 site-packages 里)
|
||||
bigqmt_signal_trader_strategy.py
|
||||
bigqmt_signal_trader_redis_rpc_runtime.py
|
||||
BIGQMT_REDIS_DRYRUN.py (★ QMT 编辑器入口,GBK 编码)
|
||||
```
|
||||
|
||||
pip 安装后的文件位置可以用这条命令定位(输出目录里就有全部 4 项):
|
||||
|
||||
```bash
|
||||
python -c "import bigqmt_signal_trader_strategy as m, os; print(os.path.dirname(m.__file__))"
|
||||
```
|
||||
|
||||
> QMT 沙箱若拒绝 `import redis`(部分券商白名单拦截),改用仓库里的 `bigqmt_no_redis/` 无 redis 版本(自包含 ZMQ 传输)。
|
||||
|
||||
### 第 3 步:创建 QMT 端私有配置
|
||||
|
||||
在 QMT 的 `python` 目录创建 `bigqmt_signal_trader_local_config.py`(含账号密码,**不要提交 git**):
|
||||
|
||||
```python
|
||||
# coding: utf-8
|
||||
BIGQMT_ACCOUNT_ID = "资金账号"
|
||||
BIGQMT_REDIS_CONFIG = {
|
||||
"host": "Redis地址", "port": 6379, "db": 5, "password": "Redis密码",
|
||||
"rpc_allow_order_methods": False, # 下单开关,默认关闭;确认风控后改 True
|
||||
"rpc_process_in_listener": True,
|
||||
"rpc_listener_methods": ("*",),
|
||||
"rpc_background_threads": False, # 若切 zmq/mysql 传输必须改 True
|
||||
"schedule_adjust": True,
|
||||
"schedule_adjust_interval": "500nMilliSecond",
|
||||
}
|
||||
```
|
||||
|
||||
> 切 zmq:配置里加 `"transport": "zmq"` 并把 `rpc_background_threads` 改 `True`(QMT 端需装 pyzmq 19.0.2,Python 3.6 最后支持的版本)。
|
||||
|
||||
### 第 4 步:在 QMT 策略编辑器运行入口
|
||||
|
||||
QMT 策略编辑器里**只加载运行 `BIGQMT_REDIS_DRYRUN.py` 一个文件**(它自动 import 其余模块)。
|
||||
若 QMT 装在非默认路径且用 exec 方式加载,需改文件里 `_known_qmt_python_dir()` 的 fallback 路径。
|
||||
|
||||
启动成功标志(QMT 输出面板):
|
||||
|
||||
```
|
||||
[bigqmt_shell] local redis config loaded keys=[...]
|
||||
[bigqmt_shell] local account config loaded=True
|
||||
[bigqmt_rpc] started channel=bigqmt:rpc:req:你的账号
|
||||
[bigqmt_signal_trader] init ok
|
||||
```
|
||||
|
||||
### 第 5 步:客户端配置 + 验证
|
||||
|
||||
客户端用环境变量(或 `bigqmt_signal_trader_client_config.py`)指向同一套 Redis/账号:
|
||||
|
||||
```powershell
|
||||
$env:BIGQMT_ACCOUNT_ID="资金账号"
|
||||
$env:BIGQMT_REDIS_HOST="Redis地址"; $env:BIGQMT_REDIS_PORT="6379"
|
||||
$env:BIGQMT_REDIS_DB="5"; $env:BIGQMT_REDIS_PASSWORD="Redis密码"
|
||||
```
|
||||
|
||||
然后验证(redis ~13ms / zmq ~0.7ms 为正常):
|
||||
|
||||
```bash
|
||||
python scripts/qmt.py ping
|
||||
```
|
||||
|
||||
### 部署排错速查
|
||||
|
||||
| 现象 | 排查 |
|
||||
|------|------|
|
||||
| `ping` 超时 | 客户端/服务端 transport 不一致(一边 redis 一边 zmq);QMT 端服务没启动;Redis 地址/密码/db 不一致 |
|
||||
| QMT 面板报 `import redis` 被拒 | 换 `bigqmt_no_redis/` 无 redis 版本 |
|
||||
| 启动了但查询全空 | 账号没对上:服务端 `BIGQMT_ACCOUNT_ID` vs 客户端 `BIGQMT_ACCOUNT_ID`;QMT 需在实盘模式 |
|
||||
| 下单报 `ORDER_DISABLED` | 正常保护,服务端配置 `rpc_allow_order_methods` 改 `True` 才放行 |
|
||||
| 详细错误日志 | QMT python 目录下 `logs/bigqmt_*.log`(保留 7 天),排错首选 |
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 第 0 步:确认连通性
|
||||
|
||||
```bash
|
||||
python scripts/qmt.py ping
|
||||
```
|
||||
|
||||
返回 `ok: true` 且 `latency_ms` 合理(redis ~13ms / zmq ~0.7ms)即表示服务端就绪。
|
||||
|
||||
### 第 1 步:一键快照(资产+持仓+委托+成交)
|
||||
|
||||
```bash
|
||||
python scripts/qmt.py snapshot
|
||||
```
|
||||
|
||||
一次 RPC 往返返回账户全景,适合快速了解当前状态。
|
||||
|
||||
## 命令速查
|
||||
|
||||
### 行情分析
|
||||
|
||||
| 命令 | 用途 | 示例 |
|
||||
|------|------|------|
|
||||
| `tick <codes...>` | 实时五档盘口 | `tick 600000.SH 000001.SZ` |
|
||||
| `kline <code>` | K线/历史行情 | `kline 600000.SH --period 1d --count 60 --dividend front` |
|
||||
| `instrument <code>` | 合约详情 | `instrument 600000.SH` |
|
||||
| `sector [name]` | 板块成分股/板块列表 | `sector "沪深A股"` |
|
||||
| `trading-dates` | 交易日历 | `trading-dates --count 10` |
|
||||
| `north` | 北向资金 | `north --period 1d` |
|
||||
| `longhubang <code>` | 龙虎榜 | `longhubang 600000.SH --count 5` |
|
||||
| `financial <codes...>` | 财务数据 | `financial 000001.SZ --tables Capital.CAPITAL` |
|
||||
| `download <codes...>` | 下载历史数据 | `download 600654.SH --period 1d --dividend front` |
|
||||
| `quote-subscribe <codes...>` | 实时全推订阅 | `quote-subscribe SH SZ --max 10` |
|
||||
|
||||
### 账户/持仓/委托
|
||||
|
||||
| 命令 | 用途 | 示例 |
|
||||
|------|------|------|
|
||||
| `account` | 账户资产 | `account` |
|
||||
| `positions [code]` | 持仓列表 | `positions` / `positions 600000.SH` |
|
||||
| `orders` | 今日委托 | `orders --cancelable` |
|
||||
| `trades` | 今日成交 | `trades` |
|
||||
| `snapshot` | 一键全景 | `snapshot` |
|
||||
|
||||
### 下单/撤单
|
||||
|
||||
| 命令 | 用途 | 示例 |
|
||||
|------|------|------|
|
||||
| `buy <code> <volume>` | 买入 | `buy 600000.SH 100 --price 7.50` |
|
||||
| `sell <code> <volume>` | 卖出 | `sell 600000.SH 100 --price 7.50` |
|
||||
| `cancel <order_id>` | 撤单 | `cancel 12345 --market SH` |
|
||||
|
||||
> 下单命令支持 `--dry-run`(只打印不下单)、`--latest`(最新价)、`--strategy`、`--remark`。
|
||||
|
||||
### 扩展查询(高频)
|
||||
|
||||
| 命令 | 用途 | 示例 |
|
||||
|------|------|------|
|
||||
| `holiday` | 节假日列表 | `holiday` |
|
||||
| `stock-name <code>` | 股票名称 | `stock-name 600000.SH` |
|
||||
| `instrument-type <code>` | 品种类型 | `instrument-type 600000.SH` |
|
||||
| `divid-factors <code>` | 除权除息因子 | `divid-factors 600000.SH` |
|
||||
| `market-times [market]` | 日内交易时段 | `market-times SH` |
|
||||
| `trading-calendar [market]` | 交易日历(含时段) | `trading-calendar SH` |
|
||||
| `option-list <code>` | 期权列表 | `option-list 510050.SH` |
|
||||
| `bsm-price ...` | BSM 期权定价 | `bsm-price C 3.0 2.8 0.03 0.3 30` |
|
||||
| `bsm-iv ...` | BSM 隐含波动率 | `bsm-iv C 3.0 2.8 0.25 0.03 30` |
|
||||
| `hkt-stats <code>` | 港股通统计 | `hkt-stats 600000.SH` |
|
||||
| `hkt-details <code>` | 港股通明细 | `hkt-details 600000.SH` |
|
||||
| `hkt-rate` | 港股通汇率 | `hkt-rate` |
|
||||
| `top10-holder <code>` | 十大股东 | `top10-holder 600000.SH` |
|
||||
| `holder-num <code>` | 股东户数 | `holder-num 600000.SH` |
|
||||
| `ipo` / `ipo-limit` | 新股数据/申购额度 | `ipo` |
|
||||
| `credit-assure` | 融资担保品合约 | `credit-assure` |
|
||||
| `credit-short` | 融券标的合约 | `credit-short` |
|
||||
| `credit-debt` | 负债合约 | `credit-debt` |
|
||||
| `his-st <code>` | 历史 ST 数据 | `his-st 600000.SH` |
|
||||
| `index-weight <index>` | 指数权重 | `index-weight 000300.SH` |
|
||||
| `industry <name>` | 行业成分 | `industry 银行` |
|
||||
| `sector-info [name]` | 板块详情 | `sector-info 沪深A股` |
|
||||
| `local-data <code>` | 本地缓存数据 | `local-data 600000.SH` |
|
||||
| `timetag2dt <ms>` | 毫秒时间戳转日期 | `timetag2dt 1751353200000` |
|
||||
| `dt2timetag <dt>` | 日期转毫秒时间戳 | `dt2timetag 20250701150000` |
|
||||
|
||||
### 通用 RPC(兜底所有方法)
|
||||
|
||||
`rpc <method> [json_params]` 可调用**任意白名单方法**(含未列出的,如 `get_l2_quote` / `call_formula` / `get_raw_financial_data` 等):
|
||||
|
||||
```bash
|
||||
python scripts/qmt.py rpc get_holidays
|
||||
python scripts/qmt.py rpc get_stock_name '{"stock":"600000.SH"}'
|
||||
python scripts/qmt.py rpc get_l2_quote '{"stock_code":"600000.SH","count":5}'
|
||||
python scripts/qmt.py rpc call_formula '{"formula_name":"MA","stock_code":"600000.SH","period":"1d"}'
|
||||
```
|
||||
|
||||
## 典型工作流
|
||||
|
||||
### 场景一:行情分析
|
||||
|
||||
分析某只股票的技术面:
|
||||
|
||||
```bash
|
||||
# 1. 看实时盘口
|
||||
python scripts/qmt.py tick 600000.SH
|
||||
|
||||
# 2. 拉最近 60 根日 K(前复权),输出含 MA5/MA20/MA60 统计
|
||||
python scripts/qmt.py kline 600000.SH --period 1d --count 60 --dividend front
|
||||
|
||||
# 3. 看合约详情(名称、上市日、最小变动价位等)
|
||||
python scripts/qmt.py instrument 600000.SH
|
||||
|
||||
# 4. 看近期龙虎榜
|
||||
python scripts/qmt.py longhubang 600000.SH --count 5
|
||||
```
|
||||
|
||||
### 场景二:持仓监控
|
||||
|
||||
```bash
|
||||
# 一键看全景
|
||||
python scripts/qmt.py snapshot
|
||||
|
||||
# 只看持仓(含浮动盈亏)
|
||||
python scripts/qmt.py positions
|
||||
|
||||
# 看可撤委托
|
||||
python scripts/qmt.py orders --cancelable
|
||||
```
|
||||
|
||||
### 场景三:下单交易
|
||||
|
||||
```bash
|
||||
# 0. 先看当前价
|
||||
python scripts/qmt.py tick 600000.SH
|
||||
|
||||
# 1. 干跑确认参数
|
||||
python scripts/qmt.py buy 600000.SH 100 --price 7.50 --dry-run
|
||||
|
||||
# 2. 真实下单(限价 7.50 买 100 股)
|
||||
python scripts/qmt.py buy 600000.SH 100 --price 7.50 --strategy my_strat
|
||||
|
||||
# 3. 确认委托进了系统
|
||||
python scripts/qmt.py orders
|
||||
|
||||
# 4. 需要时撤单
|
||||
python scripts/qmt.py cancel <order_sysid> --market SH
|
||||
```
|
||||
|
||||
### 场景四:批量行情分析
|
||||
|
||||
```bash
|
||||
# 同时看多只股票的盘口
|
||||
python scripts/qmt.py tick 600000.SH 000001.SZ 600519.SH
|
||||
|
||||
# 看板块成分股
|
||||
python scripts/qmt.py sector "沪深A股"
|
||||
|
||||
# 看北向资金流向
|
||||
python scripts/qmt.py north
|
||||
```
|
||||
|
||||
## 安全须知
|
||||
|
||||
1. **下单默认关闭**:服务端 `rpc_allow_order_methods` 默认 `False`。必须由人工在服务端配置中
|
||||
显式开启后才能下单,否则 `buy`/`sell`/`cancel` 会报 `ORDER_DISABLED` 错误。
|
||||
|
||||
2. **下单前先看价**:始终先用 `tick` 确认当前价格,避免下出明显不合理的委托。
|
||||
|
||||
3. **超时防重复**:如果 `buy`/`sell` 报 `ORDER_TIMEOUT`,委托可能已提交。**先用 `orders` 查询确认**,
|
||||
不要直接重试,避免重复下单。
|
||||
|
||||
4. **strategy_name 一致性**:下单时的 `--strategy` 和查询时的 `--strategy` 必须一致。
|
||||
查全部委托用 `orders --strategy ""`(空字符串=不过滤)。
|
||||
|
||||
5. **实盘模式**:QMT 必须运行在实盘模式(非模拟/模型交易)才能收到完整回报。
|
||||
|
||||
## 脚本说明
|
||||
|
||||
### scripts/qmt.py
|
||||
|
||||
统一 CLI 入口,包含以下子命令:
|
||||
|
||||
**基础查询**:
|
||||
- `ping` — 连通性检测(含延迟测量)
|
||||
- `account` — 查询账户资产(现金/冻结/总资产/市值)
|
||||
- `positions [code]` — 查询持仓(含浮动盈亏计算)
|
||||
- `orders [--cancelable] [--strategy ""]` — 查询今日委托(含语义化状态名)
|
||||
- `trades [--strategy ""]` — 查询今日成交
|
||||
- `snapshot` — 一键全景(资产+持仓+委托+成交)
|
||||
|
||||
**行情**:
|
||||
- `tick <codes...>` — 实时五档盘口(含涨跌幅计算)
|
||||
- `kline <code> [--period 1d] [--count N] [--dividend front]` — K线(含 MA5/20/60 统计)
|
||||
- `instrument <code>` — 合约详情
|
||||
- `sector [name]` — 板块成分股/板块列表
|
||||
- `trading-dates [--count N]` — 交易日历
|
||||
- `north [--period 1d]` — 北向资金
|
||||
- `longhubang <code> [--count N]` — 龙虎榜
|
||||
- `financial <codes...> [--tables T1,T2]` — 财务数据
|
||||
- `download <codes...>` — 下载历史数据到服务端
|
||||
- `quote-subscribe <codes...> [--max N] [--timeout S]` — 实时全推行情订阅
|
||||
|
||||
**扩展查询**:
|
||||
- `holiday` — 节假日列表
|
||||
- `stock-name <code>` — 股票名称
|
||||
- `instrument-type <code>` — 品种类型
|
||||
- `divid-factors <code>` — 除权除息因子
|
||||
- `market-times [market]` — 日内交易时段
|
||||
- `trading-calendar [market]` — 交易日历(含时段)
|
||||
- `option-list <code>` — 期权列表
|
||||
- `bsm-price` / `bsm-iv` — BSM 期权定价/隐含波动率
|
||||
- `hkt-stats` / `hkt-details` / `hkt-rate` — 港股通统计/明细/汇率
|
||||
- `top10-holder <code>` / `holder-num <code>` — 十大股东/股东户数
|
||||
- `ipo` / `ipo-limit` — 新股数据/申购额度
|
||||
- `credit-assure` / `credit-short` / `credit-debt` — 融资融券查询
|
||||
- `his-st <code>` — 历史 ST 数据
|
||||
- `index-weight <index>` — 指数权重
|
||||
- `industry <name>` — 行业成分
|
||||
- `sector-info [name]` — 板块详情
|
||||
- `local-data <code>` — 本地缓存数据
|
||||
- `timetag2dt` / `dt2timetag` — 时间戳转换
|
||||
|
||||
**交易**:
|
||||
- `buy <code> <volume> [--price P] [--latest]` — 买入下单
|
||||
- `sell <code> <volume> [--price P] [--latest]` — 卖出下单
|
||||
- `cancel <order_id> [--market SH]` — 撤单
|
||||
|
||||
**通用兜底**:
|
||||
- `rpc <method> [json_params]` — 调用任意白名单方法(未列出的方法都能这样调)
|
||||
|
||||
**配置自动发现**:脚本会自动把仓库 `src/` 加入 `sys.path`(开发模式直接运行,无需 pip install),并自动发现 QMT 的 python 目录(读 `local_config.py` 里的 transport 配置)。配置从环境变量(`BIGQMT_ACCOUNT_ID`/`BIGQMT_REDIS_HOST` 等)或配置文件读取。
|
||||
|
||||
**输出格式**:默认 JSON(`ok`/`data`/`ts` 三字段),加 `--table` 切换表格输出。错误返回 `ok: false` + `error`/`detail`/`code`,退出码 1。
|
||||
|
||||
## 参考
|
||||
|
||||
详细的 API 参数、返回值结构、常量定义和已知陷阱见 `references/api_reference.md`。
|
||||
当命令速查不够用时(如需要直接 RPC 调用、查看信用交易类型、了解回调系统等),查阅该文件。
|
||||
@@ -0,0 +1,523 @@
|
||||
# QMT API 参考手册
|
||||
|
||||
本文档是 `qmt-trader` skill 的完整 API 参考。当 SKILL.md 的速查不够用时,查阅本文件获取
|
||||
参数细节、返回值结构和已知陷阱。
|
||||
|
||||
---
|
||||
|
||||
## 1. 初始化与配置
|
||||
|
||||
### 配置来源(优先级从高到低)
|
||||
|
||||
1. **环境变量**
|
||||
| 变量 | 默认 | 说明 |
|
||||
|------|------|------|
|
||||
| `BIGQMT_ACCOUNT_ID` | — | 资金账号 |
|
||||
| `BIGQMT_REDIS_HOST` | `127.0.0.1` | Redis 地址 |
|
||||
| `BIGQMT_REDIS_PORT` | `6379` | Redis 端口 |
|
||||
| `BIGQMT_REDIS_DB` | `5` | Redis DB |
|
||||
| `BIGQMT_REDIS_PASSWORD` | — | Redis 密码 |
|
||||
| `BIGQMT_RPC_TRANSPORT` | `redis` | 传输方式 redis/zmq |
|
||||
| `BIGQMT_RPC_TIMEOUT_SECONDS` | `6.0` | RPC 超时 |
|
||||
|
||||
2. **配置文件** `bigqmt_signal_trader_client_config.py`(在 PYTHONPATH 中,gitignored)
|
||||
|
||||
3. **备选配置文件** `bigqmt_signal_trader_local_config.py`
|
||||
|
||||
### Python 初始化
|
||||
|
||||
```python
|
||||
from bigqmt_signal_trader.xtquant_compat import StockAccount, configure, xt_trader, xtdata
|
||||
|
||||
configure() # 从配置/环境变量初始化
|
||||
acc = StockAccount(xt_trader.client.account_id, "STOCK")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 行情数据 API
|
||||
|
||||
### 2.1 get_full_tick — 实时五档盘口
|
||||
|
||||
```python
|
||||
xtdata.get_full_tick(code_list)
|
||||
```
|
||||
|
||||
- **参数**: `code_list: list[str]`,如 `["000001.SZ", "600000.SH"]`;也支持整市场 `["SH"]`, `["SZ"]`
|
||||
- **返回**: `dict[code -> dict]`,每只含 `lastPrice`/`open`/`high`/`low`/`lastClose`/`volume`/`amount`/
|
||||
`bidPrice`(10档)/`askPrice`(10档)/`bidVol`/`askVol`/`time`/`stime`
|
||||
- **CLI**: `python qmt.py tick 600000.SH 000001.SZ`
|
||||
- **注意**: 整市场快照数据量大(5000+ 股),超时自动设 30 秒
|
||||
|
||||
### 2.2 get_market_data_ex — K线/历史行情
|
||||
|
||||
```python
|
||||
xtdata.get_market_data_ex(
|
||||
field_list=None, # ["close","open","high","low","volume","amount"] 或 None=全部
|
||||
stock_list=None, # ["000001.SZ"]
|
||||
period="1d", # "1d"/"1m"/"5m"/"15m"/"30m"/"60m"/"tick"
|
||||
start_time="", # "YYYYMMDD" 或 "YYYYMMDDHHMMSS"
|
||||
end_time="",
|
||||
count=-1, # -1=不限
|
||||
dividend_type="none", # "none"/"front"(前复权)/"back"(后复权)
|
||||
fill_data=True, # 是否填充缺失
|
||||
)
|
||||
```
|
||||
|
||||
- **返回**: `dict[code -> pandas.DataFrame]`,index 是时间戳字符串,列含 `time`(epoch ms)/`open`/`high`/`low`/`close`/`volume`/`amount`
|
||||
- **CLI**: `python qmt.py kline 600000.SH --period 1d --count 60 --dividend front`
|
||||
- **自愈**: 请求复权但服务端缺原始数据时(返回全 0),自动触发下载+重试
|
||||
- **陷阱**: 前/后复权必须先在服务端下载原始数据,否则返回全 0(已自愈但仍可能首次慢)
|
||||
|
||||
### 2.3 get_instrument_detail — 合约详情
|
||||
|
||||
```python
|
||||
xtdata.get_instrument_detail(stock_code) # 别名 get_instrumentdetail
|
||||
```
|
||||
|
||||
- **返回**: `dict`,含名称/上市日/合约乘数/最小变动价位等约 30 字段
|
||||
- **CLI**: `python qmt.py instrument 600000.SH`
|
||||
|
||||
### 2.4 get_stock_list_in_sector — 板块成分股
|
||||
|
||||
```python
|
||||
xtdata.get_stock_list_in_sector(sector_name) # 如 "沪深A股", "科创板", "创业板"
|
||||
```
|
||||
|
||||
- **返回**: `list[str]` 代码列表
|
||||
- **CLI**: `python qmt.py sector "沪深A股"`
|
||||
|
||||
### 2.5 get_sector_list — 板块列表
|
||||
|
||||
```python
|
||||
xtdata.get_sector_list()
|
||||
```
|
||||
|
||||
- **返回**: `list[str]`
|
||||
- **CLI**: `python qmt.py sector`
|
||||
- **注意**: 大 QMT 环境 fallback 返回 13 个常用板块名(非完整列表)
|
||||
|
||||
### 2.6 get_trading_dates — 交易日历
|
||||
|
||||
```python
|
||||
xtdata.get_trading_dates(market="SH", start_time="", end_time="", count=-1)
|
||||
```
|
||||
|
||||
- **CLI**: `python qmt.py trading-dates --count 10`
|
||||
|
||||
### 2.7 get_north_finance_change — 北向资金
|
||||
|
||||
```python
|
||||
xtdata.get_north_finance_change(period="1d")
|
||||
```
|
||||
|
||||
- **CLI**: `python qmt.py north`
|
||||
|
||||
### 2.8 get_longhubang — 龙虎榜
|
||||
|
||||
```python
|
||||
xtdata.get_longhubang(stock_list=["600000.SH"], start_time="", end_time="", count=5)
|
||||
```
|
||||
|
||||
- **返回**: `pandas.DataFrame`
|
||||
- **CLI**: `python qmt.py longhubang 600000.SH --count 5`
|
||||
|
||||
### 2.9 get_financial_data — 财务数据
|
||||
|
||||
```python
|
||||
xtdata.get_financial_data(
|
||||
stock_list=["000001.SZ"],
|
||||
table_list=["Capital.CAPITAL"], # 表名
|
||||
start_time="", end_time="",
|
||||
)
|
||||
```
|
||||
|
||||
- **CLI**: `python qmt.py financial 000001.SZ --tables Capital.CAPITAL`
|
||||
|
||||
### 2.10 download_history_data2 — 下载历史数据
|
||||
|
||||
```python
|
||||
xtdata.download_history_data2(
|
||||
stock_list=["600654.SH"], period="1d",
|
||||
start_time="20240101", dividend_type="front",
|
||||
)
|
||||
```
|
||||
|
||||
- **返回**: `{"finished": N, "total": M}`
|
||||
- **CLI**: `python qmt.py download 600654.SH --period 1d --start 20240101 --dividend front`
|
||||
|
||||
### 2.11 subscribe_whole_quote — 全推行情订阅
|
||||
|
||||
```python
|
||||
sub_id = xtdata.subscribe_whole_quote(["SH","SZ"], callback=on_quote)
|
||||
# ... 运行策略 ...
|
||||
xtdata.unsubscribe_quote(sub_id)
|
||||
```
|
||||
|
||||
- **机制**: 服务端真推送(非轮询),增量推送有变化的品种
|
||||
- **CLI**: `python qmt.py quote-subscribe SH SZ --max 10 --timeout 30`
|
||||
- **心跳**: 客户端 3 秒一次 keepalive,服务端重启后自动恢复
|
||||
|
||||
---
|
||||
|
||||
## 3. 账户/持仓/委托查询 API
|
||||
|
||||
### 3.1 query_stock_asset — 查询资产
|
||||
|
||||
```python
|
||||
asset = xt_trader.query_stock_asset(acc)
|
||||
```
|
||||
|
||||
- **返回属性**: `account_id` / `cash`(可用现金) / `frozen_cash` / `total_asset` / `market_value`
|
||||
- **CLI**: `python qmt.py account`
|
||||
- **容错**: RPC 失败时从 Redis 缓存 `bigqmt:positions:{account_id}` 读取
|
||||
|
||||
### 3.2 query_stock_positions — 查询全部持仓
|
||||
|
||||
```python
|
||||
positions = xt_trader.query_stock_positions(acc)
|
||||
```
|
||||
|
||||
- **返回属性**: `stock_code` / `stock_name` / `volume`(总持仓) / `can_use_volume`(可用) /
|
||||
`avg_price`(成本) / `price`(最新价) / `market_value` / `frozen_volume` / `yesterday_volume`
|
||||
- **CLI**: `python qmt.py positions [code]`
|
||||
|
||||
### 3.3 query_stock_position — 查询单只持仓
|
||||
|
||||
```python
|
||||
pos = xt_trader.query_stock_position(acc, "600000.SH")
|
||||
```
|
||||
|
||||
- **返回**: 单个对象或 `None`
|
||||
|
||||
### 3.4 query_stock_orders — 查询委托
|
||||
|
||||
```python
|
||||
orders = xt_trader.query_stock_orders(acc, cancelable_only=False, strategy_name="")
|
||||
```
|
||||
|
||||
- **返回属性**: `stock_code` / `order_type`(23=BUY,24=SELL) / `order_status` /
|
||||
`order_volume` / `traded_volume` / `price` / `order_sysid` / `order_remark`
|
||||
- **CLI**: `python qmt.py orders [--cancelable] [--strategy ""]`
|
||||
- **⚠️ strategy_name 陷阱**: 下单时的 strategy_name 必须和查询时一致。服务端默认 `""` 返回全部;
|
||||
客户端 `BigQmtXtTrader` 默认 `"bigqmt_signal_trader"`。用 `""` 查全部最安全。
|
||||
|
||||
### 3.5 query_stock_trades — 查询成交
|
||||
|
||||
```python
|
||||
trades = xt_trader.query_stock_trades(acc, strategy_name="")
|
||||
```
|
||||
|
||||
- **返回属性**: `stock_code` / `order_type` / `traded_volume` / `traded_price` /
|
||||
`traded_at` / `order_sysid` / `trade_id`
|
||||
- **CLI**: `python qmt.py trades`
|
||||
|
||||
### 3.6 委托状态码
|
||||
|
||||
| 值 | 常量 | 含义 |
|
||||
|----|------|------|
|
||||
| 48 | ORDER_UNREPORTED | 未申报 |
|
||||
| 49 | ORDER_WAIT_REPORTING | 等待申报 |
|
||||
| 50 | ORDER_REPORTED | 已申报 |
|
||||
| 51 | ORDER_REPORTED_CANCEL | 已申报撤单 |
|
||||
| 52 | ORDER_PARTSUCC_CANCEL | 部成撤单 |
|
||||
| 53 | ORDER_PART_CANCEL | 部撤 |
|
||||
| 54 | ORDER_CANCELED | 已撤 |
|
||||
| 55 | ORDER_PART_SUCC | 部分成交 |
|
||||
| 56 | ORDER_SUCCEEDED | 全部成交 |
|
||||
| 57 | ORDER_JUNK | 废单 |
|
||||
| 255 | ORDER_UNKNOWN | 未知 |
|
||||
|
||||
可撤状态: 49, 50, 55
|
||||
|
||||
---
|
||||
|
||||
## 4. 下单 API
|
||||
|
||||
### 4.1 order_stock — 同步下单
|
||||
|
||||
```python
|
||||
from bigqmt_signal_trader.xtquant_compat import STOCK_BUY, STOCK_SELL, FIX_PRICE, LATEST_PRICE
|
||||
|
||||
order_id = xt_trader.order_stock(
|
||||
acc, # StockAccount
|
||||
stock_code, # "600000.SH"
|
||||
order_type, # STOCK_BUY(23) / STOCK_SELL(24)
|
||||
order_volume, # int,委托数量
|
||||
price_type, # FIX_PRICE(11) / LATEST_PRICE(5)
|
||||
price, # float,限价单价格(最新价时传 0)
|
||||
strategy_name, # str
|
||||
order_remark, # str,user_order_id
|
||||
)
|
||||
```
|
||||
|
||||
- **返回**: `order_sys_id`(字符串) 或 `-1`(失败)
|
||||
- **CLI**: `python qmt.py buy 600000.SH 100 --price 7.50 [--strategy s] [--remark r]`
|
||||
- **CLI**: `python qmt.py sell 600000.SH 100 --price 7.50`
|
||||
- **⚠️ 权限**: 服务端默认 `rpc_allow_order_methods=False`,必须显式开启才能下单
|
||||
- **⚠️ 超时**: 超时后委托可能已提交,先查 `query_orders` 确认,避免重复下单
|
||||
|
||||
### 4.2 order_stock_async — 异步下单
|
||||
|
||||
```python
|
||||
seq = xt_trader.order_stock_async(acc, code, order_type, vol, price_type, price, strategy, remark)
|
||||
```
|
||||
|
||||
- **返回**: seq(结果通过 callback 回调)
|
||||
|
||||
### 4.3 order_stock_batch — 批量下单
|
||||
|
||||
```python
|
||||
results = xt_trader.order_stock_batch(acc, orders, batch_id="")
|
||||
# orders: list[dict],每项含 stock_code/action/volume/price/price_type/strategy_name
|
||||
```
|
||||
|
||||
- **上限**: 500 条/批
|
||||
|
||||
### 4.4 信用交易委托类型
|
||||
|
||||
| 常量 | 值 | 用途 |
|
||||
|------|-----|------|
|
||||
| CREDIT_BUY | 23 | 担保品买入 |
|
||||
| CREDIT_SELL | 24 | 担保品卖出 |
|
||||
| CREDIT_FIN_BUY | 27 | 融资买入 |
|
||||
| CREDIT_SLO_SELL | 28 | 融券卖出 |
|
||||
| CREDIT_BUY_SECU_REPAY | 29 | 买券还券 |
|
||||
| CREDIT_DIRECT_SECU_REPAY | 30 | 直接还券 |
|
||||
| CREDIT_SELL_SECU_REPAY | 31 | 卖券还款 |
|
||||
| CREDIT_DIRECT_CASH_REPAY | 32 | 直接还款 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 撤单 API
|
||||
|
||||
### 5.1 cancel_order_stock_sysid
|
||||
|
||||
```python
|
||||
success = xt_trader.cancel_order_stock_sysid(acc, market, order_sysid)
|
||||
# market: "SH" / "SZ" / ""
|
||||
```
|
||||
|
||||
- **CLI**: `python qmt.py cancel <order_sysid> --market SH`
|
||||
|
||||
### 5.2 cancel_order_stock
|
||||
|
||||
```python
|
||||
success = xt_trader.cancel_order_stock(acc, order_id)
|
||||
# 等价于 cancel_order_stock_sysid(acc, "", order_id)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 回调系统
|
||||
|
||||
```python
|
||||
from bigqmt_signal_trader.xtquant_compat import XtQuantTraderCallback
|
||||
|
||||
class MyCallback(XtQuantTraderCallback):
|
||||
def on_stock_order(self, order): ... # 委托变更
|
||||
def on_stock_trade(self, trade): ... # 成交推送
|
||||
def on_order_error(self, error): ... # 委托错误
|
||||
def on_cancel_error(self, error): ... # 撤单错误
|
||||
def on_order_stock_async_response(self, resp): ...
|
||||
def on_account_status(self, status): ...
|
||||
|
||||
xt_trader.register_callback(MyCallback())
|
||||
xt_trader.start()
|
||||
xt_trader.connect()
|
||||
xt_trader.subscribe(acc)
|
||||
```
|
||||
|
||||
事件推送通过 Redis pubsub 频道:
|
||||
- `bigqmt:exec:order:{account_id}`
|
||||
- `bigqmt:exec:trade:{account_id}`
|
||||
- `bigqmt:exec:order_error:{account_id}`
|
||||
- `bigqmt:exec:cancel_error:{account_id}`
|
||||
|
||||
---
|
||||
|
||||
## 7. 关键陷阱速查
|
||||
|
||||
### 7.1 strategy_name 不匹配
|
||||
- 下单用 `strategy_name="rpc_test"` → 查询用 `strategy_name="bigqmt_signal_trader"` → 返回空
|
||||
- **解决**: 查询时传 `strategy_name=""` 返回全部,或保持一致
|
||||
|
||||
### 7.2 下单静默失败
|
||||
- `passorder` 调用成功但委托没进系统(QMT 风控拒绝但没报错)
|
||||
- **解决**: 服务端下单后等 0.5 秒查 `query_orders` 确认;检查返回的 `server_error` 字段
|
||||
|
||||
### 7.3 复权 K 线返回全 0
|
||||
- 服务端缺原始数据时,前/后复权返回的 close 全是 0.0
|
||||
- **解决**: 先 `download_history_data2` 下载原始数据(客户端有自愈机制)
|
||||
|
||||
### 7.4 Transport 不匹配
|
||||
- 客户端 redis / 服务端 zmq → ping 超时
|
||||
- **解决**: 两端 `transport` 字段保持一致
|
||||
|
||||
### 7.5 QMT 必须运行在实盘模式
|
||||
- 模拟模式下委托进 QMT 界面但不在真实委托队列,`query_orders` 查不到
|
||||
- `order_stock` 返回 -1,触发 `on_order_error`
|
||||
|
||||
### 7.6 整市场快照数据量大
|
||||
- `get_full_tick(["SH"])` 返回 5000+ 股完整盘口
|
||||
- **解决**: 启用 `full_tick_cache` 或增大超时(已自动设 30 秒)
|
||||
|
||||
### 7.7 全推行情是增量的
|
||||
- `subscribe_whole_quote` 的大 QMT 回调只推有变化的品种
|
||||
- **解决**: 订阅成功后客户端自动调一次 `get_full_tick` 打底
|
||||
|
||||
### 7.8 下单超时与重复下单
|
||||
- `order_stock` 超时 → 委托可能已提交但没收到响应
|
||||
- **解决**: 超时后先查 `query_orders`/`query_trades` 确认状态,再决定是否重试
|
||||
|
||||
---
|
||||
|
||||
## 8. 常量速查
|
||||
|
||||
### 交易常量
|
||||
|
||||
| 常量 | 值 | 用途 |
|
||||
|------|-----|------|
|
||||
| STOCK_BUY | 23 | 股票买入 |
|
||||
| STOCK_SELL | 24 | 股票卖出 |
|
||||
| FIX_PRICE | 11 | 限价/指定价 |
|
||||
| LATEST_PRICE | 5 | 最新价 |
|
||||
| MARKET_PEER_PRICE_FIRST | 44 | 对手方最优价 |
|
||||
|
||||
### 账号类型
|
||||
|
||||
| 常量 | 值 |
|
||||
|------|-----|
|
||||
| FUTURE_ACCOUNT | 1 |
|
||||
| SECURITY_ACCOUNT | 2 |
|
||||
| CREDIT_ACCOUNT | 3 |
|
||||
| FUTURE_OPTION_ACCOUNT | 5 |
|
||||
| STOCK_OPTION_ACCOUNT | 6 |
|
||||
|
||||
### 期货委托类型(部分)
|
||||
|
||||
| 常量 | 值 | 用途 |
|
||||
|------|-----|------|
|
||||
| FUTURE_OPEN_LONG | 0 | 开多 |
|
||||
| FUTURE_CLOSE_LONG_TODAY | 2 | 平今多 |
|
||||
| FUTURE_OPEN_SHORT | 3 | 开空 |
|
||||
| FUTURE_CLOSE_SHORT_TODAY | 4 | 平今空 |
|
||||
| FUTURE_CLOSE_LONG_HISTORY | 6 | 平昨多 |
|
||||
| FUTURE_CLOSE_SHORT_HISTORY | 7 | 平昨空 |
|
||||
|
||||
---
|
||||
|
||||
## 9. 直接 RPC 调用(绕过兼容层)
|
||||
|
||||
当兼容层方法不够用时,可直接调 RPC:
|
||||
|
||||
```python
|
||||
from bigqmt_signal_trader.redis_rpc import call_redis_rpc
|
||||
import redis
|
||||
|
||||
r = redis.Redis(host="...", port=6379, db=5, password="...")
|
||||
resp = call_redis_rpc(r, "ACCOUNT_ID", "get_full_tick", {"codes": ["000001.SZ"]})
|
||||
print(resp["data"]["000001.SZ"]["lastPrice"])
|
||||
```
|
||||
|
||||
- **万能入口**: `xtdata.call_method("get_float_caps", stockcode="000001.SZ")`
|
||||
- **方法别名映射**:
|
||||
- `get_full_tick` → `get_ticks`
|
||||
- `get_instrument_detail` → `get_instrument`
|
||||
- `query_stock_asset` → `get_asset`
|
||||
- `query_stock_positions` → `get_positions`
|
||||
- `query_stock_orders` → `query_orders`
|
||||
- `query_stock_trades` → `query_trades`
|
||||
- `order_stock` → `submit_order`
|
||||
- `cancel_order_stock` → `cancel_order`
|
||||
|
||||
### RPC 响应结构
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"data": {...},
|
||||
"error": "",
|
||||
"server_error": "",
|
||||
"handled_at": "2024-07-01 15:00:00"
|
||||
}
|
||||
```
|
||||
|
||||
- `ok=true`: `data` 为方法返回值(DataFrame 已序列化,客户端自动还原 pandas 对象)
|
||||
- `ok=false`: `error` 为错误信息
|
||||
- `server_error`: 额外诊断(如 passorder 提交但委托未进系统)
|
||||
|
||||
---
|
||||
|
||||
## 10. 可用 RPC 方法白名单(117 个只读 + 3 个下单/撤单)
|
||||
|
||||
### 行情快照
|
||||
`get_ticks`/`get_full_tick`, `get_instrument`/`get_instrument_detail`, `get_instrument_type`,
|
||||
`get_stock_name`, `get_stock_type`, `get_last_close`, `get_last_volume`, `get_float_caps`,
|
||||
`get_total_share`, `get_turn_over_rate`, `get_weight_in_index`, `get_contract_multiplier`,
|
||||
`get_contract_expire_date`, `get_open_date`, `get_svol`, `get_bvol`, `get_risk_free_rate`,
|
||||
`is_stock_type`, `get_cb_info`
|
||||
|
||||
### K线/历史
|
||||
`get_market_data`, `get_market_data_ex`, `get_local_data`, `get_close_price`, `get_index_weight`
|
||||
|
||||
### L2 行情(需 L2 权限)
|
||||
`get_l2_quote`, `get_l2_order`, `get_l2_transaction`, `subscribe_l2thousand`
|
||||
|
||||
### 板块
|
||||
`get_stock_list_in_sector`, `get_sector_list`, `get_sector_info`, `create_sector`, `add_sector`, `remove_sector`
|
||||
|
||||
### 交易日历/时段
|
||||
`get_trading_dates`, `get_holidays`, `get_markets`, `get_market_last_trade_date`,
|
||||
`get_date_location`, `get_trading_calendar`, `get_trade_times`
|
||||
|
||||
### 数据下载
|
||||
`download_history_data`, `download_history_data2`, `download_holiday_data`,
|
||||
`download_etf_info`, `download_cb_data`, `download_history_contracts`,
|
||||
`download_index_weight`, `download_sector_data`
|
||||
|
||||
### 财务/因子
|
||||
`get_financial_data`, `download_financial_data`, `download_financial_data2`,
|
||||
`get_raw_financial_data`, `get_factor_data`
|
||||
|
||||
### ETF/期权/期货
|
||||
`get_etf_info`, `get_ipo_info`, `get_option_list`, `get_his_option_list`,
|
||||
`get_his_option_list_batch`, `get_option_detail_data`, `get_option_undl_data`,
|
||||
`get_option_undl`, `get_ETF_list`, `get_main_contract`, `get_his_contract_list`
|
||||
|
||||
### 期权定价
|
||||
`bsm_price`, `bsm_iv`, `get_option_iv`
|
||||
|
||||
### 龙虎榜/股东
|
||||
`get_longhubang`, `get_top10_share_holder`, `get_holder_num`, `get_turnover_rate`,
|
||||
`get_industry`, `get_his_st_data`, `get_his_index_data`
|
||||
|
||||
### 资金流
|
||||
`get_north_finance_change`, `get_hkt_statistics`, `get_hkt_details`, `get_hkt_exchange_rate`
|
||||
|
||||
### 因子/模型
|
||||
`call_formula`, `subscribe_formula`, `unsubscribe_formula`, `get_formula_result`, `gen_factor_index`
|
||||
|
||||
### 时间转换(纯本地)
|
||||
`datetime_to_timetag`, `timetag_to_datetime`
|
||||
|
||||
### 账户查询
|
||||
`get_asset`, `get_positions`, `query_stock_position`, `query_orders`, `query_trades`,
|
||||
`get_history_trade_detail_data`, `get_value_by_order_id`, `get_last_order_id`
|
||||
|
||||
### 融资融券(需两融权限)
|
||||
`get_assure_contract`, `get_enable_short_contract`, `get_unclosed_compacts`,
|
||||
`get_closed_compacts`, `get_debt_contract`
|
||||
|
||||
### 期权持仓
|
||||
`get_option_subject_position`, `get_comb_option`
|
||||
|
||||
### 持仓同步
|
||||
`sync_positions`
|
||||
|
||||
### 下单/撤单(需开启 rpc_allow_order_methods)
|
||||
`submit_order`/`order_stock`, `submit_orders_batch`/`order_stock_batch`,
|
||||
`cancel_order`/`cancel_order_stock`/`cancel_order_stock_sysid`
|
||||
|
||||
### 全推行情
|
||||
`subscribe_whole_quote`, `unsubscribe_whole_quote`, `quote_keepalive`
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user