[GAP-050]: quantity-aware risk contract complete

- IRiskManager.cs: add quantity-aware ValidateOrder contract

- AdvancedRiskManager.cs: delegate Tier 1 through sized BasicRiskManager overload and preserve 3-arg behavior

- NT8StrategyBase.cs: remove BasicRiskManager type-check workaround and call sized interface method

- NT8OrderAdapter.cs: size before risk validation and pass actual contracts

- tests: add AdvancedRiskManager, NT8OrderAdapter, and NT8StrategyBase coverage

Build: clean | Tests: 566 passing; Core 476 passing | Dual-deployed: no - skipped by prompt
This commit is contained in:
2026-08-25 16:39:56 -04:00
parent a673475738
commit a99ce1d0e7
10 changed files with 388 additions and 15 deletions

View File

@@ -37,7 +37,7 @@
**[GAP-045 / GAP-046] Risk-envelope coherence guards** | Stage 0/1 | ✅ IMPLEMENTED — deployed 2026-08-23 **[GAP-045 / GAP-046] Risk-envelope coherence guards** | Stage 0/1 | ✅ IMPLEMENTED — deployed 2026-08-23
- 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-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-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. - GAP-050: tracked separately below — its own entry has the corrected 2026-08-25 finding (live path already safe; fix scoped to the `IRiskManager` interface contract, not this NQ risk-guard work).
- **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. - **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). Verification: `verify-build.bat` 535/535, Core Release no-build 446/446, deploy backup `20260823_144817`. Manual NT8 compile and NQ SIM validation still required; MNQ cutover remains separate. - Prompt: `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` (Part 3 rewritten 2026-08-19, now fully actionable). Verification: `verify-build.bat` 535/535, Core Release no-build 446/446, deploy backup `20260823_144817`. Manual NT8 compile and NQ SIM validation still required; MNQ cutover remains separate.
@@ -88,6 +88,10 @@
- Found during GAP-054 verification (`DEC-20260821-01`): the regression test GAP-054's own task asked for (no `SetStopLoss` after `SetTrailStop` for a runner signal) was never written because no test seam exists — Kilocode correctly declined to fabricate coverage rather than write a fake test. Same defect class as GAP-054 (silent exit-order clobbering) currently has zero regression protection. - Found during GAP-054 verification (`DEC-20260821-01`): the regression test GAP-054's own task asked for (no `SetStopLoss` after `SetTrailStop` for a runner signal) was never written because no test seam exists — Kilocode correctly declined to fabricate coverage rather than write a fake test. Same defect class as GAP-054 (silent exit-order clobbering) currently has zero regression protection.
- Prompt: `TASK_GAP057_STOP_TRAIL_TEST_SEAM_PROMPT.md`. Implemented Option B: source-text regression seam. Added tests proving the runner entry block never calls `SetStopLoss(_runnerSignalName...)` after `SetTrailStop(_runnerSignalName...)`, the post-entry runner monitor in `OnBarUpdate()` contains no `SetStopLoss`/`SetTrailStop` calls, and no production order-management indirection was introduced. Verification: focused tests 3/3, `verify-build.bat` 558/558, Core Release no-build 469/469. Deploy intentionally skipped by task prompt. - Prompt: `TASK_GAP057_STOP_TRAIL_TEST_SEAM_PROMPT.md`. Implemented Option B: source-text regression seam. Added tests proving the runner entry block never calls `SetStopLoss(_runnerSignalName...)` after `SetTrailStop(_runnerSignalName...)`, the post-entry runner monitor in `OnBarUpdate()` contains no `SetStopLoss`/`SetTrailStop` calls, and no production order-management indirection was introduced. Verification: focused tests 3/3, `verify-build.bat` 558/558, Core Release no-build 469/469. Deploy intentionally skipped by task prompt.
**[GAP-050] MaxTradeRisk quantity term missing from IRiskManager contract** | Stage 1 | ✅ IMPLEMENTED — deploy skipped by prompt
- Originally flagged as a live risk-math gap ("$600 vs $1,000 daily limit"). Investigation on 2026-08-25 found the live path is already safe: `SimpleORBNT8`/`NT8StrategyBase` constructs `BasicRiskManager` directly and reaches its quantity-aware 4-arg `ValidateOrder` overload via a runtime type-check. The real gap is that `IRiskManager` itself never declared a quantity-aware member — `AdvancedRiskManager` (unwired to anything live) and `NT8OrderAdapter` (unwired scaffolding, also validates before sizing) would silently reintroduce the 1-contract assumption if either is ever wired up.
- Prompt: `TASK_GAP050_ADVANCED_RISK_QTY_PROMPT.md`. Implemented Option A: `IRiskManager` now declares the quantity-aware 4-arg `ValidateOrder`; `AdvancedRiskManager` delegates Tier 1 through the quantity-aware `BasicRiskManager` overload while retaining 3-arg one-contract behavior; `NT8StrategyBase` uses the interface directly instead of an `as BasicRiskManager` type-check; `NT8OrderAdapter` sizes first, rejects zero-size, then validates risk with the sized contract count. Verification: focused Core 10/10, focused Integration 13/13, `verify-build.bat` 566/566, Core Release no-build 476/476. Deploy intentionally skipped by task prompt.
**[GAP-061] Expose raw AVWAP/slope/trend-confirm inputs in STATE_CONTEXT telemetry** | Stage 1 | ✅ IMPLEMENTED — deploy skipped by prompt **[GAP-061] Expose raw AVWAP/slope/trend-confirm inputs in STATE_CONTEXT telemetry** | Stage 1 | ✅ IMPLEMENTED — deploy skipped by prompt
- Found during the "zero trades this week" investigation (`DEC-20260825-04`): every real breakout this week and on 2026-08-18 capped at Grade B/C, driven by `Trend=0.30` on every best short setup. Source read confirmed the sharper asymmetry: `trend_confirm` is `avwapSlope > 0.0 ? 1.0 : 0.0`, while short-side slope alignment requires `avwapSlope < 0.0`, so a short cannot earn both bonuses. - Found during the "zero trades this week" investigation (`DEC-20260825-04`): every real breakout this week and on 2026-08-18 capped at Grade B/C, driven by `Trend=0.30` on every best short setup. Source read confirmed the sharper asymmetry: `trend_confirm` is `avwapSlope > 0.0 ? 1.0 : 0.0`, while short-side slope alignment requires `avwapSlope < 0.0`, so a short cannot earn both bonuses.
- Prompt: `TASK_GAP061_AVWAP_TELEMETRY_PROMPT.md`. Implemented as observability-only: `STATE_CONTEXT` now includes `Avwap` (`F2`), `AvwapSlope` (`F4`), and `TrendConfirm` (`F1`) when those existing `context.CustomData` keys are present. Missing keys are omitted with no placeholders. No scoring, `trend_confirm`, `STATE:`, `STATE_DETAIL:`, risk, sizing, or order-flow logic changed. Verification: focused tests 7/7, `verify-build.bat` 561/561, Core Release no-build 472/472. Deploy intentionally skipped by task prompt. - Prompt: `TASK_GAP061_AVWAP_TELEMETRY_PROMPT.md`. Implemented as observability-only: `STATE_CONTEXT` now includes `Avwap` (`F2`), `AvwapSlope` (`F4`), and `TrendConfirm` (`F1`) when those existing `context.CustomData` keys are present. Missing keys are omitted with no placeholders. No scoring, `trend_confirm`, `STATE:`, `STATE_DETAIL:`, risk, sizing, or order-flow logic changed. Verification: focused tests 7/7, `verify-build.bat` 561/561, Core Release no-build 472/472. Deploy intentionally skipped by task prompt.

