IB API HOWTOs and Guidelines - For Beginners

Discussion in 'App Development' started by Butterfly, Nov 8, 2013.

  1. crmorris

    crmorris


    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.
     
    #51     Nov 15, 2013
  2. Butterfly

    Butterfly

    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
     
    #52     Nov 18, 2013
  3. Butterfly

    Butterfly

    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:

     
    #53     Nov 18, 2013
  4. Butterfly

    Butterfly

    for those who are interested, I will put a tutorial to run batch orders as Python scripts on a hosted headless Linux server

    quite nice,
     
    #54     Jan 12, 2014
    InterceptK likes this.


  5. 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.
     
    #55     Jan 12, 2014
  6. 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.
     
    #56     Jan 18, 2014
  7. 2rosy

    2rosy

    #57     Jan 24, 2014
  8. idontknow

    idontknow

    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?
     
    #58     Mar 13, 2014
  9. 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.
     
    #59     Apr 4, 2014
    pstrusi likes this.
  10. 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".
     
    #60     Apr 4, 2014
    tradingcomputer likes this.