9.7 KiB
F05 — Unify matching and order lifecycle on the ledger
Parent epic: E2. Priority/severity: P0 / Critical. Relative complexity: L. Recommended specialization: Rust execution semantics.
Scheduling source of truth: manifest entry F05. No task is authorized until the plan is approved. Dependencies and decision references below describe the design; the manifest controls current readiness.
Evidence and root cause
- FIN-01 — Verified: Both execution paths can act on a completed bar and fill against its current close; this is not a defensible default bar-close policy. apps/stock/engine/src/backtest/engine.rs:249; apps/stock/orchestrator/src/services/ExecutionService.ts:224.
- FIN-05 — Verified: Rust and TypeScript separately implement fill/accounting behavior; the exposed native TypeScript callback method explicitly rejects callbacks. apps/stock/engine/src/api/backtest.rs:63; apps/stock/orchestrator/src/execution/SimulationExecution.ts:114.
- FIN-06 — Verified: Native simulation fills complete requested quantities at the latest price without bar-volume participation; current risk must be enforced at acceptance and fill, including pending exposure. apps/stock/engine/src/backtest/engine.rs:374; apps/stock/engine/src/backtest/engine.rs:414.
- KEEP-01 — Verified: Preserve transaction-scoped account locking, idempotent fills/event fingerprints, durable decisions and recovery checkpoints; these are real behavior, not interfaces alone. apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts:46; apps/stock/orchestrator/src/execution/StrategyRecovery.ts:151.
Intended behavior and implementation scope
Implement pure matcher/order-transition functions over explicit execution events; replay scheduling belongs to F06. Market/limit orders use declared spread/slippage and available liquidity, with no future-bar fields. Retain DAY/GTC/IOC/FOK semantics needed by the existing paper path; unsupported stop/OCO types reject. Target mode and explicit-order mode are mutually exclusive for one strategy instance in v1. Repeated absolute targets account for owned holdings and outstanding commitments; replacements cancel only owned orders.
Exclusions
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 (reference only during additive implementation)
Write locks: rust-matching, financial-contract. One agent owns this change. Lock names do not override actual overlapping files.
Dependencies and blockers
Implementation requires F04 integrated.
Architecture decisions: ADR-003. Agents may not independently amend their policies.
Feature activation/release gates: F06. These do not block implementing or integrating this component against its own tests.
Parallel eligibility: only with disjoint actual files and reserved write locks; read FIRST-WAVE.md for the initial exact ownership boundaries.
Acceptance criteria
- Given an already-eligible execution event, market/limit price protection, volume sharing, partial fill, rejection/cancellation and expiry are deterministic.
- IOC cancels remainder; FOK either fills fully or does not fill/charge; DAY accepts only in-session; target-generated GTC survives a session boundary.
- Same owner/instrument repeated target after partial fill does not duplicate quantity; mixed target/explicit mode rejects; another owner's order cannot be cancelled.
- Pure eligibility tests reject prior/same observed event keys. Full next-open ordering is an F06 release gate, not a hidden F05 implementation requirement.
Mandatory tests
- 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. Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
Regression risks and rollback
Financial or compatibility regression; preserve existing fixtures and version changed semantics. Keep migrations additive and previous results readable. Do not add a switch that restores a correctness defect. Versioned cutover/migration is required only when persisted contracts or active engines change; never silently fall back to old economics.
Handoff
Report scope changes (if any), fixture expectations, API/schema changes, measurements, remaining limitations and commit/PR references once authorized. Request independent review; only the integration/planning owner may mark the manifest done.