Introduction to Using the IBrokers Interface to the IB API

We first need to allow API connections to the IB Trader Workstation from our own computer (localhost). So go to: Edit > Global Configuration > API > Settings and check ‘Enable ActiveX and Socket Clients’. Then add 127.0.0.1 to ‘Trusted IP Addresses’. This IP is your own computer.

We’ll first load the IBrokers and quantmod (for charting) packages with:

library(IBrokers)
## 
## IBrokers comes with NO WARRANTY.  Not intended for production use!
library(quantmod)

Connecting

Then while logged in to the TWS, type the following into R to establish a connection:

tws <- twsConnect()

‘tws’ is the name of the connection (it can be whatever you want). You can then check the connection at any time with:

isConnected(tws)
## [1] TRUE

Getting Data

Once we are connected, we may fetch historical and real time data from IB, as well as execute trades. The following are simple commands to get you started. We’ll use Twitter’s stock (ticker TWTR) as an illustration.

We first need to define the stock in R.

twtr <- twsEquity("TWTR", "SMART")

where “Smart” refers to the exchange. You can set it to a particular ECN if you would like. Once it is defined we can make a call to the function reqHistoricalData() to request the time series:

twtr.d <- reqHistoricalData(tws, twtr, barSize="5 mins", duration="6 D")
## TWS Message: 2 -1 2104 Market data farm connection is OK:usfuture 
## TWS Message: 2 -1 2104 Market data farm connection is OK:cashfarm 
## TWS Message: 2 -1 2104 Market data farm connection is OK:usopt 
## TWS Message: 2 -1 2104 Market data farm connection is OK:usfarm 
## TWS Message: 2 -1 2106 HMDS data farm connection is OK:ushmds 
## waiting for TWS reply on TWTR .... done.

This will pull TWTR stock data over the last 6 days with a 5 minute sampling frequency. The data are saved as an object named twtr.d in the global environment.

The structure of the data is:

head(twtr.d)
##                     TWTR.Open TWTR.High TWTR.Low TWTR.Close TWTR.Volume
## 2014-08-22 09:30:00     45.04     45.17    44.80      44.92        3566
## 2014-08-22 09:35:00     44.91     45.01    44.82      45.00        2253
## 2014-08-22 09:40:00     45.00     45.01    44.90      44.91        1163
## 2014-08-22 09:45:00     44.91     44.96    44.91      44.92        1065
## 2014-08-22 09:50:00     44.92     44.97    44.90      44.94         903
## 2014-08-22 09:55:00     44.93     44.97    44.85      44.92        1597
##                     TWTR.WAP TWTR.hasGaps TWTR.Count
## 2014-08-22 09:30:00    45.01            0        718
## 2014-08-22 09:35:00    44.92            0        473
## 2014-08-22 09:40:00    44.96            0        409
## 2014-08-22 09:45:00    44.94            0        411
## 2014-08-22 09:50:00    44.93            0        388
## 2014-08-22 09:55:00    44.92            0        600

where .WAP is the weighted-average price over the interval. Using quantmod to chart it for 8/22/2014:

chartSeries(twtr.d['2014-08-22'])

plot of chunk unnamed-chunk-7

Using the quantmod function Delt() we can convert the time series to returns with:

twtr.r <- Delt(twtr.d[,6])[-1]

You can also plot this transformed data with a call to chartSeries(). Here is volatility over the day — note you can change the color of the chart theme.

chartSeries(abs(twtr.r['2014-08-22']), theme='black')

plot of chunk unnamed-chunk-9

We can also open a connection and receive streaming market data with:

twtr <- twsEquity("TWTR","SMART")
twtr.mkt.data <- file('twtr.mkt.data.dat', open='a')
reqMktData(tws, twtr, file=twtr.mkt.data)

This records all market data for TWTR in a file twtr.mkt.data.dat in the working directory.

This is important in building automated trading systems. However, since R is single-threaded receiving the streaming data will lock up the R session.

We can stop receiving data with, close(twtr.mkt.data) or just click the Stop button on the Rstudio R Console.

Assignment:

Submit a web page (using R Markdown) that shows the output of doing the following:

  • Download data for some stock at a sampling frequency other than 5 minutes.
    • show the data with head()
    • chart the data with chartSeries()

Also, sumbit a .dat file with some streaming stock data.

Trading

We’ll cover trading using R/IBrokers in the next tutorial.