Multiple websocket streams with asyncio in Python

Viewed 833

Can anyone please help with asyncio? I'm using it to connect to Binance websockets. The example below is for one API key. I need to receive messages for several API keys.

Question: is it possible to do this within the same main() without creating a separate file for each API key?

async def main():
    client = await AsyncClient.create(APIkey1, APIsecret1)
    bm = BinanceSocketManager(client)
    
    # start any sockets here, i.e a trade socket
    ts = bm.trade_socket('BNBBTC')
    
    # then start receiving messages
    async with ts as tscm:
        while True:
            res = await tscm.recv()
            print(res)

    await client.close_connection()

if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
1 Answers

You can can create mutiple coroutine and put them into gather or you can just put them in ensure_future without awaiting the future. In anycase, you should probably create you client with an async context manager, as it might never be closed due to the infinite loop. So in terms of code

import asyncio
async def run_it(key, secrete):
    client = await AsyncClient.create(key, secret)
    bm = BinanceSocketManager(client)
    
    # start any sockets here, i.e a trade socket
    ts = bm.trade_socket('BNBBTC')
    
    # then start receiving messages
    async with ts as tscm:
        while True:
            res = await tscm.recv()
            print(res)

    await client.close_connection()

async def main():
    all_runs = [run_it(s,k) for (s,k) in all_keys]
    await asyncio.gather(*all_runs)

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

this assumes that in all_key is an iterable of tuples with a tuple being a pair of secret and API key

Related