Connecting to Interactive Brokers TWS Using C++
Author: Joe
Tutorial Objective: Connect to TWS using
C++
Souce Code: Download
the full source for this project 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 have a copy of Visual Studio 2005 and
have Interactive Broker's TWS API installed. You can get a copy Visual
Studio Here,
and the TWS API is available for download Here.
The goal of this tutorial is to teach you how to use the TWS API with C++,
not to teach C++. If you are unfamiliar with using C++ read through the
tutorials found Here. Although we are not trying to
teach C++ 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.
Also, I am aware that this tutorial is actually "C" and not "C++". 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. Open up Visual Studio
2005. Now select File->New->Project. Select Other languages->Visual
c++->win32->win32 console application. Name the project c++tutorial1.
Now click finish.
To make this work we will actually be using a c library for TWS.
This library is found at here.
You can download just the files needed from Here. After you download these files place them in
the folder with the rest of your project's source code.
The next step is to click project->Add Existing item. Add twsapi.c
to the project. Now we need to make several changes to the project
settings. First, go to the property page for the project. Now go
to Configure Properties->C/C++->Precompiled Headers. Chose Not using
precompiled headers. Second, in Configure Properties->C/C++->Preprocessor
change the preprocessor definitions to "WIN32;_DEBUG;_CONSOLE;DWINDOWS;WINDOWS;_WINDOWS;_DWINDOWS;_X86_".
Last, go to Configure Properties->Linker->Input. Add to additional
dependencies "WSOCK32.lib".
Now Vc++ should be configured properly. Inside your main source
file, change the includes to this:
#include "twsapi.h"
#include <windows.h>
#include <process.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <tchar.h>
Now add the function:
int thread(tws_func_t func, void *arg)
{
int err = _beginthread(func, 2*8192, arg);
return err;
}
Now we need to add all of the call back functions that are used
by the tws api when events happen.
void event_tick_price(void *opaque, long ticker_id,
long field, double price, int can_auto_execute)
{
}
void event_tick_size(void *opaque, long ticker_id, long field, int
size)
{
}
void event_order_status(void *opaque, long order_id, const char
status[], int filled, int remaining, double avg_fill_price, int
perm_id, int parent_id, double last_fill_price, int client_id)
{
}
void event_open_order(void *opaque, long order_id, const tr_contract_t
*contract, const tr_order_t *order)
{
}
void event_win_error(void *opaque, const char str[], int last_error)
{
}
void event_connection_closed(void *opaque)
{
}
void event_update_account_value(void *opaque, const char key[],
const char val[], const char currency[], const char account_name[])
{
}
void event_update_portfolio(void *opaque, const tr_contract_t *contract,
int position, double mkt_price, double mkt_value, double average_cost,
double unrealized_pnl, double realized_pnl, const char account_name[])
{
}
void event_update_account_time(void *opaque, const char time_stamp[])
{
}
void event_next_valid_id(void *opaque, long order_id)
{
}
void event_contract_details(void *opaque, const tr_contract_details_t
*contract_details)
{
}
void event_bond_contract_details(void *opaque, const tr_contract_details_t
*contract_details)
{
}
void event_exec_details(void *opaque, long order_id, const tr_contract_t
*contract, const tr_execution_t *execution)
{
}
void event_error(void *opaque, int id, int error_code, const char
error_string[])
{
}
void event_update_mkt_depth(void *opaque, long ticker_id, int position,
int operation, int side, double price, int size)
{
}
void event_update_mkt_depth_l2(void *opaque, long ticker_id, int
position, char *market_maker, int operation, int side, double price,
int size)
{
}
void event_update_news_bulletin(void *opaque, int msgid, int msg_type,
const char news_msg[], const char origin_exch[])
{
}
void event_managed_accounts(void *opaque, const char accounts_list[])
{
}
void event_receive_fa(void *opaque, long fa_data_type, const char
cxml[])
{
}
void event_historical_data(void *opaque, int reqid, const char date[],
double open, double high, double low, double close, int volume,
double wap, int has_gaps)
{
}
Now all the hard work is done. Just a few more steps remaining.
In your main function add the following lines:
void *tws;
tws=tws_create(thread, (void *) 0x12345);
int err = tws_connect(tws, "127.0.0.1" , 7496, 0);
if(err==0)
printf("\nConnected\n");
This call has 4 parameters. The first is the pointer to your tws
structure. The second 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 next 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. Before we can test this code you
need 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.
If all goes well, when you run this you should see connected displayed
in your console. If so, then congratulations, you now can connect
to the TWS using the API. Your 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
|