View File

@@ -0,0 +1,185 @@
# TASK: GAP-050 — MaxTradeRisk quantity term missing from IRiskManager contract
# Staged: 2026-08-18 (v7.0 review, "raised, not yet prompted"), decided 2026-08-25 (Option A)
# Sprint: Stage 1 — risk-interface hardening, no live-behaviour change (see THE DEFECT)
# Owner: Kilocode
# Deploy: COMMIT ONLY — do NOT run deploy-to-nt8.bat or copy build output to
# the live NT8 install as part of this task. Verify-build and commit
# as usual; leave the deploy step for the operator to run manually
# once ready.
# ─────────────────────────────────────────────────────────────────
## THE DEFECT
`MaxTradeRisk` was originally flagged as "no quantity term — worst case is
$600 against a $1,000 daily limit." That framing is **stale for the live
path** — verify this yourself in READ-FIRST before touching anything — but
the underlying interface gap is real and worth closing properly.
Current state, confirmed by direct source read on 2026-08-25:
1. `BasicRiskManager` has TWO overloads: `ValidateOrder(intent, context,
config)` (3-arg, hardcodes `candidateContracts=1` by calling the 4-arg
version) and `ValidateOrder(intent, context, config, candidateContracts)`
(4-arg, real quantity — `CalculateTradeRisk` multiplies
`StopTicks * tickValue * candidateContracts`).
2. `IRiskManager` (`src/NT8.Core/Risk/IRiskManager.cs`) only declares the
3-arg `ValidateOrder(intent, context, config)`. The 4-arg overload is
NOT part of the interface — it only exists as a concrete method on
`BasicRiskManager`.
3. **The live path is already safe**, but only via a workaround, not the
interface: `SimpleORBNT8`/`NT8StrategyBase` (`NT8StrategyBase.cs:1763`)
constructs `_riskManager = new BasicRiskManager(...)` directly, and the
order-eval flow (~2131-2136) does
`var basicRiskManager = _riskManager as BasicRiskManager; var riskDecision
= basicRiskManager != null ? basicRiskManager.ValidateOrder(intent,
context, _riskConfig, sizingResult.Contracts) : _riskManager.ValidateOrder
(intent, context, _riskConfig);` — a runtime type-check working around the
interface's own gap, only correct today because nothing else is plugged
into `_riskManager`.
4. `AdvancedRiskManager` (`src/NT8.Core/Risk/AdvancedRiskManager.cs`)
implements `IRiskManager` but has no 4-arg `ValidateOrder` at all. Its
3-arg `ValidateOrder` delegates Tier 1 to its inner `_basicRiskManager`
via the 1-contract-assumed 3-arg overload. **Confirmed not currently
wired to anything live** — `new AdvancedRiskManager(` does not appear
anywhere in `src/` outside its own file; the only places it is
constructed are `tests/NT8.Core.Tests/Risk/AdvancedRiskManagerTests.cs`
and `tests/NT8.Integration.Tests/RiskSizingIntegrationTests.cs`, both of
which build it directly and call it in isolation.
5. `NT8OrderAdapter.ExecuteIntent` (`src/NT8.Adapters/NinjaTrader/
NT8OrderAdapter.cs`) calls `_riskManager.ValidateOrder(intent, context,
config.RiskSettings)` (3-arg) **before** calling `_positionSizer.
CalculateSize(...)` — backwards even if the interface supported
quantity, since the real size isn't known yet at the point risk is
checked. `NT8OrderAdapter`/`NT8Adapter` are, in turn, only constructed by
`BaseNT8StrategyWrapper` (`src/NT8.Adapters/Wrappers/
BaseNT8StrategyWrapper.cs`), whose own doc comment says: *"This is a
template that would be extended in actual NT8 strategy files"* — nothing
in `src/` extends it. Confirmed not on the live path.
**Net: today's SIM/live trading is not exposed.** The gap is an interface
contract hole that happens to be papered over by a type-check in the one
place that matters right now, plus two pieces of unwired scaffolding that
would silently reintroduce the 1-contract assumption the moment either is
ever wired up. Fix it at the interface so this can't recur by accident.
## READ-FIRST
1. `src/NT8.Core/Risk/IRiskManager.cs` — current interface, 3-arg only.
2. `src/NT8.Core/Risk/BasicRiskManager.cs` (~lines 40-90) — the existing
3-arg-calls-4-arg pattern to mirror.
3. `src/NT8.Core/Risk/AdvancedRiskManager.cs` (full file) — constructor
wraps a real `BasicRiskManager`; existing 3-arg `ValidateOrder` runs
Tier 1 via the inner basic manager, then Tier 2 (weekly loss, trailing
drawdown), Tier 3 (cross-strategy exposure, time restrictions,
correlation), and Tier 3.5 (portfolio heat, GAP-019) — all unchanged by
this task.
4. `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` ~2095-2145 — the
sizing-then-risk-check flow and the `as BasicRiskManager` ternary this
task removes.
5. `src/NT8.Adapters/NinjaTrader/NT8OrderAdapter.cs` (full file, short) —
the `ExecuteIntent` validate-before-size ordering this task fixes.
6. Re-run the greps yourself before starting — confirm `new
AdvancedRiskManager(` and `new NT8OrderAdapter(` / `new NT8Adapter(` /
`new BaseNT8StrategyWrapper(` / `new SimpleORBNT8Wrapper(` still don't
appear anywhere in `src/` outside their own definitions and test files.
If that has changed since 2026-08-25, stop and flag it — the risk
profile of this task changes if either is now live.
## THE CHANGE — Option A (decided by operator 2026-08-25)
1. **`IRiskManager.cs`**: add
`RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext
context, RiskConfig config, int candidateContracts);` to the interface.
Keep the existing 3-arg member too (still required by both
implementations for source/test compatibility).
2. **`BasicRiskManager.cs`**: no logic change — it already has both
signatures with the exact right behaviour. Just confirm it still
compiles as an `IRiskManager` after step 1 (it should, with zero edits).
3. **`AdvancedRiskManager.cs`**: add the 4-arg `ValidateOrder(intent,
context, config, candidateContracts)`. It should run Tier 1 via
`_basicRiskManager.ValidateOrder(intent, context, config,
candidateContracts)` (the real, quantity-aware overload) instead of the
3-arg one, then fall through to the exact same Tier 2/3/3.5 body the
existing 3-arg method already has (do not duplicate that logic — factor
it into a shared private method both the 3-arg and 4-arg public methods
call, or have the 3-arg method call the new 4-arg one with
`candidateContracts=1`, mirroring `BasicRiskManager`'s own pattern
exactly — your call which is cleaner, but no behavioural duplication/
drift between the two).
4. **`NT8StrategyBase.cs` ~2131-2136**: remove the `as BasicRiskManager`
cast and fallback entirely. Replace with a direct call:
`var riskDecision = _riskManager.ValidateOrder(intent, context,
_riskConfig, sizingResult.Contracts);` — now safe for any `IRiskManager`
implementation, not just `BasicRiskManager`. This must produce byte-
identical behaviour for the live path (currently always a
`BasicRiskManager` instance) — same underlying 4-arg call, just reached
without the type-check.
5. **`NT8OrderAdapter.cs` `ExecuteIntent`**: reorder so `_positionSizer.
CalculateSize(...)` runs first, then call the 4-arg `ValidateOrder`
with the real `sizingResult.Contracts` instead of the 3-arg call before
sizing. Keep the existing `sizingResult.Contracts <= 0` early-return,
just move it ahead of the risk check.
## DO NOT
- Do not change `BasicRiskManager`'s existing logic — it's already correct
and is the class actually protecting live trading today.
- Do not change any of `AdvancedRiskManager`'s Tier 2/3/3.5 check bodies
(`ValidateWeeklyLimit`, `ValidateTrailingDrawdown`,
`ValidateCrossStrategyExposure`, `ValidateTimeRestrictions`,
`ValidateCorrelationLimits`, `ValidatePortfolioHeat`) — only how Tier 1
is invoked changes.
- Do not wire `AdvancedRiskManager` or `NT8OrderAdapter`/`NT8Adapter`/
`BaseNT8StrategyWrapper` into the live `SimpleORBNT8`/`NT8StrategyBase`
construction path. That is a separate, much larger decision (switching
which risk manager actually governs live trading) and is explicitly out
of scope for this task — this task only guarantees correctness *if* that
ever happens, it does not make it happen.
- Do not touch `src/_archive/legacy-orders/OrderManager.cs` — archived,
out of scope.
- Do not touch `RiskConfig`/`AdvancedRiskConfig` field shapes.
## TESTS (required)
1. New test(s) in `AdvancedRiskManagerTests.cs` proving the 4-arg
`ValidateOrder` correctly scales rejected/allowed decisions by
`candidateContracts` (mirror the existing quantity-aware tests in
`BasicRiskManagerTests.cs` if any exist — same shape, e.g. a trade that
passes at qty=1 but is correctly rejected at qty=3 once `StopTicks *
tickValue * 3 > MaxTradeRisk`).
2. A test proving `AdvancedRiskManager`'s 3-arg `ValidateOrder` still
behaves exactly as before (backward-compatibility / no regression for
existing callers, including `RiskSizingIntegrationTests.cs`).
3. A test proving `NT8OrderAdapter.ExecuteIntent` now calls `ValidateOrder`
with the actual sized quantity, not a hardcoded 1 (construct with a
test-double bridge/risk manager/sizer and assert the call).
4. Confirm the full existing suite still passes, including
`RiskSizingIntegrationTests.cs` and anything covering the
`NT8StrategyBase.cs` ternary area (source-text assertion is fine there,
consistent with this codebase's established precedent for
NinjaScript-derived classes that can't be instantiated directly).
## VALIDATION (operator)
None required for correctness — the live path (`BasicRiskManager` reached
directly by `SimpleORBNT8`) is unchanged in behaviour, just reached via the
interface instead of a type-check. `AdvancedRiskManager`/`NT8OrderAdapter`
remain unwired to live trading after this task. No SIM/gate validation
needed before committing; deploy is still an explicit operator step per the
header above.
## GOVERNANCE
Track as [GAP-050] in SPRINT_BOARD.md — promote out of the "operator
decision needed" catch-all line into its own entry, Option A implemented,
noting the live path was already safe and this closes the interface
contract gap plus the two unwired call sites. Update
`docs/00-governance/decisions.md` with a new dated entry recording Option A
and the implementation, referencing this task.
Reference: this task, `DEC-20260825-03` (operator decision + investigation
findings), original v7.0 review staging (`SPRINT_BOARD.md` "Also raised by
the review, not yet prompted").

View File

@@ -24,6 +24,15 @@ Use this file to record durable project decisions that affect implementation pat
- **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` (`MaybeWriteRejectSummarySnapshot`/`LogRejectRateLimited`/`ResetRejectTracking`/`WriteSessionHeader` ~1444-1517), `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` (`OnBar` ~355-432, `RecordSignalRejection` ~1015-1026), `session_20260823_230519.log` - **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` (`MaybeWriteRejectSummarySnapshot`/`LogRejectRateLimited`/`ResetRejectTracking`/`WriteSessionHeader` ~1444-1517), `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` (`OnBar` ~355-432, `RecordSignalRejection` ~1015-1026), `session_20260823_230519.log`
- **Implementation Note (2026-08-25):** GAP-060 implemented as logging/observability only. `NT8StrategyBase.MaybeWriteRejectSummarySnapshot()` no longer has a blanket midnight-to-10:00 AM suppression gate; suppression now delegates to an ORB-window-aware helper and `SimpleORBNT8` overrides that helper so the suppressed window is today's configured 09:30 + `OpeningRangeMinutes`. The once-after-ORB snapshot flag now resets per `barTime.Date`, allowing a new post-ORB summary every day in a continuous multi-day session. `OnBarUpdate()` now calls `MaybeWriteRejectSummarySnapshot(Time[0])` on the live bar heartbeat after the first realtime-bar guard, so 15-minute summary cadence can flush from regular processed bars and is not solely dependent on a newly logged reject. Existing `_rejectDetailsLogged` one-detail-line-per-reason rate limiting, reject reason strings, `REJECT:`/`REJECT SUMMARY:` formats, order flow, sizing, risk, and real trade decisions were unchanged. Open question resolved as possibility **(a)**: the missing `OrbRangeNotEstablished` visibility was adapter summary reporting, not a second SimpleORB rejection defect. A focused `SimpleORBStrategy.OnBar()` test proves the no-breakout RTH path records `OrbRangeNotEstablished` both while the ORB is building and after ORB close when no breakout confirms. Verification: focused GAP-060 tests passed 8/8; `verify-build.bat` passed with 543/543 tests (454 Core, 79 Integration, 10 Performance); `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build --verbosity minimal` passed 454/454. - **Implementation Note (2026-08-25):** GAP-060 implemented as logging/observability only. `NT8StrategyBase.MaybeWriteRejectSummarySnapshot()` no longer has a blanket midnight-to-10:00 AM suppression gate; suppression now delegates to an ORB-window-aware helper and `SimpleORBNT8` overrides that helper so the suppressed window is today's configured 09:30 + `OpeningRangeMinutes`. The once-after-ORB snapshot flag now resets per `barTime.Date`, allowing a new post-ORB summary every day in a continuous multi-day session. `OnBarUpdate()` now calls `MaybeWriteRejectSummarySnapshot(Time[0])` on the live bar heartbeat after the first realtime-bar guard, so 15-minute summary cadence can flush from regular processed bars and is not solely dependent on a newly logged reject. Existing `_rejectDetailsLogged` one-detail-line-per-reason rate limiting, reject reason strings, `REJECT:`/`REJECT SUMMARY:` formats, order flow, sizing, risk, and real trade decisions were unchanged. Open question resolved as possibility **(a)**: the missing `OrbRangeNotEstablished` visibility was adapter summary reporting, not a second SimpleORB rejection defect. A focused `SimpleORBStrategy.OnBar()` test proves the no-breakout RTH path records `OrbRangeNotEstablished` both while the ORB is building and after ORB close when no breakout confirms. Verification: focused GAP-060 tests passed 8/8; `verify-build.bat` passed with 543/543 tests (454 Core, 79 Integration, 10 Performance); `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build --verbosity minimal` passed 454/454.
- **Action Required:** Deployment remains pending. `deployment\deploy-to-nt8.bat` was attempted on 2026-08-25 but failed because NinjaTrader.exe PID 18800 locked `NT8.Core.dll`; operator instructed Kilocode to commit without deploy. After NinjaTrader is closed, rerun deployment, start NT8, manually compile NinjaScript, and in the next SIM session spanning a full trading day confirm `REJECT SUMMARY` appears throughout RTH at a reasonable cadence. - **Action Required:** Deployment remains pending. `deployment\deploy-to-nt8.bat` was attempted on 2026-08-25 but failed because NinjaTrader.exe PID 18800 locked `NT8.Core.dll`; operator instructed Kilocode to commit without deploy. After NinjaTrader is closed, rerun deployment, start NT8, manually compile NinjaScript, and in the next SIM session spanning a full trading day confirm `REJECT SUMMARY` appears throughout RTH at a reasonable cadence.
### DEC-20260825-03
- **ID:** DEC-20260825-03
- **Date:** 2026-08-25
- **Status:** implemented — Option A, deploy skipped by prompt
- **Context:** GAP-050 (`MaxTradeRisk` has no quantity term) was staged 2026-08-18 as an operator-decision item. Investigation on 2026-08-25 found the original framing ("$600 vs $1,000 daily limit") is stale for the live path: `SimpleORBNT8`/`NT8StrategyBase` constructs `BasicRiskManager` directly and already reaches the quantity-aware 4-arg `ValidateOrder(intent, context, config, candidateContracts)` overload via an `as BasicRiskManager` runtime type-check. `IRiskManager` itself, however, never declared a quantity-aware member. `AdvancedRiskManager` implemented `IRiskManager` but had no 4-arg overload and delegated Tier 1 to its inner `BasicRiskManager` through the 1-contract-assumed 3-arg call. `NT8OrderAdapter.ExecuteIntent` validated before sizing, so it also could not pass quantity. These scaffolding paths are not currently wired to live SimpleORB trading, but would silently reintroduce the 1-contract assumption if activated.
- **Decision:** Operator selected Option A: fix the contract at `IRiskManager`, add the quantity-aware implementation to `AdvancedRiskManager`, remove the live-path type-check workaround from `NT8StrategyBase`, and fix `NT8OrderAdapter.ExecuteIntent` to size before risk validation. Do not wire `AdvancedRiskManager` or `NT8OrderAdapter` into live trading in this task.
- **Implementation Note (2026-08-25):** `IRiskManager` now declares the quantity-aware 4-arg `ValidateOrder`; `BasicRiskManager` already satisfied the contract with no logic change; `AdvancedRiskManager` now has a 4-arg overload that forwards Tier 1 to `_basicRiskManager.ValidateOrder(..., candidateContracts)` and the 3-arg overload delegates to the 4-arg overload with `candidateContracts=1`; `NT8StrategyBase` now calls `_riskManager.ValidateOrder(intent, context, _riskConfig, sizingResult.Contracts)` directly instead of casting to `BasicRiskManager`; `NT8OrderAdapter.ExecuteIntent()` now sizes first, returns on `Contracts <= 0`, and then validates risk with the sized quantity. Added tests for quantity-aware AdvancedRiskManager rejection/allowance, backward-compatible 3-arg behavior, NT8OrderAdapter sized risk validation, and NT8StrategyBase source-level interface usage. Verification: focused Core tests passed 10/10; focused Integration tests passed 13/13; `verify-build.bat` passed with 566/566 tests (476 Core, 80 Integration, 10 Performance); `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build --verbosity minimal` passed 476/476. Deploy intentionally skipped by task prompt.
- **Related Files:** `src/NT8.Core/Risk/IRiskManager.cs`, `src/NT8.Core/Risk/AdvancedRiskManager.cs`, `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Adapters/NinjaTrader/NT8OrderAdapter.cs`, `tests/NT8.Core.Tests/Risk/AdvancedRiskManagerTests.cs`, `tests/NT8.Core.Tests/Adapters/NT8StrategyBaseRiskContractTests.cs`, `tests/NT8.Integration.Tests/NT8OrderAdapterIntegrationTests.cs`, `TASK_GAP050_ADVANCED_RISK_QTY_PROMPT.md`
- **Action Required:** Deploy remains a separate manual operator step. No operator validation required before commit because the live path's underlying quantity-aware `BasicRiskManager` call is unchanged.
### DEC-20260825-04 ### DEC-20260825-04
- **ID:** DEC-20260825-04 - **ID:** DEC-20260825-04
- **Date:** 2026-08-25 - **Date:** 2026-08-25

View File

@@ -81,14 +81,6 @@ namespace NT8.Adapters.NinjaTrader
try try
{ {
// Validate the intent through risk management
var riskDecision = _riskManager.ValidateOrder(intent, context, config.RiskSettings);
if (!riskDecision.Allow)
{
// Risk rejected the order flow.
return;
}
// Calculate position size // Calculate position size
var sizingResult = _positionSizer.CalculateSize(intent, context, config.SizingSettings); var sizingResult = _positionSizer.CalculateSize(intent, context, config.SizingSettings);
if (sizingResult.Contracts <= 0) if (sizingResult.Contracts <= 0)
@@ -97,6 +89,14 @@ namespace NT8.Adapters.NinjaTrader
return; return;
} }
// Validate the sized intent through risk management.
var riskDecision = _riskManager.ValidateOrder(intent, context, config.RiskSettings, sizingResult.Contracts);
if (!riskDecision.Allow)
{
// Risk rejected the order flow.
return;
}
// In a real implementation, this would call NT8's order execution methods. // In a real implementation, this would call NT8's order execution methods.
ExecuteInNT8(intent, sizingResult); ExecuteInNT8(intent, sizingResult);
} }

