IBPy Tutorial to implement Python in Interactive Brokers API

How to implement Python in Interactive Brokers API using IBPy

I hope you had a great time attending our webinar on Trading with Interactive Brokers using Python, I thought it would be a very good idea to give you a brief insight on Interactive Brokers API and using IBPy to implement Python in IB’s TWS. As we proceed, you will need an Interactive Brokers demo account and IBPy. Towards the end of this article, you will be running a simple order routing program using Interactive Brokers API.

For those of you who are already aware of Interactive Brokers (IB) and its interface, you can very well understand why I prefer IB over other available online brokerages. However, for those who have not used IB, this would be the first question that comes to mind:

Why Interactive Brokers?

When I have online brokerages like Fidelity, Capital One Investing, & Firstrade, then why should one use Interactive Brokers?


Become an algotrader. learn EPAT for algorithmic trading

Interactive Brokers is my first choice because of 5 simple reasons:

  1. International Investing in more than 100 markets
  2. Commission rates that are highly competitive
  3. Low margin rates
  4. Very friendly user interface
  5. Vast selection of order types

Among the five points mentioned above, the most important and impressive one for any beginner is point no. 2 and point no. 4, isn’t it?. The Interactive Brokers API can be used in a professional context even for those who are completely alien to it. Interactive Broker API’s connectivity with Java, C++ and Python is very impressive as well.

Enough said it is time to move to the next step. I can understand that most of you must already be eager to test their hand at the Interactive Brokers API panel. After all, nobody could say no to something very friendly that is lucrative as well. You can easily set up your account on Interactive Brokers by going to their website. There is an option wherein you can opt for a free trial package.

Algorithmic traders prefer Interactive Brokers due to its relatively straightforward API. In this article, I will be telling you how to automate trades by implementing Python in the Interactive Brokers API using a bridge called IBPy.

Interactive Brokers IBPy

As Interactive Brokers offers a platform to an incredibly wide spectrum of traders, therefore, its GUI consists of a myriad of features. This standalone application is called Trader Workstation or TWS on Interactive Brokers. Apart from the Trader Workstation, Interactive Brokers also has an IB Gateway. This particular application allows IB servers to access it using a Command Line Interface. Algo traders usually prefer using this over GUI.

What is IbPy?

IbPy is a third-party implementation of the API used for accessing the Interactive Brokers on-line trading system. IbPy implements functionality that the Python programmer can use to connect to IB, request stock ticker data, submit orders for stocks and futures, and more.

The purpose of IbPy is to conceive the native API, that is written in Java, in such a way that it can be called from Python. Two of the most significant libraries in IBPy are ib.ext and ib.opt. ib.opt derives from the functionality of ib.ext. Through IBPy, the API executes orders and fetches real-time market data feeds. The architecture essentially utilizes a client-server model.

Implementation of IB in Python

First of all, you must have an Interactive Brokers account and a Python workspace to install IBPy, and thereafter, you can use it for your coding purposes.

Installing IBPy

As I had mentioned earlier, IBPy is a Python emulator written for the Java-based Interactive Brokers API. IBPy helps in turning the development of algo trading systems in Python into a less cumbersome process. For this reason, I will be using it as a base for all kinds of interaction with the Interactive Brokers TWS. Here I am presuming that you have Python 2.7 installed on your system, else you may download it from here:


Installing On Ubuntu


IBPy can be acquired from GitHub repository.

The following code will be needed on an Ubuntu system:

Creation of subdirectory

Download IBPy

Great! You have installed Python on your Ubuntu system.

Installing IBPy on Windows

Go to the github repository and download the file from:


Unzip the downloaded file. Move this folder to the directory where you have installed Python so that it can recognize this package:


Now, open the setup with windows command prompt and type the following command: 

After this, you will have to get your Trader Workstation (TWS) in operation.

Installing Trader Workstation

Interactive Brokers Trader Workstation or TWS is the GUI that lets all registered users of Interactive Brokers to trade on their systems. Don’t worry, even if you do not have prior knowledge of programming or coding, TWS will let you do the trading work.You can download the TWS installer from interactive Brokers’ website and run it on your system.

You can download the TWS Demo from here:


Important Note

In the older versions of TWS, the user would get to choose two different programs. The first one was the TWS of Interactive Brokers and the second was the IB Gateway, about which I have already talked earlier. Although they are different applications, however, they can only be installed together. 

The IB Gateway runs on lower processing power since it does not have an evolved graphical user interface as the Trade Workstation. However, the results and other data are displayed in the form of primitive codes on the IB Gateway, making it less friendly for certain set of users who do not possess enough knowledge in coding.

You may use either of the two interfaces for your work on interactive Brokers. The functionalities of both remain the same, i.e. to relay info between your system and the Interactive Brokers server. Needless to say, the Python app will get the exact same messages from the server end of Interactive brokers.

Installation Walk-through

Once you download the application, you will find the executable file at the bottom of your browser. Click on Run when prompted with a security warning.

  • Now, click on Next.
  • Click on finish to complete your installation.
  • Click on the desktop icon and start the TWS application.

IBPy implementation in TWS

Since I am going to use a demo account, therefore, click on No User name?

  • Enter your email address and click on Login:

IBPy implementation in TWS

Configuration of Interactive Brokers Panel

