IB API HOWTOs and Guidelines - For Beginners

Quote from 2rosy:

my tutorial issimple. Your postings are scattered and unusable which is why I wrote mine. I cant understand what you are doing

As for managing OrderIDs, just make it easy and tell people to add 1.


not sure why anybody would protest your contribution, rosy. the framework is helpful.

can people please post what version of tws / gateway they're using, their version of ibpy, and the repositories they used to get them. i can't seem to get an older version of ibpy to work.
 
So far, we had examples for trading stocks, but one of the difficulty of IB API is to articulate certain derivatives strategies in programming code. Some options strategies are already built-in in IB, but others will need to coded properly.

In the following example we create a new connection to list an option with different strikes and maturity dates. This was an issue in another thread so I will post a more detailed solution for it here.


The workflow will be as follow:

- Create a new connection with a new Channel dedicated to requesting contract and instrument details
- Make the request for all the instruments details
- Capture and process that request with all the instruments details
 
ok, here is the tutorial to list all Option contracts for a given company.

In this example, we will use MSFT for simplicity. We will do a special request to the IB Server and parse the replies and print the attributes for each contract. For MSFT, there are about 2,430 options contracts with different maturities and strikes. The output will print the OSI symbol for those contracts with their strike and maturity.

It's important to understand that IB Server replies for certain instruments like Options is a bit "tricky". The objects created by the API will have objects made of a mix of values (numeric, text) and other objects. Therefore the objects will themselves have other objects in their attributes, which technically can also encapsulate other objects. This cascade of embedded objects can make your debugging extremely difficult, but it seems to be only limited to the instruments and contracts.

Here is the code:

Code:
from time import sleep
from pprint import pprint
# LOAD the ib.ext and ib.opt Libraries
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import ibConnection, Connection, message

# DEFINE a basic function to capture error messages
def error_handler(msg):
    print "IB: Server Error = ", msg

# DEFINE a catch-all function to print ALL the server replies
def IB_replies_handler(msg):
    # DEBUG - Print Raw Server Output
    # print "IB: Server Response = ", msg.typeName, msg

    # DEFINE Global Counter Output
    global c
    c=c+1;

    # HANDLE Message Type for Contract Details
    if msg.typeName.strip() == "contractDetails":
        print "Reply #" + str(msg.reqId) + ":"+ str(c)

        # DEBUG
        #dump(msg)
        #dump(a)
        #pprint (vars(a))

        # DEFINE Contract objects that will be assigned the values of the IB Server replies
        Ticker_DESC=None
        Option_DESC=None

        # ASSIGN the Underlying Security Details which encapsulate details on the Option Contracts
        Ticker_DESC=msg.contractDetails

        # EXTRACT and ASSIGN the Option Contracts details from the Ticker_DESC objects
        Option_DESC=Ticker_DESC.m_summary

        # PRINT Options Contract Details
        print "=> [{0} ({1})] Call/Put: {2} Strike: {3} Expiration: {4}".format(
Option_DESC.m_localSymbol,Option_DESC.m_conId, Option_DESC.m_right, Option_DESC.m_strike,Option_DESC.m_expiry)

# DEBUG - Dump object
def dump(obj):
  for attr in dir(obj):
    print "obj.%s = %s" % (attr, getattr(obj, attr))

# Main code
c=0

# Create the connection to IBGW with client socket id=1234
# ibConnection = Connection.create
# ibgw_conTickerChannel = ibConnection(port=7496,clientId=1234)
ibgw_conTickerChannel = Connection.create(port=4001,clientId=1234)
ibgw_conTickerChannel.connect()

# Map server replies for "Error" messages to the "error_handler" function
ibgw_conTickerChannel.register(error_handler, 'Error')

# Map all server replies to "IB_replies_handler"
ibgw_conTickerChannel.registerAll(IB_replies_handler)

# Create a contract object and update the parameters that will be sent to the ContractDetails request
order_ticker = Contract()
order_ticker.m_symbol = 'MSFT'
order_ticker.m_secType = 'OPT'
order_ticker.m_currency = 'USD'
#order_ticker.m_localSymbol = 'MSFT'

# Make the request for ContractDetails with reqID = 1
ibgw_conTickerChannel.reqContractDetails(1,order_ticker)

# Leave connection open for long replies
sleep (240)
print 'disconnected', ibgw_conTickerChannel.disconnect()

output will be something like this:

