[GAP-045/GAP-046]: risk envelope guards complete

- BasicRiskManager.cs: add sized per-position risk validation and startup validator

- NT8StrategyBase.cs: fail fast on incoherent risk config and validate after sizing

- BasicRiskManagerTests.cs: cover assertions, sized risk, property sweep, MNQ tables

- docs/00-governance: record validation evidence and NQ SIM follow-up

Build: clean | Tests: 535 passing; Core 446 passing | Deploy: backup 20260823_144817
This commit is contained in:
2026-08-23 14:50:02 -04:00
parent 6658d2d120
commit d652e29959
8 changed files with 382 additions and 35 deletions

View File

@@ -34,12 +34,12 @@
- Supersedes the "retune the breakeven trigger" framing of DEC-20260810-02 and DEC-20260815-01. - 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. - 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 / 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: `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. - **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). - 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.
**[GAP-047] Confluence factor weights pre-populated to 1.0** | Stage 1 | ✅ PART 2 IMPLEMENTED — fresh freeze required **[GAP-047] Confluence factor weights pre-populated to 1.0** | Stage 1 | ✅ PART 2 IMPLEMENTED — fresh freeze required
- `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`. - `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`.

View File

@@ -82,8 +82,8 @@ Kilocode implemented Option 0: removed the `OnBarUpdate()` `SetStopLoss` call on
**Play 6 — Validate GAP-054 before any live exposure. STILL PENDING — this is the next actual step.** **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. 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).** **Play 7 — Risk guards, all three parts (DEC-19a/19b accepted). IMPLEMENTED 2026-08-23, manual NQ SIM validation pending.**
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. `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` now fails startup for incoherent risk-envelope pairs, confirms MNQ is already `$0.50` in both hardcoded tick-value tables, and moves the live NT8 per-position `MaxTradeRisk` check to after sizing so `StopTicks * TickValue * Qty <= MaxTradeRisk` is enforced. Build/tests/deploy passed with backup `20260823_144817`. Remaining validation: manual NT8 compile, NQ SIM guard checks, and high-ATR signal behavior. The MNQ cutover is still Play 11 and was not started.
**Play 8 — MaxDailyTrades persistence (DEC-21 accepted). IMPLEMENTED 2026-08-23, manual SIM restart validation pending.** **Play 8 — MaxDailyTrades persistence (DEC-21 accepted). IMPLEMENTED 2026-08-23, manual SIM restart validation pending.**
`TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` now persists `{trading_date, daily_trade_count, account, strategy_name, symbol}` to `daily_trade_count_<AccountName>_<StrategyName>.json`, rehydrates same-date count, resets and overwrites on a new trading date, and skips file I/O when `Account == null`. Automated tests cover same-date restore, new-date reset, corrupt file, backtest no-I/O, and the 2026-08-16 19:12 / 2026-08-17 11:04 same-CME-date scenario. Remaining validation: manual NT8 compile plus SIM restart test confirming the next same-day signal rejects with `REJECT: reason=MaxDailyTrades`. `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` now persists `{trading_date, daily_trade_count, account, strategy_name, symbol}` to `daily_trade_count_<AccountName>_<StrategyName>.json`, rehydrates same-date count, resets and overwrites on a new trading date, and skips file I/O when `Account == null`. Automated tests cover same-date restore, new-date reset, corrupt file, backtest no-I/O, and the 2026-08-16 19:12 / 2026-08-17 11:04 same-CME-date scenario. Remaining validation: manual NT8 compile plus SIM restart test confirming the next same-day signal rejects with `REJECT: reason=MaxDailyTrades`.
@@ -116,7 +116,7 @@ This is a separate, later step — not part of today's six tasks. Once GAP-054,
- [x] GAP-047 Part 1/2: study delivered, DEC-20260823-01 accepted, runtime designed weights implemented and tested - [x] GAP-047 Part 1/2: study delivered, DEC-20260823-01 accepted, runtime designed weights implemented and tested
- [ ] GAP-054 runner trail: implemented, validated on sim/replay before any live gate run - [ ] GAP-054 runner trail: implemented, validated on sim/replay before any live gate run
- [x] GAP-055 persistence: implemented and automated restart/rollover-boundary tests passed; manual SIM restart validation pending - [x] GAP-055 persistence: implemented and automated restart/rollover-boundary tests passed; manual SIM restart validation pending
- [ ] GAP-045/046 all three parts: implemented on NQ, including the post-sizing Tier 1 reorder and the MNQ tick-table check - [x] GAP-045/046 all three parts: implemented on NQ, including the post-sizing Tier 1 reorder and the MNQ tick-table check; manual NQ SIM validation pending
- [ ] GAP-049 telemetry: implemented, -523.25 anomaly re-checked and resolved - [ ] 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 - [ ] `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 - [ ] SPRINT_BOARD.md, active_work.md, decisions.md all reflect end-of-day state

