def contractQuery(self): self._cf.read(self._cf_path) msg = fix42.Message() for name, value in self._cf.items(self._contract_query_section): if name == '35' or name == '115': msg.getHeader().setField(fix.StringField(int(name), value)) else: msg.setField(fix.StringField(int(name), value)) fix.Session.sendToTarget(msg, self._session)
def orderRequest(self): self._cf.read(self._cf_path) msg = fix42.Message() for name, value in self._cf.items(self._order_section): if name == '35' or name == '115': msg.getHeader().setField(fix.StringField(int(name), value)) else: msg.setField(fix.StringField(int(name), value)) msg.setField(fix.StringField(60, dt.datetime.utcnow().strftime("%Y%m%d-%H:%M:%S"))) fix.Session.sendToTarget(msg, self._session)
def new_order(self): print("Creating the following order: ") trade = fix.Message() trade.getHeader().setField(fix.BeginString(fix.BeginString_FIX42)) # trade.getHeader().setField(fix.MsgType( fix.MsgType_NewOrderSingle)) #35=D trade.setField(fix.ClOrdID(self.genOrderID())) #11=Unique order id trade.setField(fix.HandlInst(fix.HandlInst_MANUAL_ORDER_BEST_EXECUTION) ) #21=3 (Manual order, best executiona) trade.setField(fix.Symbol("ethbtc")) #55=ethbtc trade.setField(fix.Side(fix.Side_BUY)) #54=1 Buy trade.setField(fix.OrdType(fix.OrdType_LIMIT)) #40=2 Limit order trade.setField(fix.OrderQty(9)) #38=9 trade.setField(fix.Price(1.5)) #44=1.5 trade.setField( fix.StringField( 60, (datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f"))[:-3]) ) #60 TransactTime, not supported in python, so use tag number trade.setField(fix.Text("New Order")) #58 text print(trade.toString()) try: fix.Session.sendToTarget(trade, self.sessionID) except (fix.ConfigError, fix.RuntimeError) as e: print(e)
def getValue(fix_message, tag): field = fix.StringField(tag) if(fix_message.isSetField(field)): return (str(fix_message.getField(tag))) elif(fix_message.getHeader().isSetField(field)): return (str(fix_message.getHeader().getField(tag))) elif(fix_message.getTrailer().isSetField(field)): return (str(fix_message.getTrailer().getField(tag))) else: return None
def marketDataRequest(self): self._cf.read(self._cf_path) msg = fix42.Message() for name, value in self._cf.items(self._market_section): if name == '35' or name == '115': msg.getHeader().setField(fix.StringField(int(name), value)) elif name.isdigit(): msg.setField(fix.StringField(int(name), value)) elif name == 'entrytypes': type_group = fix42.MarketDataRequest().NoMDEntryTypes() for entry in value.split(';'): type_group.setField(fix.MDEntryType(entry)) msg.addGroup(type_group) elif name == 'symbols': sym_group = fix42.MarketDataRequest().NoRelatedSym() for sym in value.split(';'): sym_group.setField(fix.Symbol(sym)) msg.addGroup(sym_group) fix.Session.sendToTarget(msg, self._session)
def list_cancel_request(self): message = fix.Message() header = message.getHeader() header.setField(fix.BeginString(fix.BeginString_FIX42)) header.setField(fix.MsgType(fix.MsgType_ListCancelRequest)) #35=K message.setField(fix.ListID("List123Test")) message.setField( fix.StringField( 60, (datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f"))[:-3]) ) #60 TransactTime, not supported in python, so use tag number print(message.toString()) try: fix.Session.sendToTarget(message, self.sessionID) except (fix.ConfigError, fix.RuntimeError) as e: print(e)
def toAdmin(self, message, sessionID): try: msgType = fix.MsgType() message.getHeader().getField(msgType) if msgType.getValue() == fix.MsgType_Logon: uuid = self.Settings.get().getString('Username') password = self.Settings.get().getString('Password') message.getHeader().setField(fix.Password(password)) message.getHeader().setField(fix.StringField(12003, uuid)) self.Logger.info( "Sending Admin message to server. Session: %s. Message: %s" % (sessionID, message)) self.__messageStore.addRequest(message) except fix.RuntimeError as e: self.Logger.error('Error in toAdmin', e) return
def on_parent_order(self, message: fix.Message): """""" parent_orderid = get_field_value(message, fix.ClOrdID()) # Get parent orderid of cancel request if parent_orderid.startswith("Cancel"): parent_orderid = get_field_value(message, fix.OrigClOrdID()) # If this parent order is from previous session if parent_orderid not in self.algo_settings: # Cancel it to avoid future update self.cancel_parent_order(parent_orderid) return tradeid = get_field_value(message, fix.ExecID()) status = get_field_value(message, fix.OrdStatus()) side = get_field_value(message, fix.Side()) genus_symbol = get_field_value(message, fix.Symbol()) order_traded = get_field_value(message, fix.CumQty()) text = get_field_value(message, fix.Text()) algo_type = get_field_value(message, fix.StringField(847)) variables = {"推送编号": tradeid, "已成交": order_traded, "算法信息": text} self.algo_settings[parent_orderid] = { "symbol": genus_symbol, "side": side, "algo_type": algo_type } # Add algo active status if status in {"0", "1", "5", "6", "A", "D", "E"}: variables["active"] = True else: variables["active"] = False if status == "C": self.client.write_log("执行时间已结束,停止算法", parent_orderid) self.client.put_variables_event(parent_orderid, variables)
def cancel_order(self): message = fix.Message() header = message.getHeader() header.setField(fix.BeginString(fix.BeginString_FIX42)) header.setField(fix.MsgType(fix.MsgType_OrderCancelRequest)) #35=F originalOrderId = str(int(self.genOrderID()) - 1) message.setField(fix.OrigClOrdID(originalOrderId)) message.setField(fix.ClOrdID(str(int(originalOrderId) + 1))) #11=Unique order id message.setField(fix.OrderID("375")) message.setField(fix.Symbol("ABCD")) #55=ABCD message.setField(fix.Side(fix.Side_BUY)) #54=1 Buy message.setField( fix.StringField( 60, (datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f"))[:-3]) ) #60 TransactTime, not supported in python, so use tag number message.setField(fix.Text("Cancel my Order")) #58 text print(message.toString()) try: fix.Session.sendToTarget(message, self.sessionID) except (fix.ConfigError, fix.RuntimeError) as e: print(e)
def new_child_order(self, message: fix.Message): """""" child_order = GenusChildOrder( cl_ord_id=get_field_value(message, fix.ClOrdID()), symbol=get_field_value(message, fix.Symbol()), side=get_field_value(message, fix.Side()), order_qty=get_field_value(message, fix.OrderQty()), price=get_field_value(message, fix.Price()), order_type=get_field_value(message, fix.OrdType()), ord_status="A", parent_orderid=get_field_value(message, fix.StringField(526))) # If parent offset not exist, then this child order should be ignored offset = self.client.get_parent_offset(child_order.parent_orderid) if not offset: return symbol, genus_exchange = child_order.symbol.split(".") exchange = EXCHANGE_GNS2VT[genus_exchange] direction = DIRECTION_GNS2VT[child_order.side] order_type = ORDERTYPE_GNS2VT[child_order.order_type] vt_symbol = generate_vt_symbol(symbol, exchange) child_order.order_id = self.client.send_order( vt_symbol, direction, offset, order_type, child_order.price, child_order.order_qty, ) self.child_orders[child_order.order_id] = child_order self.genus_vt_map[child_order.cl_ord_id] = child_order.order_id msg = f"委托{direction.value}{vt_symbol}:{child_order.order_qty}@{child_order.price}" self.client.write_log(msg, algo_name=child_order.parent_orderid)
def quote_request(self,symbol,currency,quantity,side,order_type,price=None): #HEADER trade = fix50sp2.QuoteRequest() trade.getHeader().setField(fix.StringField(8,'FIXT.1.1')) #BeginMessage trade.getHeader().setField(fix.StringField(35,'R'))#MessageType trade.getHeader().setField(fix.StringField(1128,'9')) #ApplVerID - FIX50SP2 trade.getHeader().setField(fix.StringField(49,'ORP_RESZ_B')) trade.getHeader().setField(fix.StringField(56,'BLPORPBETA')) trade.getHeader().setField(fix.StringField(128,'DOR')) trade.getHeader().setField(fix.SendingTime(1))#52 trade.getHeader().setField(fix.StringField(1156,'208'))#ApplExtID trade.getHeader().setField(fix.StringField(1129,'1.5'))#CstmApplVerID #BODY trade.setField(fix.QuoteReqID(datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S') + symbol + 'RFQ' + str(side))) # 131 group_146 = fix50sp2.QuoteRequest().NoRelatedSym() # group_146 = fix.Group(146,1) if '/' not in symbol: group_146.setField(fix.StringField(55,str(symbol[:3]+'/'+symbol[3:]))) else: group_146.setField(fix.StringField(55, str(symbol))) group_146.setField(fix.StringField(167,'FXSPOT')) group_146.setField(fix.IntField(460,4)) group_146.setField(fix.SettlType('0'))#SettlType # group_146.setField(fix.StringField(63,'0'))#SettlType settl_date = datetime.datetime.utcnow()+BDay(n=2) group_146.setField(fix.SettlDate(settl_date.strftime('%Y%m%d')))#SettlDate group_146.setField(fix.OrderQty(quantity))#38 - Qty group_146.setField(fix.StringField(15,str(currency)))#Currency group_146.setField(fix.StringField(54,str(side))) # trade.setField(fix.NoPartyIDs(4))#453 - NumberOfParties group_453 = fix50sp2.QuoteRequest().NoRelatedSym().NoPartyIDs() # group_453 = fix.Group(453,1) group_453.setField(fix.StringField(448,'7613723'))#PartyID group_453.setField(fix.StringField(447,'D'))#PartyIDSource group_453.setField(fix.PartyRole(11))#452 - PartyRole group_146.addGroup(group_453) group_453.setField(fix.StringField(448,'BGD1'))#PartyID group_453.setField(fix.StringField(447,'D'))#PartyIDSource group_453.setField(fix.PartyRole(1))#452 - PartyRole. group_146.addGroup(group_453) group_453.setField(fix.StringField(448,'DOR1'))#PartyID group_453.setField(fix.StringField(447,'D'))#PartyIDSource group_453.setField(fix.PartyRole(1))#452 - PartyRole. group_146.addGroup(group_453) group_453.setField(fix.StringField(448,'DOR2'))#PartyID group_453.setField(fix.StringField(447,'D'))#PartyIDSource group_453.setField(fix.PartyRole(1))#452 - PartyRole. group_146.addGroup(group_453) trade.addGroup(group_146) trade.setField(fix.StringField(1300,'XOFF'))#market segment id # trade.setField(fix.StringField(21,'z'))#HandlInst if order_type == '2': # limit trade.setField(fix.Price(float(price))) # if market, this tag should be absent else: price = None print(f'CREATING THE FOLLOWING ORDER:\n ') # print(f'CREATING THE FOLLOWING ORDER:\n {trade.toString()}') fix.Session.sendToTarget(trade, self.sessionID)
def quote_response(self,quote_req_id,quote_id,quote_resp_type,symbol,product,side,dealer_id,price=None,currency = None,quantity = None): #HEADER quote_resp = fix50sp2.QuoteRequest() quote_resp.getHeader().setField(fix.StringField(8,'FIXT.1.1')) #BeginMessage quote_resp.getHeader().setField(fix.StringField(35,'AJ'))#MessageType quote_resp.getHeader().setField(fix.StringField(1128,'9')) #ApplVerID - FIX50SP2 quote_resp.getHeader().setField(fix.StringField(49,'ORP_RESZ_B')) quote_resp.getHeader().setField(fix.StringField(56,'BLPORPBETA')) quote_resp.getHeader().setField(fix.StringField(128,'DOR')) quote_resp.getHeader().setField(fix.SendingTime(1))#52 quote_resp.getHeader().setField(fix.StringField(1156,'208'))#ApplExtID quote_resp.getHeader().setField(fix.StringField(1129,'1.5'))#CstmApplVerID quote_resp.getHeader().setField(fix.SendingTime(1)) #BODY quote_resp.setField(fix.QuoteRespID(quote_req_id[:-4] + 'RESP' + self.genOrderID()))#693 quote_resp.setField(fix.QuoteReqID(quote_req_id)) #131 quote_resp.setField(fix.QuoteRespType(quote_resp_type))#694 quote_resp.setField(fix.Symbol(symbol))#55 quote_resp.setField(fix.Product(int(product)))#460 quote_resp.setField(fix.Side(side))#54 quote_resp.setField(fix.StringField(167,'FXSPOT')) print(datetime.datetime.utcnow().strftime('%Y%m%d-%H:%M:%S')) quote_resp.setField(fix.StringField(60,datetime.datetime.utcnow().strftime('%Y%m%d-%H:%M:%S')))#60 # quote_resp.setField(fix.TransactTime(1))#60 quote_resp.setField(fix.SettlType('0'))#63 settl_date = datetime.datetime.utcnow()+BDay(n=2) quote_resp.setField(fix.SettlDate(settl_date.strftime('%Y%m%d')))#64 if quote_resp_type == 1: # quote_resp.setField(fix.Price(float(price))) quote_resp.setField(fix.OfferPx(float(price))) quote_resp.setField(fix.OfferSpotRate(float(price))) quote_resp.setField(fix.StringField(15, str(currency))) # Currency # quote_resp.setField(fix.BidPx(float(price))) quote_resp.setField(fix.QuoteID(quote_id)) # 117 quote_resp.setField(fix.OrderQty(quantity)) #38 quote_resp.setField(fix.ClOrdID(quote_resp.getField(693)+self.genOrderID())) # 11 group_453 = fix50sp2.QuoteRequest().NoRelatedSym().NoPartyIDs() group_453.setField(fix.StringField(448,'7613723'))#PartyID group_453.setField(fix.StringField(447,'D'))#PartyIDSource group_453.setField(fix.PartyRole(11))#452 - PartyRole quote_resp.addGroup(group_453) group_453.setField(fix.StringField(448,dealer_id))#PartyID group_453.setField(fix.StringField(447,'D'))#PartyIDSource group_453.setField(fix.PartyRole(1))#452 - PartyRole. quote_resp.addGroup(group_453) quote_resp.setField(fix.StringField(1300,'XOFF'))#market segment id print(f'SENDING QUOTE RESPONSE MESSAGE:\n ') # print(f'SENDING QUOTE RESPONSE MESSAGE:\n {quote_resp.toString()}') fix.Session.sendToTarget(quote_resp, self.sessionID)
def quote_request(self,symbol,currency,quantity,side,order_type,dealers_dict): ''' send QuoteRequest message to Liquidity Providers build the message according to ORP_v1.5_QuickFIX ''' #HEADER trade = fix50sp2.QuoteRequest() trade.getHeader().setField(fix.StringField(8,'FIXT.1.1')) #BeginMessage trade.getHeader().setField(fix.StringField(35,'R'))#MessageType trade.getHeader().setField(fix.StringField(1128,'9')) #ApplVerID - FIX50SP2 trade.getHeader().setField(fix.StringField(49,'ORP_RESZ_B')) trade.getHeader().setField(fix.StringField(56,'BLPORPBETA')) trade.getHeader().setField(fix.StringField(128,'DOR')) trade.getHeader().setField(fix.SendingTime(1))#52 trade.getHeader().setField(fix.StringField(1156,'208'))#ApplExtID trade.getHeader().setField(fix.StringField(1129,'1.5'))#CstmApplVerID #BODY #QuoteReqID (131) --> RFQ+datetime+symbol+side quote_request_id = 'RFQ' + datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S') + symbol + str(side) trade.setField(fix.QuoteReqID(quote_request_id)) # 131 group_146 = fix50sp2.QuoteRequest().NoRelatedSym() if '/' not in symbol: group_146.setField(fix.StringField(55,str(symbol[:3]+'/'+symbol[3:6]))) else: group_146.setField(fix.StringField(55, str(symbol))) group_146.setField(fix.StringField(167,'FXSPOT')) group_146.setField(fix.IntField(460,4)) group_146.setField(fix.SettlType('0'))#SettlType # settl_date = datetime.datetime.utcnow()+BDay(n=2) if ((datetime.datetime.utcnow() - datetime.timedelta(hours = 4)).hour < 17) or ((datetime.datetime.utcnow() - datetime.timedelta(hours = 4)).weekday() == 6): settl_date = datetime.datetime.utcnow()+BDay(n=2) else: settl_date = datetime.datetime.utcnow() + BDay(n=3) while (settl_date.strftime('%Y%m%d') in HOLIDAYS_DICT[symbol[:3]]) or (settl_date.strftime('%Y%m%d') in HOLIDAYS_DICT[symbol[-3:]]): settl_date += BDay(n=1) group_146.setField(fix.SettlDate(settl_date.strftime('%Y%m%d')))#SettlDate group_146.setField(fix.OrderQty(quantity))#38 - Qty group_146.setField(fix.StringField(15,str(currency)))#Currency #if side == 0, get two way quotes (omit tag 54) if side != 0: group_146.setField(fix.StringField(54,str(side))) group_453 = fix50sp2.QuoteRequest().NoRelatedSym().NoPartyIDs() for dealer, party_role in dealers_dict.items(): group_453.setField(fix.StringField(448,dealer))#PartyID group_453.setField(fix.StringField(447,'D'))#PartyIDSource group_453.setField(fix.PartyRole(party_role))#452 - PartyRole. group_146.addGroup(group_453) trade.addGroup(group_146) trade.setField(fix.StringField(1300,'XOFF'))#market segment id # trade.setField(fix.StringField(21,'z'))#HandlInst if order_type == '2': # limit trade.setField(fix.Price(float(self.limit_price))) # if market, this tag should be absent print(f'CREATING THE FOLLOWING ORDER:\n {trade.toString()}') fix.Session.sendToTarget(trade, self.sessionID)