Example #1
0
    def reqMktData(self, contract):

        #logging.info('SubscriptionManager: reqMktData')

        def add_subscription(contract):
            self.handle.append(contract)
            newId = len(self.handle) - 1
            self.tickerId[ContractHelper.makeRedisKeyEx(contract)] = newId

            return newId

        id = self.is_subscribed(contract)
        if id == -1:  # not found
            id = add_subscription(contract)

            #
            # the conId must be set to zero when calling TWS reqMktData
            # otherwise TWS will fail to subscribe the contract
            self.parent.connection.reqMktData(id, contract, '', False)

            if self.persist_f:
                logging.debug(
                    'SubscriptionManager reqMktData: trigger callback')
                self.persist_f(self.handle)

            logging.info(
                'SubscriptionManager: reqMktData. Requesting market data, id = %d, contract = %s'
                % (id, ContractHelper.makeRedisKeyEx(contract)))

        else:
            self.parent.connection.reqMktData(1000 + id, contract, '', True)
            logging.info(
                'SubscriptionManager: reqMktData: contract already subscribed. Request snapshot = %d, contract = %s'
                % (id, ContractHelper.makeRedisKeyEx(contract)))
Example #2
0
 def tickSize(self, items):
     try:
         contract = self.tickerMap[items.__dict__['tickerId']]
         field = items.__dict__['field']
         ct = ContractHelper.kv2object(contract, Contract)
         print 'tickSize>> %s' % ('[%d:%s] %s=%0.4f [%s]' % \
                                     (items.__dict__['tickerId'], ContractHelper.makeRedisKeyEx(ct),\
                                     'bid' if field == 0 else ('ask' if field == 3 else ('last' if field == 5 else field)), \
                                     items.__dict__['size'], datetime.datetime.fromtimestamp(items.__dict__['ts']).strftime('%Y-%m-%d %H:%M:%S.%f')))
     except KeyError:
         print 'tickSize: keyerror: (this could happen on the 1st run as the subscription manager sub list is still empty.'
         print items
Example #3
0
 def tickPrice(self, items):
     try:
         contract = self.tickerMap[items.__dict__['tickerId']]
         field = items.__dict__['field']
         ct = ContractHelper.kv2object(contract, Contract)
         print 'tickPrice>> %s' % ('[%d:%s] %s=%0.4f [%s]' % \
                                     (items.__dict__['tickerId'], ContractHelper.makeRedisKeyEx(ct),\
                                     'bid_q' if field == 1 else ('ask_q' if field == 2 else ('last_q' if field == 4 else field)), \
                                     items.__dict__['price'], datetime.datetime.fromtimestamp(items.__dict__['ts']).strftime('%Y-%m-%d %H:%M:%S.%f')))
     except KeyError:
         print 'tickPrice: keyerror:'
         print items
Example #4
0
    def isContractSubscribed(self, contract):

        #for c in self.instrus.values():
        # 20150814 - changed to rely on DataMap values
        for c in DataMap().getData().values():
            if c['contract'] == contract:
                logging.debug(
                    "MarketDataManager: isContractSubscribed: YES %s" %
                    ContractHelper.printContract(c['contract']))
                return True

        logging.debug(
            "MarketDataManager: isContractSubscribed: No. Subscribing to %s" %
            ContractHelper.printContract(contract))
        return False
Example #5
0
    def printContractByID(self, tick_id):
        tick_id = int(tick_id)

        if DataMap().isKeyInMap(tick_id):

            s = 'Tick:%s [%s]>>' % (tick_id,
                                    ContractHelper.printContract(
                                        DataMap().get(tick_id)['contract']))
            for field, value in DataMap().get(tick_id).iteritems():
                if type(value) is not Contract:
                    s = s + "%d:[%s], " % (field, value)
            print "%s" % s

        print 'values stored in redis:'
        print "%s" % DataMap.rs.get(
            ContractHelper.makeRedisKey(DataMap().get(tick_id)['contract']))