View File

@@ -13,7 +13,7 @@ Full detail: `docs/NT8_SDK_Master_Document_v7.0_Complete.docx`.
| Order | Item | Prompt | Owner | Blocking | | 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 | | 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 | | 2 | **GAP-045/046 guards** — resolved: MNQ (cutover staged separately) + per-position semantics | `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` — implemented/deployed 2026-08-23, backup `20260823_144817` | Kilocode, on current NQ config | Manual NT8 compile and NQ SIM validation |
| 3 | **GAP-048** — split the reject taxonomy | `TASK_GAP048_REJECT_TAXONOMY_PROMPT.md` — implemented/deployed 2026-08-23, backup `20260823_142014` | Kilocode | Manual NT8 compile and dashboard spot-check | | 3 | **GAP-048** — split the reject taxonomy | `TASK_GAP048_REJECT_TAXONOMY_PROMPT.md` — implemented/deployed 2026-08-23, backup `20260823_142014` | Kilocode | Manual NT8 compile and dashboard spot-check |
| 4 | **GAP-055** — persist `MaxDailyTrades` across restarts | `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` — implemented/deployed 2026-08-23, backup `20260823_143311` | Kilocode | Manual NT8 compile and SIM restart validation | | 4 | **GAP-055** — persist `MaxDailyTrades` across restarts | `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` — implemented/deployed 2026-08-23, backup `20260823_143311` | Kilocode | Manual NT8 compile and SIM restart validation |
| 5 | **GAP-047** — Part 1 complete (commit `cbf45df`), Part 2 runtime weight fix implemented 2026-08-23 | `TASK_GAP047_PART2_WEIGHT_RUNTIME_PROMPT.md` — verification passed, deploy backup `20260823_135331` | Kilocode | Fresh gate freeze needed before gate evidence | | 5 | **GAP-047** — Part 1 complete (commit `cbf45df`), Part 2 runtime weight fix implemented 2026-08-23 | `TASK_GAP047_PART2_WEIGHT_RUNTIME_PROMPT.md` — verification passed, deploy backup `20260823_135331` | Kilocode | Fresh gate freeze needed before gate evidence |

View File

