【问题标题】:how to use the reqMktData from Ibpy properly?如何正确使用来自 Ibpy 的 reqMktData?
【发布时间】:2017-08-01 20:37:54
【问题描述】:

大家好,我刚开始研究 Ibpy 算法,我想先用纸面交易对其进行测试,但我对如何使用 reqMktData 获得最后价格有一点了解。我下单没问题,但是这 25 秒没有返回,我认为它只能在交易时间内使用,或者只是使用它有什么错误?

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

【问题讨论】:

  • 如果请求发送成功,它应该返回数据或某种错误消息。您应该确保您正在捕获错误消息。我对 Ibpy 不熟悉,但我在github.com/blampe/IbPy/wiki/Getting-Started 找到了如何启用日志记录。如果您使用的是 IBGateway,还请选中“显示日志”复选框以查看那里发生的情况(不确定如何在 TWS 中查看日志)。
  • 您好我已经修改了它,所以我可以得到错误这是我得到的:TWS 连接时间:20170801 23:59:20 WET
  • 所以显然它没有连接到 usfuture、usfarm、fundfarm 和 ushmds 是那些不应该是 24/7 的,还是我必须付费才能访问?
  • 它们应该 24/7 都在上涨,如果您还没有购买任何市场数据,您必须为任何市场数据付费。您必须在账户管理 -> 管理账户 -> 交易配置下登录并在那里订阅。
  • 明白了,我想我必须先完成应用程序才能获取数据。谢谢你的信息!

标签: python algorithmic-trading interactive-brokers ibpy


【解决方案1】:

我之前尝试过 IbPy 并成功获取数据,但现在我改用 Ibapi,这更困难,仍然无法完全交易,但它具有调整后的历史价格。

所以这是我的代码,你必须根据需要定制。

1.获取股票会员表格Excel

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 个请求,因此我将其划分为 S&P 505 的 8 个多个会话。然后每 70 只股票重新登录。我可以在 2 分钟内得到总共 505 个。

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

【讨论】:

    【解决方案2】:

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

    tws = ibConnection(port=7496,clientId=100)
    

    请注意,7496 是一个通用端口,但 clientId 是您希望指定的任何内容(在您使用的 IB 帐户中,在 File->API->Settings 下)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 2011-06-01
      • 2022-09-27
      • 2017-12-03
      相关资源
      最近更新 更多