Example #6
0
    def initialize_subscription_mgr(self):

        self.contract_subscription_mgr = SubscriptionManager(self)
        self.contract_subscription_mgr.register_persistence_callback(
            self.persist_subscriptions)
        key = self.config.get(
            "tws_gateway",
            "subscription_manager.subscriptions.redis_key").strip('"').strip(
                "'")
        if self.rs.get(key):
            #contracts = map(lambda x: ContractHelper.kvstring2contract(x), json.loads(self.rs.get(key)))

            def is_outstanding(c):

                today = time.strftime('%Y%m%d')
                if c.m_expiry < today:
                    logging.info(
                        'initialize_subscription_mgr: ignoring expired contract %s%s%s'
                        % (c.m_expiry, c.m_strike, c.m_right))
                    return False
                return True

            contracts = filter(
                lambda x: is_outstanding(x),
                map(lambda x: ContractHelper.kvstring2object(x, Contract),
                    json.loads(self.rs.get(key))))

            self.contract_subscription_mgr.load_subscription(contracts)
Example #7
0
    def tickSize(self, items):

        try:
            contract = self.tickerMap[items.__dict__['tickerId']]['contract']
            tick2oc_slot = self.tickerMap[
                items.__dict__['tickerId']]['tick2oc_slot']
            field = items.__dict__['field']

            logging.debug('tickSize>> %s' % ('[%d:%s:%s:%d] %s=%d %0.2f [%s]' % \
                                        (items.__dict__['tickerId'], ContractHelper.makeRedisKeyEx(contract),\
                                         tick2oc_slot[0], tick2oc_slot[1],\
                                        'bid_q' if field == 0 else ('ask_q' if field == 3 else ('last_q' if field == 5 else field)), \
                                        items.__dict__['size'], self.option_chains[tick2oc_slot[0]].multiplier,\
                                        datetime.datetime.fromtimestamp(items.__dict__['ts']).strftime('%Y-%m-%d %H:%M:%S.%f')))
                          )
            # is an option
            if tick2oc_slot[1] <> -999:
                o = self.get_option_in_chain(tick2oc_slot[0], tick2oc_slot[1])
                o.set_tick_value(field, items.__dict__['size'])

            # is an underylying
            else:

                self.get_underlying_in_chain(tick2oc_slot[0]).set_tick_value(
                    field, items.__dict__['size'])
                #print 'set fut price %s %d:%0.2f' % (ContractHelper.makeRedisKeyEx(self.get_underlying_in_chain(tick2oc_slot[0]).get_contract()), field, items.__dict__['price'])

        except KeyError:
            logging.error(
                'tickSize: keyerror: (this could happen on the 1st run as the subscription manager sub list is still empty.'
            )
            logging.error(''.join('%s=%s, ' % (k, v)
                                  for k, v in items.__dict__.iteritems()))
Example #8
0
    def update_rd(self, tickerId):

        # this routine saves options data into redis map
        # map structure
        #
        #key:
        #    underlying
        #         month
        #            strike
        #                right
        #value:
        #                values
        rs = DataMap().redisConn()
        if rs == None:
            logging.error(
                "update_rd: Redis connection is None! Has it been initialized?"
            )
            return

        contract = DataMap().get(tickerId)['contract']
        r_key = ContractHelper.makeRedisKey(contract)

        rs.sadd(self.rskeys['redis.datastore.key.option_set'], r_key)
        data = DataMap().simple_clone(DataMap().get(tickerId))
        data['last_updated'] = datetime.datetime.now().strftime('%Y%m%d%H%M%S')

        jd = json.dumps(data)
        rs.set(r_key, jd)
Example #9
0
 def reqMktData(self, sm_contract):
     logging.info('TWS Gateway received reqMktData request: %s' %
                  sm_contract)
     try:
         #self.contract_subscription_mgr.reqMktData(ContractHelper.kvstring2contract(sm_contract))
         self.contract_subscription_mgr.reqMktData(
             ContractHelper.kvstring2object(sm_contract, Contract))
     except:
         pass
Example #10
0
    def broadcast_analytics(self, chain_id, option):

        o_key = ContractHelper.makeRedisKeyEx(option.get_contract())
        self.rs.sadd('%s%s' % (self.rs_oc_prefix, chain_id), o_key)

        msg_str = option.object2kvstring()
        self.rs.set(o_key, msg_str)

        self.get_producer().send_messages('optionAnalytics', msg_str)
