Trade on TD Ameritrade with R

Packages Trading rameritrade

Execute trades through TD Ameritrade using the rameritrade package in R. Zero previous programming experience required!

Exploring Finance https://exploringfinance.github.io/
10-17-2020

Key Takeaways

  1. Set up a TD Developer account
  2. Use rameritrade to trade with the TD Ameritrade API
  3. Zero programming experience required

What is R?

R is one of the most popular programming languages used for Data Analysis and Data Science along with Python. Python might be slightly more common because it is a more general purpose programming language. That being said, R was built as a language for data and statistical analysis where as Python has packages that enable data analysis. Essentially R has data analysis built into its core. The data science community is filled with articles about which is better, with no clear winner.

I personally prefer R over Python because I think it has better packages for manipulating data. The tidyverse from Hadley Wickham is an incredible suite of packages for data wrangling. Regardless, both are very powerful and widely used with deep open source communities, but this article will use R. No previous programming experience should be required.

I started using R three years ago after spending most of my early career in Excel and SQL. I took a course on EDX called The Analytics Edge that propelled me into using R on a daily basis at work. It was a great introduction to the R language and data science more broadly.

If you do not yet have R, you can download it for free here. While not required, it is a great idea to also download RStudio which makes it much easier to use R. Once installed and R/RStudio is open, the rameritrade package will need to be installed using R. rameritrade is a package that facilitates interacting with the TD Ameritrade API using R. An API (Application Programming Interface) is essentially a tool that makes it easy for computers to talk to each other. Humans interact with a User Interface, computers use APIs.

Enter the following code into the R terminal (or a new R script if using RStudio) and press control+Enter. This will install rameritrade and load the functions that allow R to communicate with the TD Ameritrade API.

# Install rameritrade from CRAN
install.packages('rameritrade')

# Load the Library into R
library(rameritrade)

Creating a TD Developer App

To trade on TD Ameritrade, a brokerage account will be required. It can be a standard brokerage account or one used on the Think or Swim platform (they are technically the same). In addition to a brokerage account, a developer app must be set up and registered on TD Developer. The ‘trading app’ is a middle layer that sits between the user and the TD Ameritrade system. It will make trades on behalf of the brokerage account. Only two things are needed to enable trading through the API.

  1. A Callback URL
  2. A Consumer Key (essentially an API key)

First, set up a developer account on TD Developer. After you register an account, click on ‘My Apps’ on the top navigation bar to Add a New App. When you add an App, the user will need to create a Callback URL. This can be anything as long as no one else has used it, for example: https://MyRApp.

Add a New App

Figure 1: Add a New App


Creating an app with Callback URL

Figure 2: Creating an app with Callback URL


Once the app has been created, a Consumer Key will be generated under ‘Keys’.
Locating the Consumer Key

Figure 3: Locating the Consumer Key

Accessing a TD Account

Once an App has been created with a Callback URL, the App has been set up with a Consumer Key provided by TD. Next is granting this App access to the TD Brokerage Account by generating a Refresh Token. The following steps only need to be completed one time. Once a Refresh Token is successfully generated, access to TD Ameritrade can be maintained indefinitely.

Step 1: Bring the Consumer Key and Callback URL into R and enter the following code:

# Enter the Callback URL in the quotes below
CallbackURL = 'https://MyRApp'
# I am hiding the key here for privacy reasons, use the full Key from the TD App
ConsumerKey = 'XHSTPK.....'

# Use the td_auth_loginURL to generate a URL to grant the app access 
td_auth_loginURL(ConsumerKey,CallbackURL)

# Output: 
# [1] "https://auth.tdameritrade.com/auth?response_type=code&redirect_uri=https://MyRApp&client_id=XHSTPK.....%40AMER.OAUTHAP"
Step 2: Log into a TD Brokerage Account and ‘Allow’ the App access to the account

The function above produces a URL that is linked to the new TD App. By visiting this URL, you will be directed to a TD Ameritrade login screen.

Login Screen

Figure 4: Login Screen

A successful log in will lead to the screen below:
Allow App Access

Figure 5: Allow App Access

Step 3: Convert the one time Authorization Code into a Refresh Token

