Files
Aura/crates/aura-std/src/latch.rs
T
Brummel 2c43296c2c feat(stage1-r): bias rename + stop-rule + position-management + summarize_r (iter 1)
Iteration 1 of the Stage-1 "R-based signal quality" cycle (spec 0065): a
strategy's signal quality, measured in R on its unsized bias stream, feed-forward.
New discrete-trade machinery, NOT a SimBroker extension.

What lands:
- exposure -> bias (refs #126): the Exposure node/type/file/output-field renamed to
  Bias (computation unchanged: clamp(signal/scale,-1,+1); the SEMANTICS change — the
  output is the unsized strategy bias, sizing leaves the strategy). Scoped to the
  semantic core; behaviour-preserving cosmetics are deferred (see below).
- stop-rule nodes (refs #119): VolStop = k*EMA(|price - prev_price|) (one fused node;
  the volatility that defines 1R, close-to-close — true-range ATR deferred, needs
  OHLC) + FixedStop (constant, the test fixture / fixed-vs-vol structural-axis sibling).
- PositionManagement (refs #127): the stateful heart. Latches the entry-cycle stop
  distance as the FROZEN R-denominator (never re-read), marks/exits no-look-ahead like
  SimBroker (a position earns from the next cycle; an exit realises against the cycle's
  close), and emits ONE dense per-cycle R-record (C8). Stop-outs are NOT capped at -1R
  (a gap through the stop realises R < -1 — the honest loss tail); R is computed
  size-invariantly (size = (exit-entry)*dir / latched_dist cancels). The trade ledger
  is the rows where closed_this_cycle; the R-equity is cum_realized + unrealized; a
  position open at window end is the last row (open=true) — explicit, never silent MtM.
- summarize_r + RMetrics (refs #129): the post-run fold (NOT an in-graph node —
  recorders drain post-run). E[R], win-rate, profit-factor, avg win/loss R, by-trade
  max R-drawdown, n_open_at_end (window-end force-close). SQN / conviction terciles /
  net-of-cost / RunMetrics.r are iteration 2.

Design adversarially hardened before implementation (12-juror refute panel; decisions
on #117). Ratified implementer deviations from the plan snippet, verified by hand:
- col-4 `direction` tracks the OPEN position at cycle end (window-end synthesis; names
  the reopened leg on a reversal), falling back to the closed trade's dir only when
  flat. summarize_r does not read col 4; the R-metrics are unaffected.
- .named("exposure") kept on the 4 previously-unnamed Bias nodes so the auto-derived
  param-path stays exposure.scale (no manifest/dir-name drift) — the unnamed nodes
  would otherwise flip to bias.scale.
- intra-doc links [`Exposure`] -> [`Bias`] in sim_broker/latch + the sample-model test
  pin (cosmetic, behaviour-neutral; broken intra-doc links fail cargo doc).
- the E2E drives a full bootstrapped Harness (stronger than the plan's direct-node
  drive — exercises the real cross-crate producer->consumer seam).

Deferred (behaviour-preserving, separate cosmetic pass — NOT this iteration):
RunMetrics.exposure_sign_flips / Metric::ExposureSignFlips, SimBroker/LongOnly
"exposure" input ports, the "exposure" tap/trace names, and the .named("exposure")
instance labels. Iteration 2: the Sizer seam, the RiskExecutor composite (+ the Veto
documented-seam), summarize_r enrichment, RunMetrics.r, and the CLI/recording surface.

Verification (orchestrator-run, not agent-claimed):
- cargo build --workspace: clean.
- cargo test --workspace: all green, 0 failed (incl. the new bias/stop_rule/
  position_management unit tests, the summarize_r arithmetic tests, and the
  stage1_r_e2e capstone + layout guard).
- cargo clippy --workspace --all-targets -- -D warnings: clean (exit 0).
- Keystone RED tests pass: no_lookahead_bias_exit_realises_the_held_move,
  stop_out_is_not_capped_at_minus_one_r, no_gap_stop_is_exactly_minus_one_r,
  reversal_closes_one_leg_and_reopens, open_at_window_end_is_carried_on_the_last_row.

refs #117 #119 #126 #127 #129
2026-06-23 19:48:58 +02:00

144 lines
5.4 KiB
Rust

//! `Latch` — a level-sensitive set/reset register that emits an `f64` exposure
//! magnitude (`1.0` latched / `0.0` flat), the C5 SR-register of the
//! session-breakout vocabulary.
//!
//! Two `bool` inputs (`set`, `reset`, `Firing::Any`); one `f64` output `value`;
//! no params. **Emits `f64` directly**, not `bool`: a held position *is*
//! exposure `+1`, flat *is* `0.0`, so the output feeds [`SimBroker`](crate::SimBroker)'s
//! `f64` `exposure` slot with no cast — this is the resolution of the `bool → f64`
//! seam (no separate `Bias`/cast node).
//!
//! **State.** A persisted `held: f64`, initial `0.0`, mutated in `eval` and
//! carried across cycles in the struct — exactly how [`SimBroker`](crate::SimBroker)
//! holds `prev_price`/`prev_exposure` across cycles.
//!
//! **Logic — level SR latch, RESET-DOMINANT.** Per fired eval: if `reset` is on
//! → `held = 0.0`; else if `set` is on → `held = 1.0`; else `held` is unchanged
//! (sample-and-hold). Reset wins when both pulse (defensive default; in the
//! strategy bar3 ≠ bar5 so they never coincide).
use aura_core::{Cell, Ctx, FieldSpec, Firing, Node, NodeSchema, PortSpec, PrimitiveBuilder, ScalarKind};
/// Level-sensitive set/reset register emitting an `f64` exposure magnitude:
/// `held` → `1.0` on `set`, → `0.0` on `reset` (reset-dominant), held across
/// quiet cycles. Emits `None` only while **both** input legs are still cold
/// (nothing latched yet); a present-but-false leg is read as "no pulse".
pub struct Latch {
held: f64, // persisted exposure magnitude: 1.0 = long, 0.0 = flat
out: [Cell; 1],
}
impl Latch {
/// Build a `Latch` node, initially flat (`held = 0.0`).
pub fn new() -> Self {
Self { held: 0.0, out: [Cell::from_f64(0.0)] }
}
/// The param-generic recipe for a blueprint primitive: paramless, builds
/// through `Latch::new`.
pub fn builder() -> PrimitiveBuilder {
PrimitiveBuilder::new(
"Latch",
NodeSchema {
inputs: vec![
PortSpec { kind: ScalarKind::Bool, firing: Firing::Any, name: "set".into() },
PortSpec { kind: ScalarKind::Bool, firing: Firing::Any, name: "reset".into() },
],
output: vec![FieldSpec { name: "value".into(), kind: ScalarKind::F64 }],
params: vec![],
},
|_| Box::new(Latch::new()),
)
}
}
impl Default for Latch {
fn default() -> Self {
Self::new()
}
}
impl Node for Latch {
fn lookbacks(&self) -> Vec<usize> {
vec![1, 1]
}
fn eval(&mut self, ctx: Ctx<'_>) -> Option<&[Cell]> {
let set = ctx.bool_in(0);
let reset = ctx.bool_in(1);
if set.is_empty() && reset.is_empty() {
return None; // cold: nothing latched yet (downstream reads flat 0.0)
}
// An absent/empty leg is read as "no pulse"; a present leg pulses when true.
let set_on = set.get(0).unwrap_or(false);
let reset_on = reset.get(0).unwrap_or(false);
if reset_on {
self.held = 0.0; // reset dominates (defensive default)
} else if set_on {
self.held = 1.0;
} // else: sample-and-hold — `held` unchanged
self.out[0] = Cell::from_f64(self.held);
Some(&self.out)
}
fn label(&self) -> String {
"Latch".to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
use aura_core::{AnyColumn, Scalar, Timestamp};
fn two_bool_inputs() -> Vec<AnyColumn> {
vec![
AnyColumn::with_capacity(ScalarKind::Bool, 1),
AnyColumn::with_capacity(ScalarKind::Bool, 1),
]
}
#[test]
fn latch_holds_set_until_reset_reset_dominant() {
// The core property: a level SR latch that sample-and-HOLDS its f64
// exposure magnitude across quiet bars, with RESET dominant when both
// pulse. Both legs are present every cycle (as in the real graph: set =
// `entry`, reset = `isBar5Close`, both fresh bool streams each bar).
let mut node = Latch::new();
let mut inputs = two_bool_inputs();
// (set, reset) -> expected held
let cases = [
((false, false), 0.0), // initial: flat
((true, false), 1.0), // set latches long
((false, false), 1.0), // HOLD across a quiet bar (load-bearing sample-and-hold)
((false, true), 0.0), // reset goes flat
((false, false), 0.0), // hold flat
((true, true), 0.0), // reset-dominant: both on -> flat (pins the priority)
];
for ((set, reset), want) in cases {
inputs[0].push(Scalar::bool(set)).unwrap();
inputs[1].push(Scalar::bool(reset)).unwrap();
let got = node.eval(Ctx::new(&inputs, Timestamp(0)));
assert_eq!(got, Some([Cell::from_f64(want)].as_slice()));
}
}
#[test]
fn latch_is_none_while_both_legs_cold() {
// Before any input on either leg: nothing latched yet -> None (downstream
// reads SimBroker's cold-leg-as-0.0, i.e. flat).
let mut node = Latch::new();
let inputs = two_bool_inputs();
assert_eq!(node.eval(Ctx::new(&inputs, Timestamp(0))), None);
}
#[test]
fn input_slots_are_named_set_reset() {
let l = Latch::builder();
let names: Vec<&str> = l.schema().inputs.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["set", "reset"]);
}
}