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

client-api.mddocs/

Client API Operations

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.

Core Import

from td.client import TDClient

Capabilities

Client Initialization

Creates 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 registration
  • redirect_uri: The redirect URL specified in your TD Ameritrade application
  • account_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 multiprocessing

Authentication Methods

OAuth 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 process
  • logout(): Clears current connection state and credentials
  • oauth(): Runs the OAuth authentication process
  • grab_access_token(): Refreshes the current access token using refresh token
  • grab_refresh_token(): Obtains a new refresh token
  • grab_url(): Builds the OAuth authorization URL for manual authentication
  • exchange_code_for_token(): Exchanges authorization code for access and refresh tokens
  • validate_token(): Validates whether the current tokens are valid or expired

Market Data Methods

Methods 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 instruments
  • get_price_history(): Retrieves historical price data with flexible time ranges and frequencies
  • search_instruments(): Searches the instrument database by symbol and projection type
  • get_instruments(): Gets instrument details by CUSIP identifier
  • get_market_hours(): Returns market hours for specified markets and dates
  • get_movers(): Gets market movers data filtered by market, direction, and change type
  • get_options_chain(): Retrieves option chain data using OptionChain builder object

Account Methods

Methods 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 filtering
  • get_transactions(): Retrieves account transactions with various filtering options

User and Preferences Methods

Methods 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 account
  • get_streamer_subscription_keys(): Gets streaming subscription keys for accounts
  • get_user_principals(): Gets user principal details with optional field filtering
  • update_preferences(): Updates user preferences with provided data

Watchlist Methods

Methods 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 items
  • get_watchlist_accounts(): Gets all watchlists for an account
  • get_watchlist(): Gets a specific watchlist by ID
  • delete_watchlist(): Deletes a watchlist by ID
  • update_watchlist(): Updates an existing watchlist's name and items
  • replace_watchlist(): Replaces one watchlist with another

Order Management Methods

Methods 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 parameters
  • get_orders_query(): Gets orders for account using query parameters
  • get_orders(): Gets specific orders by ID or all orders if no ID provided
  • cancel_order(): Cancels an existing order by ID
  • place_order(): Places a new order using Order object or dictionary
  • modify_order(): Modifies an existing order
  • get_saved_order(): Gets saved orders by ID or all saved orders
  • cancel_saved_order(): Cancels a saved order by ID
  • create_saved_order(): Creates a new saved order

Streaming Methods

Method for creating streaming sessions that work with the TDStreamerClient.

def create_streaming_session() -> 'TDStreamerClient': ...

Methods:

  • create_streaming_session(): Creates and returns a configured TDStreamerClient instance

Usage Examples

Basic Authentication and Market Data

from 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
)

Account and Order Management

# 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')

Option Chain and Market Research

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

docs

authentication.md

client-api.md

enums-constants.md

exceptions.md

index.md

order-management.md

streaming.md

utilities.md

tile.json