Пример #1
0
    def order_status_request(self,cl_ord_id=None):

        if cl_ord_id is None:
            fix_orders = pd.read_csv(f'{self.write_path}/fix_orders.csv',index_col=0)
            for idx in fix_orders.index:
                ord_status_request = fix.Message()
                ord_status_request.getHeader().setField(fix.BeginString(fix.BeginString_FIX42)) #
                ord_status_request.getHeader().setField(fix.MsgType('H')) #39=D
                ord_status_request.getHeader().setField(fix.SendingTime(1))
                # ord_status_request.setField(fix.Symbol('EUR')) #55
                # ord_status_request.setField(fix.Account('U01049'))
                # ord_status_request.setField(fix.SecurityReqID('1'))
                ord_status_request.setField(fix.ClOrdID(str(idx))) #11=
                # ord_status_request.setField(fix.ClOrdID(str('*'))) #11=
                # ord_status_request.setField(fix.ClOrdID(datetime.utcnow().strftime('%Y%m%d%H%M%S')+ 'statReq' + self.genExecID())) #11=
                # ord_status_request.setField(fix.OrderID(datetime.utcnow().strftime('%Y%m%d%H%M%S')+ 'statReq' + self.genExecID()))
                # ord_status_request.setField(fix.OrderID('*'))
                # ord_status_request.setField(fix.SecurityType('CASH')) #167
                # ord_status_request.setField(fix.Side(fix.Side_SELL))
                print(f'Order status message \n {ord_status_request}')
                fix.Session.sendToTarget(ord_status_request,self.sessionID)
                print('order status request for open orders sent!')
        else:
            ord_status_request = fix.Message()
            ord_status_request.getHeader().setField(fix.BeginString(fix.BeginString_FIX42))  #
            ord_status_request.getHeader().setField(fix.MsgType('H'))  # 39=D
            ord_status_request.getHeader().setField(fix.SendingTime(1))
            ord_status_request.setField(fix.ClOrdID(str(cl_ord_id)))  # 11=
            print(f'ORDER STATUS MESSAGE \n {ord_status_request}')
            fix.Session.sendToTarget(ord_status_request, self.sessionID)
            print(f'ORDER STATUS REQUEST FOR {cl_ord_id} SENT!')
Пример #2
0
    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)
Пример #3
0
    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)
Пример #4
0
    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)
Пример #5
0
    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)
Пример #6
0
    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)
Пример #7
0
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
Пример #8
0
    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)
Пример #9
0
    def _handle_trade(self, symbol, trade, sessionID):
        self.logger.info("Trade(s) executed.")

        # if trade.session.toString() != sessionID.toString():
        if trade.session.toString() not in self.sessions:
            self.logger.debug(
                f"Trade session {trade.session} and sessionID {sessionID} "
                f"do not match, skipping trade"
            )
            self.logger.debug(f"Dumping trade \n{trade}")
            return

        trade_side = "1" if trade.side == "b" else "2"

        execution_report = self._create_execution_report(
            symbol,
            fix.Side(trade_side),
            fix.ClOrdID(trade.order_id),
            price=fix.Price(trade.price),
            quantity=fix.LastQty(trade.quantity),
            order_status=fix.OrdStatus_FILLED,
            exec_type=fix.ExecType_FILL,
        )

        return execution_report
Пример #10
0
    def getOrderCancelReject(self, message):

        beginString = fix.BeginString()
        message.getHeader().getField(beginString)

        clOrdID = fix.ClOrdID()
        orderID = fix.OrderID()
        origClOrdID = fix.OrigClOrdID()

        message.getField(clOrdID)
        message.getField(orderID)
        message.getField(origClOrdID)

        orderCancelReject = fix.Message()
        orderCancelReject.getHeader().setField(beginString)
        orderCancelReject.getHeader().setField(
            fix.MsgType(fix.MsgType_OrderCancelReject))

        orderCancelReject.setField(clOrdID)
        orderCancelReject.setField(orderID)
        orderCancelReject.setField(origClOrdID)
        orderCancelReject.setField(fix.OrdStatus(
            fix.OrdStatus_FILLED))  #39 = 2 FILLED
        orderCancelReject.setField(
            fix.CxlRejReason(0))  #102=0 TOO_LATE_TO_CANCEL
        orderCancelReject.setField(
            fix.CxlRejResponseTo(1))  #434=1  ORDER_CANCEL_REQUEST

        return orderCancelReject
