O'Reilly logo

Mastering Python for Finance by James Ma Weiming

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required