View File

@@ -2133,10 +2133,7 @@ namespace NinjaTrader.NinjaScript.Strategies
if (EnableVerboseLogging) if (EnableVerboseLogging)
Print(string.Format("[SDK] Validating sized intent: {0} {1} Qty={2}", intent.Side, intent.Symbol, sizingResult.Contracts)); Print(string.Format("[SDK] Validating sized intent: {0} {1} Qty={2}", intent.Side, intent.Symbol, sizingResult.Contracts));
var basicRiskManager = _riskManager as BasicRiskManager; var riskDecision = _riskManager.ValidateOrder(intent, context, _riskConfig, sizingResult.Contracts);
var riskDecision = basicRiskManager != null
? basicRiskManager.ValidateOrder(intent, context, _riskConfig, sizingResult.Contracts)
: _riskManager.ValidateOrder(intent, context, _riskConfig);
if (!riskDecision.Allow) if (!riskDecision.Allow)
{ {
if (EnableVerboseLogging) if (EnableVerboseLogging)

View File

@@ -73,15 +73,24 @@ namespace NT8.Core.Risk
/// Validate order intent through all risk tiers /// Validate order intent through all risk tiers
/// </summary> /// </summary>
public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config) public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config)
{
return ValidateOrder(intent, context, config, 1);
}
/// <summary>
/// Validate sized order intent through all risk tiers
/// </summary>
public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config, int candidateContracts)
{ {
if (intent == null) throw new ArgumentNullException("intent"); if (intent == null) throw new ArgumentNullException("intent");
if (context == null) throw new ArgumentNullException("context"); if (context == null) throw new ArgumentNullException("context");
if (config == null) throw new ArgumentNullException("config"); if (config == null) throw new ArgumentNullException("config");
if (candidateContracts < 0) throw new ArgumentException("candidateContracts must be non-negative", "candidateContracts");
try try
{ {
// Tier 1: Basic risk checks (delegate to BasicRiskManager) // Tier 1: Basic risk checks (delegate to BasicRiskManager)
var basicDecision = _basicRiskManager.ValidateOrder(intent, context, config); var basicDecision = _basicRiskManager.ValidateOrder(intent, context, config, candidateContracts);
if (!basicDecision.Allow) if (!basicDecision.Allow)
{ {
_logger.LogWarning("Order rejected by Tier 1 risk: {0}", basicDecision.RejectReason); _logger.LogWarning("Order rejected by Tier 1 risk: {0}", basicDecision.RejectReason);

View File

@@ -14,6 +14,11 @@ namespace NT8.Core.Risk
/// </summary> /// </summary>
RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config); RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config);
/// <summary>
/// Check if a sized order intent passes risk validation.
/// </summary>
RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config, int candidateContracts);
/// <summary> /// <summary>
/// Update risk state after fill /// Update risk state after fill
/// </summary> /// </summary>
@@ -34,4 +39,4 @@ namespace NT8.Core.Risk
/// </summary> /// </summary>
RiskStatus GetRiskStatus(); RiskStatus GetRiskStatus();
} }
} }

