-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgdax.py
95 lines (76 loc) · 3.49 KB
/
gdax.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import json
from operator import itemgetter
from base import CryptoExchange
from sortedcollection import SortedCollection
class GDAX(CryptoExchange):
url = "wss://ws-feed.gdax.com"
all_markets = ['bch_btc', 'bch_usd', 'btc_eur', 'btc_gbp', 'btc_usd', 'eth_btc', 'eth_eur', 'eth_usd', 'ltc_btc',
'ltc_eur', 'ltc_usd', 'bch_eur']
need_common_names = False
async def subscribe_ticker(self):
request = {
'type': 'subscribe',
'product_ids': [m for m in self.markets_native],
'channels': ['ticker', 'heartbeat']
# 'channels': ['ticker', 'level2', 'heartbeat']
}
await self._ws.send(json.dumps(request))
async def on_message(self, json_payload):
# print('< ', json_payload)
msg_type = json_payload['type']
try:
market = self._market_names_map[json_payload['product_id']]
if msg_type == 'l2update':
self.on_orderbook_l2update(market, json_payload['changes'])
elif msg_type == 'snapshot':
self.on_orderbook_snapshot(market, json_payload)
elif msg_type == 'heartbeat':
self.on_heartbeat(market, json_payload)
elif msg_type == 'ticker':
await self.on_ticker(market, json_payload)
except Exception as e:
pass
def on_heartbeat(self, market, data):
# self.print_orderbook()
pass
def on_orderbook_snapshot(self, symbol, data):
self.order_books[symbol] = dict()
self.order_books[symbol]['bids'] = SortedCollection(
[[float(pq) for pq in bid]
for bid in data['bids']], key=itemgetter(0)
)
self.order_books[symbol]['asks'] = SortedCollection(
[[float(pq) for pq in ask]
for ask in data['asks']], key=itemgetter(0)
)
def on_orderbook_l2update(self, symbol, data):
for change in data:
side, p, q = change
p, q = float(p), float(q)
book = self.order_books[symbol]['asks'] if side == 'sell' else self.order_books[symbol]['bids']
try:
el = book.find(p)
if q == 0: # delete from orderbook
book.remove(el) # delete order at price level p
except ValueError:
book.insert([p, q])
async def on_ticker(self, market, data):
await self.update_ticker(
market,
best_bid=float(data['best_bid']),
best_ask=float(data['best_ask']),
last_price=float(data['price']),
volume=float(data['volume_24h']),
)
# print('{:10s} {}: {}'.format(
# self.__class__.__name__, market,
# 'b {bid_size:>{widht}.{prec}f} @ {best_bid:<{widht}.{prec}f} '
# 'a {ask_size:>{widht}.{prec}f} @ {best_ask:<{widht}.{prec}f} {ts}'.format(widht=15, prec=4, ts=0,
# bid_size=0,
# ask_size=0,
# best_bid=float(data['best_bid']),
# best_ask=float(data['best_ask']))))
@classmethod
def denormalize_market_name(cls, market_name):
# xxx_yyy -> XXX-YYY
return '-'.join(market_name.split('_')).upper()