Exemplo n.º 1
0
    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())
Exemplo n.º 2
0
    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
Exemplo n.º 3
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)
Exemplo n.º 4
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)
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
 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()
Exemplo n.º 7
0
    def securityStatusRequest(self):
        # pag 80

        msg = self.buildMsgHeader("e")

        msg.setField(fix.SecurityStatusReqID("securityR"))
        msg.setField(fix.SubscriptionRequestType("1"))
        # Block Instrument

        # msg.setField(fix.NoRelatedSym(1))
        msg.setField(fix.Symbol("RFX20Sep19"))
        msg.setField((fix.SecurityExchange("ROFX")))

        fix.Session.sendToTarget(msg)
Exemplo n.º 8
0
    def querySecurityExchange(self):
        securityExchanges = [
            'AGGREGATOR', 'ALGO', 'ASE', 'SX', 'B3', 'BitMEX', 'BrokerTec',
            'CBOT', 'CFE', 'CME', 'Coinbase', 'CoinFLEX', 'CurveGlobal',
            'CZCE', 'DCE', 'DGCX', 'EEX', 'Eurex', 'Euronext', 'Fenics', 'FEX',
            'HKEX', 'ICE', 'ICE_L', 'IDEM', 'INE', 'KCG', 'LME', 'LSE', 'MEFF',
            'MOEX', 'MX', 'MX', 'NDAQ_EU', 'NFI', 'NFX', 'OSE', 'SGX', 'TFX',
            'TOCOM'
        ]
        print('Possible values include: ')
        print(', '.join(securityExchanges))
        value = input('Option: ')
        while value not in securityExchanges:
            print('Invalid Value. Please try again')
            value = input('Option: ')

        return fix.SecurityExchange(value)
Exemplo n.º 9
0
    def securityListRequest(self):
        #pag 73

        msg = fix50.SecurityListRequest()

        msg.setField(fix.SecurityReqID("listaXX"))
        msg.setField(fix.SecurityListRequestType(0))

        #group = fix50.SecurityListRequest()
        #group.setField(fix.NoRelatedSym(1))

        msg.setField(fix.Symbol('DOSep19'))
        msg.setField(fix.SecurityExchange('ROFX'))
        # msg.addGroup(group)

        # msg.setField(fix.MarketSegmentID("DDF"))   #1300
        # msg.setField(fix.MarketID('ROFX'))  #1301

        # msg.setField(fix.Symbol("RFX20Sep19"))
        # msg.setField(fix.SecurityExchange('ROFX'))
        # msg.setField(fix.CFICode("FXXXSX"))

        fix.Session.sendToTarget(msg, self.sessionID)
Exemplo n.º 10
0
    def onMessage_MarketDataSnapshotFullRefresh(self):
        """
        onMessage - Market Data - Snapshot / Full Refresh

        Message Type = 'W'.
        The Market Data Snapshot/Full Refresh messages are sent as the response to a Market Data Request
        message. The message refers to only one Market Data Request. It will contain the appropiate MDReqID
        tag value to correlate the request with the response.

        Fields:
            - (35) MsgType = W
            - (262) MDReqID = (string)
            - Block Instrument:
                - (55) Symbol = (string - Ticker)
            - Block MDfullGrp:
                - (268) NoMDEntries = (Int - number of Entries)
                    - (269) MDEntryType = 0 (Bid) / 1 (Offer) / 2 (Trade) / 4 (Opening price) / 5 (Closing Price) / 6 (Settlement Price) /
                                            7 (Trading Session High Price) / 8 (Trading Session Low Price) / B (Trade Volume) / C (Open Interest) /
                                            x (Nominal Volume) / w (Cash Volume)
                    - (270) MDEntryPx = (float - Conditional field when MDEntryType is 0-1-2-4-5-6-7-8-w)
                    - (271) MDEntrySize = (int - Conditional field when MDEntryType is 0-1-2-B-C-x)
                    - (290) MDEntryPositionNo = (int)
        """

        data = {}

        ## Number of entries following (Bid, Offer, etc)
        noMDEntries = self.getValue(fix.NoMDEntries())

        symbol = self.getValue(fix.Symbol())

        ## Market ID (ROFX, BYMA)
        marketId = self.getValue(fix.SecurityExchange())

        instrumentId = {"symbol": symbol, "marketId": marketId}
        data["instrumentId"] = instrumentId
        data["marketData"] = {"BI": [], "OF": []}

        group = fix50.MarketDataSnapshotFullRefresh().NoMDEntries()

        MDEntryType = fix.MDEntryType(
        )  # Identifies the type of entry (Bid, Offer, etc)
        MDEntryPx = fix.MDEntryPx()
        MDEntrySize = fix.MDEntrySize()
        MDEntryPositionNo = fix.MDEntryPositionNo(
        )  # Display position of a bid or offer, numbered from most competitive to least competitive
        """
        table = texttable.Texttable()
        table.set_deco(texttable.Texttable.BORDER|texttable.Texttable.HEADER)
        table.header(['Ticker','Tipo','Precio','Size','Posicion'])
        table.set_cols_width([12,20,8,8,8])
        table.set_cols_align(['c','c','c','c','c'])
        """

        for entry in range(1, int(noMDEntries) + 1):
            try:

                md = {}
                price, size, position = None, None, None

                self.message.getGroup(entry, group)
                entry_type = group.getField(MDEntryType).getString()

                if entry_type in list('01245678w'):
                    # campos que tienen precio
                    price = group.getField(MDEntryPx).getString()
                    md['price'] = float(price)

                if entry_type in list('012BCx'):
                    # campos que tienen size
                    size = group.getField(MDEntrySize).getString()
                    md['size'] = int(size)

                if entry_type in list('01'):
                    # campos que tienen orden
                    position = group.getField(MDEntryPositionNo).getString()
                    md['position'] = int(position)

                if entry_type == '0':
                    data["marketData"]["BI"].append(md)
                    tipo = 'BID'

                elif entry_type == '1':
                    data["marketData"]["OF"].append(md)
                    tipo = 'OFFER'

                elif entry_type == 'B':
                    data["marketData"]["TV"] = md
                    tipo = 'TRADE VOLUME'

                else:
                    tipo = entry_type

                # table.add_row([symbol, tipo, price, size, position])
            except:
                pass
        # Aca antes de devolver se puede mandar a una cola o algo
        return data