Get_position() & close_all_positions() problems on ibridgepy

I got two questions:

  1. Why get_position(context.security) return INFO: position: 0, I just filled an order of 1 MES, it should be 1 instead?
  2. Why did close_all_positions() fail to close my holding of 1 MES contract?
def initialize(context):
    context.place_order=True
    context.security = superSymbol(secType='FUT', symbol='MES', currency='USD', expiry='202509', exchange = 'CME')
    
def handle_data(context, data):
    if context.place_order:               
        order_target(context.security, 1)
        position = get_position(context.security)
        log.info(f" position: {position.amount}")
        close_all_positions()
        context.place_order=False
        end()

try:
    log
except NameError:
    class Logger:
        def info(self, msg):
            print(f"INFO: {msg}")
        def warn(self, msg):
            print(f"WARN: {msg}")
    log = Logger()

On my TWS, I found 1 MES successfully bought, but failed to be closed by close_all_positions(). On the other hand, i got the log on console as following:

Try to get connected to Interactive Brokers
Connected to Interactive Brokers
IBridgePy version 22.1.1
fileName = Quantra-IBridgePy\*************.py
####    Starting to initialize trader    ####
##    ACCOUNT Balance  DU*******  ##
CASH=999420.54
portfolio_value=999631.19
positions_value=0.0
##    NO ANY POSITION    ##
##    NO any order    ##
####    Initialize trader COMPLETED    ####
INFO:  position: 0
Try to get connected to Interactive Brokers
Quantra-IBridgePy\Place_and_Cancel_Orders\example_place_market_and_limit_order.py END

Hi,

One issue can be timing here. Before the code gets confirmation of the order being filled, it is moving towards checking the position. Try running only the get_position code and check output.
If this does not work, you can check the connection if it is correct.
Hope this helps.

Thanks, Rekhit. That’s keen observation. Timimg makes so much sense. I will tweak my codes and re-test it.