def qryPosition(self, InstrumentID=''): self.requestid += 1 if InstrumentID: req = ApiStruct.QryInvestorPosition(BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=InstrumentID) else: req = ApiStruct.QryInvestorPosition(BrokerID=self.broker_id, InvestorID=self.investor_id) self.ReqQryInvestorPosition(req, self.requestid)
def user_login(self, broker_id, investor_id, passwd): req = ApiStruct.ReqUserLogin(BrokerID=broker_id, UserID=investor_id, Password=passwd) self.requestid += 1 r = self.ReqUserLogin(req, self.requestid)
def ReqOrderInsert(self, order, request_id): '''报单录入请求, 需要调用成交函数''' logging.info(u'报单') oid = order.OrderRef trade = ApiStruct.Trade( InstrumentID=order.InstrumentID, Direction=order.Direction, Price=order.LimitPrice, Volume=order.VolumeTotalOriginal, OrderRef=oid, TradeID=oid, OrderSysID=oid, BrokerOrderSeq=oid, OrderLocalID=oid, TradeTime=time.strftime('%H%M%S'), #只有备案作用 ) if order.CombOffsetFlag == ApiStruct.OF_Open: #开仓. 为方便起见,假设都是股指 self.available -= order.LimitPrice * 300 * 0.17 else: self.available += order.LimitPrice * 300 * 0.17 fl_open = strategy.MAX_OPEN_OVERFLOW * 0.2 fl_close = strategy.MAX_CLOSE_OVERFLOW * 0.2 if order.CombOffsetFlag == ApiStruct.OF_Open: trade.Price += -fl_open if order.Direction == ApiStruct.D_Buy else fl_open else: trade.Price += -fl_close if order.Direction == ApiStruct.D_Buy else fl_close self.myagent.rtn_trade(trade)
def xcancel(self,instrument_id,exchange_id,order_sys_id,front_id,session_id,order_ref): """ 当以RESTART方式订阅流时,会收到之前的委托/成交回报. 在委托回报中,有各委托单状态 如果撤单的时候数据对不上号,就会有 撤单找不到相应报单 的错误 撤单请求返回的OnRtnOrder是被撤单的这个pOrder的委托响应的状态更新,不会有单独的撤单OnRtnOrder 该OnRtnOrder中, front_id,session_id等都对应到被撤的那个pOrder 如果是重新登陆,那么发出撤单命令的这个session_id和OnRtnOrder响应中的session_id是不一样的 """ self.logger.info('SPI_XC:取消命令') ref_id = self.inc_request_id() #orderActionRef是一个可有可无的值,设置错了也无关紧要 req = UStruct.InputOrderAction( InstrumentID = instrument_id, BrokerID = self._broker, InvestorID = self._investor, ActionFlag = UType.AF_Delete, OrderActionRef = ref_id, # 这需要一个int,真TM矛盾, OrderRef是一个String #OrderActionRef = order_ref, # 这个ref无关紧要,根据文档,应当是ref_id ) if exchange_id: #已设置,则采用Exchange_id+orderSysID方式. 这两种方式均可撤当日任意单 req.ExchangeID = exchange_id req.OrderSysID = order_sys_id else: #采用frontID + sessionID + orderRef标识的方式. 这两种方式均可撤当日任意单 #这个分支的测试 必须在OnRtnOrder第一次Callback时才能触发. 需要在该回调中测试 req.FrontID = front_id req.SessionID = session_id req.OrderRef = str(order_ref) ret= self.ReqOrderAction(req,self.inc_request_id()) return ret
def xclose(self, instrument_id, close_type,direction, volume,price): """ 上期所区分平昨和平今 搞反的话就会被CTP直接拒绝. 如平昨来平当日仓,且无足够昨仓,就会报:综合交易平台:平昨仓位不足 """ ref_id = self.inc_request_id() close_flag = UType.OF_CloseToday if close_type == XCLOSE_TODAY else UType.OF_Close req = UStruct.InputOrder( InstrumentID = instrument_id, Direction = self.to_ctp_direction(direction), OrderRef = str(ref_id), LimitPrice = price, #有个疑问,double类型如何保证舍入舍出,在服务器端取整? VolumeTotalOriginal = volume, OrderPriceType = UType.OPT_LimitPrice, BrokerID = self._broker, InvestorID = self._investor, CombOffsetFlag = close_flag, CombHedgeFlag = UType.HF_Speculation, #投机 5位字符, 但是只用到第0位 VolumeCondition = UType.VC_AV, MinVolume = 1, #这个作用有点不确定, 有的文档设成0了 ForceCloseReason = UType.FCC_NotForceClose, IsAutoSuspend = 1, UserForceClose = 0, TimeCondition = UType.TC_GFD, ) ret = self.ReqOrderInsert(req, ref_id) return ret
def xopen(self, instrument_id, direction, volume, price): #print("spidelegate,xopen",instrument_id,volume,price,self) ref_id = self.inc_request_id() req = UStruct.InputOrder( InstrumentID = instrument_id, Direction = self.to_ctp_direction(direction), OrderRef = str(ref_id), LimitPrice = price, #有个疑问,double类型如何保证舍入舍出,在服务器端取整? VolumeTotalOriginal = volume, OrderPriceType = UType.OPT_LimitPrice, ContingentCondition = UType.CC_Immediately, BrokerID = self._broker, InvestorID = self._investor, CombOffsetFlag = UType.OF_Open, #开仓 5位字符, 但是只用到第0位 CombHedgeFlag = UType.HF_Speculation, #投机 5位字符, 但是只用到第0位 VolumeCondition = UType.VC_AV, MinVolume = 1, #这个作用有点不确定, 有的文档设成0了 ForceCloseReason = UType.FCC_NotForceClose, IsAutoSuspend = 1, UserForceClose = 0, TimeCondition = UType.TC_GFD, ) ret = self.ReqOrderInsert(req, ref_id) return ret
def fetch_trading_account(self): #获取资金帐户 logging.info('A:获取资金帐户..') req = UStruct.QryTradingAccount(BrokerID=self._broker, InvestorID=self._investor) ref_id = self.inc_request_id() ret = self.ReqQryTradingAccount(req, ref_id) return ret,ref_id
def fetch_instruments_by_exchange(self, exchange_id): '''不能单独用exchange_id,因此没有意义 ''' req = ApiStruct.QryInstrument(ExchangeID=exchange_id, ) self.requestid += 1 r = self.ReqQryInstrument(req, self.requestid) print u'A:查询合约, 函数发出返回值:%s' % r
def user_login(self): self.logger.info('TD:trader to login') req = UStruct.ReqUserLogin(BrokerID=self._broker, UserID=self._investor, Password=self._passwd) ref_id = self.inc_request_id() ret = self.ReqUserLogin(req, ref_id) self.logger.info('TD:trader to login, issued') return ret
def formatOrder(traderSpi, inst, direc, open_close, volume, price): orderp = ApiStruct.InputOrder( InstrumentID=inst, Direction=direc, # ApiStruct.D_Buy or ApiStruct.D_Sell OrderRef=str(traderSpi.inc_request_id()), LimitPrice=price, VolumeTotalOriginal=volume, OrderPriceType=ApiStruct.OPT_LimitPrice, BrokerID=traderSpi.broker_id, InvestorID=traderSpi.investor_id, # BrokerID = '6868', # InvestorID = '10000360', UserID = traderSpi.investor_id, CombOffsetFlag=open_close, # OF_Open, OF_Close, OF_CloseToday CombHedgeFlag=ApiStruct.HF_Speculation, VolumeCondition=ApiStruct.VC_AV, MinVolume=1, ForceCloseReason=ApiStruct.FCC_NotForceClose, IsAutoSuspend=1, UserForceClose=0, TimeCondition=ApiStruct.TC_GFD, ) print orderp return orderp
def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast): """登录请求响应""" if pRspInfo.ErrorID == 0: self.front_id = pRspUserLogin.FrontID self.session_id = pRspUserLogin.SessionID self.is_login = True self.logger.info("CtpMiniTrader Login Successfully:{}".format( pRspInfo.ErrorMsg.decode("gbk"))) self.shfe_time = pRspUserLogin.SHFETime self.dce_time = pRspUserLogin.DCETime self.czce_time = pRspUserLogin.CZCETime self.ffex_time = pRspUserLogin.FFEXTime self.ine_time = pRspUserLogin.INETime self.login_time = pRspUserLogin.LoginTime req = ApiStruct.QrySettlementInfoConfirm( BrokerID=self.broker_id, InvestorID=self.investor_id, ) self.ReqSettlementInfoConfirm(req, self.request_id) # 否则,推送错误信息 else: self.logger.error("error_id: {}, error_msg:{}".format( pRspInfo.ErrorID, pRspInfo.ErrorMsg.decode('gbk'))) # 在某些情况下,会出现无法自动连接 # 这里我们手动进行一下重连 time.sleep(60) self.connect(self.user_id, self.password, self.broker_id, self.trade_front)
def OnFrontConnected(self): logger.info('Market OnFrontConnected: Login...') req = ApiStruct.ReqUserLogin(BrokerID=self.brokerID, UserID=self.userID, Password=self.password) self.requestID += 1 self.ReqUserLogin(req, self.requestID)
def OnRspQryInvestorPositionDetail(self, pInvestorPositionDetail, pRspInfo, nRequestID, bIsLast): if not pInvestorPositionDetail: return if self.api_type == 'close_all': close_order = ApiStruct.InputOrder( BrokerID=self.brokerID, InvestorID=self.userID, InstrumentID=pInvestorPositionDetail.InstrumentID, OrderPriceType=ApiStruct.OPT_LimitPrice, Direction=ApiStruct.D_Sell if pInvestorPositionDetail.Direction == ApiStruct.D_Buy else ApiStruct.D_Buy, VolumeTotalOriginal=pInvestorPositionDetail.Volume, TimeCondition=ApiStruct.TC_GFD, VolumeCondition=ApiStruct.VC_AV, CombHedgeFlag=ApiStruct.HF_Speculation, CombOffsetFlag=ApiStruct.OF_CloseToday, LimitPrice=models.TickData.latest( db, pInvestorPositionDetail.InstrumentID).last_price, ForceCloseReason=ApiStruct.FCC_NotForceClose, IsAutoSuspend=False, UserForceClose=False) self.requestID += 1 self.ReqOrderInsert(close_order, self.requestID) logger.info( 'Close remaining orders, instrument: {}, requestID={}'.format( pInvestorPositionDetail.InstrumentID, self.requestID))
def OnFrontConnected(self): print('OnFrontConnected: Login...') req = ApiStruct.ReqUserLogin(BrokerID=self.brokerID, UserID=self.userID, Password=self.password) self.requestID += 1 self.ReqUserLogin(req, self.requestID)
def Login(self, brokerid, investorid, password): '''登陆行情端''' UserInfo = ApiStruct.ReqUserLogin(BrokerID=brokerid, UserID=investorid, Password=password) self.IncReqid() self.ReqUserLogin(UserInfo, self.requestid)
def fetch_instrument_marginrate(self, instrument_id): req = ApiStruct.QryInstrumentMarginRate( BrokerID=self.cuser.broker_id, InvestorID=self.cuser.investor_id, InstrumentID=instrument_id, HedgeFlag=ApiStruct.HF_Speculation) r = self.trader.ReqQryInstrumentMarginRate(req, self.inc_request_id()) logging.info('A:查询保证金率, 函数发出返回值:%s' % r)
def fetch_investor_position(self, instrument_id): #获取合约的当前持仓 logging.info('A:获取合约%s的当前持仓..' % (instrument_id, )) req = UStruct.QryInvestorPosition(BrokerID=self._broker, InvestorID=self._investor, InstrumentID=instrument_id) ref_id = self.inc_request_id() ret = self.ReqQryInvestorPosition(req, self.ref_id) #logging.info('A:查询持仓, 函数发出返回值:%s' % rP) return ret,ref_id
def query_settlement_info(self): #不填日期表示取上一天结算单, 并在响应函数中确认 self.logger.info('TD:取上一日结算单信息并确认, BrokerID=%s, investorID=%s' % (self._broker, self._investor)) req = UStruct.QrySettlementInfo(BrokerID=self._broker, InvestorID=self._investor, TradingDay='') #time.sleep(1) #避免流控, 因为此时ticks未必已经开始动作, 故不采用macro_command_queue方式. 这里因为不再查询结算单是否已确认, 所以已经没有流控限制 ref_id = self.inc_request_id() ret = self.ReqQrySettlementInfo(req, ref_id) return ret
def QryMarketData(self, instrument): ok = self.settlementevent.wait(5) if ok: Instrument = ApiStruct.QryDepthMarketData(instrument) self.requestid += 1 self.ReqQryDepthMarketData(Instrument, self.requestid) else: self.logger.error('QryMarketData timeout')
def fetch_instrument(self, instrument_id): req = UStruct.QryInstrument( InstrumentID=instrument_id, ) ref_id = self.inc_request_id() ret = self.ReqQryInstrument(req, self.inc_request_id()) logging.info('A:查询合约, 函数发出返回值:%s' % ret) return ret
def user_login(self): self.logger.info('TD:trader to login') #req = UStruct.ReqUserLogin(BrokerID=self._broker.encode(encoding='utf-8', errors = 'strict'), UserID=self._investor.encode(encoding='utf-8', errors = 'strict'), Password=self._passwd.encode(encoding='utf-8', errors = 'strict')) req = UStruct.ReqUserLogin(BrokerID=self._broker, UserID=self._investor, Password=self._passwd) ref_id = self.inc_request_id() ret = self.ReqUserLogin(req, ref_id) self.logger.info('TD:trader to login, issued') return ret
def fetch_investor_position(self, instrument_id): #获取合约的当前持仓 print u'A:获取合约%s的当前持仓..' % (instrument_id, ) req = ApiStruct.QryInvestorPosition(BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=instrument_id) self.requestid += 1 r = self.ReqQryInvestorPosition(req, self.requestid)
def fetch_trading_account(self): #获取资金帐户 print u'A:获取资金帐户..' req = ApiStruct.QryTradingAccount(BrokerID=self.broker_id, InvestorID=self.investor_id) self.requestid += 1 r = self.ReqQryTradingAccount(req, self.requestid)
def req_user_login(self): """连接服务器""" # 如果填入了用户名密码等,则登录 if self.user_id and self.password and self.broker_id: req = ApiStruct.ReqUserLogin(BrokerID=self.broker_id, UserID=self.user_id, Password=self.password) self.req_id += 1 self.ReqUserLogin(req, self.req_id)
def OnFrontConnected(self): """ 当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 """ print('OnFrontConnected: Login...') req = ApiStruct.ReqUserLogin( BrokerID=self.broker_id, UserID=self.user_id, Password=self.password) self.request_id += 1 self.ReqUserLogin(req, self.request_id)
def QryInstrumentMarginRate(self, instrument): pQryInstrumentMarginRate = ApiStruct.QryInstrumentMarginRate( BrokerID=self.userinfo.BrokerID, InvestorID=self.userinfo.UserID, InstrumentID=instrument, HedgeFlag=ApiStruct.HF_Speculation) self.IncReqid() self.ReqQryInstrumentMarginRate(pQryInstrumentMarginRate, self.requestid)
def fetch_instrument_marginrate(self, instrument_id): req = ApiStruct.QryInstrumentMarginRate( BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=instrument_id, HedgeFlag=ApiStruct.HF_Speculation) self.requestid += 1 r = self.ReqQryInstrumentMarginRate(req, self.requestid) print u'A:查询保证金率%s, 函数发出返回值:%s' % (instrument_id, r)
def OnFrontConnected(self): log.info('客户端与交易后台建立连接成功, 开始登录') user_login_args = ApiStruct.ReqUserLogin(UserID=self.user, Password=self.password, BrokerID=self.broker) ret = self.ReqUserLogin(user_login_args, next(self.request_id)) if ret == 0: log.info('登录信息发送成功,等待返回')
def ReqUserLogin(self, pReqUserLoginField, nRequestID): '''用户登录请求''' self.logger.info("TAStub-ROI:%s" % (str(pReqUserLoginField), )) rul = UStruct.RspUserLogin(BrokerID=self._broker_id, FrontID=self._front_id, SessionID=self._session_id, MaxOrderRef=self._init_order_ref, TradingDay=self._trading_day) self.OnRspUserLogin(rul, self._suceessRspInfo, nRequestID, True)
def ReqQryInstrumentMarginRate(self, pQryInstrumentMarginRate, nRequestID): '''请求查询合约保证金率''' #print("query marginrate:",pQryInstrumentMarginRate.InstrumentID) im = UStruct.InstrumentMarginRate( InstrumentID=pQryInstrumentMarginRate.InstrumentID, LongMarginRatioByMoney=0.1, ShortMarginRatioByMoney=0.1) self.OnRspQryInstrumentMarginRate(im, self._suceessRspInfo, nRequestID, True)