Having trouble keeping track of how long market has been closed for in C# wrapper. Just curious if there is any way I can tell how long its been since trading was last opened.
It’s in Python not C#, but here is the response from Dan at Alpaca.
@alighten I see you are using the pandas_market_calendars package? Maybe consider using exchange_calendars instead. That has built in functionality to get the last close date and time (and many other handy methods). Simply do this
!pip install -q exchange_calendars import exchange_calendars as xcals
# New York Stock Exchange calendar
nyse = xcals.get_calendar("XNYS")
today = pd.to_datetime('today')
nyse.previous_close(today).tz_convert('America/New_York')
# that will return something like this
Timestamp('2023-05-31 16:00:00-0400', tz='America/New_York')
You should be able to do it directly from API.
async def update_market_status(seconds):
while True:
"""
Update the global market status and sleep until the market opens or closes.
Args:
initial_check (bool, optional): If True, only perform an initial market
status check and do not sleep. Defaults to False.
"""
# Access global variables
global market_status_open
global time_to_market_open
global time_to_market_close
# Set timezone to New York (Eastern Time)
ET = pytz.timezone('America/New_York')
logging.debug("update_market_status: Fetching clock data.")
clock = api.get_clock()
current_time = datetime.datetime.now(ET)
logging.debug(f"update_market_status: Current time: {current_time}")
if clock.is_open:
logging.debug("update_market_status: Market is open.")
market_status_open = True
time_to_market_close = (clock.next_close - current_time).total_seconds()
logging.debug(f'update_market_status: Next market close: {clock.next_close}, sleeping for {int(time_to_market_close)} seconds')
else:
logging.info("update_market_status: Market is closed.")
market_status_open = False
time_to_market_open = (clock.next_open - current_time).total_seconds()
logging.debug(f'update_market_status: Next market open: {clock.next_open}, sleeping for {int(time_to_market_open)} seconds')
await asyncio.sleep(seconds)