diff --git a/.gitattributes b/.gitattributes index d8eeb8b..3f39e85 100644 Binary files a/.gitattributes and b/.gitattributes differ diff --git a/SPRINT_BOARD.md b/SPRINT_BOARD.md index 573dc17..f7ccd95 100644 --- a/SPRINT_BOARD.md +++ b/SPRINT_BOARD.md @@ -1,5 +1,5 @@ # NT8 SDK โ€” Sprint Board -**Last Updated:** 2026-08-16 +**Last Updated:** 2026-08-18 (v7.0 review โ€” six new tasks staged) **Truth source:** compiler output, test output, deployed-file comparisons, and runtime artifacts override board claims. ## Current gate state @@ -17,6 +17,59 @@ --- +## ๐Ÿ”ด BLOCKERS โ€” staged 2026-08-18 by the v7.0 master-document review + +> Source: `docs/NT8_SDK_Master_Document_v7.0_Complete.docx` (+ `docs/NT8_SDK_v7.0_Visual_Pack.html`). +> All six were found by cross-referencing source against the live NinjaTrader log directory. +> **No source code was changed by the review** โ€” each item below is a staged prompt awaiting execution. +> **2026-08-19: all four proposed decisions accepted by operator (DEC-20260818-18/19/20/21, plus new DEC-20260819-01 on MNQ cutover sequencing). All six items below marked โœ… READY.** +> **2026-08-19, later same day: ๐Ÿ›‘ PREFLIGHT HALTED by operator before GAP-054 start.** `git status` showed uncommitted `src/` changes, NinjaTrader was running, position status was unconfirmed, and the configured account logged itself as `"gate account SimSimple ORB"`. +> **2026-08-19, still later: ๐ŸŸก PARTIALLY CLEARED.** Operator confirmed: position flat, NinjaTrader closed, and `SimSimple ORB` is "not of consequence" โ€” a new account with `gate3` explicitly in its name will be stood up for actual Gate Run #3 evidence. **One item still open: the uncommitted DASH-002 diff in `src/` (`NT8StrategyBase.cs`, `SimpleORBNT8.cs`) has not been committed or otherwise reconciled** โ€” recommended before GAP-054 lands on top of it. Full detail: `docs/00-governance/current_status.md` ยง 2026-08-19. +> **2026-08-21: GAP-054 Option 0 IMPLEMENTED and source-verified.** Landed on top of the still-uncommitted DASH-002 diff (unresolved from the line above). Builds/tests/deploy all passed; deployed hash matches repo. **Not yet SIM-validated, not yet committed, not yet cleared for RUNNER-001.** New low-priority follow-ups logged: GAP-056 (breakeven params now fully inert, not just runner-scoped as this board previously assumed) and GAP-057 (no test seam for NT8 managed SetStopLoss/SetTrailStop calls). See DEC-20260818-18 and DEC-20260821-01. + +**[GAP-054] Auto-breakeven destroys the runner's trailing stop** | Stage 2 | ๐ŸŸก IMPLEMENTED, UNVALIDATED โ€” **still blocks RUNNER-001** +- `SetStopLoss()` on `_runnerSignalName` (`NT8StrategyBase.cs` ~803) replaces the `SetTrailStop()` issued at entry (~2188/2196). Mutually exclusive per signal name in NinjaScript. +- Confirmed in 4/4 broker-confirmed trades: trail was 12โ€“16 ticks in profit when breakeven fired, moved back to +1. **The runner has never trailed.** +- Conservative floor estimate: 55 ticks (~$275 gross / ~$252 net) forgone vs $25 / $1.96 realised โ€” โ‰ˆ24% of total P&L. +- Supersedes the "retune the breakeven trigger" framing of DEC-20260810-02 and DEC-20260815-01. +- Prompt: `TASK_GAP054_RUNNER_TRAIL_PROMPT.md` (updated 2026-08-19: unconditional-skip default resolved, no new flag). Validate on SIM/replay only before any live gate run. + +**[GAP-045 / GAP-046] Risk-envelope coherence guards** | Stage 0/1 | โœ… READY +- GAP-045: `MaxStopTicks` 50 ร— $5 = $250 > `MaxTradeRisk` $200 on NQ. Five valid signals rejected 2026-08-18 10:10 ET at $225.00. The top 20% of the ATR stop range is unreachable. +- GAP-046: `EnableTrailingDrawdown=True` with `AccountStartingBalance=$0.00` blocked every entry from 14:30 ET, 27 rejections. No startup assertion pairs the two. +- GAP-050: `MaxTradeRisk` has no quantity term โ€” worst case is $600 against a $1,000 daily limit. v6.4 ยง3.2 documented a `ร— Qty` the code has never had. +- **Decided 2026-08-19:** collision resolved via MNQ (staged separately, DEC-20260819-01); MaxTradeRisk is per-position (total). Tier 1 check reorders to post-sizing. Implement and validate on NQ first โ€” MNQ cutover is a later, separate step. +- Prompt: `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` (Part 3 rewritten 2026-08-19, now fully actionable). + +**[GAP-047] Confluence factor weights pre-populated to 1.0 โ€” Part 1, offline re-scoring study** | Stage 1 | โœ… READY โ€” **highest-value task on the board** +- `ConfluenceScorer.cs` ~108โ€“117 / ~410โ€“419: the calculators' designed weights (0.20/0.15/0.15/0.20/0.15) are unreachable dead code. Every `STATE:` factor reads `x1.00`. +- Designed total weight 5.85 vs actual 10.00. Grade A reachable on factors 1โ€“5 alone under the design; close to structurally unreachable under equal weights. +- Live example: 0.640 (C) as logged vs 0.727 (B) under designed weights. **Leading hypothesis for GAP-034a and for the low trade rate.** +- Part 1 is analysis only against existing `STATE:` / `SIGNAL_DETAIL:` lines โ€” no runtime change, no risk. +- Prompt: `TASK_GAP047_WEIGHT_RESCORE_PROMPT.md`. Part 2 (the runtime change) is staged separately after the study. + +**[GAP-055] `MaxDailyTrades` does not survive a strategy restart** | Stage 0 | โœ… READY +- In-memory counter only (`SimpleORBStrategy.cs` ~39). CME trading date 2026-08-17 took two trades under `MaxDailyTrades=1` across two NT8 sessions; the second session's `DayPnL=$271.96 โ†’ $545.44` proves NT8 treated them as one day. +- Same class as the 7/28 breach that helped void Gate Run #2. **A gate run cannot currently guarantee its own cap.** +- Prompt: `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md`. + +**[GAP-048] Reject-reason taxonomy conflates four causes under `KillSwitch`** | Stage 0 | โœ… READY โ€” diagnostics only, zero trading risk +- 2026-08-17 logged `reason=KillSwitch count=647` from a real kill switch; 2026-08-18 logged `count=5` from `MaxTradeRisk`. Same label. `GradeFilter` is overloaded four ways as well. +- `REJECT SUMMARY` aggregates on `reason`, so the counts operators and the dashboard read are ambiguous. Defeats what GAP-035 was built for. +- Prompt: `TASK_GAP048_REJECT_TAXONOMY_PROMPT.md`. + +**[GAP-049] Telemetry `STATE:` score is direction-incorrect and presented as the trade grade** | Stage 1 | โœ… READY +- `GapDirectionAlignmentCalculator` reads `daily.TradeDirection`, which the telemetry path deliberately does not set (DEC-20260818-06). Confirmed: a โˆ’523 gap scored "opposes trade" on a `Direction=Sell` setup. +- The dashboard's headline Score/Grade is therefore not the trade's. Also degrades the GAP-047 study. +- Prompt: `TASK_GAP049_TELEMETRY_DIRECTION_PROMPT.md`. + +### Also raised by the review, not yet prompted +GAP-051 (`MicroUpgradeThreshold` fires every session) ยท GAP-052 (two hardcoded tick-value tables) ยท +GAP-053 (`executive_summary.md` and `roadmap.md` Sprint 3 list present ~12 completed tasks as open) ยท +plus the standing dirty working tree โ€” 17 modified, 5 untracked, including two live strategy files. + +--- + ## ๐ŸŸข PARALLEL โ€” Non-Algorithm Product Work (safe during Gate Run #3) **[DASH-001] Standalone Read-Only Dashboard** | Sprint 5 (pulled forward) | ๐Ÿ”ต ACTIVE @@ -29,6 +82,7 @@ - **Extension (2026-08-16):** Add outbound notification module to the dashboard's Python server (NOT to the NinjaScript strategy) using Apprise for unified Discord/Notifiarr/ntfy/etc. delivery. Alerts on FILL, SUBMIT, BREAKEVEN, CONNECTION LOST/RESTORED, daily P&L milestones. Bind server to 127.0.0.1 only, read-only endpoints, no POST/write routes. Poll interval must be explicit/configurable: 1-2s for live session-log tail, 5-10s for trades table/config panel. - **Bugfix/Extension (2026-08-17):** Live server current-session selection now uses newest root-level `session_*.log` by file modification time and populates `current_session` even when notification offsets start at EOF. Dashboard adds a Bars/Days-Loaded panel from existing Historical readiness and FactorWarmup log lines. - **[DASH-003] Bugfix/Extension (2026-08-17):** `/api/state` live trades now reads only the current session date's `trades_*.jsonl` instead of falling back to old historical trade records; `/api/state` also returns current-session rows/diagnostics so Daily Timeline, Config Integrity, Silent Day Explorer, and Decision/Defect headline populate without manual JSON load. +- **[DASH-004] Trading Console Alternate Dashboard Page (2026-08-17):** Add `console.html`, `console.css`, and `console.js` as a second read-only dashboard page. It uses only real `/api/state` fields, links back to the triage board, and avoids fabricated trade P&L, multi-instrument, or multi-timeframe telemetry. **[DASH-002] Continuous Confluence & Regime Telemetry** | Weekend window 2026-08-16 | ๐Ÿ”ต ACTIVE - Scope: `src\` source change โ€” adds `EnableStateTelemetry` parameter emitting periodic factor/regime state to session log (currently only logged at signal time). Additive observability only; existing SIGNAL/SUBMIT/FILL/PNL_UPDATE lines must remain byte-for-byte unaffected. diff --git a/TASK_DASH-002_PROMPT.md b/TASK_DASH-002_PROMPT.md index 4496b05..286f52e 100644 --- a/TASK_DASH-002_PROMPT.md +++ b/TASK_DASH-002_PROMPT.md @@ -18,6 +18,40 @@ BEFORE market open Monday, with time left to re-arm calmly. If read-first findings suggest this can't be done safely and verified in the available window, say so explicitly rather than rushing a deploy. +## SAFETY FINDING (resolved 2026-08-17, DEC-20260817-04) +RegimeManager, TrendRegimeDetector, and VolatilityRegimeDetector +(src\NT8.Core\Intelligence\) are instantiated in +NT8StrategyBase.InitializeSdkComponents() but are NOT called anywhere in +the live signal path today โ€” confirmed by direct read of +NT8StrategyBase.cs, SimpleORBStrategy.cs, and FactorCalculators.cs. The +regime/volatility values actually used for signal generation are computed +independently: inline SMA20/50 math in BuildStrategyContext() and +pure-function ATR-ratio math inside VolatilityRegimeFactorCalculator / +TrendAlignmentFactorCalculator, which read from context.CustomData and +have no side effects. + +RegimeManager.UpdateRegime(), TrendRegimeDetector.DetectTrend(), and +VolatilityRegimeDetector.DetectRegime() DO mutate internal state on every +call (bar history, current-regime dictionaries, transition logs) and are +currently unused/dead code. DASH-002 telemetry MUST NOT call any of these +three methods (nor VolatilityRegimeDetector.UpdateRegimeHistory(), which +also mutates state) for periodic sampling โ€” doing so would make telemetry +the first real consumer of state nothing else reads, which could corrupt +assumptions if a future task wires these classes into the live decision +path. + +Note: the read-only getters (GetCurrentRegime(), GetCurrentTrendRegime(), +GetCurrentTrendStrength(), GetRegimeDuration(), GetTransitions(), +GetRecentTransitions()) are safe to call but will return defaults +(null / TrendRegime.Range / VolatilityRegime.Normal) since nothing +populates their backing dictionaries today โ€” they are not a shortcut to +real data. Telemetry must instead sample from the same side-effect-free +sources already used for signal-time logging: the inline regime calc in +BuildStrategyContext, the existing IFactorCalculator.Calculate() pure +functions, and/or TrendRegimeDetector.CalculateTrendStrength() / +VolatilityRegimeDetector.CalculateVolatilityScore() called directly +(these are pure calculators, not the stateful Detect*/Update* methods). + ## READ-FIRST 1. Locate where factor scores (Setup, Trend, Volatility, Timing, ExecutionQuality, NarrowRange, OrbRangeVsAtr, GapDirectionAlignment, diff --git a/TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md b/TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md new file mode 100644 index 0000000..8517d1d --- /dev/null +++ b/TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md @@ -0,0 +1,141 @@ +# TASK: GAP-045 / GAP-046 โ€” Risk-envelope coherence guards +# Staged: 2026-08-18 (v7.0 review, Findings 2, 3, 4) +# ACCEPTED: 2026-08-19 โ€” see DEC-20260818-19 and DEC-20260819-01. Both operator +# decisions made: (1) resolve collision via MNQ, (2) MaxTradeRisk is +# per-position (total), not per-contract. Part 3 below is rewritten accordingly +# and is now fully actionable. Per DEC-20260819-01, implement and validate +# Parts 1-3 on the CURRENT NQ CONFIGURATION FIRST; the MNQ instrument cutover +# itself is a separate follow-on step, not part of this task. +# Sprint: Stage 0 โ€” Unblock (P0-A2) + Stage 1 (P1-C) +# Owner: Kilocode +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +## CONTEXT โ€” two live outages on 2026-08-18, both from parameter pairs that +## are individually valid and jointly impossible + +GAP-046, from 14:30 ET onward, 27 rejections: + REJECT: reason=TrailingDrawdownBreach + detail=EnableTrailingDrawdown=True but AccountStartingBalance is not configured +Confirmed in settings_Simple_ORB_NT8_20260818_142340.txt: + EnableTrailingDrawdown: True / AccountStartingBalance: $0.00 +The guard behaviour is CORRECT. There is simply no startup assertion, so a +configuration error becomes a silent all-day trading outage. + +GAP-045, at 10:10 ET, five valid Sell signals rejected: + REJECT: reason=KillSwitch detail=Risk manager rejected: Trade risk too high: $225.00 +`BasicRiskManager.CalculateTradeRisk()` returns `StopTicks * tickValue` with NO +quantity term, evaluated BEFORE sizing. On NQ ($5.00/tick) `MaxTradeRisk=$200` +caps the stop at 40 ticks, while `MaxStopTicks=50` (=$250) is configured. The +top 20% of the ATR stop range is unreachable, and the days it excludes are the +high-ATR days on which ORB expansions are largest. + +## PART 1 โ€” Startup assertions (Kilocode, no approval needed) + +Extend the GAP-003 pattern (`RiskPerTrade > MaxTradeRisk` throws at validation +time with both values named). Add, in the same place and same style: + + A. `EnableTrailingDrawdown == true` MUST imply `AccountStartingBalance > 0`. + B. `MaxStopTicks * tickValue(symbol) <= MaxTradeRisk`. + C. `MinContracts <= MaxContracts` and `MinContracts >= 1`. + D. RESOLVED (was gated on Part 3, now decided): under the per-position + semantics adopted in DEC-20260818-19, `MaxTradeRisk` already represents + worst-case single-trade dollar risk regardless of contract count. The + assertion is `MaxTradeRisk <= DailyLossLimit` (NOT `MaxTradeRisk * + MaxContracts <= DailyLossLimit` โ€” that formula belonged to the old + per-contract semantics and must not be used). Implement as a throw, same + style as A-C. + +Each assertion must name BOTH values and the symbol in its message. Fail at +startup, not at 10:10 on a breakout. + +## PART 2 โ€” Distinguish misconfiguration from a real breach + +`TrailingDrawdownBreach` currently covers both "the account breached its floor" +and "you did not configure a floor." Add a distinct reject reason +`TrailingDrawdownNotConfigured` for the second case so REJECT SUMMARY counts +are meaningful. (This overlaps TASK_GAP048 โ€” coordinate; do not duplicate.) + +## PART 3 โ€” RESOLVED 2026-08-19 (DEC-20260818-19, DEC-20260819-01) โ€” now actionable + +Both decisions have been made by the operator. This part is no longer staged +for approval โ€” implement it, in this order, ON THE CURRENT NQ CONFIGURATION. +Do not fold the MNQ instrument cutover itself into this task; that is +DEC-20260819-01's separate follow-on step, staged after everything below is +validated. + + Decision 1 (collision) โ†’ **(c) MNQ**, staged as its own later cutover. + Nothing in this task changes the traded instrument. What this task DOES do + now, in preparation: confirm MNQ is present and correctly valued in BOTH + hardcoded tick-value tables (GAP-052 โ€” `BasicRiskManager.GetTickValue` and + `BasicPositionSizer.GetTickValue`). If MNQ is missing from either table, add + it (tick size 0.25, tick value $0.50) as part of this task's Read-First + verification โ€” this does not require an operator decision, it's a data-table + completeness fix blocking the already-decided cutover. Do NOT change the + live NQ `MaxTradeRisk`/`MaxStopTicks` values as a workaround for the + collision โ€” the collision is being resolved by instrument, not by retuning + NQ. + + Decision 2 (semantics) โ†’ **per-position (total)**, not per-contract. + Implement the real ordering change now approved: `BasicRiskManager`'s Tier 1 + check must move to AFTER `BasicPositionSizer` determines quantity, or must + take an estimated/candidate quantity from the sizer, so the enforced + inequality becomes `StopTicks * tickValue * Qty <= MaxTradeRisk` โ€” replacing + today's `StopTicks * tickValue <= MaxTradeRisk` with no `Qty` term. This is + the ordering change the original entry said must not be made without + approval; it is now approved. Read `BasicPositionSizer.CalculateFixedRisk` + and `BasicRiskManager.ValidateOrder` together before touching either โ€” get + the call sequence right rather than bolting a Qty multiply onto the existing + check in place, since the existing check runs before sizing today and that + ordering is the actual defect. + + Resulting worst-case single-trade risk: `MaxTradeRisk` itself (not + `MaxTradeRisk * MaxContracts`), matching Part 1 Assertion D above. This is a + strict safety improvement over the previously-undefined $600 worst case. + +## READ-FIRST + +- `src/NT8.Core/Risk/BasicRiskManager.cs` โ€” `ValidateOrder`, `CalculateTradeRisk`, + `GetTickValue` +- `src/NT8.Core/Sizing/BasicPositionSizer.cs` โ€” `CalculateFixedRisk`, `GetTickValue` + (NOTE: there are TWO independent hardcoded tick-value tables โ€” GAP-052. Do not + add a third. Confirm MNQ is present and correct โ€” tick size 0.25, tick value + $0.50 โ€” in BOTH tables; add it if missing per Part 3 Decision 1. Whether + consolidating the two tables belongs in this task or its own is still open โ€” + flag it, don't decide it.) +- `NT8StrategyBase.cs` โ€” the trailing-drawdown monitor and where GAP-003's + assertion currently lives + +## TESTS (required) + +- Each assertion: violating pair throws with both values in the message; + satisfying pair passes; disabled feature with an unset companion passes. +- A property test over the declared `[Range]` bounds of MaxStopTicks, + MaxTradeRisk, MaxContracts, MinContracts, RiskPerTrade and DailyLossLimit + asserting that no allowed combination permits a single-trade loss above + `MaxTradeRisk` (the now-defined per-position worst case). +- A test asserting the Tier 1 check's new ordering: for a case where the old + (pre-Qty) check would have passed but the new `Qty`-aware check must reject + (e.g. sizer would pick 2 contracts and `StopTicks * tickValue * 2 > + MaxTradeRisk`), confirm the trade IS rejected under the new logic. This is + the regression test proving the ordering change actually closed GAP-050. +- A test confirming MNQ resolves correctly in both `GetTickValue` tables. + +## VALIDATION (operator) + +- Set `EnableTrailingDrawdown=True` with `AccountStartingBalance=0` and confirm + the strategy refuses to start with a clear message, rather than running all + day and rejecting every entry. +- On NQ (current instrument, before cutover): confirm a signal that would have + produced the 2026-08-18 10:10 ET rejection (`Trade risk too high: $225.00`) + now either submits with a sizer-selected quantity that respects + `MaxTradeRisk`, or is rejected with a reason that clearly reflects the + per-position check rather than the old per-contract one. +- Confirm `MaxTradeRisk <= DailyLossLimit` throws at startup when violated. +- Do NOT validate the MNQ cutover itself here โ€” that's DEC-20260819-01's + separate step, after this task's NQ validation passes. + +## GOVERNANCE + +Track as [GAP-045] and [GAP-046] in SPRINT_BOARD.md. decisions.md entries +DEC-20260818-19 and DEC-20260819-01: accepted 2026-08-19. +Reference: NT8_SDK_Master_Document_v7.0 Findings 2/3/4, Sections 5.3, 5.13, 9.3, 9.4. diff --git a/TASK_GAP047_WEIGHT_RESCORE_PROMPT.md b/TASK_GAP047_WEIGHT_RESCORE_PROMPT.md new file mode 100644 index 0000000..58178d5 --- /dev/null +++ b/TASK_GAP047_WEIGHT_RESCORE_PROMPT.md @@ -0,0 +1,104 @@ +# TASK: GAP-047 โ€” Confluence factor weights are pre-populated to 1.0 +# PART 1: offline re-scoring study (NO runtime change) +# Staged: 2026-08-18 (v7.0 review, Finding 1) +# Sprint: Stage 1 (P1-A step 1) โ€” HIGHEST-VALUE TASK IN THE PROJECT +# Owner: Kilocode (analysis) โ†’ operator (the weighting decision) +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +## THE DEFECT + +`ConfluenceScorer`'s constructor (`ConfluenceScorer.cs` ~105-117) pre-populates +`_factorWeights` with 1.0 for ALL TEN FactorType values. `ResolveWeight(type, +fallbackWeight)` (~410-419) checks that dictionary FIRST and returns the stored +value if present. It always is. The `fallbackWeight` branch โ€” where each +calculator's designed weight arrives โ€” is unreachable dead code. + +The calculators DO emit the designed weights (`FactorCalculators.cs`): + NarrowRange 0.20 (line ~569) + OrbRangeVsAtr 0.15 (~670) + GapDirectionAlignment 0.15 (~797) + BreakoutVolumeStrength 0.20 (~897) + PriorDayCloseStrength 0.15 (~1021) +Factors 1-5 (Setup, Trend, Volatility, Timing, ExecutionQuality) are 1.00 by design. + +Runtime confirmation โ€” every STATE: line in every session reads `x1.00`: + + [10:10:11.833] STATE: Regime=Bearish Direction=Sell Score=0.640 Grade=C + Factors=Setup=1.00x1.00;Trend=0.30x1.00;Volatility=0.70x1.00;Timing=1.00x1.00; + ExecutionQuality=0.80x1.00;NarrowRange=0.45x1.00;OrbRangeVsAtr=0.50x1.00; + GapDirectionAlignment=0.10x1.00;BreakoutVolumeStrength=0.85x1.00; + PriorDayCloseStrength=0.70x1.00 + +## WHY THIS MATTERS MORE THAN ANYTHING ELSE ON THE BOARD + +Designed total weight is 5.85; actual is 10.00. Under the designed scheme a +setup where factors 1-5 score well reaches Grade A (>=0.80) on those five +alone โ€” 5.0 weighted points against the 4.68 required. Under equal weights, +Grade A requires the SUM of all ten factor scores to reach 8.0, so with +GapDirectionAlignment routinely at 0.10 and OrbRangeVsAtr at 0.50, the other +eight must average 0.925. + +Grade A is close to structurally unreachable. This is the leading hypothesis +for GAP-034a's silent zero-trade days, and โ€” via trade frequency โ€” for the +seven-month projected duration of a 20-trade gate sample. + +Worked example on the live data above: 0.640 (Grade C) at equal weights vs +0.727 (Grade B) under the designed weights. + +## PART 1 โ€” THE STUDY. THIS TASK IS ANALYSIS ONLY. CHANGE NO RUNTIME CODE. + +Every `STATE:` line already contains the full factor breakdown, so the entire +study can be run against existing logs with no new instrumentation. + +1. Build a standalone script under `tools/` (suggest `tools/rescore/`) โ€” + standalone Python, zero NT8 assembly references, same rules as the other + tools. Reuse `tools/dashboard/parsers.py`'s `STATE_RE` / + `parse_state_factors()` rather than writing a third parser. + +2. Input: all `session_*.log` files in the NT8 log directory AND its ARCHIVE + subtree. Parse every `STATE:` and every `SIGNAL_DETAIL:` line. + +3. For each sampled state, compute BOTH composites: + equal = sum(score_i) / 10 + designed = sum(score_i * w_i) / 5.85 + with w = [1,1,1,1,1, 0.20, 0.15, 0.15, 0.20, 0.15] in FactorType order. + Map both to grades: A+ >=0.90, A >=0.80, B >=0.70, C >=0.60, D below, F floor. + +4. Output, as JSON and markdown: + - Grade distribution under each scheme, overall and per session + - The COUNT of samples that would cross MinTradeGrade=5 (A) under designed + weights but do not under equal weights โ€” this is the headline number + - Same for MinTradeGrade=4 (B), since the live workspace currently runs 4 + - Per-factor mean score and per-factor contribution share under each scheme + - Sessions with zero SIGNAL lines, showing their best designed-weight score + โ€” i.e. how close each silent day came to qualifying + +5. Cross-check the arithmetic against the worked example above before trusting + any aggregate: the 10:10:11 sample on 2026-08-18 must reproduce 0.640 and + 0.727 exactly. If it does not, STOP and report. + +## KNOWN CAVEAT โ€” DO NOT SKIP THIS + +`STATE:` telemetry scores are computed from a synthetic intent whose +`DailyBarContext.TradeDirection` is stale (GAP-049, DEC-20260818-06), so +direction-sensitive factors (GapDirectionAlignment, PriorDayCloseStrength, and +possibly Trend) are unreliable in telemetry. `SIGNAL_DETAIL:` lines come from +the REAL accepted intent and are trustworthy. + +Report the two populations SEPARATELY. Do not pool them. If the sample of +`SIGNAL_DETAIL:` lines is too small to be meaningful, say so plainly โ€” the +telemetry population still bounds the effect but must be labelled as +direction-degraded. + +## PART 2 โ€” NOT THIS TASK + +The runtime change (removing the pre-population or making it +configuration-driven) requires an operator decision informed by Part 1's +output, and it changes ConfigHash, so it needs a fresh freeze capture. Stage it +separately once the study is in. + +## GOVERNANCE + +Track as [GAP-047] in SPRINT_BOARD.md. The study's output is the evidence for a +decisions.md entry, Status: proposed until the operator accepts. +Reference: NT8_SDK_Master_Document_v7.0 Finding 1, Sections 4.6, 9.4 (P1-A), 12.2 (O-01). diff --git a/TASK_GAP048_REJECT_TAXONOMY_PROMPT.md b/TASK_GAP048_REJECT_TAXONOMY_PROMPT.md new file mode 100644 index 0000000..0b40604 --- /dev/null +++ b/TASK_GAP048_REJECT_TAXONOMY_PROMPT.md @@ -0,0 +1,88 @@ +# TASK: GAP-048 โ€” Split the overloaded reject-reason taxonomy +# Staged: 2026-08-18 (v7.0 review, Finding 2 remedy (a)) +# Sprint: Stage 0 โ€” Unblock (P0-C). Diagnostics only, zero trading-behaviour risk. +# Owner: Kilocode +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +## THE DEFECT + +`REJECT SUMMARY` aggregates on `reason`. Three reasons are overloaded, so the +counts an operator and the dashboard read are ambiguous. + +`KillSwitch` is emitted by FOUR distinct paths in NT8StrategyBase.cs: + ~721 the actual kill switch (EnableKillSwitch=True KillSwitchTriggered=True) + ~1970 portfolio risk block (Portfolio blocked: ...) + ~2000 Tier 1 per-strategy risk (Risk manager rejected: ...) + ~2055 circuit breaker open (Circuit breaker open: ...) + +`GradeFilter` is emitted by FOUR paths: + ~1979 EnableLongTrades=False + ~1986 EnableShortTrades=False + ~2020 sized below MinContracts + SimpleORBStrategy.cs ~613/~622 regime veto before score + SimpleORBStrategy.cs ~650 genuine grade-below-threshold + +`TrailingDrawdownBreach` covers both a real breach and an unconfigured monitor. +`OrbRangeNotEstablished` covers three distinct ORB states. + +## WHY IT MATTERS โ€” two days, two meanings, one label + + 2026-08-17 session_20260817_082103.log REJECT SUMMARY: reason=KillSwitch count=647 + โ†’ detail=EnableKillSwitch=True KillSwitchTriggered=True (a real kill switch) + + 2026-08-18 session_20260818_071117.log REJECT SUMMARY: reason=KillSwitch count=5 + โ†’ detail=Risk manager rejected: Trade risk too high: $225.00 (MaxTradeRisk) + +The `detail` line distinguishes them, but `detail` is rate-limited to the first +occurrence per reason, so the aggregate count is all an operator sees. This +directly defeats what GAP-035 was built for. + +## THE CHANGE + +Replace the overloaded literals with distinct reasons. Suggested set โ€” confirm +naming before implementing: + + KillSwitch (leave ~721 as-is) + PortfolioRisk (~1970) + MaxTradeRisk (~2000) + CircuitBreaker (~2055) + LongTradesDisabled (~1979) + ShortTradesDisabled (~1986) + SizeBelowMinContracts (~2020) + RegimeVeto (SimpleORBStrategy ~613/~622) + GradeFilter (SimpleORBStrategy ~650 โ€” genuine grade rejection only) + TrailingDrawdownBreach (real breach only) + TrailingDrawdownNotConfigured (misconfiguration โ€” coordinate with TASK_GAP045_GAP046) + +Leave `OrbRangeNotEstablished` alone for now unless it is trivial โ€” its three +sub-states are already distinguishable in `detail` and it is lower priority. + +## CONSTRAINTS + +- Logging only. MUST NOT change any guard's CONDITION, ORDER or OUTCOME. +- `REJECT:` and `REJECT SUMMARY:` LINE FORMATS must not change โ€” only the value + of the `reason=` token. Downstream parsers (`tools/dashboard/parsers.py`, + `tools/logtriage/logtriage.py`, `tools/logwatch/logwatch.py`) are + reason-agnostic and should need no change. VERIFY that claim by reading them + rather than assuming it. +- `LogRejectRateLimited()` rate-limits per unique reason. Splitting reasons + therefore INCREASES the number of `REJECT:` detail lines slightly. Confirm + this is acceptable and note the expected volume change. +- The `HistoricalReplayCatchup` exemption in `LogRejectRateLimited()` must be + preserved (DEC-20260818-08). + +## TESTS + +Assert each of the paths above produces its own distinct `reason` value. +Assert the line format is byte-identical apart from the reason token. + +## VALIDATION (operator) + +Run one session and confirm `REJECT SUMMARY` shows distinct reasons, and that +the dashboard's rejection panels still render without a frontend change. + +## GOVERNANCE + +Track as [GAP-048] in SPRINT_BOARD.md. decisions.md entry recording the final +reason vocabulary โ€” it becomes a contract for every downstream tool. +Reference: NT8_SDK_Master_Document_v7.0 Finding 2, Appendix B, Section 9.3 (P0-C). diff --git a/TASK_GAP049_TELEMETRY_DIRECTION_PROMPT.md b/TASK_GAP049_TELEMETRY_DIRECTION_PROMPT.md new file mode 100644 index 0000000..95b2bab --- /dev/null +++ b/TASK_GAP049_TELEMETRY_DIRECTION_PROMPT.md @@ -0,0 +1,92 @@ +# TASK: GAP-049 โ€” Telemetry STATE score is direction-incorrect +# Staged: 2026-08-18 (v7.0 review, Finding 5) +# Sprint: Stage 1 (P1-D) +# Owner: Kilocode +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +## THE DEFECT + +`MaybeWriteStateTelemetry()` scores a SYNTHETIC intent built by +`BuildStateTelemetryIntent()`. Per DEC-20260818-06 that intent receives the +`daily_bars` object directly and deliberately does NOT call +`AttachDailyBarContext()`, because that helper mutates trade-direction, +breakout-volume and ORB fields on the shared object. + +But `GapDirectionAlignmentCalculator.Calculate()` reads `daily.TradeDirection` +โ€” a field ONLY `AttachDailyBarContext()` sets. In the telemetry path it is +therefore stale relative to the telemetry intent's own `Side`. + +## RUNTIME PROOF โ€” 2026-08-18 10:10:11 + + STATE: ... Direction=Sell ... Score=0.640 Grade=C + STATE_DETAIL: ... GapDirectionAlignment="Large gap -523.25 opposes trade โ€” high fade risk" + +A -523 (downward) gap should ALIGN with a Sell, scoring 1.00. It scored 0.10. +The same block reported OrbRangeVsAtr="No daily bar context available" despite +87 daily bars loaded and factor warm-up logged SATISFIED. + +Thirteen seconds later the REAL intent passed the grade filter and emitted +SIGNAL. Telemetry said Grade C; the trade path said it qualified. Both are in +the same log file. + +## WHY IT MATTERS + +Every `STATE:` line โ€” and therefore every Score, Grade, factor bar and +"missed B+ setup" count on the DASH-001/DASH-004 dashboard โ€” is computed from +direction-degraded inputs and understates quality on short setups. The +dashboard is currently misleading on exactly the question it exists to answer: +"was that a good setup the system passed on?" + +It also degrades the GAP-047 re-scoring study (see TASK_GAP047). + +## READ-FIRST + +- `NT8StrategyBase.cs` `MaybeWriteStateTelemetry()`, `BuildStateTelemetryIntent()` +- `SimpleORBNT8.cs` `BuildStateTelemetryIntent()` override +- `SimpleORBStrategy.cs` `AttachDailyBarContext()` โ€” establish EXACTLY which + fields it mutates and why DEC-20260818-06 avoided calling it +- `FactorCalculators.cs` GapDirectionAlignment / PriorDayCloseStrength / + TrendAlignment โ€” establish which factors read `daily.TradeDirection` or any + other field `AttachDailyBarContext()` sets + +## PREFERRED FIX + +Build a direction-correct CLONE of `DailyBarContext` for the telemetry path: +copy the warmed daily data, set `TradeDirection` from the telemetry intent's +own `Side`, and attach the clone. The shared object must not be mutated โ€” +that constraint from DEC-20260818-06 stands and is the reason a clone is +required rather than a call to `AttachDailyBarContext()`. + +Confirm whether `DailyBarContext` is safely cloneable (arrays vs references) +before assuming it. + +## INTERIM FIX โ€” if the clone is not straightforward + +Label the value honestly rather than leaving it wrong: +- Rename the dashboard's headline to "Telemetry score (advisory)" +- Add `TelemetryScore` / `TelemetryGrade` as fields distinct from + `ConfluenceScore` / `TradeGrade` in the DashboardState contract, so a + consumer can tell the two apart (v7.0 Section 14.5) + +## ALSO IN SCOPE โ€” verify, do not assume + +The logged gap magnitude of -523.25 points is implausible for a single +overnight NQ session (~1.7% of index value). Verify `DailyBarContext.TodayOpen` +and `Closes[Count-2]` alignment against known NQ daily closes. Report either +"the values are correct and the market gapped" or an identified alignment +defect. This is P1-E in the v7.0 roadmap and may be a separate gap. + +## CONSTRAINTS + +Observability only. MUST NOT change `SIGNAL`, `SUBMIT`, `FILL`, `PNL_UPDATE` +or `REJECT` behaviour, or any real trade decision. + +## TESTS + +Given identical bar and context, telemetry score == trade-path score for the +same side. A Sell setup with a downward gap must report "aligns", not "opposes". + +## GOVERNANCE + +Track as [GAP-049] in SPRINT_BOARD.md. decisions.md entry required. +Reference: NT8_SDK_Master_Document_v7.0 Finding 5, Sections 9.4 (P1-D, P1-E), 14.5. diff --git a/TASK_GAP054_RUNNER_TRAIL_PROMPT.md b/TASK_GAP054_RUNNER_TRAIL_PROMPT.md new file mode 100644 index 0000000..45f4c2a --- /dev/null +++ b/TASK_GAP054_RUNNER_TRAIL_PROMPT.md @@ -0,0 +1,130 @@ +# TASK: GAP-054 โ€” Auto-breakeven destroys the runner's trailing stop +# Staged: 2026-08-18 (v7.0 review, Finding 6) +# ACCEPTED: 2026-08-19 โ€” see DEC-20260818-18. Option 0 approved. Runner-scoping +# sub-question resolved to "unconditional skip, no new flag" (see decision entry). +# Sprint: Stage 2 โ€” Runner. BLOCKS RUNNER-001. +# Owner: Kilocode (implementation) +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +## THE DEFECT + +In NinjaScript, `SetStopLoss()` and `SetTrailStop()` are MUTUALLY EXCLUSIVE per +signal name โ€” the later call replaces the earlier exit order for that signal. + +At entry, `SubmitOrderToNT8()` (NT8StrategyBase.cs ~2178-2196) arms the runner +correctly: + + SetStopLoss (_runnerSignalName, Ticks, intent.StopTicks, false) + SetTrailStop(_runnerSignalName, Ticks, RunnerTrailTicks, false) // wins + EnterLong/EnterShort(runnerQty, _runnerSignalName) + +Then in `OnBarUpdate()` (~797-804): + + if (EnableAutoBreakeven && !_breakevenMoved && profitTicks >= BreakevenTriggerTicks) + { + SetStopLoss(_runnerSignalName, CalculationMode.Price, bePrice, false); + _breakevenMoved = true; + } + +That `SetStopLoss` call REPLACES the live trailing stop with a static stop at +entry + BreakevenOffsetTicks. The runner never trails again for that trade. + +The comment four lines below correctly warns against re-calling SetTrailStop +here (it would reset the anchor to bar-close price โ€” real defect, 2026-04-13). +That warning is still valid. The SetStopLoss call above it was not recognised +as doing worse. + +## RUNTIME PROOF โ€” all four broker-confirmed trades + +| Trade | Session log line | Profit at BE | 12t trail would sit | Stop actually went | +|-------|-----------------------------------------------------------|--------------|---------------------|--------------------| +| 08-07 | BREAKEVEN runner stop -> 29826.00 profit=28ticks | +28t | +16t | +1t | +| 08-10 | BREAKEVEN runner stop -> 29848.50 profit=25ticks | +25t | +13t | +1t | +| 08-16 | BREAKEVEN runner stop -> 30200.08 profit=24ticks | +24t | +12t | +1t | +| 08-17 | BREAKEVEN runner stop -> 30271.00 profit=26ticks | +26t | +14t | +1t | + +The breakeven action moves the stop BACKWARDS โ€” it gives back 11-15 ticks of +already-locked profit and then freezes. Conservative floor estimate: the runner +would have banked 55 ticks (~$275 gross / ~$252 net) instead of $25 / $1.96. + +## READ-FIRST โ€” do not start coding until you have confirmed all of these + +1. Read `NT8StrategyBase.cs` around lines 785-830 and 2170-2205 in full. +2. Confirm from NinjaTrader's own documentation that SetStopLoss and + SetTrailStop are mutually exclusive per signal name. Cite the doc page in + your writeback. If NinjaTrader documents different behaviour, STOP and + report โ€” the whole task premise depends on this. +3. Confirm `_runnerActive`, `_breakevenMoved` and `_runnerSignalName` lifecycle: + where each is set, cleared, and read. + +## THE CHANGE โ€” Option 0 (APPROVED โ€” DEC-20260818-18, 2026-08-19) + +Stop applying auto-breakeven to the RUNNER leg. A trailing stop already provides +monotonically improving protection and does it better at every point. + +- In the `OnBarUpdate` breakeven block, do NOT call `SetStopLoss()` on + `_runnerSignalName`. +- Do NOT call `SetTrailStop()` there either โ€” the existing warning stands. +- `EnableAutoBreakeven`, `BreakevenTriggerTicks` and `BreakevenOffsetTicks` + must remain as parameters and must continue to work unchanged for the + scaler leg. RESOLVED (DEC-20260818-18, 2026-08-19): skip breakeven on the + runner leg unconditionally โ€” do NOT add a new `EnableRunnerBreakeven` flag + or any other toggle. If `_runnerSignalName` is the leg in question, the + breakeven block simply does not act on it, full stop. +- Keep the `BREAKEVEN ...` FileLog line only if it still describes something + that happened. If the block no longer acts, remove the log line rather than + logging a no-op. + +DO NOT change: scaler leg stop/target handling, `intent.StopTicks`, the dynamic +ATR stop, sizing, risk validation, or order submission ordering. + +## SECONDARY DEFECTS IN THE SAME BLOCK โ€” fix only if Option 0 leaves the block live + +- `entryPrice` is `Position.AveragePrice` โ€” the BLENDED average across scaler + and runner legs, not the runner's own fill. On 2026-08-16 this produced a + breakeven price of 30200.08, which is not a valid NQ price (tick 0.25). + If any breakeven logic survives, it must use the runner leg's own entry and + must round to `TickSize`. +- `Calculate = OnBarClose` means `BreakevenTriggerTicks = 20` actually fires at + 24-28 ticks. Document this in the parameter's `Description` attribute so the + value stops meaning something it does not mean. + +## TESTS (required) + +Add to `tests/NT8.Core.Tests/` or `tests/NT8.Integration.Tests/`: + +1. A regression test asserting that, for a runner signal name, no `SetStopLoss` + call is issued after a `SetTrailStop` has been issued for that same signal. + Use the existing `MockNT8OrderAdapter` / recording-adapter pattern; if no + seam exists to observe these calls, say so explicitly and propose the + smallest seam rather than fabricating coverage (GAP-022 precedent). +2. A test asserting the scaler leg's stop/target behaviour is unchanged. +3. If any breakeven logic survives: a test that the breakeven price is a valid + multiple of `TickSize`, and that it derives from the runner's entry. + +## VALIDATION (operator, after deploy + manual NinjaScript compile) + +- SIM/replay only โ€” NOT the live frozen account โ€” until this passes. +- Take one SIM trade that reaches +25 ticks or more. Confirm NO + `BREAKEVEN runner stop ->` line appears for the runner. +- Confirm the runner's exit is materially better than entry + 1 tick, and that + the exit reason in the NT8 execution grid reads as a trail stop, not a + fixed stop. +- Confirm the scaler leg still exits at its profit target unchanged. + +## SEQUENCING โ€” IMPORTANT + +This task BLOCKS RUNNER-001 (`tools/runnersweep`). Sweeping +breakeven-trigger x trail-distance against a runner whose trail is disabled +would return a trail axis with no effect and a confident, meaningless +recommendation. Fix this first, then sweep. + +It also supersedes the framing in DEC-20260810-02 and DEC-20260815-01, both of +which describe this as a parameter-placement problem. Record a superseding +decision entry when the option is chosen. + +## GOVERNANCE + +Track as [GAP-054] in SPRINT_BOARD.md. Add a decisions.md entry recording the +option chosen, the NinjaTrader documentation citation, and the expected effect. +Reference: NT8_SDK_Master_Document_v7.0 Finding 6, Sections 4.8 and 9.5 (P2-0). diff --git a/TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md b/TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md new file mode 100644 index 0000000..7d9b847 --- /dev/null +++ b/TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md @@ -0,0 +1,93 @@ +# TASK: GAP-055 โ€” MaxDailyTrades does not survive a strategy restart +# Staged: 2026-08-18 (v7.0 review, Finding 7) +# Sprint: Stage 0 โ€” Unblock (P0-F) +# Owner: Kilocode +# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +## THE DEFECT + +`_dailyTradeCount` is a plain in-memory field in `SimpleORBStrategy.cs` (~39), +zeroed at construction (~269) and on session rollover (~756, ~961). Nothing +persists it. Any strategy stop/start resets the daily cap to zero. + +GAP-032 fixed the WITHIN-session reset on position-flat. It did not address +restarts, and this is NOT closed by it. + +## RUNTIME PROOF โ€” the cap was breached on 2026-08-17 + +The CME trading date 2026-08-17 begins at 18:00 ET on Sunday 2026-08-16. +Two trades were taken on that date, with `MaxDailyTrades = 1`: + + 2026-08-16 19:12 session_20260816_181528.log +$277.72 + 2026-08-17 11:04 session_20260817_110049.log +$267.72 + +They ran in different NT8 sessions, so the counter started at zero for the +second. NT8 itself treated them as ONE trading day โ€” the first PNL_UPDATE of +the 11:04 trade reads `DayPnL=$271.96` (= $277.72 less the $5.76 entry +commission) and the session closes at `DayPnL=$545.44`, the sum of both. + +Same class as the 7/28 breach that helped void Gate Run #2 (HIST-45). + +## WHY IT MATTERS NOW + +Gate discipline explicitly contemplates restarts โ€” recompiles, workspace +changes, connection recovery. A gate run under `MaxDailyTrades = 1` therefore +cannot currently guarantee its own cap, which makes the resulting sample +uninterpretable in exactly the way the previous two gate runs were. + +## READ-FIRST + +1. Read `SimpleORBStrategy.cs` around 39, 214, 269, 440-480, 660-680, 750-760, 955-965. +2. Read how `_currentSessionDate` is derived and where the trading-date boundary + is decided. Establish whether it uses the calendar date or NT8's session date. +3. Read how the trailing-drawdown monitor persists its Conservative halt file + (`{LogDirectory}/drawdown_halt_.json`, DEC-20260818-17) โ€” reuse + that pattern rather than inventing a second persistence mechanism. + +## THE CHANGE + +1. Persist `{ trading_date, daily_trade_count, account, strategy_name, symbol }` + to `{LogDirectory}/daily_trade_count__.json` each + time the count increments. +2. On `State.Realtime` entry, rehydrate: if the persisted trading date matches + the current trading date, restore the count; otherwise start at zero and + overwrite the file. +3. Align the trading-date boundary with the CME session rollover (18:00 ET), + not the calendar date. If `SessionManager` or NT8's own session iterator + already exposes the session date, USE IT โ€” do not hardcode 18:00. +4. Log the rehydration explicitly at session start: + `DAILY_TRADE_COUNT restored: date= count= max=` + or `DAILY_TRADE_COUNT reset: new trading date `. + +MUST NOT change signal generation, grading, risk validation, sizing or order +submission. This is a counter-persistence change only. + +## EDGE CASES TO HANDLE EXPLICITLY + +- Missing, unreadable or corrupt file โ†’ start at zero, log a WARNING, do not throw. +- `LogDirectory` blank โ†’ use the same default-path fallback as session logs and + provenance (DEC-20260817-01). Do not silently skip. +- Strategy Analyzer / backtest (`Account == null`) โ†’ do NOT read or write the + file. Backtest behaviour must be byte-for-byte unchanged. +- Two strategy instances on the same account and symbol โ†’ out of scope here; + note the behaviour you implement and flag it, do not try to solve it. + +## TESTS (required) + +1. Same trading date + existing file โ†’ count restored. +2. New trading date + existing file โ†’ count reset to zero, file overwritten. +3. Corrupt file โ†’ count zero, warning logged, no exception. +4. Backtest path โ†’ no file read, no file write. +5. The 08-16 19:12 / 08-17 11:04 scenario specifically: two sessions spanning + an 18:00 ET boundary on the same CME date resolve to ONE trading date. + +## VALIDATION (operator) + +Start the strategy, take one SIM trade, stop the strategy, restart it the same +trading day, and confirm the next signal is rejected with +`REJECT: reason=MaxDailyTrades`. + +## GOVERNANCE + +Track as [GAP-055] in SPRINT_BOARD.md. Add a decisions.md entry. +Reference: NT8_SDK_Master_Document_v7.0 Finding 7, Section 9.3 (P0-F). diff --git a/docs/00-governance/2026-08-19-run-book.md b/docs/00-governance/2026-08-19-run-book.md new file mode 100644 index 0000000..3c60cf2 --- /dev/null +++ b/docs/00-governance/2026-08-19-run-book.md @@ -0,0 +1,120 @@ +# NT8-SDK โ€” Today's Run Book +**Date:** 2026-08-19 +**Prepared by:** Claude (Senior PM role, v7.0 review follow-through) +**Scope:** Execute the six staged `TASK_*.md` prompts and four proposed decisions from the 2026-08-18 v7.0 review, in a sequence that gets zero-risk items done first and gates every exit-logic or risk-parameter change behind an explicit Mo decision. +**Governing constraint carried into today:** nothing in this run book authorizes Claude to touch `src/`. Every "run" step below is Kilocode's job, triggered by you handing it the named prompt file after you've made the paired decision. + +Source documents this run book operationalizes: `SPRINT_BOARD.md` (blockers section), `docs/00-governance/active_work.md` (staged section), `docs/00-governance/decisions.md` (DEC-20260818-18 through -21), and the six `TASK_*.md` prompts at repo root. + +--- + +## 0. Before you touch anything + +1. `git status --short` โ€” working tree should show only the governance/doc files from the 2026-08-18/19 review as modified. If `src/` shows changes you didn't make, stop and find out why before Kilocode runs anything. +2. Confirm no live position is open. GAP-054 and GAP-055 both touch behavior that matters mid-trade; don't start either while a position is live. +3. Confirm which account Kilocode's test/sim runs will use โ€” per gate discipline this should NOT be the frozen live account used for gate evidence. + +**STATUS 2026-08-19: ๐Ÿ›‘ HALTED HERE.** The operator ran this checklist and correctly stopped on all +three items. Findings (full detail in `docs/00-governance/current_status.md` ยง 2026-08-19): +1. `src/` showed two modified files. Investigated and identified as known DASH-002 work-in-progress + (trailing-drawdown monitor + state telemetry, both already-accepted decisions) sitting uncommitted + โ€” not unauthorized, but must be reconciled (recommend: commit DASH-002 as its own commit) before + GAP-054 lands on top of it, so each fix's diff stays isolated and reviewable. +2. Position status: today's last session log (ended 09:13:39 ET) shows zero entries/exits, consistent + with flat โ€” but that's a static file from an already-ended session, not a live query, and does not + substitute for checking the actual NT8 Account/Positions tab now that NinjaTrader is confirmed running. +3. Account: today's session log labels the configured account **"gate account SimSimple ORB"** in its + own warning line. This is the opposite of confirmed-non-gate โ€” needs explicit operator resolution + before any SIM/test activity touches NT8, to avoid contaminating gate-run cleanliness the way Gate + Run #2 was contaminated (HIST-45). + +**Nothing past this point in the run book proceeds until items 1-3 above are explicitly resolved by +the operator.** Plays 2-4 (GAP-048, GAP-047 Part 1) are the exception โ€” zero risk, no account +interaction, no `src/` conflict with DASH-002 โ€” and remain clear to run. + +**UPDATE 2026-08-19, later same day โ€” 2 of 3 cleared.** Operator confirmed: position flat, +NinjaTrader closed, and the account question is moot for now โ€” `SimSimple ORB` isn't gate +evidence; a distinctly `gate3`-named account will be stood up for the real Gate Run #3. Items 2 +and 3 are resolved. **Item 1 (uncommitted DASH-002 diff in `src/`) is still open** โ€” NinjaTrader +being closed makes this a safe window to commit it, but that's an explicit go/no-go for the +operator, not something to do by default. Play 5 (GAP-054) should still hold until this is +answered, so the fix lands as an isolated, reviewable diff rather than on top of DASH-002's +881-line uncommitted change. + +--- + +## 1. Decision gate โ€” CLEARED 2026-08-19 + +All five decisions were made today. `decisions.md` has been updated to `accepted` for each, and a new entry `DEC-20260819-01` was added to sequence the MNQ cutover as a separate follow-on step. + +| Decision | Ask | Your call (2026-08-19) | Stakes | +|---|---|---|---| +| **DEC-20260818-18** | Stop applying auto-breakeven to the runner leg (Option 0) | **Accepted.** Parameter-scoping sub-question (flag vs. unconditional skip) resolved by default to unconditional skip, no new flag โ€” flag if you want it different. | High โ€” changes live exit behavior | +| **DEC-20260818-19a** | Resolve MaxTradeRisk/MaxStopTicks collision | **Accepted โ€” (c) move to MNQ.** | High โ€” changes risk envelope | +| **DEC-20260818-19b** | Is MaxTradeRisk per-contract or per-position? | **Accepted โ€” per-position (total).** Requires the Tier 1 check to move to after sizing; now written into `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` Part 3. | Medium | +| **DEC-20260818-20** | Approve the split reject-reason taxonomy vocabulary | **Accepted**, as proposed. | Zero | +| **DEC-20260818-21** | Approve MaxDailyTrades restart-persistence design | **Accepted**, as proposed. | Low-medium | +| **DEC-20260819-01** *(new)* | Sequencing: land all code fixes on NQ first, cut over to MNQ as a separate later step with a fresh Gate 3 freeze | **Accepted** โ€” this is my recommendation, written up as its own decision entry so the MNQ switch doesn't get conflated with defect-fix validation. Flag if you'd rather cut over sooner. | Medium โ€” affects order, not outcome | + +All six `TASK_*.md` prompts are now unblocked. Nothing is waiting on you to clear Section 2 anymore โ€” every Play below can run today. + +--- + +## 2. Play by play + +**Play 1 โ€” Decide. DONE 2026-08-19.** All five decisions recorded in `decisions.md`. + +**Play 2 โ€” Kick off the two zero-risk tracks in parallel.** +- Hand `TASK_GAP048_REJECT_TAXONOMY_PROMPT.md` to Kilocode. +- Hand `TASK_GAP047_WEIGHT_RESCORE_PROMPT.md` to Kilocode. +Both can run at the same time; neither touches runtime behavior. + +**Play 3 โ€” Review GAP-048 output.** Confirm the four overloaded KillSwitch paths and four overloaded GradeFilter paths now log distinguishable reasons, that existing log-line formats are unchanged (only the reason string), and that the existing test suite still passes. Mark SPRINT_BOARD entry done. + +**Play 4 โ€” Review GAP-047 output.** This is a study, not a change โ€” read the re-scoring report (equal-weight vs. designed-weight composite against historical STATE:/SIGNAL_DETAIL: lines). Confirm it reports the pre/post GAP-049 telemetry populations separately, per the task's caveat. Do NOT apply any weight change from this yet; it's an input to a future decision, not an approved fix. + +**Play 5 โ€” Runner trail fix (DEC-18 accepted). DONE 2026-08-21, source-verified.** +Kilocode implemented Option 0: removed the `OnBarUpdate()` `SetStopLoss` call on the runner signal, added no new `SetTrailStop` call, removed the stale `Diag_Breakeven` draw, cited NT8's own API docs on the mutual-exclusivity behavior. Independently re-read the changed code directly (not just the report) โ€” confirmed. Build/tests/deploy all passed, hash matches. Two low-priority follow-ups logged in the process (GAP-056: breakeven params now fully inert, not scaler-scoped as previously assumed; GAP-057: no test seam for NT8 managed-order call assertions) โ€” see `decisions.md` DEC-20260821-01. **Not committed yet** โ€” sits on top of the still-unreconciled DASH-002 diff from Section 0; recommend two separate commits (DASH-002 first, GAP-054 second) when the operator is ready to commit. + +**Play 6 โ€” Validate GAP-054 before any live exposure. STILL PENDING โ€” this is the next actual step.** +NinjaTrader needs to be reopened for a manual NinjaScript compile, then a SIM trade run reaching +25 ticks or more, confirming no `BREAKEVEN runner stop ->` line appears and the runner's exit is materially better than entry + 1 tick (a trail stop in the execution grid, not a fixed stop), and that the scaler leg's target behavior is unchanged. Only after this passes is GAP-054 done and RUNNER-001 unblocked. + +**Play 7 โ€” Risk guards, all three parts (DEC-19a/19b accepted).** +Hand `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` to Kilocode in full โ€” Part 3 is now written as directly actionable: implement the Tier 1 check reordering (post-sizing, `Qty`-aware) and confirm MNQ is present and correctly valued in both `GetTickValue` tables (GAP-052) as prep for the later cutover. **Do this on the current NQ configuration โ€” do not switch the traded instrument as part of this task.** That's Play 11. + +**Play 8 โ€” MaxDailyTrades persistence (DEC-21 accepted).** +Hand `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` to Kilocode. Validate with a manual restart test spanning a simulated 18:00 ET rollover boundary โ€” confirm the count persists across a restart within the same trading day and resets across the boundary. + +**Play 9 โ€” GAP-049 telemetry direction fix.** +No decision gate โ€” this is dashboard/telemetry accuracy only. Hand `TASK_GAP049_TELEMETRY_DIRECTION_PROMPT.md` to Kilocode any time today. Validate by re-checking the implausible -523.25 point gap value the task flags; confirm it resolves to a sane number after the fix. + +**Play 10 โ€” Close out today's six items.** +For every item completed today: flip its `decisions.md` Status to `implemented` as appropriate, update `SPRINT_BOARD.md` and `active_work.md` to move it out of the blockers section, and commit the governance-doc changes. Leave anything not completed today explicitly marked with what's left and why. + +**Play 11 โ€” MNQ cutover (DEC-20260819-01), only after Plays 5-8 all pass validation.** +This is a separate, later step โ€” not part of today's six tasks. Once GAP-054, GAP-045/046, and GAP-055 have landed and validated on NQ: stage a new `TASK_MNQ_CUTOVER_PROMPT.md` (not yet written), reconfigure the strategy instance to trade MNQ, retune `MaxTradeRisk`/`MaxStopTicks`/`MaxContracts` for MNQ's $0.50/tick economics rather than carrying over NQ-era values unexamined, then run `preflight.ps1 --freeze` and record a new `DEC-GATE3-CONFIG` before collecting any gate-run evidence on MNQ. Don't compress this into the same session as the code fixes โ€” if something breaks, you want to know whether it was a defect fix or the instrument switch. + +--- + +## 3. Stop conditions โ€” halt and escalate rather than push through + +- Any existing test fails after a Kilocode change. +- Kilocode touches a file outside the task's explicit DO list. +- Anything in Play 5-6 (GAP-054) is tested against the live frozen account before sim/replay validation passes. +- Play 11 (MNQ cutover) starts before Plays 5-8 have all validated on NQ. +- Kilocode changes the traded instrument as a side effect of Play 7 โ€” that's explicitly out of scope for `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md`. + +--- + +## 4. End-of-day checklist + +- [x] Section 1 decisions recorded โ€” all accepted 2026-08-19 +- [ ] GAP-048 taxonomy: implemented, tested, SPRINT_BOARD updated +- [ ] GAP-047 Part 1: study delivered, read, weight-change decision explicitly deferred (not silently applied) +- [ ] GAP-054 runner trail: implemented, validated on sim/replay before any live gate run +- [ ] GAP-055 persistence: implemented, restart/rollover-boundary test passed +- [ ] GAP-045/046 all three parts: implemented on NQ, including the post-sizing Tier 1 reorder and the MNQ tick-table check +- [ ] GAP-049 telemetry: implemented, -523.25 anomaly re-checked and resolved +- [ ] `git status --short` re-checked: confirm exactly the files each TASK prompt's DO list authorized, nothing else +- [ ] SPRINT_BOARD.md, active_work.md, decisions.md all reflect end-of-day state +- [ ] MNQ cutover (Play 11) explicitly NOT started until the six items above are validated โ€” confirm it's still pending, not skipped diff --git a/docs/00-governance/active_work.md b/docs/00-governance/active_work.md index 6448520..b3338b8 100644 --- a/docs/00-governance/active_work.md +++ b/docs/00-governance/active_work.md @@ -1,9 +1,36 @@ # Active Work -**Last Updated:** 2026-08-16 +**Last Updated:** 2026-08-19 (all four proposed decisions accepted; see decisions.md) + +## READY 2026-08-19 โ€” v7.0 review blockers, decisions accepted, none yet executed + +All four decisions proposed 2026-08-18 were accepted by the operator on 2026-08-19 +(DEC-20260818-18, -19, -20, -21), plus a new DEC-20260819-01 sequencing the MNQ +instrument cutover as its own follow-on step. Nothing below has been implemented yet โ€” +these are now unblocked for Kilocode, not still awaiting a decision. +Play-by-play execution order: `docs/00-governance/2026-08-19-run-book.md`. +Full detail: `docs/NT8_SDK_Master_Document_v7.0_Complete.docx`. + +| Order | Item | Prompt | Owner | Blocking | +|---|---|---|---|---| +| 1 | **GAP-046** โ€” set `AccountStartingBalance` or disable `EnableTrailingDrawdown` | operator action, no code | Operator | Every entry, from 14:30 ET daily | +| 2 | **GAP-045/046 guards** โ€” resolved: MNQ (cutover staged separately) + per-position semantics | `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` (Part 3 now actionable) | Kilocode, on current NQ config | All high-ATR days | +| 3 | **GAP-048** โ€” split the reject taxonomy | `TASK_GAP048_REJECT_TAXONOMY_PROMPT.md` | Kilocode | Nothing โ€” diagnostics only, safe now | +| 4 | **GAP-055** โ€” persist `MaxDailyTrades` across restarts | `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` | Kilocode | Gate Run #3 sample integrity | +| 5 | **GAP-047 Part 1** โ€” offline factor-weight re-scoring study | `TASK_GAP047_WEIGHT_RESCORE_PROMPT.md` | Kilocode | Nothing โ€” analysis only. **Highest value on the board** | +| 6 | **GAP-054** โ€” auto-breakeven destroys the runner trail | `TASK_GAP054_RUNNER_TRAIL_PROMPT.md` โ€” **Option 0 implemented + source-verified 2026-08-21, NOT yet SIM-validated, NOT committed** | Kilocode implemented; operator validates | **RUNNER-001**, still blocked until SIM/replay validation passes | +| 7 | **GAP-049** โ€” telemetry `STATE:` score is direction-incorrect | `TASK_GAP049_TELEMETRY_DIRECTION_PROMPT.md` | Kilocode | Dashboard trustworthiness; degrades item 5 | +| 8 | **MNQ cutover** โ€” reconfigure instrument, retune risk params for $0.50/tick, fresh Gate 3 freeze | not yet staged as its own TASK file | Operator + Kilocode | Only after items 2, 4, 5, 6 pass validation on NQ | + +**Sequencing note:** items 3 and 5 carry zero trading risk and can proceed immediately, in +parallel with everything else. Item 6 must land (and validate on SIM/replay) before +RUNNER-001 is executed. Item 8 (MNQ cutover) must NOT start until items 2, 4, 5, and 6 +have landed and validated on the current NQ configuration โ€” see DEC-20260819-01. + +--- ## GAP-035 โ€” Rejection-reason file logging (HIGHEST PRIORITY) **Owner:** Kilocode -**State:** Deployed 2026-08-16; pending live Output-window-to-file cross-check. It is not fully closed until the operator session confirms Output and session file agree. +**State:** Deployed 2026-08-17 (deploy-to-nt8.bat, backup `20260817_180455`); DEC-20260817-01/02 provenance fixes deployed in the same pass, source hashes verified against repo. `NinjaTrader.Custom.dll`/`.pdb` confirmed absent โ€” clean recompile is queued for next NT8 launch. Not yet compiled or cross-checked live. All four zero-trade candidates log via `_logger` only and never reach the session file. Route every signal-rejection reason through `FileLog` alongside `_logger` so a no-trade diff --git a/docs/00-governance/architecture.md b/docs/00-governance/architecture.md index 7dffddc..cb39555 100644 --- a/docs/00-governance/architecture.md +++ b/docs/00-governance/architecture.md @@ -26,3 +26,77 @@ SimpleORBNT8.cs ## Governance Notes - Core Risk/Sizing/OMS/Intelligence/Analytics layers are treated as complete and stable unless explicitly re-opened by approved work. - Hardening changes are concentrated in targeted adapter/utility components per active-work scope. + +## Platform-Neutral SDK Invariant (confirmed 2026-08-17) +`NT8.Core` (Risk, Sizing, OMS, Intelligence, Analytics, Common) contains zero +`NinjaTrader.*` references anywhere in the project โ€” confirmed by direct read +of every file touched in recent sessions (`RegimeManager.cs`, +`TrendRegimeDetector.cs`, `VolatilityRegimeDetector.cs`, `FactorCalculators.cs`, +`PortfolioRiskManager.cs`, and others). `NT8.Adapters` is the only layer that +references NinjaTrader assemblies; it exists specifically to translate between +`NT8.Core`'s broker-agnostic models (`BarData`, `StrategyContext`, +`StrategyIntent`, `OrderSide`, etc.) and NT8's own types. This is a real, +maintained property today, not an aspiration โ€” a future adapter for a +different broker/API would implement the same bridge pattern `NT8.Adapters` +uses, without touching `NT8.Core`. +**Rule:** `NT8.Core` must never gain a `using NinjaTrader.*` reference. Any +PR/Kilocode prompt that would add one should be rejected or redirected to +put that logic in `NT8.Adapters` instead. + +## Multi-Strategy / 24x7 Trading Architecture (clarified 2026-08-17) +The "shared everything but entry" pattern referenced in earlier planning is +already the real architecture, not a future change: +- `NT8StrategyBase.cs` (shared): risk gate sequencing, sizing, provenance, + logging, runner/breakeven management, regime gate, portfolio coordination. +- Each strategy's *entry* logic is a separate `IStrategy` implementation + (e.g. `SimpleORBStrategy.cs`) paired with a thin NinjaScript adapter + subclass of `NT8StrategyBase` (e.g. `SimpleORBNT8.cs`). +- Sprint 4 (`roadmap.md`) already plans exactly this pattern for + `VWAPMeanReversion`, `OvernightGapContinuation`/`OvernightGapReversion`, + and `LondonORBNT8` โ€” each a new entry module, not a rewrite of the shared + base. + +**24x7 coverage is concurrent strategy instances with disjoint session +windows, not an on/off switch between strategies.** Each session-scoped +strategy (RTH ORB, London ORB, overnight gap) runs as its own NinjaScript +strategy instance, simultaneously, each gated to its own trading window. +`PortfolioRiskManager.Instance` already exists specifically to coordinate +risk across concurrently-registered strategies (`RegisterStrategy()`, +`ValidatePortfolioRisk()` enforces a combined daily loss limit and a total +open-contract cap across every registered strategy) โ€” this was already +built for this scenario, it just hasn't been exercised with more than one +strategy family yet. Running `SimpleORBNT8` plus a future `LondonORBNT8` +simultaneously on the same account is the intended production pattern, not +a single-frozen-account gate-validation-only concept (that doctrine +governs *gate validation discipline*, not permanent production topology). + +**Known gap: no multi-account dimension.** `PortfolioRiskManager` is a +process-wide singleton keyed only by `strategyId` โ€” there is no account key +anywhere in its state (`_strategyPnL`, `_strategyOpenContracts`, +`_registeredStrategies` are all `Dictionary` with no account +segregation). Two strategies on *different* accounts would currently have +their P&L and contract counts aggregated together incorrectly. This must be +fixed (add an account key to the singleton's internal dictionaries, or move +to per-account instances) before "multiple accounts simultaneously" is safe +to run. Tracked as GAP-042 in `roadmap.md`. + +## Control Plane (answers "must this be an NT8 AddOn?") +Two real paths exist; the NT8 AddOn is not the only option: +1. **NT8 AddOn (WPF panel)** โ€” already on the roadmap (Sprint 6, "NT8 Add-On + WPF panel"). Fully NT8-native, can call directly into running strategy + instances. Ties the control UI to NT8's process and UI framework. +2. **External command channel** โ€” more aligned with the platform-neutral + goal. `IStrategy.SetParameters(Dictionary)` already + exists and is already used internally (`force_session_reset`, + `clear_trade_taken`). This could be extended so `NT8StrategyBase` + polls a small local command file/HTTP endpoint on each bar close (which + already fires every bar regardless of strategy) and applies any pending + command via the existing `SetParameters()` path, then acknowledges it. + This keeps the command surface broker-agnostic โ€” the same mechanism + would work if `NT8.Adapters` were ever joined by an adapter for a + different platform, whereas an NT8 AddOn only ever works for NT8. +**Recommendation:** build the external command channel first (smaller, +platform-neutral, reuses existing `SetParameters()` plumbing) and treat the +NT8 AddOn as an optional additional UI surface later, not a prerequisite. +Neither is scoped for implementation yet โ€” this section records the design +direction so it isn't re-litigated from scratch later. diff --git a/docs/00-governance/current_status.md b/docs/00-governance/current_status.md index f9a8cb7..23e21d5 100644 --- a/docs/00-governance/current_status.md +++ b/docs/00-governance/current_status.md @@ -1,5 +1,281 @@ # Current Status โ€” NT8 SDK -**Last Updated:** 2026-08-16 (weekly Sunday republish โ€” see `docs/02-runbooks/weekly_roadmap_cadence.md`) +**Last Updated:** 2026-08-21 (GAP-054 implemented and source-verified, not yet validated or committed โ€” see below) + +--- + +## 2026-08-21 โ€” GAP-054 Option 0 IMPLEMENTED, independently source-verified, NOT yet validated or committed + +Kilocode reported implementing Option 0 (DEC-20260818-18) in `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`: +removed the `OnBarUpdate()` call that set a static `SetStopLoss` on the runner leg after entry, added +no new `SetTrailStop()` call, removed the stale `Diag_Breakeven` runner draw object, and cited local +NT8 API documentation (`NinjaTrader.Core.xml`) confirming `SetStopLoss`/`SetTrailStop` are both +signal-scoped `fromEntrySignal` methods. `verify-build.bat` (511/511) and `NT8.Core.Tests` (422/422) +passed, `deploy-to-nt8.bat` succeeded, and the deployed source hash was confirmed matching the repo. +No new regression test was added for the SetStopLoss/SetTrailStop ordering itself โ€” Kilocode reported +no clean test seam exists for NT8's managed-order calls and correctly declined to fabricate coverage, +per the task file's own instruction for that scenario. + +**This review independently re-read the changed code** (not just Kilocode's report) and confirms: +- The `OnBarUpdate()` runner block is now comment-only โ€” no `SetStopLoss`/`SetTrailStop` call remains. +- The `BREAKEVEN runner stop ->` `FileLog` line is gone, not just the chart diagnostic. +- **Correction to the record:** DEC-20260818-18's implementation carried forward a line (written + during the 2026-08-19 decision-acceptance pass) claiming `EnableAutoBreakeven`/`BreakevenTriggerTicks`/ + `BreakevenOffsetTicks` "continue to govern the scaler leg only, unchanged." Source inspection shows + this was never accurate โ€” the pre-fix breakeven block only ever acted on the runner signal; there was + no separate scaler-leg breakeven path to preserve. All three parameters are now fully inert (declared, + defaulted, referenced once in a log/settings line, read nowhere else). Functionally harmless โ€” it + matches the intended zero-breakeven outcome โ€” but is a stale-parameter hygiene issue. Corrected in + `decisions.md`; logged as **GAP-056** (new, DEC-20260821-01) for a future low-priority cleanup + (Description-attribute update or removal). +- **GAP-057** (new, same entry): the missing test-seam proposal for NT8 managed-order call assertions + is worth its own lightweight follow-up, since this is the same defect class (silent exit-order + clobbering) that produced GAP-054 in the first place. + +**What's still outstanding before this is done:** +1. **SIM/replay validation has not happened.** Per the task file and DEC-20260818-18's own Action + Required: take one SIM trade reaching +25 ticks or more, confirm no `BREAKEVEN runner stop ->` line, + confirm the runner exits materially above entry + 1 tick as a trail stop rather than a fixed stop, + confirm the scaler leg's target behavior is unchanged. NinjaTrader is currently closed, so this + requires a manual NinjaScript compile and a SIM session before it can run. +2. **Not committed.** Kilocode explicitly held off ("commits require explicit request"). This now sits + on top of the still-unreconciled DASH-002 diff flagged 2026-08-19 below โ€” GAP-054 and DASH-002 are + both uncommitted in the same working tree. Recommend committing as two separate commits (DASH-002 + first, GAP-054 second) to preserve an isolated, reviewable history for each, once the operator + decides to commit. +3. **RUNNER-001 remains blocked** until validation (item 1) passes โ€” the sweep must not run against + an unvalidated fix any more than it should run against the original defect. + +--- + +## 2026-08-19 โ€” PREFLIGHT HALTED before GAP-054 start (operator call, correctly enforced) + +All five decisions from the 2026-08-18 v7.0 review were accepted 2026-08-19 (DEC-20260818-18/19/20/21, +DEC-20260819-01), and all six staged `TASK_*.md` prompts were marked โœ… READY. Before handing GAP-054 +to Kilocode, the operator ran the run book's Section 0 preflight and correctly halted on four findings. +**No GAP-054 (or any) implementation work has started.** This section documents the findings โ€” read-only +investigation only, nothing in `src/` was touched by this investigation. + +### Finding 1 โ€” the two modified `src/` files are known, already-accepted work-in-progress, not unknown changes +`git diff --stat -- src/` shows: +- `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` โ€” 881 insertions / 84 deletions +- `src/NT8.Adapters/Strategies/SimpleORBNT8.cs` โ€” 159 insertions + +Content inspection (`git diff` keyword search) confirms both diffs are **DASH-002** โ€” +the `TrailingDrawdownMonitor` implementation (DEC-20260818-17, accepted 2026-08-18) plus the +`EnableStateTelemetry`/`EnableEthTelemetry` continuous confluence/regime telemetry (DEC-20260817-* +series, unblocked 2026-08-17/18). `TASK_DASH-002_PROMPT.md` itself is also modified (34-line +append, consistent with the task file's own completion-note convention). `roadmap.md` already +noted this state: "DASH-002 (`EnableStateTelemetry`) remains prompt-staged; no implementation has +[been] committed." This is expected, tracked, already-decided work sitting uncommitted โ€” **not** +an unauthorized or unexplained change. It is still a real precondition problem for GAP-054: landing +GAP-054's runner-trail fix in `NT8StrategyBase.cs` on top of an uncommitted 881-line diff makes +GAP-054's own diff impossible to review in isolation and impossible to cleanly roll back. +**Recommended reconciliation: commit the DASH-002 work as its own commit (citing DEC-20260818-17 +and the DEC-20260817-04/09 series) before any GAP-054/045/046/055 work starts**, so each subsequent +fix produces an isolated, reviewable diff. This is Kilocode/operator's call, not made unilaterally here. + +### Finding 2 โ€” the currently configured account is logged as the GATE account, not a separate SIM account +Today's session log (`session_20260819_073754.log`, 07:37:54โ€“09:13:39 ET) logs: +`Account : SimSimple ORB` ... `WARNING: EnableKillSwitch=False for gate account SimSimple ORB.` +The phrase **"gate account SimSimple ORB"** is the strategy's own internal label. This directly +bears on the operator's stop condition #4 (confirm the test account is a non-gate SIM account) โ€” +the evidence points the other way: the account currently wired into the NT8 instance appears to be +the same one used for gate-run evidence, not a separate disposable SIM account. +**This needs explicit operator confirmation before any validation activity, live or SIM, touches +NT8** โ€” testing GAP-054 on the gate account risks the same kind of contamination that voided Gate +Run #2 (HIST-45), even in SIM mode, if it leaves state, logs, or habits that bleed into the next +real gate attempt. + +### Finding 3 โ€” position status cannot be confirmed from static files; this file inspection does not substitute for a live check +Same session log: zero `ENTRY`/`EXIT`/`MarketPosition` lines appear anywhere in the file โ€” every +line is a `REJECT` (`HistoricalReplayCatchup` x1, `RthGuard` x7, `WarmupIncomplete` x1) โ€” consistent +with a flat position as of the session's own end at 09:13:39 ET. The settings export +(`settings_Simple_ORB_NT8_20260819_073755.txt`) still shows `AccountStartingBalance: $0.00` with +`EnableTrailingDrawdown` โ€” the exact GAP-046 misconfiguration โ€” still live in the deployed config. +**This is supporting evidence only.** The session log file is a static snapshot from a session that +had already ended before this investigation; NinjaTrader is reported running now (PID 34864), and +no tool available to this review can query live position state. The operator's own live check of the +NT8 Account/Positions tab remains the only real confirmation. + +### Finding 4 โ€” `tools/runnersweep/RUNNER-001_sweep_output.{json,md}` predate the GAP-054 finding +Both files are timestamped 2026-08-17 22:01, before the 2026-08-18 review that diagnosed the runner +trail defect. Per `TASK_GAP054_RUNNER_TRAIL_PROMPT.md`'s own sequencing note, a sweep run against a +runner whose trail was silently disabled "would return a trail axis with no effect and a confident, +meaningless recommendation." **This existing output should be treated as superseded/invalid and +RUNNER-001 re-run only after GAP-054 lands and validates** โ€” flagging so it isn't mistaken for a +current result. + +### What is NOT blocked +GAP-048 (reject taxonomy) and GAP-047 Part 1 (offline weight re-scoring study) remain zero-risk, +diagnostics/analysis-only, and do not touch `src/` in a way that interacts with position state or +the gate account question โ€” Plays 2-4 in the run book can proceed independently of this halt. + +### 2026-08-19, later same day โ€” Findings 2 and 3 resolved by operator; Finding 1 still open + +Operator confirmed directly: live position is flat, NinjaTrader is closed (removing all +account-touching risk for the moment), and the current `SimSimple ORB` account/label is "not of +consequence" โ€” a new account with `gate3` explicitly in its name will be set up for the actual +Gate Run #3 evidence, kept distinct from whatever account casual SIM testing uses. This resolves +the ambiguity Finding 2 raised: `SimSimple ORB` is not being relied on as gate-run evidence, so +testing GAP-054 on it does not risk contaminating Gate 3 the way Gate Run #2 was contaminated. +**Recommended going forward: apply the same explicit-naming discipline to every future +purpose-specific account** (a `gate3`-named account for gate evidence, clearly distinct names for +anything else), so this ambiguity doesn't recur โ€” worth folding into `DEC-GATE3-CONFIG` guidance +whenever that's next touched. + +**Finding 1 (the uncommitted DASH-002 diff in `src/`) is still open** โ€” not addressed by this +message. NinjaTrader being closed makes now a safe window to commit it before GAP-054 lands on +top, but that action (`git add`/`git commit`) has not been taken; it needs an explicit go-ahead +rather than being done unilaterally, since it formalizes already-implemented code into history. +Recurring housekeeping note: a stale `.git/index.lock` has now appeared twice in this repo +(cleared both times by renaming it aside); if this keeps recurring it's worth finding what's +creating it before it blocks an actual `git commit`. + +--- + +## 2026-08-18 โ€” v7.0 REVIEW: TWO NEW LIVE BLOCKERS AND ONE LONG-STANDING DEFECT + +Source: `docs/NT8_SDK_Master_Document_v7.0_Complete.docx` (+ `docs/NT8_SDK_v7.0_Visual_Pack.html`). +First review conducted with simultaneous access to the repository **and** the live NinjaTrader +log directory. **No source code was changed by this review.** Everything below is a finding +plus a recommendation; nothing has been applied. + +### BLOCKER โ€” GAP-045: `MaxTradeRisk` / `MaxStopTicks` collision stops all trades on high-ATR days +`session_20260818_071117.log`, 10:10:24 ET: +`REJECT: reason=KillSwitch detail=Risk manager rejected: Trade risk too high: $225.00` +Five valid `SIGNAL: Sell NQ` lines, zero submissions. `BasicRiskManager.CalculateTradeRisk()` +returns `StopTicks x tickValue` (no quantity term, evaluated before sizing). A 45-tick ATR stop +on NQ = $225 > `MaxTradeRisk` $200. `MinContracts=1` is already the floor, so the trade is +unplaceable, not resizable. `MaxStopTicks=50` (= $250) and `MaxTradeRisk=$200` are mutually +inconsistent: the top 20% of the configured stop range is unreachable. +**Fix: choose `MaxTradeRisk=$250` or `MaxStopTicks=40`, record the decision.** + +### BLOCKER โ€” GAP-046: trailing-drawdown monitor blocks every entry when misconfigured +`session_20260818_142340.log`, 14:30 ET onward, 27 rejections: +`REJECT: reason=TrailingDrawdownBreach detail=EnableTrailingDrawdown=True but AccountStartingBalance is not configured` +Confirmed in `settings_Simple_ORB_NT8_20260818_142340.txt`: `EnableTrailingDrawdown: True`, +`AccountStartingBalance: $0.00`. The guard behaviour is correct; there is no startup assertion +pairing the two, and a misconfiguration is indistinguishable from a real breach in the summary counts. +**Fix: set `AccountStartingBalance` or disable the monitor; add the GAP-003-style startup assertion.** + +### CRITICAL โ€” GAP-047: confluence factor weights are pre-populated to 1.0; designed weights are unreachable +`ConfluenceScorer.cs` ~108-117 pre-populates `_factorWeights` with 1.0 for all ten `FactorType` +values. `ResolveWeight()` (~410-419) checks that dictionary first, so the `fallbackWeight` branch +carrying each calculator's designed weight (NarrowRange 0.20, OrbRangeVsAtr 0.15, +GapDirectionAlignment 0.15, BreakoutVolumeStrength 0.20, PriorDayCloseStrength 0.15) is +unreachable dead code. Runtime-confirmed: every factor in every `STATE:` line reads `x1.00`. +Designed total weight 5.85; actual 10.00. Under the designed scheme Grade A (0.80) is reachable +on factors 1-5 alone; under equal weights it requires all ten to average 0.80, which is close to +structurally unreachable. Today's live example: composite 0.640 (Grade C) at equal weights vs +**0.727 (Grade B)** under the designed weights. +**This is now the primary suspect for GAP-034's silent zero-trade days.** +**Fix: offline re-scoring study first, then an explicit weighting decision, then implementation.** + +### CRITICAL โ€” GAP-054: auto-breakeven destroys the runner's trailing stop (it has never trailed) +`SetStopLoss()` and `SetTrailStop()` are mutually exclusive per signal name in NinjaScript. +At entry (`NT8StrategyBase.cs` ~2178-2196) the runner is armed correctly: `SetStopLoss` then +`SetTrailStop(_runnerSignalName, Ticks, RunnerTrailTicks=12)` then `EnterLong/Short`. Then in +`OnBarUpdate` (~803) the auto-breakeven block calls +`SetStopLoss(_runnerSignalName, CalculationMode.Price, bePrice, false)` โ€” **replacing the live +trail with a static stop at entry + 1 tick.** The trail never runs again for that trade. +The source comment four lines below correctly warns against re-calling `SetTrailStop` here; the +`SetStopLoss` call above it was not recognised as doing the same damage. + +Runtime proof, all four broker-confirmed trades: + +| Trade | Log line | Profit when BE fired | Where a 12t trail sat | Where the stop went | +|---|---|---|---|---| +| 08-07 | `BREAKEVEN runner stop -> 29826.00 profit=28ticks` | +28 t | +16 t | +1 t | +| 08-10 | `BREAKEVEN runner stop -> 29848.50 profit=25ticks` | +25 t | +13 t | +1 t | +| 08-16 | `BREAKEVEN runner stop -> 30200.08 profit=24ticks` | +24 t | +12 t | +1 t | +| 08-17 | `BREAKEVEN runner stop -> 30271.00 profit=26ticks` | +26 t | +14 t | +1 t | + +The breakeven action moves the stop **backwards**, giving back 11-15 ticks of already-locked +profit per trade and then freezing. Conservative floor estimate: the runner would have banked +55 ticks = $275 gross / ~$252 net instead of $25 / $1.96 โ€” roughly a **24% uplift on total +realised P&L** from deleting one call site. + +Two secondary defects in the same block: `entryPrice` is `Position.AveragePrice` (the blended +3-contract average, not the runner's fill โ€” on 08-16 it produced the off-tick price `30200.08`), +and `Calculate = OnBarClose` means the 20-tick trigger actually fires at 24-28 ticks. + +**This supersedes the "runner underperforms, retune the trigger" framing in DEC-20260810-02 and +DEC-20260815-01.** The runner has never been tested. **Fix before RUNNER-001** โ€” sweeping +breakeven-trigger x trail-distance against a disabled trail measures nothing. +**Recommended fix: stop applying auto-breakeven to the runner leg at all.** A trailing stop +already provides monotonically improving protection. + +### HIGH โ€” GAP-055: `MaxDailyTrades` does not survive a strategy restart, and was breached 2026-08-17 +`_dailyTradeCount` is an in-memory field in `SimpleORBStrategy` (~39), zeroed at construction +(~269) and on session rollover (~756, ~961). Nothing persists it. +CME trading date 2026-08-17 begins 18:00 ET Sunday 08-16. Two trades were taken on that date โ€” +08-16 19:12 (+$277.72, `session_20260816_181528.log`) and 08-17 11:04 (+$267.72, +`session_20260817_110049.log`) โ€” in two different NT8 sessions, with `MaxDailyTrades=1`. +NT8 itself treated them as one day: the first `PNL_UPDATE` of the 11:04 trade reads +`DayPnL=$271.96` (= $277.72 less the $5.76 entry commission) and the session closes at +`DayPnL=$545.44`. Same class as the 7/28 breach that helped void Gate Run #2. +**A gate run under `MaxDailyTrades=1` cannot currently guarantee its own cap**, because gate +discipline explicitly contemplates restarts. Fix: persist the count and its trading date with +session provenance and rehydrate at startup; align the date boundary with the CME 18:00 ET rollover. + +### Recommended split of GAP-034 +- **GAP-034a** โ€” no candidate produced (08-03, 08-04, 08-13). Primary suspect: GAP-047. Still open. +- **GAP-034b** โ€” candidate produced but blocked at a risk gate. **ROOT-CAUSED** by GAP-045/046. + +### Other findings (see v7.0 Sections 1, 6, 7) +- **GAP-048** โ€” reject taxonomy conflates four causes under `KillSwitch` (portfolio block, Tier 1 + risk, circuit breaker, actual kill switch). 08-17 logged `count=647` from a real kill switch; + 08-18 logged `count=5` from `MaxTradeRisk`. Same label. Defeats GAP-035's purpose. +- **GAP-049** โ€” the dashboard's headline Score/Grade come from the telemetry path, whose + `DailyBarContext.TradeDirection` is stale by design (DEC-20260818-06). Live proof: a -523 gap + scored as "opposes trade" on a `Direction=Sell` setup. +- **GAP-050** โ€” `MaxTradeRisk` has no quantity term. Worst-case position risk is + `MaxTradeRisk x MaxContracts` = $600 against a $1,000 daily limit. The master document has + described this control incorrectly since v4. +- **GAP-051** โ€” `MicroUpgradeThreshold` fires every session at a $49k balance. +- **GAP-052** โ€” two independent hardcoded tick-value tables (`BasicRiskManager`, `BasicPositionSizer`). +- **GAP-053** โ€” `executive_summary.md` (dated 2026-05-04) and this roadmap's Sprint 3 list present + ~12 tasks completed on 2026-07-11 as still open. Actively misleads onboarding. + +### Configuration drift โ€” the frozen baseline no longer describes anything that runs +2026-08-18 alone produced **nine distinct `ConfigHash` values, three distinct `CodeVersion` MVIDs +and five different bar periods** (HFT Algo 13/42069, 13 Minute, 5 Minute, 15 Minute, 30 Minute). +Drifted from `baseline.json`: `MinTradeGrade` 5 -> 4, `EnableKillSwitch` True -> False, +`RiskPerTrade` $200 -> $100, plus the new `EnableTrailingDrawdown=True`. Two strategy instances +also ran concurrently on the same account and instrument (`065020` and `071117`), both emitting +`SIGNAL: Sell NQ` at 10:10:24 โ€” the single-frozen-account doctrine violated again. +`docs/gate-runs/gate3/baseline.json` should be treated as historical and re-captured. +Note also that the frozen settings export (`settings_..._20260816_121735.txt`) came from a session +archived the same day as having **no trading activity at all**. + +### Trading record to date (broker-confirmed, reconciled against execution grids) +Four trades, all long, all winners, **net $1,035.88** after $69.12 commission. Only **three** are +RTH_ORB (the 2026-08-16 trade entered 19:12 ET, outside RTH) โ€” $758.16. No two share a `ConfigHash`. +The **runner leg has earned $1.96 net across four trades** (0.19% of P&L for 33% of exposure) and +**-$7.28 on RTH_ORB trades only**. Breakeven trigger 20 ticks fires before the 28-tick ATR target +in 4/4 trades. This is now enough evidence to act on; RUNNER-001 should test *disabling* the +runner as a candidate, not only tuning the trigger. + +### Working tree +**DIRTY again** โ€” 17 modified, 5 untracked, including `NT8StrategyBase.cs` and `SimpleORBNT8.cs` +carrying the uncommitted DEC-20260818-01..-17 work that is deployed and running. The running +system is ahead of the last commit. Branch is `cleanup/wrappers-pass2`, not `main`. + +### Recommended immediate order of work (v7.0 Section 10) +N-01 set `AccountStartingBalance` or disable the monitor - N-02 resolve `MaxTradeRisk` - +N-03 stage the reject-taxonomy + startup-assertion prompt - N-04 commit the tree - +N-05 reduce to one armed instance - N-06 make `configdiff` a failing preflight check - +N-07 re-capture the freeze - N-08 fix the stale governance docs - +**N-09 the offline factor-weighting re-scoring study (highest-value task in the project)**. + +### Timeline reality +At the observed rate of ~0.7 broker-confirmed trades per week, a 20-trade gate sample takes +roughly **seven months**. Trade frequency, not per-trade edge, is the binding constraint on +profitability. If GAP-047 is the cause of the low rate, fixing it is worth more than everything +else on the roadmap combined. + +--- + ## RESOLVED 2026-08-16 โ€” Dirty working tree blocked Gate 3 freeze Earlier freeze attempts today (`freeze_20260816_003543`, `freeze_20260816_003653`, plus @@ -147,7 +423,11 @@ Bar boundaries differ, so breakout bars differ. Tick Replay must be on for compa - All five directories above are committed as standalone tooling. ## Authoritative documents -- Master document: **v6.4, republished 2026-08-16** โ€” supersedes the v6.1 reference below. +- Master document: **v7.0, 2026-08-18** โ€” `docs/NT8_SDK_Master_Document_v7.0_Complete.docx`, + with the interactive companion `docs/NT8_SDK_v7.0_Visual_Pack.html`. Supersedes v6.4 for status, + gap register, roadmap, parameters and next steps. v6.4's Appendices B, D, E and F (NT8 Add-On + XAML, ViewModel contracts, UI wireframes) remain valid as build references. +- Prior master document (superseded): **v6.4, republished 2026-08-16**. Delivered by the operator's Claude session; placing the file under `docs/` and updating this pointer is tracked alongside the Blocker 1 cleanup commit. - Prior reference (superseded): `docs/NT8_SDK_Master_Document_v6.1_Complete.docx` diff --git a/docs/00-governance/decisions.md b/docs/00-governance/decisions.md index bb92530..3b2f1e6 100644 --- a/docs/00-governance/decisions.md +++ b/docs/00-governance/decisions.md @@ -13,6 +13,300 @@ Use this file to record durable project decisions that affect implementation pat ## Decision Log +### DEC-20260821-01 +- **ID:** DEC-20260821-01 +- **Date:** 2026-08-21 +- **Status:** logged, no operator decision needed โ€” tracking only +- **Context:** Discovered while independently verifying the GAP-054 implementation (source read of `NT8StrategyBase.cs`). Two small residual items surfaced that the GAP-054 task didn't require closing but that shouldn't get lost: + 1. **GAP-056 โ€” `EnableAutoBreakeven`/`BreakevenTriggerTicks`/`BreakevenOffsetTicks` are now fully inert.** The only code path that ever read them was the runner breakeven block GAP-054 removed; there was never a separate scaler-leg breakeven implementation. All three parameters remain declared and defaulted in the strategy's NinjaTrader UI but do nothing. Not a trading-risk item โ€” inert means harmless โ€” but an operator setting `EnableAutoBreakeven=true` in the UI would reasonably expect it to do something. Recommended fix, low priority: either mark the parameters `[Browsable(false)]`/update their `Description` attributes to state they're currently unused, or remove them outright in a later cleanup pass. + 2. **GAP-057 โ€” no test seam exposes NinjaScript's `SetStopLoss`/`SetTrailStop` managed-order calls.** `TASK_GAP054_RUNNER_TRAIL_PROMPT.md` asked for a regression test asserting no `SetStopLoss` call is issued after `SetTrailStop` for a runner signal, with instructions to propose the smallest seam if none exists. Kilocode correctly did not fabricate coverage, but a concrete seam proposal wasn't written up. This is the same defect class as GAP-054 (silent exit-order clobbering) โ€” worth closing so a future change to this block gets real regression coverage instead of relying on manual source review, as this review just did. +- **Decision:** Track both, do not action either as part of GAP-054. No operator decision required to log them. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `TASK_GAP054_RUNNER_TRAIL_PROMPT.md` +- **Action Required:** None immediate. Stage as low-priority follow-up prompts when convenient. + +### DEC-20260819-01 +- **ID:** DEC-20260819-01 +- **Date:** 2026-08-19 +- **Status:** accepted +- **Context:** DEC-20260818-19 resolved the MaxTradeRisk/MaxStopTicks collision by moving the traded instrument from NQ to MNQ. This is a materially larger change than the other five items staged 2026-08-18: it changes `ConfigHash`, invalidates every settings/provenance export and gate-run comparison made under NQ, and interacts with the roadmap's Stage 2 instrument sequencing (Section 9.5, P2-0, already documented in the v7.0 master document as a future step โ€” this decision brings it forward rather than introducing it new). Layering an instrument cutover on top of unvalidated defect fixes (GAP-054, GAP-045/046, GAP-055) would make it impossible to tell, if something went wrong, whether the cause was a code defect or the instrument switch. +- **Decision:** Sequence the MNQ cutover as its own final step, after โ€” not concurrent with โ€” the code-level fixes: + 1. Land and validate GAP-048, GAP-047 (Part 1), GAP-054, GAP-045/046 (Parts 1-3), GAP-055 on the current NQ configuration, in SIM/replay, per each task's own validation section. + 2. Only once all of the above pass validation, execute the MNQ instrument cutover: confirm MNQ is present in both hardcoded tick-value tables (GAP-052 โ€” `BasicRiskManager.GetTickValue` and `BasicPositionSizer.GetTickValue`), reconfigure the strategy instance to MNQ, and re-tune `MaxTradeRisk`/`MaxStopTicks`/`MaxContracts` for MNQ's $0.50/tick economics rather than leaving NQ-era values in place unexamined. + 3. Run `preflight.ps1 --freeze` and produce a new `DEC-GATE3-CONFIG` for the MNQ configuration before any gate-run evidence is collected on it. Prior NQ-based gate evidence remains valid for its own record but is not comparable to post-cutover results. +- **Consequences:** Adds a discrete cutover step to the roadmap rather than folding it into GAP-045/046; keeps defect-fix validation and instrument-change validation from being confounded. Historical Strategy Analyzer/backtest results tied to NQ tick economics are not directly comparable post-cutover. +- **Related Files:** `docs/00-governance/decisions.md`, `docs/00-governance/roadmap.md`, `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md`, `docs/00-governance/2026-08-19-run-book.md` +- **Action Required:** Execute in the order above. Flag to Claude/Mo once step 1 items are all validated so the MNQ cutover task can be staged as its own TASK_*.md prompt. + +### DEC-20260818-21 +- **ID:** DEC-20260818-21 +- **Date:** 2026-08-18 +- **Status:** **accepted** (2026-08-19) +- **Operator Decision (2026-08-19):** Accepted as proposed โ€” persist the daily trade count using the DEC-20260818-17 halt-file pattern, rehydrate at `State.Realtime`, align to the CME 18:00 ET rollover. +- **Context:** `MaxDailyTrades` is enforced from `_dailyTradeCount`, a plain in-memory field in `SimpleORBStrategy.cs` (~39) zeroed at construction (~269) and on session rollover (~756, ~961). Nothing persists it across a strategy stop/start. The CME trading date 2026-08-17 (beginning 18:00 ET Sunday 08-16) took two trades under `MaxDailyTrades=1`: 08-16 19:12 (+$277.72, `session_20260816_181528.log`) and 08-17 11:04 (+$267.72, `session_20260817_110049.log`), in two different NT8 sessions. NT8 itself treated them as one trading day โ€” the first `PNL_UPDATE` of the 11:04 trade reads `DayPnL=$271.96` (the prior trade's $277.72 less the $5.76 entry commission) and the session closes at `DayPnL=$545.44`. This is the same class as the 7/28 breach that contributed to voiding Gate Run #2 (HIST-45) and is NOT closed by GAP-032, which fixed the within-session position-flat reset only. +- **Decision:** Persist `{trading_date, daily_trade_count, account, strategy_name, symbol}` to `{LogDirectory}/daily_trade_count__.json` on each increment, and rehydrate at `State.Realtime` entry when the persisted trading date matches. Reuse the persistence pattern already established for the Conservative trailing-drawdown halt file (DEC-20260818-17) rather than inventing a second mechanism. Align the trading-date boundary with the CME session rollover (18:00 ET) rather than the calendar date, using `SessionManager` or NT8's own session date if either already exposes it. Strategy Analyzer/backtest (`Account == null`) must neither read nor write the file so backtest behaviour is byte-for-byte unchanged. +- **Consequences:** Gate discipline explicitly contemplates restarts (recompiles, workspace changes, connection recovery), so without this a gate run under `MaxDailyTrades=1` cannot guarantee its own cap and its sample is uninterpretable in the same way the previous two were. Adds a small file-I/O dependency to the realtime path; a missing or corrupt file must degrade to count-zero plus a WARNING, never an exception. +- **Related Files:** `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md`, `docs/00-governance/decisions.md` +- **Action Required:** Accepted. Execute `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md`; then verify by taking one SIM trade, restarting the strategy the same trading day, and confirming the next signal is rejected with `REJECT: reason=MaxDailyTrades`. + +### DEC-20260818-20 +- **ID:** DEC-20260818-20 +- **Date:** 2026-08-18 +- **Status:** **accepted** (2026-08-19) +- **Operator Decision (2026-08-19):** Taxonomy split approved as proposed โ€” no changes to the vocabulary list. +- **Context:** Three of the nine reject reasons in production are overloaded. `KillSwitch` is emitted by four distinct paths in `NT8StrategyBase.cs` โ€” the actual kill switch (~721), a portfolio-risk block (~1970), a Tier 1 per-strategy risk rejection (~2000) and a circuit-breaker open (~2055). `GradeFilter` is emitted by four paths across `NT8StrategyBase.cs` (~1979, ~1986, ~2020) and `SimpleORBStrategy.cs` (~613/~622, ~650). `TrailingDrawdownBreach` covers both a genuine breach and an unconfigured monitor. `REJECT SUMMARY` aggregates on `reason`, and `LogRejectRateLimited()` emits the disambiguating `detail` line only on the first occurrence per reason, so the aggregate counts are the only thing an operator or the dashboard sees. Demonstrated: `session_20260817_082103.log` logged `reason=KillSwitch count=647` from a real kill switch, and `session_20260818_071117.log` logged `reason=KillSwitch count=5` from a `MaxTradeRisk` rejection. This directly defeats the purpose GAP-035 was built for. +- **Decision:** Split the reject vocabulary into distinct reasons โ€” `KillSwitch`, `PortfolioRisk`, `MaxTradeRisk`, `CircuitBreaker`, `LongTradesDisabled`, `ShortTradesDisabled`, `SizeBelowMinContracts`, `RegimeVeto`, `GradeFilter` (genuine grade rejection only), `TrailingDrawdownBreach` (real breach only) and `TrailingDrawdownNotConfigured`. Logging only: no guard condition, ordering or outcome may change, and the `REJECT:` / `REJECT SUMMARY:` line formats must remain byte-identical apart from the `reason=` token. The `HistoricalReplayCatchup` exemption inside `LogRejectRateLimited()` (DEC-20260818-08) is preserved. +- **Consequences:** The reason vocabulary becomes a contract for `tools/dashboard/parsers.py`, `tools/logtriage/logtriage.py` and `tools/logwatch/logwatch.py`; those parsers are believed reason-agnostic and must be read to confirm it rather than assumed. Splitting reasons slightly increases `REJECT:` detail-line volume, since rate limiting is per unique reason. `OrbRangeNotEstablished` retains its three sub-states under one reason for now โ€” they are already distinguishable in `detail` and this is lower priority. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `tools/dashboard/parsers.py`, `tools/logtriage/logtriage.py`, `tools/logwatch/logwatch.py`, `TASK_GAP048_REJECT_TAXONOMY_PROMPT.md` +- **Action Required:** Confirmed. Execute `TASK_GAP048_REJECT_TAXONOMY_PROMPT.md`. + +### DEC-20260818-19 +- **ID:** DEC-20260818-19 +- **Date:** 2026-08-18 +- **Status:** **accepted** (2026-08-19). Both decisions made. +- **Operator Decision (2026-08-19):** Decision 1 โ†’ **(c) move to MNQ.** Decision 2 โ†’ **per-position (total), not per-contract.** MaxTradeRisk is now the ceiling on total single-trade dollar risk across all contracts in the position, not a per-contract stop-distance ceiling. +- **Consequence of Decision 2 for the Tier 1 check:** the ordering change flagged as "must not be made without an approved decision" in the original entry is now approved. `BasicRiskManager`'s Tier 1 check must move to after `BasicPositionSizer` determines quantity (or take an estimated/candidate quantity) so that `StopTicks ร— tickValue ร— Qty โ‰ค MaxTradeRisk` is the actual enforced inequality, replacing today's `StopTicks ร— tickValue โ‰ค MaxTradeRisk` with no `Qty` term. +- **Consequence of Decision 2 for Part 1 Assertion D (TASK_GAP045_GAP046):** under per-contract semantics the original assertion was `MaxTradeRisk ร— MaxContracts โ‰ค DailyLossLimit`, reflecting a worst case scaled by contract count. Under per-position semantics, `MaxTradeRisk` already *is* the worst-case single-trade dollar loss regardless of contract count, so the correct assertion is `MaxTradeRisk โ‰ค DailyLossLimit` (a single trade must not be able to consume the whole daily loss limit on its own). This is a strictly tighter, simpler, and safer bound than the one it replaces โ€” worst-case single-trade risk drops from the previously undefined-in-practice $600 to whatever `MaxTradeRisk` is explicitly set to. +- **Sequencing (see DEC-20260819-01 below):** the risk-guard code changes (Parts 1โ€“3 of `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md`) are instrument-agnostic and should land and be validated on the current NQ configuration first. The MNQ instrument cutover itself is a separate, subsequent deployment step โ€” see DEC-20260819-01. +- **Context (original):** Two independent live outages on 2026-08-18 traced to parameter pairs that are individually valid and jointly impossible. (1) `BasicRiskManager.CalculateTradeRisk()` returns `intent.StopTicks * tickValue` with no quantity term, evaluated before sizing. On NQ at $5.00/tick, `MaxTradeRisk=$200` caps the stop at 40 ticks while `MaxStopTicks=50` (=$250) is configured, so the top 20% of the ATR stop range is unreachable. `session_20260818_071117.log` at 10:10:24 ET: five valid `SIGNAL: Sell NQ` lines, zero submissions, `REJECT: reason=KillSwitch detail=Risk manager rejected: Trade risk too high: $225.00`. `MinContracts=1` is already the floor, so the trade was unplaceable rather than resizable. (2) Separately, the parameter's display name is "Max Trade Risk" and master document v6.4 ยง3.2 documents the Tier 1 formula as `(StopTicks ร— TickVal ร— Qty) > MaxTradeRisk`. The code has never had the quantity term, so worst-case position risk is `MaxTradeRisk ร— MaxContracts` = $600 against a $1,000 `DailyLossLimit`. +- **Decision (proposed, two parts):** **Decision 1 โ€” resolve the collision.** Choose one of: (a) `MaxTradeRisk = $250`, making `MaxStopTicks=50` reachable and raising per-contract worst case 25%; (b) `MaxStopTicks = 40`, leaving nothing unreachable but tightening the stop relative to ATR on volatile days and raising stop-out rate; (c) validate on MNQ at $0.50/tick, where 50 ticks = $25 per contract, the collision disappears entirely and sizing becomes granular enough for `MaxContracts` to do real work. **Decision 2 โ€” define the semantics.** State explicitly whether `MaxTradeRisk` is a per-contract stop-distance ceiling (what the code does today) or a per-position risk limit (what the name and the master document imply). If per-position, the Tier 1 check must move to after sizing or take an estimated quantity โ€” a real ordering change that must not be made without this entry being accepted first. Independently of both, add startup assertions in the GAP-003 style for: `EnableTrailingDrawdown โ‡’ AccountStartingBalance > 0`; `MaxStopTicks ร— tickValue โ‰ค MaxTradeRisk`; `MinContracts โ‰ค MaxContracts`; and a bound relating `MaxTradeRisk ร— MaxContracts` to `DailyLossLimit`. +- **Consequences:** Either value change alters `ConfigHash` and requires a fresh freeze capture and a new `DEC-GATE3-CONFIG`. Option (c) is a larger strategic change than a parameter edit and interacts with the roadmap's instrument sequencing; it is also the only option that removes the class of problem rather than an instance of it. Until Decision 2 is answered, the system's true worst-case single-trade loss is undefined in the documentation and under-enforced in the code, which is the largest open drawdown exposure in the project. +- **Related Files:** `src/NT8.Core/Risk/BasicRiskManager.cs`, `src/NT8.Core/Sizing/BasicPositionSizer.cs`, `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` +- **Action Required:** Both decisions made โ€” see above. Execute `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` in full (Part 3 is now unblocked) on the current NQ configuration. Hold the MNQ instrument cutover itself for DEC-20260819-01's sequencing. + +### DEC-20260818-18 +- **ID:** DEC-20260818-18 +- **Date:** 2026-08-18 +- **Status:** **implemented** (2026-08-21). Supersedes DEC-20260810-02 and DEC-20260815-01 on the runner question. +- **Operator Decision (2026-08-19):** Accepted โ€” stop applying auto-breakeven to the runner leg. +- **Parameter-scoping sub-question resolution:** the entry left open whether `EnableAutoBreakeven` becomes runner-scoped-off by default or gains a separate `EnableRunnerBreakeven` flag. Not addressed in the 2026-08-19 acceptance message. Default resolved here rather than blocking implementation: **unconditionally skip breakeven on the runner leg in the `OnBarUpdate` block; do not add a new flag.** Rationale โ€” a trailing stop already dominates a frozen breakeven at every point once GAP-054 is fixed, so a toggle to re-enable the strictly worse behavior adds parameter surface and testing burden without a scenario where an operator would want it. `EnableAutoBreakeven`/`BreakevenTriggerTicks`/`BreakevenOffsetTicks` continue to govern the scaler leg only, unchanged. If Mo wants the flag instead of the unconditional skip, say so and this line will be revised before Kilocode implements it. +- **Context:** `SetStopLoss()` and `SetTrailStop()` are mutually exclusive per signal name in NinjaScript โ€” the later call replaces the earlier exit order. `SubmitOrderToNT8()` (`NT8StrategyBase.cs` ~2178-2196) arms the runner correctly with `SetStopLoss` then `SetTrailStop(_runnerSignalName, Ticks, RunnerTrailTicks)` then `EnterLong/EnterShort`. But the auto-breakeven block in `OnBarUpdate()` (~797-804) then calls `SetStopLoss(_runnerSignalName, CalculationMode.Price, bePrice, false)`, replacing the live trail with a static stop at entry + `BreakevenOffsetTicks`. The runner never trails again. All four broker-confirmed trades log it: `BREAKEVEN runner stop -> ... profit=28/25/24/26 ticks`, at which points a 12-tick trail would have sat at +16/+13/+12/+14 ticks while the stop was moved to +1. The breakeven action therefore moves the stop backwards, giving back 11-15 ticks of already-locked profit and freezing. Conservative floor estimate: 55 ticks (~$275 gross, ~$252 net) versus the $25 gross / $1.96 net actually realised โ€” roughly 24% of total realised P&L. Two secondary defects sit in the same block: `entryPrice` is `Position.AveragePrice`, the blended average across both legs rather than the runner's own fill (on 2026-08-16 producing the off-tick breakeven price 30200.08 on a 0.25-tick instrument), and `Calculate = OnBarClose` means `BreakevenTriggerTicks = 20` actually fires at 24-28 ticks. +- **Decision (proposed):** Stop applying auto-breakeven to the runner leg. A trailing stop already provides monotonically improving protection and does so better than a frozen breakeven at every point. `EnableAutoBreakeven`, `BreakevenTriggerTicks` and `BreakevenOffsetTicks` remain as parameters; whether they become runner-scoped-off by default or gain a separate `EnableRunnerBreakeven` flag defaulting to false is an open sub-question for the operator. The existing prohibition on calling `SetTrailStop()` inside `OnBarUpdate` (which would reset the trail anchor to bar-close price โ€” a real defect diagnosed 2026-04-13) stands unchanged. Before implementation, NinjaTrader's own documentation must be cited confirming the mutual-exclusivity behaviour; if it documents otherwise, the task stops and reports. +- **Consequences:** This supersedes the framing in DEC-20260810-02 and DEC-20260815-01, both of which treated the runner as a parameter-placement problem and deferred or scoped a breakeven-trigger retune. The runner has in fact never been tested, so its economics are unknown rather than poor, and the earlier conclusion that it might be worth disabling was drawn from data the defect produced. **RUNNER-001 must not execute until this lands** โ€” an 18-combination sweep over breakeven trigger ร— trail distance against a disabled trail would return a trail axis with no effect and a confident, meaningless recommendation. Historical Strategy Analyzer results involving the runner leg are not comparable across this change. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `tools/runnersweep/runnersweep.py`, `TASK_GAP054_RUNNER_TRAIL_PROMPT.md`, `docs/00-governance/decisions.md` +- **Implementation Note (2026-08-21):** Implemented Option 0 in `NT8StrategyBase.cs`: `OnBarUpdate()` no longer calls `SetStopLoss()` or `SetTrailStop()` for `_runnerSignalName` after entry, and the stale runner breakeven diagnostic draw is removed. Local installed NT8 API documentation citation: `C:\Program Files\NinjaTrader 8\bin\NinjaTrader.Core.xml` documents `StrategyBase.SetStopLoss(string, CalculationMode, double, bool)` as tying the stop-loss exit to `fromEntrySignal`, and `StrategyBase.SetTrailStop(string, CalculationMode, double, bool)` as tying the trail-stop exit to `fromEntrySignal` with trail stops amended tick-by-tick. The implementation preserves the single entry-time `SetTrailStop()` call so NT8 owns the live runner trail. Verified 511/511 (`verify-build.bat`) and 422/422 (`NT8.Core.Tests`) passing, `deploy-to-nt8.bat` succeeded, deployed source hash confirmed matching the repo. +- **Independent source verification (Claude, 2026-08-21):** Read the post-change `OnBarUpdate()` block directly (not just the report) โ€” confirms no `SetStopLoss`/`SetTrailStop` call remains for `_runnerSignalName`, the block is now a comment-only no-op, and the `BREAKEVEN runner stop ->` `FileLog` line is gone (not merely the chart draw object). **Correction to this entry's own "Parameter-scoping sub-question resolution" line above:** it stated `EnableAutoBreakeven`/`BreakevenTriggerTicks`/`BreakevenOffsetTicks` "continue to govern the scaler leg only, unchanged." Source inspection shows this was never true โ€” the original breakeven block only ever acted on `_runnerSignalName`; there was no separate scaler-leg breakeven path in the pre-fix code for it to have governed. All three parameters are declared, defaulted (`EnableAutoBreakeven=true`, `BreakevenTriggerTicks=20`, `BreakevenOffsetTicks=1`), and referenced once in a settings-export/log line โ€” but are now fully inert with no functional effect anywhere. This is functionally fine (matches the intended zero-breakeven outcome) but is a stale-parameter hygiene issue, not a scaler-leg regression. Tracked as GAP-056 below rather than left as a silent contradiction in this entry. +- **Action Required:** Deployed on 2026-08-21, not yet committed ("commits require explicit request" โ€” operator to decide, see current_status.md). Manually compile NinjaScript, then validate on SIM/replay โ€” NOT the live frozen account โ€” that no `BREAKEVEN runner stop ->` line appears and the runner exits materially above entry + 1 tick before this is eligible for a live gate run. **This validation has not yet happened โ€” GAP-054 still blocks RUNNER-001 until it does.** + +### DEC-20260818-17 +- **ID:** DEC-20260818-17 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** Funded-prop trailing drawdown risk must be tracked at the account level, not by strategy name. `PortfolioRiskManager` is intentionally not reused as the model because it is currently keyed by strategy name only, which is GAP-042 and would silently let two strategies on one account each maintain a separate drawdown buffer. +- **Decision:** Add an account-keyed `TrailingDrawdownMonitor` inside `NT8StrategyBase` with one shared high-water/lock/breach state per `Account.Name`. Equity is read with `Account.Get(AccountItem.NetLiquidation, Currency.UsDollar)`; installed NT8 API metadata confirms `AccountItem.NetLiquidation` exists and labels it as Net liquidation, with separate `CashValue`, `RealizedProfitLoss`, and `UnrealizedProfitLoss` account items. Runtime SIM validation must still cross-check this value against NT8 account display with an open position. Formula: update `currentPeak = max(currentPeak, equity)`. If not locked and `currentPeak >= AccountStartingBalance + TrailingDrawdownLockOffset`, set `locked=true` and `lockedPeakValue=currentPeak`. Reference point is `locked ? lockedPeakValue : currentPeak`; halt threshold is `referencePoint - TrailingDrawdownHaltBuffer`. If `equity <= haltThreshold`, set account breach state, flatten registered strategies for that account with `ExitLong("TrailingDrawdownHalt")` and `ExitShort("TrailingDrawdownHalt")`, log `TRAILING_DRAWDOWN_BREACH: Account= Equity= Peak= Floor= Locked= Time=`, and block new entries with reject reason `TrailingDrawdownBreach` for the rest of the session. +- **Consequences:** The monitor is fully opt-in via `EnableTrailingDrawdown=false` default, so existing gate-validation sessions are inert unless explicitly enabled. Multiple strategy instances sharing one account name share one drawdown floor and breach state. Conservative-tier breaches write `{LogDirectory}/drawdown_halt_.json`; startup with that file present enters halted state until the operator manually deletes it. Normal/Aggressive breaches are in-memory only and clear on restart. This task deliberately does not implement EOD/Option-2 mode or Python/Apprise notification wiring. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md` +- **Action Required:** In SIM, verify `AccountItem.NetLiquidation` includes unrealized P&L by comparing logged equity with NT8 account display while a position is open; test breach flattening, persisted Conservative halt, restart behavior by tier, lock-in floor behavior, disabled-mode inertness, and two-strategy shared account state. + +### DEC-20260818-16 +- **ID:** DEC-20260818-16 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** The operator trades both a funded prop account with strict trailing drawdown rules and a small personal/micro account that should become eligible for a different risk posture as capital grows. One static risk posture cannot accurately represent both accounts. +- **Decision:** Add a manual `RiskTier` NinjaScript setting with `Conservative`, `Normal`, and `Aggressive`, defaulting to `Normal`. Add `MicroUpgradeThreshold` defaulting to `5000`; each realtime bar reads account balance via `Account.Get(AccountItem.CashValue, Currency.UsDollar)` and, once per strategy session, logs/prints `TIER_UPGRADE_SUGGESTED: Balance= crossed threshold=; review RiskTier setting.` when crossed. The strategy never changes `RiskTier` automatically. +- **Consequences:** Risk posture becomes explicit in strategy settings and provenance without creating hidden automatic tier changes. The upgrade threshold is advisory only and safe for live use because it cannot alter sizing, risk validation, order submission, or drawdown halt behavior. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Confirm in SIM that threshold crossing logs exactly once and does not change `RiskTier` or any order behavior. + +### DEC-20260818-15 +- **ID:** DEC-20260818-15 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** The dashboard console only showed rejection/risk visibility from the live raw-log tail, so a meaningful `REJECT:` could scroll out and disappear from operator view even though the full session file still contained durable `REJECT SUMMARY:` and `REJECT:` records. The same dashboard also lacked signal-vs-fill visibility and had no approximation for good telemetry setups that could not become trades because a session-level block had already appeared. Today's 10:10 `SIGNAL` followed by `KillSwitch`/MaxTradeRisk rejection in `session_20260818_071117.log` made the gap concrete. +- **Decision:** Add read-only dashboard KPIs sourced from the full current `session_*.log` file on every `/api/state` poll: `session_reject_totals`, `signal_outcomes`, `signal_grade_summary`, `missed_grade_b_plus_count`, and capped `missed_grade_b_plus_samples`. The full-file read per poll is an accepted dashboard observability trade-off and should not be over-engineered with caching unless it is measured as slow. Signal-vs-fill correlation treats a `FILL` before the next `SIGNAL` as filled and captures the following `REJECT:` reason when present. Older `SIGNAL: Sell NQ | LIVE MODE` lines without inline grade/score use the latest prior `STATE:` grade/score so current logs remain analyzable. +- **Consequences:** Risk/reject counts are persistent for the full session and no longer disappear when raw-tail lines scroll out. Signal outcomes make rejected/unfilled generated signals visible by grade. Missed B+ setup counting is explicitly approximate: it infers blocked opportunity from `STATE:` samples after blocking `REJECT:` reasons (`RthGuard`, `MaxDailyTrades`, `KillSwitch`, `CmeHoliday`) have appeared, not from a first-class signal-quality-vs-execution-outcome model. Revisit this metric once the pending MaxDailyTrades architecture decision discussed in today's DEC-20260818-14 follow-up session is implemented, because that design should make the distinction exact rather than inferred. This remains observability-only and cannot affect live trading behavior because it only reads log files under `tools/dashboard`. +- **Related Files:** `tools/dashboard/parsers.py`, `tools/dashboard/server.py`, `tools/dashboard/console.html`, `tools/dashboard/console.js`, `docs/00-governance/decisions.md` +- **Action Required:** In a later live session, compare dashboard missed-setup samples against raw `STATE:` lines after any real `MaxDailyTrades` block and revise the approximation once MaxDailyTrades emits exact signal-quality/execution-outcome telemetry. + +### DEC-20260818-14 +- **ID:** DEC-20260818-14 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** Follow-up verification for DEC-20260818-11 confirmed the `SimpleORBNT8` side of fixed-position UI consolidation is wired, not just the `NT8StrategyBase` extension point. The repo and deployed NT8 Custom source both contain `SimpleORBNT8.AppendTopLeftDiagnosticLines(List lines)` for TradeTaken/DailyTradeCount and a single `Diag_BottomLeft` block for ORBRange/BreakoutDir. +- **Decision:** Treat the current `SimpleORBNT8` implementation as completion of DEC-20260818-11 rather than a new visual feature. No additional code change is required: old `Diag_TradeTaken`/`Diag_DailyCount` cleanup remains owned by the base consolidated top-left draw path, and old `Diag_ORBRange`/`Diag_BreakoutDir` cleanup remains owned by the SimpleORB bottom-left draw path before drawing `Diag_BottomLeft`. +- **Consequences:** The intended fixed-position consolidation is complete in source and deployed NinjaScript source. Runtime visual validation is still required for stacked top-left and bottom-left rendering and for any collision with NT8's native strategy-parameter display. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** In NT8, visually confirm the consolidated top-left and bottom-left blocks render without overlap under simultaneous active conditions. + +### DEC-20260818-13 +- **ID:** DEC-20260818-13 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** Follow-up verification for DEC-20260818-12 confirmed that event-driven telemetry's pending-breakout change detection depends on `SimpleORBNT8` overriding `GetStateTelemetryPendingBreakoutDirection()`. Without that strategy-specific override, the base implementation returns `0`, causing the intended `0 -> 1` or `0 -> -1` breakout-arm transition to be invisible to `MaybeWriteStateTelemetry()`. +- **Decision:** Treat the existing `SimpleORBNT8.GetStateTelemetryPendingBreakoutDirection()` override as required completion of DEC-20260818-12 rather than a separate telemetry feature. The override reads `_sdkStrategy as SdkSimpleORB` and returns `sdkOrb.PendingBreakoutDirection` when available, otherwise `0`, matching the null-check pattern used by the neighboring telemetry overrides. +- **Consequences:** Pending-breakout direction changes now have a strategy-specific data source for the event-driven `STATE:` path. Runtime validation is still required to confirm a live/SIM breakout-arm transition emits immediately and that the periodic 30-second snapshot remains unaffected. +- **Related Files:** `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md` +- **Action Required:** In live/SIM, force a breakout-bar/confirmation sequence and confirm a `STATE:` line appears when `PendingBreakoutDirection` changes. + +### DEC-20260818-12 +- **ID:** DEC-20260818-12 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** The 30-second `STATE:` telemetry snapshot is useful for ambient health monitoring but can lag fast ORB breakout/confirmation transitions on primary bars that close less than 30 seconds apart. The operator needs to see entry-imminent state changes in real time without turning `STATE:` into per-bar score-noise logging. +- **Decision:** `MaybeWriteStateTelemetry()` now samples on meaningful change, not only on a clock. It still preserves the existing 30-second periodic snapshot and its independent cooldown, but it also emits an immediate supplementary `STATE:`/`STATE_DETAIL:`/`STATE_CONTEXT:` set whenever either `SimpleORBNT8.PendingBreakoutDirection` changes or the telemetry grade crosses the configured `MinTradeGrade` threshold in either direction. The change-triggered emission does not reset `_lastStateTelemetryTime`, so the periodic health snapshot continues on its own cadence. This is deliberately limited to PendingBreakoutDirection and grade-threshold crossing; exact score decimal changes are ignored to avoid choppy log volume. +- **Consequences:** Fast breakout arming/resetting and grade eligibility transitions should now appear in the session log immediately instead of waiting for the next 30-second snapshot. This design is distinct from the `REJECT:` rate-limiting model: `STATE:` change-triggering is about sampling dynamic state at meaningful transitions, while `REJECT:` rate limiting is about avoiding repetition of static facts. The two throttling strategies must not be conflated. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** In live/SIM, force a rapid breakout-bar/confirmation sequence and confirm `STATE:` appears at the pending-direction change; run a quiet session to confirm periodic ~30s `STATE:` output remains; measure `STATE` line count during a choppy ORB window. + +### DEC-20260818-11 +- **ID:** DEC-20260818-11 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** Multiple `Draw.TextFixed()` diagnostics shared the same fixed chart positions. NinjaScript does not auto-stack these calls, so `Diag_Regime`, `Diag_Runner`, `Diag_TradeTaken`, and `Diag_DailyCount` collided at `TextPosition.TopLeft`, while `Diag_ORBRange` and `Diag_BreakoutDir` collided at `TextPosition.BottomLeft`. This visual-only issue is independent of DEC-20260818-10's ETH refresh path, although ETH refresh made stale/colliding fixed labels more visible. +- **Decision:** `NT8StrategyBase.DrawDiagnostics()` now builds a single newline-joined top-left diagnostics block and exposes `AppendTopLeftDiagnosticLines(List lines)` for derived strategies. `SimpleORBNT8` overrides that hook to append TradeTaken and DailyTradeCount under the same top-left draw call. `SimpleORBNT8.DrawDiagnostics()` now similarly builds one newline-joined bottom-left block for ORB range and breakout direction. Old separate tags are removed before the combined tags are drawn so stale chart objects do not linger. Color consolidation choice: the top-left block uses white text on a black background for mixed-status readability; the bottom-left ORB block uses white text on a dark-blue background, preserving the prior ORB range block's visual theme while accepting a single color for breakout direction. +- **Consequences:** Simultaneously active diagnostic lines at the same fixed position now render as stacked text in one chart object instead of overlapping. Per-line colors are intentionally not preserved because `Draw.TextFixed()` styles the whole fixed text object. Single-occupant positions (`Diag_Session` top-right, `Diag_TestMode` center, and `Diag_Prov` bottom-right) are unchanged. Native NT8 strategy-parameter-display overlap has not been validated in this code session and still requires visual chart confirmation. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Visually verify multiple top-left and bottom-left conditions render stacked, and confirm whether NT8's native strategy-parameter display still overlaps the consolidated top-left block. + +### DEC-20260818-10 +- **ID:** DEC-20260818-10 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** DEC-20260818-07 intentionally scoped `EnableEthTelemetry` to text telemetry only: the ETH branch called `MaybeWriteStateTelemetry()` and returned before `DrawDiagnostics()`. Live chart review showed stale RTH visual labels during ETH because `DrawDiagnostics()` had not run since a prior RTH/TestMode bar. Source review of `NT8StrategyBase.DrawDiagnostics()` and `SimpleORBNT8.DrawDiagnostics()` confirmed the methods are gated by `EnableChartDiagnostics` and use chart drawing calls only, without `_sdkStrategy.OnBar()`, `ProcessStrategyIntent()`, order submission, or trading state mutation. +- **Decision:** When a bar is outside RTH, TestMode is false, and `EnableEthTelemetry` is true, the existing ETH telemetry branch now calls `DrawDiagnostics()` in the same try/catch after building read-only bar/context state and writing optional state telemetry. The branch still returns before `_sdkStrategy.OnBar()` and `ProcessStrategyIntent()`, so ETH telemetry remains visual/read-only only. +- **Consequences:** With `EnableEthTelemetry=true` and `EnableChartDiagnostics=true`, the chart's session tag, ORB box, trigger lines, and breakout indicators can refresh during ETH instead of displaying stale RTH drawings. With `EnableEthTelemetry=false`, default ETH behavior remains unchanged. RTH and Strategy Analyzer paths are unchanged. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** In a live ETH session, verify `SESSION: ETH` and ORB visual diagnostics refresh with `EnableEthTelemetry=true`/`EnableChartDiagnostics=true`, and verify no `SUBMIT`/`FILL` lines appear outside RTH from this path. + +### DEC-20260818-09 +- **ID:** DEC-20260818-09 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** `ProcessStrategyIntent()` calculated position size using the static `intent.StopTicks` emitted by the SDK strategy, while `SubmitOrderToNT8()` later overwrote `intent.StopTicks` with the ATR-derived dynamic stop when `EnableDynamicStop=true`. That meant contract count was based on a stale stop distance and could diverge materially from the actual submitted stop risk. The same ordering defect affected `RecommendedContracts` telemetry because the telemetry intent used `SimpleORBNT8.StopTicks` rather than the current dynamic stop. This is distinct from DEC-20260818-08's historical-replay order-submission block. +- **Decision:** Dynamic ATR stop finalization now happens before sizing. `NT8StrategyBase.ProcessStrategyIntent()` applies the existing `EnableDynamicStop && CurrentBars[0] >= AtrPeriod` formula and min/max clamping before portfolio/per-strategy risk, `_positionSizer.CalculateSize()`, and submission. `SubmitOrderToNT8()` no longer recomputes or overwrites `intent.StopTicks`; it trusts the already-finalized value. Telemetry uses the same helper before `RecommendedContracts` sizing, and `SimpleORBNT8.BuildStateTelemetryIntent()` seeds the telemetry intent with the finalized stop ticks rather than the static `StopTicks` parameter. +- **Consequences:** With `EnableDynamicStop=true`, real order sizing, `SUBMIT Stop=`, and `RecommendedContracts` now reference the same stop distance. Historical Strategy Analyzer results with dynamic stop enabled are expected to change because this corrects a real contract-sizing defect. With `EnableDynamicStop=false`, the helper is a no-op and static-stop behavior is unchanged. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** In NT8, compare one dynamic-stop signal end to end: dynamic stop log, `SUBMIT Stop=`, submitted contract count, and `STATE_CONTEXT RecommendedContracts` should all reflect the ATR-finalized stop. Run a Strategy Analyzer before/after comparison with `EnableDynamicStop=true` and record the expected contract-count/P&L delta. + +### DEC-20260818-08 +- **ID:** DEC-20260818-08 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** Live/SIM strategy startup can process NT8 historical catch-up bars before `State.Realtime`. DEC-20260817-02 fixed the prior partial symptom by preventing `WriteTradeProvenance()` from writing phantom `trades_*.jsonl` rows outside realtime, but it explicitly did not alter signal generation, risk validation, sizing, or order submission. Live evidence later confirmed that historical catch-up bars from prior RTH sessions could still produce a full Intent -> Risk approved -> Sized -> Submitted -> Filled sequence because the realtime replay-age guard and `_realtimeBarSeen` guard do not run while `State == State.Historical`, and the RTH guard checks time of day without date freshness. +- **Decision:** `NT8StrategyBase.ProcessStrategyIntent()` now blocks live/SIM historical replay catch-up before any portfolio risk, direction, risk-manager, sizing, or order-submission logic when `State == State.Historical && Account != null`. The reject reason is distinct: `HistoricalReplayCatchup`. Strategy Analyzer/backtest behavior remains intentionally untouched because `Account == null` during genuine `State.Historical` backtests, so simulated historical orders still flow normally there. `LogRejectRateLimited()` permits this one reason to write a `REJECT:` line even though `State` is historical, so the catch-up safety block is visible in session diagnostics. +- **Consequences:** This closes the actual order-submission gap left open by DEC-20260817-02 while retaining that provenance-file gate as an independent second safety net. MaxDailyTrades and daily P&L should no longer be affected by live/SIM catch-up activity because catch-up-phase intents cannot reach submission at all. Validation still requires a live/SIM restart with catch-up history and a Strategy Analyzer regression comparison for unchanged trade count and P&L. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Restart NT8 with the live/SIM strategy attached to an account and confirm `REJECT: reason=HistoricalReplayCatchup` appears during catch-up with zero `SUBMIT`/`FILL` until `State.Realtime` and `_realtimeBarSeen` are true; run a Strategy Analyzer backtest over the same range and confirm trade count and P&L are unchanged. + +### DEC-20260818-07 +- **ID:** DEC-20260818-07 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** In the consolidated fix batch, the operator needed regime/factor/grade telemetry during ETH hours without touching the real `SimpleORBStrategy` entry state machine. The existing RTH guard in `NT8StrategyBase.OnBarUpdate()` returned before `MaybeWriteStateTelemetry()`, so sessions started during ETH produced no `STATE:` lines. The real strategy path must remain protected: no ETH call to `_sdkStrategy.OnBar()`, no `ProcessStrategyIntent()`, and no TestMode behavior changes. +- **Decision:** Added opt-in `EnableEthTelemetry` (`false` by default) under Diagnostics. When a bar is outside RTH and TestMode is false, the existing `RthGuard` rejection still logs; if and only if `EnableEthTelemetry` is true, `NT8StrategyBase` builds `BarData`/`StrategyContext` from current read-only adapter state, calls `MaybeWriteStateTelemetry()`, then returns immediately. This path does not call `DrawDiagnostics()`, `_sdkStrategy.OnBar()`, or `ProcessStrategyIntent()`. +- **Consequences:** Default ETH behavior remains unchanged. Operators can opt into `STATE:`/`STATE_DETAIL:`/`STATE_CONTEXT:` during ETH at the existing telemetry throttle for diagnostics only, with no path to submit an ETH order through this feature. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md` +- **Action Required:** In a live ETH session, verify `EnableEthTelemetry=false` produces no ETH `STATE:` lines, `EnableEthTelemetry=true` produces state telemetry, and no `SUBMIT`/`FILL` lines appear outside RTH. + +### DEC-20260818-06 +- **ID:** DEC-20260818-06 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** In the consolidated fix batch, real `STATE_DETAIL:` output showed daily-context factors returning "No daily bar context available" even though `SimpleORBNT8.OnBarUpdate()` already builds `DailyBarContext` every bar and stores it at `_strategyConfig.Parameters["daily_bars"]`. Root cause: real intents get this context via `SimpleORBStrategy.AttachDailyBarContext()`, but the synthetic `SimpleORBNT8.BuildStateTelemetryIntent()` created an empty metadata dictionary, and factor calculators read daily context from `intent.Metadata["daily_bars"]`. +- **Decision:** `SimpleORBNT8.BuildStateTelemetryIntent()` now creates a metadata dictionary and, when `_strategyConfig.Parameters["daily_bars"]` exists, attaches that same object under `"daily_bars"` before returning the synthetic telemetry intent. It deliberately does not call `AttachDailyBarContext()` because that helper mutates trade-direction, breakout-volume, and ORB fields for real trade candidates. +- **Consequences:** State telemetry factors can now use the same warmed daily context as the accepted-trade path without mutating SDK strategy state. Expected live result is real NR4/NR7 and ORB-vs-ATR reason text in `STATE_DETAIL:` once daily context is warmed, with no change to `SIGNAL`/`SUBMIT`/`FILL`/`REJECT` behavior. +- **Related Files:** `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Confirm live `STATE_DETAIL:` reason strings no longer report missing daily context once the daily series is warmed. + +### DEC-20260818-05 +- **ID:** DEC-20260818-05 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** The dashboard Data Series Detail panel exposed that `SimpleORBNT8` was loading duplicate daily bar series: `SimpleORBNT8.OnStateChange()` called `AddDataSeries(BarsPeriodType.Day, 1)` in `State.Configure`, then called `base.OnStateChange()`, whose `State.Configure` branch also added the shared daily series for TASK-06c regime SMA20/50 context. Live evidence showed `BarsArray[1]` and `BarsArray[2]` were both `DayBarsType`, `DaysToLoad=365`, `HistoricalBarsLoaded=130`. This was an existing latent bug that predated today's telemetry/dashboard work and was only made visible because the dashboard now shows the full `BarsArray` readiness detail. +- **Decision:** Removed the subclass `AddDataSeries(BarsPeriodType.Day, 1)` call from `SimpleORBNT8`. The base class remains the single owner of the shared daily series, so `BarsArray[1]` keeps the same role and ordering for `SimpleORBNT8.BuildDailyBarContext()` and `NT8StrategyBase.BuildStrategyContext()` regime calculations. A source comment now notes that `NT8StrategyBase` provides the shared daily series to avoid reintroducing the duplicate. +- **Consequences:** Expected live readiness is now two series total: primary bars plus one daily series, with the same daily historical count as before. NR7, ORB-vs-ATR, regime SMA20/50, signal generation, sizing, and order behavior should remain unchanged because all current consumers already read daily data from index `[1]`; the removed `[2]` series had no intended consumer. +- **Related Files:** `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** After deploy and NT8 compile, confirm the Historical readiness block/dashboard Data Series Detail reports only primary plus one daily series and that daily bar count remains unchanged. + +### DEC-20260818-04 +- **ID:** DEC-20260818-04 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** DEC-20260818-02/03 added `STATE_CONTEXT:` (ORB high/low/window from `SimpleORBNT8`, plus the universal `RecommendedContracts` field from `NT8StrategyBase`) but left dashboard parsing for a separate task, and verification against the actual deployed source (`NT8StrategyBase.cs`, `SimpleORBNT8.cs`) confirmed the format matched exactly what was documented. +- **Decision:** Added `STATE_CONTEXT_RE`/`parse_state_context_fields()` to `parsers.py` (plain space-separated `Key=Value` tokens, deliberately generic rather than ORB-specific since the field set is strategy-extensible per the `GetStateTelemetryContextFields()` extension point). `server.py._apply_event()` stores the result at `live_state.state_context`. `console.html`/`console.js`: a new ORB range block renders `OrbHigh`/`OrbLow`/window under Strategy Status's Session Filter section (with an honest "not yet established" empty state), and the State Telemetry stat-grid gains a fifth `Recommended Contracts` stat sourced live from `state_context.RecommendedContracts` when present โ€” distinct from the existing post-trade `last_submit.fields` sizing block, since this one updates continuously at the telemetry cadence rather than only after a real SUBMIT. +- **Consequences:** Closes the loop on both DEC-20260818-02 and DEC-20260818-03's deferred dashboard work in one pass. Not yet executed against a live payload, since Claude has no code-execution access on the operator's machine โ€” verify via `/api/state` or the console page once a session with an established ORB range is running. +- **Related Files:** `tools/dashboard/parsers.py`, `tools/dashboard/server.py`, `tools/dashboard/console.html`, `tools/dashboard/console.js`, `docs/00-governance/decisions.md` +- **Action Required:** Confirm `live_state.state_context` populates with `OrbHigh`/`OrbLow`/`OrbWindowStart`/`OrbWindowEnd`/`OrbReady`/`RecommendedContracts` once the ORB range establishes in a live session, and that the dashboard's ORB Range block and Recommended Contracts stat render correctly. + +### DEC-20260818-03 +- **ID:** DEC-20260818-03 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** The operator re-authorized recommended-contract telemetry after DEC-20260818-01 clarified that `BasicPositionSizer.CalculateSize()` has no internal mutable state a telemetry-only call could corrupt. The only side effect is logger output, which does not feed back into sizing/order behavior and is limited by the existing 30-second state telemetry throttle. +- **Decision:** `MaybeWriteStateTelemetry()` now calls `_positionSizer.CalculateSize(telemetryIntent, context, _sizingConfig)` after computing the confluence score, only inside the existing `EnableStateTelemetry && EnableFileLogging && State == State.Realtime` and 30-second throttle gates. The resulting `SizingResult.Contracts` is logged only, never stored or used for order submission. Because DEC-20260818-02 already introduced `STATE_CONTEXT:`, the recommended size extends that line as `RecommendedContracts=` instead of creating another near-duplicate telemetry line. When ORB context is also ready, the full line is `STATE_CONTEXT: OrbHigh= OrbLow= OrbWindowStart= OrbWindowEnd= OrbReady= RecommendedContracts=`; before ORB readiness, `STATE_CONTEXT: RecommendedContracts=` may still be emitted. +- **Consequences:** The dashboard/parser follow-up can read one context line for both strategy-specific context and display-only recommended sizing. Trustworthiness still requires live validation: when a real trade later submits under matching conditions, `RecommendedContracts` should match `SUBMIT`'s `Scaler + Runner` quantity; if not, telemetry inputs must be reconciled before presenting the value as authoritative. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Run a live session and compare `STATE_CONTEXT RecommendedContracts=` against the next matching `SUBMIT Scaler= Runner=` total. + +### DEC-20260818-02 +- **ID:** DEC-20260818-02 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** The operator needs the opening-range high/low and ORB window visible in text telemetry and the dashboard, but ORB fields are strategy-specific and should not become part of `NT8StrategyBase.cs`'s generic `STATE:` schema. `SimpleORBNT8.DrawDiagnostics()` already reads these values from `SimpleORBStrategy`'s public diagnostic getters, so logging them can remain read-only and aligned with chart diagnostics. +- **Decision:** Added `protected virtual Dictionary GetStateTelemetryContextFields(BarData barData, StrategyContext context)` to `NT8StrategyBase`; the base implementation returns `null`. `MaybeWriteStateTelemetry()` now calls the extension point at the same throttled cadence as `STATE:`/`STATE_DETAIL:` and emits `STATE_CONTEXT: Key1=Value1 Key2=Value2 ...` only when a strategy returns non-empty fields. `SimpleORBNT8` overrides the method and returns `OrbHigh= OrbLow= OrbWindowStart= OrbWindowEnd= OrbReady=` once `sdkOrb.OpeningRangeReady` is true and `OpeningRangeHigh > OpeningRangeLow`; otherwise it returns `null` so consumers can distinguish not-ready from ready values. +- **Consequences:** Future strategies can add strategy-specific state telemetry context without changing the generic `STATE:` line or hardcoding ORB concepts into the base class. The format deliberately uses unquoted space-separated key/value tokens because these values are numeric/time/boolean tokens with no internal spaces. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Parser/dashboard support for `STATE_CONTEXT:` should be added in a separate presentation/data task if these fields need UI display. + +### DEC-20260818-01 +- **ID:** DEC-20260818-01 +- **Date:** 2026-08-18 +- **Status:** accepted +- **Context:** The "show recommended contract count during state telemetry" task instructed Kilocode to stop if `BasicPositionSizer.CalculateSize()` wasn't provably stateless, mirroring DEC-20260817-04's caution for `RegimeManager`/`TrendRegimeDetector`/`VolatilityRegimeDetector`. Kilocode correctly stopped, reporting `CalculateSize()` calls `_logger.LogDebug()`/`LogWarning()`, which `BasicLogger` routes to `Console.WriteLine()`, and is therefore not I/O-free. +- **Decision:** Direct source read of `BasicPositionSizer.cs` confirms it has exactly one instance field (`_logger`, set once in the constructor, never written to elsewhere) and no other state. `CalculateSize()` derives its result purely from its `(intent, context, config)` parameters and returns a fresh `SizingResult` each call; there is no internal history/dictionary a telemetry-only call could seed or corrupt. This is categorically different from the `RegimeManager` case, where the disqualifying risk was a diagnostic call silently building up state (`_barHistory`, `_currentStates`, `_transitions`) that a future real caller would then see polluted. `BasicPositionSizer` has no such state; its only side effect is console text output, which does not feed back into any calculation, does not affect order behavior, and is negligible in volume at the existing 30-second telemetry throttle. The task is re-authorized: `MaybeWriteStateTelemetry()` may call `_positionSizer.CalculateSize()` for display purposes. +- **Consequences:** Establishes the actual test for future "is this safe to call for telemetry" questions: state that could corrupt a future real caller disqualifies a component (as with `RegimeManager`); I/O alone, on a component with no other internal state, does not. Future prompts citing "not provably stateless" should specify which kind of impurity was found rather than treating all impurity as equally disqualifying. +- **Related Files:** `src/NT8.Core/Sizing/BasicPositionSizer.cs`, `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Re-run the recommended-contract-count telemetry task per the original prompt, now unblocked. + +### DEC-20260817-11 +- **ID:** DEC-20260817-11 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** Operator raised several architecture questions after reviewing the console dashboard: whether the platform-neutral SDK goal is still real, whether 24x7 trading means switching strategies or running them concurrently, whether a control-plane UI requires an NT8 AddOn, and flagged that multi-account/multi-timeframe support aren't yet real. Each was answered by direct source reading rather than recollection (`NT8.Core` file contents confirmed no `NinjaTrader.*` references; `PortfolioRiskManager.cs` read in full to confirm its concurrent-strategy design and its lack of an account key). +- **Decision:** Recorded findings in `docs/00-governance/architecture.md`: a Platform-Neutral SDK Invariant section (with an explicit rule against `NT8.Core` gaining NinjaTrader references), a Multi-Strategy / 24x7 Trading Architecture section confirming the "shared everything but entry" pattern is already real and that `PortfolioRiskManager` was already built for concurrent strategies, and a Control Plane section presenting the external-command-channel alternative to an NT8 AddOn. Added `GAP-042` (no account dimension in `PortfolioRiskManager`) to Sprint 4 in `roadmap.md`, and added multi-timeframe regime alignment as an unscoped Sprint 6 idea, both cross-referenced back to `architecture.md`. +- **Consequences:** These answers are now durable repo state rather than only having existed in a chat response. Future sessions asking the same architecture questions can be pointed at `architecture.md` directly. `GAP-042` must be resolved before Sprint 4's multi-strategy plans extend to multiple accounts. +- **Related Files:** `docs/00-governance/architecture.md`, `docs/00-governance/roadmap.md`, `docs/00-governance/decisions.md` +- **Action Required:** None in code now. `GAP-042` implementation and the multi-timeframe regime design pass are both unscoped future work, not queued into an active sprint. + +### DEC-20260817-10 +- **ID:** DEC-20260817-10 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** DEC-20260817-09 added `STATE_DETAIL:`/`SIGNAL_DETAIL:` log lines and appended sizing-rationale fields to `SUBMIT`, but explicitly left dashboard/logtriage parser updates for a separate task. Console.js's Confluences and Factor Breakdown panels had no way to surface the human-readable factor reasons (e.g. NR4/NR7 determination, ORB-vs-ATR ratio) the operator specifically asked for, and the R:R panel had no live per-trade sizing data, only static config. Also found and removed dead code predating this session's changes: `parsers.py` had two `STATE_RE` definitions (the second silently overwrote the first), which left an entire `state = STATE_RE.search(message)` branch in `parse_session_event()` permanently unreachable since the newer regex's branch, positioned earlier in the function, always matched and returned first. +- **Decision:** Added `parse_quoted_reasons()` (reverses `EscapeLogValue()`'s backslash/quote escaping) and `STATE_DETAIL_RE`/`SIGNAL_DETAIL_RE` to `parsers.py`; `parse_session_event()` now returns `type: "STATE_DETAIL"`/`"SIGNAL_DETAIL"` events with a `reasons` dict keyed by factor name. Added `parse_submit_fields()` (numeric coercion for `BaseTarget`/`DynamicTarget`/`GradeMult`/`ModeMult`/`CombinedMult`, leaving `"N/A"` as a string so it's distinguishable from `0`) and enriched the existing `SUBMIT` event with a `fields` dict. `server.py._apply_event()` stores these at `live_state.state_telemetry_reasons`, `live_state.last_signal_reasons`, and within `live_state.last_submit.fields`. `console.html`/`console.js`: Confluences and Factor Breakdown rows now carry a `title` tooltip from `state_telemetry_reasons[name]` when available; a new "Live Sizing" block under the static R:R panel renders `last_submit.fields` once a trade has submitted this session, with an honest "no trade submitted yet" empty state otherwise. +- **Consequences:** This closes the loop DEC-20260817-09 left open โ€” factor reasons and per-trade sizing rationale now reach the dashboard, not just the session log. Parsing logic was verified by hand-tracing the documented formats against `DEC-20260817-09`'s exact line specifications (quoted-value escaping, unquoted `SUBMIT` fields with `N/A` fallback) but not executed, since Claude has no code-execution access on the operator's machine, and the underlying `NT8StrategyBase.cs` change has not yet been redeployed (blocked on `NT8.Core.dll` file lock โ€” NinjaTrader must fully close before `deploy-to-nt8.bat` can succeed). The dead `STATE_RE` shadow bug predated this session's own DASH-002 work but was only now discovered and removed. +- **Related Files:** `tools/dashboard/parsers.py`, `tools/dashboard/server.py`, `tools/dashboard/console.html`, `tools/dashboard/console.js`, `docs/00-governance/decisions.md` +- **Action Required:** Once NT8.Core.dll is unlocked and the telemetry enrichment redeploys/recompiles cleanly, confirm via `/api/state` (or the console page) that `state_telemetry_reasons`, `last_signal_reasons`, and `last_submit.fields` populate with real values, and that tooltips render correctly on hover. + +### DEC-20260817-09 +- **ID:** DEC-20260817-09 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** DASH-002 `STATE:` telemetry and accepted-trade `SIGNAL`/`SUBMIT` logging exposed scores and order shape but discarded already-computed sizing rationale and each `ConfluenceFactor.Reason`. The data already exists on `intent.Metadata` and `ConfluenceScore.Factors`; surfacing it is logging-only and must not change signal generation, sizing, risk validation, or order submission behavior. +- **Decision:** Keep existing score-bearing line formats intact except for appending metadata fields to `SUBMIT`. Accepted-trade factor reasons are emitted as a separate line immediately after `SIGNAL`: `SIGNAL_DETAIL: Setup="" Trend="" Volatility="" Timing="" ExecutionQuality="" NarrowRange="" OrbRangeVsAtr="" GapDirectionAlignment="" BreakoutVolumeStrength="" PriorDayCloseStrength=""`. State telemetry factor reasons are emitted at the same cadence and immediately after `STATE`: `STATE_DETAIL: Setup="" Trend="" Volatility="" Timing="" ExecutionQuality="" NarrowRange="" OrbRangeVsAtr="" GapDirectionAlignment="" BreakoutVolumeStrength="" PriorDayCloseStrength=""`. The `SUBMIT` line appends `BaseTarget= DynamicTarget= GradeMult= ModeMult= CombinedMult=` after the existing `Mode=` field. +- **Consequences:** Dashboard/logtriage parsers can add support for `SIGNAL_DETAIL`, `STATE_DETAIL`, and appended `SUBMIT` fields later without ambiguity. Existing `SIGNAL`, `Factors:`, `FILL`, `PNL_UPDATE`, and `REJECT` lines are not removed or reordered. Reason values are double-quoted with backslashes and quotes escaped because reason text may contain punctuation or semicolons. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Update dashboard/logtriage parsers in a separate task if these detail lines need structured UI display. + +### DEC-20260817-08 +- **ID:** DEC-20260817-08 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** DASH-002's `STATE:` telemetry line was confirmed live in `session_20260817_202803.log` (validated in a real realtime session: `STATE: Regime=Neutral Direction=Buy DirectionSource=OpeningRangeMidpoint Score=0.550 Grade=D Factors=Setup=0.50x1.00;...`), but `tools/dashboard/parsers.py`'s `parse_session_event()` had no handling for it โ€” the dashboard's `console.html`/`console.js` plan (DASH-004) explicitly noted this as "pending DASH-002" and had no real data source yet. +- **Decision:** Added `STATE_RE` and `parse_state_factors()` to `parsers.py`, following the same `Factors=name=scorexweight;...` convention already used for `GradeFilter` reject-detail parsing. `parse_session_event()` now returns a `type: "STATE"` event with `regime`, `direction`, `direction_source`, `score`, `grade`, and a structured `factors` list. `server.py._apply_event()` stores the latest one at `live_state.state_telemetry`, refreshed every poll from the session-log tail like every other live field, so it is available via `/api/state` with no additional wiring. +- **Consequences:** Live regime/grade/factor data now actually reaches the dashboard rather than sitting only in the session log. Observed cadence in this test session was ~5 minutes, not the 30s floor from DEC-20260817-07, because this session's primary series is `MinuteBarsType` and `MaybeWriteStateTelemetry()` only gets a chance to fire on `OnBarUpdate()` (bar close) โ€” on the gate's actual HFT Algo Bars primary series, cadence will sit much closer to the 30s floor. Parsing logic was hand-verified against the real log line (all six capture groups resolve correctly, including the `Grade=D` immediately followed by ` Factors=` boundary) but not executed, since Claude has no code-execution access on the operator's machine. +- **Related Files:** `tools/dashboard/parsers.py`, `tools/dashboard/server.py`, `docs/00-governance/decisions.md` +- **Action Required:** Confirm via a live `/api/state` poll (or the dashboard once loaded) that `live_state.state_telemetry` populates and updates roughly on the observed cadence. + +### DEC-20260817-07 +- **ID:** DEC-20260817-07 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** DASH-002 needs continuous confluence/regime telemetry for the dashboard, but per-HFT-bar logging could create excessive session-log volume and disk I/O on the strategy thread. The implementation must remain additive observability only and must not call state-mutating regime detector methods documented in DEC-20260817-04. +- **Decision:** Emit `STATE:` telemetry at most once every 30 seconds while `State == State.Realtime`, `EnableFileLogging == true`, and `EnableStateTelemetry == true`. The line records `Regime`, diagnostic `Direction`, `DirectionSource`, `Score`, `Grade`, and `Factors==x;...` using the same factor-breakdown convention consumed by dashboard GradeFilter parsing. Direction is explicit so synthetic diagnostic scoring cannot be mistaken for an accepted trade signal. +- **Consequences:** Expected full RTH volume is approximately 780 lines per 6.5-hour session, plus normal session logs, which is low enough for operator diagnostics while avoiding per-bar HFT log flooding. Existing `SIGNAL`, `SUBMIT`, `FILL`, `PNL_UPDATE`, and `REJECT` lines remain unchanged. The dashboard can replace its DASH-002 placeholder with real latest-state telemetry when these lines are present. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `tools/dashboard/parsers.py`, `tools/dashboard/server.py`, `tools/dashboard/console.html`, `tools/dashboard/console.js` +- **Action Required:** Dual-deploy, manually compile all NinjaScript in NT8, and verify `STATE:` lines appear in a realtime session before relying on dashboard telemetry. + ### DEC-20260713-01 - **ID:** DEC-20260713-01 - **Date:** 2026-07-13 @@ -237,3 +531,63 @@ Use this file to record durable project decisions that affect implementation pat - **Consequences:** Every gate week starts with governance docs that are at most a few hours stale, not up to 7 days. The master document's Section 23.4 heartbeat language is superseded by this entry and should read as a pointer to this runbook in the next master document revision (v6.4). - **Related Files:** `docs/00-governance/roadmap.md`, `docs/00-governance/current_status.md`, `docs/02-runbooks/weekly_roadmap_cadence.md`, `docs/00-governance/decisions.md` - **Action Required:** None in code. First scheduled Sunday review configured 2026-08-16 for 2026-08-23 onward. + +### DEC-20260817-01 +- **ID:** DEC-20260817-01 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** `WriteSessionProvenance()` and `WriteTradeProvenance()` returned silently when `LogDirectory` was blank, while `InitFileLog()` and `WriteSettingsFile()` already used the default path `Documents\NinjaTrader 8\log\nt8-sdk`. The ORB-specific `WriteSessionProvenance()` override had the same silent guard. This created a split-brain evidence state: `session_*.log` and `settings_*.txt` continued writing, but `provenance_*.json` and `trades_*.jsonl` did not. The affected period includes broker-confirmed trades from 2026-08-07, 2026-08-10, 2026-08-16, and 2026-08-17. +- **Decision:** Provenance and trade JSONL writes must use the same default log directory fallback as session logs/settings whenever `LogDirectory` is blank. The fallback must be explicit in both `Print()` and `FileLog()` so this failure mode is never silent again. +- **Consequences:** Gate evidence for trades since 2026-07-31 cannot rely on missing provenance/trade JSONL as proof of no trades or no submissions. Broker statements/session logs remain necessary for those sessions. Future blank `LogDirectory` configurations produce provenance and trade records at the default path with visible warnings. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `docs/00-governance/decisions.md` +- **Action Required:** Redeploy and manually NinjaScript-compile before relying on new provenance/trade JSONL artifacts. + +### DEC-20260817-02 +- **ID:** DEC-20260817-02 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** `trades_Simple_ORB_NT8_20260817.jsonl` received 57 rows during a 14-second restart replay window (`2026-08-17T16:51:16.124Z` through `2026-08-17T16:51:30.109Z`) while broker execution grid review showed no matching activity. `OnExecutionUpdate()` and live session-log `SIGNAL`/`SUBMIT` writes are already `State.Realtime` gated, but `WriteTradeProvenance()` was called from `SubmitOrderToNT8()` without an equivalent gate. Source review also found that live-chart historical replay passes `AllowDailyTradeCountIncrement=false` when `State.Historical` and `Account != null`, so accepted historical intents do not increment `_dailyTradeCount` and `MaxDailyTrades` cannot cap the replay burst in that mode. The persisted trade JSONL has only wall-clock `timestamp_utc`; it does not include the bar's own historical timestamp, so exact per-row bar-date distribution cannot be reconstructed from the file. +- **Decision:** `WriteTradeProvenance()` must return immediately unless `State == State.Realtime`. This is a provenance/data-integrity gate only and must not alter signal generation, risk validation, order submission, or entry/exit behavior. Do not change historical daily-count logic without a separate approved task because it may affect Strategy Analyzer/backtest behavior. +- **Consequences:** Historical catch-up/replay can no longer append phantom trade provenance rows. Existing `trades_Simple_ORB_NT8_20260817.jsonl` is contaminated by 57 phantom rows (`49` Buy, `8` Sell; `43` `RTH_ORB`, `14` `ETH`; all quantity `3`, grade `A`) and must not be used by dashboard/logtriage as clean gate evidence. Future forensic schema work should consider adding a `bar_time` field to trade provenance so replay investigations can map rows to historical bars. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `docs/00-governance/decisions.md`, `C:\Users\billy\Documents\NinjaTrader 8\log\nt8-sdk\trades_Simple_ORB_NT8_20260817.jsonl` +- **Action Required:** Archive the contaminated 2026-08-17 trade JSONL before the next gate attempt, redeploy with the strategy disabled, delete `NinjaTrader.Custom.dll`, compile all NinjaScript cleanly, and verify a clean session start before re-arming. + +### DEC-20260817-06 +- **ID:** DEC-20260817-06 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** `tools/runnersweep/runnersweep.py`'s `is_runner_leg()` classified a trade row as a runner leg only if the literal words "runner" or "run" appeared in its Leg/Entry name/Exit name/Signal name fields (and excluded rows containing "scaler"/"scale"). `SubmitOrderToNT8()` in `NT8StrategyBase.cs` actually names legs `SDK_{Symbol}_R_{hex}` (runner) and `SDK_{Symbol}_S_{hex}` (scaler) โ€” neither word appears in either name. Every combo in the 18-run sweep would therefore have been marked invalid with "missing runner-leg rows" regardless of how correctly the Strategy Analyzer backtests were run and exported, discovered before any backtest time was spent by reading `SubmitOrderToNT8()`'s signal-naming logic directly rather than assuming the tool's existing matcher was correct. +- **Decision:** `is_runner_leg()` now also matches the literal `_r_`/`_s_` token from the real signal-naming convention, in addition to the original word-based matching (kept for compatibility with differently-named strategies). Verified safe: the `{hex}` suffix in `SDK_{Symbol}_R_{hex}`/`SDK_{Symbol}_S_{hex}` is a GUID-derived hex string (characters `0-9a-f` only), which cannot contain the letters `r` or `s` needed to form a false `_r_`/`_s_` match, so there is no risk of misclassifying the hex portion as a leg marker. +- **Consequences:** The sweep can now correctly separate runner-leg trades from scaler-leg trades once real Strategy Analyzer exports are analyzed. This was caught before any of the 18 backtests were run, avoiding wasted analyzer time on exports the tool would have silently mis-scored. +- **Related Files:** `tools/runnersweep/runnersweep.py`, `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` (`SubmitOrderToNT8()`), `docs/00-governance/decisions.md` +- **Action Required:** None in code beyond the fix already made. When real Strategy Analyzer exports exist, spot-check that `runner_trades`/`combined_trade_count` in the JSON output look proportionally reasonable (Mode1DualLeg splits each fill into one scaler row and one runner row) before trusting the recommendation. + +### DEC-20260817-05 +- **ID:** DEC-20260817-05 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** DEC-20260817-03 noted that `tools/dashboard/server.py` already parsed `REJECT:`/`REJECT SUMMARY:` lines for the live current-session tail via a private `_parse_rejections()`/`_parse_key_values()` pair, but `tools/logtriage/logtriage.py`'s file-based parser had no reject handling at all โ€” so any offline/historical `logtriage.py --json` run (the primary use case for silent-day forensics on past sessions) exposed no rejection data, and the two files carried duplicate, divergence-prone parsing logic. +- **Decision:** Added `parse_key_values()` to `logtriage.py` as the canonical parser (identical marker-bounded-value approach to the original `server.py` implementation, so `detail` text containing `=` or the word "bar" parses correctly). `SessionSummary` now carries `reject_summaries`, `reject_records`, and `reject_summary_final` (last-observed count per reason), populated while parsing `session_*.log` and exposed via `to_dict()`. The `SILENT DAY` diagnostic in `build_diagnostics()` now appends a `Rejections: =, ...` breakdown (and machine-readable `reject_totals`) whenever data is available, so a silent day is self-explanatory in triage output rather than merely flagged. `server.py._build_current_rows()` no longer needs its own reject parsing โ€” `logtriage.parse_session_file()` already supplies the fields on `row_dicts[0]` โ€” so the duplicate `_parse_rejections()`/`_parse_key_values()` methods and the now-unused `lines` parameter on `_build_current_rows()` were removed. Field names/shapes are unchanged from what `server.py` produced before and match what `tools/dashboard/app.js` already expects (`row.reject_summaries[].{reason,count,line}`, `row.reject_records[].{reason,detail,bar,line}`), so no frontend change was needed. +- **Consequences:** `logtriage.py --json` run against archived log directories now surfaces the same rejection data the live dashboard already showed for the current session, closing the gap DEC-20260817-03 flagged. There is exactly one parser for this line format going forward instead of two. Logic was verified by hand-tracing both the `REJECT:` and `REJECT SUMMARY:` lines from the real `session_20260817_125115.log` archive; it has not been executed, since Claude has no code-execution access on the operator's machine โ€” an operator run of `python tools/logtriage/logtriage.py --json` against the archive is the next real validation step. +- **Related Files:** `tools/logtriage/logtriage.py`, `tools/logtriage/README.md`, `tools/dashboard/server.py`, `docs/00-governance/decisions.md` +- **Action Required:** Run `python tools/logtriage/logtriage.py "C:\Users\billy\Documents\NinjaTrader 8\log\nt8-sdk\ARCHIVE" --json` and confirm `reject_summaries`/`reject_records`/`reject_summary_final` appear on session rows with no exceptions raised; spot-check the `SILENT DAY` diagnostic message on a known silent day. + +### DEC-20260817-04 +- **ID:** DEC-20260817-04 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** DASH-002 was blocked pending confirmation that synthetic telemetry generation does not invoke state-mutating paths in `RegimeManager`, `TrendRegimeDetector`, or `VolatilityRegimeDetector`. Direct source review of `NT8StrategyBase.cs`, `SimpleORBStrategy.cs`, and `FactorCalculators.cs` confirms these three classes are instantiated in `InitializeSdkComponents()` but never called anywhere in the live signal path. The regime/volatility values actually used for signal generation are computed independently: inline SMA20/50 math in `BuildStrategyContext()` and pure-function ATR-ratio math inside `VolatilityRegimeFactorCalculator`/`TrendAlignmentFactorCalculator`, both of which read from `context.CustomData` with no side effects. `RegimeManager.UpdateRegime()`, `TrendRegimeDetector.DetectTrend()`, and `VolatilityRegimeDetector.DetectRegime()` mutate bar history, current-regime dictionaries, and transition logs on every call, and are currently dead code. +- **Decision:** DASH-002 is unblocked. Telemetry implementation must sample only from the existing side-effect-free sources (the inline regime calc in `BuildStrategyContext` and the existing `IFactorCalculator.Calculate()` pure functions) and must not call `RegimeManager.UpdateRegime()`, `TrendRegimeDetector.DetectTrend()`, or `VolatilityRegimeDetector.DetectRegime()` for periodic sampling. This constraint is now recorded in `TASK_DASH-002_PROMPT.md`. +- **Consequences:** DASH-002 can proceed without risk of corrupting future use of the regime-detector classes. If a later task wires `RegimeManager`/`TrendRegimeDetector`/`VolatilityRegimeDetector` into the live decision path, it starts from genuinely empty state rather than state pre-seeded by telemetry sampling. +- **Related Files:** `TASK_DASH-002_PROMPT.md`, `src/NT8.Core/Intelligence/RegimeManager.cs`, `src/NT8.Core/Intelligence/TrendRegimeDetector.cs`, `src/NT8.Core/Intelligence/VolatilityRegimeDetector.cs`, `docs/00-governance/decisions.md` +- **Action Required:** None in code from this decision alone. Kilocode proceeds with DASH-002 per the updated prompt. + +### DEC-20260817-03 +- **ID:** DEC-20260817-03 +- **Date:** 2026-08-17 +- **Status:** accepted +- **Context:** GAP-035 made per-reason rejection details readable by logging only the first `REJECT:` line for each unique reason. Aggregate counts were still only written by `WriteRejectSummary()` at `State.Terminated`, leaving armed live sessions without current silent-day counts until the strategy stopped. Dashboard live parsing and `logwatch.py` already understand `REJECT SUMMARY: reason= count=`, but `tools/logtriage/logtriage.py` does not currently parse these lines despite dashboard copy referring to "logtriage JSON" for silent-day summary data. +- **Decision:** Keep per-detail `LogRejectRateLimited()` behavior unchanged, but write aggregate `REJECT SUMMARY` snapshots during live sessions. The cadence is first live rejection at or after 10:00 ET, then every 15 bar-minutes while live rejections continue. The summary line format remains unchanged so existing live dashboard/logwatch parsers continue to consume it. +- **Consequences:** Operators can see current rejection counts during the session without flooding the log with every individual rejection. Offline `logtriage.py --json` will still not expose these summaries until a separate parser update is approved. +- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `tools/logwatch/logwatch.py`, `tools/dashboard/server.py`, `tools/dashboard/app.js`, `tools/logtriage/logtriage.py`, `docs/00-governance/decisions.md` +- **Action Required:** Validate in a live RTH session that at least one `REJECT SUMMARY` snapshot appears before termination and that displayed counts match `_rejectCounts` at snapshot time. diff --git a/docs/00-governance/roadmap.md b/docs/00-governance/roadmap.md index a10cf97..625b4fa 100644 --- a/docs/00-governance/roadmap.md +++ b/docs/00-governance/roadmap.md @@ -1,6 +1,8 @@ # Roadmap -**Last Updated:** 2026-08-16 (weekly Sunday republish โ€” see `docs/02-runbooks/weekly_roadmap_cadence.md`, DEC-20260816-01) -**Master Reference:** NT8_SDK_Master_Document_v6.4_Complete.docx โ€” Sections 7, 8, 21 +**Last Updated:** 2026-08-18 (v7.0 master-document review; last Sunday republish 2026-08-16 โ€” see `docs/02-runbooks/weekly_roadmap_cadence.md`, DEC-20260816-01) +**Master Reference:** NT8_SDK_Master_Document_v7.0_Complete.docx โ€” Sections 7, 8, 9, 10, 12 +(+ interactive companion `docs/NT8_SDK_v7.0_Visual_Pack.html`). v6.4 remains the reference for +Appendices B, D, E and F only. ## Sequencing Rule No sprint advances until its gate criteria are met. No exceptions. @@ -12,10 +14,53 @@ allowance. See `docs/02-runbooks/weekly_roadmap_cadence.md` and `DEC-20260816-01 --- -## CURRENT BLOCKER -1. **GAP-034** โ€” Gate Run #3 cannot start. Three sessions (08-03, 08-04, 08-13) produced - zero trades on days with clear NQ breakouts, root cause unidentified. See - `current_status.md` and `TASK_GAP035_GAP034_PROMPT.md`. +## CURRENT BLOCKERS (revised 2026-08-18 by the v7.0 review โ€” see `current_status.md`) + +1. **GAP-045 โ€” `MaxTradeRisk` / `MaxStopTicks` collision.** `StopTicks x tickValue` with no + quantity term, evaluated before sizing. NQ: `MaxStopTicks` 50 x $5 = $250 > `MaxTradeRisk` $200, + so the top 20% of the ATR stop range is unreachable and high-ATR days produce zero trades. + **Confirmed live 2026-08-18 10:10 ET: five valid Sell signals, all rejected at $225.00.** +2. **GAP-046 โ€” trailing-drawdown monitor blocks every entry when `AccountStartingBalance` is unset.** + Confirmed live 2026-08-18 from 14:30 ET, 27 rejections. Needs a startup assertion pairing + `EnableTrailingDrawdown` with a positive `AccountStartingBalance`. +3. **GAP-047 โ€” confluence factor weights pre-populated to 1.0; the designed weights are dead code.** + `ConfluenceScorer.cs` ~108-117 / ~410-419. Runtime-confirmed by `x1.00` on every factor in every + `STATE:` line. Makes Grade A close to structurally unreachable. **Primary suspect for GAP-034a.** +4. **GAP-034a โ€” silent zero-trade defect, no candidate produced** (08-03, 08-04, 08-13). Still open; + GAP-047 is now the leading hypothesis, ahead of the four candidates previously ranked. + (**GAP-034b โ€” candidate produced but blocked at a risk gate โ€” is ROOT-CAUSED** by GAP-045/046.) +5. **GAP-054 โ€” auto-breakeven destroys the runner's trailing stop.** `SetStopLoss()` on + `_runnerSignalName` (~803) replaces the `SetTrailStop()` issued at entry (~2188/2196); the two + are mutually exclusive per signal name in NinjaScript. Confirmed in 4/4 broker-confirmed trades: + the trail was 12-16 ticks in profit when breakeven fired and was moved back to +1. + **Blocks RUNNER-001** โ€” the sweep would measure a disabled trail. Supersedes the + "retune the breakeven trigger" framing of DEC-20260810-02 / DEC-20260815-01. +6. **GAP-055 โ€” `MaxDailyTrades` does not survive a restart.** In-memory counter only. CME trading + date 2026-08-17 took two trades under `MaxDailyTrades=1` across two NT8 sessions; the second + session's `DayPnL` proves NT8 treated them as one day. +7. **Dirty working tree.** 17 modified, 5 untracked, including `NT8StrategyBase.cs` and + `SimpleORBNT8.cs` carrying uncommitted DEC-20260818-01..-17 work that is deployed and running. + +### Also raised by the v7.0 review (open, not blocking Gate 3 start) +- **GAP-048** โ€” reject taxonomy conflates four causes under `KillSwitch` (portfolio block, Tier 1 + risk, circuit breaker, actual kill switch). Diagnostics-only fix; zero trading-behaviour risk. +- **GAP-049** โ€” telemetry `STATE:` score is direction-incorrect and is presented as the trade grade. +- **GAP-050** โ€” `MaxTradeRisk` has no quantity term; worst case is $600 vs a $1,000 daily limit. +- **GAP-051** โ€” `MicroUpgradeThreshold` fires every session at the current balance. +- **GAP-052** โ€” two independent hardcoded tick-value tables. +- **GAP-053** โ€” `executive_summary.md` and this document's Sprint 3 list present ~12 tasks + completed 2026-07-11 as still open. Prune or regenerate. + +### Numbering caution +v6.4 renumbered the July 17-31 data-audit findings to GAP-041..046, which now collide with this +document's own GAP-042/043/044. **This register is authoritative for `GAP-` numbers.** The historical +audit findings are renamed `HIST-41`..`HIST-46` in v7.0 Section 7.6. + +### Configuration freeze status +`docs/gate-runs/gate3/baseline.json` no longer describes any running system: 2026-08-18 produced +nine distinct `ConfigHash` values, three `CodeVersion` MVIDs and five bar periods, with +`MinTradeGrade` 5->4, `EnableKillSwitch` True->False and `RiskPerTrade` $200->$100 drifted from the +baseline. Two instances also ran concurrently on the same account and instrument. Re-capture required. Resolved 2026-08-16: the dirty working tree blocker was cleared and `docs/gate-runs/gate3/baseline.json` was produced by `freeze_20260816_170304`. @@ -58,9 +103,16 @@ distance, recorded in a superseding decision entry, before `DEC-GATE3-CONFIG` is ## Sprint 3 โ€” Production Hardening (ACTIVE) All tasks in order in SPRINT_BOARD.md. Full prompts in KILOCODE_RUNBOOK.md. -Architecture defects (blocks live trading): -- TASK-06a: Runner Mode enum + NT8StrategyBase redesign -- TASK-06b: ATR-based dynamic stop +> **STALE-LIST WARNING (GAP-053, added 2026-08-18).** The lists immediately below still show +> TASK-06a, TASK-06b, GAP-003, GAP-004, GAP-005, GAP-006, GAP-008, GAP-009, GAP-010, GAP-019 and +> GAP-022 as open work. **All of these were completed on 2026-07-11 / 07-14** โ€” see the historical +> record in `SPRINT_BOARD.md` and DEC-20260711-01..09, DEC-20260713-02. GAP-011 was completed +> 2026-07-11 and GAP-040 is implemented and firing in production as of 2026-08-18. This block has +> not been pruned since July and misleads anyone onboarding. Prune it at the next republish. + +Architecture defects (COMPLETED 2026-07-11 โ€” retained here only until this block is pruned): +- ~~TASK-06a: Runner Mode enum + NT8StrategyBase redesign~~ โœ… 2026-07-11 (DEC-20260711-01) +- ~~TASK-06b: ATR-based dynamic stop~~ โœ… 2026-07-11 (DEC-20260711-02) Risk hardening: - GAP-019: Portfolio Heat Tier 3.5 (MaxHeatPct enforcement) @@ -117,6 +169,84 @@ Gate criteria for Sprint 3 โ†’ Sprint 4: - GAP-013: ContractRollHandler completion - GAP-015: Config JSON export/import - GAP-014: LiquidityMonitor Level II prep +- GAP-042: `PortfolioRiskManager` has no account dimension (singleton keyed + only by strategyId) โ€” must be fixed before running strategies on + different accounts simultaneously; see `docs/00-governance/architecture.md` + "Multi-Strategy / 24x7 Trading Architecture" for detail. Required before + Sprint 4's multi-strategy plans extend to multiple accounts. +- GAP-043: Primary bar series (`HFTAlgoBarsType`) is a third-party custom + bar type, not native to NT8 โ€” confirmed 2026-08-18 by full-repo search + (zero matches; it does not exist anywhere in this SDK). Vendor + dependency risk: if the add-on stops being maintained, updated, or + compatible with a future NT8 version, the primary series becomes + unavailable with no in-repo fallback. Operator has deferred deep + investigation but wants to revisit. + **Candidates to evaluate:** Tick Bars (500, 1000 ticks), Volume Bars + (1000, 2500 contracts), Range Bars (4-tick/1.0pt, 8-tick/2.0pt) โ€” all + native NT8 bar types, all well-documented under Strategy Analyzer + Tick + Replay (ties to `DEC-20260814-03`'s 60-day warm-up rule). + **Order Flow+** is not a peer candidate for bar cadence โ€” it's NT8's + premium volumetric/footprint data layer, normally applied on top of a + time/tick/volume bar type rather than replacing it. None of today's + factor calculators consume anything beyond OHLCV+volume, so adopting it + would require new factor-calculator work (e.g. a real order-flow- + imbalance confluence factor) before it changed strategy behavior at + all โ€” a separate, larger project from the bar-cadence question, and it + requires a Level II/market-depth subscription. + **Before comparing:** confirm `HFTAlgoBarsType` actually supports + Strategy Analyzer + Tick Replay โ€” some custom bar generators are + live-only and can't produce a matched backtest baseline, in which case + the comparison would need to lean on existing live/SIM session history + as the baseline instead. + **Data limitation:** `SIGNAL`/`SUBMIT`/`STATE_DETAIL` FileLog lines only + write during `State.Realtime`, not Strategy Analyzer backtests โ€” grade/ + score/factor-reason data won't be available for backtest comparison, + only NT8's native Trades-tab columns (entry/exit price, P&L, MAE/MFE, + bars-in-trade). Comparison would need to lean on trade count, win rate, + profit factor, average R-multiple, and average bars-in-trade (a proxy + for confirmation-timing character) rather than confluence grading. + **Sequencing:** run this only after GAP-034-adjacent live-risk fixes + (historical-replay order submission, sizing-before-dynamic-stop + reordering) are confirmed clean on the *current* bar type โ€” changing + bar type in the same window as fixing live-risk bugs would make it hard + to attribute any behavior change to the right cause. A bar-type change + also alters `ConfigHash` (`DEC-20260810-01`), so it requires restarting + Gate validation from a clean baseline regardless of when it happens. +- GAP-044: Primary series `DaysToLoad` does not respect the operator's + configured value, and this is now confirmed independent of bar type โ€” + originally observed 2026-08-18 with the third-party `HFTAlgoBarsType` + (configured 120, logged `DaysToLoad=3`), then reproduced the same day + with fully native `MinuteBarsType` on 5-minute bars (configured 90, + logged `DaysToLoad=5`). This rules out the vendor bar type (`GAP-043`) + as the cause โ€” the two issues are unrelated and should not be + conflated. Full-repo search confirms nothing in this SDK's source sets + or overrides `DaysToLoad` for the primary series (`BarsArray[0]`); it is + driven entirely by NT8 platform/workspace state invisible to the + codebase (either the chart's own Data Series configuration, or the + Strategies dialog's independent Data Series tab, depending on how the + strategy is attached), so this cannot be diagnosed or fixed from source + alone. `DEC-20260814-03`'s 60-trading-day warm-up requirement for valid + backtests depends on `DaysToLoad` actually taking effect, so this + should be resolved before relying on backtest comparisons for `GAP-043` + or any other Strategy Analyzer work. + **Operator-side troubleshooting, not yet attempted/ruled out:** confirm + which dialog actually governs `BarsArray[0]` for the current attach + method (chart-inherited vs. Strategies-dialog independent series); + check for a saved workspace/template reasserting a stale value on load; + try disabling the strategy, changing the value, then re-enabling rather + than editing live; check whether the field is set to an explicit number + vs. a "Default"/auto mode that may resolve independently of the typed + value. + **Operator hypothesis (2026-08-18):** the saved NT8 workspace is + reasserting a stale `DaysToLoad` value on load โ€” operator reports a + prior, similar experience with workspace state persisting settings it + shouldn't have. Confirmation test: create a brand-new chart (not opened + from the existing saved workspace) and attach the strategy there with + the desired `DaysToLoad`. If it holds on the fresh chart, the workspace + is confirmed as the cause; if it still reverts, the cause is elsewhere + (see troubleshooting list above). NT8 workspaces are stored as XML under + `Documents\NinjaTrader 8\workspaces\` if direct inspection or discarding + the stale one becomes necessary. Not yet tested as of this entry. - Go live with 1 MNQ contract (micro) after SIM gate + Sprint 3 complete Gate criteria: 2 weeks live MNQ PF > 1.8, max loss < $100/day @@ -139,7 +269,18 @@ Gate criteria: 60+ days live fills, model trained and walk-forward validated --- ## Sprint 6 โ€” Full Dashboard + iOS (deferred) -- Dashboard Phase 3 (control layer: pause, flatten, kill switch) +- Dashboard Phase 3 (control layer: pause, flatten, kill switch) โ€” two + design paths recorded in `docs/00-governance/architecture.md` "Control + Plane": an NT8 Add-On WPF panel (below) or an external command-file + channel extending the existing `SetParameters()` plumbing. Recommendation + is to build the external channel first for platform-neutrality. - Dashboard Phase 4 (intelligence layer: playbook, health score, missed trades) +- Multi-timeframe regime alignment (raised by operator 2026-08-17): the + console dashboard mockup's "full timeframe continuity" concept โ€” scoring + regime agreement across several timeframes (e.g. 5m/15m/1h/daily) rather + than today's single daily SMA20/50 value โ€” is a real feature idea but not + scoped. Needs its own `NT8.Core/Intelligence` design pass (new factor + calculator or `RegimeManager` usage across multiple bar series) before + implementation; not a quick addition to existing telemetry. - iOS companion app - NT8 Add-On WPF panel (Section 22 / Appendix D of master doc) diff --git a/docs/NT8_SDK_Master_Document_v7.0_Complete.docx b/docs/NT8_SDK_Master_Document_v7.0_Complete.docx new file mode 100644 index 0000000..132ac65 Binary files /dev/null and b/docs/NT8_SDK_Master_Document_v7.0_Complete.docx differ diff --git a/docs/NT8_SDK_v7.0_Visual_Pack.html b/docs/NT8_SDK_v7.0_Visual_Pack.html new file mode 100644 index 0000000..72b9ef1 --- /dev/null +++ b/docs/NT8_SDK_v7.0_Visual_Pack.html @@ -0,0 +1,556 @@ + + + + + +NT8-SDK v7.0 โ€” Visual Pack + + + +
+ +
+
+

