erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.75k stars 723 forks source link

Troubles with cancelOrder #690

Open enricoangelelli opened 5 months ago

enricoangelelli commented 5 months ago

Hello, I ran this notebook and it looks like I got troubles with ib.cancelOrder(order). The following code produced the reported output. Although the order is canceled anyway, the error is sometimes blocking for the cells that follow, if any, in a seemingly random way I could not figure out. By the way, errorCode 10147 is not documented in TWS API

import ib_insync
ib_insync.util.startLoop()
ib = ib_insync.IB()
ib.connect('127.0.0.1', 7497, clientId=5)
contract = ib_insync.Stock('AMZN','SMART','USD')
ib.qualifyContracts(contract)
print(contract)
qty = 30
price = 168.5
order = ib_insync.LimitOrder('SELL',qty,price * 1.05)
trade = ib.placeOrder(contract, order)
ib.sleep(4)
print(trade.order.orderId,trade.orderStatus.status)
ib.cancelOrder(order);
ib.sleep(1)
print(ib.openTrades())
print(trade.log)
ib.disconnect()
Stock(conId=3691937, symbol='AMZN', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='AMZN', tradingClass='NMS')
Error 10147, reqId 902: OrderId 902 that needs to be cancelled is not found.
Canceled order: Trade(contract=Stock(conId=3691937, symbol='AMZN', exchange='SMART', primaryExchange='NASDAQ', currency='USD', localSymbol='AMZN', tradingClass='NMS'), order=LimitOrder(orderId=902, clientId=5, action='SELL', totalQuantity=30, lmtPrice=176.925), orderStatus=OrderStatus(orderId=902, status='Cancelled', filled=0.0, remaining=0.0, avgFillPrice=0.0, permId=0, parentId=0, lastFillPrice=0.0, clientId=0, whyHeld='', mktCapPrice=0.0), fills=[], log=[TradeLogEntry(time=datetime.datetime(2024, 2, 5, 16, 3, 20, 779512, tzinfo=datetime.timezone.utc), status='PendingSubmit', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 2, 5, 16, 3, 24, 796915, tzinfo=datetime.timezone.utc), status='PendingCancel', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 2, 5, 16, 3, 24, 797860, tzinfo=datetime.timezone.utc), status='Cancelled', message='Error 10147, reqId 902: OrderId 902 that needs to be cancelled is not found.', errorCode=10147)], advancedError='')
902 PendingSubmit
[]
[TradeLogEntry(time=datetime.datetime(2024, 2, 5, 16, 3, 20, 779512, tzinfo=datetime.timezone.utc), status='PendingSubmit', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 2, 5, 16, 3, 24, 796915, tzinfo=datetime.timezone.utc), status='PendingCancel', message='', errorCode=0), TradeLogEntry(time=datetime.datetime(2024, 2, 5, 16, 3, 24, 797860, tzinfo=datetime.timezone.utc), status='Cancelled', message='Error 10147, reqId 902: OrderId 902 that needs to be cancelled is not found.', errorCode=10147)]

Thank you in advance for any help. Best, Enrico