2

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

That worked. Thanks a lot!
Good to hear, don't forget to accept answers that helped you
If you want to avoid asyncio.gather alltogether as your program grows larger and more complex, here is a nice API: elsampsa.github.io/task_thread/_build/html/index.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.