[GOV]: sync governance to v9.0 + 2026-10-24 findings; stage GAP-077/067 prompts
Some checks failed
CI Build & Test / Build & Test (Windows) (push) Has been cancelled
CI Build & Test / Build & Test (Linux/mono) (push) Has been cancelled

This commit is contained in:
2026-10-26 08:12:20 -04:00
parent bf7acbb94a
commit 5907e9cc54
16 changed files with 4728 additions and 22 deletions

View File

@@ -0,0 +1,144 @@
# TASK: GAP-077 — Strategy Analyzer backtests take zero trades: live catch-up guard blocks every historical intent
# Staged: 2026-10-24 — DEC-20261024-01
# Sprint: Stage 0 — restore trust in the artifact
# Owner: Kilocode
# Deploy: COMMIT ONLY — do NOT run deploy-to-nt8.bat. The operator deploys once, after P0-A
# (orphan sweep) and the other Stage 0 commits have landed. See NEXT_PROMPT.md.
# Constraints: C# 5.0 / .NET Framework 4.8 — no string interpolation, no `?.`, no `=>` bodies,
# no async/await, no pattern matching. NT8 API must be verified against
# https://developer.ninjatrader.com/docs/desktop — do not infer signatures.
## THE DEFECT (evidence, not hypothesis)
`session_20261019_155354.log` — a Strategy Analyzer backtest, MNQ, Jan–Oct 2026:
```
Mode : LIVE/SIM <- wrong; this is a backtest
Account : Backtest <- Account is NOT null in Strategy Analyzer
REJECT: reason=HistoricalReplayCatchup detail=Blocked catch-up replay order Time=2026-01-02 10:14:00
REJECT SUMMARY: reason=HistoricalReplayCatchup count=117
```
117 intents generated, 117 blocked, zero `SUBMIT`, zero `FILL`. 15,594 of the log's 15,613 lines are
repeated `REJECT SUMMARY` lines.
Cause — `NT8StrategyBase.ProcessStrategyIntent()` (~`:2069` deployed):
```csharp
if (State == State.Historical && Account != null) // intended: live catch-up replay only
```
`DEC-20260818-08` assumed `Account == null` during genuine Strategy Analyzer runs. That is false —
Strategy Analyzer assigns the `Backtest` account. Every backtest since 2026-08-18 has therefore
blocked every intent. `DEC-20260818-08`'s own Action Required ("run a Strategy Analyzer backtest …
confirm trade count and P&L are unchanged") was never executed.
## SAME FALSE ASSUMPTION ELSEWHERE — ALL IN SCOPE
1. **`ShouldAllowDailyTradeCountIncrement()`** (~`:2000`): in `State.Historical` returns
`Account == null` → always `false` in a backtest. Fixing only the entry guard would let backtests
take **unlimited trades per day**, silently diverging from live `MaxDailyTrades` rules. Must be
fixed in the same commit.
2. **Daily-trade-count persistence wiring** (~`:595`, `if (_sdkStrategy != null && Account != null)`):
confirm which `State` branch this runs in. A backtest must never read or write
`daily_trade_count_Backtest_*.json`. If it can, gate it on the new predicate.
3. **`TrailingDrawdownMonitor` registration** (~`:1797`, `InitializeTrailingDrawdownState` ~`:1834`):
a backtest registers an account literally named `Backtest` with the singleton monitor. Gate on the
new predicate unless reading shows it is provably inert.
4. **Session header `Mode` label** (`WriteSessionHeader`, ~`:1620`): computed from
`State == State.Historical`, but the header is written from `State.DataLoaded`, so it always reads
`LIVE/SIM`. Use the new predicate.
5. **`LogRejectRateLimited()`** (~`:1528`): drops every non-Realtime reason except
`HistoricalReplayCatchup`, so a backtest can never record `GradeFilter`, `OrbRangeNotEstablished`,
`RegimeVeto`, `MaxDailyTrades` etc. In a backtest, **count** all reasons (so `REJECT SUMMARY` is
meaningful) and write each reason's first `REJECT:` detail line once. Live/SIM historical
catch-up behaviour must stay exactly as it is today.
6. **`MaybeWriteRejectSummarySnapshot()`** (~`:1563`): in a backtest, write at most **one** summary
per trading date (plus the existing end-of-session summary). Live/SIM cadence unchanged.
## READ-FIRST
1. `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` — every occurrence of `Account != null`,
`Account == null`, `State.Historical`, `_realtimeBarSeen`, `LogRejectRateLimited`,
`MaybeWriteRejectSummarySnapshot`, `WriteSessionHeader`. Enumerate them all in your
implementation note with a keep/change verdict for each.
2. `tests/NT8.Core.Tests/Adapters/NT8StrategyBaseHistoricalGuardTests.cs` — the second test asserts
the literal `if (State == State.Historical && Account != null)`. **It enshrines the bug** and must
be rewritten, not deleted.
3. `docs/00-governance/decisions.md` — `DEC-20260818-08` (the original guard), `DEC-20261024-01`
(this task).
4. NT8 docs: `IsInStrategyAnalyzer`. The documented definition is "run from a Strategy Analyzer
chart". Confirm from the docs (and, if available, local `NinjaTrader.Core.xml` metadata) that it is
`true` during the backtest execution itself, not only for the Analyzer's chart display. Report what
you found; do not assume.
## THE FIX
Add one private predicate to `NT8StrategyBase` and route every item above through it:
```csharp
/// <summary>
/// True when this instance is executing inside Strategy Analyzer (backtest/optimization),
/// as opposed to a live/SIM account replaying catch-up history. GAP-077.
/// </summary>
private bool IsBacktestRun()
{
if (IsInStrategyAnalyzer)
return true;
if (Account != null && string.Equals(Account.Name, "Backtest", StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
```
- The `Account.Name == "Backtest"` clause is the evidence-backed half (the Oct 19 header proves the
name). Keep it even if `IsInStrategyAnalyzer` checks out. If the docs show a better-specified API,
propose it in the note; do not swap it in unasked.
- Catch-up guard becomes `if (State == State.Historical && !IsBacktestRun())`.
- `ShouldAllowDailyTradeCountIncrement()` historical branch becomes `return IsBacktestRun();`.
- Header: `Mode : BACKTEST` when `IsBacktestRun()`, else `LIVE/SIM`.
## DO NOT
- Do not change any live/SIM behaviour. A live account in `State.Historical` must still be blocked
with `HistoricalReplayCatchup` before portfolio risk, sizing and submission, exactly as today.
- Do not touch `SimpleORBStrategy.cs`, scoring, risk limits, sizing, or the replay-burst guard.
- Do not delete the orphan `bin\Custom\Strategies\SimpleORBStrategy.cs` — that is operator task P0-A.
- Do not deploy.
## REQUIRED TESTS (every one must fail against the current source)
1. Rewrite `ProcessStrategyIntent_BlocksLiveAccountHistoricalOrdersBeforeRiskAndSubmission` to assert
the guard reads `State == State.Historical && !IsBacktestRun()` and still precedes portfolio risk
and `SubmitOrderToNT8`.
2. New: `IsBacktestRun()` exists and contains both the `IsInStrategyAnalyzer` clause and the
`"Backtest"` account-name clause.
3. New: `ShouldAllowDailyTradeCountIncrement()`'s historical branch references `IsBacktestRun()` and
does **not** contain `Account == null`.
4. New: no remaining `State == State.Historical && Account != null` anywhere in
`NT8StrategyBase.cs` (regression guard against the original defect).
5. New: `WriteSessionHeader()`'s `Mode` line references `IsBacktestRun()`.
Source-text tests in the established `NT8StrategyBaseHistoricalGuardTests` pattern are acceptable —
this class cannot be instantiated outside NT8.
## VERIFICATION
- `verify-build.bat` green; report total test count.
- `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build`.
- Commit: `[GAP-077]: backtest historical guard + backtest-aware reject logging`.
## OPERATOR VALIDATION (after P0-A + deploy + full recompile — not part of this task)
1. Strategy Analyzer, same settings as 2026-10-19 (MNQ, Jan–Oct 2026, ≥60 trading-day warm-up):
header reads `Mode : BACKTEST`; `SUBMIT`/`FILL` present; trade count > 0; **max one trade per
trading date**; `REJECT SUMMARY` shows real strategy reasons (`GradeFilter`,
`OrbRangeNotEstablished`, …); no `daily_trade_count_Backtest_*.json` created.
2. Live/SIM late enable on the SIM account: `REJECT: reason=HistoricalReplayCatchup` still appears
during catch-up; zero historical `SUBMIT`.
## GOVERNANCE
Track as **GAP-077** in `SPRINT_BOARD.md` (HIGH). Update `DEC-20261024-01` status to `implemented`
with commit SHA and test counts. Note that GAP-076 (does Strategy Analyzer bind the orphan or the
DLL?) is answered empirically by operator validation step 1 once P0-A has landed.