I have some code, to fetch prices from several markets:
def getprices(exchange):
inst = getattr(ccxt, exchange)()
prices = inst.fetch_ticker('symbol')
data = {f'{exchange}': prices}
return data
prices_data = {}
fails = []
for exchange in exchanges:
try:
prices_data.update(getprices(exchange))
print('prices successfully pulled for ' +exchange)
except:
fails.append(exchange)
print('price pull fail for ' +exchange)
This code is working, but problem i gathering is time of synchronous iteration is much slower than async i want to make it async.
I tried to make it async by several ways the only workable this one:
async def getprices(exchange):
inst = getattr(ccxt, exchange)()
prices = inst.fetch_ticker(symbol)
data = {f'{exchange}': prices}
return data
async def main():
task1 = asyncio.create_task(getprices(stock1))
task2 = asyncio.create_task(getprices(stock2))
task3 = asyncio.create_task(getprices(stock3))
task4 = asyncio.create_task(getprices(stock4))
task5 = asyncio.create_task(getprices(stock5))
task6 = asyncio.create_task(getprices(stock6))
await task1
await task2
await task3
await task4
await task5
await task6
asyncio.run(main())
This code is working, but how you see it has much more writed not necessary (i believe) blocks of code, and has no exception catch