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 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 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 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 xopen(self, instrument_id, direction, volume, price): ref_id = self.inc_request_id() ''' self.BrokerID = '' #经纪公司代码, char[11] self.InvestorID = '' #投资者代码, char[13] self.InstrumentID = '' #合约代码, char[31] self.OrderRef = '' #报单引用, char[13] self.UserID = '' #用户代码, char[16] self.OrderPriceType = '' #报单价格条件, char self.Direction = '' #买卖方向, char self.CombOffsetFlag = '' #组合开平标志, char[5] self.CombHedgeFlag = '' #组合投机套保标志, char[5] self.LimitPrice = 'Price' #价格, double self.VolumeTotalOriginal = 'Volume' #数量, int self.TimeCondition = '' #有效期类型, char self.GTDDate = 'Date' #GTD日期, char[9] self.VolumeCondition = '' #成交量类型, char self.MinVolume = 'Volume' #最小成交量, int self.ContingentCondition = '' #触发条件, char self.StopPrice = 'Price' #止损价, double self.ForceCloseReason = '' #强平原因, char self.IsAutoSuspend = 'Bool' #自动挂起标志, int self.BusinessUnit = '' #业务单元, char[21] self.RequestID = '' #请求编号, int self.UserForceClose = 'Bool' #用户强评标志, int self.IsSwapOrder = 'Bool' #互换单标志, int ''' #print("spidelegate,xopen",str(ref_id).encode(encoding='utf-8', errors = 'strict'),self.to_ctp_direction(direction),instrument_id,volume,price,self._broker,self._investor,self) print("spidelegate,xopen",str(ref_id).encode(encoding='utf-8', errors = 'strict'),UType.OF_Open,UType.HF_Speculation) req = UStruct.InputOrder( InstrumentID = instrument_id.encode(encoding='utf-8', errors = 'strict'), Direction = self.to_ctp_direction(direction), OrderRef = str(ref_id).encode(encoding='utf-8', errors = 'strict'), 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 close_orders_for_any_price(self): orders = list() if self.Position > 0: orders.append( ApiStruct.InputOrder( BrokerID=self.BrokerID, InvestorID=self.InvestorID, InstrumentID=self.InstrumentID, OrderPriceType=ApiStruct.OPT_AnyPrice, Direction=self.CloseDirection, VolumeTotalOriginal=self.Position, TimeCondition=ApiStruct.TC_GFD, VolumeCondition=ApiStruct.VC_AV, CombHedgeFlag=self.HedgeFlag, CombOffsetFlag=ApiStruct.OF_CloseToday, ForceCloseReason=ApiStruct.FCC_NotForceClose, IsAutoSuspend=False, UserForceClose=False)) return orders
def SendOrder(self, instrument, direction, offsetflag, volume, price): '''发送报单''' if offsetflag != ApiStruct.OF_Open: #平仓则判定是否当下session持仓数量是否合法 with self.positionlock: ind = (instrument, str(1 - int(direction))) #转换相反持仓信息index if ind not in self.position or len(self.position[ind]) == 0: self.logger.error('SendOrder[%s, %s]: not exist volume' % ind) return else: ans = 0 for i in self.position[ind]: ans += i.Volume if ans < volume: self.logger.error( 'SendOrder[%s, %s]: No enough volume' % ind) return #下单 with self.maxorderreflock: self.maxorderref += 1 pInputOrder = ApiStruct.InputOrder( BrokerID=self.brokerid, InvestorID=self.investorid, InstrumentID=instrument, OrderRef=str(self.maxorderref), OrderPriceType=ApiStruct.OPT_LimitPrice, Direction=direction, CombOffsetFlag=offsetflag, CombHedgeFlag=ApiStruct.HF_Speculation, LimitPrice=price, VolumeTotalOriginal=volume, TimeCondition=ApiStruct.TC_GFD, VolumeCondition=ApiStruct.VC_AV, MinVolume=1, ContingentCondition=ApiStruct.CC_Immediately, ) self.IncReqid() self.ReqOrderInsert(pInputOrder, self.requestid)
def close_orders_for_limited_price(self, db): orders = list() # if self.YdPosition > 0: # orders.append(ApiStruct.InputOrder( # BrokerID=self.BrokerID, # InvestorID=self.InvestorID, # InstrumentID=self.InstrumentID, # OrderPriceType=ApiStruct.OPT_LimitPrice, # Direction=self.CloseDirection, # VolumeTotalOriginal=self.YdPosition, # TimeCondition=ApiStruct.TC_GFD, # VolumeCondition=ApiStruct.VC_AV, # CombHedgeFlag=self.HedgeFlag, # CombOffsetFlag=ApiStruct.OF_CloseYesterday, # LimitPrice=TickData.latest(db, self.InstrumentID).last_price, # ForceCloseReason=ApiStruct.FCC_NotForceClose, # IsAutoSuspend=False, # UserForceClose=False # )) if self.Position > 0: orders.append( ApiStruct.InputOrder( BrokerID=self.BrokerID, InvestorID=self.InvestorID, InstrumentID=self.InstrumentID, OrderPriceType=ApiStruct.OPT_LimitPrice, Direction=self.CloseDirection, VolumeTotalOriginal=self.Position, TimeCondition=ApiStruct.TC_GFD, VolumeCondition=ApiStruct.VC_AV, CombHedgeFlag=self.HedgeFlag, CombOffsetFlag=ApiStruct.OF_CloseToday, LimitPrice=TickData.latest(db, self.InstrumentID).last_price, ForceCloseReason=ApiStruct.FCC_NotForceClose, IsAutoSuspend=False, UserForceClose=False)) return orders
def followOrder(): # global orderList from ctp_win32 import ApiStruct # from Strategy import Strategy # s = S = ApiStruct.D_Sell # b = B = ApiStruct.D_Buy # k = K = ApiStruct.OF_Open # p = P = ApiStruct.OF_Close # from colorama import init, Fore, Back, Style # from TraderDelegate import TraderDelegate # from tapy import cross, crossdown # init() try: #读取账户信息 acinfo = shelve.open(msfile) BROKER_ID = acinfo['BROKER_ID'] INVESTOR_ID = acinfo['INVESTOR_ID'] PASSWORD = acinfo['PASSWORD'] ADDR_MD = acinfo['ADDR_MD'] ADDR_TRADE = acinfo['ADDR_TRADE'] acinfo.close() flacinfo = shelve.open(flfile) flBROKER_ID = flacinfo['BROKER_ID'] flINVESTOR_ID = flacinfo['INVESTOR_ID'] flPASSWORD = flacinfo['PASSWORD'] flADDR_MD = flacinfo['ADDR_MD'] flADDR_TRADE = flacinfo['ADDR_TRADE'] flacinfo.close() master_trade = TraderDelegate(broker_id=BROKER_ID, investor_id=INVESTOR_ID, passwd=PASSWORD, userProductInfo='webstock') master_trade.Create(LOGS_DIR + BROKER_ID) # T = {} # T['TE_RESUME'] = 'int' # 流重传方式 # TERT_RESTART = 0 # 从本交易日开始重传 # TERT_RESUME = 1 # 从上次收到的续传 # TERT_QUICK = 2 # 只传送登录后的流内容 master_trade.SubscribePublicTopic(1) master_trade.SubscribePrivateTopic(1) master_trade.RegisterFront(ADDR_TRADE) master_trade.Init() print BROKER_ID, INVESTOR_ID print u'主帐号登录完成。' followTrader1 = TraderDelegate(broker_id=flBROKER_ID, investor_id=flINVESTOR_ID, passwd=flPASSWORD) followTrader1.Create('f1') followTrader1.RegisterFront(flADDR_TRADE) followTrader1.SubscribePublicTopic(ApiStruct.TERT_QUICK) followTrader1.SubscribePrivateTopic(ApiStruct.TERT_QUICK) followTrader1.Init() print u'跟单账号:', flINVESTOR_ID, u'登录完成。' except IOError: print IOError return while True: try: order_master = q_order_list.get(timeout=1) q_order_list.task_done() om = deepcopy(order_master) # order_master = orderList[-1] if orderList else q_order_list.get() if om.InvestorID == master_trade.investor_id: print u'主帐号下单:' print time.asctime(), u'下单时间:', om.InsertTime, u'帐号',om.InvestorID, u'合约:',om.InstrumentID,u'方向:',om.Direction,\ u'开平:',om.CombOffsetFlag print u'数量:', om.VolumeTotalOriginal, u'价格:', om.LimitPrice if om.InvestorID == followTrader1.investor_id: print u'跟单账号下单:', om # print str(j.FrontID)+str(j.SessionID).strip()+j.OrderRef,j.SequenceNo, j.BrokerOrderSeq, j.RequestID,j.OrderSysID,j.OrderStatus,j.OrderLocalID # print j.InsertTime # print '--'*50 # print order_master.InsertDate, # print order_master.InsertTime, # print order_master.StatusMsg.decode('gbk'), # print order_master.OrderSource.decode('gbk') # print order_master.BrokerID, # print order_master.InvestorID # print order_master.InstrumentID, # print order_master.LimitPrice, # print order_master.Direction, # print order_master.CombOffsetFlag # print order_master.CombHedgeFlag # print order_master.OrderPriceType # print order_master.RequestID # print order_master.UserProductInfo # print order_master.InvestorID, master_trade.investor_id if order_master.InvestorID == master_trade.investor_id: order = ApiStruct.InputOrder( BrokerID=followTrader1.broker_id, InvestorID=followTrader1.investor_id, UserID=followTrader1.investor_id) # order.BrokerID = followTrader1.broker_id # order.InvestorID = followTrader1.investor_id order.InstrumentID = order_master.InstrumentID order.Direction = order_master.Direction order.CombHedgeFlag = order_master.CombHedgeFlag order.CombOffsetFlag = order_master.CombOffsetFlag order.LimitPrice = order_master.LimitPrice order.VolumeTotalOriginal = order_master.VolumeTotalOriginal order.VolumeTotal = order_master.VolumeTotal order.MinVolume = 1 order.OrderPriceType = order_master.OrderPriceType order.OrderRef = order_master.OrderRef # order.RequestID = order_master.RequestID order.ForceCloseReason = ApiStruct.FCC_NotForceClose order.IsAutoSuspend = 1 order.UserForceClose = 0 order.TimeCondition = ApiStruct.TC_GFD order.VolumeCondition = ApiStruct.VC_AV followTrader1.ReqOrderInsert(order, order_master.RequestID) except Queue.Empty as e: pass
def ReqOrderInsert2(self, InstrumentID, LimitPrice, Volumes, Direction=ApiStruct.D_Buy, TimeCondition=ApiStruct.TC_IOC, CombOffsetFlag=ApiStruct.OF_Open, OrderPriceType='2'): """ OrderPriceType: #报单价格条件, char OPT_AnyPrice = '1' #任意价 OPT_LimitPrice = '2' #限价 OPT_BestPrice = '3' #最优价 OPT_LastPrice = '4' #最新价 Direction: D_Buy = '0' #买 D_Sell = '1' #卖 TimeCondition: #有效期类型, char TC_IOC = '1' #立即完成,否则撤销 TC_GFS = '2' #本节有效 TC_GFD = '3' #当日有效 TC_GTD = '4' #指定日期前有效 TC_GTC = '5' #撤销前有效 TC_GFA = '6' #集合竞价有效 CombOffsetFlag: OF_Open = '0' #开仓 OF_Close = '1' #平仓 OF_ForceClose = '2' #强平 OF_CloseToday = '3' #平今 OF_CloseYesterday = '4' #平昨 OF_ForceOff = '5' #强减 OF_LocalForceClose = '6' #本地强平 VolumeCondition: #成交量类型, char VC_AV = '1' #任何数量 VC_MV = '2' #最小数量 VC_CV = '3' #全部数量 ContingentCondition: #触发条件, char CC_Immediately = '1' #立即 CC_Touch = '2' #止损 CC_TouchProfit = '3' #止赢 CC_ParkedOrder = '4' #预埋单 ForceCloseReason: #强平原因, char FCC_NotForceClose = '0' #非强平 FCC_LackDeposit = '1' #资金不足 FCC_ClientOverPositionLimit = '2' #客户超仓 FCC_MemberOverPositionLimit = '3' #会员超仓 FCC_NotMultiple = '4' #持仓非整数倍 FCC_Violation = '5' #违规 FCC_Other = '6' #其它 FCC_PersonDeliv = '7' #自然人临近交割 """ self.request_id += 1 self.ReqOrderInsert( ApiStruct.InputOrder( BrokerID=self.broker_id, InvestorID=self.investor_id, InstrumentID=InstrumentID, OrderRef='', UserID='', OrderPriceType=OrderPriceType, Direction=Direction, CombOffsetFlag=CombOffsetFlag, LimitPrice=LimitPrice, CombHedgeFlag='1', VolumeTotalOriginal=Volumes, TimeCondition=TimeCondition, GTDDate='', VolumeCondition='1', MinVolume=0, ContingentCondition='1', StopPrice=0.0, ForceCloseReason='0', # IsAutoSuspend=0, # BusinessUnit='', # RequestID=0, # UserForceClose=0, # IsSwapOrder=0 ), self.request_id) self.wait(InstrumentID, LimitPrice)