@@ -1,5 +1,28 @@
# Current Status — NT8 SDK # Current Status — NT8 SDK
**Last Updated:** 2026-08-23 (GAP-055 MaxDailyTrades persistence implemented and deployed) **Last Updated:** 2026-08-23 (GAP-045/046 risk guards implemented and deployed)
---
## 2026-08-23 — GAP-045/046 IMPLEMENTED, manual NT8/NQ SIM validation pending
Kilocode executed `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` Parts 1-3 on the current NQ configuration. The MNQ instrument cutover was not performed and remains a separate DEC-20260819-01 follow-on.
Implementation notes:
- Added startup risk-envelope assertions via `RiskEnvelopeValidator` and `NT8StrategyBase`.
- `EnableTrailingDrawdown=True` now requires `AccountStartingBalance>0` at startup.
- `MaxStopTicks * TickValue <= MaxTradeRisk`, `MinContracts>=1`, `MinContracts<=MaxContracts`, and `MaxTradeRisk<=DailyLossLimit` are enforced before runtime order flow.
- GAP-048 had already split the misconfigured trailing-drawdown reject reason to `TrailingDrawdownNotConfigured`; no duplicate taxonomy change was needed.
- Confirmed MNQ is present and valued at `$0.50` in both `BasicRiskManager` and `BasicPositionSizer` tick-value tables.
- Added quantity-aware per-position risk enforcement: the NT8 live path now sizes first, then validates `StopTicks * TickValue * Qty <= MaxTradeRisk` against the selected quantity.
- Existing `IRiskManager.ValidateOrder()` compatibility remains for older callers and validates one contract.
Evidence:
- Added tests for all startup assertions, quantity-aware Tier 1 rejection, the old pre-quantity pass / new two-contract reject case, bounded property-style range coverage, and MNQ tick table parity.
- `verify-build.bat`: passed, 535/535 tests.
- `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build --verbosity minimal`: passed, 446/446.
- `deployment\deploy-to-nt8.bat`: completed; backup `deployment\backups\20260823_144817`; `NinjaTrader.Custom.dll` was not present to invalidate.
Next required action: manual NinjaScript compile after starting NinjaTrader, then NQ SIM validation of startup guard failures and the quantity-aware per-position `MaxTradeRisk` behavior. Do not validate or execute the MNQ cutover as part of this task.
--- ---

View File

@@ -88,7 +88,9 @@ Use this file to record durable project decisions that affect implementation pat
- **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`. - **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. - **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` - **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. - **Implementation Note (2026-08-23):** Executed `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` Parts 1-3 on the current NQ configuration without changing the traded instrument or retuning NQ values. Added `RiskEnvelopeValidator.ValidateStartupConfiguration()` and wired `NT8StrategyBase` startup to fail fast when: `EnableTrailingDrawdown=True` with `AccountStartingBalance<=0`; `MaxStopTicks * TickValue > MaxTradeRisk`; `MinContracts<1` or `MinContracts>MaxContracts`; or `MaxTradeRisk>DailyLossLimit`. Messages include the symbol and both conflicting values. GAP-048 had already split the nonconfigured trailing-drawdown reject reason to `TrailingDrawdownNotConfigured`, so no duplicate taxonomy change was needed. Confirmed MNQ exists at `$0.50` in both hardcoded tick-value tables; no table patch was needed. Implemented the approved per-position semantics by adding a sized `BasicRiskManager.ValidateOrder(..., candidateContracts)` overload and moving `NT8StrategyBase.ProcessStrategyIntent()` to calculate size before risk validation, then enforce `StopTicks * tickValue * Qty <= MaxTradeRisk` against the selected quantity. Existing `IRiskManager.ValidateOrder()` remains compatible and still validates one contract for older callers.
- **Verification (2026-08-23):** Added tests for each startup assertion's fail/pass behavior, quantity-aware Tier 1 rejection, the old pre-quantity passing case now rejecting at two contracts, a bounded property-style sweep over declared ranges, and MNQ tick-value parity in both risk and sizing tables. `verify-build.bat` passed 535/535 tests (446 Core, 79 Integration, 10 Performance); `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build --verbosity minimal` passed 446/446; `deployment\deploy-to-nt8.bat` completed with backup `20260823_144817` and noted `NinjaTrader.Custom.dll` was not present to invalidate.
- **Action Required:** Manually compile in NinjaTrader. Validate on NQ before MNQ cutover: verify the misconfigured trailing-drawdown pair refuses startup, `MaxTradeRisk<=DailyLossLimit` is enforced, and a former 10:10-style high-ATR signal either sizes within `MaxTradeRisk` or rejects from the quantity-aware per-position check. Do not perform the MNQ cutover in this validation step.
### DEC-20260818-18 ### DEC-20260818-18
- **ID:** DEC-20260818-18 - **ID:** DEC-20260818-18

View File

