-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathderibit_V2_API_Websocket.py
More file actions
67 lines (56 loc) · 1.91 KB
/
deribit_V2_API_Websocket.py
File metadata and controls
67 lines (56 loc) · 1.91 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
from websocket import create_connection, WebSocketConnectionClosedException
import json
import time
class Deribitv2API():
def __init__(self):
self.msg = \
{"jsonrpc": "2.0",
"method": "public/subscribe",
"id": 42,
"params": {
"channels": ["quote.BTC-PERPETUAL"]}
}
self.listOfNotifications = []
self.ws = None
self.url = None
def setting_url(self, url):
self.url = url
def startSocket(self):
# try again after a failure
while True:
try:
self.connect()
self.listen()
except Exception as e:
self.endSocketDueToError(e)
def connect(self):
self.ws = create_connection(self.url)
self.ws.send(json.dumps(self.msg))
def listen(self):
# trigger whilst true keep listening
while self.ws.connected:
try:
# puts all the incoming data into a list of a map
mapData = json.loads(self.ws.recv())
self.listOfNotifications.append(mapData)
except Exception as e:
self.endSocketDueToError(e)
return
def disconnect(self):
try:
if self.ws.connected:
self.ws.close()
except WebSocketConnectionClosedException as e:
print(str(e) + " error on closing")
print("Socket Closed")
# send the data to the logicalEngine
def endSocketDueToError(self, e):
print(e, " closing websocket")
self.disconnect()
def getListOfData(self):
if len(self.listOfNotifications) > 1:
self.listOfNotifications = self.listOfNotifications[-2:]
# returns the last value in the list
return self.listOfNotifications[-1]
# since we have no data don't return anything
return None