简体   繁体   中英

Getting options chain from IB api using ib insync (Python)

I have this simple script to get all options prices for an option chain in IB. my problem is that it is painfully slow (11sec per contract). I know that I can use multi processing but it still seems like there must be a better way to do this. I like the simplicity of ib insync and would prefer to stay away from the regular ib api package as much as possible. Help would be much appreciated

from ib_insync import *

ib = IB()
ib.connect('127.0.0.1', 4001, clientId=666, timeout = 11)


def get_multiple_expirations_strikes(exp_list,strike_list):

    for i in exp_list:
        print('Expiration: ', i)
        for x in strike_list:
            for k in ['C','P']:
                contract = Option('AAPL', i, x, k, 'SMART')
                details = ib.reqTickers(contract)
                print ('strike: ',x,' C/P: ',k," ",details[0].close)

The above code seems to work fine but it is very slow. I have tried to add multiprocessing but apparently that doesn't work so well with ib insync. The code below is using starmap but it is returning an error.

from ib_insync import *
import multiprocessing


ib = IB()
ib.connect('127.0.0.1', 4001, clientId=666, timeout=11)

def get_contract(symbol,exp,strike,kind):

    contract = Option(symbol, exp, strike, kind, 'SMART')
    details = ib.reqTickers(contract)
    print('strike: ', strike, ' C/P: ', kind, " ", details[0].close)



def get_multiple_expirations_strikes(symbol,exp_list,strike_list):

    inputs = []
    for i in exp_list:
        for x in strike_list:
            for k in ['C','P']:
                inputs.append([symbol,i,x,k])


    with multiprocessing.Pool(processes= 3) as pool:
        g = pool.starmap(get_contract,inputs)


    print(g)

get_multiple_expirations_strikes('AAPL',['20191115', '20200320'],[155.0, 160.0, 165.0, 170.0])
ib.disconnect()

error message: OSError: [Errno 9] Bad file descriptor

This is an old thread, so your problem will most likely be solved since long. Nevertheless... I think the problem is that you are fetching the contracts one by one. You can fetch the entire option chain, like this: https://nbviewer.org/github/erdewit/ib_insync/blob/master/notebooks/option_chain.ipynb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM