🚀 AI 一键生成 qmt 策略代码
立即体验

qmt 平台如何根据委托号 orderId 撤单?cancel 函数使用指南

qmt | 发布时间: 2026/7/22
以下内容由 EasyQuant 生成。

问题描述

请根据以下 SEO 主题生成完整页面内容:

Title: qmt 撤单 API 详解:如何使用 cancel 函数取消指定委托?

Question: qmt 怎么根据委托号 orderId 撤单?

解决方案

QMT 撤单 API 详解:如何使用 cancel 函数取消指定委托?

在量化交易中,及时撤销未成交的委托是资金管理和风险控制的重要手段。QMT 平台提供了 cancel() 函数,允许开发者根据委托号(orderId)对指定的委托进行撤单操作。本文将详细解析该接口的参数、返回值及核心使用流程。


1. cancel 撤单函数接口定义

1.1 函数原型

cancel(orderId, accountId, accountType, ContextInfo)

1.2 参数说明

  • orderId (string):委托号(合同编号),通常通过 get_last_order_id() 或交易回调 order_callback 获取。
  • accountId (string):资金账号。
  • accountType (string):账号类型,可选值包括:
    • 'STOCK':股票
    • 'FUTURE':期货
    • 'CREDIT':信用(两融)
    • 'HUGANGTONG':沪港通
    • 'SHENGANGTONG':深港通
    • 'STOCK_OPTION':期权
  • ContextInfo:Python 策略运行环境对象。

1.3 返回值

  • bool:是否成功发出了取消委托信号。True 表示撤单信号已发送,False 表示发送失败。

2. 撤单核心辅助函数

在执行撤单前,通常需要确认委托是否可以撤销,QMT 提供了以下辅助接口:

2.1 查询委托是否可撤:can_cancel_order()

can_cancel_order(orderId, accountID, strAccountType)
  • 返回值True(可撤销)或 False(不可撤销,如已成、已撤、废单等状态)。

2.2 获取最新委托号:get_last_order_id()

get_last_order_id(accountID, strAccountType, strDatatype)
  • strDatatype 传入 'ORDER',即可获取该账号最新一笔委托的 orderId

3. 完整撤单代码示例

以下示例展示了如何在 handlebar 中下单后,获取委托号,判断其是否可撤,并最终调用 cancel 函数进行撤单的完整逻辑:

#coding:gbk

def init(ContextInfo):
    # 设定交易账号
    ContextInfo.accid = '6000000248'
    ContextInfo.set_account(ContextInfo.accid)
    ContextInfo.stock = '600000.SH'

def handlebar(ContextInfo):
    # 仅在最后一根 K 线(实盘/模拟盘中)执行交易逻辑
    if not ContextInfo.is_last_bar():
        return

    # 1. 模拟发送一笔限价买入委托
    # 使用 passorder 发送指定价委托,返回后可通过 get_last_order_id 获取委托号
    passorder(23, 1101, ContextInfo.accid, ContextInfo.stock, 11, 9.5, 100, 'MyStrategy', 1, 'remark_01', ContextInfo)
    
    # 2. 获取刚刚发送的委托号
    orderid = get_last_order_id(ContextInfo.accid, 'STOCK', 'ORDER')
    print(f"当前最新委托号: {orderid}")
    
    if orderid != '-1':
        # 3. 检查该委托是否可以撤单
        can_cancel = can_cancel_order(orderid, ContextInfo.accid, 'STOCK')
        print(f"委托是否可撤: {can_cancel}")
        
        if can_cancel:
            # 4. 执行撤单操作
            ret = cancel(orderid, ContextInfo.accid, 'STOCK', ContextInfo)
            print(f"撤单信号发送结果: {ret}")

4. 注意事项

  1. 运行模式限制cancel()can_cancel_order() 等函数在回测模式下无实际意义,仅在实盘模拟盘运行模式下生效。
  2. 异步机制cancel() 返回 True 仅代表撤单指令成功发送到了柜台,并不代表撤单已经完成。最终的撤单结果需要通过 order_callback() 回调函数或查询委托状态来确认(状态变为 ENTRUST_STATUS_CANCELED 即为已撤)。