ib_insync Guide – Interactive Brokers API

    Date:

    The post “ib_insync Guide – Interactive Brokers API” first appeared on AlgoTrading101 blog.

    Excerpt

    What is ib_insync?

    ib_insync is a framework that simplifies the Interactive Brokers (IB) Native Python API that was developed by the IB team.

    Why should I use ib_insync?

    The following snippet, from the ib_insync documentation, sums it up nicely-

    “The goal of the IB-insync library is to make working with the Trader Workstation API from Interactive Brokers as easy as possible.”

    The Native Python API has a bit of a reputation for being complicated. It doesn’t follow the same style that most Python programmers have become accustomed to and the learning curve is steep.

    ib-insync offers a more familiar environment for Python programmers. It also simplifies other aspects like installation and has an active support group. Further, it has extensive documentation and is well-maintained.

    ib_insync simplifies the methods and syntax used in the Interactive Brokers Native Python API. Also, and this is an important one, ib_insync uses asynchronous execution.

    We will discuss asynchronous programming in a bit more detail later on in this guide. But in short, this manages the communication received from the API, ensuring that we wait for data when it’s urgent and don’t sit idle when it’s not.

    Why shouldn’t I use ib_insync?

    The asynchronous methods in ib_insync in some cases can make it difficult to implement further speed optimization.

    Since ib_insync already uses an event loop, adding additional multiprocessing or other external asynchronous methods can be a challenge.

    For example, let’s say you want to use alternative data in your strategy, obtained from an external source. With the native IB API, you can simply launch a new thread and quickly make asynchronous calls to the external alternative data API.

    With ib_insync, you’ll have to ensure that your additional custom functions don’t interfere with ib_insync’s event loop.

    In other words, if your strategy is extremely time sensitive (we are talking milliseconds), then it might be easier to implement speed improvements using the native API compared to ib_insync. Unless you are an advanced user with an in-depth understanding of asynchronous frameworks.

    Note that ib_insync was not created by the IB team.

    What is the Interactive Brokers API?

    ib_insync is built on top of the IB Native API.

    The IB API is an interface that allows traders to trade algorithmically with Interactive Brokers. Almost all of the things that can be done in the client can be done through the API.

    This means you can execute trades, get both live and historical data, and check on your account details, all programmatically.

    One thing to note about the Interactive Brokers API is that it is not a REST API. That means you’re not directly connecting to IB’s server via your code. Rather, all of the interaction takes place via one of their client apps. 

    How to sign up for a demo account for Interactive Brokers and set up the trading platform?

    There are two ways to get a demo account with Interactive Brokers. If you already have a live account, a demo will have automatically been created for you. Simply use the same user name and password that was created for your live account.

    The benefit of being an existing client is that you’ll have access to live data and any data packages that you’ve subscribed to.

    If you’re not already a client, here is a demo account creation guide. The process is quick, you just need to download the software and use your email to sign in.

    The experience of a demo account will be similar to that of a live environment. The difference is that data is delayed by 10 to 15 minutes.

    That means you’ll have access to data that you would otherwise need to pay for on a live account, albeit delayed.

    How do I get started with ib_insync?

    The easiest way to install ib_insync is by using pip.

    pip install ib_insync

    You should also have a client installed. You can use either TWS or IB Gateway. Make sure that the API is enabled within the client before attempting to make a connection.

    IB-insync works in both interactive environments and script mode. We will use Jupyter notebooks for the examples in this guide.

    from ib_insync import *
    
    util.startLoop()  # only use in interactive environments (i.e. Jupyter Notebooks)

    We start by importing the library. The second line in the code snippet above is specific for interactive environments like Jupyter environments. It’s not needed otherwise and will throw an error if you try to use it in script mode.

    ib = IB()
    ib.connect()

    Next, we will instantiate the IB class and establish a connection. When running the cell, we get a message showing we are connected.

    In this case, we just use the connect() function without passing through any parameters as we are configured to use the defaults.

    But if you need to change the port number or client id, you can do so by passing in the appropriate parameters in the connect function as follows:

    ib = IB()
    ib.connect(host='127.0.0.1', port=7497, clientId=1)

    How to retrieve the current price of a stock using ib_insync?

    Whenever data is required for any asset, we start by creating a “contract”. This is to specify some details about the asset we want data for.

    The ib_insync has helper functions and classes to simplify contract creation for most of the common asset types.

    nflx_contract = Stock('NFLX', 'SMART', 'USD')

    In the above code example, we use the Stock() helper Class to create a contract. We’ve passed through three values here:

    1. The ticker – NFLX in this case
    2. The exchange it trades on. By specifying “SMART” here, IB will automatically route this to the appropriate exchange.
    3. The currency the stock trades in which is US dollars.

    There is still some further information IB will need. We can use the qualify contracts function to automatically fill in this additional information.

    ib.qualifyContracts(nflx_contract)

    You should get an output that looks like this.

    As per the image, it has determined the conIdprimaryExchange, and tradingClass automatically.

    Next, we can request a tick data stream as follows.

    data = ib.reqMktData(nflx_contract)

    Now that a tick stream has been created, we can view the current price by calling the marketPrice function which show the latest price in our Jupyter Notebook.

    data.marketPrice()

    Visit the AlgoTrading101 blog for instructions retrieve market data for currencies.

    Disclosure: Interactive Brokers

    Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

    This material is from AlgoTrading101 and is being posted with its permission. The views expressed in this material are solely those of the author and/or AlgoTrading101 and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

    Disclosure: Order Types / TWS

    The order types available through Interactive Brokers LLC’s Trader Workstation are designed to help you limit your loss and/or lock in a profit. Market conditions and other factors may affect execution. In general, orders guarantee a fill or guarantee a price, but not both. In extreme market conditions, an order may either be executed at a different price than anticipated or may not be filled in the marketplace.

    Go Source

    Chart

    SignUp For Breaking Alerts

    New Graphic

    We respect your email privacy

    Share post:

    Popular

    More like this
    Related

    Mr. Market ❤️ Jerome Powell

    By mid-morning I’d already been asked multiple times about...

    Bulls Chant “Don’t Fight the Fed”: Sep. 19, 2024

    Stocks are soaring following yesterday afternoon’s Fed pivot in...

    Proprietary Trading Desk Setup: A Step by Step Guide – Part I

    Establishing a proprietary trading desk is a complex yet...

    Wall Street Wants You to Be Manic. Be Focused Instead.

    Wall Street wants you to be a short-term event...