feat(engine): add canonical risk and order matching

This commit is contained in:
Boki 2026-10-22 22:15:34 -04:00
parent b65acccd91
commit ccf333cc0a
13 changed files with 5129 additions and 36 deletions

View file

@ -17,9 +17,20 @@ Implement canonical cash-long-only funding, pending fee-inclusive reservations,
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Execution policy clarifications
The approved ADRs remain unchanged. The initial additive implementation pins these explicit configuration semantics; no default production thresholds or active-account migration are introduced:
- Quantity units for order/position limits; base-currency amounts for symbol/gross exposure, daily loss and explicitly named maximum drawdown amount. Commission is an immutable Rust rate in [0, 1], calculated from exact quantity × price × rate and rounded once at eight places.
- Pending buys reserve fee-inclusive cash at the canonical mark (market) or max(mark, limit). Pending sells reserve owner inventory, never anticipated buying power; their fill proceeds fund fees. Pending sells do not offset buy exposure. Actual fills recheck other commitments and the remainder, including split-fill rounding. Unaffordable remainder rejects/releases without resizing or borrowing.
- Increasing risk requires fresh non-future canonical marks across held and pending assets, using explicit engine event time and a configured maximum mark age. Reductions still enforce inventory/funding/order-size rules. Daily and drawdown halts latch on marked loss; explicit account boundaries reset only daily state, including when retained marks are old. Same-session repetition cannot rebase, and future/backdated boundaries reject.
- A private-owned Ledger facade is the only canonical risk entry point. Normalized explicit-order and target-derived admission share one policy; actual target expansion, mode enforcement, matching, venue expiry scheduling and replay remain F05/F06. Resource-release hooks are not a second matcher.
- Operator reset is a separate host-held capability with recorded reason/baseline, absent from strategy inputs. This is API authority separation, not authentication or an untrusted-code sandbox. F07 must expose only the risk-governed facade; later host/auth adapters must enforce their own authority.
- Checkpoints validate reservations, risk state and recorded outcomes by deterministic reconstruction. They do not authenticate an attacker-modified history and are not full replay/strategy/RNG or SQL recovery snapshots. Normal transitions must not copy/replay the entire retained history.
## Likely files and ownership
- apps/stock/engine/src/risk/mod.rs
- apps/stock/engine/src/risk/mod.rs (reference only during additive implementation)
- apps/stock/engine/src/financial/risk.rs (new)
- apps/stock/engine/src/financial/ledger.rs
@ -44,6 +55,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
- competing_reservations, adverse_gap_reject_remainder, stale_other_symbol, marked_loss_halt, explicit_risk_session_boundary.
- drawdown_halt_survives_rollover_restore, unauthorized_reset_denied, alternate_venue_does_not_reset_account_day.
- Property test raw order and target paths cannot bypass the same policy.
- Partial-fill quantum rounding, zero-cash funded sell, pending sells do not credit buy exposure, stale/future other pending symbol, wrong-owner sell/cancel, accepted/rejected command replay and conflicting reuse, same-session no-rebase, future/backdated boundary rejection, restored reservation tamper and overflow atomicity.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.

View file

