Ibpy:如何捕获从reqAccountSummary返回的数据

时间:2017-11-07 06:57:51

标签: python-3.x ibpy

我正在使用来自交互式经纪人的ibapi,我一直坚持如何捕获返回的数据。例如,根据api docs,当我请求reqAccountSummary()时,该方法通过accountSummary()传递数据。但他们的例子只打印数据。我已经尝试捕获数据或将其分配给变量,但没有在他们的文档中显示如何执行此操作。我也谷歌搜索,只找到register()和registerAll(),但这是来自ib.opt,这不是最新的工作ibapi包。

这是我的代码。你能告诉我如何修改accountSummary()来捕获数据吗?

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.common import *
class TestApp(EWrapper,EClient):
    def __init__(self):
        EClient.__init__(self,self)

    # request account data:
    def my_reqAccountSummary1(self, reqId:int, groupName:str, tags:str):
        self.reqAccountSummary(reqId, "All", "TotalCashValue")


    # The received data is passed to accountSummary()
    def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str):
        super().accountSummary(reqId, account, tag, value, currency)
        print("Acct# Summary. ReqId>:", reqId, "Acct:", account, "Tag: ", tag, "Value:", value, "Currency:", currency)
        return value  #This is my attempt which doesn't work


def main():
    app = TestApp()
    app.connect("127.0.0.1",7497,clientId=0)

    app.my_reqAccountSummary1(8003, "All", "TotalCashValue")  #"This works, but the data is print to screen. I don't know how to assign the received TotalCashValue to a variable"

    # myTotalCashValue=app.my_reqAccountSummary1(8003, "All", "TotalCashValue")  #"My attempt doesn't work"
    # more code to stop trading if myTotalCashValue is low

    app.run()

if __name__=="__main__":
    main()

1 个答案:

答案 0 :(得分:1)

您不能在main函数中执行此操作,因为app.run会侦听来自TWS的响应。一旦你按照正确的方式设置了所有回调,主函数将永远在app.run中循环。

您必须将代码直接放入accountSummary函数中。这就是这些程序的工作方式,您可以直接使用逻辑  回调函数。您始终可以指定self.myTotalCashValue = value以使其可用于班级的其他部分,甚至可用于其他线程。

- 或 -

您在线程中运行app.run并等待值返回,例如

self._myTotalCashValue = value添加到a​​ccountSummary,导入threadingtime,然后在main中添加以下内容:

t = threading.Thread(target=app.run)
t.daemon = True
t.start()
while not hasattr(app,"_myTotalCashValue"):
    time.sleep(1)
print(app._myTotalCashValue)

与线程一样,您必须对appmain之间的共享内存稍微小心。