@@ -1652,6 +1652,8 @@ namespace NinjaTrader.NinjaScript.Strategies
_riskConfig, _riskConfig,
_sizingConfig); _sizingConfig);
ValidateStartupRiskConfiguration();
_riskManager = new BasicRiskManager(_logger, DailyLossLimit); _riskManager = new BasicRiskManager(_logger, DailyLossLimit);
_positionSizer = new BasicPositionSizer(_logger); _positionSizer = new BasicPositionSizer(_logger);
_circuitBreaker = new ExecutionCircuitBreaker( _circuitBreaker = new ExecutionCircuitBreaker(
@@ -1688,6 +1690,28 @@ namespace NinjaTrader.NinjaScript.Strategies
_currentSession = null; _currentSession = null;
} }
private void ValidateStartupRiskConfiguration()
{
string symbol = Instrument != null && Instrument.MasterInstrument != null
? Instrument.MasterInstrument.Name
: "UNKNOWN";
double tickValue = 12.50;
if (Instrument != null && Instrument.MasterInstrument != null)
tickValue = Instrument.MasterInstrument.TickSize * Instrument.MasterInstrument.PointValue;
RiskEnvelopeValidator.ValidateStartupConfiguration(
symbol,
tickValue,
EnableTrailingDrawdown,
AccountStartingBalance,
MaxStopTicks,
MaxTradeRisk,
MinContracts,
MaxContracts,
DailyLossLimit);
}
private void InitializeTrailingDrawdownState() private void InitializeTrailingDrawdownState()
{ {
if (Account == null) if (Account == null)
@@ -1980,23 +2004,6 @@ namespace NinjaTrader.NinjaScript.Strategies
return; return;
} }
if (EnableVerboseLogging)
Print(string.Format("[SDK] Validating intent: {0} {1}", intent.Side, intent.Symbol));
var riskDecision = _riskManager.ValidateOrder(intent, context, _riskConfig);
if (!riskDecision.Allow)
{
if (EnableVerboseLogging)
Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason));
if (_logger != null)
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
LogRejectRateLimited("MaxTradeRisk", string.Format("Risk manager rejected: {0}", riskDecision.RejectReason), Time[0]);
return;
}
if (EnableVerboseLogging)
Print(string.Format("[SDK] Risk approved"));
var sizingResult = _positionSizer.CalculateSize(intent, context, _sizingConfig); var sizingResult = _positionSizer.CalculateSize(intent, context, _sizingConfig);
if (EnableVerboseLogging) if (EnableVerboseLogging)
{ {
@@ -2014,6 +2021,26 @@ namespace NinjaTrader.NinjaScript.Strategies
return; return;
} }
if (EnableVerboseLogging)
Print(string.Format("[SDK] Validating sized intent: {0} {1} Qty={2}", intent.Side, intent.Symbol, sizingResult.Contracts));
var basicRiskManager = _riskManager as BasicRiskManager;
var riskDecision = basicRiskManager != null
? basicRiskManager.ValidateOrder(intent, context, _riskConfig, sizingResult.Contracts)
: _riskManager.ValidateOrder(intent, context, _riskConfig);
if (!riskDecision.Allow)
{
if (EnableVerboseLogging)
Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason));
if (_logger != null)
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
LogRejectRateLimited("MaxTradeRisk", string.Format("Risk manager rejected: {0}", riskDecision.RejectReason), Time[0]);
return;
}
if (EnableVerboseLogging)
Print(string.Format("[SDK] Risk approved"));
var request = new OmsOrderRequest(); var request = new OmsOrderRequest();
request.Symbol = intent.Symbol; request.Symbol = intent.Symbol;
request.Side = MapOrderSide(intent.Side); request.Side = MapOrderSide(intent.Side);

View File

