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

utilities.mddocs/

Utilities and Helpers

The utilities module provides helper classes and functions for path management, date/time conversions, option chain building, watchlist management, and streaming message parsing. These utilities support the core functionality of the TD Ameritrade API client.

Core Imports

from td.utils import StatePath, TDUtilities
from td.option_chain import OptionChain
from td.watchlist_item import WatchlistItem
from td.message import StreamingMessage, StreamingMessageComponent

Capabilities

StatePath Class

Path management utility for handling credentials storage, settings files, and library configuration directories.

class StatePath:
    def __init__(self, file_path: str = None) -> None: ...
    @property
    def get_file_path(self) -> str: ...
    def path_home(self) -> str: ...
    @property
    def home_directory(self) -> str: ...
    @property
    def library_directory(self) -> str: ...
    @property
    def settings_directory(self) -> str: ...
    def json_settings_path(self) -> str: ...
    def json_library_path(self) -> str: ...
    @property
    def does_credentials_file_exist(self) -> bool: ...
    def write_to_settings(self, state: Dict) -> None: ...
    def write_credentials(self, file_path: str, state: Dict) -> None: ...
    def read_credentials(self, file_path: str) -> Dict: ...
    def delete_credentials(self, file_path: str) -> None: ...
    def define_settings_location(self, location_id: str, location: str) -> None: ...

Methods:

  • get_file_path: Returns the current file path being managed
  • path_home(): Gets the user's home directory path
  • home_directory: Property returning user home directory
  • library_directory: Property returning library-specific directory
  • settings_directory: Property returning settings directory path
  • json_settings_path(): Returns path for JSON settings file
  • json_library_path(): Returns path for JSON library configuration file
  • does_credentials_file_exist: Property checking if credentials file exists
  • write_to_settings(): Writes data to the settings folder
  • write_credentials(): Writes credential data to specified file
  • read_credentials(): Reads credential data from file
  • delete_credentials(): Deletes credential file
  • define_settings_location(): Sets custom location for settings storage

TDUtilities Class

Date and time conversion utilities for working with TD Ameritrade API timestamp formats.

class TDUtilities:
    @staticmethod
    def milliseconds_since_epoch(dt_object) -> int: ...
    @staticmethod
    def datetime_from_milliseconds_since_epoch(ms_since_epoch: int, timezone: str = None) -> datetime: ...

Methods:

  • milliseconds_since_epoch(): Converts datetime object to milliseconds since Unix epoch
  • datetime_from_milliseconds_since_epoch(): Converts milliseconds to datetime object with optional timezone

OptionChain Class

Helper class for building option chain API requests with proper parameter validation.

class OptionChain:
    def __init__(self) -> None: ...
    def validate_chain(self) -> bool: ...
    def add_chain_key(self, key_name: str, key_value: str) -> None: ...
    @property
    def query_parameters(self) -> Dict: ...

Methods:

  • validate_chain(): Validates current option chain parameters
  • add_chain_key(): Adds a parameter key-value pair to the chain request
  • query_parameters: Property returning dictionary of query parameters for API request

WatchlistItem Class

Helper class for building watchlist items with proper validation for watchlist API requests.

class WatchlistItem:
    def __init__(self) -> None: ...
    def validate_watchlist(self, keyword_args: Dict) -> bool: ...
    def create_watchlist_json(self) -> str: ...

Methods:

  • validate_watchlist(): Validates watchlist parameters using keyword arguments
  • create_watchlist_json(): Creates properly formatted JSON string for watchlist API requests

StreamingMessage Class

Parser for streaming WebSocket messages from TD Ameritrade streaming services.

class StreamingMessage:
    def __init__(self) -> None: ...
    def parse(self, message: str) -> None: ...
    def set_components(self) -> None: ...
    @property
    def components_count(self) -> int: ...
    @property
    def is_data_response(self) -> bool: ...
    @property
    def is_subscription_response(self) -> bool: ...

Methods:

  • parse(): Parses raw JSON string message from streaming WebSocket
  • set_components(): Converts parsed responses to component objects
  • components_count: Property returning number of message components
  • is_data_response: Property indicating if message contains data
  • is_subscription_response: Property indicating if message is subscription confirmation

StreamingMessageComponent Class

Individual component within a streaming message, representing a single data item or service response.

class StreamingMessageComponent:
    def __init__(self) -> None: ...
    @property
    def service(self) -> str: ...
    def time_recieved(self, as_datetime: bool = False): ...
    @property
    def command(self) -> str: ...
    @property
    def content(self) -> Dict: ...
    @property
    def content_count(self) -> int: ...

Methods:

  • service: Property returning the streaming service name for this component
  • time_recieved(): Returns time message was received, optionally as datetime object
  • command: Property returning the command type for this component
  • content: Property returning the data content of this component
  • content_count: Property returning number of content items in this component

Usage Examples

Path Management with StatePath

from td.utils import StatePath

# Initialize path manager
path_manager = StatePath()

# Check if credentials exist
if path_manager.does_credentials_file_exist:
    print("Credentials file found")
    
    # Read existing credentials
    credentials = path_manager.read_credentials(
        path_manager.json_settings_path()
    )
    print(f"Loaded credentials for: {credentials.get('client_id')}")
else:
    print("No credentials file found")

# Write new credentials
new_credentials = {
    'client_id': 'your_client_id@AMER.OAUTHAP',
    'access_token': 'your_access_token',
    'refresh_token': 'your_refresh_token'
}

