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

标签 python api ibpy

我正在尝试通过 Ibpy 从 Interactive Brokers (IB) 获取历史数据。 我已经为这个任务尝试了几个脚本,这些脚本是我从其他表明它应该工作的人那里改编而来的。但是,它们都不适合我! 我是 python 的新手,所以我承认我对这些方法的工作原理并不完全了解——但是,我应该尝试最明显的修复。下面我列出了我尝试过的两个脚本。 我正在使用 python 2x。

在交易平台我有以下设置:

选中:启用 ActiveX 和套接字客户端。 未选中:启用 DDE 客户端。 未选中:只读 API。 选中:在连接时下载打开的订单。 选中:发送投资组合时包括外汇头寸。 选中:发送 EEP 的状态更新。 套接字端口 = 7496。 checked:使用负数绑定(bind)自动订单。 未选中:创建 API 消息日志文件。 未选中:在 API 日志文件中包含市场数据。 日志记录级别 = 错误。 主 API 客户端 ID = 222。 向 API 发送批量数据的超时时间为 30 秒。 组分交换分隔符 = 空白。 选中:仅允许来自本地主机的连接。

API - 检查的预防措施:绕过 API 订单的订单预防措施。此选项卡中的其他所有内容均未选中。

当我运行 python 脚本时,我已经登录并运行了 TWS,并且与其他人在网上所说的相比,上面的 TWS API 设置似乎是正确的。我有一个订阅美股数据的真实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 还很陌生?

非常感谢任何帮助。

最佳答案

始终实现错误处理程序,API 会告诉您出了什么问题。在这种情况下,它表示使用“1 天”作为条形大小。

没必要 sleep 。使用 nextValidId 了解连接何时准备就绪。使用不同的结束方法来了解您何时完成。 historicalDataEnd 似乎还没有在 IBpy 中实现,所以只需查找“完成”

不要关闭 api 日志记录,它会显示错误以及发送到 TWS 和从 TWS 发送的所有不同消息。您可以关闭日志文件中的市场数据,因为它很多。在您的 jts 目录中查找文件“api.222.Wed.log”。

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

关于python - IBPY 中的 reqHistoricalData 不返回任何内容 [python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811393/

相关文章:

api - RESTful API 中身份验证 token 的存储位置

python - 在 python 3.5 中写入 gzipped fasta 文件

python - sqlite3 fetchall 有必要吗?

python - 配置 Spyder 或 Pycharm 以符合 PEP8 风格标准

android - 使用改造和 Moshi 解析 api 响应不完全 "json"

java - EDT 违规是否可能导致外部软件出现 NullPointerException?

algorithmic-trading - IBPY 获取正确的历史成交量数据

python - 无法使用 python 连接到 Interactive Brokers

python - 将 django-rest-interface 与 http put 一起使用