@@ -43,10 +43,19 @@ namespace NT8.Core.Risk
} }
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>
/// Validates a sized order against Tier 1 risk controls.
/// </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");
// GAP-003: Validate RiskPerTrade <= MaxTradeRisk at startup // GAP-003: Validate RiskPerTrade <= MaxTradeRisk at startup
if (config.RiskPerTrade > config.MaxTradeRisk) if (config.RiskPerTrade > config.MaxTradeRisk)
@@ -100,7 +109,7 @@ namespace NT8.Core.Risk
} }
// Tier 1: Per-trade risk limit // Tier 1: Per-trade risk limit
var tradeRisk = CalculateTradeRisk(intent, context); var tradeRisk = CalculateTradeRisk(intent, context, candidateContracts);
if (tradeRisk > config.MaxTradeRisk) if (tradeRisk > config.MaxTradeRisk)
{ {
_logger.LogWarning("Trade risk too high: {0:C} > {1:C}", tradeRisk, config.MaxTradeRisk); _logger.LogWarning("Trade risk too high: {0:C} > {1:C}", tradeRisk, config.MaxTradeRisk);
@@ -108,6 +117,7 @@ namespace NT8.Core.Risk
var riskMetrics = new Dictionary<string, object>(); var riskMetrics = new Dictionary<string, object>();
riskMetrics.Add("trade_risk", tradeRisk); riskMetrics.Add("trade_risk", tradeRisk);
riskMetrics.Add("limit", config.MaxTradeRisk); riskMetrics.Add("limit", config.MaxTradeRisk);
riskMetrics.Add("contracts", candidateContracts);
return new RiskDecision( return new RiskDecision(
allow: false, allow: false,
@@ -158,11 +168,11 @@ namespace NT8.Core.Risk
} }
} }
private static double CalculateTradeRisk(StrategyIntent intent, StrategyContext context) private static double CalculateTradeRisk(StrategyIntent intent, StrategyContext context, int candidateContracts)
{ {
// Get tick value for symbol - this will be enhanced in later phases // Get tick value for symbol - this will be enhanced in later phases
var tickValue = GetTickValue(intent.Symbol); var tickValue = GetTickValue(intent.Symbol);
return intent.StopTicks * tickValue; return intent.StopTicks * tickValue * candidateContracts;
} }
private static double GetTickValue(string symbol) private static double GetTickValue(string symbol)
@@ -180,6 +190,21 @@ namespace NT8.Core.Risk
} }
} }
/// <summary>
/// Gets supported symbols with their tick values.
/// </summary>
public static Dictionary<string, double> GetSupportedSymbols()
{
var symbols = new Dictionary<string, double>();
symbols.Add("ES", 12.50);
symbols.Add("MES", 1.25);
symbols.Add("NQ", 5.00);
symbols.Add("MNQ", 0.50);
symbols.Add("CL", 10.00);
symbols.Add("GC", 10.00);
return symbols;
}
private int GetOpenPositionCount() private int GetOpenPositionCount()
{ {
// For Phase 0, return simplified count // For Phase 0, return simplified count
@@ -311,4 +336,67 @@ namespace NT8.Core.Risk
} }
} }
} }
/// <summary>
/// Validates risk-envelope parameter pairs before realtime order flow starts.
/// </summary>
public static class RiskEnvelopeValidator
{
/// <summary>
/// Throws when a risk-envelope parameter pair is internally inconsistent.
/// </summary>
public static void ValidateStartupConfiguration(
string symbol,
double tickValue,
bool enableTrailingDrawdown,
double accountStartingBalance,
int maxStopTicks,
double maxTradeRisk,
int minContracts,
int maxContracts,
double dailyLossLimit)
{
if (string.IsNullOrEmpty(symbol))
symbol = "UNKNOWN";
if (enableTrailingDrawdown && accountStartingBalance <= 0.0)
{
throw new ArgumentException(string.Format(
"Invalid risk configuration for {0}: EnableTrailingDrawdown ({1}) requires AccountStartingBalance ({2:F2}) > 0.",
symbol,
enableTrailingDrawdown,
accountStartingBalance));
}
double maxStopRisk = maxStopTicks * tickValue;
if (maxStopRisk > maxTradeRisk)
{
throw new ArgumentException(string.Format(
"Invalid risk configuration for {0}: MaxStopTicks ({1}) * TickValue ({2:F2}) = {3:F2} cannot exceed MaxTradeRisk ({4:F2}).",
symbol,
maxStopTicks,
tickValue,
maxStopRisk,
maxTradeRisk));
}
if (minContracts < 1 || minContracts > maxContracts)
{
throw new ArgumentException(string.Format(
"Invalid risk configuration for {0}: MinContracts ({1}) must be >= 1 and <= MaxContracts ({2}).",
symbol,
minContracts,
maxContracts));
}
if (maxTradeRisk > dailyLossLimit)
{
throw new ArgumentException(string.Format(
"Invalid risk configuration for {0}: MaxTradeRisk ({1:F2}) cannot exceed DailyLossLimit ({2:F2}).",
symbol,
maxTradeRisk,
dailyLossLimit));
}
}
}
} }

