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

exceptions.mddocs/

Exception Handling

The TD Ameritrade Python API provides custom exception classes for handling different types of API errors and HTTP response codes. These exceptions help identify specific error conditions and enable appropriate error handling strategies.

Core Import

from td.exceptions import (
    TknExpError, ExdLmtError, NotNulError, 
    ForbidError, NotFndError, ServerError, GeneralError
)

Capabilities

Token Expiration Errors

Exception raised when access tokens have expired and need to be refreshed.

class TknExpError(Exception):
    def __init__(self, message: str) -> None: ...

Usage: Raised when API calls fail due to expired access tokens. Indicates that token refresh is required before retrying the request.

API Limit Exceeded Errors

Exception raised when API query limits or rate limits have been exceeded.

class ExdLmtError(Exception):
    def __init__(self, message: str) -> None: ...

Usage: Raised when the API returns rate limiting errors. Indicates that request frequency should be reduced or retry delays should be implemented.

Null Value Errors

Exception raised when null values are provided for required fields.

class NotNulError(Exception):
    def __init__(self, message: str) -> None: ...

Usage: Raised when API requests contain null or missing values for required parameters. Indicates that required fields need to be provided.

Forbidden Access Errors

Exception raised for HTTP 403 Forbidden responses indicating insufficient permissions.

class ForbidError(Exception):
    def __init__(self, message: str) -> None: ...

Usage: Raised when API calls are rejected due to insufficient permissions or unauthorized access. May indicate account permission restrictions or invalid authentication.

Resource Not Found Errors

Exception raised when requested resources or criteria are not found.

class NotFndError(Exception):
    def __init__(self, message: str) -> None: ...

Usage: Raised when API requests reference resources that don't exist, such as invalid account numbers, order IDs, or symbol names.

Server-side Errors

Exception raised for HTTP 500+ server errors indicating TD Ameritrade service issues.

class ServerError(Exception):
    def __init__(self, message: str) -> None: ...

Usage: Raised when TD Ameritrade API servers return internal server errors. Indicates temporary service issues that may resolve with retry attempts.

General HTTP Errors

Exception raised for general HTTP 400+ status codes not covered by specific exceptions.

class GeneralError(Exception):
    def __init__(self, message: str) -> None: ...

Usage: Raised for HTTP error responses that don't fall into other specific error categories. Provides general error handling for various API response codes.

Usage Examples

Basic Exception Handling

from td.client import TDClient
from td.exceptions import TknExpError, ForbidError, NotFndError

try:
    client = TDClient(
        client_id='your_client_id@AMER.OAUTHAP',
        redirect_uri='http://localhost:8080/callback'
    )
    client.login()
    
    # Get quotes
    quotes = client.get_quotes(['AAPL', 'MSFT'])
    print(quotes)
    
except TknExpError as e:
    print(f"Token expired: {e}")
    # Handle token refresh
    client.grab_access_token()
    
except ForbidError as e:
    print(f"Access forbidden: {e}")
    # Check account permissions or re-authenticate
    
except NotFndError as e:
    print(f"Resource not found: {e}")
    # Verify symbols or resource identifiers

Comprehensive Error Handling

from td.exceptions import *

def safe_api_call(client, operation, *args, **kwargs):
    """Wrapper function with comprehensive error handling"""
    try:
        return operation(*args, **kwargs)
        
    except TknExpError:
        print("Token expired, refreshing...")
        client.grab_access_token()
        # Retry the operation
        return operation(*args, **kwargs)
        
    except ExdLmtError:
        print("Rate limit exceeded, waiting...")
        import time
        time.sleep(60)  # Wait 1 minute
        return operation(*args, **kwargs)
        
    except ForbidError as e:
        print(f"Access forbidden: {e}")
        print("Check account permissions or authentication")
        return None
        
    except NotFndError as e:
        print(f"Resource not found: {e}")
        print("Verify the requested resource exists")
        return None
        
    except NotNulError as e:
        print(f"Required field missing: {e}")
        print("Provide all required parameters")
        return None
        
    except ServerError as e:
        print(f"Server error: {e}")
        print("TD Ameritrade service issue, try again later")
        return None
        
    except GeneralError as e:
        print(f"API error: {e}")
        print("General API error occurred")
        return None

# Usage
client = TDClient(client_id='...', redirect_uri='...')
client.login()

# Safe API calls
quotes = safe_api_call(client, client.get_quotes, ['AAPL', 'MSFT'])
accounts = safe_api_call(client, client.get_accounts)

Retry Logic with Exceptions

import time
from td.exceptions import TknExpError, ExdLmtError, ServerError