Example #11
0
    def map_gw_ticker_to_option_chains(self):

        for k, option_chain in self.option_chains.iteritems():
            for option in option_chain.get_option_chain():
                self.get_command_handler().reqMktData(option.get_contract())
            self.get_command_handler().reqMktData(
                option_chain.get_underlying().get_contract())

        self.get_command_handler().gw_req_subscriptions()
        while not self.download_gw_map_done:
            sleep(1)
            logging.info(
                'map_gw_ticker_to_option_chains: awaiting subscription table down to get done...'
            )
            pass

        logging.info(
            'map_gw_ticker_to_option_chains: complete download subscription table from gw'
        )

        # for each tick id in the tickerMap, compare...
        for tickerId, cv in self.tickerMap.iteritems():

            # for each chain in the option chain, iterate...
            for chain_id, chain in self.option_chains.iteritems():

                # for each of the item (Option object) within the option chain...
                for i in range(len(chain.get_option_chain())):

                    # if a match is found...
                    if cv['contract'] == chain.get_option_chain(
                    )[i].get_contract():
                        print 'id:%s col:%d -> tickerId: %d >> %s %s' % (chain_id, i, tickerId, ContractHelper.makeRedisKeyEx(cv['contract']),\
                                                                          ContractHelper.makeRedisKeyEx(chain.get_option_chain()[i].get_contract()))

                        # update the ticker map
                        # key= tws ticker id
                        # value-> key: tick2oc_slot (ticker map to option chain slot) => [chain_id, the ith element]
                        cv['tick2oc_slot'] = [chain_id, i]

                if chain.get_underlying().get_contract() == cv['contract']:
                    print 'id:%s col:%d -> tickerId: %d >> %s %s' % (chain_id, i, tickerId, ContractHelper.makeRedisKeyEx(cv['contract']),\
                                                                      ContractHelper.makeRedisKeyEx(chain.get_underlying().get_contract()))
                    cv['tick2oc_slot'] = [chain_id, -999]
Example #12
0
 def is_subscribed(self, contract):
     #print self.conId.keys()
     ckey = ContractHelper.makeRedisKeyEx(contract)
     if ckey not in self.tickerId.keys():
         return -1
     else:
         # note that 0 can be a key
         # be careful when checking the return values
         # check for true false instead of using implicit comparsion
         return self.tickerId[ckey]
Example #13
0
    def build_chain(self, px, bound, trade_vol):
        self.set_trade_vol(trade_vol)
        undlypx = round(px / self.spd_size) * self.spd_size
        upper_limit = undlypx * (1 + bound)
        lower_limit = undlypx * (1 - bound)

        base_opt_contract = json.loads(
            ContractHelper.object2kvstring(
                self.get_underlying().get_contract()))

        #for i in self.xfrange(int(undlypx), int(upper_limit ), self.spd_size):
        for i in self.xfrange(undlypx, upper_limit, self.spd_size):

            base_opt_contract['m_secType'] = 'OPT'
            base_opt_contract['m_strike'] = i
            base_opt_contract['m_expiry'] = self.expiry
            base_opt_contract['m_right'] = 'C'
            base_opt_contract['m_multiplier'] = self.multiplier
            #self.options.append(ContractHelper.kv2object(base_opt_contract, Contract))
            self.options.append(
                Option(ContractHelper.kv2object(base_opt_contract, Contract)))

            base_opt_contract['m_right'] = 'P'
            #self.options.append(ContractHelper.kv2object(base_opt_contract, Contract))
            self.options.append(
                Option(ContractHelper.kv2object(base_opt_contract, Contract)))

        for i in self.xfrange(undlypx - self.spd_size, lower_limit,
                              -self.spd_size):
            base_opt_contract['m_secType'] = 'OPT'
            base_opt_contract['m_strike'] = i
            base_opt_contract['m_expiry'] = self.expiry
            base_opt_contract['m_right'] = 'C'
            base_opt_contract['m_multiplier'] = self.multiplier
            #self.options.append(ContractHelper.kv2object(base_opt_contract, Contract))
            self.options.append(
                Option(ContractHelper.kv2object(base_opt_contract, Contract)))

            base_opt_contract['m_right'] = 'P'
            #self.options.append(ContractHelper.kv2object(base_opt_contract, Contract))
            self.options.append(
                Option(ContractHelper.kv2object(base_opt_contract, Contract)))
