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

streaming.mddocs/

Real-time Streaming

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.

Core Import

from td.stream import TDStreamerClient

Capabilities

Client Initialization

Creates 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 data
  • user_principal_data: User principal information from TD Ameritrade API
  • credentials: Authentication credentials for streaming connection

Connection Management

Methods 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 output
  • close_stream(): Closes the WebSocket connection and stops streaming
  • write_behavior(): Configures CSV file output for streaming data with write mode and append settings
  • build_pipeline(): Builds the data processing pipeline and returns WebSocket connection
  • start_pipeline(): Starts receiving and processing streaming data, returns data from websocket
  • unsubscribe(): Unsubscribes from a specific streaming service and returns status message
  • heartbeat(): Sends heartbeat to server every 5 seconds to maintain connection
  • close_logic(): Defines how the stream should close based on logic type (empty, market-hours)

Service Configuration

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 data
  • chart(): Subscribes to chart data for specified symbols and fields
  • actives(): Subscribes to active stocks data for venue and duration
  • account_activity(): Subscribes to account activity notifications
  • chart_history_futures(): Gets historical chart data for futures contracts

Level 1 Data Subscriptions

Methods 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 data
  • level_one_options(): Subscribes to Level 1 option quote data
  • level_one_futures(): Subscribes to Level 1 futures quote data
  • level_one_forex(): Subscribes to Level 1 forex quote data
  • level_one_futures_options(): Subscribes to Level 1 futures options quote data

Level 2 Data Subscriptions

Methods 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 data
  • level_two_options(): Subscribes to Level 2 option market depth data
  • level_two_nasdaq(): Subscribes to Level 2 NASDAQ market depth data
  • level_two_total_view(): Subscribes to Level 2 total view market depth data

Other Streaming Services

Additional 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 symbols
  • timesale(): Subscribes to time and sales data for specified service and symbols

Usage Examples

Basic Streaming Setup

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

Advanced Streaming with File Output

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

Options and Futures Streaming

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

Account Activity Monitoring

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

Service Management

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

Field IDs and Data Formats

The streaming API uses numeric field IDs to specify which data fields to receive. Common field IDs include:

  • Level 1 Equity Fields: '0' (symbol), '1' (bid price), '2' (ask price), '3' (last price), '4' (bid size), '5' (ask size), '6' (total volume)
  • Level 2 Fields: '0' (symbol), '1' (time), '2' (bid/ask data)
  • News Fields: '0' (symbol), '1' (headline), '2' (story time)

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

docs

authentication.md

client-api.md

enums-constants.md

exceptions.md

index.md

order-management.md

streaming.md

utilities.md

tile.json