NT8-SDK โ€” Visual Pack v7.0

+

Companion to NT8_SDK_Master_Document_v7.0_Complete.docx ยท rev B ยท evidence as of 2026-08-18 ยท repo C:\dev\nt8-sdk @ f617574

+
+ +
+ + + + +
+

1 ยท Nine-layer architecture

+

Layers 1โ€“8 are platform-free. Layer 9 is the only one that imports NinjaTrader. That separation is real and maintained โ€” it is what makes a broker-neutral platform achievable rather than a rewrite. The status column is honest about which layers are actually load-bearing today.

+
+
1
Strategy
IStrategy ยท SimpleORBStrategy ยท NT8 wrappers
Signal only. Emits StrategyIntent
load-bearing
+
2
Intelligence
ConfluenceScorer ยท 10 ร— IFactorCalculator ยท GradeFilter
Quality gate before risk
weighting defect
+
3
Risk
BasicRisk T1 ยท AdvancedRisk T2/T3/T3.5 ยท PortfolioRiskManager
Four checkpoints per trade
blocking trades
+
4
Sizing
BasicPositionSizer ยท GradeBasedSizer ยท VolatilityAdjustedSizer
Dollar risk โ†’ contracts
load-bearing
+
5
OMS
OrderStateMachine ยท BasicOrderManager ยท DuplicateOrderDetector
Thread-safe order lifecycle
load-bearing
+
6
Analytics
TradeRecorder ยท PerformanceCalculator ยท MonteCarlo ยท PnLAttributor
Measurement, ML dataset
built, unconsumed
+
7
Execution
CircuitBreaker ยท TrailingStopManager ยท ExecutionQualityTracker
Execution safety, fill quality
wired
+
8
Market Data
SessionManager ยท AVWAPCalculator ยท LiquidityMonitor
Context for factors
depth hardcoded
+
9
NT8 Adapter Ring
NT8StrategyBase (2,880 lines) ยท OrderAdapter ยท DataAdapter ยท LoggingAdapter
Only layer importing NinjaTrader
load-bearing
+
+

