tastyware / tastytrade

An unofficial, sync/async Python SDK for Tastytrade!
https://tastyworks-api.rtfd.io
MIT License
126 stars 43 forks source link

session.get_candle() problem if market closed #96

Closed kaidaniel82 closed 1 year ago

kaidaniel82 commented 1 year ago

The response status is 200 but, as expected, no data point is available. This causes the code in line 233 in the session.py to crash.

start_day = WEEKEND session.get_candle(symbols=['VIXY'], interval='5m', start_time=start_day)

leads to: KeyError: <EventType.CANDLE: 'Candle'>

Graeme22 commented 1 year ago

Can you add more context? E.g. what date is WEEKEND?

kaidaniel82 commented 1 year ago

It appears to be an edge case. The data from yesterday didn't work yesterday but is functioning today. The data from today isn't working at the moment. Regardless, if data = response.json()[EventType.CANDLE] in session.py line 233 doesn't contain candle data, the code crashes. This could be easily fixed by validating whether the key exists in the response dict().

This is the complete code example which crashed:

from datetime import datetime, timezone
from tastytrade import ProductionSession

session = ProductionSession('USER', 'PW')
start_day = datetime(2023, 11, 12, tzinfo=timezone.utc) # THIS is TODAY

print(start_day)
data_history = session.get_candle(symbols=["VIXY"], interval="5m", start_time=start_day, end_time=None)

I propose a solution in the following manner for code in session.py line 233ff:

    data = response.json()

    if EventType.CANDLE in data:
        data = data[EventType.CANDLE]
        candles = []
        for _, v in data.items():
            candles.extend([Candle(**d) for d in v])

        return candles
    else:
        return []
Graeme22 commented 1 year ago

Ah, makes sense now. So the market is closed weekends, the data you're trying to fetch doesn't exist.

I'm going to close this, your fix would prevent the crash but since this is incorrect usage I think the error is appropriate.

kaidaniel82 commented 1 year ago

I would agree if the behavior was consistent. Yesterday's date works today, but not yesterday. If I set extendet_trading-hours to True, the date no longer works. There are some combinations that work but not 100%. Its about dealing with empty data. Its an uncovered error. This can't be handled from outside of session.py, because other situations could also lead to a crash.

Graeme22 commented 1 year ago

Yesterday's date was also invalid though.

Since this is an SDK, it's not unexpected that an error would be thrown by illegal/nonsensical requests. If you for some reason need to cover those cases, you can use error handling in your application.