My code requests two api gets and compares them. I'm iterating against a dictionary in a for loop to determine where to point the get request. Sending GET, waiting for reply, then performing math, then moving to next item in dictionary takes a long time because of the waiting for reply.
There are numerous conversations that asyncio is a solution to this, but the code chunks I see in answers don't seem to help (or I can't figure out how to apply). See here, here, here for excellent conversations on asyncio. I'm fairly certain that if I batch the requests it will speed up iteration significantly. IE send 20 requests (arbitrary), get 20 responses, compare the outputs, repeat.
Here is my non-async code, modified a bit for readability.
value_ops = {'name1':['text','ticker1','ticker2','ticker3'],
'name2':['text','ticker1','ticker2','ticker3'],
...
}
# This are the two api GET reqeusts
def pm_check(od_pm,pSide):
#[code cunk here] output is json that I'm grabbing two values from
def ks_check(od_ks,kSide,direction):
#[code cunk here] output is json that I'm grabbing two values from
def opp_check(tradename,ticker1,ticker2,ticker3):
pm_check(ticker1,'asks')
ks_check(ticker2,'yes','buy')
#comparison math code chunk omitted
for value in value_ops.values()
opp_check(*value)
So the code that's working iterates against the dictionary to grab the values, feeds them into the api call function, and does some calculation, and then goes on to the next value to repeat.
I think ending point would be to send all the api requests at same time, store them in a table, and then do some calcs on that entire table. IE in a batch of 20 etc.
What I was trying as a starting point was:
value_ops = {'name1':['tradename','ticker1','ticker2','ticker3'],
'name2':['tradename','ticker1','ticker2','ticker3'],
...
}
# This are the two api GET reqeusts
async def pm_check(od_pm,pSide):
#[code cunk here] output is json that I'm grabbing two values from
async def ks_check(od_ks,kSide,direction):
#[code cunk here] output is json that I'm grabbing two values from
async def opp_check(tradename,ticker1,ticker2,ticker3):
pm_check(ticker1,'asks')
ks_check(ticker2,'yes','buy')
#comparison math code chunk omitted
import asyncio
async def process_all():
tasks = []
async for value in value_ops.values():
task = asyncio.create_task(opp_check(*value))
tasks.append(task)
await asyncio.gather(*tasks)
asyncio.run(process_all())
I was hoping that this would let me proof of concept async iteration on my loop. It's throwing a runtimeerror [asyncio.run() cannot be called from a running event loop]
. I suspect that while I can get past this error, the result won't actually be what I'm looking for.
Any feedback on how to speed this up is appreciated. I had also tried multiprocessing but that did nothing to speed me up (which I think makes sense this isn't a cpu issues it's the downtime while waiting for the GET reply).
EDIT: I'm using anaconda environment if relevant.