how to send ping message using async library

async def send_ping(stream: ReconnectingWebsocket):
    #TODO: check for pong message
    while True:
        
        try:
            await stream.ping()
            print(f"Ping sent at time: {datetime.datetime.now(utc_2)}") 
            logging.info("Ping sent")
        except Exception as e:
            logging.info(f"Failed to send ping: {str(e)}")
            break
        await asyncio.sleep(60*10)  # Ping every 10 minutes

async def async_stream_data(symbol, bsm: BinanceSocketManager, connection_status):
    global stream_weights
    max_backoff_interval = 3600
    backoff_interval = 60
    reconnect_interval = 60*60
    rl = RateLimiter(6000, 1)
    ping_tasks = []
    #run an infinite loop so it reconnects when the connection is lost or an error occurs
    while True:
        try:
            async with bsm.futures_multiplex_socket(streams=[f"{symbol.lower()}@depth20@100ms", f"{symbol.lower()}@kline_4h", f"{symbol.lower()}@trade"]) as stream:
                logging.info(f"Connected to {symbol}")
                connection_status[symbol] = True
                #Ping task
                loop = asyncio.get_event_loop()
                ping_task = loop.create_task(send_ping(stream))
                ping_tasks.append(ping_task)

async def main():
    
    global bot_start_time
   
    bot_start_time = datetime.datetime.now(utc_2)
    hello_message_txt = f"""
    🔰 ----- LOB-bot 🚀 -----

    - Started at : {bot_start_time}
    - Coins : {async_coins}
    {notes}
        """
    await send_telegram_message(hello_message_txt)
    
    global order_books, columns, BUFFER_SIZE
    #client = Client(api_key, api_secret)
    client = await AsyncClient.create(api_key, api_secret)
    bsm = BinanceSocketManager(client,user_timeout=60)

ws_coins = ["BTCUSDT", "WIFUSDT"]
tasks = []
connection_status = {coin: False for coin in ws_coins}
 try:
  for coin in ws_coins:
              loop = asyncio.get_event_loop()
              tasks.append(loop.create_task(async_stream_data(coin, bsm, connection_status)))
  
  # await all asyns tasks
          return await asyncio.gather(*tasks, return_exceptions=True)

except Exception as e:
        print(f"An Exception occured in main: {e}")

if __name__ == "__main__":
    asyncio.run(main(), debug=True)


Hi,

I’ve spent hours and I can’t find any documentation on how to send/receive ping and pong and their responses format that supports asyncio and futures. I’ve left a snippet of relevant code above.

I have read the binance future connector github repo binance-futures-connector-python/binance/websocket/binance_socket_manager.py at main · binance/binance-futures-connector-python · GitHub

If i use the BinanceSocketManager from here i get this error, it’s apparently not suitable with AsyncClient:
TypeError: argument of type ‘AsyncClient’ is not iterable

Anyone please help. My code stops running on the server due to this. As of now I’m fetching my BinanceSocketManager(BSM) using this this path from python-binance package

from binance.streams import BinanceSocketManager

it results in Error: “stream” using this BSM version, I’m certain it comes from syntax error in send_ping:

await stream.ping()

Any help is deeply appreciated