Sub topic 12
Order States from Submission to Completion
Every order on a centralized exchange moves through a set of states, from the moment you submit it to the moment it is finished. Reading these states correctly tells you what to expect next and what you can still change. This chapter assumes you know what limit and market orders are, how the matching engine fills them, and what partial fills and time in force mean. It also assumes you can read simple Python.
Why states matter
An order is not a single event. It is a record that changes over time. Your client, the exchange's API, and the matching engine each hold a view of that record, and these views can briefly disagree. If you know the possible states and the legal moves between them, you can answer practical questions:
- Is my order still on the book, or is it done?
- How much of it has filled, and how much is left?
- Can I still cancel it?
- Why did a position or balance change when I saw no confirmation?
Exact names differ between exchanges. One exchange writes NEW, another writes open or live. The ideas below hold across them, so check your exchange's API documentation for its exact labels.
The common states
| State | Meaning | Still on the book? | Final? |
|---|---|---|---|
| Pending (or received) | The exchange has accepted the message but has not yet placed it in the matching engine | No | No |
| Open (or new) | The order rests on the book with its full quantity unfilled | Yes | No |
| Partially filled | Some quantity has traded and the rest still rests on the book | Yes | No |
| Filled | The full quantity has traded | No | Yes |
| Canceled | You or the exchange removed the unfilled remainder | No | Yes |
| Rejected | The exchange refused the order and it never reached the book | No | Yes |
| Expired | The order's time in force ran out before it filled | No | Yes |
A final state is also called a terminal state. Once an order is terminal, it never changes again. You cannot cancel a filled order, and you cannot revive a canceled one. To trade again you submit a new order with a new identifier.
How an order moves between states
The diagram shows the normal paths. Notice that only the open and partially filled states can still change.
Several paths deserve a closer look.
Immediate fills skip the resting state
A market order, or a limit order that crosses the spread, matches as soon as the engine processes it. It may go from pending straight to filled. It never rests on the book, so there is nothing to cancel by the time you could react.
Partially filled is a real state, not an error
If a limit buy for 4 units meets only 2 units at an acceptable price, 2 units fill and 2 units rest. The order is partially filled and still active. Its average fill price covers only the traded part. The resting part can still fill later, at your limit price or better.
Canceling a partly filled order keeps the fills
Canceling removes only the unfilled remainder. The trades that already happened stay. The final state is usually reported as canceled, and the order carries a nonzero filled quantity. Some exchanges label this "partially filled, canceled." Always check the filled quantity before assuming a canceled order did nothing.
Time in force decides the ending
Time in force sets how an order ends when it does not fully fill:
- GTC (good till canceled) stays open until it fills or you cancel it.
- IOC (immediate or cancel) fills what it can at once, then the rest is canceled or expired.
- FOK (fill or kill) either fills completely at once or is canceled with no fills.
So an IOC order that fills 3 of 5 units ends in a terminal state with 3 units filled and 2 units not filled. It does not rest.
Rejections happen before the book
An exchange rejects an order when it fails a check. Common reasons are:
- Insufficient balance.
- A price that breaks the exchange's tick size (the smallest allowed price step).
- A quantity below the minimum order size.
- A post-only order that would have crossed the spread and taken liquidity.
- A price too far from the market, under a price-band rule.
A rejected order has zero fills and never touched the book.
Tracking an order in code
The following program models an order and enforces the legal transitions. It also keeps the filled quantity and average fill price up to date as fills arrive. It is a teaching model, not an exchange client.
from enum import Enum
class State(Enum):
PENDING = "pending"
OPEN = "open"
PARTIALLY_FILLED = "partially_filled"
FILLED = "filled"
CANCELED = "canceled"
REJECTED = "rejected"
EXPIRED = "expired"
TERMINAL = {State.FILLED, State.CANCELED, State.REJECTED, State.EXPIRED}
ALLOWED = {
State.PENDING: {State.OPEN, State.PARTIALLY_FILLED, State.FILLED, State.REJECTED,
State.CANCELED, State.EXPIRED},
State.OPEN: {State.PARTIALLY_FILLED, State.FILLED, State.CANCELED, State.EXPIRED},
State.PARTIALLY_FILLED: {State.PARTIALLY_FILLED, State.FILLED, State.CANCELED,
State.EXPIRED},
}
class Order:
def __init__(self, qty):
self.qty = qty
self.filled = 0.0
self.notional = 0.0 # sum of price * size over all fills
self.state = State.PENDING
def _move(self, new_state):
if self.state in TERMINAL:
raise ValueError(f"order is final in state {self.state.value}")
if new_state not in ALLOWED[self.state]:
raise ValueError(f"cannot go from {self.state.value} to {new_state.value}")
self.state = new_state
def accept(self):
self._move(State.OPEN)
def reject(self):
self._move(State.REJECTED)
def fill(self, price, size):
if size <= 0 or self.filled + size > self.qty + 1e-12:
raise ValueError("invalid fill size")
self.filled += size
self.notional += price * size
done = abs(self.qty - self.filled) < 1e-12
self._move(State.FILLED if done else State.PARTIALLY_FILLED)
def cancel(self):
self._move(State.CANCELED)
@property
def remaining(self):
return self.qty - self.filled
@property
def avg_price(self):
return self.notional / self.filled if self.filled else None
order = Order(4.0)
order.accept()
order.fill(100.0, 2.0)
print(order.state.value, order.remaining, order.avg_price) # partially_filled 2.0 100.0
order.fill(100.5, 1.0)
print(order.state.value, order.remaining, order.avg_price) # partially_filled 1.0 100.16666666666667
order.cancel()
print(order.state.value, order.filled, order.avg_price) # canceled 3.0 100.16666666666667
try:
order.fill(100.5, 1.0)
except ValueError as err:
print(err) # order is final in state canceledTwo details in this code mirror real systems. The average price comes from total traded value divided by total filled quantity, so it updates correctly across many fills. A terminal order refuses further changes.
Cancel requests are asynchronous
A cancel is a request, not an instant change. Between the moment you send it and the moment the engine processes it, your order can still be matched. This produces a race.
The result is that you meant to cancel and instead you traded. This is normal behavior, not a bug. Your code must handle it:
- Treat a "cancel accepted" message as the only proof that a cancel worked.
- Treat a "too late" or "unknown order" reply as a prompt to query the order's current state.
- Never assume a canceled request means zero fills until the final report arrives.
Reading states through the API
Exchanges usually give you two ways to learn an order's state.
- Polling: you ask for the order by its identifier. It is simple but can be slow and can hit rate limits.
- Streaming: the exchange pushes updates over a WebSocket (a long-lived two-way connection). Updates arrive quickly but can be missed if the connection drops.
A reliable client uses both. It listens to the stream for speed, and it polls to reconcile (compare its local record with the exchange's record) after a reconnect.
Use a client order ID
Most exchanges let you attach your own identifier, often called a client order ID, to each order. Suppose your network request times out. You do not know whether the exchange received the order. If you resend without care, you may create a duplicate. With a client order ID, you can look up the order by that ID first. If it exists, you do not resend. Many exchanges also reject a second order that reuses the same ID, which protects you from accidental duplicates.
Unknown outcomes
A timeout leaves an order in an unknown state from your side. The safe procedure is:
- Do not resend yet.
- Query by client order ID.
- If the exchange has the order, adopt its state.
- If the exchange does not have the order after the query succeeds, you may resend.
Edge cases to watch
- Out-of-order messages. A stream can deliver a fill report before the acceptance report. Use the exchange's sequence number or timestamp, not arrival order, when you can.
- Duplicate messages. After a reconnect you may receive the same fill twice. Track each trade's identifier and ignore repeats, or your filled quantity will be too high.
- Rounding. Sizes in floating-point numbers can leave a tiny remainder such as 0.0000000001 after what should be a full fill. Use the exchange's decimal strings or the
decimalmodule for real money, and compare with a tolerance only in toy code. - Self-expiring orders. A day order or an order with an expiry time moves to expired without any action from you. Your record must handle changes you did not trigger.
- Stop orders have an extra stage. A stop order waits in a triggered-or-not condition before it becomes a live order. Until the stop price is reached, it is typically held off the book, and your exchange may show a state such as "untriggered." After it triggers, it follows the normal path above as a market or limit order.
- Exchange-initiated cancels. An exchange may cancel your orders during maintenance, after a self-trade prevention rule fires, or when you lose margin. The final state is canceled, but you did not ask for it.
Putting it together
Consider a limit buy for 4 units at 100.5, submitted as GTC, against asks of 2 units at 100.0, 3 units at 100.5, and 5 units at 101.0.
- The order arrives and passes validation.
- It crosses the spread, so it matches at once: 2 units at 100.0, then 2 units at 100.5.
- All 4 units fill, so the order goes from pending to filled with an average price of 100.25.
- It never rests on the book, so no cancel is possible.
Now change the limit price to 100.2. Only the 100.0 level qualifies. The order fills 2 units and the remaining 2 units rest as a bid. The state is partially filled. If you then cancel, the final state is canceled with 2 units filled. If you had sent the same order as IOC, the remaining 2 units would not rest, and the order would end with 2 units filled and no open remainder.
Exercise
You send a cancel for a resting buy order of 5 units. Your cancel reply says "order already filled," and your account shows 5 more units than before. Was this a bug, and what should your client have done before reporting the order as canceled?
Show answer
It was not a bug. The cancel was a request, and the resting order was matched before the engine processed it, so the order reached the terminal state filled. Your client should have treated only a "cancel accepted" reply as proof of cancellation, queried the order's state after the "too late" reply, and recorded it as filled with 5 units traded.
Exercise
A limit sell for 6 units at 99.0 is submitted as IOC. The bid side holds 2 units at 99.5 and 1 unit at 99.0, then lower prices. What is the filled quantity, the average fill price, and the final state of the order?
Show answer
The order can trade against bids at 99.0 or higher, so it fills 2 units at 99.5 and 1 unit at 99.0, for 3 units total. The average price is (2 x 99.5 + 1 x 99.0) / 3 = 298.0 / 3, which is about 99.33. IOC does not let the remaining 3 units rest, so they are canceled or expired. The order ends in a terminal state with 3 units filled.
Exercise
Your client sends a new order and the request times out with no reply. Describe the steps you take before deciding whether to send it again, and name the field that makes this safe.
Show answer
Do not resend at once. Query the exchange for an order with the client order ID you attached. If the exchange returns the order, adopt its state and do not resend. If the query succeeds and finds no such order, you can resend. The client order ID lets you identify the order without relying on an exchange-assigned ID you never received, and it often blocks duplicates.