我已经尝试IbPy之前,并成功获取数据,但现在我已经使用Ibapi,而这是更困难的,仍然不能完全交易,但它有一个调整后的历史价格。
所以这是我的代码,你必须定制你想要的东西。
1.Get该股成员的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.注册的历史价格通过使用循环,因为我的帐户有单位力矩100请求的限制,所以我devide它转化为S8中多个会话& P 505.然后重新登录每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()
如果请求发送成功,它应该返回数据或某种错误消息。你应该确保你正在捕获错误信息。我不熟悉Ibpy,但我发现如何在这里启用日志记录https://github.com/blampe/IbPy/wiki/Getting-Started。如果您正在使用IBGateway,请检查'show log'复选框以查看发生了什么(不知道如何查看TWS中的日志)。 – kingdc
嗨,我已修改它,所以我可以得到的错误,这就是我得到的:TWS连接时间:20170801 23:59:20湿 –
TB1
显然,它没有连接到usfuture,usfarm,fundfarm和ushmds是那些不应该全天候运行或者我必须付款才能访问? – TB1