简体   繁体   中英

Order book design for Coinbase Pro

Based on Coinbase Pro Websocket document I am building local copy of orderbook in python. Their data structure is

{
  "type": "snapshot",
  ...
  "bids": [[price1, size1], [price2, size2], ...]
}

and subsequently

{
  "type": "l2update",
  ...
  "changes": [[side1, price1, size1], [side2, price2, size2], ...]
}

My requirement is to maintain this orderbook and be able to peek the top of book (quotes) efficiently. I'm using SortedDict from sortedcontainers but is this the best way? I've heard some use skiplist data structure for orderbook as well. Let me know if someone knows the best practice to maintain orderbook.

My current snippet is like this.

class Book:
    def __init__(self):
        self.bids = SortedDict()
        self.asks = SortedDict()
        self.timestamp = pd.Timestamp.now().tz_localize('America/New_York')

    def snapshot(self, msg):
        self.bids = SortedDict([[Decimal(v[0]), Decimal(v[1])]
                                for v in msg['bids']])
        self.asks = SortedDict([[Decimal(v[0]), Decimal(v[1])]
                                for v in msg['asks']])
        self.timestamp = pd.Timestamp.now().tz_localize('America/New_York')

    def update(self, msg):
        for c in msg['changes']:
            side, price, size = c
            price = Decimal(price)
            size = Decimal(size)
            o = self.bids
            if side == 'sell':
                o = self.asks
            if size == 0:
                del o[price]
            else:
                o[price] = size
        self.timestamp = pd.Timestamp(
            msg['time']).tz_convert('America/New_York')

    def get_quotes(self):
        return self.asks.peekitem(index=0), self.bids.peekitem(index=-1)

I found this old post from a blog of a former quant. Apparently the best way is to use binary trees. Hope you can try to implement this model and figure out which one is the best.

https://web.archive.org/web/20110219163448/http://howtohft.wordpress.com/2011/02/15/how-to-build-a-fast-limit-order-book/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM