holds latest tick bid/ask/last size
358302
def handleTickSize(self, msg):
        

        if msg.size < 0:
            return

        df2use = self.marketData
        if self.contracts[msg.tickerId].m_secType in ("OPT", "FOP"):
            df2use = self.optionsData

        # create tick holder for ticker
        if msg.tickerId not in df2use.keys():
            df2use[msg.tickerId] = df2use[0].copy()

        # ---------------------
        # market data
        # ---------------------
        # bid size
        if msg.field == dataTypes["FIELD_BID_SIZE"]:
            df2use[msg.tickerId]['bidsize'] = int(msg.size)
        # ask size
        elif msg.field == dataTypes["FIELD_ASK_SIZE"]:
            df2use[msg.tickerId]['asksize'] = int(msg.size)
        # last size
        elif msg.field == dataTypes["FIELD_LAST_SIZE"]:
            df2use[msg.tickerId]['lastsize'] = int(msg.size)

        # ---------------------
        # options data
        # ---------------------
        # open interest
        elif msg.field == dataTypes["FIELD_OPEN_INTEREST"]:
            df2use[msg.tickerId]['oi'] = int(msg.size)

        elif msg.field == dataTypes["FIELD_OPTION_CALL_OPEN_INTEREST"] and \
                self.contracts[msg.tickerId].m_right == "CALL":
            df2use[msg.tickerId]['oi'] = int(msg.size)

        elif msg.field == dataTypes["FIELD_OPTION_PUT_OPEN_INTEREST"] and \
                self.contracts[msg.tickerId].m_right == "PUT":
            df2use[msg.tickerId]['oi'] = int(msg.size)

        # volume
        elif msg.field == dataTypes["FIELD_VOLUME"]:
            df2use[msg.tickerId]['volume'] = int(msg.size)

        elif msg.field == dataTypes["FIELD_OPTION_CALL_VOLUME"] and \
                self.contracts[msg.tickerId].m_right == "CALL":
            df2use[msg.tickerId]['volume'] = int(msg.size)

        elif msg.field == dataTypes["FIELD_OPTION_PUT_VOLUME"] and \
                self.contracts[msg.tickerId].m_right == "PUT":
            df2use[msg.tickerId]['volume'] = int(msg.size)

        # fire callback
        self.ibCallback(caller="handleTickSize", msg=msg)
1044788
def remove_last_entry(self):
        """"""
        self.current_beat -= 1.0 / self.bar[-1][1]
        self.bar = self.bar[:-1]
        return self.current_beat
1145949
def last(self, db=_DefaultDB):
        '''
        
        '''
        self._acqXactForReading()
        try:
            with self.xact.cursor(db=db.db) as curs:
                if not curs.last():
                    return None
                return curs.key(), curs.value()
        finally:
            self._relXactForReading()
643540
def _last_values(self):
        
        if not self.session.get('last_request_uri'):
            self.session.last_request_uri = None
        self.session.last_request_at = self.session.get('last_request_at', 0)
648323
def set_last_row_idx(self, last_row_idx):
		'''
		
		'''
		assert last_row_idx >= self._max_row
		self._max_row = last_row_idx
		return self
1118970
def _flush_graph_val(self):
        """"""
        if not self._graphvals2set:
            return
        delafter = {}
        for graph, key, branch, turn, tick, value in self._graphvals2set:
            if (graph, key, branch) in delafter:
                delafter[graph, key, branch] = min((
                    (turn, tick),
                    delafter[graph, key, branch]
                ))
            else:
                delafter[graph, key, branch] = (turn, tick)
        self.sqlmany(
            'del_graph_val_after',
            *((graph, key, branch, turn, turn, tick)
              for ((graph, key, branch), (turn, tick)) in delafter.items())
        )
        self.sqlmany('graph_val_insert', *self._graphvals2set)
        self._graphvals2set = []