Dead code worth knowing about: RegimeManager, TrendRegimeDetector and VolatilityRegimeDetector are instantiated in Layer 2 but never called in the live signal path (DEC-20260817-04). The regime values actually used come from inline SMA20/50 arithmetic in BuildStrategyContext().

+
+ + +
+

2 ยท The bar-to-trade pipeline

+

Eighteen stages between a bar closing and an order reaching the broker. The order matters: SIGNAL: is written at stage 8, before every risk gate, which is what makes a silent day diagnosable. Red rows are where trades died on 2026-08-18.

+
+
1
CME holiday guard
CmeHoliday
clear
+
2
Connection state
โ€” (bar skipped)
clear
+
3
Kill switch
KillSwitch
off today
+
4
Warm-up โ€” first realtime bar
WarmupIncomplete
17 today
+
5
RTH window guard
RthGuard
233 today
+
6
ETH telemetry branch โ†’ return
โ€”
opt-in
+
7a
ORB range established
OrbRangeNotEstablished
OrbReady=True
+
7b
Two-bar pullback confirmation
OrbRangeNotEstablished
confirmed
+
7c
Direction filters ยท AVWAP short veto
GradeFilter
passed
+
7d
Confluence grade โ‰ฅ MinTradeGrade
GradeFilter
GAP-047 suspect
+
7e
MaxDailyTrades cap
MaxDailyTrades
not hit
+
8
SIGNAL: written โ€” unconditional, before all risk gates
โ€”
5 today
+
9
Historical replay catch-up block
HistoricalReplayCatchup
317 today
+
10
Dynamic ATR stop finalised โ€” before sizing
โ€”
45 ticks
+
11
Trailing drawdown monitor
TrailingDrawdownBreach
27 blocked
+
12
Portfolio risk
KillSwitch (mislabelled)
passed
+
13
Tier 1 per-trade risk โ€” StopTicks ร— tickValue โ‰ค MaxTradeRisk
KillSwitch (mislabelled)
5 blocked
+
14
Position sizing
GradeFilter (mislabelled)
never reached
+
15
Circuit breaker
KillSwitch (mislabelled)
never reached
+
16
Runner mode resolution
โ€”
never reached
+
17
SetStopLoss / SetProfitTarget โ†’ Enterโ€ฆManaged
โ€”
0 today
+
18
SUBMIT: + provenance row (realtime only)
โ€”
0 today
+
+

Four rows share the label KillSwitch (stages 3, 12, 13, 15) and four share GradeFilter (7c, 7d, 14). REJECT SUMMARY aggregates on reason, so its counts are ambiguous. On 2026-08-17 a session logged KillSwitch count=647 from a genuine kill switch; on 08-18 a session logged KillSwitch count=5 from a MaxTradeRisk rejection. Splitting the taxonomy is task P0-C.

+
+ + +
+

3 ยท Risk validation โ€” four tiers plus the new monitor

+

A trade must clear every applicable tier. The annotation on Tier 1 is the most consequential correction in v7.0.

+
+TIER 1 โ€” BasicRiskManager + โ”œโ”€ Daily loss P&L โ‰ค โˆ’DailyLossLimit ($1,000) โ†’ HALT for the day + โ”œโ”€ Per-trade risk StopTicks ร— tickValue > MaxTradeRisk ($200) โ†’ REJECT + โ”‚ โ†‘ NO QUANTITY TERM. Evaluated BEFORE sizing. + โ”‚ โ†‘ NQ: caps the stop at 40 ticks. MaxStopTicks is 50. + โ”‚ โ†‘ 2026-08-18: rejected 5 signals at $225.00 > $200.00 + โ”‚ โ†‘ Real worst case = MaxTradeRisk ร— MaxContracts = $600 + โ”œโ”€ Position count OpenPositions โ‰ฅ MaxOpenPositions (3) โ†’ REJECT + โ””โ”€ 80% warning P&L โ‰ค โˆ’$800 โ†’ LOG only + +TIER 2 โ€” AdvancedRiskManager (weekly + drawdown) + โ”œโ”€ Weekly loss WeeklyPnL โ‰ค โˆ’WeeklyLossLimit โ†’ HALT, resets Monday + โ”œโ”€ Trailing DD TrailingDrawdown โ‰ฅ DrawdownLimit โ†’ HALT until recovery + โ””โ”€ DD 80% DrawdownPct โ‰ฅ 0.8 โ†’ LOG alert + +TIER 3 โ€” cross-strategy + โ””โ”€ Cross exposure TotalExposure > MaxCrossStrategyExposure โ†’ REJECT + +TIER 3.5 โ€” portfolio heat + โ””โ”€ Heat % (TotalOpenRisk + NewTradeRisk) / Equity ร— 100 โ†’ REJECT if > MaxHeatPct (3.0%) + โ†‘ this tier DOES include quantity โ€” Tier 1 does not + +TRAILING DRAWDOWN MONITOR โ€” account-keyed, new 2026-08-18 + โ”œโ”€ equity = Account.Get(AccountItem.NetLiquidation) โ† not yet validated + โ”œโ”€ peak = max(peak, equity) + โ”œโ”€ lock-in if peak โ‰ฅ AccountStartingBalance + LockOffset (100) โ†’ lock + โ”œโ”€ reference = locked ? lockedPeak : peak + โ”œโ”€ floor = reference โˆ’ HaltBuffer (2000) + โ””โ”€ GUARD: EnableTrailingDrawdown=True + AccountStartingBalance=0 โ†’ BLOCK ALL ENTRIES + โ†‘ 2026-08-18 14:30 onward. 27 rejections. No startup assertion. +
+
+ + +
+

