1313
1414class Socket (object ):
1515 def __init__ (self , socketids , debug = False ):
16+ # setting the logger
1617 logger = logging .getLogger (__name__ )
1718 logger .setLevel (logging .DEBUG )
1819 f_handler = logging .FileHandler ('socket.log' )
@@ -24,6 +25,7 @@ def __init__(self, socketids, debug=False):
2425 logger .addHandler (f_handler )
2526 self .logger = logger
2627
28+ # initializing the cache
2729 self .url_worker = 'https://worker.cryptomkt.com'
2830 self .currencies_data = dict ()
2931 self .balance_data = dict ()
@@ -34,13 +36,25 @@ def __init__(self, socketids, debug=False):
3436 self .historical_book_data = dict ()
3537 self .candles_data = dict ()
3638 self .board_data = dict ()
39+ # to make subscriptions persistants in reconnections,
40+ # we store them here, and in a reconnect, we subscribe again.
41+ self .subsciptions = dict ()
3742
38- self . socketids = socketids
43+ # initializing the socket
3944 sio = socketio .Client ()
4045
46+ # defining basic events of the socket
4147 @sio .event
4248 def connect ():
4349 print ('connected to server' )
50+ # every time we connect or reconnect, we have
51+ # to autenticate us, else we can't recieve data anymore.
52+ self .logger .debug ('authenticating' )
53+ sio .emit ('user-auth' , socketids )
54+ subscription_list = [key for key in self .subsciptions .keys ()]
55+ if len (subscription_list ) > 0 :
56+ self .subscribe (* subscription_list )
57+
4458
4559 @sio .event
4660 def disconnect ():
@@ -49,10 +63,7 @@ def disconnect():
4963 self .logger .debug ('connecting to cryptomarket' )
5064 sio .connect (self .url_worker )
5165
52- self .logger .debug ('authenticating' )
53- sio .emit ('user-auth' , socketids )
54-
55-
66+ # defining all the cryptomarket events of the socket
5667 @sio .on ('currencies' )
5768 def currencies_handler (data ):
5869 self .logger .debug ('currencies recieved: {}' .format (data ))
@@ -309,11 +320,14 @@ def board_delta_handler(delta):
309320 def subscribe (self , * market_pairs ):
310321 self .logger .debug ('starting subscriptions: {}' .format (market_pairs ))
311322 for pair in market_pairs :
323+ self .subsciptions [pair ] = True
312324 self .sio .emit ('subscribe' , pair )
313325
314326 def unsubscribe (self , * market_pairs ):
315327 self .logger .debug ('ending subscriptions: {}' .format (market_pairs ))
316328 for pair in market_pairs :
329+ if pair in self .subsciptions :
330+ del self .subsciptions [pair ]
317331 self .sio .emit ('unsubscribe' , pair )
318332
319333 def on (self , event , handler ):
0 commit comments