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:
- Authenticate using an access token.
- Fetch account details.
- Retrieve live market quotes for a stock.
- 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.
No Comments have been Posted.