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

You are experiencing a couple of key issues while using the Binance API with asyncio. Specifically, you are trying to implement automatic pinging to maintain a WebSocket connection, and you’re encountering type errors with BinanceSocketManager when using it with AsyncClient.

send a ping and check for a pong with asyncio, ensure your WebSocket client supports asyncio operations natively. using websockets library, it directly supports asyncio and can handle ping/pong mechanisms under the hood.

import datetime
import asyncio
import logging

async def send_ping(stream):
while True:
try:
pong_waiter = await stream.ping()
await pong_waiter # Wait for pong
logging.info(f"Ping sent at {datetime.datetime.now()} and pong received")
except Exception as e:
logging.error(f"Failed to send ping: {str(e)}")
break
await asyncio.sleep(600) # Ping every 10 minutes

Ensure WebSocket client library (stream) supports the .ping() method that returns a pong_waiter.

Reagarding use of BinanceSocketManager with AsyncClient:
BinanceSocketManager with AsyncClient can not be used without some modifications:

  1. Make sure you are using the correct versions of python-binance library where BinanceSocketManager is designed to work with AsyncClient.
  2. If BinanceSocketManager does not natively support AsyncClient, you may need to either update the library or modify the BinanceSocketManager class to handle asynchronous operations properly…

consider checking the resources:
Binance Official API Docs
&

Sorry If I misunderstood your problem or may have informed you something that you may have already tried or already know and didnt work.