0

我试图将 IB 头寸/账户值导出到数据框中,以便在 python 中进行进一步处理。但未能弄清楚如何实现这一目标。任何人都可以帮忙吗?

import pandas as pd
import numpy as np 
import time 

import ibapi
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
import threading
import sys
import queue

from ibapi.contract import Contract

class MyWrapper(EWrapper):
#@property        
    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)
        if (len(contract.symbol)<5) & (contract.secType == 'STK'):
            new_symbol = contract.symbol.zfill(5)
        else:
            new_symbol = contract.symbol
        print (contract.secType, contract.exchange, new_symbol, "Position:", position, "MarketPrice:", marketPrice, "MarketValue:", marketValue, "AverageCost:", averageCost, "UnrealizedPNL:", unrealizedPNL, "RealizedPNL:", realizedPNL)

accountName = '' 
callback = MyWrapper() # wrapper = MyWrapper()
#Instntiate My Wrapper.callback
tws = EClient(callback) # app = EClient(wrapper)
  #Instantiate EClient and return data to call back
host = '127.0.0.1'
port = 4001
clientID = 8
tws.connect(host, port, clientID)                 

print("serverVersion:%s connectionTime:%s" %     (tws.serverVersion(), tws.twsConnectionTime()))
print(tws.isConnected())

    tws.reqAccountUpdates(1, accountName)
time.sleep(2)
tws.run()
accvalue = pd.DataFrame(callback.updatePortfolio, columns = ['Symbol','Position','MarketPrice','MarketValue',
                            'AverageCost', 'UnrealisedPnL', 'RealisedPnL'])
#accvalue = callback.updateAccountValue
print ('Account: \n' + accvalue)
4

1 回答 1

0

你在正确的轨道上。您需要在包装器内设置队列类对象,以收集来自您正在调用的客户端函数的响应。然后,您可以对数据做任何您想做的事情。看看这个博客 --> https://qoppac.blogspot.com/2017/03/interactive-brokers-native-python-api.html

那里有一些代码可以重用以帮助实现。

于 2019-05-07T01:47:46.970 回答