Order lifecycle

From JoelLewis/finance_skills · View interactive version

Order lifecycle is an AI agent skill from the GitHub repository JoelLewis/finance_skills. Guide the design and implementation of order lifecycle management in trading systems. Owns FIX application-layer message flows (NewOrderSingle, ExecutionReport, cancel/replace) and order state. Use when building an order state machine for an OMS or EMS, handling cancel/replace race conditions, defin

How to use this skill

Skill file

Order Lifecycle

Core Concepts

Order State Machine

The order state machine is the central abstraction in any order management system. It defines every state an order can occupy and every valid transition between states. A correctly implemented state machine prevents impossible transitions (such as filling a canceled order), ensures audit trail completeness, and provides the foundation for order status reporting to clients, counterparties, and regulators.

Canonical order states:

Terminal vs. non-terminal states: Terminal states (Filled, Canceled, Replaced, Rejected, Expired) represent the end of an order's lifecycle — no further transitions are possible. Non-terminal states (New, Pending New, Accepted, Partially Filled, Pending Cancel, Pending Replace, Suspended, Done for Day) may transition to other states. The state machine must enforce the invariant that no transition out of a terminal state is ever permitted.

Valid state transitions (representative, not exhaustive):

State persistence and recovery: The order state must be persisted durably — typically to a database or write-ahead log — before any acknowledgment is sent to the order originator or any action is taken on the order. If the OMS restarts after a crash, it must be able to reconstruct the current state of every active order from persisted state plus any messages received from execution venues during recovery. This requires idempotent message processing (handling duplicate execution reports without double-counting fills) and state reconciliation with venue order status queries.

Order Types

Order types define the execution instructions that govern how an order interacts with the market.

Time-in-Force Instructions

Time-in-force (TIF) instructions specify how long an order remains active before it is automatically canceled or expires.

Behavior at market close: DAY orders are canceled. GTC and GTD orders transition to Done for Day and are reactivated the next trading day. IOC and FOK orders, by definition, will have already been filled or canceled before close. MOC and LOC orders execute during the closing auction. The OMS must correctly handle each TIF at the end-of-day transition, including generating appropriate cancel confirmations for expired DAY orders and updating state for multi-day orders.

Overnight handling: GTC orders that are Done for Day must be resubmitted or reactivated at the venue on the next trading day. Some venues maintain GTC orders natively; others require the OMS to resubmit them each morning. The OMS must track which GTC orders need resubmission and handle the resubmission process as part of the start-of-day workflow.

FIX Protocol Fundamentals

The Financial Information eXchange (FIX) protocol is the dominant standard for electronic trading communication. Understanding FIX is essential for building or integrating with any execution venue, broker, or counterparty.

FIX message types for order flow:

Key FIX tags: The tags that drive OMS state are ClOrdID (11) / OrderID (37) / OrigClOrdID (41) for order identification and chaining, OrdStatus (39) and ExecType (150) for state transitions, and CumQty (14) / LeavesQty (151) / AvgPx (6) for fill accounting. Trust the venue's LeavesQty rather than deriving remaining quantity independently — the two can diverge after partial fills and replacements.

FIX session vs. application layer: FIX operates on two layers: the session layer (connection management, heartbeats, sequence numbers, gap recovery) and the application layer (orders, executions, cancels — the subject of this skill). Session-layer management is owned by the exchange-connectivity skill (trading-operations); a lost session requires reconnection and sequence reconciliation there before application-level messaging can resume.

FIX versions: FIX 4.2 remains widely deployed and is the baseline for many venues. FIX 4.4 added improvements including better support for multi-leg orders and allocation messaging. FIX 5.0 introduced the FIXT transport layer (separating session and application protocols) and added support for market data and post-trade messaging. When connecting to a new venue, confirm which FIX version and which message extensions (if any) the venue supports.

Cancel and Replace Workflows

Cancel and replace workflows are among the most operationally sensitive parts of order lifecycle management. They involve concurrent state changes, race conditions, and the possibility of unexpected outcomes.

Cancel request flow:

  1. The OMS sends an OrderCancelRequest (MsgType=F) to the venue, referencing the OrigClOrdID of the order to cancel and assigning a new ClOrdID to the cancel request.
  2. The order transitions to Pending Cancel in the OMS.
  3. The venue responds with either an ExecutionReport (ExecType=Canceled, OrdStatus=Canceled) confirming the cancel, or an OrderCancelReject (MsgType=9) rejecting the cancel request.
  4. If canceled, the order transitions to Canceled (terminal). If rejected, the order reverts to its prior state (Accepted or Partially Filled).

