NAME
Finance::InteractiveBrokers::TWS - Lets you talk to Interactivebrokers Trader's Workstation using Perl.
This module is a wrapper around InteractiveBroker's Trader's Workstation (TWS) Java interface, that lets one interact with the TWS using Perl, via the vendor supplied API. This means that all the functionality available to Java programmers is also available to you.
VERSION
0.0.6 - Still Alpha since bugs are being found and the interface is changing. But all in all it seems to work quite nicely
SYNOPSIS
Methods implemented by Finance::InteractiveBrokers::TWS
use Finance::InteractiveBrokers::TWS;
my $tws = Finance::InteractiveBrokers::TWS->new(callback=>$callback);
my $callback = $tws->get_callback();
my $rc = $tws->eConnect($host, $port, $client_id);
my $rc = $tws->eDisconnect();
my $rc = $tws->isConnected(@parms);
my $rc = $tws->process_messages($seconds_to_wait);
Shortcuts for instantiating IB Java classes
my $combo_leg = $tws->ComboLeg->new(@parms);
my $contract_details = $tws->ContractDetails->new(@parms);
my $contract = $tws->Contract->new(parms);
my $execution_filter = $tws->ExecutionFilter->new(@parms);
my $execution = $tws->Execution->new(@parms);
my $order = $tws->Order->new(@parms);
my $scanner_sub = $tws->ScannerSubscription->new(@parms);
Shortcuts for asking TWS to do something for you
$tws->cancelHistoricalData(@parms);
$tws->cancelMktData(@parms);
$tws->cancelMktDepth(@parms);
$tws->cancelNewsBulletins(@parms);
$tws->cancelOrder(@parms);
$tws->cancelScannerSubscription(@parms);
$tws->exerciseOptions(@parms);
$tws->placeOrder(@parms);
$tws->replaceFA(@parms);
$tws->reqAccountUpdates(@parms);
$tws->reqAllOpenOrders(@parms);
$tws->reqAutoOpenOrders(@parms);
$tws->reqContractDetails(@parms);
$tws->reqExecutions(@parms);
$tws->reqHistoricalData(@parms);
$tws->reqIds(@parms);
$tws->reqManagedAccts(@parms);
$tws->reqMktData(@parms);
$tws->reqMktDepth(@parms);
$tws->reqNewsBulletins(@parms);
$tws->reqOpenOrders(@parms);
$tws->reqScannerParameters(@parms);
$tws->reqScannerSubscription(@parms);
$tws->requestFA(@parms);
$tws->setServerLogLevel(@parms);
DESCRIPTION
Finance::InteractiveBrokers::TWS - Is a wrapper around InteractiveBrokers Traders Workstation (TWS) Java interface, that lets one interact with the TWS using Perl, via the vendor supplied API.
It uses Inline::Java to wrap InteractiveBrokers' Java API that IB supplies to communicate with the TWS. As such, the method names don't conform to Perl standards and in most cases follow Java standards.
After numerous attempts at writing a pure perl module I opted for this solution because:
Using Inline::Java resulted in a much simpler and smaller module
The interaction and call syntax is identical to the Java API (because it is the Java API) and as such, you can ask questions on the IB bulletin board and yahoo, and be using the same method names and call syntax as they are. In other words, people will know what you're talking about.
IB changes their interface with some frequency, which required re-writing my interface every time
IB changes there message stream, which required me to modify my parser
Whenever IB changes something I'd have to diff the old API versus the new API and try to figure out what changed and how that affected my code
Class methods
The following methods are provided by the Finance::InteractiveBrokers::TWS class
new
Sorta obvious, this instantiates an object of class Finance::InteractiveBrokers::TWS. It requires a single parameter: a callback object. That is, you (the user) has to write an class that can handle messages that the TWS will send to this client.
my $tws = Finance::InteractiveBrokers::TWS->new($callback);
get_callback
Simply returns the callback you supplied when you instantiated this class. Provided in case you need to pass around your $tws and want to access data you might have cached away in your callback
my $callback = $tws->get_callback();
eConnect
Establishes (or tries to) a connection to the TWS defined in its parameters. It accepts 3 parameters:
- 1 IP address or Host name - DEFAULTS to localhost
- 2 The port upon which TWS is accepting connections - DEFAULTS to 7496
- 3 The client ID - DEFAULTS to process id
my $boolean = $tws->eConnect($host, $port, $client_id)
eDisconnect
Disconnects from the TWS, and returns a boolean of success or failure in disconnection.
my $booean = $tws->eDisconnect();
isConnected
Returns a boolean of whether or not you are currently connected to the TWS
my $boolean = $tws->isConnected();
process_messages
Processes the messages the TWS has emitted. It accepts a single optional parameter of how many seconds to listen for messages to process. It returns the number of callbacks processed. If no messages are found within the wait period, control is returned to the caller.
my $seconds_to_wait = 2;
$number_of_callbacks_processed = $tws->process_messages($seconds_to_wait);
dump_event
This is a custom method that does not exist in the IB API. Its useful for testing and debuging. Simply call it passing the arguments received by the event handler "as is" along with the event name and it will print out the contents of the event in a pretty Data::Dumper format.
An example inside the callback: sub updateMktDepth { my ($self, @args) = @_;
my $subname = 'updateMktDepth';
print "\n****Called $sub_name: \n";
my $obj = bless {}, 'callback';
my $tws = Finance::InteractiveBrokers::TWS->new($obj);
$tws->dump_event($sub_name, \@args);
return;
}
Obviously, you wouldn't want to do it this way in your real code, since you'd be creating and destroying tws objects continuously. But as an example its easy to see how to use it.
dump_java_object
Again a custom method that comes in handy when testing and debuging. Since you can't use Data::Dumper on a java object like "contract" or "order", you need to explode it manually, pulling out all the keys
Call it like:
$tws->dump_java_object($contract);
Java methods
The following methods are not implemented by Finance::InteractiveBrokers::TWS, but instead are accessed thru your $tws and implemented by the IB published API. The obvious benefit is I have to do less work. The other benefit (probably more important to you) is that when IB changes things this code continues to work.
IB's documentation is pretty weak. But here is a link to IBs website with a list of methods you can call once you have created a Finance::InteractiveBrokers::TWS object
http://www.interactivebrokers.com/php/webhelp/Interoperability/Socket_Client_Java/java_eclientsocket.htm
cancelHistoricalData
$tws->cancelHistoricalData(@parms);
cancelMktData
$tws->cancelMktData(@parms);
cancelMktDepth
$tws->cancelMktDepth(@parms);
cancelNewsBulletins
$tws->cancelNewsBulletins(@parms);
cancelOrder
$tws->cancelOrder(@parms);
cancelScannerSubscription
$tws->cancelScannerSubscription(@parms);
exerciseOptions
$tws->exerciseOptions(@parms);
placeOrder
$tws->placeOrder(@parms);
replaceFA
$tws->replaceFA(@parms);
reqAccountUpdates
$tws->reqAccountUpdates(@parms);
reqAllOpenOrders
$tws->reqAllOpenOrders(@parms);
reqAutoOpenOrders
$tws->reqAutoOpenOrders(@parms);
reqContractDetails
$tws->reqContractDetails(@parms);
reqExecutions
$tws->reqExecutions(@parms);
reqHistoricalData
$tws->reqHistoricalData(@parms);
reqIds
$tws->reqIds(@parms);
reqManagedAccts
$tws->reqManagedAccts(@parms);
reqMktData
$tws->reqMktData(@parms);
reqMktDepth
$tws->reqMktDepth(@parms);
reqNewsBulletins
$tws->reqNewsBulletins(@parms);
reqOpenOrders
$tws->reqOpenOrders(@parms);
reqScannerParameters
$tws->reqScannerParameters(@parms);
reqScannerSubscription
$tws->reqScannerSubscription(@parms);
requestFA
$tws->requestFA(@parms);
setServerLogLevel
$tws->setServerLogLevel(@parms);
Creating Java Objects
In addition to the methods described just above. There are some additional methods available for creating the other IB Java objects necessary for interacting with the TWS.
Instantiating
When instantiating these objects you can pass all the parameters in positionally according to how IB has documented them. Or you can just create them blank and set the attributes later.
my $ComboLeg = $tws->ComboLeg->new(@parms);
my $Contract = $tws->Contract->new(@parms);
my $ContractDetails = $tws->ContractDetails->new(@parms);
my $EClientSocket = $tws->EClientSocket->new(@parms);
my $Execution = $tws->Execution->new(@parms);
my $ExecutionFilter = $tws->ExecutionFilter->new(@parms);
my $Order = $tws->Order->new(@parms);
my $ScannerSubscription = $tws->ScannerSubscription->new(@parms);
If you find that IB publishes a new Java object that you need to use and it's not included above, you can still use the new object. The above list is really just a shortcut for doing it the long way. Such as:
my $order = Finance::InteractiveBrokers::TWS::com::ib::client::ComboLeg->new();
Set/Get
When Inline::Java creates these objects it hands back a Perl reference to hash. Thus working with these objects is simple. To set a attribute of an object you do it like:
$contract->{m_symbol} = 'YHOO';
To get an attribute of an object you do it like:
my $symbol = $contract->{m_symbol};
CALLBACK
The callback is the custom code you write to handle the messages the TWS emits and that are picked up by the API. The API dispatches (call) your callback to handle processing of the message.
The methods that are called are described (poorly) by IB at:
http://www.interactivebrokers.com/php/webhelp/Interoperability/Socket_Client_Java/java_ewrapper.htm
But in general, you will have methods in your callback like:
sub tickPrice {
my ($self, @args) = @_;
# do something when you get a change in price
}
sub error {
my ($self, @args) = @_;
# handle the error
}
Again, these methods are described by IB on their website.
EXAMPLE
package Local::Callback;
use strict;
sub new {
bless {}, shift;
}
sub nextValidId {
my $self = shift;
$self->{nextValidId} = $_[0];
print "nextValidId called with: ", join(" ", @_), "\n";
}
sub error {
my ($self, $return_code, $error_num, $error_text) = @_;
print "error called with: ", join('|', $return_code,
$error_num, $error_text), "\n";
# sleep for some predetermined time if I get a 502
# Couldn't connect to TWS. Confirm that "Enable ActiveX and
# Socket Clients" is enabled on the TWS "Configure->API" menu.
if ($error_num == 502) {
sleep 60;
}
}
sub AUTOLOAD {
my ($self, @args) = @_;
our $AUTOLOAD;
print "$AUTOLOAD called with: ", join '^', @args, "\n";
return;
}
package main;
use Finance::InteractiveBrokers::TWS;
my $tws;
while (1) {
if (defined $tws and $tws->isConnected) {
$tws->process_messages(1);
}
else {
connect_to_tws();
}
}
$tws->eDisconnect;
# connect_to_tws, connects to the tws and sets up a few
# objects that we want clean at every new connection
sub connect_to_tws {
my $callback = Local::Callback->new();
$tws = Finance::InteractiveBrokers::TWS->new($callback);
#### Host Port Client_ID
#### ---- ---- ---------
my @tws_GUI_location = qw/ 127.0.0.1 7496 15 /;
$tws->eConnect(@tws_GUI_location);
my $contract_id = 50; # this can be any number you want
my $contract = $tws->Contract->new();
$contract->{m_symbol} = 'YHOO';
$contract->{m_secType} = 'STK';
$contract->{m_exchange} = 'SMART';
$tws->reqMktData($contract_id, $contract);
$tws->process_messages(3);
return;
}
HELP
You are welcome to email me if you are having problems with this module. You should also look at the IB forums (http://www.interactivebrokers.com/cgi-bin/discus/discus.pl) if you have questions about interacting with the TWS (i.e. how to get TWS to do something for you, what the proper call syntax is...)
There is also another forum on: http://finance.groups.yahoo.com/group/TWSAPI . I'm not exactly sure of what the difference is.
There is a Wiki for TWS at: http://chuckcaplan.com/twsapi/
DIAGNOSTICS
If you receive an error something like:
Inline_Bridge is not abstract and does not override abstract method...
The error message was:
TWS_581d.java:6: Inline_Bridge is not abstract and does not override abstract method tickOptionComputation(int,int,double,double) in com.ib.client.EWrapper
class Inline_Bridge extends InlineJavaPerlCaller implements EWrapper {
^
1 error
It means that this module (Finance::InteractiveBrokers::TWS) is not up to date with the current IB API version you have installed. Specifically, this module is missing a new method implemented by the API.
The easiest fix is to look at the specification of the method (in this case tickOptionComputation), in the EWrapper.java file in the IBJts/java/com/ib/client directory where you installed the IB API, and implement it in the __Java__ section of this module. Additionally, add the appropriate entry into the tws.conf file (Its really simple code, I promise you can figure it out, just copy and paste a different section). Then do a "make realclean && perl Makefile.PL && make && make test" and see if that fixes the compile error.
Finance::InteractiveBrokers::TWS::java::lang::NullPointerException=HASH(0x8b671cc)
This means you did not supply a callback object when you instantiated a Finance::IB:TWS object.
The error message was:
TWS_661f.java:21: incompatible types
found : int
required: java.lang.Object
tickerId, field, price, canAutoExecute
^
The above error is sort of a bug, sort of an inconsistancy. But basically if you are running Java <= 1.4 then you need to alter the TWS.pm source and change the lines that look like:
perlobj.InvokeMethod("tickPrice", new Object [] {
tickerId, field, price, canAutoExecute
});
and manually cast the variables into their types directly, like this:
perlobj.InvokeMethod("tickPrice", new Object [] {
new Integer (tickerId), new Integer (field), new Double (price),
new Integer (canAutoExecute)});
I don't feel like going through all the code to do this, especially since most people will be using Java 1.5 and above shortly
Other errors during first time use
Please delete the installation and start over making sure you install as "root". YOU MUST RUN THE tests. The tests create a directory where the Inline::Java places some necessary files.
CONFIGURATION AND ENVIRONMENT
You need to compile the *.java API source files into java class files prior to using this module. Do it like:
$ cd ~/IBJts/java/com/ib/client/
$ javac *.java
Furthermore Finance::InteractiveBrokers::TWS does require that you set your CLASSPATH environmental variable to the location of the IBJts/java directory where you installed the IB API. Such as:
$ export CLASSPATH=~/IBJts/java
DEPENDENCIES
Java JDK/JRE version >= 1.5 - If you have a lower version there is a workaround see DIAGNOSTICS
InteractiveBrokers TWS GUI application
Inline
Inline::Java v.50_92 or greater
Object::InsideOut
Tie::IxHash;
Config::General;
INCOMPATIBILITIES
See above DIAGNOSTICS
BUGS AND LIMITATIONS
See above DIAGNOSTICS
Please report any bugs or feature requests to bug-finance-ib-tws@rt.cpan.org
, or through the web interface at http://rt.cpan.org.
VERY SPECIAL THANKS
Patrick LeBoutillier - Author of Inline::Java, and for all his help while I learned how to use Inline::Java
ACKNOWLEDGEMENTS
Carl Erickson wrote the first Perl interface. Based on his README, it was sort of a proof of concept, and doesn't implement all of TWS's functionality. Carl is pretty active on the TWS mailing list(s). He doesn't actively "support" the perl code, but he's very helpful if you want to try it and need some help. This code is meant to be synchronous and blocking; in that you request market data, and your program blocks until you get the data back. Every time you want new data, you request it.
You can find the code on the Yahoo TWSAPI group, I think the following link will work: http://finance.groups.yahoo.com/group/TWSAPI/files/Perl%20Code/
AUTHOR
Jay Strauss <tws_at_heyjay.com>
LICENCE AND COPYRIGHT
Copyright (c) 2006, Jay Strauss <tws_at_heyjay.com>
. All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.
DISCLAIMER OF WARRANTY
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.