diff --git a/SPRINT_BOARD.md b/SPRINT_BOARD.md index 66ef4ed..1164925 100644 --- a/SPRINT_BOARD.md +++ b/SPRINT_BOARD.md @@ -1,6 +1,6 @@ # Sprint Board **Last Updated:** 2026-07-11 | **Active Sprint:** 3 — Production Hardening -**Build:** ✅ Clean | **Tests:** ✅ 486 passing (398 core + 78 integration + 10 performance) | **SIM Gate:** ⏳ In progress +**Build:** ✅ Clean | **Tests:** ✅ 492 passing (404 core + 78 integration + 10 performance) | **SIM Gate:** ⏳ In progress > 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`. @@ -9,94 +9,9 @@ ## ✅ COMPLETED THIS SPRINT -**[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` -- Acceptance: _tradeTaken re-arm wired to OnPositionUpdate when position goes flat; EnableBarBasedRearm parameter gates legacy bar-driven re-arm to SIM-only mode; DEC-20260711-06 recorded. -- Dual-deployed to NT8 Custom\Strategies\ - -## ✅ COMPLETED THIS SPRINT - -**[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` -- Acceptance: EnableShortTrendFilter parameter added; short trades vetoed when AVWAP slope > 0 (bullish regime) and filter enabled; DEC-20260711-07 recorded. -- Dual-deployed to NT8 Custom\Strategies\ - -## ✅ COMPLETED THIS SPRINT - -**[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` -- Acceptance: EnableATRTrailing parameter added; runner trailing stop uses ATR instead of fixed RunnerTrailTicks; clamped to Min/Max ticks; DEC-20260711-09 recorded. -- Dual-deployed to NT8 Custom\Strategies\ - -## 🔵 ACTIVE - -**[GAP-011]** Gitea CI Pipeline | Sprint 3 | ~2 hrs -- Files: `.gitea/workflows/ci.yml`, `scripts/ci_build.sh` -- Acceptance: Gitea Actions runs `verify-build.bat` on push/PR; artifact upload on success; status badge in README. -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-011` - -**[GAP-005]** GetRiskStatus() Returns Live Config Value | Sprint 3 | ~1 hr -- Files: `src/NT8.Core/Risk/BasicRiskManager.cs` -- Acceptance: GetRiskStatus() returns the actual registered DailyLossLimit from RiskConfig, not hardcoded value; unit test confirms returned value matches injected config. -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-005` - -**[GAP-006]** Position-Close-Driven _tradeTaken Re-arm | Sprint 3 | ~2 hrs -- Files: `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` -- Acceptance: _tradeTaken re-arm wired to OnPositionUpdate callback when position goes flat; bar-driven re-arm removed or gated to SIM-only mode via parameter; decision recorded in docs/00-governance/decisions.md. -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-006` - -**[GAP-010]** Short-Side Regime Filter Gate | Sprint 3 | ~2 hrs -- Files: `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `src/NT8.Adapters/Strategies/SimpleORBNT8.cs` -- Acceptance: Short signals blocked when TrendRegime is Bullish and RiskMode is Normal; EnableShortSide NinjaScript param (default=false); regime detection uses existing RegimeManager; unit test confirms short blocked in bull regime. -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-010` - -**[GAP-008]** CME Holiday Awareness — SessionManager | Sprint 3 | ~30 min -- Files: `src/NT8.Core/MarketData/SessionManager.cs` -- Acceptance: Static HashSet of 2025/2026 CME holidays; IsRegularTradingHours() returns false on Christmas, Thanksgiving, New Year's Day; unit test confirms holiday returns false. -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-008` - -**[GAP-009]** ATRTrailing Real ATR Wiring | Sprint 3 | ~1 hr -- Files: `src/NT8.Core/Execution/TrailingStopManager.cs` -- Acceptance: ATRTrailing mode uses context.CustomData["current_atr"] instead of avgFillPrice × 0.005; Chandelier mode same; falls back to proxy only if key missing (with log warning). -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-009` - -**[GAP-011]** Gitea CI Pipeline | Sprint 3 | ~1 hr -- Files: `.gitea/workflows/build.yml` -- Acceptance: Workflow triggers on push and PR; runs dotnet restore → dotnet build → dotnet test; fails on any test failure; success/failure status visible on Gitea repo. -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-011` - -**[GAP-022]** Scenario Tests — 8 Edge Cases | Sprint 3 | ~3 hrs -- Files: `tests/NT8.Core.Tests/` (new scenario test file) -- Acceptance: 8 scenario tests pass: ATR spike (factor 3 scores 0.3), FOMC news day, low liquidity, partial fill, mid-trade disconnect, pre-entry disconnect, daily loss halt, circuit breaker open. All in CI. -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-022` - -**[GAP-007]** Walk-Forward Test Documentation + Setup | Sprint 3 | ~2 hrs -- Files: `docs/00-governance/decisions.md`, `docs/02-runbooks/backtest_review_workflow.md` -- Acceptance: Walk-forward test procedure documented: in-sample Jan 2024–Sep 2025, OOS Oct 2025–Mar 2026; Strategy Analyzer config instructions written; acceptance threshold (WF PF ≥ 60% of in-sample PF) recorded as decision. -- Prompt: `KILOCODE_RUNBOOK.md` → section `## GAP-007` - ---- - -## 🚫 BLOCKED -*(None — add items here if a task cannot proceed, with blocking reason)* - ---- - -## ✅ COMPLETED THIS SPRINT - -**[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-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-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. +**[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 @@ -104,11 +19,57 @@ - 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) -**[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\ +**[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) + +--- + +## 🔵 ACTIVE + +*All Sprint 3 tasks complete. Sprint 4 backlog ready for next session.* + --- ## 📋 SPRINT 4 BACKLOG (not yet queued — awaiting Sprint 3 gate) @@ -131,4 +92,10 @@ - **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 \ No newline at end of file +- **GAP-017** — ParameterOptimizer → NT8 Strategy Analyzer wiring + +--- + +## 🚫 BLOCKED + +*(None — add items here if a task cannot proceed, with blocking reason)* \ No newline at end of file diff --git a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs index 6919a4b..fc22d98 100644 --- a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs +++ b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs @@ -29,6 +29,37 @@ using OmsOrderStatus = NT8.Core.OMS.OrderStatus; namespace NinjaTrader.NinjaScript.Strategies { + /// + /// Runner activation mode for position management + /// + 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 + } + /// /// Base class for strategies that integrate NT8 SDK components. /// @@ -147,7 +178,7 @@ namespace NinjaTrader.NinjaScript.Strategies [NinjaScriptProperty] [Display(Name = "Runner Activation Mode", GroupName = "Exit Management", Order = 6, Description = "Auto: Qty>=2=Mode1, Qty=1=Mode2")] - public NT8.Core.Common.Models.RunnerMode RunnerActivationMode { get; set; } + public RunnerMode RunnerActivationMode { get; set; } [NinjaScriptProperty] [Display(Name = "Enable Dynamic ATR Stop", GroupName = "Exit Management", Order = 7)] @@ -212,6 +243,43 @@ namespace NinjaTrader.NinjaScript.Strategies #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 + } + + [NinjaScriptProperty] + [Display(Name = "Runner Activation Mode", GroupName = "Exit Management", Order = 6, Description = "Auto: Qty>=2=Mode1, Qty=1=Mode2")] + public RunnerMode RunnerActivationMode { get; set; } + + #endregion + // INT8ExecutionBridge implementation public void EnterLongManaged(int quantity, string signalName, int stopTicks, int targetTicks, double tickSize) { @@ -263,21 +331,21 @@ namespace NinjaTrader.NinjaScript.Strategies /// The configured runner mode. /// The order quantity. /// The resolved runner mode. - private NT8.Core.Common.Models.RunnerMode ResolveRunnerMode(NT8.Core.Common.Models.RunnerMode configured, int qty) + private RunnerMode ResolveRunnerMode(RunnerMode configured, int qty) { - if (configured == NT8.Core.Common.Models.RunnerMode.Disabled) - return NT8.Core.Common.Models.RunnerMode.Disabled; - if (configured == NT8.Core.Common.Models.RunnerMode.Mode1DualLeg) - return NT8.Core.Common.Models.RunnerMode.Mode1DualLeg; - if (configured == NT8.Core.Common.Models.RunnerMode.Mode2RunnerOnly) - return NT8.Core.Common.Models.RunnerMode.Mode2RunnerOnly; - if (configured == NT8.Core.Common.Models.RunnerMode.Mode3ScalerOnly) - return NT8.Core.Common.Models.RunnerMode.Mode3ScalerOnly; + 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 quantity if (qty >= 2) - return NT8.Core.Common.Models.RunnerMode.Mode1DualLeg; - return NT8.Core.Common.Models.RunnerMode.Mode2RunnerOnly; + return RunnerMode.Mode1DualLeg; + return RunnerMode.Mode2RunnerOnly; } /// @@ -1072,109 +1140,109 @@ namespace NinjaTrader.NinjaScript.Strategies } var request = new OmsOrderRequest(); - request.Symbol = intent.Symbol; - request.Side = MapOrderSide(intent.Side); - request.Type = MapOrderType(intent.EntryType); - request.Quantity = sizingResult.Contracts; - request.LimitPrice = intent.LimitPrice.HasValue ? (decimal?)intent.LimitPrice.Value : null; - request.StopPrice = null; + request.Symbol = intent.Symbol; + request.Side = MapOrderSide(intent.Side); + request.Type = MapOrderType(intent.EntryType); + request.Quantity = sizingResult.Contracts; + request.LimitPrice = intent.LimitPrice.HasValue ? (decimal?)intent.LimitPrice.Value : null; + request.StopPrice = null; - if (EnableVerboseLogging) - { - Print(string.Format("[SDK] Submitting order: {0} {1} {2} @ {3}", - request.Side, - request.Quantity, - request.Symbol, - request.Type)); - } + if (EnableVerboseLogging) + { + Print(string.Format("[SDK] Submitting order: {0} {1} {2} @ {3}", + request.Side, + request.Quantity, + request.Symbol, + request.Type)); + } - SubmitOrderToNT8(request, intent); - _ordersSubmittedToday++; - } + SubmitOrderToNT8(request, intent); + _ordersSubmittedToday++; + } - private void SubmitOrderToNT8(OmsOrderRequest request, StrategyIntent intent) - { - if (State != State.Historical) - { - if (_circuitBreaker != null && !_circuitBreaker.ShouldAllowOrder()) - { - var cbState = _circuitBreaker.GetState(); - Print(String.Format("[SDK] Circuit breaker OPEN — order blocked: {0}", cbState.Reason)); - if (_logger != null) - _logger.LogWarning("Circuit breaker blocked order: {0}", cbState.Reason); - return; - } - } + private void SubmitOrderToNT8(OmsOrderRequest request, StrategyIntent intent) + { + if (State != State.Historical) + { + if (_circuitBreaker != null && !_circuitBreaker.ShouldAllowOrder()) + { + var cbState = _circuitBreaker.GetState(); + Print(String.Format("[SDK] Circuit breaker OPEN — order blocked: {0}", cbState.Reason)); + if (_logger != null) + _logger.LogWarning("Circuit breaker blocked order: {0}", cbState.Reason); + return; + } + } - try - { - // Resolve runner mode based on configuration and quantity - NT8.Core.Common.Models.RunnerMode resolvedMode = ResolveRunnerMode(RunnerActivationMode, request.Quantity); - Print(String.Format("[SDK] Runner mode resolved: {0} (Qty={1})", resolvedMode, request.Quantity)); + try + { + // Resolve runner mode based on configuration and quantity + RunnerMode resolvedMode = ResolveRunnerMode(RunnerActivationMode, request.Quantity); + Print(String.Format("[SDK] Runner mode resolved: {0} (Qty={1})", resolvedMode, request.Quantity)); - // Dynamic ATR-based stop calculation (before sizing/mode logic) - 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; - - // Pass ATR to context for Factor 3 and TrailingStopManager (in ticks) - if (intent.Context != null && intent.Context.CustomData != null) - intent.Context.CustomData["current_atr"] = atrValue / TickSize; + // Dynamic ATR-based stop calculation (before sizing/mode logic) + 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; - Print(String.Format("[SDK] Dynamic stop: ATR={0:F1}t x {1} = {2}t (${3})", - atrValue / TickSize, AtrMultiplier, intent.StopTicks, intent.StopTicks * 5)); - } + // Pass ATR to Metadata for Factor 3 and TrailingStopManager (in ticks) + if (intent.Metadata != null) + intent.Metadata["current_atr"] = atrValue / TickSize; - int scalerQty = 0; - int runnerQty = 0; - bool useRunnerLeg = false; - bool useScalerLeg = false; + Print(String.Format("[SDK] Dynamic stop: ATR={0:F1}t x {1} = {2}t (${3})", + atrValue / TickSize, AtrMultiplier, intent.StopTicks, intent.StopTicks * 5)); + } - switch (resolvedMode) - { - case NT8.Core.Common.Models.RunnerMode.Mode1DualLeg: - // Scaler leg: Qty-1 with fixed target, Runner leg: 1 with trail stop - scalerQty = request.Quantity >= 2 ? request.Quantity - 1 : request.Quantity; - runnerQty = 1; - useScalerLeg = scalerQty > 0; - useRunnerLeg = runnerQty > 0; - break; + int scalerQty = 0; + int runnerQty = 0; + bool useRunnerLeg = false; + bool useScalerLeg = false; - case NT8.Core.Common.Models.RunnerMode.Mode2RunnerOnly: - // Full qty on trailing stop only, no fixed target - scalerQty = 0; - runnerQty = request.Quantity; - useScalerLeg = false; - useRunnerLeg = true; - break; + switch (resolvedMode) + { + case RunnerMode.Mode1DualLeg: + // Scaler leg: Qty-1 with fixed target, Runner leg: 1 with trail stop + scalerQty = request.Quantity >= 2 ? request.Quantity - 1 : request.Quantity; + runnerQty = 1; + useScalerLeg = scalerQty > 0; + useRunnerLeg = runnerQty > 0; + break; - case NT8.Core.Common.Models.RunnerMode.Mode3ScalerOnly: - // Full qty with fixed target, no runner - scalerQty = request.Quantity; - runnerQty = 0; - useScalerLeg = true; - useRunnerLeg = false; - break; + case RunnerMode.Mode2RunnerOnly: + // Full qty on trailing stop only, no fixed target + scalerQty = 0; + runnerQty = request.Quantity; + useScalerLeg = false; + useRunnerLeg = true; + break; - case NT8.Core.Common.Models.RunnerMode.Disabled: - // Original single-leg behavior, no runner - scalerQty = request.Quantity; - runnerQty = 0; - useScalerLeg = true; - useRunnerLeg = false; - break; + case RunnerMode.Mode3ScalerOnly: + // Full qty with fixed target, no runner + scalerQty = request.Quantity; + runnerQty = 0; + useScalerLeg = true; + useRunnerLeg = false; + break; - default: - // Fallback: Auto mode default behavior (should not reach here since ResolveRunnerMode handles Auto) - scalerQty = request.Quantity; - runnerQty = 0; - useScalerLeg = true; - useRunnerLeg = false; - break; - } + case RunnerMode.Disabled: + // Original single-leg behavior, no runner + scalerQty = request.Quantity; + runnerQty = 0; + useScalerLeg = true; + useRunnerLeg = false; + break; + + default: + // Fallback: Auto mode default behavior (should not reach here since ResolveRunnerMode handles Auto) + scalerQty = request.Quantity; + runnerQty = 0; + useScalerLeg = true; + useRunnerLeg = false; + break; + } string baseId = Guid.NewGuid().ToString("N").Substring(0, 12); _scalerSignalName = useScalerLeg ? String.Format("SDK_{0}_S_{1}", intent.Symbol, baseId) : null;