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

utilities.mddocs/

0

# Utilities and Helpers

1

2

The utilities module provides helper classes and functions for path management, date/time conversions, option chain building, watchlist management, and streaming message parsing. These utilities support the core functionality of the TD Ameritrade API client.

3

4

## Core Imports

5

6

```python

7

from td.utils import StatePath, TDUtilities

8

from td.option_chain import OptionChain

9

from td.watchlist_item import WatchlistItem

10

from td.message import StreamingMessage, StreamingMessageComponent

11

```

12

13

## Capabilities

14

15

### StatePath Class

16

17

Path management utility for handling credentials storage, settings files, and library configuration directories.

18

19

```python { .api }

20

class StatePath:

21

def __init__(self, file_path: str = None) -> None: ...

22

@property

23

def get_file_path(self) -> str: ...

24

def path_home(self) -> str: ...

25

@property

26

def home_directory(self) -> str: ...

27

@property

28

def library_directory(self) -> str: ...

29

@property

30

def settings_directory(self) -> str: ...

31

def json_settings_path(self) -> str: ...

32

def json_library_path(self) -> str: ...

33

@property

34

def does_credentials_file_exist(self) -> bool: ...

35

def write_to_settings(self, state: Dict) -> None: ...

36

def write_credentials(self, file_path: str, state: Dict) -> None: ...

37

def read_credentials(self, file_path: str) -> Dict: ...

38

def delete_credentials(self, file_path: str) -> None: ...

39

def define_settings_location(self, location_id: str, location: str) -> None: ...

40

```

41

42

**Methods:**

43

- `get_file_path`: Returns the current file path being managed

44

- `path_home()`: Gets the user's home directory path

45

- `home_directory`: Property returning user home directory

46

- `library_directory`: Property returning library-specific directory

47

- `settings_directory`: Property returning settings directory path

48

- `json_settings_path()`: Returns path for JSON settings file

49

- `json_library_path()`: Returns path for JSON library configuration file

50

- `does_credentials_file_exist`: Property checking if credentials file exists

51

- `write_to_settings()`: Writes data to the settings folder

52

- `write_credentials()`: Writes credential data to specified file

53

- `read_credentials()`: Reads credential data from file

54

- `delete_credentials()`: Deletes credential file

55

- `define_settings_location()`: Sets custom location for settings storage

56

57

### TDUtilities Class

58

59

Date and time conversion utilities for working with TD Ameritrade API timestamp formats.

60

61

```python { .api }

62

class TDUtilities:

63

@staticmethod

64

def milliseconds_since_epoch(dt_object) -> int: ...

65

@staticmethod

66

def datetime_from_milliseconds_since_epoch(ms_since_epoch: int, timezone: str = None) -> datetime: ...

67

```

68

69

**Methods:**

70

- `milliseconds_since_epoch()`: Converts datetime object to milliseconds since Unix epoch

71

- `datetime_from_milliseconds_since_epoch()`: Converts milliseconds to datetime object with optional timezone

72

73

### OptionChain Class

74

75

Helper class for building option chain API requests with proper parameter validation.

76

77

```python { .api }

78

class OptionChain:

79

def __init__(self) -> None: ...

80

def validate_chain(self) -> bool: ...

81

def add_chain_key(self, key_name: str, key_value: str) -> None: ...

82

@property

83

def query_parameters(self) -> Dict: ...

84

```

85

86

**Methods:**

87

- `validate_chain()`: Validates current option chain parameters

88

- `add_chain_key()`: Adds a parameter key-value pair to the chain request

89

- `query_parameters`: Property returning dictionary of query parameters for API request

90

91

### WatchlistItem Class

92

93

Helper class for building watchlist items with proper validation for watchlist API requests.

94

95

```python { .api }

96

class WatchlistItem:

97

def __init__(self) -> None: ...

98

def validate_watchlist(self, keyword_args: Dict) -> bool: ...

99

def create_watchlist_json(self) -> str: ...

100

```

101

102

**Methods:**

103

- `validate_watchlist()`: Validates watchlist parameters using keyword arguments

104

- `create_watchlist_json()`: Creates properly formatted JSON string for watchlist API requests

105

106

### StreamingMessage Class

107

108

Parser for streaming WebSocket messages from TD Ameritrade streaming services.

109

110

