ibpy:提取多个合同的API响应

时间:2015-05-08 18:15:16

标签: python tws interactive-brokers ibpy

我有兴趣使用ibpy和Interactive Brokers API来获取给定100个股票的实时计时数据。下面的代码,来自网络上的示例适用于一个股票。有人可以告诉我如何同时为100只股票做这个吗?

Python脚本:

  preg_match_all('/Blocks/',$word,$matches);
  $found = count($matches[1]);

命令行输出:

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()

1 个答案:

答案 0 :(得分:9)

当您请求数据时,您会给出一个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)

如果我想以某种方式使用它,现在我拥有所有当前数据。另一种选择是保存它并制作图形的一些结构。 enter image description here