我试图将 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)