diff --git a/KILOCODE_RUNBOOK.md b/KILOCODE_RUNBOOK.md index f7c13ff..17694e3 100644 --- a/KILOCODE_RUNBOOK.md +++ b/KILOCODE_RUNBOOK.md @@ -1,538 +1,45 @@ -# 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). -``` +# NT8 SDK Operator and Engineering Runbook +**Current state:** Sprint 2.7 cleanup complete; Gate Run #2 is waiting for the human configuration freeze. +**Canonical current state:** `SPRINT_BOARD.md` and `docs/00-governance/current_status.md`. + +## Completed gate-enabling work + +| Item | State | Evidence | +|---|---|---| +| TASK-GOV-02 | Complete | July 11 historical record restored; master documents are at `docs/` and `docs/02-runbooks/`; DEC-20260713-02 records the correction. | +| TASK-00a / GAP-024 | Complete | Session/trade provenance, SHA256 parameter hash, exact session tags, settings export, and TestMode state are implemented. | +| GAP-022 | Partial by design | Five executable scenario assertions pass. Three scenarios are deferred behind missing source seams; no fake tests were added. | +| GAP-029 | Complete | Session, trade, settings, and strategy snapshot provenance carry an assembly-version/module-MVID code stamp. | + +## RB-4.1 — Gate Run #2 configuration freeze + +1. Deploy the verified cleanup source to NinjaTrader Custom\Strategies and compile in the NinjaScript Editor. +2. Configure SimSimple ORB: + - `EnableDynamicStop=TRUE` + - `RunnerActivationMode=Auto` + - `RegimeGate=GradePenalty` + - `MinTradeGrade=A` + - `MaxDailyTrades=1` + - `TestMode=FALSE` + - `EnableFileLogging=TRUE` + - `EnableVerboseLogging=TRUE` + - `LogDirectory=C:\\Users\\billy\\Documents\\NinjaTrader 8\\log\\nt8-sdk` +3. Export settings and archive the `ConfigHash` and `CodeVersion`. +4. Record `DEC-GATE2-CONFIG` with the frozen values and gate start date. +5. Once the gate begins, do not dual-deploy to the gate machine. Archive daily provenance/trade files and provide weekly heartbeats. + +## Parallel branch-only work during the gate + +### GAP-025 — Runner No-Fill Anomaly Diagnosis +- Add diagnostic-only logging for runner order and execution state. +- Capture a SIM fill sequence and diagnose the no-fill condition. +- This blocks live promotion, not the SIM gate. + +### GAP-022-FOLLOWUP — Connection-State Test Seam +- Add an injectable connection-state seam around `NT8StrategyBase`. +- Implement the three deferred scenarios only after the required calendar/sizing and connection seams exist. + +## Post-gate sequence +1. Produce an automated Gate Report from `trades_*.jsonl` and provenance artifacts. +2. Record the ruling in `docs/00-governance/decisions.md`. +3. A pass enables GAP-007 walk-forward validation, then Sprint 3 work. diff --git a/NEXT_PROMPT.md b/NEXT_PROMPT.md index c93e472..b712d23 100644 --- a/NEXT_PROMPT.md +++ b/NEXT_PROMPT.md @@ -1,37 +1,23 @@ -# NEXT: GAP-011 — Gitea CI Pipeline -# Staged: 2026-07-11 -# Sprint: 3 | Estimated: ~2 hrs -# ───────────────────────────────────────────────────────────────── -# Copy everything below this line and paste into Kilocode chat. +# NEXT: RB-4.1 — Gate Run #2 Configuration Freeze +# Staged: 2026-07-14 +# Sprint: 2.7 | Estimated: ~20 min operator work # ───────────────────────────────────────────────────────────────── -Read docs/00-governance/active_work.md and SPRINT_BOARD.md before starting. +This is a **human operator procedure**, not a coding task. Do not change strategy source or deploy any branch work after the configuration freeze. -Implement GAP-011: Gitea CI Pipeline — add Gitea Actions workflow that runs verify-build.bat on push and PR. +1. Before the gate begins, deploy the verified cleanup source to NinjaTrader `Custom\Strategies` and use the NinjaScript Editor to compile it. +2. In SimSimple ORB, set and triple-check: + - `EnableDynamicStop=TRUE` + - `RunnerActivationMode=Auto` + - `RegimeGate=GradePenalty` + - `MinTradeGrade=A` + - `MaxDailyTrades=1` + - `TestMode=FALSE` + - `EnableFileLogging=TRUE` + - `EnableVerboseLogging=TRUE` + - `LogDirectory=C:\\Users\\billy\\Documents\\NinjaTrader 8\\log\\nt8-sdk` +3. Export the settings file. Record both `ConfigHash` and `CodeVersion` from the export. +4. Add `DEC-GATE2-CONFIG` to `docs/00-governance/decisions.md`, including the export location, frozen values, hashes/stamp, and gate start date. +5. At gate start, apply a no-dual-deploy freeze to the gate machine. Preserve daily `provenance_*.json` and `trades_*.jsonl` artifacts and write weekly runbook heartbeats. -WHAT TO BUILD: -1. Create `.gitea/workflows/ci.yml` with: - - Triggers: push to main, PR to main - - Jobs: build-and-test - - Runs on: ubuntu-latest (with Windows runner for .NET Framework) - - Steps: - - Checkout - - Setup .NET (SDK 4.8) - - Run verify-build.bat - - Upload artifacts on failure (build logs, test results) - - Optional: Comment PR with summary - -2. Add `scripts/ci_build.sh` wrapper that calls verify-build.bat (for Linux runners) - -3. Update README.md with Gitea Actions status badge - -CONSTRAINTS: -- Must work on Gitea's Windows runner (self-hosted or ubuntu with wine/mono) -- verify-build.bat must be the single source of truth for build+test -- No new dependencies - -VERIFICATION: -- Push a test commit — Gitea Actions should run and show green -- verify-build.bat must pass (492 tests) - -WHEN DONE: Follow .kilocode/rules/self_learning_loop.md completely (all 6 steps). \ No newline at end of file +Acceptance: an auditable frozen-config record exists before Gate Run #2; no branch work is deployed while the gate is active. diff --git a/SPRINT_BOARD.md b/SPRINT_BOARD.md index 1164925..42856ca 100644 --- a/SPRINT_BOARD.md +++ b/SPRINT_BOARD.md @@ -1,101 +1,95 @@ -# Sprint Board -**Last Updated:** 2026-07-11 | **Active Sprint:** 3 — Production Hardening -**Build:** ✅ Clean | **Tests:** ✅ 492 passing (404 core + 78 integration + 10 performance) | **SIM Gate:** ⏳ In progress +# NT8 SDK — Sprint Board +**Last Updated:** 2026-07-14 +**Truth source:** compiler output, test output, deployed-file comparisons, and runtime artifacts override board claims. -> Kilocode maintains this file. After every task: move ACTIVE → COMPLETED, advance QUEUE → ACTIVE. -> Full prompts for every task are in `KILOCODE_RUNBOOK.md`. Next prompt is always in `NEXT_PROMPT.md`. +## Current gate state + +| Area | State | Evidence / required next step | +|---|---|---| +| Core source build | ✅ | `verify-build.bat`: 0 errors; 6 existing CS1998 warnings in test mocks/tests. | +| Automated tests | ✅ | 497 passed: 409 Core, 78 Integration, 10 Performance. | +| Provenance | ✅ | Session/trade records include session, parameter hash, and compiled code-version stamp. | +| Scenario coverage | 🟡 | 5/8 genuine assertions; 3 explicitly deferred for missing seams. | +| Gate Run #2 | ⏳ | Complete RB-4.1 configuration freeze, deploy/compile the cleanup source, then start the gate. | + +> **Gate deployment rule:** Once RB-4.1 is recorded and Gate Run #2 begins, do not dual-deploy to the gate machine. Run GAP-025 and connection-seam work in branches only. --- -## ✅ COMPLETED THIS SPRINT +## 🔵 ACTIVE — Human Gate Preparation -**[TASK-06a]** Runner Mode Architecture | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Core/Common/Models/Configuration.cs` (RunnerMode enum), `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` -- Implemented: RunnerMode enum (Auto, Mode1DualLeg, Mode2RunnerOnly, Mode3ScalerOnly, Disabled); ResolveRunnerMode() with Auto logic (Qty≥2→Mode1, Qty=1→Mode2); four mode behaviors in SubmitOrderToNT8(); [SDK] log confirms resolved mode; dual-deployed to NT8 Custom\Strategies\ -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (486 tests passing) - -**[TASK-06b]** ATR Dynamic Stop | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` -- Implemented: EnableDynamicStop, AtrPeriod (14), AtrMultiplier (1.5), MinStopTicks (12), MaxStopTicks (50); ATR accessed via ATR(Close, AtrPeriod)[0] in State.Configure; intent.StopTicks overridden pre-sizing; [SDK] Dynamic stop log confirms ATR stop value; context.CustomData["current_atr"] populated; dual-deployed. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (486 tests passing) - -**[GAP-019]** Portfolio Heat — Tier 3.5 Risk Layer | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Core/Risk/AdvancedRiskManager.cs`, `src/NT8.Core/Risk/AdvancedRiskModels.cs` -- Implemented: MaxHeatPct parameter (default 3.0) in AdvancedRiskConfig; ValidatePortfolioHeat() calculates TotalOpenRisk/AccountBalance; called as Tier 3.5 in ValidateOrder(); returns RiskDecision.Reject with reason when exceeded; _logger.LogDebug heat check logging; edge cases for 0/negative account balance handled. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (486 tests passing) - -**[GAP-003]** RiskPerTrade ≤ MaxTradeRisk Assertion | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Core/Common/Models/Configuration.cs` (RiskPerTrade property), `src/NT8.Core/Risk/BasicRiskManager.cs`, `tests/NT8.Core.Tests/Risk/BasicRiskManagerTests.cs` -- Implemented: RiskPerTrade property in RiskConfig; validation in ValidateOrder() throws ArgumentException if RiskPerTrade > MaxTradeRisk; unit tests for >, ==, < cases. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (401 core tests passing) - -**[GAP-004]** orbRangeTicks Hardcoded 0.0 Fix | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs`, `src/NT8.Core/Intelligence/FactorCalculators.cs` (DailyBarContext) -- Implemented: OrbRangeTicks field added to DailyBarContext; BuildDailyBarContext now calculates orbRangeTicks = (ORB high - ORB low) / TickSize; CreateIntent passes computed value; Factor 7 (ORBvsATR) now receives correct orb_range_ticks. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (401 core tests passing) - -**[GAP-005]** GetRiskStatus() Returns Live Config Value | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Core/Risk/BasicRiskManager.cs`, `tests/NT8.Core.Tests/Risk/BasicRiskManagerTests.cs` -- Implemented: _currentDailyLossLimit field updated from config.DailyLossLimit on each ValidateOrder(); GetRiskStatus() returns actual value; constructors initialize to default (1000) or provided value; 3 unit tests: explicit limit, default, config switching. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (492 tests passing) - -**[GAP-006]** Position-Close-Driven _tradeTaken Re-arm | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs` -- Implemented: OnPositionUpdate() sends clear_trade_taken when position goes flat; EnableBarBasedRearm parameter (default false) gates legacy bar-driven re-arm for SIM-only; SimpleORBStrategy.SetParameters() handles both force_session_reset and clear_trade_taken. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (492 tests passing) - -**[GAP-010]** Short-Side Regime Filter | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs` -- Implemented: EnableShortTrendFilter parameter (default true); short veto when AVWAP slope > 0 (bullish); long veto in bearish regime always enforced; parameter passed via StrategyContext.CustomData; logs when vetoed. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (492 tests passing) - -**[GAP-008]** CME Holiday Awareness | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Core/Calendar/CmeHolidayCalendar.cs` (new), `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs` -- Implemented: CmeHolidayCalendar with 9 observed holidays + Good Friday (Easter calc); EnableCMEHolidayGuard parameter (default true); NT8StrategyBase.OnBarUpdate() skips on holidays; SimpleORBStrategy.OnBar() skips ORB window; early-close tracking via IsEarlyClose(). -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (492 tests passing) - -**[GAP-009]** ATR Trailing Real ATR Wiring | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs` -- Implemented: EnableATRTrailing, ATRTrailingPeriod (14), ATRTrailingMultiplier (2.0), ATRTrailingMinTicks (8), ATRTrailingMaxTicks (60); SubmitOrderToNT8() computes trailTicks = clamp(round(ATR(Close,Period)[0]/TickSize * Mult), Min, Max); uses SetTrailStop; logs [SDK] ATR Trail line; falls back to RunnerTrailTicks when disabled. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (492 tests passing) - -**[GAP-011]** Gitea CI Pipeline | Sprint 3 | ✅ DONE 2026-07-11 -- Files: `.gitea/workflows/ci.yml`, `scripts/ci_build.sh` -- Implemented: Gitea Actions workflow with Windows self-hosted runner (primary) + Linux/mono fallback; triggers on push/PR to main; runs verify-build.bat logic; uploads test artifacts and build logs on failure; ci_build.sh wrapper for Linux/mono runners. -- Verification: .\verify-build.bat ✅ | dotnet test ✅ (492 tests passing) +**[RB-4.1] Gate Run #2 Configuration Freeze** | Human operator | 🔵 ACTIVE +- In SimSimple ORB, set and verify: `EnableDynamicStop=TRUE`, `RunnerActivationMode=Auto`, `RegimeGate=GradePenalty`, `MinTradeGrade=A`, `MaxDailyTrades=1`, `TestMode=FALSE`, `EnableFileLogging=TRUE`, `EnableVerboseLogging=TRUE`, and `LogDirectory=C:\\Users\\billy\\Documents\\NinjaTrader 8\\log\\nt8-sdk`. +- Export settings, retain the parameter hash and code-version stamp, and record `DEC-GATE2-CONFIG` with the gate start date. +- Before the gate begins, dual-deploy the completed cleanup source and run the NinjaTrader compile check. +- Acceptance: the frozen export/provenance evidence is archived and the no-deploy rule is in force at gate start. --- -## 🔵 ACTIVE +## 📋 QUEUE — no deploy to the gate machine during a run -*All Sprint 3 tasks complete. Sprint 4 backlog ready for next session.* +**[GAP-025] Runner No-Fill Anomaly Diagnosis** | Sprint 2.7 | ⏳ QUEUED — branch-only during Gate Run #2 +- Add diagnostic-only runner order/execution state logging. +- Diagnose the SIM fill sequence; this blocks live promotion, not Gate Run #2. + +**[GAP-022-FOLLOWUP] Connection-State Test Seam** | Sprint 2.7 | ⏳ QUEUED — branch-only during Gate Run #2 +- Add an injectable connection-state seam around `NT8StrategyBase`. +- Then implement the three deferred scenarios: news-day reduced sizing, mid-trade disconnect, and pre-entry disconnect. + +**[GAP-030] Historical ORB State Hydration** | Sprint 2.7 | ⏳ QUEUED — branch-only during Gate Run #2 +- On a late strategy enable, reconstruct only the current day's 09:30–10:00 ET opening-range high/low from loaded bars. +- Preserve the realtime replay guard: hydrated historical bars must never create an intent/order; only genuine post-hydration realtime bars may be evaluated. +- Add tests for correct range reconstruction and for zero historical-order submissions. + +**[GAP-007] Walk-Forward Validation** | Sprint 2.7 | ⏳ QUEUED — only after a passing Gate Run #2 ruling --- -## 📋 SPRINT 4 BACKLOG (not yet queued — awaiting Sprint 3 gate) +## ✅ COMPLETED — Sprint 2.7 -- **VWAPMeanReversion** — new core strategy, 11 AM–2 PM RTH window, uses AVWAPCalculator -- **OvernightGapContinuation** — gap >0.5% from prior close, enter at open in gap direction -- **OvernightGapReversion** — gap >1% stalls and reverses, 15-min time gate -- **LondonORBNT8** — 30-min ORB at 3:00–3:30 AM ET, MaxContracts=1 -- **GAP-013** — ContractRollHandler.InitiateRollover() completion -- **GAP-015** — Config JSON export/import (StrategyConfig, RiskConfig, SizingConfig) -- **GAP-014** — LiquidityMonitor Level II data prep -- **MNQ Phase 1 Prep** — go-live checklist, MNQ parameter calibration, risk limits for micro +**[TASK-GOV-02] Governance Truth Reconciliation** | ✅ 2026-07-13 +- Restored the July 11 historical record, corrected documentation placement, and logged DEC-20260713-02. + +**[TASK-00a] Provenance Controls (reissued)** | ✅ 2026-07-13 +- Session provenance, trade JSONL, SHA256 parameter hashing, settings export, TestMode state, and July 11 parameter export are implemented. + +**[GAP-024] Session Tagging Data Layer** | ✅ 2026-07-13 +- Exact `RTH_ORB`, `ETH`, `HOLIDAY`, and `EARLY_CLOSE` tags are written to provenance and trade records. + +**[GAP-022] Scenario Tests** | 🟡 PARTIAL — 5/8 verified 2026-07-14 +- Implemented with real assertions: high volatility rejection, low liquidity degradation, partial fill, daily-loss halt, and circuit-breaker open. +- Deferred honestly with source TODOs: news-day reduced sizing needs calendar/sizing-policy API; mid-trade and pre-entry disconnect scenarios need an injectable connection-state seam. + +**[GAP-029] Code-Version Provenance Stamp** | ✅ 2026-07-14 +- Session provenance, per-trade JSONL, settings exports, and SimpleORB snapshots now record the compiled assembly version plus module MVID. +- Each real-time signal also writes its TestMode/LIVE MODE state to the session file log. --- -## 📋 SPRINT 5 BACKLOG (deferred — requires 60+ days live data) +## 📋 HISTORICAL RECORD: July 11 Sprint (Sprint 2) — COMPLETED -- **FastAPI /predict endpoint** — LightGBM/XGBoost on Ollama workstation -- **MLSignalFactorCalculator** — 11th IFactorCalculator calling /predict -- **Multi-strategy PortfolioManager** — coordinator for shared-account strategies -- **Dashboard Phase 1+2** — read-only then real-time WebSocket -- **n8n AM Briefing** — daily pre-market summary (see IDEAS_BACKLOG.md) -- **GAP-017** — ParameterOptimizer → NT8 Strategy Analyzer wiring +The following 11 tasks were completed on 2026-07-11 and are already implemented in code. They were incorrectly erased/re-queued during a prior governance rewrite; this record preserves their actual completion dates. + +| Task | Sprint | Date | Status | +|---|---:|---|---| +| TASK-06a Runner Mode | 2 | 2026-07-11 | ✅ | +| TASK-06b ATR Dynamic Stop | 2 | 2026-07-11 | ✅ | +| GAP-019 Portfolio Heat | 2 | 2026-07-11 | ✅ | +| GAP-003 RiskPerTrade Assert | 2 | 2026-07-11 | ✅ | +| GAP-004 orbRangeTicks Fix | 2 | 2026-07-11 | ✅ | +| GAP-005 GetRiskStatus Live | 2 | 2026-07-11 | ✅ | +| GAP-006 Position-Close Re-arm | 2 | 2026-07-11 | ✅ | +| GAP-010 Short-Side Filter | 2 | 2026-07-11 | ✅ | +| GAP-008 CME Holiday | 2 | 2026-07-11 | ✅ | +| GAP-009 ATR Trailing | 2 | 2026-07-11 | ✅ | +| GAP-011 Gitea CI | 2 | 2026-07-11 | ✅ | --- -## 🚫 BLOCKED +## 📋 Sprint 3 Backlog — deferred until Gate Run #2 ruling -*(None — add items here if a task cannot proceed, with blocking reason)* \ No newline at end of file +- TASK-06d — VWAP Mean Reversion +- GAP-013 — ContractRollHandler completion +- GAP-014 — LiquidityMonitor Level II preparation +- GAP-015 — Config JSON export/import +- MNQ-001 / MNQ-002 — MNQ preparation and parameter calibration diff --git a/TASK_00a_PROMPT.md b/TASK_00a_PROMPT.md new file mode 100644 index 0000000..46811ed --- /dev/null +++ b/TASK_00a_PROMPT.md @@ -0,0 +1,86 @@ +# TASK-00a — Provenance Controls (Sprint 2.6) +**Spec:** NT8_SDK_Master_Document_v6.1 — Section 3.1 +**Depends on:** TASK-FIX-01 (HEAD must compile) + +--- + +``` +Read docs/00-governance/active_work.md and SPRINT_BOARD.md before starting. + +Implement TASK-00a: Provenance Controls — export full strategy configuration + runtime parameters on every session start and every trade, so Gate Run #2 trades are 100% reproducible from exported artifacts alone. + +WHAT TO BUILD: + +1. In NT8StrategyBase.cs (src/NT8.Adapters/Strategies/NT8StrategyBase.cs): + a. Add method: protected virtual void WriteSessionProvenance() + - Called at end of State.SetDefaults and on State.Realtime transition + - Exports to: /provenance__.json + - JSON structure: + { + "session_id": "", + "strategy_name": "", + "timestamp_utc": "", + "nt8_version": "", + "sdk_version": "6.1", + "config_hash": "", + "ninjascript_properties": { }, + "sdk_parameters": { }, + "july_11_params": { + "RunnerActivationMode": "", + "EnableDynamicStop": , + "AtrMultiplier": , + "EnableShortTrendFilter": , + "EnableATRTrailing": , + "ATRTrailingMultiplier": , + "EnableCMEHolidayGuard": , + "EnableBarBasedRearm": + }, + "test_mode_banner": "" or "" + } + - C# 5.0: use StringBuilder, no $\"\", no ?. operator + + b. Add method: protected virtual void WriteTradeProvenance(StrategyIntent intent, double atrStopTicks) + - Called in SubmitOrderToNT8 after intent is fully resolved + - Appends to: /trades__.jsonl (JSON Lines) + - Each line: + { + "session_id": "", + "trade_seq": , + "timestamp_utc": "", + "symbol": "", + "side": "", + "quantity": , + "stop_ticks": , + "target_ticks": , + "atr_stop_ticks": , + "resolved_runner_mode": "", + "confluence_grade": "", + "confluence_score": , + "risk_mode": "", + "daily_pnl_at_entry": + } + +2. In SimpleORBNT8.cs (src/NT8.Adapters/Strategies/SimpleORBNT8.cs): + - Override WriteSessionProvenance() to include ORB-specific params: + OpeningRangeMinutes, StdDevMultiplier, StopTicks, TargetTicks, MinTradeGrade, MaxDailyTrades, TestMode + +3. In SimpleORBStrategy.cs (src/NT8.Strategies/Examples/SimpleORBStrategy.cs): + - Add public string GetProvenanceSnapshot() returning JSON of _tradeTaken, _dailyTradeCount, _openingRangeHigh/Low, _currentSessionDate, regime state + +4. Add [NinjaScriptProperty] string LogDirectory (default = @"C:\NT8Logs\Provenance") to NT8StrategyBase + - Ensure directory exists on first write + +CONSTRAINTS: +- C# 5.0 only: StringBuilder, no string interpolation, no ?. or ??, no =>, no var fields, no pattern matching +- Use System.Security.Cryptography.SHA256 for config_hash +- Newtonsoft.Json already available (NT8 dependency) +- Dual-deploy ALL changed files to C:\Users\billy\Documents\NinjaTrader 8\bin\Custom\Strategies\ + +VERIFICATION: +- .\verify-build.bat ✅ +- dotnet test ✅ (492 tests) +- Enable strategy in NT8 SIM → verify provenance_*.json and trades_*.jsonl created with correct structure +- Verify July 11 params appear in provenance with actual runtime values + +WHEN DONE: Follow .kilocode/rules/self_learning_loop.md completely (all 6 steps). +``` \ No newline at end of file diff --git a/TASK_00b_PROMPT.md b/TASK_00b_PROMPT.md new file mode 100644 index 0000000..9eb70ef --- /dev/null +++ b/TASK_00b_PROMPT.md @@ -0,0 +1,79 @@ +# TASK-00b — Chart Diagnostics (Sprint 2.6) +**Spec:** NT8_SDK_Master_Document_v6.1 — Section 3.2 +**Depends on:** TASK-FIX-01 + +--- + +``` +Read docs/00-governance/active_work.md and SPRINT_BOARD.md before starting. + +Implement TASK-00b: Chart Diagnostics — visual on-chart proof of every decision so Gate Run #2 reviewers can see exactly what the strategy saw without opening logs. + +WHAT TO BUILD: + +1. In NT8StrategyBase.cs (src/NT8.Adapters/Strategies/NT8StrategyBase.cs): + a. Add [NinjaScriptProperty] bool EnableChartDiagnostics (default = true) + b. Add protected virtual void DrawDiagnostics(BarData bar, StrategyContext context, StrategyIntent intent) + - Called from SubmitOrderToNT8 after intent resolved, and from OnBarUpdate for passive display + - Uses NinjaTrader.NinjaScript.DrawingTools.Draw.* methods + - C# 5.0: explicit null checks, no ?. operator + + c. Required visual elements (all behind EnableChartDiagnostics): + i. ORB Range Box: Draw.Rectangle from _openingRangeStart/_openingRangeHigh to _openingRangeEnd/_openingRangeLow + Color: semi-transparent blue, tag "ORB_Range" + ii. Breakout Arrows: Draw.ArrowUp/Down at breakout bar (long/short trigger) + Tag: "ORB_Breakout_" + iii. ATR Dynamic Stop Line: Draw.Line horizontal at entry ± ATR stop distance + Color: orange, DashStyle.Dash, tag "ATR_Stop_" + Show ONLY when EnableDynamicStop=true AND CurrentBars[0] >= AtrPeriod + iv. Resolved RunnerMode Label: Draw.Text at top-right of chart + Text: "Runner: (Qty=)" + Color: green=Mode1, blue=Mode2, gray=Mode3/Disabled, tag "Runner_Mode" + v. Regime Indicator: Draw.Text below RunnerMode + Text: "Regime: | AVWAP Slope: " + Color: green=bullish, red=bearish, gray=neutral, tag "Regime" + vi. Session Tag: Draw.Text at session start + Text: "RTH_ORB | | " + Tag: "Session_Tag" + vii. Test Mode Banner: Draw.TextFixed at top-center (if TestMode=true) + Text: "⚠ TEST MODE ACTIVE — NOT LIVE ⚠", large red font, tag "TestMode_Banner" + viii. Provenance Link: Draw.TextFixed at bottom-right + Text: "Provenance: provenance__.json" + Tag: "Provenance_Link" + + d. Cleanup: In OnStateChange → State.Terminated, remove all objects with tags above + (DrawObjects.RemoveAllWithTag("ORB_Range"), etc.) + +2. In SimpleORBNT8.cs (src/NT8.Adapters/Strategies/SimpleORBNT8.cs): + - Override DrawDiagnostics to add ORB-specific: + - Draw.Line for longTrigger/shortTrigger levels (dashed green/red) + - Draw.Text for MinTradeGrade threshold on chart + +3. In SimpleORBStrategy.cs (src/NT8.Strategies/Examples/SimpleORBStrategy.cs): + - Add public void DrawDiagnostics(BarData bar, StrategyContext context, StrategyIntent intent, NT8StrategyBase adapter) + - Called by adapter's DrawDiagnostics + - Exposes internal state: _openingRangeHigh/Low, _tradeTaken, _dailyTradeCount, regime from context + +CONSTRAINTS: +- C# 5.0 only +- Draw.* calls only on primary series (BarsInProgress == 0) +- All tags prefixed with strategy Name to avoid collisions +- Colors: System.Windows.Media.Color or Brushes from NinjaTrader.Gui +- Dual-deploy ALL changed files to NT8 Custom\Strategies\ + +VERIFICATION: +- .\verify-build.bat ✅ +- dotnet test ✅ (492 tests) +- Enable in NT8 SIM on 5-min NQ chart → verify ALL elements appear: + [ ] ORB blue box at 9:30-10:00 + [ ] Breakout arrows on signal bars + [ ] Orange dashed ATR stop line at entry ± distance + [ ] "Runner: Mode2RunnerOnly (Qty=1)" label (when Qty=1) + [ ] "Regime: Bullish | AVWAP Slope: 0.0023" label + [ ] "RTH_ORB | 2026-07-13 | Normal" session tag + [ ] TestMode banner when TestMode=true + [ ] Provenance file link at bottom-right +- Disable EnableChartDiagnostics=false → verify ALL drawings removed + +WHEN DONE: Follow .kilocode/rules/self_learning_loop.md completely (all 6 steps). +``` \ No newline at end of file diff --git a/TASK_06c_PROMPT.md b/TASK_06c_PROMPT.md new file mode 100644 index 0000000..038bc48 --- /dev/null +++ b/TASK_06c_PROMPT.md @@ -0,0 +1,94 @@ +# TASK-06c — TrendRegime Gate (Sprint 2.6) +**Spec:** NT8_SDK_Master_Document_v6.1 — Section 6.3 +**Depends on:** TASK-FIX-01, TASK-00b (for regime display) + +--- + +``` +Read docs/00-governance/active_work.md and SPRINT_BOARD.md before starting. + +Implement TASK-06c: Wire existing RegimeManager/TrendRegimeDetector into the live pipeline. +Subsumes GAP-010 short veto into a configurable RegimeGateMode. + +WHAT TO BUILD: + +1. In NT8StrategyBase.cs (src/NT8.Adapters/Strategies/NT8StrategyBase.cs): + a. Add [NinjaScriptProperty] RegimeGateMode RegimeGate (default = RegimeGateMode.GradePenalty) + enum RegimeGateMode { Disabled, GradePenalty, HardVeto } + - Disabled: no regime gating (legacy) + - GradePenalty: downgrade confluence grade by 1 when trend against trade (A→B, B→C, etc.) + - HardVeto: block trade when trend against trade (current GAP-010 behavior for shorts) + + b. Add [NinjaScriptProperty] int SmaPeriodShort (default = 20) + c. Add [NinjaScriptProperty] int SmaPeriodLong (default = 50) + d. In OnStateChange → State.Configure: + - AddDataSeries(BarsPeriodType.Day, 1) for daily bars (if not already present) + - Initialize RegimeManager with SMA20/50 on daily series + + e. In BuildStrategyContext (or equivalent): + - Compute daily SMA20 and SMA50 from daily series (BarsArray[1]) + - Determine trend: SMA20 > SMA50 = Bullish, SMA20 < SMA50 = Bearish, else Neutral + - Pass to context.CustomData: + "regime_trend": "Bullish"/"Bearish"/"Neutral" + "regime_sma20": + "regime_sma50": + "regime_gate_mode": (int)RegimeGate + + f. In SubmitOrderToNT8 (before sizing): + - Read regime_trend and regime_gate_mode from context + - Apply gate: + if (RegimeGate == RegimeGateMode.HardVeto) + { + bool trendAgainst = (side == Buy && trend == Bearish) || (side == Sell && trend == Bullish); + if (trendAgainst) + { + Log("[SDK] HardVeto: trend {0} against {1}", trend, side); + return null; // block trade + } + } + else if (RegimeGate == RegimeGateMode.GradePenalty) + { + bool trendAgainst = (side == Buy && trend == Bearish) || (side == Sell && trend == Bullish); + if (trendAgainst) + { + // Downgrade grade in intent.Metadata + intent.Metadata["regime_penalty"] = true; + Log("[SDK] GradePenalty: trend {0} against {1} — grade -1", trend, side); + } + } + + g. Update DrawDiagnostics (TASK-00b) to show SMA20/SMA50 and regime gate mode + +2. In SimpleORBNT8.cs (src/NT8.Adapters/Strategies/SimpleORBNT8.cs): + - Add [NinjaScriptProperty] for RegimeGate, SmaPeriodShort, SmaPeriodLong + - Pass to ConfigureStrategyParameters → _strategyConfig.Parameters + +3. In SimpleORBStrategy.cs (src/NT8.Strategies/Examples/SimpleORBStrategy.cs): + a. Add RegimeGateMode property (with getter/setter for _regimeGateMode) + b. In OnBar, when regime_penalty in intent.Metadata: + - Downgrade final grade by 1 notch before GradeFilter check + - Log: "RegimePenalty applied: grade {0} -> {1}" + c. Remove the hardcoded EnableShortTrendFilter veto logic (lines ~490-520) + - It is NOW subsumed by RegimeGateMode.HardVeto + - Keep EnableShortTrendFilter parameter for backward compat but make it NO-OP when RegimeGate != Disabled + - Log warning if both enabled: "EnableShortTrendFilter ignored — RegimeGateMode={0} supersedes" + +CONSTRAINTS: +- C# 5.0 only +- Use existing RegimeManager/TrendRegimeDetector from NT8.Core.Intelligence +- Daily bars already added in SimpleORBNT8.Configure → State.Configure +- Do NOT break existing EnableShortTrendFilter behavior when RegimeGate=Disabled +- Dual-deploy ALL changed files to NT8 Custom\Strategies\ + +VERIFICATION: +- .\verify-build.bat ✅ +- dotnet test ✅ (492 tests) +- NT8 SIM: test all three RegimeGateMode values: + [ ] Disabled: shorts fire in bullish regime (current behavior) + [ ] GradePenalty: short in bullish regime → grade A→B, B→C, etc. (verify in provenance) + [ ] HardVeto: short in bullish regime → blocked, long in bearish → blocked (verify in provenance) +- Verify SMA20/SMA50 lines appear on daily chart when EnableChartDiagnostics=true +- Verify provenance includes "regime_gate_mode" and "regime_trend" + +WHEN DONE: Follow .kilocode/rules/self_learning_loop.md completely (all 6 steps). +``` \ No newline at end of file diff --git a/docs/00-governance/active_work.md b/docs/00-governance/active_work.md index 042e7bf..606c358 100644 --- a/docs/00-governance/active_work.md +++ b/docs/00-governance/active_work.md @@ -1,22 +1,25 @@ # Active Work -**Last Updated:** 2026-05-04 -**Sprint:** 3 — Production Hardening +**Last Updated:** 2026-07-14 -## Currently Active -**TASK-06a — Runner Mode Architecture** -- Spec: NT8_SDK_Master_Document_v6_Final.docx — Section 6.1 -- Files: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` -- Est: ~3 hrs -- Acceptance: RunnerMode enum exists; Auto mode resolves Mode1 (Qty≥2) or Mode2 (Qty=1); - Mode2 uses SetTrailStop only (no SetProfitTarget); [SDK] log confirms resolved mode; - verify-build.bat passes; all tests pass; dual-deployed to NT8 Custom. -- Prompt: `NEXT_PROMPT.md` (ready to paste) +## RB-4.1 — Gate Run #2 Configuration Freeze +**Owner:** Human operator +**State:** Active; gate clock has not started. -## Blockers -None currently. +1. Deploy the verified cleanup source to NinjaTrader Custom\Strategies and run NinjaTrader's compile check. +2. In SimSimple ORB, set and triple-check: + - `EnableDynamicStop=TRUE` + - `RunnerActivationMode=Auto` + - `RegimeGate=GradePenalty` + - `MinTradeGrade=A` + - `MaxDailyTrades=1` + - `TestMode=FALSE` + - `EnableFileLogging=TRUE` + - `EnableVerboseLogging=TRUE` + - `LogDirectory=C:\\Users\\billy\\Documents\\NinjaTrader 8\\log\\nt8-sdk` +3. Export settings; preserve the parameter hash and code-version stamp. +4. Add `DEC-GATE2-CONFIG` with the frozen configuration and planned start date. +5. At gate start, enforce the no-dual-deploy rule. GAP-025 and GAP-022-FOLLOWUP remain branch-only work. -## Notes for Next Claude Review Session -- Feed `SPRINT_BOARD.md` + `docs/00-governance/current_status.md` to Claude -- Ask: "Review our state and plan the next workset" -- Claude will assess completed tasks, check learning files, and update SPRINT_BOARD.md - with any re-prioritization before the next Kilocode execution batch +## Parallel work, not a gate prerequisite +- GAP-025 runner no-fill diagnosis blocks live promotion, not Gate Run #2. +- GAP-022-FOLLOWUP needs an injectable connection-state seam before the three deferred scenarios can be implemented honestly. diff --git a/docs/00-governance/common_failures.md b/docs/00-governance/common_failures.md index 7c72593..de45990 100644 --- a/docs/00-governance/common_failures.md +++ b/docs/00-governance/common_failures.md @@ -28,12 +28,21 @@ Record concise error fingerprints and verified fixes. - Root cause: wrong overload or argument ordering. - Fix: align call with exact method signature and parameter types. -6. **MaxDailyTrades overlap: second trade fires while first position still open** +5. **MaxDailyTrades overlap: second trade fires while first position still open** - Root cause: `_tradeTaken` re-arm in `SimpleORBStrategy` is bar-driven, not position-close-driven. The strategy re-arms on the next bar after generating an intent, regardless of whether NT8 has closed the previous position. - Risk: only relevant when `MaxDailyTrades > 1`. With default `MaxDailyTrades=1` this cannot occur. - Mitigation (SIM): `MaxOpenPositions` and `DailyLossLimit` in NT8 adapter limit exposure. - Fix (pre-live): wire re-arm to position-close callback in `NT8StrategyBase`. See DEC-20260429-01 in `docs/00-governance/decisions.md`. -5. **C# 6+ syntax in C# 5 project** +6. **C# 6+ syntax in C# 5 project** - Root cause: use of `$""`, `?.`, `nameof`, expression-bodied members, etc. - Fix: rewrite using C# 5 compatible constructs. + +## New Entries +7. **Post-task build verification skipped -- build broken after task completion** + - Date: 2026-07-13 + - Error: `CS0101` (duplicate `RunnerMode` enum), `CS0101` (duplicate `RunnerActivationMode` property), `CS1513` (unbalanced `#region`/`#endregion`) + - Fingerprint: `NT8StrategyBase.cs` ~line 249 (nested enum), ~line 279 (duplicate property), ~line 281 (extra `#endregion`) + - Root cause: Post-task build verification (`verify-build.bat` + `dotnet test`) was skipped after a previous task. Duplicate enum/property and unbalanced `#region`/`#endregion` compiled in IDE with Roslyn leniency but failed the strict dotnet CLI build used by NT8 SDK CI. + - Fix: Removed nested `RunnerMode` enum (keep namespace-level at line ~35), removed duplicate `RunnerActivationMode` property (keep `[NinjaScriptProperty]` version at line ~181), removed extra `#endregion` at line 281. Ran `verify-build.bat` + `dotnet test` -- 492 tests passed (10 perf + 78 integration + 404 core). + - Prevention link: Add mandatory `verify-build.bat && dotnet test --verbosity minimal` step to every task completion checklist in `docs/00-governance/decisions.md` and sprint templates. \ No newline at end of file diff --git a/docs/00-governance/current_status.md b/docs/00-governance/current_status.md index 187bbb2..3e6796a 100644 --- a/docs/00-governance/current_status.md +++ b/docs/00-governance/current_status.md @@ -1,35 +1,24 @@ -# Current Status -**Last Updated:** 2026-07-11 | **Sprint:** 3 — Production Hardening -**Last Completed Task:** GAP-009 — ATR Trailing Real ATR Wiring -**Active Task:** GAP-011 — Gitea CI Pipeline (see NEXT_PROMPT.md) +# Current Status — NT8 SDK +**Last Updated:** 2026-07-14 -## Build State -- `dotnet build`: ✅ passing (baseline confirmed before Sprint 3 start) -- `dotnet test`: ✅ 492 passing (404 core + 78 integration + 10 performance) -- NT8 NinjaScript compile: ✅ confirmed in SIM +## Verified implementation state +- **Last completed task:** GAP-029 — Code-Version Provenance Stamp +- **Active task:** RB-4.1 — Gate Run #2 Configuration Freeze (human operator) +- **Next code task:** GAP-025 — Runner No-Fill Anomaly Diagnosis (branch-only during the gate) +- **Following code task:** GAP-022-FOLLOWUP — connection-state seam and the three deferred scenarios -## SIM Validation Gate (Sprint 2 — ongoing parallel) -- Status: Collecting data -- Gate criteria: PF > 2.0, MaxDD < $500, 2+ weeks uninterrupted -- Gate met: NO — do not deploy live capital until gate is met +## Build and test evidence +- `verify-build.bat` completed successfully on 2026-07-14. +- Build: **0 errors**, **6 CS1998 warnings** in existing test mock/test methods. +- Tests: **497 passed, 0 failed** — 409 Core, 78 Integration, 10 Performance. -## Open Architecture Defects (block live trading) -| ID | Issue | Sprint | Status | -|---|---|---|---| -| TASK-06a | Runner Mode — useRunner = Qty≥2 is wrong architecture | 3 | ✅ COMPLETED | -| TASK-06b | ATR dynamic stop — fixed 8-tick stop too tight | 3 | ✅ COMPLETED | -| GAP-019 | Portfolio Heat Tier 3.5 not implemented | 3 | ✅ COMPLETED | -| GAP-003 | RiskPerTrade can exceed MaxTradeRisk silently | 3 | ✅ COMPLETED | -| GAP-004 | orbRangeTicks hardcoded 0.0 | 3 | ✅ COMPLETED | -| GAP-005 | GetRiskStatus() returns hardcoded value | 3 | ✅ COMPLETED | -| GAP-006 | _tradeTaken re-arm is bar-driven not position-close-driven | 3 | ✅ COMPLETED | -| GAP-010 | Short trades lack regime filter | 3 | ✅ COMPLETED | -| GAP-008 | No CME holiday awareness | 3 | ✅ COMPLETED | -| GAP-009 | ATR Trailing uses bar range not real ATR | 3 | ✅ COMPLETED | -| GAP-011 | No CI pipeline for Gitea | 3 | 🔴 ACTIVE | +## Gate readiness +- Provenance records have `session_id`, `trade_seq`, parameter-only `config_hash`, exact `session_tag`, and compiled `code_version` (assembly version + MVID). +- Every real-time signal writes its `TEST MODE ACTIVE` or `LIVE MODE` status to the session file log. +- GAP-022 has five real scenario assertions. Its remaining three requirements are deferred architecture work, not fabricated tests. +- **Before gate start:** deploy the cleanup source to NinjaTrader Custom\Strategies and run the NinjaTrader compile check. Then freeze the configuration and enforce the no-deploy rule. -## Operational State -- Deploy script: `deployment\Deploy-To-NT8.ps1` — deletes DLL, forces full recompile ✅ -- Kilocode rules: `.kilocode\rules\` — 14 active rule files ✅ -- Sprint board: `SPRINT_BOARD.md` — tasks ordered, prompts staged in KILOCODE_RUNBOOK.md ✅ -- Ideas backlog: `docs\IDEAS_BACKLOG.md` — add ideas here between sessions ✅ \ No newline at end of file +## Authoritative documents +- Master document: `docs/NT8_SDK_Master_Document_v6.1_Complete.docx` +- Operator runbook: `docs/02-runbooks/NT8_SDK_Operator_Runbook_v1.0.docx` +- Decision correction: `DEC-20260713-02` diff --git a/docs/00-governance/decisions.md b/docs/00-governance/decisions.md index 86c78e4..dc0b840 100644 --- a/docs/00-governance/decisions.md +++ b/docs/00-governance/decisions.md @@ -13,6 +13,16 @@ Use this file to record durable project decisions that affect implementation pat ## 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 @@ -105,4 +115,45 @@ Use this file to record durable project decisions that affect implementation pat - **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. \ No newline at end of file +- **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. diff --git a/docs/00-governance/patterns_and_antipatterns.md b/docs/00-governance/patterns_and_antipatterns.md index 12b823d..059d8a1 100644 --- a/docs/00-governance/patterns_and_antipatterns.md +++ b/docs/00-governance/patterns_and_antipatterns.md @@ -48,3 +48,8 @@ Capture recurring implementation patterns that impact compile stability. — can generate a second intent while first position is still open. - Why it matters: see DEC-20260429-01 in `docs/00-governance/decisions.md`. - Action required: wire re-arm to position-close callback in `NT8StrategyBase` before go-live. + +8. **Compiled-code provenance stamp** (2026-07-14) + - Good pattern: persist the running assembly version plus `ManifestModule.ModuleVersionId` alongside the parameter-only configuration hash. + - Anti-pattern: treat an unchanged parameter hash as proof that unchanged code is running. + - Why it matters: a mid-gate recompile/redeploy can preserve settings while changing executable behavior; the module MVID makes that drift detectable in session and trade artifacts. diff --git a/docs/00-governance/roadmap.md b/docs/00-governance/roadmap.md index 7eeb676..64676df 100644 --- a/docs/00-governance/roadmap.md +++ b/docs/00-governance/roadmap.md @@ -1,5 +1,5 @@ # Roadmap -**Last Updated:** 2026-05-04 +**Last Updated:** 2026-07-14 **Master Reference:** NT8_SDK_Master_Document_v6_Final.docx — Sections 7, 8, 21 ## Sequencing Rule @@ -35,6 +35,7 @@ Infrastructure: - GAP-011: Gitea CI pipeline (build.yml) - GAP-009: ATRTrailing real ATR wiring (replace proxy) - GAP-022: 8 scenario tests (ATR spike, FOMC, partial fill, disconnect, etc.) +- GAP-030: Historical ORB state hydration — safely reconstruct the current day's 09:30–10:00 ET range after a late enable without evaluating historical bars as signals; retain the realtime replay guard and add no-historical-order tests. - GAP-007: Walk-forward test setup documentation Gate criteria for Sprint 3 → Sprint 4: diff --git a/docs/02-runbooks/NT8_SDK_Operator_Runbook_v1.0.docx b/docs/02-runbooks/NT8_SDK_Operator_Runbook_v1.0.docx new file mode 100644 index 0000000..b3f81d2 Binary files /dev/null and b/docs/02-runbooks/NT8_SDK_Operator_Runbook_v1.0.docx differ diff --git a/docs/INDEX.md b/docs/INDEX.md index 726c291..65a849d 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -13,6 +13,10 @@ Navigation links in this file may be stale or broken. ## 📚 Documentation Structure +### Master Documents (v6.1 — Authoritative) +- **[NT8 SDK Master Document v6.1 Complete](NT8_SDK_Master_Document_v6.1_Complete.docx)** — Complete specification, architecture, all sprints, all gaps, all decisions +- **[NT8 SDK Operator Runbook v1.0](02-runbooks/NT8_SDK_Operator_Runbook_v1.0.docx)** — Operator procedures, SIM gate, go-live checklist, runbooks + ### Getting Started - **[Quick Start Guide](QUICK_START.md)** - Get trading in 10 minutes - **[README](README.md)** - Project overview and main documentation diff --git a/docs/NT8_SDK_Master_Document_v6.1_Complete.docx b/docs/NT8_SDK_Master_Document_v6.1_Complete.docx new file mode 100644 index 0000000..82612cf Binary files /dev/null and b/docs/NT8_SDK_Master_Document_v6.1_Complete.docx differ diff --git a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs index fc22d98..c546991 100644 --- a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs +++ b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs @@ -3,21 +3,28 @@ using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Windows.Media; using NinjaTrader.Cbi; using NinjaTrader.Data; using NinjaTrader.Gui; using NinjaTrader.Gui.Chart; using NinjaTrader.Gui.Tools; using NinjaTrader.NinjaScript; +using NinjaTrader.NinjaScript.DrawingTools; using NinjaTrader.NinjaScript.Indicators; using NinjaTrader.NinjaScript.Strategies; using NT8.Adapters.NinjaTrader; using NT8.Core.Common.Interfaces; using NT8.Core.Common.Models; using NT8.Core.Execution; +using NT8.Core.Intelligence; using NT8.Core.Logging; using NT8.Core.Risk; using NT8.Core.Sizing; +using Newtonsoft.Json; using SdkPosition = NT8.Core.Common.Models.Position; using SdkOrderSide = NT8.Core.Common.Models.OrderSide; using SdkOrderType = NT8.Core.Common.Models.OrderType; @@ -60,6 +67,27 @@ namespace NinjaTrader.NinjaScript.Strategies Disabled } + /// + /// Regime gate mode for trend regime filtering + /// + public enum RegimeGateMode + { + /// + /// No regime gating (legacy behavior) + /// + Disabled = 0, + + /// + /// Downgrade confluence grade by 1 when trend is against trade direction + /// + GradePenalty = 1, + + /// + /// Block trade when trend is against trade direction (subsumes EnableShortTrendFilter) + /// + HardVeto = 2 + } + /// /// Base class for strategies that integrate NT8 SDK components. /// @@ -94,6 +122,19 @@ namespace NinjaTrader.NinjaScript.Strategies private System.IO.StreamWriter _fileLog; private readonly object _fileLock = new object(); + // TASK-00a: Provenance Controls - session tracking + protected string _sessionId; + private int _tradeSequence; + + // TASK-06c: TrendRegime Gate - RegimeManager for daily SMA trend detection + private RegimeManager _regimeManager; + private TrendRegimeDetector _trendDetector; + private VolatilityRegimeDetector _volatilityDetector; + private double _dailySmaShort; + private double _dailySmaLong; + private string _regimeTrend; + private int _dailyBarCount; + #region User-Configurable Properties [NinjaScriptProperty] @@ -142,9 +183,13 @@ namespace NinjaTrader.NinjaScript.Strategies public bool EnableFileLogging { get; set; } [NinjaScriptProperty] - [Display(Name = "Log Directory", GroupName = "Diagnostics", Order = 11)] + [Display(Name = "Log Directory", GroupName = "Diagnostics", Order = 11, Description = "Directory for provenance JSON/JSONL exports. Default: C:\\NT8Logs\\Provenance")] public string LogDirectory { get; set; } + [NinjaScriptProperty] + [Display(Name = "Enable Chart Diagnostics", GroupName = "Diagnostics", Order = 12, Description = "When true, draws visual diagnostic elements on the chart for every decision.")] + public bool EnableChartDiagnostics { get; set; } + [NinjaScriptProperty] [Display(Name = "Enable Long Trades", GroupName = "Trade Direction", Order = 1)] public bool EnableLongTrades { get; set; } @@ -241,42 +286,20 @@ namespace NinjaTrader.NinjaScript.Strategies [Range(1, 200)] public int ATRTrailingMaxTicks { get; set; } - #endregion - - /// - /// Runner activation mode for position management (defined locally for NinjaScript compilation) - /// - public enum RunnerMode - { - /// - /// Automatically resolve based on quantity: Qty>=2 => Mode1DualLeg, Qty=1 => Mode2RunnerOnly - /// - Auto, - - /// - /// Dual-leg: scaler leg with fixed target + runner leg with trailing stop - /// - Mode1DualLeg, - - /// - /// Runner-only: full position on trailing stop, no fixed target - /// - Mode2RunnerOnly, - - /// - /// Scaler-only: full position with fixed target, no runner - /// - Mode3ScalerOnly, - - /// - /// Disabled: original single-leg behavior, no runner - /// - Disabled - } + // TASK-06c: TrendRegime Gate + [NinjaScriptProperty] + [Display(Name = "Regime Gate Mode", GroupName = "Regime Gate", Order = 1, Description = "Controls how trend regime affects trades: Disabled=legacy, GradePenalty=downgrade grade by 1, HardVeto=block trade when trend against direction.")] + public RegimeGateMode RegimeGate { get; set; } [NinjaScriptProperty] - [Display(Name = "Runner Activation Mode", GroupName = "Exit Management", Order = 6, Description = "Auto: Qty>=2=Mode1, Qty=1=Mode2")] - public RunnerMode RunnerActivationMode { get; set; } + [Display(Name = "SMA Period Short", GroupName = "Regime Gate", Order = 2, Description = "Short SMA period for daily trend detection (default 20).")] + [Range(5, 100)] + public int SmaPeriodShort { get; set; } + + [NinjaScriptProperty] + [Display(Name = "SMA Period Long", GroupName = "Regime Gate", Order = 3, Description = "Long SMA period for daily trend detection (default 50).")] + [Range(10, 200)] + public int SmaPeriodLong { get; set; } #endregion @@ -399,7 +422,7 @@ namespace NinjaTrader.NinjaScript.Strategies BreakevenOffsetTicks = 1; EnableRunner = true; RunnerTrailTicks = 12; - RunnerActivationMode = NT8.Core.Common.Models.RunnerMode.Auto; + RunnerActivationMode = RunnerMode.Auto; EnableDynamicStop = false; AtrPeriod = 14; AtrMultiplier = 1.5; @@ -413,11 +436,24 @@ namespace NinjaTrader.NinjaScript.Strategies ATRTrailingMultiplier = 2.0; // GAP-009: default 2.0 multiplier ATRTrailingMinTicks = 8; // GAP-009: default min 8 ticks ATRTrailingMaxTicks = 60; // GAP-009: default max 60 ticks + EnableChartDiagnostics = false; // Chart diagnostics disabled by default _killSwitchTriggered = false; _connectionLost = false; + + // TASK-00a: Generate session ID for provenance tracking + _sessionId = System.Guid.NewGuid().ToString("N"); + _tradeSequence = 0; + + // TASK-06c: TrendRegime Gate defaults + RegimeGate = RegimeGateMode.GradePenalty; + SmaPeriodShort = 20; + SmaPeriodLong = 50; } else if (State == State.Configure) { + // TASK-06c: Add daily bar series for SMA20/50 trend regime detection + AddDataSeries(BarsPeriodType.Day, 1); + // Register ATR indicator series for dynamic stop calculation // ATR is accessed via ATR(Close, AtrPeriod)[0] in NinjaScript // No separate AddDataSeries needed - ATR uses the primary bar series @@ -466,6 +502,9 @@ namespace NinjaTrader.NinjaScript.Strategies Print(string.Format("[SDK] ForceSessionReset: _tradeTaken cleared on live start at {0}", DateTime.Now.ToString("HH:mm:ss"))); } + // TASK-00a: Write session provenance on realtime transition + WriteSessionProvenance(); + WriteSettingsFile(); } else if (State == State.Terminated) @@ -616,6 +655,9 @@ namespace NinjaTrader.NinjaScript.Strategies Close[0])); } + // Draw chart diagnostics for visual proof of every decision + DrawDiagnostics(); + // --- Breakeven and runner trailing monitor --- if (_runnerActive && !string.IsNullOrEmpty(_runnerSignalName) && Position.Quantity != 0) { @@ -971,6 +1013,12 @@ namespace NinjaTrader.NinjaScript.Strategies timeout: TimeSpan.FromSeconds(30)); _executionAdapter = new NT8ExecutionAdapter(); + // TASK-06c: Initialize RegimeManager for trend regime detection + ILogger regimeLogger = new BasicLogger(Name + "_Regime"); + _volatilityDetector = new VolatilityRegimeDetector(regimeLogger, 50); + _trendDetector = new TrendRegimeDetector(regimeLogger); + _regimeManager = new RegimeManager(regimeLogger, _volatilityDetector, _trendDetector, 100, 50); + _sdkStrategy = CreateSdkStrategy(); if (_sdkStrategy == null) throw new InvalidOperationException("CreateSdkStrategy returned null"); @@ -1011,6 +1059,50 @@ namespace NinjaTrader.NinjaScript.Strategies // GAP-010: Pass short trend filter setting to SDK strategy customData.Add("EnableShortTrendFilter", EnableShortTrendFilter); + // TASK-06c: Regime Gate - compute daily SMA20/50 trend from daily series (BarsArray[1]) + if (RegimeGate != RegimeGateMode.Disabled && BarsArray != null && BarsArray.Length > 1 + && CurrentBars != null && CurrentBars.Length > 1 && CurrentBars[1] >= SmaPeriodLong) + { + double sumShort = 0.0; + double sumLong = 0.0; + int dailyIndex = 1; // BarsArray[1] is daily series + for (int i = 0; i < SmaPeriodShort; i++) + { + sumShort += Closes[dailyIndex][i]; + } + for (int i = 0; i < SmaPeriodLong; i++) + { + sumLong += Closes[dailyIndex][i]; + } + _dailySmaShort = sumShort / SmaPeriodShort; + _dailySmaLong = sumLong / SmaPeriodLong; + + if (_dailySmaShort > _dailySmaLong) + _regimeTrend = "Bullish"; + else if (_dailySmaShort < _dailySmaLong) + _regimeTrend = "Bearish"; + else + _regimeTrend = "Neutral"; + + _dailyBarCount = CurrentBars[1] + 1; + + customData.Add("regime_trend", _regimeTrend); + customData.Add("regime_sma20", _dailySmaShort); + customData.Add("regime_sma50", _dailySmaLong); + customData.Add("regime_gate_mode", (int)RegimeGate); + customData.Add("regime_sma_period_short", SmaPeriodShort); + customData.Add("regime_sma_period_long", SmaPeriodLong); + } + else + { + customData.Add("regime_trend", "Neutral"); + customData.Add("regime_sma20", 0.0); + customData.Add("regime_sma50", 0.0); + customData.Add("regime_gate_mode", (int)RegimeGateMode.Disabled); + customData.Add("regime_sma_period_short", SmaPeriodShort); + customData.Add("regime_sma_period_long", SmaPeriodLong); + } + return NT8DataConverter.ConvertContext( Instrument.MasterInstrument.Name, Time[0], @@ -1083,6 +1175,9 @@ namespace NinjaTrader.NinjaScript.Strategies if (State == State.Realtime && !_realtimeBarSeen) return; + if (EnableFileLogging && State == State.Realtime) + FileLog(string.Format("SIGNAL: {0} {1} | {2}", intent.Side, intent.Symbol, GetTestModeBanner())); + // Portfolio-level risk check — runs before per-strategy risk validation var portfolioDecision = PortfolioRiskManager.Instance.ValidatePortfolioRisk(Name, intent); if (!portfolioDecision.Allow) @@ -1330,6 +1425,15 @@ namespace NinjaTrader.NinjaScript.Strategies if (_circuitBreaker != null) _circuitBreaker.OnSuccess(); + + // TASK-00a: Write trade provenance + double atrStopTicks = 0.0; + if (EnableDynamicStop && CurrentBars[0] >= AtrPeriod) + { + double atrValue = ATR(Close, AtrPeriod)[0]; + atrStopTicks = System.Math.Round(atrValue / TickSize * AtrMultiplier); + } + WriteTradeProvenance(intent, request.Quantity, atrStopTicks); } catch (Exception ex) { @@ -1401,6 +1505,38 @@ namespace NinjaTrader.NinjaScript.Strategies lines.Add(string.Format("MinTradeGrade : {0}", MinTradeGrade)); lines.Add(string.Format("EnableFileLogging : {0}", EnableFileLogging)); lines.Add(string.Format("LogDirectory : {0}", string.IsNullOrEmpty(LogDirectory) ? "(default)" : LogDirectory)); + lines.Add("--- July 11 Sprint 2 Params ---"); + lines.Add(string.Format("RunnerActivationMode: {0}", RunnerActivationMode.ToString())); + lines.Add(string.Format("EnableDynamicStop : {0}", EnableDynamicStop)); + lines.Add(string.Format("AtrMultiplier : {0:F2}", AtrMultiplier)); + lines.Add(string.Format("EnableShortTrendFilter: {0}", EnableShortTrendFilter)); + lines.Add(string.Format("EnableATRTrailing : {0}", EnableATRTrailing)); + lines.Add(string.Format("ATRTrailingMultiplier: {0:F2}", ATRTrailingMultiplier)); + lines.Add(string.Format("EnableCMEHolidayGuard: {0}", EnableCMEHolidayGuard)); + lines.Add(string.Format("EnableBarBasedRearm : {0}", EnableBarBasedRearm)); + + // TestMode and ForceSessionReset from strategy config + bool testMode = false; + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode")) + { + var tm = _strategyConfig.Parameters["TestMode"]; + if (tm is bool) + testMode = (bool)tm; + } + lines.Add(string.Format("TestMode : {0}", testMode)); + + bool forceSessionReset = false; + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("ForceSessionReset")) + { + var fsr = _strategyConfig.Parameters["ForceSessionReset"]; + if (fsr is bool) + forceSessionReset = (bool)fsr; + } + lines.Add(string.Format("ForceSessionReset : {0}", forceSessionReset)); + + lines.Add(string.Format("ConfigHash : {0}", ComputeConfigHash())); + lines.Add(string.Format("CodeVersion : {0}", GetCodeVersionStamp())); + lines.Add("--- Portfolio ---"); lines.Add(string.Format("PortfolioStatus : {0}", PortfolioRiskManager.Instance.GetStatusSnapshot())); lines.Add("=== END SETTINGS ==="); @@ -1444,5 +1580,339 @@ namespace NinjaTrader.NinjaScript.Strategies Print(string.Format("[NT8-SDK] WARNING: Could not write settings file: {0}", ex.Message)); } } + + /// + /// Draws visual diagnostic elements on the chart to provide visual proof of every decision. + /// Override in derived classes to add strategy-specific diagnostic elements. + /// Called from OnBarUpdate when EnableChartDiagnostics is true. + /// + protected virtual void DrawDiagnostics() + { + if (!EnableChartDiagnostics) + return; + + // 1. Regime Indicator - AVWAP slope banner in top-left + if (_currentSession != null && _strategyConfig != null && _strategyConfig.Parameters != null) + { + if (_strategyConfig.Parameters.ContainsKey("avwap_slope")) + { + var slope = _strategyConfig.Parameters["avwap_slope"]; + if (slope is double) + { + double slopeVal = (double)slope; + string regimeText = slopeVal > 0 ? "REGIME: BULLISH" : "REGIME: BEARISH"; + Brush regimeBrush = slopeVal > 0 ? Brushes.LimeGreen : Brushes.Red; + Draw.TextFixed(this, "Diag_Regime", regimeText, TextPosition.TopLeft, regimeBrush, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100); + } + } + } + + // 2. Session Tag - RTH/ETH tag in top-right + if (_currentSession != null) + { + string sessionTag = _currentSession.IsRth ? "SESSION: RTH" : "SESSION: ETH"; + Brush sessionBrush = _currentSession.IsRth ? Brushes.DodgerBlue : Brushes.Orange; + Draw.TextFixed(this, "Diag_Session", sessionTag, TextPosition.TopRight, sessionBrush, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100); + } + + // 3. Runner Mode Label - shows current runner mode + if (EnableRunner) + { + string runnerText = "RUNNER: " + RunnerActivationMode.ToString(); + Draw.TextFixed(this, "Diag_Runner", runnerText, TextPosition.TopLeft, Brushes.Yellow, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100); + } + + // 4. TestMode Banner - prominent when TestMode is active + bool testMode = false; + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode")) + { + var tm = _strategyConfig.Parameters["TestMode"]; + if (tm is bool) + testMode = (bool)tm; + } + if (testMode) + { + Draw.TextFixed(this, "Diag_TestMode", "TEST MODE ACTIVE", TextPosition.Center, Brushes.White, new SimpleFont("Arial", 14), Brushes.Red, Brushes.Red, 100); + } + + // 5. ATR Stop Line - current dynamic stop level + 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)); + double stopPrice = Position.MarketPosition == MarketPosition.Long + ? Position.AveragePrice - (dynStop * TickSize) + : Position.AveragePrice + (dynStop * TickSize); + Draw.Line(this, "Diag_ATRStop", false, CurrentBar - 1, stopPrice, CurrentBar, stopPrice, Brushes.Cyan, DashStyleHelper.Dash, 2); + } + + // 6. Breakeven Level - visual line when breakeven is triggered + if (EnableAutoBreakeven && _breakevenMoved && !string.IsNullOrEmpty(_runnerSignalName)) + { + double bePrice = Position.MarketPosition == MarketPosition.Long + ? Position.AveragePrice + (BreakevenOffsetTicks * TickSize) + : Position.AveragePrice - (BreakevenOffsetTicks * TickSize); + Draw.Line(this, "Diag_Breakeven", false, CurrentBar - 1, bePrice, CurrentBar, bePrice, Brushes.LimeGreen, DashStyleHelper.Dot, 2); + } + + // 7. Provenance Link - subtle text with settings file reference + Draw.TextFixed(this, "Diag_Prov", "Prov: settings_" + Name.Replace(" ", "_") + "_" + DateTime.Now.ToString("yyyyMMdd"), TextPosition.BottomRight, Brushes.Gray, new SimpleFont("Arial", 8), Brushes.Transparent, Brushes.Transparent, 50); + } + + #region TASK-00a: Provenance Controls + + /// + /// Generates a SHA256 hash of all NinjaScriptProperty values for configuration provenance. + /// + protected string ComputeConfigHash() + { + var props = new List(); + var propsList = this.GetType().GetProperties(); + foreach (var prop in propsList) + { + var attr = prop.GetCustomAttributes(typeof(NinjaScriptPropertyAttribute), true); + if (attr.Length > 0) + { + var val = prop.GetValue(this, null); + props.Add(prop.Name + "=" + (val != null ? val.ToString() : "null")); + } + } + var combined = string.Join("|", props); + using (var sha = SHA256.Create()) + { + var bytes = Encoding.UTF8.GetBytes(combined); + var hash = sha.ComputeHash(bytes); + var sb = new StringBuilder(); + foreach (var b in hash) + sb.Append(b.ToString("x2")); + return sb.ToString(); + } + } + + /// + /// Identifies the compiled strategy assembly so a mid-gate redeploy is detectable + /// even when the NinjaScript parameter hash is unchanged. + /// + protected virtual string GetCodeVersionStamp() + { + try + { + var assembly = GetType().Assembly; + string version = assembly.GetName().Version != null + ? assembly.GetName().Version.ToString() + : "unknown"; + return version + ":" + assembly.ManifestModule.ModuleVersionId.ToString("N"); + } + catch + { + return "unknown"; + } + } + + /// + /// Writes session provenance JSON file at session start and realtime transition. + /// + protected virtual void WriteSessionProvenance() + { + try + { + if (string.IsNullOrEmpty(LogDirectory)) + return; + + if (_sessionId == null) + _sessionId = Guid.NewGuid().ToString(); + + var dir = LogDirectory; + Directory.CreateDirectory(dir); + + var provenance = new Dictionary + { + { "session_id", _sessionId }, + { "strategy_name", Name }, + { "timestamp_utc", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") }, + { "nt8_version", "NinjaTrader 8" }, + { "sdk_version", "6.1" }, + { "config_hash", ComputeConfigHash() }, + { "code_version", GetCodeVersionStamp() }, + { "ninjascript_properties", GetNinjaScriptProperties() }, + { "sdk_parameters", GetSdkParameters() }, + { "july_11_params", GetJuly11Params() }, + { "test_mode_banner", GetTestModeBanner() }, + { "session_tag", GetSessionTag() } + }; + + var safeName = Name.Replace(" ", "_").Replace("/", "_").Replace("\\", "_"); + var path = Path.Combine(dir, string.Format("provenance_{0}_{1}.json", safeName, DateTime.Now.ToString("yyyyMMdd_HHmmss"))); + var json = JsonConvert.SerializeObject(provenance, Formatting.Indented); + File.WriteAllText(path, json); + Print(string.Format("[NT8-SDK] Session provenance exported: {0}", path)); + } + catch (Exception ex) + { + Print(string.Format("[NT8-SDK] WARNING: Could not write session provenance: {0}", ex.Message)); + } + } + + /// + /// Writes trade provenance JSONL line for each trade. + /// + protected virtual void WriteTradeProvenance(StrategyIntent intent, int quantity, double atrStopTicks) + { + try + { + if (string.IsNullOrEmpty(LogDirectory)) + return; + + if (_sessionId == null) + _sessionId = Guid.NewGuid().ToString(); + + _tradeSequence++; + + var dir = LogDirectory; + Directory.CreateDirectory(dir); + + var trade = new Dictionary + { + { "session_id", _sessionId }, + { "trade_seq", _tradeSequence }, + { "timestamp_utc", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") }, + { "symbol", intent.Symbol }, + { "side", intent.Side.ToString() }, + { "quantity", quantity }, + { "stop_ticks", intent.StopTicks }, + { "target_ticks", intent.TargetTicks }, + { "atr_stop_ticks", atrStopTicks }, + { "resolved_runner_mode", GetResolvedRunnerMode().ToString() }, + { "confluence_grade", GetConfluenceGrade().ToString() }, + { "confluence_score", GetConfluenceScore() }, + { "risk_mode", GetRiskMode().ToString() }, + { "daily_pnl_at_entry", GetDailyPnL() }, + { "session_tag", GetSessionTag() }, + { "code_version", GetCodeVersionStamp() } + }; + + var safeName = Name.Replace(" ", "_").Replace("/", "_").Replace("\\", "_"); + var path = Path.Combine(LogDirectory, string.Format("trades_{0}_{1}.jsonl", Name.Replace(" ", "_"), DateTime.Now.ToString("yyyyMMdd"))); + var json = JsonConvert.SerializeObject(trade); + File.AppendAllText(path, json + Environment.NewLine); + } + catch (Exception ex) + { + Print(string.Format("[NT8-SDK] WARNING: Could not write trade provenance: {0}", ex.Message)); + } + } + + protected Dictionary GetNinjaScriptProperties() + { + var dict = new Dictionary(); + var props = this.GetType().GetProperties(); + foreach (var prop in props) + { + var attr = prop.GetCustomAttributes(typeof(NinjaScriptPropertyAttribute), true); + if (attr.Length > 0) + { + var val = prop.GetValue(this, null); + dict[prop.Name] = val; + } + } + return dict; + } + + protected Dictionary GetSdkParameters() + { + var dict = new Dictionary(); + if (_strategyConfig != null && _strategyConfig.Parameters != null) + { + foreach (var kvp in _strategyConfig.Parameters) + dict[kvp.Key] = kvp.Value; + } + return dict; + } + + protected Dictionary GetJuly11Params() + { + return new Dictionary + { + { "RunnerActivationMode", RunnerActivationMode.ToString() }, + { "EnableDynamicStop", EnableDynamicStop }, + { "AtrMultiplier", AtrMultiplier }, + { "EnableShortTrendFilter", EnableShortTrendFilter }, + { "EnableATRTrailing", EnableATRTrailing }, + { "ATRTrailingMultiplier", ATRTrailingMultiplier }, + { "EnableCMEHolidayGuard", EnableCMEHolidayGuard }, + { "EnableBarBasedRearm", EnableBarBasedRearm } + }; + } + + protected string GetTestModeBanner() + { + bool testMode = false; + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode")) + { + var tm = _strategyConfig.Parameters["TestMode"]; + if (tm is bool) + testMode = (bool)tm; + } + return testMode ? "TEST MODE ACTIVE" : "LIVE MODE"; + } + + private RunnerMode GetResolvedRunnerMode() + { + // This would need to be called in context where request.Quantity is available + return ResolveRunnerMode(RunnerActivationMode, 1); + } + + private string GetConfluenceGrade() + { + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("confluence_grade")) + { + var grade = _strategyConfig.Parameters["confluence_grade"]; + if (grade != null) return grade.ToString(); + } + return "Unknown"; + } + + private double GetConfluenceScore() + { + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("confluence_weighted_score")) + { + var score = _strategyConfig.Parameters["confluence_weighted_score"]; + if (score is double) return (double)score; + } + return 0.0; + } + + private string GetRiskMode() + { + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("risk_mode")) + { + var mode = _strategyConfig.Parameters["risk_mode"]; + if (mode != null) return mode.ToString(); + } + return "Unknown"; + } + + private double GetDailyPnL() + { + if (_lastAccountInfo != null) + return _lastAccountInfo.DailyPnL; + return 0.0; + } + + protected virtual string GetSessionTag() + { + if (_currentSession != null) + { + if (NT8.Core.Calendar.CmeHolidayCalendar.IsHoliday(Time[0].Date)) + return "HOLIDAY"; + if (NT8.Core.Calendar.CmeHolidayCalendar.IsEarlyClose(Time[0].Date)) + return "EARLY_CLOSE"; + return _currentSession.IsRth ? "RTH_ORB" : "ETH"; + } + return "UNKNOWN"; + } + + #endregion } } diff --git a/src/NT8.Adapters/Strategies/SimpleORBNT8.cs b/src/NT8.Adapters/Strategies/SimpleORBNT8.cs index c1fba3b..4193ecf 100644 --- a/src/NT8.Adapters/Strategies/SimpleORBNT8.cs +++ b/src/NT8.Adapters/Strategies/SimpleORBNT8.cs @@ -3,17 +3,21 @@ using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Windows.Media; using NinjaTrader.Cbi; using NinjaTrader.Data; using NinjaTrader.Gui; using NinjaTrader.Gui.Chart; using NinjaTrader.Gui.Tools; using NinjaTrader.NinjaScript; +using NinjaTrader.NinjaScript.DrawingTools; using NinjaTrader.NinjaScript.Indicators; using NinjaTrader.NinjaScript.Strategies; using NT8.Core.Common.Interfaces; using NT8.Core.Intelligence; using NT8.Strategies.Examples; +using Newtonsoft.Json; using SdkSimpleORB = NT8.Strategies.Examples.SimpleORBStrategy; namespace NinjaTrader.NinjaScript.Strategies @@ -98,6 +102,13 @@ namespace NinjaTrader.NinjaScript.Strategies [Range(1, 100)] public int TargetTicks { get; set; } + // ORB internal state for diagnostics + private double _openingRangeHigh; + private double _openingRangeLow; + private bool _openingRangeReady; + private bool _breakoutBarSeen; + private int _pendingBreakoutDirection; + protected override void OnStateChange() { if (State == State.SetDefaults) @@ -334,5 +345,151 @@ namespace NinjaTrader.NinjaScript.Strategies ctx.AvgIntradayBarVolume = intradayCount > 0 ? sumVol / intradayCount : Volume[0]; return ctx; } + + /// + /// Draws ORB-specific visual diagnostic elements on the chart. + /// Overrides base DrawDiagnostics to add ORB trigger lines, breakout arrows, and ORB box. + /// + protected override void DrawDiagnostics() + { + base.DrawDiagnostics(); + + if (!EnableChartDiagnostics) + return; + + // Access SDK strategy for ORB state + var sdkOrb = _sdkStrategy as SdkSimpleORB; + if (sdkOrb == null) + return; + + // 1. ORB Box - rectangle showing opening range high/low + if (sdkOrb.OpeningRangeReady && sdkOrb.OpeningRangeHigh > sdkOrb.OpeningRangeLow) + { + Draw.Rectangle(this, "Diag_ORBBox", false, CurrentBar - 1, sdkOrb.OpeningRangeHigh, CurrentBar, sdkOrb.OpeningRangeLow, Brushes.DodgerBlue, Brushes.Transparent, 2); + } + + // 2. ORB Trigger Lines - horizontal lines at breakout levels + if (sdkOrb.OpeningRangeReady && sdkOrb.OpeningRangeHigh > sdkOrb.OpeningRangeLow) + { + double openingRange = sdkOrb.OpeningRangeHigh - sdkOrb.OpeningRangeLow; + double volatilityBuffer = openingRange * (sdkOrb.StdDevMultiplier - 1.0); + if (volatilityBuffer < 0.0) volatilityBuffer = 0.0; + + double longTrigger = sdkOrb.OpeningRangeHigh + volatilityBuffer; + double shortTrigger = sdkOrb.OpeningRangeLow - volatilityBuffer; + + Draw.Line(this, "Diag_LongTrigger", false, CurrentBar - 20, longTrigger, CurrentBar, longTrigger, Brushes.LimeGreen, DashStyleHelper.Dash, 2); + Draw.Line(this, "Diag_ShortTrigger", false, CurrentBar - 20, shortTrigger, CurrentBar, shortTrigger, Brushes.Red, DashStyleHelper.Dash, 2); + } + + // 3. Breakout Arrows - mark breakout bar and confirmation bar + if (sdkOrb.BreakoutBarSeen) + { + // Breakout bar marker (triangle at breakout bar) + double arrowPrice = sdkOrb.PendingBreakoutDirection == 1 ? sdkOrb.OpeningRangeHigh : sdkOrb.OpeningRangeLow; + Brush arrowBrush = sdkOrb.PendingBreakoutDirection == 1 ? Brushes.LimeGreen : Brushes.Red; + Draw.ArrowUp(this, "Diag_BreakoutArrow", false, CurrentBar - 1, arrowPrice, arrowBrush); + } + + // 4. ORB Range Text - show ORB range in ticks + if (sdkOrb.OpeningRangeReady && sdkOrb.OpeningRangeHigh > sdkOrb.OpeningRangeLow) + { + double tickSize = TickSize; + if (tickSize <= 0.0) tickSize = 0.25; + double orbRangeTicks = Math.Round((sdkOrb.OpeningRangeHigh - sdkOrb.OpeningRangeLow) / tickSize); + string orbText = string.Format("ORB: {0:F0} ticks | Mult: {1:F1}", orbRangeTicks, sdkOrb.StdDevMultiplier); + Draw.TextFixed(this, "Diag_ORBRange", orbText, TextPosition.BottomLeft, Brushes.White, new SimpleFont("Arial", 9), Brushes.DarkBlue, Brushes.DarkBlue, 80); + } + + // 5. Breakout Direction Indicator + if (sdkOrb.BreakoutBarSeen) + { + string dirText = sdkOrb.PendingBreakoutDirection == 1 ? "BREAKOUT: LONG" : "BREAKOUT: SHORT"; + Brush dirBrush = sdkOrb.PendingBreakoutDirection == 1 ? Brushes.LimeGreen : Brushes.Red; + Draw.TextFixed(this, "Diag_BreakoutDir", dirText, TextPosition.BottomLeft, dirBrush, new SimpleFont("Arial", 9), Brushes.Black, Brushes.Black, 80); + } + + // 6. Trade Taken Status + bool testMode = false; + if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode")) + { + var tm = _strategyConfig.Parameters["TestMode"]; + if (tm is bool) + testMode = (bool)tm; + } + + if (testMode) + { + if (sdkOrb.TradeTaken) + { + Draw.TextFixed(this, "Diag_TradeTaken", "TRADE TAKEN (TestMode)", TextPosition.TopLeft, Brushes.Yellow, new SimpleFont("Arial", 10), Brushes.Red, Brushes.Red, 100); + } + } + + // 7. Daily Trade Count + if (sdkOrb.DailyTradeCount > 0) + { + string countText = string.Format("DAILY TRADES: {0}", sdkOrb.DailyTradeCount); + Draw.TextFixed(this, "Diag_DailyCount", countText, TextPosition.TopLeft, Brushes.Orange, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100); + } + } + + /// + /// Overrides base WriteSessionProvenance to include ORB-specific parameters. + /// + protected override void WriteSessionProvenance() + { + try + { + if (string.IsNullOrEmpty(LogDirectory)) + return; + + if (_sessionId == null) + _sessionId = Guid.NewGuid().ToString(); + + var dir = LogDirectory; + Directory.CreateDirectory(dir); + + var provenance = new Dictionary + { + { "session_id", _sessionId }, + { "strategy_name", Name }, + { "timestamp_utc", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") }, + { "nt8_version", "NinjaTrader 8" }, + { "sdk_version", "6.1" }, + { "config_hash", ComputeConfigHash() }, + { "ninjascript_properties", GetNinjaScriptProperties() }, + { "sdk_parameters", GetSdkParameters() }, + { "july_11_params", GetJuly11Params() }, + { "orb_params", GetOrbParams() }, + { "test_mode_banner", GetTestModeBanner() }, + { "session_tag", GetSessionTag() } + }; + + var safeName = Name.Replace(" ", "_").Replace("/", "_").Replace("\\", "_"); + var path = Path.Combine(dir, string.Format("provenance_{0}_{1}.json", safeName, DateTime.Now.ToString("yyyyMMdd_HHmmss"))); + var json = JsonConvert.SerializeObject(provenance, Formatting.Indented); + File.WriteAllText(path, json); + Print(string.Format("[NT8-SDK] Session provenance exported: {0}", path)); + } + catch (Exception ex) + { + Print(string.Format("[NT8-SDK] WARNING: Could not write session provenance: {0}", ex.Message)); + } + } + + private Dictionary GetOrbParams() + { + return new Dictionary + { + { "OpeningRangeMinutes", OpeningRangeMinutes }, + { "StdDevMultiplier", StdDevMultiplier }, + { "StopTicks", StopTicks }, + { "TargetTicks", TargetTicks }, + { "MinTradeGrade", MinTradeGrade }, + { "MaxDailyTrades", MaxDailyTrades }, + { "TestMode", TestMode } + }; + } } } diff --git a/src/NT8.Core/Calendar/CmeHolidayCalendar.cs b/src/NT8.Core/Calendar/CmeHolidayCalendar.cs index f935c8d..1b12374 100644 --- a/src/NT8.Core/Calendar/CmeHolidayCalendar.cs +++ b/src/NT8.Core/Calendar/CmeHolidayCalendar.cs @@ -1,163 +1,96 @@ using System; -using System.Collections.Generic; -using NT8.Core.Logging; namespace NT8.Core.Calendar { /// - /// CME Holiday Calendar - determines if a given date is a CME holiday or early-close day. - /// Covers standard US futures holidays observed by CME Group (CBOT, CME, COMEX, NYMEX). + /// CME equity-index holiday calendar used by strategy guards and provenance tags. + /// This deliberately models full closures and common early closes only; exchange + /// notices remain authoritative for exceptional schedules. /// public static class CmeHolidayCalendar { - private static readonly ILogger _logger = new BasicLogger("CmeHolidayCalendar"); - - /// - /// Checks if the given date is a CME full holiday (market closed all day). - /// - /// Date to check (date portion only). - /// True if CME holiday, false otherwise. - public static bool IsHoliday(DateTime date) - { - var d = date.Date; - int year = d.Year; - - // Fixed-date holidays (observed on nearest weekday if weekend) - if (IsObservedHoliday(d, year, 1, 1)) return true; // New Year's Day - if (IsObservedHoliday(d, year, 7, 4)) return true; // Independence Day - if (IsObservedHoliday(d, year, 12, 25)) return true; // Christmas Day - - // Monday holidays (3rd Monday Jan, 3rd Monday Feb, last Monday May, 1st Monday Sep) - if (IsNthWeekday(d, year, 1, DayOfWeek.Monday, 3)) return true; // MLK Jr. Day - if (IsNthWeekday(d, year, 2, DayOfWeek.Monday, 3)) return true; // Presidents Day - if (IsLastWeekday(d, year, 5, DayOfWeek.Monday)) return true; // Memorial Day - if (IsNthWeekday(d, year, 9, DayOfWeek.Monday, 1)) return true; // Labor Day - - // Thanksgiving: 4th Thursday November - if (IsNthWeekday(d, year, 11, DayOfWeek.Thursday, 4)) return true; - - // Good Friday (Friday before Easter) - if (d == GetGoodFriday(year)) return true; - - return false; - } - - /// - /// Checks if the given date is a CME early-close day (market closes at 1:00 PM ET or 1:15 PM ET). - /// - /// Date to check. - /// True if early close, false otherwise. - public static bool IsEarlyClose(DateTime date) - { - var d = date.Date; - int year = d.Year; - - // Day after Thanksgiving (Black Friday) - early close 1:00 PM ET - var thanksgiving = GetNthWeekday(year, 11, DayOfWeek.Thursday, 4); - if (d == thanksgiving.AddDays(1)) return true; - - // Christmas Eve (Dec 24) - if not weekend, early close 1:15 PM ET - if (IsObservedHoliday(d, year, 12, 24)) return true; - - // New Year's Eve (Dec 31) - if not weekend, early close 1:15 PM ET - if (IsObservedHoliday(d, year, 12, 31)) return true; - - // Day before Independence Day (Jul 3) - if not weekend, early close - if (IsObservedHoliday(d, year, 7, 3)) return true; - - return false; - } - - /// - /// Gets the trading session type for a date: Regular, EarlyClose, or Closed. - /// - public static SessionType GetSessionType(DateTime date) - { - if (IsHoliday(date)) return SessionType.Closed; - if (IsEarlyClose(date)) return SessionType.EarlyClose; - return SessionType.Regular; - } - - /// - /// Determines if strategy should skip ORB logic for this date. - /// public static bool ShouldSkipOrbWindow(DateTime date) { - return GetSessionType(date) != SessionType.Regular; + return IsHoliday(date); } - // ────────────────────────────────────────────────────────────── - // Helpers - // ────────────────────────────────────────────────────────────── - - /// - /// Checks if date matches a fixed holiday, with weekend observance rules. - /// If holiday falls on Saturday, observed Friday. If Sunday, observed Monday. - /// - private static bool IsObservedHoliday(DateTime date, int year, int month, int day) + public static bool IsHoliday(DateTime date) { - var actual = new DateTime(year, month, day); - var observed = GetObservedDate(actual); - return date == observed; + DateTime day = date.Date; + int year = day.Year; + + if (day == ObservedFixedHoliday(year, 1, 1)) + return true; + if (day == NthWeekdayOfMonth(year, 1, DayOfWeek.Monday, 3)) + return true; + if (day == NthWeekdayOfMonth(year, 2, DayOfWeek.Monday, 3)) + return true; + if (day == GetEasterSunday(year).AddDays(-2)) + return true; + if (day == LastWeekdayOfMonth(year, 5, DayOfWeek.Monday)) + return true; + if (day == ObservedFixedHoliday(year, 7, 4)) + return true; + if (day == NthWeekdayOfMonth(year, 9, DayOfWeek.Monday, 1)) + return true; + if (day == NthWeekdayOfMonth(year, 11, DayOfWeek.Thursday, 4)) + return true; + if (day == ObservedFixedHoliday(year, 12, 25)) + return true; + + return false; } - /// - /// Returns the observed date for a fixed holiday (weekend -> nearest weekday). - /// - private static DateTime GetObservedDate(DateTime actual) + public static bool IsEarlyClose(DateTime date) { - if (actual.DayOfWeek == DayOfWeek.Saturday) - return actual.AddDays(-1); // Observed Friday - if (actual.DayOfWeek == DayOfWeek.Sunday) - return actual.AddDays(1); // Observed Monday - return actual; + DateTime day = date.Date; + int year = day.Year; + DateTime thanksgiving = NthWeekdayOfMonth(year, 11, DayOfWeek.Thursday, 4); + + if (day == thanksgiving.AddDays(1)) + return true; + + DateTime christmasEve = new DateTime(year, 12, 24); + if (christmasEve.DayOfWeek != DayOfWeek.Saturday + && christmasEve.DayOfWeek != DayOfWeek.Sunday + && day == christmasEve) + return true; + + DateTime independenceEve = new DateTime(year, 7, 3); + if (independenceEve.DayOfWeek != DayOfWeek.Saturday + && independenceEve.DayOfWeek != DayOfWeek.Sunday + && day == independenceEve) + return true; + + return false; } - /// - /// Checks if date is the Nth occurrence of a weekday in a month (e.g., 3rd Monday). - /// - private static bool IsNthWeekday(DateTime date, int year, int month, DayOfWeek dow, int n) + private static DateTime ObservedFixedHoliday(int year, int month, int day) { - var target = GetNthWeekday(year, month, dow, n); - return date == target; + DateTime holiday = new DateTime(year, month, day); + if (holiday.DayOfWeek == DayOfWeek.Saturday) + return holiday.AddDays(-1); + if (holiday.DayOfWeek == DayOfWeek.Sunday) + return holiday.AddDays(1); + return holiday; } - /// - /// Returns the Nth occurrence of a weekday in a month. - /// - private static DateTime GetNthWeekday(int year, int month, DayOfWeek dow, int n) + private static DateTime NthWeekdayOfMonth(int year, int month, DayOfWeek weekday, int occurrence) { - var first = new DateTime(year, month, 1); - int offset = ((int)dow - (int)first.DayOfWeek + 7) % 7; - var firstOccurrence = first.AddDays(offset); - return firstOccurrence.AddDays(7 * (n - 1)); + DateTime date = new DateTime(year, month, 1); + int offset = ((int)weekday - (int)date.DayOfWeek + 7) % 7; + return date.AddDays(offset + ((occurrence - 1) * 7)); } - /// - /// Checks if date is the last occurrence of a weekday in a month (e.g., last Monday). - /// - private static bool IsLastWeekday(DateTime date, int year, int month, DayOfWeek dow) + private static DateTime LastWeekdayOfMonth(int year, int month, DayOfWeek weekday) { - var target = GetLastWeekday(year, month, dow); - return date == target; + DateTime date = new DateTime(year, month, DateTime.DaysInMonth(year, month)); + int offset = ((int)date.DayOfWeek - (int)weekday + 7) % 7; + return date.AddDays(-offset); } - /// - /// Returns the last occurrence of a weekday in a month. - /// - private static DateTime GetLastWeekday(int year, int month, DayOfWeek dow) + private static DateTime GetEasterSunday(int year) { - var lastDay = new DateTime(year, month, DateTime.DaysInMonth(year, month)); - int offset = ((int)lastDay.DayOfWeek - (int)dow + 7) % 7; - return lastDay.AddDays(-offset); - } - - /// - /// Computes Good Friday for a given year using Anonymous Gregorian algorithm. - /// - private static DateTime GetGoodFriday(int year) - { - // Anonymous Gregorian algorithm for Easter Sunday int a = year % 19; int b = year / 100; int c = year % 100; @@ -165,26 +98,14 @@ namespace NT8.Core.Calendar int e = b % 4; int f = (b + 8) / 25; int g = (b - f + 1) / 3; - int h = (19 * a + b - d - g + 15) % 30; + int h = ((19 * a) + b - d - g + 15) % 30; int i = c / 4; int k = c % 4; - int l = (32 + 2 * e + 2 * i - h - k) % 7; - int m = (a + 11 * h + 22 * l) / 451; - int month = (h + l - 7 * m + 114) / 31; - int day = ((h + l - 7 * m + 114) % 31) + 1; - - var easter = new DateTime(year, month, day); - return easter.AddDays(-2); // Good Friday = 2 days before Easter - } - - /// - /// Enum for session type. - /// - public enum SessionType - { - Regular, - EarlyClose, - Closed + int l = (32 + (2 * e) + (2 * i) - h - k) % 7; + int m = (a + (11 * h) + (22 * l)) / 451; + int month = (h + l - (7 * m) + 114) / 31; + int day = ((h + l - (7 * m) + 114) % 31) + 1; + return new DateTime(year, month, day); } } -} \ No newline at end of file +} diff --git a/src/NT8.Core/NT8.Core.csproj b/src/NT8.Core/NT8.Core.csproj index 33f7ad2..beb9902 100644 --- a/src/NT8.Core/NT8.Core.csproj +++ b/src/NT8.Core/NT8.Core.csproj @@ -9,10 +9,11 @@ + - + \ No newline at end of file diff --git a/src/NT8.Strategies/Examples/SimpleORBStrategy.cs b/src/NT8.Strategies/Examples/SimpleORBStrategy.cs index 3125901..29b4e6e 100644 --- a/src/NT8.Strategies/Examples/SimpleORBStrategy.cs +++ b/src/NT8.Strategies/Examples/SimpleORBStrategy.cs @@ -6,6 +6,7 @@ using NT8.Core.Common.Models; using NT8.Core.Indicators; using NT8.Core.Intelligence; using NT8.Core.Logging; +using Newtonsoft.Json; namespace NT8.Strategies.Examples { @@ -141,6 +142,94 @@ namespace NT8.Strategies.Examples set { _atrTrailingMaxTicks = value; } } + /// + /// Gets the current opening range high for chart diagnostics. + /// + public double OpeningRangeHigh + { + get { return _openingRangeHigh; } + } + + /// + /// Gets the current opening range low for chart diagnostics. + /// + public double OpeningRangeLow + { + get { return _openingRangeLow; } + } + + /// + /// Gets whether the opening range is ready for chart diagnostics. + /// + public bool OpeningRangeReady + { + get { return _openingRangeReady; } + } + + /// + /// Gets whether a breakout bar has been seen for chart diagnostics. + /// + public bool BreakoutBarSeen + { + get { return _breakoutBarSeen; } + } + + /// + /// Gets the pending breakout direction for chart diagnostics (1=Long, -1=Short, 0=None). + /// + public int PendingBreakoutDirection + { + get { return _pendingBreakoutDirection; } + } + + /// + /// Gets whether a trade has been taken for chart diagnostics. + /// + public bool TradeTaken + { + get { return _tradeTaken; } + } + + /// + /// Gets the opening range start time for chart diagnostics. + /// + public DateTime OpeningRangeStart + { + get { return _openingRangeStart; } + } + + /// + /// Gets the opening range end time for chart diagnostics. + /// + public DateTime OpeningRangeEnd + { + get { return _openingRangeEnd; } + } + + /// + /// Gets the current daily trade count for chart diagnostics. + /// + public int DailyTradeCount + { + get { return _dailyTradeCount; } + } + + /// + /// Gets the std dev multiplier for chart diagnostics. + /// + public double StdDevMultiplier + { + get { return _stdDevMultiplier; } + } + + /// + /// Gets the opening range minutes for chart diagnostics. + /// + public int OpeningRangeMinutes + { + get { return _openingRangeMinutes; } + } + /// /// Gets strategy metadata. /// @@ -1027,5 +1116,91 @@ namespace NT8.Strategies.Examples } intent.Metadata["daily_bars"] = daily; } + + /// + /// Returns diagnostic state for chart visualization. + /// Called by NT8 adapter to draw chart diagnostics. + /// + /// Diagnostic state object. + public Dictionary GetDiagnostics() + { + var diag = new Dictionary(); + diag.Add("openingRangeHigh", _openingRangeHigh); + diag.Add("openingRangeLow", _openingRangeLow); + diag.Add("openingRangeReady", _openingRangeReady); + diag.Add("breakoutBarSeen", _breakoutBarSeen); + diag.Add("pendingBreakoutDirection", _pendingBreakoutDirection); + diag.Add("tradeTaken", _tradeTaken); + diag.Add("openingRangeStart", _openingRangeStart); + diag.Add("openingRangeEnd", _openingRangeEnd); + diag.Add("dailyTradeCount", _dailyTradeCount); + diag.Add("stdDevMultiplier", _stdDevMultiplier); + diag.Add("openingRangeMinutes", _openingRangeMinutes); + return diag; + } + + /// + /// Returns a JSON snapshot of internal strategy state for provenance tracking. + /// + /// JSON string of internal state. + public string GetProvenanceSnapshot() + { + try + { + string sessionTag = "UNKNOWN"; + try + { + if (_currentSessionDate != DateTime.MinValue) + { + if (CmeHolidayCalendar.IsHoliday(_currentSessionDate)) + sessionTag = "HOLIDAY"; + else if (CmeHolidayCalendar.IsEarlyClose(_currentSessionDate)) + sessionTag = "EARLY_CLOSE"; + else + sessionTag = "RTH_ORB"; // SimpleORBStrategy only trades RTH + } + } + catch { } + + var snapshot = new Dictionary + { + { "tradeTaken", _tradeTaken }, + { "dailyTradeCount", _dailyTradeCount }, + { "openingRangeHigh", _openingRangeHigh }, + { "openingRangeLow", _openingRangeLow }, + { "currentSessionDate", _currentSessionDate.ToString("yyyy-MM-dd") }, + { "breakoutBarSeen", _breakoutBarSeen }, + { "pendingBreakoutDirection", _pendingBreakoutDirection }, + { "openingRangeStart", _openingRangeStart.ToString("yyyy-MM-dd HH:mm:ss") }, + { "openingRangeEnd", _openingRangeEnd.ToString("yyyy-MM-dd HH:mm:ss") }, + { "stdDevMultiplier", _stdDevMultiplier }, + { "openingRangeMinutes", _openingRangeMinutes }, + { "session_tag", sessionTag }, + { "code_version", GetCodeVersionStamp() } + }; + + return JsonConvert.SerializeObject(snapshot, Newtonsoft.Json.Formatting.Indented); + } + catch (Exception ex) + { + return "{\"error\": \"" + ex.Message + "\"}"; + } + } + + private string GetCodeVersionStamp() + { + try + { + var assembly = GetType().Assembly; + string version = assembly.GetName().Version != null + ? assembly.GetName().Version.ToString() + : "unknown"; + return version + ":" + assembly.ManifestModule.ModuleVersionId.ToString("N"); + } + catch + { + return "unknown"; + } + } } } diff --git a/tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs b/tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs new file mode 100644 index 0000000..0b2fa4f --- /dev/null +++ b/tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NT8.Adapters.NinjaTrader; +using NT8.Core.Common.Models; +using NT8.Core.Execution; +using NT8.Core.Intelligence; +using NT8.Core.Logging; +using NT8.Core.MarketData; +using NT8.Core.OMS; +using NT8.Core.Risk; +using NT8.Core.Tests.Mocks; + +namespace NT8.Core.Tests.Scenarios +{ + /// + /// Executable scenario coverage for behaviors already exposed by Core APIs. + /// + /// Intentionally not represented as passing tests here because no truthful + /// Core seam exists yet: NEWS_DAY_REDUCED_SIZE, MID_TRADE_DISCONNECT, and + /// PRE_ENTRY_DISCONNECT. See the TODO block at the end of this file. + /// + [TestClass] + public class ScenarioTests + { + [TestMethod] + public void HIGH_VOLATILITY_DAY_ExtremeAtrRatioScoresLowAndDcpRejectsTrade() + { + var context = CreateContext(); + context.CustomData.Add("current_atr", 40.0); + context.CustomData.Add("normal_atr", 25.0); + var intent = CreateIntent(); + var bar = CreateBar(); + var calculator = new VolatilityRegimeFactorCalculator(); + + var factor = calculator.Calculate(intent, context, bar); + var factors = new List(); + factors.Add(calculator); + var confluence = new ConfluenceScorer(new BasicLogger("ScenarioTests"), 20) + .CalculateScore(intent, context, bar, factors); + + Assert.AreEqual(FactorType.Volatility, factor.Type); + Assert.AreEqual(0.3, factor.Score, 0.000001); + Assert.AreEqual(TradeGrade.F, confluence.Grade); + Assert.IsFalse(new GradeFilter().ShouldAcceptTrade(confluence.Grade, NT8.Core.Intelligence.RiskMode.DCP)); + } + + [TestMethod] + public void LOW_LIQUIDITY_WideSpreadIsUnacceptableAndLowExecutionQualityScoresPointFour() + { + var monitor = new LiquidityMonitor(new MockLogger()); + monitor.UpdateSpread("NQ", 18000.00, 18000.25, 1000); + monitor.UpdateSpread("NQ", 18000.00, 18000.25, 1000); + monitor.UpdateSpread("NQ", 18000.00, 18002.00, 1000); + + var liquidity = monitor.CalculateLiquidityScore("NQ"); + var context = CreateContext(); + context.CustomData.Add("recent_execution_quality", 0.3); + var factor = new ExecutionQualityFactorCalculator().Calculate(CreateIntent(), context, CreateBar()); + + Assert.AreEqual(LiquidityScore.Poor, liquidity); + Assert.IsFalse(monitor.IsLiquidityAcceptable("NQ", LiquidityScore.Excellent)); + Assert.AreEqual(FactorType.ExecutionQuality, factor.Type); + Assert.AreEqual(0.4, factor.Score, 0.000001); + } + + [TestMethod] + public void PARTIAL_FILL_AdapterTracksPartiallyFilledOrderWithoutCreatingSecondOrder() + { + var adapter = new NT8ExecutionAdapter(); + var tracking = adapter.SubmitOrder(CreateOrderRequest(3), "SDK-1"); + + adapter.ProcessOrderUpdate("NT8-1", "SDK-1", "PARTFILLED", 1, 4202.0, 0, null); + adapter.ProcessExecution("NT8-1", "EX-1", 4202.0, 1, DateTime.UtcNow); + + var status = adapter.GetOrderStatus("SDK-1"); + Assert.IsNotNull(tracking); + Assert.IsNotNull(status); + Assert.AreEqual(OrderState.PartiallyFilled, status.State); + Assert.AreEqual(1, status.FilledQuantity); + Assert.IsNull(adapter.GetOrderStatus("SDK-1-RETRY")); + } + + [TestMethod] + public void DAILY_LOSS_HALT_RejectsCurrentAndSubsequentEntriesForSession() + { + var manager = new BasicRiskManager(new BasicLogger("ScenarioTests")); + var config = new RiskConfig(500.0, 100.0, 3, true); + var intent = CreateIntent(); + var context = CreateContext(); + + manager.OnPnLUpdate(0.0, -500.0); + var initialDecision = manager.ValidateOrder(intent, context, config); + var laterDecision = manager.ValidateOrder(intent, context, config); + + Assert.IsFalse(initialDecision.Allow); + Assert.AreEqual(RiskLevel.Critical, initialDecision.RiskLevel); + Assert.IsFalse(laterDecision.Allow); + Assert.AreEqual(RiskLevel.Critical, laterDecision.RiskLevel); + } + + [TestMethod] + public void CIRCUIT_BREAKER_OPEN_ThreeRejectionsBlockFurtherOrders() + { + var breaker = new ExecutionCircuitBreaker( + new BasicLogger("ScenarioTests"), + 3, + TimeSpan.FromSeconds(30), + TimeSpan.FromSeconds(5), + 100, + 3); + + breaker.RecordOrderRejection("simulated rejection"); + breaker.RecordOrderRejection("simulated rejection"); + breaker.RecordOrderRejection("simulated rejection"); + + Assert.AreEqual(CircuitBreakerStatus.Open, breaker.GetState().Status); + Assert.IsFalse(breaker.ShouldAllowOrder()); + } + + private static StrategyIntent CreateIntent() + { + return new StrategyIntent( + "NQ", + NT8.Core.Common.Models.OrderSide.Buy, + NT8.Core.Common.Models.OrderType.Market, + null, + 10, + 20, + 0.75, + "Scenario test", + new Dictionary()); + } + + private static StrategyContext CreateContext() + { + return new StrategyContext( + "NQ", + DateTime.UtcNow, + new Position("NQ", 0, 0, 0, 0, DateTime.UtcNow), + new AccountInfo(100000, 100000, 0, 0, DateTime.UtcNow), + new MarketSession(DateTime.Today.AddHours(9.5), DateTime.Today.AddHours(16), true, "RTH"), + new Dictionary()); + } + + private static BarData CreateBar() + { + return new BarData("NQ", DateTime.UtcNow, 18000, 18010, 17990, 18005, 1000, TimeSpan.FromMinutes(1)); + } + + private static OrderRequest CreateOrderRequest(int quantity) + { + return new OrderRequest + { + Symbol = "NQ", + Side = NT8.Core.OMS.OrderSide.Buy, + Type = NT8.Core.OMS.OrderType.Market, + Quantity = quantity, + TimeInForce = TimeInForce.Day, + ClientOrderId = "SDK-1" + }; + } + + // TODO GAP-022 follow-ons (not claimed as covered): + // NEWS_DAY_REDUCED_SIZE requires high-impact-event calendar and sizing-policy APIs. + // MID_TRADE_DISCONNECT requires an injectable connection-state seam around NT8StrategyBase. + // PRE_ENTRY_DISCONNECT requires an atomic pre-submit connection check and test seam. + } +}