ib-api-reloaded / ib_async

Python sync/async framework for Interactive Brokers API (replaces ib_insync)
BSD 2-Clause "Simplified" License
412 stars 64 forks source link

laggy portfolio pnl #69

Open noob-tubem opened 1 month ago

noob-tubem commented 1 month ago

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?

mattsta commented 1 month ago

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: