MCPcopy Create free account
hub / github.com/danpaquin/coinbasepro-python / OrderBook

Class OrderBook

cbpro/order_book.py:15–229  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13
14
15class OrderBook(object):
16 def __init__(self, product_id='BTC-USD', log_to=None):
17 self._asks = SortedDict()
18 self._bids = SortedDict()
19 self._client = PublicClient()
20 self._sequence = -1
21 self._log_to = log_to
22 if self._log_to:
23 assert hasattr(self._log_to, 'write')
24 self._current_ticker = None
25 self.product_id = product_id
26
27 def reset_book(self):
28 self._asks = SortedDict()
29 self._bids = SortedDict()
30 res = self._client.get_product_order_book(product_id=self.product_id, level=3)
31 for bid in res['bids']:
32 self.add({
33 'id': bid[2],
34 'side': 'buy',
35 'price': Decimal(bid[0]),
36 'size': Decimal(bid[1])
37 })
38 for ask in res['asks']:
39 self.add({
40 'id': ask[2],
41 'side': 'sell',
42 'price': Decimal(ask[0]),
43 'size': Decimal(ask[1])
44 })
45 self._sequence = res['sequence']
46
47 def process_message(self, message):
48 if message.get('product_id') == self.product_id:
49 if self._log_to:
50 pickle.dump(message, self._log_to)
51
52 sequence = message.get('sequence', -1)
53 if self._sequence == -1:
54 self.reset_book()
55 return
56 if sequence <= self._sequence:
57 # ignore older messages (e.g. before order book initialization from getProductOrderBook)
58 return
59 elif sequence > self._sequence + 1:
60 self.on_sequence_gap(self._sequence, sequence)
61 return
62
63 msg_type = message['type']
64 if msg_type == 'open':
65 self.add(message)
66 elif msg_type == 'done' and 'price' in message:
67 self.remove(message)
68 elif msg_type == 'match':
69 self.match(message)
70 self._current_ticker = message
71 elif msg_type == 'change':
72 self.change(message)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected