IBrokers - Interactive Brokers and R



Similar documents
Real Time Market Data and Trade Execution with R

Algorithmic Trading with R. How to lose money without really trying.

Developing Algo Trading Applications with SmartQuant Framework The Getting Started Guide SmartQuant Ltd Dr. Anton B.

Quant Trader. Broker Connectivity and Trade Execution. Presented by Quant Trade Technologies, Inc.

Package IBrokers. R topics documented: February 19, Type Package

API Reference Guide June 2011 Updated through API Release Interactive Brokers LLC. All rights reserved.

How To Use Mts Bondspro From A Computer To A Trading System

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

irods and Metadata survey Version 0.1 Date March Abhijeet Kodgire 25th

Getting Started with the TWS Java API November 2013 Supports TWS API Release Interactive Brokers LLC. All rights reserved.

Microsoft Windows PowerShell v2 For Administrators

BarTender Integration Methods. Integrating BarTender s Printing and Design Functionality with Your Custom Application WHITE PAPER

Using the Caché SQL Gateway

Storage and Playback Getting Started Guide

Object-Oriented Databases db4o: Part 2

Network Data Management Protocol (NDMP) White Paper

Software Tool House Inc.

Introducing Apache Pivot. Greg Brown, Todd Volkert 6/10/2010

Developing a Web Server Platform with SAPI Support for AJAX RPC using JSON

PIE. Internal Structure

Integrating the Internet into Your Measurement System. DataSocket Technical Overview

DEVELOPING DATA PROVIDERS FOR NEEDFORTRADE STUDIO PLATFORM DATA PROVIDER TYPES

Expedite for Windows Software Development Kit Programming Guide

JSE ITAC INITIATIVE. Frequently Asked Questions. July 2014

q for Gods Whitepaper Series (Edition 7) Common Design Principles for kdb+ Gateways

Software Automated Testing

DiskPulse DISK CHANGE MONITOR

NASA Workflow Tool. User Guide. September 29, 2010

Oracle Marketing Encyclopedia System

mframe Software Development Platform KEY FEATURES

socketio Documentation

SOFTWARE TESTING TRAINING COURSES CONTENTS

Transparent Redirection of Network Sockets 1

INTRODUCTION TO ATRIUM... 2 SYSTEM REQUIREMENTS... 2 TECHNICAL DETAILS... 2 LOGGING INTO ATRIUM... 3 SETTINGS... 4 NAVIGATION PANEL...

CheckPoint FireWall-1 Version 3.0 Highlights Contents

CORRELATE for Microsoft Sharepoint Windows Services

OpenText Output Transformation Server

Commander. The World's Leading Software for Label, Barcode, RFID & Card Printing

S3 Monitor Design and Implementation Plans

1 Basic Configuration of Cisco 2600 Router. Basic Configuration Cisco 2600 Router

A Java proxy for MS SQL Server Reporting Services

Web Services for Management Perl Library VMware ESX Server 3.5, VMware ESX Server 3i version 3.5, and VMware VirtualCenter 2.5

Building Applications Using Micro Focus COBOL

Who? Wolfgang Ziegler (fago) Klaus Purer (klausi) Sebastian Gilits (sepgil) epiqo Austrian based Drupal company Drupal Austria user group

Complete Java Web Development

Dell One Identity Cloud Access Manager How to Develop OpenID Connect Apps

BarTender s ActiveX Automation Interface. The World's Leading Software for Label, Barcode, RFID & Card Printing

Amazon Web Services Primer. William Strickland COP 6938 Fall 2012 University of Central Florida

Intel NetMerge Call Processing Software Introduction

Version Overview. Business value

Integrating Autotask Service Desk Ticketing with the Cisco OnPlus Portal

Triton. All the trading power of ITG, now on your desktop. Client-Site Trading Products

Developing Microsoft SharePoint Server 2013 Advanced Solutions

Valdi for Equity Trading High performance trading solutions for global markets

T R A D I N G S O L U T I O N S

EMC AVAMAR INTEGRATION WITH EMC DATA DOMAIN SYSTEMS

Lab Management, Device Provisioning and Test Automation Software

Oracle Primavera Gateway

How To Install Linux Titan

