ib-api-reloaded / ib_async

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

Updating ib.reqPnL method to avoid AssertionError in case of repetitive calls #56

Open praditik opened 3 months ago

praditik commented 3 months ago

Earlier, an assert statement assert key not in self.wrapper.pnlKey2ReqId was causing the AssertionError when reqPnL is called second time for same set of inputs. This update avoids the error and returns existing PnL class object if already subscribed.

Minimum reproducible example

from ib_async import IB
import time
ib = IB()
account = "DUXXXXXXX"
ib.connect(clientId=5)
ib.sleep()
data=ib.reqPnL(account)
ib.sleep()
#Do something with data and for whatever reason, call ib.reqPnL again
data = ib.reqPnL(account) #This line causes the error
ib.sleep()

This creates error as follows

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\algoBot\pnlTrial.py", line 11, in <module>
    data = ib.reqPnL(account)
           ^^^^^^^^^^^^^^^^^^
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\ib_async\ib.py", line 951, in reqPnL
    assert key not in self.wrapper.pnlKey2ReqId
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

Even though calling ib.reqPnL() multiple times is not a sensible choice, this can be done accidentally by someone assuming ib.reqPnL to have same behavior as reqMktData or other requests. These other request methods generate no error and hence the reqPnL should also be consistent with other methods.

Hence, proposing the change.