```python { .api }

111

class StreamingMessage:

112

def __init__(self) -> None: ...

113

def parse(self, message: str) -> None: ...

114

def set_components(self) -> None: ...

115

@property

116

def components_count(self) -> int: ...

117

@property

118

def is_data_response(self) -> bool: ...

119

@property

120

def is_subscription_response(self) -> bool: ...

121

```

122

123

**Methods:**

124

- `parse()`: Parses raw JSON string message from streaming WebSocket

125

- `set_components()`: Converts parsed responses to component objects

126

- `components_count`: Property returning number of message components

127

- `is_data_response`: Property indicating if message contains data

128

- `is_subscription_response`: Property indicating if message is subscription confirmation

129

130

### StreamingMessageComponent Class

131

132

Individual component within a streaming message, representing a single data item or service response.

133

134

```python { .api }

135

class StreamingMessageComponent:

136

def __init__(self) -> None: ...

137

@property

138

def service(self) -> str: ...

139

def time_recieved(self, as_datetime: bool = False): ...

140

@property

141

def command(self) -> str: ...

142

@property

143

def content(self) -> Dict: ...

144

@property

145

def content_count(self) -> int: ...

146

```

147

148

**Methods:**

149

- `service`: Property returning the streaming service name for this component

150

- `time_recieved()`: Returns time message was received, optionally as datetime object

151

- `command`: Property returning the command type for this component

152

- `content`: Property returning the data content of this component

153

- `content_count`: Property returning number of content items in this component

154

155

## Usage Examples

156

157

### Path Management with StatePath

158

159

```python

160

from td.utils import StatePath

161

162

# Initialize path manager

163

path_manager = StatePath()

164

165

# Check if credentials exist

166

if path_manager.does_credentials_file_exist:

167

print("Credentials file found")

168

169

# Read existing credentials

170

credentials = path_manager.read_credentials(

171

path_manager.json_settings_path()

172

)

173

print(f"Loaded credentials for: {credentials.get('client_id')}")

174

else:

175

print("No credentials file found")

176

177

# Write new credentials

178

new_credentials = {

179

'client_id': 'your_client_id@AMER.OAUTHAP',

180

'access_token': 'your_access_token',

181

'refresh_token': 'your_refresh_token'

182

}

183

184

path_manager.write_credentials(

185

path_manager.json_settings_path(),

186

new_credentials

187

)

188

189

# Write to settings folder

190

settings_data = {

191

'default_account': '123456789',

192

'preferred_session': 'NORMAL'

193

}

194

path_manager.write_to_settings(settings_data)

195

196

# Custom settings location

197

path_manager.define_settings_location('custom', '/path/to/custom/settings')

198

```

199

200

### Date/Time Conversions with TDUtilities

201

202

```python

203

from td.utils import TDUtilities

204

from datetime import datetime, timezone

205

206

# Convert datetime to milliseconds (TD Ameritrade format)

207

now = datetime.now(timezone.utc)

208

ms_timestamp = TDUtilities.milliseconds_since_epoch(now)

209

print(f"Current time in milliseconds: {ms_timestamp}")

210

211

# Convert milliseconds back to datetime

212

converted_dt = TDUtilities.datetime_from_milliseconds_since_epoch(

213

ms_timestamp,

214

timezone='UTC'

215

)

216

print(f"Converted back: {converted_dt}")

217

218

# Use with TD Ameritrade API date parameters

219

start_date = datetime(2023, 1, 1, tzinfo=timezone.utc)

220

end_date = datetime(2023, 12, 31, tzinfo=timezone.utc)

221

222

start_ms = TDUtilities.milliseconds_since_epoch(start_date)

223

end_ms = TDUtilities.milliseconds_since_epoch(end_date)

224

225

# Use in price history request

226

price_history = client.get_price_history(

227

symbol='AAPL',

228

start_date=str(start_ms),

229

end_date=str(end_ms),

230

frequency_type='daily',

231

frequency=1

232

)

233

```

234

235

### Option Chain Building

236

237