Server Version: 59
TWS Time at connection:20131118 21:00:22 ICT
Reply #1:3
=> [MSFT 140118C00030000 (94207576)] Call/Put: C Strike: 30.0 Expiration: 20140117
Reply #1:4
=> [MSFT 150117C00025000 (113711355)] Call/Put: C Strike: 25.0 Expiration: 20150116
Reply #1:5
=> [MSFT 150117C00028000 (113711358)] Call/Put: C Strike: 28.0 Expiration: 20150116
Reply #1:6
=> [MSFT 150117C00015000 (119687106)] Call/Put: C Strike: 15.0 Expiration: 20150116
Reply #1:7
=> [MSFT 140419C00030000 (129896961)] Call/Put: C Strike: 30.0 Expiration: 20140417
Reply #1:8
=> [MSFT 140419P00028000 (129896986)] Call/Put: P Strike: 28.0 Expiration: 20140417
Reply #1:9
=> [MSFT 140419P00040000 (129897004)] Call/Put: P Strike: 40.0 Expiration: 20140417
Reply #1:10
=> [MSFT 140419C00025000 (130376282)] Call/Put: C Strike: 25.0 Expiration: 20140417
Reply #1:11
=> [MSFT 140419C00045000 (130376287)] Call/Put: C Strike: 45.0 Expiration: 20140417
Reply #1:12
=> [MSFT 140419P00018000 (130376291)] Call/Put: P Strike: 18.0 Expiration: 20140417
Reply #1:13
=> [MSFT 140419P00023000 (130376297)] Call/Put: P Strike: 23.0 Expiration: 20140417
Reply #1:14
=> [MSFT 140419C00019000 (131672170)] Call/Put: C Strike: 19.0 Expiration: 20140417
Reply #1:15
=> [MSFT 140419C00021000 (131672175)] Call/Put: C Strike: 21.0 Expiration: 20140417
Reply #1:16
=> [MSFT 140419C00026000 (131672180)] Call/Put: C Strike: 26.0 Expiration: 20140417
Reply #1:17
...
Reply #1:2416
=> [MSFT 131122C00030000 (136426311)] Call/Put: C Strike: 30.0 Expiration: 20131122
...
Reply #1:2430
=> [MSFT 131122C00031500 (136426312)] Call/Put: C Strike: 31.5 Expiration: 20131122
...
 
Quote from rwk:

I trade via TWSAPI, and I'm thinking about switching to Python for my primary language. It's my understanding that IbPy is Python 2, and I prefer to use Python 3. Can IbPy be upgraded?

Has anybody considered using Python with the ActiveX? I am also thinking of switching from Win7 to Linux. Does anybody run the ActiveX on Linux via Wine?



I believe Kiwi is running his setup on Linux, don't know if he still uses IB or not. You can contact him on Sierra Charts support board.
 
Quote from stevegee58:

There's already a Yahoo group for the IB API that's very active and has plenty of source code available.

I use the C++ class wrapper from there for all my apps.

There is also a pretty large specialized group about IB API on Linkedin called "Interactive Brokers Traders and Fund Managers" (just drop me a PM if you want the direct URL).

I used to read the SMF too, but very few post there lately.
 
I got a question about the Market Depth feature in the IB API.

When I try to request Deep Market data from the Java or C++ demo-client, or generally via the reqMktDepth method, I get the error:
"10000001 10092 Deep market data is not supported for this combination of security type/exchange"

The TWS Market Depth tool, and other API-functions work fine, though.

I tried stable and beta releases of both the API and Trader Workstation and standard parameters.

Does it work for you?
 
Hi
I am *very* late to this discussion but recently I have posted some tutorials getting started with either C++ or C# and the ActiveX and Socket/EWrapper C# API. I am adding new tutorials all of the time so feel free to drop me a line if you would like to see something specific. http://holowczak.com/category/ib/

Cheers,

Rich H.
 
I got a question about the Market Depth feature in the IB API.

When I try to request Deep Market data from the Java or C++ demo-client, or generally via the reqMktDepth method, I get the error:
"10000001 10092 Deep market data is not supported for this combination of security type/exchange"

The TWS Market Depth tool, and other API-functions work fine, though.

I tried stable and beta releases of both the API and Trader Workstation and standard parameters.

Does it work for you?

First you'll need to make sure your account is permissioned for Market Depth. Likely by default it will not be. Then you can try combinations like IBM on ARCA or MSFT on ISLAND. That taps in to the actual limit order books on those exchanges.

It looks to me like the "Market Depth" tool available in TWS is really just a presentation of the top of the order book from each exchange. e.g., if you take the consolidated Level 1 quote feed you would see the best bid and off price/size from each of the equity markets. The tool in TWS assembles these and sorts them by price and time. So it is a kind of "pseudo order book".
 
Back
Top