laggy portfolio pnl
Opened this issue · 1 comments
I am using ib.portfolio() to view the unrealized pnl of each of my positions in real time, but the pnl does not update anywhere near as fast as TWS itself updates - often it takes on the order of minutes to update my position's pnl. Here is a snippet of my code:
`
while True:
# while trading_hours_2(now_dt)
pf_items = []
pf = ib.portfolio()
for pi in pf:
pf_items.append(pi)
for option in pair:
while not option.filled():
ib.sleep(0.3)
c = option.contract
for item in pf_items:
if c.symbol == item.contract.symbol and c.strike == item.contract.strike and c.right == item.contract.right:
match c.right:
case 'C':
call = item
case 'P':
put = item
# print(f"UNREALIZED PNL {call.unrealizedPNL + put.unrealizedPNL}")
now = dt.datetime.now()
now_dt = dt.datetime.strftime(now, "%Y-%m-%d %H:%M:%S")
sec_price = sec_data.marketPrice()
ib.sleep(0.5)
with open(f'{filepath}\\STRANGLES_{now_dt[:10]}.csv', 'a', newline = '') as f:
writer = csvwriter(f, delimiter=',')
writer.writerow([now_dt, call.unrealizedPNL, put.unrealizedPNL, call.unrealizedPNL + put.unrealizedPNL, sec_price])
sec_price = sec_data.marketPrice()
if call.unrealizedPNL + put.unrealizedPNL > tgt:
# if True:
# sell both
ccon = call.contract; ccon.exchange = 'SMART'
pcon = put.contract; pcon.exchange = 'SMART'
ib.placeOrder(ccon, MarketOrder('SELL', 1))
ib.placeOrder(pcon, MarketOrder('SELL', 1))
sys.exit()
ib.sleep(0.5)`
that file write statement shows the same exact pnl for minutes at a time even as I'm watching it update on TWS, and even if I kill the code and restart it it shows the same pnl as before. Is this a problem I can fix or could it be an ibkr problem?
Yeah, that will not show correct results because of how IBKR reports those values.
Short version: you have to compare a live quote against your average cost of each position then calculate your current PnL value if you need updates faster than every couple minutes.
There's a couple problems:
- IBKR provides a
marketPrice
field for each position in your portfolio, but the value only updates maybe once per minute or slower. - subscribing to updates
- you have to manually subscribe to live PnL updates for each position in your portfolio: https://interactivebrokers.github.io/tws-api/pnl.html
- PNL reset time
- the PNL value isn't reset when you close a position.
- if you open a position and close it, then open it again, the PNL won't start at
$0
. It will still consider your old position too.
- account-wide PnL summary reporting
- account-wide DailyPnL and NetLiquidiation reporting is noticeably delayed
- the account "RealizedPnL" and "Unrealized PnL" values are updated in near-real-time.