/
unicorn_binance_websocket_api_manager.py
executable file
·1482 lines (1339 loc) · 71.8 KB
/
unicorn_binance_websocket_api_manager.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# File: unicorn_binance_websocket_api/unicorn_binance_websocket_api_manager.py
#
# Part of ‘UNICORN Binance WebSocket API’
# Project website: https://github.com/unicorn-data-analysis/unicorn-binance-websocket-api
# Documentation: https://www.unicorn-data.com/unicorn-binance-websocket-api.html
# PyPI: https://pypi.org/project/unicorn-binance-websocket-api/
#
# Author: UNICORN Data Analysis
# https://www.unicorn-data.com/
#
# Copyright (c) 2019, UNICORN Data Analysis
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from .unicorn_binance_websocket_api_socket import BinanceWebSocketApiSocket
from .unicorn_binance_websocket_api_restclient import BinanceWebSocketApiRestclient
from .unicorn_binance_websocket_api_restserver import BinanceWebSocketApiRestServer
from cheroot import wsgi
from datetime import datetime
from flask import Flask
from flask_restful import Api
import asyncio
import colorama
import copy
import logging
import requests
import sys
import threading
import time
import uuid
class BinanceWebSocketApiManager(threading.Thread):
"""
A python API to handle the Binance websocket API
Binance websocket API documentation:
https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md
https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md
:param process_stream_data: Provide a function/method to process the received webstream data. The function
will be called with one variable like `process_stream_data(data)` where
data` cointains the raw_stream_data. If not provided, the raw stream_data will get
stored in the stream_buffer.
:type process_stream_data: function
"""
def __init__(self, process_stream_data=False, exchange="binance.com"):
threading.Thread.__init__(self)
self.version = "1.3.10.dev"
if process_stream_data is False:
# no special method to process stream data provided, so we use write_to_stream_buffer:
self.process_stream_data = self.add_to_stream_buffer
else:
# use the provided method to process stream data:
self.process_stream_data = process_stream_data
self.exchange = exchange
if self.exchange == "binance.com":
self.websocket_base_uri = "wss://stream.binance.com:9443/"
elif self.exchange == "binance.je":
self.websocket_base_uri = "wss://stream.binance.je:9443/"
self.stop_manager_request = None
self._frequent_checks_restart_request = None
self._keepalive_streams_restart_request = None
self.api_key = False
self.api_secret = False
self.frequent_checks_list = {}
self.keep_max_received_last_second_entries = 5
self.keepalive_streams_list = {}
self.most_receives_per_second = 0
self.monitoring_api_server = False
self.monitoring_total_received_bytes = 0
self.monitoring_total_receives = 0
self.reconnects = 0
self.restart_requests = {}
self.start_time = time.time()
self.stream_buffer = []
self.last_entry_added_to_stream_buffer = 0
self.last_monitoring_check = time.time()
self.last_update_check_github = {'timestamp': time.time(),
'status': None}
self.stream_list = {}
self.total_received_bytes = 0
self.total_receives = 0
self.websocket_list = {}
self.binance_api_status = {'weight': None,
'timestamp': 0,
'status_code': None}
self.start()
colorama.init()
def _add_socket_to_socket_list(self, stream_id, channels, markets):
# create a list entry for new sockets
self.stream_list[stream_id] = {'exchange': "binance",
'stream_id': copy.deepcopy(stream_id),
'channels': copy.deepcopy(channels),
'markets': copy.deepcopy(markets),
'api_key': copy.deepcopy(self.api_key),
'api_secret': copy.deepcopy(self.api_secret),
'status': 'starting',
'start_time': time.time(),
'processed_receives_total': 0,
'receives_statistic_last_second': {'most_receives_per_second': 0, 'entries': {}},
'seconds_to_last_heartbeat': None,
'last_heartbeat': None,
'stop_request': None,
'seconds_since_has_stopped': None,
'has_stopped': False,
'reconnects': 0,
'logged_reconnects': [],
'last_static_ping_listen_key': 0,
'listen_key': False,
'listen_key_cache_time': 30 * 60,
'processed_receives_statistic': {}}
logging.debug("BinanceWebSocketApiManager->_add_socket_to_socket_list(" +
str(stream_id) + ", " + str(channels) + ", " + str(markets) + ")")
def _create_stream_thread(self, loop, stream_id, channels, markets, restart=False):
# co function of self.create_stream to create a thread for the socket and to manage the coroutine
if restart is False:
self._add_socket_to_socket_list(stream_id, channels, markets)
asyncio.set_event_loop(loop)
binance_websocket_api_socket = BinanceWebSocketApiSocket(self, loop, stream_id, channels, markets)
try:
loop.run_until_complete(binance_websocket_api_socket.start_socket())
finally:
loop.close()
def _frequent_checks(self):
frequent_checks_id = time.time()
self.frequent_checks_list[frequent_checks_id] = {'last_heartbeat': 0,
'stop_request': None,
'has_stopped': False}
logging.info("BinanceWebSocketApiManager->_frequent_checks() new instance created with frequent_checks_id=" +
str(frequent_checks_id))
for frequent_checks_instance in self.frequent_checks_list:
if frequent_checks_instance != frequent_checks_id:
try:
if (self.keepalive_streams_list[frequent_checks_instance]['last_heartbeat'] + 3) > time.time():
logging.info("BinanceWebSocketApiManager->_frequent_checks() found an other living instance, "
"so i stop" + str(frequent_checks_id))
sys.exit(1)
except KeyError:
logging.debug("BinanceWebSocketApiManager->_frequent_checks() - Info: KeyError "
"" + str(frequent_checks_id))
# threaded loop for min 1 check per second
while self.stop_manager_request is None and self.frequent_checks_list[frequent_checks_id]['stop_request'] \
is None:
self.frequent_checks_list[frequent_checks_id]['last_heartbeat'] = time.time()
time.sleep(0.8)
current_timestamp = int(time.time())
last_timestamp = current_timestamp - 1
next_to_last_timestamp = current_timestamp - 2
total_most_stream_receives_last_timestamp = 0
total_most_stream_receives_next_to_last_timestamp = 0
active_stream_list = self.get_active_stream_list()
# count most_receives_per_second total last second
if active_stream_list:
for stream_id in active_stream_list:
# set the streams `most_receives_per_second` value
try:
if self.stream_list[stream_id]['receives_statistic_last_second']['entries'][last_timestamp] > \
self.stream_list[stream_id]['receives_statistic_last_second'][
'most_receives_per_second']:
self.stream_list[stream_id]['receives_statistic_last_second']['most_receives_per_second'] = \
self.stream_list[stream_id]['receives_statistic_last_second']['entries'][last_timestamp]
except KeyError:
pass
try:
total_most_stream_receives_last_timestamp += self.stream_list[stream_id]['receives_statistic_last_second']['entries'][last_timestamp]
except KeyError:
pass
try:
total_most_stream_receives_next_to_last_timestamp += self.stream_list[stream_id]['receives_statistic_last_second']['entries'][next_to_last_timestamp]
except KeyError:
pass
# delete list entries older than `keep_max_received_last_second_entries`
delete_index = []
if len(self.stream_list[stream_id]['receives_statistic_last_second']['entries']) > self.keep_max_received_last_second_entries:
for timestamp_key in self.stream_list[stream_id]['receives_statistic_last_second']['entries']:
try:
if timestamp_key < current_timestamp - self.keep_max_received_last_second_entries:
delete_index.append(timestamp_key)
except ValueError as error_msg:
logging.error(
"BinanceWebSocketManager->_frequent_checks() timestamp_key=" + str(timestamp_key) +
" current_timestamp=" + str(current_timestamp) + " keep_max_received_last_second_"
"entries=" + str(self.keep_max_received_last_second_entries) + " error_msg=" +
str(error_msg))
for timestamp_key in delete_index:
self.stream_list[stream_id]['receives_statistic_last_second']['entries'].pop(timestamp_key, None)
# set most_receives_per_second
try:
if int(self.most_receives_per_second) < int(total_most_stream_receives_last_timestamp):
self.most_receives_per_second = int(total_most_stream_receives_last_timestamp)
except ValueError as error_msg:
logging.error("BinanceWebSocketManager->_frequent_checks() self.most_receives_per_second"
"=" + str(self.most_receives_per_second) + " total_most_stream_receives_last_timestamp"
"=" + str(total_most_stream_receives_last_timestamp) + " total_most_stream_receives_next_"
"to_last_timestamp=" + str(total_most_stream_receives_next_to_last_timestamp) + " error_"
"msg=" + str(error_msg))
try:
if int(self.most_receives_per_second) < int(total_most_stream_receives_next_to_last_timestamp):
self.most_receives_per_second = int(total_most_stream_receives_next_to_last_timestamp)
except ValueError as error_msg:
logging.error("BinanceWebSocketManager->_frequent_checks() self.most_receives_per_second=" + str(
self.most_receives_per_second) + " total_most_stream_receives_last_timestamp=" +
str(total_most_stream_receives_last_timestamp) + " total_most_stream_receives_next_to_"
"last_timestamp=" +
str(total_most_stream_receives_next_to_last_timestamp) + " error_msg=" + str(error_msg))
# control _keepalive_streams
found_alive_keepalive_streams = False
for keepalive_streams_id in self.keepalive_streams_list:
try:
if (current_timestamp - self.keepalive_streams_list[keepalive_streams_id]['last_heartbeat']) < 3:
found_alive_keepalive_streams = True
except TypeError:
pass
# start a new one, if there isnt one
if found_alive_keepalive_streams is False:
self._keepalive_streams_restart_request = True
# send keepalive for `!userData` streams every 30 minutes
if active_stream_list:
for stream_id in active_stream_list:
if isinstance(active_stream_list[stream_id]['markets'], str):
active_stream_list[stream_id]['markets'] = [active_stream_list[stream_id]['markets'],]
if isinstance(active_stream_list[stream_id]['markets'], list):
if "!userData" in active_stream_list[stream_id]['markets']:
if (active_stream_list[stream_id]['start_time'] + active_stream_list[stream_id]['listen_key_cache_time']) \
< time.time() and (active_stream_list[stream_id]['last_static_ping_listen_key'] +
active_stream_list[stream_id]['listen_key_cache_time']) < time.time():
# keep-alive the listenKey
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(self.exchange,
self.stream_list[stream_id]['api_key'],
self.stream_list[stream_id]['api_secret'],
self.get_version(),
self.binance_api_status)
binance_websocket_api_restclient.keepalive_listen_key(self.stream_list[stream_id]['listen_key'])
del binance_websocket_api_restclient
# set last_static_ping_listen_key
self.stream_list[stream_id]['last_static_ping_listen_key'] = time.time()
self.set_heartbeat(stream_id)
logging.info("sent listen_key keepalive ping for stream_id=" + str(stream_id))
sys.exit(0)
def _fill_up_space(self, demand_of_chars, string):
blanks_pre = ""
blanks_post = ""
demand_of_blanks = demand_of_chars - len(str(string)) - 1
while len(blanks_pre) < demand_of_blanks:
blanks_pre += " "
blanks_post = " "
return blanks_pre + str(string) + blanks_post
def _keepalive_streams(self):
keepalive_streams_id = time.time()
self.keepalive_streams_list[keepalive_streams_id] = {'last_heartbeat': 0,
'stop_request': None,
'has_stopped': False}
logging.info(
"BinanceWebSocketApiManager->_keepalive_streams() new instance created with keepalive_streams_id=" +
str(keepalive_streams_id))
for keepalive_streams_instance in self.keepalive_streams_list:
if keepalive_streams_instance != keepalive_streams_id:
if (self.keepalive_streams_list[keepalive_streams_instance]['last_heartbeat'] + 3) > time.time():
logging.info(
"BinanceWebSocketApiManager->_keepalive_streams() found an other living instance, so i stopp" +
str(keepalive_streams_id))
sys.exit(1)
# threaded loop to restart crashed streams:
while self.stop_manager_request is None and \
self.keepalive_streams_list[keepalive_streams_id]['stop_request'] is None:
self.keepalive_streams_list[keepalive_streams_id]['last_heartbeat'] = time.time()
time.sleep(1)
# restart streams with a restart_request (status == new)
temp_restart_requests = copy.deepcopy(self.restart_requests)
for stream_id in temp_restart_requests:
# find restarts that didnt work
try:
if self.restart_requests[stream_id]['status'] == "restarted" and \
self.restart_requests[stream_id]['last_restart_time']+5 < time.time():
self.restart_requests[stream_id]['status'] = "new"
# restart streams with requests
if self.restart_requests[stream_id]['status'] == "new":
self.restart_stream(stream_id)
self.restart_requests[stream_id]['status'] = "restarted"
self.restart_requests[stream_id]['last_restart_time'] = time.time()
self.stream_list[stream_id]['status'] = "restarting"
except KeyError:
pass
# control frequent_checks_threads for two cases:
# 1) there should only be one! stop others if necessary:
found_alive_frequent_checks = False
current_timestamp = time.time()
for frequent_checks_id in self.frequent_checks_list:
try:
if (current_timestamp - self.frequent_checks_list[frequent_checks_id]['last_heartbeat']) < 2:
found_alive_frequent_checks = True
except TypeError:
pass
# 2) start a new one, if there isnt one
if found_alive_frequent_checks is False:
self._frequent_checks_restart_request = True
sys.exit(0)
def _start_monitoring_api(self, host, port, warn_on_update):
logging.info("starting monitoring API server ...")
app = Flask(__name__)
api = Api(app)
api.add_resource(BinanceWebSocketApiRestServer, "/status/<string:statusformat>",
resource_class_kwargs={'handler_binance_websocket_api_manager': self,
'warn_on_update': warn_on_update})
try:
dispatcher = wsgi.PathInfoDispatcher({'/': app})
self.monitoring_api_server = wsgi.WSGIServer((host, port), dispatcher)
self.monitoring_api_server.start()
except RuntimeError as error_msg:
logging.error("monitoring API server is going down! - info: " + str(error_msg))
def add_to_stream_buffer(self, stream_data):
"""
Kick back data to the stream_buffer
If it is not possible to process received stream data (for example, the database is restarting, so its not
possible to save the data), you can return the data back into the stream_buffer. After a few seconds you stopped
writing data back to the stream_buffer, the BinanceWebSocketApiManager starts flushing back the data to normal
processing.
:param stream_data: the data you want to write back to the buffer
:type stream_data: raw stream_data or unicorn_fied stream data
"""
self.stream_buffer.append(stream_data)
self.last_entry_added_to_stream_buffer = time.time()
def add_total_received_bytes(self, size):
# add received bytes to the total received bytes statistic
self.total_received_bytes += int(size)
def create_stream(self, channels, markets):
"""
Create a websocket stream
:param channels: provide the channels you wish to stream
:type channels: str, tuple, list, set
:param markets: provide the markets you wish to stream
:type markets: str, tuple, list, set
:return: stream_id or False
"""
# create a stream
stream_id = uuid.uuid4()
if not self.is_websocket_uri_length_valid(channels, markets):
logging.error("BinanceWebSocketApiManager->create_stream(" + str(channels) + ", " + str(markets) + ") "
"Info: the allowed max length of an URI to binance websocket server is 8004 characters")
return False
else:
logging.info("BinanceWebSocketApiManager->create_stream(" + str(channels) + ", " + str(markets) + ")")
loop = asyncio.new_event_loop()
thread = threading.Thread(target=self._create_stream_thread, args=(loop, stream_id, channels, markets))
thread.start()
return stream_id
def create_websocket_uri(self, channels, markets, stream_id=False, api_key=False, api_secret=False):
"""
Create a websocket URI
:param channels: provide the channels to create the URI
:type channels: str, tuple, list, set
:param markets: provide the markets to create the URI
:type markets: str, tuple, list, set
:param stream_id: provide a stream_id (only needed for userData Streams (acquiring a listenKey)
:type stream_id: uuid
:param api_key: provide a valid Binance API key
:type api_key: str
:param api_secret: provide a valid Binance API secret
:type api_secret: str
:return: str or False
"""
if type(channels) is str:
channels = [channels]
if type(markets) is str:
markets = [markets]
if len(channels) == 1:
if "arr" in channels:
query = "ws/"
else:
query = "stream?streams="
else:
query = "stream?streams="
for channel in channels:
if channel == "!ticker":
logging.error("Can not create 'arr@!ticker' in a multi channel socket! "
"Unfortunatly Binance only stream it in a single stream socket! "
"Use binance_websocket_api_manager.create_stream([\"arr\"], [\"!ticker\"]) to initiate "
"an extra connection.")
continue
if channel == "!miniTicker":
logging.error("Can not create 'arr@!miniTicker' in a multi channel socket! "
"Unfortunatly Binance only stream it in a single stream socket! ./"
"Use binance_websocket_api_manager.create_stream([\"arr\"], [\"!miniTicker\"]) to "
"initiate an extra connection.")
continue
if channel == "!userData":
logging.error("Can not create 'outboundAccountInfo' in a multi channel socket! "
"Unfortunatly Binance only stream it in a single stream socket! ./"
"Use binance_websocket_api_manager.create_stream([\"arr\"], [\"!userData\"]) to "
"initiate an extra connection.")
continue
for market in markets:
if market == "!userData":
if stream_id is not False:
# only execute this code block with a provided stream_id
response = self.get_listen_key_from_restclient(stream_id, api_key, api_secret)
try:
if response['code'] == -2014 or response['code'] == -2015:
return response
else:
logging.critical("Found new error code from restclient: " + str(response))
return response
except KeyError:
pass
except TypeError:
pass
if response:
try:
uri = self.websocket_base_uri + "ws/" + str(response['listenKey'])
return uri
except KeyError:
return False
except TypeError:
return False
else:
return False
else:
return False
elif market == "!miniTicker":
query += market + "@" + channel + "/"
else:
query += market.lower() + "@" + channel + "/"
uri = self.websocket_base_uri + str(query)
return uri
def delete_listen_key_by_stream_id(self, stream_id):
"""
Delete a binance listen_key from a specific !userData stream
:param stream_id: id of a !userData stream
:type stream_id: uuid
"""
if self.stream_list[stream_id]['listen_key'] is not False:
logging.info("BinanceWebSocketApiManager->stop_manager_with_all_streams(" + str(
stream_id) + ")->delete_listen_key")
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(self.exchange,
self.stream_list[stream_id]['api_key'],
self.stream_list[stream_id]['api_secret'],
self.get_version(),
self.used_weight)
binance_websocket_api_restclient.delete_listen_key(self.stream_list[stream_id]['listen_key'])
del binance_websocket_api_restclient
def delete_stream_from_stream_list(self, stream_id):
"""
Delete a stream from the stream_list
Even if a stream crashes or get stopped, its data remains in the BinanceWebSocketApiManager till you stop the
BinanceWebSocketApiManager itself. If you want to tidy up the stream_list you can use this method.
:param stream_id: id of a stream
:type stream_id: uuid
:return: bool
"""
logging.debug("deleting " + str(stream_id) + " from stream_list")
return self.stream_list.pop(stream_id, False)
def get_active_stream_list(self):
"""
Get a list of all active streams
:return: set
"""
# get the stream_list without stopped and crashed streams
stream_list_with_active_streams = {}
for stream_id in self.stream_list:
if self.stream_list[stream_id]['status'] == "running":
stream_list_with_active_streams[stream_id] = self.stream_list[stream_id]
try:
if len(stream_list_with_active_streams[stream_id]) > 0:
return stream_list_with_active_streams
except KeyError:
return False
except UnboundLocalError:
return False
def get_all_receives_last_second(self):
"""
Get the number of all receives of the last second
:return: int
"""
# how much receives did we have last second?
all_receives_last_second = 0
last_second_timestamp = int(time.time()) - 1
for stream_id in self.stream_list:
try:
all_receives_last_second += self.stream_list[stream_id]['receives_statistic_last_second']['entries'][
last_second_timestamp]
except KeyError:
pass
return all_receives_last_second
def get_binance_api_status(self):
"""
Get used_weight, last status_code and the timestamp of the last status update
:return: dict
"""
return self.binance_api_status
def get_human_bytesize(self, bytes):
if bytes > 1024 * 1024 * 1024:
bytes = str(round(bytes / (1024 * 1024 * 1024), 2)) + " gB"
elif bytes > 1024 * 1024:
bytes = str(round(bytes / (1024 * 1024), 1)) + " mB"
elif bytes > 1024:
bytes = str(int(bytes / 1024)) + " kB"
return bytes
def get_human_uptime(self, uptime):
# formats a timestamp to a human readable output
if uptime > (60 * 60 * 24):
uptime_days = int(uptime / (60 * 60 * 24))
uptime_hours = int(((uptime - (uptime_days * (60 * 60 * 24))) / (60 * 60)))
uptime_minutes = int((uptime - ((uptime_days * (60 * 60 * 24)) + (uptime_hours * 60 * 60))) / 60)
uptime_seconds = int(
uptime - ((uptime_days * (60 * 60 * 24)) + ((uptime_hours * (60 * 60)) + (uptime_minutes * 60))))
uptime = str(uptime_days) + "d:" + str(uptime_hours) + "h:" + str(int(uptime_minutes)) + "m:" + str(
int(uptime_seconds)) + "s"
elif uptime > (60 * 60):
uptime_hours = int(uptime / (60 * 60))
uptime_minutes = int((uptime - (uptime_hours * (60 * 60))) / 60)
uptime_seconds = int(uptime - ((uptime_hours * (60 * 60)) + (uptime_minutes * 60)))
uptime = str(uptime_hours) + "h:" + str(int(uptime_minutes)) + "m:" + str(int(uptime_seconds)) + "s"
elif uptime > 60:
uptime_minutes = int(uptime / 60)
uptime_seconds = uptime - uptime_minutes * 60
uptime = str(uptime_minutes) + "m:" + str(int(uptime_seconds)) + "s"
else:
uptime = str(int(uptime)) + " seconds"
return uptime
def get_latest_release_info(self):
"""
Get infos about the latest available release
:return: dict or False
"""
try:
respond = requests.get('https://api.github.com/repos/unicorn-data-analysis/unicorn-binance-websocket-api/'
'releases/latest')
latest_release_info = respond.json()
return latest_release_info
except Exception:
return False
def get_latest_version(self):
"""
Get the version of the latest available release (cache time 1 hour)
:return: str or False
"""
# Do a fresh request if status is None or last timestamp is older 1 hour
if self.last_update_check_github['status'] is None or \
(self.last_update_check_github['timestamp']+(60*60) < time.time()):
self.last_update_check_github['status'] = self.get_latest_release_info()
if self.last_update_check_github['status']:
try:
return self.last_update_check_github['status']["tag_name"]
except KeyError:
return "unknown"
else:
return "unknown"
def get_listen_key_from_restclient(self, stream_id, api_key, api_secret):
"""
Get a new or cached (<30m) listen_key
:param stream_id: provide a stream_id
:type stream_id: uuid
:param api_key: provide a valid Binance API key
:type api_key: str
:param api_secret: provide a valid Binance API secret
:type api_secret: str
:return: str or False
"""
if (self.stream_list[stream_id]['start_time'] + self.stream_list[stream_id]['listen_key_cache_time']) > \
time.time() or (self.stream_list[stream_id]['last_static_ping_listen_key'] +
self.stream_list[stream_id]['listen_key_cache_time']) > time.time():
# listen_key is not older than 30 min
if self.stream_list[stream_id]['listen_key'] is not False:
response = {'listenKey': self.stream_list[stream_id]['listen_key']}
return response
# no cached listen_key or listen_key is older than 30 min
# acquire a new listen_key:
binance_websocket_api_restclient = BinanceWebSocketApiRestclient(self.exchange, api_key, api_secret,
self.get_version(), self.binance_api_status)
response = binance_websocket_api_restclient.get_listen_key()
del binance_websocket_api_restclient
if response:
# save and return the valid listen_key
try:
self.stream_list[stream_id]['listen_key'] = str(response['listenKey'])
return response
except KeyError:
# no valid listen_key, but a response from endpoint
return response
except TypeError:
return response
else:
# no valid listen_key
return False
def get_most_receives_per_second(self):
"""
Get the highest total receives per second value
:return: int
"""
return self.most_receives_per_second
def get_number_of_streams_in_stream_list(self):
"""
Get the number of streams that are stored in the stream_list
:return: int
"""
return len(self.stream_list)
def get_keep_max_received_last_second_entries(self):
"""
Get the number of received_last_second entries are stored till they get deleted
:return: int
"""
return self.keep_max_received_last_second_entries
def get_monitoring_status_icinga(self, warn_on_update=True):
"""
Get status and perfdata to monitor and collect metrics with ICINGA/Nagios
:param warn_on_update: set to `False` to disable the update warning
:type warn_on_update: bool
status: OK, WARNING, CRITICAL
- WARNING: on restarts, available updates
- CRITICAL: crashed streams
perfdata:
- average receives per second since last status check
- average speed per second since last status check
- total received bytes since start
- total received length since start
- stream_buffer size
- stream_buffer length
- reconnects
- uptime
:return: dict (text, time, return_code)
"""
result = self.get_monitoring_status_plain(warn_on_update=warn_on_update)
if len(result['update_msg']) > 0:
result['update_msg'] = " - " + result['update_msg']
check_message = "BINANCE WEBSOCKETS - " + result['status_text'] + ": O:" + str(result['active_streams']) + \
"/R:" + str(result['restarting_streams']) + "/C:" + str(result['crashed_streams']) + "/S:" + \
str(result['stopped_streams']) + result['update_msg'] + " | " + "average_receives_per_second=" + \
str(result['average_receives_per_second']) + ";;;0 transfer_rate_per_second=" + \
str(result['average_speed_per_second']) + "KB;;;0" + " total_received_length=" + \
str(result['total_received_length']) + "c;;;0 total_received_size=" + \
str(result['total_received_mb']) + "MB;;;0 stream_buffer_size=" + \
str(result['stream_buffer_mb']) + "MB;;;0 stream_buffer_length=" + \
str(result['stream_buffer_items']) + ";;;0 reconnects=" + str(result['reconnects']) + "c;;;0 " \
"uptime_days=" + str(result['uptime']) + "c;;;0"
status = {'text': check_message,
'time': int(result['timestamp']),
'return_code': result['return_code']}
return status
def get_monitoring_status_plain(self, warn_on_update=True):
"""
Get plain monitoring status data:
active_streams, crashed_streams, restarting_streams, stopped_streams, return_code, status_text,
timestamp, update_msg, average_receives_per_second, average_speed_per_second, total_received_mb,
stream_buffer_items, stream_buffer_mb, reconnects, uptime
:param warn_on_update: set to `False` to disable the update warning
:type warn_on_update: bool
:return: dict
"""
result = {}
result['active_streams'] = 0
result['crashed_streams'] = 0
result['restarting_streams'] = 0
result['return_code'] = 0
result['status_text'] = "OK"
result['stopped_streams'] = 0
result['timestamp'] = time.time()
result['update_msg'] = ""
time_period = result['timestamp'] - self.last_monitoring_check
for stream_id in self.stream_list:
if self.stream_list[stream_id]['status'] == "running":
result['active_streams'] += 1
elif self.stream_list[stream_id]['status'] == "stopped":
result['stopped_streams'] += 1
elif self.stream_list[stream_id]['status'] == "restarting":
result['restarting_streams'] += 1
elif "crashed" in self.stream_list[stream_id]['status']:
result['crashed_streams'] += 1
if self.is_update_availabe():
result['update_msg'] = "Update " + str(self.get_latest_version()) + " available!"
if warn_on_update is True:
result['status_text'] = "WARNING"
result['return_code'] = 1
if result['crashed_streams'] > 0:
result['status_text'] = "CRITICAL"
result['return_code'] = 2
elif result['restarting_streams'] > 0:
result['status_text'] = "WARNING"
result['return_code'] = 1
result['average_receives_per_second'] = ((self.total_receives - self.monitoring_total_receives) /
time_period).__round__(2)
result['average_speed_per_second'] = (((self.total_received_bytes - self.monitoring_total_received_bytes) /
time_period) / 1024).__round__(2)
result['total_received_mb'] = (self.get_total_received_bytes() / (1024 * 1024)).__round__(2)
result['total_received_length'] = self.total_receives
result['stream_buffer_items'] = str(self.get_stream_buffer_length())
result['stream_buffer_mb'] = (self.get_stream_buffer_byte_size() / (1024 * 1024)).__round__(4)
result['reconnects'] = self.get_reconnects()
self.monitoring_total_receives = self.get_total_receives()
self.monitoring_total_received_bytes = self.get_total_received_bytes()
self.last_monitoring_check = result['timestamp']
result['uptime'] = ((result['timestamp'] - self.start_time) / (60*60*24)).__round__(3)
return result
def get_reconnects(self):
"""
Get the number of total reconnects
:return: int
"""
return self.reconnects
def get_start_time(self):
"""
Get the start_time of the BinanceWebSocketApiManager instance
:return: timestamp
"""
return self.start_time
def get_stream_buffer_byte_size(self):
"""
Get the current byte size of the stream_buffer
:return: int
"""
return sys.getsizeof(self.stream_buffer)
def get_stream_buffer_length(self):
"""
Get the current number of items in the stream_buffer
:return: int
"""
return len(self.stream_buffer)
def get_stream_info(self, stream_id):
"""
Get infos about a specific stream
:param stream_id: id of a stream
:type stream_id: uuid
:return: set
"""
current_timestamp = time.time()
try:
temp_stream_list = copy.deepcopy(self.stream_list)
except RuntimeError:
return self.get_stream_info(stream_id)
if temp_stream_list[stream_id]['last_heartbeat'] is not None:
temp_stream_list[stream_id]['seconds_to_last_heartbeat'] = \
current_timestamp - self.stream_list[stream_id]['last_heartbeat']
if temp_stream_list[stream_id]['has_stopped'] is not False:
temp_stream_list[stream_id]['seconds_since_has_stopped'] = \
int(current_timestamp) - int(self.stream_list[stream_id]['has_stopped'])
try:
self.stream_list[stream_id]['processed_receives_statistic'] = self.get_stream_statistic(stream_id)
except ZeroDivisionError:
pass
return temp_stream_list[stream_id]
def get_stream_list(self):
"""
Get a list of all streams
:return: set
"""
# get the stream list
temp_stream_list = {}
for stream_id in self.stream_list:
temp_stream_list[stream_id] = self.get_stream_info(stream_id)
return temp_stream_list
def get_stream_receives_last_second(self, stream_id):
"""
Get the number of receives of specific stream from the last seconds
:param stream_id: id of a stream
:type stream_id: uuid
:return: int
"""
last_second_timestamp = int(time.time()) - 1
try:
return self.stream_list[stream_id]['receives_statistic_last_second']['entries'][last_second_timestamp]
except KeyError:
return 0
def get_stream_statistic(self, stream_id):
"""
Get the statistic of a specific stream
:param stream_id: id of a stream
:type stream_id: uuid
:return: set
"""
stream_statistic = {'stream_receives_per_second': 0,
'stream_receives_per_minute': 0,
'stream_receives_per_hour': 0,
'stream_receives_per_day': 0,
'stream_receives_per_month': 0,
'stream_receives_per_year': 0}
if self.stream_list[stream_id]['status'] == "running":
stream_statistic['uptime'] = time.time() - self.stream_list[stream_id]['start_time']
elif self.stream_list[stream_id]['status'] == "stopped":
stream_statistic['uptime'] = self.stream_list[stream_id]['has_stopped'] - self.stream_list[stream_id]['start_time']
elif "crashed" in self.stream_list[stream_id]['status']:
stream_statistic['uptime'] = self.stream_list[stream_id]['has_stopped'] - self.stream_list[stream_id]['start_time']
elif self.stream_list[stream_id]['status'] == "restarting":
stream_statistic['uptime'] = time.time() - self.stream_list[stream_id]['start_time']
else:
stream_statistic['uptime'] = time.time() - self.stream_list[stream_id]['start_time']
try:
stream_receives_per_second = self.stream_list[stream_id]['processed_receives_total'] / stream_statistic['uptime']
except ZeroDivisionError:
stream_receives_per_second = 0
stream_statistic['stream_receives_per_second'] = stream_receives_per_second
if stream_statistic['uptime'] > 60:
stream_statistic['stream_receives_per_minute'] = stream_receives_per_second * 60
if stream_statistic['uptime'] > 60 * 60:
stream_statistic['stream_receives_per_hour'] = stream_receives_per_second * 60 * 60
if stream_statistic['uptime'] > 60 * 60 * 24:
stream_statistic['stream_receives_per_day'] = stream_receives_per_second * 60 * 60 * 24
if stream_statistic['uptime'] > 60 * 60 * 24 * 30:
stream_statistic['stream_receives_per_month'] = stream_receives_per_second * 60 * 60 * 24 * 30
if stream_statistic['uptime'] > 60 * 60 * 24 * 30 * 12:
stream_statistic['stream_receives_per_year'] = stream_receives_per_second * 60 * 60 * 24 * 30 * 12
return stream_statistic
def get_total_received_bytes(self):
"""
Get number of total received bytes
:return: int
"""
# how much bytes did we receive till now?
return self.total_received_bytes
def get_total_receives(self):
"""
Get the number of total receives
:return: int
"""
return self.total_receives
def get_version(self):
"""
Get the package/module version
:return: str
"""
return self.version
def get_websocket_uri_length(self, channels, markets):
"""
Get the length of the generated websocket URI
:param channels: provide the channels to create the URI
:type channels: str, tuple, list, set
:param markets: provide the markets to create the URI
:type markets: str, tuple, list, set
:return: int
"""
uri = self.create_websocket_uri(channels, markets)
return len(uri)
def increase_processed_receives_statistic(self, stream_id):
# for every receive we call this method to increase the receives statistics
current_timestamp = int(time.time())
# for every received row of data, the stream counts + 1 in to the statistic (average values)
self.stream_list[stream_id]['processed_receives_total'] += 1
# increase for every received row the global received stats for the current second
try:
self.stream_list[stream_id]['receives_statistic_last_second']['entries'][current_timestamp] += 1
except KeyError:
self.stream_list[stream_id]['receives_statistic_last_second']['entries'][current_timestamp] = 1
# increase `total_receives`
self.total_receives += 1
def increase_reconnect_counter(self, stream_id):
# at every reconnect we call this method to increase the reconnect statistic
self.stream_list[stream_id]['logged_reconnects'].append(time.time())
self.stream_list[stream_id]['reconnects'] += 1
self.reconnects += 1
def is_manager_stopping(self):
"""
Returns `True` if the manager has a stop request, 'False' if not.
:return: bool
"""
if self.stop_manager_request is None:
return False
else:
return True
def is_stop_request(self, stream_id):
"""
Has a specific stream a stop_request?
:param stream_id: id of a stream
:type stream_id: uuid
:return: bool
"""
logging.debug("BinanceWebSocketApiManager->is_stop_request(" + str(stream_id) + ")")
if self.stream_list[stream_id]['stop_request'] is True:
return True
elif self.is_manager_stopping():
return True
else:
return False
def is_update_availabe(self):
"""
Is a new release of this package available?
:return: bool
"""
installed_version = self.get_version()
if ".dev" in installed_version:
installed_version = installed_version[:-4]
if self.get_latest_version() == installed_version:
return False
elif self.get_latest_version() == "unknown":
return False
else:
return True