首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确使用Ibpy中的reqMktData?

如何正确使用Ibpy中的reqMktData?
EN

Stack Overflow用户
提问于 2017-08-02 04:37:55
回答 2查看 3.9K关注 0票数 1

嗨,伙计们,我刚刚开始研究Ibpy算法,我想先用纸交易来测试它,但我对如何使用reqMktData获得最后的价格有一点了解。我下订单没有问题,但这25秒内没有返回任何东西,我想它只在交易时间使用,或者可能只是使用错误有什么想法吗?

代码语言:javascript
复制
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(788,c,"",False)
sleep(25)
print 'All done'

tws.disconnect()
EN

回答 2

Stack Overflow用户

发布于 2017-08-17 13:03:00

我以前尝试过IbPy,并成功地获得了数据,但现在我使用了Ibapi,它更困难,仍然不能完全交易,但它有一个调整后的历史价格。

这是我的代码,你可以裁剪你想要的东西。

1.获取股票成员表单Excel

代码语言:javascript
复制
from ib.opt import ibConnection, message
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.ext.TickType import TickType as tt
from time import sleep, time, strftime
import datetime
from __future__ import print_function #I'm using 3.x style print
import pandas as pd
import numpy as np
from math import ceil
import re

xls_file = pd.ExcelFile('xxxx\\Interactive_Broker_trading\\SNP2.xlsx')
df = xls_file.parse('Sheet1')
Ticker = df.iloc[:,1]
all_data = pd.DataFrame(Ticker)
all_data.columns = ['ticker']
all_data['type'] = 'STK'
all_data['exchange'] = 'SMART'
all_data['curr'] = 'USD'
all_data['bidPrice'] =0
all_data['askPrice'] =0
all_data['lastPrice'] =0
all_data['HistoryPrice']=0

2.通过使用for循环获取历史价格,因为我的帐户每分钟有100个请求的限制,所以我将其划分为标准普尔505的8个多会话。然后重新登录每70只股票。我可以在2分钟内得到505个总数。

代码语言:javascript
复制
def error_handler(msg):
    print(msg)
def my_callback_handler(msg):
    if msg.field in [tt.BID,tt.ASK,tt.LAST]:
#         from ib.ext.TickType import TickType as tt

        #now we can just store the response in the data frame
        all_data.loc[msg.tickerId,tt.getField(msg.field)] = msg.price
#         if msg.field == tt.LAST:
# #             print('a')
#             print(all_data.loc[msg.tickerId,'ticker'],msg.price)

t = time()
max_amount_per_Iter = 70 #max number per iter to save cost
max_Iter = ceil(len(all_data)/max_amount_per_Iter)
for i in range (0,max_Iter):
    print('====================for : ',i+1,'==========================')
    sleep(1)
    tws = ibConnection(clientId=11+i)
    tws.register(my_callback_handler, message.tickPrice, message.tickSize)
    tws.register(error_handler, 'Error')
    tws.connect()
    all_dum = all_data.iloc[i*max_amount_per_Iter:min((i+1)*max_amount_per_Iter,len(all_data)),:]
    for index, row in all_dum.iterrows():


        c = Contract()
        c.m_symbol = row['ticker']
        c.m_exchange = row['exchange']
        c.m_currency = row['curr']
        c.m_secType = row['type']
        # the tickerId is just the index in but for some reason it needs str()
        tws.reqMktData(str(index),c,'',False)

        sleep(0.2)
    sleep(2)
    print('=========End round : ',i+1,'with time :',time() - t,'==============')
    tws.disconnect()
票数 1
EN

Stack Overflow用户

发布于 2017-08-05 06:27:34

我认为这与IB内部的市场数据订阅有关,因为我也遇到了类似的问题。我在connection上得到了一个TWS时间...随“市场数据场连接”消息一起在结果中返回。确保已建立连接端口和clientID,即:

代码语言:javascript
复制
tws = ibConnection(port=7496,clientId=100)

请注意,7496是一个通用端口,但clientId是您希望指定的任何端口(在文件->应用编程接口->设置下使用的IB帐户中)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45447272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档