DdeExcelApiGettingStarted
DdeExcelApiGettingStarted
DdeExcelApiGettingStarted
Sun, Sun Microsystems, the Sun Logo and Java are trademarks or registered
trademarks of Sun Microsystems, Inc. in the United States and other countries.
Excel, Windows and Visual Basic (VB) are trademarks or registered trademarks
of the Microsoft Corporation in the United States and/or in other countries.
Any symbols displayed within these pages are for illustrative purposes only, and
are not intended to portray any recommendation.
Table of Contents
Introduction ........................................................................................................... 10
Organization .................................................................................................. 11
Icons .............................................................................................................. 13
An Example .................................................................................................. 19
Part II: Preparing to Use the DDE for Excel API ................................................. 22
www.interactivebrokers.com 3
Part III: Getting to Know the DDE for Excel Sample Spreadsheet ...................... 29
An Example .................................................................................................. 42
4 www.interactivebrokers.com
Chapter 12 – The Executions Page ....................................................................... 50
Chapter 17 - The Contract Details and Bond Contract Details Pages .................. 69
www.interactivebrokers.com 5
Contract Details Page.................................................................................... 69
6 www.interactivebrokers.com
Enable or Start the Subroutine .................................................................. 86
Code Summary.......................................................................................... 87
Code Summary.......................................................................................... 89
Code Summary.......................................................................................... 91
Code Summary.......................................................................................... 92
Code Summary.......................................................................................... 94
www.interactivebrokers.com 7
Help with the TWS API ................................................................................ 97
IB Features Poll......................................................................................... 99
Chapter 24 – The DDE for Excel API for Advisors ........................................... 100
8 www.interactivebrokers.com
Allocation Profiles ...................................................................................... 117
www.interactivebrokers.com 9
Introduction
You might be looking at this book for any number of reasons, including:
• You love IB’s TWS, and are interested in seeing how using its API can
enhance your trading.
• You use another online trading application that doesn’t provide the
functionality of TWS, and you want to find out more about TWS and its
API capabilities.
Or maybe you have a reason of your own. However you traveled this happy path,
you now hold in your hands a unique and potentially priceless tome of
information. Well, maybe that’s a tiny bit of an exaggeration. The information in
this book will, however, show you how to use the trading functionality of IB’s
Trader Workstation and its API. Keep reading to find out how easy it can be to
augment and enhance your trading via the TWS API.
10 www.interactivebrokers.com
How to Use this Guide
Before you get started, you should read this section to learn how this book is
organized, and see which graphical conventions are used throughout.
To get the most of out of this guide, you should have at least basic PC skills as
well as some basic familiarity with Microsoft Excel.
Organization
We’ve divided this book into five major sections, each of which comprises a
number of smaller subsections, and each of those have even smaller groupings of
paragraphs and figures…well, you get the picture. Here’s how we’ve broken
things down:
If you already know you want to learn about the TWS API, just skip on ahead.
www.interactivebrokers.com 11
things you can do with all of the “action buttons” that we have thoughtfully
included to help improve your efficiency.
12 www.interactivebrokers.com
Icons
When youu see this guyy, you know w that there iss something
that relatees specificallly to TWS - maybe a new w feature to
watch for,, or maybe thhere’s sometthing you’ree familiar
with in TW WS and are looking
l for in
i the API.
TWS
S-Related
Exceel Tip
This show
ws you wheree there is a particularly
p u
useful or
importantt point beingg made.
Impo
ortant!
Takee a Peek!
Go Outside!
O
www.interaactivebrokers.ccom 1
13
Part I: Introducing the DDE for Excel API
The best place to start is by getting an idea of what the Trader Workstation, or
TWS, is all about. In this section, first we’ll describe the TWS and some of its
major features. Then we’ll explain how the API can be used to enhance and
customize your trading environment. Finally, we’ll give you a summary of some
of the things the DDE for Excel API, (versus our other API platforms), can do for
you!
14 www.interactivebrokers.com
Chapter 1 - What is TWS?
Interactive Brokers’ Trader Workstation, or TWS, is an online trading platform
that lets you trade and manage orders for all types of financial products (including
stocks, bonds, options, futures and Forex) on markets all over the world - all from
a single spreadsheet-like screen.
To get a little bit of a feel for TWS, go to the IB website and try the TWS
demo application. Its functionality is slightly limited and it only supports a
small number of symbols, but you’ll definitely get the idea. Once you have
an approved, funded account you’ll also be able to use the PaperTrader, our
simulated trading tool, with paper-money funding in the amount of $100,000,
which you can replenish at any time through TWS Account Management.
• Send and manage orders for all sorts of products (all from the same
screen!);
• Monitor the market through Level II, NYSE Deep Book and IB’s market
depth;
www.interactivebrokers.com 15
• Keep a close eye on all aspects of your account and executions;
Basically, almost anything you can think of TWS can do - or will be able to do
soon. We are continually adding new features, and use the latest technology to
make things faster, easier and more efficient. As a matter of fact, it was this faith
in technology’s ability to improve a trader’s success in the markets (held by IB’s
founder and CEO Thomas Peterffy) that launched this successful endeavor in the
first place. Since the introduction of TWS in 1995, IB has nurtured this
relationship between technology and trading almost to the point of obsession!
And as they say, one person’s obsession is another person’s treasure - at least in
this case that’s how the saying goes, since TWS is indeed a treasure trove to
serious traders and investors.
16 www.interactivebrokers.com
What? An order ticket? Sure, we have an order ticket if that’s what you really
want. But we thought you might find it easier to simply click on the bid or ask
price and have us create a complete order line right instantly, right in front of your
eyes! Look it over, and if it’s what you want click a button to transmit the order.
You can easily change any of the order parameters, right on the order line. Then
just click the green Transmit guy to transmit your order! It’s fast and it’s easy, and
you can even customize this minimal two-click procedure (by creating hotkeys
and setting order defaults for example) so that you’re creating and transmitting
orders with just ONE click of the mouse.
TWS also provides a host of real-time account and execution reporting tools. You
can go to the Account Window at any time to see your account balance, total
available funds, net liquidation and equity with loan value and more. You can also
monitor this data directly from your trading window using the Trader Dashboard,
a monitoring tool you can configure to display the last price for any contracts, and
account-related information directly on your trading window.
www.interactivebrokers.com 17
Chapter 2 - Why Would I Use an API?
OK! Now that you have a little bit more of a feel for TWS and what it can do, you
can move on to the amazing API. If you actually read that last chapter, you might
be thinking to yourself “Why would I want to use an API when TWS seems to do
everything.” Or you might be thinking “Hm, I wonder if TWS can… fill in the
blank?” OK, if you’re asking the first question, we’ll explain why you might find
the API useful, and if you’re asking the second, it’s actually the API that can fill
in that blank.
TWS has the capability to do tons of different things, but it does them in a certain
way, and displays results in a certain way, and it’s pretty likely that our
development team, as fantastic as they are, hasn’t yet exhausted the number of
features and way of implementing these features that all of you collectively can
come up with. So it’s very likely that you, with your unique way of thinking, will
be or have been inspired by the power of TWS to say something like “Holy moly,
I can’t believe I can really do all of this with TWS! Now if I could only just …fill
in the blank…, my life would be complete!”
That’s where the API comes in. Now, you can …fill in the blank…! It’s going to
take a little work to get there, but once you see how cool it is to be able to access
functionality from one application from another, completely unrelated one, you’ll
be hooked.
In addition to allowing you pretty much free reign to create new things and piece
together existing things in new ways, the API is also a great way to automate your
tasks. You use the API to harness the power behind the TWS - in different ways.
Here’s an analogy that might help you understand the relationship between TWS
and the API. Start by imagining TWS as a book (since TWS is constantly being
enhanced, our analogy imagines a static snapshot of TWS at a specific point in
time). It’s the reference book you were looking for, filled with interesting and
useful information, a book with a beginning, middle and end, which follows a
certain train of logic. You could skip certain chapters, read Chapter 10 first and
Chapter 2 last, but it’s still a book. Now imagine, in comparison, that the API is
the word processing program in which the book was created with the text of the
book right there. This allows you access to everything in the book, and most
importantly, it lets you continually change and update material, and automate any
tasks that you’d have to perform manually using just a book, like finding an index
reference or going to a specific page from the table of contents.
The API works in conjunction with TWS and with the processing functions that
run behind TWS, including IB’s SmartRouting, high-speed order transmission
and execution, support for over 40 orders types, etc. TWS accesses this
18 www.interactivebrokers.com
functionality in a certain way, and you can design your API to take advantage of it
in other ways.
An Example
It’s always easier to understand something when you have a real life example to
contemplate. Following is a simple situation in which the API could be used to
create a custom result.
TWS provides an optional field that shows you your position-specific P&L for the
day, as either a percentage or an absolute value. Suppose you want to modify your
position based on your P&L value? At this writing, the only way to do this would
be to watch the market data line to see if the P&L changed, and then manually
create and transmit an order if you happened to catch the value at the right point.
Now, enter the API! You can instruct the API to automatically trigger an order
with specific parameters (such as limit price and quantity) when the P&L hits a
certain point. That’s power! (See Chapter 20 for details on how to actually
implement this feature).
Another Example
Another nice benefit of the API is that it gives you the ability to use the data in
TWS in different ways. TWS provides an extensive Account Information window
that’s chock-full of everything you’ll ever want to know about your account
status. The thing is, it’s only displayed in a TWS window, like the one below.
www.interactivebrokers.com 19
But, what if you wanted to do something else with this information, like have it
reflected in some kind of spreadsheet where you log information for all accounts
that you own, including your checking account, Interactive Brokers’ account,
401K, ROIs, etc? Again - enter the API!
You can instruct the API to get any specific account or execution information and
put it wherever it belongs in a spreadsheet. The information is linked to TWS, so
it’s easy to keep the information updated by simply linking to a running version of
TWS. With a little experimenting and some help from the TWS Users’ Guide,
you’ll be slinging data like a short-order API chef in no time!
20 www.interactivebrokers.com
IB’s API is supported in multiple programming languages including: Java, C++,
and Active X, and VBA for Excel. This book focuses specifically on just one, the
Excel version. Why would you use Excel with the API?
Here are some of the strongest arguments in support of using the DDE for Excel
API, at least to start:
Since this API uses Microsoft Excel as its development environment, most users
already have at least a basic familiarity with its functionality. You may not know
exactly how to write Visual Basic for Applications code, but you can see values in
a cell, and with a little coaching will be able to view the sample code behind the
stuff we give you and learn from that.
It comes with a fantastic sample program that can and should be used as a starting
point for anything else you want to do.
The Excel sample application provides a series of worksheet pages populated with
sample data, each geared toward helping you implement some specific action, like
getting market data, sending orders or viewing execution reports.
The learning curve is small and the time to development is fast. You’re not going
to need a programming course before you get started here. If you have some basic
PC skills and a good idea of what you want to do, you could create and implement
an API interface in a matter of days. In general, the time it will take you to
implement your new API is minimal compared to our other API technologies.
In order to use the API, you need to have TWS running, and must include
your login name on each function page of the Excel spreadsheet.
There are a few other things you must do before the DDE for Excel API will run.
The next chapter gets you geared up and ready to go.
www.interactivebrokers.com 21
Part II: Preparing to Use the DDE for
Excel API
Although the API provides great flexibility in implementing your automated
trading ideas, all of its functionality runs through the Trader Workstation. This
means that you must have a TWS account with IB, and that you must have your
TWS running in order for the API to work. This section takes you through the
minor prep work you need to complete, step by step.
22 www.interactivebrokers.com
Chapter 3 - Enable TWS to Support the API
If you don’t have an account with IB, you can run a lot of the following tasks
using the Demo TWS system. It will have some limitations, but you’ll get a feel
for things. If you have an account, we recommend opening a PaperTrader version,
which simulates the TWS trading environment, and gives you $100,000 in
phantom cash to trade with.
OK, log into TWS, or click the Live Trader Workstation icon on the bottom of the
IB homepage, then click the type of demo you want to use. Good! Now look up at
the top of the trading window, and you’ll see a bunch of menus. You want to click
on the Configure menu, and then hold your mouse over the API submenu. And
check the Enable DDE Clients checkbox. You also need to ensure that you have
Microsoft Excel installed on your computer. If you don’t have it, go to the
Microsoft website to order it. If you’re using Word or have MS Office installed,
you probably already have it.
That’s it for the first step. TWS is now enabled to support the DDE for Excel API.
The rest isn’t too complicated either, just follow along as we continue our API
preparations.
www.interactivebrokers.com 23
Chapter 4 - Download the API Software
Next, you need to download the API software from the IB website.
The API Software page contains three tabs. Click the Proprietary API tab to see a
table with links to software downloads that are compatible with Windows, MAC
or Unix platforms. When available, there will also be a Windows Beta version of
the software. Look across the top of the table and find the OS you need.
24 www.interactivebrokers.com
For this book,
b we assume that youu are using Windows. Iff you’re usingg
a differennt operating system (Macc, Unix), be sure
s to adjusst the
instructioons accordinggly!
In the Winndows colum mn, click onn Download Latest Verssion. This oppens a File
Download d box, wheree you can deecide whetheer to save thee installationn file,
InstallAX
X.exe file, or open it. Wee recommendd you choosee Save and then select a
place wheere you can easily
e find itt, like your desktop
d (youu choose the path in the
Save in field at the topp of the Savve As box thaat opens up). Once you’vve selected a
good placce to put it, click
c the Savve button. It takes
t secondds to downlooad the
executablle file.
www.interaactivebrokers.ccom 2
25
Step 2: Install the API software.
Next, go to the place you saved the file, maybe your desktop, and double-click the
InstallAX.exe file icon. This starts the installation wizard, a process that displays a
series of dialog boxes with questions you must answer, to make installing the
application easier for you.
Once you have completed the installation wizard, the sample application installs,
and you’re ready to open Excel, connect to TWS, and get started using the sample
DDE for Excel API application!
26 www.interactivebrokers.com
Chapter 5 – Using the DDE for Excel Sample
Spreadsheet
OK, you’ve got all the pieces in place. By the end of this chapter, you’ll actually
be inside the sample API application, all ready to start receiving market data,
create and transmit orders, and do lots of other cool stuff. The sample application
is actually a complete application on its own, and provides everything you need to
get started and more. As a matter of fact, your best bet is to use this file as the
starting point in creating your own DDE for Excel API application. We’ll show
you how to do that after we get you inside.
This next section shows you where to go to open the sample application and hook
up the pages to the TWS. Be patient with this prep work. Before you know it,
you’ll be in Chapter 6, where you’ll finally get to use the spreadsheet pages in the
DDE for Excel API application.
OK, first let’s get TWS started. Log into your account, or even better, log into
your PaperTrader account. If you don’t yet have a paper trading account, go to the
IB website and look at the PaperTrader page under the software menu. The
PaperTrader account gives you access to everything you can get through your
regular account, but you use phantom money to trade, instead of your hard-earned
real money.
Now, use your Windows explorer to find the Excel file. If you didn’t change the
Save location, you’ll most likely find your application, which is called
TwsDde.xls, under My Computer in C:/Jts/Exce/Excel. Double-click this file
icon, and when you see a message about macros, be sure you click the button that
says Enable Macros. If you don’t enable the macros, the sample application will
be useless to you!
The first page you’ll see is the Tickers page. At the top, you’ll see a dark blue
section header that says Toolbar. This gives you all the action buttons you’ll need
to use the features on the page. But for now, you need to focus on the next
section, or the blue header that says “Which Trader Workstation.” This section
has an editable field titled “User Name.” This important field is the place that will
connect you to TWS when you enter the username of the workstation you’re
running. If you enter the wrong username, or forget to enter anything, you won’t
get connected and nothing will work!
www.interactivebrokers.com 27
So, enter your login Username
U (not your passsword, just your
y usernamme). Since
ve to enter thhis usernamee on most off the other paages too, we recommendd
you’ll hav
taking a few
f minutes to copy the namen from this
t field, use the tabs at the bottom
of the worrksheet to move
m from paage to page, and paste yoour usernam me in each
occurrencce of the Useer Name field.
We mentiioned earlierr that this sammple spreadsheet providdes the perfecct starting
point for developing
d y
your own DD DE for Exceel API. Sincee you have soo much in
here to woork with, wee think it maakes sense to save this saample spreaddsheet with a
new namee so that it becomes yourr own file.
If you werre to keep thee existing naame in the cuurrent folderr, the next
time you downloaded
d a new versioon everythinng you’d donne would be
deleted annd replaced with
w latest sooftware. Givving it a new w name
allows youu to keep alll of your chaanges intact.
28 www.interacttivebrokers.com
m
Part III: Getting to Know the DDE for Excel
Sample Spreadsheet
By now you should have the “working” version of the Excel sample spreadsheet
up and running. Now comes the fun part - becoming familiar with all the cool
features. The sample pages give you lots of functionality without making you
figure out how to implement it. More importantly, you can look at the underlying
Visual Basic code to see how it was done, and use some of it to get starting
implementing new creative features of your own!
www.interactivebrokers.com 29
Chapter 6 - Introducing the Excel Pages
When you first open the sample spreadsheet, you’ll find that our development
team has included data on many of the pages to help you better understand how
they work. You can use or delete the data as you want, and add your own. Here’s
what you see when you first open the spreadsheet:
You can see examples on the Tickers page of how to create tickers for stocks,
options, futures, future options, indexes, currency and combination lines. In the
next chapter, “The Tickers Page,” we’ll show you how to set up your own ticker
lines and request market data.
30 www.interactivebrokers.com
The Pages
When you open the spreadsheet, you’ll see a row of tabs along the bottom of the
worksheet. Each of these tabs opens a page, and each page is dedicated to a
specific function or subset of functions. Many of the titles are self-explanatory,
but we’ve summarized them all in the following table.
www.interactivebrokers.com 31
DDE for Excel
E API Sp
preadsheet Pages
Page Descrip
ption
code con
nnecting to th
hese pages too revise it and work off off
the newe
er pages withhout losing fu
unctionality. We
W don’t
recommeend using thiis page to sta
art new projeects!
Each pagge includes a row of actioon buttons at a the top. Cllicking thesee
buttons teells Excel to run a “macro,” which is i basically a piece of
Visual Baasic code dessigned to maake somethinng specific happen in
your spreeadsheet, likee populatingg your tickerr line with livve market
data. In Section
S IV, “LLet’s Open ‘er Up”, we’ll show youu how to creaate and use
this code to completelly customizee your appliccation!
Commo
on Action
n Buttons
s
Although each page is geared tow ward accompplishing a diffferent set off tasks, they
n some comm
all contain mon elemennts, includingg some of the same actioon buttons.
The table below descrribes these common
c butttons.
Button Na
ame Descriptio
on
Combo Legs Allows youu to identify individual legss to be sent as
a a
combinatioon order.
Set Refres
sh Rate The Refressh Rate value e is in millisec
conds, and deetermines
how often the DDE link k to TWS is re efreshed. The
e default
refresh ratte is 1000 (uppdates every y 1 second), and
a the
allowed range is 100 to o 2000, inclus sive.
1 = SYSTE
EM
2 = ERROR
R
32 www.interacttivebrokers.com
m
Button Name Description
3 = WARNING
4 = INFORMATION
5 = DETAIL
Show Errors Jumps to the Error Code field and shows the Last Error.
Clear All Links Removes all links to the TWS. Use this button to ready your
spreadsheet for saving to disk.
www.interactivebrokers.com 33
Chapter 7 - The Tickers Page
The Tickers page happens to be the first page you see when you open the Excel
sample application. Again, remember that you MUST have TWS running, and
you must enter your TWS user name in the Which Trader Workstation? area
before you‘ll be able to get data.
Define a Ticker
OK, the Tickers page is designed for two main tasks: first, to define tickers, and
second, to get market data for those tickers. To get started, we’ll enter a ticker for
a stock, and then request market data. You can see that the TWS API
development team has included a bunch of sample rows to show you where to
enter your information. We’ll create a new blank row. When you select any of
these rows you need to select from the row number in the far left column.
Otherwise, you’ll only be selecting a single field and many of the programmed
actions won’t work. So, let’s select any row by clicking the mouse on one of the
row numbers, then use your right-click button and select Insert. Voila, you have a
new blank row! OK, let’s do it!
34 www.interactivebrokers.com
1. First, put your mouse in the Symbol field and enter an underlying symbol,
for example IBM.1
3. Since you want market data for a stock symbol, you don’t need the next
four columns (Expiry, Strike, P/C and Multiplier) so tab past them and get
to the Exchange field. This field defines where the market data comes
from. For example, enter NYSE.
4. Now tab to the currency field and enter the currency in which the product
trades (for example, USD for US dollars). This field also helps define the
correct symbol.
OK, now you need to…wait a sec. You’re done! You’ve successfully entered a
ticker line for a stock product. Now, want to get some market data running against
this ticker? OK, but before you do this, you should know that you can also define
tickers using the Ticker box, which pops up when you click the Create Ticker
button. Tab through these fields just as you did on the page row, and click OK to
put the ticker row on your screen.
1. Click on the row number in the farthest left column to select the entire
row.
2. Now, move your mouse up to the top of the page and click the button that
says Request Market Data.
That’s it. You should now be seeing a row of market data running across all of the
black fields that are applicable to the type of product you entered on the line. So
in this case, you won’t see any data in the Implied vol or Delta fields, or any of
the other fields that are used for other asset types.
Want to do it again? Let’s get data for all of the sample tickers included. If you
click in the first row and then press the Request Market Data button, each line will
www.interactivebrokers.com 35
be filled in, and you will be moved to the next line automatically. Keep clicking
the button and soon you’ll have data for the whole page. That’s all there is to it!
Simply select a ticker line and then click the Combo Legs button that sits right in
front of the Request Market Data button. You’ll get a little dialog box that helps
you define the characteristics of the leg, such as the ratio of this leg to the rest, the
side (buy or sell), the exchange, and whether the order will open or close a
position.
After you have defined the parameters, click the Add button to see the leg in the
Combination Legs box. Then click OK to close the box, and the Combo Leg field
on that ticker row will now be populated to identify the ticker as part of a
combination order.
We’ve now covered all of the Tickers page functionality. If you want to review
the definitions of the remaining common buttons, review the table earlier in this
chapter. Otherwise, let’s proceed to creating orders from the Orders page!
36 www.interactivebrokers.com
Chapter 8 - The Orders Page
In TWS you view market data and send orders from the same page, but in the
DDE for Excel API you have a separate page for Orders. Click the Orders tab on
the bottom of the spreadsheet, and take a look.
You see a bunch of lines that look very similar to the ticker lines you entered on
the Tickers page. In fact, they are just like those entries. The difference is that
with these ticker entries you’ll be submitting orders instead of viewing market
data. Like most pages in the sample spreadsheet, many of the rows are already
populated to help you understand how the rows and fields work. You might
however, prefer to have these rows populated with the same tickers you entered
on the Tickers page, so that you can monitor prices and submit orders on the
same symbol from two different pages.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
www.interactivebrokers.com 37
Add Your Tickers to the Orders Page
To add your tickers from the Tickers page to the Orders page, simply copy and
paste your ticker lines from one page to another.
1. On the Tickers page, select a row by clicking the row number in the far
left column, then right click and choose Copy. The selected row starts
blinking away likes it’s on a marquee. For example, copy the IBM ticker
line.
2. Now, come back to the Orders page, select a blank row by clicking in the
number field of a blank row, right click and choose Paste.
Depending on which version of Excel you are using, you can also choose
Insert Copied Cells to paste the copied ticker row a blank row; this
command automatically moves the other rows down to make room for the
new row.
You’ve just created a new potential order row. You can also enter a new ticker
symbol manually just as you did on the Tickers page.
Create an Order
Now you’ll create an order for the IBM1 stock ticker, which you entered by
copying and pasting its ticker row onto the Orders page.
1. First, click your mouse in the Action field (the first of the black fields) on
the IBM1 ticker line, and enter Buy or Sell.
2. Tab through the fields, and enter the order Quantity (let’s use 100 for this
example), the Order Type (we’ll use Limit - you can see a list of valid
order types in a bulleted list on the next page.
3. Since it’s a limit order, you need to enter a limit price. Take a look at the
IBM1 market data and come up with a reasonable limit price. Note the
Auxiliary Price field. This is only used for certain order types, such as
relative orders, that need two prices. You don’t need to use it for a basic
limit order.
38 www.interactivebrokers.com
Order Types
The order types currently supported through the DDE for Excel API are:
• Limit (LMT)
• Market (MKT)
• Limit if Touched (LIT)
• Market if Touched (MIT)
• Market on Close (MOC)
• Limit on Close (LOC)
• Pegged to Market (PEGMKT)
• Relative (REL)
• Stop (STP)
• Stop Limit (STPLMT)
• Trailing Stop (TRAIL)
• Trailing Stop Limit (TRAILLMT)
• Volume-Weighted Average Price (VWAP)
• Volatility orders (VOL)
www.interactivebrokers.com 39
We recom mmend you taake a look att the Order Info
I section on
o the
Trading menu
m at
http://indiividuals.interractivebrokeers.com/en/pp.php?f=ordderTypes&o&
&
ib_entity==lic.
Now you’’ve entered alla of the bassic order infoformation. Iff you transmiitted your
order righht now, it woould be validd and a Day time
t in forcee would be used.
u
However,, you have much
m more fllexibility thaan that, if you care to expplore it, withh
Extended d Order Atttributes. Wee’ll go into thhem in detaiil in Chapterr 9 since theyy
have theirr own tab, buut the last release of the API made thhese attributes available
on the Orrders page so that you caan customize them orderr by order. Scroll S past thhe
Order Staatus section and
a take a quuick look at the attributees in the secoond black
section. Here’s
H wheree you enter a good-till-caancelled timee in force, orr mark orderrs
as part off an OCA (onne cancels alll) group. Yoou can skip ahead
a if youu want to readd
about thesse now, or sccroll back annd look at thhe beige Order Status secction of the
Orders sppreadsheet.
Order Status
S Fie
elds
The Order Status fieldds let you knnow what’s happening
h w your ordder. If you
with
want to seee this in acttion, change the limit ordder type to a market ordeer, delete thee
limit pricee and send thhe order. Hoow do you doo that? You may have allready
figured ouut that you simply selectt the order linne, make yoour changes and
a click thee
Place/Mo odify Order button.
b It maay move too quickly for you to see, but
b if you’ree
lucky youu’ll see the Status
S field say
s Submitteed then changge to Filled, and you’ll
note the Filled
F field go
g from 0 to 100. If you’’d submittedd a larger ordder that didn’t
get complletely filled, you’d have values in booth the Filledd and the Reemaining
fields. Wee also show you the averrage price off the filled portion of thee order, and
the price of
o the last filll.
40 www.interacttivebrokers.com
m
Chapter 9 - The Extended Order Attributes
Page
These attributes are completely optional, but you’ll find yourself perusing and
using at least some of them as you become more comfortable with the IB way of
trading. Some of these attributes are only applicable to Institutional traders and
others only to advisors, and these are well marked. If you click the Extended
Order Attributes tab, you’ll notice that this page looks quite different from all of
the other pages. It doesn’t look like the normal data page, instead it’s a list with
the attribute and some notes sandwiching the active Value field, where you enter
your input to control the attributes.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
The Extended Order Attributes page is a template. This means that any values
you enter in the fields on this page will apply to all orders you transmit UNLESS
you specify a different attribute value on that order line. Remember the last
chapter, where you took a look at the second black section of fields labeled
Extended Order Attributes?. That section of the Orders page lets you set
attributes at the order level, versus the Extended Order Attributes page, which
applies attributes at a global level, affecting all orders.
www.interactivebrokers.com 41
There is one
o small cattch to all of this templatee business, and a that is thhe time in
force. Thee time in forrce field dictates which attributes
a willl be appliedd to your
order. If you
y leave thee TIF value blankb on youur order linee all of the vaalues that
currently reside in thee Extended Order
O Attribuutes template will be appplied to yourr
order. If however
h youu ENTER a timet in forcee value, the EOAs
E (you know,
k
Extended Order Attribbutes) on thee EOA page will no longger be used for f that
order, whhich leaves evvery other EOAE field blaank. So, if you’re thinkinng to
yourself, “Self, I thinkk I’ll enter a different tim
me in force for
f this orderr, but use alll
of the oth
her attributes from the EO OA page.” well,
w let’s jusst say you’d be kidding
yourself!
An Exa
ample
Still don’tt understandd? Let’s lookk at somethinng basic thatt will resonatte with manyy
traders, th
he time in force value off DAY. A daay order is faamiliar to us all, it’s
simply an n order that will
w be canceelled at the close
c of the day’s
d markett if it hasn’t
executed. If you noticce on this Exxtended Ord der Attributtes page, thee very first
value at thhe top of thee page is DA
AY, in the timme in force row.
r Now, iff you create
and transmmit an order and don’t ennter any valuue in the Tim me in Force field that
appears on your orderr line, then your
y order byy default is a DAY orderr, since it
uses whattever value is in this Exttended Orderr Attributes template.
t
Now go back
b to that order
o on the Orders pagge, but beforee you transm mit it, scroll
over to th
he right and enter
e GTC (ggood till canncelled) in thhe Time in Foorce field.
Now, for JUST THAT T ORDER, youy have chaanged the tim me in force tot good-till-
cancelled, and the ordder will conttinue to workk, day after day,
d until it either
e
executes or
o gets canceelled. On thee other handd, if you weree to have enttered GTC
as the tim
me in force onn the Extendded Order Attributes
A p
page, all of your
y orders
from that day forwardd would havee the GTC tiime in force,, ‘till death do d they part.
Remembeer that the template appliies for all off the fields onn this page, not just the
time in fo
orce.
Extend
ded Orderr Attributtes
As you caan see in Apppendix A, thhe API suppoorts many opptional orderr attributes.
42 www.interacttivebrokers.com
m
Now you’ve seen the Orders page, where you create your basic orders, and the
lovely Extended Orders Attributes page, where you apply such characteristics as a
new time in force, a display size to create an iceberg order, a discretionary amount
to give more leeway to your limit orders, and even a checkbox to hide your entire
order. You can do a lot of cool things with these two pages, but the one thing you
can’t do is set up conditional orders, which are described in the next chapter.
www.interactivebrokers.com 43
Chapter 10: The Conditional Orders Page
A conditional order is one that relies on something else happening, either a price
changing or another order executing, before this order is submitted. Let’s take a
look at this useful and outstanding order.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
In a nutshell, a conditional order is one that waits around, all set to go, for
something precipitous to happen that will trigger its coming to life. For example,
you might want to submit a sell order for 100 shares of XYZ, but you only want
to do it if you’re first able to buy 100 shares of LMNOP at some specific price.
With the conditional order all set waiting in the wings, you don’t need to sit
around watching and waiting to see if the first order executes. All you need to do
is set up a trigger condition and let it go.
Take a look at the paired set of sample orders that are included on the
Conditional Orders page in the sample spreadsheet.
The key field in a conditional order is field Y11, the Statement trigger field. Until
some condition is met, the value in this field is always FALSE. This means
nothing will happen. When your condition is met, this value becomes TRUE and
that triggers your conditional order.
In the above illustration, note the value “FALSE” which appears in cell Y11, the
trigger Statement field. When you put your curser in this cell, the cell’s condition
trigger displays on the formula line. In this case the condition says
“=(M10=T10),” which in English means “the value in this field will be TRUE
when the value in cell M10 is equal to the value in cell T10.” Let’s look closer
and see what M10 and T10 really are. You see that cell M10 is the Quantity field
for the first order, and has a value of 10. Cell T10 is the Filled field for that order
and currently has no value. Since the filled field shows the filled order quantity,
44 www.interactivebrokers.com
this meanns that the second order will
w only triggger when thhe full quantity of the
first orderr has executeed.
To see thiis order in acction, highligght the orderr on row 10 and click thee
Place/Moodify Order button.
b Sincee it’s a markket order it shhould executte quickly, so
watch clo
osely!
1. Too get this vallue, go to thee Tickers paage and put your
y cursor in the Bid
1
Prrice field on the line thatt’s displayingg IBM markket data (if youy don’t
haave it, add it!!) Now lookk up in the foormula line (iit’s right undder the
toolbar at the top
t of the paage, and has the equal siggn to identiffy it) and seee
that it says “=uusername|tikk!id4?bid” but
b with yourr username instead
i of thee
woord “usernam me.” Copy thhis value usiing the Copyy command or o Ctrl + C,
then scoot righht back to thhe Condition nal Orders page.
p
2. Noow, let’s set this up. Starrt in a blank line, and ennter the undeerlying and
her parameters in the Coontract Desccription fieldds (IBM1, ST
oth TK, Smart
an
nd USD).
You mighht be wonderring why youu didn’t just useu the form mula “O 12 >
81.00” orr something like that, sinnce you can pinpoint
p the column andd
row in whhich the partticipating bidd price residdes. The reasson is that
you’re using two diffeerent pages, both of whicch have an “O “ 12” fieldd.
The Condditional Ordeers page wouuld use the O 12 value from fr its own
www.interaactivebrokers.ccom 4
45
page, and that would not help you one bit. So in this case, to avoid confusion you
have to use the actual field code.
4. Again, move your cursor to some other field, and now you’ll see that the
value in the Statement field is “FALSE,” which is just what you want! If
the IBM1 bid price drops below 81.00, this will become TRUE, and when
the Statement value is true - it triggers the conditional order!
5. Next, you need to tell the API what you want it to do if the bid price drops
below 81.00. So, in the ADD/MOD field, enter ADD (since you’re not
modifying an order), then BUY in the Action field, 500 in the Quantity
field, LMT in the Order Type field and 80.90 in the Lmt Price field.
OK, you’ve done it. Will this execute for you? Who knows? But if your
conditions are ever met, your new order will be submitted, that you can count on!
You can do lots of interesting things with the Conditional Orders feature. We
recommend you log into your PaperTrader account and experiment.
46 www.interactivebrokers.com
Chapter 11 – The Open Orders Page
The Open Orders page shows you all transmitted orders, including those that
have been accepted by the IB system, and those that are working at an exchange..
Once you have subscribed, the page is updated each time you submit a new order,
either through the API or in TWS.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
How Do I Subscribe?
Another way to say this would be “View your open orders.” You don’t subscribe
in the everyday sense of signing up, paying a fee and receiving something. You
simply click a button, and the VBA macros working behind the scenes quickly do
all the complicated stuff, so that you can see all of your open orders. In addition,
these macros ensure that this data updates in real-time, so that if an order executes
you’ll know it.
To do this, imply click the Subscribe to Open Orders button on the toolbar. All of
your orders will display in the Excel worksheet as soon as they are accepted. If
you don’t currently have any working orders, the API will kindly tell you that you
have “None at this time.”
Even when you log out of TWS or close down your Excel spreadsheet, your
subscription remains active until you elect to cancel it by clicking the Cancel
Open Orders Subscription button. If you entered new orders via TWS while the
API was shut down, as soon as you log back in any new open orders are
displayed.
www.interactivebrokers.com 47
Named Ranges for Results
The results are displayed in a “named range” so that they can easily be
manipulated through a page-specific Worksheet_Calculate macro, which our API
developers have written and included. A named range is a Microsoft Excel feature
that lets you assign a meaningful name to a single cell or a range of cells. In the
DDE for Excel API VB code, we use named ranges on every page to represent
ranges of cells on that page. For example, on the Open Orders page, we assigned
the named range “openSubOrders” to all of the cells in the Order Description
portion of the Open Order results to easily reference those cells in the code.
In Microsoft Excel 2007, you access the named range feature on the
Formulas tab (for example, the Name Manager displays all names defined
for the current worksheet). In previous versions of Microsoft Excel, you
define name ranges from the Insert menu.
Using named ranges, you can tell the API to put the open orders somewhere else,
like on a different spreadsheet or in a different set of rows and columns.
1. Use the Excel Tools menu, mouse over the Macro subcommand and then
choose Macros.
If you are using Excel 2007, select the View tab at the top of the screen,
then click Macros button.
3. To see the named ranges used on this page, open the code for Sheet 10 and
look at the code for the macros used on this page.
In Excel 2007, you can view all of the named ranges used in the entire API
spreadsheet by clicking the Formulas tab, then clicking Name Manager.
In previous versions of Excel, you can view and define named ranges by
clicking Name > Define on the Insert menu. There is also a Name
Manager for Excel utility available from Microsoft for versions of Excel
prior to Excel 2007.
48 www.interactivebrokers.com
What Happens If an Open Order Executes?
Once an order executes, it remains on the Open Orders page for 30 seconds, with
the Status value changed to FILLED. Then the filled order is cleared away, and
you can see it on the Executions page (once you subscribe to real-time
executions, of course!).
www.interactivebrokers.com 49
Chapter 12 – The Executions Page
The Executions page is pretty straightforward - it displays the current day’s
executions.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
OK, to do all this stuff, simply click the Subscribe to Executions button on the
toolbar. All of the day’s executions will display in the Excel worksheet. If you
currently do not have any execution reports, the API will kindly tell you that you
have “None at this time.”
Clearing Executions
To clear the spreadsheet of all displayed executions, first cancel the subscription,
and then click the Clear Executions button.
50 www.interactivebrokers.com
Named Ranges for Results
The results are displayed in a “named range” so that they can easily be
manipulated through a page-specific Worksheet_Calculate macro, which our API
developers have written and included. A named range is a Microsoft Excel feature
that lets you assign a meaningful name to a single cell or a range of cells. In the
DDE for Excel API VB code, we use named ranges on every page to represent
ranges of cells on that page. For example, on the Executions page, we assigned
the named range “execSubDetails” to all of the cells in the Execution Description
portion of the Executions page results to easily reference those cells in the code.
In Microsoft Excel 2007, you access the named range feature on the
Formulas tab (for example, the Name Manager displays all names defined
for the current worksheet). In previous versions of Microsoft Excel, you
define name ranges from the Insert menu.
Using named ranges, you can tell the API to put this execution data somewhere
else, like on a different spreadsheet or in a different set of rows and columns.
1. Use the Excel Tools menu, mouse over the Macro subcommand and then
choose Macros.
If you are using Excel 2007, select the View tab at the top of the screen,
then click Macros button.
3. To see the named ranges used on this page, open the code for Sheet 11 and
look at the code for the macros used on this page.
In Excel 2007, you can view all of the named ranges used in the entire API
spreadsheet by clicking the Formulas tab, then clicking Name Manager.
In previous versions of Excel, you can view and define named ranges by
clicking Name > Define on the Insert menu. There is also a Name
Manager for Excel utility available from Microsoft for versions of Excel
prior to Excel 2007.
www.interactivebrokers.com 51
The Executions Reporting Page
In addition to viewing all executions, you can filter your returns using the
Executions Reporting page. This page is linked to the Executions page (which
means you don’t need to enter your username anywhere) and can be used as long
as you have subscribed to the executions function on the Executions page.
52 www.interactivebrokers.com
Chapter 13 – The Account Page
The Account page shows you everything you will ever need to know about the
status of your account. Once you’ve entered your TWS Username, simply click
the Subscribe to Account Updates button and the Account Values section will be
filled with up-to-the-minute values, from your Equity with Loan Value through
your margin and P&L values. (see Appendix B for details on all of the values
shown on the Account page). These values are updated every 3 minutes.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
www.interactivebrokers.com 53
Your “subscription” remains active until you elect to cancel it by clicking the
Cancel Account Subscription button. Note the little field between the buttons and
the spreadsheet titled “Last Update Time.” This time tells you when the API last
updated the values on the spreadsheet through TWS. These values are checked
and updated automatically every three minutes.
To make this work, simply click the Subscribe to Account Updates button on the
toolbar. Your latest account information instantly populates the page.
In Microsoft Excel 2007, you access the named range feature on the
Formulas tab (for example, the Name Manager displays all names defined
for the current worksheet). In previous versions of Microsoft Excel, you
define name ranges from the Insert menu.
Using named ranges, you can tell the API to put this execution data somewhere
else, like on a different spreadsheet or in a different set of rows and columns.
1. Use the Excel Tools menu, mouse over the Macro subcommand and then
choose Macros.
If you are using Excel 2007, select the View tab at the top of the screen,
then click Macros button.
54 www.interactivebrokers.com
2. Scroll down the list to find the Worksheet_Calculate macro specific to the
page functionality you’re interested in. For example, Sheet14 macros
apply to the Account page, which you can infer by the Sheet14 macro
names, such as subscribeToAccts and requestManagedAccts.
3. To see the named ranges used on this page, open the code for Sheet 11 and
look at the code for the macros used on this page.
In Excel 2007, you can view all of the named ranges used in the entire API
spreadsheet by clicking the Formulas tab, then clicking Name Manager.
In previous versions of Excel, you can view and define named ranges by
clicking Name > Define on the Insert menu. There is also a Name
Manager for Excel utility available from Microsoft for versions of Excel
prior to Excel 2007.
www.interactivebrokers.com 55
Chapter 14 – The Portfolio Page
The Portfolio page displays all of your current positions.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
To view your portfolio, simply click the Subscribe to Portfolio Updates button to
populate the page with the current positions you hold in your portfolio. This page
works the same as the Account page, and also goes out to TWS and updates the
values every three minutes, which you can see in the Last Update Time field in
the Which Trader Workstation area.
56 www.interactivebrokers.com
Chapter 15 – The Historical Data Page
Use the Historical Data tab to request historical data for an instrument based on
data you enter in a query. This information equates to charting a contract in TWS
, except that the information you see is all in rows on a spreadsheet, rather than in
a pretty colored line or bar chart! As a matter of fact, each row value in the
spreadsheet is considered a “bar” just a like a bar in your chart. You can request
historical data as far back as a year, and also for expired futures contracts.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
Excel shows the results on a separate page, which it creates specifically for these
results. When you define the parameters, you’ll include a name for your historical
data returns in the Page Name field.
Note that since the query returns a named range of cells, you can write VBA
macros to perform computations on it, and you can chart and sort the data in
Excel.
www.interactivebrokers.com 57
How Do I Request Historical Data?
Requesting historical data is as easy as pushing a button! Well, first you need to
make sure you’re hooked up to TWS through your user name, and then you have
to figure out which symbol you want to request data for. After you’ve done all
THAT, well THEN it’s just as easy as pushing a button!
The Historical Data page in the sample application comes pre-populated with all
types of instruments as examples for you to follow when creating a ticker and
then requesting historical data. To create a ticker line, it’s the same simple process
you used to add tickers on the Tickers page. You can either click the Create
Ticker button and enter the description in the Ticker dialog box, or you can click
your mouse in an empty Symbol field on the worksheet page and tab through the
fields necessary to define your ticker.
Parameter Description
Name
End Data/Time Use the format yyyymmdd {space}hh:mm:ss{space}tmz
where the time zone is allowed (optionally) after a space at the
end.
Duration This is the time span the request will cover, and is specified
using the format integer {space} unit, where valid units are:
S (seconds)
D (days)
W (weeks)
M (months)
58 www.interactivebrokers.com
Parameter Description
Name
30 SECS 4
1 MINS 5
2 MINS 6
3 MINS 16
5 MINS 7
15 MINS 8
30 MINS 9
1 HOUR 10
1 DAY 11
1 WEEK 12
1 MONTH 13
3 MONTHS 14
1 YEAR 15
Trades
Midpoint
Bid
Ask
Bid_ Ask
All but the Bid_Ask data contain the start time, open, high, low,
close, volume, trade count and weighted average price during
the time slice queried.
For the Bid/Ask query, the open and close values are the time-
weighted average bid and the time-weighted average offer,
respectively. These bars are identical to the TWS charts'
candlestick bars.
RTH Only Regular Trading Hours only. Valid values include:
0 - all data available during the time span requested is
returned, including time intervals when the market in question
was outside of regular trading hours.
1 - only data within the regular trading hours for the product
requested is returned, even if the time span falls partially or
completely outside.
www.interactivebrokers.com 59
Parameter Description
Name
Date Format Valid values include:
Style
1 - dates that apply to bars are returned in the format
yyyymmdd{space}{space}hh:mm:dd (the same format used
when reporting executions).
Page Name The name you enter will be used to name the new system-
created page into which Excel puts the historical data.
Expired Valid values include True and False. If true, the query will run
on an expired contract, although it is limited to the last year of
the contract’s life, and is currently only valid for expired futures
contracts.
OK, so you’ve created a ticker and then entered all the query information you’ll
need. Your spreadsheet page looks something like this:
Now just click the Request Historical Data button and after a few moments, the
API will create a new page that looks something like this:
60 www.interactivebrokers.com
Notice that the date and time, the opening price, the high and low prices and, the
closing price, all for that bar. You also see the trading volume, the number of
trades that occurred (trade count) per bar, and the weighted average price.
www.interactivebrokers.com 61
62 www.interactivebrokers.com
Chapter 16 - The Market Scanner Page
The market scanners use the criteria you enter along with the scan code definition
to return X number of the top matching contracts, all in a nice, new scanner page.
For example, you might want to know the top 30 most active stocks currently
trading on the NYSE. You can view these results on the above mentioned nice
new scanner page, which by the way YOU named, and can even activate a feature
that will make this page pop to the front of your application any time there are
additions, deletions or any other changes to the list. Let’s see how to do all this!
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
www.interactivebrokers.com 63
How Do
o I Subsc
cribe to a Market Scanner?
S ?
Look at th he list of “Sccan Codes” ini the Scan Code
C field. This
T field, allong with thee
rest of thee subscriptioon details, tellls the API which
w data too return to yoou. We havee
included a bunch of thhem for you, but more could be addeed that you might m want
to see.
Just select a scan line, modify anyy of the filterr elements iff you want (tthey’re
describedd in the first of
o two tabless below) andd click the Sttart Scanner
Subscription. Once it successfullyy subscribes to the scan, the value too the left of
the name in the Ctrl column
c changes from PR ROCESSING G to SUBSCR RIBED.
Elemen
nts of a Market
M Da
ata Scan
The follow
wing table describes
d the elements thhat make up a scanner suubscription, in
i
other worrds, the availlable fields into which yoou can enterr the descripttive
informatioon that will get
g you whaat you want to t see!
Waatch out for thet Activatee Page field! It seems likke a nice featture that getss
youur attention any
a time the results channge. But whaat it will do isi pop this
sca
anner page too the front off the applicaation regarddless of what else is goingg
on, such as youu entering daata on anotheer worksheeet or creatingg some
complex and
a ingeniouus VBA codee to perform some amaziing feat. Thiss feature
doesn’t ca
are, it interrrupts at will! If you find it
i interrupts too much, juust change
the value in this field to FALSE.
The follow
wing table liists the elem
ments that maake up a marrket data scann.
Element Name
N Descriptio
on
Page name
e This is the name that will
w be given to t the new pa age that
is created with the scan nner data.
Activate Page? If set to tru
ue, the new scanner
s page
e will pop to the
t front
of the work ksheet pages s every time a result returrns. This
could be as s often as every minute.
Scan Code
e Identifies the
t type of sc
can. See the Take a Peek!! Note
above for some
s instructtion on how you
y can find the scan
64 www.interacttivebrokers.com
m
Element Name Description
codes!
Instrument Identifies the instrument type used in the scan.
www.interactivebrokers.com 65
Available Market Scanners
The following table shows a list (current as of April 2008) of the available
scanners.
66 www.interactivebrokers.com
Market Scanner Parameters
Parameter Description
High Option Shows the top underlying contracts (stocks or indices) with the
Imp Vol Over largest divergence between implied and historical volatilities.
Historical
Low Option Imp Shows the top underlying contracts (stocks or indices) with the
Vol Over smallest divergence between implied and historical volatilities.
Historical
Most Active by Displays the most active contracts sorted descending by options
Opt Volume volume.
Most Active by Returns the top 50 underlying contracts with the (highest number
Opt Open of outstanding call contracts) + (highest number of outstanding put
Interest contracts)
High Opt Put option volumes are divided by call option volumes and the top
Volume P/C underlying symbols with the highest ratios are displayed.
Ratio
Low Opt Put option volumes are divided by call option volumes and the top
Volume P/C underlying symbols with the lowest ratios are displayed.
Ratio
High Option Returns the top 50 contracts with the highest put/call ratio of
Open Interest outstanding option contracts.
P/C Ratio
Low Option Returns the top 50 contracts with the lowest put/call ratio of
Open Interest outstanding option contracts.
P/C Ratio
Hot by Option Shows the top underlying contracts for highest options volume over
Volume a 10-day average.
Market Lets you see exchange-specific statistics for:
Statistics
Advancing, declining and unchanged issues
www.interactivebrokers.com 67
Deleting Market Scanner Results
If you want to delete this page at any time, just right click on the tabbed title and
select Delete.
68 www.interactivebrokers.com
Chapter 17 - The Contract Details and Bond
Contract Details Pages
The Contract Details and Bond Contract Details pages may be two of the least
complicated, yet most useful, of all the pages. Basically, use these two pages to
get important contract-related information that you might need to help you enter
valid parameters on other pages. What? Well for example, you might want to find
out what order types are supported for specific instrument on a certain exchange.
Use the Contract Details page! Or you might need the ConID or some coupon
information for a bond to allow you to properly request a ticker. Use the Bond
Contract Details page! The main reason these are separated is that the contract
information for bonds is so different from that on other instruments, we’d have
need a billion columns on one worksheet to cover them all.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
Expired Options
Under the Options heading, notice that since this application was written, some of
the options have expired. If you try to get details on these expired options, all
you’ll get are zeros. Now, click the Show Errors button, and look at the last error
message. It tells you that “No security definition has been found for the request.”
In other words, this doesn’t exist anymore! If you just change the date to a valid
expiry and request the details again, the API will be able to help you out.
The following picture shows you the results of a contract details request.
www.interactivebrokers.com 69
Notice that the expiry date on the first option in the list has been modified.
70 www.interactivebrokers.com
Using Contract Details on Other Pages
To use any of the data from the Contract Details or Bond Contract Details
pages on other pages, copy and paste the contents of a cell.
www.interactivebrokers.com 71
Chapter 18 – The Market Depth Page
Market Depth shows you the alternative bids and offers away from the inside
quote, which gives you a broader picture of what’s happening and can help you to
better gauge market liquidity. You can also specify SUPERSOES for instruments
that trade on Nasdaq and receive Level II Nasdaq market quotes.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
Now, if you want to see more than ten lines, you can modify the value in the
reqMktDepth macro. Here’s what to do:
72 www.interactivebrokers.com
1. Onn the Tools menu,
m selectt Macro, theen select Maccros. The VBBA editing
en
nvironment opens
o in a neew window, and a list off macros is displayed.
d
Co
onst maxRow
ws = 10
3. Chhange this “10” to whateever numberr of rows youu want to dissplay, save
the macro andd go back happpily to yourr worksheet..
Cool, huhh? Just a little taste of hoow fun and easy it is to work
w with VB BA. Of
course, in
n this case yoou were just editing sommeone else’s work,
w but thhat’s the bestt
way to staart.
Cancellling a Ma
arket Dep
pth Reque
est
If you waant to cancel your markett depth request, click thee Cancel Maarket Depth
button.
www.interaactivebrokers.ccom 7
73
Chapter 19 – The Old Style Executions and
Account-Portfolio Pages
The development team left two vestiges of the old-style screens: the Old Style
Executions and the Old Style Account -Portfolio screens. They present the same
data as the newer Executions, Account and Portfolio pages, but require you to
click a button for each line of data. In addition, the latest and more efficient
versions of both also break out the Account and Portfolio features to two pages,
and include a new Executions Reporting page. These pages were left intact in
deference to users who already have code linked to them. If by chance you
happen to be one of these users, you should probably think about ending your
dependence on these pages, and start using the “new fangled” pages instead.
As always, make sure TWS is running, and don’t forget to enter your
username in the User Name field!
74 www.interactivebrokers.com
Part IV: Creating Your Own API Application
In this section, you’ll be leaving the world of the known, and venturing into new
territory. Now that you’re familiar with the DDE for Excel API and how it works,
it’s time to leave the nest and make your own way. And we know that this is why
you’re really here - to find out how to manipulate the API to create an application
that does what YOU want, and it’s probably something you can’t find anywhere
else. This section shows you the basics of using the VBA editor, and provides a
few samples of some real-life API application scenarios a customer might want to
implement.
www.interactivebrokers.com 75
Chapter 20 – Download the Samples
Along with the samples, we’ve also put together a whole DDE Excel worksheet
with the code included, which you can download to your local drive directly from:
http://individuals.interactivebrokers.com/en/p.php?f=programInterface&p=a&
ib_entity=lic, click the Proprietary API tab, then click Getting Starting Guide to
display the page with the downloadable samples.
In the course of viewing and perhaps modifying these sample scenarios, you’ll get
a little bit of a feel for how VBA works, and maybe you’ll even get some new
ideas of situations you’d like to create yourself. Of course, in order to protect your
million-dollar idea, you’ll have to implement your ideas on your own. We include
a list of some helpful VBA reference books and other outside help in Chapter 23 –
Additional Resources.
76 www.interactivebrokers.com
Chapter 21 - Using VBA to Customize the API
The Excel pages have been deliberately designed to give you easy access to the
Visual Basic for Applications code that sits behind its functionality. Specifically:
• Each worksheet page that includes buttons has that button’s macro logic in
its own VBA rather than in worksheet-wide modules. This makes the
VBA that does work on a specific page easier to find and understand, and
makes it easier for you, the user, to add functionality to an existing
worksheet, or to base the code in a new custom-built worksheet on that of
one of our pre-existing worksheets.
• You’ll find the functions in the util module particularly helpful in building
new VBA functionality. For example, the composeLink function puts
together a link that receives data such as the bid size, execution ID or
option model volatility. The composeContractReq function reads a
contract description right out of another page, like the Tickers or Orders
page, and builds the DDE string representing it.
Now let’s take a look at how you can access all of this VBA stuff!
From the Excel interface, open one of the pages by clicking a tab at the bottom of
the screen, say the Executions Reporting tab. OK, now open the VBE by clicking
Alt + F11. See? Not only does the editor open, but it opens with the active sheet
selected in the Project Explorer section, in this case Sheet.16 (Executions
Reporting).
www.interactivebrokers.com 77
Looking at the Visual Basic Editor
Here’s what you’re looking at:
Project Explorer
Code Window
Properties Window
The Project Explorer shows a tree diagram that lists all projects (we have only
one project which is called TwsDde.xls), at least one node (in this example it’s
Microsoft Excel Objects), and the objects contained in the node. You’ll notice
that the Microsoft Excel Objects correspond to the pages in the DDE for Excel
API spreadsheet. The VBA Project Explorer also shows an object called This
Workbook which holds any VBA modules. The Excel spreadsheet includes a
clearLinks module for each worksheet, which you see as a button on the Tickers
page called Clear All Links. This piece of code removes all DDE links to TWS
that the VBA (which IB provided) could create. This does things like canceling
market data, historical data and scanner subscriptions, and prepares your
worksheet to be saved to disk. If you were to add some of your own custom links,
78 www.interactivebrokers.com
you could
d add them too this clearL
Links modulee. This woulld clear yourr links as well
when youu click the Cllear All Linkks button.
Below thee Project Expplorer is the Properties Window, whichw displayys propertiess
specific to
o the type off object you have selecteed in the Projject Exploreer.
• En
nter it directlly into the coode window
w.
• Co
opy the codee from one module
m and paste
p it into another.
a
The Immmediate Wind dow allows you to execuute VBA staatements direectly, and to
debug. If you don’t seee this windoow when youu open VBA A, press Ctrl + G. The
windows and menus workw along the
t lines of other
o Windoows GUIs, foor example
you have right-click menus
m and dropdown
d lists and toolbaar icons just like you
have in MS
M Excel or MS M Word. We’reW not gooing to try too teach you how
h to
become a VBA experrt, but we wiill give you a very imporrtant piece of advice:
READ CH HAPTER 211 AND GET T A HOLD OF O SOME OF O THOSE OUTSIDE
O
RESOUR RCES!! We’lll discuss othher VBA bassics as we crreate some sample
applicatio
ons in the nexxt chapter.
Create and
a Save a VBA Ma
acro
y to the seerious API saamples, we’ll show you how to
Before wee introduce you
create a useful
u but sim
mple macro of
o your ownn! You’ll recoord a simplee task that
enters youur username on a page. This
T has som me limitationns, but it’s a good way too
get started
d and take a look at som
me code that VBA
V construucts for you when you
record your actions.
www.interaactivebrokers.ccom 7
79
You’re going to record your actions as you click in the User Name cell
and enter your TWS User Name. You’ll assign a hotkey (say, Ctrl + U),
and then when you open a new page, you’ll only need to press Ctrl + U to
enter your user name on the page.
2. Next, start the macro recorder. This is simpler than clicking the record
button on your VCR.
3. On the Tools menu, select Macro, then click Record New Macro. A little
information box opens, and you’ll want to oblige it by entering some
useful information.
If you are using Excel 2007, click the View tab, then click the down arrow
on the Macros button and select Record Macro from the drop-down menu.
4. Type the name of your macro. (For example, you can name your macro
“AutoUserName” for two reasons: first, it’s descriptive so you can
remember what it does, and second it begins with the letter “A” so it will
be right at the top of the macro list and easy to find.)
5. Now enter a shortcut key which you’ll press along with the “Ctrl” key to
activate the macro. You’re going to keep it in This Workbook, and leave
the default description, so we’re done here. Click OK to start the recorder.
Be aware that any keys you press at this point, or any click of the mouse,
will be recorded, so don’t do anything! You want to keep this as clean as
possible so you won’t have to go in later and remove lots of extraneous
VBA code.
80 www.interactivebrokers.com
6. Click in the User Name entry box, type your username and press Enter.
7. Stop the recording process by clicking the blue square STOP button on the
recorder.
If you are using Excel 2007, click the View tab, then click the down arrow
on the Macros button and select Stop Recording from the drop-down
menu.
Next, you’ll, oh - wait a minute. You’re done. Yes, really, that’s it! But don’t get
too excited yet - there’s one catch to this particular example macro. Next you’ll
run the code and see what happens.
1. On the Tickers page, delete your user name from that field, then run your
new macro by clicking the hotkey combination, which in your example
would be Ctrl + U.
You should see your username magically appear in the field. Don’t worry
if you made a typo, we’ll be going into the editor and you can fix it there.
Now you may be thinking to yourself “Hey, but you said there was a
catch! What’s the catch?”
HUH? What just happened? Your username ended up in the wrong place, that’s
what happened! When you recorded the macro, the exact location of the entry cell
you used was recorded, and on the Tickers page that User Name cell is B5. It
just so happens that on all of the other pages it’s D5! Your macro is good, but it
can’t reason, it can only use the information you gave it. It has no idea, and really
doesn’t care either way, if the results are what you had hoped for.
But this isn’t such terrible news, because it gives you a chance to go into the VBA
code, take a look at what’s going on and make a minor change to make the code
slightly more useful.
Select Macro from the Tools menu, then Macros from the menu. If you are using
Excel 2007, click the View tab, then click the Macros button), and find your
macro in the list. Your macro should appear at the top of the list. Next, select your
macro, and then click the Edit button to open it in the VBE Editor.
www.interactivebrokers.com 81
Modules
Notice that you’re in the VBE editor, and Modules is highlighted in the Project
Explorer. Although you named the macro, you didn’t name this module, so do
that now so it’s easier to find in the future.
In the Properties window, click the name Module1 and enter a new name. In the
hierarchy of things, the Module is the container of the macro (or sub procedure)
and could ultimately be home to more of these macros, so you don’t want the
Module name to be the same as your macro. We could call it something like Tests
and put anything we want to play with in this module.
82 www.interactivebrokers.com
The Actual Code
Now look to your right, and you’ll see your macro sitting there, just waiting.
Although at first glance this might look like Greek to you, if you take just a
second longer, you’ll start to make sense of some of it, especially if you think
back to what you just recorded.
First, at the top and bottom in blue text you see the words “Sub” and then “End
Sub.” These tell you that what lies between is a little piece of code called a sub
procedure (or routine). Note that words in green have a single quote in front of
them. This indicates that they are “comments” and they’re not part of the code.
Once you put the single quote in, you can type an explanation or description,
whatever you want, and VBA won’t try to do anything with it.
Next you come to the VBA code that your little macro created, and you might
recognize the notorious cell, B5, in the Range.Select method. Let’s change this
value to “D5” instead (this simple change will make the macro work on all pages
EXCEPT the tickers page, but we really just want to make a change and see it
work) and if you mistyped your username, this is where you can correct it. In
addition, after you entered the username during the recording session, remember
that you pressed the Enter key. That action is reflected in the Range (“B6”).Select
method, but you really don’t want to select another cell, so just delete that line
altogether, and then save your work. If you run your macro on any of the pages
other than the Tickers page, now you’ll get an accurate result.
Chapter 22 includes some useful and more complex code samples that you’ll want
to explore moving forward.
www.interactivebrokers.com 83
Chapter 22 - Sample Applications for the API
We’ve included five real-life samples to help you get a feel for what you can do
with the DDE for Excel API, beyond the features already included for you. Your
best bet for exploring these samples is to open the Excel spreadsheet you’ll find
via the Samples link below, and run it against your TWS.
For each sample , we’ve include a detailed description including its primary
raison d’être. And along with getting the chance to examine some VBA code and
see some cool stuff, you can save the sample spreadsheet in your local directory
with another name, and use the code as your own!
The list below includes an overview of each sample. If you click the title, you’ll
go directly to the page that gives more specific details on the example.
Samples Overview
• Sell based on P & L - Sell positions with a P&L greater than or equal to a
user-defined trigger value.
84 www.interactivebrokers.com
Download the Samples
Download the TwsDdeBeginners.xls spreadsheet right onto your computer to have
instant access to the code and the new worksheets.
http://individuals.interactivebrokers.com/en/p.php?f=programInterface&a&ib_ent
ity=lic.
Then click Getting Started Guide to display the page with the downloadable
samples.
www.interactivebrokers.com 85
Modify the P&L Trigger Value
The purpose of this sample
is to sell open positions in your portfolio that have: Realized P&L + Unrealized
P&L >= a pre-defined value. This pre-defined value is stored in a variable called
P_AND_L_TRIGGER_VALUE and is set to 50. You can modify the value of the
P&L Trigger Value variable by changing the value in the declaration:
Save your changes. When the trigger value is reached, a sell market order is
created. This information is logged on the worksheet titled “Auto Orders.” The
results of the order will then appear on the other worksheets that have subscribed
to account changes, for example, “Executions” and “Portfolio”.
86 www.interactivebrokers.com
Code Summary
Module(s)/Subroutine(s):
Example1
automateTrade() – The subroutine that monitors
P&L for your open positions
startTimer() – Starts the P&L background macro
stopTimer() – Stops the P&L background macro
ExampleUtil
Contains common functions for the examples
New Worksheet(s)
The “Auto Orders ” page was created to log the orders that are initiated by
background macros. It also contains controls to start/stop the background macros.
www.interactivebrokers.com 87
How Does the Sample Work?
The purpose of this sample is to buy the top three implied volatility gainers and
sell them when they are no longer ranked within the top five.
a. Note that in order to obtain the ask price, you need to have the
ticker already running on the Tickers page. It will auto-create the
ticker if not there, but in that case cannot immediately get the ask
price due to a delay in processing. On the next run of the macro (it
runs every 2 minutes), it will pick up the ask price.
For each of the three top stocks (previous top stocks), the macro continuously
checks to see if the stock’s rank has fallen below the fifth position. If it has, the
macro then checks to see if there are open positions in the portfolio. If so, a sell
market order is created. This occurs for each run of the macro, except the first run
when there are no “previous top stocks.”
88 www.interactivebrokers.com
As in Example1, the information is logged on the worksheet titled “Auto Orders.”
The results of the order(s) will then appear on the other worksheets that have
subscribed to account changes, for example, “Executions ” and “Portfolio .”
This subroutine runs in the background and can be enabled when you first open
the spreadsheet, or by clicking the “Start” button on the “Auto Orders ” screen for
“VOL.”. The scheduling is controlled by the variables RUN_WHAT and
RUN_INTERVAL_SECONDS. The RUN_WHAT variable contains the macro
name, i.e., Example2.watchVolatilityGainers, and the
RUN_INTERVAL_SECONDS variable contains how often the macro should run,
i.e., 120 seconds.
Code Summary
Module(s)/Subroutine(s):
Example2
watchVolatilityGainers() – The subroutine that
monitors top volatility gainers.
startTimer() – Starts the VOL background macro.
stopTimer() – Stops the VOL background macro.
ExampleUtil
Contains common functions for the examples.
New Worksheet(s):
The “Auto Orders ” sheet was created to log the orders that are initiated by
background macros. It also contains controls to start/stop the background macros.
This is the same worksheet used for Example1, Sell based on P & L.
www.interactivebrokers.com 89
Example 3 : Export Daily Executions
The code for this macro is in the Example3 module. Use the Alt + F11 hotkey
combination to open the VBE editor, and in the Project Explorer open the
Modules directory and double click Example3.
The macro will first check that there is data available on the Executions screen. If
there is, it will create a destination file (variable DestFile) with the file name
format: C:\TWSExecutions_$userName_$date.txt. You can change the file
destination by modifying the directory in this variable. The macro will then write
all the executions data to the file in comma delimited format.
To view this data in another worksheet, open the .txt file in Excel, and follow the
wizard to view the comma-delimited data.
90 www.interactivebrokers.com
Run the Macro
This macro is set to run when the spreadsheet is closed. This is managed in the
Workbook_BeforeClose() subroutine that is part of the ThisWorkbook object.
Code Summary
Module(s)/Subroutine(s):
Example3
exportExecutions() – The subroutine that performs
the export
ExampleUtil
Contains common functions for the examples
ThisWorkbook
Workbook_BeforeClose() – Executes the export
before close
New Worksheet(s):
None
www.interactivebrokers.com 91
Example 4 : Create DDE “OptionTrader”
The code for this macro is in the Example4 module. Use the Alt + F11 hotkey
combination to open the VBE editor, and in the Project Explorer open the
Modules directory and double click Example4.
Use the new Options Trader page, and enter the underlying symbol in the
Underlying field. Click the Get Quote button to create a ticker for the underlying
in the Quote Panel. Cool!
Now click the Load Chains button. This subroutine will take the market price
from the ticker (bid + ask) / 2 and generate a list of the five closest strike prices.
Next, the subroutine determines the next two months for expiry. The call and put
tickers are then created using the five closest strikes and the next two expiries.
Code Summary
Module(s)/Subroutine(s):
92 www.interactivebrokers.com
Example4
getQuote() – The subroutine that loads the ticker
for the underlying.
loadChains() – The subroutine that loads the
option chains for the underlying.
ExampleUtil
Contains common functions for the examples
New Worksheet(s):
The OptionTrader page contains a format similar to the TWS OptionTrader. It
provides the buttons Get Quote and Load Chains, which (surprisingly enough!)
are used to call the getQuote() and loadChains() macros! How’s that for
coincidence?
www.interactivebrokers.com 93
How Does the Sample Work?
The purpose of this sample is to convert base currency for values in the portfolio
to the currency you enter in the new Convert base to: field. The catch to this
macro is that you must have the currency already in your portfolio so that the
macro can get the conversion rate.
Go to the Portfolio page and scroll to the right to see the new conversion fields.
In the Convert base to field, enter a currency and click Go. As long as the
currency exists in your account, a conversion rate can be obtained. Otherwise, you
won’t be able to run this sample. If you’re testing this with a PaperTrader or
demo account, you can make some Forex trades to get some currencies in your
portfolio and then run this again to see how cool it is. Of course if you’re using
your regular account, you might not want to be so cavalier with your money!
Note that for each row in your Portfolio , conversions will be made as long as the
currency of the position is in the base currency. If the record is not in the base
currency, the data in the conversion section will remain blank. The conversion
rate is also displayed along with the currency code.
Code Summary
Module(s)/Subroutine(s):
Example5
convertPortfolioData() – The subroutine that
performs conversion
ExampleUtil
Contains common functions for the examples
Modified Worksheet(s):
The “Portfolio ”page was modified by extending the matrix with the following
columns: Market price, Market value, Avg cost, Unrealized value and Realized
value. An input field for currency was added along, with the Go button to perform
the conversion and the Rate field to display the current conversion rate.
94 www.interactivebrokers.com
Part V: Where to Go from Here
If you’ve come this far and actually read the book, you now have a pretty decent
grasp on what the DDE API can do, and how to make it do some of the things
you want. Now we’ll suggest some helpful outside resources you can use to help
you keep moving forward.
www.interactivebrokers.com 95
Chapter 23 – Additional Resources
There are many resources out there that will be adequate in getting you where you
need to go. If you have some books or places that you like, feel free to stick with
them. The following are the resources we find most helpful, and perhaps they’ll
be good to you, too!
For a broader view of VBA, a book might give you more. We recommend any of
the following publications, some more basic than others:
Walkenbach, John. Excel 2003 Power Programming with VBA. Indianapolis, IN:
Wiley Publishing, 2004.
Jacobson, Reed. Microsoft Excel 2002 Visual Basic for Applications Step-by-
Step. Redmond WA: Microsoft Press, 2001.
Bovey, Rob et al. Excel 2002 VBA: Programmers Reference. Indianapolis, IN:
Wiley Publishing, 2003.
96 www.interactivebrokers.com
Help with the TWS API
For help specific to the Excel TWS API, the one best place to go, really the
ONLY place to go, is the Interactive Brokers website. Once you get there, you
have lots of resources. Just type www.interactivebrokers.com in your browser’s
address line. Now that you’re there, let me tell you where you can go.
• To access the API Reference Guide, from the IB web site click Software
> Application Programming, then click the Proprietary API tab, then
click Reference Guide. Click the Online Guide button to open the online
guide, which contains a section devoted entirely to the DDE for Excel
API.
• To access these notes, from the IB web site click Software > Application
Programming, then click the Proprietary API tab, then click either API
Beta Notes or API Release Notes.
www.interactivebrokers.com 97
• To view the API Highlights, from the IB web site click Software >
Application Programming, then click the Proprietary API tab, then click
Beginner’s Guide, then select the API Highlights link in the text.
• To register for the API webinar, from IB web site click Education >
Webinars. On the Live Webinars page, click the Application Program
Interface tab, then click the TWS Application Programming Interface
(API) expandable topic. You will find a brief description of the webinar,
the date and time of the next presentation, and a registration link.
• To view the recorded version of the API webinar, from the Live Webinars
page click the Watch Previously Recorded Webinars button. Links to
recorded versions of previously recorded webinars are listed on the page.
• To view or participate in the API Traders Chat, from the IB web site
click Education > Bulletin Boards & Chats, then select the API Chat
page and click the Launch API Trader Chat button.
• To participate in the Traders’ Chat, from click the Chat button in TWS.
98 www.interactivebrokers.com
IB Customer Service
IB customers can also call or email customer service if you can’t find the answer
to your question, but IB makes it clear that the API is designed for use by
programmers and that their support in this area is limited. Still, the customer
service crew is very knowledgeable and will do their best to help resolve your
issue.
• From the IB web site, click Help & Contacts > Customer Service, where
you can send an inquiry to Customer Service or get other important
information about IB Customer Service.
IB Features Poll
The IB Features Poll lets IB customers submit suggestions for future product
features, and vote and comment on existing suggestions.
• From the IB web site, click About IB > New Features Poll. Suggestions
are listed by category; click a plus sign next to a category to view all
feature suggestions for that category. To submit a suggestion, click the
Submit Suggestion link.
www.interactivebrokers.com 99
Chapter 24 – The DDE for Excel API for
Advisors
Much of the content included is applicable to both individual traders and advisors,
but there are some specific areas of interest for those of you who handle multiple
clients. This section focuses on the features that are only available to multi-client
account advisors.
Note that at this time, although you can allocate portions of an order to multiple
accounts via the DDE API, you must first configure account groups, account
profiles, methods and percentages manually through the TWS . You can check the
TWS Users Guide on the IB website for instructions on how to do this.
• You are account number DF16045, and you manage 3 subaccounts named
DU16046, DU16047, DU16048.
• In TWS , you have created an Account Group called LowRisk, added all
the subaccounts to this group, and selected AvailableEquity as that group’s
default allocation method. This method dictates that the total number of
shares in an executed order will be split between the accounts in the group
based on the ratio of their available equity. If account DU16046 has
available equity in the amount of $25,000, DU16047 has $50,000 and
DU16048 has $100,000, the ratio is 1:2:4, and an order for 700 shares
would see DU16046 with 100 shares, DU16047 with 200 shares and
DU16048DU10705 with a whopping 400 shares of the order!
• In TWS, you have also created an Allocation Profile that you call
HighRisk, set the allocation specifics to Percentages, and allocated 65%
to DU16046 and 35% to DU16048. When you use this Allocation Profile,
the total executed order quantity will be split 65/35.
That’s all you need to know for now. Let’s put our focus back on the Excel
spreadsheet and allocate some shares!!
100 www.interactivebrokers.com
Set up an order to buy 300 shares of YHOO1 at the market price, and allocate all
the shares in the order to a single account, say DU16047. OK, it sounds simple,
but how do actually do it?
First open the Orders page, and make sure you‘re linked up to your TWS
account.
Now, you need to use the Extended Order Attributes . As we discussed earlier,
you can enter these attributes on a per order basis using the area on the order line,
or you can leave all that alone and use the Extended Order Attributes page. The
catch is, some of these need to have a value of “0” to indicate that you don’t want
to use them, and it’s easier to leave these filled out on the page than to go through
and enter them manually for every order. Start by using the Extended Order
Attributes page and end by viewing these same attributes on the order line itself.
Open the Extended Order Attributes page. In this case, where you’re giving the
entire order to one account, you only need to use one of the attributes, specifically
the Account field. It’s labeled “Institutional Only” but don’t let that scare you, it’s
for you too!
Enter the account number in the field, and while you’re in there take a look and
see the other fields that contain values. You’ll see something similar to the
following figure:
www.interactivebrokers.com 101
Remember, you only entered a value in the Account field, the other values are
there by default.
Now let’s go back to the Orders page and scroll to the right to where you can see
the Extended Order Attributes cell, which are all dark gray by default. Note that at
this point, there are no values in any of these fields.
102 www.interactivebrokers.com
Select thee YHOO ordder by highligghting the orrder line, and then click the Apply
Extended Template buutton. If youu scroll to thee right now, you’ll see thhat some of
these field
ds have valuues, includingg the Accounnt field whiich displays the account
number you
y entered. TheT template populated all of the othhers that reqquire a value,
and now you’re
y readyy to transmit the order. Itt will probabbly fill quickkly since it’s
a market order.
o
Accoun
nt Group
ps: There
e really IS
S a metho
od …
Now you’’ll use the acccount groupp we createdd, and although we originnally set thiss
up to allocate shares using
u the Avvailable Equiity method, for this ordeer we want alll
of the acccounts in thiss group to geet an equal share of the booty.
b Here’s how easy it
i
is to do th
hat!
Submit an 7 shares off YHOO1 annd see how thhey get alloccated equallyy
n order for 700
between the
t three acccounts in ourr group.
Start by opening
o the Extended
E O
Order Attribbutes page. First
F you need to delete
the Accouunt number specified
s in our last ordeer from the Account
A fieldd. Now, let’ss
find the FA
F Group annd FA Methood fields.
Remembeer that the Exxtended Ordder Attributees page holdds all valuess
until you change themm. In addition, if you donn’t manuallyy enter any
Extendedd attributes on
o your orderr line (startiing with the Time in
Force), thhe values on this page arre automaticcally appliedd to your
order EVE
VEN IF you don’t
d click thhe Apply Exteended Tempplate button!
Next, enteer the methood. Since youu want to disstribute the shares
s evenlyy, enter
EqualQuaantity as the method, agaain being preecise with yoour syntax.
www.interaactivebrokers.ccom 1003
Once it fills, go back to the Execuutions page and take a loook - you’ll see a total of
o
1
700 sharees of YHOO hypotheticaally BOT annd distributedd evenly am mongst the
three acco
ounts in yourr group! Butt you’re not done. Next, you’ll test-ddrive the finaal
allocation
n tool - the Allocation
A Prrofile.
Start by deleting
d the values
v in thee FA Group and
a FA Methhod fields onn the
Extended Order Attribbutes page.
In the FA
A Profile fieldd enter the exxact name of our profilee, HighRisk. =
Go back to
t the Orderrs page and create a marrket order foor 1000 sharees of
YHOO1.
104 www.interacttivebrokers.com
m
Advisor Fields
That’s all folks! Except for reference, we’ve put together a table that tells you a
bit about each of the advisor-oriented fields.
www.interactivebrokers.com 105
Advisor Field Description Valid Values
Request Located on the Account page, N/A
Managed used to view a list of valid account
Accounts button numbers.
FA Managed After you click the Request N/A
Accounts Managed Account button, the
received cell. account values are displayed in
this cell.
*Refer to Appendix C for more details and examples on each of the listed
allocation methods and profiles.
In Summary…
Well, you’ve done it. You’ve made your way through the book, and you’re still
alive to talk about it! And along the way you’ve created the beginnings of your
own Application Programming Interface. Hopefully you’ve also lain to rest some
of the fears you had about tackling this type of project. It’s not so intimidating
when you break it down and take the time to focus on each piece separately.
106 www.interactivebrokers.com
Appendix A – Extended Order Attributes
Attribute Valid Values
timeInForce DAY
GTC
OPG
IOC
ocaGroup String
account The account number, used for institutional and advisor accounts.
open/close O, C (for institutions)
origin 0, 1 (for institutions)
orderRef String
transmit 0 (don't transmit)
1 (transmit)
Parent order Id String (the order ID used for the parent order, use for bracket and auto
trailing stop orders)
blockOrder 0 (not a block order)
1 (this is a block order)
www.interactivebrokers.com 107
Attribute Valid Values
the bid and ask must be less than 0.1% of the midpoint.
Hidden Only valid for orders routed to Island.
0 - False
1 (order not visible when viewing market depth)
Discretionary Used in conjunction with a limit order to give the order a greater price
Amount range over which to execute.
Good After Enter the date and time after which the order will become active. Use the
Time format YYYYMMDD hh:mm:ss
Good 'Till Date The order continues working until the close of market on the date you
enter. Use the format YYYYMMDD. To specify a time of day to close the
order, enter the time using the format HH:MM:SS. Specify the time zone
using a valid three-letter acronym.
FA Group For Advisor accounts only. The name of the Account Group.
FA Method For Advisor accounts only. The share allocation method.
EqualQuantity
NetLiq
AvailableEquity
PctChange
FA Percentage For Advisor accounts only. The share allocation percentage.
FA Profile For Advisor accounts only. The name of the Share Allocation profile.
Short Sale Slot For institutional accounts only; for SSHORT actions.
1 – If you hold the shares
2 – Shares will be delivered from elsewhere.
Short Sale If shares are delivered from elsewhere, enter where in a comma-delimited
Location list with no spaces. For institutional accounts only.
OCA Type 1 = Cancel on Fill with Block
2 = Reduce on Fill with Block
3 = Reduce on Fill without Block
Rule 80A Individual = 'I'
Agency = 'A',
AgentOtherMember = 'W'
IndividualPTIA = 'J'
AgencyPTIA = 'U'
AgentOtherMemberPTIA = 'M'
IndividualPT = 'K'
AgencyPT = 'Y'
AgentOtherMemberPT = 'N'
108 www.interactivebrokers.com
Attribute Valid Values
Settling Firm Institutions only
All or None 0 = false
1 = true
Minimum Qty Identifies the order as a minimum quantity order.
Percent Offset The percent offset for relative orders.
Electronic 0 = false
Trade Only
1 = true
Firm Quote 0 = false
Only
1 = true
NBBO Price Maximum SMART order distance from the NBBO.
Cap
Auction For BOX exchange only.
Strategy
match = 1
improvement = 2
transparent = 3
Starting Price The starting price. For BOX orders only.
Stock Ref Price Used for VOL orders to compute the limit price sent to an exchange
(whether or not Continuous Update is used), and for price range
monitoring. Also used for price improvement option orders.
Delta The stock delta. For BOX orders only.
Stock Range The lower value for the acceptable underlying stock price range. For price
Lower improvement option orders on BOX and VOL orders with dynamic
management.
Stock Range The upper value for the acceptable underlying stock price range. For price
Upper improvement option orders on BOX and VOL orders with dynamic
management.
Volatility The option price in volatility, as calculated by TWS ' Option Analytics. This
value is expressed as a percent and is used to calculate the limit price
sent to the exchange.
Volatility Type 1 = daily
2 = annual
Reference Price 1 = average
Type
2 = BidOrAsk
Hedge Delta Prior to TWS Release 859, use "1" to send a market order, "0" for no
Order Type order. After TWS 859, enter an accepted order type such as: MKT, LMT,
REL.
Continuous 0 = false
Update
1 = true
Hedge Delta Enter the Aux Price for Hedge Delta order types that require one.
www.interactivebrokers.com 109
Attribute Valid Values
Aux Price
Trail Stop Price Used for Trailing Stop Limit orders only. This is the stop trigger price for
TRAILLMT orders.
Scale Num Used for Scale orders only, this value defines the number of components
Components in the order.
Scale Used for Scale orders only, this value defines the order size of the each
Component order component.
Size
Scale Price Used for Scale orders only, this value is used to calculate the per-unit
Increment price of each component in the order. This cannot be a negative number.
Outside RTH 0 = false
1 = true
110 www.interactivebrokers.com
Appendix B – Account Page Values
Values in the Account page are described in the table below. Note that your
spreadsheet might show the same field name on multiple rows, maybe with
something like this: Available Funds, Available Funds - S and AvailableFunds -
C. The above example would be showing the total Available Funds, the Available
Funds for securities, and the Available Funds for commodities.
Day Trades The number of day trades you have left for
Remaining T+1, a 4-day pattern day-trader.
T+2, T+3, T+4
Equity With For Securities:
Loan Value
Cash Account : Settled Cash
Margin Account :
www.interactivebrokers.com 111
Field Description Notes
Total cash value + stock value + bond
value + (non-U.S. & Canada securities
options value)
For Commodities:
Cash Account : Total cash value +
commodities option value - futures
maintenance margin requirement +
minimum (0, futures PNL)
Margin Account : Total cash value +
commodities option value - futures
maintenance margin requirement
Excess Liquidity Equity with Loan Value - Maintenance
margin
Exchange Rate The exchange rate of the currency to your
base currency.
Full Available For securities:
Funds Equity with Loan Value - Initial margin
For commodities:
Net Liquidation Value - Initial margin
Full Excess Equity with Loan Value - Maintenance
Liquidity margin
Full Init Margin Overnight initial margin requirement in the
Req base currency of the account.
Full Maint Maintenance margin requirement as of
Margin Req next period's margin change in the base
currency of the account.
Future Option Real-time mark-to-market value of futures
Value options.
Futures PNL Real-time change in futures value since
last settlement.
Gross Position Long Stock Value + Short Stock Value +
Value Long Option Value + Short Option Value.
Init Margin Req Initial margin requirement in the base
currency of the account.
Leverage For Securities:
Gross Position value / Net Liquidation
value
For Commodities:
Net Liquidation value - Initial margin
Look Ahead For Securities:
Available Funds
Equity with loan value - look ahead initial
margin.
For Commodities:
112 www.interactivebrokers.com
Field Description Notes
Net Liquidation value - look ahead initial
margin.
Look Ahead Equity with loan value - look ahead
Excess Liquidity maintenance margin.
Look Ahead Init Initial margin requirement as of next
Margin Req period's margin change in the base
currency of the account.
Look Ahead Maintenance margin requirement as of
Maint Margin next period's margin change in the base
Req currency of the account.
Maint Margin Maintenance margin requirement in the
Req base currency of the account.
www.interactivebrokers.com 113
Field Description Notes
commodities option value - futures
maintenance margin requirement +
minimum (0, futures PNL)
Margin Account : Total cash value - futures
maintenance margin requirement
SMA Max ((EWL - US initial margin Only applicable for
requirements)*, (Prior Day SMA +/- securities.
change in day's cash +/- US initial margin
requirements** for trades made during
the day.))
*calculated end of day under US Stock
rules, regardless of country of trading.
**at the time of the trade
Stock Market Real-time mark-to-market value of stock
Value
Total Cash Cash recognized at the time of trade +
Balance futures PNL
Total Cash Total cash value of stock, commodities and
Value securities
114 www.interactivebrokers.com
Appendix C – Allocation Methods and Profiles
Allocation Methods for Account Groups
Note that you must type the method name in exactly as appears here, or your
order won’t work.
EqualQuantity Method
Requires you to specify an order size. This method distributes shares equally
between all accounts in the group.
Example: You transmit an order for 400 shares of stock ABC. If your Account
Group includes four accounts, each account receives 100 shares. If your Account
Group includes six accounts, each account receives 66 shares, and then 1 share is
allocated to each account until all are distributed.
NetLiq Method
Requires you to specify an order size. This method distributes shares based on the
net liquidation value of each account. The system calculates ratios based on the
Net Liquidation value in each account and allocates shares based on these ratios.
Example: You transmit an order for 700 shares of stock XYZ. The account group
includes three accounts, A, B and C with Net Liquidation values of $25,000,
$50,000 and $100,000 respectively. The system calculates a ratio of 1:2:4 and
allocates 100 shares to Client A, 200 shares to Client B, and 400 shares to Client
C.
AvailableEquity Method
Requires you to specify an order size. This method distributes shares based on the
amount of equity with loan value currently available in each account. The system
calculates ratios based on the Equity with Loan value in each account and
allocates shares based on these ratios.
Example: You transmit an order for 700 shares of stock XYZ. The account group
includes three accounts, A, B and C with available equity in the amounts of
$25,000, $50,000 and $100,000 respectively. The system calculates a ratio of
1:2:4 and allocates 100 shares to Client A, 200 shares to Client B, and 400 shares
to Client C.
PctChange Method
This method only works when you already hold a position in the selected
instrument. Do not specify an order size. Since the quantity is calculated by the
www.interactivebrokers.com 115
system, the order size is displayed in the Quantity field after the order is
acknowledged. This method increases or decreases an already existing position.
Positive percents will increase a position, negative percents will decrease a
position.
Example 1: Assume that three of the six accounts in this group hold long positions
in stock XYZ. Client A has 100 shares, Client B has 400 shares, and Client C has
200 shares. You want to increase their holdings by 50%, so you enter "50" in the
percentage field. The system calculates that your order size needs to be equal to
350 shares. It then allocates 50 shares to Client A, 200 shares to Client B, and 100
shares to Client C.
Example 2: You want to close out all long positions for three of the five accounts
in a group. You create a sell order and enter "-100" in the Percentage field. The
system calculates 100% of each position for every account in the group that holds
a position, and sells all shares to close the positions.
These handy charts make it easy to see how negative and positive percent values
will affect long and short positions for both buy and sell orders. Phew, that was a
mouthful!
116 www.interactivebrokers.com
Allocation Profiles
Percentages
This method will split the total number of shares in the order between listed
accounts based on the percentages you indicate.
Example: An order for 1000 shares using a profile with four accounts at 25% each
would allocate 250 shares to each listed account in the profile.
Ratios
This method calculates the allocation of shares to the listed accounts based on the
ratios you indicate.
Example: An order for 1000 shares using a profile with four accounts set to a ratio
of 4, 2, 1, 1 would allocate 500, 250, 125 and 125 shares to the listed accounts,
respectively.
Shares
This method allocates an absolute number of shares to each account listed. If you
use this method, you don’t need to enter an order quantity. The order size is
determined by adding together the number of shares allocated to each account in
the profile.
www.interactivebrokers.com 117
Index
A VBA code sample ....................................... 84
API E
download the sample Excel application .......24 VBA code sample ....................................... 84
Buy/Sell based on Top Implied Volatility Gainer VBA code samples ...................................... 84
Market Scan results
118 www.interactivebrokers.com
Extended Order Attributes Market Scanner ................................................ 66
F Named Ranges
Historical Data O
J Organization ..................................................... 11
L P
M Query Specification
www.interactivebrokers.com 119
Subscribe to a Market Scanner ......................... 64
R
Summary Description
Request Market Data ........................................35
on contract details page ......................... 69, 70
run.bat ...............................................................64
T
S
Tickers ....................................................... 30, 34
sample ................................. 28, 30, 34, 64, 79, 86
TWS .................................... 33, 34, 35, 59, 65, 74
sample application
adding market data ...................................... 16
description of ...............................................21
configure to support the API ....................... 23
enable macros ..............................................27
connect via Excel API ............................... 27
Sample Applications
what is it? .................................................... 15
API code samples ........................................84
sample scenarios
V
120 www.interactivebrokers.com