If you want to cancel one of your orders that are not completely filled yet, you need to follow these steps:
Step 1: Determine the order's external ID
To successfully cancel one of your orders, you need the order's ID that the order book has assigned. You can find it in the externalOrderId field of the data returned by the and API endpoints (see for details).
The external order ID is a 64 bit integer that will serve as the only argument to the cancel function.
Step 2: Send the cancellation request
Next, you need to call one of the cancel functions of the order book smart contract. Depending on whether the order that you want to cancel is a buy or a sell order, you need to call cancelBuyOrder or cancelSellOrder, respectively.
You can use the following code snippet to cancel a buy order:
order_book_address = '0x456789abcdef123' # the address of the order book contract
order_book_contract = w3.eth.contract(address=order_book_address, abi=order_book_abi) # load the order book contract
cancel_buy_order_tx = order_book_contract.functions.cancelBuyOrder(externalOrderId).buildTransaction({'from': my_wallet}) # build the buy order transaction
signed_tx = w3.eth.account.sign_transaction(cancel_buy_order_tx, private_key=my_private_key) # sign the transaction with your private key
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) # send the transaction
w3.eth.wait_for_transaction_receipt(tx_hash) # wait for the transaction to go through
Code snippet to cancel a sell order:
order_book_address = '0x456789abcdef123' # the address of the order book contract
order_book_contract = w3.eth.contract(address=order_book_address, abi=order_book_abi) # load the order book contract
cancel_sell_order_tx = order_book_contract.functions.cancelSellOrder(externalOrderId).buildTransaction({'from': my_wallet}) # build the buy order transaction
signed_tx = w3.eth.account.sign_transaction(cancel_sell_order_tx, private_key=my_private_key) # sign the transaction with your private key
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) # send the transaction
w3.eth.wait_for_transaction_receipt(tx_hash) # wait for the transaction to go through
Note that due to the inner workings of the blockchain, it can take a couple of seconds after you sent your cancellation request until your order is shown as cancelled.