8

我有兴趣将 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
4

1 回答 1

10

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

如果我想以某种方式使用它,现在我拥有所有当前数据。另一种选择是一些结构来保存它并制作图表。 在此处输入图像描述

于 2015-05-10T23:06:56.973 回答