A python client library for the TD Ameritrade API.
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.
from td.oauth import run, shutdown_server
from td.app.auth import FlaskTDAuthCommand-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 flowshutdown_server(): Gracefully shuts down the Flask OAuth serverParameters for run():
flask_client: Flask application instance configured for OAuthclose_after: Whether to automatically close the server after authenticationThe 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 serverAdvanced 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 authenticationgrab_access_token_and_refresh_token(): Exchanges callback URL for access and refresh tokensgrab_refresh_token(): Refreshes expired access token using refresh tokensave_token(): Saves token information to secure storagesave_state(): Saves authentication state and credentialsfrom 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'])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 automaticallyfrom 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)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}")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()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 expirefrom 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']}")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 callsTD Ameritrade requires the client ID to include the OAuth application suffix:
your_client_id@AMER.OAUTHAPMYAPP12345@AMER.OAUTHAPThe redirect URI must match exactly what was configured in your TD Ameritrade developer application:
http://localhost:8080/callbackThe library automatically manages credential storage:
.td_python_api/credentials_path parameterHandle 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