Requesting Portfolio Data

View as MarkdownOpen in Claude

Requesting portfolio data requires the use of the reqAccountUpdates() function which returns data via the updateAccountValue(), updatePortfolio(), and the updateAccountTime() callback functions.

The accountDownloadEnd() callback function runs when all account information has been returned.

Comprehensive example code for C++, C#, Java, Python and Visual Basic can be found in the /samples directory of the downloaded TWS API file.

Python
1from ibapi.client import EClient
2from ibapi.wrapper import EWrapper
3from ibapi.contract import Contract
4import time
5import threading
6
7port = 4002
8
9class TestApp(EWrapper, EClient):
10 def __init__(self):
11 EClient.__init__(self, self)
12 self.nextOrderId = None
13
14 def error(self, reqId, errorTime, errorCode, errorString, advancedOrderReject=""):
15 print("Error: ", reqId, " ", errorCode, " ", errorString)
16
17 def nextValidId(self, orderId):
18 self.nextOrderId = orderId
19
20 def updatePortfolio(
21 self,
22 contract: Contract,
23 position: float,
24 marketPrice: float,
25 marketValue: float,
26 averageCost: float,
27 unrealizedPNL: float,
28 realizedPNL: float,
29 accountName: str,
30 ):
31 print(
32 "UpdatePortfolio.",
33 "Symbol:",
34 contract.symbol,
35 "SecType:",
36 contract.secType,
37 "Exchange:",
38 contract.exchange,
39 "Position:",
40 position,
41 "MarketPrice:",
42 marketPrice,
43 "MarketValue:",
44 marketValue,
45 "AverageCost:",
46 averageCost,
47 "UnrealizedPNL:",
48 unrealizedPNL,
49 "RealizedPNL:",
50 realizedPNL,
51 "AccountName:",
52 accountName,
53 )
54
55 def updateAccountValue(self, key: str, val: str, currency: str, accountName: str):
56 print(
57 "UpdateAccountValue. Key:",
58 key,
59 "Value:",
60 val,
61 "Currency:",
62 currency,
63 "AccountName:",
64 accountName,
65 )
66
67 def updateAccountTime(self, timeStamp: str):
68 print("UpdateAccountTime. Time:", timeStamp)
69
70 def accountDownloadEnd(self, accountName: str):
71 print("AccountDownloadEnd. Account:", accountName)
72
73
74app = TestApp()
75app.connect("127.0.0.1", port, 0)
76threading.Thread(target=app.run).start()
77time.sleep(1)
78
79app.reqAccountUpdates(True, "")