3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在量化交易中,及时撤销未成交的委托是资金管理和风险控制的重要手段。QMT 平台提供了 cancel() 函数,允许开发者根据委托号(orderId)对指定的委托进行撤单操作。本文将详细解析该接口的参数、返回值及核心使用流程。
cancel(orderId, accountId, accountType, ContextInfo)
get_last_order_id() 或交易回调 order_callback 获取。'STOCK':股票'FUTURE':期货'CREDIT':信用(两融)'HUGANGTONG':沪港通'SHENGANGTONG':深港通'STOCK_OPTION':期权True 表示撤单信号已发送,False 表示发送失败。在执行撤单前,通常需要确认委托是否可以撤销,QMT 提供了以下辅助接口:
can_cancel_order()can_cancel_order(orderId, accountID, strAccountType)
True(可撤销)或 False(不可撤销,如已成、已撤、废单等状态)。get_last_order_id()get_last_order_id(accountID, strAccountType, strDatatype)
'ORDER',即可获取该账号最新一笔委托的 orderId。以下示例展示了如何在 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}")
cancel()、can_cancel_order() 等函数在回测模式下无实际意义,仅在实盘或模拟盘运行模式下生效。cancel() 返回 True 仅代表撤单指令成功发送到了柜台,并不代表撤单已经完成。最终的撤单结果需要通过 order_callback() 回调函数或查询委托状态来确认(状态变为 ENTRUST_STATUS_CANCELED 即为已撤)。