async def _book(self, msg: dict, pair: str, timestamp: float): delta = {BID: [], ASK: []} msg = msg[1:-2] if 'as' in msg[0]: # Snapshot bids = { Decimal(update[0]): Decimal(update[1]) for update in msg[0]['bs'] } asks = { Decimal(update[0]): Decimal(update[1]) for update in msg[0]['as'] } self._l2_book[pair] = OrderBook( self.id, pair, max_depth=self.max_depth, bids=bids, asks=asks, checksum_format='KRAKEN', truncate=self.max_depth != self.valid_depths[-1]) await self.book_callback(L2_BOOK, self._l2_book[pair], timestamp, raw=msg) else: for m in msg: for s, updates in m.items(): side = False if s == 'b': side = BID elif s == 'a': side = ASK if side: for update in updates: price, size, *_ = update price = Decimal(price) size = Decimal(size) if size == 0: # Per Kraken's technical support # they deliver erroneous deletion messages # periodically which should be ignored if price in self._l2_book[pair].book[side]: del self._l2_book[pair].book[side][price] delta[side].append((price, 0)) else: delta[side].append((price, size)) self._l2_book[pair].book[side][price] = size if self.checksum_validation and 'c' in msg[0] and self._l2_book[ pair].book.checksum() != int(msg[0]['c']): raise BadChecksum("Checksum validation on orderbook failed") await self.book_callback( L2_BOOK, self._l2_book[pair], timestamp, delta=delta, raw=msg, checksum=int(msg[0]['c']) if 'c' in msg[0] else None)
async def _book(self, msg: dict, pair: str, timestamp: float): delta = {BID: [], ASK: []} msg = msg[1:-2] if 'as' in msg[0]: # Snapshot self.l2_book[pair] = { BID: sd({ Decimal(update[0]): Decimal(update[1]) for update in msg[0]['bs'] }), ASK: sd({ Decimal(update[0]): Decimal(update[1]) for update in msg[0]['as'] }) } await self.book_callback(self.l2_book[pair], L2_BOOK, pair, True, delta, timestamp, timestamp) else: for m in msg: for s, updates in m.items(): side = False if s == 'b': side = BID elif s == 'a': side = ASK if side: for update in updates: price, size, *_ = update price = Decimal(price) size = Decimal(size) if size == 0: # Per Kraken's technical support # they deliver erroneous deletion messages # periodically which should be ignored if price in self.l2_book[pair][side]: del self.l2_book[pair][side][price] delta[side].append((price, 0)) else: delta[side].append((price, size)) self.l2_book[pair][side][price] = size for side in (BID, ASK): while len(self.l2_book[pair][side]) > self.book_depth: del_price = self.l2_book[pair][side].items( )[0 if side == BID else -1][0] del self.l2_book[pair][side][del_price] delta[side].append((del_price, 0)) if self.checksum_validation and 'c' in msg[ 0] and self.__calc_checksum(pair) != msg[0]['c']: raise BadChecksum("Checksum validation on orderbook failed") await self.book_callback(self.l2_book[pair], L2_BOOK, pair, False, delta, timestamp, timestamp)