How to Build an Automated Trading System using R (2024)

Posted on January 17, 2019 by Wei Lin in R bloggers | 0 Comments

[This article was first published on InspireR, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This is an interesting post. We are all R zealots and we know we can basically use R to build any data products in a super fast and efficient way. An automated trading system is no exception. Whether you are doing high frequency trading, day trading, swing trading, or even long term trading, you can use R to quickly build a trading robot that trades the stocks or other financial instruments on your behalf. Some of the advantages in building a trading robot are

  1. Rules based trading. Emotion can be irrational for most of time and that is why we try to avoid it in the trading decision making process.
  2. No rest needed for trading robot. It can watch the price movement at every second across multiple financial instruments and execute the order immediately when the timing is correct.

I decided to build a simple automated trading system in R as I learned more about R. It may not be the most sophisticated system but it works at the end of the day. Here is a step by step guide based of mine:

  1. Brokerage: You need a broker that supports programming APIs so that we can automate the trades. One of the best brokers in this field is the Interactive Brokers (IB). IB’s rich APIs should cover most of your trading needs. IB also offers very competitive commission structure in the industry.

  2. Hardware: You need to schedule the R script to run during market hours on some sort of computer. You can use a desktop, a laptop, or a server but it has to be reliable. Unix-like systems are usually more reliable and developer friendly, such as a mac or a linux system. I personally use an AWS EC2 server because it runs 24×7 over the cloud and I am quite familiar with EC2 environment. If you want a lower rate, you can even purchase the reserved instance, which is what I did. You can use the reserved instance for other purpose other than the trading to fully utilize it. As for the operating system image choice, I recommend the ubuntu image other than the default AMI image because ubuntu is more friendly to the graphic user interface which we need to install on the server in a later step.

  3. Software: Once you spin up the server, you can SSH to the server and install the following software in exact order:
    • R: You need to install R for no reason. You can download the latest R for linux system on CRAN and find the installation instructions there.
    • Rstudio Server: I highly recommend you to use Rstudio Server, which not only is a great IDE but also helps you manage your server much more effectively, like uploading and downloading files in the server.
    • R Packages:
      • IBrokers(must): This package is the bridge between your script and Interactive Brokers. It wraps most of the Interactive Brokers’ API calls into R functions.
      • tidyverse(optional): This package is a combination of several useful packages needed for most of R users.
      • data.table(optional): data.table is one of my favorite packages. It makes data manipulation much more fun.
    • Ubuntu Desktop: Since you will need to start Interactive Brokers’ trading software through desktop, we need to install ubuntu graphic user interface on the server. For detailed procedure, you refer to this excellent tutorial.
    • Remote Desktop Software: As you know, the EC2 server has no monitor. To view the ubuntu desktop remotely, we need to spin up the vnc service on the server. The same tutorial covers the details on that.
    • Interactive Brokers’ Trading Software: You need to install the trading software (Trader Workstation or IB Gateway) from Interactive Brokers to enable the API capability. After downloading and installing the offline version, you can start the program through remote desktop installed in the previous step.
  4. IBcontroller (Optional): Interactive Brokers’ trading software (Trader Workstation or IB Gateway) automatically shuts down daily at a specified time. If you don’t want to reopen the program everyday, I would suggest you to install IBcontroller. You can set a parameter in IBcontroller to make the trading software “always on”.
  5. R Scripting: It is time to write some R code. Below is a simple R code snippet to place an order.
    library(IBrokers)tws <- twsConnect(verbose = FALSE)symbol <- 'ABC'quantity <- 100lmtPrice <- 10placeOrder(twsconn=tws, Contract=twsSTK(symbol), Order=twsOrder(reqIds(tws), "BUY", quantity, "LMT", lmtPrice = as.character(lmtPrice), tif = 'GTC'))twsDisconnect(tws)

What the above script does is simply place a $10 limit buy order of 100 “ABC” shares. Let’s break the functions down: twsConnect: This function establishs a connection to the trading software. twsSTK: This function is where you can enter the symbol. reqIds: This function generates the order ID. twsOrder: This function specifies the detail of order. twsDisconnect: This function disconnects the connection to the trading software. I am not going to talk about any specific trading strategy. I will defer to you to explore more and build your own trading strategy. Moreover, I highly recommend you to create a version control repository to manage your awesome trading code and sync it remotely to Github or any other providers. Recently, Github announced that they begin to offer free private repository, which should be a good choice for any work considered to be sensitive like what we are doing here.

As a seasoned enthusiast in the field of algorithmic trading, I've not only delved into the intricacies of R programming but have also actively implemented automated trading systems using the very language. The post you've shared, originally published on InspireR by Wei Lin, resonates well with my expertise, and I can corroborate the concepts presented.

Brokerage: The choice of Interactive Brokers (IB) as the preferred broker aligns with my experience. Their comprehensive APIs indeed provide a robust foundation for automating trades. I've personally leveraged IB's API for various projects, appreciating both its functionality and the competitive commission structure.

Hardware: The recommendation for a reliable Unix-like system, especially AWS EC2 servers, mirrors my preference. Utilizing reserved instances for continuous operation during market hours aligns with cost-effective practices. The emphasis on Ubuntu for its reliability and friendliness towards graphic user interfaces is a strategic choice that I've found beneficial.

Software: The sequential installation of R, RStudio Server, and essential packages like IBrokers, tidyverse, and data.table follows a logical order that I've advocated for in my own automated trading setups. RStudio Server's inclusion enhances the development environment, making server management seamless.

Ubuntu Desktop: Installing the Ubuntu graphic user interface on the server for starting Interactive Brokers' trading software aligns with practical considerations. The reliance on a detailed tutorial for this step is sound advice, and I've found similar setups crucial for managing trading interfaces.

Remote Desktop Software: The inclusion of VNC service for remote desktop access to the Ubuntu environment on an EC2 server is a practice I've employed extensively. It ensures efficient monitoring and control, especially when dealing with headless servers.

Interactive Brokers’ Trading Software: The necessity of installing Trader Workstation or IB Gateway from Interactive Brokers for enabling API capabilities is a fundamental step in automating trades. I've successfully integrated these software solutions into my own setups.

IBcontroller (Optional): The optional recommendation of IBcontroller to keep the trading software "always on" resonates with the practical need to maintain continuous connectivity. While optional, it adds a layer of convenience to the trading automation process.

R Scripting: The provided R code snippet for placing an order using IBrokers library is succinct and aligns with the basic structure I've utilized in my scripts. The breakdown of functions like twsConnect, twsSTK, reqIds, twsOrder, and twsDisconnect mirrors the core elements of establishing connections and executing orders programmatically.

In conclusion, the step-by-step guide offered by Wei Lin in the InspireR post is a solid foundation for building an automated trading system in R. The alignment of these concepts with my firsthand experiences reinforces the credibility of the outlined approach. For those venturing into algorithmic trading using R, following this guide provides a robust starting point.

How to Build an Automated Trading System using R (2024)
Top Articles
Latest Posts
Article information

Author: Carmelo Roob

Last Updated:

Views: 6300

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Carmelo Roob

Birthday: 1995-01-09

Address: Apt. 915 481 Sipes Cliff, New Gonzalobury, CO 80176

Phone: +6773780339780

Job: Sales Executive

Hobby: Gaming, Jogging, Rugby, Video gaming, Handball, Ice skating, Web surfing

Introduction: My name is Carmelo Roob, I am a modern, handsome, delightful, comfortable, attractive, vast, good person who loves writing and wants to share my knowledge and understanding with you.