hackingthemarkets / tradingview-tdameritrade-option-bot

TD Ameritrade API option orders from TradingView webhook alerts
85 stars 40 forks source link

Advaned auth for serverless app #1

Open KJJorgensen opened 3 years ago

KJJorgensen commented 3 years ago

I'm having a problem with the token path not being found when deploying to the cloud with both chalice and flask. The token path is not an issue when I run the app locally. I think the fix lies in the advanced functionality section of the client authorization. There it lists 'tda.auth.client_from_access_functions(api_key, token_read_func, token_write_func, asyncio=False' as being used in a serverless application. Could this be my problem? My feature request is adding a script to this repository that shows how to make this authentification method work. Maybe just as a template to replace the other Auth methods for those of us struggling to get this app working in the cloud. A video breaking this down would help aswell

Thank you for your time and all the awesome information

gsquarediv commented 1 year ago

This is how I implemented the client_from_access_functions authentication method. Hope it helps.

# Get a fresh token from TD Ameritrade and upload it to AWS S3
def get_new_token():
    s3 = boto3.client('s3')
    token_path = os.path.join(os.path.dirname(__file__), 'chalicelib', 'token.json')
    auth.client_from_manual_flow(config.api_key, 'https://localhost', token_path)
    s3.upload_file(token_path, 'td-ameritrade', 'token.json')
    return

def read_token():
    s3 = boto3.client('s3')
    try:
        s3_object = s3.get_object(Bucket='td-ameritrade', Key='token.json')
    except s3.exceptions.NoSuchKey:
        get_new_token()
        s3_object = s3.get_object(Bucket='td-ameritrade', Key='token.json')
    s3token = json.loads(s3_object['Body'].read().decode('utf-8'))
    return s3token

def write_token(token, *args, **kwargs):
    s3 = boto3.client('s3')
    s3.put_object(Body=json.dumps(token), Bucket='td-ameritrade', Key='token.json')
    return

c = auth.client_from_access_functions(config.api_key, token_read_func=read_token, token_write_func=write_token)