A python client library for the TD Ameritrade API.
The TDStreamerClient provides WebSocket-based streaming capabilities for real-time market data, account activity, and news. It supports Level 1 and Level 2 market data for equities, options, futures, and forex, along with account activity monitoring and news headline streaming.
from td.stream import TDStreamerClientCreates a streaming client instance configured with WebSocket URL, user credentials, and principal data obtained from the main TDClient.
class TDStreamerClient:
def __init__(self, websocket_url: str, user_principal_data: Dict, credentials: Dict) -> None: ...Parameters:
websocket_url: WebSocket endpoint URL for streaming datauser_principal_data: User principal information from TD Ameritrade APIcredentials: Authentication credentials for streaming connectionMethods for managing the streaming connection, data pipeline, and output configuration.
def stream(print_to_console: bool = True) -> None: ...
def close_stream() -> None: ...
def write_behavior(file_path: str, write: str = 'csv', append_mode: bool = True) -> None: ...
def build_pipeline() -> websockets.WebSocketClientProtocol: ...
def start_pipeline() -> dict: ...
def unsubscribe(service: str) -> dict: ...
def heartbeat() -> None: ...
def close_logic(logic_type: str) -> bool: ...Methods:
stream(): Starts the streaming connection with optional console outputclose_stream(): Closes the WebSocket connection and stops streamingwrite_behavior(): Configures CSV file output for streaming data with write mode and append settingsbuild_pipeline(): Builds the data processing pipeline and returns WebSocket connectionstart_pipeline(): Starts receiving and processing streaming data, returns data from websocketunsubscribe(): Unsubscribes from a specific streaming service and returns status messageheartbeat(): Sends heartbeat to server every 5 seconds to maintain connectionclose_logic(): Defines how the stream should close based on logic type (empty, market-hours)Methods for configuring streaming service parameters and data quality settings.
def quality_of_service(qos_level: str) -> None: ...
def chart(service: str, symbols: List[str], fields: List[str] = None) -> None: ...
def actives(service: str, venue: str, duration: str) -> None: ...
def account_activity() -> None: ...
def chart_history_futures(symbol: str, frequency: str, start_time: str, end_time: str, period: str = None) -> None: ...Methods:
quality_of_service(): Sets the quality of service level for streaming datachart(): Subscribes to chart data for specified symbols and fieldsactives(): Subscribes to active stocks data for venue and durationaccount_activity(): Subscribes to account activity notificationschart_history_futures(): Gets historical chart data for futures contractsMethods for subscribing to Level 1 market data across different asset classes.
def level_one_quotes(symbols: List[str], fields: List[str] = None) -> None: ...
def level_one_options(symbols: List[str], fields: List[str] = None) -> None: ...
def level_one_futures(symbols: List[str], fields: List[str] = None) -> None: ...
def level_one_forex(symbols: List[str], fields: List[str] = None) -> None: ...
def level_one_futures_options(symbols: List[str], fields: List[str] = None) -> None: ...Methods:
level_one_quotes(): Subscribes to Level 1 equity quote datalevel_one_options(): Subscribes to Level 1 option quote datalevel_one_futures(): Subscribes to Level 1 futures quote datalevel_one_forex(): Subscribes to Level 1 forex quote datalevel_one_futures_options(): Subscribes to Level 1 futures options quote dataMethods for subscribing to Level 2 market depth data with order book information.
def level_two_quotes(symbols: List[str], fields: List[str] = None) -> None: ...
def level_two_options(symbols: List[str], fields: List[str] = None) -> None: ...
def level_two_nasdaq(symbols: List[str], fields: List[str] = None) -> None: ...
def level_two_total_view(symbols: List[str], fields: List[str] = None) -> None: ...Methods:
level_two_quotes(): Subscribes to Level 2 equity market depth datalevel_two_options(): Subscribes to Level 2 option market depth datalevel_two_nasdaq(): Subscribes to Level 2 NASDAQ market depth datalevel_two_total_view(): Subscribes to Level 2 total view market depth dataAdditional streaming services for news and time-and-sales data.
def news_headline(symbols: List[str], fields: List[str] = None) -> None: ...
def timesale(service: str, symbols: List[str], fields: List[str] = None) -> None: ...Methods:
news_headline(): Subscribes to news headline feeds for specified symbolstimesale(): Subscribes to time and sales data for specified service and symbolsfrom td.client import TDClient
from td.stream import TDStreamerClient
# Create and authenticate main client
client = TDClient(
client_id='your_client_id',
redirect_uri='http://localhost:8080/callback'
)
client.login()
# Create streaming session
streaming_client = client.create_streaming_session()
# Subscribe to Level 1 quotes
streaming_client.level_one_quotes(['AAPL', 'MSFT', 'GOOGL'])
# Start streaming with console output
streaming_client.stream(print_to_console=True)# Configure CSV file output
streaming_client.write_behavior(
file_path='market_data.csv',
write=True,
append_mode=True
)
# Subscribe to multiple data types
streaming_client.level_one_quotes(['AAPL', 'MSFT'], fields=['0', '1', '2', '3'])
streaming_client.level_two_quotes(['AAPL'], fields=['0', '1', '2'])
streaming_client.news_headline(['AAPL', 'MSFT'])
# Set quality of service
streaming_client.quality_of_service('2')
# Start streaming without console output
streaming_client.stream(print_to_console=False)# Subscribe to options data
streaming_client.level_one_options(['AAPL_021724C150', 'AAPL_021724P150'])
# Subscribe to futures data
streaming_client.level_one_futures(['/ES', '/NQ', '/YM'])
# Subscribe to forex data
streaming_client.level_one_forex(['EUR/USD', 'GBP/USD'])
# Subscribe to active stocks
streaming_client.actives('ACTIVES_NASDAQ', 'NASDAQ', '60')
# Start streaming
streaming_client.stream()# Subscribe to account activity
streaming_client.account_activity()
# Subscribe to Level 1 quotes for portfolio monitoring
portfolio_symbols = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA']
streaming_client.level_one_quotes(portfolio_symbols)
# Start streaming with file output
streaming_client.write_behavior('portfolio_data.csv', True, True)
streaming_client.stream()# Build and start pipeline manually
streaming_client.build_pipeline()
streaming_client.start_pipeline()
# Unsubscribe from specific services
streaming_client.unsubscribe('LEVELONE_EQUITIES')
streaming_client.unsubscribe('NEWS_HEADLINE')
# Close streaming connection
streaming_client.close_stream()The streaming API uses numeric field IDs to specify which data fields to receive. Common field IDs include:
Refer to the enums module for complete field ID mappings and valid parameter values for different streaming services.
Install with Tessl CLI
npx tessl i tessl/pypi-td-ameritrade-python-api