unipaas V1.9g Release Notes

CA VM:Operator r3. Product Overview. Business Value. Delivery Approach

In: Proceedings of RECPAD th Portuguese Conference on Pattern Recognition June 27th- 28th, 2002 Aveiro, Portugal

Agent Languages. Overview. Requirements. Java. Tcl/Tk. Telescript. Evaluation. Artificial Intelligence Intelligent Agents

Integrating VoltDB with Hadoop

Property & Casualty Insurance Solutions from CCS Technology Solutions

Print Audit 6 Network Installation Guide

CORD Monitoring Service

TATJA: A Test Automation Tool for Java Applets

Migrating Non-Oracle Databases and their Applications to Oracle Database 12c O R A C L E W H I T E P A P E R D E C E M B E R

EDISPHERE. Application Integration

Ikasan ESB Reference Architecture Review

Data Center Automation with SUSE Manager Federal Deployment Agency Bundesagentur für Arbeit Data Center Automation Project

The EMSX Platform. A Modular, Scalable, Efficient, Adaptable Platform to Manage Multi-technology Networks. A White Paper.

HP Operations Orchestration Software

Jonathan Worthington Scarborough Linux User Group

Security Overview of the Integrity Virtual Machines Architecture

Kore Bots Platform Competitive Comparison Overview Kore Bots Platform Competitive Comparison Overview

Windows PowerShell Cookbook

Website Builder Quick Start. This document describes the API calls and steps needed to get started using the enom Website Builder.

Using the Studio Source Control Hooks

PERFORMANCE STABILITY CONNECTIVITY TIME TO MARKET. A Bloomberg offering

SimWebLink.NET Remote Control and Monitoring in the Simulink

Test Run Analysis Interpretation (AI) Made Easy with OpenLoad

ASSET AND INVESTMENT MANAGER (AIM) A Bloomberg Trading Solutions Offering BE AGILE

The ECL Scheduler. Boca Raton Documentation Team

Insurance was never like this before!

HP OO 10.X - SiteScope Monitoring Templates

Limi Kalita / (IJCSIT) International Journal of Computer Science and Information Technologies, Vol. 5 (3), 2014, Socket Programming

Addressing Mobile Load Testing Challenges. A Neotys White Paper

Transparent Redirection of Network Sockets 1

Developing large-scale Applications in Python

GLOBAL CONSULTING SERVICES TOOLS FOR WEBMETHODS Software AG. All rights reserved. For internal use only

Extensibility. vcloud Automation Center 6.0 EN

Java Web Services SDK

Transcription:

IBrokers - Interactive Brokers and R Jeffrey A. Ryan September 21, 2014 Contents 1 Introduction 1 2 The API 2 2.1 Data.................................. 2 2.2 Execution............................... 2 2.3 Miscellaneous functionality..................... 3 3 IB and R 3 3.1 Getting started............................ 3 3.2 Getting data from the TWS..................... 4 3.3 Future API access.......................... 6 4 Conclusion 6 Abstract The statistical language R offers a great environment for rapid trade idea development and testing. Interactive Broker s Trader Workstation offers a robust platform for execution of these ideas. Previously it was required to use an external language to interface the impressive API capabilities of the Trader Workstation be it Java, Python, C++, or a myriad of other language interfaces, both officially supported or otherwise. What had been lacking was a native R interface to access this impressive API. This is now available in the new IBrokers package. 1 Introduction 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. Interactive Brokers [1] is an international brokerage firm specializing in electronic execution in products ranging from equities to bonds, options to futures, as well as FX, all from a single account. To facilitate this they offer access 1

to their Trader Workstation platform (TWS) through a variety of proprietary APIs. The workstation application is written in Java and all communication is handled via sockets between the client and the TWS. Access to the API has official support in Java (all platforms), as well as C++, DDE for Excel, and ActiveX (available only for Windows). There are numerous third-party applications and API interfaces available to access the API. These include IbPy - a python translation of the official Java code, a Perl version, and a portable C version. All of these methods, while useful outside of R [3] can t offer true R-level access, including native callbacks and error management, to the TWS API. For this an R solution was required. What this also means is that this implementation is restricted at present to single-threaded API access. This introduction is broken into two parts. First it will provide an overview of the overall API from Interactive Brokers, as well as examine some of the more common documented methods. The second section will examine the specific implementation of this API in the IBrokers [4] package. 2 The API The most up to date documentation on the overall API can be found on Interactive Brokers own site [2]. While it is a constantly evolving library - most of the core functionality persists from one version to the next. The principal purpose of the API is to offer a programmatic alternative to manual screen-based trading through Interactive Brokers. 2.1 Data In order for trade decisions to be automated, data must be processed by the client application. To retrieve real-time data from the TWS there are three primary access methods - reqmktdata, reqmktdepth, and reqrealtimebars. Additionally, limited historical data can be retrieved for many products via the reqhistoricaldata accessor function. All of these operate with callback handlers within the public API - so it is possible to allow for custom actions based on the incoming data. New in the beta version of the API are tools to access fundamental data from Thompson Financial. These are not in production versions as of this writing. 2.2 Execution The API also allows for order execution to be programmatically driven. Through a variety of functions, it is possible to view, modify, and submit orders to be executed by the TWS. 2

2.3 Miscellaneous functionality Additional functionality offered includes access to account information, contract details, connection status and news bulletins from the TWS. 3 IB and R As R offers an ever-growing tooklit of statistical as well as financial functionality, it is becoming a platform of choice for quantitative research and even trading. For institutional users many tools exists to help tie data from external sources into R. Probably the most common is the use of Bloomberg data in R via the RBloomberg package. While many professionals have access to a Bloomberg terminal, it is not usually practical or necessary for smaller or single product traders. Interactive Brokers gives these users access to many professional features - as well as industry leading executions and prices - all from a solid GUI based application. To make the transition to programmatically interacting with this application, it had been necessary to use one of the supported or contributed API libraries available. For many users this poses no issue as many are either unaware of R as a quantitative platform, or make use of it in a limited manner. For those that use R more frequently it is important to find a workable solution accessible from within R. This is the purpose of IBrokers. 3.1 Getting started The first step in interacting with the TWS is to create a connection. To do so, it is first necessary to enable the TWS to allow for incoming socket connections. The TWS user manual is the most up to date reference on how to accomplish this, but as of this document it is simply a matter of Configure > API > Enable ActiveX and Sockets. You should also add your machine (127.0.0.1) to the Trusted IP Addresses. An new option for connecting to Interactive Brokers API is now available using the IBGateway client provided by Interactive Brokers. This is a lowresource, non-gui application that can be used in place of the TWS. The only variation to the connection procedure is that the default port for the IBGateway application is 4001, which must be changed in the twsconnect call if used. For the rest of the document, TWS will be used but keep in mind all functionality is now available when using the IBGateway as well. From the R prompt, load the package and establish a connection. Once connected you can then check some basic connection information. Multiple TWS connections are allowed per client, though a distinct clientid is required, and given R s single threaded nature it is not of much value in a single session. Multiple R sessions can run against a single TWS instance though, and in that case would require distinct clientid values. If no further queries are required, twsdisconnect will disconnect the R session from the TWS. 3

> library(ibrokers) > tws <- twsconnect() > tws > reqcurrenttime(tws) > serverversion(tws) > twsdisconnect(tws) 3.2 Getting data from the TWS The current IBrokers implementation is focused on retrieving data from the TWS. To that end, five important functions are made available in the API: reqcontractdetails: retrieves detailed product information. reqmktdata: retrieves real-time market data. reqmktdepth: retrieves real-time order book data. reqrealtimebars: retrieves real-time OHLC data. reqhistoricaldata: retrieves historical data. In addition, due to the complexity of requests, helper functions unique to IBrokers are included to make constructing these requests faster and less error-prone. A family of contract specifier functions used for the above calls includes: twscontract: create a general Contract object. twsequity/twsstk: wrapper to create equity Contract objects twsoption/twsopt: wrapper to create option Contract objects. twsfuture/twsfut: wrapper to create futures Contract objects. twsfuture/twsfop: wrapper to create futures options Contract objects. twscurrency/twscash: wrapper to create currency Contract objects. twsbag: wrapper to create a combo. Using the above functions to request market data from the TWS is quite straightforward. > tws <- twsconnect() > twsfuture("ym","ecbot","200809") > reqcontractdetails(tws, twsequity("qqqq")) > reqmktdata(tws, twsequity("qqqq")) Unique again to the IBrokers implementation is the use of passed callback handlers to the data functions. These are available to help customize output and to facilitate the creation of automated trading programs based on user-defined criteria coded entirely in R. 4

