def test_checkIsInMessage(self): self.object.setVersion(fix.BeginString_FIX40) self.object.addField(fix.BeginString().getTag()) self.object.addField(fix.BodyLength().getTag()) self.object.addField(fix.MsgType().getTag()) self.object.addField(fix.CheckSum().getTag()) self.object.addField(fix.TestReqID().getTag()) self.object.addField(fix.Symbol().getTag()) self.object.addMsgType(fix.MsgType_TestRequest) self.object.addMsgField(fix.MsgType_TestRequest, fix.TestReqID().getTag()) testReqID = fix.TestReqID("1") message = fix40.TestRequest() message.setField(testReqID) try: self.object.validate(message) self.failUnless(1) except fix.Exception as e: self.failUnless(0) message.setField(fix.Symbol("MSFT")) try: self.object.validate(message) self.failUnless(0) except fix.Exception as e: self.failUnless(1)
def run(self): logon = fix44.Logon() #Keep sending a sample set of messages to server, where the second message while (1): message = fix.Message() header = message.getHeader() header.setField(fix.BeginString("FIX.4.4")) header.setField(fix.SenderCompID("COEPUSER")) header.setField(fix.TargetCompID("COEPEXCH")) header.setField(fix.MsgType("D")) message.setField(fix.ClOrdID("3")) message.setField(fix.Symbol("amzn")) message.setField(fix.Side(Side_BUY)) message.setField(58, "Buy shares") message.setField(fix.Price(87)) message.setField(fix.OrderQty(2)) transact_time = datetime.utcnow() message.setField(60, transact_time.strftime("%Y%m%d-22:29:00.000")) message.setField(fix.Account("EXECLINKS")) message.setField(40, "2") status = fix.Session.sendToTarget(message, self.sessionID) print("Status: ", status) print(message) time.sleep(5) message = fix.Message() header = message.getHeader() header.setField(fix.BeginString("FIX.4.4")) header.setField(fix.SenderCompID("COEPUSER")) header.setField(fix.TargetCompID("COEPEXCH")) header.setField(fix.MsgType("D")) message.setField(fix.ClOrdID("3")) message.setField(fix.Symbol("amzn")) message.setField(fix.Side(Side_SELL)) message.setField(58, "Sell shares") message.setField(fix.Price(87)) message.setField(fix.OrderQty(2)) transact_time = datetime.utcnow() message.setField(60, transact_time.strftime("%Y%m%d-22:29:00.000")) message.setField(fix.Account("EXECLINKS")) message.setField(40, "2") status = fix.Session.sendToTarget(message, self.sessionID) print("Status: ", status) print(message) time.sleep(100)
def onMessage_SecurityList(self) -> dict: group = fix50.SecurityList().NoRelatedSym() # print(group) mktSegmentID = self.getValue(fix.MarketSegmentID()) noRelatedSym = self.getValue(fix.NoRelatedSym()) mktSegment = {} tickerData = {} #allSecurities = {} for tickers in range(1, noRelatedSym + 1): self.message.getGroup(tickers, group) aux = { 'symbol': self.getValueGroup(group, fix.Symbol()), 'factor': self.getValueGroup(group, fix.Factor()), 'securityDesc': self.getValueGroup(group, fix.SecurityDesc()), 'cfiCode': self.getValueGroup(group, fix.CFICode()), 'contractMultiplier': self.getValueGroup(group, fix.ContractMultiplier()), 'minPriceIncrement': self.getValueGroup(group, fix.MinPriceIncrement()), 'tickSize': group.getField(5023), 'instrumentPricePrecision': group.getField(5514), 'instrumentSizePrecision': group.getField(7117), 'currency': self.getValueGroup(group, fix.Currency()), 'maxTradeVol': self.getValueGroup(group, fix.MaxTradeVol()), 'minTradeVol': self.getValueGroup(group, fix.MinTradeVol()), 'lowLimitPrice': self.getValueGroup(group, fix.LowLimitPrice()), 'highLimitPrice': self.getValueGroup(group, fix.HighLimitPrice()) } tickerData[self.getValueGroup(group, fix.Symbol())] = aux mktSegment[mktSegmentID] = tickerData # para unir todos los diccionarios en 1 #allSecurities[mktSegmentID] = mktSegment return mktSegment
def newOrderSingle(self): try: LOG_EVENT("New Order Single") orderMsg = fix.Message() orderMsg.getHeader().setField(self.sessionID.getBeginString()) orderMsg.getHeader().setField( fix.MsgType(fix.MsgType_NewOrderSingle)) orderMsg.getHeader().setField(self.sessionID.getSenderCompID()) orderMsg.getHeader().setField(self.sessionID.getTargetCompID()) orderMsg.getHeader().setField(fix.MsgSeqNum(self.genOrderID())) sendingTime = fix.SendingTime() sendingTime.setString( datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f")) orderMsg.getHeader().setField(sendingTime) orderMsg.setField(fix.Account("17018382")) orderMsg.setField(fix.ClOrdID(self.genExecID())) orderMsg.setField(fix.OrderQty(100)) orderMsg.setField(fix.OrdType(fix.TriggerOrderType_LIMIT)) orderMsg.setField(fix.Price(1.216)) orderMsg.setField(fix.Symbol("X.US.OREURUSD")) orderMsg.setField(fix.Side(fix.Side_BUY)) tranactionTime = fix.TransactTime() tranactionTime.setString( datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f")) orderMsg.setField(tranactionTime) orderMsg.setField(fix.OpenClose(fix.OpenClose_OPEN)) LOG_PACKET(orderMsg.toString()) fix.Session.sendToTarget(orderMsg, self.sessionID) except Exception as e: print(e)
def cancel(self, message, sessionID): symbol = fix.Symbol() side = fix.Side() orderQty = fix.OrderQty() clOrdID = fix.ClOrdID() org = fix.OrigClOrdID() message.getField(symbol) message.getField(side) message.getField(orderQty) message.getField(clOrdID) message.getField(org) log.info("cancel:\nsymbol:{},side:{},orderQty:{},clOrdID:{},org:{} -----"\ .format(symbol, side, orderQty, clOrdID, org)) cancel = fix44.OrderCancelReject() cancel.setField(clOrdID) cancel.setField(fix.OrderID(self.genOrderID())) cancel.setField(fix.OrdStatus(fix.OrdStatus_NEW)) cancel.setField(fix.OrigClOrdID(org.getValue())) cancel.setField(fix.Text('order completed')) cancel.setField(fix.TransactTime()) cancel.setField(fix.CxlRejReason(fix.CxlRejReason_BROKER)) cancel.setField( fix.CxlRejResponseTo(fix.CxlRejResponseTo_ORDER_CANCEL_REQUEST)) fix.Session.sendToTarget(cancel, sessionID)
def market_data_request(self, sender_comp_id, target_comp_id, symbols): md_types = [ fix.MDEntryType_BID, fix.MDEntryType_OFFER, fix.MDEntryType_TRADE ] message = fix42.MarketDataRequest() header = message.getHeader() header.setField(fix.SenderCompID(sender_comp_id)) header.setField(fix.TargetCompID(target_comp_id)) message.setField(fix.MDReqID(self._generate_id())) message.setField( fix.SubscriptionRequestType( fix.SubscriptionRequestType_SNAPSHOT_PLUS_UPDATES)) message.setField(fix.MarketDepth(10)) group = fix42.MarketDataRequest().NoMDEntryTypes() for md_type in md_types: group.setField(fix.MDEntryType(md_type)) message.addGroup(group) group = fix42.MarketDataRequest().NoRelatedSym() for symbol in symbols: group.setField(fix.Symbol(symbol)) message.addGroup(group) try: fix.Session.sendToTarget(message) except fix.SessionNotFound: raise Exception(f"No session found {message}, exiting...")
def __init__(self, symbol, maturity, qty): super(FutureOrder, self).__init__() self.CFICode = fix.CFICode('FXXXXS') self.Symbol = fix.Symbol(symbol) self.Maturity = fix.MaturityMonthYear(maturity) self.Quantity = fix.OrderQty(qty) self.TransactionTime = fix.TransactTime()
def createOrderBookRequest(self): orderBookRequest = fix44.MarketDataRequest() noRelatedSym = fix44.MarketDataRequest.NoRelatedSym() noRelatedSym.setField(fix.Symbol('BTC/CNY')) orderBookRequest.addGroup(noRelatedSym) orderBookRequest.setField( fix.MDReqID("123")) # Unique ID assigned to this request orderBookRequest.setField( fix.SubscriptionRequestType('1')) # 0 = Snapshot # 1 = Snapshot + Subscribe # 2 Unsubscribe orderBookRequest.setField( fix.MDUpdateType(1)) # 0 = full refresh, 1: incremental refresh orderBookRequest.setField(fix.MarketDepth(0)) # 0 = full book, group1 = fix44.MarketDataRequest.NoMDEntryTypes() group1.setField(fix.MDEntryType('0')) # bids orderBookRequest.addGroup(group1) group2 = fix44.MarketDataRequest.NoMDEntryTypes() group2.setField(fix.MDEntryType('1')) # asks orderBookRequest.addGroup(group2) return orderBookRequest
def put_new_order(self, instrument, side, price, size): """Request sample new order single""" message = quickfix44.NewOrderSingle() header = message.getHeader() print("Executing : " + str(instrument) + ":" + str(side) + ":" + str(price) + ":" + str(size)) message.setField(quickfix.ClOrdID(self.genExecID())) message.setField(quickfix.Side(side)) message.setField(quickfix.Symbol(instrument.symbol)) message.setField(quickfix.SecurityExchange(instrument.exchange)) message.setField(quickfix.OrderQty(size)) message.setField(quickfix.Price(int(price))) message.setField(quickfix.OrdType(quickfix.OrdType_LIMIT)) message.setField(quickfix.TimeInForce('0')) message.setField(quickfix.Text("NewOrderSingle")) trstime = quickfix.TransactTime() trstime.setString( datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f")[:-3]) message.setField(trstime) msg = message.toString().replace(__SOH__, "|") print("New Order Single: " + msg) quickfix.Session.sendToTarget(message, self.sessionID)
def cancel_order(self, execution_report): message = quickfix44.OrderCancelRequest() orig_cl_ord_id = quickfix.OrigClOrdID() order_id = quickfix.OrderID() symbol_field = quickfix.Symbol() security_exchange_field = quickfix.SecurityExchange() execution_report.getField(symbol_field) execution_report.getField(security_exchange_field) execution_report.getField(order_id) orig_cl_ord_id.setValue(order_id.getValue()) message.setField(symbol_field) message.setField(security_exchange_field) message.setField(orig_cl_ord_id) message.setField(quickfix.ClOrdID(self.genExecID())) side = quickfix.Side() execution_report.getField(side) message.setField(side) trstime = quickfix.TransactTime() trstime.setString( datetime.utcnow().strftime("%Y%m%d-%H:%M:%S.%f")[:-3]) message.setField(trstime) quickfix.Session.sendToTarget(message, self.sessionID)
def new_order(sender_comp_id, target_comp_id, symbol, quantity, price, side, order_type): if side.lower() == "buy": side = fix.Side_BUY else: side = fix.Side_SELL message = Message() header = message.getHeader() header.setField(fix.BeginString("FIX.4.2")) header.setField(fix.SenderCompID(sender_comp_id)) header.setField(fix.TargetCompID(target_comp_id)) header.setField(fix.MsgType("D")) ord_id = get_order_id(sender_comp_id, symbol) message.setField(fix.ClOrdID(ord_id)) message.setField(fix.Symbol(symbol)) message.setField(fix.Side(side)) message.setField(fix.Price(float(price))) if order_type.lower() == "market": message.setField(fix.OrdType(fix.OrdType_MARKET)) else: message.setField(fix.OrdType(fix.OrdType_LIMIT)) message.setField(fix.HandlInst(fix.HandlInst_MANUAL_ORDER_BEST_EXECUTION)) message.setField(fix.TransactTime()) message.setField(fix.OrderQty(float(quantity))) message.setField(fix.Text(f"{side} {symbol} {quantity}@{price}")) return message
def send_mkt_data_req(self, symbol): """ :param symbol: str """ print("send_mkt_data_req: ", symbol) message = fix44.MarketDataRequest() message.setField(fix.MDReqID(self.next_id())) message.setField( fix.SubscriptionRequestType( fix.SubscriptionRequestType_SNAPSHOT_PLUS_UPDATES)) message.setField(fix.MarketDepth(3)) message.setField(fix.MDUpdateType( fix.MDUpdateType_INCREMENTAL_REFRESH)) symbol_group = fix44.MarketDataRequest.NoRelatedSym() symbol_group.setField(fix.Symbol(symbol)) message.addGroup(symbol_group) types = fix44.MarketDataRequest.NoMDEntryTypes() types.setField(fix.MDEntryType(fix.MDEntryType_BID)) message.addGroup(types) types = fix44.MarketDataRequest.NoMDEntryTypes() types.setField(fix.MDEntryType(fix.MDEntryType_OFFER)) message.addGroup(types) fix.Session_sendToTarget(message, self.sessionID)
def process_security_list(self, security_list): no_related_sym = quickfix.NoRelatedSym() symbol_field = quickfix.Symbol() security_list.getField(no_related_sym) number_of_instruments = int(no_related_sym.getValue()) for i in range(number_of_instruments): group = quickfix.Group(no_related_sym.getField(), symbol_field.getField()) security_list.getGroup(i + 1, group) group.getField(symbol_field) security_exchange = quickfix.SecurityExchange() group.getField(security_exchange) exchange = security_exchange.getValue() symbol = symbol_field.getValue() instrument = self.reference_data.ins_instrument(exchange, symbol) print("New Instrument : " + str(instrument)) text_field = quickfix.Text() if group.isSetField(text_field): group.getField(text_field) text = str(text_field.getValue()) ref_data = json.loads(text) self.reference_data.ins_reference_data(instrument, ref_data)
def scrip_msg(scrip_element: Scrip): scrip_subscription = fix.Message() # 8, BeginString scrip_subscription.getHeader().setField(fix.BeginString(fix.BeginString_FIXT11)) # 35, Message Type scrip_subscription.getHeader().setField(fix.MsgType(fix.MsgType_MarketDataRequest)) # 49, SenderCompId scrip_subscription.getHeader().setField(fix.SenderCompID(sender_id)) # 56, TargetCompId scrip_subscription.getHeader().setField(fix.TargetCompID(target_id)) # 34, Message SeqNumber scrip_subscription.setField(fix.MsgSeqNum(1)) # 50, SenderSubID scrip_subscription.setField(fix.SenderSubID(scrip_element.exchange)) # 924, UserRequestType scrip_subscription.setField(fix.UserRequestType(1)) # 115 ,doubtful, but may be gateway id according to examples # NSECM = 2, NSEFO = 1 scrip_subscription.setField(115, "%s" % scrip_element.gatewayID) # 55, Symbol scrip_subscription.setField(fix.Symbol(scrip_element.symbol)) # 1775, price divisor scrip_subscription.setField(1775, "0") # 167, Instrument scrip_subscription.setField(167, scrip_element.instrument) # 48, Token No. scrip_subscription.setField(48, "%s" % scrip_element.token_no) # 263, Broadcast type scrip_subscription.setField(263, "0") scrip_subscription = bytes(scrip_subscription.toString(), encoding="UTF-8") return scrip_subscription
def sendOrder(self, ticker, side, type, px, qty): nos = fix.Message() nos.getHeader().setField(fix.BeginString(fix.BeginString_FIX44)) nos.getHeader().setField(fix.MsgType(fix.MsgType_NewOrderSingle)) symbol = fix.Symbol(ticker) nos.setField(symbol) if side == "BUY": side = fix.Side(fix.Side_BUY) if side == "SELL": side = fix.Side(fix.Side_SELL) nos.setField(side) if type == "MARKET": ordType = fix.OrdType(fix.OrdType_MARKET) px = fix.Price(0) if type == "LIMIT": ordType = fix.OrdType(fix.OrdType_MARKET) px = fix.Price(px) nos.setField(ordType) nos.setField(px) orderQty = fix.OrderQty(qty) clOrdID = fix.ClOrdID(self.genOrderID()) nos.setField(orderQty) nos.setField(clOrdID) TimeInForce = fix.TimeInForce(fix.TimeInForce_GOOD_TILL_CANCEL) TransactTime = fix.TransactTime() nos.setField(TimeInForce) nos.setField(TransactTime) fix.Session.sendToTarget(nos, self.sessionID)
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 suscribeMD(self): print( "SUSCRIBE MD***************************************************************************" ) if len(self.tickers) == 0 or len(self.entries) == 0: return allowed_entries = ['0', '1', '2', '4', '5', '6', '7', '8', 'B', 'C'] if not all(elem in allowed_entries for elem in self.entries): return msg = fix50.MarketDataRequest() header = msg.getHeader() header.setField(fix.SenderCompID(self.usrID)) header.setField(fix.TargetCompID(self.targetCompID)) # --------------------- msg.setField(fix.MDReqID("ListaMktData")) msg.setField(fix.SubscriptionRequestType('1')) msg.setField(fix.MarketDepth(1)) msg.setField(fix.MDUpdateType(0)) msg.setField(fix.AggregatedBook(True)) # BlockMDReqGrp group = fix50.MarketDataRequest().NoMDEntryTypes() for field in self.entries: group.setField(fix.MDEntryType(str(field))) msg.addGroup(group) # Symbols norelatedsym = fix50.MarketDataRequest().NoRelatedSym() for ticker in self.tickers: norelatedsym.setField(fix.Symbol(ticker)) logfix.warning("--> Suscribe Ticker >> (%s)" % ticker) msg.addGroup(norelatedsym) fix.Session.sendToTarget(msg)
def publishMarketData(self): self.logger.info("FixServer: publishMarketData %s", self.subscriptions) for subscription in self.subscriptions: if not subscription.hasSessions(): self.logger.info( "FixServer:No session subscribed, skip publish symbol %s", subscription.symbol) continue message = self.fixVersion.MarketDataSnapshotFullRefresh() message.setField(quickfix.Symbol(subscription.symbol)) message.setField(quickfix.MDReqID(self.idGen.reqID())) group = self.fixVersion.MarketDataSnapshotFullRefresh( ).NoMDEntries() subscription.createOrderBook() for quote in subscription.orderbook: self.logger.info('FixServer:add quote to fix message %s', str(quote)) group.setField(quickfix.MDEntryType(quote.side)) group.setField(quickfix.MDEntryPx(quote.price)) group.setField(quickfix.MDEntrySize(quote.size)) group.setField(quickfix.QuoteEntryID(quote.id)) group.setField(quickfix.Currency(subscription.currency)) group.setField( quickfix.QuoteCondition( quickfix.QuoteCondition_OPEN_ACTIVE)) message.addGroup(group) for sessionID in subscription: self.sendToTarget(message, sessionID)
def onLogon(self, sessionID): self.sessionID = sessionID print("onLogon - sessionID: " + sessionID.toString()) currency_pairs = ['GBP/USD', 'EUR/USD'] for ccy in currency_pairs: mdr = fix.Message() mdr.getHeader().setField(fix.BeginString(fix.BeginString_FIX44)) mdr.getHeader().setField(fix.MsgType(fix.MsgType_MarketDataRequest)) current_milli_time = lambda: int(round(time.time() * 1000)) mdr.setField(fix.MDReqID(str(current_milli_time()))) # a random string mdr.setField(fix.SubscriptionRequestType(fix.SubscriptionRequestType_SNAPSHOT_PLUS_UPDATES)) # what stater required mdr.setField(fix.MarketDepth(1)) # what stater required mdr.setField(fix.AggregatedBook(True)) mdr.setField(fix.NoMDEntryTypes(1)) # what stater required mdr.setField(fix.MDUpdateType(fix.MDUpdateType_INCREMENTAL_REFRESH)) # what stater required group = fix44.MarketDataRequest().NoMDEntryTypes() group.setField(fix.MDEntryType(fix.MDEntryType_BID)) mdr.addGroup(group) group.setField(fix.MDEntryType(fix.MDEntryType_OFFER)) mdr.addGroup(group) mdr.setField(fix.NoRelatedSym(1)) symbol = fix44.MarketDataRequest().NoRelatedSym() symbol.setField(fix.Symbol(ccy)) mdr.addGroup(symbol) fix.Session.sendToTarget(mdr, sessionID)
def OnNoPositions(self, message): logger.info("OnNoPositions") symbol = fix.Symbol() exch = fix.SecurityExchange() message.getField(symbol) message.getField(exch) groupRead = UapGroup.NoPositions() PosType = fix.PosType() LongQty = fix.LongQty() ShortQty = fix.ShortQty() NoPos = fix.UapGroup() message.getField(NoPos) logger.info("NoPos:" + NoPos.getString() + symbol.getString() + "." + exch.getString()) for i in range(NoPos.getValue()): message.getGroup(i + 1, groupRead) groupRead.getFieldIfSet(PosType) groupRead.getFieldIfSet(LongQty) groupRead.getFieldIfSet(ShortQty) if (PosType.getString() == "SB"): logger.info("股份余额:" + LongQty.getString()) elif (PosType.getString() == "SAV"): logger.info("股份可用余额:" + LongQty.getString()) elif (PosType.getString() == "SQ"): logger.info("当前拥股数:" + LongQty.getString()) elif (PosType.getString() == "LB"): logger.info("昨日余额:" + LongQty.getString()) elif (PosType.getString() == "SBQ"): logger.info("今日买入数量:" + LongQty.getString()) elif (PosType.getString() == "SS"): logger.info("卖出冻结数:" + ShortQty.getString()) elif (PosType.getString() == "SF"): logger.info("人工冻结数:" + ShortQty.getString())
def compose_market_data_request(self): market_data_request = quickfix44.MarketDataRequest() market_data_request.setField(quickfix.MDReqID('1')) market_data_request.setField(quickfix.SubscriptionRequestType(quickfix.SubscriptionRequestType_SNAPSHOT_PLUS_UPDATES)) market_data_request.setField(quickfix.MarketDepth(0)) market_data_request.setField(quickfix.NoMDEntryTypes(2)) market_data_request.setField(quickfix.MDUpdateType(quickfix.MDUpdateType_INCREMENTAL_REFRESH)) group = quickfix44.MarketDataRequest().NoMDEntryTypes() group.setField(quickfix.MDEntryType(quickfix.MDEntryType_BID)) market_data_request.addGroup(group) group.setField(quickfix.MDEntryType(quickfix.MDEntryType_OFFER)) market_data_request.addGroup(group) market_data_request.setField(quickfix.NoRelatedSym(self.reference_data.get_count())) symbol = quickfix44.MarketDataRequest().NoRelatedSym() for instrument in self.reference_data.get_instruments(): symbol.setField(quickfix.SecurityExchange(instrument.exchange)) symbol.setField(quickfix.Symbol(instrument.symbol)) market_data_request.addGroup(symbol) return market_data_request
def report_child_order(self, child_order: GenusChildOrder, trade: TradeData = None): """""" self.exec_id += 1 message = new_message(fix.MsgType_ExecutionReport) message.setField(fix.ClOrdID(child_order.cl_ord_id)) message.setField(fix.OrderID(child_order.order_id)) message.setField(fix.ExecID(str(self.exec_id))) message.setField(fix.OrdStatus(child_order.ord_status)) message.setField(fix.ExecType(child_order.ord_status)) message.setField(fix.Symbol(child_order.symbol)) message.setField(fix.Side(child_order.side)) message.setField(fix.OrderQty(child_order.order_qty)) message.setField(fix.CumQty(child_order.cum_qty)) message.setField( fix.LeavesQty(child_order.order_qty - child_order.cum_qty)) message.setField(fix.AvgPx(child_order.avg_px)) if trade: message.setField(fix.LastShares(trade.volume)) message.setField(fix.LastPx(trade.price)) fix.Session.sendToTarget(message, self.session_id)
def on_market_data_request(self, message): print('Market Data REQUEST!') message_fields = { 'md_reqID': fix.MDReqID(), 'depth': fix.MarketDepth(), 'subscription_type': fix.SubscriptionRequestType(), } message_details = {} for k, v in message_fields.items(): message_details[k] = self.get_field_value(message, v) message_details['entry_types'] = {} message_details['symbols'] = {} n_entry_types = self.get_field_value(message, fix.NoMDEntryTypes()) group = fix44.MarketDataRequest().NoMDEntryTypes() for i in range(n_entry_types): message.getGroup(i + 1, group) message_details['entry_types'][i] = self.get_field_value( group, fix.MDEntryType()) n_symbols = self.get_field_value(message, fix.NoRelatedSym()) group = fix44.MarketDataRequest().NoRelatedSym() for i in range(n_symbols): message.getGroup(i + 1, group) message_details['symbols'][i] = self.get_field_value( group, fix.Symbol()) orderID = self.gen_orderID() self.orders[orderID] = message_details # testing self.test_snaps(message_details, full=True) self.test_snaps(message_details, full=False)
def makeOrder(self, snapshot): self.logger.info("FIXSIM-CLIENT Snapshot received %s", str(snapshot)) quote = snapshot.getRandomQuote() self.logger.info("FIXSIM-CLIENT make order for quote %s", str(quote)) order = self.fixVersion.NewOrderSingle() order.setField( quickfix.HandlInst( quickfix. HandlInst_AUTOMATED_EXECUTION_ORDER_PUBLIC_BROKER_INTERVENTION_OK )) order.setField( quickfix.SecurityType( quickfix.SecurityType_FOREIGN_EXCHANGE_CONTRACT)) order.setField(quickfix.OrdType(quickfix.OrdType_PREVIOUSLY_QUOTED)) order.setField(quickfix.ClOrdID(self.idGen.orderID())) order.setField(quickfix.QuoteID(quote.id)) order.setField(quickfix.SecurityDesc("SPOT")) order.setField(quickfix.Symbol(snapshot.symbol)) order.setField(quickfix.Currency(quote.currency)) order.setField(quickfix.Side(quote.side)) order.setField(quickfix.OrderQty(quote.size)) order.setField(quickfix.FutSettDate("SP")) order.setField(quickfix.Price(quote.price)) order.setField(quickfix.TransactTime()) order.setField( quickfix.TimeInForce(quickfix.TimeInForce_IMMEDIATE_OR_CANCEL)) self.sendToTarget(order, self.orderSession)
def subscribe(self): if self.marketSession is None: self.logger.info( "FIXSIM-CLIENT Market session is none, skip subscribing") return for subscription in self.subscriptions: message = self.fixVersion.MarketDataRequest() message.setField(quickfix.MDReqID(self.idGen.reqID())) message.setField( quickfix.SubscriptionRequestType( quickfix.SubscriptionRequestType_SNAPSHOT_PLUS_UPDATES)) message.setField( quickfix.MDUpdateType(quickfix.MDUpdateType_FULL_REFRESH)) message.setField(quickfix.MarketDepth(0)) message.setField(quickfix.MDReqID(self.idGen.reqID())) relatedSym = self.fixVersion.MarketDataRequest.NoRelatedSym() relatedSym.setField(quickfix.Product(quickfix.Product_CURRENCY)) relatedSym.setField( quickfix.SecurityType( quickfix.SecurityType_FOREIGN_EXCHANGE_CONTRACT)) relatedSym.setField(quickfix.Symbol(subscription.symbol)) message.addGroup(relatedSym) group = self.fixVersion.MarketDataRequest.NoMDEntryTypes() group.setField(quickfix.MDEntryType(quickfix.MDEntryType_BID)) message.addGroup(group) group.setField(quickfix.MDEntryType(quickfix.MDEntryType_BID)) message.addGroup(group) self.sendToTarget(message, self.marketSession)
def getExecutionReportForNewOrder(self, message): beginString = fix.BeginString() message.getHeader().getField(beginString) symbol = fix.Symbol() side = fix.Side() ordType = fix.OrdType() orderQty = fix.OrderQty() price = fix.Price() clOrdID = fix.ClOrdID() message.getField(ordType) if ordType.getValue() != fix.OrdType_LIMIT: raise fix.IncorrectTagValue(ordType.getField()) message.getField(symbol) message.getField(side) message.getField(orderQty) message.getField(price) message.getField(clOrdID) executionReport = fix.Message() executionReport.getHeader().setField(beginString) executionReport.getHeader().setField( fix.MsgType(fix.MsgType_ExecutionReport)) executionReport.setField(fix.OrderID(self.genOrderID())) executionReport.setField(fix.ExecID(self.genExecID())) executionReport.setField(fix.OrdStatus(fix.OrdStatus_FILLED)) executionReport.setField(symbol) executionReport.setField(side) executionReport.setField(fix.CumQty(orderQty.getValue())) executionReport.setField(fix.AvgPx(price.getValue())) executionReport.setField(fix.LastShares(orderQty.getValue())) executionReport.setField(fix.LastPx(price.getValue())) executionReport.setField(clOrdID) executionReport.setField(orderQty) executionReport.setField(fix.Text("New order accepted!")) # Since FIX 4.3, ExecTransType is killed and the values are moved to ExecType if beginString.getValue( ) == fix.BeginString_FIX40 or beginString.getValue( ) == fix.BeginString_FIX41 or beginString.getValue( ) == fix.BeginString_FIX42: executionReport.setField(fix.ExecTransType(fix.ExecTransType_NEW)) # ExecType and LeavesQty fields only existsince FIX 4.1 if beginString.getValue() >= fix.BeginString_FIX41: if beginString.getValue() <= fix.BeginString_FIX42: executionReport.setField(fix.ExecType( fix.ExecType_FILL)) #150=2 FILL (or 1 PARTIAL_FILL) else: # FILL and PARTIAL_FILL are removed and replaced by TRADE (F) since FIX 4.3 as these info can be retrieved from OrdStatus field executionReport.setField(fix.ExecType( fix.ExecType_TRADE)) #150=F TRADE executionReport.setField(fix.LeavesQty(0)) return executionReport
def test_replaceGroup(self): self.object.setField( fix.ListID( "1" ) ) self.object.setField( fix.BidType( 0 ) ) self.object.setField( fix.TotNoOrders( 3 ) ) group = fix42.NewOrderList.NoOrders() group.setField( fix.ClOrdID( "A" ) ) group.setField( fix.ListSeqNo( 1 ) ) group.setField( fix.Symbol( "DELL" ) ) group.setField( fix.Side( '1' ) ) self.object.addGroup( group ) group.setField( fix.ClOrdID( "B" ) ) group.setField( fix.ListSeqNo( 2 ) ) group.setField( fix.Symbol( "LNUX" ) ) group.setField( fix.Side( '2' ) ) self.object.addGroup( group ); group.setField( fix.ClOrdID( "C" ) ) group.setField( fix.ListSeqNo( 3 ) ) group.setField( fix.Symbol( "RHAT" ) ) group.setField( fix.Side( '3' ) ) self.object.addGroup( group ); group.setField( fix.ClOrdID( "D" ) ) group.setField( fix.ListSeqNo( 4 ) ) group.setField( fix.Symbol( "AAPL" ) ) group.setField( fix.Side( '4' ) ) self.object.replaceGroup( 2, group ); noOrders = fix.NoOrders() assert( self.object.hasGroup(1, group) ) assert( self.object.hasGroup(2, group) ) assert( self.object.hasGroup(3, group) ) self.assertEqual( 3, self.object.groupCount(fix.NoOrders().getTag()) ) self.object.getField( noOrders ) self.assertEqual( 3, noOrders.getValue() ) clOrdID = fix.ClOrdID() self.object.getGroup( 1, group ) self.assertEqual( "A", group.getField(clOrdID).getString() ) self.object.getGroup( 2, group ) self.assertEqual( "D", group.getField(clOrdID).getString() ) self.object.getGroup( 3, group ) self.assertEqual( "C", group.getField(clOrdID).getString() )
def __init__(self, reference_data, market_data): self.reference_data = reference_data self.market_data = market_data self.symbol_field = quickfix.Symbol() self.security_exchange_field = quickfix.SecurityExchange() self.no_md_entries = quickfix.NoMDEntries() self.md_entry_type = quickfix.MDEntryType() self.md_entry_price = quickfix.MDEntryPx() self.md_entry_size = quickfix.MDEntrySize()
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 market_data_request(self, sender_comp_id, target_comp_id, symbols): md_types = [ fix.MDEntryType_BID, fix.MDEntryType_OFFER, fix.MDEntryType_TRADE ] message = fix44.MarketDataRequest() header = message.getHeader() header.setField(fix.SenderCompID(sender_comp_id)) header.setField(fix.TargetCompID(target_comp_id)) message.setField(fix.MDReqID(self._generate_id())) message.setField( fix.SubscriptionRequestType( fix.SubscriptionRequestType_SNAPSHOT_PLUS_UPDATES)) # message.setField( # fix.SubscriptionRequestType( # fix.SubscriptionRequestType_SNAPSHOT # ) # ) """ Valid values: 0 = Full Book 1 = Top of Book N>1 = Report best N price tiers of data """ message.setField(fix.MarketDepth(0)) """ Valid values: 0 = Full Refresh 1 = Incremental Refresh """ message.setField(fix.MDUpdateType( fix.MDUpdateType_INCREMENTAL_REFRESH)) group = fix44.MarketDataRequest().NoMDEntryTypes() for md_type in md_types: group.setField(fix.MDEntryType(md_type)) message.addGroup(group) group = fix44.MarketDataRequest().NoRelatedSym() for symbol in symbols: group.setField(fix.Symbol(symbol)) message.addGroup(group) try: fix.Session.sendToTarget(message) except fix.SessionNotFound: raise Exception(f"No session found {message}, exiting...")