ibpy:提取多个合同的API响应 [英] ibpy: extract API responses for multiple contracts

查看:90
本文介绍了ibpy:提取多个合同的API响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对将ibpy与Interactive Brokers API结合使用来获取给定的100只股票的实时报价数据感兴趣.下面的代码来自网络上的示例,仅适用于一种股票.有人可以告诉我如何同时处理100只股票吗?

I am interested in using ibpy with Interactive Brokers API to get real time tick data for a given universe of 100 stocks. The code below, from examples on the web works for one stock. Can someone tell me how i can do this for 100 stocks at the same time?

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,用于标识响应消息是针对哪个请求的.

When you request data, you give a tickerId that identifies which request the response message is for.

我将从文件中读取证券列表,并将其放入数据框,然后将索引用作股票代码.它将使查找和存储数据变得更加容易.

I would read a list of securities from a file and put them in a data frame and just use the index as the tickerId. It will make finding and storing the data that much easier.

这是我制作数据结构的方式

Here's how I make the data structure

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在数据框中找到行.

Now to make the requests I just loop through the data frame. In the callback I use the tickerId to find the row in the data frame.

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)

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

Now I have all my current data if I want to use it somehow. Another option would be some structure to save it and make a graph.

这篇关于ibpy:提取多个合同的API响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