Files
nt8-sdk/docs/00-governance/decisions.md
mo c9041df36a Sprint 3: Production Hardening — 9 tasks completed
## Summary
Implemented 9 production-hardening tasks across risk, execution, calendar, and governance.
All changes verified: build clean (0 errors), 492 tests passing (404 core + 78 integration + 10 perf).

## Core Changes

### Risk & Portfolio (3 tasks)
- **GAP-019** Portfolio Heat Tier 3.5: Added MaxHeatPct (default 3%) to AdvancedRiskConfig;
  ValidatePortfolioHeat() computes TotalOpenRisk + NewTradeRisk / Equity * 100; rejects when exceeded.
- **GAP-003** RiskPerTrade <= MaxTradeRisk Assertion: RiskPerTrade property in RiskConfig; throws
  ArgumentException at ValidateOrder() if RiskPerTrade > MaxTradeRisk; 3 unit tests.
- **GAP-005** GetRiskStatus() Live Config: _currentDailyLossLimit field updated from config.DailyLossLimit
  on each ValidateOrder(); GetRiskStatus() returns actual value; 3 unit tests.

### Execution & Position Management (3 tasks)
- **TASK-06a** Runner Mode Architecture: RunnerMode enum (Auto/Mode1DualLeg/Mode2RunnerOnly/
  Mode3ScalerOnly/Disabled); ResolveRunnerMode() logic; 4-mode SubmitOrderToNT8() behavior.
- **TASK-06b** ATR Dynamic Stop: EnableDynamicStop, AtrPeriod, AtrMultiplier, MinStopTicks, MaxStopTicks;
  computes dynStop = clamp(round(ATR/TickSize * Mult), Min, Max); overrides intent.StopTicks.
- **GAP-006** Position-Close Re-arm: OnPositionUpdate() sends clear_trade_taken when flat;
  EnableBarBasedRearm parameter gates legacy bar-driven re-arm (default false for live).

### Strategy Intelligence (2 tasks)
- **GAP-004** orbRangeTicks Fix: DailyBarContext.OrbRangeTicks field; computed from actual ORB
  high/low / TickSize; passed to Factor 7 (ORBvsATR).
- **GAP-010** Short-Side Regime Filter: EnableShortTrendFilter param; vetoes shorts when
  AVWAP slope > 0 (bullish); configurable, default true.

### Calendar & Trailing (2 tasks)
- **GAP-008** CME Holiday Awareness: NEW CmeHolidayCalendar.cs with 9 observed holidays +
  Good Friday (Easter calc); EnableCMEHolidayGuard skips ORB window on holidays.
- **GAP-009** ATR Trailing Real ATR: EnableATRTrailing, ATRTrailingPeriod (14), ATRTrailingMultiplier (2.0),
  ATRTrailingMinTicks (8), ATRTrailingMaxTicks (60); computes trailTicks from ATR(Close,Period)[0].

## Governance
- SPRINT_BOARD.md, current_status.md, decisions.md (DEC-20260711-01 through -09), NEXT_PROMPT.md updated
- All 9 tasks moved ACTIVE -> COMPLETED; GAP-011 (Gitea CI) now ACTIVE

## Verification
- verify-build.bat: 0 errors, 0 warnings
- Tests: 492 passing (404 core + 78 integration + 10 performance)

## Files
- Modified: 13 source, 3 test, 9 governance
- Deleted: 28 obsolete spec/docs
- Added: 1 new module (NT8.Core.Calendar), governance files
- Dual-deployed to NT8 Custom\Strategies\

## Rollback
Tag: sprint3-production-hardening-complete
To revert: git reset --hard sprint3-production-hardening-complete
2026-07-13 08:38:25 -04:00

