Building a mean-reverting algorithmic trading system

In the previous section, we established a connection to IB TWS and sent a market order of 100 shares. In this section, we will add logic functions to buy or sell a number of shares, read tick data, and track our positions. In essence, we will try to create a simple, fully automated algorithmic trading system.

Setting up the main program

Since our code might get a little complicated, let's tidy up and put everything into a class named AlgoSystem. We will import the following modules:

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
import time
import pandas as pd
import datetime as dt

In the initialization section of our class, declare the ...

Get Mastering Python for Finance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.