Manual Order Execution Workflow & Risk Gateway

Code Version: 0.7.0 | Wiki Version: 0.7.0

1. Architectural Overview

The Order Gateway is the central execution authority for drt-multi-venue. It provides deterministic, zero-data-loss order management without requiring reinforcement learning model actions. The gateway orchestrates pre-trade risk validation, strict state machine lifecycle transitions, background GTD order and position expiry monitors, multi-venue order routing, and live position reconciliation.

Subsystem Module Path Primary Responsibility
Pre-Trade Risk Engine services/order_gateway/risk_rules.py Fat-finger size limits, $\le 2\%$ price deviation checks, monotonic multi-TP/SL sanity, position count caps, and Redis killswitch intercept.
Lifecycle State Machine services/order_gateway/lifecycle.py Deterministic order transitions (9 states), fill averaging, DuckDB persistence (orders.duckdb), and Redis event publishing.
Expiry & Session Watcher services/order_gateway/expiry_watcher.py Automated GTD order timeout cancellation and position session flattening (auto_close_on_session_close).
Multi-Venue Router services/order_gateway/router.py Parameter translation, position bracket modification, and order dispatch across FXCMBrokerClient and IBKRBrokerClient with zero-mock resilient routing.
Position Reconciler services/order_gateway/reconciliation.py Periodic 10s polling of broker ground truth, discrepancy detection, and Redis position stream broadcasts.

2. Order Lifecycle State Machine

Order states progress through a strictly deterministic state graph. Any transition not explicitly defined in VALID_TRANSITIONS raises an InvalidStateTransitionError.

+------------------+ | PENDING_SUBMIT | +------------------+ / \ (Risk Pass) / \ (Risk Fail) v v +-------------+ +--------------+ | SUBMITTED | | REJECTED | [Terminal] +-------------+ +--------------+ / | \ (Acked by Brk)/ | \ (Broker Error) v | v +--------------+| +--------------+ | ACKNOWLEDGED || | REJECTED | [Terminal] +--------------+| +--------------+ / | \ | (Fill) / (Part) \ \ +------------+ v v \ \ | +--------+ +--------------+ | (User Cancel / GTD Expire) | FILLED | |PARTIALLY_FILL| v +--------+ +--------------+ +----------------+ [Terminal] | | \ | CANCEL_PENDING | | | \ +----------------+ | | \ | | | v v | | +----------------+ | +---->| CANCELLED | [Terminal] | +----------------+ | ^ | (GTD Expired) | +-------------------+ | (Auto GTD Mark) v +--------------+ | EXPIRED | [Terminal] +--------------+

Terminal states (FILLED, CANCELLED, EXPIRED, REJECTED) are immutable. Once reached, no further transitions are allowed.

3. Pre-Trade Risk & Fat-Finger Safeguards

Every manual order undergoes six synchronous and asynchronous validation checks prior to broker transmission:

  1. Killswitch Intercept: If the Redis killswitch is active for the target venue, symbol, or globally: $$\text{Killswitch}(\text{scope}) = \text{True} \implies \text{REJECT}$$
  2. Maximum Position Cap: Limits open positions per venue to prevent over-leverage (default $N_{\text{max}} = 5$): $$N_{\text{open}} \ge N_{\text{max}} \implies \text{REJECT}$$
  3. Instrument Size Bounds: Rejects non-positive or oversized quantities based on asset class (e.g. max 5 micro futures contracts, 100K units FX): $$0 < Q_{\text{order}} \le Q_{\text{max}}(\text{symbol})$$
  4. 2% Price Deviation Filter: For Limit and Stop orders, verifies that the target price is within 2% of the current market midpoint price: $$\frac{|P_{\text{order}} - P_{\text{mid}}|}{P_{\text{mid}}} \le 0.02$$
  5. Monotonic Bracket Sanity:
    • Buy Orders: Enforces strict monotonic progression: $$P_{\text{sl}} < P_{\text{entry}} < P_{\text{tp1}} < P_{\text{tp2}}$$
    • Sell Orders: Enforces inverse monotonic progression: $$P_{\text{sl}} > P_{\text{entry}} > P_{\text{tp1}} > P_{\text{tp2}}$$
    • Quantity Allocation: Sum of Take Profit allocations must equal 100%: $$\text{tp1\_qty\_pct} + (\text{tp2\_qty\_pct} \text{ or } 0) = 1.0 \pm 10^{-4}$$
  6. Expiry Horizon Validation: All specified timestamps (order_expiry and position_expiry) must be strictly in the future in UTC coordinates: $$T_{\text{expiry}} > T_{\text{now}} (\text{UTC})$$

4. Background Expiry & Session Close Watcher

The ExpiryWatcher executes continuous background monitoring on a 1.0s cadence:

5. Redis Streams Event Architecture

Every order action, state change, and position reconciliation report is published to high-throughput Redis Streams:

Stream Key Payload Schema Consumer Role
orders.requests OrderRequest Inbound placement queue consumed by OrderRouter worker group.
orders.events.{venue}.{order_id} Order state event: from_state, to_state, filled_size, avg_fill_price Per-order event log for client UI subscribers and trade loggers.
orders.events Unified order event stream across all venues Global audit log, trade telemetry, and persistent analytics.
orders.positions.{venue} {venue, ts, positions: [...], discrepancies: [...]} Reconciled broker position reports published every 10 seconds.

6. Position Bracket Modification (SL & TP Amendment)

Active positions across FXCM and IBKR can have their Take Profit and Stop Loss levels amended at any time via REST and ForexConnect / TWS APIs without needing to close or recreate the position:

7. CLI Order Management Tooling

The scripts/submit_test_order.py utility provides complete command-line order placement and inspection for paper and demo operations:

# Submit a compliant Market order with bracket Take Profit and Stop Loss:
python3 scripts/submit_test_order.py --venue FXCM --symbol NAS100 --side buy --size 1 --type market --tp 29550 --sl 29300

# Submit a Limit order with GTD expiry in 60 seconds:
python3 scripts/submit_test_order.py --venue FXCM --symbol NAS100 --side sell --size 1 --type limit --price 29550 --order-expiry-sec 60

# Query order status by client or broker order ID:
python3 scripts/submit_test_order.py --status cli_test_001

# Cancel an active open order:
python3 scripts/submit_test_order.py --cancel 237786284 --venue FXCM

# Query broker active positions:
python3 scripts/submit_test_order.py --venue FXCM --positions