nx_fin_risk_engine_gate.nx source
↩ module page · 43 lines · 2382 B
1// nx_fin_risk_engine_gate.nx -- R4 GATE: proves the sizers + circuit breaker on hand-computed values (no
2// network, no false-green). Kelly, the 1% risk rule, the drawdown breaker, and the ADV cap each checked
3// against arithmetic done by hand. Exits 0 iff all pass. license_tier: ORIGINAL
4import "nx_gate.nx"
5import "nx_fin_marketdata.nx"
6import "nx_fin_risk_engine.nx"
7
8func chk(name: *u8, got: i64, want: i64, st: *i64) -> i64 {
9 if got == want { st[0] = st[0] + 1; gw(" PASS " as *u8); gw(name); gw("\n" as *u8) }
10 else { st[1] = st[1] + 1; gw(" FAIL " as *u8); gw(name); gw(" got=" as *u8); gn(got); gw(" want=" as *u8); gn(want); gw("\n" as *u8) }
11 return 0
12}
13
14func main() -> i64 {
15 let st: *i64 = sys_mmap(16) as *i64
16 st[0] = 0; st[1] = 0
17
18 // -- Kelly: p=60%, avgWin=200, avgLoss=100 -> b=2 -> f* = 0.6 - 0.4/2 = 0.4 = 4000 bps --
19 chk("kelly 60%/200/100 = 4000 bps" as *u8, re_kelly_bps(6000, 200, 100), 4000, st)
20 chk("no-edge kelly (40%/100/100) -> 0" as *u8, re_kelly_bps(4000, 100, 100), 0, st)
21 chk("no-loss-estimate kelly -> 0" as *u8, re_kelly_bps(6000, 200, 0), 0, st)
22 chk("half-Kelly of 4000 = 2000 bps" as *u8, re_frac_kelly(4000, 5000), 2000, st)
23
24 // -- the 1% risk rule: $10k equity, 1% risk, entry 1000 stop 900 (risk 100/sh) -> 100 shares --
25 chk("size-by-risk 1% -> 100 sh" as *u8, re_size_by_risk(1000000, 100, 1000, 900), 100, st)
26 chk("bad stop (stop>=entry) -> 0" as *u8, re_size_by_risk(1000000, 100, 1000, 1000), 0, st)
27
28 // -- Kelly fraction -> shares: 20% of $10k / $10.00 = $2000/1000c = 200 sh --
29 chk("size-by-kelly 20% @1000c -> 200 sh" as *u8, re_size_by_kelly(1000000, 2000, 1000), 200, st)
30
31 // -- max-drawdown circuit breaker --
32 chk("dd 5% < 20% limit -> trade ok" as *u8, re_dd_ok(500, 2000), 1, st)
33 chk("dd 25% >= 20% limit -> HALT" as *u8, re_dd_ok(2500, 2000), 0, st)
34
35 // -- ADV scaling-wall cap (composes R1 md_capacity) --
36 chk("cap loose (10bps ADV) -> unchanged 100" as *u8, re_cap_shares(100, 1000, 100000000, 10), 100, st)
37 chk("cap tight (5bps ADV) -> 50" as *u8, re_cap_shares(100, 1000, 100000000, 5), 50, st)
38
39 gw("nx_fin_risk_engine_gate: PASS=" as *u8); gn(st[0]); gw(" FAIL=" as *u8); gn(st[1]); gw("\n" as *u8)
40 if st[1] == 0 { gw("R4 nx_fin_risk_engine: GREEN\n" as *u8); return 0 }
41 gw("R4 nx_fin_risk_engine: RED\n" as *u8)
42 return 1
43}