Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python上获取ibapi中的一系列请求_Python_Wrapper_Quantitative Finance_Interactive Brokers - Fatal编程技术网

如何在python上获取ibapi中的一系列请求

如何在python上获取ibapi中的一系列请求,python,wrapper,quantitative-finance,interactive-brokers,Python,Wrapper,Quantitative Finance,Interactive Brokers,我对Python和ibapi都是新手,我问过Interactive Broker本身,他们只告诉我: self.done最初是在父类EClient中定义的 用于指示当前API连接已“完成”。你应该 不要将其用作停止自己构建的循环的指示器。 您可以保持一个API客户端连接处于活动状态,直到完成 下载了您需要的所有历史数据。如果你需要慢下来 在请求数据的速度方面,您可以使用其他线程控件 python,例如sleep()函数,在 循环,这样它就不会同时发送所有合同的历史数据请求 一次 所以我认为错误来

我对Python和ibapi都是新手,我问过Interactive Broker本身,他们只告诉我:

self.done最初是在父类EClient中定义的 用于指示当前API连接已“完成”。你应该 不要将其用作停止自己构建的循环的指示器。 您可以保持一个API客户端连接处于活动状态,直到完成 下载了您需要的所有历史数据。如果你需要慢下来 在请求数据的速度方面,您可以使用其他线程控件 python,例如sleep()函数,在 循环,这样它就不会同时发送所有合同的历史数据请求 一次

所以我认为错误来自

self.done = True
这是我的密码

from ibapi import wrapper
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract as IBcontract
from threading import Thread
import queue
import datetime
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
from ibapi.contract import *
from ibapi.ticktype import *

class TestApp(wrapper.EWrapper, EClient):

def __init__(self):
    wrapper.EWrapper.__init__(self)
    EClient.__init__(self, wrapper=self)


@iswrapper
def historicalData(self, reqId:int, bar: BarData):
    print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open,
          "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
          "Count:", bar.barCount, "WAP:", bar.average)
    if  all_data.iloc[reqId,7] == 0:
        all_data.iloc[reqId,7] = bar.close
    self.done = True

@iswrapper
def historicalDataEnd(self, reqId: int, start: str, end: str):
    super().historicalDataEnd(reqId, start, end)
    print("HistoricalDataEnd ", reqId, "from", start, "to", end)

@iswrapper
def historicalDataUpdate(self, reqId: int, bar: BarData):
    print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open,
          "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
          "Count:", bar.barCount, "WAP:", bar.average)

def main():
    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('====================round : ',i+1,'===============================')
        app = TestApp()
        app.connect("127.0.0.1", 7496, clientId=i)
        print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime()))
        for j in range (0,min(max_amount_per_Iter,len(all_data)-i*max_amount_per_Iter)):
            print(j+i*70)
        app.i = j+i*max_amount_per_Iter

        contract = Contract()
        contract.symbol = all_data.iloc[app.i,0]
        contract.secType = all_data.iloc[app.i,1]
        contract.currency = all_data.iloc[app.i,3]
        contract.exchange = all_data.iloc[app.i,2]            

        app.reqHistoricalData(app.i, contract, "","1 W", "1 day", "Adjusted_Last", 1, 1, False, []) 

        app.run()

    sleep(1)
    app.disconnect()
    sleep(0.02)
    print('=========End round : ',i+1,'with time :',time() - t,'==============')

if __name__ == "__main__":
    main()
我希望看到一个建议,如何在不使用self.done或断开TWS的情况下传递到下一个迭代。如果我不包括self.done,程序将在第一次迭代I=0,j=0时在无限循环上运行,没有人告诉它退出

因此,如果你不知道可以解决我问题的直接答案,你可以建议:

  • 在这种情况下,是否有其他流量控制可以使用

  • 或者cancelHistoricalData命令(如果可以用于此情况)

  • 或者有没有办法在类中构建类并仅在没有断开类中我的ID的子类中执行self.done=True

  • 另外,我对requestMarketData也有同样的问题

    更新V2 这是我试图打印的一些结果

    ====================round :  1 ===============================
    step2
    serverVersion:124 connectionTime:b'20170821 22:34:09 ICT'
    0
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:hfarm
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:jfarm
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfuture
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:eufarm
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:cashfarm
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfarm.us
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfarm
    ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:ilhmds
    ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:euhmds
    ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:fundfarm
    ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:ushmds
    HistoricalData.  0  Date: 20170815 Open: 67.2 High: 68.24 Low: 66.99 Close: 68.02 Volume: 13268 Count: 9453 WAP: 67.8105
    HistoricalData.  0  Date: 20170816 Open: 68.28 High: 68.91 Low: 67.45 Close: 68.01 Volume: 11950 Count: 9723 WAP: 68.457
    HistoricalData.  0  Date: 20170817 Open: 67.8 High: 68.53 Low: 66.83 Close: 66.89 Volume: 11407 Count: 9432 WAP: 67.504
    HistoricalData.  0  Date: 20170818 Open: 66.91 High: 67.25 Low: 66.57 Close: 66.78 Volume: 12091 Count: 9637 WAP: 66.8445
    HistoricalData.  0  Date: 20170821 Open: 66.9 High: 66.96 Low: 66.14 Close: 66.28 Volume: 3317 Count: 2541 WAP: 66.3425
    HistoricalDataEnd  0 from 20170814  22:34:14 to 20170821  22:34:14
    ERROR:root:ERROR 1 504 Not connected
    ERROR:root:ERROR 2 504 Not connected
    ERROR:root:ERROR 3 504 Not connected
    ERROR:root:ERROR 4 504 Not connected
    ERROR:root:ERROR 5 504 Not connected
    ERROR:root:ERROR 6 504 Not connected
    ERROR:root:ERROR 7 504 Not connected
    ERROR:root:ERROR 8 504 Not connected
    ERROR:root:ERROR 9 504 Not connected
    ERROR:root:ERROR 10 504 Not connected
    ERROR:root:ERROR 11 504 Not connected
    ERROR:root:ERROR 12 504 Not connected
    ERROR:root:ERROR 13 504 Not connected
    ERROR:root:ERROR 14 504 Not connected
    ERROR:root:ERROR 15 504 Not connected
    ERROR:root:ERROR 16 504 Not connected
    ERROR:root:ERROR 17 504 Not connected
    ERROR:root:ERROR 18 504 Not connected
    ERROR:root:ERROR 19 504 Not connected
    ERROR:root:ERROR 20 504 Not connected
    ERROR:root:ERROR 21 504 Not connected
    ERROR:root:ERROR 22 504 Not connected
    ERROR:root:ERROR 23 504 Not connected
    ERROR:root:ERROR 24 504 Not connected
    ERROR:root:ERROR 25 504 Not connected
    ERROR:root:ERROR 26 504 Not connected
    ERROR:root:ERROR 27 504 Not connected
    ERROR:root:ERROR 28 504 Not connected
    ERROR:root:ERROR 29 504 Not connected
    ERROR:root:ERROR 30 504 Not connected
    ERROR:root:ERROR 31 504 Not connected
    ERROR:root:ERROR 32 504 Not connected
    ERROR:root:ERROR 33 504 Not connected
    ERROR:root:ERROR 34 504 Not connected
    ERROR:root:ERROR 35 504 Not connected
    ERROR:root:ERROR 36 504 Not connected
    ERROR:root:ERROR 37 504 Not connected
    ERROR:root:ERROR 38 504 Not connected
    ERROR:root:ERROR 39 504 Not connected
    ERROR:root:ERROR 40 504 Not connected
    ERROR:root:ERROR 41 504 Not connected
    ERROR:root:ERROR 42 504 Not connected
    ERROR:root:ERROR 43 504 Not connected
    ERROR:root:ERROR 44 504 Not connected
    ERROR:root:ERROR 45 504 Not connected
    ERROR:root:ERROR 46 504 Not connected
    ERROR:root:ERROR 47 504 Not connected
    ERROR:root:ERROR 48 504 Not connected
    ERROR:root:ERROR 49 504 Not connected
    ERROR:root:ERROR 50 504 Not connected
    ERROR:root:ERROR 51 504 Not connected
    ERROR:root:ERROR 52 504 Not connected
    ERROR:root:ERROR 53 504 Not connected
    ERROR:root:ERROR 54 504 Not connected
    ERROR:root:ERROR 55 504 Not connected
    ERROR:root:ERROR 56 504 Not connected
    ERROR:root:ERROR 57 504 Not connected
    ERROR:root:ERROR 58 504 Not connected
    ERROR:root:ERROR 59 504 Not connected
    ERROR:root:ERROR 60 504 Not connected
    ERROR:root:ERROR 61 504 Not connected
    ERROR:root:ERROR 62 504 Not connected
    ERROR:root:ERROR 63 504 Not connected
    ERROR:root:ERROR 64 504 Not connected
    ERROR:root:ERROR 65 504 Not connected
    ERROR:root:ERROR 66 504 Not connected
    ERROR:root:ERROR 67 504 Not connected
    ERROR:root:ERROR 68 504 Not connected
    ERROR:root:ERROR 69 504 Not connected
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    =========End round :  1 with time : 7.807971477508545 ==============
    ====================round :  2 ===============================
    step2
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:hfarm
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:jfarm
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfuture
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:eufarm
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:cashfarm
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfarm.us
    ERROR:root:ERROR -1 2104 Market data farm connection is OK:usfarm
    ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:ilhmds
    ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:euhmds
    ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:fundfarm
    ERROR:root:ERROR -1 2106 HMDS data farm connection is OK:ushmds
    serverVersion:124 connectionTime:b'20170821 22:34:17 ICT'
    70
    HistoricalData.  70  Date: 20170815 Open: 117.23 High: 117.62 Low: 116.58 Close: 117.43 Volume: 7232 Count: 6205 WAP: 117.1295
    HistoricalData.  70  Date: 20170816 Open: 117.49 High: 119.59 Low: 117.03 Close: 119.25 Volume: 16468 Count: 11498 WAP: 118.8035
    HistoricalData.  70  Date: 20170817 Open: 119.19 High: 119.48 Low: 116.46 Close: 116.47 Volume: 12285 Count: 10072 WAP: 117.4645
    HistoricalData.  70  Date: 20170818 Open: 116.0 High: 117.84 Low: 115.46 Close: 116.88 Volume: 14917 Count: 10824 WAP: 116.9795
    HistoricalData.  70  Date: 20170821 Open: 116.85 High: 117.4 Low: 116.15 Close: 116.77 Volume: 3471 Count: 2599 WAP: 116.5535
    HistoricalDataEnd  70 from 20170814  22:34:19 to 20170821  22:34:19
    ERROR:root:ERROR 71 504 Not connected
    ERROR:root:ERROR 72 504 Not connected
    

    您需要使用另一个标志来终止历史数据提取,而不是像IB所示的“保留”的
    self.done

    如果
    print x.\uu dict\uu
    其中
    x
    TestApp
    的一个实例,您将看到基类已经在使用什么,并且不应该被重写,除非您已经对此处显示的方法进行了重写

    如果你想存储结果,而不是仅仅打印结果;最好像我在这里做的那样使用队列:


    您需要使用另一个标志来终止历史数据提取,而不是
    self.done
    ,如IB所示,它是“保留的”

    如果
    print x.\uu dict\uu
    其中
    x
    TestApp
    的一个实例,您将看到基类已经在使用什么,并且不应该被重写,除非您已经对此处显示的方法进行了重写

    如果你想存储结果,而不是仅仅打印结果;最好像我在这里做的那样使用队列:


    我建议在这里重新设计一下

    在您的示例中,您在获取第一个数据后立即使用self.done=True断开与API的连接。由于请求的数据以非常快的速度到达,因此在执行此操作之前,您将获得请求的所有数据。在输出中看到的结果是:您获得并处理了第一个请求的所有数据,然后发现自己断开了连接。这句话对我来说是重复的

  • 删除“self.done=True”行。这一点都不好,你不会想要的

  • 重新构造代码,使其在向API发送下一个请求之前等待historicalDataEnd事件。API可以处理并行请求,但服务器不能容忍非常频繁的历史数据请求。如果发送请求的速度太快,则会出现错误。请求之间可能也需要一些sleep()

  • 我假设app.run()会等待断开连接,这就是为什么需要“完成”标志操作的原因。把那条线也移走。如果确实需要此调用来捕获消息(我不知道TestApp类及其基类),那么请确保在所有请求的数据到达并处理后调用disconnect(),实际上是在historicalDataEnd()中。在这种情况下,在下一个循环之前需要重新连接,而在for j中的app.run()调用之后,现在缺少该连接

  • 以下是我建议的修改:

    from ibapi import wrapper
    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.contract import Contract as IBcontract
    from threading import Thread
    import queue
    import datetime
    from ibapi.utils import iswrapper #just for decorator
    from ibapi.common import *
    from ibapi.contract import *
    from ibapi.ticktype import *
    
    class TestApp(wrapper.EWrapper, EClient):
    
    def __init__(self):
        wrapper.EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)
    
    
    @iswrapper
    def historicalData(self, reqId:int, bar: BarData):
        print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open,
              "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
              "Count:", bar.barCount, "WAP:", bar.average)
        if  all_data.iloc[reqId,7] == 0:
            all_data.iloc[reqId,7] = bar.close
        # the line below is not necessary
        #self.done = True
    
    @iswrapper
    def historicalDataEnd(self, reqId: int, start: str, end: str):
        super().historicalDataEnd(reqId, start, end)
        print("HistoricalDataEnd ", reqId, "from", start, "to", end)
        print('=========End round : ',app.i+1,'with time :',time() - app.t,'==============')
    
        app.i++
        if app.i==len(all_data):
            app.disconnect() # Disconnect here: get out of app.run() when all data processed
        else:
            # add some sleep here if necessary
            reqNext()
    
    
    @iswrapper
    def historicalDataUpdate(self, reqId: int, bar: BarData):
        print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open,
              "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
              "Count:", bar.barCount, "WAP:", bar.average)
    
    
    def reqNext():
        print('====================round : ',app.i+1,'===============================')
        contract = Contract()
        contract.symbol = all_data.iloc[app.i,0]
        contract.secType = all_data.iloc[app.i,1]
        contract.currency = all_data.iloc[app.i,3]
        contract.exchange = all_data.iloc[app.i,2]
        app.reqHistoricalData(app.i, contract, "","1 W", "1 day", "Adjusted_Last", 1, 1, False, []) 
    
    
    def main():
        app = TestApp()
        app.connect("127.0.0.1", 7496, clientId=1234)
        print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime()))
    
        app.i = 0
        app.t = time()
        reqNext()
        app.run()
        # when we arrive here, app is disconnected already
    
    
    if __name__ == "__main__":
        main()
    

    我建议重新设计一下

    在您的示例中,您在获取第一个数据后立即使用self.done=True断开与API的连接。由于请求的数据以非常快的速度到达,因此在执行此操作之前,您将获得请求的所有数据。在输出中看到的结果是:您获得并处理了第一个请求的所有数据,然后发现自己断开了连接。这句话对我来说是重复的

  • 删除“self.done=True”行。这一点都不好,你不会想要的

  • 重新构造代码,使其在向API发送下一个请求之前等待historicalDataEnd事件。API可以处理并行请求,但服务器不能容忍非常频繁的历史数据请求。如果发送请求的速度太快,则会出现错误。请求之间可能也需要一些sleep()

  • 我假设app.run()会等待断开连接,这就是为什么需要“完成”标志操作的原因。把那条线也移走。如果确实需要此调用来捕获消息(我不知道TestApp类及其基类),那么请确保在所有请求的数据到达并处理后调用disconnect(),实际上是在historicalDataEnd()中。在这种情况下,在下一个循环之前需要重新连接,而在for j中的app.run()调用之后,现在缺少该连接

  • 以下是我建议的修改:

    from ibapi import wrapper
    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.contract import Contract as IBcontract
    from threading import Thread
    import queue
    import datetime
    from ibapi.utils import iswrapper #just for decorator
    from ibapi.common import *
    from ibapi.contract import *
    from ibapi.ticktype import *
    
    class TestApp(wrapper.EWrapper, EClient):
    
    def __init__(self):
        wrapper.EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)
    
    
    @iswrapper
    def historicalData(self, reqId:int, bar: BarData):
        print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open,
              "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
              "Count:", bar.barCount, "WAP:", bar.average)
        if  all_data.iloc[reqId,7] == 0:
            all_data.iloc[reqId,7] = bar.close
        # the line below is not necessary
        #self.done = True
    
    @iswrapper
    def historicalDataEnd(self, reqId: int, start: str, end: str):
        super().historicalDataEnd(reqId, start, end)
        print("HistoricalDataEnd ", reqId, "from", start, "to", end)
        print('=========End round : ',app.i+1,'with time :',time() - app.t,'==============')
    
        app.i++
        if app.i==len(all_data):
            app.disconnect() # Disconnect here: get out of app.run() when all data processed
        else:
            # add some sleep here if necessary
            reqNext()
    
    
    @iswrapper
    def historicalDataUpdate(self, reqId: int, bar: BarData):
        print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open,
              "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
              "Count:", bar.barCount, "WAP:", bar.average)
    
    
    def reqNext():
        print('====================round : ',app.i+1,'===============================')
        contract = Contract()
        contract.symbol = all_data.iloc[app.i,0]
        contract.secType = all_data.iloc[app.i,1]
        contract.currency = all_data.iloc[app.i,3]
        contract.exchange = all_data.iloc[app.i,2]
        app.reqHistoricalData(app.i, contract, "","1 W", "1 day", "Adjusted_Last", 1, 1, False, []) 
    
    
    def main():
        app = TestApp()
        app.connect("127.0.0.1", 7496, clientId=1234)
        print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime()))
    
        app.i = 0
        app.t = time()
        reqNext()
        app.run()
        # when we arrive here, app is disconnected already
    
    
    if __name__ == "__main__":
        main()
    

    非常感谢Janos,这真的帮助了我,我已经改变了这一点,这是工作

    谢谢你的建议我会改进的

    因为你的代码有一些bug,所以我让它可以运行

    from ibapi import wrapper
    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.contract import Contract as IBcontract
    from threading import Thread
    import queue
    import datetime
    from ibapi.utils import iswrapper #just for decorator
    from ibapi.common import *
    from ibapi.contract import *
    from ibapi.ticktype import *
    
    class TestApp(wrapper.EWrapper, EClient):
    
        def __init__(self):
            wrapper.EWrapper.__init__(self)
            EClient.__init__(self, wrapper=self)
    
    
        @iswrapper
        def historicalData(self, reqId:int, bar: BarData):
            print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open,
                  "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
              "Count:", bar.barCount, "WAP:", bar.average)
            if  all_data.iloc[reqId,7] == 0:
                all_data.iloc[reqId,7] = bar.close
        # the line below is not necessary
        #self.done = True
    
        @iswrapper
        def historicalDataEnd(self, reqId: int, start: str, end: str):
            super().historicalDataEnd(reqId, start, end)
            print("HistoricalDataEnd ", reqId, "from", start, "to", end)
            print('=========End round : ',self.i+1,'with time :',time() - self.t,'==============')
    
            self.i = self.i+1
            if self.i==len(all_data):
                self.disconnect() # Disconnect here: get out of app.run() when all data processed
            else:
            # add some sleep here if necessary
                reqNext(self.i,self)
    
    
        @iswrapper
        def historicalDataUpdate(self, reqId: int, bar: BarData):
            print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open,
                  "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
                  "Count:", bar.barCount, "WAP:", bar.average)
    
    
    def reqNext(i,app):
            print('====================round : ',i+1,'===============================')
            contract = Contract()
            contract.symbol = all_data.iloc[i,0]
            contract.secType = all_data.iloc[i,1]
            contract.currency = all_data.iloc[i,3]
            contract.exchange = all_data.iloc[i,2]
            app.reqHistoricalData(i, contract, "","1 W", "1 day", "Adjusted_Last", 1, 1, False, []) 
    
    
    def main():
        app = TestApp()
        app.connect("127.0.0.1", 7496, clientId=1234)
        print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime()))
        app.i = 0
        app.t = time()
        reqNext(app.i,app)
        app.run()
        # when we arrive here, app is disconnected already
    
    
    if __name__ == "__main__":
        main()
    

    非常感谢Janos,这真的帮助了我,我已经改变了这一点,这是工作

    谢谢你的建议我会改进的

    因为你的代码有一些bug,所以我让它可以运行

    from ibapi import wrapper
    from ibapi.client import EClient
    from ibapi.wrapper import EWrapper
    from ibapi.contract import Contract as IBcontract
    from threading import Thread
    import queue
    import datetime
    from ibapi.utils import iswrapper #just for decorator
    from ibapi.common import *
    from ibapi.contract import *
    from ibapi.ticktype import *
    
    class TestApp(wrapper.EWrapper, EClient):
    
        def __init__(self):
            wrapper.EWrapper.__init__(self)
            EClient.__init__(self, wrapper=self)
    
    
        @iswrapper
        def historicalData(self, reqId:int, bar: BarData):
            print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open,
                  "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
              "Count:", bar.barCount, "WAP:", bar.average)
            if  all_data.iloc[reqId,7] == 0:
                all_data.iloc[reqId,7] = bar.close
        # the line below is not necessary
        #self.done = True
    
        @iswrapper
        def historicalDataEnd(self, reqId: int, start: str, end: str):
            super().historicalDataEnd(reqId, start, end)
            print("HistoricalDataEnd ", reqId, "from", start, "to", end)
            print('=========End round : ',self.i+1,'with time :',time() - self.t,'==============')
    
            self.i = self.i+1
            if self.i==len(all_data):
                self.disconnect() # Disconnect here: get out of app.run() when all data processed
            else:
            # add some sleep here if necessary
                reqNext(self.i,self)
    
    
        @iswrapper
        def historicalDataUpdate(self, reqId: int, bar: BarData):
            print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open,
                  "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
                  "Count:", bar.barCount, "WAP:", bar.average)
    
    
    def reqNext(i,app):
            print('====================round : ',i+1,'===============================')
            contract = Contract()
            contract.symbol = all_data.iloc[i,0]
            contract.secType = all_data.iloc[i,1]
            contract.currency = all_data.iloc[i,3]
            contract.exchange = all_data.iloc[i,2]
            app.reqHistoricalData(i, contract, "","1 W", "1 day", "Adjusted_Last", 1, 1, False, []) 
    
    
    def main():
        app = TestApp()
        app.connect("127.0.0.1", 7496, clientId=1234)
        print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime()))
        app.i = 0
        app.t = time()
        reqNext(app.i,app)
        app.run()
        # when we arrive here, app is disconnected already
    
    
    if __name__ == "__main__":
        main()
    

    你能告诉我到底是什么问题吗?我知道你想下载历史数据,但你没有告诉我出了什么问题。你没有得到数据吗?还是有错误?您也可以分享您发送给IB的问题。我无法从安检中弄清楚