From e68b138fc69dca61bf95c9ea5f767120a223967e Mon Sep 17 00:00:00 2001 From: mo Date: Mon, 3 Aug 2026 08:54:54 -0400 Subject: [PATCH] GAP-032: enforce session daily trade limit - retain accepted-trade count after position-flat events - reject same-session entries with explicit MaxDailyTrades logging - verify next-session re-entry and update Gate 3 governance Build: clean | Tests: 500 passing | Dual-deployed: yes --- NEXT_PROMPT.md | 2 +- SPRINT_BOARD.md | 7 +- docs/00-governance/active_work.md | 2 +- docs/00-governance/common_failures.md | 5 + docs/00-governance/current_status.md | 5 +- .../patterns_and_antipatterns.md | 4 + .../Strategies/NT8StrategyBase.cs | 12 +- .../Examples/SimpleORBStrategy.cs | 12 +- .../Intelligence/OrbConfluenceFactorTests.cs | 103 ++++++++++++++++++ 9 files changed, 132 insertions(+), 20 deletions(-) diff --git a/NEXT_PROMPT.md b/NEXT_PROMPT.md index a7bc9b6..1c883b5 100644 --- a/NEXT_PROMPT.md +++ b/NEXT_PROMPT.md @@ -5,7 +5,7 @@ This is a **human operator procedure**, not a coding task. Gate 2 was contaminated. Do not change strategy source or deploy any branch work after the Gate 3 configuration freeze. -1. Start NinjaTrader and use the NinjaScript Editor to compile the provenance fix deployed on 2026-08-03. +1. Start NinjaTrader and use the NinjaScript Editor to compile the Gate 3 provenance and daily-limit fixes deployed on 2026-08-03. 2. In SimSimple ORB, set and triple-check: - `EnableDynamicStop=TRUE` - `RunnerActivationMode=Auto` diff --git a/SPRINT_BOARD.md b/SPRINT_BOARD.md index b167cec..2cb97c5 100644 --- a/SPRINT_BOARD.md +++ b/SPRINT_BOARD.md @@ -11,7 +11,7 @@ | Provenance | ✅ | Gate 3 fix serializes grade, score, submitted runner mode, and ORB ticks from the accepted intent/submission data. | | Scenario coverage | 🟡 | 5/8 genuine assertions; 3 explicitly deferred for missing seams. | | Gate Run #2 | ❌ | Contaminated; provenance defects were identified after the run. | -| Gate Run #3 | ⏳ | Provenance fix deployed; complete the manual NinjaScript compile and freeze a new configuration. | +| Gate Run #3 | ⏳ | Provenance and daily-limit fixes deployed; complete the manual NinjaScript compile and freeze a new configuration. | > **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. @@ -52,6 +52,11 @@ - Trade JSONL now serializes confluence grade/score and ORB ticks from the accepted intent metadata and the exact runner mode resolved for submission. - Release build passed with zero errors; 498 tests passed; deployed source and assembly hashes match. Manual NinjaScript compile remains part of RB-4.1. +**[GAP-032] Session-Scoped MaxDailyTrades Enforcement** | ✅ 2026-08-03 +- Position-flat updates no longer reset trade eligibility; the accepted-intent count persists until trading-date rollover. +- Same-session rejection logs `MaxDailyTrades reached`; next-session first entry is covered by tests. +- Release build passed; 500 tests passed; deployed source and assembly hashes match. Manual NinjaScript compile remains part of RB-4.1. + **[TASK-GOV-02] Governance Truth Reconciliation** | ✅ 2026-07-13 - Restored the July 11 historical record, corrected documentation placement, and logged DEC-20260713-02. diff --git a/docs/00-governance/active_work.md b/docs/00-governance/active_work.md index 91a5d44..156365b 100644 --- a/docs/00-governance/active_work.md +++ b/docs/00-governance/active_work.md @@ -5,7 +5,7 @@ **Owner:** Human operator **State:** Active; Gate 2 was contaminated and the Gate 3 clock has not started. -1. Start NinjaTrader and run the NinjaScript compile check for the provenance fix deployed on 2026-08-03. +1. Start NinjaTrader and run the NinjaScript compile check for the Gate 3 provenance and daily-limit fixes deployed on 2026-08-03. 2. In SimSimple ORB, set and triple-check: - `EnableDynamicStop=TRUE` - `RunnerActivationMode=Auto` diff --git a/docs/00-governance/common_failures.md b/docs/00-governance/common_failures.md index 8f83985..d5f4c24 100644 --- a/docs/00-governance/common_failures.md +++ b/docs/00-governance/common_failures.md @@ -51,3 +51,8 @@ Record concise error fingerprints and verified fixes. - **Root cause:** The JSONL writer read confluence values from static strategy configuration and recomputed runner mode with quantity `1`, while the session logger used accepted intent metadata and the actual resolved submission mode. - **Fix:** Serialize from the accepted `StrategyIntent.Metadata` and pass the submission's `resolvedMode` into the provenance writer. - **Prevention:** Logging artifacts for a submitted trade must consume the same immutable decision/submission objects used by the human-readable session log. + +## 2026-08-03 [GAP-032] — Position-flat event bypassed MaxDailyTrades +- **Root cause:** Position closure cleared `_tradeTaken`, while the daily-limit guard required both `_tradeTaken` and a count at the limit. +- **Fix:** Make `_dailyTradeCount >= MaxDailyTrades` authoritative and reset the count only in session rollover handling. +- **Prevention:** Daily eligibility counters must be scoped to trading date, never position lifecycle. diff --git a/docs/00-governance/current_status.md b/docs/00-governance/current_status.md index 0b26494..5e9da48 100644 --- a/docs/00-governance/current_status.md +++ b/docs/00-governance/current_status.md @@ -2,7 +2,7 @@ **Last Updated:** 2026-08-03 ## Verified implementation state -- **Last completed task:** GAP-031 — Trade Provenance Signal/Submission Wiring +- **Last completed task:** GAP-032 — Session-Scoped MaxDailyTrades Enforcement - **Active task:** RB-4.1 — Gate Run #3 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 @@ -10,10 +10,11 @@ ## Build and test evidence - `verify-build.bat` is not executable under Windows `cmd.exe` because the tracked batch file uses LF-only line endings. - Release build: **0 errors**, **9 existing CS1998 warnings**. -- Tests: **498 passed, 0 failed** — 410 Core, 78 Integration, 10 Performance. +- Tests: **500 passed, 0 failed** — 412 Core, 78 Integration, 10 Performance. ## Gate readiness - Trade provenance now reads grade, weighted score, and ORB ticks from the accepted intent metadata and records the exact runner mode resolved for submission. +- `MaxDailyTrades` now remains enforced after position-flat events and resets only when the trading session date rolls over. - 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 3 start:** complete the pending NinjaTrader compile check, freeze the configuration, and enforce the no-deploy rule. diff --git a/docs/00-governance/patterns_and_antipatterns.md b/docs/00-governance/patterns_and_antipatterns.md index 5ead913..d3be726 100644 --- a/docs/00-governance/patterns_and_antipatterns.md +++ b/docs/00-governance/patterns_and_antipatterns.md @@ -57,3 +57,7 @@ Capture recurring implementation patterns that impact compile stability. ## 2026-08-03 [GAP-031] — Submission-sourced trade provenance - **DO:** Serialize grade, score, ORB range, and resolved mode from the accepted intent and the exact submission decision. - **DON'T:** Recompute trade facts later from configuration defaults or assumed quantities. + +## 2026-08-03 [GAP-032] — Session-scoped daily trade limits +- **DO:** Increment on accepted intent and reset only when the trading session date changes. +- **DON'T:** Re-arm a daily trade allowance when a position returns flat. diff --git a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs index 0805441..e6aef43 100644 --- a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs +++ b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs @@ -839,19 +839,13 @@ namespace NinjaTrader.NinjaScript.Strategies FileLog(string.Format("PNL_UPDATE DayPnL={0:C} Position={1} Qty={2}", dayPnL, marketPosition, quantity)); - // GAP-006: Clear _tradeTaken when position goes flat (position-close-driven re-arm) - // This replaces the bar-driven re-arm in SimpleORBStrategy which was unreliable + // Position state must not reset the session-scoped daily trade limit. if (marketPosition == MarketPosition.Flat || quantity == 0) { - if (_sdkStrategy != null && _sdkStrategy.GetParameters().ContainsKey("force_session_reset")) - { - // Let the strategy handle its own tradeTaken flag - _sdkStrategy.SetParameters(new Dictionary { { "clear_trade_taken", true } }); - } if (EnableVerboseLogging) - Print(string.Format("[SDK] Position flat detected — clearing tradeTaken flag")); + Print(string.Format("[SDK] Position flat detected — daily trade count remains active until session rollover")); if (EnableFileLogging && State == State.Realtime) - FileLog("POSITION FLAT — clearing tradeTaken flag"); + FileLog("POSITION FLAT — daily trade count remains active until session rollover"); } } catch (Exception ex) diff --git a/src/NT8.Strategies/Examples/SimpleORBStrategy.cs b/src/NT8.Strategies/Examples/SimpleORBStrategy.cs index 29b4e6e..f59e75c 100644 --- a/src/NT8.Strategies/Examples/SimpleORBStrategy.cs +++ b/src/NT8.Strategies/Examples/SimpleORBStrategy.cs @@ -443,11 +443,11 @@ namespace NT8.Strategies.Examples maxDailyTrades = (int)mdv; } - if (_tradeTaken && _dailyTradeCount >= maxDailyTrades) + if (_dailyTradeCount >= maxDailyTrades) { if (_logger != null) - _logger.LogDebug( - "SimpleORBStrategy skip: daily trade limit reached ({0}/{1}) for session {2:yyyy-MM-dd}; bar={3:yyyy-MM-dd HH:mm}; symbol={4}", + _logger.LogInformation( + "MaxDailyTrades reached ({0}/{1}) for session {2:yyyy-MM-dd}; rejecting signal at {3:yyyy-MM-dd HH:mm}; symbol={4}", _dailyTradeCount, maxDailyTrades, _currentSessionDate, @@ -748,7 +748,8 @@ namespace NT8.Strategies.Examples } } - // GAP-006: clear_trade_taken from NT8StrategyBase.OnPositionUpdate when position goes flat + // Retained for compatibility with older adapters. Position-flat state must not + // reset session-scoped trade eligibility; ResetSession owns the daily reset. if (parameters.ContainsKey("clear_trade_taken")) { var val = parameters["clear_trade_taken"]; @@ -756,11 +757,10 @@ namespace NT8.Strategies.Examples { lock (_lock) { - _tradeTaken = false; _breakoutBarSeen = false; _pendingBreakoutDirection = 0; if (_logger != null) - _logger.LogInformation("Position-close re-arm: _tradeTaken cleared"); + _logger.LogInformation("Position flat: MaxDailyTrades count retained until session rollover"); } } } diff --git a/tests/NT8.Core.Tests/Intelligence/OrbConfluenceFactorTests.cs b/tests/NT8.Core.Tests/Intelligence/OrbConfluenceFactorTests.cs index cb73d4d..7a877a2 100644 --- a/tests/NT8.Core.Tests/Intelligence/OrbConfluenceFactorTests.cs +++ b/tests/NT8.Core.Tests/Intelligence/OrbConfluenceFactorTests.cs @@ -472,6 +472,109 @@ namespace NT8.Core.Tests.Intelligence Assert.IsNull(intent2, "Second trade should be blocked when MaxDailyTrades=1"); } + [TestMethod] + public void SimpleORB_MaxDailyTrades_PositionFlatDoesNotRearmSameSession() + { + var logger = new RecordingLogger(); + var strategy = CreateDailyLimitStrategy(logger); + DateTime sessionStart = DateTime.Today.AddHours(9.5); + StrategyContext context = CreateDailyLimitContext(sessionStart); + + StrategyIntent first = strategy.OnBar(CreateBreakoutBar(sessionStart.AddMinutes(44)), context); + Assert.IsNotNull(first, "First signal should fire"); + first.Metadata["trade_grade"] = "A"; + var positionFlat = new Dictionary(); + positionFlat.Add("clear_trade_taken", true); + strategy.SetParameters(positionFlat); + context.CurrentTime = sessionStart.AddMinutes(54); + StrategyIntent second = strategy.OnBar(CreateBreakoutBar(sessionStart.AddMinutes(54)), context); + + Assert.AreEqual("A", first.Metadata["trade_grade"].ToString(), "Synthetic first signal must be grade A"); + Assert.IsNull(second, "Second same-session signal must be rejected after position returns flat"); + Assert.IsTrue(logger.Contains("MaxDailyTrades reached"), "Rejection must log MaxDailyTrades reached"); + } + + [TestMethod] + public void SimpleORB_MaxDailyTrades_NextSessionAllowsFirstSignal() + { + var logger = new RecordingLogger(); + var strategy = CreateDailyLimitStrategy(logger); + DateTime firstSessionStart = DateTime.Today.AddHours(9.5); + StrategyContext context = CreateDailyLimitContext(firstSessionStart); + + StrategyIntent first = strategy.OnBar(CreateBreakoutBar(firstSessionStart.AddMinutes(44)), context); + Assert.IsNotNull(first, "First session signal should fire"); + first.Metadata["trade_grade"] = "A"; + DateTime nextSessionStart = firstSessionStart.AddDays(1); + context.Session = new MarketSession(nextSessionStart, nextSessionStart.Date.AddHours(16), true, "RTH"); + context.CurrentTime = nextSessionStart.AddMinutes(44); + StrategyIntent nextDay = strategy.OnBar(CreateBreakoutBar(nextSessionStart.AddMinutes(44)), context); + + Assert.AreEqual("A", first.Metadata["trade_grade"].ToString(), "Synthetic first signal must be grade A"); + Assert.IsNotNull(nextDay, "First signal after session rollover should fire normally"); + } + + private static NT8.Strategies.Examples.SimpleORBStrategy CreateDailyLimitStrategy(ILogger logger) + { + var strategy = new NT8.Strategies.Examples.SimpleORBStrategy(30, 1.0); + var config = new StrategyConfig( + "SimpleORB", + "NQ", + new Dictionary(), + new RiskConfig(1000.0, 200.0, 2, false), + new SizingConfig(SizingMethod.FixedDollarRisk, 1, 3, 100.0, null)); + config.Parameters.Add("TestMode", true); + config.Parameters.Add("MaxDailyTrades", 1); + config.Parameters.Add("StopTicks", 8); + config.Parameters.Add("TargetTicks", 16); + config.Parameters.Add("MinTradeGrade", 1); + strategy.Initialize(config, null, logger); + return strategy; + } + + private static StrategyContext CreateDailyLimitContext(DateTime sessionStart) + { + var session = new MarketSession(sessionStart, sessionStart.Date.AddHours(16), true, "RTH"); + return new StrategyContext( + "NQ", + sessionStart.AddMinutes(44), + null, + new AccountInfo(100000, 100000, 0, 0, DateTime.UtcNow), + session, + new Dictionary()); + } + + private static BarData CreateBreakoutBar(DateTime time) + { + return new BarData("NQ", time, 19000, 19060, 18990, 19065, 1500, TimeSpan.FromMinutes(5)); + } + + private class RecordingLogger : ILogger + { + private readonly List _messages = new List(); + + public bool Contains(string value) + { + for (int i = 0; i < _messages.Count; i++) + { + if (_messages[i].IndexOf(value, StringComparison.Ordinal) >= 0) + return true; + } + return false; + } + + public void LogDebug(string message, params object[] args) { Add(message, args); } + public void LogInformation(string message, params object[] args) { Add(message, args); } + public void LogWarning(string message, params object[] args) { Add(message, args); } + public void LogError(string message, params object[] args) { Add(message, args); } + public void LogCritical(string message, params object[] args) { Add(message, args); } + + private void Add(string message, params object[] args) + { + _messages.Add(args != null && args.Length > 0 ? String.Format(message, args) : message); + } + } + private static StrategyIntent CreateIntent() { return new StrategyIntent(