如何使用IB API获取当前价格



我有这个代码,我需要在变量中存储最后的价格,我该怎么办?

class IBapi(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
def tickPrice(self, reqId, tickType, price, attrib):
if tickType == 2 and reqId == 1:
print('The current ask price is: ', price)

app = IBapi()
app.connect('127.0.0.1', 7497, 123)
#Create contract object
apple_contract = Contract()
apple_contract.symbol = 'AAPL'
apple_contract.secType = 'STK'
apple_contract.exchange = 'SMART'
apple_contract.currency = 'USD'

app.reqMktData(1, apple_contract, '', False, False, [])

我需要在一个变量中保存当前价格

考虑到给定的代码,这里有一个想法:

req_id = 1
def get_reqId():
global req_id
return (req_id + 1)
def run_loop():
app.run()

class IBapi(EWrapper, EClient):
market_data = {}
request_mapping = {}
def __init__(self):
EClient.__init__(self, self)
def tickPrice(self, reqId, tickType, price, attrib):
if tickType == 2 and reqId == 1:
print('The current ask price is: ', price)
symbol = self.request_mapping[reqId]
self.market_data[symbol] = price
app = IBapi()
app.connect('127.0.0.1', 7497, 123)
#Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()
time.sleep(1)
#Create contract object
apple_contract = Contract()
apple_contract.symbol = 'AAPL'
apple_contract.secType = 'STK'
apple_contract.exchange = 'SMART'
apple_contract.currency = 'USD'
request_id = get_reqId()
app.request_mapping[request_id] = 'AAPL'
app.reqMktData(1, apple_contract, '', True, False, [])
time.sleep(2)
print(app.market_data['AAPL'])

注意:

  • 在线程中启动,这样就不会阻止主线程执行
  • 在IBapi类中,为市场数据和请求定义字典映射
  • 使用get_reqId((获取用于映射目的的唯一reqId
  • 在执行reqMktData之前,将每个requestID映射到其符号函数
  • 将reqMktData的快照参数更改为True

相关内容

  • 没有找到相关文章

最新更新