The journey so far has been pretty easy, hasn’t it? It is great if you agreed with me on that one. After installing the TWS and/or IB Gateway, we have to make some changes in the configurations before implementing our strategies on Interactive Brokers’ servers. The software will connect to the server properly only once these settings are changed.


  • Go to API settings in TWS

Setting preferences for IBPY on Interactive Brokers TWS

Setting preferences for IBPY on Interactive Brokers TWS

  • Check the Enable ActiveX and Socket Clients
  • Set Socket port to unused port.
  • Set the Master API client ID to 100
  • Create a Trusted IP Address and set to

Global preferences for Interactive Brokers API using IBPy

Running the first program

So, all done with the configuration?

Great! We are now ready to run our first program.

Before you start typing in those codes, make sure that you have started TWS (or IB Gateway). Many times, I get questions as to why we get an error message when the code is run. Like I had mentioned in the previous section, your system is connected to the Interactive Brokers’ server through the TWS or IB Gateway. So, if you haven’t turned it on, then you are bound to get an exception message, no matter how smartly you have developed your code.

Let’s start working on the coding step-by-step.

Open Spyder (Start – All Programs – Anaconda2 – Spyder)

On the Spyder console, I will be entering my codes.

Spyder interface for IBPy

1) We start by importing necessary modules for our code:
Connection is a module that connects the API with IB while message performs the task of a courier between the server and the system, it basically retrieves messages from the Interactive Brokers server.
Just like every transaction in the real-world involves some kind of a contract or agreement, we have Contract here as well. All orders on Interactive Brokers are made using contract.
2) Making the contract function
The contract function has the following parameters:

  • Symbol
  • Security Type
  • Exchange
  • Primary Exchange
  • Currency

The values of these parameters must be set accordingly.

3) Setting the Order Function

Order function allows us to make orders of different types. The order function has the following parameters:

  • Order Type
  • Total Quantity
  • Market Action (Buy or sell)

Considering that our order does have a set price, we code it in the following way:

The conditional statement will now set up the order as a simple market order without any set price. 

The client id & port should be the same as you had set in the Global preferences

4) Initiating Connection to API

Establish the connection to TWS.


Assign error handling function.


Assign server messages handling function.


Create AAPL contract and send order

In the above line, AAPL is Apple Inc. and STK is the name of the security type. The exchange and primary exchange has been set to SMART. When we set these two parameters to SMART, then we are actually using Interactive Brokers smart routing system which enables the algo to find the best route to carry out the trade. And of course, the currency has been set to USD.

We wish to sell 100 shares of AAPL

Our order is to sell 1 stocks and our price is $100.

We have placed an order on IB TWS with the following parameters:

  • Order id
  • Contract
  • offer

“Always remember that the order id should be unique.”

5) Disconnecting

And finally you need to disconnect:      

Yes, you are done with your first order on Interactive brokers’ API using basic Python coding. Keep in mind that the demo account that you are using might not give you all the privileges of a paid account.

Running the Code

Click on the Green colored ‘Play’ button or simply press F5 in Spyder. On your TWS Demo system, you will get a popup regarding your order. Click on OK.

IBPy confirmation


You can see the final output on the bottom right side of Interactive Brokers TWS panel.

Output of algo using IBPy

Just in case you want to have a look at the complete code at one go, here it is:

Next Step

I am sure that you have all run your code and made your first transaction using Interactive Brokers API and IBPy. We can see the output on the TWS where you will be selling 100 shares of APPLE. This is a very generic and simple type automated execution using Interactive Brokers API.

You can watch QuantInsti’s webinar on Trading with Interactive Brokers using Python, where Dr. Hui Liu has explained how to use another wrapper called IBridgePy. Dr Hui Liu is one of the pioneers in the field. So, if you wish to know how you can implement Algo strategies in the live market using Python on Interactive Broker’s API, then you should definitely check out the videos from our recently concluded webinar. To know more about algorithmic trading, enrol for EPAT.


Become an algotrader. learn EPAT for algorithmic trading

Sources & References: quantstart.com, pythonprogramming.net, interactivebrokers.com

One thought on “IBPy Tutorial to implement Python in Interactive Brokers API

  1. February 2, 2017

    Bas Reply


    First of all, thank you for sharing the provided sample code and the further explanation. As a Python newbie this article is helping me a lot to understand the syntax.

    After configuring TWS I’ve tried to run your sample code with Spyder 2.3.8 (Python 2.7) on Linux Ubuntu, and this gave me some error messages. Here’s the full console output:


    Python 2.7.12 (default, Nov 19 2016, 06:48:10)
    [GCC 5.4.0 20160609] on linux2
    Type “help”, “copyright”, “credits” or “license” for more information.
    >>> runfile(‘/home/administrator/Documents/IBPySampleCode.py’, wdir=’/home/administrator/Documents’)
    Traceback (most recent call last):
    File “”, line 1, in
    File “/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py”, line 699, in runfile
    execfile(filename, namespace)
    File “/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py”, line 81, in execfile
    builtins.execfile(filename, *where)
    File “/home/administrator/Documents/IBPySampleCode.py”, line 14
    print “Server Error:”, msg
    IndentationError: expected an indented block


    Is there a way to resolve these issues?
    Thank you in advance!


Leave a Reply

Your email address will not be published. Required fields are marked *