Shared Flashcard Set

Details

Perl IB API
Perl api
59
Computer Science
Professional
10/28/2006

Additional Computer Science Flashcards

 


 

Cards

Term
How does the perl package Finance::InteractiveBrokers::TWS work?
Definition
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.
Term
What does the new method do and how does it work?
Definition
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.
Term
What does the Finance::InteractiveBrokers::TWS perl package do?
Definition
Term
What is an example of the new method?
Definition
my $tws = Finance::InteractiveBrokers::TWS->new($callback);
Term
What does the get_callback function do?
Definition
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
Term
What is an example of the get_callback function?
Definition
my $callback = $tws->get_callback();
Term
What does the eConnect method do?
Definition
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
Term
What is an example of the eConnect method?
Definition
my $boolean = $tws->eConnect($host, $port, $client_id)
Term
What does eDisconnect do?
Definition
Disconnects from the TWS, and returns a boolean of success or failure in disconnection.
Term
What is an example of eDisconnect?
Definition
my $booean = $tws->eDisconnect();
Term
What does the isConnected method do?
Definition
Returns a boolean of whether or not you are currently connected to the TWS
Term
What is an example of the isConnected method?
Definition
my $boolean = $tws->isConnected();
Term
What does the process_messages method do?
Definition
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.
Term
What is an example of the process_messages method?
Definition
my $seconds_to_wait = 2;
$number_of_callbacks_processed = $tws->process_messages($seconds_to_wait);
Term
What does the dump_event do?
Definition
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.
Term
What is an example of the dump_event method?
Definition
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.
Term
What does the dump_java_object method do?
Definition
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
Term
What is an example of the dump_java_object method?
Definition
$tws->dump_java_object($contract);
Term
What are the methods implemented by Finance::InteractiveBrokers::TWS?
Definition
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);
Term
What are the short cuts to instantiating IB Java Classes?
Definition
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);
Term
What methods are not implemented by Finance::InteractiveBrokers::TWS, but instead are accessed thru your $tws and implemented by the IB published API?
Definition
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.

$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);
Term
What does the cancelMktData method do?
Definition
After calling this method, market data for the specified id will stop flowing.

You pass the same arguments you passed to reqMarketData.
Term
What is an example of using cancelMktData?
Definition
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->cancelMktData($contract_id);
Term
What does the cancelHistoricalData method do?
Definition
Used if an internet disconnect has occurred or the results of a query are otherwise delayed and the application is no longer interested in receiving the data.
Term
What does the cancelMktDepth method do?
Definition
After calling this method, market depth data for the specified id will stop flowing.

It takes the same argument that was appsed to requestMktDepth
Term
What does the cancelNewsBulletins method do?
Definition
Call this method to stop receiving news bulletins.
Term
What does the cancelOrder method do?
Definition
Call this method to cancel an order.

Arguments:

id- the order ID that was specified previously in the call to placeOrder()
Term
What does the cancelScannerSubscription do?
Definition
Don't know
Term
What does the exerciseOptions method do?
Definition
void exerciseOptions(long id, Contract contract,long exerciseAction, long exerciseQuantity, long override)

Parameters
id - the ticker id. Must be a unique value.

contract - this structure contains a description of the contract for which market depth data is being requested.

exerciseAction - specifies whether you want the option to lapse or be exercised. Values are 1 = exercise, 2 = lapse.

exerciseQuantity - the quantity you want to exercise.

override - specifies whether your setting will override the system's natural action. For example, if your action is "exercise" and the option is not in-the-money, by natural action the option would not exercise. If you have override set to "yes" the natural action would be overridden and the out-of-the money option would be exercised. Values are: 0 = no, 1 = yes.
Term
What does the placeOrder method do?
Definition
Function
void placeOrder( int id, Contract contract, Order order)See Extended Order Attributes.

Parameters
id - the order id. You must specify a unique value. When the order status returns, it will be identified by this tag. This tag is also used when canceling the order.

contract - this structure contains a description of the contract which is being traded.

order - this structure contains the details of the order. Note: Each client MUST connect with a unique clientId.

Notes
Call this method to place an order. The order status will be returned by the orderStatus event.
Term
What does the replaceFA do?
Definition
Function
requestFA(long faDataType)

Parameters
faDataType - specifies the type of Financial Advisor configuration data being requested. Valid values include:

1 = GROUPS

2 = PROFILE

3 =ACCOUNT ALIASES

Notes
Call this method to request FA configuration information from TWS. The data returns in an XML string via a "receiveFA" ActiveX event.
Term
What does the reqAccountUpdates method do?
Definition
Function
void reqAccountUpdates(boolean subscribe, String acctCode)

Parameters
subscribe - If set to TRUE, the client will start receiving account and portfolio updates. If set to FALSE, the client will stop receiving this information.

acctCode - the account code for which to receive account and portfolio updates.

Notes
Call this function to start getting account values, portfolio, and last update time information.
Term
What does the reqAllOpenOrders method do?
Definition
Function
void reqAllOpenOrders()

Parameters
bAutoBind - If set to TRUE, newly created TWS orders will be implicitly associated with the client. If set to FALSE, no association will be made.


