sammchardy / python-binance

Binance Exchange API python implementation for automated trading
https://python-binance.readthedocs.io/en/latest/
MIT License
6.07k stars 2.21k forks source link

Websocket freezing #908

Closed kokojiji01 closed 3 years ago

kokojiji01 commented 3 years ago

Hello! I noticed that after around 42 seconds my application freezes

I can get rid of the error by removing the line await time.sleep(0.1) in my code. But in my actual trading bot there is some math that needs to be done and the sleep is command is replacing it.

Here's my code to illustrate the issue:

import asyncio
import time

from binance import BinanceSocketManager, AsyncClient

async def socket():
    messages = 0
    streams = ["ethbtc@bookTicker", "btcusdt@trade", "ethusdt@bookTicker"]
    start_time = time.time()

    client = await AsyncClient.create()
    bm = BinanceSocketManager(client)

    multi_socket = bm.multiplex_socket(streams)

    async with multi_socket as ms:
        while True:
            messages += 1
            msg = await ms.recv()

            time.sleep(0.1) # This illustrates some math that would be done

            # print current message's stream and the total amount of messages received
            message = msg["stream"]
            msg = f"\rMessages: {messages} Message: {message} Time: {float(time.time()-start_time)}       "
            print(msg, end="")

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(socket())

Expected behavior Expecting a continuous stream of messages. Instead stream freezes permanently after around 42 second.

Environment (please complete the following information):

Note Repost of https://github.com/sammchardy/python-binance/issues/862#issue-894140160 that was supposed to be fixed but wasn't. Switched the following line from the original post. await asyncio.sleep(0.1) to time.sleep(0.1)

I don't know if this makes a difference but in my real application the thread is busy doing math so it isn't something that can be awaited if have understood coroutines correctly.

remi027 commented 3 years ago

This problem is caused by bad internet or disconnections and it's caused by your msg = await ms.recv(), where it will try to wait for that data, even if it can't ever find one, thus, blocking the execution of the whole code. To solve the problem you should use the asyncio function wait_for() in place of your msg = await ms.recv() As in: msg = await asyncio.wait_for(ms.recv(), SECONDS_TO_TIMEOUT)