IBPY中的reqHistoricalData不会返回任何内容[python]

时间:2017-03-15 13:36:08

标签: python api ibpy

我正试图通过Ibpy从盈透证券(IB)获取历史数据。 我已经为这个任务尝试了几个脚本,我已经从其他人那里调整过来,表明它应该可行。但是,它们都不适合我! 我是python的新手,所以我承认我没有完全了解这些方法的工作原理 - 但是,我应该尝试最明显的修复。下面我列出了我尝试过的两个脚本。 我使用的是python 2x。

在TWS中,我有以下设置:

选中:启用ActiveX和套接字客户端。 unchecked:启用DDE客户端。 未选中:只读API。 选中:下载连接时打开的订单。 选中:发送投资组合时包含FX位置。 选中:发送EEP的状态更新。 套接字端口= 7496。 选中:使用负数绑定自动订单。 unchecked:创建API消息日志文件。 未选中:在API日志文件中包含市场数据。 记录级别=错误。 主API客户端ID = 222。 将批量数据发送到API的超时时间为30秒。 组件Exch Separator =空白。 选中:仅允许来自localhost的连接。

API - 检查注意事项:绕过API订单的订单注意事项。其他所有内容都在此选项卡中未选中。

当我运行python脚本并且上面的TWS API设置与其他人在网上说的相比时,我已经登录并运行了TWS。我有一个真实的IB账户订阅了美国股票数据。还应该提到的是,我试图运行另一个脚本通过IBPY下订单 - 这很有用,所以问题似乎只存在(至少目前)关于获取历史数据。

脚本1:

from time import sleep, strftime, localtime  
from ib.ext.Contract import Contract  
from ib.opt import ibConnection, message  


new_symbolinput = ['AAPL']
newDataList = []  
dataDownload = []  

def historical_data_handler(msg):  
    global newDataList  
    print (msg.reqId, msg.date, msg.close)
    if ('finished' in str(msg.date)) == False:  
        new_symbol = new_symbolinput[msg.reqId]  
        dataStr = '%s, %s, %s' % (new_symbol, strftime("%Y-%m-%d", localtime(int(msg.date))), msg.close)  
        newDataList = newDataList + [dataStr]
    else:  
        new_symbol = new_symbolinput[msg.reqId]  
        filename = 'minutetrades' + new_symbol + '.csv'  
        csvfile = open('IBdata/' + filename,'w')
        for item in newDataList:  
            csvfile.write('{} \n'.format(item))
        csvfile.close()  
        newDataList = []  
        global dataDownload  
        dataDownload.append(new_symbol)  


con = ibConnection(port=7496, clientId=222)  
con.register(historical_data_handler, message.historicalData)  
con.connect()  

symbol_id = 0  
for i in new_symbolinput:  
    print (i)  
    qqq = Contract()  
    qqq.m_symbol = i  
    qqq.m_secType = 'STK'  
    qqq.m_exchange = 'SMART'  
    qqq.m_currency = 'USD'
    con.reqHistoricalData(symbol_id, qqq, '20161101', '1 W', '1 D', 'MIDPOINT', 1, 2)  

    symbol_id = symbol_id + 1  
    sleep(10)  

print (dataDownload) 
filename = 'downloaded_symbols.csv'  
csvfile = open('IBdata/' + filename,'w')  
for item in dataDownload:  
    csvfile.write('%s \n' % item)  
csvfile.close()

这应该返回csv文件中的数据。创建了csv文件,但它是空的。

响应:

Server Version: 76
TWS Time at connection:20170315 14:18:06 CET
AAPL
[]

所以它显然没有任何回报。

脚本2:

from time import sleep, strftime
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message

def my_account_handler(msg):
    print(msg)

def my_tick_handler(msg):
    print(msg)

def my_hist_data_handler(msg):
    print(msg)


if __name__ == '__main__':

    con = ibConnection(port=7496,clientId=222)
    con.register(my_account_handler, 'UpdateAccountValue')
    con.register(my_tick_handler, message.tickSize, message.tickPrice)
    con.register(my_hist_data_handler, message.historicalData)
    con.connect()

    print(con.isConnected())

    def inner():

        qqqq = Contract()
        qqqq.m_secType = "STK" 
        qqqq.m_symbol = "AAPL"
        qqqq.m_currency = "USD"
        qqqq.m_exchange = "SMART"
        endtime = strftime('%Y%m%d %H:%M:%S')
        print(endtime)
        print(con.reqHistoricalData(1,qqqq,endtime,"1 W","1 D","MIDPOINT",1,2))



    sleep(10)

    inner()
    sleep(5)
    print('disconnected', con.disconnect())
    print(con.isConnected())

这里的回应:

Server Version: 76
TWS Time at connection:20170315 14:29:53 CET
True
20170315 14:30:05
None
('disconnected', True)
False

再一次没有返回。我不知道为什么,因为它似乎适用于其他人。我可能错过了一些基本的东西,因为我对Python很陌生?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

始终实施错误处理程序,API会告诉您错误的原因。在这种情况下,它说使用" 1天"对于酒吧大小。

没有必要睡觉。使用nextValidId知道连接何时就绪。使用不同的最终方法来了解您何时完成。 historicalDataEnd似乎还没有在IBpy中实现,所以只需查看已完成的内容即可。

不要关闭api日志记录,它会显示错误以及发送到TWS和从TWS发送的所有不同消息。您可以关闭日志文件中的市场数据,因为它非常多。寻找一个文件' api.222.Wed.log'在你的jts dir。

from time import sleep, strftime
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message
import pandas as pd
import numpy as np

def nextValidId_handler(msg):
    print(msg)
    inner()

hist = []

def my_hist_data_handler(msg):
    print(msg)
    if "finished" in msg.date:
        print('disconnecting', con.disconnect())
        df = df = pd.DataFrame(index=np.arange(0, len(hist)), columns=('date', 'close', 'volume'))
        for index, msg in enumerate(hist):
            df.loc[index,'date':'volume'] = msg.date, msg.close, msg.volume
        print(df )
    else:
        hist.append(msg)    

def error_handler(msg):
    print(msg)

if __name__ == '__main__':

    con = ibConnection(port=7497,clientId=222)
    con.register(error_handler, message.Error)
    con.register(nextValidId_handler, message.nextValidId)
    con.register(my_hist_data_handler, message.historicalData)
    con.connect()

    print(con.isConnected())

    def inner():

        qqqq = Contract()
        qqqq.m_secType = "STK" 
        qqqq.m_symbol = "AAPL"
        qqqq.m_currency = "USD"
        qqqq.m_exchange = "SMART"
        endtime = strftime('%Y%m%d %H:%M:%S')
        print(endtime)
        con.reqHistoricalData(1,qqqq,endtime,"1 W","1 day","MIDPOINT",1,2)

    print(con.isConnected())