0

Api calls could be speeded up with asynchronous calls. So I thought I can speed up my program by using asyncio. By displaying the results, the execution looks like synchronous. So I'm completely confused. What did I do wrong?

import asyncio
# pip install git+https://github.com/sammchardy/python-binance.git@00dc9a978590e79d4aa02e6c75106a3632990e8d
from binance import AsyncClient
import time


async def catch_up_aggtrades(client, symbols):
    start = time.time()   
    for symbol in symbols:
        await get_historical_aggtrades(client, symbol)
    end = time.time()
    print(end-start)


async def get_historical_aggtrades(client, symbol):
    async for trade in client.aggregate_trade_iter(symbol, '5 minutes ago UTC'):
        print("symbol {} -> {}".format(symbol, trade))


async def main():
    client = await AsyncClient.create()
    symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT']
    await catch_up_aggtrades(client, symbols)
    while True:
       await asyncio.sleep(20, loop=loop)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
lovelace63
  • 352
  • 1
  • 6
  • 15

1 Answers1

1

Try this:

async def catch_up_aggtrades(client, symbols):
    start = time.time()   
    await asyncio.gather(*[get_historical_aggtrades(client, symbol) for symbol in symbols])
    end = time.time()
    print(end-start)
Waket Zheng
  • 5,065
  • 2
  • 17
  • 30