4 ยท Confluence scoring โ€” designed weights vs what actually runs

+

Each factor calculator emits its designed weight. ConfluenceScorer's constructor pre-populates a weight dictionary with 1.0 for all ten factor types, and ResolveWeight() checks that dictionary first โ€” so the calculators' weights are unreachable dead code. Every STATE: line in production reads x1.00.

+
+
+ Designed weight (from the factor calculators) + Actual runtime weight (pre-populated, always 1.00) +
+
+
+ +

The same ten factor scores, both ways โ€” live data, 2026-08-18 10:10:11 ET

+
+
Composite โ€” equal weights
0.640
Grade C ยท what the system logged
+
Composite โ€” designed weights
0.727
Grade B ยท one full grade higher
+
Total weight
10.00 vs 5.85
Context factors carry 50% instead of 14.5%
+
Grade A reachability
structurally hard
Needs all ten factors โ‰ฅ 0.80 average; designed scheme reaches A on factors 1โ€“5 alone
+
+ +

Live factor scores that produced those composites

+ + + +
#FactorScoreDesigned wtActual wtReason logged
+

Grade thresholds: A+ โ‰ฅ 0.90 ยท A โ‰ฅ 0.80 ยท B โ‰ฅ 0.70 ยท C โ‰ฅ 0.60 ยท D below ยท F at floor. The live gate configuration froze MinTradeGrade = 5 (Grade A); today's workspace runs MinTradeGrade = 4 (Grade B) โ€” itself a drift from the frozen baseline.

+
+ + +
+

5 ยท Runner economics โ€” why the third contract earns nothing

+

Revised in rev B โ€” the diagnosis changed. The runner is not badly tuned. Its trailing stop is switched off mid-trade. SetStopLoss() and SetTrailStop() are mutually exclusive per signal name in NinjaScript, and the auto-breakeven block calls SetStopLoss() on the runner signal โ€” replacing a live 12-tick trail with a static stop at entry +1. In 4/4 trades the trail was already 12โ€“16 ticks in profit when breakeven fired and was moved backwards.

+
+AT ENTRY โ€” correct NinjaScript + SetStopLoss (_runnerSignalName, Ticks, intent.StopTicks) initial protective stop + SetTrailStop(_runnerSignalName, Ticks, RunnerTrailTicks=12) โ† replaces it with a LIVE 12-tick trail + EnterLong/EnterShort(runnerQty, _runnerSignalName) + +IN OnBarUpdate โ€” the defect (NT8StrategyBase.cs ~803) + if (EnableAutoBreakeven && !_breakevenMoved && profitTicks >= 20) + SetStopLoss(_runnerSignalName, Price, entry+1tick) โ† DESTROYS THE TRAIL + +WHAT THAT DOES TO THE STOP + entry โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถ price + โ”‚ + โ”œโ”€โ”€ +12..16t where the live 12-tick trail already sat when breakeven fired + โ”‚ + โ”œโ”€โ”€ +1t where SetStopLoss moved it โ† 11โ€“15 ticks of locked profit given back + โ”‚ + โ”œโ”€โ”€ +24..28t breakeven actually fires here, not at 20 (Calculate = OnBarClose) + โ”‚ + โ””โ”€โ”€ ... trail is gone. Runner sits static until stopped near entry. + +THE SOURCE COMMENT FOUR LINES BELOW + "Do NOT call SetTrailStop here โ€” that resets the trail anchor..." + The author correctly avoided that trap and did not notice that the + SetStopLoss call above it destroys the trail outright. +
+ + + + + + + + + +
TradeProfit when BE firedWhere a 12t trail satWhere the stop wentRunner grossRunner net
2026-08-07+28 t+16 t+1 t$5.00โˆ’$0.76
2026-08-10+25 t+13 t+1 t$0.00โˆ’$5.76
2026-08-16+24 t+12 t+1 t$15.00+$9.24
2026-08-17+26 t+14 t+1 t$5.00โˆ’$0.76
4 tradesโ€”55 t = $2754 t = $20$25.00+$1.96
+
+
Total net P&L
$1,035.88
4 broker-confirmed trades, after $69.12 commission
+
Runner share of P&L
0.19%
for 33% of contract exposure
+
RTH_ORB trades only
3
$758.16 ยท the 08-16 trade was ETH
+
Runner net, RTH only
โˆ’$7.28
on gate-eligible trades, it loses money
+
Runner net with a working trail
โ‰ˆ$252
conservative floor: exit at the trail's position when BE fired. It ratchets further, so this is a lower bound
+
Uplift on realised P&L
โ‰ˆ24%
$1,035.88 โ†’ โ‰ˆ$1,286 ยท from deleting one call site
+
+

Two secondary defects in the same block. entryPrice is Position.AveragePrice โ€” the blended 3-contract average, not the runner's own fill. On 08-16 that produced a breakeven price of 30200.08, which is not a valid NQ price (tick 0.25). And because Calculate = OnBarClose, the 20-tick trigger actually fires at 24โ€“28 ticks.

Consequence for STAGE 2: the RUNNER-001 sweep must not run until this is fixed. An 18-combination sweep over breakeven trigger ร— trail distance against a runner whose trail is disabled would return a trail axis with no effect and a confident, meaningless recommendation. Fix first (task P2-0), then sweep.

+
+ + +
+

6 ยท Parameter interaction map

+

Fourteen interactions between parameters that are individually reasonable. Four are actively broken; two of those are stopping trades today.

+
+
+ + +
+

7 ยท Gap register

+

Colour is severity. GAP-045 through GAP-053 are new in v7.0. Note the numbering caution: GAP-042/043/044 mean the repository's definitions; the July audit findings that v6.4 gave those numbers are renamed HIST-41โ€ฆ46 to make a third collision impossible.

+

Blocking

+
+

Open โ€” high

+
+

Open โ€” medium and low

+
+

Recently closed

+
+
+ + +
+

8 ยท Roadmap v7.0 โ€” critical path

+

Re-sequenced around three principles: unblock before optimising, fix the measuring instrument before measuring, and treat sample rate as a first-class objective. Stage 3's duration is the whole story.

+
+
STAGE 0
Unblock
P0-A trailing drawdown ยท P0-A2 startup assertion ยท P0-B MaxTradeRisk ยท P0-C reject taxonomy ยท P0-D commit tree ยท P0-E re-freeze
1โ€“2 days
optimistic 1
+
STAGE 1
Trustworthy instrument
P1-A factor weighting โ† highest-value item in the project ยท P1-B risk envelope ยท P1-C coherence assertions ยท P1-D telemetry direction ยท P1-E gap magnitude ยท P1-F DaysToLoad ยท P1-G configdiff as a gate
1โ€“2 weeks
optimistic 3d
+
STAGE 2
Runner
P2-A analyzer viability โ†’ P2-B 18-combination sweep โ†’ P2-C analyse โ†’ P2-D superseding decision ยท depends on P1-F
1โ€“2 weeks
optimistic 2d
+
STAGE 3
Gate Run #3
โ‰ฅ2 weeks AND โ‰ฅ20 RTH_ORB trades, single frozen account ยท outcome matrix decides PASS / CONDITIONAL / MARGINAL / NO EDGE / NEGATIVE / FAIL-on-risk
2โ€“7 months
optimistic 2wk
+
STAGE 4
Ruling
Gate report ยท grade-vs-outcome correlation (never measured) ยท direction split ยท runner attribution ยท cost analysis ยท GAP-007 walk-forward
1โ€“2 weeks
+
STAGE 5
Live micro
1 MNQ contract ยท real capital ยท trailing drawdown properly configured ยท PF > 1.8, max daily loss < $100
6โ€“10 weeks
+
STAGE 6
Scale
GAP-042 account dimension (prerequisite) ยท scale NQ size ยท LondonORBNT8 ยท VWAPMeanReversion ยท overnight gap ยท GAP-043 bar-type evaluation
โ€”
+
STAGE 7
Platform
External command channel (read side can start in Stage 3) ยท broker-neutral event schema ยท web + mobile dashboard ยท additional broker adapters
โ€”
+
+
+
Trades in the last 6 weeks
4
โ‰ˆ0.7 per week
+
20-trade sample at that rate
โ‰ˆ7 months
This is the binding constraint, not the edge
+
To first live capital
4โ€“10 mo
optimistic โ‰ˆ11 weeks
+
If GAP-047 is the cause
weeks
Fixing the weighting could compress Stage 3 from months to weeks
+
+
+ + +
+

9 ยท 2026-08-18 โ€” the day in evidence

+

Sixteen sessions started. Five valid signals. Zero orders. Two independent blockers, both root-caused, both fixable this week.

