Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Articles

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:

  1. A TD Ameritrade developer account.
  2. A registered application with a
    client_id
    and
    redirect_uri
    .
  3. 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)
  1. Replace
    YOUR_CLIENT_ID
    with your
    client_id
    .
  2. Run the script and open
    http://localhost:5000
    in a browser. Follow the authorization process to get the access token.

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

  1. Replace
    YOUR_ACCESS_TOKEN
    with the token received from the authentication script.
  2. Tokens expire after 30 minutes. To keep the app running, use the refresh token mechanism.
  3. For more API endpoints, refer to TD Ameritrade's API documentation.

 

caa January 25 2025 29 reads 0 comments Print

0 comments

Leave a Comment

Please Login to Post a Comment.
  • No Comments have been Posted.

Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 2
Members Online 0

Total Members: 14
Newest Member: Frank_nKansas