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

streaming.mddocs/

0

# Real-time Streaming

1

2

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.

3

4

## Core Import

5

6

```python

7

from td.stream import TDStreamerClient

8

```

9

10

## Capabilities

11

12

### Client Initialization

13

14

Creates a streaming client instance configured with WebSocket URL, user credentials, and principal data obtained from the main TDClient.

15

16

```python { .api }

17

class TDStreamerClient:

18

def __init__(self, websocket_url: str, user_principal_data: Dict, credentials: Dict) -> None: ...

19

```

20

21

**Parameters:**

22

- `websocket_url`: WebSocket endpoint URL for streaming data

23

- `user_principal_data`: User principal information from TD Ameritrade API

24

- `credentials`: Authentication credentials for streaming connection

25

26

### Connection Management

27

28

Methods for managing the streaming connection, data pipeline, and output configuration.

29

30

```python { .api }

31

def stream(print_to_console: bool = True) -> None: ...

32

def close_stream() -> None: ...

33

def write_behavior(file_path: str, write: str = 'csv', append_mode: bool = True) -> None: ...

34

def build_pipeline() -> websockets.WebSocketClientProtocol: ...

35

def start_pipeline() -> dict: ...

36

def unsubscribe(service: str) -> dict: ...

37

def heartbeat() -> None: ...

38

def close_logic(logic_type: str) -> bool: ...

39

```

40

41

**Methods:**

42

- `stream()`: Starts the streaming connection with optional console output

43

- `close_stream()`: Closes the WebSocket connection and stops streaming

44

- `write_behavior()`: Configures CSV file output for streaming data with write mode and append settings

45

- `build_pipeline()`: Builds the data processing pipeline and returns WebSocket connection

46

- `start_pipeline()`: Starts receiving and processing streaming data, returns data from websocket

47

- `unsubscribe()`: Unsubscribes from a specific streaming service and returns status message

48

- `heartbeat()`: Sends heartbeat to server every 5 seconds to maintain connection

49

- `close_logic()`: Defines how the stream should close based on logic type (empty, market-hours)

50

51

### Service Configuration

52

53

Methods for configuring streaming service parameters and data quality settings.

54

55

```python { .api }

56

def quality_of_service(qos_level: str) -> None: ...

57

def chart(service: str, symbols: List[str], fields: List[str] = None) -> None: ...

58

def actives(service: str, venue: str, duration: str) -> None: ...

59

def account_activity() -> None: ...

60

def chart_history_futures(symbol: str, frequency: str, start_time: str, end_time: str, period: str = None) -> None: ...

61

```

62

63

**Methods:**

64

- `quality_of_service()`: Sets the quality of service level for streaming data

65

- `chart()`: Subscribes to chart data for specified symbols and fields

66

- `actives()`: Subscribes to active stocks data for venue and duration

67

- `account_activity()`: Subscribes to account activity notifications

68

- `chart_history_futures()`: Gets historical chart data for futures contracts

69

70

### Level 1 Data Subscriptions

71

72

Methods for subscribing to Level 1 market data across different asset classes.

73

74

```python { .api }

75

def level_one_quotes(symbols: List[str], fields: List[str] = None) -> None: ...

76

def level_one_options(symbols: List[str], fields: List[str] = None) -> None: ...

77

def level_one_futures(symbols: List[str], fields: List[str] = None) -> None: ...

78

def level_one_forex(symbols: List[str], fields: List[str] = None) -> None: ...

79

def level_one_futures_options(symbols: List[str], fields: List[str] = None) -> None: ...

80

```

81

82

**Methods:**

83

- `level_one_quotes()`: Subscribes to Level 1 equity quote data

84

- `level_one_options()`: Subscribes to Level 1 option quote data

85

- `level_one_futures()`: Subscribes to Level 1 futures quote data

86

- `level_one_forex()`: Subscribes to Level 1 forex quote data

87

- `level_one_futures_options()`: Subscribes to Level 1 futures options quote data

88

89

### Level 2 Data Subscriptions

90

91

Methods for subscribing to Level 2 market depth data with order book information.

92

93

```python { .api }

94

def level_two_quotes(symbols: List[str], fields: List[str] = None) -> None: ...

95

def level_two_options(symbols: List[str], fields: List[str] = None) -> None: ...

96

def level_two_nasdaq(symbols: List[str], fields: List[str] = None) -> None: ...

97

def level_two_total_view(symbols: List[str], fields: List[str] = None) -> None: ...

98

```

