Interactive Brokers (IB) API Example Using IBAPI

June 18, 2018

Introduction

The dream of many software developers is to build software which generates a steady income without doing much work; much like Canadian permanent disability cheques that roll in reliably every month for life. Unfortunately, the former requires risking cold, hard, cash. If you have a lot of money, you can invest in a high dividend paying stock. The other method is to perform stock trades based how markets will perform.

I will go through the basics of trading using a programmatic connection to the Interactive Brokers gateway which exposes the Interactive Brokers Application Programming Interface (IBAPI) on Windows. I think the software is best run on Windows.

I used the following links to assist with setting up the Interactive Brokers API.

Install Interactive Brokers API

interactivebrokers.github.io Installing the Interactive Brokers API will create a directory “C:\TWS API" for the API source code in addition to automatically copying two files into the Windows directory for the ActiveX/DDE and C++ APIs. It is important that the API installs to the C: drive, as otherwise API applications may not be able to find the associated files. The Windows installer also copies compiled dynamic linked libraries (DLL) of the 32 versions of the ActiveX control TWSLib.dll, C# API CSharpAPI.dll, and C++ API TwsSocketClient.dll. Starting in version 973.03, the Windows installer also installs a 32 bit version of the RTDServer control. To use a 64 bit application which loads the API as a dynamic library, it is necessary to compile and install a 64 bit version of the desired control.

Install the IB Gateway for Windows

[IB Gateway for Windows] (https://www.interactivebrokers.ca/en/index.php?f=16457 “IB Gateway for Windows”) Install the IB Gateway for Windows.

Before we run the IB Gateway, we should create a paper trading account.

  • Go to your Interactive Brokers account management and create a paper trading account. I use the paper trading account to prevent executing live trades. account management

  • On the account management page go to Account Settings > Paper Trading Account. Create a username and password and ensure “Share real-time market data subscriptions with paper trading account?” is set to YES. This is important otherwise you will not be able to get stock prices.

  • Run IB Gateway for Windows with the paper trading account. Ensure the following settings by selecting Configure > Settings. The most important setting is the Socket port. This is the port used for connecting your Python code to the gateway. IB Gateway for Windows

  • Install [Python3] (https://www.python.org/downloads/windows/ “Python3”) for Windows.

  • Go to the “C:\TWS API\samples\Python” samples directory and just browse some of the files to get a feel for the python code. Find the Python API which interacts with the IB Gateway. It is named “ibapi” and I put it here: “C:\TWS API\source\pythonclient\ibapi”.

Install Visual Studio Code IDE

The Visual Studio Code IDE is free and has a good visual debugger for python. Once installed, make sure you set the Python interpreter to Python 3.6. To use a specific interpreter, select the Python: Select Interpreter command from the Command Palette (Ctrl+Shift+P). C:\Program Files\Python36\python.exe Ctrl+Shift+P

Code

Include the ibapi folder in your project by copying the ibapi folder and importing in Python

from ibapi.wrapper import EWrapper
import ibapi.decoder
import ibapi.wrapper
from ibapi.common import *
from ibapi.ticktype import TickType, TickTypeEnum
from ibapi.comm import *
from ibapi.message import IN, OUT
from ibapi.client import EClient
from ibapi.connection import Connection
from ibapi.reader import EReader
from ibapi.utils import *
from ibapi.execution import ExecutionFilter
from ibapi.scanner import ScannerSubscription
from ibapi.order_condition import *
from ibapi.contract import *
from ibapi.order import *
from ibapi.order_state import *
from Testbed.ContractSamples import ContractSamples
from Testbed.OrderSamples import OrderSamples

Your imports/includes could end up looking very long. I have the following as my imports for my entire trading algorithm.

import sys
import socket
import struct
import array
import inspect
import time
import argparse
import os.path
import json
import csv
from pprint import pprint
import twitter
from fred import Fred
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr

import urllib
#import urllib2
import requests
from bs4 import BeautifulSoup as bs
import shutil

from ibapi.wrapper import EWrapper
import ibapi.decoder
import ibapi.wrapper
from ibapi.common import *
from ibapi.ticktype import TickType, TickTypeEnum
from ibapi.comm import *
from ibapi.message import IN, OUT
from ibapi.client import EClient
from ibapi.connection import Connection
from ibapi.reader import EReader
from ibapi.utils import *
from ibapi.execution import ExecutionFilter
from ibapi.scanner import ScannerSubscription
from ibapi.order_condition import *
from ibapi.contract import *
from ibapi.order import *
from ibapi.order_state import *
from Testbed.ContractSamples import ContractSamples
from Testbed.OrderSamples import OrderSamples

import datetime
import datetime as dt
from datetime import timedelta
import quandl as qdl
# Install https://www.anaconda.com/download/ 
import pandas_datareader as pdr
import pandas as pd
# Import Matplotlib's `pyplot` module as `plt`
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
#import statsmodels.api as sm
# Import the `datetools` module from `pandas`
#from pandas.core import datetools
import pandas.tseries as pdts

comments powered by Disqus