Best way to subscribe and unsubscribe to symbols in websocket

Hi, I’m new to algo trading and getting started with different systems. So far the plan is to get real-time data for multiple symbols using Fyers V3 API and send it Kafka from where I can consume and run my logic on different nodes. As part of this, I want to subscribe and unsubscribe to some of the symbols in real-time based on my strategies.

But the problem I’m facing is, if I run the websocket in Foreground mode I’m not able to run the socket’s subscribe and unsubscribe commands. If I run the websocket in Background mode, the data is getting written to a file (which I’m not able to get it working yet), I’m unable to use the on_message callback function to write the symbol details to Kafka brokers for further processing.

Can you please help with what is the best way to subscribe and unsubscribe from the symbols while still being able to use something like on_message callbacks so that I can write data to Kafka for further processing?

Programming Language: Python

Hi @RETTwWs510 ,
Using Foreground mode will allow to subscribe and unsubscribe a symbol Dynamically.
Subscribe to a symbol to start receiving data, on_message to process incoming data . Either you can store this data in a file, and read this file to send updates to Kafka or using on_message to send data directly to Kafka. Once you have collected enough data for your logic, then you can unsubscribe symbol.

Note:-
Use subscribe to start receiving data and unsubscribe to stop receiving it. If a symbol is already subscribed, avoid subscribing to another symbol immediately. Instead, unsubscribe from the current socket first, then subscribe to multiple symbols together.

Thanks @JOJYsbsZnC for the reply! Can you please explain what does the keep_running function do? I noticed that in the background mode the data gets written to the file even though I’ve not run this function.