Notes
Call this method to request the open orders that were placed from all clients and also from TWS. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper.

Note: No association is made between the returned orders and the requesting client.
Term
What does the reqAutoOpenOrders method do?
Definition
Function
void reqAutoOpenOrders(boolean bAutoBind)

Parameters
bAutoBind - If set to TRUE, newly created TWS orders will be implicitly associated with the client. If set to FALSE, no association will be made.

Notes
Call this method to request that newly created TWS orders be implicitly associated with the client. When a new TWS order is created, the order will be associated with the client and fed back through the openOrder() and orderStatus() functions on the EWrapper.
Term
What does the reqContractDetails method do?
Definition
Function
void reqContractDetails (Contract contract)

Parameters
Contract- summary description of the contract being looked up.

Notes
Call this function to download all details for a particular underlying. the contract details will be received via the contractDetails() function on the EWrapper.
Term
What does the reqExecutions method do?
Definition
Function
reqExecutions(ExecutionFilter filter)

Parameters
filter - the filter criteria used to determine which execution reports are returned.

Notes
When this method is called, the execution reports that meet the filter criteria are downloaded to the client via the execDetails() method.
Term
What does the reqHistoricalData method do?
Definition
Function
void reqHistoricalData (int id, Contract contract, String endDateTime, String durationStr, long barSizeSetting, String whatToShow, int useRTH, int formatDate)

Parameters
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data.

contract- this structure contains a description of the contract for which market data is being requested.

endDataTime - defines a query end date and time at any point during the past 6 mos. Valid values include any date/time within the past six months in the format: yyyymmdd HH:mm:ss ttt

where "ttt" is the optional time zone.

durationStr - set the query duration up to one week, using a time unit of seconds, days or weeks. Valid values include any integer followed by a space and then S(seconds), D (days) or W (week). If no unit is specified, seconds is used.

barSizeSetting - specifies the size of the bars that will be returned (within IB/TWS limits). Valid values include:

Bar Size Parametric Value
1 sec
1
5 secs 2
15 secs 3
30 secs 4
1 min. 5
2 mins
6

5 mins.
7

15 mins
8

30 mins
9

1 hour
10

1 day
11




whatToShow - determines the nature of data being extracted. Valid values include:

TRADES

MIDPOINT

BID

ASK

BID/ASK

useRTH - determines whether to return all data available during the requested time span, or only data that falls within regular trading hours. Valid values include:

0 - all data is returned even where the market in question was outside of its regular trading hours.

1 - only data within the regular trading hours is returned, even if the requested time span falls partially or completely outside of the RTH.

formatDate - determines the date format applied to returned bars. Valid values include:

1 - dates applying to bars returned in the format:
yyyymmdd{space}{space}hh:mm:dd

2 - dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.

Notes
Term
What does the reqIds method do?
Definition
Don't know, I don't even see it at http://www.interactivebrokers.com/php/webhelp/Interoperability/Socket_Client_Java/java_eclientsocket.htm, it may be deprecated.
Term
What does the reqManagedAccts method do?
Definition
Function
void reqManagedAccts()

Parameters


Notes
Call this method to request the list of managed accounts. The list will be returned by the managedAccounts() function on the EWrapper.

Note: This request can only be made when connected to a Financial Advisor (FA) account.
Term
What does the reqMktData method do?
Definition
Function
void reqMktData(int id, Contract contract)

Parameters
id - the ticker id. Must be a unique value. When the market data returns, it will be identified by this tag. This is also used when canceling the market data.

contract- this structure contains a description of the contract for which market data is being requested.

Notes
Call this function to request market data. The market data will be returned by the tickPrice and tickSize events.
Term
What does the reqMktDepth method do?
Definition
Function
void reqMktDepth(int id, Contract contract, long numRows)

Parameters
id - the ticker id. Must be a unique value. When the market depth data returns, it will be identified by this tag. This is also used when canceling the market depth.

contract- this structure contains a description of the contract for which market depth data is being requested.

numRows- specifies the number of market depth rows to display.

Notes
Call this method to request market depth for a specific contract. The market depth will be returned by the updateMktDepth() and updateMktDepthL2() events.
Term
What does the reqNewsBulletins method do?
Definition
Function
void reqNewsBulletins(boolean AllMsgs)

Parameters
allMsgs - if set to TRUE, returns all the existing bulletins for the current day and any new ones. IF set to FALSE, will only return new bulletins.

Notes
Call this method to start receiving news bulletins. Each bulletin will be returned by the updateNewsBulletin() event.
Term
What does the reqOpenOrders method do?
Definition
Function
void reqOpenOrders()

Parameters


Notes
Call this method to request the open orders that were placed from this client. Each open order will be fed back through the openOrder() and orderStatus() functions on the EWrapper.

Note: The client with a clientId of "0" will also receive the TWS-owned open orders. These orders will be associated with the client and a new orderId will be generated. This association will persist over multiple API and TWS sessions.
Term
What does the reqScannerParameters method do?
Definition
Function
void reqScannerParameters()

Parameters


Notes
Requests an XML string that describes all possible scanner queries.
Term
What does the reqScannerSubscription method do?
Definition
Function
void reqScannerSubscription(int tickerId, contract ScannerSubscription)

