or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdclient-api.mdenums-constants.mdexceptions.mdindex.mdorder-management.mdstreaming.mdutilities.md

client-api.mddocs/

0

# Client API Operations

1

2

The TDClient class is the main interface for interacting with TD Ameritrade's REST API. It handles OAuth authentication, session management, and provides methods for all major API endpoints including market data, account information, order management, and user preferences.

3

4

## Core Import

5

6

```python

7

from td.client import TDClient

8

```

9

10

## Capabilities

11

12

### Client Initialization

13

14

Creates a new TDClient instance with OAuth configuration and optional settings for credentials management and multiprocessing safety.

15

16

```python { .api }

17

class TDClient:

18

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: ...

19

```

20

21

**Parameters:**

22

- `client_id`: The Consumer ID assigned during TD Ameritrade app registration

23

- `redirect_uri`: The redirect URL specified in your TD Ameritrade application

24

- `account_number`: Your main TD Ameritrade account number (optional)

25

- `credentials_path`: Path to JSON credentials file (optional)

26

- `auth_flow`: Authentication flow type - 'default' for command-line or 'flask' for web-based

27

- `_do_init`: Whether to initialize configuration on creation

28

- `_multiprocessing_safe`: Enable thread-safe token caching for multiprocessing

29

30

### Authentication Methods

31

32

OAuth 2.0 authentication workflow methods for logging in, managing tokens, and handling session state.

33

34

```python { .api }

35

def login() -> bool: ...

36

def logout() -> None: ...

37

def oauth() -> None: ...

38

def grab_access_token() -> dict: ...

39

def grab_refresh_token() -> bool: ...

40

def grab_url() -> dict: ...

41

def exchange_code_for_token(code: str, return_refresh_token: bool) -> dict: ...

42

def validate_token(already_updated_from_cache: bool = False) -> bool: ...

43

```

44

45

**Methods:**

46

- `login()`: Initiates the complete OAuth login process

47

- `logout()`: Clears current connection state and credentials

48

- `oauth()`: Runs the OAuth authentication process

49

- `grab_access_token()`: Refreshes the current access token using refresh token

50

- `grab_refresh_token()`: Obtains a new refresh token

51

- `grab_url()`: Builds the OAuth authorization URL for manual authentication

52

- `exchange_code_for_token()`: Exchanges authorization code for access and refresh tokens

53

- `validate_token()`: Validates whether the current tokens are valid or expired

54

55

### Market Data Methods

56

57

Methods for retrieving real-time and historical market data, instrument searches, and market information.

58

59

```python { .api }

60

def get_quotes(instruments: List[str]) -> Dict: ...

61

def get_price_history(symbol: str, period_type: str = None, period: int = None, start_date: str = None, end_date: str = None, frequency_type: str = None, frequency: int = None, extended_hours: bool = True) -> Dict: ...

62

def search_instruments(symbol: str, projection: str) -> Dict: ...

63

def get_instruments(cusip: str) -> Dict: ...

64

def get_market_hours(markets: List[str], date: str = None) -> Dict: ...

65

def get_movers(market: str, direction: str, change: str) -> Dict: ...

66

def get_options_chain(option_chain) -> Dict: ...

67

```

68

69

**Methods:**

70

- `get_quotes()`: Gets real-time quotes for specified instruments

71

- `get_price_history()`: Retrieves historical price data with flexible time ranges and frequencies

72

- `search_instruments()`: Searches the instrument database by symbol and projection type

73

- `get_instruments()`: Gets instrument details by CUSIP identifier

74

- `get_market_hours()`: Returns market hours for specified markets and dates

75

- `get_movers()`: Gets market movers data filtered by market, direction, and change type

76

- `get_options_chain()`: Retrieves option chain data using OptionChain builder object

77

78

### Account Methods

79

80

Methods for accessing account information, balances, positions, and transaction history.

81

82

```python { .api }

83

def get_accounts(account: str = None, fields: List[str] = None) -> Dict: ...

84

def get_transactions(account: str, transaction_type: str = None, symbol: str = None, start_date: str = None, end_date: str = None, transaction_id: str = None) -> Dict: ...

85

```

86

87

**Methods:**

88

- `get_accounts()`: Gets account information with optional field filtering

89

- `get_transactions()`: Retrieves account transactions with various filtering options

90

91

### User and Preferences Methods

92

93

Methods for managing user preferences, subscription keys, and principal information.

94

95

```python { .api }

96

def get_preferences(account: str) -> Dict: ...

97

def get_streamer_subscription_keys(accounts: List[str]) -> Dict: ...

98

def get_user_principals(fields: List[str] = None) -> Dict: ...

99

def update_preferences(account: str, data_payload: Dict) -> Dict: ...

100

```

101

102

**Methods:**

103

- `get_preferences()`: Gets user preferences for specified account

104

- `get_streamer_subscription_keys()`: Gets streaming subscription keys for accounts

105

