'Change a symbol / interval of a kline socket (python-binance)

as an exercise I am trying to create a live chart via the binance api in a GUI. I want to put an option in the GUI that the chart can change interval and symbol, because I'm new to programming I don't know how to start with this.

I wrote the following code, is it possible to make the kline socket change symbol or interval?

import time
import pandas as pd
from binance import ThreadedWebsocketManager

class Socket:
    def __init__(self, symbol, interval):
        super().__init__()
        self._current_symbol = symbol
        self._current_interval = interval

        self._candles_df = pd.DataFrame(columns=["Date", "Open", "Low", "Close", "High", "Volume"])
        self._twm = ThreadedWebsocketManager()

    def change_interval(self, new_interval):
        self._current_interval = new_interval
        # ???
        # Can I restart the socket with a new interval ?

    def change_symbol(self, new_symbol):
        self._current_symbol = new_symbol
        # ???
        # Can I restart the socket with a new symbol ?

    def handle_socket_message(self, msg):
        candle = msg["k"]
        candle = {"Date": candle["t"], "Open": candle["o"], "Low": candle["l"], "Close": candle["c"], "High": candle["h"], "Volume": candle["v"]}
        self._candles_df = self._candles_df.append(candle, ignore_index=True)

    def run(self):
        self._twm.start()
        self._socket_name = self._twm.start_kline_socket(callback=self.handle_socket_message, symbol=self._current_symbol, interval=self._current_interval)

    def get_candles(self):
        if self._candles_df.empty:
            return None
        else:
            return self._candles_df


def update_chart(candle_data):
    # simulate update chart ...
    print(candle_data)


# symbols = [ 'BTCUSDT', 'ETHUSDT', 'BNBUSDT', 'SOLUSDT', 'ADAUSDT', 'XRPUSDT', 'DOTUSDT', 'LINKUSDT', 'XMRUSDT', 'LTCUSDT' ]
# intervals = [ "1m", "5m", "15m", "4h" ]

current_symbol = "BTCUSDT"
current_interval = "1m"
if __name__ == '__main__':
    socket = Socket(current_symbol, current_interval)
    socket.run()

    index = 0
    while True:
        time.sleep(1)
        update_chart(socket.get_candles())
        index += 1

        if index == 5:
            # simulate a change of symbol / interval
            socket.change_symbol("ETHUSDT") # -> ???

thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source