I have the TD API in Python and I'm trying to get 423 quotes from the multiple quote api portal and it doesn't always return 423. Does this sound like an async situation? This is my attempt at implementing async but I'm sure I didn't do it correct. Any pointers?
n = symbols_list
payload = {'symbol':n}
content = requests.get(url = endpoint, params = payload, headers = headers)
data = content.json()
time.sleep(1)
async def get(
session: aiohttp.ClientSession,
n: str,
**kwargs
) -> dict:
url = endpoint
headers = headers
print(f"Requesting {url}")
resp = await session.request('GET', url=url, **kwargs)
# Note that this may raise an exception for non-2xx responses
# You can either handle that here, or pass the exception through
data = await resp.json()
print('Received data for {url}')
return data
async def main(n, **kwargs):
# Asynchronous context manager. Prefer this rather
# than using a different session for each GET request
async with aiohttp.ClientSession() as session:
tasks = []
for symbols in n:
try:
tasks.append(get(session=session, n=symbols, **kwargs))
payload = {'symbol':symbols}
a = data
b = a[symbols]['symbol']
c = a[symbols]['lastPrice']
d = a[symbols]['netChange']
e = a[symbols]['totalVolume']
f = a[symbols]['regularMarketLastPrice']
g = a[symbols]['highPrice']
h = a[symbols]['lowPrice']
quotes = pd.DataFrame({'symbol' : [symbols], 'last' : [c], 'change' : [d], 'volume' : [e]
,'OOCLast' : [f], 'high' : [g], 'low' : [h]})
quotes.to_sql(name='quotes', con=engine, if_exists='append')
except:
pass
# asyncio.gather() will wait on the entire task set to be
# completed. If you want to process results greedily as they come in,
# loop over asyncio.as_com#pleted()
htmls = await asyncio.gather(*tasks, return_exceptions=True)
return htmls
if __name__ == '__main__':
n = symbols_list
# ...
# Either take colors from stdin or make some default here
await main(n)
This may be a bit more than you were looking for but you can modify it as you wish. I use the first call to get the symbols dataset so I can play around with a large list of symbols and test the api endpoints.
See comments inline:
Note: some sybmols won't return anything, but the following code is pretty consistent in and works well for me.
Output: