简体   繁体   中英

Get bid/ask price from Interactive Brokers using python

This code:

ib = IB()
ib.connect('127.0.0.1', 7496)

contract = Stock('SLV', 'SMART', 'USD')

test=ib.reqTickers(contract) 
print(test)

will print out this:

[Ticker(contract=Stock(symbol='SLV', exchange='SMART', currency='USD'), time=datetime.datetime(2019, 7, 1, 15, 18, 43, 287622, tzinfo=datetime.timezone.utc), bid=14.26, bidSize=11224, ask=14.27, askSize=2970, last=14.27, lastSize=1, volume=48694, open=14.24, high=14.33, low=14.24, close=14.33, halted=0.0, ticks=[], tickByTicks=[], domBids=[], domAsks=[], domTicks=[])]

Now I need to get the bid and ask prices.

Doing print(test.ask) or print(test.bid) normally gets error: AttributeError: 'list' object has no attribute 'ask'.

I tried many other things similar to the above but got similar errors.

您的test是一个长度为1的列表,其唯一条目是您感兴趣的Ticker对象。请尝试test[0].ask

I had a similar problem, solved this way:

test , in your example, is a list of Ticker objects. Also, in your example, contract contains a single contract, but would more commonly contain a group of contracts (* contracts ), as per the ib_insync documents here .

The following code is a solution:

test = ib.reqTickers(contract)
for _, r in enumerate(test):
    print(r.contract.symbol, r.time, r.bid, r.ask, r.close)

The better code (also per the documents link) would be:

tickers = [ib.reqTickers(*contracts)]
for i, r in enumerate(tickers):
    for j, t in enumerate(r):
        print(t.contract.symbol, t.time, t.bid, t.ask, t.close)

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