我有兴趣使用 ibpy 和 Interactive Brokers API 来获取给定 100 只股票的实时报价数据。下面的代码来自网络上的示例,适用于一只股票。谁能告诉我如何同时处理 100 只股票?
Python 脚本:
from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from time import sleep
def my_callback_handler(msg):
inside_mkt_bid = ''
inside_mkt_ask = ''
if msg.field == 1:
inside_mkt_bid = msg.price
print 'bid', inside_mkt_bid
elif msg.field == 2:
inside_mkt_ask = msg.price
print 'ask', inside_mkt_ask
tws = ibConnection()
tws.register(my_callback_handler, message.tickSize, message.tickPrice)
tws.connect()
c = Contract()
c.m_symbol = "DATA"
c.m_secType = "STK"
c.m_exchange = "SMART"
c.m_currency = "USD"
tws.reqMktData(1,c,"",False)
sleep(25)
print 'All done'
tws.disconnect()
命令行输出:
Server Version: 76
TWS Time at connection:20150508 13:42:02 EST
bid 111.42
ask 111.5
bid 111.43
bid 111.44
bid 111.42
bid 111.38
bid 111.32
ask 111.44
All done
最佳答案
当您请求数据时,您会提供一个 tickerId,用于标识响应消息针对的是哪个请求。
我会从文件中读取证券列表并将它们放入数据框中,然后只使用索引作为 tickerId。这将使查找和存储数据变得更加容易。
下面是我的数据结构
from __future__ import print_function #I'm using 3.x style print
import pandas as pd
#better to read these from a file
contracts = pd.DataFrame([
['IBM','SMART','USD'],
['AAPL','SMART','USD'],
['GOOG','SMART','USD'],
['ES','GLOBEX','USD','201506','50'],
['CL','NYMEX','USD','201506','1000']
])
# make decent column names
contracts.columns = ['sym','exch','curr','expiry','mult']
#add these specific column names to match the name returned by TickType.getField()
contracts['bidPrice'] = 0
contracts['askPrice'] = 0
contracts['lastPrice'] = 0
现在发出请求,我只是循环遍历数据框。在回调中,我使用 tickerId 在数据框中查找行。
from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from ib.ext.TickType import TickType as tt
from time import sleep
def error_handler(msg):
print (msg)
def my_callback_handler(msg):
if msg.field in [tt.BID,tt.ASK,tt.LAST]:
#now we can just store the response in the data frame
contracts.loc[msg.tickerId,tt.getField(msg.field)] = msg.price
if msg.field == tt.LAST:
print(contracts.loc[msg.tickerId,'sym'],msg.price)
tws = ibConnection(clientId=1)
tws.register(my_callback_handler, message.tickPrice, message.tickSize)
tws.register(error_handler, 'Error')
tws.connect()
for index, row in contracts.iterrows():
c = Contract()
c.m_symbol = row['sym']
c.m_exchange = row['exch']
c.m_currency = row['curr']
c.m_secType = 'STK' if row['expiry'] is None else 'FUT'
c.m_expiry = row['expiry']
c.m_multiplier = row['mult']
# the tickerId is just the index in but for some reason it needs str()
tws.reqMktData(str(index),c,"",False)
如果我想以某种方式使用它,现在我拥有所有当前数据。另一种选择是使用某种结构来保存它并制作图表。
关于python - ibpy:提取多个合约的 API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30130319/