How to stop fyers websocket gracefully? close_connection() method from data_ws.FyersDataSocket stop websocket but not running thread. I think it’s a bug.
How to stop fyers websocket gracefully? close_connection() method from data_ws.FyersDataSocket stop websocket but not running thread. I think it’s a bug.
Hi @s_m_a ,
Can you elaborate the issue
Have a look overt the following block of code first:
class FyersWebSocket:
def __init__(self, symbols, data_type="SymbolUpdate", on_message=None):
self.fyers = FyersToken()
self.on_message = on_message
self.fyers_ws = None
self.symbols = symbols
self.data_type = data_type
self.client_id = self.fyers.CLIENT_ID
self.token = self.fyers.access_token()
self.access_token = self.client_id + ':' + self.token
def start_websocket(self):
def onerror(message):
print("Error:", message)
def onclose(message):
print("Connection closed:", message)
def onopen():
self.fyers_ws.subscribe(symbols = self.symbols, data_type = self.data_type)
self.fyers_ws.keep_running()
self.fyers_ws = data_ws.FyersDataSocket(
access_token = self.access_token,
log_path = "",
litemode = False,
write_to_file = False,
reconnect = True,
on_connect = onopen,
on_close = onclose,
on_error = onerror,
on_message = self.on_message
)
threading.Thread(target = self.fyers_ws.connect).start()
def stop_websocket(self):
self.fyers_ws.close_connection()
Now have a look over the main function:
def main():
symbols = ["NSE:USDINR23AUGFUT", "NSE:GBPINR23AUGFUT", "NSE:EURINR23AUGFUT", "NSE:JPYINR23AUGFUT"]
socket = FyersWebSocket(symbols=symbols, on_message=custom_onmessage)
# signal.signal(signal.SIGINT, signal.SIG_DFL)
try:
socket.start_websocket()
except KeyboardInterrupt:
socket.stop_websocket()
if __name__ == "__main__":
main()
The start_websocket is working fine, but whenever a KeyboardInterrupt or SystemExit event occurs, stop_websocket never terminates the program gracefully. To handle this, I have to forcefully terminate the program using a signal handler.
It seems like the FyersDataSocket class we are using from the data_ws.py module of the fyers_apiv3 library doesn’t provide the join() method directly for the ws_thread. The join() method is generally used to wait for a thread to complete its execution, but it seems that this specific library doesn’t provide the capability to gracefully join the thread using the standard join() method.
Hi @s_m_a ,
We resolved this issue, can you please update SDK by the below command and please let me know if issue is resolved or not.
pip install fyers-apiv3==3.0.2
Thanks! Issue resolved.
The same WebSocket close issue exists in ‘fyers-apiv3.0.3’ as it did in ‘fyers-apiv3==3.0.1’.