forked from whittlem/pycryptobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script-binance-webhooks.py
64 lines (54 loc) · 1.7 KB
/
script-binance-webhooks.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
import json, time
from threading import Thread
from websocket import create_connection, WebSocketConnectionClosedException
def main():
ws = None
thread = None
thread_running = False
thread_keepalive = None
def websocket_thread():
global ws
ws = create_connection("wss://stream.binance.com:9443/ws")
ws.send(
json.dumps(
{
"method": "SUBSCRIBE",
"params": ["btcusdt@miniTicker","btcusdt@kline_1m","btcusdt@kline_5m","btcusdt@kline_15m","btcusdt@kline_1h","btcusdt@kline_6h","btcusdt@kline_1d"],
"id": 1,
}
)
)
thread_keepalive.start()
while not thread_running:
try:
data = ws.recv()
if data != "":
msg = json.loads(data)
else:
msg = {}
except ValueError as e:
print(e)
print("{} - data: {}".format(e, data))
except Exception as e:
print(e)
print("{} - data: {}".format(e, data))
else:
if "result" not in msg:
print(msg)
try:
if ws:
ws.close()
except WebSocketConnectionClosedException:
pass
finally:
thread_keepalive.join()
def websocket_keepalive(interval=30):
global ws
while ws.connected:
ws.ping("keepalive")
time.sleep(interval)
thread = Thread(target=websocket_thread)
thread_keepalive = Thread(target=websocket_keepalive)
thread.start()
if __name__ == "__main__":
main()