# NT8-SDK Kilocode Runbook — Sprint 3 **Updated:** 2026-05-04 | Contains: all Sprint 3 task prompts in execution order. **How to use:** Current task prompt is always staged in `NEXT_PROMPT.md`. Find the next task here by ID. > **Pre-flight (do once before starting Sprint 3):** > 1. `Ctrl+Shift+B` → expect `✅ All checks passed!` > 2. `dotnet test tests/NT8.Core.Tests/NT8.Core.Tests.csproj --verbosity minimal` → 240+ passing > If either fails — fix the baseline first. Do not start until both are clean. --- ## TASK-06a — Runner Mode Architecture **Why:** The current `useRunner = Qty >= 2` check is architecturally wrong. It couples position management to capital sizing and means the runner NEVER fires at responsible ATR-based stops. Runner should be a position management MODE, not a quantity gate. **Spec reference:** NT8_SDK_Master_Document_v6_Final.docx — Section 6.1 --- ``` Read docs/00-governance/active_work.md and .kilocode/rules/project_context.md before starting. Implement TASK-06a: Runner Mode Architecture redesign in NT8StrategyBase. WHAT TO BUILD: 1. Add a RunnerMode enum to the appropriate models file in src/NT8.Core/Common/ or src/NT8.Core/Risk/: public enum RunnerMode { Auto, Mode1DualLeg, Mode2RunnerOnly, Mode3ScalerOnly, Disabled } C# 5.0: no expression-bodied members, no $"" string interpolation, no ?. operator. 2. In NT8StrategyBase.cs (src/NT8.Adapters/Strategies/NT8StrategyBase.cs): a. Add [NinjaScriptProperty] public RunnerMode RunnerActivationMode with default = RunnerMode.Auto b. Add private method: private RunnerMode ResolveRunnerMode(RunnerMode configured, int qty) Logic: if (configured == RunnerMode.Disabled) return RunnerMode.Disabled; if (configured == RunnerMode.Mode1DualLeg) return RunnerMode.Mode1DualLeg; if (configured == RunnerMode.Mode2RunnerOnly) return RunnerMode.Mode2RunnerOnly; if (configured == RunnerMode.Mode3ScalerOnly) return RunnerMode.Mode3ScalerOnly; // Auto: resolve based on qty if (qty >= 2) return RunnerMode.Mode1DualLeg; return RunnerMode.Mode2RunnerOnly; c. In SubmitOrderToNT8() (or wherever entry/stop/target logic lives), REPLACE: bool useRunner = EnableRunner && request.Quantity >= 2; WITH: RunnerMode resolvedMode = ResolveRunnerMode(RunnerActivationMode, request.Quantity); d. Implement mode behaviour: - Mode1DualLeg: scalerQty = request.Quantity - 1, runnerQty = 1 SetStopLoss(scalerSignal), SetProfitTarget(scalerSignal, TargetTicks), EnterLong(scalerQty, scalerSignal) SetTrailStop(runnerSignal, CalculationMode.Ticks, RunnerTrailTicks, false), EnterLong(1, runnerSignal) - Mode2RunnerOnly: full qty gets trail stop only, no fixed target SetTrailStop(runnerSignal, CalculationMode.Ticks, RunnerTrailTicks, false), EnterLong(qty, runnerSignal) - Mode3ScalerOnly: full qty gets fixed target, no runner SetStopLoss(scalerSignal), SetProfitTarget(scalerSignal, TargetTicks), EnterLong(qty, scalerSignal) - Disabled: original single-leg behaviour, no runner e. Log the resolved mode: Print(string.Format("[SDK] Runner mode resolved: {0} (Qty={1})", resolvedMode, request.Quantity)); 3. DUAL-DEPLOY: copy the updated NT8StrategyBase.cs to: C:\Users\billy\Documents\NinjaTrader 8\bin\Custom\Strategies\NT8StrategyBase.cs CONSTRAINTS: - C# 5.0 only: string.Format() not $"", explicit null checks not ?., full block syntax not => - Do NOT change constructor, InitializeSdkComponents(), or any risk/sizing logic - Do NOT modify any test files unless adding new tests for RunnerMode - SetStopLoss/SetProfitTarget MUST be called before EnterLong/EnterShort on every branch VERIFICATION: - .\verify-build.bat must show ✅ All checks passed! - dotnet test must pass with 0 failures - Tell me exactly what lines you changed and in which files WHEN DONE: Follow .kilocode/rules/self_learning_loop.md completely (all 6 steps). ``` --- ## TASK-06b — ATR Dynamic Stop **Why:** Fixed 8-tick stop on NQ ignores market volatility. ATR=20 ticks means 8 ticks gets stopped out by normal noise before the move develops. Dynamic stop sizes the stop to actual market conditions. **Spec reference:** NT8_SDK_Master_Document_v6_Final.docx — Section 6.2 --- ``` Read docs/00-governance/active_work.md and SPRINT_BOARD.md before starting. Implement TASK-06b: ATR-based dynamic stop in NT8StrategyBase and SimpleORBNT8. WHAT TO BUILD: 1. In NT8StrategyBase.cs (src/NT8.Adapters/Strategies/NT8StrategyBase.cs): a. Add these [NinjaScriptProperty] parameters: - public bool EnableDynamicStop (default = false) - public int AtrPeriod (default = 14) - public double AtrMultiplier (default = 1.5) - public int MinStopTicks (default = 12) - public int MaxStopTicks (default = 50) b. In OnStateChange() → State.Configure: register ATR indicator series: AddDataSeries(Data.BarsPeriodType.Minute, 5); // only if not already present // ATR is accessed via ATR(Close, AtrPeriod)[0] in NinjaScript c. In SubmitOrderToNT8() or the intent processing method, BEFORE calling CalculateSize(): if (EnableDynamicStop && CurrentBars[0] >= AtrPeriod) { double atrValue = ATR(Close, AtrPeriod)[0]; int dynStop = (int)System.Math.Round(atrValue / TickSize * AtrMultiplier); dynStop = System.Math.Max(MinStopTicks, System.Math.Min(MaxStopTicks, dynStop)); intent.StopTicks = dynStop; // Recalculate target if using fixed R:R ratio (TargetTicks = StopTicks * RRRatio) // Pass ATR to context for Factor 3 and TrailingStopManager: // context.CustomData["current_atr"] = atrValue / TickSize; // in ticks } d. Log: Print(string.Format("[SDK] Dynamic stop: ATR={0:F1}t x {1} = {2}t (${3})", atrValue/TickSize, AtrMultiplier, intent.StopTicks, intent.StopTicks * 5)); 2. In SimpleORBNT8.cs (src/NT8.Adapters/Strategies/SimpleORBNT8.cs): - Verify EnableDynamicStop is exposed as a parameter (it inherits from NT8StrategyBase, so likely automatic) - If it needs to be explicitly exposed, add it to the NinjaScript parameter block 3. DUAL-DEPLOY both files to C:\Users\billy\Documents\NinjaTrader 8\bin\Custom\Strategies\ CONSTRAINTS: - C# 5.0 only - Do NOT change RiskConfig, SizingConfig, or any test files - If ATR series is not available yet (CurrentBars[0] < AtrPeriod), skip dynamic stop and use intent.StopTicks as-is VERIFICATION: - .\verify-build.bat must show ✅ All checks passed! - dotnet test must pass with 0 failures WHEN DONE: Follow .kilocode/rules/self_learning_loop.md completely (all 6 steps). ``` --- ## GAP-019 — Portfolio Heat Tier 3.5 **Why:** Without a heat limit, three open positions can each risk 2% of account simultaneously = 6% aggregate. Heat caps total open risk as a % of account balance. Reference: Section 3.2 of master doc. --- ``` Read docs/00-governance/active_work.md and SPRINT_BOARD.md before starting. Implement GAP-019: Portfolio Heat — Tier 3.5 risk layer in AdvancedRiskManager. WHAT TO BUILD: 1. In the appropriate RiskModels or RiskConfig class (src/NT8.Core/Risk/): - Add MaxHeatPct property (double, default = 3.0) to RiskConfig or AdvancedRiskConfig - Add AccountBalance property (double) to whatever context object is passed to risk validation 2. In AdvancedRiskManager.cs (src/NT8.Core/Risk/AdvancedRiskManager.cs): a. Add private method ValidatePortfolioHeat(OrderIntent intent, double accountBalance): - Calculate TotalOpenRisk = sum of (StopTicks * TickValue * Qty) across all open positions (use existing open position tracking, or accept it as a parameter) - Calculate NewTradeRisk = intent.StopTicks * tickValue * intendedQty - Calculate HeatPct = (TotalOpenRisk + NewTradeRisk) / accountBalance * 100.0 - If HeatPct > MaxHeatPct: return RiskDecision.Reject with reason: string.Format("Portfolio heat {0:F1}% exceeds limit {1:F1}%", HeatPct, MaxHeatPct) - Otherwise: return RiskDecision.Approve b. Call ValidatePortfolioHeat() as the last check in ValidateOrder(), AFTER Tier 3 cross-exposure check c. Log the heat check: Print(string.Format("[SDK] Heat check: {0:F1}% of {1:F1}% limit", HeatPct, MaxHeatPct)); 3. Add unit test in tests/NT8.Core.Tests/Risk/ verifying: - Heat limit exceeded → RiskDecision.Reject - Heat within limit → RiskDecision.Approve - AccountBalance = 0 edge case handled (return Approve or skip check) CONSTRAINTS: - C# 5.0 only - Do not change Tier 1, 2, or 3 logic — only ADD Tier 3.5 after them - TickValue for NQ = 5.0, for MNQ = 0.50 — use a constant or pass via config VERIFICATION: - .\verify-build.bat ✅ - dotnet test ✅ with new heat tests passing WHEN DONE: Follow .kilocode/rules/self_learning_loop.md completely (all 6 steps). ``` --- ## GAP-003 — RiskPerTrade ≤ MaxTradeRisk Assertion --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-003: Add startup assertion that RiskPerTrade <= MaxTradeRisk in BasicRiskManager. WHAT TO BUILD: In BasicRiskManager.cs (src/NT8.Core/Risk/BasicRiskManager.cs): 1. In the constructor or Initialize() method, immediately after receiving RiskConfig: if (riskConfig.RiskPerTrade > riskConfig.MaxTradeRisk) { throw new System.ArgumentException(string.Format( "Invalid RiskConfig: RiskPerTrade ({0}) cannot exceed MaxTradeRisk ({1}). " + "Increase MaxTradeRisk or reduce RiskPerTrade.", riskConfig.RiskPerTrade, riskConfig.MaxTradeRisk)); } 2. Add unit test in tests/NT8.Core.Tests/Risk/ verifying: - RiskPerTrade > MaxTradeRisk throws ArgumentException - RiskPerTrade == MaxTradeRisk is accepted (no throw) - RiskPerTrade < MaxTradeRisk is accepted (no throw) CONSTRAINTS: C# 5.0 only. Touch only BasicRiskManager.cs and its test file. VERIFICATION: .\verify-build.bat ✅ | dotnet test ✅ WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-004 — orbRangeTicks Hardcoded 0.0 Fix --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-004: Fix orbRangeTicks hardcoded 0.0 in DailyBarContext / SimpleORBStrategy. WHAT TO BUILD: 1. In SimpleORBStrategy.cs (src/NT8.Strategies/Examples/SimpleORBStrategy.cs): - Find where DailyBarContext is constructed and orbRangeTicks is set - Replace the hardcoded 0.0 with: (int)System.Math.Round((orbHigh - orbLow) / tickSize) - Ensure orbHigh, orbLow, and tickSize are available at that point in the code 2. In SimpleORBNT8.cs (src/NT8.Adapters/Strategies/SimpleORBNT8.cs): - Confirm tickSize (TickSize from NT8) is being passed to SimpleORBStrategy or available in context - If not wired: pass TickSize as a parameter when constructing StrategyContext or DailyBarContext 3. DUAL-DEPLOY SimpleORBNT8.cs to NT8 Custom\Strategies\ CONSTRAINTS: C# 5.0. Touch only these two files plus any unit tests. VERIFICATION: .\verify-build.bat ✅ | dotnet test ✅ WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-005 — GetRiskStatus() Returns Live Config Value --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-005: GetRiskStatus() must return the actual registered DailyLossLimit from injected RiskConfig. WHAT TO BUILD: In BasicRiskManager.cs (src/NT8.Core/Risk/BasicRiskManager.cs): 1. Find GetRiskStatus() method 2. Replace any hardcoded limit value with the stored _riskConfig.DailyLossLimit (or equivalent field) 3. Confirm all numeric fields in the returned status come from _riskConfig, not constants Add or update unit test: inject a RiskConfig with a specific DailyLossLimit value, call GetRiskStatus(), assert the returned limit field equals the injected value. CONSTRAINTS: C# 5.0. Touch only BasicRiskManager.cs and its test file. VERIFICATION: .\verify-build.bat ✅ | dotnet test ✅ WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-006 — Position-Close-Driven _tradeTaken Re-arm --- ``` Read docs/00-governance/active_work.md and docs/00-governance/decisions.md (DEC-20260429-01) before starting. Implement GAP-006: Wire _tradeTaken re-arm to position-close callback in NT8StrategyBase. CONTEXT: DEC-20260429-01 documented that _tradeTaken is currently re-armed on the next bar after a trade intent, not when the NT8 position actually closes. This is acceptable in SIM but must be fixed before live trading with MaxDailyTrades > 1. WHAT TO BUILD: In NT8StrategyBase.cs (src/NT8.Adapters/Strategies/NT8StrategyBase.cs): 1. Find or add an OnPositionUpdate override: protected override void OnPositionUpdate(Cbi.Position position, double averagePrice, int quantity, Cbi.MarketPosition marketPosition) NOTE: Verify exact NT8 signature at https://developer.ninjatrader.com/docs/desktop before implementing. 2. In OnPositionUpdate, when the position goes flat (MarketPosition.Flat or quantity == 0): _tradeTaken = false; if (EnableVerboseLogging) Print("[SDK] Position closed — _tradeTaken reset via OnPositionUpdate"); 3. Remove or gate the old bar-based re-arm logic (the increment/reset tied to bar counting) - Gate with a parameter: AddParameterBool EnableBarBasedRearm default=false - Or remove entirely if position-close re-arm is sufficient 4. Record the decision: append to docs/00-governance/decisions.md: DEC-20260504-01: _tradeTaken re-arm switched from bar-driven to position-close-driven (OnPositionUpdate). Bar-driven code removed. This is required for MaxDailyTrades > 1 in live trading. 5. DUAL-DEPLOY NT8StrategyBase.cs to NT8 Custom\Strategies\ CONSTRAINTS: C# 5.0. Verify OnPositionUpdate signature against NT8 docs before writing it. VERIFICATION: .\verify-build.bat ✅ | dotnet test ✅ WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-010 — Short-Side Regime Filter Gate --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-010: Gate short-side signals behind a regime filter in SimpleORBStrategy. WHAT TO BUILD: 1. In SimpleORBStrategy.cs (src/NT8.Strategies/Examples/SimpleORBStrategy.cs): a. Add a parameter EnableShortSide (bool, default = false) to StrategyConfig or as a direct parameter b. In OnBar() or wherever short-side signals are generated: if (!EnableShortSide) { /* skip short signal, return null intent */ } c. If EnableShortSide is true, add regime check: if (regime.TrendDirection == TrendDirection.Bullish && riskMode == RiskMode.Normal) { /* block short, log: "[SDK] Short blocked: bullish trend regime + normal risk mode" */ } 2. In SimpleORBNT8.cs (src/NT8.Adapters/Strategies/SimpleORBNT8.cs): a. Expose EnableShortSide as a [NinjaScriptProperty] (default = false) b. Pass to SimpleORBStrategy at construction 3. DUAL-DEPLOY SimpleORBNT8.cs to NT8 Custom\Strategies\ CONSTRAINTS: C# 5.0. Only touch SimpleORBStrategy.cs and SimpleORBNT8.cs (+ test file). VERIFICATION: .\verify-build.bat ✅ | dotnet test ✅ including regime filter tests WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-008 — CME Holiday Awareness --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-008: Add static CME holiday HashSet to SessionManager. WHAT TO BUILD: In SessionManager.cs (src/NT8.Core/MarketData/SessionManager.cs): 1. Add a private static readonly HashSet _cmeHolidays containing these dates (use new DateTime(year, month, day) for each, no times): 2025: Jan 1, Jan 20, Feb 17, Apr 18, May 26, Jun 19, Jul 4, Sep 1, Nov 27, Dec 25 2026: Jan 1, Jan 19, Feb 16, Apr 3, May 25, Jun 19, Jul 3, Sep 7, Nov 26, Dec 25 2. In IsRegularTradingHours() or the relevant session check method: DateTime today = new DateTime(time.Year, time.Month, time.Day); if (_cmeHolidays.Contains(today)) return false; 3. Add unit tests verifying: - Dec 25, 2025 returns false - Jan 1, 2026 returns false - A normal trading day (e.g., Jan 7, 2026) still returns true within RTH hours CONSTRAINTS: C# 5.0. Touch only SessionManager.cs and its test file. VERIFICATION: .\verify-build.bat ✅ | dotnet test ✅ WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-009 — ATRTrailing Real ATR Wiring --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-009: Replace ATR proxy in TrailingStopManager with real ATR from context. WHAT TO BUILD: In TrailingStopManager.cs (src/NT8.Core/Execution/TrailingStopManager.cs): 1. Find where estimatedAtr = avgFillPrice * 0.005m (or similar proxy) is calculated 2. Replace with: double realAtr = 0.0; if (context != null && context.CustomData.ContainsKey("current_atr")) realAtr = (double)context.CustomData["current_atr"]; // value is in ticks double atrToUse = realAtr > 0.0 ? realAtr : avgFillPrice * 0.005 / tickValue; // fallback if (realAtr <= 0.0) logger.LogWarning("[SDK] TrailingStop: using ATR proxy — wire current_atr to context for accuracy"); 3. Apply same fix to Chandelier mode CONSTRAINTS: C# 5.0. Touch only TrailingStopManager.cs and its test file. VERIFICATION: .\verify-build.bat ✅ | dotnet test ✅ WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-011 — Gitea CI Pipeline --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-011: Create Gitea CI workflow that builds and tests on every push. WHAT TO BUILD: Create .gitea/workflows/build.yml with this content (adapt as needed for the Gitea runner): name: Build and Test on: push: branches: [main, 'sprint-*'] pull_request: branches: [main] jobs: build: runs-on: windows-latest steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v3 with: dotnet-version: '4.8.x' - name: Restore dependencies run: dotnet restore NT8-SDK.sln - name: Build run: dotnet build NT8-SDK.sln --configuration Release --no-restore - name: Test run: dotnet test tests/NT8.Core.Tests/NT8.Core.Tests.csproj --no-build --verbosity minimal NOTE: If the Gitea runner uses a different OS tag or .NET version, adjust accordingly. Verify the workflow syntax is correct for the Gitea Actions runner version on git.thehussains.org. VERIFICATION: Push a test commit and confirm the CI badge shows on the Gitea repo page. WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-022 — Scenario Tests --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-022: Write 8 scenario tests covering edge-case behaviors. Reference: NT8_SDK_Master_Document_v6_Final.docx — Section 11.1 CREATE: tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs Write tests for these 8 scenarios: 1. HIGH_VOLATILITY_DAY: ATR ratio > 1.5 → Factor 3 (VolatilityRegime) scores 0.3 → grade likely F or D → no trade taken 2. NEWS_DAY_REDUCED_SIZE: SessionManager flags high-impact event → if ReducedSizeOnNewsDay: MaxContracts halved 3. LOW_LIQUIDITY: LiquidityMonitor spread exceeds threshold → Factor 5 (ExecutionQuality) drops to 0.4 → grade degrades 4. PARTIAL_FILL: NT8 partial fill on scaler leg → OMS transitions to PARTIALLY_FILLED → no duplicate entry 5. MID_TRADE_DISCONNECT: _connectionLost=true while position open → no new orders → position retained 6. PRE_ENTRY_DISCONNECT: _connectionLost fires between signal approval and order submission → order not submitted 7. DAILY_LOSS_HALT: DailyPnL hits DailyLossLimit → HALT fires → no new entries rest of session 8. CIRCUIT_BREAKER_OPEN: 3 consecutive rejections → CB opens → ShouldAllowOrder() returns false Each test should: - Set up the relevant state using mocks or test doubles - Trigger the scenario - Assert the expected system response (rejection, halt, no order, etc.) - Be independent (no shared state between tests) CONSTRAINTS: C# 5.0. Only create new test file — do not modify existing source files. If a scenario requires a missing interface or mock, note it as a TODO comment. VERIFICATION: .\verify-build.bat ✅ | dotnet test ✅ with all 8 new tests passing WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ``` --- ## GAP-007 — Walk-Forward Test Documentation --- ``` Read docs/00-governance/active_work.md before starting. Implement GAP-007: Document the walk-forward test procedure and record the acceptance threshold. WHAT TO BUILD: 1. Update docs/02-runbooks/backtest_review_workflow.md with a new section: ## Walk-Forward Validation Procedure - In-sample period: Jan 1, 2024 – Sep 30, 2025 (use for parameter selection) - Walk-forward period: Oct 1, 2025 – Mar 31, 2026 (never seen during optimization) - Tool: NT8 Strategy Analyzer → Optimization tab → Walk Forward - Acceptance threshold: WF Profit Factor ≥ 60% of in-sample Profit Factor Example: In-sample PF = 3.0 → WF PF must be ≥ 1.8 - If WF PF < 60% of in-sample: parameters are overfit — must re-evaluate - Parameters to test: MinTradeGrade, AtrMultiplier, RunnerTrailTicks, DailyLossLimit 2. Append to docs/00-governance/decisions.md: ### DEC-20260504-02 - ID: DEC-20260504-02 - Date: 2026-05-04 - Status: accepted - Context: All backtests to date are in-sample (Jan–Mar 2026 optimization window). Going live on in-sample parameters without OOS validation is a model risk. - Decision: Walk-forward acceptance threshold set at WF PF ≥ 60% of in-sample PF. No live capital deployed until this threshold is met on the Oct 2025–Mar 2026 OOS period. - Consequences: Adds ~1 week to Sprint 3 timeline for running and documenting WF results. - Related Files: docs/02-runbooks/backtest_review_workflow.md CONSTRAINTS: Documentation only — no source code changes. VERIFICATION: Files exist and contain the above content. WHEN DONE: Follow .kilocode/rules/self_learning_loop.md (all 6 steps). ```