alpacahq / alpaca-py

The Official Python SDK for Alpaca API
https://alpaca.markets/sdks/python/getting_started.html
Apache License 2.0
537 stars 134 forks source link

fix: Support timezone aware datetime for get_orders() #377

Closed hiohiohio closed 10 months ago

hiohiohio commented 10 months ago

Fixes https://github.com/alpacahq/alpaca-py/issues/236

Context:

Changes:

you can use below code to check in google colab

# use alpaca-py v0.13.1 to reproduce this issue
# ! pip install alpaca-py==0.13.1
! pip install git+https://github.com/hiohiohio/alpaca-py.git@support-datetime-with-timezone

import datetime
from zoneinfo import ZoneInfo

from alpaca.trading.requests import GetOrdersRequest
from alpaca.trading.enums import QueryOrderStatus
from alpaca.trading.client import TradingClient

api_key=<YOUR API KEY>
secret_key=<YOUR SECRET KEY>
paper = True

# timezone aware datetime (UTC)
client = TradingClient(api_key, secret_key, paper=paper)
nowUTC = datetime.datetime.now(datetime.timezone.utc)
req = GetOrdersRequest(status=QueryOrderStatus.ALL, until=nowUTC)
print(client.get_orders(req)[:1]) # APIError <= is resolved

# naive datetime is treated as UTC (same as before)
now = datetime.datetime.now()
req2 = GetOrdersRequest(status=QueryOrderStatus.ALL, until=now)
print(client.get_orders(req2)[:1])

# timezone aware datetime (ET)
nowNY = datetime.datetime.now(ZoneInfo("US/Eastern"))
req3 = GetOrdersRequest(status=QueryOrderStatus.ALL, until=nowNY)
print(client.get_orders(req3)[:1])