Manual Order Execution Workflow & Risk Gateway
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.
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:
- Killswitch Intercept: If the Redis killswitch is active for the target venue, symbol, or globally: $$\text{Killswitch}(\text{scope}) = \text{True} \implies \text{REJECT}$$
- 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}$$
- 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})$$
- 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$$
-
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}$$
-
Expiry Horizon Validation: All specified timestamps (
order_expiryandposition_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:
- Order Expiry (GTD Timeouts): Stale un-triggered pending limit or stop orders whose
order_expiryhas elapsed are cancelled on the broker and transitioned toOrderState.EXPIRED. - Position Expiry: Positions held past
position_expirytrigger immediate market closing orders in the opposite direction. - Session Close Boundary Flattening: For orders with
auto_close_on_session_close = True, the watcher tracks current Tokyo (ADR), London (ODR), and New York (RDR) regional session close boundaries usingRegionalSessionEngine. When the UTC clock approaches session close, a market flattening order is dispatched to ensure flat books overnight.
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:
- Dashboard REST Endpoint:
POST /api/positions/{position_id}/modifywith payload{"venue": "FXCM", "sl_price": 29350.0, "tp1_price": 29500.0} - ForexConnect Gateway:
POST /positions/{trade_id}/modifytranslates to native ForexConnect SDK commands (EDIT_ORDERfor existing contingent stops/limits, orCREATE_ORDERif brackets were not initially set). - Event Broadcast: Publishes
POSITION_MODIFIEDevents to Redis streamorders.events.{VENUE}and updates dashboard UI via WebSockets.
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