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 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 send(self, order): orderId = self.SocketInitiator.application.genOrderID() account = self.SocketInitiator.application.Settings.get().getString( 'Account') trade = fix44.NewOrderSingle() trade.setField(fix.Account(account)) trade.setField(fix.ClOrdID(orderId)) trade.setField(order.CFICode) trade.setField(order.TransactionTime) trade.setField(order.Quantity) trade.setField(order.OrdType) trade.setField(order.Side) trade.setField(order.Symbol) trade.setField(order.Maturity) if isinstance(order, FutureLimitOrder): trade.setField(order.Price) self.SocketInitiator.application.send(trade) ordType = OrderType.Limit if isinstance( order, FutureLimitOrder) else OrderType.Market ordSide = OrderSide.Buy if isinstance(order, BuyOrder) else OrderSide.Sell price = order.Price.getValue() if isinstance( order, FutureLimitOrder) else None return Trade(orderId, order.Symbol.getString(), order.Maturity.getString(), order.Quantity.getValue(), ordType, ordSide, price)
def GetAccountInfo(self, accessKey, secretKey): message = fix.Message() header = message.getHeader() header.setField(fix.MsgType('U1000')) account = GenAccountString(accessKey, secretKey).getAccountString() message.setField(fix.Account(account)) accReqID = str(uuid.uuid1()) message.setField(myfix.AccReqID(accReqID)) fix.Session.sendToTarget(message, self.sessionID)
def make_single_order(self, order_id, symbol, qty): account = "YIZHE0" order = fix44.NewOrderSingle() order.setField(fix.Account(account)) order.setField(fix.ClOrdID(order_id)) order.setField(fix.Symbol(symbol)) order.setField(fix.Side("1")) order.setField(fix.OrdType("U")) order.setField(fix.OrderQty(qty)) order.setField(fix.Price(49)) return order
def collateralInquiry(self): inqId = self.SocketInitiator.application.genInquiryID() account = self.SocketInitiator.application.Settings.get().getString( 'Account') message = fix44.CollateralInquiry() message.setField(fix.Account(account)) message.setField(fix.CollInquiryID(inqId)) self.SocketInitiator.application.send(message) return inqId
def msgtofix_quote(quote_msg): """ Converte Quote (message) para Quote (fix). """ quoterequest_msg, quoterequest_fix = get_quoterequest(quote_msg.QuoteReqID) quote = fix44.Quote() quote.reverseRoute(quoterequest_fix.getHeader()) if quoterequest_msg.SecurityType == messages.EnumSecurityType.SPOT: set_field(quote, fix.SecurityType, "FXSPOT") elif quoterequest_msg.SecurityType == messages.EnumSecurityType.NDF: set_field(quote, fix.SecurityType, "FXNDF") set_field(quote, fix.QuoteReqID, quote_msg.QuoteReqID) set_field(quote, fix.QuoteID, quote_msg.QuoteID) set_field(quote, fix.OfferPx, quote_msg.OfferPx) set_field(quote, fix.OfferSpotRate, quote_msg.OfferSpotRate) set_field(quote, fix.BidPx, quote_msg.BidPx) set_field(quote, fix.BidSpotRate, quote_msg.BidSpotRate) set_field(quote, fix.QuoteCondition, "A") quote.setField(5082, "2") set_field(quote, fix.Symbol, quoterequest_fix.getField(fix.Symbol().getField())) set_field(quote, fix.Account, quoterequest_fix.getField(fix.Account().getField())) copy_field(quoterequest_fix, quote, fix.FutSettDate) copy_field(quoterequest_fix, quote, fix.FutSettDate2) copy_field(quoterequest_fix, quote, 6215) copy_field(quoterequest_fix, quote, 6216) transact_time = fix.TransactTime() time_str = get_utc_time().strftime("%Y%m%d-%H:%M:%S.%f")[:-3] transact_time.setString(time_str) quote.setField(transact_time) quote_msg.TransactTime = time_str if quoterequest_msg.SecurityType == messages.EnumSecurityType.NDF: copy_field(quoterequest_fix, quote, fix.OrdType) copy_field(quoterequest_fix, quote, fix.TradeDate) copy_field(quoterequest_fix, quote, fix.SettlCurrency) copy_field(quoterequest_fix, quote, 5974) # FixingSource copy_field(quoterequest_fix, quote, 6203) # FixingDate taker_side = str(quoterequest_fix.getField(fix.Side().getField())) if taker_side == '1': set_field(quote, fix.OfferForwardPoints, quote_msg.Details.get('forward_points')) elif taker_side == '2': set_field(quote, fix.BidForwardPoints, quote_msg.Details.get('forward_points')) return quote
def requestForPositions(self): clrDate = datetime.now().strftime("%Y%m%d") inqId = self.SocketInitiator.application.genInquiryID() account = self.SocketInitiator.application.Settings.get().getString( 'Account') message = fix44.RequestForPositions() message.setField(fix.Account(account)) message.setField(fix.TransactTime()) message.setField( fix.AccountType( fix.AccountType_ACCOUNT_IS_CARRIED_ON_CUSTOMER_SIDE_OF_BOOKS)) message.setField(fix.ClearingBusinessDate(clrDate)) message.setField(fix.PosReqType(fix.PosReqType_POSITIONS)) message.setField(fix.PosReqID(inqId)) self.SocketInitiator.application.send(message) return inqId
def order_cancel_request(self,account,symbol,side,quantity): print("Creating order_cancel_request message... ") cancel_request_message = fix.Message() cancel_request_message.getHeader().setField(fix.BeginString(fix.BeginString_FIX42)) # cancel_request_message.getHeader().setField(fix.MsgType('F')) #39=D cancel_request_message.getHeader().setField(fix.SendingTime(1)) cancel_request_message.setField(fix.Account(str(account))) #1 cancel_request_message.setField(fix.ClOrdID(str('order_cancel_request'+self.genOrderID()))) #11 cancel_request_message.setField(fix.OrigClOrdID(str(self.orders[0]))) #41 cancel_request_message.setField(fix.Symbol(str(symbol))) #55 cancel_request_message.setField(fix.Side(str(side))) #54 cancel_request_message.setField(fix.OrderQty(quantity)) #38 print('sending order_cancel_request message...') print(f'order_cancel_request message: {cancel_request_message.toString()}') fix.Session.sendToTarget(cancel_request_message, self.sessionID) print('order_cancel_request message sent!')
def cancel(self, trade): orderId = self.SocketInitiator.application.genOrderID() account = self.SocketInitiator.application.Settings.get().getString( 'Account') cancel = fix44.OrderCancelRequest() cancel.setField(fix.Account(account)) cancel.setField(fix.ClOrdID(orderId)) cancel.setField(fix.OrigClOrdID(trade.OrderId)) cancel.setField(trade.CFICode) cancel.setField(fix.TransactTime()) cancel.setField(fix.OrderQty(trade.Quantity)) cancel.setField( fix.Side(fix.Side_BUY if trade.OrderSide == OrderSide.Buy else fix.Side_SELL)) cancel.setField(fix.Symbol(trade.Symbol)) cancel.setField(fix.MaturityMonthYear(trade.Maturity)) self.SocketInitiator.application.send(cancel)
def order_cancel_replace(self,account,symbol,side,quantity,order_type,price): print("Creating order_cancel_replace message... ") cancel_replace_message = fix.Message() cancel_replace_message.getHeader().setField(fix.BeginString(fix.BeginString_FIX42)) # cancel_replace_message.getHeader().setField(fix.MsgType('G')) #39=D cancel_replace_message.getHeader().setField(fix.SendingTime(1)) cancel_replace_message.setField(fix.Account(str(account))) #1 cancel_replace_message.setField(fix.HandlInst(fix.HandlInst_AUTOMATED_EXECUTION_ORDER_PUBLIC_BROKER_INTERVENTION_OK)) #21=3 (Manual order), 21=2 automated execution only supported value cancel_replace_message.setField(fix.ClOrdID(str('order_cancel_replace'+self.genOrderID()))) #11 cancel_replace_message.setField(fix.OrigClOrdID(str(self.orders[0]))) #41 cancel_replace_message.setField(fix.Symbol(str(symbol))) #55 cancel_replace_message.setField(fix.Side(str(side))) #54 cancel_replace_message.setField(fix.OrderQty(quantity)) #38 cancel_replace_message.setField(fix.OrdType(str(order_type))) #40 cancel_replace_message.setField(fix.Price(price)) #44 print('sending order_cancel_replace message...') print(f'order_cancel_replace message: {cancel_replace_message.toString()}') fix.Session.sendToTarget(cancel_replace_message, self.sessionID) print('order_cancel_replace message sent!')
def checkAccountData(self): try: LOG_EVENT("Check Account Data") orderMsg = fix.Message() orderMsg.getHeader().setField(self.sessionID.getBeginString()) orderMsg.getHeader().setField(fix.MsgType("UAR")) 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(20003, self.genExecID()) LOG_PACKET(orderMsg.toString()) fix.Session.sendToTarget(orderMsg, self.sessionID) except Exception as e: print(e)
def onNOS(self, message): trade = fix.Message() header = trade.getHeader() header.setField(fix.BeginString("FIX.4.4")) header.setField(fix.SenderCompID("COEPUSER")) header.setField(fix.TargetCompID("COEPEXCH")) header.setField(fix.MsgType("D")) trade.setField(fix.ClOrdID(message['order_id'])) trade.setField(fix.Symbol(message['symbol'])) if message['side'] == 'sell': trade.setField(fix.Side(Side_SELL)) trade.setField(58, "Sell shares") else: trade.setField(fix.Side(Side_BUY)) trade.setField(58, "Buy shares") trade.setField(40, "2") trade.setField(fix.Price(message['ask_price'])) trade.setField(fix.OrderQty(message['total_qty'])) transact_time = datetime.utcnow() trade.setField(60, transact_time.strftime("%Y%m%d-22:29:00.000")) trade.setField(fix.Account("EXECLINKS")) fix.Session_sendToTarget(trade, self.sessionID) return
def put_order(self,security_type,symbol,currency,quantity,side,order_type,account,time_id,price=None): if quantity != 0 : trade = fix.Message() ''' STANDARD MESSAGE HEADER Required Tags: 8(BeginString) - 9(BodyLength) - 35(MsgType) - 49(SenderCompID) - 56(TargetCompID) - 34(MsgSeqNum) - 52(SendingTime) ''' trade.getHeader().setField(fix.BeginString(fix.BeginString_FIX42)) # trade.getHeader().setField(fix.MsgType(fix.MsgType_NewOrderSingle)) #39=D trade.getHeader().setField(fix.SendingTime(1)) # unique_order_id = self.genExecID() # print(f'Unique Order ID: {unique_order_id}') # trade.setField(fix.ClOrdID(unique_order_id)) #11=Unique order trade.setField(fix.HandlInst(fix.HandlInst_AUTOMATED_EXECUTION_ORDER_PUBLIC_BROKER_INTERVENTION_OK)) #21=3 (Manual order), 21=2 automated execution only supported value trade.setField(fix.Symbol(str(symbol))) #55 trade.setField(fix.Currency(str(currency))) #15 trade.setField(fix.SecurityType(str(security_type))) #167 trade.setField(fix.Side(str(side))) #54=1 Buy trade.setField(fix.OrdType(str(order_type))) #40=2 Limit order, 40=1 Market trade.setField(fix.OrderQty(quantity)) #38 if order_type != 1: #not market trade.setField(fix.Price(price)) # if market, this tag should be absent else: price = None trade.setField(fix.Account(str(account))) trade.setField(fix.ExDestination('IDEALPRO')) trade.setField(fix.CustomerOrFirm(0)) trade.setField(fix.ClOrdID(time_id+trade.getField(55)+trade.getField(15)+trade.getField(54))) #11= # trade.setField(fix.ClOrdID(datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')+trade.getField(55)+trade.getField(15)+trade.getField(54))) #11= # dnow = datetime.utcnow().strftime('%Y%m%d-%H:%M:%S') # tag = fix.TransactTime() #default = current time, SendingTime does the same thing # tag.setString(dnow.strftime('%Y%m%d-%H:%M:%S')) # trade.setField(tag) print(f'CREATING THE FOLLOWING ORDER:\n {trade.toString()}') fix.Session.sendToTarget(trade, self.sessionID) self.orders_dict[trade.getField(11)] = {#'id':trade.getField(11), #'datetime': trade.getField(11)[:12], 'account':trade.getField(1), 'symbol':trade.getField(55)+'.' + trade.getField(15), 'qty':trade.getField(38), 'ord_type':trade.getField(40), 'side':trade.getField(54), 'price':price, 'status':'sent' } else: print(f'QUANTITY IS 0!\nCHECK FOR STATUS OF LAST ORDER') if os.path.exists(f'{self.write_path}fix_orders.csv'): temp_orders = pd.read_csv(f'{self.write_path}fix_orders.csv',index_col=0) symbol_entries = temp_orders[temp_orders['symbol'] == symbol] last_symbol_entry = symbol_entries.iloc[-1] new_entry = last_symbol_entry new_id = time_id + last_symbol_entry.name[6:] new_entry.name = new_id temp_orders = temp_orders.append(last_symbol_entry,ignore_index=False) temp_orders.to_csv(f'{self.write_path}fix_orders.csv',) self.order_status_request(cl_ord_id=last_symbol_entry) # self.order_status_request(cl_ord_id=temp_orders.index[-1]) else: print(f'QUANTITY IS 0!\n FIX ORDERS FIRST RUN') time.sleep(100)
def queryAccount(self): value = input('Account: ') return fix.Account(value)
def __unpackMessage(self, message): msgType = fix.MsgType() message.getHeader().getField(msgType) if msgType.getValue() == fix.MsgType_RequestForPositionsAck: account = fix.Account() message.getField(account) posId = fix.PosReqID() message.getField(posId) self.Notifier.notifyMsgHandlers( Notify.Account, Account=account.getValue(), PosReqID=posId.getValue(), Symbol=None, Maturity=None, NoPositions=0, LongQty=0, ShortQty=0, PosAmt=0, SettlPrice=0, NoPosAmt=0, ClearingBusinessDate=None, AccountInquiry=AccountInquiry.RequestForPositions) elif msgType.getValue() == fix.MsgType_PositionReport: account = fix.Account() message.getField(account) posId = fix.PosReqID() message.getField(posId) symbol = fix.Symbol() message.getField(symbol) maturity = fix.MaturityMonthYear() message.getField(maturity) noPositions = fix.NoPositions() message.getField(noPositions) longQty = fix.LongQty() message.getField(longQty) shortQty = fix.ShortQty() message.getField(shortQty) posAmt = fix.PosAmt() message.getField(posAmt) cBusDate = fix.ClearingBusinessDate() message.getField(cBusDate) settlePrice = fix.SettlPrice() message.getField(settlePrice) noPosAmt = fix.NoPosAmt() message.getField(noPosAmt) self.Notifier.notifyMsgHandlers( Notify.Account, Account=account.getValue(), PosReqID=posId.getValue(), Symbol=symbol.getValue(), Maturity=maturity.getValue(), NoPositions=noPositions.getValue(), LongQty=longQty.getValue(), ShortQty=shortQty.getValue(), PosAmt=posAmt.getValue(), SettlPrice=settlePrice.getValue(), NoPosAmt=noPosAmt.getValue(), ClearingBusinessDate=cBusDate.getValue(), AccountInquiry=AccountInquiry.RequestForPositions) elif msgType.getValue() == fix.MsgType_CollateralReport: account = fix.Account() message.getField(account) ccy = fix.Currency() message.getField(ccy) csh = fix.CashOutstanding() message.getField(csh) colId = fix.CollInquiryID() message.getField(colId) self.Notifier.notifyMsgHandlers( Notify.Account, Account=account.getValue(), Currency=ccy.getValue(), Balance=csh.getValue(), CollInquiryID=colId.getValue(), AccountInquiry=AccountInquiry.CollateralInquiry) elif msgType.getValue() == fix.MsgType_OrderCancelReject: cId = fix.ClOrdID() message.getField(cId) origClOrdID = fix.OrigClOrdID() message.getField(origClOrdID) self.Notifier.notifyMsgHandlers(Notify.Order, ClientOrderId=cId.getValue(), Symbol=None, AvgPx=None, Quantity=None, Side=None, Status=OrderStatus.CancelRejected, OrigClOrdID=origClOrdID.getValue(), Sender=self.FixClientRef) elif msgType.getValue() == fix.MsgType_ExecutionReport: cId = fix.ClOrdID() message.getField(cId) fixStatus = fix.OrdStatus() message.getField(fixStatus) price = fix.AvgPx() message.getField(price) qty = fix.OrderQty() message.getField(qty) side = fix.Side() message.getField(side) symbol = fix.Symbol() message.getField(symbol) orderSide = None origOrderId = None if side.getValue() == fix.Side_BUY: orderSide = OrderSide.Buy elif side.getValue() == fix.Side_SELL: orderSide = OrderSide.Sell status = None if fixStatus.getValue() == fix.OrdStatus_NEW: status = OrderStatus.New elif fixStatus.getValue() == fix.OrdStatus_CANCELED: status = OrderStatus.Cancelled origClOrdID = fix.OrigClOrdID() message.getField(origClOrdID) origOrderId = origClOrdID.getValue() elif fixStatus.getValue() == fix.OrdStatus_FILLED: status = OrderStatus.Filled elif fixStatus.getValue() == fix.OrdStatus_REJECTED: status = OrderStatus.Rejected if status is not None: self.Notifier.notifyMsgHandlers(Notify.Order, ClientOrderId=cId.getValue(), Symbol=symbol.getValue(), AvgPx=price.getValue(), Quantity=qty.getValue(), Side=orderSide, Status=status, OrigClOrdID=origOrderId, Sender=self.FixClientRef)
def send_NewOrderSingle(self, order): if order.error: print( '[ERROR] The order cannot be sent because it contains errors.') return if order.ClOrdID is None: order.ClOrdID = self.app.next_ClOrdID() elif order.ClOrdID in self.Open_Orders.keys(): print( '[ERROR] Order not sent. There is already an open order with the same ID. Please use a different one or just leave it empty.' ) return message = fix.Message() header = message.getHeader() # Set message type to NewOrderSingle (35=D) header.setField(fix.MsgType(fix.MsgType_NewOrderSingle)) # Tag 11 - Unique ID to assign to this trade. message.setField(fix.ClOrdID(str(order.ClOrdID))) # Tag 1 - Account ID as provided by FIX administrator message.setField(fix.Account(self.account)) # Tag 55 message.setField(fix.Symbol(str(order.symbol))) # Tag 54 (1 == buy, 2 == sell) message.setField(fix.Side(str(order.side))) # Tag 38 message.setField(fix.OrderQty(int(order.quantity))) # Tag 40 (1 == market, 2 == limit) message.setField(fix.OrdType(str(order.type))) # Tag 44: not needed for market orders. if order.price is not None: message.setField(fix.Price(order.price)) # Tag 10000 - TTL in milliseconds for open trade expiration. message.setField(fix.IntField(10000, order.ttl)) # Tag 10001 (deviation: maximum allowed slippage) # Double value. Accepted deviation from the price submitted in tag 44. Only applicable if 40=2. # Defaults to 0.0. Setting this value to 0.00002 for a sell EURUSD limit order would allow for # execution on prices as low as 0.2 pips below the specified price. The preferred mode of operation # for limit orders is to set tag 44 at current market price and use tag 10001 to define a specific # slippage acceptance. if str(order.type) == '2': message.setField(fix.DoubleField(10001, order.deviation)) # Tag 60 (current time in UTC). 3 means 3 digits (milliseconds) message.setField(fix.TransactTime(3)) if self.sessionID_Trade is not None: # Add trade to local open orders: self.app.add_order(order) fix.Session.sendToTarget(message, self.sessionID_Trade) else: print( '[ERROR] send_NewOrderSingle() failed. sessionID_Trade is None!' )