108 lines
15 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Architecture Decisions
Use this file to record durable project decisions that affect implementation patterns, interfaces, or workflow.
## Decision Template
- ID: DEC-YYYYMMDD-XX
- Date:
- Status: proposed | accepted | superseded
- Context:
- Decision:
- Consequences:
- Related Files:
## Decision Log
### DEC-20260711-03
- **ID:** DEC-20260711-03
- **Date:** 2026-07-11
- **Status:** accepted
- **Context:** Without a portfolio-level heat limit, multiple strategies or multiple positions within a strategy could each risk 2-3% of account simultaneously, leading to 6-9%+ aggregate risk. Need a Tier 3.5 check that caps total open risk + new trade risk as % of account balance.
- **Decision:** Added MaxHeatPct (default 3.0%) to AdvancedRiskConfig. Implemented ValidatePortfolioHeat() in AdvancedRiskManager that computes: TotalOpenRisk = Σ|exposure| from _state.ExposureBySymbol; NewTradeRisk = |intent.StopTicks × tickValue × estimatedQty|; HeatPct = (TotalOpenRisk + NewTradeRisk) / Account.Equity × 100. Called as Tier 3.5 in ValidateOrder() after correlation checks. Returns Reject with detailed metrics when exceeded. Edge cases: skips if MaxHeatPct ≤ 0 or account balance ≤ 0. Logs via _logger.LogDebug.
- **Consequences:** Prevents aggregate risk blowout across strategies. Backward compatible: MaxHeatPct=0 disables. Dual-deployed to NT8 Custom\Strategies\.
- **Related Files:** `src\NT8.Core\Risk\AdvancedRiskModels.cs` (MaxHeatPct in AdvancedRiskConfig), `src\NT8.Core\Risk\AdvancedRiskManager.cs` (ValidatePortfolioHeat, Tier 3.5 call)
- **Action Required:** Verify in SIM — session log should show "[SDK] Heat check: X% of 3.0% limit" when heat check runs; test rejection by loading multiple strategies/positions to exceed 3% heat.
### DEC-20260711-04
- **ID:** DEC-20260711-04
- **Date:** 2026-07-11
- **Status:** accepted
- **Context:** RiskPerTrade (sizing parameter) could exceed MaxTradeRisk (validation limit) silently, allowing trades that would be rejected by the risk manager. This created a configuration hazard where the sizing engine would calculate position sizes based on RiskPerTrade, only to have them rejected by MaxTradeRisk check.
- **Decision:** Added RiskPerTrade property to RiskConfig (defaults to MaxTradeRisk for backward compatibility). In BasicRiskManager.ValidateOrder(), added startup assertion: if (config.RiskPerTrade > config.MaxTradeRisk) throw ArgumentException with clear message identifying both values. This fails fast at order validation time rather than silently rejecting trades.
- **Consequences:** Configuration errors are caught immediately with actionable message. Backward compatible: existing configs without explicit RiskPerTrade use MaxTradeRisk value. Added 3 unit tests: > throws, == accepted, < accepted.
- **Related Files:** `src\NT8.Core\Common\Models\Configuration.cs` (RiskPerTrade in RiskConfig), `src\NT8.Core\Risk\BasicRiskManager.cs` (validation in ValidateOrder), `tests\NT8.Core.Tests\Risk\BasicRiskManagerTests.cs` (3 new tests)
- **Action Required:** Verify in SIM with config where RiskPerTrade > MaxTradeRisk — should throw ArgumentException with clear message.
### DEC-20260711-02
- **ID:** DEC-20260711-02
- **Date:** 2026-07-11
- **Status:** accepted
- **Context:** Fixed 8-tick stop on NQ ignores market volatility. At typical ATR of 20-40 ticks, an 8-tick stop causes chronic stop-outs before the move develops. Need dynamic ATR-based stop sizing that adapts to actual market conditions.
- **Decision:** Implemented ATR-based dynamic stop in NT8StrategyBase with 5 new parameters: EnableDynamicStop (default false), AtrPeriod (14), AtrMultiplier (1.5), MinStopTicks (12), MaxStopTicks (50). In SubmitOrderToNT8(), before sizing: if EnableDynamicStop and CurrentBars[0] >= AtrPeriod, compute dynStop = clamp(round(ATR[0]/TickSize × AtrMultiplier), Min, Max), override intent.StopTicks, recalculate target from R:R ratio, pass ATR to context.CustomData["current_atr"] for Factor 3 and TrailingStopManager. Added [SDK] Dynamic stop logging.
- **Consequences:** Stop now scales with volatility — tighter stops in quiet markets, wider in volatile. Backward compatible: EnableDynamicStop=false preserves fixed StopTicks. Dual-deployed to NT8 Custom\Strategies\.
- **Related Files:** `src\NT8.Adapters\Strategies\NT8StrategyBase.cs` (5 params, dynamic stop logic, logging)
- **Action Required:** Verify in SIM with EnableDynamicStop=true — session log should show [SDK] Dynamic stop line with computed value inside 12-50t; chart stop line should sit at ATR distance, not fixed 40t.
### DEC-20260711-01
- **ID:** DEC-20260711-01
- **Date:** 2026-07-11
- **Status:** accepted
- **Context:** The original runner architecture coupled position management to capital sizing via `useRunner = Qty >= 2`. This meant the runner (trailing stop leg) never activated at responsible ATR-based stops (typically Qty=1 at $200 risk with NQ ATR=20-40 ticks). The runner should be a POSITION MANAGEMENT MODE, not a quantity gate.
- **Decision:** Implemented `RunnerMode` enum with four modes: Auto (resolves Mode1 when Qty≥2, Mode2 when Qty=1), Mode1DualLeg (scaler + runner), Mode2RunnerOnly (full qty on trail stop, no fixed target), Mode3ScalerOnly (full qty with fixed target, no runner), Disabled (original single-leg). Added `[NinjaScriptProperty] RunnerActivationMode` to NT8StrategyBase with default `Auto`. Replaced the hardcoded quantity check with `ResolveRunnerMode()` logic and mode-specific order submission in `SubmitOrderToNT8()`. Added `[SDK] Runner mode resolved: {Mode} (Qty={N})` logging.
- **Consequences:** Runner now fires at Qty=1 with ATR-based stops, decoupling position management from sizing. Backward compatible: existing configs with `EnableRunner=true` and Qty≥2 will resolve to Mode1DualLeg automatically. Dual-deployed to NT8 Custom\Strategies\.
- **Related Files:** `src\NT8.Core\Common\Models\Configuration.cs` (RunnerMode enum), `src\NT8.Adapters\Strategies\NT8StrategyBase.cs` (RunnerActivationMode property, ResolveRunnerMode(), SubmitOrderToNT8() mode logic)
- **Action Required:** Verify Mode2RunnerOnly behavior in SIM with Qty=1 scenarios.
### DEC-20260711-06
- **ID:** DEC-20260711-06
- **Date:** 2026-07-11
- **Status:** accepted
- **Context:** The bar-driven `_tradeTaken` re-arm in `SimpleORBStrategy.OnBar()` was unreliable — it cleared `_tradeTaken` on the next bar after a trade intent, regardless of whether the NT8 position actually closed. This could allow overlapping entries if a new breakout bar arrived before the first trade was filled or stopped out. The original decision (DEC-20260429-01) accepted this for SIM but noted it must be fixed before live.
- **Decision:**
1. Added `OnPositionUpdate()` logic in `NT8StrategyBase` that detects when position goes flat (`MarketPosition.Flat` or `Quantity == 0`) and sends `clear_trade_taken` to the SDK strategy via `SetParameters()`.
2. Added `clear_trade_taken` handler in `SimpleORBStrategy.SetParameters()` that clears `_tradeTaken`, `_breakoutBarSeen`, and `_pendingBreakoutDirection` (but preserves `_dailyTradeCount`).
3. Added `EnableBarBasedRearm` parameter (default `false`) to both `NT8StrategyBase` and `SimpleORBNT8` to gate the legacy bar-driven re-arm for SIM-only mode.
4. The bar-driven re-arm in `SimpleORBStrategy.OnBar()` now only executes when `EnableBarBasedRearm == true`.
- **Consequences:** Position-close re-arm is now the primary mechanism for live trading (reliable, NT8-native). Bar-driven re-arm is opt-in via `EnableBarBasedRearm=true` for SIM/backtest scenarios. Backward compatible: defaults disable bar-driven re-arm, preserving existing behavior when explicitly enabled. Dual-deployed to NT8 Custom\Strategies\.
- **Related Files:** `src\NT8.Adapters\Strategies\NT8StrategyBase.cs` (EnableBarBasedRearm param, OnPositionUpdate clear_trade_taken), `src\NT8.Adapters\Strategies\SimpleORBNT8.cs` (EnableBarBasedRearm param), `src\NT8.Strategies\Examples\SimpleORBStrategy.cs` (_enableBarBasedRearm field, SetParameters handlers, gated bar-driven re-arm)
- **Action Required:** Verify in SIM with EnableBarBasedRearm=false — position close should clear _tradeTaken and allow new breakout; test EnableBarBasedRearm=true for SIM comparison.
### DEC-20260711-07
- **ID:** DEC-20260711-07
- **Date:** 2026-07-11
- **Status:** accepted
- **Context:** Short trades were being vetoed by the AVWAP slope check (slope > 0 = bullish regime) without a configurable parameter. This made the filter mandatory and untestable in isolation — users couldn't disable it for testing or strategies that intentionally trade counter-trend.
- **Decision:** Added `EnableShortTrendFilter` parameter (default `true`) to `NT8StrategyBase`, `SimpleORBNT8`, and `SimpleORBStrategy`. In `SimpleORBStrategy.OnBar()`, the short veto logic now checks this flag: when `true`, shorts are blocked if AVWAP slope > 0; when `false`, shorts are allowed regardless of regime. Long veto in bearish regime (slope < 0) remains always enforced. The flag is passed from NT8 adapter to SDK strategy via `StrategyContext.CustomData["EnableShortTrendFilter"]`.
- **Consequences:** Short trend filter is now configurable and testable. Backward compatible: default `true` preserves existing behavior. Dual-deployed to NT8 Custom\Strategies\.
- **Related Files:** `src\NT8.Adapters\Strategies\NT8StrategyBase.cs` (EnableShortTrendFilter param, BuildStrategyContext), `src\NT8.Adapters\Strategies\SimpleORBNT8.cs` (EnableShortTrendFilter param + ConfigureStrategyParameters), `src\NT8.Strategies\Examples\SimpleORBStrategy.cs` (_enableShortTrendFilter field, SetParameters, OnBar gating)
- **Action Required:** Verify in SIM with EnableShortTrendFilter=false — short trades should fire even in bullish regime; with EnableShortTrendFilter=true (default) — shorts blocked when AVWAP slope > 0.
### DEC-20260429-01
- **ID:** DEC-20260429-01
- **Date:** 2026-04-29
- **Status:** accepted
- **Context:** `MaxDailyTrades` re-arm logic in `SimpleORBStrategy.OnBar()` clears `_tradeTaken` and resets pullback confirmation state on the *next bar after a trade intent is generated*, not when the NT8 position actually closes. This is because `SimpleORBStrategy` is a pure C# core class with no visibility into NT8 position lifecycle — it only sees bars.
- **Decision:** Accept bar-based re-arm for SIM data collection phase. The daily loss limit (`DailyLossLimit`) and `MaxOpenPositions` in the NT8 adapter act as the live position guard, preventing overlapping entries from causing runaway risk in practice.
- **Consequences:** In a fast market, a second trade intent could be generated while the first position is still open if the next breakout bar arrives before NT8 has filled or stopped the first trade. This is acceptable in SIM but must be addressed before live trading. The fix is to wire re-arm to a position-close callback in `NT8StrategyBase` (Sprint 3/4 concern).
- **Related Files:** `src\NT8.Strategies\Examples\SimpleORBStrategy.cs`, `src\NT8.Adapters\Strategies\NT8StrategyBase.cs`
- **Action Required (pre-live):** Implement position-close-driven re-arm in `NT8StrategyBase` before going live with `MaxDailyTrades > 1`.
### DEC-20260711-08
- **ID:** DEC-20260711-08
- **Date:** 2026-07-11
- **Status:** accepted
- **Context:** The strategy had no awareness of CME holidays, meaning it would attempt to trade on days when the market is closed (New Year's Day, MLK Day, Presidents Day, Good Friday, Memorial Day, Independence Day, Labor Day, Thanksgiving, Christmas) or has early closes (day after Thanksgiving, Christmas Eve, New Year's Eve). This caused errors and wasted compute on non-trading days.
- **Decision:** Implemented `CmeHolidayCalendar` with full CME holiday schedule including observed dates (weekend -> nearest weekday). Added `EnableCMEHolidayGuard` parameter (default `true`) to `NT8StrategyBase`, `SimpleORBNT8`, and `SimpleORBStrategy`. In `NT8StrategyBase.OnBarUpdate()`, checks `CmeHolidayCalendar.IsHoliday(Time[0].Date)` and skips bar processing. In `SimpleORBStrategy.OnBar()`, checks `CmeHolidayCalendar.ShouldSkipOrbWindow(bar.Time.Date)` and returns null. Holiday list: New Year's Day (Jan 1), MLK Jr. Day (3rd Mon Jan), Presidents Day (3rd Mon Feb), Good Friday (computed via Easter), Memorial Day (last Mon May), Independence Day (Jul 4), Labor Day (1st Mon Sep), Thanksgiving (4th Thu Nov), Christmas (Dec 25). Early-close days also tracked via `IsEarlyClose()`.
- **Consequences:** Strategy now automatically skips non-trading days. Backward compatible: default `true` preserves new behavior; can disable for testing. Dual-deployed to NT8 Custom\Strategies\.
- **Related Files:** `src\NT8.Core\Calendar\CmeHolidayCalendar.cs` (new), `src\NT8.Adapters\Strategies\NT8StrategyBase.cs` (EnableCMEHolidayGuard, OnBarUpdate), `src\NT8.Strategies\Examples\SimpleORBStrategy.cs` (EnableCMEHolidayGuard, OnBar), `src\NT8.Adapters\Strategies\SimpleORBNT8.cs` (EnableCMEHolidayGuard)
- **Action Required:** Verify in SIM — session log should show "[SDK] CME Holiday Guard: skipping bar YYYY-MM-DD (holiday)" on CME holidays; strategy should not generate signals on those days.
### DEC-20260711-09
- **ID:** DEC-20260711-09
- **Date:** 2026-07-11
- **Status:** accepted
- **Context:** The runner trailing stop used a fixed `RunnerTrailTicks` (default 12-20 ticks) regardless of market volatility. In quiet markets this was too wide (giving back profits); in volatile markets too tight (premature stop-outs). Need ATR-based trailing that adapts to actual market conditions.
- **Decision:** Added ATR-based trailing stop with 5 new parameters: `EnableATRTrailing` (default `false`), `ATRTrailingPeriod` (14), `ATRTrailingMultiplier` (2.0), `ATRTrailingMinTicks` (8), `ATRTrailingMaxTicks` (60). When `EnableATRTrailing=true` and `CurrentBars[0] >= ATRTrailingPeriod`, computes `trailTicks = clamp(round(ATR(Close, ATRTrailingPeriod)[0] / TickSize * ATRTrailingMultiplier), ATRTrailingMinTicks, ATRTrailingMaxTicks)` and calls `SetTrailStop` with this dynamic value instead of fixed `RunnerTrailTicks`. Added logging: `[SDK] ATR Trail: ATR={X}ticks x {Y} = {Z}ticks (clamped {Min}-{Max})`. When disabled, falls back to fixed `RunnerTrailTicks`.
- **Consequences:** Trailing stop now scales with volatility — tighter in quiet markets, wider in volatile. Backward compatible: `EnableATRTrailing=false` preserves fixed tick trail. Dual-deployed to NT8 Custom\Strategies\.
- **Related Files:** `src\NT8.Adapters\Strategies\NT8StrategyBase.cs` (5 params, ATR trailing logic in SubmitOrderToNT8, logging), `src\NT8.Strategies\Examples\SimpleORBStrategy.cs` (_enableAtrTrailing field, SetParameters, ATRTrailingPeriod/Multiplier/MinTicks/MaxTicks properties), `src\NT8.Adapters\Strategies\SimpleORBNT8.cs` (EnableATRTrailing, ATRTrailingPeriod/Multiplier/MinTicks/MaxTicks params + ConfigureStrategyParameters)
- **Action Required:** Verify in SIM with EnableATRTrailing=true — session log should show [SDK] ATR Trail line with computed value inside 8-60t; chart trail stop should sit at ATR distance, not fixed 20t.