Example #14
0
def test4():
    #global host, port

    f = open(
        '/home/larry/l1304/workspace/finopt/data/subscription-nov-HSI.txt')
    lns = f.readlines()
    cs = map(
        lambda l: ContractHelper.makeContract(tuple(l.strip('\n').split(','))),
        lns)
    c = SampleClient(host, port, 'SampleClient-777')
    c.connect()
    #for contract in cs:
    #c.get_command_handler().reqMktData(cs[0])
    #
    #     contract = Contract() #
    #     contract.m_symbol = 'EUR'
    #     contract.m_currency = 'USD'
    #     contract.m_secType = 'CASH'
    #     contract.m_exchange = 'IDEALPRO'
    #     c.get_command_handler().reqMktData(contract)
    #
    #     contract.m_symbol = 'HSI'
    #     contract.m_currency = 'HKD'
    #     contract.m_secType = 'OPT'
    #     contract.m_exchange = 'HKFE'
    #     contract.m_strike = 21000
    #     contract.m_multiplier = 50.0
    #     contract.m_includeExpired = False
    #
    #     contract.m_right = 'P'
    #     contract.m_expiry = '20151127'
    contract = Contract()
    contract.m_symbol = 'GOOG'
    contract.m_currency = 'USD'
    contract.m_secType = 'STK'
    contract.m_exchange = 'SMART'
    #contract.m_strike = 58.5
    #contract.m_multiplier = 100
    #contract.m_includeExpired = False

    #contract.m_right = 'P'
    #contract.m_expiry = '20151120'
    c.get_command_handler().reqMktData(contract)
    contract = Contract()
    contract.m_symbol = 'EWT'
    contract.m_currency = 'USD'
    contract.m_secType = 'STK'
    contract.m_exchange = 'SMART'
    c.get_command_handler().reqMktData(contract)
    sleep(1)
    c.get_command_handler().gw_req_subscriptions()

    sleep(10)
    c.disconnect()
Example #15
0
def test7():
    contractTuple = ('VMW', 'STK', 'SMART', 'USD', '', 0, '')
    contract = ContractHelper.makeContract(contractTuple)
    oc = OptionsChain('t7')

    oc.set_underlying(contract)

    oc.set_option_structure(contract, 0.5, 100, 0.0012, 0.0328, '20151211')
    oc.build_chain(59.3, 0.08, 0.22)

    c = SampleClient(host, port, 'SampleClient-777')
    c.connect()
    #c.get_command_handler().reqIds()
    c.get_command_handler().gw_req_subscriptions()

    c.get_command_handler().reqMktData(contract)
    for ct in oc.get_option_chain():
        c.get_command_handler().reqMktData(ct.get_contract())
        print ContractHelper.object2kvstring(ct.get_contract())
    sleep(3)
    c.disconnect()
Example #16
0
def test6():

    contractTuple = ('HSI', 'FUT', 'HKFE', 'HKD', '20151127', 0, '')
    #contractTuple = ('VMW', 'STK', 'SMART', 'USD', '', 0, '')
    contract = ContractHelper.makeContract(contractTuple)
    oc = OptionsChain('test6')

    oc.set_underlying(contract)
    oc.set_option_structure(contract, 200, 50, 0.005, 0.003, '20151127')
    oc.build_chain(22300, 0.1)
    c = SampleClient(host, port, 'SampleClient-777')
    c.connect()
    #c.get_command_handler().reqIds()
    c.get_command_handler().gw_req_subscriptions()

    c.get_command_handler().reqMktData(contract)
    for ct in oc.get_option_chain():
        c.get_command_handler().reqMktData(ct.get_contract())
        print ContractHelper.object2kvstring(ct.get_contract())
    sleep(8)
    c.disconnect()
Example #17
0
    def object2kvstring(self):

        try:
            kv = self.object2kv()
            return '{"%s":%s, "%s":%s, "%s":%s, "%s":%s}' % (
                'analytics', dict2str(kv['analytics']), 'contract',
                ContractHelper.contract2kvstring(
                    self.get_contract()), 'tick_values',
                dict2str(kv['tick_values']), 'extra', dict2str(kv['extra']))
        except:
            logging.error('Exception Option.object2kvstring')

        return None