Пример #11
0
    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 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)
Пример #13
0
    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)
Пример #14
0
    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)
Пример #15
0
    def fromApp(self, message, sessionID):

        if self.verbose:
            print(f'[fromApp] {sessionID} | {read_FIX_message(message)}')

        log(self.logger,
            f'[fromApp] {sessionID} | {read_FIX_message(message)}')

        # Get incoming message Type
        msgType = fix.MsgType()
        message.getHeader().getField(msgType)
        msgType = msgType.getValue()

        # Get timestamp (tag 52)
        sending_time = extract_message_field_value(fix.SendingTime(), message,
                                                   'datetime')
        # print('sending_time:', sending_time)

        ########## Quote messages ##########

        if msgType == fix.MsgType_MassQuote:

            self.parse_MassQuote(message, sending_time)

        elif msgType == fix.MsgType_MarketDataSnapshotFullRefresh:

            self.parse_MarketDataSnapshotFullRefresh(message, sending_time)

        # 3) Process MarketDataSnapshot_IncrementalRefresh message
        elif msgType == fix.MsgType_MarketDataIncrementalRefresh:

            print(self._server_str + ' {MD} INCREMENTAL REFRESH!')

        ########## Trade messages ##########

        elif msgType == fix.MsgType_ExecutionReport:

            self.parse_ExecutionReport(message, sending_time)

        elif msgType == fix.MsgType_OrderCancelReject:

            # An OrderCancelReject will be sent as an answer to an  OrderCancelRequest, which cannot be executed.
            # Not much to do here as our order dict would stay the same.
            # If it was canceled successfully, we should get an execution report.

            ClOrdID = extract_message_field_value(fix.ClOrdID(), message,
                                                  'int')

            print(
                f'[fromApp] Order Cancel Request Rejected for order: {ClOrdID}'
            )

        elif msgType == fix.MsgType_MarketDataRequestReject:

            text = extract_message_field_value(fix.Text(), message, 'str')
            print(f'[fromApp] Market Data Request Reject with message: {text}')

        elif self.verbose:
            print(f'[fromApp] {sessionID} | {read_FIX_message(message)}')
            print('unknown message type: ', msgType)
Пример #16
0
    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
Пример #17
0
    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() )
Пример #18
0
    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 fromApp(self, message, sessionID):
        beginString = fix.BeginString()
        msgType = fix.MsgType()
        message.getHeader().getField(beginString)
        message.getHeader().getField(msgType)

        symbol = fix.Symbol()
        side = fix.Side()
        ordType = fix.OrdType()
        orderQty = fix.OrderQty()
        price = fix.Price()
        clOrdID = fix.ClOrdID()

        message.getField(ordType)
        print(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)

        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))

        if beginString.getValue() >= fix.BeginString_FIX41:
            executionReport.setField(fix.ExecType(fix.ExecType_FILL))
            executionReport.setField(fix.LeavesQty(0))

        try:
            fix.Session.sendToTarget(executionReport, sessionID)
        except (SessionNotFound, e):
            return
Пример #20
0
 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
Пример #21
0
 def put_order(self):
     print("Creating the following order: ")
     trade = fix.Message()
     trade.setField(fix.ClOrdID(self.genExecID()))  # 11=Unique order
     trade.setField(fix.HandlInst(fix.HandlInst_MANUAL_ORDER_BEST_EXECUTION))
     trade.setField(fix.Symbol('SMBL'))
     trade.setField(fix.Side(fix.Side_BUY))
     trade.setField(fix.OrdType(fix.OrdType_LIMIT))
     trade.setField(fix.OrderQty(100))
     trade.setField(fix.Price(10))
     print trade.toString()
     fix.Session.sendToTarget(trade, self.sessionID)
 def sendCancelAck(self, orderID):
     message = self.startFIXString(orderID)
     message.setField(quickfix.OrderQty(self.orders[orderID]['leaves']))
     message.setField(quickfix.ExecType(quickfix.ExecType_CANCELED))
     if 'cxlClOrdID' in self.orders[orderID]:
         message.setField(quickfix.ClOrdID(self.orders[orderID]['cxlClOrdID']))
     if 'origClOrdID' in self.orders[orderID]:
         message.setField(quickfix.OrigClOrdID(self.orders[orderID]['origClOrdID']))
     else:
         message.setField(quickfix.OrigClOrdID(self.orders[orderID]['clOrdID']))
     quickfix.Session.sendToTarget(message, self.orders[orderID]['session'])
     self.orders[orderID]['state'] = 'Canceled'
Пример #23
0
 def send_execution_report(self, orderID, orderStatus, execType, details):
     report = self.start_new_message(fix.MsgType_ExecutionReport)
     # required fields FIX4.4
     report_fields = [
         {
             fix.ExecID: self.gen_execID(),
             fix.OrderID: orderID,
             fix.ExecType: execType,
             fix.OrdStatus: orderStatus,
         },
         {
             fix.Symbol: 'symbol',
             fix.Side: 'side',
             fix.LeavesQty: 'leaves_qty',
             fix.CumQty: 'cum_qty',
             fix.AvgPx: 'avg_px',
         },
     ]
     # additional fields
     order_specific_fields = {
         fix.ExecType_NEW: {
             fix.OrderQty: 'quantity',
             fix.Price: 'price',
             fix.OrdType: 'type',
         },
         fix.ExecType_TRADE: {
             fix.LastPx: 'last_px',
             fix.LastQty: 'last_qty',
         },
         fix.ExecType_CANCELED: {
             fix.OrigClOrdID: 'original_orderID',
             fix.OrderQty: 'quantity',
         },
         fix.ExecType_REPLACE: {
             fix.OrigClOrdID: 'original_orderID',
             fix.OrderQty: 'quantity',
         },
         fix.ExecType_REJECTED: {
             fix.OrdRejReason: 'reject_reason',
         },
     }
     for i in range(len(report_fields)):
         for k, v in report_fields[i].items():
             if i == 0:
                 report.setField(k(v))
             else:
                 report.setField(k(details[v]))
     report.setField(fix.ClOrdID(details['client_orderID']))
     for k, v in order_specific_fields[execType].items():
         report.setField(k(details[v]))
     fix.Session.sendToTarget(report, self.sessionID)
     return report
Пример #24
0
 def request_order(self):
     message = fix.Message()
     header = message.getHeader()
     header.setField(fix.BeginString(fix.BeginString_FIX42))
     header.setField(fix.MsgType(fix.MsgType_OrderStatusRequest))  #35=H
     message.setField(fix.ClOrdID("*"))
     message.setField(fix.OrderID("375"))
     message.setField(fix.Side(fix.Side_BUY))  #54=1 Buy
     message.setField(fix.Symbol("ABCD"))  #55=ABCD
     print(message.toString())
     try:
         fix.Session.sendToTarget(message, self.sessionID)
     except (fix.ConfigError, fix.RuntimeError) as e:
         print(e)
Пример #25
0
    def sendOrderCancelRequest(self):
        message = fix.Message()
        header = message.getHeader()

        header.setField(fix.BeginString("FIX.4.2"))
        header.setField(fix.SenderCompID("CLIENT1"))
        header.setField(fix.TargetCompID("EXECUTOR"))
        header.setField(fix.MsgType("D"))
        message.setField(fix.OrigClOrdID("123"))
        message.setField(fix.ClOrdID("321"))
        message.setField(fix.Symbol("LNUX"))
        message.setField(fix.Side(fix.Side_BUY))
        message.setField(fix.Text("Cancel My Order!"))
        fix.Session.sendToTarget(message, self.sessionID)
