Contents

Interactive Brokers Python API

Contents
Warning
This is by no means an attempt to write a comprehensive manual or guide to the Interactive Brokers API!

Introduction

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
from time import sleep


class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def error(self, req_id, error_code, error_string):
        print("Error: ", req_id, " ", error_code, " ", error_string)

    def tickPrice(self, req_id, tick_type, price, attrib):
        print("Tick Price. req_id:", req_id, "tick_type:", TickTypeEnum.to_str(tick_type), "Price:", price, end=' ')

    def tickSize(self, req_id, tick_type, size):
        print("Tick Size. req_id:", req_id, "tickType:", TickTypeEnum.to_str(tick_type), "Size:", size)


def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)
    sleep(1)

    # Switch to delayed-frozen data if live is not available
    app.reqMarketDataType(4)

    # Stock
    con_stk = Contract()
    con_stk.symbol = "AAPL"
    con_stk.secType = "STK"
    con_stk.exchange = "SMART"
    con_stk.currency = "USD"
    con_stk.primaryExchange = "NASDAQ"
    app.reqMktData(reqId=1, contract=con_stk, genericTickList="", snapshot=False, regulatorySnapshot=False, mktDataOptions=[])

    # Futures
    con_fut = Contract()
    con_fut.symbol = "ES"
    con_fut.localSymbol = "ESU1"
    con_fut.secType = "FUT"
    con_fut.lastTradeDateOrContractMonth = "20210917"
    con_fut.currency = "USD"
    con_fut.exchange = "SMART"
    con_fut.primaryExchange = "GLOBEX"
    app.reqMktData(reqId=2, contract=con_fut, genericTickList="", snapshot=False, regulatorySnapshot=False, mktDataOptions=[])

    app.run()


if __name__ == "__main__":
    main()
{"mode":"full","isActive":false}