Quickstart¶
Before You Begin¶
This package assumes you or someone who trusts you has set up a TDAmeritrade app through their developer portal. If you haven’t done this, see TDAmeritrade’s getting started guide.
To authenticate against the TDAmeritrade API, you need:
- An OAuth redirect URI
- An OAuth user ID
- Your TDAmeritrade account number
You create these first two items when you register a new app with TDAmeritrade.
Current Uses¶
Auth and Positions¶
To get started, use the following code snippet to create an authenticated client and pull your account positions:
from tdameritrade_client.client import TDClient
td_client = TDClient(acct_number=<your account number>,
oauth_user_id=<the id registered to the TD app you would like to authenticate with>,
redirect_uri=<the redirect URI registered to the TD app>,
token_path=<optional path to an existing access token>)
td_client.run_auth()
acct_info = td_client.get_positions()
When you authenticate for the first time, you will have to sign in with the account that is linked to all accounts you would like to request positions for. The auth flow will write an access token for that account, and you can only pull positions for the account you signed in with and any linked accounts.
Note that the first full auth flow will cause your browser to warn you of an untrusted certificate. This is because the self-signed certificate in question is written by the library and hosted from your localhost, and is therefore safe to trust.
Search for Instrument¶
You can search for an instrument by ticker, CUSIP, or by its description:
from tdameritrade_client.client import TDClient
td_client = TDClient(acct_number, oauth_user_id, redirect_uri, token_path)
td_client.run_auth()
print(td_client.get_instrument(symbol='aapl', projection='symbol-search'))
>> {'AAPL': {'cusip': '037833100', 'symbol': 'AAPL', 'description': 'Apple Inc. - Common Stock', 'exchange': 'NASDAQ', 'assetType': 'EQUITY'}}
print(td_client.get_instrument(symbol='037833AK6', projection='symbol-search'))
>> {'037833AK6': {'bondPrice': 98.762, 'cusip': '037833AK6', 'symbol': '037833AK6', 'description': 'APPLE INC SENIOR NOTE M/W 2.4 2023-05-03', 'exchange': 'OTC', 'assetType': 'BOND'}}
print(td_client.get_instrument(symbol='Apple Inc.*', projection='desc-regex'))
>> {'AAPL42': {'cusip': '037833BK5', 'symbol': 'AAPL42', 'description': 'Apple Inc', 'exchange': 'NYSE', 'assetType': 'EQUITY'}, 'AAPL26': { . . . } . . .}
Get Quote¶
Get a quote for a known ticker symbol:
from tdameritrade_client.client import TDClient
td_client = TDClient(acct_number, oauth_user_id, redirect_uri, token_path)
td_client.run_auth()
print(td_client.get_quote(symbol='aapl'))
>> {'AAPL': {'assetType': 'EQUITY', 'symbol': 'AAPL', 'description': 'Apple Inc. - Common Stock',
'bidPrice': 196.89, 'bidSize': 500, 'bidId': 'K', 'askPrice': 197.0, 'askSize': 5000,
'askId': 'K', 'lastPrice': 196.9, 'lastSize': 100, 'lastId': 'Q', 'openPrice': 196.45,
'highPrice': 197.1, 'lowPrice': 195.93, 'bidTick': ' ', 'closePrice': 197.0, 'netChange': -0.1,
'totalVolume': 18526644, 'quoteTimeInLong': 1554508799032, 'tradeTimeInLong': 1554508799032,
'mark': 197.0, 'exchange': 'q', 'exchangeName': 'NASDAQ', 'marginable': True, 'shortable': True,
'volatility': 0.0082, 'digits': 4, '52WkHigh': 233.47, '52WkLow': 142.0, 'nAV': 0.0,
'peRatio': 16.5064, 'divAmount': 2.92, 'divYield': 1.48, 'divDate': '2019-02-08 00:00:00.0',
'securityStatus': 'Normal', 'regularMarketLastPrice': 197.0, 'regularMarketLastSize': 11280,
'regularMarketNetChange': 0.0, 'regularMarketTradeTimeInLong': 1554494400394, 'delayed': False}}
Get Price History¶
There are two methods to retrieve price history: by date range, or by period.
Search by date:
from datetime import datetime from tdameritrade_client.client import TDClient td_client = TDClient(acct_number, oauth_user_id, redirect_uri, token_path) td_client.run_auth() print(td_client.get_dated_price_history(symbol='aapl', start_date=datetime(2019, 4, 23, 11, 0, 0), end_date=datetime(2019, 4, 23, 11, 2, 0)) >> { "candles": [ { "open": 203.72, "high": 203.75, "low": 203.72, "close": 203.75, "volume": 750, "datetime": "2019-04-23_11-00-00" }, { "open": 203.75, "high": 203.75, "low": 203.75, "close": 203.75, "volume": 200, "datetime": "2019-04-23_11-01-00" } ], "symbol": "AAPL", "empty": false }
The datetimes providing a daterange should be given in UTC. Note: TDAmeritrade will return an error if there are no data entries in the given time interval. There is normally data starting at 11am UTC.
Search by period:
from tdameritrade_client.client import TDClient td_client = TDClient(acct_number, oauth_user_id, redirect_uri, token_path) td_client.run_auth() print(td_client.get_period_price_history(symbol='aapl', period_type='day', period=1, frequency_type='minute', frequency=30) >> { "candles": [ { "open": 210.1, "high": 210.45, "low": 210.05, "close": 210.12, "volume": 16642, "datetime": "2019-05-03_11-00-00" }, { "open": 210.2, "high": 210.46, "low": 210.2, "close": 210.45, "volume": 20356, "datetime": "2019-05-03_11-30-00" }, { "open": 210.44, "high": 210.54, "low": 210.28, "close": 210.35, "volume": 31383, "datetime": "2019-05-03_12-00-00" }, { "open": 210.35, "high": 210.99, "low": 209.87, "close": 210.78, "volume": 140608, "datetime": "2019-05-03_12-30-00" }, . . . ], "symbol": "AAPL", "empty": false }
Get Movers¶
Get top 10 movers (up or down) by percent or value of one of the DOW, NASDAQ, or S&P500 indices:
from tdameritrade_client.client import TDClient
td_client = TDClient(acct_number, oauth_user_id, redirect_uri, token_path)
td_client.run_auth()
print(td_client.get_movers(index='$DJI', direction='up', change='percent'))
>> [
{
"change": 0,
"description": "string",
"direction": "up",
"symbol": "string",
"totalVolume": 0
},
{
"change": 0,
"description": "string",
"direction": "up",
"symbol": "string",
"totalVolume": 0
},
. . .
]
Get Hours¶
Get market hours on a given date for a given market. The date must be in the future. valid markets are any of [‘EQUITY’, ‘OPTION’, ‘FUTURE’, ‘BOND’, ‘FOREX’]. The following was run before 2019-05-20:
from tdameritrade_client.client import TDClient
td_client = TDClient(acct_number, oauth_user_id, redirect_uri, token_path)
td_client.run_auth()
print(td_client.get_hours(markets='EQUITY', date=datetime(2019, 5, 20))
>> {'equity':
{'EQ':
{
'date': '2019-05-20',
'marketType': 'EQUITY',
'exchange': 'NULL',
'category': 'NULL',
'product': 'EQ',
'productName': 'equity',
'isOpen': True,
'sessionHours': {
'preMarket': [{'start': '2019-05-20T07:00:00-04:00', 'end': '2019-05-20T09:30:00-04:00'}], 'regularMarket': [{'start': '2019-05-20T09:30:00-04:00', 'end': '2019-05-20T16:00:00-04:00'}],
'postMarket': [{'start': '2019-05-20T16:00:00-04:00', 'end': '2019-05-20T20:00:00-04:00'}]
}
}
}
}
Get Transactions for an Account¶
Get transactions for an account within a time window. Optionally filter based on symbol or transaction type:
from tdameritrade_client.client import TDClient
td_client = TDClient(acct_number, oauth_user_id, redirect_uri, token_path)
td_client.run_auth()
print(td_client.get_transactions(start_date=datetime(2019, 3, 20), end_date=datetime(2019, 5, 20), symbol='VOO',
type='BUY_ONLY')
>> [
{
"type": "TRADE",
"subAccount": "1",
"settlementDate": "2019-04-04",
"orderId": ". . .",
"netAmount": -3938.62,
"transactionDate": "2019-04-02T13:31:03+0000",
"orderDate": "2019-04-02T13:31:03+0000",
"transactionSubType": "BY",
"transactionId": . . .,
"cashBalanceEffectFlag": true,
"description": "BUY TRADE",
. . .
},
. . .
]