+
+
06:50 / 07:11
Two strategy instances arm on the same account and instrument (SimSimple ORB / NQ SEP26), both on HFT Algo Bars. Both run until 13:12. single-account doctrine violated
+
07:11:17
Session header: DaysToLoad=3 on the primary series (configured 120) ยท WARNING: EnableKillSwitch=False for gate account ยท factor warm-up SATISFIED, 87 daily bars
+
09:30 โ€“ 10:00
Opening range forms: high 29,769.75, low 29,604.75 โ€” a 165-point range
+
10:10:11
STATE: Regime=Bearish Direction=Sell Score=0.640 Grade=C โ€” every factor at x1.00. STATE_CONTEXT: OrbReady=True RecommendedContracts=1. The same block reports GapDirectionAlignment="Large gap โˆ’523.25 opposes trade" on a Sell โ€” the telemetry path's direction is stale Finding 5
+
10:10:24.956
SIGNAL: Sell NQ | LIVE MODE โ€” the real intent passed the grade filter
+
10:10:24.956
REJECT: reason=KillSwitch detail=Risk manager rejected: Trade risk too high: $225.00
45-tick ATR stop ร— $5.00 = $225.00 > MaxTradeRisk $200.00. MinContracts=1 is already the floor; there is nothing to reduce. Blocker A
+
10:10:25 โ†’ 10:10:46
Four more SIGNAL: Sell NQ lines. All rejected. REJECT SUMMARY: reason=KillSwitch count=5
+
13:19 โ€“ 14:23
Five more sessions started across five different bar periods โ€” HFT Algo, 5 Minute, 15 Minute, 30 Minute, 13 Minute. Nine distinct ConfigHash values and three distinct CodeVersion MVIDs on the day config freeze not in force
+
14:30:00.133
REJECT: reason=TrailingDrawdownBreach detail=EnableTrailingDrawdown=True but AccountStartingBalance is not configured
The monitor added today (DEC-20260818-17) correctly refuses to run without a floor โ€” and its refusal blocks every entry for the rest of the session. 27 rejections. Blocker B
+
16:40
Last session terminates. Signals: 5 ยท Submissions: 0 ยท Fills: 0 ยท P&L: $0.00
+
+

What this day proves. The strategy found a textbook setup โ€” a clean 165-point opening range, a confirmed breakout, a bearish regime, and 4.1ร— average breakout volume โ€” and could not act on it, twice, for two reasons that have nothing to do with the trading hypothesis. That is the whole argument for Stage 0.

+
+ + +
+

10 ยท The 24ร—5 session clock

+

24ร—5 coverage is concurrent strategy instances with disjoint session windows, not switching between strategies โ€” settled in architecture.md on 2026-08-17. PortfolioRiskManager was already built for it. A new strategy is a new IStrategy plus a thin NinjaScript subclass; the shared base is not forked. The roadmap names four strategies. It has never had a clock. Here it is.

+
+
03:00
LondonORBNT8 โ€” 03:00โ€“03:30 ET opening range
Sprint 4 ยท named only
no design
+
09:30
SimpleORBNT8 โ€” 09:30โ€“10:00 ET opening range
under validation
the one that exists
+
11:00
VWAPMeanReversion โ€” 11:00โ€“14:00 ET
Sprint 4 ยท named only
no design
+
15:00
unassigned โ€” closing drive / second RTH ORB
not on the roadmap
gap
+
18:00
unassigned โ€” Asia-session ORB, the symmetric counterpart to London
not on the roadmap
gap
+
O/N
OvernightGapContinuation / OvernightGapReversion โ€” event-driven
Sprint 4 ยท named only
no design
+
+

Prerequisites before any of this starts

+ + + + + + + + + +
PrerequisiteWhy
Stage 5 passedDo not multiply an unvalidated edge
GAP-042 โ€” account dimension in PortfolioRiskManagerThe singleton is keyed only by strategyId. Fine for several strategies on one account; unsafe across accounts
GAP-055 โ€” MaxDailyTrades persistenceA cap that resets on restart becomes per-strategy-per-restart once several instances run
A portfolio daily loss limit distinct from the sum of per-strategy limitsThree strategies at $1,000 each is a $3,000 day. The hook exists; the number has never been set
Instrument decision (MNQ vs NQ)Three strategies on NQ at MinContracts=1 is a much blunter instrument than three on MNQ
+

Assessment: the roadmap covers roughly two thirds of a tradeable 24ร—5 clock, by name only โ€” no entry hypothesis, no session-window map before this one, no per-strategy design pass. The architecture to support it is genuinely ready and has never been collected. Correctly sequenced behind Stage 5, but the design work is a real outstanding item, not a checkbox.

+
+ +
NT8-SDK Visual Pack v7.0 rev B ยท generated 2026-08-18 ยท companion to NT8_SDK_Master_Document_v7.0_Complete.docx
All figures traced to C:\dev\nt8-sdk and Documents\NinjaTrader 8\log\nt8-sdk. No source code was modified.
+ +
+ + + + diff --git a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs index 572776f..751368b 100644 --- a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs +++ b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs @@ -88,6 +88,27 @@ namespace NinjaTrader.NinjaScript.Strategies HardVeto = 2 } + /// + /// Manual risk posture tier. This is an operator setting only; code never changes it automatically. + /// + public enum RiskTier + { + /// + /// Lowest risk posture; drawdown breaches persist across restarts until the operator removes the halt file. + /// + Conservative, + + /// + /// Default risk posture; drawdown breaches are in-memory only. + /// + Normal, + + /// + /// Highest risk posture; drawdown breaches are in-memory only. + /// + Aggressive + } + /// /// Base class for strategies that integrate NT8 SDK components. /// @@ -123,6 +144,17 @@ namespace NinjaTrader.NinjaScript.Strategies private readonly object _fileLock = new object(); private readonly Dictionary _rejectCounts = new Dictionary(); private readonly HashSet _rejectDetailsLogged = new HashSet(); + private const int REJECT_SUMMARY_SNAPSHOT_INTERVAL_MINUTES = 15; + private const int STATE_TELEMETRY_INTERVAL_SECONDS = 30; + private DateTime _lastRejectSummarySnapshotTime = DateTime.MinValue; + private DateTime _lastStateTelemetryTime = DateTime.MinValue; + private bool _stateTelemetryChangeInitialized; + private int _lastStateTelemetryPendingBreakoutDirection; + private bool _lastStateTelemetryGradeMeetsThreshold; + private bool _orbRejectSummarySnapshotWritten; + private bool _microUpgradeSuggested; + private bool _trailingDrawdownHalted; + private string _trailingDrawdownAccountName; // TASK-00a: Provenance Controls - session tracking protected string _sessionId; @@ -155,6 +187,34 @@ namespace NinjaTrader.NinjaScript.Strategies [Display(Name = "Max Positions", GroupName = "Risk", Order = 3)] public int MaxOpenPositions { get; set; } + [NinjaScriptProperty] + [Display(Name = "Risk Tier", GroupName = "Risk Tier", Order = 1, Description = "Manual operator risk posture. This is never changed automatically by the strategy.")] + public RiskTier RiskTier { get; set; } + + [NinjaScriptProperty] + [Display(Name = "Micro Upgrade Threshold", GroupName = "Risk Tier", Order = 2, Description = "Informational balance threshold. Crossing it logs a one-time suggestion only; RiskTier is not changed automatically.")] + public double MicroUpgradeThreshold { get; set; } + + [NinjaScriptProperty] + [Display(Name = "Enable Trailing Drawdown", GroupName = "Trailing Drawdown", Order = 1, Description = "Opt-in account-scoped realtime trailing drawdown halt monitor.")] + public bool EnableTrailingDrawdown { get; set; } + + [NinjaScriptProperty] + [Display(Name = "Account Starting Balance", GroupName = "Trailing Drawdown", Order = 2, Description = "Explicit account starting balance from funded activation; required when trailing drawdown is enabled.")] + public double AccountStartingBalance { get; set; } + + [NinjaScriptProperty] + [Display(Name = "Trailing Drawdown Amount", GroupName = "Trailing Drawdown", Order = 3, Description = "Real account trailing drawdown amount. Informational for this monitor; halt uses the configured halt buffer.")] + public double TrailingDrawdownAmount { get; set; } + + [NinjaScriptProperty] + [Display(Name = "Trailing Drawdown Halt Buffer", GroupName = "Trailing Drawdown", Order = 4, Description = "Halt distance below active peak/locked value. Defaults to 2000 to halt before a 2500 trail is reached.")] + public double TrailingDrawdownHaltBuffer { get; set; } + + [NinjaScriptProperty] + [Display(Name = "Trailing Drawdown Lock Offset", GroupName = "Trailing Drawdown", Order = 5, Description = "Lock-in offset above starting balance. Default 100 matches Bulenox; other firms may need different values.")] + public double TrailingDrawdownLockOffset { get; set; } + [NinjaScriptProperty] [Display(Name = "Risk Per Trade", GroupName = "Sizing", Order = 1)] public double RiskPerTrade { get; set; } @@ -192,6 +252,14 @@ namespace NinjaTrader.NinjaScript.Strategies [Display(Name = "Enable Chart Diagnostics", GroupName = "Diagnostics", Order = 12, Description = "When true, draws visual diagnostic elements on the chart for every decision.")] public bool EnableChartDiagnostics { get; set; } + [NinjaScriptProperty] + [Display(Name = "Enable State Telemetry", GroupName = "Diagnostics", Order = 13, Description = "When true, emits throttled realtime confluence and regime telemetry to the session log.")] + public bool EnableStateTelemetry { get; set; } + + [NinjaScriptProperty] + [Display(Name = "Enable ETH Telemetry", GroupName = "Diagnostics", Order = 14, Description = "When true, emits read-only state telemetry outside RTH without running signal generation.")] + public bool EnableEthTelemetry { get; set; } + [NinjaScriptProperty] [Display(Name = "Enable Long Trades", GroupName = "Trade Direction", Order = 1)] public bool EnableLongTrades { get; set; } @@ -410,6 +478,13 @@ namespace NinjaTrader.NinjaScript.Strategies DailyLossLimit = 1000.0; MaxTradeRisk = 200.0; MaxOpenPositions = 3; + RiskTier = RiskTier.Normal; + MicroUpgradeThreshold = 5000.0; + EnableTrailingDrawdown = false; + AccountStartingBalance = 0.0; + TrailingDrawdownAmount = 2500.0; + TrailingDrawdownHaltBuffer = 2000.0; + TrailingDrawdownLockOffset = 100.0; RiskPerTrade = 100.0; MinContracts = 1; MaxContracts = 3; @@ -440,8 +515,13 @@ namespace NinjaTrader.NinjaScript.Strategies ATRTrailingMinTicks = 8; // GAP-009: default min 8 ticks ATRTrailingMaxTicks = 60; // GAP-009: default max 60 ticks EnableChartDiagnostics = false; // Chart diagnostics disabled by default + EnableStateTelemetry = true; // DASH-002: additive realtime observability + EnableEthTelemetry = false; // Read-only ETH telemetry is opt-in only _killSwitchTriggered = false; _connectionLost = false; + _microUpgradeSuggested = false; + _trailingDrawdownHalted = false; + _trailingDrawdownAccountName = null; // TASK-00a: Generate session ID for provenance tracking _sessionId = System.Guid.NewGuid().ToString("N"); @@ -477,6 +557,7 @@ namespace NinjaTrader.NinjaScript.Strategies EntriesPerDirection)); InitFileLog(); InitializeSdkComponents(); + InitializeTrailingDrawdownState(); _sdkInitialized = true; Print(string.Format("[SDK] {0} initialized successfully", Name)); WriteSettingsFile(); @@ -513,6 +594,8 @@ namespace NinjaTrader.NinjaScript.Strategies } else if (State == State.Terminated) { + if (!string.IsNullOrEmpty(_trailingDrawdownAccountName)) + TrailingDrawdownMonitor.Instance.UnregisterStrategy(_trailingDrawdownAccountName, this); PortfolioRiskManager.Instance.UnregisterStrategy(Name); WriteSessionFooter(); } @@ -595,6 +678,8 @@ namespace NinjaTrader.NinjaScript.Strategies _breakevenMoved = false; _scalerSignalName = null; _runnerSignalName = null; + _lastStateTelemetryTime = DateTime.MinValue; + _stateTelemetryChangeInitialized = false; } _lastBarTime = Time[0]; @@ -612,6 +697,10 @@ namespace NinjaTrader.NinjaScript.Strategies // Sync actual open position to portfolio manager on every bar PortfolioRiskManager.Instance.UpdateOpenContracts(Name, Math.Abs(Position.Quantity)); + MonitorMicroAccountUpgrade(); + if (CheckTrailingDrawdownMonitor()) + return; + // Kill switch โ€” checked AFTER bar guards so ExitLong/ExitShort are valid if (EnableKillSwitch) { @@ -660,6 +749,21 @@ namespace NinjaTrader.NinjaScript.Strategies Print(string.Format("[SDK] Skipping ETH bar {0} at {1:HH:mm}", CurrentBar, Time[0])); LogRejectRateLimited("RthGuard", string.Format("Time={0:HH:mm:ss} TestMode={1}", Time[0], isTestMode), Time[0]); + if (EnableEthTelemetry) + { + try + { + BarData ethBarData = ConvertCurrentBar(); + StrategyContext ethContext = BuildStrategyContext(); + MaybeWriteStateTelemetry(ethBarData, ethContext); + DrawDiagnostics(); + } + catch (Exception ex) + { + if (_logger != null) + _logger.LogWarning("ETH telemetry/diagnostics failed: {0}", ex.Message); + } + } return; } @@ -712,6 +816,8 @@ namespace NinjaTrader.NinjaScript.Strategies intent = _sdkStrategy.OnBar(barData, context); } + MaybeWriteStateTelemetry(barData, context); + if (intent != null) { Print(string.Format("[SDK] Intent generated: {0} {1} @ {2}", intent.Side, intent.Symbol, intent.EntryType)); @@ -732,6 +838,341 @@ namespace NinjaTrader.NinjaScript.Strategies } } + private void MonitorMicroAccountUpgrade() + { + if (_microUpgradeSuggested || Account == null || MicroUpgradeThreshold <= 0.0 || State != State.Realtime) + return; + + try + { + double balance = Account.Get(AccountItem.CashValue, Currency.UsDollar); + if (balance >= MicroUpgradeThreshold) + { + _microUpgradeSuggested = true; + string message = string.Format("TIER_UPGRADE_SUGGESTED: Balance={0:F2} crossed threshold={1:F2}; review RiskTier setting.", balance, MicroUpgradeThreshold); + Print(message); + FileLog(message); + } + } + catch (Exception ex) + { + if (EnableVerboseLogging) + Print(string.Format("[SDK] Micro upgrade balance check failed: {0}", ex.Message)); + } + } + + private bool CheckTrailingDrawdownMonitor() + { + if (!EnableTrailingDrawdown || Account == null || State != State.Realtime) + return _trailingDrawdownHalted; + + if (_trailingDrawdownHalted) + return true; + + if (AccountStartingBalance <= 0.0) + { + LogRejectRateLimited("TrailingDrawdownBreach", "EnableTrailingDrawdown=True but AccountStartingBalance is not configured", Time[0]); + return true; + } + + try + { + string accountName = Account.Name; + double equity = Account.Get(AccountItem.NetLiquidation, Currency.UsDollar); + TrailingDrawdownStatus status = TrailingDrawdownMonitor.Instance.UpdateEquity( + accountName, + equity, + AccountStartingBalance, + TrailingDrawdownHaltBuffer, + TrailingDrawdownLockOffset, + Time[0]); + + if (status != null && status.Breached) + { + HandleTrailingDrawdownBreach(status, true); + return true; + } + } + catch (Exception ex) + { + Print(string.Format("[SDK] Trailing drawdown monitor error: {0}", ex.Message)); + if (_logger != null) + _logger.LogError("Trailing drawdown monitor error: {0}", ex.Message); + } + + return _trailingDrawdownHalted; + } + + private void HandleTrailingDrawdownBreach(TrailingDrawdownStatus status, bool flatten) + { + if (status == null) + return; + + _trailingDrawdownHalted = true; + string message = string.Format("TRAILING_DRAWDOWN_BREACH: Account={0} Equity={1:F2} Peak={2:F2} Floor={3:F2} Locked={4} Time={5:yyyy-MM-dd HH:mm:ss}", + status.AccountName, + status.Equity, + status.ReferencePeak, + status.HaltThreshold, + status.Locked, + status.Time); + Print(message); + FileLog(message); + LogRejectRateLimited("TrailingDrawdownBreach", string.Format("Account={0} Equity={1:F2} Floor={2:F2} Locked={3}", status.AccountName, status.Equity, status.HaltThreshold, status.Locked), status.Time); + + if (RiskTier == RiskTier.Conservative) + WriteTrailingDrawdownHaltFile(status); + + if (flatten) + TrailingDrawdownMonitor.Instance.FlattenRegisteredStrategies(status.AccountName, status); + } + + private void FlattenForTrailingDrawdown(TrailingDrawdownStatus status) + { + _trailingDrawdownHalted = true; + try + { + ExitLong("TrailingDrawdownHalt"); + ExitShort("TrailingDrawdownHalt"); + } + catch (Exception ex) + { + Print(string.Format("[SDK] Trailing drawdown flatten error: {0}", ex.Message)); + } + } + + private void MaybeWriteStateTelemetry(BarData barData, StrategyContext context) + { + if (!EnableStateTelemetry || !EnableFileLogging || State != State.Realtime) + return; + if (barData == null || context == null) + return; + + DateTime now = DateTime.Now; + + try + { + StrategyIntent telemetryIntent = BuildStateTelemetryIntent(barData, context); + if (telemetryIntent == null) + return; + + ApplyDynamicStopToIntent(telemetryIntent, false); + + var scorer = new ConfluenceScorer(_logger != null ? _logger : new BasicLogger(Name), 10); + var score = scorer.CalculateScore(telemetryIntent, context, barData, BuildStateTelemetryFactors()); + string factors = FormatTelemetryFactors(score); + string regime = GetTelemetryRegime(context); + string directionSource = GetStateTelemetryDirectionSource(barData, context); + int pendingBreakoutDirection = GetStateTelemetryPendingBreakoutDirection(barData, context); + bool gradeMeetsThreshold = score != null && (int)score.Grade >= MinTradeGrade; + bool periodicDue = _lastStateTelemetryTime == DateTime.MinValue + || (now - _lastStateTelemetryTime).TotalSeconds >= STATE_TELEMETRY_INTERVAL_SECONDS; + bool changed = !_stateTelemetryChangeInitialized + || pendingBreakoutDirection != _lastStateTelemetryPendingBreakoutDirection + || gradeMeetsThreshold != _lastStateTelemetryGradeMeetsThreshold; + + if (!periodicDue && !changed) + return; + + FileLog(string.Format("STATE: Regime={0} Direction={1} DirectionSource={2} Score={3:F3} Grade={4} Factors={5}", + regime, + telemetryIntent.Side, + directionSource, + score.WeightedScore, + score.Grade, + factors)); + string detail = FormatFactorReasons(score); + if (!string.IsNullOrEmpty(detail)) + FileLog(string.Format("STATE_DETAIL: {0}", detail)); + Dictionary contextFields = GetStateTelemetryContextFields(barData, context); + contextFields = AddRecommendedContractsContextField(contextFields, telemetryIntent, context); + string contextDetail = FormatTelemetryContextFields(contextFields); + if (!string.IsNullOrEmpty(contextDetail)) + FileLog(string.Format("STATE_CONTEXT: {0}", contextDetail)); + + _lastStateTelemetryPendingBreakoutDirection = pendingBreakoutDirection; + _lastStateTelemetryGradeMeetsThreshold = gradeMeetsThreshold; + _stateTelemetryChangeInitialized = true; + if (periodicDue) + _lastStateTelemetryTime = now; + } + catch (Exception ex) + { + if (_logger != null) + _logger.LogWarning("State telemetry failed: {0}", ex.Message); + } + } + + protected virtual StrategyIntent BuildStateTelemetryIntent(BarData barData, StrategyContext context) + { + SdkOrderSide side = SdkOrderSide.Buy; + if (Position != null && Position.MarketPosition == MarketPosition.Short) + side = SdkOrderSide.Sell; + + return new StrategyIntent( + context.Symbol, + side, + SdkOrderType.Market, + null, + 1, + null, + 0.0, + "DASH-002 state telemetry sample", + new Dictionary()); + } + + protected virtual string GetStateTelemetryDirectionSource(BarData barData, StrategyContext context) + { + if (Position != null && Position.MarketPosition != MarketPosition.Flat) + return "Position"; + return "DefaultLong"; + } + + protected virtual int GetStateTelemetryPendingBreakoutDirection(BarData barData, StrategyContext context) + { + return 0; + } + + protected virtual Dictionary GetStateTelemetryContextFields(BarData barData, StrategyContext context) + { + return null; + } + + private Dictionary AddRecommendedContractsContextField(Dictionary fields, StrategyIntent telemetryIntent, StrategyContext context) + { + if (_positionSizer == null || _sizingConfig == null || telemetryIntent == null || context == null) + return fields; + + SizingResult sizingResult = _positionSizer.CalculateSize(telemetryIntent, context, _sizingConfig); + if (sizingResult == null) + return fields; + + if (fields == null) + fields = new Dictionary(); + if (fields.ContainsKey("RecommendedContracts")) + fields["RecommendedContracts"] = sizingResult.Contracts.ToString(); + else + fields.Add("RecommendedContracts", sizingResult.Contracts.ToString()); + + return fields; + } + + protected int ResolveDynamicStopTicks(int configuredStopTicks, Dictionary metadata, bool logCalculation) + { + if (!EnableDynamicStop || CurrentBars == null || CurrentBars.Length == 0 || CurrentBars[0] < AtrPeriod) + return configuredStopTicks; + + double atrValue = ATR(Close, AtrPeriod)[0]; + int dynStop = (int)System.Math.Round(atrValue / TickSize * AtrMultiplier); + dynStop = System.Math.Max(MinStopTicks, System.Math.Min(MaxStopTicks, dynStop)); + + if (metadata != null) + metadata["current_atr"] = atrValue / TickSize; + + if (logCalculation) + { + Print(String.Format("[SDK] Dynamic stop: ATR={0:F1}t x {1} = {2}t (${3})", + atrValue / TickSize, AtrMultiplier, dynStop, dynStop * 5)); + } + + return dynStop; + } + + private void ApplyDynamicStopToIntent(StrategyIntent intent, bool logCalculation) + { + if (intent == null) + return; + + intent.StopTicks = ResolveDynamicStopTicks((int)intent.StopTicks, intent.Metadata, logCalculation); + } + + private List BuildStateTelemetryFactors() + { + var factors = new List(); + factors.Add(new OrbSetupFactorCalculator()); + factors.Add(new TrendAlignmentFactorCalculator()); + factors.Add(new VolatilityRegimeFactorCalculator()); + factors.Add(new TimeInSessionFactorCalculator()); + factors.Add(new ExecutionQualityFactorCalculator()); + factors.Add(new NarrowRangeFactorCalculator(_logger)); + factors.Add(new OrbRangeVsAtrFactorCalculator(_logger)); + factors.Add(new GapDirectionAlignmentCalculator(_logger)); + factors.Add(new BreakoutVolumeStrengthCalculator(_logger)); + factors.Add(new PriorDayCloseStrengthCalculator(_logger)); + return factors; + } + + private string FormatTelemetryFactors(ConfluenceScore score) + { + if (score == null || score.Factors == null) + return "none"; + + StringBuilder builder = new StringBuilder(); + foreach (ConfluenceFactor factor in score.Factors) + { + if (builder.Length > 0) + builder.Append(";"); + builder.Append(string.Format("{0}={1:F2}x{2:F2}", factor.Type, factor.Score, factor.Weight)); + } + + return builder.Length > 0 ? builder.ToString() : "none"; + } + + private string FormatTelemetryContextFields(Dictionary fields) + { + if (fields == null || fields.Count == 0) + return string.Empty; + + StringBuilder builder = new StringBuilder(); + foreach (KeyValuePair field in fields) + { + if (string.IsNullOrEmpty(field.Key) || string.IsNullOrEmpty(field.Value)) + continue; + if (builder.Length > 0) + builder.Append(" "); + builder.Append(string.Format("{0}={1}", field.Key, field.Value)); + } + + return builder.ToString(); + } + + private string FormatFactorReasons(ConfluenceScore score) + { + if (score == null || score.Factors == null) + return string.Empty; + + StringBuilder builder = new StringBuilder(); + foreach (ConfluenceFactor factor in score.Factors) + { + if (builder.Length > 0) + builder.Append(" "); + builder.Append(string.Format("{0}=\"{1}\"", factor.Type, EscapeLogValue(factor.Reason))); + } + + return builder.ToString(); + } + + private string EscapeLogValue(string value) + { + if (value == null) + return string.Empty; + return value.Replace("\\", "\\\\").Replace("\"", "\\\""); + } + + private string GetMetadataText(StrategyIntent intent, string key) + { + if (intent == null || intent.Metadata == null || string.IsNullOrEmpty(key) || !intent.Metadata.ContainsKey(key) || intent.Metadata[key] == null) + return "N/A"; + return intent.Metadata[key].ToString(); + } + + private string GetTelemetryRegime(StrategyContext context) + { + if (context != null && context.CustomData != null && context.CustomData.ContainsKey("regime_trend") && context.CustomData["regime_trend"] != null) + return context.CustomData["regime_trend"].ToString(); + return "Neutral"; + } + protected override void OnOrderUpdate( Order order, double limitPrice, @@ -900,11 +1341,7 @@ namespace NinjaTrader.NinjaScript.Strategies try { - string dir = string.IsNullOrEmpty(LogDirectory) - ? System.IO.Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - "NinjaTrader 8", "log", "nt8-sdk") - : LogDirectory; + string dir = ResolveLogDirectory(false, "session file log"); System.IO.Directory.CreateDirectory(dir); @@ -922,6 +1359,28 @@ namespace NinjaTrader.NinjaScript.Strategies } } + private string GetDefaultLogDirectory() + { + return System.IO.Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + "NinjaTrader 8", "log", "nt8-sdk"); + } + + protected string ResolveLogDirectory(bool warnWhenDefault, string purpose) + { + if (!string.IsNullOrEmpty(LogDirectory)) + return LogDirectory; + + string dir = GetDefaultLogDirectory(); + if (warnWhenDefault) + { + string warning = string.Format("[NT8-SDK] WARNING: LogDirectory is blank; using default log directory for {0}: {1}", purpose, dir); + Print(warning); + FileLog(warning); + } + return dir; + } + private void FileLog(string message) { if (_fileLog == null) @@ -961,7 +1420,10 @@ namespace NinjaTrader.NinjaScript.Strategies private void LogRejectRateLimited(string reason, string detail, DateTime barTime) { - if (!EnableFileLogging || State != State.Realtime) + if (!EnableFileLogging) + return; + + if (State != State.Realtime && reason != "HistoricalReplayCatchup") return; if (string.IsNullOrEmpty(reason)) @@ -974,6 +1436,8 @@ namespace NinjaTrader.NinjaScript.Strategies _rejectCounts.Add(reason, 0); _rejectCounts[reason] = _rejectCounts[reason] + 1; + MaybeWriteRejectSummarySnapshot(barTime); + if (_rejectDetailsLogged.Contains(reason)) return; @@ -994,10 +1458,32 @@ namespace NinjaTrader.NinjaScript.Strategies } } + private void MaybeWriteRejectSummarySnapshot(DateTime barTime) + { + if (_rejectCounts.Count == 0) + return; + + if (barTime.TimeOfDay < new TimeSpan(10, 0, 0)) + return; + + bool dueAfterOrbWindow = !_orbRejectSummarySnapshotWritten; + bool dueInterval = _lastRejectSummarySnapshotTime != DateTime.MinValue + && (barTime - _lastRejectSummarySnapshotTime).TotalMinutes >= REJECT_SUMMARY_SNAPSHOT_INTERVAL_MINUTES; + + if (!dueAfterOrbWindow && !dueInterval) + return; + + WriteRejectSummary(); + _lastRejectSummarySnapshotTime = barTime; + _orbRejectSummarySnapshotWritten = true; + } + private void ResetRejectTracking() { _rejectCounts.Clear(); _rejectDetailsLogged.Clear(); + _lastRejectSummarySnapshotTime = DateTime.MinValue; + _orbRejectSummarySnapshotWritten = false; } private void WriteSessionHeader() @@ -1179,6 +1665,12 @@ namespace NinjaTrader.NinjaScript.Strategies PortfolioRiskManager.Instance.RegisterStrategy(Name, _riskConfig); Print(string.Format("[NT8-SDK] Registered with PortfolioRiskManager: {0}", PortfolioRiskManager.Instance.GetStatusSnapshot())); + if (Account != null) + { + _trailingDrawdownAccountName = Account.Name; + TrailingDrawdownMonitor.Instance.RegisterStrategy(_trailingDrawdownAccountName, this); + } + _ordersSubmittedToday = 0; _lastBarTime = DateTime.MinValue; _lastAccountInfo = null; @@ -1186,6 +1678,92 @@ namespace NinjaTrader.NinjaScript.Strategies _currentSession = null; } + private void InitializeTrailingDrawdownState() + { + if (Account == null) + return; + + _trailingDrawdownAccountName = Account.Name; + TrailingDrawdownMonitor.Instance.RegisterStrategy(_trailingDrawdownAccountName, this); + + if (!EnableTrailingDrawdown) + return; + + string haltPath = GetTrailingDrawdownHaltFilePath(_trailingDrawdownAccountName); + if (!string.IsNullOrEmpty(haltPath) && System.IO.File.Exists(haltPath)) + { + _trailingDrawdownHalted = true; + string message = string.Format("TRAILING_DRAWDOWN_HALTED: Account={0} persisted halt file present at {1}; delete file manually to resume.", _trailingDrawdownAccountName, haltPath); + Print(message); + FileLog(message); + } + } + + private string GetTrailingDrawdownHaltFilePath(string accountName) + { + if (string.IsNullOrEmpty(accountName)) + return string.Empty; + + string safeAccount = MakeSafeFileName(accountName); + string dir = ResolveLogDirectory(false, "trailing drawdown halt state"); + return System.IO.Path.Combine(dir, string.Format("drawdown_halt_{0}.json", safeAccount)); + } + + private string MakeSafeFileName(string value) + { + if (string.IsNullOrEmpty(value)) + return "account"; + + char[] invalid = System.IO.Path.GetInvalidFileNameChars(); + StringBuilder builder = new StringBuilder(value.Length); + for (int i = 0; i < value.Length; i++) + { + char c = value[i]; + bool isInvalid = false; + for (int j = 0; j < invalid.Length; j++) + { + if (c == invalid[j]) + { + isInvalid = true; + break; + } + } + builder.Append(isInvalid ? '_' : c); + } + return builder.ToString(); + } + + private void WriteTrailingDrawdownHaltFile(TrailingDrawdownStatus status) + { + if (status == null || string.IsNullOrEmpty(status.AccountName)) + return; + + try + { + string path = GetTrailingDrawdownHaltFilePath(status.AccountName); + if (string.IsNullOrEmpty(path)) + return; + + string dir = System.IO.Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) + System.IO.Directory.CreateDirectory(dir); + + var payload = new Dictionary(); + payload.Add("account", status.AccountName); + payload.Add("breach_timestamp", status.Time.ToString("yyyy-MM-dd HH:mm:ss")); + payload.Add("equity_at_breach", status.Equity); + payload.Add("floor_at_breach", status.HaltThreshold); + payload.Add("peak_reference", status.ReferencePeak); + payload.Add("locked", status.Locked); + System.IO.File.WriteAllText(path, JsonConvert.SerializeObject(payload, Formatting.Indented)); + FileLog(string.Format("TRAILING_DRAWDOWN_HALT_FILE: Account={0} Path={1}", status.AccountName, path)); + } + catch (Exception ex) + { + Print(string.Format("[SDK] Failed to write trailing drawdown halt file: {0}", ex.Message)); + } + } + private BarData ConvertCurrentBar() { // NT8 Time[0] is already in local time (ET on this machine). Use it directly. @@ -1333,6 +1911,14 @@ namespace NinjaTrader.NinjaScript.Strategies private void ProcessStrategyIntent(StrategyIntent intent, StrategyContext context) { + if (State == State.Historical && Account != null) + { + LogRejectRateLimited("HistoricalReplayCatchup", + string.Format("Blocked catch-up replay order Time={0:yyyy-MM-dd HH:mm:ss}", Time[0]), + Time[0]); + return; + } + // In live/SIM: block if we haven't seen a genuine realtime bar yet (replay guard). // In Strategy Analyzer (State.Historical): always allow โ€” backtest must execute normally. if (State == State.Realtime && !_realtimeBarSeen) @@ -1341,6 +1927,15 @@ namespace NinjaTrader.NinjaScript.Strategies return; } + if (_trailingDrawdownHalted || (EnableTrailingDrawdown && Account != null && TrailingDrawdownMonitor.Instance.IsHalted(Account.Name))) + { + _trailingDrawdownHalted = true; + LogRejectRateLimited("TrailingDrawdownBreach", "Trailing drawdown halt active; new entries blocked for this session", Time[0]); + return; + } + + ApplyDynamicStopToIntent(intent, true); + if (EnableFileLogging && State == State.Realtime) FileLog(string.Format("SIGNAL: {0} {1} | {2}", intent.Side, intent.Symbol, GetTestModeBanner())); @@ -1447,22 +2042,6 @@ namespace NinjaTrader.NinjaScript.Strategies RunnerMode resolvedMode = ResolveRunnerMode(RunnerActivationMode, request.Quantity); Print(String.Format("[SDK] Runner mode resolved: {0} (Qty={1})", resolvedMode, request.Quantity)); - // Dynamic ATR-based stop calculation (before sizing/mode logic) - if (EnableDynamicStop && CurrentBars[0] >= AtrPeriod) - { - double atrValue = ATR(Close, AtrPeriod)[0]; - int dynStop = (int)System.Math.Round(atrValue / TickSize * AtrMultiplier); - dynStop = System.Math.Max(MinStopTicks, System.Math.Min(MaxStopTicks, dynStop)); - intent.StopTicks = dynStop; - - // Pass ATR to Metadata for Factor 3 and TrailingStopManager (in ticks) - if (intent.Metadata != null) - intent.Metadata["current_atr"] = atrValue / TickSize; - - Print(String.Format("[SDK] Dynamic stop: ATR={0:F1}t x {1} = {2}t (${3})", - atrValue / TickSize, AtrMultiplier, intent.StopTicks, intent.StopTicks * 5)); - } - int scalerQty = 0; int runnerQty = 0; bool useRunnerLeg = false; @@ -1522,6 +2101,7 @@ namespace NinjaTrader.NinjaScript.Strategies string grade = "N/A"; string score = "N/A"; string factors = string.Empty; + string factorReasons = string.Empty; if (intent.Metadata != null && intent.Metadata.ContainsKey("confluence_score")) { var cs = intent.Metadata["confluence_score"] as NT8.Core.Intelligence.ConfluenceScore; @@ -1533,15 +2113,23 @@ namespace NinjaTrader.NinjaScript.Strategies foreach (var f in cs.Factors) sb.Append(String.Format("{0}={1:F2} ", f.Type, f.Score)); factors = sb.ToString().TrimEnd(); + factorReasons = FormatFactorReasons(cs); } } FileLog(String.Format("SIGNAL {0} | Grade={1} | Score={2}", intent.Side, grade, score)); + if (!string.IsNullOrEmpty(factorReasons)) + FileLog(String.Format("SIGNAL_DETAIL: {0}", factorReasons)); if (!string.IsNullOrEmpty(factors)) FileLog(String.Format(" Factors: {0}", factors)); - FileLog(String.Format("SUBMIT Scaler={0} Runner={1} Stop={2} Target={3} Mode={4}", + FileLog(String.Format("SUBMIT Scaler={0} Runner={1} Stop={2} Target={3} Mode={4} BaseTarget={5} DynamicTarget={6} GradeMult={7} ModeMult={8} CombinedMult={9}", scalerQty, runnerQty, intent.StopTicks, intent.TargetTicks.HasValue ? intent.TargetTicks.Value.ToString() : "none", - resolvedMode)); + resolvedMode, + GetMetadataText(intent, "base_target_ticks"), + GetMetadataText(intent, "dynamic_target_ticks"), + GetMetadataText(intent, "grade_multiplier"), + GetMetadataText(intent, "mode_multiplier"), + GetMetadataText(intent, "combined_multiplier"))); } // --- Submit scaler leg --- @@ -1600,11 +2188,8 @@ namespace NinjaTrader.NinjaScript.Strategies // TASK-00a: Write trade provenance double atrStopTicks = 0.0; - if (EnableDynamicStop && CurrentBars[0] >= AtrPeriod) - { - double atrValue = ATR(Close, AtrPeriod)[0]; - atrStopTicks = System.Math.Round(atrValue / TickSize * AtrMultiplier); - } + if (EnableDynamicStop) + atrStopTicks = intent.StopTicks; WriteTradeProvenance(intent, request.Quantity, atrStopTicks, resolvedMode); } catch (Exception ex) @@ -1665,6 +2250,14 @@ namespace NinjaTrader.NinjaScript.Strategies lines.Add(string.Format("MaxTradeRisk : {0:C}", MaxTradeRisk)); lines.Add(string.Format("MaxOpenPositions : {0}", MaxOpenPositions)); lines.Add(string.Format("RiskPerTrade : {0:C}", RiskPerTrade)); + lines.Add(string.Format("RiskTier : {0}", RiskTier)); + lines.Add(string.Format("MicroUpgradeThreshold: {0:C}", MicroUpgradeThreshold)); + lines.Add("--- Trailing Drawdown ---"); + lines.Add(string.Format("EnableTrailingDrawdown: {0}", EnableTrailingDrawdown)); + lines.Add(string.Format("AccountStartingBalance: {0:C}", AccountStartingBalance)); + lines.Add(string.Format("TrailingDrawdownAmount: {0:C}", TrailingDrawdownAmount)); + lines.Add(string.Format("TrailingDrawdownHaltBuffer: {0:C}", TrailingDrawdownHaltBuffer)); + lines.Add(string.Format("TrailingDrawdownLockOffset: {0:C}", TrailingDrawdownLockOffset)); lines.Add("--- Sizing ---"); lines.Add(string.Format("MinContracts : {0}", MinContracts)); lines.Add(string.Format("MaxContracts : {0}", MaxContracts)); @@ -1674,6 +2267,8 @@ namespace NinjaTrader.NinjaScript.Strategies lines.Add("--- Controls ---"); lines.Add(string.Format("EnableKillSwitch : {0}", EnableKillSwitch)); lines.Add(string.Format("EnableVerboseLogging: {0}", EnableVerboseLogging)); + lines.Add(string.Format("EnableStateTelemetry: {0}", EnableStateTelemetry)); + lines.Add(string.Format("EnableEthTelemetry : {0}", EnableEthTelemetry)); lines.Add(string.Format("MinTradeGrade : {0}", MinTradeGrade)); lines.Add(string.Format("EnableFileLogging : {0}", EnableFileLogging)); lines.Add(string.Format("LogDirectory : {0}", string.IsNullOrEmpty(LogDirectory) ? "(default)" : LogDirectory)); @@ -1726,11 +2321,7 @@ namespace NinjaTrader.NinjaScript.Strategies try { - string dir = string.IsNullOrEmpty(LogDirectory) - ? System.IO.Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - "NinjaTrader 8", "log", "nt8-sdk") - : LogDirectory; + string dir = ResolveLogDirectory(false, "settings export"); System.IO.Directory.CreateDirectory(dir); @@ -1763,6 +2354,8 @@ namespace NinjaTrader.NinjaScript.Strategies if (!EnableChartDiagnostics) return; + var topLeftLines = new List(); + // 1. Regime Indicator - AVWAP slope banner in top-left if (_currentSession != null && _strategyConfig != null && _strategyConfig.Parameters != null) { @@ -1773,13 +2366,26 @@ namespace NinjaTrader.NinjaScript.Strategies { double slopeVal = (double)slope; string regimeText = slopeVal > 0 ? "REGIME: BULLISH" : "REGIME: BEARISH"; - Brush regimeBrush = slopeVal > 0 ? Brushes.LimeGreen : Brushes.Red; - Draw.TextFixed(this, "Diag_Regime", regimeText, TextPosition.TopLeft, regimeBrush, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100); + topLeftLines.Add(regimeText); } } } - // 2. Session Tag - RTH/ETH tag in top-right + // 2. Runner Mode Label - shows current runner mode + if (EnableRunner) + topLeftLines.Add("RUNNER: " + RunnerActivationMode.ToString()); + + AppendTopLeftDiagnosticLines(topLeftLines); + RemoveDrawObject("Diag_Regime"); + RemoveDrawObject("Diag_Runner"); + RemoveDrawObject("Diag_TradeTaken"); + RemoveDrawObject("Diag_DailyCount"); + if (topLeftLines.Count > 0) + Draw.TextFixed(this, "Diag_TopLeft", string.Join(Environment.NewLine, topLeftLines.ToArray()), TextPosition.TopLeft, Brushes.White, new SimpleFont("Arial", 10), Brushes.Black, Brushes.Black, 80); + else + RemoveDrawObject("Diag_TopLeft"); + + // 3. Session Tag - RTH/ETH tag in top-right if (_currentSession != null) { string sessionTag = _currentSession.IsRth ? "SESSION: RTH" : "SESSION: ETH"; @@ -1787,13 +2393,6 @@ namespace NinjaTrader.NinjaScript.Strategies Draw.TextFixed(this, "Diag_Session", sessionTag, TextPosition.TopRight, sessionBrush, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100); } - // 3. Runner Mode Label - shows current runner mode - if (EnableRunner) - { - string runnerText = "RUNNER: " + RunnerActivationMode.ToString(); - Draw.TextFixed(this, "Diag_Runner", runnerText, TextPosition.TopLeft, Brushes.Yellow, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100); - } - // 4. TestMode Banner - prominent when TestMode is active bool testMode = false; if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode")) @@ -1825,6 +2424,185 @@ namespace NinjaTrader.NinjaScript.Strategies Draw.TextFixed(this, "Diag_Prov", "Prov: settings_" + Name.Replace(" ", "_") + "_" + DateTime.Now.ToString("yyyyMMdd"), TextPosition.BottomRight, Brushes.Gray, new SimpleFont("Arial", 8), Brushes.Transparent, Brushes.Transparent, 50); } + /// + /// Allows derived strategies to add lines to the shared top-left diagnostics block. + /// + protected virtual void AppendTopLeftDiagnosticLines(List lines) + { + } + + private class TrailingDrawdownStatus + { + public string AccountName { get; set; } + public double Equity { get; set; } + public double Peak { get; set; } + public double LockedPeak { get; set; } + public bool Locked { get; set; } + public double ReferencePeak { get; set; } + public double HaltThreshold { get; set; } + public bool Breached { get; set; } + public DateTime Time { get; set; } + } + + private class TrailingDrawdownAccountState + { + public double Peak { get; set; } + public double LockedPeak { get; set; } + public bool Locked { get; set; } + public bool Breached { get; set; } + + public TrailingDrawdownAccountState(double startingBalance) + { + Peak = startingBalance; + LockedPeak = 0.0; + Locked = false; + Breached = false; + } + } + + private class TrailingDrawdownMonitor + { + private static readonly object _instanceLock = new object(); + private static TrailingDrawdownMonitor _instance; + + public static TrailingDrawdownMonitor Instance + { + get + { + if (_instance == null) + { + lock (_instanceLock) + { + if (_instance == null) + _instance = new TrailingDrawdownMonitor(); + } + } + return _instance; + } + } + + private readonly object _lock; + private readonly Dictionary _states; + private readonly Dictionary> _strategiesByAccount; + + private TrailingDrawdownMonitor() + { + _lock = new object(); + _states = new Dictionary(); + _strategiesByAccount = new Dictionary>(); + } + + public void RegisterStrategy(string accountName, NT8StrategyBase strategy) + { + if (string.IsNullOrEmpty(accountName) || strategy == null) + return; + + lock (_lock) + { + List strategies; + if (!_strategiesByAccount.TryGetValue(accountName, out strategies)) + { + strategies = new List(); + _strategiesByAccount.Add(accountName, strategies); + } + if (!strategies.Contains(strategy)) + strategies.Add(strategy); + } + } + + public void UnregisterStrategy(string accountName, NT8StrategyBase strategy) + { + if (string.IsNullOrEmpty(accountName) || strategy == null) + return; + + lock (_lock) + { + List strategies; + if (_strategiesByAccount.TryGetValue(accountName, out strategies)) + { + strategies.Remove(strategy); + if (strategies.Count == 0) + { + _strategiesByAccount.Remove(accountName); + _states.Remove(accountName); + } + } + } + } + + public bool IsHalted(string accountName) + { + if (string.IsNullOrEmpty(accountName)) + return false; + + lock (_lock) + { + TrailingDrawdownAccountState state; + return _states.TryGetValue(accountName, out state) && state.Breached; + } + } + + public TrailingDrawdownStatus UpdateEquity(string accountName, double equity, double startingBalance, double haltBuffer, double lockOffset, DateTime time) + { + if (string.IsNullOrEmpty(accountName)) + throw new ArgumentNullException("accountName"); + + lock (_lock) + { + TrailingDrawdownAccountState state; + if (!_states.TryGetValue(accountName, out state)) + { + state = new TrailingDrawdownAccountState(System.Math.Max(startingBalance, equity)); + _states.Add(accountName, state); + } + + if (equity > state.Peak) + state.Peak = equity; + + if (!state.Locked && state.Peak >= startingBalance + lockOffset) + { + state.Locked = true; + state.LockedPeak = state.Peak; + } + + double referencePeak = state.Locked ? state.LockedPeak : state.Peak; + double haltThreshold = referencePeak - haltBuffer; + if (equity <= haltThreshold) + state.Breached = true; + + return new TrailingDrawdownStatus + { + AccountName = accountName, + Equity = equity, + Peak = state.Peak, + LockedPeak = state.LockedPeak, + Locked = state.Locked, + ReferencePeak = referencePeak, + HaltThreshold = haltThreshold, + Breached = state.Breached, + Time = time + }; + } + } + + public void FlattenRegisteredStrategies(string accountName, TrailingDrawdownStatus status) + { + List strategies = new List(); + lock (_lock) + { + List registered; + if (_strategiesByAccount.TryGetValue(accountName, out registered)) + strategies.AddRange(registered); + } + + foreach (NT8StrategyBase strategy in strategies) + { + if (strategy != null) + strategy.FlattenForTrailingDrawdown(status); + } + } + } + #region TASK-00a: Provenance Controls /// @@ -1899,13 +2677,10 @@ namespace NinjaTrader.NinjaScript.Strategies { try { - if (string.IsNullOrEmpty(LogDirectory)) - return; - if (_sessionId == null) _sessionId = Guid.NewGuid().ToString(); - var dir = LogDirectory; + var dir = ResolveLogDirectory(true, "session provenance"); Directory.CreateDirectory(dir); var provenance = new Dictionary @@ -1941,21 +2716,21 @@ namespace NinjaTrader.NinjaScript.Strategies /// protected virtual void WriteTradeProvenance(StrategyIntent intent, int quantity, double atrStopTicks, RunnerMode resolvedMode) { + if (State != State.Realtime) + return; + try { - if (string.IsNullOrEmpty(LogDirectory)) - return; - if (_sessionId == null) _sessionId = Guid.NewGuid().ToString(); _tradeSequence++; - var dir = LogDirectory; + var dir = ResolveLogDirectory(true, "trade provenance"); Directory.CreateDirectory(dir); var safeName = Name.Replace(" ", "_").Replace("/", "_").Replace("\\", "_"); - var path = Path.Combine(LogDirectory, string.Format("trades_{0}_{1}.jsonl", Name.Replace(" ", "_"), DateTime.Now.ToString("yyyyMMdd"))); + var path = Path.Combine(dir, string.Format("trades_{0}_{1}.jsonl", safeName, DateTime.Now.ToString("yyyyMMdd"))); var json = TradeProvenanceSerializer.Serialize( _sessionId, _tradeSequence, diff --git a/src/NT8.Adapters/Strategies/SimpleORBNT8.cs b/src/NT8.Adapters/Strategies/SimpleORBNT8.cs index 3b55a6b..d456a69 100644 --- a/src/NT8.Adapters/Strategies/SimpleORBNT8.cs +++ b/src/NT8.Adapters/Strategies/SimpleORBNT8.cs @@ -15,9 +15,11 @@ using NinjaTrader.NinjaScript.DrawingTools; using NinjaTrader.NinjaScript.Indicators; using NinjaTrader.NinjaScript.Strategies; using NT8.Core.Common.Interfaces; +using NT8.Core.Common.Models; using NT8.Core.Intelligence; using NT8.Strategies.Examples; using Newtonsoft.Json; +using SdkOrderType = NT8.Core.Common.Models.OrderType; using SdkSimpleORB = NT8.Strategies.Examples.SimpleORBStrategy; namespace NinjaTrader.NinjaScript.Strategies @@ -157,7 +159,7 @@ namespace NinjaTrader.NinjaScript.Strategies } else if (State == State.Configure) { - AddDataSeries(BarsPeriodType.Day, 1); + // NT8StrategyBase adds the shared daily series for regime and ORB context at BarsArray[1]. } base.OnStateChange(); @@ -201,6 +203,120 @@ namespace NinjaTrader.NinjaScript.Strategies return new SdkSimpleORB(OpeningRangeMinutes, StdDevMultiplier); } + protected override StrategyIntent BuildStateTelemetryIntent(BarData barData, StrategyContext context) + { + SdkSimpleORB sdkOrb = _sdkStrategy as SdkSimpleORB; + OrderSide side = OrderSide.Buy; + + if (sdkOrb != null) + { + if (sdkOrb.PendingBreakoutDirection < 0) + side = OrderSide.Sell; + else if (sdkOrb.PendingBreakoutDirection > 0) + side = OrderSide.Buy; + else if (sdkOrb.OpeningRangeReady && sdkOrb.OpeningRangeHigh > sdkOrb.OpeningRangeLow) + { + double midpoint = (sdkOrb.OpeningRangeHigh + sdkOrb.OpeningRangeLow) / 2.0; + side = barData.Close >= midpoint ? OrderSide.Buy : OrderSide.Sell; + } + else if (Position != null && Position.MarketPosition == MarketPosition.Short) + { + side = OrderSide.Sell; + } + } + + Dictionary metadata = new Dictionary(); + if (_strategyConfig != null + && _strategyConfig.Parameters != null + && _strategyConfig.Parameters.ContainsKey("daily_bars") + && _strategyConfig.Parameters["daily_bars"] != null) + { + metadata.Add("daily_bars", _strategyConfig.Parameters["daily_bars"]); + } + + int stopTicks = ResolveDynamicStopTicks(StopTicks, metadata, false); + + return new StrategyIntent( + context.Symbol, + side, + SdkOrderType.Market, + null, + stopTicks, + TargetTicks, + 0.0, + "DASH-002 Simple ORB state telemetry sample", + metadata); + } + + protected override string GetStateTelemetryDirectionSource(BarData barData, StrategyContext context) + { + SdkSimpleORB sdkOrb = _sdkStrategy as SdkSimpleORB; + if (sdkOrb != null) + { + if (sdkOrb.PendingBreakoutDirection != 0) + return "PendingBreakout"; + if (sdkOrb.OpeningRangeReady && sdkOrb.OpeningRangeHigh > sdkOrb.OpeningRangeLow) + return "OpeningRangeMidpoint"; + } + + if (Position != null && Position.MarketPosition != MarketPosition.Flat) + return "Position"; + + return "DefaultLong"; + } + + protected override int GetStateTelemetryPendingBreakoutDirection(BarData barData, StrategyContext context) + { + SdkSimpleORB sdkOrb = _sdkStrategy as SdkSimpleORB; + if (sdkOrb == null) + return 0; + return sdkOrb.PendingBreakoutDirection; + } + + /// + /// Adds Simple ORB status lines to the shared top-left diagnostics block. + /// + protected override void AppendTopLeftDiagnosticLines(List lines) + { + if (lines == null) + return; + + SdkSimpleORB sdkOrb = _sdkStrategy as SdkSimpleORB; + if (sdkOrb == null) + return; + + bool testMode = false; + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode")) + { + var tm = _strategyConfig.Parameters["TestMode"]; + if (tm is bool) + testMode = (bool)tm; + } + + if (testMode && sdkOrb.TradeTaken) + lines.Add("TRADE TAKEN (TestMode)"); + + if (sdkOrb.DailyTradeCount > 0) + lines.Add(string.Format("DAILY TRADES: {0}", sdkOrb.DailyTradeCount)); + } + + protected override Dictionary GetStateTelemetryContextFields(BarData barData, StrategyContext context) + { + SdkSimpleORB sdkOrb = _sdkStrategy as SdkSimpleORB; + if (sdkOrb == null) + return null; + if (!sdkOrb.OpeningRangeReady || sdkOrb.OpeningRangeHigh <= sdkOrb.OpeningRangeLow) + return null; + + Dictionary fields = new Dictionary(); + fields.Add("OrbHigh", sdkOrb.OpeningRangeHigh.ToString("F2")); + fields.Add("OrbLow", sdkOrb.OpeningRangeLow.ToString("F2")); + fields.Add("OrbWindowStart", sdkOrb.OpeningRangeStart.ToString("HH:mm")); + fields.Add("OrbWindowEnd", sdkOrb.OpeningRangeEnd.ToString("HH:mm")); + fields.Add("OrbReady", sdkOrb.OpeningRangeReady.ToString()); + return fields; + } + protected override void ConfigureStrategyParameters() { _strategyConfig.RiskSettings.DailyLossLimit = DailyLossLimit; @@ -363,6 +479,8 @@ namespace NinjaTrader.NinjaScript.Strategies if (sdkOrb == null) return; + var bottomLeftLines = new List(); + // 1. ORB Box - rectangle showing opening range high/low if (sdkOrb.OpeningRangeReady && sdkOrb.OpeningRangeHigh > sdkOrb.OpeningRangeLow) { @@ -399,40 +517,22 @@ namespace NinjaTrader.NinjaScript.Strategies if (tickSize <= 0.0) tickSize = 0.25; double orbRangeTicks = Math.Round((sdkOrb.OpeningRangeHigh - sdkOrb.OpeningRangeLow) / tickSize); string orbText = string.Format("ORB: {0:F0} ticks | Mult: {1:F1}", orbRangeTicks, sdkOrb.StdDevMultiplier); - Draw.TextFixed(this, "Diag_ORBRange", orbText, TextPosition.BottomLeft, Brushes.White, new SimpleFont("Arial", 9), Brushes.DarkBlue, Brushes.DarkBlue, 80); + bottomLeftLines.Add(orbText); } // 5. Breakout Direction Indicator if (sdkOrb.BreakoutBarSeen) { string dirText = sdkOrb.PendingBreakoutDirection == 1 ? "BREAKOUT: LONG" : "BREAKOUT: SHORT"; - Brush dirBrush = sdkOrb.PendingBreakoutDirection == 1 ? Brushes.LimeGreen : Brushes.Red; - Draw.TextFixed(this, "Diag_BreakoutDir", dirText, TextPosition.BottomLeft, dirBrush, new SimpleFont("Arial", 9), Brushes.Black, Brushes.Black, 80); + bottomLeftLines.Add(dirText); } - // 6. Trade Taken Status - bool testMode = false; - if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode")) - { - var tm = _strategyConfig.Parameters["TestMode"]; - if (tm is bool) - testMode = (bool)tm; - } - - if (testMode) - { - if (sdkOrb.TradeTaken) - { - Draw.TextFixed(this, "Diag_TradeTaken", "TRADE TAKEN (TestMode)", TextPosition.TopLeft, Brushes.Yellow, new SimpleFont("Arial", 10), Brushes.Red, Brushes.Red, 100); - } - } - - // 7. Daily Trade Count - if (sdkOrb.DailyTradeCount > 0) - { - string countText = string.Format("DAILY TRADES: {0}", sdkOrb.DailyTradeCount); - Draw.TextFixed(this, "Diag_DailyCount", countText, TextPosition.TopLeft, Brushes.Orange, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100); - } + RemoveDrawObject("Diag_ORBRange"); + RemoveDrawObject("Diag_BreakoutDir"); + if (bottomLeftLines.Count > 0) + Draw.TextFixed(this, "Diag_BottomLeft", string.Join(Environment.NewLine, bottomLeftLines.ToArray()), TextPosition.BottomLeft, Brushes.White, new SimpleFont("Arial", 9), Brushes.DarkBlue, Brushes.DarkBlue, 80); + else + RemoveDrawObject("Diag_BottomLeft"); } /// @@ -442,13 +542,10 @@ namespace NinjaTrader.NinjaScript.Strategies { try { - if (string.IsNullOrEmpty(LogDirectory)) - return; - if (_sessionId == null) _sessionId = Guid.NewGuid().ToString(); - var dir = LogDirectory; + var dir = ResolveLogDirectory(true, "Simple ORB session provenance"); Directory.CreateDirectory(dir); var provenance = new Dictionary diff --git a/tools/dashboard/README.md b/tools/dashboard/README.md index 1aa15ba..49c1040 100644 --- a/tools/dashboard/README.md +++ b/tools/dashboard/README.md @@ -52,6 +52,12 @@ Then open: http://127.0.0.1:8765/ ``` +The alternate trading-terminal view is available at: + +```text +http://127.0.0.1:8765/console.html +``` + Live read-only server launch: ```powershell @@ -72,7 +78,7 @@ http://127.0.0.1:8765/ 3. Click `Select triage.json` and choose the generated file. 4. Review the five views. -For live mode, launch `server.py`; the browser polls `/api/state` automatically every 5 seconds. +For live mode, launch `server.py`; `index.html` polls `/api/state` automatically every 5 seconds and `console.html` polls every 2 seconds. ## Live Server Config @@ -149,10 +155,14 @@ Webhook/notification failures are logged to stderr and never crash or block the ## Views +`index.html` is the triage board for deciding whether a silent session was a strategy decision or an operational defect. + +`console.html` is the alternate trading-console page. It consumes the same read-only `/api/state` payload and shows live strategy status, session readiness, provenance-backed trade rows, count-only grade distribution, PNL_UPDATE curve data, real FactorType score breakdowns, and raw log tail data. Fields that are not emitted by the runtime, such as entry/exit price and per-trade P&L, are explicitly marked unavailable instead of being inferred. + 1. Gate progress: trades banked against the 20-trade minimum, elapsed session days, current traded-session streak, and diagnostic count. 2. Daily timeline: one row per session, color-coded as traded, silent, or config violation. -3. Trade detail: grade, score, entry/exit fields, and scaler versus runner P&L attribution when present in TOOL-001 trade records. -4. Provenance health: sentinel/default-value counts per provenance field across trade records. +3. Trade detail: grade, score, and provenance fields when present in TOOL-001 trade records. +4. Provenance health: sentinel/default-value counts per field across trade records. 5. Config integrity: `ConfigHash` and `CodeVersion` timeline with drift markers. ## Data Contract diff --git a/tools/dashboard/console.css b/tools/dashboard/console.css new file mode 100644 index 0000000..ca14d6c --- /dev/null +++ b/tools/dashboard/console.css @@ -0,0 +1,279 @@ +:root { + --bg: #06090c; + --bg-glow: radial-gradient(circle at 12% -10%, #0d1f26 0%, transparent 45%); + --panel: #0b1015; + --panel-border: #1b2530; + --panel-border-soft: #141c25; + --text: #dce6ee; + --muted: #5f7182; + --muted-2: #8695a3; + --cyan: #35d1e8; + --green: #22c55e; + --green-dim: rgba(34, 197, 94, 0.14); + --red: #f5495f; + --red-dim: rgba(245, 73, 95, 0.14); + --amber: #f5a623; + --amber-dim: rgba(245, 166, 35, 0.14); + --blue: #4fa3ff; + --grade-a: #22c55e; + --grade-b: #4fa3ff; + --grade-c: #f5a623; + --grade-d: #5f7182; + --grade-f: #f5495f; + --mono: "JetBrains Mono", "SF Mono", ui-monospace, Menlo, Consolas, "Courier New", monospace; +} + +* { box-sizing: border-box; } + +body { + margin: 0; + min-height: 100vh; + background: var(--bg-glow), var(--bg); + color: var(--text); + font-family: var(--mono); +} + +a { color: var(--cyan); text-decoration: none; } +a:hover { text-decoration: underline; } + +.console-header { + display: flex; + justify-content: space-between; + align-items: flex-end; + gap: 1rem; + padding: 1.5rem; + border-bottom: 1px solid var(--panel-border-soft); +} + +.console-header h1 { + margin: 0.2rem 0; + font-size: clamp(1.9rem, 4vw, 4rem); + letter-spacing: -0.06em; + text-transform: uppercase; +} + +.eyebrow, .subhead, .muted, .card-note, small { color: var(--muted-2); } +.eyebrow { margin: 0; font-size: 0.72rem; letter-spacing: 0.18em; text-transform: uppercase; } +.subhead { margin: 0; } + +.header-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 0.7rem; +} + +.header-clock { color: var(--muted-2); font-size: 0.9rem; } +.nav-link { border: 1px solid var(--panel-border); border-radius: 999rem; padding: 0.4rem 0.75rem; } +.hidden { display: none !important; } + +main.console-grid { + display: grid; + grid-template-columns: repeat(12, minmax(0, 1fr)); + gap: 1rem; + padding: 1rem 1.5rem 1.5rem; +} + +.col-4 { grid-column: span 4; } +.col-8 { grid-column: span 8; } +.col-12 { grid-column: span 12; } + +.card { + background: var(--panel); + border: 1px solid var(--panel-border); + border-radius: 0.55rem; + padding: 1rem; +} + +.card-title { + position: relative; + margin: 0 0 0.8rem; + padding-left: 0.75rem; + font-size: 0.95rem; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.card-title::before { + content: ""; + position: absolute; + left: 0; + top: 0.05rem; + bottom: 0.05rem; + width: 3px; + background: var(--cyan); +} + +.section-stack { display: grid; gap: 1rem; } +.field-row { display: flex; justify-content: space-between; gap: 1rem; padding: 0.45rem 0; border-bottom: 1px solid var(--panel-border-soft); } +.field-row span:first-child { color: var(--muted); } +.field-row strong { text-align: right; } + +.pill, .side-pill, .grade-tag { + display: inline-flex; + align-items: center; + border-radius: 999rem; + border: 1px solid currentColor; + background: transparent; + font-size: 0.75rem; + font-weight: 700; + letter-spacing: 0.05em; + padding: 0.22rem 0.5rem; + text-transform: uppercase; +} + +.pill.good { color: var(--green); } +.pill.bad { color: var(--red); } +.pill.warn { color: var(--amber); } +.pill.info { color: var(--blue); } +.pill.muted { color: var(--muted); } +.side-pill.long { color: var(--green); } +.side-pill.short { color: var(--red); } +.side-pill.neutral { color: var(--muted); } + +.grade-a { color: var(--grade-a); } +.grade-b { color: var(--grade-b); } +.grade-c { color: var(--grade-c); } +.grade-d { color: var(--grade-d); } +.grade-f { color: var(--grade-f); } + +.confluence-list, .readiness-strip, .factor-bars, .stat-grid, .grade-grid { + display: grid; + gap: 0.65rem; +} + +.confluence-item, .readiness-chip, .factor-row, .stat-cell, .grade-cell { + border: 1px solid var(--panel-border-soft); + border-radius: 0.45rem; + background: rgba(255, 255, 255, 0.015); +} + +.confluence-item { + display: block; + padding: 0.5rem; +} + +.confluence-main { + display: flex; + justify-content: space-between; + gap: 0.6rem; +} + +.confluence-reason { + color: var(--muted-2); + font-size: 0.72rem; + font-style: italic; + margin-top: 0.3rem; +} + +.confluence-item.unmet { color: var(--muted); } +.confluence-score { color: var(--muted-2); white-space: nowrap; } +.source-tag { color: var(--cyan); font-size: 0.7rem; letter-spacing: 0.08em; text-transform: uppercase; } + +.readiness-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.readiness-chip { padding: 0.65rem; } +.readiness-chip strong { display: block; margin-bottom: 0.25rem; } +.readiness-chip.good { border-color: rgba(34, 197, 94, 0.45); } +.readiness-chip.bad { border-color: rgba(245, 73, 95, 0.45); } +.readiness-chip.warn { border-color: rgba(245, 166, 35, 0.45); } +.readiness-summary { + border: 1px solid rgba(79, 163, 255, 0.35); + border-radius: 0.5rem; + color: var(--text); + margin: 0.9rem 0; + padding: 0.75rem; +} +.readiness-detail { + border-top: 1px solid var(--panel-border-soft); + margin-top: 0.8rem; + padding-top: 0.8rem; +} +.readiness-detail summary { + color: var(--muted-2); + cursor: pointer; + font-size: 0.78rem; + letter-spacing: 0.1em; + margin-bottom: 0.75rem; + text-transform: uppercase; +} + +.telemetry-note, .data-gap { + border: 1px dashed var(--panel-border); + border-radius: 0.5rem; + color: var(--muted-2); + margin-top: 0.8rem; + padding: 0.75rem; +} + +.table-wrap { overflow-x: auto; } +table { width: 100%; border-collapse: collapse; } +th, td { border-bottom: 1px solid var(--panel-border-soft); padding: 0.65rem 0.6rem; text-align: left; white-space: nowrap; } +th { color: var(--muted); font-size: 0.72rem; letter-spacing: 0.08em; text-transform: uppercase; } +td.empty { color: var(--muted); text-align: center; } + +.grade-grid { grid-template-columns: repeat(5, minmax(0, 1fr)); } +.grade-cell { padding: 0.8rem; } +.grade-cell strong { display: block; font-size: 2rem; margin-top: 0.35rem; } + +.factor-row { padding: 0.65rem; } +.factor-meta { display: flex; justify-content: space-between; gap: 1rem; margin-bottom: 0.45rem; } +.factor-reason { color: var(--muted-2); font-size: 0.72rem; font-style: italic; margin-top: 0.4rem; } +.factor-track, .risk-track { background: #071018; border-radius: 999rem; overflow: hidden; } +.factor-track { height: 0.45rem; } +.factor-fill { height: 100%; width: 0; background: var(--cyan); } +.risk-track { height: 0.7rem; background: linear-gradient(90deg, var(--green-dim), var(--amber-dim), var(--red-dim)); border: 1px solid var(--panel-border-soft); } +.risk-fill { height: 100%; width: 0; background: var(--red); } + +.stat-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.stat-cell { padding: 0.75rem; } +.stat-cell span { color: var(--muted); display: block; font-size: 0.75rem; text-transform: uppercase; } +.stat-cell strong { display: block; font-size: 1.45rem; margin-top: 0.3rem; } +.telemetry-subtext { color: var(--muted-2); display: block; font-size: 0.72rem; margin-top: 0.2rem; text-transform: none; } + +.pnl-chart { width: 100%; min-height: 16rem; } +.pnl-chart svg { display: block; width: 100%; height: 16rem; border: 1px solid var(--panel-border-soft); border-radius: 0.45rem; background: #071018; } +.axis-label { color: var(--muted); display: flex; justify-content: space-between; margin-top: 0.4rem; font-size: 0.75rem; } + +.raw-log { + max-height: 24rem; + overflow: auto; + margin: 0; + padding: 0.85rem; + background: #071018; + border: 1px solid var(--panel-border-soft); + border-radius: 0.45rem; + color: var(--muted-2); + font-family: var(--mono); + font-size: 0.82rem; + line-height: 1.45; + white-space: pre-wrap; +} + +.raw-log-line { color: var(--muted-2); display: block; } +.raw-log-signal { color: var(--cyan); } +.raw-log-submit { color: var(--amber); } +.raw-log-fill { color: var(--green); } +.raw-log-reject { color: var(--red); } +.raw-log-reject-summary { color: rgba(245, 73, 95, 0.72); } +.raw-log-state { color: var(--blue); } +.raw-log-warning { color: var(--amber); } +.raw-log-connection-lost { color: var(--red); font-weight: 700; } +.raw-log-connection-restored { color: var(--green); font-weight: 700; } +.raw-log-session { color: var(--cyan); font-weight: 700; } + +.footnote { color: var(--muted); margin: 0.75rem 0 0; font-size: 0.82rem; } +.unavailable { border-color: rgba(245, 73, 95, 0.55); color: var(--red); } + +@media (max-width: 1100px) { + .col-4, .col-8, .col-12 { grid-column: 1 / -1; } + .readiness-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} + +@media (max-width: 640px) { + .console-header { align-items: flex-start; flex-direction: column; padding: 1rem; } + .header-actions { justify-content: flex-start; } + main.console-grid { padding: 1rem; } + .readiness-strip, .grade-grid, .stat-grid { grid-template-columns: 1fr; } + th, td { padding: 0.55rem 0.45rem; } +} diff --git a/tools/dashboard/console.html b/tools/dashboard/console.html new file mode 100644 index 0000000..afd73ea --- /dev/null +++ b/tools/dashboard/console.html @@ -0,0 +1,145 @@ + + + + + + NT8 SDK Trading Console + + + +
+
+

