# 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-20260713-01 - **ID:** DEC-20260713-01 - **Date:** 2026-07-13 - **Status:** accepted - **Context:** July 11 sprint executed 11 tasks from old pre-v6.1 queue (TASK-06a, TASK-06b, GAP-003/004/005/006/008/009/010/011/019) but skipped v6.1-mandated TASK-00a/00b (provenance + chart diagnostics). HEAD left broken (duplicate enum/property). Sprint 2.6 executed repair + v6.1 instrumentation in strict order. - **Decision:** Accept July 11 work as valid Sprint 2 substance; Sprint 2.6 completes v6.1 instrumentation. Next sprint = Sprint 3 (Second Strategy + MNQ). - **Consequences:** Sprint numbering aligned with v6.1. Governance artifacts now match code reality. SIM gate requires all 5 Sprint 2.6 tasks + governance reconciliation before live. - **Related Files:** `docs/00-governance/current_status.md`, `SPRINT_BOARD.md`, `KILOCODE_RUNBOOK.md`, `docs/00-governance/decisions.md`, `docs/00-governance/active_work.md`, `docs/INDEX.md`, `docs/archive/master_docs/NT8_SDK_Master_Document_v6.1_Complete.docx`, `docs/archive/master_docs/NT8_SDK_Operator_Runbook_v1.0.docx` - **Action Required:** All Sprint 2.6 governance artifacts committed. Sprint 3 queue active in KILOCODE_RUNBOOK.md. SIM gate remains blocked until governance reconciliation complete. ### 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. ### DEC-20260713-01 - **ID:** DEC-20260713-01 - **Date:** 2026-07-13 - **Status:** superseded - **Context:** Sprint 2.6 (July 11) completed all 5 technical tasks (TASK-FIX-01, TASK-00a, TASK-00b, TASK-06c, GAP-024) and build/tests passed (492 tests). However, the v6.1 Master Document and Operator Runbook (dated July 13) were not committed to the repository, and Sprint artifacts (SPRINT_BOARD.md, KILOCODE_RUNBOOK.md, current_status.md) still reflected Sprint 2.6 state. Governance required reconciliation: commit v6.1 docs to repo archive, promote Sprint 4 backlog to Sprint 3 queue, rewrite sprint artifacts for Sprint 3 (Second Strategy + MNQ Prep), and log this reconciliation decision. - **Decision:** 1. Committed NT8_SDK_Master_Document_v6.1_Complete.docx and NT8_SDK_Operator_Runbook_v1.0.docx to docs/archive/master_docs/ 2. Rewrote SPRINT_BOARD.md: all 6 Sprint 2.6 tasks marked COMPLETED; Sprint 4 backlog promoted to Sprint 3 queue (TASK-06a Runner Mode, TASK-06b ATR Dynamic Stop, GAP-019 Portfolio Heat, GAP-003 RiskPerTrade Assertion, GAP-004 orbRangeTicks Fix, GAP-005 GetRiskStatus, GAP-006 Position Close Re-arm, GAP-010 Short Regime Filter, GAP-008 CME Holiday, GAP-009 ATR Trailing, GAP-011 Gitea CI, GAP-022 Scenario Tests, GAP-007 Walk-Forward Docs) 3. Rewrote KILOCODE_RUNBOOK.md for Sprint 3 (Second Strategy + MNQ Prep) with TASK-06a, GAP-013, GAP-015, GAP-014, MNQ-001, MNQ-002 as the Sprint 3 queue 4. Logged DEC-20260713-01 in decisions.md (this entry) 5. Updated current_status.md to Sprint 3 handoff state - **Consequences:** Sprint 2.6 governance fully reconciled. Sprint 3 queue defined and staged. SIM Gate remains blocked until governance reconciliation complete (now satisfied). All governance files consistent. Build and 492 tests still pass. - **Related Files:** `docs/archive/master_docs/NT8_SDK_Master_Document_v6.1_Complete.docx`, `docs/archive/master_docs/NT8_SDK_Operator_Runbook_v1.0.docx`, `SPRINT_BOARD.md`, `KILOCODE_RUNBOOK.md`, `docs/00-governance/current_status.md`, `docs/00-governance/decisions.md` - **Action Required:** Verify .\verify-build.bat ✅ | dotnet test ✅ (492 tests) | git status clean ### DEC-20260713-02 - **ID:** DEC-20260713-02 - **Date:** 2026-07-13 - **Status:** accepted - **Context:** The 2026-07-13 reconciliation (DEC-20260713-01) incorrectly re-queued 12 implemented tasks, archived master docs, and staged TASK-06a as next action. Code greps confirm all 12 tasks already implemented in code (verified by grep on ResolveRunnerMode, EnableDynamicStop, orbRangeTicks, CmeHolidayCalendar, EnableShortTrendFilter, GetRiskStatus, OnPositionUpdate, clear_trade_taken, ValidatePortfolioHeat, RiskPerTrade). - **Decision:** Restore governance to match code reality. 1. Move 12 July 11 tasks back to COMPLETED with 2026-07-11 dates in SPRINT_BOARD.md. 2. Sprint 2.7 queue = TASK-00a (reissued), GAP-024 data layer, GAP-022 scenario tests, GAP-025 diagnosis. 3. Move master docs from `docs/archive/master_docs/` → `docs/` + `docs/02-runbooks/`. 3. Overwrite NEXT_PROMPT.md with TASK-00a reissue (grep-verifiable acceptance). 4. Log this decision as DEC-20260713-02 superseding DEC-20260713-01. 5. Update current_status.md for Sprint 2.7. - **Consequences:** Sprint numbering realigned (2.7 truth reconciliation before 3). Governance artifacts now match code greps. NEXT_PROMPT.md stages TASK-00a reissue. DEC-20260713-01 superseded by this entry. - **Related Files:** `SPRINT_BOARD.md`, `KILOCODE_RUNBOOK.md`, `NEXT_PROMPT.md`, `docs/00-governance/current_status.md`, `docs/00-governance/decisions.md`, `docs/archive/master_docs/` (to be moved) - **Action Required:** Complete TASK-GOV-02 (governance reconciliation), then TASK-00a reissue. ### DEC-20260714-01 - **ID:** DEC-20260714-01 - **Date:** 2026-07-14 - **Status:** accepted - **Context:** `ComputeConfigHash()` correctly fingerprints NinjaScript parameters, but a mid-gate recompile or redeploy can change executable code while preserving every parameter value and therefore the same config hash. - **Decision:** Persist a compiled-code stamp in all gate-relevant provenance. The stamp is the running assembly version plus `ManifestModule.ModuleVersionId`; it is written to session provenance, each trade JSONL record, settings exports, and the SimpleORB strategy snapshot. Each real-time signal also writes its TestMode/LIVE MODE state to the session file log. - **Consequences:** Parameter drift and code drift are distinguishable without relying on a manually maintained git SHA. The Gate Run #2 procedure must archive both `ConfigHash` and `CodeVersion`, and it forbids dual-deploys after the configuration freeze. - **Related Files:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `docs/00-governance/patterns_and_antipatterns.md`, `SPRINT_BOARD.md`, `NEXT_PROMPT.md`. - **Action Required:** Deploy the cleanup source, compile it in NinjaTrader, then record `DEC-GATE2-CONFIG` before starting the gate.