python-binance icon indicating copy to clipboard operation
python-binance copied to clipboard

Can't close websockets

Open frangte opened this issue 7 years ago • 3 comments

Hi every one,

I wrap binance.websocket in my custom class (for my usecase).

class BinanceSocket(object):
    def __init__(self, api_key, api_secret):
        self.connection_key = ''
        self.binance_client = Client(api_key=api_key, api_secret=api_secret)
        self.binance_stream = BinanceSocketManager(self.binance_client)
        self.__transactions = []
        self.timer = Timer(INTERVAL, lambda: self._auto_trigger())

    def start(self):
        self.connection_key = self.binance_stream.start_user_socket(lambda msg: self._handle_message(msg))
        self.binance_stream.start()
        self.timer.start()

    def stop(self):
        self.binance_stream.stop_socket(self.connection_key)

    def _handle_message(self, msg):
        if self._is_filled_event(msg):
            self.__transactions.append(msg)
            if len(self.__transactions) == MAX_LEN_MESSAGE:
                self._send_task()

    def _send_task(self):
        if len(self.__transactions) == 0:
            return
        print(self.__transactions)
        self.__transactions = []

    def _auto_trigger(self):
        self._send_task()
        self.timeout = Timer(INTERVAL, lambda: self._auto_trigger())
        self.timeout.start()

    @staticmethod
    def _is_filled_event(msg: dict) -> bool:
        if msg['e'] == 'executionReport':
            if msg['x'] == 'TRADE' and msg['X'] == 'FILLED':
                return True
        return False

if __name__ == '__main__':
    worker = BinanceSocket(
        api_key='****',
        api_secret='****'
    )

    worker.start()
    time.sleep(2)
    worker.stop()

as you can see in stop() function i call to binance_stream.stop_socket(self.connection_key) but this thread still running and not exit.

Anyone can help me stop socket correctly in my usecase.

Thanks!

frangte avatar Jan 23 '19 17:01 frangte

And this is result after using Ctrl + c.

image

frangte avatar Jan 23 '19 17:01 frangte

I have never had luck with stop_socket working. I have always used bm.close per this issue. https://github.com/sammchardy/python-binance/issues/202

Bm.close will close the socket but leave the socket manager open. You can add new sockets to the socket manager at any time. One word of warning. If you close the socket you used to open the socket manager with, it runs like a fat lazy dog on reconnect. I always just leave my opening socket open and ignore values until I want them. That way other sockets don't take several seconds to reconnect and you have some responsiveness.

CJ1976 avatar Jan 24 '19 08:01 CJ1976

Resolve this issue with canel() timer.

frangte avatar Jan 24 '19 08:01 frangte