Пример #26
0
    def fromApp(self, message, sessionID):
		beginString = fix.BeginString()
		msgType = fix.MsgType()
		message.getHeader().getField( beginString )
		message.getHeader().getField( msgType )


		if msgType.getValue() == 'F':
			print 'Cancel Request'
			symbol = fix.Symbol()
			side = fix.Side()
			clOrdID = fix.ClOrdID()
			origClOrdID = fix.OrigClOrdID()
			orderQty = fix.OrderQty()

			message.getField( orderQty )
			message.getField( clOrdID )
			message.getField( origClOrdID )
			message.getField( symbol )
			message.getField( side )

			executionReport = fix.Message()
			executionReport.getHeader().setField( beginString )
			executionReport.getHeader().setField( fix.MsgType(fix.MsgType_ExecutionReport) )
			executionReport.setField( symbol )
			executionReport.setField( side )
			executionReport.setField( clOrdID )
			executionReport.setField( origClOrdID )
			executionReport.setField( fix.ExecID(self.genExecID()) )
			executionReport.setField( fix.OrderID(self.genOrderID()) )
			executionReport.setField( fix.AvgPx(0))
			executionReport.setField( fix.LastShares(0))
			executionReport.setField( fix.CumQty(0))

			if beginString.getValue() == fix.BeginString_FIX40 or beginString.getValue() == fix.BeginString_FIX41 or beginString.getValue() == fix.BeginString_FIX42:
				executionReport.setField( fix.ExecTransType(fix.ExecTransType_CANCEL) )
			executionReport.setField( fix.OrdStatus(fix.OrdStatus_CANCELED) )

			if beginString.getValue() >= fix.BeginString_FIX41:
				executionReport.setField( fix.ExecType(fix.ExecType_CANCELED) )
				executionReport.setField( fix.LeavesQty(0) )
			else:
				executionReport.setField( fix.ExecType(fix.ExecType_CANCELED) )
				executionReport.setField( fix.LeavesQty(0) )

			try:
				print executionReport
				fix.Session.sendToTarget( executionReport, sessionID )
			except SessionNotFound, e:
				return
 def startFIXString(self, orderID):
     message = quickfix.Message()
     message.getHeader().setField(quickfix.BeginString(quickfix.BeginString_FIX42))
     message.getHeader().setField(quickfix.MsgType(quickfix.MsgType_ExecutionReport))
     message.getHeader().setField(quickfix.SendingTime())
     message.getHeader().setField(quickfix.TransactTime())
     message.setField(quickfix.ClOrdID(self.orders[orderID]['clOrdID']))
     message.setField(quickfix.OrderQty(self.orders[orderID]['quantity']))
     message.setField(quickfix.Symbol(self.orders[orderID]['symbol']))
     message.setField(quickfix.Side(self.orders[orderID]['side']))
     message.setField(quickfix.ExecID(str(self.getNextExecID(self.orders[orderID]['target']))))
     if 'exchangeID' not in self.orders[orderID]:
         self.orders[orderID]['exchangeID'] = self.getNextExchangeID(self.orders[orderID]['target'])
     message.setField(quickfix.OrderID(str(self.orders[orderID]['exchangeID'])))
     return message
Пример #28
0
    def send_cancel(self, order):
        order.status = OrdStatus.PENDING_CANCEL

        message = fix.Message()
        message.getHeader().setField(
            fix.MsgType(fix.MsgType_OrderCancelRequest))

        message.setField(fix.Symbol(order.symbol))
        message.setField(fix.Side(order.side))
        message.setField(fix.OrderQty(order.qty))

        cl_ord_id = self.order_store.generate_next_cl_ord_id(order.order_id)
        message.setField(fix.ClOrdID(cl_ord_id))

        self.order_store.update_order_maps(cl_ord_id, order)
        self._send_message(message)
Пример #29
0
    def __get_attributes(self, message):
        price = fix.Price()
        quantity = fix.OrderQty()
        symbol = fix.Symbol()
        side = fix.Side()
        order_type = fix.OrdType()
        client_order_id = fix.ClOrdID()

        message.getField(client_order_id)
        message.getField(side)
        message.getField(order_type)
        message.getField(symbol)
        message.getField(price)
        message.getField(quantity)

        return (symbol, price, quantity, side, order_type, client_order_id)
def sendHelloWorldMessage(sessionID):
    message = fix.Message()
    header = message.getHeader()

    header.setField(fix.BeginString("FIX.4.1"))
    header.setField(fix.SenderCompID("HELLOWORLD_TRADER"))
    header.setField(fix.TargetCompID("HELLOWORLD_EXCHANGE"))
    header.setField(fix.MsgType(fix.MsgType_NewOrderSingle))
    message.setField(fix.ClOrdID('1'))
    message.setField(fix.HandlInst('1'))
    message.setField(fix.Symbol('BMLL'))
    message.setField(fix.Side(fix.Side_BUY))
    message.setField(fix.OrdType(fix.OrdType_MARKET))
    message.setField(fix.Text("Hello Exchange! How are you?"))

    fix.Session.sendToTarget(message, sessionID)