erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.76k stars 726 forks source link

ib.reqMktData(contract, genericTickList='236') cant get shortableShares #637

Closed zero1386 closed 10 months ago

zero1386 commented 10 months ago

I found it difficult to get shortableShares data with ib.reqMktData(contract, genericTickList='236'), but it became very easy when 4 threads were turned on. I guess there is something wrong with passing genericTickList in asyncio, but I haven't confirmed it. My code is as follows:

from concurrent.futures import ThreadPoolExecutor from ib_insync import * import asyncio

def asy_shortableShares(symbol, clientId): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) ib = IB() for i in range(5): ib.connect('127.0.0.1', 4001, clientId=clientId)

    #
    contract = Stock(symbol=symbol, exchange='SMART', currency='USD')
    ib.reqMarketDataType(3)

    ticker = ib.reqMktData(contract, genericTickList='236')

    ib.sleep(2)
    shortableShares = ticker.shortableShares
    #print(f"{shortableShares}")

    ib.cancelMktData(contract)
    ib.disconnect()

    if shortableShares >= 0:
        return shortableShares

return None

def get_shortableShares(symbol):

float clientId 1:4

with ThreadPoolExecutor(max_workers=4) as executor:
    futures = [executor.submit(asy_shortableShares, symbol, clientId) for clientId in range(4)]

    for future in futures:
        result = future.result()
        if result is not None:
            return result
return None

if name == "main": symbol = "AAPL"

results = get_shortableShares(symbol)
print(f"Symbol: {symbol}, Shortable Shares: {results}")
erdewit commented 10 months ago

I think sleeping for two seconds is to short. It's better to wait until the actual data comes in.