0

我想使用数据框来存储我的投资组合信息并每分钟更新一次。但是下面的代码结果是空的,我错过了什么吗?

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
import pandas as pd
import time


class IBapi(EWrapper, EClient):


    def __init__(self):
        EClient.__init__(self, self)
        self.all_positions = pd.DataFrame([], columns=['ConID', 'Symbol', 'Quantity', 'Average Cost', 'MarketPrice', 'marketValue', 'unrealizedONL', 'realizedPNL'])

    def updatePortfolio(self, contract: Contract, position: float, marketPrice: float, marketValue: float,averageCost: float, unrealizedPNL: float, realizedPNL:float, accountName:str):
        super().updatePortfolio(contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName)
        index = str(contract.conId)
        self.all_positions.loc[index] = contract.conId, contract.symbol, position, averageCost, marketPrice, marketValue, unrealizedPNL, realizedPNL


def main():

    app = IBapi()
    app.connect('127.0.0.1', 7497, 0)
    app.reqAccountUpdates(True, "XXXXXXXX")
    current_positions = app.reqAccountUpdates(True, "XXXXXXX")

    app.run()
    print(current_positions.to_string())
    app.disconnect()

if __name__ == "__main__":
    main()
4

1 回答 1

0

reqAcccountUpdates是一个异步函数调用——它发送一个传出消息但不等待响应。(由于消息发起了对数据流的订阅,因此返回的不是单个响应,而是一系列响应)。

所以current_positions在:

current_positions = app.reqAccountUpdates(True, "XXXXXXX")

将永远是无。相反,响应app.all_positions由覆盖的updatePortfolio()函数存储。

此外,run()循环是一个无限循环,因此之后的行将不会执行。最常见的这种类型的架构将由 python futures/asyncio 模块(如在ib_insync库中)或运行循环的附加线程处理。

于 2020-07-06T20:08:39.303 回答