Cancel a pending order
kite.cancel_order(variety="regular", order_id=order_id)
Same terminal-state constraint as modify (chapter 54) — you can only cancel an order that's still OPEN or TRIGGER PENDING. Cancelling an already-COMPLETE order raises OrderException.
Cancel-and-verify pattern
def cancel_and_confirm(kite, order_id: str, variety="regular", timeout_s=5) -> bool:
try:
kite.cancel_order(variety=variety, order_id=order_id)
except OrderException as e:
logging.warning(f"Cancel request failed, checking actual state: {e}")
result = poll_order_status(kite, order_id, timeout_s=timeout_s)
return result["status"] == "CANCELLED"
The except branch matters: a cancel can fail because the order *just* filled a moment before your cancel reached the exchange — that's not a bug in your code, it's an inherent race in any resting-order system. Always re-check actual status after a cancel attempt rather than trusting the call's success/failure alone.
Cancelling all open orders — a common "get out safely" operation
def cancel_all_open_orders(kite):
open_orders = [o for o in kite.orders() if o["status"] in ("OPEN", "TRIGGER PENDING")]
for o in open_orders:
try:
kite.cancel_order(variety=o["variety"], order_id=o["order_id"])
except OrderException:
pass # likely filled/cancelled between the list and this call — fine
return len(open_orders)
This is a building block for the kill switch (chapter 90) — a manual or automatic "stop everything" action should cancel all resting orders as one of its first steps, before deciding whether to also square off open positions.
Cancelling one leg of a multi-order strategy without affecting the other
If you've placed both a target limit sell and a stop-loss SL-M for the same position (chapter 51's manual bracket pattern), filling either one should trigger cancelling the other (an "OCO" — one-cancels-other — pattern). Kite Connect has no native OCO order type; you implement it yourself by watching order updates (chapter 53) and calling cancel_order() on the sibling the moment one leg completes.