ThinkOrSwim (TOS) by TD Ameritrade API program in python
ThinkOrSwim (TOS), by TD Ameritrade, provides an API for accessing financial data, placing trades, and interacting with user accounts programmatically. TD Ameritrade's API can be integrated with Python to automate and analyze trading tasks.
Here’s a guide to getting started with the TD Ameritrade API using Python:
---
### 1. **Create a TD Ameritrade Developer Account and Get API Key**
- Register for a [TD Ameritrade Developer account](https://developer.tdameritrade.com/).
- After logging in, create a new app to get an **API key**. This key is needed for making authenticated requests.
### 2. **Install the Necessary Libraries**
- Install `requests` for handling HTTP requests and `pandas` if you’d like to work with dataframes.
```bash
pip install requests pandas
```
### 3. **OAuth Authentication with TD Ameritrade**
- TD Ameritrade’s API uses OAuth 2.0 for authentication. Use your API key to generate an access token.
- Implementing OAuth 2.0 in Python requires redirection, which can be done using `requests`.
#### Sample Code to Get OAuth Access Token
```python
import requests
from urllib.parse import urlencode
# Define client_id and redirect_uri
client_id = 'YOUR_API_KEY@AMER.OAUTHAP'
redirect_uri = 'http://localhost'
# Step 1: Authorization URL
auth_url = 'https://auth.tdameritrade.com/auth'
params = {
'response_type': 'code',
'redirect_uri': redirect_uri,
'client_id': client_id
}
print("Go to the following URL and authorize:", auth_url + '?' + urlencode(params))
```
After authorizing, a code will be generated in the redirected URL. Capture this code and use it to obtain the access token.
---
### 4. **Get Access Token Using Authorization Code**
- Exchange the authorization code for an access token, which allows you to make API requests.
```python
# Exchange authorization code for an access token
token_url = 'https://api.tdameritrade.com/v1/oauth2/token'
auth_code = input("Enter the code from the redirected URL: ")
# Request for access token
data = {
'grant_type': 'authorization_code',
'access_type': 'offline',
'code': auth_code,
'client_id': client_id,
'redirect_uri': redirect_uri
}
response = requests.post(token_url, data=data)
access_token = response.json()['access_token']
print("Access Token:", access_token)
```
### 5. **Using the API to Get Market Data and Account Information**
- With the access token, you can query endpoints for stock prices, account data, historical data, and more.
#### Example: Fetching Real-Time Quotes
```python
headers = {'Authorization': f'Bearer {access_token}'}
symbol = 'AAPL' # Replace with your desired stock symbol
quote_url = f'https://api.tdameritrade.com/v1/marketdata/{symbol}/quotes'
response = requests.get(quote_url, headers=headers)
print(response.json())
```
#### Example: Fetching Historical Data
```python
params = {
'apikey': client_id,
'periodType': 'month',
'period': '1',
'frequencyType': 'daily',
'frequency': '1'
}
historical_url = f'https://api.tdameritrade.com/v1/marketdata/{symbol}/pricehistory'
response = requests.get(historical_url, headers=headers, params=params)
data = response.json()
print(data)
```
---
### 6. **Placing a Trade Order**
- Placing orders requires additional permissions and configurations within your TD Ameritrade account.
```python
order_url = 'https://api.tdameritrade.com/v1/accounts/YOUR_ACCOUNT_ID/orders'
order_data = {
"orderType": "LIMIT",
"session": "NORMAL",
"duration": "DAY",
"orderStrategyType": "SINGLE",
"orderLegCollection": [
{
"instruction": "BUY",
"quantity": 1,
"instrument": {
"symbol": symbol,
"assetType": "EQUITY"
}
}
]
}
response = requests.post(order_url, headers=headers, json=order_data)
print(response.json())
```
### 7. **Automating API Requests**
- Using Python, you can create scheduled tasks with libraries like `schedule` or `APScheduler` to run API requests periodically, e.g., fetching data every minute or updating trade decisions based on market data.
### 8. **Error Handling and Refreshing Access Tokens**
- TD Ameritrade access tokens expire every 30 minutes, so you may need to refresh tokens periodically. TD Ameritrade provides a refresh token with a longer expiry for this purpose.
#### Example: Refreshing Access Token
```python
refresh_data = {
'grant_type': 'refresh_token',
'refresh_token': 'YOUR_REFRESH_TOKEN',
'client_id': client_id
}
response = requests.post(token_url, data=refresh_data)
new_access_token = response.json()['access_token']
```
---
Using these steps, you can build robust trading applications in Python that interact with TD Ameritrade’s ThinkOrSwim platform.
No Comments have been Posted.