如何将IB位置数据导出到数据帧?

时间:2019-04-18 16:45:32

标签: python interactive-brokers ib-api

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

1 个答案:

答案 0 :(得分:0)

您处在正确的轨道上。您需要在包装器内部设置队列类对象,以从正在调用的客户端函数中收集响应。然后,您可以对数据进行任何所需的操作。看看这个博客-> https://qoppac.blogspot.com/2017/03/interactive-brokers-native-python-api.html

有些代码可以重复使用以帮助实现。