Each function has a file argument which allows for persistent data capture to a file. In the case of the real-time methods, file is passed internally to cat, which mean that the argument may contain a file name or any valid connection object. Using the default arguments, with some minor allowable exceptions, it is possible to record incoming data to a file for later playback using the same request functions used on live data. The playback argument allows for one to control the speed of the returned data. By default playback=1 the data is retrieved with respect to the original timestamps. This value is multiplied by the difference in time between original message timestamps, increasing the value will slow the playback and decreasing toward 0 will speed up the playback. > reqmktdata(tws, twsequity("sbux"), CALLBACK=NULL, file="sbux.dat") > twsp <- twsconnect(filename="sbux.dat") To playback the saved data, call reqmktdata again: > reqmktdata(twsp) > reqmktdata(twsp, playback=0) Each data function has special callback methods associated with the expected results. These are documented in the standard R help files of IBrokers. Each distinct message recieved from the TWS invokes a callback function - by default the callbacks built into IBrokers. Users may set these callbacks to functions of there own design, or set them to NULL to return the raw message data, as was show previously when saving data for later playback. Additionally, the real-time data methods reqmktdata, reqmktdepth, and reqrealtimebars all have a special CALLBACK argument to allow for custom raw message handling. This allows for simplified management of data calls, while offering highly customizable receiver handling. Using this will bypass the built in error management of TWS errors, so the developer should be aware of low-level API interactions before using this feature. Using CALLBACK involves some understanding of the underlying API process within IBrokers. In general it is as simple as sending a special series of nul seperated messages to the TWS, and then interpreting the messages returned. All are character strings, and each request or returned value starts with an identifying code indicating the nature of the content to follow. The current data methods, based on the official API, simply request the data, and then enter into a loop awaiting the returned messages branching to message specific callbacks as appropriate. Utilizing a custom CALLBACK method allows for this loop to be contained entirely within your own code. Setting CALLBACK=NULL will send to raw message level data to cat, which in turn will use the file argument to that function to either return the data to the standard output, or redirected via an open connection, a file, or a pipe. The details of this can be seen in the help pages for R s cat. Setting CALLBACK=NA will result in a request to the API for the data in question, but will not enter into a loop to manage the incoming messages. 5

This can be used to launch multiple requests within one R session, and then followed with code to read the resulting messages. This is simply a short-cut to hand-coding the requests, and provides no built in message handling logic. This also means that the incoming messages will continue to accumulate until read or cancelled by your code, or a disconnect from the TWS. Obviously this requires the most work, but can offer the most flexibility when it comes to producing a true real-time analysis tool. An additional caveat with respect to multiple requests within a single session. It is important to recognize that each request must have a unique tickerid associated with it, to identify the returned content properly. At present, this must be kept track of by the user. 3.3 Future API access Future additions will focus on implementing a robust order management collection of functions to allow for a complete data processing trade workflow. Additionally, more of the standard API tools will contiue to be integrated into the package. 4 Conclusion The TWS platform offers the quantitative trader unparalleled access to automated trading tools via its API. IBrokers allows the R developer direct access to this API for rapid trade idea development, testing, and eventual execution. References [1] Interactive Brokers: Interactive Broker s Trader Workstation and API, URL http://www.interactivebrokers.com [2] Interactive Brokers Application Programming Interface: Interactive Broker s Trader Workstation API, URL http://individuals.interactivebrokers.com/en/p.php?f=programinterface&ib entity=llc [3] R Development Core Team: R: A Language and Environment for Statistical Computing, R Foundation for Statistical Computing, Vienna, Austria. ISBN 3-900051-07-0, URL http://www.r-project.org [4] Jeffrey A. Ryan: IBrokers: R API to Interactive Brokers Trader Workstation, R package version 0.3-0, 2008 6