99

100

**Methods:**

101

- `level_two_quotes()`: Subscribes to Level 2 equity market depth data

102

- `level_two_options()`: Subscribes to Level 2 option market depth data

103

- `level_two_nasdaq()`: Subscribes to Level 2 NASDAQ market depth data

104

- `level_two_total_view()`: Subscribes to Level 2 total view market depth data

105

106

### Other Streaming Services

107

108

Additional streaming services for news and time-and-sales data.

109

110

```python { .api }

111

def news_headline(symbols: List[str], fields: List[str] = None) -> None: ...

112

def timesale(service: str, symbols: List[str], fields: List[str] = None) -> None: ...

113

```

114

115

**Methods:**

116

- `news_headline()`: Subscribes to news headline feeds for specified symbols

117

- `timesale()`: Subscribes to time and sales data for specified service and symbols

118

119

## Usage Examples

120

121

### Basic Streaming Setup

122

123

```python

124

from td.client import TDClient

125

from td.stream import TDStreamerClient

126

127

# Create and authenticate main client

128

client = TDClient(

129

client_id='your_client_id',

130

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

131

)

132

client.login()

133

134

# Create streaming session

135

streaming_client = client.create_streaming_session()

136

137

# Subscribe to Level 1 quotes

138

streaming_client.level_one_quotes(['AAPL', 'MSFT', 'GOOGL'])

139

140

# Start streaming with console output

141

streaming_client.stream(print_to_console=True)

142

```

143

144

### Advanced Streaming with File Output

145

146

```python

147

# Configure CSV file output

148

streaming_client.write_behavior(

149

file_path='market_data.csv',

150

write=True,

151

append_mode=True

152

)

153

154

# Subscribe to multiple data types

155

streaming_client.level_one_quotes(['AAPL', 'MSFT'], fields=['0', '1', '2', '3'])

156

streaming_client.level_two_quotes(['AAPL'], fields=['0', '1', '2'])

157

streaming_client.news_headline(['AAPL', 'MSFT'])

158

159

# Set quality of service

160

streaming_client.quality_of_service('2')

161

162

# Start streaming without console output

163

streaming_client.stream(print_to_console=False)

164

```

165

166

### Options and Futures Streaming

167

168

```python

169

# Subscribe to options data

170

streaming_client.level_one_options(['AAPL_021724C150', 'AAPL_021724P150'])

171

172

# Subscribe to futures data

173

streaming_client.level_one_futures(['/ES', '/NQ', '/YM'])

174

175

# Subscribe to forex data

176

streaming_client.level_one_forex(['EUR/USD', 'GBP/USD'])

177

178

# Subscribe to active stocks

179

streaming_client.actives('ACTIVES_NASDAQ', 'NASDAQ', '60')

180

181

# Start streaming

182

streaming_client.stream()

183

```

184

185

### Account Activity Monitoring

186

187

```python

188

# Subscribe to account activity

189

streaming_client.account_activity()

190

191

# Subscribe to Level 1 quotes for portfolio monitoring

192

portfolio_symbols = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA']

193

streaming_client.level_one_quotes(portfolio_symbols)

194

195

# Start streaming with file output

196

streaming_client.write_behavior('portfolio_data.csv', True, True)

197

streaming_client.stream()

198

```

199

200

### Service Management

201

202

```python

203

# Build and start pipeline manually

204

streaming_client.build_pipeline()

205

streaming_client.start_pipeline()

206

207

# Unsubscribe from specific services

208

streaming_client.unsubscribe('LEVELONE_EQUITIES')

209

streaming_client.unsubscribe('NEWS_HEADLINE')

210

211

# Close streaming connection

212

streaming_client.close_stream()

213

```

214

215

## Field IDs and Data Formats

216

217

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

218

219

- **Level 1 Equity Fields**: '0' (symbol), '1' (bid price), '2' (ask price), '3' (last price), '4' (bid size), '5' (ask size), '6' (total volume)

220

- **Level 2 Fields**: '0' (symbol), '1' (time), '2' (bid/ask data)

221

- **News Fields**: '0' (symbol), '1' (headline), '2' (story time)

222

223

Refer to the enums module for complete field ID mappings and valid parameter values for different streaming services.