Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:51bitquant Ai hedge fund crypto DepthCache

From Leeroopedia
Knowledge Sources
Domains Crypto_Markets, Real_Time_Streaming, Order_Book
Last Updated 2026-10-28 14:00 GMT

Overview

Concrete tool for maintaining a synchronized local order book (bids/asks) from Binance websocket depth streams, provided by the `DepthCache` and `DepthCacheManager` family of classes.

Description

The DepthCache class holds in-memory bid/ask dictionaries keyed by price level, removing any level whose quantity drops to `"0.00000000"`. BaseDepthCacheManager is an abstract async context manager that initializes a REST snapshot, opens a websocket depth socket, and applies incoming diff/partial messages to the cache. DepthCacheManager (spot) enforces sequential update-ID continuity — buffering pre-snapshot messages, dropping stale updates (`u <= last_update_id`), and re-initializing on gaps (`U != last_update_id + 1`). FuturesDepthCacheManager replaces (not merges) levels. OptionsDepthCacheManager binds an options depth socket. ThreadedDepthCacheManager runs the whole manager in a background thread via Implementation:51bitquant_Ai_hedge_fund_crypto_ThreadedApiManager.

Usage

  • Live order-book analysis: subscribe to a symbol's depth stream and read the sorted book on every callback for real-time spread/microstructure analysis.
  • Spot diff book: use `DepthCacheManager` with `refresh_interval` to periodically re-snapshot from REST and stay aligned.
  • Futures/options books: use `FuturesDepthCacheManager` / `OptionsDepthCacheManager` for the corresponding market segments.
  • Threaded (sync callers): use `ThreadedDepthCacheManager` when the calling code is synchronous and cannot drive an asyncio loop itself.

Code Reference

Source Location

Signature

class DepthCache(object):
    def __init__(self, symbol, conv_type: Callable = float): ...

    def add_bid(self, bid): ...
    def add_ask(self, ask): ...
    def get_bids(self): ...
    def get_asks(self): ...

    @staticmethod
    def sort_depth(vals, reverse=False, conv_type: Callable = float): ...


class BaseDepthCacheManager:
    TIMEOUT = 60

    def __init__(
        self,
        client,
        symbol,
        loop=None,
        refresh_interval: Optional[int] = DEFAULT_REFRESH,  # 30 min
        bm=None,
        limit=10,
        conv_type=float,
    ): ...

    async def __aenter__(self): ...
    async def __aexit__(self, *args, **kwargs): ...
    async def recv(self): ...
    def get_depth_cache(self): ...
    async def close(self): ...
    def get_symbol(self): ...


class DepthCacheManager(BaseDepthCacheManager):
    def __init__(
        self,
        client,
        symbol,
        loop=None,
        refresh_interval: Optional[int] = None,
        bm=None,
        limit=500,
        conv_type=float,
        ws_interval=None,
    ): ...


class FuturesDepthCacheManager(BaseDepthCacheManager): ...
class OptionsDepthCacheManager(BaseDepthCacheManager): ...


class ThreadedDepthCacheManager(ThreadedApiManager):
    def __init__(
        self,
        api_key: Optional[str] = None,
        api_secret: Optional[str] = None,
        requests_params: Optional[Dict[str, str]] = None,
        tld: str = "com",
        testnet: bool = False,
    ): ...

    def start_depth_cache(
        self,
        callback: Callable,
        symbol: str,
        refresh_interval=None,
        bm=None,
        limit=10,
        conv_type=float,
        ws_interval=0,
    ) -> str: ...

    def start_futures_depth_socket(self, callback, symbol, ...) -> str: ...
    def start_options_depth_socket(self, callback, symbol, ...) -> str: ...

Import

from src.gateway.binance.ws.depthcache import (
    DepthCache,
    DepthCacheManager,
    FuturesDepthCacheManager,
    OptionsDepthCacheManager,
    ThreadedDepthCacheManager,
)

I/O Contract

Inputs

Name Type Required Description
client AsyncClient Yes Binance async REST client (for snapshot + listen keys)
symbol str Yes Trading symbol, e.g. `"BTCUSDT"`
refresh_interval int No Seconds between REST re-snapshots; `0`/`None` disables (default 1800)
bm BinanceSocketManager No Reused socket manager; created if omitted
limit int No Order book depth for the REST snapshot (spot default 500)
conv_type Callable No Type for price/quantity, default `float`
ws_interval int No Spot diff update cadence: `0`/`None` (1s) or `100` (100ms)

Outputs

Name Type Description
DepthCache.get_bids() list[list] Sorted `[price, qty]` bids descending by price
DepthCache.get_asks() list[list] Sorted `[price, qty]` asks ascending by price
DepthCache.update_time int Last event time / update id
recv() DepthCache Yields the updated cache per processed depth message
start_depth_cache() str Connection key path (threaded variant)

Usage Examples

Async Spot Depth Cache

import asyncio
from src.gateway.binance.async_client import AsyncClient
from src.gateway.binance.ws.depthcache import DepthCacheManager

async def main():
    client = await AsyncClient.create(api_key="...", api_secret="...")
    dcm = DepthCacheManager(client, "BTCUSDT", limit=100, ws_interval=100)
    async with dcm:
        while True:
            cache = await dcm.recv()
            if cache:
                bids = cache.get_bids()[:5]
                asks = cache.get_asks()[:5]
                spread = float(asks[0][0]) - float(bids[0][0])
                print(f"top bid={bids[0]} top ask={asks[0]} spread={spread}")

asyncio.run(main())

Threaded Depth Cache (sync caller)

from src.gateway.binance.ws.depthcache import ThreadedDepthCacheManager

def on_depth(cache):
    # Called from the manager thread with the updated DepthCache
    print("bids:", cache.get_bids()[:3], "asks:", cache.get_asks()[:3])

mgr = ThreadedDepthCacheManager(api_key="...", api_secret="...")
mgr.start_depth_socket(on_depth, symbol="BTCUSDT", limit=10, ws_interval=0)
# ... later:
mgr.stop()

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment