超时撤单包含买入超时撤单和卖出超时撤单,撤单后调整价格重新买入或卖出未完成的数量。
#encoding:gbk
import pandas as pd
import numpy as np
import datetime
import talib
def init(ContextInfo):
ContextInfo.accID='80041016'
ContextInfo.set_account(ContextInfo.accID)
ContextInfo.run_time('cancel_order_timer','10nSecond','2023-01-01 00:00:00')
def handlebar(ContextInfo):
pass
def cancel_order_timer(ContextInfo):
#获取委托对象列表
orders=get_trade_detail_data(ContextInfo.accID,'STOCK','ORDER')
#遍历委托对象列表
for order in orders:
#判断委托对象是否可以撤销
if can_cancel_order(order.m_strOrderSysID,ContextInfo.accID,'STOCK'):
ordercode=order.m_strInstrumentID+'.'+order.m_strExchangeID #获取委托单的证券代码
dt=order.m_strInsertDate+' '+order.m_strInsertTime #委托日期+委托时间
dt=datetime.datetime.strptime(dt,'%Y%m%d %H%M%S') #委托日期时间字符串解析成日期时间对象
now=datetime.datetime.now() #获取当前日期时间
second=(now-dt).seconds #当前日期时间-委托日期时间,获取秒数时间差
if second>60: #如果超过60秒
#买入委托超时,撤单并重新下单,委托价格需要修改
cancel(order.m_strOrderSysID,ContextInfo.accID,'STOCK',ContextInfo)
print('合同编号',order.m_strOrderSysID,'股票代码',ordercode,order.m_strInstrumentName,order.m_strOptName,'超时60秒撤单')
if order.m_strOptName=='限价买入': #如果是限价买入的委托撤单,则重新委托买入
passorder(23,1101,ContextInfo.accID,ordercode,11,order.m_dLimitPrice,order.m_nVolumeTotal,'定时撤单策略',1,'委托买入',ContextInfo)
print('重新委托买入')
if order.m_strOptName=='限价卖出': #如果是限价卖出的委托撤单,则重新委托卖出
passorder(24,1101,ContextInfo.accID,ordercode,11,order.m_dLimitPrice,order.m_nVolumeTotal,'定时撤单策略',1,'委托卖出',ContextInfo)
print('重新委托卖出')
上面代码中重新委托买入和重新委托卖出时,为了测试方便用了前一个委托单的委托价格,所以实际应用时,需要重新调整为可能可以买入或卖出的价格。