View File

@@ -0,0 +1,61 @@
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NT8.Core.Tests.Adapters
{
[TestClass]
public class NT8StrategyBaseRiskContractTests
{
[TestMethod]
public void ProcessStrategyIntent_UsesQuantityAwareRiskInterfaceCall()
{
string source = File.ReadAllText(FindSourceFile());
string method = ExtractMethodBlock(source, "private void ProcessStrategyIntent");
Assert.IsTrue(method.Contains("_riskManager.ValidateOrder(intent, context, _riskConfig, sizingResult.Contracts)"), "Sized risk validation must use the IRiskManager quantity-aware overload.");
Assert.IsFalse(method.Contains("_riskManager as BasicRiskManager"), "Sized risk validation must not depend on a BasicRiskManager type check.");
}
private static string FindSourceFile()
{
DirectoryInfo dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
while (dir != null)
{
string candidate = Path.Combine(dir.FullName, "src", "NT8.Adapters", "Strategies", "NT8StrategyBase.cs");
if (File.Exists(candidate))
return candidate;
dir = dir.Parent;
}
throw new FileNotFoundException("Could not locate src\\NT8.Adapters\\Strategies\\NT8StrategyBase.cs from test output directory.");
}
private static string ExtractMethodBlock(string source, string signature)
{
int start = source.IndexOf(signature, StringComparison.Ordinal);
if (start < 0)
Assert.Fail("Source does not contain method: " + signature);
int brace = source.IndexOf("{", start, StringComparison.Ordinal);
if (brace < 0)
Assert.Fail("Method has no opening brace: " + signature);
int depth = 0;
for (int i = brace; i < source.Length; i++)
{
if (source[i] == '{')
depth++;
else if (source[i] == '}')
{
depth--;
if (depth == 0)
return source.Substring(start, i - start + 1);
}
}
Assert.Fail("Method has no closing brace: " + signature);
return string.Empty;
}
}
}

