Skip to content

Commit c0528db

Browse files
committed
format, add option chain object, add more sample responses
1 parent f962ef3 commit c0528db

47 files changed

Lines changed: 64883 additions & 1769 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

samples/api_charts.py

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,21 @@
1515

1616
# Define a list of all valid periods
1717
valid_values = {
18-
'minute':{
19-
'day':[1, 2, 3, 4, 5, 10]
18+
'minute': {
19+
'day': [1, 2, 3, 4, 5, 10]
2020
},
21-
'daily':{
22-
'month':[1, 2, 3, 6],
23-
'year':[1, 2, 3, 5, 10, 15, 20],
24-
'ytd':[1]
21+
'daily': {
22+
'month': [1, 2, 3, 6],
23+
'year': [1, 2, 3, 5, 10, 15, 20],
24+
'ytd': [1]
2525
},
26-
'weekly':{
27-
'month':[1, 2, 3, 6],
28-
'year':[1, 2, 3, 5, 10, 15, 20],
29-
'ytd':[1]
26+
'weekly': {
27+
'month': [1, 2, 3, 6],
28+
'year': [1, 2, 3, 5, 10, 15, 20],
29+
'ytd': [1]
3030
},
31-
'monthly':{
32-
'year':[1, 2, 3, 5, 10, 15, 20]
31+
'monthly': {
32+
'year': [1, 2, 3, 5, 10, 15, 20]
3333
}
3434
}
3535

@@ -47,7 +47,7 @@
4747
possible_values = frequency_periods[frequency_period]
4848

4949
for value in possible_values:
50-
50+
5151
# Define the dynamic arguments - I want 5 DAYS of historical 1-minute bars.
5252
hist_periodType = frequency_period
5353
hist_period = value
@@ -56,9 +56,9 @@
5656

5757
# make the request
5858
historical_1_minute = TDSession.get_price_history(
59-
symbol=hist_symbol,
59+
symbol=hist_symbol,
6060
period_type=hist_periodType,
61-
period=hist_period,
61+
period=hist_period,
6262
frequency_type=hist_frequencyType,
6363
frequency=hist_frequency,
6464
extended_hours=hist_needExtendedHoursData
@@ -77,7 +77,8 @@
7777
# Define 300 days ago.
7878
today_ago = datetime.now() - timedelta(days=lookback_period)
7979

80-
# The TD API expects a timestamp in milliseconds. However, the timestamp() method only returns to seconds so multiply it by 1000.
80+
# The TD API expects a timestamp in milliseconds. However, the timestamp()
81+
# method only returns to seconds so multiply it by 1000.
8182
today_00 = str(int(round(today_00.timestamp() * 1000)))
8283
today_ago = str(int(round(today_ago.timestamp() * 1000)))
8384

@@ -92,7 +93,7 @@
9293

9394
# Make the request
9495
historical_custom = TDSession.get_price_history(
95-
symbol=hist_symbol,
96+
symbol=hist_symbol,
9697
period_type=hist_periodType,
9798
frequency_type=hist_frequencyType,
9899
start_date=hist_startDate,
@@ -103,4 +104,6 @@
103104

104105
# Grab the candle count.
105106
candle_count = len(historical_custom['candles'])
106-
print('For PERIOD TYPE {} with CUSTOM PERIOD {} you got {} candles.'.format(hist_periodType, lookback_period, candle_count))
107+
print('For PERIOD TYPE {} with CUSTOM PERIOD {} you got {} candles.'.format(
108+
hist_periodType, lookback_period, candle_count)
109+
)

samples/api_oauth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@
1111
)
1212

1313
# Login to the session
14-
TDSession.login()
14+
TDSession.login()

samples/api_orders.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,18 @@
5858
new_order.add_order_leg(order_leg=new_order_leg)
5959

6060
# Print it out so you can see it, normally this method is called by the TD API when using the td.client object.
61-
print("YOU HAVE {} ORDER(S) IN THE ORDER LEGS COLLECTION.".format(new_order.order_legs_count))
61+
print("YOU HAVE {} ORDER(S) IN THE ORDER LEGS COLLECTION.".format(
62+
new_order.order_legs_count)
63+
)
6264
print('-'*80)
6365

6466
# We could also add a copied order to our order leg collection.
6567
new_order.add_order_leg(order_leg=copied_order_leg)
6668

6769
# Print it out so we can see both now.
68-
print("YOU HAVE {} ORDER(S) IN THE ORDER LEGS COLLECTION.".format(new_order.order_legs_count))
70+
print("YOU HAVE {} ORDER(S) IN THE ORDER LEGS COLLECTION.".format(
71+
new_order.order_legs_count)
72+
)
6973
print('-'*80)
7074

7175

@@ -113,7 +117,10 @@
113117

114118

115119
# Define the ASSET to be traded - ENUM EXAMPLE -- SYMBOL MUST ALWAYS BE A STRING.
116-
child_order_leg.order_leg_asset(asset_type=ORDER_ASSET_TYPE.EQUITY, symbol='AMZN')
120+
child_order_leg.order_leg_asset(
121+
asset_type=ORDER_ASSET_TYPE.EQUITY,
122+
symbol='AMZN'
123+
)
117124

118125
# Define the ASSET to be traded - STRING EXAMPLE -- SYMBOL MUST ALWAYS BE A STRING.
119126
child_order_leg.order_leg_asset(asset_type='EQUITY', symbol='AMZN')
@@ -123,11 +130,15 @@
123130
child_order.add_order_leg(order_leg=child_order_leg)
124131

125132
# Display the count.
126-
print("YOU HAVE {} ORDER(S) IN THE ORDER LEGS COLLECTION.".format(child_order.order_legs_count))
133+
print("YOU HAVE {} ORDER(S) IN THE ORDER LEGS COLLECTION.".format(
134+
child_order.order_legs_count)
135+
)
127136
print('-'*80)
128137

129138
# Add the Child Order Strategy to the PARENT ORDER or in other words the order we created originally.
130139
new_order.add_child_order_strategy(child_order_strategy=child_order)
131140

132141
# Print it so the user can see all the info at once.
133-
print("YOU HAVE {} CHILD ORDER STRATEGIES IN THE CHILD ORDER STRATEGIES COLLECTION.".format(new_order.child_order_count))
142+
print("YOU HAVE {} CHILD ORDER STRATEGIES IN THE CHILD ORDER STRATEGIES COLLECTION.".format(
143+
new_order.child_order_count)
144+
)

samples/api_pipeline.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,18 @@
1818
# Level One Quote
1919
TDStreamingClient.level_one_quotes(
2020
symbols=["SPY", "IVV", "SDS", "SH"],
21-
fields=list(range(0,50))
21+
fields=list(range(0, 50))
2222
)
2323

2424
# Level One Option
2525
TDStreamingClient.level_one_futures(
2626
symbols=['/ES'],
27-
fields=list(range(0,42))
27+
fields=list(range(0, 42))
2828
)
2929

3030
# Data Pipeline function
31+
32+
3133
async def data_pipeline():
3234
"""
3335
This is an example of how to build a data pipeline,
@@ -59,10 +61,10 @@ async def data_pipeline():
5961

6062
# Keep going as long as we can recieve data.
6163
while True:
62-
64+
6365
# Start the Pipeline.
6466
data = await TDStreamingClient.start_pipeline()
65-
67+
6668
# Grab the Data, if there was any. Remember not every message will have `data.`
6769
if 'data' in data:
6870

@@ -77,7 +79,7 @@ async def data_pipeline():
7779

7880
print('-'*80)
7981
data_response_count += 1
80-
82+
8183
# If we get a heartbeat notice, let's increment our counter.
8284
elif 'notify' in data:
8385
print(data['notify'][0])
@@ -94,8 +96,8 @@ async def data_pipeline():
9496
# Once we have 5 heartbeats, let's close the stream. Make sure to break the while loop.
9597
# or else you will encounter an exception.
9698
if heartbeat_response_count == 3:
97-
await TDStreamingClient.close_stream()
98-
break
99+
await TDStreamingClient.close_stream()
100+
break
99101

100102
# Run the pipeline.
101103
asyncio.run(data_pipeline())

samples/api_regular.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646

4747
# `get_market_hours` Endpoint with multiple values
4848
market_hours_multi = TDSession.get_market_hours(
49-
markets=['EQUITY','FOREX'],
49+
markets=['EQUITY', 'FOREX'],
5050
date=datetime.today().isoformat()
5151
)
5252

@@ -72,25 +72,31 @@
7272
preference_data = TDSession.get_preferences(account='<ACCOUNT_NUMBER>')
7373

7474
# `get_subscription_keys` endpoint. Should not return an error
75-
streamer_keys = TDSession.get_streamer_subscription_keys(accounts=['<ACCOUNT_NUMBER>'])
75+
streamer_keys = TDSession.get_streamer_subscription_keys(
76+
accounts=['<ACCOUNT_NUMBER>']
77+
)
7678

7779
# `get_user_ principals` endpoint. Should not return an error.
78-
prinicpals_data = TDSession.get_user_principals(fields=['preferences', 'surrogateIds'])
80+
prinicpals_data = TDSession.get_user_principals(
81+
fields=['preferences', 'surrogateIds']
82+
)
7983

8084
# `get_transactions` Endpoint with single values
81-
transaction_data_single = TDSession.get_transactions(transaction_id='YOUR_TRANSACTION_ID')
85+
transaction_data_single = TDSession.get_transactions(
86+
transaction_id='YOUR_TRANSACTION_ID'
87+
)
8288

8389
# Option Chain Example
8490
opt_chain = {
85-
'symbol':'MSFT',
86-
'contractType':'CALL',
87-
'optionType':'S',
88-
'fromDate':'2020-04-01',
89-
'afterDate':'2020-05-01',
90-
'strikeCount':4,
91-
'includeQuotes':True,
92-
'range':'ITM',
93-
'strategy':'ANALYTICAL',
91+
'symbol': 'MSFT',
92+
'contractType': 'CALL',
93+
'optionType': 'S',
94+
'fromDate': '2020-04-01',
95+
'afterDate': '2020-05-01',
96+
'strikeCount': 4,
97+
'includeQuotes': True,
98+
'range': 'ITM',
99+
'strategy': 'ANALYTICAL',
94100
'volatility': 29.0
95101
}
96102

samples/api_streaming.py

Lines changed: 69 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import pprint
2+
23
from datetime import datetime
34
from datetime import timedelta
45
from td.client import TDClient
@@ -19,60 +20,111 @@
1920
# Set the data dump location
2021
TDStreamingClient.write_behavior(
2122
write='csv',
22-
file_path=r"../td-ameritrade-python-api/samples/raw_data.csv",
23+
file_path=r"../td-ameritrade-python-api/samples/raw_data.csv",
2324
append_mode=True
2425
)
2526

2627
# Account Activity
2728
TDStreamingClient.account_activity()
2829

2930
# Actives
30-
TDStreamingClient.actives(service='ACTIVES_NASDAQ', venue='NASDAQ', duration='ALL')
31+
TDStreamingClient.actives(
32+
service='ACTIVES_NASDAQ',
33+
venue='NASDAQ',
34+
duration='ALL'
35+
)
3136

3237
# Quality of Service
3338
TDStreamingClient.quality_of_service(qos_level='express')
3439

3540
# Level One Quote
36-
TDStreamingClient.level_one_quotes(symbols=["SPY", "IVV", "SDS", "SH", "SPXL", "SPXS", "SPXU", "SSO", "UPRO", "VOO"], fields=list(range(0,50)))
41+
TDStreamingClient.level_one_quotes(
42+
symbols=["SPY", "IVV", "SDS"],
43+
fields=list(range(0, 50))
44+
)
3745

3846
# Level One Option
39-
TDStreamingClient.level_one_options(symbols=['AAPL_040920C115'], fields=list(range(0,42)))
47+
TDStreamingClient.level_one_options(
48+
symbols=['AAPL_040920C115'],
49+
fields=list(range(0, 42))
50+
)
4051

4152
# Level One Futures
42-
TDStreamingClient.level_one_futures(symbols=['/CL'], fields = list(range(0,34)))
53+
TDStreamingClient.level_one_futures(
54+
symbols=['/CL'],
55+
fields=list(range(0, 34))
56+
)
4357

4458
# Level One Forex
45-
TDStreamingClient.level_one_forex(symbols=['EUR/USD'], fields=list(range(0,20)))
59+
TDStreamingClient.level_one_forex(
60+
symbols=['EUR/USD'],
61+
fields=list(range(0, 20))
62+
)
4663

4764
# Level One Futures Options
48-
TDStreamingClient.level_one_futures_options(symbols=['./EW2J20C2675'], fields=list(range(0,36)))
65+
TDStreamingClient.level_one_futures_options(
66+
symbols=['./EW2J20C2675'],
67+
fields=list(range(0, 36))
68+
)
4969

5070
# Charts Futures
51-
TDStreamingClient.chart(service='CHART_EQUITY', symbols=['AAPL','MSFT'], fields=[0,1,2,3,4,5,6,7])
71+
TDStreamingClient.chart(
72+
service='CHART_EQUITY',
73+
symbols=['AAPL', 'MSFT'],
74+
fields=[0, 1, 2, 3, 4, 5, 6, 7]
75+
)
5276

5377
# Chart History Futures
54-
TDStreamingClient.chart_history_futures(symbol = ['/ES'], frequency='m1', start_time='1586304000000', end_time='1586329200000')
78+
TDStreamingClient.chart_history_futures(
79+
symbol=['/ES'],
80+
frequency='m1',
81+
start_time='1586304000000',
82+
end_time='1586329200000'
83+
)
5584

5685
# Timesale - Equity
57-
TDStreamingClient.timesale(service='TIMESALE_EQUITY', symbols=['AAPL'], fields=[0, 1, 2, 3, 4])
86+
TDStreamingClient.timesale(
87+
service='TIMESALE_EQUITY',
88+
symbols=['AAPL'],
89+
fields=[0, 1, 2, 3, 4]
90+
)
5891

5992
# Timesale - Futures
60-
TDStreamingClient.timesale(service='TIMESALE_FUTURES', symbols=['/ES'], fields=[0, 1, 2, 3, 4])
93+
TDStreamingClient.timesale(
94+
service='TIMESALE_FUTURES',
95+
symbols=['/ES'],
96+
fields=[0, 1, 2, 3, 4]
97+
)
6198

6299
# News Headline
63-
TDStreamingClient.news_headline(symbols=['AAPL', 'SPY'], fields=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
100+
TDStreamingClient.news_headline(
101+
symbols=['AAPL', 'SPY'],
102+
fields=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
103+
)
64104

65105
# Level Two Quotes
66-
TDStreamingClient.level_two_quotes(symbols = ['IBM'], fields = [0,1,2])
106+
TDStreamingClient.level_two_quotes(
107+
symbols=['IBM'],
108+
fields=[0, 1, 2]
109+
)
67110

68111
# Level Two Options
69-
TDStreamingClient.level_two_options(symbols=['AAPL_040920C115'], fields = [0,1,2])
112+
TDStreamingClient.level_two_options(
113+
symbols=['AAPL_040920C115'],
114+
fields=[0, 1, 2]
115+
)
70116

71117
# Level Two NASQDAQ
72-
TDStreamingClient.level_two_nasdaq(symbols = ['MSFT'], fields = [0,1,2])
118+
TDStreamingClient.level_two_nasdaq(
119+
symbols=['MSFT'],
120+
fields=[0, 1, 2]
121+
)
73122

74-
# Level Two Total View
75-
TDStreamingClient.level_two_total_view(symbols = ['AAPL'], fields = ['0','1','2'])
123+
# Level Two Total View
124+
TDStreamingClient.level_two_total_view(
125+
symbols=['AAPL'],
126+
fields=['0', '1', '2']
127+
)
76128

77129
# Stream it.
78130
TDStreamingClient.stream()

0 commit comments

Comments
 (0)