Example #18
0
    def construct_port(self, pos_msg):
        # port structure
        #
        # exch,type,contract_mth,right, strike,con_ration,pos,avgcost
        #
        # Tick Value      Description
        # 5001            impl vol
        # 5002            delta
        # 5003            gamma
        # 5004            theta
        # 5005            vega
        # 5005            premium

        # 6001            avgCost
        # 6002            pos

        toks = ContractHelper.printContract(pos_msg.contract).split('-')
        s = ''

        slots = [0, 1, 4, 6]
        s = s + '%s,%s,%s' % (','.join(
            toks[i] for i in slots), toks[5].replace(
                '.0', ''), '50.0' if toks[0][1:] == 'HSI' else '10.0')
        s = s.replace('[',
                      '') + ",%0.4f,%0.4f" % (pos_msg.pos, pos_msg.avgCost)

        self.port.append(s)

        ckey = ContractHelper.makeRedisKey(pos_msg.contract)
        multiplier = 50.0 if toks[0][1:] == 'HSI' else 10.0

        self.r_set(
            ckey,
            json.dumps({
                "contract": ckey,
                "6002": pos_msg.pos,
                "6001": pos_msg.avgCost,
                "6007": multiplier
            }))
Example #19
0
    def gw_subscriptions(self, items):
        # <class 'comms.tws_protocol_helper.Message'>
        # sample
        #{0: {'contract': <ib.ext.Contract.Contract object at 0x7ff8f8c9e210>}, 1: {'contract': <ib.ext.Contract.Contract object at 0x7ff8f8c9e250>},... }
        #print items.__dict__['subscriptions']

        l = map(
            lambda x: {x[0]: {
                           'contract': x[1]
                       }},
            map(
                lambda x:
                (x[0], ContractHelper.kvstring2object(x[1], Contract)),
                items.__dict__['subscriptions']))
        #l = map(lambda x: {x[0]: x[1]}, map(lambda x: (x[0], json.loads(x[1])), items.__dict__['subscriptions']))
        for i in l:
            self.tickerMap.update(i)
        logging.info('gw_subscriptions -> dump tickerMap ')
        logging.info(''.join('%s=%s,' %
                             (k, ContractHelper.makeRedisKeyEx(v['contract']))
                             for k, v in self.tickerMap.iteritems()))

        self.download_gw_map_done = True
Example #20
0
    def printMap(self):

        for tick_id, instr_v in DataMap().getData().iteritems():
            s = 'Tick:%s [%s]>>' % (tick_id,
                                    ContractHelper.printContract(
                                        DataMap().get(tick_id)['contract']))
            for field, value in sorted(instr_v.iteritems()):
                if type(value) is Contract:
                    continue
                    #s = s + "%s," % ContractHelper.printContract(value)
                else:
                    s = s + "%d:[%s], " % (field, value)

            print "%s" % s
Example #21
0
    def persist_subscriptions(self, contracts):

        key = self.config.get(
            "tws_gateway",
            "subscription_manager.subscriptions.redis_key").strip('"').strip(
                "'")
        #cs = json.dumps(map(lambda x: ContractHelper.contract2kvstring(x) if x <> None else None, contracts))
        cs = json.dumps(
            map(
                lambda x: ContractHelper.object2kvstring(x)
                if x <> None else None, contracts))
        logging.debug(
            'Tws_gateway: updating subscription table to redis store %s' % cs)
        self.rs.set(key, cs)
Example #22
0
    def subscribe(self, contract):

        tick_id = -1
        if self.isContractSubscribed(contract) == False:
            #logging.debug( 'MarketDataManager:subscribe subscrbing to' + ContractHelper.printContract(contract))

            self.con.reqMktData(self.tick_id, contract, '', False)
            tick_id = self.tick_id
            #self.instrus[self.tick_id] = {}
            #self.instrus[self.tick_id]['contract'] = contract

            DataMap().set(self.tick_id, {})
            DataMap().get(self.tick_id)['contract'] = contract

            logging.debug(
                'MarketDataManager:subscribe DataMap stored value - >' +
                ContractHelper.printContract(DataMap().get(self.tick_id)
                                             ['contract']))
            self.tick_id = self.tick_id + 1

        else:
            logging.debug("Contract has been subscribed already %s" %
                          ContractHelper.printContract(contract))
        return tick_id
