tda-api
tda-api copied to clipboard
Modify streaming sample in docs to indicate how to save incoming JSON data
When using the streaming sample from the docs, I'm able to stream level one futures, with quotes printed in the console.
However, it's unclear where one would make changes so as to save the json data to file. If anyone has suggestions, could you please indicate how to approach this on the below block:
async def read_stream():
await stream_client.login()
await stream_client.quality_of_service(StreamClient.QOSLevel.EXPRESS)
# Always add handlers before subscribing because many streams start sending
# data immediately after success, and messages with no handlers are dropped.
stream_client.add_level_one_futures_handler(
lambda msg: print(json.dumps(msg, indent=4)))
await stream_client.level_one_futures_subs(['/ES'])
while True:
await stream_client.handle_message(z)
asyncio.run(read_stream())
Replace the lambda function with a function call to a function you write that could either connect to database or just write to file.
Thanks @rkinetic
If anyone needs it, this worked for me:
stream_client.add_level_one_futures_handler(
# lambda msg: print(json.dumps(msg, indent=4))
lambda msg: save_to_file(json.dumps(msg, indent=4))
)
def save_to_file(msg):
x = json.loads(msg)
f = csv.writer(open('file.csv', 'a', newline=''))
f.writerow([
x['timestamp'],
x['content'][0].get('LAST_PRICE', 'nan'),
x['content'][0].get('TOTAL_VOLUME', 'nan')
])
Issues are not an appropriate venue for support. Please visit our discord to ask the community for help:
https://discord.gg/nfrd9gh
On second thought, I'm reopening this because we've been thinking about writing samples, and this might be a good one to provide.