Connecting to Interactive Brokers TWS Using Java
Author: Joe
Tutorial Objective: Connect to TWS using
Java
Souce Code: Download the full source
for this tutorial Here
Disclaimer
This tutorial is to be used at your own risk. By using this tutorial
you agree not to hold the writers of this tutorial, StockBotProgramming.com,
or anyone affiliated with StockBotProgrammign.com liable for any
damages that may occur as a result of using this tutorial and/or
provided source code.
This tutorial will assume you are using Java NetBeans, however if
you are familiar with Eclipse the same ideas apply. You will also
need the TWS API, which is available for download Here.
The goal of this tutorial is to teach you how to use the TWS API
with Java, not to teach Java. If you are unfamiliar with using Java
read through the tutorials found Here. Although
we are not trying to teach Java in this tutorial, we will try to
make things as simple as possible. The code generated here will
not be the "best" or most "optimized" ways of doing things. That
is not the point of the tutorial. We want to provide a simple and
workable foundation on which to build a bot. If you have any suggestions
regarding this tutorial or if you notice any mistakes suggest it
here.
First we will need to create a new project, so open NetBeans if
you haven't already. Now click File->New Project. Select General->Java
Application and click next. Name your project "JavaTutorial1" and
click finish. The first thing we need to do is get Java set up to
use the api. The easiest way to do this is from within NetBeans
right click on JavaTutorial1 and select properties. From the source
category click "Add Folder". Now navigate to the folder where the
tws api is installed. The folder you want to add is called com.
On my computer the folder is at c:\jts\java\com
Now inside your main.java file add the line:
import com.ib.client.*;
Put that line after the package declaration. The next thing we need
to do is make the Java application run our main class. At the bottom
of the source code you should see
public static void main(String[] args) {
// TODO code application logic here
}
Where it says add the following line after the TODO comment:
Main myMain= new Main();
Next, go towards the top of the source code to the main class declaration
and change the class declaration to:
public class Main implements EWrapper{
If you tried building the project now you will notice a lot of errors.
Since we are implementing the EWrapper class, we must add all of
the required function prototypes to our code. Add the following
lines to the class:
public void tickPrice(int tickerId, int field,
double price,int canAutoExecute )
{
}
public void tickSize(int tickerId, int field, int size)
{
}
public void orderStatus( int orderId, String status, int filled,
int remaining, double avgFillPrice, int permId, int parentId, double
lastFillPrice, int clientId)
{
}
public void openOrder(int orderId, Contract contract, Order order)
{
}
public void error(String str)
{
}
public void connectionClosed()
{
}
public void updateAccountValue(String key, String value, String
currency, String accountName)
{
}
public void updatePortfolio(Contract contract, int position, double
marketPrice, double marketValue)
{
}
public void updateAccountTime(String timeStamp)
{
}
public void nextValidId(int orderId)
{
}
public void contractDetails(ContractDetails contractDetails)
{
}
public void execDetails(int orderId, Contract contract, Execution
execution)
{
}
public void error(int id, int errorCode, String errorMsg)
{
}
public void updateMktDepth(int tickerId, int position, int operation,
int side, double price, int size) {
}
public void updateMktDepthL2(int tickerId, int position, String
marketMaker, int operation, int side, double price, int size) {
}
public void updateNewsBulletin( int msgId, int msgType, String message,
String origExchange){
}
public void managedAccounts( String accountsList){
}
public void receiveFA(int faDataType, String xml){
}
public void intradayData(int reqId, String date, double open, double
high, double low, double close, int volume, double WAP, boolean
hasGaps){
}
public void updatePortfolio(Contract contract, int position, double
marketPrice, double marketValue, double averageCost, double unrealizedPNL,
double realizedPNL, String accountName){
}
public void scannerData(int reqId, int rank, ContractDetails contractDetails,
String distance, String benchmark, String projection){
}
public void scannerData(int reqId, int rank, ContractDetails contractDetails,
String distance, String benchmark, String projection,String temp){
}
public void historicalData(int reqId, String date, double open,
double high, double low,
double close, int volume, int other, double WAP, boolean hasGaps)
{
}
public void bondContractDetails(ContractDetails contractDetails){
}
public void tickEFP(int x,int y,double m,String
str1,double n,int k,String str2,double l ,double v)
{
}
public void tickString(int a,int b,String
c)
{
}
public void tickGeneric(int a,int b,double
c)
{
}
public void tickOptionComputation(int a,int
b,double c ,double d,double e,double f)
{}
public void error(Exception e)
{
}
Now we are almost on the home stretch. Go to the Main initialization
function at the top of the code. We will add our connection code
here so the application connects on startup. The first lines you
want to add are:
EClientSocket m_client = new EClientSocket(this);
m_client.eConnect("127.0.0.1",7496, 0);
This call has 3 parameters. The first is the ip address where TWS
is running. In our example we used "127.0.0.1" which is your local
box that you are on. The second parameter 7496 is the socket port
number that TWS is listening on. By default this is the port, however
you can change this from within TWS. The last parameter is the client
id. This tells the TWS who you are. We chose 0 in this case. If
you wanted to run a second bot connected to this same TWS make its
client id 1, or another number besides 0. This is a good time to
make sure that your TWS is set to accept bot connections. To do
this turn on TWS if not already on and go to: Configure->Api and
make sure there Is a check next to Enable ActiveX and socket clients.
Now the program will connect to the TWS on startup. To test this
code make sure TWS is turned on and configured to allow socket connections.
Next build the NetBeans project and then run it. At the bottom of
the screen NetBeans outputs some information, you should see something
like "TWS Time at connection:20070424 10:32:31 CST". If this is
what you see then congratulations, you now can connect to the TWS
using the API. You are well on your way towards building a fully
functional Bot. Next we will add a tutorial showing how to get data
on a particular stock symbol.
Download the full source for this project Here
|