Hi Ameet,
Seems like Fyers has got it wrong here, when they say.
-
run_background=True mode, they will only print the messages
-
run_background=False, you will not get back control of the main thread as WS runs in main thread.
probably they do not know how production trading works. They also have made distinction between runbackground and background_flag class attributes, which is bit difficult to understand why.
I think best option for now is
- after subscribe make fyersSocket.background_flag = False
symbol = ['MCX:CRUDEOIL22FEBFUT', 'MCX:GOLD22APRFUT']
fyersSocket.subscribe(symbol=symbol, data_type=data_type)
fyersSocket.background_flag = False
Caveat : But this might not not work good with the multiple calls to subscribe will make background_flag=True for some time and you will miss few updates in between. so second clean solution with extra code.
- to override class FyersSocket with its private method __ on * message() which raises the websocketdata callback irrespective of backgoundflag. please see how I have inherited private method with FyersSocket prefix for any priavate attribute with ‘’*__" in front of in FyersSocket
class CustomFyersSocket(FyersSocket):
def __init__(self, *args, **kwargs):
FyersSocket.__init__(self, *args, **kwargs)
def _FyersSocket__on_message(self, ws, msg):
if self._FyersSocket__data_type == "symbolData":
self.response = self.parse_symbol_data(msg)
if type(msg) == str:
if "error" in msg:
msg = json.loads(msg)
self.response_out["s"] = msg["s"]
self.response_out["code"] = msg["code"]
self.response_out["message"] = msg["message"]
self.response = self.response_out
self.logger.error(self.response)
if self.websocket_data is not None:
self.websocket_data(self.response)
else:
print(f"Response:{self.response}")
else:
if self.websocket_data is not None:
self.websocket_data(self.response)
else:
print(f"Response:{self.response}")
# self.logger.debug(self.response)
else:
self.response = msg
if type(msg) == str:
if "error" in msg:
msg = json.loads(msg)
self.response_out["s"] = msg["s"]
self.response_out["code"] = msg["code"]
self.response_out["message"] = msg["message"]
self.response = self.response_out
self.logger.error(self.response)
if self.websocket_data is not None:
self.websocket_data(self.response)
else:
print(f"Response:{self.response}")
else:
if self.websocket_data is not None:
self.websocket_data(self.response)
else:
print(f"Response:{self.response}")
else:
if self.websocket_data is not None:
self.websocket_data(self.response)
else:
print(f"Response:{self.response}")
# self.websocket_data()
return
# if self.__ws_message is not None:
# self.__ws_message(msg)