Example #23
0
    def gw_req_subscriptions(self, value=None):

        #subm = map(lambda i: ContractHelper.contract2kvstring(self.contract_subscription_mgr.handle[i]), range(len(self.contract_subscription_mgr.handle)))
        #subm = map(lambda i: ContractHelper.object2kvstring(self.contract_subscription_mgr.handle[i]), range(len(self.contract_subscription_mgr.handle)))
        subm = map(
            lambda i: (i,
                       ContractHelper.object2kvstring(
                           self.contract_subscription_mgr.handle[i])),
            range(len(self.contract_subscription_mgr.handle)))

        print subm
        if subm:
            self.tws_event_handler.broadcast_event('gw_subscriptions',
                                                   {'subscriptions': subm},
                                                   source='GW')
Example #24
0
    def placeOrder(self, value=None):
        logging.info('TWS_gateway - placeOrder value=%s' % value)
        try:
            vals = json.loads(value)
        except ValueError:
            logging.error('TWS_gateway - placeOrder Exception %s' %
                          traceback.format_exc())
            return

#        c = ContractHelper.kvstring2contract(vals[1])
        o = OrderHelper.kvstring2object(vals[2], Order)
        o.__dict__['transmit'] = self.ib_order_transmit
        #         print c.__dict__
        #         print o.__dict__
        #         print '---------------------'

        #self.connection.placeOrder(vals[0], ContractHelper.kvstring2contract(vals[1]), OrderHelper.kvstring2object(vals[2], Order))
        self.connection.placeOrder(
            vals[0], ContractHelper.kvstring2object(vals[1], Contract),
            OrderHelper.kvstring2object(vals[2], Order))
Example #25
0
    def printMapCSV(self):
        keys = [
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 5001, 5002, 5003, 5004, 5005,
            5006
        ]
        print 'tick id,contract,' + ','.join(str(k) for k in keys)
        lines = ''
        for tick_id, instr_v in DataMap().getData().iteritems():

            #s = '%s,%s-%s-%s,' % (tick_id, DataMap().get(tick_id)['contract'].m_right, DataMap().get(tick_id)['contract'].m_expiry, DataMap().get(tick_id)['contract'].m_strike)
            s = '%s,%s,' % (tick_id,
                            ContractHelper.makeRedisKey(
                                DataMap().get(tick_id)['contract']))
            for k in keys:
                if k in instr_v.keys():
                    s = s + "%s, " % (instr_v[k])
                else:
                    s = s + ','

            print s

            lines += "%s\n" % s
        return lines
Example #26
0
def test_subscription():
    s = SubscriptionManager()
    contractTuple = ('HSI', 'FUT', 'HKFE', 'HKD', '20151029', 0, '')
    c = ContractHelper.makeContract(contractTuple)
    print s.is_subscribed(c)
    print s.add_subscription(c)
    print s.is_subscribed(c)
    s.dump()

    fr = open('/home/larry-13.04/workspace/finopt/data/subscription-hsio.txt')
    for l in fr.readlines():
        if l[0] <> '#':

            s.add_subscription(
                ContractHelper.makeContract(
                    tuple([t for t in l.strip('\n').split(',')])))
    fr.close()
    s.dump()

    fr = open('/home/larry-13.04/workspace/finopt/data/subscription-hsio.txt')
    for l in fr.readlines():
        if l[0] <> '#':

            print s.add_subscription(
                ContractHelper.makeContract(
                    tuple([t for t in l.strip('\n').split(',')])))
    s.dump()
    contractTuple = ('HSI', 'FUT', 'HKFE', 'HKD', '20151127', 0, '')
    c = ContractHelper.makeContract(contractTuple)
    print s.is_subscribed(c)
    print s.add_subscription(c)
    print s.is_subscribed(c), ContractHelper.printContract(
        s.itemAt(s.is_subscribed(c)))

    print 'test itemAt:'
    contractTuple = ('HSI', 'OPT', 'HKFE', 'HKD', '20151127', 21400, 'C')
    c = ContractHelper.makeContract(contractTuple)
    print s.is_subscribed(c), ContractHelper.printContract(
        s.itemAt(s.is_subscribed(c)))
