Connecting to Interactive Brokers API with Java

Introduction

The hardest part of creating your own automated trading system (ATS) is starting. This article is the first step of creating ATS. API provides great flexibility in implementing your automated trading ideas, all of its functionality runs through TWS or IB Gateway. This means that you must have a TWS account with IB, and that you must have your TWS/IB Gateway running in order for the API to work.

Download and Install IB API client

This step takes you out to the IB download API website at interactivebrokers.github.io

  1. Download twsapi_macunix.n.m.jar to your computer. I use version 9.71.
        (where n and m are the major and minor version numbers respectively.)
  2. Access the command line terminal.
        (On a MAC from the Applications menu. First select Utilities then select Terminal.)
  3. At the command line, extract the contents of the jar file by typing, where n.m is your version:
        jar xf twsapi_macunix.n.m.jar

    screen-shot-2017-01-08-at-18-05-14

    Fig.1: OSX Terminal window with unpacking command

  4. Open Netbeans and create new project
       (File-> New Project -> Java Application -> YourProjectName -> Finish)
  5. Add JavaClient source package folder
       (Right click your project -> Properties -> Source -> Add Folder -> ../IBJts/source/JavaClient  )
screen-shot-2017-01-08-at-18-06-18-1

Fig.2: NetBeans Project Properties window

 

Connecting to API

Now when we are done with installation we can continue to actually connecting to our account. In our package we create two classes. Logger.java and API.java. We creating Logger.java, because its parameter in ApiController constructor method.

In logger we implement all abstract methods. In our case it’s just method log().

Now in our main class we implements IConnectionHandler Interface from com.ib.controller.ApiController. Again we have to implement all its abstract methods. For the sake of simplicity we leave them empty.

 

Now when we run our API (you have to be logged in IB Gateway) we should seen following output:

screen-shot-2017-01-08-at-18-47-57

Fig.3: NetBeans console output after successful connection

And in IB Gateway we should seen our client connected:

screen-shot-2017-01-08-at-18-46-29

Fig.4: IB Gateway window after successful client connection

As you notice we have public void connected() and public void disconnected() methods implemented but not used, so far. This two methods serving as hooks and are called after api is connected() and after api is disconnected(). So this is your starting point. Good luck!

o3gemve

Fig.5: Unlimited power you now have

Resources

[1] IB API Reference Guide

[2] IB API Download page

[3] [PDF] Java API Getting Started

 

 

Buy me a coffeeOut of coffee 😱, please help!