Interactive Brokers With R: Ibrokers Trading API

IBrokers - R Package for Trading with IB API

By Milind Paradkar

Interactive Brokers (IB) is a leading U.S.-based electronic brokerage firm. Interactive Brokers offers API solutions in different programming languages like Java, .NET (C#), C++, ActiveX or DDE to build your own trading applications. Apart from these programming languages, traders can also trade on Interactive Brokers with R or Python.

In our previous article, we covered IBridgePy written by Dr. Hui Liu. IBridgePy is a wrapper for Interactive Brokers’ C++ API that allows one to trade in Interactive Brokers (IB) using Python. The article covered the key topics from the webinar, “Trading with Interactive Brokers using Python”, which was conducted by Dr. Hui Liu and hosted by QuantInsti®. You can watch the recording of Dr. Hui Liu’s webinar here.

Interactive Brokers With R: Ibrokers Trading APIClick To Tweet

Another popular programming language that is widely used by algorithmic developers for data analysis, coding strategies, and backtesting is R programming. Interactive Brokers in collaboration with QuantInstiTM hosted a webinar, “Trading using R on Interactive Brokers” which was held on 2nd March 2017 at 10:00 AM ET.  The webinar was conducted by Anil Yadav, Director at QuantInsti®. Anil is also an Algo strategy advisor at iRageCapital, one of the leading HFT firms in India and has managed a portfolio of equity futures using Interactive Brokers with R. The webinar was very well received by the audience and it covered all the relevant topics to get one trading in live markets on Interactive Brokers with R! You can click on the download button below for the related R files used in the webinar.

The webinar covered the following topics:

  • Installing R-studio IDE
  • Reference sheet for the IBrokers Package
  • TWS configuration
  • Understanding the structure – CallBack, eWrapper, ProcessMessage
  • Viewing account information details in R
  • Downloading historical data in R
  • Printing real-time data on R console
  • Sending predefined order using R script
  • Sending event based order using R script

The webinar includes sample strategy and also mentions the warnings and pitfalls that a developer needs to be aware of when trading on Interactive Brokers with R.

This post gives a brief on the IBrokers package for all the R coders/enthusiasts, Interactive Brokers’ clients, and wannabe traders.

Learn Algorithmic trading from Experienced Market Practitioners




  • This field is for validation purposes and should be left unchanged.

About the Interactive Brokers’ APIs

Before we cover the IBrokers package a short brief on the application program interfaces (APIs) offered by Interactive Brokers (IB) for trading programmatically. IB is an international brokerage firm which specializes in electronic execution in products ranging from equities to bonds, options to futures, Forex, all from a single account. Trader Workstation (TWS) is Interactive Brokers widely used desktop trading platform. Interactive Brokers provides several API programming languages (Java, .Net, C++, ActiveX, DDE.) which can be used to link to one’s system and trade on your IB account. The API allows you to connect through either the TWS or the IB Gateway.

  1. Connecting through the TWS requires that you have the application running, but also allows you to test and confirm that your API orders are working correctly.
  2. Connecting through the IB Gateway allows you to use the API without a large graphical user interface (GUI) application running, but does not provide an interface for you to test and confirm API activity.

Some of the key uses of the API include:

  1. To retrieve real-time data from the TWS
  2. To programmatically execute the orders (view, modify, and submit orders to be executed)
  3. Access to account information, connection status.
  4. Access to contract details and news bulletins from the TWS.

Exploring the IBrokers package

The IBrokers package authored by Jeffery Ryan is a pure R implementation of the TWS API and lets you trade in Interactive Brokers with R. We will cover some of the important functions from the package in this post.

To install the IBrokers package, follow the standard installation function in R, i.e. install.packages().

install.packages(“IBrokers”)

Some important functions from IBrokers package:

twsConnect Function

This function is used to establish, check or terminate a connection to TWS. The function returns a twsConnection object for use in subsequent TWS API calls.

Example:

# To establish a connection to TWS
tws = twsConnect()

# To check the connection to TWS
isConnected(tws)

# To disconnect 
twsDisconnect(tws)

twsConnectionTime Function

This function provides the time when the connection to the TWS was made.

Example:

library(IBrokers)
tws = twsConnect()
twsConnectionTime(tws)

[1] “20170227 10:10:38 IST”

reqAccountUpdates Function

This function is used to request and view account details from Interactive Brokers.

Example:

library(IBrokers)
tws = twsConnect()
accountInfo = reqAccountUpdates(tws)
head(accountInfo)

# [[1]]
# value       currency
# AccountCode            DU15157
# AccountOrGroup         DU15157   USD
# AccountReady           true
# AccountType            UNIVERSAL
# AccruedCash            0         USD

twsContract Function

This function creates, test or coerces a twsContract for use in API calls. The value returned by the function is a twsContract object.

Example:

contract = twsContract(0,"AAPL","STK","SMART","ISLAND", "","0.0","USD","","","",NULL,NULL,"0")

Similarly, there is a twsCurrency function which is a wrapper to twsContract to make ‘currency/FX’ contracts easier to specify.

reqMktData Function

This function allows for streaming market data to be handled in R.

Example:

library(IBrokers)
tws = twsConnect()
symbol = twsSTK("AAPL")
reqMktData(tws,symbol)

reqHistoricalData Function

This function is used to request historical data from TWS.

Example:

library(IBrokers)
tws = twsConnect(port=7497)
symbol = twsSTK("AAPL")
data_AAPL = reqHistoricalData(tws, symbol)
print (data_AAPL)

placeOrder Function

This function is used to place or cancel an order to the TWS.

Example:

library(IBrokers)
tws = twsConnect()
id = as.numeric(reqIds(tws))
myorder = twsOrder(id, orderType="STP LMT", lmtPrice="108.01",
                   auxPrice="108.10",action="SELL",totalQuantity="10"
                   transmit=FALSE)    
placeOrder(tws, twsSTK("AAPL"), myorder))

These were some of the key functions of the IBrokers package. One can formulate a strategy using other statistical packages in R and then use the functions from the IBrokers package to retrieve market data, view account info, and execute/modify orders via R.

Disclaimer: This software is in no way affiliated, endorsed, or approved by Interactive Brokers or any of its affiliates. It comes with absolutely no warranty and should not be used in actual trading unless the user can read and understand the source. IBrokers is a pure R implementation of the TWS API.

Next Step

If you want to learn various aspects of Algorithmic trading then check out the Executive Programme in Algorithmic Trading (EPAT™). The course covers training modules like Statistics & Econometrics, Financial Computing & Technology, and Algorithmic & Quantitative Trading. EPAT™ equips you with the required skill sets to be a successful trader. Enroll now!

Learn Algorithmic trading from Experienced Market Practitioners




  • This field is for validation purposes and should be left unchanged.

Download Data File

  • Webinar Files

Login to DOWNLOAD these files for FREE!

Existing Users Log In