-
-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathclient.py
2191 lines (1673 loc) · 76.1 KB
/
client.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
import os
import time
import json
import pprint
import datetime
import pathlib
import requests
from requests.adapters import HTTPAdapter, Retry
import urllib.parse
from typing import Any
from typing import Dict
from typing import List
from typing import Union
from typing import Optional
from datetime import timedelta
from td.utils import StatePath
from td.utils import TDUtilities
from td.orders import Order
from td.orders import OrderLeg
from td.stream import TDStreamerClient
from td.option_chain import OptionChain
from td.enums import VALID_CHART_VALUES
from td.enums import ENDPOINT_ARGUMENTS
from td.oauth import run
from td.oauth import shutdown
from td.app.auth import FlaskTDAuth
from td.exceptions import TknExpError
from td.exceptions import ExdLmtError
from td.exceptions import NotNulError
from td.exceptions import ForbidError
from td.exceptions import NotFndError
from td.exceptions import ServerError
from td.exceptions import GeneralError
class TDClient():
"""TD Ameritrade API Client Class.
Implements OAuth 2.0 Authorization Code Grant workflow, handles configuration
and state management, adds token for authenticated calls, and performs request
to the TD Ameritrade API.
_multiprocessing_safe flag = True makes a single instance of this client safe to pass to multiple threads / processes,
as it will check a shared token cache first upon token expiration rather than each thread invalidating each others tokens.
Only the first thread to see a token has expired will actually request a new one, the other threads / processes will pull
from cache.
"""
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:
"""Creates a new instance of the TDClient Object.
Initializes the session with default values and any user-provided overrides.The
following arguments MUST be specified at runtime or else initalization will fail.
### Arguments:
----
consumer_id {str} -- The Consumer ID assigned to you during the App registration.
This can be found at the app registration portal.
redirect_uri {str} -- This is the redirect URL that you specified when you created your
TD Ameritrade Application.
Keyword ### Arguments:
----
account_number {str} -- This is the account number for your main
TD Ameritrade Account. (default: {None})
credentials_path {str} -- The path to the JSON credentials file generated by the
TDClient object. (default: {None})
auth_flow {str} -- Specifies is authentication is done through the command line (`default`) or
through the flask app `flask`. (default: {'default'})
### Usage:
----
>>> # Credentials Path & Account Specified.
>>> td_session = TDClient(
client_id='<CLIENT_ID>',
redirect_uri='<REDIRECT_URI>',
account_number='<ACCOUNT_NUMBER>',
credentials_path='<CREDENTIALS_PATH>'
)
>>> td_session.login()
>>>
>>> # Credentials Path & Account not Specified.
>>> td_session = TDClient(
client_id='<CLIENT_ID>',
redirect_uri='<REDIRECT_URI>'
)
>>> td_session.login()
"""
# Define the configuration settings.
self.config = {
'cache_state': True,
'api_endpoint': 'https://api.tdameritrade.com',
'api_version': 'v1',
'auth_endpoint': 'https://auth.tdameritrade.com/auth',
'token_endpoint': 'oauth2/token',
'refresh_enabled': True
}
# Define the initalized state, these are the default values.
self.state = {
'access_token': None,
'refresh_token': None,
'logged_in': False
}
self._cached_state = None
self._multiprocessing_safe = _multiprocessing_safe
self._multiprocessing_lock = None
if self._multiprocessing_safe:
import multiprocessing as mp
self._cached_state = mp.Manager().dict()
self._multiprocessing_lock = mp.Lock()
self._cached_state.update({
'access_token': None,
'refresh_token': None,
'logged_in': False
})
self.auth_flow = auth_flow
self.client_id = client_id
self.redirect_uri = redirect_uri
self.account_number = account_number
self.credentials_path = pathlib.Path(credentials_path)
self._td_utilities = TDUtilities()
if self.auth_flow == 'flask':
self._flask_app = FlaskTDAuth(
client_id=self.client_id,
redirect_uri=self.redirect_uri,
credentials_file=self.credentials_path
)
else:
self._flask_app = None
# define a new attribute called 'authstate' and initialize to `False`. This will be used by our login function.
self.authstate = False
# call the state_manager method and update the state to init (initalized)
if _do_init:
self._state_manager('init')
# Initalize the client with no streaming session.
self.streaming_session = None
def __repr__(self) -> str:
"""String representation of our TD Ameritrade Class instance."""
# define the string representation
str_representation = '<TDAmeritrade Client (logged_in={login_state}, authorized={auth_state})>'.format(
login_state=self.state['logged_in'],
auth_state=self.authstate
)
return str_representation
def _headers(self, mode: str = None) -> dict:
"""Create the headers for a request.
Returns a dictionary of default HTTP headers for calls to TD Ameritrade API,
in the headers we defined the Authorization and access token.
### Arguments:
----
mode {str} -- Defines the content-type for the headers dictionary. (default: {None})
### Returns:
----
{dict} -- Dictionary with the Access token and content-type
if specified
"""
# create the headers dictionary
headers = {
'Authorization': 'Bearer {token}'.format(token = self.state['access_token'])
}
if mode == 'json':
headers['Content-Type'] = 'application/json'
elif mode == 'form':
headers['Content-Type'] = 'application/x-www-form-urlencoded'
return headers
def _api_endpoint(self, endpoint: str, resource: str = None) -> str:
"""Convert relative endpoint (e.g., 'quotes') to full API endpoint.
### Arguments:
----
endpoint {str} -- The URL that needs conversion to a full endpoint URL.
resource {str} -- The API resource URL that you want to request. (default: {None})
### Returns:
----
{str} -- A full url that specifies a valid endpoint.
"""
# Define the parts.
if resource:
parts = [resource, self.config['api_version'], endpoint]
else:
parts = [self.config['api_endpoint'], self.config['api_version'], endpoint]
# Built the URl
return '/'.join(parts)
def _state_manager(self, action: str) -> None:
"""Manages the session state.
Manages the self.state dictionary. Initalize State will set
the properties to their default value. Save will save the
current state if 'cache_state' is set to TRUE.
### Arguments:
----
action {str}: action argument must of one of the following:
'init' -- Initalize State.
'save' -- Save the current state.
"""
credentials_file_exists = self.credentials_path.exists()
# if they allow for caching and the file exists then load it.
if action == 'init' and credentials_file_exists:
with open(file=self.credentials_path, mode='r') as json_file:
self.state.update(json.load(json_file))
if self._multiprocessing_safe:
self._cached_state.update(self.state)
# if they want to save it and have allowed for caching then load the file.
elif action == 'save':
with open(file=self.credentials_path, mode='w+') as json_file:
if self._multiprocessing_safe:
json.dump(obj=dict(self._cached_state), fp=json_file, indent=4)
else:
json.dump(obj=self.state, fp=json_file, indent=4)
def login(self) -> bool:
"""Logs the user into the TD Ameritrade API.
Ask the user to authenticate themselves via the TD Ameritrade Authentication Portal. This will
create a URL, display it for the User to go to and request that they paste the final URL into
command window. Once the user is authenticated the API key is valide for 90 days, so refresh
tokens may be used from this point, up to the 90 days.
### Returns:
----
{bool} -- Specifies whether it was successful or not.
"""
# Only attempt silent SSO if the credential file exists.
if self.credentials_path.exists() and self._silent_sso():
self.authstate = True
return True
else:
self.oauth()
self.authstate = True
return True
if self._flask_app and self.auth_flow == 'flask':
run(flask_client=self._flask_app, close_after=True)
def logout(self) -> None:
"""Clears the current TD Ameritrade Connection state."""
# change state to initalized so they will have to either get a
# new access token or refresh token next time they use the API
self._state_manager('init')
def grab_access_token(self) -> dict:
"""Refreshes the current access token.
This takes a valid refresh token and refreshes
an expired access token. This is different from
exchanging a code for an access token.
### Returns:
----
{bool} -- `True` if successful, `False` otherwise.
"""
# build the parameters of our request
data = {
'client_id': self.client_id,
'grant_type': 'refresh_token',
'refresh_token': self.state['refresh_token']
}
# Make the request.
response = requests.post(
url="https://api.tdameritrade.com/v1/oauth2/token",
headers={'Content-Type': 'application/x-www-form-urlencoded'},
data=data
)
if response.ok:
self._token_save(
token_dict=response.json(),
includes_refresh=False
)
def grab_refresh_token(self) -> bool:
"""Grabs a new refresh token if expired.
This takes a valid refresh token and requests
a new refresh token along with an access token.
This is similar to `grab_access_token` but it
does not include the `access_type` argument.
Which specifies to return a new refresh token
along with an access token.
### Returns:
----
{bool} -- `True` if successful, `False` otherwise.
"""
# build the parameters of our request
data = {
'client_id': self.client_id,
'grant_type': 'refresh_token',
'access_type': 'offline',
'refresh_token': self.state['refresh_token']
}
# Make the request.
response = requests.post(
url="https://api.tdameritrade.com/v1/oauth2/token",
headers={'Content-Type': 'application/x-www-form-urlencoded'},
data=data
)
if response.ok:
self._token_save(
token_dict=response.json(),
includes_refresh=True
)
return True
def grab_url(self) -> dict:
"""Builds the URL that is used for oAuth."""
# prepare the payload to login
data = {
'response_type': 'code',
'redirect_uri': self.redirect_uri,
'client_id': self.client_id + '@AMER.OAUTHAP'
}
# url encode the data.
params = urllib.parse.urlencode(data)
# build the full URL for the authentication endpoint.
url = "https://auth.tdameritrade.com/auth?" + params
return url
def oauth(self) -> None:
"""Runs the oAuth process for the TD Ameritrade API."""
# Create the Auth URL.
url = self.grab_url()
# Print the URL.
print(
'Please go to URL provided authorize your account: {}'.format(url)
)
# Paste it back and store it.
self.code = input(
'Paste the full URL redirect here: '
)
# Exchange the Code for an Acess Token.
self.exchange_code_for_token(
code=self.code,
return_refresh_token=True
)
def exchange_code_for_token(self, code: str, return_refresh_token: bool) -> dict:
"""Access token handler for AuthCode Workflow.
### Overview:
----
This takes the authorization code parsed from
the auth endpoint to call the token endpoint
and obtain an access token.
### Returns:
----
{bool} -- `True` if successful, `False` otherwise.
"""
# Parse the URL
url_dict = urllib.parse.parse_qs(self.code)
# Grab the Code.
url_code = list(url_dict.values())[0][0]
# Define the parameters of our access token post.
data = {
'grant_type': 'authorization_code',
'client_id': self.client_id + '@AMER.OAUTHAP',
'code': url_code,
'redirect_uri': self.redirect_uri
}
if return_refresh_token:
data['access_type'] = 'offline'
# Make the request.
response = requests.post(
url="https://api.tdameritrade.com/v1/oauth2/token",
headers={'Content-Type': 'application/x-www-form-urlencoded'},
data=data
)
if response.ok:
self._token_save(
token_dict=response.json(),
includes_refresh=True
)
return True
def validate_token(self, already_updated_from_cache=False) -> bool:
"""Validates whether the tokens are valid or not.
### Returns
-------
bool
Returns `True` if the tokens were valid, `False` if
the credentials file doesn't exist.
"""
if 'refresh_token_expires_at' in self.state and 'access_token_expires_at' in self.state:
# Grab the Expire Times.
refresh_token_exp = self.state['refresh_token_expires_at']
access_token_exp = self.state['access_token_expires_at']
refresh_token_ts = datetime.datetime.fromtimestamp(refresh_token_exp)
access_token_ts = datetime.datetime.fromtimestamp(access_token_exp)
# Grab the Expire Thresholds.
refresh_token_exp_threshold = refresh_token_ts - timedelta(days=2)
access_token_exp_threshold = access_token_ts - timedelta(minutes=5)
# Convert to Seconds.
refresh_token_exp_threshold = refresh_token_exp_threshold.timestamp()
access_token_exp_threshold = access_token_exp_threshold.timestamp()
# See if we need a new Refresh Token.
if datetime.datetime.now().timestamp() > refresh_token_exp_threshold:
if self._multiprocessing_safe and not already_updated_from_cache:
# ONLY ONE PROCESS / THREAD CAN GET A NEW TOKEN AT THE SAME TIME! Update from cache then revalidate!
# Only using the multiprocessing cache here prevents added latency checking cross process values
# except when the token has expired, which should only be once every 30 minutes. Better than making
# state a full MP dict.
with self._multiprocessing_lock:
self.state.update(dict(self._cached_state))
self.validate_token(already_updated_from_cache=True)
else:
print("Grabbing new refresh token...")
self.grab_refresh_token()
# See if we need a new Access Token.
if datetime.datetime.now().timestamp() > access_token_exp_threshold:
if self._multiprocessing_safe and not already_updated_from_cache:
# ONLY ONE PROCESS / THREAD CAN GET A NEW TOKEN AT THE SAME TIME! Update from cache then revalidate!
# Only using the multiprocessing cache here prevents added latency checking cross process values
# except when the token has expired, which should only be once every 30 minutes. Better than making
# state a full MP dict.
with self._multiprocessing_lock:
self.state.update(dict(self._cached_state))
self.validate_token(already_updated_from_cache=True)
else:
print("Grabbing new access token...")
self.grab_access_token()
return True
else:
pprint.pprint(
{
"credential_path": str(self.credentials_path),
"message": "The credential file does not contain expiration times for your tokens, please go through the oAuth process."
}
)
return False
def _silent_sso(self) -> bool:
"""
Overview:
----
Attempt a silent authentication, by checking whether current
access token is valid and/or attempting to refresh it. Returns
True if we have successfully stored a valid access token.
### Returns:
----
{bool} -- Specifies whether it was successful or not.
"""
if self.validate_token():
return True
else:
return False
def _token_save(self, token_dict: dict, includes_refresh: bool = False) -> dict:
"""Parses the token and saves it.
Overview:
----
Parses an access token from the response of a POST request and saves it
in the state dictionary for future use. Additionally, it will store the
expiration time and the refresh token.
### Arguments:
----
token_dict {dict} -- A response object recieved from the `grab_refresh_token` or
`grab_access_token` methods.
### Returns:
----
{dict} -- A token dictionary with the new added values.
"""
# store token expiration time
access_token_expire = time.time() + int(token_dict['expires_in'])
acc_timestamp = datetime.datetime.fromtimestamp(access_token_expire)
acc_timestamp = acc_timestamp.isoformat()
# Save to the State.
self.state['access_token'] = token_dict['access_token']
self.state['access_token_expires_at'] = access_token_expire
self.state['access_token_expires_at_date'] = acc_timestamp
if includes_refresh:
refresh_token_expire = time.time() + int(token_dict['refresh_token_expires_in'])
ref_timestamp = datetime.datetime.fromtimestamp(refresh_token_expire)
ref_timestamp = ref_timestamp.isoformat()
# Save to the State.
self.state['refresh_token'] = token_dict['refresh_token']
self.state['refresh_token_expires_at'] = refresh_token_expire
self.state['refresh_token_expires_at_date'] = ref_timestamp
self.state['logged_in'] = True
if self._multiprocessing_safe:
self._cached_state.update(self.state)
self._state_manager('save')
return self.state
def _make_request(self, method: str, endpoint: str, mode: str = None, params: dict = None, data: dict = None, json:dict = None,
order_details: bool = False) -> Any:
"""Handles all the requests in the library.
A central function used to handle all the requests made in the library,
this function handles building the URL, defining Content-Type, passing
through payloads, and handling any errors that may arise during the request.
### Arguments:
----
method: The Request method, can be one of the
following: ['get','post','put','delete','patch']
endpoint: The API URL endpoint, example is 'quotes'
mode: The content-type mode, can be one of the
following: ['form','json']
params: The URL params for the request.
data: A data payload for a request.
json: A json data payload for a request
### Returns:
----
A Dictionary object containing the JSON values.
"""
url = self._api_endpoint(endpoint=endpoint)
# Make sure the token is valid if it's not a Token API call.
self.validate_token()
headers = self._headers(mode=mode)
# Define a new session.
request_session = requests.Session()
retries = Retry(total=5, backoff_factor=0.1)
adapter = HTTPAdapter(max_retries=retries)
request_session.mount('http://', adapter)
request_session.mount('https://', adapter)
request_session.verify = True
# Define a new request.
request_request = requests.Request(
method=method.upper(),
headers=headers,
url=url,
params=params,
data=data,
json=json
).prepare()
# Send the request.
response: requests.Response = request_session.send(request=request_request)
request_session.close()
# grab the status code
status_code = response.status_code
# grab the response headers.
response_headers = response.headers
# Grab the order id, if it exists.
if 'Location' in response_headers:
order_id = response_headers['Location'].split('orders/')[1]
else:
order_id = ''
# If it's okay and we need details, then add them.
if response.ok and order_details:
response_dict = {
'order_id':order_id,
'headers':response_headers,
'content':response.content,
'status_code':status_code,
'request_body':response.request.body,
'request_method':response.request.method
}
return response_dict
# If it's okay and no details.
elif response.ok:
return response.json()
else:
if response.status_code == 400:
raise NotNulError(message=response.text)
elif response.status_code == 401:
try:
self.grab_access_token()
except:
raise TknExpError(message=response.text)
elif response.status_code == 403:
raise ForbidError(message=response.text)
elif response.status_code == 404:
raise NotFndError(message=response.text)
elif response.status_code == 429:
raise ExdLmtError(message=response.text)
elif response.status_code == 500 or response.status_code == 503:
raise ServerError(message=response.text)
elif response.status_code > 400:
raise GeneralError(message=response.text)
def _validate_arguments(self, endpoint: str, parameter_name: str, parameter_argument: List[str]) -> bool:
"""Validates arguments for an API call.
This will validate an argument for the specified endpoint and raise an error if the argument
is not valid. Can take both a list of arguments or a single argument.
### Arguments:
----
endpoint {str} -- This is the endpoint name, and should line up
exactly with the TD Ameritrade Client library.
parameter_name {str} -- An endpoint can have a parameter that needs
to be passed through, this represents the name
of that parameter.
parameter_argument {List[str]} -- The arguments being validated for the
particular parameter name. This can either be a single value or a list
of values.
### Returns:
----
{bool} --- If all arguments are valid then `True`, `False` if any are invalid.
Raises:
----
ValueError()
### Usage:
----
>>> api_endpoint = 'get_market_hours'
>>> para_name = 'markets'
>>> para_args = ['FOREX', 'EQUITY']
>>> self.validate_arguments(
endpoint = api_endpoint,
parameter_name = para_name,
parameter_argument = para_args
)
"""
message = '\nThe argument is not valid, please choose a valid argument: {}\n'
# Grab the parameters, and the possible arguments.
parameters = ENDPOINT_ARGUMENTS[endpoint]
arguments = parameters[parameter_name]
if isinstance(parameter_argument,str):
parameter_argument = [parameter_argument]
# See if any of the arguments aren't in the possible values.
validation_result = [argument in arguments for argument in parameter_argument]
# if any of the results are FALSE then raise an error.
if False in validation_result:
raise ValueError(message.format(' ,'.join(arguments)))
else:
return True
def _prepare_arguments_list(self, parameter_list: List) -> str:
"""Preps an argument list for an API Call.
Some endpoints can take multiple values for a parameter, this
method takes that list and creates a valid string that can be
used in an API request. The list can have either one index or
multiple indexes.
### Arguments:
----
parameter_list: A list of paramater values
assigned to an argument.
### Usage:
----
>>> td_client._prepare_arguments_list(
parameter_list=['MSFT', 'SQ']
)
"""
return ','.join(parameter_list)
def get_quotes(self, instruments: List) -> Dict:
"""Grabs real-time quotes for an instrument.
Serves as the mechanism to make a request to the Get Quote and Get Quotes Endpoint.
If one item is provided a Get Quote request will be made and if more than one item
is provided then a Get Quotes request will be made.
### Documentation:
----
https://developer.tdameritrade.com/quotes/apis
### Arguments:
----
instruments: A list of different financial instruments.
### Usage:
----
>>> td_client.get_quotes(instruments=['MSFT'])
>>> td_client.get_quotes(instruments=['MSFT','SQ'])
"""
# because we have a list argument, prep it for the request.
instruments = self._prepare_arguments_list(
parameter_list=instruments
)
# build the params dictionary
params = {
'apikey': self.client_id,
'symbol': instruments
}
# define the endpoint
endpoint = 'marketdata/quotes'
# return the response of the get request.
return self._make_request(method='get', endpoint=endpoint, params=params)
def get_price_history(self, symbol: str, period_type:str = None, period: str = None, start_date:str = None, end_date:str = None,
frequency_type: str = None, frequency: str = None, extended_hours: bool = True) -> Dict:
"""Gets historical candle data for a financial instrument.
### Documentation:
----
https://developer.tdameritrade.com/price-history/apis
### Arguments:
----
symbol: The ticker symbol to request data for.
period_type: The type of period to show.
Valid values are day, month, year, or
ytd (year to date). Default is day.
period: The number of periods to show.
start_date: Start date as milliseconds
since epoch.
end_date: End date as milliseconds
since epoch.
frequency_type: The type of frequency with
which a new candle is formed.
frequency: The number of the frequency type
to be included in each candle.
extended_hours: True to return extended hours
data, false for regular market hours only.
Default is true
"""
# Fail early, can't have a period with start and end date specified.
if (start_date and end_date and period):
raise ValueError('Cannot have Period with start date and end date')
# Check only if you don't have a date and do have a period.
elif (not start_date and not end_date and period):
# Attempt to grab the key, if it fails we know there is an error.
# check if the period is valid.
if int(period) in VALID_CHART_VALUES[frequency_type][period_type]:
True
else:
raise IndexError('Invalid Period.')
if frequency_type == 'minute' and int(frequency) not in [1, 5, 10, 15, 30]:
raise ValueError('Invalid Minute Frequency, must be 1,5,10,15,30')
# build the params dictionary
params = {
'apikey': self.client_id,
'period': period,
'periodType': period_type,
'startDate': start_date,
'endDate': end_date,
'frequency': frequency,
'frequencyType': frequency_type,
'needExtendedHoursData': extended_hours
}
# define the endpoint
endpoint = 'marketdata/{}/pricehistory'.format(symbol)
# return the response of the get request.
return self._make_request(method='get', endpoint=endpoint, params=params)
def search_instruments(self, symbol: str, projection: str = None) -> Dict:
""" Search or retrieve instrument data, including fundamental data.
### Documentation:
----
https://developer.tdameritrade.com/instruments/apis/get/instruments
### Arguments:
----
symbol: The symbol of the financial instrument you would
like to search.
projection: The type of request, default is "symbol-search".
The type of request include the following:
1. symbol-search
Retrieve instrument data of a specific symbol or cusip
2. symbol-regex
Retrieve instrument data for all symbols matching regex.
Example: symbol=XYZ.* will return all symbols beginning with XYZ
3. desc-search
Retrieve instrument data for instruments whose description contains
the word supplied. Example: symbol=FakeCompany will return all
instruments with FakeCompany in the description
4. desc-regex
Search description with full regex support. Example: symbol=XYZ.[A-C]
returns all instruments whose descriptions contain a word beginning
with XYZ followed by a character A through C
5. fundamental
Returns fundamental data for a single instrument specified by exact symbol.
### Usage:
----
>>> td_client.search_instrument(
symbol='XYZ',
projection='symbol-search'
)
>>> td_client.search_instrument(
symbol='XYZ.*',
projection='symbol-regex'
)
>>> td_client.search_instrument(
symbol='FakeCompany',
projection='desc-search'
)
>>> td_client.search_instrument(
symbol='XYZ.[A-C]',
projection='desc-regex'
)
>>> td_client.search_instrument(
symbol='XYZ.[A-C]',
projection='fundamental'
)
"""
# validate argument
self._validate_arguments(
endpoint='search_instruments',
parameter_name='projection',
parameter_argument=projection
)
# build the params dictionary
params = {
'apikey': self.client_id,
'symbol': symbol,
'projection': projection
}
# define the endpoint
endpoint = 'instruments'
# return the response of the get request.
return self._make_request(method='get', endpoint=endpoint, params=params)
def get_instruments(self, cusip: str) -> Dict:
"""Searches an Instrument.
Get an instrument by CUSIP (Committee on Uniform Securities Identification Procedures) code.
### Documentation:
----
https://developer.tdameritrade.com/instruments/apis/get/instruments/%7Bcusip%7D
### Arguments:
----
cusip: The CUSIP code of a given financial instrument.
### Usage:
----
>>> td_client.get_instruments(
cusip='SomeCUSIPNumber'
)
"""
# build the params dictionary
params = {
'apikey': self.client_id
}
# define the endpoint
endpoint = 'instruments/{cusip}'.format(cusip=cusip)
# return the response of the get request.
return self._make_request(method='get', endpoint=endpoint, params=params)
def get_market_hours(self, markets: List[str], date: str) -> Dict:
"""Returns the hours for a specific market.
Serves as the mechanism to make a request to the "Get Hours for Multiple Markets" and
"Get Hours for Single Markets" Endpoint. If one market is provided a "Get Hours for Single Markets"
request will be made and if more than one item is provided then a "Get Hours for Multiple Markets"
request will be made.
### Documentation:
----
https://developer.tdameritrade.com/market-hours/apis
### Arguments:
----
markets: The markets for which you're requesting market hours,
comma-separated. Valid markets are:
EQUITY, OPTION, FUTURE, BOND, or FOREX.
date: The date you wish to recieve market hours for.
Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz