class Test: def __init__(self): self.Session = '' dllpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'lib') self.q = Quote( os.path.join( dllpath, 'ctp_quote.' + ('dll' if 'Windows' in platform.system() else 'so'))) self.t = Trade( os.path.join( dllpath, 'ctp_trade.' + ('dll' if 'Windows' in platform.system() else 'so'))) self.req = 0 self.ordered = False self.needAuth = False self.RelogEnable = True def q_OnFrontConnected(self): print('connected') self.q.ReqUserLogin(BrokerID=self.broker, UserID=self.investor, Password=self.pwd) def q_OnRspUserLogin(self, rsp: ctp.CThostFtdcRspUserLoginField, info: ctp.CThostFtdcRspInfoField, req: int, last: bool): print(info) self.q.SubscribeMarketData('rb1812') def q_OnTick(self, tick: ctp.CThostFtdcMarketDataField): f = tick # print(tick) if not self.ordered: _thread.start_new_thread(self.Order, (f, )) self.ordered = True def Order(self, f: ctp.CThostFtdcMarketDataField): print("报单") self.req += 1 self.t.ReqOrderInsert( BrokerID=self.broker, InvestorID=self.investor, InstrumentID=f.getInstrumentID(), OrderRef='{0:>12}'.format(self.req), UserID=self.investor, OrderPriceType=ctp.OrderPriceTypeType.LimitPrice, Direction=ctp.DirectionType.Buy, CombOffsetFlag=ctp.OffsetFlagType.Open.__char__(), CombHedgeFlag=ctp.HedgeFlagType.Speculation.__char__(), LimitPrice=f.getLastPrice() - 50, VolumeTotalOriginal=1, TimeCondition=ctp.TimeConditionType.GFD, # GTDDate='' VolumeCondition=ctp.VolumeConditionType.AV, MinVolume=1, ContingentCondition=ctp.ContingentConditionType.Immediately, StopPrice=0, ForceCloseReason=ctp.ForceCloseReasonType.NotForceClose, IsAutoSuspend=0, IsSwapOrder=0, UserForceClose=0) def OnFrontConnected(self): if not self.RelogEnable: return print('connected') if self.needAuth: self.t.ReqAuthenticate(self.broker, self.investor, '@haifeng', '8MTL59FK1QGLKQW2') else: self.t.ReqUserLogin(BrokerID=self.broker, UserID=self.investor, Password=self.pwd, UserProductInfo='@haifeng') def OnFrontDisconnected(self, reason: int): print(reason) def OnRspAuthenticate( self, pRspAuthenticateField: ctp.CThostFtdcRspAuthenticateField, pRspInfo: ctp.CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): print('auth:{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg())) self.t.ReqUserLogin(BrokerID=self.broker, UserID=self.investor, Password=self.pwd, UserProductInfo='@haifeng') def OnRspUserLogin(self, rsp: ctp.CThostFtdcRspUserLoginField, info: ctp.CThostFtdcRspInfoField, req: int, last: bool): print(info.getErrorMsg()) if info.getErrorID() == 0: self.Session = rsp.getSessionID() self.t.ReqSettlementInfoConfirm(BrokerID=self.broker, InvestorID=self.investor) else: self.RelogEnable = False def OnRspSettlementInfoConfirm( self, pSettlementInfoConfirm: ctp.CThostFtdcSettlementInfoConfirmField, pRspInfo: ctp.CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): # print(pSettlementInfoConfirm) _thread.start_new_thread(self.StartQuote, ()) def StartQuote(self): self.q.CreateApi() spi = self.q.CreateSpi() self.q.RegisterSpi(spi) self.q.OnFrontConnected = self.q_OnFrontConnected self.q.OnRspUserLogin = self.q_OnRspUserLogin self.q.OnRtnDepthMarketData = self.q_OnTick self.q.RegCB() self.q.RegisterFront(self.frontAddr.split(',')[1]) self.q.Init() # self.q.Join() def Qry(self): sleep(1.1) self.t.ReqQryInstrument() while True: sleep(1.1) self.t.ReqQryTradingAccount(self.broker, self.investor) sleep(1.1) self.t.ReqQryInvestorPosition(self.broker, self.investor) return def OnRtnInstrumentStatus( self, pInstrumentStatus: ctp.CThostFtdcInstrumentStatusField): print(pInstrumentStatus.getInstrumentStatus()) def OnRspOrderInsert(self, pInputOrder: ctp.CThostFtdcInputOrderField, pRspInfo: ctp.CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): print(pRspInfo) print(pInputOrder) print(pRspInfo.getErrorMsg()) def OnRtnOrder(self, pOrder: ctp.CThostFtdcOrderField): print(pOrder) if pOrder.getSessionID() == self.Session and pOrder.getOrderStatus( ) == ctp.OrderStatusType.NoTradeQueueing: print("撤单") self.t.ReqOrderAction(self.broker, self.investor, InstrumentID=pOrder.getInstrumentID(), OrderRef=pOrder.getOrderRef(), FrontID=pOrder.getFrontID(), SessionID=pOrder.getSessionID(), ActionFlag=ctp.ActionFlagType.Delete) def Run(self): # CreateApi时会用到log目录,需要在程序目录下创建**而非dll下** self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self.OnFrontConnected self.t.OnFrontDisconnected = self.OnFrontDisconnected self.t.OnRspUserLogin = self.OnRspUserLogin self.t.OnRspSettlementInfoConfirm = self.OnRspSettlementInfoConfirm self.t.OnRspAuthenticate = self.OnRspAuthenticate self.t.OnRtnInstrumentStatus = self.OnRtnInstrumentStatus self.t.OnRspOrderInsert = self.OnRspOrderInsert self.t.OnRtnOrder = self.OnRtnOrder # _thread.start_new_thread(self.Qry, ()) self.t.RegCB() self.frontAddr = 'tcp://180.168.146.187:10000,tcp://180.168.146.187:10010' self.broker = '9999' self.investor = '008107' self.pwd = '1' self.t.RegisterFront(self.frontAddr.split(',')[0]) self.t.SubscribePrivateTopic(nResumeType=2) # quick self.t.SubscribePrivateTopic(nResumeType=2) self.t.Init()
class TdApi: def __init__(self, userid, password, brokerid, RegisterFront, product_info, app_id, auth_code): # 初始化账号 self.t = Trade() self.userid = userid self.password = password self.brokerid = brokerid self.product_info = product_info self.app_id = app_id self.auth_code = auth_code api = self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self.onFrontConnected # 交易服务器登陆相应 self.t.OnFrontDisconnected = self.onFrontDisconnected self.t.OnRspAuthenticate = self.onRspAuthenticate # 申请码检验 self.t.OnRspUserLogin = self.onRspUserLogin # 用户登陆 self.t.OnRspUserLogout = self.onRspUserLogout # 用户登出 self.t.OnRtnInstrumentStatus = self.onRtnInstrumentStatus self.t.OnRspQryInstrument = self.onRspQryInstrument # 查询全部交易合约 self.t.OnRspSettlementInfoConfirm = self.onRspSettlementInfoConfirm # 结算单确认,显示登陆日期 self.t.OnRspQryTradingAccount = self.onRspQryTradingAccount # 查询账户 self.t.OnRtnOrder = self.onRtnOrder # 报单 self.t.OnRtnTrade = self.onRtnTrade # 成交 # self.t.OnRspParkedOrderInsert = self.onRspParkedOrderInsert self.t.OnErrRtnOrderInsert = self.onErrRtnOrderInsert self.t.OnRspQryDepthMarketData = self.onRspQryDepthMarketData # 查询涨跌停 self.t.RegCB() self.t.RegisterFront(RegisterFront) self.t.Init() self.islogin = False def onFrontConnected(self): """服务器连接""" downLogProgram('交易服务器连接成功') self.t.ReqAuthenticate(self.brokerid, self.userid, self.product_info, self.auth_code, self.app_id) def onFrontDisconnected(self, n): downLogProgram('交易服务器连接断开') def onRspAuthenticate( self, pRspAuthenticateField: CThostFtdcRspAuthenticateField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): downLogProgram('auth:{0}:{1}'.format(pRspInfo.getErrorID(), pRspInfo.getErrorMsg())) if pRspInfo.getErrorMsg() == '正确' or pRspInfo.getErrorMsg( ) == 'CTP:认证码错误,尽快获取正确的认证码。当前系统或者用户豁免终端认证,可以登录': self.t.ReqUserLogin(BrokerID=self.brokerid, UserID=self.userid, Password=self.password, UserProductInfo=self.product_info) elif pRspInfo.getErrorMsg() == 'CTP:前置不活跃': threading.Timer(60, self.t.ReqAuthenticate, [ self.brokerid, self.userid, self.product_info, self.auth_code, self.app_id ]).start() def onRspUserLogin(self, data, error, n, last): """登陆回报""" if error.getErrorID() == 0: self.Investor = data.getUserID() self.BrokerID = data.getBrokerID() log = self.Investor + '交易服务器登陆成功' self.islogin = True self.t.ReqSettlementInfoConfirm(self.BrokerID, self.Investor) # 对账单确认 self.t.ReqQryDepthMarketData() downLogProgram(log) else: log = '交易服务器登陆回报,错误代码:' + str(error.getErrorID()) + \ ', 错误信息:' + str(error.getErrorMsg()) downLogProgram(log) if error.getErrorMsg() == 'CTP:客户端未认证': # 过 60 秒后,重新登陆一次 threading.Timer(60, self.t.ReqUserLogin, [ '', self.brokerid, self.userid, self.password, self.product_info ]).start() def onRspUserLogout(self, data, error, n, last): if error.getErrorID() == 0: log = '交易服务器登出成功' self.islogin = False else: log = '交易服务器登出回报,错误代码:' + str(error.getErrorID()) + \ ', 错误信息:' + str(error.getErrorMsg()) downLogProgram(log) def onRtnInstrumentStatus(self, data): pass def onRspQryInstrument(self, data, error, n, last): pass def onRspSettlementInfoConfirm(self, data, error, n, last): """确认结算信息回报""" downLogProgram('账号:{}, 日期:{}, 时间:{}'.format(data.getInvestorID(), data.getConfirmDate(), data.getConfirmTime())) def getPosition(self): self.checkPosition = False downLogProgram("读取账号持仓情况") self.t.ReqQryInvestorPosition(self.brokerid, self.userid) def onRspQryTradingAccount(self, data, error, n, last): """资金账户查询回报""" if error.getErrorID() == 0: event = Event(type_=EVENT_ACCOUNT) event.dict_['BrokerID'] = data.getBrokerID() event.dict_['AccountID'] = data.getAccountID() event.dict_['PreDeposit'] = data.getPreDeposit() event.dict_['PreBalance'] = data.getPreBalance() event.dict_['PreMargin'] = data.getPreMargin() event.dict_['CurrMargin'] = data.getCurrMargin() event.dict_['Available'] = data.getAvailable() event.dict_['WithdrawQuota'] = data.getWithdrawQuota() ee.put(event) else: log = ('账户查询回报,错误代码:' + str(error.getErrorID()) + ', 错误信息:' + str(error.getErrorMsg())) downLogProgram(log) def getAccount(self): self.t.ReqQryTradingAccount(self.brokerid, self.userid) def onRtnOrder(self, data): # 常规报单事件 if time(7) <= datetime.now().time() <= time( 8, 15): # # 判断 连接 断开 与 连接 重连 的问题 return event = Event(type_=EVENT_ORDER) event.dict_ = data.__dict__.copy() ee.put(event) def onRtnTrade(self, data): """成交回报""" if time(7) <= datetime.now().time() <= time(8, 15): return event = Event(type_=EVENT_TRADE) event.dict_ = data.__dict__.copy() ee.put(event) # 预下单,没有用了 def onRspParkedOrderInsert(self, data=CThostFtdcParkedOrderField, pRspInfo=CThostFtdcRspInfoField, nRequestID=int, bIsLast=bool): event = Event(type_=EVENT_ORDERPARK) event.dict_['data'] = data._fields_ ee.put(event) def onErrRtnOrderInsert(self, data, error): """发单错误回报(交易所)""" if time(7) <= datetime.now().time() <= time(8, 15): return event = Event(type_=EVENT_ERROR) event.dict_['OrderRef'] = data.getOrderRef() event.dict_['InstrumentID'] = data.getInstrumentID() event.dict_['Direction'] = data.getDirection() event.dict_['CombOffsetFlag'] = data.getCombOffsetFlag() event.dict_['VolumeTotalOriginal'] = data.getVolumeTotalOriginal() event.dict_['LimitPrice'] = data.getLimitPrice() event.dict_['ErrorMsg'] = error.getErrorMsg() ee.put(event) # region 下单操作 def sendorder(self, instrumentid, orderRef, price, vol, direction, offset, OrderPriceType=TThostFtdcOrderPriceTypeType. THOST_FTDC_OPT_LimitPrice): goodsCode = getGoodsCode(instrumentid) if goodsCode.split('.')[1] == 'SHF': exChangeID = 'SHFE' elif goodsCode.split('.')[1] == 'DCE': exChangeID = 'DCE' elif goodsCode.split('.')[1] == 'CZC': exChangeID = 'CZCE' elif goodsCode.split('.')[1] == 'CFE': exChangeID = 'CFFEX' elif goodsCode.split('.')[1] == 'INE': exChangeID = 'INE' self.t.ReqOrderInsert( BrokerID=self.brokerid, InvestorID=self.userid, InstrumentID=instrumentid, OrderRef=orderRef, UserID=self.userid, OrderPriceType=OrderPriceType, Direction=direction, CombOffsetFlag=offset, CombHedgeFlag=chr( TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), LimitPrice=price, VolumeTotalOriginal=vol, TimeCondition=TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD, VolumeCondition=TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV, MinVolume=1, ForceCloseReason=TThostFtdcForceCloseReasonType. THOST_FTDC_FCC_NotForceClose, ContingentCondition=TThostFtdcContingentConditionType. THOST_FTDC_CC_Immediately, ExchangeID=exChangeID) return orderRef def buy(self, symbol, orderRef, price, vol): # 买开 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value) self.sendorder(symbol, orderRef, price, vol, direction, offset) def sell(self, symbol, orderRef, price, vol): # 买平 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value) self.sendorder(symbol, orderRef, price, vol, direction, offset) def sellMarket(self, symbol, orderRef, vol): # 买平市 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value) self.sendorder(symbol, orderRef, 0, vol, direction, offset, TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice) def sellToday(self, symbol, orderRef, price, vol): # 买平今 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value) self.sendorder(symbol, orderRef, price, vol, direction, offset) def sellMarketToday(self, symbol, orderRef, vol): # 买平市 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value) self.sendorder(symbol, orderRef, 0, vol, direction, offset, TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice) def short(self, symbol, orderRef, price, vol): # 卖开 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value) self.sendorder(symbol, orderRef, price, vol, direction, offset) def cover(self, symbol, orderRef, price, vol): # 卖平 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value) self.sendorder(symbol, orderRef, price, vol, direction, offset) def coverMarket(self, symbol, orderRef, vol): # 卖平市 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value) self.sendorder(symbol, orderRef, 0, vol, direction, offset, TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice) def coverToday(self, symbol, orderRef, price, vol): # 卖平今 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value) self.sendorder(symbol, orderRef, price, vol, direction, offset) def coverMarketToday(self, symbol, orderRef, vol): # 卖平市 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value) self.sendorder(symbol, orderRef, 0, vol, direction, offset, TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice) def cancelOrder(self, order): """撤单""" self.t.ReqOrderAction( BrokerID=self.brokerid, InvestorID=self.userid, OrderRef=order['OrderRef'], FrontID=int(order['FrontID']), SessionID=int(order['SessionID']), OrderSysID=order['OrderSysID'], ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete, ExchangeID=order["ExchangeID"], InstrumentID=order['InstrumentID']) # endregion # region 预埋单 def sendorderPark(self, instrumentid, orderRef, price, vol, direction, offset, OrderPriceType=TThostFtdcOrderPriceTypeType. THOST_FTDC_OPT_LimitPrice): goodsCode = getGoodsCode(instrumentid) if goodsCode.split('.')[1] == 'SHF': exChangeID = 'SHFE' elif goodsCode.split('.')[1] == 'DCE': exChangeID = 'DCE' elif goodsCode.split('.')[1] == 'CZC': exChangeID = 'CZCE' elif goodsCode.split('.')[1] == 'CFE': exChangeID = 'CFFEX' elif goodsCode.split('.')[1] == 'INE': exChangeID = 'INE' self.t.ReqParkedOrderInsert( BrokerID=self.brokerid, InvestorID=self.userid, InstrumentID=instrumentid, OrderRef=orderRef, UserID=self.userid, OrderPriceType=OrderPriceType, Direction=direction, CombOffsetFlag=offset, CombHedgeFlag=chr( TThostFtdcHedgeFlagType.THOST_FTDC_HF_Speculation.value), LimitPrice=price, VolumeTotalOriginal=vol, TimeCondition=TThostFtdcTimeConditionType.THOST_FTDC_TC_GFD, VolumeCondition=TThostFtdcVolumeConditionType.THOST_FTDC_VC_AV, MinVolume=1, ForceCloseReason=TThostFtdcForceCloseReasonType. THOST_FTDC_FCC_NotForceClose, ContingentCondition=TThostFtdcContingentConditionType. THOST_FTDC_CC_Immediately, ExchangeID=exChangeID) return orderRef def buyPark(self, symbol, orderRef, price, vol): # 多开 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value) self.sendorderPark(symbol, orderRef, price, vol, direction, offset) def sellPark(self, symbol, orderRef, price, vol): # 多平 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value) self.sendorderPark(symbol, orderRef, price, vol, direction, offset) def sellMarketPark(self, symbol, orderRef, vol): # 多平 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value) self.sendorderPark( symbol, orderRef, 0, vol, direction, offset, TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice) def selltodayPark(self, symbol, orderRef, price, vol): # 平今多 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value) self.sendorderPark(symbol, orderRef, price, vol, direction, offset) def shortPark(self, symbol, orderRef, price, vol): # 卖开空开 direction = TThostFtdcDirectionType.THOST_FTDC_D_Sell offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Open.value) self.sendorderPark(symbol, orderRef, price, vol, direction, offset) def coverPark(self, symbol, orderRef, price, vol): # 空平 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value) self.sendorderPark(symbol, orderRef, price, vol, direction, offset) def coverMarketPark(self, symbol, orderRef, vol): # 空平 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_Close.value) self.sendorderPark( symbol, orderRef, 0, vol, direction, offset, TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice) def covertodayPark(self, symbol, orderRef, price, vol): # 平今空 direction = TThostFtdcDirectionType.THOST_FTDC_D_Buy offset = chr(TThostFtdcOffsetFlagType.THOST_FTDC_OF_CloseToday.value) self.sendorderPark(symbol, orderRef, price, vol, direction, offset) def cancelOrderPark(self, order): # 预撤单 self.t.ReqParkedOrderAction( BrokerID=self.brokerid, InvestorID=self.userid, OrderRef=order['OrderRef'], FrontID=int(order['FrontID']), SessionID=int(order['SessionID']), OrderSysID=order['OrderSysID'], ActionFlag=TThostFtdcActionFlagType.THOST_FTDC_AF_Delete, ExchangeID=order["ExchangeID"], InstrumentID=order['InstrumentID']) def onRspQryDepthMarketData(self, data, error, n, last): #获取tick数据操作 icon = filter(lambda x: x.isalpha(), data.getInstrumentID()) icon = ''.join(list(icon)) event = Event(type_=EVENT_INSTRUMENT) event.dict_['InstrumentID'] = data.getInstrumentID() event.dict_['ProductID'] = icon event.dict_['OpenInterest'] = data.getOpenInterest() event.dict_['last'] = last # 主力合约的涨停版 if event.dict_['InstrumentID'] in listInstrument: # 可以避免多线程下数据的混乱 if dictInstrumentUpDownPrice.get(event.dict_['InstrumentID'], [0, 0]) == [0, 0]: dictInstrumentUpDownPrice[event.dict_['InstrumentID']] = [ data.getUpperLimitPrice(), data.getLowerLimitPrice() ] ee.put(event)