256938
def current_hold_price(self):
        
        
        def weights(x):
            n=len(x)
            res=1
            while res>0 or res<0:
                res=sum(x[:n]['amount'])
                n=n-1
            
            x=x[n+1:]     
            
            if sum(x['amount']) != 0:
                return np.average(
                    x['price'],
                    weights=x['amount'],
                    returned=True
                )
            else:
                return np.nan
        return self.history_table.set_index(
            'datetime',
            drop=False
        ).sort_index().groupby('code').apply(weights).dropna()
550827
def tick(self):
        """"""
        now = datetime.datetime.now()
        self.add(now)

        # Create a list of timestamps, one for each period and
        # representing the beginning of that period (i.e. since now.)
        tstamps = [now - datetime.timedelta(seconds=xx)
                   for xx in self._periods]

        # Trim off any tick values older than the earliest timestamp.
        self.removeLT(min(tstamps))

        # Create a list of counts, one for each period and
        # representing the number of ticks in that period.
        counts = [self.getCountGT(xx) for xx in tstamps]

        # Compute a list of rates for the periods.
        rates = [float(xx)/yy for xx, yy in zip(counts, self._periods)]

        # Return the rates as a tuple.
        return tuple(rates)
161213
def last_modified(self, last_modified):
        """"""
        self._indicator_data['lastModified'] = self._utils.format_datetime(
            last_modified, date_format='%Y-%m-%dT%H:%M:%SZ'
        )
1351730
def last(self):
        

        if self.limit > self.total:
            return None
        elif self.offset >= self.total:
            return None
        else:
            offset = (self.total / self.limit) * self.limit
            return {'page[offset]': offset, 'page[limit]': self.limit}
952870
def last_change(self):
        
        try:
            cdt = self.latest('created')
            udt = self.latest('updated')
            #print cdt, udt
            return max(cdt.created, udt.updated)

        except ObjectDoesNotExist:
            return None
114863
def on_bar(self, event):
        '''
        
        '''
        'while updating the market data'

        print(
            "on_bar account {} ".format(self.account_cookie),
            event.market_data.data
        )
        print(event.send_order)
        try:
            for code in event.market_data.code:

                if self.sell_available.get(code, 0) > 0:
                    print('可以卖出 {}'.format(self._currenttime))
                    event.send_order(
                        account_cookie=self.account_cookie,
                        amount=self.sell_available[code],
                        amount_model=AMOUNT_MODEL.BY_AMOUNT,
                        time=self.current_time,
                        code=code,
                        price=0,
                        order_model=ORDER_MODEL.MARKET,
                        towards=ORDER_DIRECTION.SELL,
                        market_type=self.market_type,
                        frequence=self.frequence,
                        broker_name=self.broker
                    )
                else:
                    print('{} 无仓位, 买入{}'.format(self._currenttime, code))
                    event.send_order(
                        account_cookie=self.account_cookie,
                        amount=100,
                        amount_model=AMOUNT_MODEL.BY_AMOUNT,
                        time=self.current_time,
                        code=code,
                        price=0,
                        order_model=ORDER_MODEL.MARKET,
                        towards=ORDER_DIRECTION.BUY,
                        market_type=self.market_type,
                        frequence=self.frequence,
                        broker_name=self.broker
                    )
        except Exception as e:
            print(e)
140016
def discard_last(self, indices):
        """"""
        for i in indices:
            self.buffer_expire[i] = self.buffer_expire[i][:-1]
            self.buffer[i] = self.buffer[i][:-1]
811268
def get_last_available_price(self) -> PriceModel:
        
        price_db = PriceDbApplication()
        symbol = SecuritySymbol(self.security.namespace, self.security.mnemonic)
        result = price_db.get_latest_price(symbol)
        return result
1108062
def last(self, callback=None, default=None):
        
        if callback is not None:
            for val in reversed(self.items):
                if callback(val):
                    return val

            return value(default)

        if len(self.items) > 0:
            return self.items[-1]
        else:
            return default
1078963
def _last_index(x, default_dim):
  """"""
  if x.get_shape().ndims is not None:
    return len(x.get_shape()) - 1
  else:
    return default_dim
301860
def last_modified(self):
        
        if self.entries:
            latest = max(self.entries, key=lambda x: x.last_modified)
            return arrow.get(latest.last_modified)
        return arrow.get()