@ -19,10 +19,25 @@ Implement pure matcher/order-transition functions over explicit execution events
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
## Execution policy clarifications
The initial component remains additive and Rust-only, privately owning F04 RiskAccount; no mutable risk/ledger escape hatch, parallel accounting, legacy engine or NAPI cutover. F06 derives and schedules events/calendars; F07/S01 supply actual strategy barriers. This task consumes explicit host inputs and proves component behavior.
- Event eligibility uses availability time, phase, instrument and source sequence plus the pinned execution-series identity. Reject prior/observed execution keys; adjacent next-open at the same timestamp may be eligible under zero latency. Configured latency delays eligibility. No retroactive decision insertion into consumed execution phases. Open events cannot carry future OHLCV. A bar has one shared capacity pool across sides/owners; quotes have explicit bid/ask capacity. Only accepted fills consume it.
- Physical quote time is separate from delivery/availability time. Preserve it on marks and require it to be at or after order readiness: late delivery cannot fill an order that did not yet exist. Ineligible old quotes do not consume IOC/FOK opportunities. Explicit open time must match its execution key; F06 must skip/reject missed opens rather than freshen them.
- Deduplicate physical opens by instrument/open time and quotes by instrument/observation time/source sequence, independently of delivery key. Exact-key retries return receipts; changed-key redelivery of the same physical event rejects without minting capacity. Do not assume source sequences increase chronologically; distinct quotes sharing a millisecond remain possible.
- Pin relative half-spread and slippage rates in [0, 1). For bar opens, derive fixed-eight-place executable bid/ask first; then apply adverse slippage at another declared posting boundary. Quotes already include spread. Limits must cross the executable quote before slippage; qualifying prices are clamped to the limit, never filled through it. Quote financial marks use an exact once-rounded midpoint. F04 alone computes fees and funding.
- DAY binds an explicit open venue session and expires at its close; account risk-session reset is separate. IOC/FOK use their first eligible opportunity: IOC cancels remainder; FOK fills the whole remainder once or cancels without fills/fees. Unknown/zero liquidity cannot fill. GTC survives venue closure; run termination cancels without invented liquidation.
- Registered strategy mode is fixed. Each listed target is an absolute owner quantity; omitted instruments are unchanged, duplicate entries reject, and explicit zero closes that instrument. Holdings plus signed outstanding commitments determine unchanged targets. Changed targets cancel only that owner's instrument commitments before recomputing; if replacement risk rejects, cancellation remains a recorded outcome.
- Owners use stable configured identity order and each decision preserves its explicit intent/target array priority. Sparse target updates are not an atomic portfolio rebalance: earlier entries can reserve cash before later entries release commitments. No anticipated sell proceeds or hidden release-all reordering.
- Preflight structural errors across the entire submitted batch/event before mutation. Generated IDs encode tuples unambiguously. Exact repeated events/decisions return original receipts without refilling capacity or replaying effects; conflicting identity reuse rejects. Checkpoints retain order state, priority, identity/cursor/session state and F04 state.
- Decision admission uses one coordinator revision for the shared portfolio/order/reservation view. This token is distinct from the nested economic-only FinancialSnapshot ledger revision; F07 must expose the coordinator token for submitting a batch. No wire shape or TypeScript financial arithmetic changes here.
- A later internal numeric failure after successful subtransitions is a terminal failed-attempt receipt containing the ordered committed prefix, not a retryable generic error or successful event. All further mutations refuse; restore preserves failure. F06/F07 must discard failed attempts and never publish successful results. This keeps individual F04 transitions atomic without whole-account/history cloning or a second rollback engine.
## Likely files and ownership
- apps/stock/engine/src/financial/matching.rs (new)
- apps/stock/engine/src/backtest/engine.rs
- apps/stock/engine/src/backtest/engine.rs (reference only during additive implementation)
Write locks: rust-matching, financial-contract. One agent owns this change. Lock names do not override actual overlapping files.
@ -47,6 +62,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
- matcher_gap_limit, shared_volume_capacity, partial_cancel, IOC_remainder, FOK_atomicity, DAY_expiry, target_GTC_replace.
- unchanged_target_no_duplicate, mixed_intent_mode_rejected, wrong_owner_cancel, ineligible_event_key_rejected.
- Adjacent-open/positive-latency eligibility, same quote/key conflict, pinned execution series, unknown/zero capacity, risk rejection preserves shared capacity, later invalid batch member is atomic, terminal numeric failure records prefix and survives restore, partial-fill/target replay and omitted-target semantics.
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.

View file

@ -14,6 +14,8 @@ Scheduling source of truth: [manifest entry F06](../manifest.json). No task is a
Implement the replay cursor once: sorted immutable events with stable availability/phase/instrument/sequence ordering; add a small pending-event queue only where required. Absorb P02's nonquadratic load and disabled-by-default hot-loop trade logging. Generate open-only execution events from one designated execution series; feature-only frames do not add liquidity or undeclared decision triggers. Publish completed observations, evaluate declared decision barriers, then next-interval opens under recorded zero/nonzero latency policy.
Consume F05's explicit event contract without reconstructing a second matcher: quote observation time is not delivery time, and eligibility requires an order to be ready by physical quote time. Open time must equal its execution key; skip/reject missed opens, never relabel them as newly occurring. Decision admission uses the coordinator's shared portfolio/order revision, distinct from the nested economic ledger revision. Terminal F05 failures retain diagnostic prefixes but must fail/discard the replay attempt, never produce successful performance results.
## Exclusions
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.