Notes on Algorithmic Trading with Interactive Brokers

Reading notes on Algorithmic Trading with Interactive Brokers (Python and C++): IBKR fees, TWS API gateways, and building an algorithmic trading workflow.

Book: Algorithmic Trading With Interactive Brokers: Python and C++

Resources

Terms, Glossary, Notations…

Refer to this Notion Note

Before Diving In

#KIM :

  • Can safely skip all sections with C++
  • You don’t have to know/trade every instrument.

Chapters

Chap 1: Fun Facts

#KIM Fun Facts:

  1. Michael Lewis developed an algorithmic method of recruiting players. And pumped the winning rate of the team in the World Series in 2013. Read more on MoneyBall.
  2. Thomas Peterffy programmed the world’s first algorithm to read NASDAQ prices and place trades in 1987. NASDAQ banned him, but he won at the end anyways. He’s the founder of IBKR.
  3. Things about fees(Normally opt for tiered pricing):
    1. Tiered Pricing usually consists:
      1. Commision per share
      2. Minimum per order
      3. Maximum per order
    2. Fixed Pricing usually consists:
      1. Base fee
      2. Minimum fee per order
      3. Maximum fee per order
  4. TWS V.S. APIs
    1. Web API
      1. Client Portal Gateway(CPG)
    2. TWS API(Main Gateway)
      1. TWS Desktop
      2. IB Gateway
    3. FIX API
    4. TWS API, the actual Python Wrapper

IBKR’s Client Portal is a web-based, simplified user interface.

Chap 2 TWS: A first glance

TWS Getting Started

#KIM Best Practices:

  1. Train using paper account.
  2. Get familiar with GUI.
Order/Instruments Types
  • Limit Orders
  • Stop Orders:
    • Buy Stop
    • Sell Stop
    • Trailing Stop(Trail the price using a fixed offset or a percentage)
  • Shot Sell/Short
  • Bonds
    • Treasuries
    • Corporate Bonds
    • #glossary Maturity
    • #glossary Face Value/Par Value/Par
    • #glossary Discount
    • #glossary Premium
    • #glossary Coupon Payment
    • #glossary Coupon Rate
    • #glossary Current Yield
    • #glossary Yield to Maturity/YTM
    • #glossary Credit
      • Moody’s
      • S&P’s
      • Fitch
      • Ratings:
        • AAA/AA+/AA/AA-/A+/A/A-/BBB+/BBB+/BBB-
    • #glossary Convertible
    • #glossary Callable
    • #glossary Putable
    • #glossary CUSIP

#KIM > With TWS, traders can specify whether the stop price should trail the security’s price using a fixed offset or a percentage.

Chap 3 Stock Options

First, #glossary :

  • Forward Contracts
  • Futures Contracts
  • Options
    • Premium: The price of the option.
    • Expiration
    • Exercising
    • Assignment
    • Strike Price:
    • Calls and Puts
      • Call(Longing Orientated): The RIGHT to buy at the strike price for the OWNER.
        • Buying the right to buy
        • Selling the right to sell
      • Put(Shorting Orientated): The RIGHT to sell at the strike price for the OWNER.
        • Buying the right to sell
        • Selling the right to sell
  • Swaps

Call’s formula

$$ Profit = (Sell Price - Strike Price)-Premium $$ $$ Breakeven = Strike Price + Premium $$

Put’s Formula

$$ profit = (strikeprice - buyprice)-premium $$ $$ breakeven=strikeprice-premium $$ #KIM

  • All options expire at 4:00PM Eastern Time(New York) on the third Friday of the expiration month.
  • Weekly options are released on Thursday and expire the following Friday.
    • Weeklys has lower premium.
    • Can enable traders make decisions for short-term.
  • Every monthly option is assigned to one the 3 cycles:
    • “Jan”:1,4,7,10
    • “Feb”:2,5,8,11
    • “March"3,6,9,12
  • Possible expired month starting at month $x$: $x$,$x+1$,$next\ two\ months\ in\ que\ in\ cycle$.
  • LEAPS expire in more than 1 year(Mostly in 2 years.).
    • higher premium
    • less risky
    • long-term
  • Bid: Buying price
  • Ask: Selling Price

Chap 5 Futures

Skip due to insufficient trading permission in IBKR.

Chap 6 Into the IBKR API

Glossary

TWS: TWS Desktop or IB Gateway.

Most fundamental classes from ibapi: EClient and EWrapper

Sockets

All connections to TWS are made through sockets.

Classes

#KIM Noteworthies:

  • Client Class: EClient $\cup$ EWrapper
  • Instances of client classes and their wrappers
  • Methods most named like: reqXYZ()

Chap 7 Contracts and Orders

#KIM :

  • As the name implies, Contract()s are de facto contacts in business, it defines the underlying asset, order type, currency, quantity, etc.
  • As the name implies, Order()s are to put Contract()s in action(buy/sell).
  • What is SMART routing: IBKR’s middle relay to trade your orders among the exchanges, from nation wide to potentially worldwide.

Best Practices:

  • Create a cheat sheet with all the fundamental methods,

Contracts in IBKR consists:

  1. Must-have arguments;
  2. Optional arguments;
  3. Derivative specific arguments

Must-haves are:

  1. Ticker symbol as symbol
  2. Security Type as secType
    1. STK
    2. BOND
    3. IND
    4. FUND
    5. OPT
    6. FUT
    7. CASH
    8. NEWS
  3. Currency currency
  4. Exchange exchange

Useful Methods

#KIM :

  • EClient calls a callback from EWrapper generalized: client.reqXYZ -> EWrapper.XYZ. But usually we define classes that combine both EClient and EWrapper, so code usually unifies client and wrapper.
  • Of all sorts of ids, name it reqId, Order ID, Contract ID, conId… IBKR takes id handling very seriously and I like this rigid approach. Every tangible object associated with ibapi has an id
reqContractDetails

Client’s Call:

twsapi_class.contractDetails(int reqId, ContractDetails contractDetails)
Order()

Arguments:

  • action
  • totalQuantity
  • orderType
reqMatchingSymbols
twsapi_class.reqMatchingSymbols(int reqId, string pattern)
Noteworthy methods, functions…
  • placeOrder(orderId, contract, order)
  • openOrder
  • reqIds
  • reqExecutions
  • reqPositions
  • reqAccountSummary
  • orderStatus

Request order status:

  • reqOpenOrders()
  • reqAllOpenOrders()
  • reqAutoOpenOrders(bool bind)

#KIM :

Powered by Ignorance.