CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-td-ameritrade-python-api

A python client library for the TD Ameritrade API.

Overview
Eval results
Files

authentication.mddocs/

Authentication

The TD Ameritrade Python API provides OAuth 2.0 authentication through multiple approaches: command-line based authentication and Flask web-based authentication. The system handles access tokens, refresh tokens, and credential storage automatically.

Core Imports

from td.oauth import run, shutdown_server
from td.app.auth import FlaskTDAuth

Capabilities

Flask OAuth Server

Command-line OAuth authentication using a local Flask server for handling the OAuth callback flow.

def run(flask_client, close_after: bool = True) -> None: ...
def shutdown_server() -> None: ...

Functions:

  • run(): Starts a Flask server to handle OAuth authentication flow
  • shutdown_server(): Gracefully shuts down the Flask OAuth server

Parameters for run():

  • flask_client: Flask application instance configured for OAuth
  • close_after: Whether to automatically close the server after authentication

Flask Routes

The OAuth server exposes several routes for the authentication flow:

  • / - Home route displaying authentication status
  • /login - Initiates the OAuth login process
  • /login/callback - Handles OAuth callback from TD Ameritrade
  • /login/refresh - Handles token refresh requests
  • /shutdown - Shuts down the OAuth server

FlaskTDAuth Class

Advanced OAuth authentication helper using Flask and requests-oauthlib for more control over the authentication process.

class FlaskTDAuth:
    def __init__(self, client_id: str, redirect_uri: str) -> None: ...
    def authorization_url(self) -> str: ...
    def grab_access_token_and_refresh_token(self, url: str) -> Dict: ...
    def grab_refresh_token(self) -> Dict: ...
    def save_token(self, token_dict: Dict) -> None: ...
    def save_state(self, token_dict: Dict) -> None: ...

Methods:

  • authorization_url(): Generates the OAuth authorization URL for user authentication
  • grab_access_token_and_refresh_token(): Exchanges callback URL for access and refresh tokens
  • grab_refresh_token(): Refreshes expired access token using refresh token
  • save_token(): Saves token information to secure storage
  • save_state(): Saves authentication state and credentials

Usage Examples

Basic Authentication Flow

from td.client import TDClient

# Initialize client with OAuth parameters
client = TDClient(
    client_id='your_client_id@AMER.OAUTHAP',
    redirect_uri='http://localhost:8080/callback',
    account_number='your_account_number'
)

# Login using default command-line OAuth flow
client.login()

# Client is now authenticated and ready for API calls
quotes = client.get_quotes(['AAPL', 'MSFT'])

Flask-based Authentication

from td.client import TDClient

# Initialize client with Flask authentication flow
client = TDClient(
    client_id='your_client_id@AMER.OAUTHAP',
    redirect_uri='http://localhost:8080/callback',
    auth_flow='flask'
)

# Login using Flask web-based OAuth flow
client.login()

# Authentication will open a web browser for user consent
# Server will handle callback automatically

Manual OAuth with FlaskTDAuth

from td.app.auth import FlaskTDAuth

# Initialize Flask OAuth helper
auth = FlaskTDAuth(
    client_id='your_client_id@AMER.OAUTHAP',
    redirect_uri='http://localhost:8080/callback'
)

# Get authorization URL
auth_url = auth.authorization_url()
print(f"Please visit: {auth_url}")

# After user authorization, handle callback
# (callback_url would be received from TD Ameritrade)
callback_url = "http://localhost:8080/callback?code=..."
tokens = auth.grab_access_token_and_refresh_token(callback_url)

# Save tokens
auth.save_token(tokens)
auth.save_state(tokens)

Token Management

from td.client import TDClient

# Initialize client
client = TDClient(
    client_id='your_client_id@AMER.OAUTHAP',
    redirect_uri='http://localhost:8080/callback',
    credentials_path='/path/to/credentials.json'
)

# Login will automatically load saved credentials if available
client.login()

# Manual token refresh
new_token = client.grab_access_token()
print(f"New access token: {new_token}")

# Get new refresh token
refresh_token = client.grab_refresh_token()
print(f"New refresh token: {refresh_token}")

# Manual OAuth URL generation
oauth_url = client.grab_url()
print(f"OAuth URL: {oauth_url}")

Custom OAuth Server

from td.oauth import run, shutdown_server
from flask import Flask

# Create custom Flask app
app = Flask(__name__)

# Configure OAuth settings
app.config['CLIENT_ID'] = 'your_client_id@AMER.OAUTHAP'
app.config['REDIRECT_URI'] = 'http://localhost:8080/callback'

# Run OAuth server
try:
    run(app, close_after=True)
except KeyboardInterrupt:
    shutdown_server()

Multiprocessing Safe Authentication

from td.client import TDClient

# Initialize client with multiprocessing safety
client = TDClient(
    client_id='your_client_id@AMER.OAUTHAP',
    redirect_uri='http://localhost:8080/callback',
    _multiprocessing_safe=True
)

# Login - safe for use across multiple processes
client.login()

# Token cache will be shared across processes
# Only one process will refresh tokens when they expire

Exchange Authorization Code

from td.client import TDClient

# Initialize client
client = TDClient(
    client_id='your_client_id@AMER.OAUTHAP',
    redirect_uri='http://localhost:8080/callback'
)

# Exchange authorization code for tokens
# (authorization_code obtained from OAuth callback)
authorization_code = "received_from_callback"
tokens = client.exchange_code_for_token(
    code=authorization_code,
    return_refresh_token=True
)

print(f"Access Token: {tokens['access_token']}")
print(f"Refresh Token: {tokens['refresh_token']}")

Logout and Session Management

from td.client import TDClient

# Initialize and authenticate
client = TDClient(
    client_id='your_client_id@AMER.OAUTHAP',
    redirect_uri='http://localhost:8080/callback'
)
client.login()

# Use API
accounts = client.get_accounts()

# Logout to clear session
client.logout()

# Client is now logged out and credentials are cleared
# Need to login again for further API calls

Authentication Configuration

Client ID Format

TD Ameritrade requires the client ID to include the OAuth application suffix:

  • Format: your_client_id@AMER.OAUTHAP
  • Example: MYAPP12345@AMER.OAUTHAP

Redirect URI

The redirect URI must match exactly what was configured in your TD Ameritrade developer application:

  • Common development URI: http://localhost:8080/callback
  • Production URIs must use HTTPS

Credentials Storage

The library automatically manages credential storage:

  • Default location: User's home directory under .td_python_api/
  • Custom path can be specified with credentials_path parameter
  • Credentials include access token, refresh token, and expiration information

Authentication Errors

Handle authentication errors using the exception classes:

from td.exceptions import TknExpError, ForbidError

try:
    client.login()
    quotes = client.get_quotes(['AAPL'])
except TknExpError:
    print("Token expired, need to re-authenticate")
    client.login()
except ForbidError:
    print("Access forbidden, check API permissions")

Install with Tessl CLI

npx tessl i tessl/pypi-td-ameritrade-python-api

docs

authentication.md

client-api.md

enums-constants.md

exceptions.md

index.md

order-management.md

streaming.md

utilities.md

tile.json