Once clicking ‘Allow’ the next page will most likely show a type of error. This is expected. The URL at the top of this page is the Authorization Code needed in the next step.

Authorization Code

Figure 6: Authorization Code

Step 4: Use the Authorization Code to generate a Refresh Token

Copy the Authorization code into R. The Authorization Code, Consumer Key, and Callback URL will be passed to td_auth_refreshToken to generate a Refresh Token. Keep in mind, the Authorization Code can only be used one time so be sure to save the function output into a variable or Steps 1-3 will need to be repeated.

The Refresh Token is valid for 90 days so it is a good idea to save this to a secure location locally. Refresh Tokens can be used to generate new Refresh Tokens as they near expiration. If done before expiration, steps 1-4 will not be required again. See the rameritrade web page for more detailed instructions.

# Enter the authorization code with '' as shown below
AuthCode = 'https://myrapp/?code=XmNs9dZWnDlp9W1WB%2BY2m4NHOVlguLpbu%2FmIKQ5cN3eHOFmBgo2V4bIXt7p2m0Abyox8n5vG2n9ygeqg%2BhGN32AKOHglZjrdA05ap4MhpWqDBeeL6Zevm2dQYjEdirFtpx%2BU3f0Ds1XsOXMRnVaCDo0c%2Fq79URmDPq9toUN8B8UfRP3UvSHBNmv2fBJllY%2BxN4EfkFNUHlCzCDer9f6UlOJ8pBxaecx703hHZ86XKDOlTbF3uWx2ernS%2BSlqFG1EPn48mafqV0ByFkltj5rhdAGaMpoYEn0Na1IjYlwbCPW3OSnka8JnWl%2B7zotOnQt5TYehjt5pUuAP0UxQg....'

# Generate a Refresh Token. 
RefreshToken = td_auth_refreshToken(ConsumerKey, CallbackURL, AuthCode)
# [1] "Successful Refresh Token Generated"

# The Refresh Token lasts for 90 days so should be saved to reference later, but this is not critical
# This will save the token to the current working directory
saveRDS(RefreshToken,'TDRefToken.rds')
getwd() # will show where the token has been saved

Logging in and making a trade through the API

Step 5: Create an Access Token to enable trading

Once a Refresh Token is generated, it can be used to generate Access Tokens which provide short term access to the TD Accounts. The td_auth_accessToken automatically stores the Access Token into R options so that it does not need to be passed into every function.


# Obtain an access token to make a trade
AccessToken = td_auth_accessToken(ConsumerKey, RefreshToken)
# [1] "Successful Login. Access Token has been stored and will be valid for 30 minutes"
Step 6: Make a trade

Finally the fun part!

Note: I am not recommending SPLG, I am simply using it as an example


# My account number is stored locally so that I do not need to enter it in each time
accountNumber = readRDS('/home/rstudio/Secure/TDActNum.rds')
# The account number can also be entered directly in the R code
accountNumber = 1234567890



# The default is a market Order
Ord0 = td_placeOrder(accountNumber,       # TD Account number
                     ticker = 'SPLG',     # ticker to buy
                     quantity = 1,        # Number of shares to buy/sell
                     instruction = 'BUY') # instruction to buy or sell
                                  
# Check the status of the order
OrderStatus = td_orderDetail(Ord0$orderId, accountNumber)
str(OrderStatus)
# List of 19
# $ session                 : chr "NORMAL"
# $ duration                : chr "DAY"
# $ orderType               : chr "MARKET"
# $ complexOrderStrategyType: chr "NONE"
# $ quantity                : num 1
# $ filledQuantity          : num 0

# I don't actually want to make this trade, so I am cancelling the order
td_cancelOrder(Ord0$orderId, accountNumber)
# [1] "Order Cancelled"

Conclusion

This is a very basic example of making a trade on the TD Ameritrade platform using the rameritrade package in R. After the initial set up, trading becomes very easy. In future articles I will cover more complex examples such as allocating a portfolio, rebalancing, and automation.

Disclosure: This article is not intended to be financial advice. Anyone using the rameritrade package does so at their own risk and should understand the trades they are making. It is strongly recommended to make trends in off market hours first to ensure the order entry is correct.