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

Python sample for interacting with the TD Ameritrade API

Here’s a basic Python sample for interacting with the TD Ameritrade API using the requests library. This example demonstrates how to:

  1. Authenticate using an access token.
  2. Fetch account details.
  3. Retrieve live market quotes for a stock.
  4. Place an order.

Setup

Before running the code, ensure you have:

  • A TD Ameritrade Developer Account.
  • An API Key (Consumer Key).
  • An OAuth Access Token (required for authenticated requests).

Install Dependencies

pip install requests

Python Code

import requests
import json

# TD Ameritrade API credentials
API_KEY = "YOUR_API_KEY_HERE" # Consumer Key from TD Ameritrade Developer Account
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN_HERE" # OAuth Access Token
ACCOUNT_ID = "YOUR_ACCOUNT_ID_HERE" # Your TD Ameritrade Account Number

# Base URL
BASE_URL = "https://api.tdameritrade.com/v1"

# Headers for authentication
HEADERS = {
 "Authorization": f"Bearer {ACCESS_TOKEN}",
 "Content-Type": "application/json"
}

# 1️⃣ Fetch Account Details
def get_account_info():
 url = f"{BASE_URL}/accounts/{ACCOUNT_ID}"
 response = requests.get(url, headers=HEADERS)
 return response.json()

# 2️⃣ Get Stock Quote
def get_stock_quote(symbol):
 url = f"{BASE_URL}/marketdata/{symbol}/quotes"
 response = requests.get(url, headers=HEADERS)
 return response.json()

# 3️⃣ Place an Order (Example: Buy 1 share of AAPL at Market Price)
def place_order():
 url = f"{BASE_URL}/accounts/{ACCOUNT_ID}/orders"
 
 order_payload = {
 "orderType": "LIMIT",
 "session": "NORMAL",
 "duration": "DAY",
 "orderStrategyType": "SINGLE",
 "orderLegCollection": [
 {
 "instruction": "BUY",
 "quantity": 1,
 "instrument": {
 "symbol": "AAPL",
 "assetType": "EQUITY"
 }
 }
 ],
 "price": "170.00" # Replace with the desired price
 }

 response = requests.post(url, headers=HEADERS, json=order_payload)
 return response.json()

# Run functions
if __name__ == "__main__":
 print("Fetching Account Info...")
 print(json.dumps(get_account_info(), indent=4))

 print("nFetching Stock Quote for AAPL...")
 print(json.dumps(get_stock_quote("AAPL"), indent=4))

 print("nPlacing Order for AAPL...")
 print(json.dumps(place_order(), indent=4))

Key Features

Fetch account details – Retrieves balances and positions.
Get stock quote – Fetches the latest market price for a given stock symbol.
Place a stock order – Sends a limit order to buy 1 share of AAPL.

 

caa February 03 2025 24 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 3
Members Online 0

Total Members: 14
Newest Member: Frank_nKansas