or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdclient-api.mdenums-constants.mdexceptions.mdindex.mdorder-management.mdstreaming.mdutilities.md
tile.json

tessl/pypi-td-ameritrade-python-api

A python client library for the TD Ameritrade API.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/td-ameritrade-python-api@0.3.x

To install, run

npx @tessl/cli install tessl/pypi-td-ameritrade-python-api@0.3.0

index.mddocs/

TD Ameritrade Python API

A 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.

Package Information

  • Package Name: td-ameritrade-python-api
  • Language: Python
  • Installation: pip install td-ameritrade-python-api
  • Minimum Python Version: 3.7+

Core Imports

from 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, ServerError

Basic Usage

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

Architecture

The TD Ameritrade Python API is organized around several key components:

  • TDClient: Main REST API client handling authentication and all HTTP-based endpoints
  • TDStreamerClient: WebSocket client for real-time streaming data subscriptions
  • Order System: Classes for building complex trade orders with multiple legs and strategies
  • Authentication: OAuth 2.0 flow with both command-line and Flask-based options
  • Enums & Constants: Comprehensive definitions for all API parameters and values

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.

Capabilities

Client API Operations

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: ...

Client API

Real-time Streaming

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: ...

Streaming

Order Management

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': ...

Order Management

Authentication

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: ...

Authentication

Enumerations and Constants

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: str

Enums and Constants

Utilities and Helpers

Utility 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: ...

Utilities

Exception Handling

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): ...

Exceptions