-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtd_api.py
2194 lines (1599 loc) · 82 KB
/
td_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 08:23:24 2019
The MIT License
Copyright (c) 2018 Addison Lynch
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@author: LC
Based on areed1192 / td-ameritrade-python-api
Method Type Method Type Header Endpoint
Authentication Post Access Token POST None /oauth2/token
User Info and Get User Principals GET Bearer<token> /userprincipals
Preferennces Get Streamer Subs. Keys GET Bearer<token> /userprincipals/streamersubscriptionkeys
Get Preferences GET Bearer<token> /accounts/{accountId}/preferences
Update Preferences PUT Bearer<token>+application/json /accounts/{accountId}/preferences
Accounts Get Accounts GET Bearer<token> /accounts
Get Account GET Bearer<token> /accounts/{accountId}
Orders Get Order by Query GET Bearer<token> /orders
Get Order by Path GET Bearer<token> /accounts/{accountId}/orders
Get Order GET Bearer<token> /accounts/{accountId}/orders/{orderId}
Cancel Order DELETE Bearer<token> /accounts/{accountId}/orders/{orderId}
Place Order POST Bearer<token>+application/json /accounts/{accountId}/orders
Replace Order PUT Bearer<token>+application/json /accounts/{accountId}/orders/{orderId}
Saved Orders Get Saved Orders by Path GET Bearer<token> /accounts/{accountId}/
savedorders
Get Saved Order GET Bearer<token> /accounts/{accountId}/savedorders/{savedorderId}
Cancel Saved Order DELETE Bearer<token> /accounts/{accountId}/savedorders/{savedorderId}
Create Saved Order POST Bearer<token>+application/json /accounts/{accountId}/
savedorders
Replace Saved Order PUT Bearer<token>+application/json /accounts/{accountId}/savedorders/{savedorderId}
Transactions Get Transaction GET Bearer<token> /accounts/{accountId}/
transactions/
History Get Transactions GET Bearer<token> /accounts/{accountId}/
transactions/
Watchlist Get Multiple Accounts Watchlist GET Bearer<token> /accounts/watchlists
Get Single Account Watchlist GET Bearer<token> /accounts/{accountId}/
watchlists
Get Watchlist GET Bearer<token> /accounts/{accountId}/watchlists/{watchlistId}
Delete Watchlist DELETE Bearer<token> /accounts/{accountId}/watchlists/{watchlistId}
Create Watchlist POST Bearer<token>+application/json /accounts/{accountId}/
watchlists
Replace Watchlist PUT Bearer<token>+application/json /accounts/{accountId}/watchlists/{watchlistId}
Update Watchlist PATCH Bearer<token>+application/json /accounts/{accountId}/watchlists/{watchlistId}
Instruments Search Instruments GET Bearer<token> /instruments
Get Instrument GET Bearer<token> /instruments/{cusip}
Market Hours Get Hours for Multiple Markets GET Bearer<token> /marketdata/hours
Get Hours for a Single Market GET Bearer<token> /marketdata/{market}/hours
Movers Get Movers GET Bearer<token> /marketdata/{index}/movers
Option Chains Get Option Chain GET Bearer<token> /marketdata/chains
Price History Get Price History GET Bearer<token> /marketdata/{symbol}/
pricehistory
Quotes Get Quote GET Bearer<token> /marketdata/{symbol}/quotes
Get Quotes GET Bearer<token> /marketdata/quotes
"""
from datetime import datetime
import json
import requests
from td_authentication import TDAuthentication
def prepare_parameter_list(parameter_list = None):
'''
This prepares a parameter that is a list for an API request. If
the list contains more than one item uit will joint the list
using the "," delimiter. If only one itemis in the list then only
the first item will be returned.
NAME: parameter_list
DESC: A List of parameter values assigned to an argument.
TYPE: List
EXAMPLE:
Object.handle_list(parameter_list = ['MSFT', 'SQ'])
'''
# if more than one item, join.
if len(parameter_list) > 1:
parameter_list = ','.join(parameter_list)
else: # take the first item.
parameter_list = parameter_list[0]
return parameter_list
class TDApi():
'''
TD Ameritrade API Class.
Performs request to the TD Ameritrade API. Response in JSON format.
'''
def __init__(self, td_cfg):
'''
Initialize object with provided account info
Open Authentication object to have a valid access token for every request.
The following 2 lines create authentication object and run it.
It will be use in the headers method to send a valid token.
'''
self._auth = TDAuthentication(td_cfg)
#self._auth.authenticate()
if self._auth:
self.account_id = self.get_user_principals(fields=['preferences'])['primaryAccountId']
print(self.account_id)
print("TDAPI Initialized at:".ljust(50)+str(datetime.now()))
else:
print("Could not authenticate")
def __repr__(self):
'''
defines the string representation of our TD Ameritrade Class instance.
'''
# define the string representation
return str(self._auth)
#### User Info & Preferences
def get_preferences(self, account = None):
'''
Get's User Preferences for specific account
Documentation Link:
https://developer.tdameritrade.com/user-principal/apis/get/
accounts/%7BaccountTd%7D/preferences-0
NAME: account
DESC: The account number you wish to receive preference data for.
TYPE: String
EXAMPLES:
Object.get_preferences(account = 'MyAccountNumber')
'''
account = account or self.account_id
#define the endpoint
endpoint = f'/accounts/{account}/preferences'
#grab the original headers we have stored.
url, merged_headers = self._auth.headers(endpoint)
# return teh resposnse of the get request.
return requests.get(url=url, headers=merged_headers, verify = True, timeout = 10).json()
def get_streamer_subscription_keys(self, account = None):
'''
SubscriptionKey for provided accounts or default accounts.
Documentation Link:
https://developer.tdameritrade.com/user-principal/apis/get/
userprincipals/streamersubscriptionkeys-0
NAME: account
DESC: A list of account numbers you wish to receive a streamer key for.
TYPE: List<String>
EXAMPLES:
Object.get_streamer_subscription_keys(account = ['MyAccountNum1'])
Object.get_streamer_subscription_keys(account = ['MyAccountNum1', 'MyAccountNum2'])
'''
account = account or self.account_id
# becasue we have a list arguments, prep it for the request.
account = prepare_parameter_list(parameter_list = account)
#buid the params dictionary
data = {'accountIds':account}
# define the endpoint
endpoint = '/userprincipals/streamersubscriptionkeys'
# grab the original haders we have stored
url, merged_headers = self._auth.headers(endpoint)
#return the response of the get request
return requests.get(url = url, headers=merged_headers, params = data,
verify = True, timeout = 10).json()
def get_user_principals(self, fields = None):
'''
Returns User Principals details.
Documentation Link:
https://developer.tdameritrade.com/user-principal/
apis/get/userprincipals-0
NAME: fields
DESC: A comma separated String which allows one specify additional fields to return.
None of these fields are returned by default. Possible values in this String can be:
1. streamerSubscriptionKeys
2. streamerConnectionInfo
3. preferences
4. surrogateIds
TYPE: List<String>
EXAMPLES:
Object.get_user_principals(fields = ['preferences'])
Object.get_user_principals(fields = ['preferences', 'streamerConnectionInfo'])
'''
# because we have a list argumnent, prep it for the request
fields = prepare_parameter_list(parameter_list = fields)
#build the params dictionary
data = {'fields':fields}
# define teh endpoint
endpoint = '/userprincipals'
#grab the original header we have stored
url, merged_headers = self._auth.headers(endpoint)
#return the response of the get request.
return requests.get(url = url, headers=merged_headers, params = data,
verify = True, timeout = 10).json()
def update_preferences(self, account = None, data_payload = None):
'''
Update preferences for a specific account. Please note that the directOptionsRouting and
directEquityRouting values cannot be modified via this operation.
Documentation Link:
https://developers.tdameritrade.com/user-principals/apis/put/
accounts/%7BaccountId%7D/preferences-0
NAME: account
DESC: The account number you wish to update preferences for.
TYPE: String
NAME: dataPayload
DESC: A dictionary that provides all the keys you wish to update. It must contain the
following keys to be build.
"expressTrading": false,
"directOptionsRouting": false,
"directEquityRouting": false,
"defaultEquityOrderLegInstruction": "'BUY' or 'SELL' or 'BUY_TO_COVER'
or 'SELL_SHORT' or 'NONE'",
"defaultEquityOrderType": "'MARKET' or 'LIMIT' or 'STOP' or 'STOP_LIMIT'
or 'TRAILING_STOP' or 'MARKET_ON_CLOSE' or 'NONE'",
"defaultEquityOrderPriceLinkType": "'VALUE' or 'PERCENT' or 'NONE'",
"defaultEquityOrderDuration": "'DAY' or 'GOOD_TILL_CANCEL' or 'NONE'",
"defaultEquityOrderMarketSession": "'AM' or 'PM' or 'NORMAL' or 'SEAMLESS' or 'NONE'",
"defaultEquityQuantity": 0,
"mutualFundTaxLotMethod": "'FIFO' or 'LIFO' or 'HIGH_COST' or 'LOW_COST'
or 'MINIMUM_TAX' or 'AVERAGE_COST' or 'NONE'",
"optionTaxLotMethod": "'FIFO' or 'LIFO' or 'HIGH_COST' or 'LOW_COST' or 'MINIMUM_TAX'
or 'AVERAGE_COST' or 'NONE'",
"equityTaxLotMethod": "'FIFO' or 'LIFO' or 'HIGH_COST' or 'LOW_COST' or 'MINIMUM_TAX'
or 'AVERAGE_COST' or 'NONE'",
"defaultAdvancedToolLaunch": "'TA' or 'N' or 'Y' or 'TOS' or 'NONE' or 'CC2'",
"authTokenTimeout": "'FIFTY_FIVE_MINUTES' or 'TWO_HOURS' or 'FOUR_HOURS'
or 'EIGHT_HOURS'"
default:
Payload = {
"expressTrading": False,
"directOptionsRouting": False,
"directEquityRouting": False,
"defaultEquityOrderLegInstruction": 'NONE',
"defaultEquityOrderType": 'MARKET',
"defaultEquityOrderPriceLinkType": 'NONE',
"defaultEquityOrderDuration": 'DAY',
"defaultEquityOrderMarketSession": 'NORMAL',
"defaultEquityQuantity": 0,
"mutualFundTaxLotMethod": 'FIFO',
"optionTaxLotMethod": 'FIFO',
"equityTaxLotMethod": 'FIFO',
"defaultAdvancedToolLaunch": 'NONE',
"authTokenTimeout": 'FIFTY_FIVE_MINUTES'
}
TYPE: dictionary
EXAMPLES:
Object.update_preferences(account = 'MyAccountNumber', dataPayload = Payload)
'''
account = account or self.account_id
#define teh endpoint
endpoint = f'/accounts/{account}/preferences'
#grab the original headers we have stored
url, merged_headers = self._auth.headers(endpoint, mode = 'application/json')
# make the request
response = requests.put(url=url, headers = merged_headers, data = json.dumps(data_payload),
verify = True, timeout = 10)
if response.status_code == 204:
print("Preferences successfully updated.\n")
else:
print(response.content)
#### ACCOUNT
def get_accounts(self, account = None, fields = None):
'''
Account balances, positions, and orders for a specific account.
Account balances, positions, and orders for all linked accounts.
Serves as the mechanism to make a request to the "Get Accounts" and "Get Account" endpoint.
If one account is provided a "Get Account" request will be made and if more than one account
is provided then a "Get Accounts" request will be made.
Documentation Link: http://developer.tdameritrade.com/
account-access/apis
NAME: account
DESC: The account number you wish to receive data on. Default values is 'all'
which will return all accounts of the user.
TYPE: String
NAME: fields
DESC: Balances displayed by default, additional field can be added here by
adding position or orders.
TYPE = List<String>
EXAMPLE:
Object.get_accounts(account = 'all', fields = ['orders'])
Object.get_accounts(account = 'My AccountNumber', fields = ['orders', 'positions'])
'''
account = account or self.account_id
# because we have a listarguments prep it for request.
fields = prepare_parameter_list(parameter_list = fields)
#build a parameter dictionary
data = {'fields':fields}
#if all use '/accounts' else pass through the account number.
if account == 'all':
endpoint = '/accounts'
else:
endpoint = f'/accounts/{account}'
#grab the original headers we have stored.
url, merged_headers = self._auth.headers(endpoint)
#return the response of the get request.
return requests.get(url = url, headers = merged_headers, params = data,
verify = True, timeout = 10).json()
#### TRANSACTION HISTORY
def get_transactions(self, account = None, transaction_type = None, symbol = None,
start_date = None, end_date = None, transaction_id = None):
'''
Serves to make a request to the "Get Transactions" and "Get Transaction" Endpoint.
If one 'transaction_id'is provided a "Get Transaction" request will be made and if it is
not provided then a "Get Transactions"request will be made.
Documentation Link: https://developer.tdameritrade.com/transaction-history/apis
NAME: account
DESC: The account number you wish to recieve transactions for.
TYPE: string
NAME: transaction_type
DESC: The type of transaction. Only transactions with specified type will be returned. Valid
values are the following: ALL, TRADE, BUY_ONLY, SELL_ONLY, CASH_INOR_CASH_OUT,
CHECKING, DIVIDEND, INTEREST, ITHER, ADVISOR_FEES
TYPE: String
NAME: symbol
DESC: The symbol in the specified transaction. Only transactions with the specified
symbol will be returned.
TYPE: string
NAME: start_date
DESC: Only transactions after the start date (included) will be returned. Note: the Max date
range is one year. Valid ISO-8601 formats are: yyyy-MM-dd.
TYPE: String
NAME: end_date
DESC: Only transactions before the End Date (included) will be returned. Mote: the max date
range is one year. Valid ISO-8601 formats are: yyyy-MM-dd
TYPE: String
NAME: transaction_id
DESC: The transaction ID you wish to search. If this is specified a "Get transaction"request
is made. Should only be used if you wish to return one transaction.
TYPE: String
EXAMPLES:
Object.get_transactions(account = 'MyAccountNum', transaction_type = 'ALL',
start_date = '2019-01-31', end_date = '2019-04-28')
Object.get_transactions(account = 'MyAccountNum', transaction_type = 'ALL',
start_date = '2019-01-31')
Object.get_transactions(account = 'MyAccountNum', transaction_type = 'TRADE')
Object.get_transactions(transaction_id = 'MyTransactionID')
'''
#grab the original headers we have stored.
account = account or self.account_id
# if transaction_id is not made, it means will need to make a request
# to the get_transaction endpoint.
if transaction_id:
#define the endpoint:
endpoint = f'/accounts/{account}/transactions/{transaction_id}'
url, merged_headers = self._auth.headers(endpoint)
# return the response of the get request
return requests.get(url = url, headers=merged_headers,
verify = True, timeout = 10).json()
# if it isn't then we need to make a request to the get_transactions endpoint.
#build the params dictionary
data = {'type':transaction_type,
'symbol':symbol,
'startDate':start_date,
'endDate':end_date}
#define the endpoint
endpoint = f'/accounts/{account}/transactions'
url, merged_headers = self._auth.headers(endpoint)
# return the response of the get request
return requests.get(url= url, headers = merged_headers, params=data,
verify = True, timeout = 10).json()
#### WATCHLIST
def create_watchlist(self, account = None, name = None, watchlist_items = None):
'''
Create watchlist. This methos dows not verify that the symbol or asses type are valid.
Documentation Link:
https://developer.tdameritrade.com/watchlist/apis/post/accounts/%7BaccountId%7D/watchlist-0
NAME: account
DESC: The account number you wish to create the watchlist for.
TYPE: String
NAME: name
DESC: The name you want to give your wathclist.
TYPE: String
NAME: watchlistItems
DESC: A list of watchlistitems object.
TYPE: List<WatchListItems>
Full WatchListItem = {
"name": "string",
"watchlistItems": [
{
"quantity": 0,
"averagePrice": 0,
"commission": 0,
"purchasedDate": "DateParam\"",
"instrument": {
"symbol": "string",
"assetType": "'EQUITY' or
'OPTION' or
'MUTUAL_FUND'
or 'FIXED_INCOME'
or 'INDEX'"
}
}
]
}
EXAMPLES:
WatchlistItem =[{"instrument":{"symbol": "BLUE",
"assetType": 'EQUITY'},
{"instrument":{"symbol": "AAPL",
"assetType": 'EQUITY'}
}]
FullWatchListItem = [
{
"quantity": 100,
"averagePrice": 100,
"commission": 10,
"purchasedDate": "2020-03-12",
"instrument": {
"symbol": "AAPL",
"assetType": 'EQUITY'
}
}
]
Object.create_watchlist(account = 'MyAccountNum', name = 'MyWatchListName',
watchlistItems = WatchlistItem)
'''
#define the payload
payload = {"name": name, "watchlistItems": watchlist_items}
account = account or self.account_id
# define the endpoint
endpoint = f'/accounts/{account}/watchlists'
#grab the original headers we have stored.
url, merged_headers = self._auth.headers(endpoint, mode = 'application/json')
#make the request
response = requests.post(url = url, headers = merged_headers, data = json.dumps(payload),
verify = True, timeout = 10)
if response.status_code == 201:
print(f"Watchlist {name} was successfully created.\n")
else:
print(response.content)
def get_watchlist_accounts(self, account = None):
'''
Serves as the mechanism to make a request to the "Get Watchlist for single accoun"and
"Get Watchlist for Multiple Accounts"Endpoint. If one accountis provided a
"Get Watchlist for single account"request will be made and if 'all' is provided then a
"Get Watchlist for multipleAccounts"request will be made.
Documentation Link: https://developer.tdameritrade.com/watchlist/apis
NAME: account
DESC: The account number you wish to pull watchlists from. Default value is 'all'
TYPE: String
EXAMPLES:
Object.get_watchlist_accounts(account = 'all')
Object.get_watchlist_accounts(account = 'MyAccount1')
'''
account = account or self.account_id
#define the endpoint
if account == 'all':
endpoint = '/accounts/watchlists'
else:
endpoint = f'/accounts/{account}/watchlists'
# grab the original headers we have stored.
url, merged_headers = self._auth.headers(endpoint)
#Make the request
return requests.get(url = url, headers = merged_headers, verify = True, timeout = 10).json()
def get_watchlist(self, account = None, watchlist_id = None):
'''
Returns a specific watchlist for a specific account.
Documentation Link:
https://developer.tdameritrade.com/watchlist/apis/get/accounts/%7BaccountId%7D/
watchlists/%7BwatchlistId%7D-0
NAME: account
DESC: The account number you wish to pull watchlists from
TYPE: String
NAME: watchlist_id
DESC: The ID of the watchlist you wish to return.
TYPE: String
EXAMPLES:
Object.get_watchlist(account = 'MyAccount1', watchlist_id = 'MyWatchlistId')
'''
account = account or self.account_id
# define the endpoint
endpoint = f'/accounts/{account}/watchlists/{watchlist_id}'
#grab the original headers we have stored.
url, merged_headers = self._auth.headers(endpoint)
#make a request
return requests.get(url = url, headers = merged_headers, verify = True, timeout = 10).json()
def delete_watchlist(self, account = None, watchlist_id = None):
'''
Deletes a specific watchlist for a specific account.
Documentation Link
https://developer.tdameritrade.com/watchlist/apis/delete/accounts/%7BaccountId%7D/
watchlist/%7BwatchlistId&7D-0
NAME: account
DESC: The account number you wish to delete the watchlist from.
TYPE: String
NAME: watchlist_id
DESC: The ID of the watchlist you wish to delete.
TYPE: String
EXAMPLES:
Object.delete_watchlist(account = 'MyAccount1', watchlist_id = 'MyWatchlistId')
'''
account = account or self.account_id
#define the endpoint
endpoint = f'/accounts/{account}/watchlists/{watchlist_id}'
# grab the original headers we have stored.
url, merged_headers = self._auth.headers(endpoint)
#make teh request
response = requests.delete(url = url, headers = merged_headers, verify = True, timeout = 10)
if response.status_code == 204:
return print(f"Watchlist {watchlist_id} was successfully deleted.\n")
return print(response.content)
def update_watchlist(self, account = None, watchlist_id = None, name_new = None,
watchlist_items_to_add = None):
'''
Partially update watchlist for a sppecific account: change watchlis name, add the
beggining/end of a watchlist, update or delete items in a watchlist. This method does not
verify that the symbol or asset type are valid.
Documentation Link:
https://developer.tdameritrade.com/watchlist/apis/patch/accounts/%7BaccountId%7D/
watchlist/%7BwatchlistId%7D-0
NAME: account
DESC: The account number that containsteh watchlist you wich to update.
TYPE: STring
NAME: watchlist_id
DESC: The ID of the watchlistyou wish to update
TYPE: String
NAME: watchlistItems
DESC: A List of the original watchlist items you wish to update and their modified keys.
TYPE: List<WatchListItems>
EXAMPLES:
Session.Object.update_watchlist(account = 'MyAccountNumber',
watchlist_id = 'WatchListID',
watchlistItems = [WatchListItem1, WatchListItem2])
'''
# define the payload
payload = {"name": name_new, "watchlistItems": watchlist_items_to_add}
#define the endpoint
account = account or self.account_id
endpoint = f'/accounts/{account}/watchlists/{watchlist_id}'
#grab the original headers we have stored.
url, merged_headers = self._auth.headers(endpoint, mode = 'application/json')
#make a request
response = requests.patch(url = url, headers = merged_headers, data = json.dumps(payload),
verify = True, timeout = 10)
if response.status_code == 204:
return print(f"Watchlist {watchlist_id} was successfully updated.\n")
return print(response.content)
def replace_watchlist(self, account = None, watchlist_id = None, name_new = None,
watchlist_items_new = None):
'''
Replace watchlist for a specific account. This method does not verify that the symbol
or asset type are valid.
Documentation Link:
https://developer.tdameritrade.com/watchlist/apis/put/accounts/%7BaccountId%7D/
watchlists/%7BwatchlistId%7D-0
NAME: account
DESC: The account number that contains teh watchlist you wish to replace.
TYPE: String
NAME: watchlist_id
DESC: The ID of the watchlist you wish to replace.
TYPE: String
NAME: name_new
DESC: The name of teh new watchlist.
TYPE: String
NAME: watchlistItems_new
DESC: The new watchlistitems you wish to add to teh watchlist.
TYPE: List<WatchListItems>
EXAMPLES:
Session.Object.replace_watchlist(account = 'MyAccountNumber',
watchlist_id = 'WatchListID',
name_new = 'MyNewName',
watchlistItems_new = [WatchListItem1, WatchListItem2])
'''
# define the payload
payload = {"name": name_new, "watchlistItems": watchlist_items_new}
# define the endpoint
account = account or self.account_id
endpoint = f'/accounts/{account}/watchlists/{watchlist_id}'
# grab teh original headers we have stored.
url, merged_headers = self._auth.headers(endpoint, mode = 'application/json')
#make the request
response = requests.put(url = url, headers = merged_headers, data = json.dumps(payload),
verify = True, timeout = 10)
if response.status_code == 204:
return print(f"Watchlist {watchlist_id} was successfully repleaced.\n")
return print(response.content)
#### ORDERS
def get_orders_path(self, account = None, max_results = None, from_entered_time = None,
to_entered_time = None, status = None):
'''
Returns the savedorders for a specific account.
Documentation Link:
https://developer.tdameritrade.com/account-access/apis/get/accounts/%7BaccountId%7D/orders-0
NAME: account
DESC: The account number that you want to query for orders.
TYPE: String
NAME: max_results
DESC: The maximum nymber of orders to receive.
TYPE: integer
NAME: from_entered_time
DESC: Specifies that no orders entered before this time should be returned.
Valid ISO-8601 formats are : yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz
Date must be within 60 days from today's date. 'toEnteredTime' must also be set.
TYPE: string
NAME: to_entered_time
DESC: Specifies that no orders entered after this time should be returned.
Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz.
'fromEnteredTime' must also be set.
TYPE: String
NAME: status
DESC: Specifies that only orders of this status should be returned. Possible values are:
1. AWAITING_PARENT_ORDER
2. AWAITING_CONDITION
3. AWAITING_MANUAL_REVIEW
4. ACCEPTED
5. AWAITING_UR_NOT
6. PENDING_ACTIVATION
7. QUEUED
8. WORKING
9. REJECTED
10. PENDING_CANCEL
11. CANCELED
12. PENDING_REPLACE
13. REPLACED
14. FILLED
15. EXPIRED
EXAMPLES:
Object.get_orders_path(account = 'MyAccountID', max_result = 6,
from_entered_time = '2019-10-01', to_entered_tme = '2019-10-10)
Object.get_orders_path(account = 'MyAccountID', max_result = 6, status = 'EXPIRED')
Object.get_orders_path(account = 'MyAccountID', status ='REJECTED')
Object.get_orders_path(account = 'MyAccountID')
'''
# define the payload
data = {"maxResults": max_results, "fromEnteredTime": from_entered_time,
"toEnteredTime": to_entered_time, "status": status}
#define the endpoint
account = account or self.account_id
endpoint = f'/accounts/{account}/orders'
# grab the originbal headers we have stored.
url, merged_headers =self._auth.headers(endpoint)
#make the request
return requests.get(url=url, headers = merged_headers, params = data,
verify = True, timeout = 10).json()
def get_orders_query(self, account = None, max_results = None, from_entered_time = None,
to_entered_time = None, status = None):
'''
All orders for a specific account or, if account ID isn't specified, orders will be
returned for all linked accounts
Documentation Link: https://developer.tdameritrade.com/account-access/apis/get/orders-0
NAME: account
DESC: The account number that you want to query for orders.
TYPE: String
NAME: max_results
DESC: The maximum nymber of orders to receive.
TYPE: integer
NAME: from_entered_time
DESC: Specifies that no orders entered before this time should be returned.
Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz
Date must be within 60 days from today's date. 'toEnteredTime' must also be set.
TYPE: string
NAME: to_entered_time
DESC: Specifies that no orders entered after this time should be returned.
Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz.
'fromEnteredTime' must also be set.
TYPE: String
NAME: status
DESC: Specifies that only orders of this status should be returned. Possible values are:
1. AWAITING_PARENT_ORDER
2. AWAITING_CONDITION
3. AWAITING_MANUAL_REVIEW
4. ACCEPTED
5. AWAITING_UR_NOT
6. PENDING_ACTIVATION
7. QUEUED
8. WORKING
9. REJECTED
10. PENDING_CANCEL
11. CANCELED
12. PENDING_REPLACE
13. REPLACED
14. FILLED
15. EXPIRED
EXAMPLES:
Object.get_orders_query(account = 'MyAccountID', max_result = 6,
from_entered_time = '2019-10-01', to_entered_tme = '2019-10-10)
Object.get_orders_query(account = 'MyAccountID', max_result = 6, status = 'EXPIRED')
Object.get_orders_query(account = 'MyAccountID', status ='REJECTED')
Object.get_orders_query(account = 'MyAccountID')
'''
# define the payload
account = account or self.account_id
data = {"accountId":account,
"maxResults": max_results,
"fromEnteredTime": from_entered_time,
"toEnteredTime": to_entered_time,
"status": status}
# define teh endpoint
endpoint = '/orders'
# grab the originbal headers we have stored.
url, merged_headers =self._auth.headers(endpoint)
#make the request
return requests.get(url=url, headers = merged_headers, params = data,
verify = True, timeout = 10).json()
def get_order(self, account = None, order_id = None):
'''
Get a specific order for a specific account.
Documentation Link: https://developers.tdameritrade.com/account-access/apis/get/orders-a
NAME: account
DESC: The accountnumber that you want to queary the order for.
TYPE: String
NAME: order_id
DESC: The order id.
TYPE: String
EXA<PLES:
Session.Object.get_order(account = 'MyAccountID', order_id_ 'MyOrderID')
'''
#define the endpoint
account = account or self.account_id
endpoint = f'/accounts/{account}/orders/{order_id}'
# grab the originbal headers we have stored.
url, merged_headers =self._auth.headers(endpoint)
#make the request
return requests.get(url=url, headers = merged_headers, verify = True, timeout = 10).json()
def cancel_order(self, account = None, order_id = None):
'''
Cancel specific order for a specific account.
Documentation Link:
https://developers.tdameritrade.com/account-access/apis/delete/accounts/%7BaccountId%7D/
orders/%7BporderID%7D-0
NAME: account
DESC: The accountnumber that you want to queary the order for.
TYPE: String
NAME: order_id
DESC: The order id.
TYPE: String
EXAMPLES:
Session.Object.cancel_order(account = 'MyAccountID', order_id_ 'MyOrderID')
'''
#define the endpoint
account = account or self.account_id
endpoint = f'/accounts/{account}/orders/{order_id}'
# grab the originbal headers we have stored.
url, merged_headers =self._auth.headers(endpoint)
#make the request
response = requests.delete(url=url, headers = merged_headers, verify = True, timeout = 10)
if response.status_code == 200:
return print(f"Order {order_id} was successfully CANCELED.\n")
return print(response.content)
def create_order(self, account = None, symbol = None, price = None, quantity = '0',
instruction = None, asset_type = None, order_type = 'MARKET',
session = 'NORMAL', duration = 'DAY', order_strategy_type = 'SINGLE'):