• Stars
    star
    684
  • Rank 66,068 (Top 2 %)
  • Language
    Python
  • License
    MIT License
  • Created about 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Unofficial Python API client library for TD Ameritrade. This library allows for easy access of the Standard API and allows users to build data pipelines for the Streaming API.

UPDATE

This repo will soon be updated to include the new https://github.com/areed1192/td-ameritrade-api library. The master branch will be overwritten and the old code will need to be updated to reflect the new changes. If you would like to start rewriting your old code, please refer to the new branch merge-new-repo or go the link above.

Unofficial TD Ameritrade Python API Library

Table of Contents

Overview

Current Version: 0.3.5

The unofficial Python API client library for TD Ameritrade allows individuals with TD Ameritrade accounts to manage trades, pull historical and real-time data, manage their accounts, create and modify orders all using the Python programming language.

To learn more about the TD Ameritrade API, please refer to the official documentation.

What's in the API

  • Authentication - access tokens, refresh tokens, request authentication.
  • Accounts & Trading
  • Market Hours
  • Instruments
  • Movers
  • Option Chains
  • Price History
  • Quotes
  • Transaction History
  • User Info & Preferences
  • Watchlist

Requirements

The following requirements must be met to use this API:

  • A TD Ameritrade account, you'll need your account password and account number to use the API.
  • A TD Ameritrade Developer Account
  • A TD Ameritrade Developer API Key
  • A Consumer ID
  • A Redirect URI, sometimes called Redirect URL
  • Python 3.7 or later.

API Key and Credentials

Each TD Ameritrade API request requires a TD Ameritrade Developer API Key, a consumer ID, an account password, an account number, and a redirect URI. API Keys, consumer IDs, and redirect URIs are generated from the TD Ameritrade developer portal. To set up and create your TD Ameritrade developer account, please refer to the official documentation.

Additionally, to authenticate yourself using this library, you will need to provide your account number and password for your main TD Ameritrade account.

Important: Your account number, an account password, consumer ID, and API key should be kept secret.

Installation

The project can be found at PyPI, if you'd like to view the project please use this link.

pip install td-ameritrade-python-api

To upgrade the library run the following command:

pip install --upgrade td-ameritrade-python-api

Usage

This example demonstrates how to login to the API and demonstrates sending a request using the get_quotes endpoint, using your API key.

Credentials: Please note, that the credentials_path is a file path that will house the credentials like your refresh token and access token. You must specify the credentials_path argument yourself so that you are aware of where the tokens will be stored. For example, if you specify the credentials_path as C:\Users\Public\Credentials\td_state.json it would store your tokens in a JSON file located in a folder called Credentials located under the Users profile.

# Import the client
from td.client import TDClient

# Create a new session, credentials path is required.
TDSession = TDClient(
    client_id='<CLIENT_ID>',
    redirect_uri='<REDIRECT_URI>',
    credentials_path='<PATH_TO_CREDENTIALS_FILE>'
)

# Login to the session
TDSession.login()

# Grab real-time quotes for 'MSFT' (Microsoft)
msft_quotes = TDSession.get_quotes(instruments=['MSFT'])

# Grab real-time quotes for 'AMZN' (Amazon) and 'SQ' (Square)
multiple_quotes = TDSession.get_quotes(instruments=['AMZN','SQ'])

Features

Authentication Workflow Support

Automatically will handle the authentication workflow for new users, returning users, and users with expired tokens (refresh token or access token).

Request Validation

For certain requests, in a limited fashion, it will help validate your request when possible. For example, when using the get_movers endpoint, it will automatically validate that the market you're requesting data from is one of the valid options.

Customized Objects for Watchlists, Orders, and Option Chains

Requests for saved orders, regular orders, watchlists, and option chains can be a challenging process that has multiple opportunities to make mistakes. This library has built-in objects that will allow you to quickly build your request and then validate certain portions of your request when possible.

Library Requirements

The following requirements must be met before being able to use the TD Ameritrade Python API library.

  • You must have a TD Ameritrade Account.
  • You must have a TD Ameritrade Developer Account. Please go to following folder for instructions on how to create a Developer account.

Documentation and Resources

Official API Documentation

Unofficial Documentation

Support these Projects

Patreon: Help support this project and future projects by donating to my Patreon Page. I'm always looking to add more content for individuals like yourself, unfortuantely some of the APIs I would require me to pay monthly fees.

YouTube: If you'd like to watch more of my content, feel free to visit my YouTube channel Sigma Coding.

Hire Me: If you have a project, you think I can help you with feel free to reach out at [email protected] or fill out the contract request form

Authentication Workflow

Step 1 - Start the Script:

While in Visual Studio Code, right click anywhere in the code editor while in the file that contains your code. The following dropdown will appear:

Terminal Dropdown

From the dropdown, click Run Python file in Terminal, this will start the python script.

Step 2 - Go to Redirect URL:

The TD Library will automatically generate the redirect URL that will navigate you to the TD website for for you authentication. You can either copy the link and paste it into a browser manually or if you're using Visual Studio Code you can press CTRL + Click to have Visual Studio Code navigate you to the URL immeditately.

Redirect URI

Step 3 - Login to the TD API:

Once you've arrived at the login screen, you'll need to provide your credentials to authenticate the session. Please provide your Account Username and Account Password in the userform and then press enter. As a reminder these, are the same username/password combination you use to login to your regular TD Account.

