TD Ameritrade API sample program
Here’s a basic sample program demonstrating how to use the TD Ameritrade API to fetch stock quotes. Before proceeding, make sure you have the following:
- A TD Ameritrade developer account.
- A registered application with a
andclient_id
.redirect_uri
- Python installed, with required libraries (
,requests
).flask
Install Dependencies
pip install requests flask
Sample Program
1. Authentication Script
This uses OAuth to obtain an access token.
from flask import Flask, request
import webbrowser
import requests
import urllib.parse
# TD Ameritrade App Details
client_id = "YOUR_CLIENT_ID" # Replace with your client_id
redirect_uri = "http://localhost:5000/callback"
app = Flask(__name__)
@app.route("/")
def login():
auth_url = f"https://auth.tdameritrade.com/auth?response_type=code&redirect_uri={urllib.parse.quote(redirect_uri)}&client_id={client_id}%40AMER.OAUTHAP"
return f'Click here to authorize'
@app.route("/callback")
def callback():
auth_code = request.args.get("code")
token_url = "https://api.tdameritrade.com/v1/oauth2/token"
data = {
"grant_type": "authorization_code",
"access_type": "offline",
"code": auth_code,
"client_id": f"{client_id}@AMER.OAUTHAP",
"redirect_uri": redirect_uri,
}
response = requests.post(token_url, data=data)
if response.status_code == 200:
access_token = response.json().get("access_token")
return f"Access Token: {access_token}. Save it for API calls."
else:
return f"Error: {response.json()}"
if __name__ == "__main__":
webbrowser.open("http://localhost:5000")
app.run(debug=True)
- Replace
with yourYOUR_CLIENT_ID
.client_id
- Run the script and open
in a browser. Follow the authorization process to get the access token.http://localhost:5000
2. Fetch Stock Quotes
Once you have an access token, use it to make API calls.
import requests
# Replace with your access token
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
def get_quote(symbol):
url = f"https://api.tdameritrade.com/v1/marketdata/{symbol}/quotes"
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
quote = response.json().get(symbol.upper(), {})
print(f"Symbol: {quote.get('symbol')}")
print(f"Last Price: {quote.get('lastPrice')}")
print(f"52 Week High: {quote.get('52WkHigh')}")
print(f"52 Week Low: {quote.get('52WkLow')}")
else:
print(f"Error: {response.json()}")
# Example: Fetch quotes for Apple (AAPL)
get_quote("AAPL")
Notes
- Replace
with the token received from the authentication script.YOUR_ACCESS_TOKEN
- Tokens expire after 30 minutes. To keep the app running, use the refresh token mechanism.
- For more API endpoints, refer to TD Ameritrade's API documentation.
No Comments have been Posted.