- `get_user_principals()`: Gets user principal details with optional field filtering

106

- `update_preferences()`: Updates user preferences with provided data

107

108

### Watchlist Methods

109

110

Methods for creating, reading, updating, and deleting watchlists associated with accounts.

111

112

```python { .api }

113

def create_watchlist(account: str, name: str, watchlistItems: List[Dict]) -> Dict: ...

114

def get_watchlist_accounts(account: str) -> Dict: ...

115

def get_watchlist(account: str, watchlist_id: str) -> Dict: ...

116

def delete_watchlist(account: str, watchlist_id: str) -> Dict: ...

117

def update_watchlist(account: str, watchlist_id: str, name: str, watchlistItems: List[Dict]) -> Dict: ...

118

def replace_watchlist(account: str, watchlist_id_new: str, watchlist_id_old: str, name_new: str, watchlistItems_new: List[Dict]) -> Dict: ...

119

```

120

121

**Methods:**

122

- `create_watchlist()`: Creates a new watchlist with specified items

123

- `get_watchlist_accounts()`: Gets all watchlists for an account

124

- `get_watchlist()`: Gets a specific watchlist by ID

125

- `delete_watchlist()`: Deletes a watchlist by ID

126

- `update_watchlist()`: Updates an existing watchlist's name and items

127

- `replace_watchlist()`: Replaces one watchlist with another

128

129

### Order Management Methods

130

131

Methods for placing, modifying, canceling, and retrieving orders and saved orders.

132

133

```python { .api }

134

def get_orders_path(account: str, max_results: int = None, from_entered_time: str = None, to_entered_time: str = None, status: str = None) -> Dict: ...

135

def get_orders_query(account: str, max_results: int = None, from_entered_time: str = None, to_entered_time: str = None, status: str = None) -> Dict: ...

136

def get_orders(account: str, order_id: str = None) -> Dict: ...

137

def cancel_order(account: str, order_id: str) -> Dict: ...

138

def place_order(account: str, order: Dict) -> Dict: ...

139

def modify_order(account: str, order: Dict, order_id: str) -> Dict: ...

140

def get_saved_order(account: str, saved_order_id: str = None) -> Dict: ...

141

def cancel_saved_order(account: str, saved_order_id: str) -> Dict: ...

142

def create_saved_order(account: str, saved_order: Dict) -> Dict: ...

143

```

144

145

**Methods:**

146

- `get_orders_path()`: Gets orders for account using path-based parameters

147

- `get_orders_query()`: Gets orders for account using query parameters

148

- `get_orders()`: Gets specific orders by ID or all orders if no ID provided

149

- `cancel_order()`: Cancels an existing order by ID

150

- `place_order()`: Places a new order using Order object or dictionary

151

- `modify_order()`: Modifies an existing order

152

- `get_saved_order()`: Gets saved orders by ID or all saved orders

153

- `cancel_saved_order()`: Cancels a saved order by ID

154

- `create_saved_order()`: Creates a new saved order

155

156

### Streaming Methods

157

158

Method for creating streaming sessions that work with the TDStreamerClient.

159

160

```python { .api }

161

def create_streaming_session() -> 'TDStreamerClient': ...

162

```

163

164

**Methods:**

165

- `create_streaming_session()`: Creates and returns a configured TDStreamerClient instance

166

167

## Usage Examples

168

169

### Basic Authentication and Market Data

170

171

```python

172

from td.client import TDClient

173

174

# Initialize and authenticate

175

client = TDClient(

176

client_id='your_client_id',

177

redirect_uri='http://localhost:8080/callback'

178

)

179

client.login()

180

181

# Get real-time quotes

182

quotes = client.get_quotes(['AAPL', 'MSFT', 'TSLA'])

183

184

# Get historical data

185

history = client.get_price_history(

186

symbol='AAPL',

187

period_type='year',

188

period=1,

189

frequency_type='daily',

190

frequency=1

191

)

192

```

193

194

### Account and Order Management

195

196

```python

197

# Get account information

198

accounts = client.get_accounts(fields=['positions', 'orders'])

199

200

# Get account transactions

201

transactions = client.get_transactions(

202

account='123456789',

203

start_date='2023-01-01',

204

end_date='2023-12-31'

205

)

206

207

# Get current orders

208

orders = client.get_orders(account='123456789')

209

```

210

211

### Option Chain and Market Research

212

213

```python

214

from td.option_chain import OptionChain

215

216

# Build option chain request

217

option_chain = OptionChain()

218

option_chain.add_chain_key('symbol', 'AAPL')

219

option_chain.add_chain_key('contractType', 'CALL')

220

option_chain.add_chain_key('range', 'ITM')

221

222

# Get option chain data

223

chain_data = client.get_options_chain(option_chain)

224

225

# Search for instruments

226

instruments = client.search_instruments('AAPL', 'symbol-search')

227

228

# Get market movers

229

movers = client.get_movers('$SPX.X', 'up', 'percent')

230

```