"TD Login

Step 4 - Accept the Terms:

Accept the Terms of the API by clicking Allow, this will redirect you.

TD Terms

Step 5 - Copy the Authorization Code:

After accepting the terms, you'll be taken to the URL that you provided as your redirect URI. However, at the end of that URL will be authorization code. To complete the authentication workflow, copy the URL as it appears below. Don't worry if the numbers don't match, as you will have a different code.

Auth Code

Step 6 - Paste the Authorization Code in the Terminal:

Take the URL and copy it into the Terminal, after you have pasted it, press Enter. The authentication workflow will complete and the script will start running. At this stage, we are exchanging your authorization code for an access token. That access token is valid only for 30 minutes. However, a refresh token is also stored that will refresh your access token when it expires.

Paste URL

After, that the script should run. Additionally, if you go to the location you specified in the credentials_path arugment you will now see td_state.json file. This file contains all the info used during a session. Please DO NOT DELETE THIS FILE OR ELSE YOU WILL NEED TO GO THROUGH THE STEPS ABOVE.

More Repositories

1

sigma_coding_youtube

This is a collection of all the code that can be found on my YouTube channel Sigma Coding.
Jupyter Notebook
963
star
2

python-trading-robot

A trading robot, that can submit basic orders in an automated fashion using the TD API.
Python
447
star
3

interactive-broker-python-api

A python packaged used to interact with the Interactive Brokers REST API.
Python
321
star
4

python-sec

A simple python library that allows for easy access of the SEC website so that someone can parse filings, collect data, and query documents.
Python
116
star
5

td-ameritrade-api

The unofficial Python API client library for TD Ameritrade. This library allows for easy access of the Standard REST API and Streaming API.
Python
109
star
6

tradestation-python-api

A Python Client library for the TradeStation API.
Python
88
star
7

finance-news-aggregator

A news aggregator in python, that focuses primarily on business and market news sources.
Python
68
star
8

interactive-brokers-api

A python application used to interact with the Interactive Brokers REST API.
Python
57
star
9

ms-graph-python-client

A Python Client Application that allows users to interact with the Microsoft Graph API.
Python
50
star
10

portfolio-optimization

A python application, that demonstrates optimizing a portfolio using machine learning.
Python
40
star
11

sigma-coding

This is a repository used for educational purposes to demonstrate how to upload a Python package to PyPi.
Python
39
star
12

power-bi-python-api

The Unofficial Python API wrapper for the Microsoft Power BI REST API.
Python
38
star
13

azure-sql-data-project

A python application that is used to create instances of SQL Server instances on Microsoft Azure, and insert data into those databases.
Python
30
star
14

excel-custom-function-add-in

A tutorial on how to build an Excel Custom Function Add-In using the new Office JavaScript API.
TypeScript
17
star
15

python-bureau-economic-analysis-api-client

A Python API client used to pull and retrieve data from the US Bureau of Economic Analysis
Python
13
star
16

azure-functions-http

A tutorial that covers how to use Azure functions using the python programming language.
Python
10
star
17

trading-system

A python application that leverages Microsoft Azure to build a fully functional trading system.
Python
10
star
18

us-federal-treasury-python-api

A Python application which is used to pull data from the United States Federal Treasury API.
Python
7
star
19

sigma-template

Serves as a template folder for other repos I create.
Python
7
star
20

us-federal-register-python-api

A python API client for the United States Federal Register.
Python
5
star
21

trading-factory

My Azure Data Factory for managing my trading system.
Python
5
star
22

youtube-python-client

A Python client library for the YouTube API.
Python
5
star
23

united-states-congress-python-api

A Python API client for the United States Congressional data found GovInfo.com.
Python
5
star
24

trade-robot

A python package that allows you to place automated trades using the TD Ameritrade API.
Python
4
star
25

us-federal-reserve-python-api

A Python application which is used to pull data from the US Federal Reserve.
Python
4
star
26

amzn-associates-api

A python API client library used to interact with the Amazon Associates Marketing API.
Python
3
star
27

sigma-utilities

Random Code I used to help with different projects.
Python
3
star
28

epa-scraper-project

This is a python project that collects and stores data from the EPA website.
3
star
29

tap-federal-reserve

A singer Tap for extracting data from the United States Federal Reserver API (FRED).
Python
3
star
30

python-for-starters

A guide on how to get up and running with Python, VSCode, Git, & GitHub on Windows.
Python
2
star
31

new-office-add-in

TypeScript
2
star
32

energy-scraper

A python program that will go and scrape EPA data.
2
star
33

sigma-azure-management

A Python project that demonstrates managing different Azure Services.
TSQL
2
star
34

gmail-api-python

A Python project that uses the Gmail API in Python.
Python
2
star
35

trading-data-factory

A Python Application that leverages the Azure Data Factory to store trading data.
Python
2
star
36

azure-and-terraform

Terraform modules used to create Azure resources for other projects.
HCL
1
star
37

interview-items

A collection of items I use for interview purposes.
Jupyter Notebook
1
star
38

logistic-regression-model-stocks

Python
1
star
39

docker-trading-data-workflow

A docker application used to collect price data using a docker image.
Python
1
star
40

excel-python-com-server

Demonstrates how to create a Python COM Server using the Win32COM library.
Python
1
star