forked from danpaquin/coinbasepro-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebsocketClient.py
More file actions
74 lines (62 loc) · 1.89 KB
/
WebsocketClient.py
File metadata and controls
74 lines (62 loc) · 1.89 KB
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
#
# GDAX/WebsocketClient.py
# Daniel Paquin
#
# Template object to receive messages from the GDAX Websocket Feed
import json, time
from threading import Thread
from websocket import create_connection
class WebsocketClient(object):
def __init__(self, ws_url="wss://ws-feed-public.sandbox.gdax.com", product_id="BTC-USD"):
if ws_url[-1] == "/":
self.url = ws_url[:-1]
else:
self.url = ws_url
self.product_id = product_id
def go():
self.connect()
self.listen()
self.thread = Thread(target=go)
self.thread.daemon = True
self.thread.start()
def connect(self):
self.open()
self.stop = False
self.ws = create_connection(self.url)
if type(self.product_id) is list:
#product_ids - plural for multiple products
subParams = json.dumps({"type": "subscribe", "product_ids": self.product_id})
else:
subParams = json.dumps({"type": "subscribe", "product_id": self.product_id})
self.ws.send(subParams)
def open(self):
print("-- Subscribed! --")
def listen(self):
while not self.stop:
try:
msg = json.loads(self.ws.recv())
except Exception as e:
self.on_error(e)
else:
self.message(msg)
def on_error(self, e):
self.close()
def message(self, msg):
print(msg)
def close(self):
self.stop = True
if self.ws and self.ws.connected:
self.ws.close()
self.ws = None
self.closed()
def closed(self):
print("Socket Closed")
if __name__ == "__main__":
newWS = WebsocketClient() # Runs in a separate thread
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
newWS.stop = True
newWS.thread.join()
newWS.close()