Trading Console

+

Simple ORB NT8

+

NQ ยท OPENING RANGE BREAKOUT

+
+
+ --:--:-- ET + Market unknown + + Triage Board +
+
+ +
+
+

Strategy Status

+
Live server unavailable. Open through tools/dashboard/server.py for live data.
+
+
+
ConnectionUnavailable
+
Mode-
+
Account-
+
SymbolNQ
+
+
+

Configured Risk (static)

+
R:R Ratio-
+
Target Ticks-
+
Stop Ticks-
+
Target Dollars-
+
Stop Dollars-
+

Static configured values above. Live per-trade sizing rationale below, once a trade has submitted this session.

+
+
+
+

Session Filter

+
WindowRTH ORB WINDOW
+
RTH Guard09:30-16:00 ET
+
+
+
+

Confluences

+
+

+
+
+
+ +
+

Session Readiness

+

Read from the current session Historical readiness block.

+

State Telemetry

+
+

Readiness summary unavailable until data loads.

+
+ Data Series Detail +
+
+
+ Factor Warm-Up Detail +
+
+
No state telemetry received yet this session.
+
+ +
+

Risk & Rejection Summary

+

Full current-session file, not limited to the raw-log tail.

+
+
Missed B+ Setups (approximate)0
+
+

Approximate: inferred from STATE samples after blocking REJECT reasons have appeared in the session log.

+
+ +
+

Signals by Grade

+

Generated signals correlated with fills before the next signal or session end.

+
+
+ Signal Outcome Detail +
+
+
+ +
+

Trade Log

+
+

Entry/exit price and per-trade P&L are not yet in trade provenance.

+
+ +
+

Grade Distribution

+
+
+ +
+

Intraday P&L Curve

+
+
+ +
+

Factor Breakdown

+

+
+
+ + + +
+

Raw Log