View File

@@ -1,8 +1,10 @@
using NT8.Core.Risk; using NT8.Core.Risk;
using NT8.Core.Common.Models; using NT8.Core.Common.Models;
using NT8.Core.Logging; using NT8.Core.Logging;
using NT8.Core.Sizing;
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.TestTools.UnitTesting;
using System; using System;
using System.Collections.Generic;
namespace NT8.Core.Tests.Risk namespace NT8.Core.Tests.Risk
{ {
@@ -175,6 +177,205 @@ namespace NT8.Core.Tests.Risk
Assert.IsNotNull(result); Assert.IsNotNull(result);
} }
[TestMethod]
public void ValidateStartupConfiguration_TrailingDrawdownEnabledWithoutBalance_ShouldThrowWithBothValuesAndSymbol()
{
var ex = Assert.ThrowsException<ArgumentException>(() => RiskEnvelopeValidator.ValidateStartupConfiguration(
"NQ", 5.00, true, 0.0, 40, 200.0, 1, 3, 1000.0));
AssertContains(ex.Message, "NQ");
AssertContains(ex.Message, "EnableTrailingDrawdown (True)");
AssertContains(ex.Message, "AccountStartingBalance (0.00)");
}
[TestMethod]
public void ValidateStartupConfiguration_TrailingDrawdownDisabledWithZeroBalance_ShouldPass()
{
RiskEnvelopeValidator.ValidateStartupConfiguration("NQ", 5.00, false, 0.0, 40, 200.0, 1, 3, 1000.0);
}
[TestMethod]
public void ValidateStartupConfiguration_MaxStopTicksRiskExceedsMaxTradeRisk_ShouldThrowWithBothValuesAndSymbol()
{
var ex = Assert.ThrowsException<ArgumentException>(() => RiskEnvelopeValidator.ValidateStartupConfiguration(
"NQ", 5.00, false, 0.0, 50, 200.0, 1, 3, 1000.0));
AssertContains(ex.Message, "NQ");
AssertContains(ex.Message, "MaxStopTicks (50)");
AssertContains(ex.Message, "MaxTradeRisk (200.00)");
}
[TestMethod]
public void ValidateStartupConfiguration_MaxStopTicksRiskWithinMaxTradeRisk_ShouldPass()
{
RiskEnvelopeValidator.ValidateStartupConfiguration("NQ", 5.00, false, 0.0, 40, 200.0, 1, 3, 1000.0);
}
[TestMethod]
public void ValidateStartupConfiguration_MinContractsGreaterThanMaxContracts_ShouldThrowWithBothValuesAndSymbol()
{
var ex = Assert.ThrowsException<ArgumentException>(() => RiskEnvelopeValidator.ValidateStartupConfiguration(
"NQ", 5.00, false, 0.0, 40, 200.0, 4, 3, 1000.0));
AssertContains(ex.Message, "NQ");
AssertContains(ex.Message, "MinContracts (4)");
AssertContains(ex.Message, "MaxContracts (3)");
}
[TestMethod]
public void ValidateStartupConfiguration_MinContractsBelowOne_ShouldThrowWithBothValuesAndSymbol()
{
var ex = Assert.ThrowsException<ArgumentException>(() => RiskEnvelopeValidator.ValidateStartupConfiguration(
"NQ", 5.00, false, 0.0, 40, 200.0, 0, 3, 1000.0));
AssertContains(ex.Message, "NQ");
AssertContains(ex.Message, "MinContracts (0)");
AssertContains(ex.Message, "MaxContracts (3)");
}
[TestMethod]
public void ValidateStartupConfiguration_MinContractsWithinMaxContracts_ShouldPass()
{
RiskEnvelopeValidator.ValidateStartupConfiguration("NQ", 5.00, false, 0.0, 40, 200.0, 1, 3, 1000.0);
}
[TestMethod]
public void ValidateStartupConfiguration_MaxTradeRiskExceedsDailyLossLimit_ShouldThrowWithBothValuesAndSymbol()
{
var ex = Assert.ThrowsException<ArgumentException>(() => RiskEnvelopeValidator.ValidateStartupConfiguration(
"NQ", 5.00, false, 0.0, 20, 1200.0, 1, 3, 1000.0));
AssertContains(ex.Message, "NQ");
AssertContains(ex.Message, "MaxTradeRisk (1200.00)");
AssertContains(ex.Message, "DailyLossLimit (1000.00)");
}
[TestMethod]
public void ValidateStartupConfiguration_MaxTradeRiskWithinDailyLossLimit_ShouldPass()
{
RiskEnvelopeValidator.ValidateStartupConfiguration("NQ", 5.00, false, 0.0, 40, 200.0, 1, 3, 1000.0);
}
[TestMethod]
public void ValidateOrder_SizedQuantityExceedsMaxTradeRisk_ShouldReject()
{
var intent = TestDataBuilder.CreateValidIntent(symbol: "NQ", stopTicks: 30);
var context = TestDataBuilder.CreateTestContext();
var config = new RiskConfig(1000.0, 200.0, 5, true);
var result = _riskManager.ValidateOrder(intent, context, config, 2);
Assert.IsFalse(result.Allow);
AssertContains(result.RejectReason, "Trade risk too high");
Assert.AreEqual(300.0, result.RiskMetrics["trade_risk"]);
Assert.AreEqual(2, result.RiskMetrics["contracts"]);
}
[TestMethod]
public void ValidateOrder_OldPreQuantityCasePassesOneContractButRejectsTwoContracts()
{
var intent = TestDataBuilder.CreateValidIntent(symbol: "NQ", stopTicks: 30);
var context = TestDataBuilder.CreateTestContext();
var config = new RiskConfig(1000.0, 200.0, 5, true);
var oneContract = _riskManager.ValidateOrder(intent, context, config, 1);
var twoContracts = _riskManager.ValidateOrder(intent, context, config, 2);
Assert.IsTrue(oneContract.Allow);
Assert.IsFalse(twoContracts.Allow);
Assert.AreEqual(150.0, oneContract.RiskMetrics["trade_risk"]);
Assert.AreEqual(300.0, twoContracts.RiskMetrics["trade_risk"]);
}
[TestMethod]
public void BasicPositionSizerAndRiskManager_SizedOrderingRejectsTwoContractRiskAboveMaxTradeRisk()
{
var intent = TestDataBuilder.CreateValidIntent(symbol: "NQ", stopTicks: 30);
var context = TestDataBuilder.CreateTestContext();
var methodParameters = new Dictionary<string, object>();
methodParameters.Add("contracts", 2);
var sizingConfig = new SizingConfig(SizingMethod.FixedContracts, 1, 3, 100.0, methodParameters);
var riskConfig = new RiskConfig(1000.0, 200.0, 5, true);
var sizer = new BasicPositionSizer(_logger);
SizingResult sizing = sizer.CalculateSize(intent, context, sizingConfig);
RiskDecision decision = _riskManager.ValidateOrder(intent, context, riskConfig, sizing.Contracts);
Assert.AreEqual(2, sizing.Contracts);
Assert.AreEqual(300.0, sizing.RiskAmount);
Assert.IsFalse(decision.Allow);
AssertContains(decision.RejectReason, "Trade risk too high");
}
[TestMethod]
public void RiskEnvelope_PropertySweep_NoAllowedCombinationPermitsLossAboveMaxTradeRisk()
{
int[] maxStopTicksValues = new int[] { 1, 8, 40, 100, 200 };
double[] maxTradeRiskValues = new double[] { 50.0, 200.0, 500.0, 1000.0 };
int[] minContractsValues = new int[] { 1, 2 };
int[] maxContractsValues = new int[] { 1, 2, 3 };
double[] riskPerTradeValues = new double[] { 50.0, 200.0, 500.0 };
double[] dailyLossLimitValues = new double[] { 200.0, 1000.0 };
var sizer = new BasicPositionSizer(_logger);
var context = TestDataBuilder.CreateTestContext();
foreach (int maxStopTicks in maxStopTicksValues)
{
foreach (double maxTradeRisk in maxTradeRiskValues)
{
foreach (int minContracts in minContractsValues)
{
foreach (int maxContracts in maxContractsValues)
{
foreach (double riskPerTrade in riskPerTradeValues)
{
foreach (double dailyLossLimit in dailyLossLimitValues)
{
if (minContracts > maxContracts)
continue;
if (riskPerTrade > maxTradeRisk)
continue;
try
{
RiskEnvelopeValidator.ValidateStartupConfiguration("NQ", 5.00, false, 0.0, maxStopTicks, maxTradeRisk, minContracts, maxContracts, dailyLossLimit);
}
catch (ArgumentException)
{
continue;
}
var intent = TestDataBuilder.CreateValidIntent(symbol: "NQ", stopTicks: maxStopTicks);
var sizingConfig = new SizingConfig(SizingMethod.FixedDollarRisk, minContracts, maxContracts, riskPerTrade, null);
var riskConfig = new RiskConfig(dailyLossLimit, maxTradeRisk, 5, true);
riskConfig.RiskPerTrade = riskPerTrade;
SizingResult sizing = sizer.CalculateSize(intent, context, sizingConfig);
RiskDecision decision = _riskManager.ValidateOrder(intent, context, riskConfig, sizing.Contracts);
if (decision.Allow)
Assert.IsTrue(sizing.RiskAmount <= maxTradeRisk, string.Format("Allowed risk {0} exceeded MaxTradeRisk {1}", sizing.RiskAmount, maxTradeRisk));
else
Assert.IsTrue(sizing.RiskAmount > maxTradeRisk || decision.RejectReason.Contains("Trade risk too high"), decision.RejectReason);
}
}
}
}
}
}
}
[TestMethod]
public void GetSupportedSymbols_MnqIsCorrectInBothRiskAndSizingTables()
{
Dictionary<string, double> riskSymbols = BasicRiskManager.GetSupportedSymbols();
Dictionary<string, double> sizingSymbols = BasicPositionSizer.GetSupportedSymbols();
Assert.IsTrue(riskSymbols.ContainsKey("MNQ"));
Assert.IsTrue(sizingSymbols.ContainsKey("MNQ"));
Assert.AreEqual(0.50, riskSymbols["MNQ"]);
Assert.AreEqual(0.50, sizingSymbols["MNQ"]);
}
[TestMethod] [TestMethod]
public void GetRiskStatus_ReturnsConfiguredDailyLossLimit() public void GetRiskStatus_ReturnsConfiguredDailyLossLimit()
{ {
@@ -259,5 +460,11 @@ namespace NT8.Core.Tests.Risk
Assert.AreEqual(1000.0, status1.DailyLossLimit, "First status should reflect first config"); Assert.AreEqual(1000.0, status1.DailyLossLimit, "First status should reflect first config");
Assert.AreEqual(2000.0, status2.DailyLossLimit, "Second status should reflect second config"); Assert.AreEqual(2000.0, status2.DailyLossLimit, "Second status should reflect second config");
} }
private static void AssertContains(string actual, string expected)
{
Assert.IsTrue(actual.IndexOf(expected, StringComparison.Ordinal) >= 0,
string.Format("Expected '{0}' to contain '{1}'", actual, expected));
}
} }
} }