Parameters
tickerId - the ticker ID. Must be a unique value.

ScannerSubscription - this structure contains possible parameters used to filter results.

Notes
Term
What does the requestFA method do?
Definition
Function
requestFA(long faDataType)

Parameters
faDataType - specifies the type of Financial Advisor configuration data being requested. Valid values include:

1 = GROUPS

2 = PROFILE

3 =ACCOUNT ALIASES

Notes
Call this method to request FA configuration information from TWS. The data returns in an XML string via a "receiveFA" ActiveX event.
Term
What does the setServerLogLevel method do?
Definition
Function
void setServerLogLevel(int level)

Parameters
logLevel - specifies the level of log entry detail used by the server (TWS) when processing API requests. Valid values include:

1 = SYSTEM

2 = ERROR

3 = WARNING

4 = INFORMATION

5 = DETAIL

Notes
The default level is ERROR. Refer to the API logging page for more details.
Term
What is important to understand about instantiating ib objects?
Definition
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);
Term
What happens if you find that IB publishes a new Java object that you need to use and it's not included
Definition
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();
Term
What is important to understand about setting/getting IB objects in perl?
Definition
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};
Term
What does the callback function do?
Definition
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.
Term
When a placeOrder method is called what happens? What if the connection goes down after the placeOrder method is called?
Definition
orderStatus is called, and when the order is executed, execDetails is called when it fills. provided you are still connected with the same
client id under which the order was placed. Whether you are tracking order
ids is irrelevant (after all, TWS has no knowledge of what you're tracking).

If you are not connected at the time the order is filled, you won't get the
execDetails unless you call reqExecutions, at which point you will get
execDetails for all the executions that have occurred during the trading
session (NOT your API session).

So if you place an order, and then the connection drops out and recovers, it
is wise to call reqExecutions in case the order was filled during the
outage.
Term
How do I get the current state of the portfolio in tws, with pending orders etc...?
Definition
make an initial call to reqAccountUpdates to
get the current position at startup

You can't get individual executions from
the updatePortfolio event, just overall positions. But that info includes
the average price, which is enough to be able to calculate the current value
of the position using the current bid/ask. (Having said that, the fact that
the average cost includes commission complicates things a bit - you'd have
to know what the commision is.)

Individual executions are of course obtained via the execDetails event.

Some people recommend storing executions in a database.
Term
What is a good generic strategy for creating the stock trading application?
Definition
1. Start up and get all open orders, current positions held, profit/loss on those positions
2. Read a database on all stocks I want to buy and when to sell
3. Call reqMktData on all of those stocks
4. React to events in tickPrice to determine when to sell or buy
Term
What is a good reconnect strategy?
Definition
I've not found a definitive way of knowing when TWS has completed startup so I
too sleep though for an initial 20 seconds. I then attempt connects from my API
handler using eConnect(host, port, clientid).. and if it is successful then a
call to isConnected() returns true...otherwise I sleep for 2 additional seconds
and attempt another connection. This will repeat itself up to10 times where if
it has continued to fail I reset the applications and start over from the
beginning.
Term
When creating a tws app, what approach is good?
Definition
Basically figure out what events you need to get. For example reqMktData causes and event to be sent to tickPrice, so make sure you override tickPrice in the Callback.pm. placeOrder causes events to orderStatus and execDetails. Reading IB api can assist in understanding what events occur for the request functions.
Term
What are all the functions that can be overwridden to get events?
Definition
Override the following functions:

Override tickPrice() and tickSize() functions to handle the market data.

Override the orderStatus() function to receive order status.

Override the error() function to receive error information.

Override the connectionClosed() function to be notified when TWS terminates the connection.

Override the updateAccountValue() function to receive current account value information.

Override the updateAccountTime() function to receive the last update time of account information.

Override the updatePortfolio() function to receive current portfolio information.

Override the contractDetails() function to receive contract information.

Override the execDetails() function to receive execution report information.

Override the updateNewsBulletin() function to receive news bulletins.

Override the managedAccounts() function to see a list of the Financial Advisor (FA) managed accounts.
Term
Is it possible to automatically start up tws and login to TWS somehow from the client program?
Definition
Yes, Is it possible to have TWS open without having to type in the username/password each time without using third party software? -- YES. See http://www.interactivebrokers.com/discus/messages/3/28517.html?1115470928 for details.

The largest collection of fully automatic starter programs is at http://finance.groups.yahoo.com/group/TWSAPI/files/ (you will have to join the group to see this directory) under "Auto Login Codes". Some of these programs are only for Windows, like tripack and beejay. The most comprehensive solution that runs under Java is IBController. The documentation for IBController even includes Java code you can import into your project so that the entire launch and monitoring of the connection process is controlled directly by your program, which for Java based TWS API software may be the most robust way to handle integration.
Term
What is the best way to figure out the status of my account, with executiocs, pending orders, balances etc, through the api
Definition
reqAccountUpdates(true, ""); twsSocket.reqAllOpenOrders(); reqExecutions(new ExecutionFilter());
Supporting users have an ad free experience!