+
No live log data loaded.
+
+
+ + + + + + diff --git a/tools/dashboard/console.js b/tools/dashboard/console.js new file mode 100644 index 0000000..05d4e82 --- /dev/null +++ b/tools/dashboard/console.js @@ -0,0 +1,671 @@ +(function () { + "use strict"; + + var POLL_MS = 2000; + var FACTORS = ["Setup", "Trend", "Volatility", "Timing", "ExecutionQuality", "NarrowRange", "OrbRangeVsAtr", "GapDirectionAlignment", "BreakoutVolumeStrength", "PriorDayCloseStrength"]; + var GRADES = ["A", "B", "C", "D", "F"]; + var emptyTemplate = document.getElementById("empty-row"); + var latestPayload = null; + + function byId(id) { return document.getElementById(id); } + function asArray(value) { return Array.isArray(value) ? value : []; } + + function display(value) { + if (value === null || value === undefined || value === "") { + return "-"; + } + return String(value); + } + + function numberValue(value) { + if (typeof value === "number") { + return value; + } + if (value === null || value === undefined) { + return 0; + } + var parsed = parseFloat(String(value).replace(/[$,%]/g, "").replace(/,/g, "")); + return isNaN(parsed) ? 0 : parsed; + } + + function money(value) { + if (value === null || value === undefined || value === "") { + return "-"; + } + return "$" + numberValue(value).toFixed(2); + } + + function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } + + function setText(id, value) { byId(id).textContent = value; } + function setHtml(id, value) { byId(id).innerHTML = value; } + + function h(value) { + return display(value).replace(/[&<>"]/g, function (character) { + return { "&": "&", "<": "<", ">": ">", "\"": """ }[character]; + }); + } + + function pill(label, kind) { + return '' + h(label) + ''; + } + + function gradeClass(grade) { + var normalized = String(grade || "").toLowerCase().charAt(0); + return "grade-" + (normalized || "d"); + } + + function latestRow(payload) { + var rows = asArray(payload.rows); + return rows.length ? rows[rows.length - 1] : {}; + } + + function collectRejectRecords(payload) { + var results = []; + asArray(payload.reject_records || payload.rejects || payload.rejections).forEach(function (item) { + results.push(normalizeRejectRecord(item)); + }); + asArray(payload.rows).forEach(function (row) { + asArray(row.reject_records || row.rejects || row.rejections).forEach(function (item) { + results.push(normalizeRejectRecord(item)); + }); + }); + asArray(payload.diagnostics).forEach(function (item) { + if (item && (item.code === "REJECT" || item.event_type === "REJECT")) { + results.push(normalizeRejectRecord(item)); + } + }); + return results.filter(function (item) { return item.reason || item.detail; }); + } + + function normalizeRejectRecord(item) { + if (!item) { + return {}; + } + if (typeof item === "string") { + return parseRejectLine(item); + } + var line = item.line || item.message || item.raw || ""; + var parsed = line ? parseRejectLine(String(line)) : {}; + return { + reason: item.reason || item.reject_reason || parsed.reason, + detail: item.detail || item.reject_detail || parsed.detail || "", + bar: item.bar || item.bar_time || parsed.bar, + raw: line || item.raw || "" + }; + } + + function parseRejectLine(line) { + var reasonMatch = /reason=([^\s]+)/i.exec(line || ""); + var detailMatch = /detail=(.*?)(?:\s+bar=|$)/i.exec(line || ""); + var barMatch = /\sbar=(.*)$/i.exec(line || ""); + return { + reason: reasonMatch ? reasonMatch[1] : null, + detail: detailMatch ? detailMatch[1] : "", + bar: barMatch ? barMatch[1] : null, + raw: line + }; + } + + function parseFactors(detail) { + var factors = []; + var match = /Factors=([^\n]+)/i.exec(detail || ""); + if (!match) { + return factors; + } + match[1].split(";").forEach(function (part) { + var factor = /^([^=]+)=([0-9.]+)(?:x([0-9.]+))?/i.exec(part.trim()); + if (factor) { + factors.push({ name: factor[1], score: numberValue(factor[2]), weight: factor[3] ? numberValue(factor[3]) : 1 }); + } + }); + return factors; + } + + function pickFactors(payload) { + var telemetry = latestStateTelemetry(payload); + if (telemetry && asArray(telemetry.factors).length) { + return { factors: asArray(telemetry.factors), source: "live", label: "live state telemetry" }; + } + + var records = collectRejectRecords(payload).filter(function (record) { return record.reason === "GradeFilter"; }); + var i; + for (i = records.length - 1; i >= 0; i -= 1) { + var parsed = parseFactors(records[i].detail || records[i].raw || ""); + if (parsed.length) { + return { factors: parsed, source: "last rejection", label: "last GradeFilter rejection" }; + } + } + return { factors: [], source: "unavailable", label: "No factor data available yet โ€” waiting on state telemetry or a GradeFilter rejection." }; + } + + function latestStateTelemetry(payload) { + var live = payload.live_state || {}; + if (live.state_telemetry) { + return live.state_telemetry; + } + + var events = asArray(payload.events); + var i; + for (i = events.length - 1; i >= 0; i -= 1) { + if (events[i] && events[i].type === "STATE") { + return events[i]; + } + } + + return null; + } + + function factorMap(factors) { + var map = {}; + factors.forEach(function (factor) { map[factor.name] = factor; }); + return map; + } + + function clear(node) { + while (node.firstChild) { + node.removeChild(node.firstChild); + } + } + + function renderHeader(payload) { + var settings = payload.settings || {}; + var telemetry = latestStateTelemetry(payload); + var regimePill = byId("regime-pill"); + setText("strategy-name", settings.StrategyName || "Simple ORB NT8"); + if (telemetry && telemetry.regime) { + regimePill.className = "pill info"; + regimePill.textContent = "Regime " + telemetry.regime; + } else { + regimePill.className = "pill info hidden"; + regimePill.textContent = ""; + } + } + + function renderClock() { + var now = new Date(); + var parts = new Intl.DateTimeFormat("en-US", { timeZone: "America/New_York", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit", weekday: "short" }).formatToParts(now); + var values = {}; + parts.forEach(function (part) { values[part.type] = part.value; }); + var hour = Number(values.hour || 0); + var minute = Number(values.minute || 0); + var day = values.weekday || ""; + var minutes = hour * 60 + minute; + var weekday = day !== "Sat" && day !== "Sun"; + var open = weekday && minutes >= 570 && minutes < 960; + setText("live-clock", (values.hour || "--") + ":" + (values.minute || "--") + ":" + (values.second || "--") + " ET"); + setHtml("market-pill", pill(open ? "Market open" : "Market closed", open ? "good" : "muted")); + } + + function renderStatus(payload) { + var live = payload.live_state || {}; + var settings = payload.settings || {}; + var connection = live.connection || "Unavailable"; + var connectionKind = connection === "OK" || connection === "RESTORED" ? "good" : (connection === "LOST" ? "bad" : "muted"); + setHtml("connection-pill", pill(connection, connectionKind)); + setText("mode-value", display(live.mode)); + setText("account-value", display(live.account)); + setText("symbol-value", display(live.symbol || settings.Instrument || "NQ")); + setText("rr-ratio", display(settings.RR_Ratio)); + setText("target-ticks", display(settings.TargetTicks)); + setText("stop-ticks", display(settings.StopTicks)); + setText("target-dollars", display(settings.TargetDollars)); + setText("stop-dollars", display(settings.StopDollars)); + setText("orb-window", settings.OpeningRangeMinutes ? "09:30 + " + display(settings.OpeningRangeMinutes) + " min ORB" : "OpeningRangeMinutes unavailable"); + renderOrbRange(payload); + renderDynamicSizing(payload); + renderConfluences(payload); + } + + function renderOrbRange(payload) { + var node = byId("orb-range"); + var fields = ((payload.live_state || {}).state_context) || {}; + clear(node); + if (!("OrbHigh" in fields) || !("OrbLow" in fields)) { + node.innerHTML = '
ORB range not yet established this session.
'; + return; + } + node.innerHTML = '
ORB High' + h(fields.OrbHigh) + '
' + + '
ORB Low' + h(fields.OrbLow) + '
' + + '
Window' + h(fields.OrbWindowStart) + ' โ€“ ' + h(fields.OrbWindowEnd) + ' ET
'; + } + + function renderDynamicSizing(payload) { + var node = byId("dynamic-sizing"); + var submit = (payload.live_state || {}).last_submit; + var fields = submit && submit.fields ? submit.fields : null; + clear(node); + if (!fields || !("CombinedMult" in fields)) { + node.innerHTML = '
No trade submitted yet this session โ€” dynamic sizing rationale appears here after the first SUBMIT.
'; + return; + } + var rows = [ + ["Base Target", fields.BaseTarget], + ["Dynamic Target", fields.DynamicTarget], + ["Grade Multiplier", fields.GradeMult], + ["Mode Multiplier", fields.ModeMult], + ["Combined Multiplier", fields.CombinedMult] + ]; + rows.forEach(function (pair) { + var row = document.createElement("div"); + row.className = "field-row"; + var value = pair[1]; + var text = typeof value === "number" ? value.toFixed(3) : display(value); + row.innerHTML = "" + h(pair[0]) + "" + h(text) + ""; + node.appendChild(row); + }); + } + + function renderConfluences(payload) { + var list = byId("confluence-list"); + var picked = pickFactors(payload); + var map = factorMap(picked.factors); + var reasons = ((payload.live_state || {}).state_telemetry_reasons) || {}; + clear(list); + FACTORS.forEach(function (name) { + var factor = map[name]; + var reason = reasons[name]; + var row = document.createElement("div"); + row.className = "confluence-item" + (factor ? "" : " unmet"); + if (reason) { + row.title = reason; + } + row.innerHTML = "
" + h(name) + "" + (factor ? h(factor.score.toFixed(3) + " x " + factor.weight.toFixed(2)) : "unmet") + "
" + + (reason ? "
" + h(reason) + "
" : ""); + list.appendChild(row); + }); + setHtml("confluence-note", picked.factors.length ? '' + h(picked.source) + ' ' + h("Showing factors from " + picked.label + ".") : h(picked.label)); + } + + function renderReadiness(payload) { + var readiness = payload.readiness || {}; + setText("readiness-context", readiness.context || "No Historical readiness block found in the current payload."); + renderStateTelemetry(payload); + setText("readiness-summary", summarizeReadiness(readiness)); + renderDataSeries(asArray(readiness.data_series)); + renderWarmups(asArray(readiness.factors)); + } + + function renderStateTelemetry(payload) { + var node = byId("state-telemetry"); + var telemetry = latestStateTelemetry(payload); + clear(node); + if (!telemetry) { + node.innerHTML = '
No state telemetry received yet this session.
'; + setText("telemetry-note", "No state telemetry received yet this session. EnableStateTelemetry may be false, or the session may not have reached a STATE line yet."); + return; + } + + var directionSource = telemetry.direction_source || telemetry.directionsource; + var recommendedContracts = ((payload.live_state || {}).state_context) || {}; + node.innerHTML = '
Regime' + h(telemetry.regime) + '
' + + '
Direction' + h(telemetry.direction) + 'via ' + h(directionSource) + '
' + + '
Score' + h(telemetry.score !== undefined ? Number(telemetry.score).toFixed(3) : "-") + '
' + + '
Grade' + h(telemetry.grade) + '
' + + ('RecommendedContracts' in recommendedContracts ? '
Recommended Contracts' + h(recommendedContracts.RecommendedContracts) + '
' : ''); + setText("telemetry-note", "Latest STATE telemetry at " + display(telemetry.timestamp) + "; direction source: " + display(directionSource) + "."); + } + + function summarizeReadiness(readiness) { + var series = asArray(readiness.data_series); + var factors = asArray(readiness.factors); + var primary = series.length ? series[0] : null; + var daily = null; + var factorStatus = "unavailable"; + var i; + + for (i = 0; i < series.length; i += 1) { + if (String(series[i].type || "").toLowerCase().indexOf("day") >= 0 || String(series[i].type || "").toLowerCase().indexOf("daily") >= 0) { + daily = series[i]; + break; + } + } + + if (!daily && series.length > 1) { + daily = series[series.length - 1]; + } + + for (i = 0; i < factors.length; i += 1) { + var name = String(factors[i].name || ""); + if (name.indexOf("NarrowRange") === 0 || name.indexOf("OrbRangeVsAtr") === 0) { + if (String(factors[i].status || "").toUpperCase() !== "SATISFIED") { + factorStatus = "still warming up"; + break; + } + factorStatus = factorStatus === "unavailable" ? "SATISFIED" : factorStatus; + } + } + + if (!primary && !daily && !factors.length) { + return "Readiness summary unavailable until data loads."; + } + + return "Primary series: " + display(primary ? primary.historical_bars_loaded : null) + " bars loaded (" + display(primary ? primary.days_to_load : null) + "d configured). Daily context: " + display(daily ? daily.historical_bars_loaded : null) + " bars โ€” narrow-range and ORB-vs-ATR factors are " + factorStatus + "."; + } + + function renderDataSeries(series) { + var node = byId("data-series"); + clear(node); + if (!series.length) { + node.innerHTML = '
No data series readiness data available.
'; + return; + } + series.forEach(function (item) { + var chip = document.createElement("div"); + chip.className = "readiness-chip info"; + chip.innerHTML = "Series[" + h(item.index) + "] " + h(item.type) + "DaysToLoad " + h(item.days_to_load) + " ยท HistoricalBarsLoaded " + h(item.historical_bars_loaded) + ""; + node.appendChild(chip); + }); + } + + function renderWarmups(factors) { + var node = byId("warmup-factors"); + clear(node); + if (!factors.length) { + node.innerHTML = '
No factor warm-up data available.
'; + return; + } + factors.forEach(function (factor) { + var status = String(factor.status || "").toUpperCase(); + var kind = status === "SATISFIED" ? "good" : (status === "FAILED" ? "bad" : "warn"); + var chip = document.createElement("div"); + chip.className = "readiness-chip " + kind; + chip.innerHTML = "" + h(factor.name) + "" + h(factor.status) + " ยท " + h(factor.loaded) + "/" + h(factor.required) + " daily bars"; + node.appendChild(chip); + }); + } + + function renderTable(id, headers, rows) { + var table = byId(id); + var thead = document.createElement("thead"); + var tbody = document.createElement("tbody"); + var tr = document.createElement("tr"); + clear(table); + headers.forEach(function (header) { + var th = document.createElement("th"); + th.textContent = header; + tr.appendChild(th); + }); + thead.appendChild(tr); + table.appendChild(thead); + if (!rows.length) { + tbody.appendChild(emptyTemplate.content.cloneNode(true)); + } else { + rows.forEach(function (cells) { + var row = document.createElement("tr"); + cells.forEach(function (cell) { + var td = document.createElement("td"); + if (cell && cell.html) { + td.innerHTML = cell.html; + } else { + td.textContent = display(cell); + } + row.appendChild(td); + }); + tbody.appendChild(row); + }); + } + table.appendChild(tbody); + } + + function renderTrades(payload) { + var rows = asArray(payload.trades).map(function (trade) { + var side = String(trade.side || "").toLowerCase(); + var grade = display(trade.confluence_grade); + return [ + trade.trade_seq, + trade.timestamp_utc, + { html: '' + h(trade.side) + '' }, + { html: '' + h(grade) + '' }, + trade.confluence_score, + trade.resolved_runner_mode, + display(trade.stop_ticks) + " / " + display(trade.target_ticks), + trade.session_tag + ]; + }); + renderTable("trade-table", ["Seq", "Timestamp UTC", "Side", "Grade", "Score", "Runner Mode", "Stop / Target", "Session Tag"], rows); + } + + function renderRiskAndRejects(payload) { + var totals = payload.session_reject_totals || {}; + var rejectNode = byId("reject-totals"); + var reasons = Object.keys(totals).sort(function (a, b) { return String(a).localeCompare(String(b)); }); + clear(rejectNode); + if (!reasons.length) { + rejectNode.innerHTML = '
No full-session rejection totals found yet.
'; + } else { + reasons.forEach(function (reason) { + var row = document.createElement("div"); + row.className = "field-row"; + row.innerHTML = '' + h(reason) + '' + h(totals[reason]) + ''; + rejectNode.appendChild(row); + }); + } + + setText("missed-bplus-count", display(payload.missed_grade_b_plus_count || 0)); + renderMissedBPlusSamples(payload); + } + + function renderMissedBPlusSamples(payload) { + var node = byId("missed-bplus-samples"); + var samples = asArray(payload.missed_grade_b_plus_samples); + clear(node); + if (!samples.length) { + node.innerHTML = '
No approximate missed B+ samples found.
'; + return; + } + var list = document.createElement("div"); + list.className = "section-stack"; + samples.slice(-5).forEach(function (sample) { + var item = document.createElement("div"); + item.className = "readiness-chip warn"; + item.innerHTML = '' + h(sample.timestamp) + ' Grade ' + h(sample.grade) + ' ยท Score ' + h(Number(sample.score || 0).toFixed(3)) + 'Blocked by ' + h(sample.blocking_reason) + ''; + list.appendChild(item); + }); + node.appendChild(list); + } + + function renderSignalOutcomes(payload) { + var summaryRows = asArray(payload.signal_grade_summary).map(function (item) { + var reasons = item.reject_reasons || {}; + var reasonText = Object.keys(reasons).sort().map(function (reason) { return reason + "=" + reasons[reason]; }).join(", "); + return [ + { html: '' + h(item.grade) + '' }, + item.generated, + item.filled, + item.rejected, + reasonText || "-" + ]; + }); + renderTable("signal-grade-table", ["Grade", "Generated", "Filled", "Rejected", "Reject Reasons"], summaryRows); + + var outcomeRows = asArray(payload.signal_outcomes).map(function (item) { + return [ + item.time, + item.side, + { html: '' + h(item.grade) + '' }, + item.score === null || item.score === undefined ? "-" : Number(item.score).toFixed(3), + item.filled ? "Yes" : "No", + item.reject_reason || "-", + item.reject_detail || "" + ]; + }); + renderTable("signal-outcome-table", ["Time", "Side", "Grade", "Score", "Filled", "Reject", "Detail"], outcomeRows); + } + + function renderGrades(payload) { + var counts = { A: 0, B: 0, C: 0, D: 0, F: 0 }; + asArray(payload.trades).forEach(function (trade) { + var grade = String(trade.confluence_grade || "").toUpperCase().charAt(0); + if (Object.prototype.hasOwnProperty.call(counts, grade)) { + counts[grade] += 1; + } + }); + var grid = byId("grade-grid"); + clear(grid); + GRADES.forEach(function (grade) { + var cell = document.createElement("div"); + cell.className = "grade-cell " + gradeClass(grade); + cell.innerHTML = "Grade " + h(grade) + "" + counts[grade] + "trade count"; + grid.appendChild(cell); + }); + } + + function renderPnlCurve(payload) { + var points = asArray(payload.events).filter(function (event) { return event.type === "PNL_UPDATE"; }); + var node = byId("pnl-chart"); + clear(node); + if (points.length < 2) { + node.innerHTML = '
Fewer than 2 PNL_UPDATE events available. Intraday curve unavailable.
'; + return; + } + var values = points.map(function (point) { return numberValue(point.daily_pnl); }); + var min = Math.min.apply(Math, values); + var max = Math.max.apply(Math, values); + var span = max - min || 1; + var width = 900; + var height = 240; + var coords = values.map(function (value, index) { + var x = points.length === 1 ? 0 : (index / (points.length - 1)) * width; + var y = height - ((value - min) / span) * height; + return x.toFixed(1) + "," + y.toFixed(1); + }).join(" "); + var zeroY = clamp(height - ((0 - min) / span) * height, 0, height); + node.innerHTML = '
' + h(points[0].timestamp) + '' + h(money(min) + ' to ' + money(max)) + '' + h(points[points.length - 1].timestamp) + '
'; + } + + function renderFactors(payload) { + var node = byId("factor-bars"); + var picked = pickFactors(payload); + var map = factorMap(picked.factors); + var reasons = ((payload.live_state || {}).state_telemetry_reasons) || {}; + clear(node); + setHtml("factor-source", picked.factors.length ? '' + h(picked.source) + ' ' + h("Showing factors from " + picked.label + ".") : h(picked.label)); + FACTORS.forEach(function (name) { + var factor = map[name]; + var reason = reasons[name]; + var score = factor ? clamp(factor.score, 0, 1) : 0; + var row = document.createElement("div"); + row.className = "factor-row"; + if (reason) { + row.title = reason; + } + row.innerHTML = '
' + h(name) + '' + (factor ? h(factor.score.toFixed(3)) : "unavailable") + '
' + + (reason ? '
' + h(reason) + '
' : ''); + node.appendChild(row); + }); + } + + function renderSummary(payload) { + var live = payload.live_state || {}; + var row = latestRow(payload); + var settings = payload.settings || {}; + var dailyPnl = numberValue(live.daily_pnl); + var dailyLossLimit = numberValue(settings.DailyLossLimit); + var used = dailyLossLimit > 0 ? clamp(Math.abs(Math.min(0, dailyPnl)) / dailyLossLimit * 100, 0, 100) : null; + setText("summary-symbol", display(live.symbol || settings.Instrument || "NQ")); + setText("summary-pnl", money(live.daily_pnl)); + setText("summary-trades", String(asArray(payload.trades).length)); + setText("summary-position", display(live.position)); + setText("row-net-pnl", money(row.net_pnl)); + setText("row-submits", display(row.submits)); + setText("row-fills", display(row.fills)); + setText("loss-used-label", used === null ? "DailyLossLimit unavailable" : used.toFixed(1) + "%"); + byId("loss-used-fill").style.width = (used === null ? 0 : used) + "%"; + } + + function renderRaw(payload) { + var lines = asArray(payload.raw_tail); + var node = byId("raw-log"); + clear(node); + if (!lines.length) { + node.textContent = "No live log data loaded."; + return; + } + lines.forEach(function (line) { + var item = document.createElement("span"); + item.className = "raw-log-line " + classifyLogLine(line); + item.textContent = display(line); + node.appendChild(item); + }); + } + + function classifyLogLine(line) { + var value = String(line || "").toUpperCase(); + if (value.indexOf("CONNECTION LOST") >= 0) { + return "raw-log-connection-lost"; + } + if (value.indexOf("CONNECTION RESTORED") >= 0) { + return "raw-log-connection-restored"; + } + if (value.indexOf("SESSION START") >= 0 || value.indexOf("SESSION END") >= 0) { + return "raw-log-session"; + } + if (value.indexOf("REJECT SUMMARY") >= 0) { + return "raw-log-reject-summary"; + } + if (value.indexOf("REJECT") >= 0) { + return "raw-log-reject"; + } + if (value.indexOf("SIGNAL") >= 0) { + return "raw-log-signal"; + } + if (value.indexOf("SUBMIT") >= 0) { + return "raw-log-submit"; + } + if (value.indexOf("FILL") >= 0) { + return "raw-log-fill"; + } + if (value.indexOf("STATE") >= 0) { + return "raw-log-state"; + } + if (value.indexOf("WARNING") >= 0) { + return "raw-log-warning"; + } + return ""; + } + + function render(payload) { + latestPayload = payload; + byId("server-message").className = "telemetry-note"; + setText("server-message", "Live server connected. Values are sourced from /api/state."); + renderHeader(payload); + renderStatus(payload); + renderReadiness(payload); + renderRiskAndRejects(payload); + renderSignalOutcomes(payload); + renderTrades(payload); + renderGrades(payload); + renderPnlCurve(payload); + renderFactors(payload); + renderSummary(payload); + renderRaw(payload); + } + + function renderUnavailable(message) { + if (!latestPayload) { + render({ live_state: {}, readiness: {}, rows: [], diagnostics: [], events: [], trades: [], settings: {}, raw_tail: [] }); + } + byId("server-message").className = "telemetry-note unavailable"; + setText("server-message", message || "Live server unavailable. Open through tools/dashboard/server.py for live data."); + } + + function loadServerState() { + fetch("/api/state", { cache: "no-store" }).then(function (response) { + if (!response.ok) { + throw new Error("HTTP " + response.status); + } + return response.json(); + }).then(function (payload) { + render(payload || {}); + }).catch(function () { + renderUnavailable("Live server unavailable. Open through tools/dashboard/server.py for live data."); + }); + } + + renderClock(); + renderUnavailable("Live server unavailable. Open through tools/dashboard/server.py for live data."); + loadServerState(); + setInterval(renderClock, 1000); + setInterval(loadServerState, POLL_MS); +}()); diff --git a/tools/dashboard/index.html b/tools/dashboard/index.html index e23cdde..b92db09 100644 --- a/tools/dashboard/index.html +++ b/tools/dashboard/index.html @@ -17,6 +17,7 @@ Mode Static HTML + vanilla JS No NT8 references. No writes. + Trading Console diff --git a/tools/dashboard/parsers.py b/tools/dashboard/parsers.py index 448c3b0..edfef0d 100644 --- a/tools/dashboard/parsers.py +++ b/tools/dashboard/parsers.py @@ -18,6 +18,11 @@ LOG_TS_RE = re.compile(r"^\[(\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?)\]\s*(.*)$") SESSION_START_RE = re.compile(r"=== SESSION START\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+===", re.IGNORECASE) SUBMIT_RE = re.compile(r"\bSUBMIT\b\s*(.*)$", re.IGNORECASE) FILL_RE = re.compile(r"\bFILL\b\s+(Long|Short)\s+(\d+)\s+@\s+([0-9.]+)", re.IGNORECASE) +SIGNAL_RE = re.compile(r"\bSIGNAL:?\s+(Buy|Sell|Long|Short)\b(?:\s+([^|]+?))?(?:\s*\|\s*(.*))?$", re.IGNORECASE) +SIGNAL_GRADE_RE = re.compile(r"\bGrade=([^\s|]+)", re.IGNORECASE) +SIGNAL_SCORE_RE = re.compile(r"\bScore=([0-9.]+)", re.IGNORECASE) +REJECT_RE = re.compile(r"\bREJECT:\s*(.*)$", re.IGNORECASE) +REJECT_SUMMARY_RE = re.compile(r"\bREJECT SUMMARY:\s*(.*)$", re.IGNORECASE) BREAKEVEN_RE = re.compile(r"\bBREAKEVEN\b\s*(.*)$", re.IGNORECASE) RUNNER_CLOSED_RE = re.compile(r"RUNNER closed", re.IGNORECASE) CONNECTION_RE = re.compile(r"CONNECTION\s+(LOST|RESTORED)", re.IGNORECASE) @@ -29,6 +34,133 @@ MODE_RE = re.compile(r"^Mode\s*:\s*(.+)$", re.IGNORECASE) DATA_SERIES_RE = re.compile(r"DataSeries\[(\d+)\]\s*:\s*Type=([^\s]+)\s+DaysToLoad=([^\s]+)\s+HistoricalBarsLoaded=([^\s]+)", re.IGNORECASE) FACTOR_WARMUP_RE = re.compile(r"FactorWarmup\s*:\s*(.*)$", re.IGNORECASE) FACTOR_STATUS_RE = re.compile(r"([A-Za-z0-9_]+)=(SATISFIED|FAILED|UNSATISFIED)\s*\((\d+)/(\d+)\s+daily bars\)", re.IGNORECASE) +STATE_RE = re.compile( + r"STATE:\s*Regime=(\S+)\s+Direction=(\S+)\s+DirectionSource=(\S+)\s+Score=([0-9.]+)\s+Grade=(\S+)\s+Factors=(.*)$", + re.IGNORECASE, +) +STATE_FACTOR_ENTRY_RE = re.compile(r"^([^=]+)=([0-9.]+)(?:x([0-9.]+))?$") +STATE_DETAIL_RE = re.compile(r"\bSTATE_DETAIL:\s*(.*)$", re.IGNORECASE) +SIGNAL_DETAIL_RE = re.compile(r"\bSIGNAL_DETAIL:\s*(.*)$", re.IGNORECASE) +QUOTED_KV_RE = re.compile(r'(\w+)="((?:[^"\\]|\\.)*)"') +SUBMIT_FIELD_RE = re.compile( + r"\b(Scaler|Runner|Stop|Target|Mode|BaseTarget|DynamicTarget|GradeMult|ModeMult|CombinedMult)=(\S+)", + re.IGNORECASE, +) +SUBMIT_NUMERIC_FIELDS = ("BaseTarget", "DynamicTarget", "GradeMult", "ModeMult", "CombinedMult") +STATE_CONTEXT_RE = re.compile(r"\bSTATE_CONTEXT:\s*(.*)$", re.IGNORECASE) +STATE_CONTEXT_FIELD_RE = re.compile(r"(\w+)=(\S+)") +REJECT_KV_RE = re.compile(r"\b(reason|detail|bar|count)=", re.IGNORECASE) +BLOCKING_REJECT_REASONS = set(["RthGuard", "MaxDailyTrades", "KillSwitch", "CmeHoliday"]) + + +def parse_key_values(text: str) -> Dict[str, str]: + """Parses marker-bounded key=value text for REJECT lines. + + Values such as detail=... may contain spaces or additional '=' tokens, so + this uses known key markers as boundaries rather than splitting on spaces. + """ + result: Dict[str, str] = {} + matches = list(REJECT_KV_RE.finditer(text or "")) + for index, match in enumerate(matches): + key = match.group(1) + value_start = match.end() + value_end = matches[index + 1].start() if index + 1 < len(matches) else len(text or "") + result[key] = (text or "")[value_start:value_end].strip() + return result + + +def grade_rank(grade: Any) -> int: + text = str(grade or "").upper().strip() + if text == "A+": + return 6 + if text == "A": + return 5 + if text == "B": + return 4 + if text == "C": + return 3 + if text == "D": + return 2 + if text == "F": + return 1 + return 0 + + +def is_grade_b_or_better(grade: Any) -> bool: + return grade_rank(grade) >= grade_rank("B") + + +def parse_state_context_fields(text: str) -> Dict[str, str]: + """Parses STATE_CONTEXT: unquoted Key=Value tokens (DEC-20260818-02/03). + + Unlike STATE_DETAIL:/SIGNAL_DETAIL:, these values are plain tokens + (numbers, HH:mm times, booleans) with no internal spaces or quoting, so + a simple space/= split is sufficient. The field set is deliberately + generic โ€” GetStateTelemetryContextFields() is an extension point any + strategy can override with its own keys (e.g. SimpleORBNT8's OrbHigh/ + OrbLow/OrbWindowStart/OrbWindowEnd/OrbReady), plus the universal + RecommendedContracts field NT8StrategyBase always appends when present. + """ + fields: Dict[str, str] = {} + for key, value in STATE_CONTEXT_FIELD_RE.findall(text or ""): + fields[key] = value + return fields + + +def parse_quoted_reasons(text: str) -> Dict[str, str]: + """Parses STATE_DETAIL:/SIGNAL_DETAIL: quoted key="value" pairs (DEC-20260817-09). + + Reverses NT8StrategyBase.cs's EscapeLogValue() (\\ -> \\\\, " -> \\") with a + single backslash-escaped-char substitution, which correctly handles both + escape sequences in one pass since the original escaping only ever emits + a backslash followed by exactly one of those two characters. + """ + result: Dict[str, str] = {} + for key, raw_value in QUOTED_KV_RE.findall(text or ""): + result[key] = re.sub(r"\\(.)", r"\1", raw_value) + return result + + +def parse_submit_fields(detail: str) -> Dict[str, Any]: + """Parses SUBMIT line fields, including the DEC-20260817-09 sizing-rationale + fields appended after Mode=. Numeric fields are coerced to float where + parseable; GetMetadataText() emits "N/A" for missing intent.Metadata keys, + which is left as a string so the dashboard can render it distinctly from 0. + """ + fields: Dict[str, Any] = {} + for key, value in SUBMIT_FIELD_RE.findall(detail or ""): + if key in SUBMIT_NUMERIC_FIELDS and value != "N/A": + try: + fields[key] = float(value) + continue + except ValueError: + pass + fields[key] = value + return fields + + +def parse_state_factors(text: str) -> List[Dict[str, Any]]: + """Parses the DASH-002 STATE: line's Factors=name=scorexweight;... segment. + + Same convention as the GradeFilter reject-detail factor breakdown + (app.js's parseFactors()), reused here for consistency rather than + inventing a second format. + """ + factors: List[Dict[str, Any]] = [] + if not text: + return factors + for part in text.split(";"): + part = part.strip() + if not part: + continue + match = STATE_FACTOR_ENTRY_RE.match(part) + if match: + factors.append({ + "name": match.group(1), + "score": float(match.group(2)), + "weight": float(match.group(3)) if match.group(3) else 1.0, + }) + return factors def expand_path(raw_path: str) -> Path: @@ -113,6 +245,43 @@ def parse_money(value: str) -> float: return 0.0 +def parse_state_telemetry_detail(detail: str) -> Dict[str, Any]: + result: Dict[str, Any] = {"detail": detail} + factors_match = re.search(r"Factors=([^\n]+)$", detail or "", re.IGNORECASE) + if factors_match: + result["factors"] = parse_factor_breakdown(factors_match.group(1)) + detail = detail[:factors_match.start()].strip() + for match in re.finditer(r"(Regime|Direction|DirectionSource|Score|Grade)=([^\s]+)", detail or "", re.IGNORECASE): + key = match.group(1).lower() + value = match.group(2) + if key == "score": + try: + result[key] = float(value) + except ValueError: + result[key] = value + else: + result[key] = value + return result + + +def parse_factor_breakdown(text: str) -> List[Dict[str, Any]]: + factors: List[Dict[str, Any]] = [] + for part in (text or "").split(";"): + match = re.match(r"^([^=]+)=([0-9.]+)(?:x([0-9.]+))?$", part.strip(), re.IGNORECASE) + if match is None: + continue + try: + score = float(match.group(2)) + except ValueError: + score = 0.0 + try: + weight = float(match.group(3)) if match.group(3) else 1.0 + except ValueError: + weight = 1.0 + factors.append({"name": match.group(1), "score": score, "weight": weight}) + return factors + + def parse_session_event(path: Path, line: str) -> Optional[Dict[str, Any]]: timestamp, message = split_log_line(line) base: Dict[str, Any] = {"timestamp": timestamp, "line": line, "source": str(path)} @@ -123,10 +292,43 @@ def parse_session_event(path: Path, line: str) -> Optional[Dict[str, Any]]: payload.update({"type": "SESSION START", "session_start": start.group(1)}) return payload + state = STATE_RE.search(message) + if state: + payload = dict(base) + payload.update({ + "type": "STATE", + "regime": state.group(1), + "direction": state.group(2), + "direction_source": state.group(3), + "score": float(state.group(4)), + "grade": state.group(5), + "factors": parse_state_factors(state.group(6)), + }) + return payload + submit = SUBMIT_RE.search(message) if submit: payload = dict(base) - payload.update({"type": "SUBMIT", "detail": submit.group(1).strip()}) + detail_text = submit.group(1).strip() + payload.update({"type": "SUBMIT", "detail": detail_text, "fields": parse_submit_fields(detail_text)}) + return payload + + state_detail = STATE_DETAIL_RE.search(message) + if state_detail: + payload = dict(base) + payload.update({"type": "STATE_DETAIL", "reasons": parse_quoted_reasons(state_detail.group(1))}) + return payload + + signal_detail = SIGNAL_DETAIL_RE.search(message) + if signal_detail: + payload = dict(base) + payload.update({"type": "SIGNAL_DETAIL", "reasons": parse_quoted_reasons(signal_detail.group(1))}) + return payload + + state_context = STATE_CONTEXT_RE.search(message) + if state_context: + payload = dict(base) + payload.update({"type": "STATE_CONTEXT", "fields": parse_state_context_fields(state_context.group(1))}) return payload fill = FILL_RE.search(message) @@ -185,6 +387,160 @@ def parse_session_event(path: Path, line: str) -> Optional[Dict[str, Any]]: return None +def parse_signal_line(message: str, timestamp: Optional[str], source_line: str, latest_state: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: + signal = SIGNAL_RE.search(message or "") + if signal is None: + return None + + side = signal.group(1) + detail = signal.group(3) or "" + grade_match = SIGNAL_GRADE_RE.search(message or "") + score_match = SIGNAL_SCORE_RE.search(message or "") + grade = grade_match.group(1) if grade_match else None + score: Optional[float] = None + if score_match: + try: + score = float(score_match.group(1)) + except ValueError: + score = None + + if latest_state is not None: + if grade is None: + grade = latest_state.get("grade") + if score is None and latest_state.get("score") is not None: + score = latest_state.get("score") + + return { + "time": timestamp, + "side": side, + "grade": grade or "Unknown", + "score": score, + "filled": False, + "reject_reason": None, + "reject_detail": "", + "line": source_line, + } + + +def parse_full_session_kpis(path: Optional[Path]) -> Dict[str, Any]: + """Parses full-session dashboard KPIs from a session_*.log file. + + This is intentionally read-only observability. It never writes to NT8, never + touches strategy state, and cannot affect live trading behavior. + """ + empty = { + "session_reject_totals": {}, + "signal_outcomes": [], + "signal_grade_summary": [], + "missed_grade_b_plus_count": 0, + "missed_grade_b_plus_samples": [], + } + if path is None or not path.exists(): + return empty + + try: + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + return empty + + reject_summary_final: Dict[str, int] = {} + reject_record_counts: Dict[str, int] = {} + signal_outcomes: List[Dict[str, Any]] = [] + latest_state: Optional[Dict[str, Any]] = None + current_signal: Optional[Dict[str, Any]] = None + active_blocking_reason: Optional[str] = None + missed_samples: List[Dict[str, Any]] = [] + missed_count = 0 + + for line in lines: + timestamp, message = split_log_line(line) + + state = STATE_RE.search(message) + if state: + latest_state = { + "timestamp": timestamp, + "regime": state.group(1), + "direction": state.group(2), + "direction_source": state.group(3), + "score": float(state.group(4)), + "grade": state.group(5), + } + if active_blocking_reason and is_grade_b_or_better(latest_state.get("grade")): + missed_count += 1 + missed_samples.append({ + "timestamp": timestamp, + "grade": latest_state.get("grade"), + "score": latest_state.get("score"), + "blocking_reason": active_blocking_reason, + }) + missed_samples = missed_samples[-20:] + continue + + reject_summary = REJECT_SUMMARY_RE.search(message) + if reject_summary: + parts = parse_key_values(reject_summary.group(1)) + reason = parts.get("reason") + if reason: + try: + reject_summary_final[reason] = int(parts.get("count", "0")) + except ValueError: + reject_summary_final[reason] = 0 + continue + + reject = REJECT_RE.search(message) + if reject: + parts = parse_key_values(reject.group(1)) + reason = parts.get("reason") + if reason: + reject_record_counts[reason] = reject_record_counts.get(reason, 0) + 1 + if reason in BLOCKING_REJECT_REASONS: + active_blocking_reason = reason + if current_signal is not None and not current_signal.get("filled") and not current_signal.get("reject_reason"): + current_signal["reject_reason"] = reason + current_signal["reject_detail"] = parts.get("detail", "") + continue + + parsed_signal = parse_signal_line(message, timestamp, line, latest_state) + if parsed_signal is not None: + signal_outcomes.append(parsed_signal) + current_signal = parsed_signal + continue + + if FILL_RE.search(message): + if current_signal is not None and not current_signal.get("filled"): + current_signal["filled"] = True + continue + + totals = dict(reject_summary_final) + for reason, count in reject_record_counts.items(): + if reason not in totals: + totals[reason] = count + + grade_summary: Dict[str, Dict[str, Any]] = {} + for outcome in signal_outcomes: + grade = str(outcome.get("grade") or "Unknown") + if grade not in grade_summary: + grade_summary[grade] = {"grade": grade, "generated": 0, "filled": 0, "rejected": 0, "reject_reasons": {}} + summary = grade_summary[grade] + summary["generated"] += 1 + if outcome.get("filled"): + summary["filled"] += 1 + if outcome.get("reject_reason"): + summary["rejected"] += 1 + reason = str(outcome.get("reject_reason")) + summary["reject_reasons"][reason] = summary["reject_reasons"].get(reason, 0) + 1 + + sorted_grade_summary = sorted(grade_summary.values(), key=lambda item: (-grade_rank(item.get("grade")), str(item.get("grade")))) + + return { + "session_reject_totals": {reason: totals[reason] for reason in sorted(totals.keys(), key=str.lower)}, + "signal_outcomes": signal_outcomes, + "signal_grade_summary": sorted_grade_summary, + "missed_grade_b_plus_count": missed_count, + "missed_grade_b_plus_samples": missed_samples, + } + + def parse_readiness(lines: List[str]) -> Dict[str, Any]: data_series: Dict[int, Dict[str, Any]] = {} factors: Dict[str, Dict[str, Any]] = {} diff --git a/tools/dashboard/server.py b/tools/dashboard/server.py index 2eb60e7..014db8d 100644 --- a/tools/dashboard/server.py +++ b/tools/dashboard/server.py @@ -81,6 +81,11 @@ class DashboardRuntime: self.readiness: Dict[str, Any] = {} self.rows: List[Dict[str, Any]] = [] self.diagnostics: List[Dict[str, Any]] = [] + self.session_reject_totals: Dict[str, int] = {} + self.signal_outcomes: List[Dict[str, Any]] = [] + self.signal_grade_summary: List[Dict[str, Any]] = [] + self.missed_grade_b_plus_count = 0 + self.missed_grade_b_plus_samples: List[Dict[str, Any]] = [] self.current_session_file: Optional[str] = None self.current_session_date: Optional[str] = None self.polling = config.get("polling", {}) if isinstance(config.get("polling", {}), dict) else {} @@ -108,6 +113,11 @@ class DashboardRuntime: "readiness": dict(self.readiness), "rows": list(self.rows), "diagnostics": list(self.diagnostics), + "session_reject_totals": dict(self.session_reject_totals), + "signal_outcomes": list(self.signal_outcomes), + "signal_grade_summary": list(self.signal_grade_summary), + "missed_grade_b_plus_count": self.missed_grade_b_plus_count, + "missed_grade_b_plus_samples": list(self.missed_grade_b_plus_samples), "events": list(self.latest_events[-100:]), "trades": list(self.trades), "provenance": self.provenance, @@ -145,7 +155,8 @@ class DashboardRuntime: self.current_session_date = session_date self.readiness = parsers.parse_readiness(raw_tail) self._refresh_live_state_from_tail(path, raw_tail) - self.rows, self.diagnostics = self._build_current_rows(path, raw_tail) + self.rows, self.diagnostics = self._build_current_rows(path) + self._refresh_session_kpis(path) offset = self.state.get_offset(path) if offset is None: try: @@ -170,6 +181,14 @@ class DashboardRuntime: if event is not None: self._apply_event(event) + def _refresh_session_kpis(self, path: Path) -> None: + kpis = parsers.parse_full_session_kpis(path) + self.session_reject_totals = kpis.get("session_reject_totals", {}) + self.signal_outcomes = kpis.get("signal_outcomes", []) + self.signal_grade_summary = kpis.get("signal_grade_summary", []) + self.missed_grade_b_plus_count = int(kpis.get("missed_grade_b_plus_count") or 0) + self.missed_grade_b_plus_samples = kpis.get("missed_grade_b_plus_samples", []) + def _poll_trades(self) -> None: date_key = self.current_session_date or time.strftime("%Y%m%d") path = parsers.trades_file_for_date(self.log_dir, date_key) @@ -183,7 +202,7 @@ class DashboardRuntime: return name[8:16] return time.strftime("%Y%m%d") - def _build_current_rows(self, path: Path, lines: List[str]) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + def _build_current_rows(self, path: Path) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: if logtriage is None: return [], [] try: @@ -195,10 +214,6 @@ class DashboardRuntime: rows = logtriage.build_rows([session], settings_by_date, provenance_by_date, trades_by_session) diagnostics = logtriage.build_diagnostics(rows, settings_by_date, provenance_by_date, trade_defects) row_dicts = [row.to_dict() for row in rows] - if row_dicts: - reject_summaries, reject_records = self._parse_rejections(lines, session.date) - row_dicts[0]["reject_summaries"] = reject_summaries - row_dicts[0]["reject_records"] = reject_records return row_dicts, diagnostics except Exception as ex: return [], [{"date": time.strftime("%Y-%m-%d"), "code": "LIVE ROW BUILD FAILED", "message": str(ex)}] @@ -229,36 +244,6 @@ class DashboardRuntime: snapshots.append(snapshot) return {date: snapshots} if snapshots else {} - def _parse_rejections(self, lines: List[str], date: str) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: - summaries: List[Dict[str, Any]] = [] - records: List[Dict[str, Any]] = [] - for line in lines: - timestamp, message = parsers.split_log_line(line) - if message.startswith("REJECT SUMMARY:"): - parts = self._parse_key_values(message.replace("REJECT SUMMARY:", "", 1)) - summaries.append({"date": date, "reason": parts.get("reason"), "count": int(parts.get("count", "0") or 0), "line": line}) - elif message.startswith("REJECT:"): - parts = self._parse_key_values(message.replace("REJECT:", "", 1)) - records.append({"date": date, "reason": parts.get("reason"), "detail": parts.get("detail"), "bar": parts.get("bar"), "line": line}) - return summaries, records - - def _parse_key_values(self, text: str) -> Dict[str, str]: - values: Dict[str, str] = {} - keys = ["reason", "detail", "bar", "count"] - for index, key in enumerate(keys): - marker = key + "=" - start = text.find(marker) - if start < 0: - continue - value_start = start + len(marker) - value_end = len(text) - for later_key in keys[index + 1:]: - later = text.find(" " + later_key + "=", value_start) - if later >= 0: - value_end = min(value_end, later) - values[key] = text[value_start:value_end].strip() - return values - def _poll_provenance(self) -> None: provenance_path = parsers.latest_provenance_file(self.log_dir) settings_path = parsers.latest_settings_file(self.log_dir) @@ -285,6 +270,14 @@ class DashboardRuntime: session_key = str(event.get("session_start") or event.get("source") or "unknown") self.state.rollover_session(session_key) self.live_state["session_start"] = event.get("session_start") + elif event_type == "STATE": + self.live_state["state_telemetry"] = event + elif event_type == "STATE_DETAIL": + self.live_state["state_telemetry_reasons"] = event.get("reasons", {}) + elif event_type == "SIGNAL_DETAIL": + self.live_state["last_signal_reasons"] = event.get("reasons", {}) + elif event_type == "STATE_CONTEXT": + self.live_state["state_context"] = event.get("fields", {}) elif event_type == "ACCOUNT": self.live_state["account"] = event.get("account") elif event_type == "SYMBOL": diff --git a/tools/logtriage/README.md b/tools/logtriage/README.md index 291bddd..4f25345 100644 --- a/tools/logtriage/README.md +++ b/tools/logtriage/README.md @@ -28,6 +28,18 @@ Text mode prints: `--json` emits machine-readable output for dashboard ingestion, including session rows, diagnostics, and per-trade records enriched with source file and line metadata. +### REJECT / REJECT SUMMARY parsing + +Each session row now also includes: + +- `reject_summaries`: every `REJECT SUMMARY: reason= count=` line encountered, in file order, as `{date, reason, count, line}`. Because GAP-035 writes these as periodic cumulative snapshots (first live rejection at/after 10:00 ET, then every 15 bar-minutes, plus a final snapshot at session end), this is a history of counts over the session, not a single tally. +- `reject_records`: every `REJECT: reason= detail= bar=