import tda import logging, sys tda.debug.enable_bug_report_logging() def display_token_info(token_path): import json import pandas as pd import logging with open(token_path) as f: token = json.load(f) if 'refresh_token_expires_in' in token['token']: refresh_offset = int(token['token']['refresh_token_expires_in']) else: print('token.refresh_token_expires_in DNE! Using default 90 days.') refresh_offset = 7776000 access_exp = int(token['creation_timestamp']) + refresh_offset access_tm = pd.to_datetime(access_exp,unit='s').tz_localize('UTC').tz_convert('America/Chicago') print(f"Access token expiration: {access_tm}") refresh_tm = pd.to_datetime(token['token']['expires_at'],unit='s').tz_localize('UTC').tz_convert('America/Chicago') print(f"Refresh token expiration: {refresh_tm}") rn = pd.Timestamp.now(tz='UTC') pd.to_datetime(access_exp,unit='s').tz_localize('UTC') # Access refresh tokens are refreshed 5 days before expiration working_exp_date = pd.to_datetime(access_exp,unit='s').tz_localize('UTC') - \ pd.Timedelta(10, "d") if ( rn >= working_exp_date ): print(""" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Access token about to expire. Time to refresh it. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! """) def logins(): # Login to TD-Ameritrade TOKEN_PATH = '/tmp/token.json' API_KEY = 'XXXX@AMER.OAUTHAP' REDIRECT_URI = 'https://127.0.0.1/' ACCT_ID = XXXX def make_webdriver(): # Import selenium here because it's slow to import from selenium import webdriver driver = webdriver.Firefox() atexit.register(lambda: driver.quit()) return driver c = tda.auth.easy_client( API_KEY, REDIRECT_URI, TOKEN_PATH, make_webdriver) return c # Configure main logging FORMAT = "[%(levelname)s:%(funcName)s:%(lineno)s]: %(message)s" logging.basicConfig(stream=sys.stdout, format=FORMAT, level=logging.INFO) # ChatGPT # Configure httpx logging httpx_logger = logging.getLogger("httpx") httpx_logger.setLevel(logging.DEBUG) # Set the desired logging level for httpx requests # login c = logins() # display the age of the refresh token on disk display_token_info('/tmp/token.json') # display the behavior of a call when the token on disk is expired r = c.get_user_principals() # display the age of the refresh token on disk display_token_info('/tmp/token.json')