IBPY中的reqHistoricalData不返回任何内容[python] [英] reqHistoricalData in IBPY doesn't return anything [python]

查看:109
本文介绍了IBPY中的reqHistoricalData不返回任何内容[python]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Ibpy从盈透证券(IB)获取历史数据. 我已经为该任务尝试了几种脚本,并从其他脚本中修改了这些脚本以表明它应该可以工作.但是,它们都不对我有用! 我是python的新手,所以我承认我对这些方法的工作方法不完全了解-但是,我应该尝试过最明显的修复程序.下面,我列出了我尝试过的两个脚本. 我正在使用python 2x.

I am trying to obtain historical data from Interactive Brokers (IB) through Ibpy. I have tried several scripts for this task, which I have adapted from others who indicate that it should work. None of them work for me, however! I am new to python, so I admit that I do not have complete insight into the workings of these methods - however, I should have tried the most obvious fixes. Below I have listed two of the scripts I have tried. I'm using python 2x.

在TWS中,我有以下设置:

In TWS I have the following settings:

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

checked: Enable ActiveX and Socket Clients. unchecked: Enable DDE clients. unchecked: Read-Only API. checked: Download open orders on connection. checked: Include FX posistions when sending portfolio. checked: Send status updates for EEP. Socket port = 7496. checked: Use negative numbers to bind automatic orders. unchecked: Create API message log file. unchecked: Include market data in API log file. Logging Level = Error. Master API client ID = 222. Timeout to send bulk data to API is 30 seconds. Component Exch Separator = Blank. checked: Allow connections from localhost only.

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

API - Precautions checked: Bypass Order Precautions for API Orders. everything else all unchecked in this tab.

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

I have got TWS logged in and running when I run the python scripts and the TWS API settings above seem correct compared with what everyone else is saying online. I have a real IB account subscribed to US equity data. It should further be mentioned that I tried to run another script placing an order through IBPY as well - this worked, so the problem seems to exist only (at the moment at least) regarding obtaining the historical data.

脚本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文件已创建,但为空.

this should return the data in a csv file. The csv file is created, but it is empty.

响应:

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

因此,它显然不会返回任何内容.

So it clearly doesn't return anything.

脚本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的新手?

Again nothing is returned. I have no idea why, as it seems to work for others. I might have missed something fundamental as I'm quite new to Python?

非常感谢您的帮助.

推荐答案

始终实施错误处理程序,API会告诉您出了什么问题.在这种情况下,条形尺寸应使用"1天".

Always implement an error handler and the API will tell you what's wrong. In this case it says use "1 day" for a bar size.

没有必要睡觉.使用nextValidId知道连接准备就绪的时间.使用不同的结束方法来了解完成的时间. historicalDataEnd似乎尚未在IBpy中实现,因此只需查找完成"

There's no need to sleep. Use nextValidId to know when the connection is ready. Use the different end methods to know when you're done. historicalDataEnd doesn't seem to be implemented yet in IBpy so just look for 'finished'

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

Don't shut off api logging, it would have shown the error as well as all the different messages sent to and from TWS. You can shut off market data in the log file as it's quite a lot. Look for a file 'api.222.Wed.log' in your 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())

这篇关于IBPY中的reqHistoricalData不返回任何内容[python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