Search code examples
pythontwsib-api

Why can't I print the quantity of stock held using (IBKR's TWS) ib-api positions function? (partly solved)


I am trying to use the quantity of a particular stock held as a variable.

My relevant code is:

    def position(self, account, contract, position, avgCost):
        super().position(account, contract, position, avgCost)
        print(contract, position)
        # self.quantity_held = position
        # if contract == 'applestock_contract':
        #     self.quantity_held = position
        if contract == app.applestock_contract:
            self.applestock_quantity_held = position # this was previously just "position", no "app."
        # if contract == 'app.applestock_contract':
        #     self.quantity_held = position

I have commented other bits of code that I have tried.

When I try to print the value of applestock_contract, it comes out as 0 (but this is incorrect).


Solution

  • One approach is to define the contract by features of the contract e.g.

    if contract.symbol == 'APPL':
        self.applestock_quantity_held = position