A python client library for the TD Ameritrade API.
npx @tessl/cli install tessl/pypi-td-ameritrade-python-api@0.3.00
# TD Ameritrade Python API
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: td-ameritrade-python-api
7
- **Language**: Python
8
- **Installation**: `pip install td-ameritrade-python-api`
9
- **Minimum Python Version**: 3.7+
10
11
## Core Imports
12
13
```python
14
from td.client import TDClient
15
from td.stream import TDStreamerClient
16
from td.orders import Order, OrderLeg
17
from td.enums import ORDER_SESSION, DURATION, ORDER_TYPE
18
from td.exceptions import TknExpError, ServerError
19
```
20
21
## Basic Usage
22
23
```python
24
from td.client import TDClient
25
26
# Initialize the client
27
td_client = TDClient(
28
client_id='your_client_id',
29
redirect_uri='http://localhost:8080/callback',
30
account_number='your_account_number'
31
)
32
33
# Login and authenticate
34
td_client.login()
35
36
# Get real-time quotes
37
quotes = td_client.get_quotes(['AAPL', 'MSFT', 'GOOGL'])
38
print(quotes)
39
40
# Get account information
41
accounts = td_client.get_accounts()
42
print(accounts)
43
44
# Get historical price data
45
price_history = td_client.get_price_history(
46
symbol='AAPL',
47
period_type='month',
48
period=6,
49
frequency_type='daily',
50
frequency=1
51
)
52
print(price_history)
53
```
54
55
## Architecture
56
57
The TD Ameritrade Python API is organized around several key components:
58
59
- **TDClient**: Main REST API client handling authentication and all HTTP-based endpoints
60
- **TDStreamerClient**: WebSocket client for real-time streaming data subscriptions
61
- **Order System**: Classes for building complex trade orders with multiple legs and strategies
62
- **Authentication**: OAuth 2.0 flow with both command-line and Flask-based options
63
- **Enums & Constants**: Comprehensive definitions for all API parameters and values
64
65
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.
66
67
## Capabilities
68
69
### Client API Operations
70
71
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.
72
73
```python { .api }
74
class TDClient:
75
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: ...
76
def login() -> None: ...
77
def get_quotes(instruments: List[str]) -> Dict: ...
78
def get_accounts(account: str = None, fields: List[str] = None) -> Dict: ...
79
def get_price_history(symbol: str, **kwargs) -> Dict: ...
80
```
81
82
[Client API](./client-api.md)
83
84
### Real-time Streaming
85
86
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.
87
88
```python { .api }
89
class TDStreamerClient:
90
def __init__(self, websocket_url: str, user_principal_data: Dict, credentials: Dict) -> None: ...
91
def stream(print_to_console: bool = True) -> None: ...
92
def level_one_quotes(symbols: List[str], fields: List[str] = None) -> None: ...
93
def level_two_quotes(symbols: List[str], fields: List[str] = None) -> None: ...
94
```
95
96
[Streaming](./streaming.md)
97
98
### Order Management
99
100
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.
101
102
```python { .api }
103
class Order:
104
def __init__(self) -> None: ...
105
def order_type(self, order_type: str) -> 'Order': ...
106
def add_order_leg(self, order_leg: 'OrderLeg') -> None: ...
107
108
class OrderLeg:
109
def __init__(self) -> None: ...
110
def order_leg_instruction(self, instruction: str) -> 'OrderLeg': ...
111
def order_leg_asset(self, asset_type: str, symbol: str) -> 'OrderLeg': ...
112
```
113
114
[Order Management](./order-management.md)
115
116
### Authentication
117
118
OAuth 2.0 authentication flow with support for both command-line and Flask-based workflows. Handles access tokens, refresh tokens, and credential storage.
119
120
```python { .api }
121
def run(flask_client, close_after: bool = True) -> None: ...
122
def shutdown_server() -> None: ...
123
124
class FlaskTDAuth:
125
def __init__(self, client_id: str, redirect_uri: str) -> None: ...
126
def authorization_url() -> str: ...
127
def grab_access_token_and_refresh_token(url: str) -> Dict: ...
128
```
129
130
[Authentication](./authentication.md)
131
132
### Enumerations and Constants
133
134
Comprehensive enums and constants for all API parameters, order types, asset types, market sessions, and field IDs. Essential for constructing valid API requests.
135
136
```python { .api }
137
class ORDER_SESSION:
138
NORMAL: str
139
AM: str
140
PM: str
141
SEAMLESS: str
142
143
class ORDER_TYPE:
144
MARKET: str
145
LIMIT: str
146
STOP: str
147
STOP_LIMIT: str
148
```
149
150
[Enums and Constants](./enums-constants.md)
151
152
### Utilities and Helpers
153
154
Utility classes for path management, date/time conversions, option chain building, watchlist management, and message parsing for streaming data.
155
156
```python { .api }
157
class StatePath:
158
def write_credentials(file_path: str, state: Dict) -> None: ...
159
def read_credentials(file_path: str) -> Dict: ...
160
161
class TDUtilities:
162
@staticmethod
163
def milliseconds_since_epoch(dt_object) -> int: ...
164
```
165
166
[Utilities](./utilities.md)
167
168
### Exception Handling
169
170
Custom exception classes for handling different types of API errors, including token expiration, rate limiting, forbidden access, and server errors.
171
172
```python { .api }
173
class TknExpError(Exception): ...
174
class ExdLmtError(Exception): ...
175
class ForbidError(Exception): ...
176
class ServerError(Exception): ...
177
```
178
179
[Exceptions](./exceptions.md)