tda-api icon indicating copy to clipboard operation
tda-api copied to clipboard

Modify streaming sample in docs to indicate how to save incoming JSON data

Open trogloditee opened this issue 3 years ago • 4 comments

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())

trogloditee avatar Mar 11 '21 18:03 trogloditee

Replace the lambda function with a function call to a function you write that could either connect to database or just write to file.

rkinetic avatar Mar 11 '21 22:03 rkinetic

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')
 ])

trogloditee avatar Mar 12 '21 00:03 trogloditee

Issues are not an appropriate venue for support. Please visit our discord to ask the community for help:

https://discord.gg/nfrd9gh

alexgolec avatar Mar 12 '21 13:03 alexgolec

On second thought, I'm reopening this because we've been thinking about writing samples, and this might be a good one to provide.

alexgolec avatar Mar 12 '21 13:03 alexgolec