def retry_api_call(client, operation, max_retries=3, *args, **kwargs):
    """Retry API calls with exponential backoff"""
    for attempt in range(max_retries):
        try:
            return operation(*args, **kwargs)
            
        except TknExpError:
            print(f"Attempt {attempt + 1}: Token expired, refreshing...")
            client.grab_access_token()
            
        except ExdLmtError:
            wait_time = (2 ** attempt) * 60  # Exponential backoff
            print(f"Attempt {attempt + 1}: Rate limited, waiting {wait_time}s...")
            time.sleep(wait_time)
            
        except ServerError:
            wait_time = (2 ** attempt) * 30
            print(f"Attempt {attempt + 1}: Server error, waiting {wait_time}s...")
            time.sleep(wait_time)
            
        if attempt == max_retries - 1:
            print("Max retries exceeded")
            raise
            
    return None

# Usage with retry logic
try:
    quotes = retry_api_call(client, client.get_quotes, 3, ['AAPL', 'MSFT'])
    print(quotes)
except Exception as e:
    print(f"Failed after retries: {e}")

Order Placement Error Handling

from td.orders import Order, OrderLeg
from td.exceptions import NotNulError, ForbidError, GeneralError

def place_order_safely(client, account_id, order):
    """Safely place an order with proper error handling"""
    try:
        response = client.place_order(account_id, order)
        print(f"Order placed successfully: {response}")
        return response
        
    except NotNulError as e:
        print(f"Missing required order fields: {e}")
        print("Check that all order legs have required parameters")
        return None
        
    except ForbidError as e:
        print(f"Order rejected - insufficient permissions: {e}")
        print("Check account trading permissions")
        return None
        
    except GeneralError as e:
        print(f"Order rejected: {e}")
        print("Check order parameters and market conditions")
        return None

# Create and place order with error handling
order = Order()
order.order_type('LIMIT')
order.order_price(150.00)

leg = OrderLeg()
leg.order_leg_instruction('BUY')
leg.order_leg_asset('EQUITY', 'AAPL')
leg.order_leg_quantity(100)

order.add_order_leg(leg)

result = place_order_safely(client, '123456789', order)

Streaming Error Handling

from td.stream import TDStreamerClient
from td.exceptions import TknExpError, ServerError

def start_streaming_safely(client):
    """Start streaming with error handling"""
    try:
        streaming_client = client.create_streaming_session()
        streaming_client.level_one_quotes(['AAPL', 'MSFT'])
        streaming_client.stream()
        
    except TknExpError:
        print("Streaming authentication failed, refreshing tokens...")
        client.grab_access_token()
        # Recreate streaming session
        streaming_client = client.create_streaming_session()
        streaming_client.level_one_quotes(['AAPL', 'MSFT'])
        streaming_client.stream()
        
    except ServerError as e:
        print(f"Streaming server error: {e}")
        print("TD Ameritrade streaming service issue")
        
    except Exception as e:
        print(f"Streaming error: {e}")
        print("General streaming error occurred")

# Start streaming with error handling
start_streaming_safely(client)

Context Manager for Error Handling

from contextlib import contextmanager
from td.exceptions import TknExpError

@contextmanager
def td_api_session(client):
    """Context manager for TD API sessions with automatic token refresh"""
    try:
        yield client
    except TknExpError:
        print("Token expired during session, refreshing...")
        client.grab_access_token()
        yield client

# Usage with context manager
client = TDClient(client_id='...', redirect_uri='...')
client.login()

with td_api_session(client) as session:
    quotes = session.get_quotes(['AAPL'])
    accounts = session.get_accounts()
    orders = session.get_orders('123456789')

Error Response Codes

The exceptions map to specific HTTP response codes and TD Ameritrade API error conditions:

  • TknExpError: Token expiration (401 Unauthorized)
  • ExdLmtError: Rate limiting (429 Too Many Requests)
  • NotNulError: Missing required fields (400 Bad Request)
  • ForbidError: Insufficient permissions (403 Forbidden)
  • NotFndError: Resource not found (404 Not Found)
  • ServerError: Server issues (500+ Server Errors)
  • GeneralError: Other HTTP errors (400+ Client/Server Errors)

Best Practices

  1. Always handle TknExpError - Tokens expire regularly and need refresh
  2. Implement retry logic for ExdLmtError and ServerError conditions
  3. Validate inputs before API calls to prevent NotNulError and NotFndError
  4. Check account permissions when encountering ForbidError
  5. Use context managers for automatic error handling in sessions
  6. Log errors appropriately for debugging and monitoring
  7. Implement exponential backoff for rate limiting scenarios

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