Replace (amend) request flow:

  1. The OMS sends an OrderCancelReplaceRequest (MsgType=G) to the venue, referencing the OrigClOrdID and providing the amended order parameters (new price, new quantity, or both) with a new ClOrdID.
  2. The order transitions to Pending Replace.
  3. The venue responds with either an ExecutionReport (ExecType=Replaced, OrdStatus=Replaced) confirming the replacement, or an OrderCancelReject rejecting the request.
  4. If replaced, the original order transitions to Replaced (terminal) and a new order is created in the OMS with the amended parameters and the new ClOrdID. If rejected, the original order reverts to its prior state.

Race conditions — cancel vs. fill: The most critical race condition occurs when a cancel request and a fill cross in flight. The OMS sends a cancel request, but before the venue processes it, the order fills (fully or partially). The venue may respond with a fill ExecutionReport followed by an OrderCancelReject (because the order is now filled and cannot be canceled), or with both a fill and a cancel confirmation (if only a partial fill occurred and the remaining quantity was canceled). The OMS must handle all possible message orderings:

Order chaining (ClOrdID to OrigClOrdID linking): Each cancel or replace creates a new link in the order chain. The original order has ClOrdID=A. A replace request references OrigClOrdID=A and assigns ClOrdID=B. A subsequent replace references OrigClOrdID=B and assigns ClOrdID=C. The OMS must maintain this chain to correctly correlate all messages belonging to the same logical order. Breaking the chain — for example, referencing the wrong OrigClOrdID — will cause the venue to reject the request or, worse, cancel or replace the wrong order.

Pending state discipline: While an order is in Pending Cancel or Pending Replace, the OMS should not submit additional cancel or replace requests for the same order. Submitting concurrent cancel/replace requests creates ambiguity about which request the venue is processing and can lead to unexpected outcomes. Queue any new cancel or replace intent until the pending request is resolved.

Order Validation

Order validation is the set of checks performed before an order is submitted to an execution venue. Thorough validation catches errors early, prevents rejections at the venue, and enforces risk management and compliance constraints.

Pre-submission validation (OMS-level):

Exchange-level validation: Even after OMS validation, the exchange performs its own checks: valid symbol for the venue, order type supported by the venue, price within the venue's price band (limit-up/limit-down), quantity within the venue's maximum order size, and participant permissions. Exchange rejections result in a FIX Reject or ExecutionReport with ExecType=Rejected and a reason code.

Reject handling and error codes: When an order is rejected — either by the OMS or by the venue — the rejection reason must be captured, logged, and communicated to the order originator. FIX Tag 103 (OrdRejReason) provides standardized rejection codes: broker/exchange option (0), unknown symbol (1), exchange closed (2), order exceeds limit (3), too late to enter (4), unknown order (5), duplicate order (6), and others. The OMS should map venue-specific rejection codes to actionable error messages for traders and operations staff.

Multi-Leg and Contingent Orders

Trading systems must support orders that involve multiple legs or contingent execution logic.

Order Audit Trail

Regulatory requirements mandate comprehensive audit trails for all order activity.

Consolidated Audit Trail (CAT): CAT, which replaced FINRA's OATS (Order Audit Trail System), requires broker-dealers and certain other participants to report detailed lifecycle events for every order in NMS securities and listed options. Reportable events include order receipt, order origination, order routing, order modification (cancel/replace), order execution, and order cancellation. CAT requires customer identification at the point of order origination, enabling regulators to trace every order from inception through execution or cancellation, across all venues and intermediaries.

Timestamp precision: CAT requires timestamps with millisecond precision at minimum, and many firms capture microsecond or nanosecond precision for internal analytics and compliance. Clock synchronization across all systems in the order flow is essential — FINRA Rule 4590 requires clocks to be synchronized within specified tolerances (generally one second for manual events, 50 milliseconds for electronic events). Timestamp drift between the OMS, FIX gateway, and execution venues can create audit trail inconsistencies that are difficult to resolve.

Order event logging: Every state transition, every message sent, and every message received must be logged with a timestamp, the message content (or key fields), and the system component that processed the event. The log must be immutable — entries cannot be modified or deleted after creation. This event log forms the basis for regulatory reporting, dispute resolution, and operational forensics.

Reconstruction capability: Regulators may request a complete reconstruction of order activity for a specific time period, security, account, or trader. The audit trail must support reconstruction at any level of granularity: a single order's complete lifecycle, all orders for a security during a trading session, or all orders originated by a specific desk or individual. Reconstruction requires correlating OMS records, FIX message logs, execution venue reports, and clearing/settlement records.

Worked Examples

Three worked examples are in references/examples.md — load for an end-to-end scenario: (1) designing an order state machine for a broker-dealer's OMS, (2) implementing cancel/replace workflows with race-condition handling, (3) integrating FIX connectivity to a new execution venue (see exchange-connectivity for session-layer detail).

Common Pitfalls

Cross-References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.