Order Cancelation
This example demonstrates how to cancel an order on the 21X platform. It involves using the REST client to retrieve the user’s open orders, extracting the orderId, initializing the OrderBook class, and canceling the order.
Steps to Cancel an Order
Initialize the REST API Client
Use the REST client to fetch the open orders associated with your wallet.
from x21_sdk import Client
# Initialize the REST client with authentication
client = Client()Fetch Open Orders
Retrieve the list of open orders for your wallet using getWalletOrders.
from x21_sdk.client.api.order import get_wallet_orders
from x21_sdk.client.models import OrderStatusEnum, OrderKindEnum
wallet_address = "0xYourWalletAddress"
wallet_orders = get_wallet_orders.sync(
client=client,
wallet_address=wallet_address,
only_open=True, # Ensure only open orders are retrieved
)
# Display open orders
for order in wallet_orders.items:
print(order)
selected_order = next(
order
for order in wallet_orders.items
if order.status == OrderStatusEnum.OPEN and order.order_kind == OrderKindEnum.BUY
)
# Select an order ID to cancel
trading_pair_id = selected_order.trading_pair_id
order_id_to_cancel = selected_order.external_order_idRetrieve OrderBook Address
Use the getTradingPair endpoint to retrieve general information for the selected trading pair.
from x21_sdk.client.api.public_market_data import get_trading_pair
trading_pair = get_trading_pair.sync(
client=client,
id=trading_pair_id,
)
orderbook_address = trading_pair.smart_contract_order_bookInitialize the OrderBook Class
OrderBook ClassUse the orderbook_address (of the trading_pair) to initialize the OrderBook class for smart contract interaction.
from x21_sdk import OrderBook
# fetch orderbook_address via the trading_pair_id
# Initialize the OrderBook with Web3 provider and contract address
order_book = OrderBook(
private_key="your_private_key",
orderbook_addr=orderbook_address,
rpc_url="https://polygon-mainnet.g.alchemy.com/v2/YOUR_API_KEY",
)Cancel the Order
Use the cancel_buy_order or cancel_sell_order method, depending on the type of order you wish to cancel.
# Example: Cancel a buy order
order_book.cancel_buy_order(order_id=order_id_to_cancel)
print(f"Order canceled successfully!")Summary of Workflow
Use the REST API client to fetch open orders for your wallet via
getWalletOrders.Extract the
orderIdand correspondingtrading_pair_idfrom the response.Fetch the trading_pair information to get the corresponding
orderbook_address.Initialize the
OrderBookclass with the retrieved address.Cancel the specified order using the appropriate
OrderBookmethod.
Last updated

