This code 'finds' market price for option spread. Why is it so slow?

Discussion in 'Automated Trading' started by yosuji198, Mar 21, 2020.

  1. Hi Community,

    The below code is built in Python using ib_insync. The goal is the execute an option spread at the market price. Often options are illiquid so so if you buy a spread you could pay higher than midprice and if you sell a spread you could sell for less than midprice, potentially. That's why a SNAP to PRIM order is used here instead of SNAP to MID. Regardless, this code takes a few seconds to initialize and a few seconds to loop between each offset.
    Is it because ib.reqMarketDataType and ib.reqTickers slows it down? Is there any way to speed this up?

    from ib_insync import *
    ib = IB()
    ib.connect("", 7497, clientId=4001)

    maximum_limit_price = 11.5
    spread_contract = Contract()
    spread_contract.symbol = "AAPL"
    spread_contract.secType = "BAG"
    spread_contract.currency = "USD" = "SMART"
    option1 = Option('AAPL', '20200327', 230.0, 'C', 'SMART', tradingClass='AAPL')
    option2 = Option('AAPL', '20200327', 245.0, 'C', 'SMART', tradingClass='AAPL')
    # ib.qualifyContracts(option2)
    contracts = [option1, option2]
    leg1 = ComboLeg()
    leg1.conId = option1.conId
    leg1.ratio = 1
    leg1.action = "BUY" = "SMART"
    leg2 = ComboLeg()
    leg2.conId = option2.conId
    leg2.ratio = 1
    leg2.action = "SELL" = "SMART"
    spread_contract.comboLegs = []
    ib_order = Order()
    ib_order.orderType = 'SNAP PRIM'
    ib_order.action = 'BUY'
    ib_order.totalQuantity = 5
    i = 0
    flag_loop = True
    data = ib.reqTickers(spread_contract)
    offset = 0.5

    while i < 15:
    data = ib.reqTickers(spread_contract)
    limit_price = data[0].bid + offset
    if limit_price < maximum_limit_price:
    ib_order.auxPrice = offset
    trade = ib.placeOrder(spread_contract, ib_order)
    if trade.orderStatus.status == 'Filled':
    print('', trade)
    offset += 0.5
    i += 1
  2. traider


    dont use reqMarketData for event driven

    def on_tick(self, ticker):
    ticker.updateEvent += rader.on_tick
    TooEffingOld likes this.
  3. Thanks traider we'll try it
  4. Sorry traider, we didn't understand your post. My coder took a look at self.on_tick and says that self.on_tick uses reqMktData itself.
    So essentially only way to get data is reqMktData or reqTicker functions. Does that sound right?
  5. traider


    Look at this
    look at all his notebooks very good examples
  6. Our code runs faster now. We still used ib.reqMarketDataType(3) but we took out the ib.reqTickers it wasn't necessary and was just slowing things down.
    My coder looked at the link traider sent but didn't think it was relevant. We're just looking for simple bid & ask prices for option spreads not depth