A python client library for the TD Ameritrade API.
The TDClient class is the main interface for interacting with TD Ameritrade's REST API. It handles OAuth authentication, session management, and provides methods for all major API endpoints including market data, account information, order management, and user preferences.
from td.client import TDClientCreates a new TDClient instance with OAuth configuration and optional settings for credentials management and multiprocessing safety.
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: ...Parameters:
client_id: The Consumer ID assigned during TD Ameritrade app registrationredirect_uri: The redirect URL specified in your TD Ameritrade applicationaccount_number: Your main TD Ameritrade account number (optional)credentials_path: Path to JSON credentials file (optional)auth_flow: Authentication flow type - 'default' for command-line or 'flask' for web-based_do_init: Whether to initialize configuration on creation_multiprocessing_safe: Enable thread-safe token caching for multiprocessingOAuth 2.0 authentication workflow methods for logging in, managing tokens, and handling session state.
def login() -> bool: ...
def logout() -> None: ...
def oauth() -> None: ...
def grab_access_token() -> dict: ...
def grab_refresh_token() -> bool: ...
def grab_url() -> dict: ...
def exchange_code_for_token(code: str, return_refresh_token: bool) -> dict: ...
def validate_token(already_updated_from_cache: bool = False) -> bool: ...Methods:
login(): Initiates the complete OAuth login processlogout(): Clears current connection state and credentialsoauth(): Runs the OAuth authentication processgrab_access_token(): Refreshes the current access token using refresh tokengrab_refresh_token(): Obtains a new refresh tokengrab_url(): Builds the OAuth authorization URL for manual authenticationexchange_code_for_token(): Exchanges authorization code for access and refresh tokensvalidate_token(): Validates whether the current tokens are valid or expiredMethods for retrieving real-time and historical market data, instrument searches, and market information.
def get_quotes(instruments: List[str]) -> Dict: ...
def get_price_history(symbol: str, period_type: str = None, period: int = None, start_date: str = None, end_date: str = None, frequency_type: str = None, frequency: int = None, extended_hours: bool = True) -> Dict: ...
def search_instruments(symbol: str, projection: str) -> Dict: ...
def get_instruments(cusip: str) -> Dict: ...
def get_market_hours(markets: List[str], date: str = None) -> Dict: ...
def get_movers(market: str, direction: str, change: str) -> Dict: ...
def get_options_chain(option_chain) -> Dict: ...Methods:
get_quotes(): Gets real-time quotes for specified instrumentsget_price_history(): Retrieves historical price data with flexible time ranges and frequenciessearch_instruments(): Searches the instrument database by symbol and projection typeget_instruments(): Gets instrument details by CUSIP identifierget_market_hours(): Returns market hours for specified markets and datesget_movers(): Gets market movers data filtered by market, direction, and change typeget_options_chain(): Retrieves option chain data using OptionChain builder objectMethods for accessing account information, balances, positions, and transaction history.
def get_accounts(account: str = None, fields: List[str] = None) -> Dict: ...
def get_transactions(account: str, transaction_type: str = None, symbol: str = None, start_date: str = None, end_date: str = None, transaction_id: str = None) -> Dict: ...Methods:
get_accounts(): Gets account information with optional field filteringget_transactions(): Retrieves account transactions with various filtering optionsMethods for managing user preferences, subscription keys, and principal information.
def get_preferences(account: str) -> Dict: ...
def get_streamer_subscription_keys(accounts: List[str]) -> Dict: ...
def get_user_principals(fields: List[str] = None) -> Dict: ...
def update_preferences(account: str, data_payload: Dict) -> Dict: ...Methods:
get_preferences(): Gets user preferences for specified accountget_streamer_subscription_keys(): Gets streaming subscription keys for accountsget_user_principals(): Gets user principal details with optional field filteringupdate_preferences(): Updates user preferences with provided dataMethods for creating, reading, updating, and deleting watchlists associated with accounts.
def create_watchlist(account: str, name: str, watchlistItems: List[Dict]) -> Dict: ...
def get_watchlist_accounts(account: str) -> Dict: ...
def get_watchlist(account: str, watchlist_id: str) -> Dict: ...
def delete_watchlist(account: str, watchlist_id: str) -> Dict: ...
def update_watchlist(account: str, watchlist_id: str, name: str, watchlistItems: List[Dict]) -> Dict: ...
def replace_watchlist(account: str, watchlist_id_new: str, watchlist_id_old: str, name_new: str, watchlistItems_new: List[Dict]) -> Dict: ...Methods:
create_watchlist(): Creates a new watchlist with specified itemsget_watchlist_accounts(): Gets all watchlists for an accountget_watchlist(): Gets a specific watchlist by IDdelete_watchlist(): Deletes a watchlist by IDupdate_watchlist(): Updates an existing watchlist's name and itemsreplace_watchlist(): Replaces one watchlist with anotherMethods for placing, modifying, canceling, and retrieving orders and saved orders.
def get_orders_path(account: str, max_results: int = None, from_entered_time: str = None, to_entered_time: str = None, status: str = None) -> Dict: ...
def get_orders_query(account: str, max_results: int = None, from_entered_time: str = None, to_entered_time: str = None, status: str = None) -> Dict: ...
def get_orders(account: str, order_id: str = None) -> Dict: ...
def cancel_order(account: str, order_id: str) -> Dict: ...
def place_order(account: str, order: Dict) -> Dict: ...
def modify_order(account: str, order: Dict, order_id: str) -> Dict: ...
def get_saved_order(account: str, saved_order_id: str = None) -> Dict: ...
def cancel_saved_order(account: str, saved_order_id: str) -> Dict: ...
def create_saved_order(account: str, saved_order: Dict) -> Dict: ...Methods:
get_orders_path(): Gets orders for account using path-based parametersget_orders_query(): Gets orders for account using query parametersget_orders(): Gets specific orders by ID or all orders if no ID providedcancel_order(): Cancels an existing order by IDplace_order(): Places a new order using Order object or dictionarymodify_order(): Modifies an existing orderget_saved_order(): Gets saved orders by ID or all saved orderscancel_saved_order(): Cancels a saved order by IDcreate_saved_order(): Creates a new saved orderMethod for creating streaming sessions that work with the TDStreamerClient.
def create_streaming_session() -> 'TDStreamerClient': ...Methods:
create_streaming_session(): Creates and returns a configured TDStreamerClient instancefrom td.client import TDClient
# Initialize and authenticate
client = TDClient(
client_id='your_client_id',
redirect_uri='http://localhost:8080/callback'
)
client.login()
# Get real-time quotes
quotes = client.get_quotes(['AAPL', 'MSFT', 'TSLA'])
# Get historical data
history = client.get_price_history(
symbol='AAPL',
period_type='year',
period=1,
frequency_type='daily',
frequency=1
)# Get account information
accounts = client.get_accounts(fields=['positions', 'orders'])
# Get account transactions
transactions = client.get_transactions(
account='123456789',
start_date='2023-01-01',
end_date='2023-12-31'
)
# Get current orders
orders = client.get_orders(account='123456789')from td.option_chain import OptionChain
# Build option chain request
option_chain = OptionChain()
option_chain.add_chain_key('symbol', 'AAPL')
option_chain.add_chain_key('contractType', 'CALL')
option_chain.add_chain_key('range', 'ITM')
# Get option chain data
chain_data = client.get_options_chain(option_chain)
# Search for instruments
instruments = client.search_instruments('AAPL', 'symbol-search')
# Get market movers
movers = client.get_movers('$SPX.X', 'up', 'percent')Install with Tessl CLI
npx tessl i tessl/pypi-td-ameritrade-python-api