View File

@@ -182,6 +182,77 @@ namespace NT8.Core.Tests.Risk
Assert.AreEqual(RiskLevel.Medium, result.RiskLevel); Assert.AreEqual(RiskLevel.Medium, result.RiskLevel);
} }
[TestMethod]
public void ValidateOrder_WithCandidateContracts_RejectedWhenSizedRiskExceedsLimit()
{
// Arrange
var manager = CreateManager(
weeklyLossLimit: 100000,
trailingDrawdownLimit: 50000,
maxCrossStrategyExposure: 100000,
maxCorrelatedExposure: 100000,
tradingTimeWindows: new List<TradingTimeWindow>());
var intent = TestDataBuilder.CreateValidIntent(symbol: "NQ", stopTicks: 20);
var context = TestDataBuilder.CreateTestContext(symbol: "NQ");
var config = new RiskConfig(1000.0, 200.0, 5, true);
// Act
var result = manager.ValidateOrder(intent, context, config, 3);
// Assert
Assert.IsFalse(result.Allow);
Assert.IsTrue(result.RejectReason.Contains("Trade risk too high"));
Assert.AreEqual(3, result.RiskMetrics["contracts"]);
}
[TestMethod]
public void ValidateOrder_WithCandidateContracts_AllowsSameIntentAtOneContract()
{
// Arrange
var manager = CreateManager(
weeklyLossLimit: 100000,
trailingDrawdownLimit: 50000,
maxCrossStrategyExposure: 100000,
maxCorrelatedExposure: 100000,
tradingTimeWindows: new List<TradingTimeWindow>());
var intent = TestDataBuilder.CreateValidIntent(symbol: "NQ", stopTicks: 20);
var context = TestDataBuilder.CreateTestContext(symbol: "NQ");
var config = new RiskConfig(1000.0, 200.0, 5, true);
// Act
var result = manager.ValidateOrder(intent, context, config, 1);
// Assert
Assert.IsTrue(result.Allow, result.RejectReason);
}
[TestMethod]
public void ValidateOrder_ThreeArgumentOverload_RetainsOneContractBehavior()
{
// Arrange
var manager = CreateManager(
weeklyLossLimit: 100000,
trailingDrawdownLimit: 50000,
maxCrossStrategyExposure: 100000,
maxCorrelatedExposure: 100000,
tradingTimeWindows: new List<TradingTimeWindow>());
var intent = TestDataBuilder.CreateValidIntent(symbol: "NQ", stopTicks: 20);
var context = TestDataBuilder.CreateTestContext(symbol: "NQ");
var config = new RiskConfig(1000.0, 200.0, 5, true);
// Act
var threeArgument = manager.ValidateOrder(intent, context, config);
var oneContract = manager.ValidateOrder(intent, context, config, 1);
// Assert
Assert.AreEqual(oneContract.Allow, threeArgument.Allow);
Assert.AreEqual(oneContract.RejectReason, threeArgument.RejectReason);
Assert.AreEqual(oneContract.RiskLevel, threeArgument.RiskLevel);
}
private static AdvancedRiskManager CreateManager( private static AdvancedRiskManager CreateManager(
double weeklyLossLimit, double weeklyLossLimit,
double trailingDrawdownLimit, double trailingDrawdownLimit,

View File

@@ -99,6 +99,24 @@ namespace NT8.Integration.Tests
Assert.AreEqual(16, history[0].TargetTicks); Assert.AreEqual(16, history[0].TargetTicks);
} }
[TestMethod]
public void ExecuteIntent_ValidatesRiskWithSizedContracts()
{
// Arrange
var adapter = new NT8OrderAdapter(new FakeBridge());
var risk = new TestRiskManager(true);
var sizer = new TestPositionSizer(4);
adapter.Initialize(risk, sizer);
// Act
adapter.ExecuteIntent(CreateIntent(), CreateContext(), CreateConfig());
// Assert
Assert.AreEqual(4, risk.LastCandidateContracts);
Assert.AreEqual(0, risk.ThreeArgumentValidateCalls);
Assert.AreEqual(1, risk.FourArgumentValidateCalls);
}
[TestMethod] [TestMethod]
public void GetExecutionHistory_ReturnsCopy_NotMutableInternalReference() public void GetExecutionHistory_ReturnsCopy_NotMutableInternalReference()
{ {
@@ -193,13 +211,27 @@ namespace NT8.Integration.Tests
{ {
private readonly bool _allow; private readonly bool _allow;
public int LastCandidateContracts { get; private set; }
public int ThreeArgumentValidateCalls { get; private set; }
public int FourArgumentValidateCalls { get; private set; }
public TestRiskManager(bool allow) public TestRiskManager(bool allow)
{ {
_allow = allow; _allow = allow;
LastCandidateContracts = -1;
} }
public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config) public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config)
{ {
ThreeArgumentValidateCalls++;
return ValidateOrder(intent, context, config, 1);
}
public RiskDecision ValidateOrder(StrategyIntent intent, StrategyContext context, RiskConfig config, int candidateContracts)
{
FourArgumentValidateCalls++;
LastCandidateContracts = candidateContracts;
return new RiskDecision( return new RiskDecision(
_allow, _allow,
_allow ? null : "Rejected by test risk manager", _allow ? null : "Rejected by test risk manager",