path_manager.write_credentials(
    path_manager.json_settings_path(),
    new_credentials
)

# Write to settings folder
settings_data = {
    'default_account': '123456789',
    'preferred_session': 'NORMAL'
}
path_manager.write_to_settings(settings_data)

# Custom settings location
path_manager.define_settings_location('custom', '/path/to/custom/settings')

Date/Time Conversions with TDUtilities

from td.utils import TDUtilities
from datetime import datetime, timezone

# Convert datetime to milliseconds (TD Ameritrade format)
now = datetime.now(timezone.utc)
ms_timestamp = TDUtilities.milliseconds_since_epoch(now)
print(f"Current time in milliseconds: {ms_timestamp}")

# Convert milliseconds back to datetime
converted_dt = TDUtilities.datetime_from_milliseconds_since_epoch(
    ms_timestamp, 
    timezone='UTC'
)
print(f"Converted back: {converted_dt}")

# Use with TD Ameritrade API date parameters
start_date = datetime(2023, 1, 1, tzinfo=timezone.utc)
end_date = datetime(2023, 12, 31, tzinfo=timezone.utc)

start_ms = TDUtilities.milliseconds_since_epoch(start_date)
end_ms = TDUtilities.milliseconds_since_epoch(end_date)

# Use in price history request
price_history = client.get_price_history(
    symbol='AAPL',
    start_date=str(start_ms),
    end_date=str(end_ms),
    frequency_type='daily',
    frequency=1
)

Option Chain Building

from td.option_chain import OptionChain
from td.enums import OPTION_CHAIN_STRATEGY, OPTION_CHAIN_RANGE

# Build basic 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('strategy', OPTION_CHAIN_STRATEGY.SINGLE)

# Validate the chain
if option_chain.validate_chain():
    # Get the query parameters
    params = option_chain.query_parameters
    print(f"Option chain parameters: {params}")
    
    # Use with client
    chain_data = client.get_options_chain(option_chain)
else:
    print("Invalid option chain parameters")

# Advanced option chain with multiple filters
advanced_chain = OptionChain()
advanced_chain.add_chain_key('symbol', 'SPY')
advanced_chain.add_chain_key('contractType', 'ALL')
advanced_chain.add_chain_key('strategy', OPTION_CHAIN_STRATEGY.ANALYTICAL)
advanced_chain.add_chain_key('range', OPTION_CHAIN_RANGE.ITM)
advanced_chain.add_chain_key('strikeCount', '10')
advanced_chain.add_chain_key('expMonth', 'ALL')

chain_data = client.get_options_chain(advanced_chain)

Watchlist Management

from td.watchlist_item import WatchlistItem

# Create watchlist item
watchlist_item = WatchlistItem()

# Validate watchlist parameters
watchlist_params = {
    'symbol': 'AAPL',
    'instrument_type': 'EQUITY',
    'quantity': 100
}

if watchlist_item.validate_watchlist(watchlist_params):
    # Create JSON for API request
    watchlist_json = watchlist_item.create_watchlist_json()
    print(f"Watchlist JSON: {watchlist_json}")
    
    # Use with client watchlist methods
    watchlist_data = client.create_watchlist(
        account='123456789',
        name='My Portfolio',
        watchlistItems=[watchlist_json]
    )
else:
    print("Invalid watchlist parameters")

Streaming Message Parsing

from td.message import StreamingMessage, StreamingMessageComponent

# Initialize message parser
message_parser = StreamingMessage()

# Parse incoming streaming message
raw_message = '{"notify":[{"heartbeat":"1234567890"}]}'
message_parser.parse(raw_message)

# Process message components
message_parser.set_components()

print(f"Message has {message_parser.components_count} components")
print(f"Is data response: {message_parser.is_data_response}")
print(f"Is subscription response: {message_parser.is_subscription_response}")

# Access individual components
if message_parser.components_count > 0:
    component = message_parser.components[0]  # Access first component
    
    print(f"Service: {component.service}")
    print(f"Command: {component.command}")
    print(f"Content: {component.content}")
    print(f"Time received: {component.time_recieved(as_datetime=True)}")
    print(f"Content count: {component.content_count}")

Combined Utility Usage

from td.utils import StatePath, TDUtilities
from td.option_chain import OptionChain
from datetime import datetime, timezone

# Initialize utilities
path_manager = StatePath()
option_builder = OptionChain()

# Read saved preferences
if path_manager.does_credentials_file_exist:
    credentials = path_manager.read_credentials(
        path_manager.json_settings_path()
    )
    
    # Create client with saved credentials
    client = TDClient(
        client_id=credentials['client_id'],
        redirect_uri=credentials['redirect_uri'],
        credentials_path=path_manager.json_settings_path()
    )
    client.login()
    
    # Build option chain with date filtering
    expiry_date = datetime(2024, 3, 15, tzinfo=timezone.utc)
    expiry_ms = TDUtilities.milliseconds_since_epoch(expiry_date)
    
    option_builder.add_chain_key('symbol', 'AAPL')
    option_builder.add_chain_key('toDate', str(expiry_ms))
    
    if option_builder.validate_chain():
        options = client.get_options_chain(option_builder)
        print(f"Retrieved {len(options)} option chains")

Path Structure

The StatePath utility manages the following directory structure:

~/.td_python_api/
├── settings/
│   ├── config.json
│   └── preferences.json
└── credentials/
    └── td_credentials.json
  • settings/: General configuration and preferences
  • credentials/: Secure storage for authentication tokens
  • Custom locations can be defined using define_settings_location()

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