Example #27
0
    def tickPrice(self, items):
        try:
            contract = self.tickerMap[items.__dict__['tickerId']]['contract']
            field = items.__dict__['field']
            tick2oc_slot = self.tickerMap[
                items.__dict__['tickerId']]['tick2oc_slot']
            today = time.strftime('%Y%m%d')
            price = items.__dict__['price']

            #
            # perform some sanity check
            #
            # if field is not bid, ask, last, or close, pass
            if field not in [1, 2, 4, 9]:
                logging.debug('tickPrice: discard unwanted msg field:%d' %
                              field)
                return

            # if we received a negative price, pass
            if price == -1:
                logging.debug('tickPrice: discard unwanted msg price==-1')
                return

            logging.debug( 'tickPrice>> %s' % ('[%d:%s:%s:%d] %s=%0.4f [%s]' % \
                                        (items.__dict__['tickerId'], ContractHelper.makeRedisKeyEx(contract),\
                                         tick2oc_slot[0], tick2oc_slot[1],\
                                        'bid' if field == 1 else ('ask' if field == 2 else ('last' if field == 4 else field)), \
                                        items.__dict__['price'], datetime.datetime.fromtimestamp(items.__dict__['ts']).strftime('%Y-%m-%d %H:%M:%S.%f')))
                          )

            # is an option
            if tick2oc_slot[1] <> -999:
                o = self.get_option_in_chain(tick2oc_slot[0], tick2oc_slot[1])
                o.set_tick_value(field, items.__dict__['price'])

                try:
                    spot = self.get_underlying_in_chain(
                        tick2oc_slot[0]).get_tick_value(4)

                    # the underlying price may not be available when we receive tick price for options
                    if spot <> None:

                        rate = self.option_chains[tick2oc_slot[0]].rate
                        div = self.option_chains[tick2oc_slot[0]].div
                        tvol = self.option_chains[tick2oc_slot[0]].trade_vol
                        logging.debug('sp=%0.4f, x=%0.4f, %s, evald=%s, expiryd=%s, r=%0.4f, d=%0.4f, v=%0.4f, px[%d]=%0.4f' % (\
                                                spot, contract.m_strike, contract.m_right, today, contract.m_expiry, rate,\
                                                div, tvol, field, items.__dict__['price']))

                        results = None
                        iv = optcal.cal_implvol(spot, contract.m_strike, contract.m_right, today, contract.m_expiry, rate,\
                                                div, tvol, items.__dict__['price'])
                        results = optcal.cal_option(spot, contract.m_strike,
                                                    contract.m_right, today,
                                                    contract.m_expiry, rate,
                                                    div, iv['imvol'])
                        results[Option.IMPL_VOL] = iv['imvol']
                        #print results
                        o.set_analytics(**results)
                        logging.debug(o.get_analytics())
                        o.set_extra_attributes('spot', spot)
                        o.set_extra_attributes('rate', rate)
                        o.set_extra_attributes('div', div)
                        o.set_extra_attributes('chain_id', tick2oc_slot[0])

                except Exception, err:
                    logging.error(traceback.format_exc())

                o.set_extra_attributes(
                    'last_updated',
                    datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
                self.broadcast_analytics(tick2oc_slot[0], o)
                logging.debug(o.object2kvstring())
            # is an underylying
            else:
Example #28
0
 def subscribe_tuple(self, tuple):
     return self.subscribe(ContractHelper.makeContract(tuple))
Example #29
0
    def pretty_print(self):
        sorted_opt = sorted(
            map(
                lambda i:
                (self.options[i].get_contract().m_strike, self.options[i]),
                range(len(self.options))))

        def format_tick_val(val, fmt):
            if val == None:
                length = len(fmt % (0))
                return ' ' * length

            return fmt % (val)

        sorted_call = filter(lambda x: x[1].get_contract().m_right == 'C',
                             sorted_opt)
        sorted_put = filter(lambda x: x[1].get_contract().m_right == 'P',
                            sorted_opt)
        # last, bidq, bid, ask, askq, imvol, delta, theta
        fmt_spec = '%8.2f'
        fmt_spec2 = '%8.4f'
        fmt_specq = '%8d'
        fmt_call = map(
            lambda x: (x[0], '%s,%s,%s,%s,%s,%s,%s,%s' % (
                format_tick_val(x[1].get_tick_value(4), fmt_spec),
                format_tick_val(x[1].get_tick_value(0), fmt_specq),
                format_tick_val(x[1].get_tick_value(1), fmt_spec),
                format_tick_val(x[1].get_tick_value(2), fmt_spec),
                format_tick_val(x[1].get_tick_value(3), fmt_specq),
                format_tick_val(x[1].get_analytics()[Option.IMPL_VOL],
                                fmt_spec2),
                format_tick_val(x[1].get_analytics()[Option.DELTA], fmt_spec2),
                format_tick_val(x[1].get_analytics()[Option.THETA], fmt_spec2),
            )), sorted_call)

        fmt_put = map(
            lambda x: (x[0], '%s,%s,%s,%s,%s,%s,%s,%s' % (
                format_tick_val(x[1].get_tick_value(4), fmt_spec),
                format_tick_val(x[1].get_tick_value(0), fmt_specq),
                format_tick_val(x[1].get_tick_value(1), fmt_spec),
                format_tick_val(x[1].get_tick_value(2), fmt_spec),
                format_tick_val(x[1].get_tick_value(3), fmt_specq),
                format_tick_val(x[1].get_analytics()[Option.IMPL_VOL],
                                fmt_spec2),
                format_tick_val(x[1].get_analytics()[Option.DELTA], fmt_spec2),
                format_tick_val(x[1].get_analytics()[Option.THETA], fmt_spec2),
            )), sorted_put)
        title = '%s%30s%s' % ('-' * 40,
                              ContractHelper.makeRedisKeyEx(
                                  self.get_underlying().get_contract()).center(
                                      50, ' '), '-' * 40)
        header = '%8s|%8s|%8s|%8s|%8s|%8s|%8s|%8s |%8s| %8s|%8s|%8s|%8s|%8s|%8s|%8s|%8s' % (
            'last', 'bidq', 'bid', 'ask', 'askq', 'ivol', 'delta', 'theta',
            'strike', 'last', 'bidq', 'bid', 'ask', 'askq', 'ivol', 'delta',
            'theta')
        combined = map(
            lambda i: '%s |%8.2f| %s' %
            (fmt_call[i][1], fmt_put[i][0], fmt_put[i][1]),
            range(len(fmt_call)))
        footer = '%s' % ('-' * 130)
        print title
        print header
        for e in combined:
            print e
        print footer
Example #30
0
        exit(-1)

    cfg_path = sys.argv[1:]
    config = ConfigParser.SafeConfigParser()
    if len(config.read(cfg_path)) == 0:
        raise ValueError, "Failed to open config file"

    logconfig = eval(
        config.get(
            "options_chain",
            "options_calculation_engine.logconfig").strip('"').strip("'"))
    logconfig['format'] = '%(asctime)s %(levelname)-8s %(message)s'
    logging.basicConfig(**logconfig)

    contractTuple = ('QQQ', 'STK', 'SMART', 'USD', '', 0, '')
    contract = ContractHelper.makeContract(contractTuple)
    oc = OptionsChain('QQQ-MAR24')
    oc.set_option_structure(contract, 2.5, 100, 0.005, 0.003, '20160324')
    oc.build_chain(98.0, 0.025, 0.25)
    for c in oc.get_option_chain():
        print '%s' % ContractHelper.makeRedisKeyEx(c.get_contract())

    near_expiry = '20160226'
    contractTuple = ('HSI', 'FUT', 'HKFE', 'HKD', near_expiry, 0, '')
    contract = ContractHelper.makeContract(contractTuple)
    oc1 = OptionsChain('HSI-%s' % near_expiry)
    oc1.set_option_structure(contract, 200, 50, 0.0012, 0.0328, near_expiry)
    oc1.build_chain(19200, 0.08, 0.219)
    for c in oc1.get_option_chain():
        print '%s' % ContractHelper.makeRedisKeyEx(c.get_contract())