```python

238

from td.option_chain import OptionChain

239

from td.enums import OPTION_CHAIN_STRATEGY, OPTION_CHAIN_RANGE

240

241

# Build basic option chain request

242

option_chain = OptionChain()

243

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

244

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

245

option_chain.add_chain_key('strategy', OPTION_CHAIN_STRATEGY.SINGLE)

246

247

# Validate the chain

248

if option_chain.validate_chain():

249

# Get the query parameters

250

params = option_chain.query_parameters

251

print(f"Option chain parameters: {params}")

252

253

# Use with client

254

chain_data = client.get_options_chain(option_chain)

255

else:

256

print("Invalid option chain parameters")

257

258

# Advanced option chain with multiple filters

259

advanced_chain = OptionChain()

260

advanced_chain.add_chain_key('symbol', 'SPY')

261

advanced_chain.add_chain_key('contractType', 'ALL')

262

advanced_chain.add_chain_key('strategy', OPTION_CHAIN_STRATEGY.ANALYTICAL)

263

advanced_chain.add_chain_key('range', OPTION_CHAIN_RANGE.ITM)

264

advanced_chain.add_chain_key('strikeCount', '10')

265

advanced_chain.add_chain_key('expMonth', 'ALL')

266

267

chain_data = client.get_options_chain(advanced_chain)

268

```

269

270

### Watchlist Management

271

272

```python

273

from td.watchlist_item import WatchlistItem

274

275

# Create watchlist item

276

watchlist_item = WatchlistItem()

277

278

# Validate watchlist parameters

279

watchlist_params = {

280

'symbol': 'AAPL',

281

'instrument_type': 'EQUITY',

282

'quantity': 100

283

}

284

285

if watchlist_item.validate_watchlist(watchlist_params):

286

# Create JSON for API request

287

watchlist_json = watchlist_item.create_watchlist_json()

288

print(f"Watchlist JSON: {watchlist_json}")

289

290

# Use with client watchlist methods

291

watchlist_data = client.create_watchlist(

292

account='123456789',

293

name='My Portfolio',

294

watchlistItems=[watchlist_json]

295

)

296

else:

297

print("Invalid watchlist parameters")

298

```

299

300

### Streaming Message Parsing

301

302

```python

303

from td.message import StreamingMessage, StreamingMessageComponent

304

305

# Initialize message parser

306

message_parser = StreamingMessage()

307

308

# Parse incoming streaming message

309

raw_message = '{"notify":[{"heartbeat":"1234567890"}]}'

310

message_parser.parse(raw_message)

311

312

# Process message components

313

message_parser.set_components()

314

315

print(f"Message has {message_parser.components_count} components")

316

print(f"Is data response: {message_parser.is_data_response}")

317

print(f"Is subscription response: {message_parser.is_subscription_response}")

318

319

# Access individual components

320

if message_parser.components_count > 0:

321

component = message_parser.components[0] # Access first component

322

323

print(f"Service: {component.service}")

324

print(f"Command: {component.command}")

325

print(f"Content: {component.content}")

326

print(f"Time received: {component.time_recieved(as_datetime=True)}")

327

print(f"Content count: {component.content_count}")

328

```

329

330

### Combined Utility Usage

331

332

```python

333

from td.utils import StatePath, TDUtilities

334

from td.option_chain import OptionChain

335

from datetime import datetime, timezone

336

337

# Initialize utilities

338

path_manager = StatePath()

339

option_builder = OptionChain()

340

341

# Read saved preferences

342

if path_manager.does_credentials_file_exist:

343

credentials = path_manager.read_credentials(

344

path_manager.json_settings_path()

345

)

346

347

# Create client with saved credentials

348

client = TDClient(

349

client_id=credentials['client_id'],

350

redirect_uri=credentials['redirect_uri'],

351

credentials_path=path_manager.json_settings_path()

352

)

353

client.login()

354

355

# Build option chain with date filtering

356

expiry_date = datetime(2024, 3, 15, tzinfo=timezone.utc)

357

expiry_ms = TDUtilities.milliseconds_since_epoch(expiry_date)

358

359

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

360

option_builder.add_chain_key('toDate', str(expiry_ms))

361

362

if option_builder.validate_chain():

363

options = client.get_options_chain(option_builder)

364

print(f"Retrieved {len(options)} option chains")

365

```

366

367

## Path Structure

368

369

The StatePath utility manages the following directory structure:

370

371

```

372

~/.td_python_api/

373

├── settings/

374

│ ├── config.json

375

│ └── preferences.json

376

└── credentials/

377

└── td_credentials.json

378

```

379

380

- **settings/**: General configuration and preferences

381

- **credentials/**: Secure storage for authentication tokens

382

- Custom locations can be defined using `define_settings_location()`