A python client library for the TD Ameritrade API.
npx @tessl/cli install tessl/pypi-td-ameritrade-python-api@0.3.0A comprehensive Python client library for the TD Ameritrade API that enables developers to manage trades, pull historical and real-time data, manage accounts, and create and modify orders programmatically. The library provides OAuth authentication workflows, streaming data capabilities, and complete coverage of TD Ameritrade's REST API endpoints.
pip install td-ameritrade-python-apifrom td.client import TDClient
from td.stream import TDStreamerClient
from td.orders import Order, OrderLeg
from td.enums import ORDER_SESSION, DURATION, ORDER_TYPE
from td.exceptions import TknExpError, ServerErrorfrom td.client import TDClient
# Initialize the client
td_client = TDClient(
client_id='your_client_id',
redirect_uri='http://localhost:8080/callback',
account_number='your_account_number'
)
# Login and authenticate
td_client.login()
# Get real-time quotes
quotes = td_client.get_quotes(['AAPL', 'MSFT', 'GOOGL'])
print(quotes)
# Get account information
accounts = td_client.get_accounts()
print(accounts)
# Get historical price data
price_history = td_client.get_price_history(
symbol='AAPL',
period_type='month',
period=6,
frequency_type='daily',
frequency=1
)
print(price_history)The TD Ameritrade Python API is organized around several key components:
The library follows a modular design where each major functional area is contained in its own module, allowing developers to import only the components they need for their specific use cases.
Core REST API functionality including authentication, market data retrieval, account management, and basic order operations. The TDClient class provides methods for all standard TD Ameritrade API endpoints.
class TDClient:
def __init__(self, client_id: str, redirect_uri: str, account_number: str = None, credentials_path: str = None, auth_flow: str = 'default', _do_init: bool = True, _multiprocessing_safe = False) -> None: ...
def login() -> None: ...
def get_quotes(instruments: List[str]) -> Dict: ...
def get_accounts(account: str = None, fields: List[str] = None) -> Dict: ...
def get_price_history(symbol: str, **kwargs) -> Dict: ...WebSocket-based streaming client for real-time market data, account activity, and news. Supports Level 1 and Level 2 data for equities, options, futures, and forex.
class TDStreamerClient:
def __init__(self, websocket_url: str, user_principal_data: Dict, credentials: Dict) -> None: ...
def stream(print_to_console: bool = True) -> None: ...
def level_one_quotes(symbols: List[str], fields: List[str] = None) -> None: ...
def level_two_quotes(symbols: List[str], fields: List[str] = None) -> None: ...Comprehensive order building and management system supporting simple orders, complex multi-leg strategies, and conditional orders. Includes classes for building order legs and complete order structures.
class Order:
def __init__(self) -> None: ...
def order_type(self, order_type: str) -> 'Order': ...
def add_order_leg(self, order_leg: 'OrderLeg') -> None: ...
class OrderLeg:
def __init__(self) -> None: ...
def order_leg_instruction(self, instruction: str) -> 'OrderLeg': ...
def order_leg_asset(self, asset_type: str, symbol: str) -> 'OrderLeg': ...OAuth 2.0 authentication flow with support for both command-line and Flask-based workflows. Handles access tokens, refresh tokens, and credential storage.
def run(flask_client, close_after: bool = True) -> None: ...
def shutdown_server() -> None: ...
class FlaskTDAuth:
def __init__(self, client_id: str, redirect_uri: str) -> None: ...
def authorization_url() -> str: ...
def grab_access_token_and_refresh_token(url: str) -> Dict: ...Comprehensive enums and constants for all API parameters, order types, asset types, market sessions, and field IDs. Essential for constructing valid API requests.
class ORDER_SESSION:
NORMAL: str
AM: str
PM: str
SEAMLESS: str
class ORDER_TYPE:
MARKET: str
LIMIT: str
STOP: str
STOP_LIMIT: strUtility classes for path management, date/time conversions, option chain building, watchlist management, and message parsing for streaming data.
class StatePath:
def write_credentials(file_path: str, state: Dict) -> None: ...
def read_credentials(file_path: str) -> Dict: ...
class TDUtilities:
@staticmethod
def milliseconds_since_epoch(dt_object) -> int: ...Custom exception classes for handling different types of API errors, including token expiration, rate limiting, forbidden access, and server errors.
class TknExpError(Exception): ...
class ExdLmtError(Exception): ...
class ForbidError(Exception): ...
class ServerError(Exception): ...