diff --git a/SPRINT_BOARD.md b/SPRINT_BOARD.md index ffd4e63..e29a907 100644 --- a/SPRINT_BOARD.md +++ b/SPRINT_BOARD.md @@ -49,10 +49,10 @@ - **Part 2 implemented 2026-08-23 (DEC-20260823-01):** replaced the five wrong `1.0` literals with the designed values. Composite normalization already correct (dynamic `weightedScoreSum/totalWeight`) — verified, unchanged. No SIM trade required to validate; fully tested in `NT8.Core`. - Prompt: `TASK_GAP047_PART2_WEIGHT_RUNTIME_PROMPT.md`. Verification: `verify-build.bat` 514/514, Core Release no-build 425/425, deploy backup `20260823_135331`. Fresh gate config freeze needed before any gate evidence collected after this lands. -**[GAP-055] `MaxDailyTrades` does not survive a strategy restart** | Stage 0 | ✅ READY +**[GAP-055] `MaxDailyTrades` does not survive a strategy restart** | Stage 0 | ✅ IMPLEMENTED — deployed 2026-08-23 - In-memory counter only (`SimpleORBStrategy.cs` ~39). CME trading date 2026-08-17 took two trades under `MaxDailyTrades=1` across two NT8 sessions; the second session's `DayPnL=$271.96 → $545.44` proves NT8 treated them as one day. - Same class as the 7/28 breach that helped void Gate Run #2. **A gate run cannot currently guarantee its own cap.** -- Prompt: `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md`. +- Prompt: `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md`. Verification: `verify-build.bat` 521/521, Core Release no-build 432/432, deploy backup `20260823_143311`. Manual NT8 compile and SIM restart validation still required. **[GAP-048] Reject-reason taxonomy conflates four causes under `KillSwitch`** | Stage 0 | ✅ IMPLEMENTED — deployed 2026-08-23 - 2026-08-17 logged `reason=KillSwitch count=647` from a real kill switch; 2026-08-18 logged `count=5` from `MaxTradeRisk`. Same label. `GradeFilter` is overloaded four ways as well. diff --git a/docs/00-governance/2026-08-19-run-book.md b/docs/00-governance/2026-08-19-run-book.md index ef42d23..b42b2d6 100644 --- a/docs/00-governance/2026-08-19-run-book.md +++ b/docs/00-governance/2026-08-19-run-book.md @@ -85,8 +85,8 @@ NinjaTrader needs to be reopened for a manual NinjaScript compile, then a SIM tr **Play 7 — Risk guards, all three parts (DEC-19a/19b accepted).** Hand `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` to Kilocode in full — Part 3 is now written as directly actionable: implement the Tier 1 check reordering (post-sizing, `Qty`-aware) and confirm MNQ is present and correctly valued in both `GetTickValue` tables (GAP-052) as prep for the later cutover. **Do this on the current NQ configuration — do not switch the traded instrument as part of this task.** That's Play 11. -**Play 8 — MaxDailyTrades persistence (DEC-21 accepted).** -Hand `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` to Kilocode. Validate with a manual restart test spanning a simulated 18:00 ET rollover boundary — confirm the count persists across a restart within the same trading day and resets across the boundary. +**Play 8 — MaxDailyTrades persistence (DEC-21 accepted). IMPLEMENTED 2026-08-23, manual SIM restart validation pending.** +`TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` now persists `{trading_date, daily_trade_count, account, strategy_name, symbol}` to `daily_trade_count__.json`, rehydrates same-date count, resets and overwrites on a new trading date, and skips file I/O when `Account == null`. Automated tests cover same-date restore, new-date reset, corrupt file, backtest no-I/O, and the 2026-08-16 19:12 / 2026-08-17 11:04 same-CME-date scenario. Remaining validation: manual NT8 compile plus SIM restart test confirming the next same-day signal rejects with `REJECT: reason=MaxDailyTrades`. **Play 9 — GAP-049 telemetry direction fix.** No decision gate — this is dashboard/telemetry accuracy only. Hand `TASK_GAP049_TELEMETRY_DIRECTION_PROMPT.md` to Kilocode any time today. Validate by re-checking the implausible -523.25 point gap value the task flags; confirm it resolves to a sane number after the fix. @@ -115,7 +115,7 @@ This is a separate, later step — not part of today's six tasks. Once GAP-054, - [x] GAP-048 taxonomy: implemented, tested, SPRINT_BOARD updated; manual NT8/dashboard spot-check pending - [x] GAP-047 Part 1/2: study delivered, DEC-20260823-01 accepted, runtime designed weights implemented and tested - [ ] GAP-054 runner trail: implemented, validated on sim/replay before any live gate run -- [ ] GAP-055 persistence: implemented, restart/rollover-boundary test passed +- [x] GAP-055 persistence: implemented and automated restart/rollover-boundary tests passed; manual SIM restart validation pending - [ ] GAP-045/046 all three parts: implemented on NQ, including the post-sizing Tier 1 reorder and the MNQ tick-table check - [ ] GAP-049 telemetry: implemented, -523.25 anomaly re-checked and resolved - [ ] `git status --short` re-checked: confirm exactly the files each TASK prompt's DO list authorized, nothing else diff --git a/docs/00-governance/active_work.md b/docs/00-governance/active_work.md index 2ce9ed4..0170bea 100644 --- a/docs/00-governance/active_work.md +++ b/docs/00-governance/active_work.md @@ -15,7 +15,7 @@ Full detail: `docs/NT8_SDK_Master_Document_v7.0_Complete.docx`. | 1 | **GAP-046** — set `AccountStartingBalance` or disable `EnableTrailingDrawdown` | operator action, no code | Operator | Every entry, from 14:30 ET daily | | 2 | **GAP-045/046 guards** — resolved: MNQ (cutover staged separately) + per-position semantics | `TASK_GAP045_GAP046_RISK_GUARDS_PROMPT.md` (Part 3 now actionable) | Kilocode, on current NQ config | All high-ATR days | | 3 | **GAP-048** — split the reject taxonomy | `TASK_GAP048_REJECT_TAXONOMY_PROMPT.md` — implemented/deployed 2026-08-23, backup `20260823_142014` | Kilocode | Manual NT8 compile and dashboard spot-check | -| 4 | **GAP-055** — persist `MaxDailyTrades` across restarts | `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` | Kilocode | Gate Run #3 sample integrity | +| 4 | **GAP-055** — persist `MaxDailyTrades` across restarts | `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md` — implemented/deployed 2026-08-23, backup `20260823_143311` | Kilocode | Manual NT8 compile and SIM restart validation | | 5 | **GAP-047** — Part 1 complete (commit `cbf45df`), Part 2 runtime weight fix implemented 2026-08-23 | `TASK_GAP047_PART2_WEIGHT_RUNTIME_PROMPT.md` — verification passed, deploy backup `20260823_135331` | Kilocode | Fresh gate freeze needed before gate evidence | | 6 | **GAP-054** — auto-breakeven destroys the runner trail | `TASK_GAP054_RUNNER_TRAIL_PROMPT.md` — **Option 0 implemented + source-verified 2026-08-21, NOT yet SIM-validated, NOT committed** | Kilocode implemented; operator validates | **RUNNER-001**, still blocked until SIM/replay validation passes | | 7 | **GAP-049** — telemetry `STATE:` score is direction-incorrect | `TASK_GAP049_TELEMETRY_DIRECTION_PROMPT.md` | Kilocode | Dashboard trustworthiness; degrades item 5 | diff --git a/docs/00-governance/current_status.md b/docs/00-governance/current_status.md index f329d1b..04bcf9a 100644 --- a/docs/00-governance/current_status.md +++ b/docs/00-governance/current_status.md @@ -1,5 +1,26 @@ # Current Status — NT8 SDK -**Last Updated:** 2026-08-23 (GAP-048 reject taxonomy implemented and deployed) +**Last Updated:** 2026-08-23 (GAP-055 MaxDailyTrades persistence implemented and deployed) + +--- + +## 2026-08-23 — GAP-055 IMPLEMENTED, manual NT8/SIM restart validation pending + +Kilocode executed `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md`. `MaxDailyTrades` now persists across live/SIM strategy restarts by writing `{LogDirectory}\daily_trade_count__.json` after each daily-count increment and rehydrating once per trading date on the first realtime-eligible bar after session reset. + +Implementation notes: +- Persistence is opt-in from the NT8 adapter and enabled only when `Account != null`. +- Strategy Analyzer/backtest paths with `Account == null` do not read or write the file. +- Trading date follows the adapter/session date already used by `BuildSessionInfo()` / `MarketSession.SessionStart`, so the 2026-08-16 19:12 ET and 2026-08-17 11:04 ET sessions both resolve to trading date 2026-08-17. +- Missing/corrupt/unreadable files start at zero, log a warning, and do not throw. +- File key is account + strategy name as specified; `symbol` is stored in the payload, and multiple same-account/same-strategy instances share the same counter by design for this task. + +Evidence: +- Added tests for same-date restore, new-date reset/overwrite, corrupt-file warning/no throw, `Account == null` no-read/no-write behavior, and the 2026-08-16 evening / 2026-08-17 morning same-CME-date scenario. +- `verify-build.bat`: passed, 521/521 tests. +- `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build --verbosity minimal`: passed, 432/432. +- `deployment\deploy-to-nt8.bat`: completed; backup `deployment\backups\20260823_143311`; `NinjaTrader.Custom.dll` was not present to invalidate. + +Next required action: manual NinjaScript compile after starting NinjaTrader, then SIM validation by taking one trade, stopping/restarting the strategy on the same trading day, and confirming the next signal is rejected with `REJECT: reason=MaxDailyTrades`. --- diff --git a/docs/00-governance/decisions.md b/docs/00-governance/decisions.md index 6ddbd68..8836497 100644 --- a/docs/00-governance/decisions.md +++ b/docs/00-governance/decisions.md @@ -60,7 +60,9 @@ Use this file to record durable project decisions that affect implementation pat - **Decision:** Persist `{trading_date, daily_trade_count, account, strategy_name, symbol}` to `{LogDirectory}/daily_trade_count__.json` on each increment, and rehydrate at `State.Realtime` entry when the persisted trading date matches. Reuse the persistence pattern already established for the Conservative trailing-drawdown halt file (DEC-20260818-17) rather than inventing a second mechanism. Align the trading-date boundary with the CME session rollover (18:00 ET) rather than the calendar date, using `SessionManager` or NT8's own session date if either already exposes it. Strategy Analyzer/backtest (`Account == null`) must neither read nor write the file so backtest behaviour is byte-for-byte unchanged. - **Consequences:** Gate discipline explicitly contemplates restarts (recompiles, workspace changes, connection recovery), so without this a gate run under `MaxDailyTrades=1` cannot guarantee its own cap and its sample is uninterpretable in the same way the previous two were. Adds a small file-I/O dependency to the realtime path; a missing or corrupt file must degrade to count-zero plus a WARNING, never an exception. - **Related Files:** `src/NT8.Strategies/Examples/SimpleORBStrategy.cs`, `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md`, `docs/00-governance/decisions.md` -- **Action Required:** Accepted. Execute `TASK_GAP055_MAXDAILYTRADES_PERSIST_PROMPT.md`; then verify by taking one SIM trade, restarting the strategy the same trading day, and confirming the next signal is rejected with `REJECT: reason=MaxDailyTrades`. +- **Implementation Note (2026-08-23):** Implemented as opt-in live/SIM persistence from the adapter into `SimpleORBStrategy`. `NT8StrategyBase` enables persistence only when `Account != null`, passes account/name/resolved log directory metadata at `State.Realtime`, and also includes the metadata on realtime contexts. `SimpleORBNT8` seeds the same metadata into the shared `StrategyConfig`. `SimpleORBStrategy` rehydrates once per trading date on the first realtime-eligible bar after session reset, restores when the file date matches, resets and overwrites when the date differs, writes after every daily-count increment, and logs either `DAILY_TRADE_COUNT restored: date= count= max=` or `DAILY_TRADE_COUNT reset: new trading date `. Missing/corrupt/unreadable files degrade to count zero plus `DAILY_TRADE_COUNT warning...` without throwing. Trading date follows the adapter/session date already used by `BuildSessionInfo()`/`MarketSession.SessionStart`, so 2026-08-16 19:12 ET and 2026-08-17 11:04 ET both resolve to trading date 2026-08-17. Backtest/Strategy Analyzer contexts with `Account == null` do not read or write state even if persistence parameters are present. The file key is exactly the approved `{AccountName}_{StrategyName}` path; `symbol` is recorded in the payload, but multiple same-account/same-strategy instances intentionally share the counter and distinct per-instance keys remain out of scope. +- **Verification (2026-08-23):** Added tests for same-date restore, new-date reset/overwrite, corrupt-file warning/no throw, `Account == null` no-read/no-write behavior, and the 2026-08-16 19:12 / 2026-08-17 11:04 same-CME-date restart scenario. `verify-build.bat` passed 521/521 tests (432 Core, 79 Integration, 10 Performance); `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build --verbosity minimal` passed 432/432; `deployment\deploy-to-nt8.bat` completed with backup `20260823_143311` and noted `NinjaTrader.Custom.dll` was not present to invalidate. +- **Action Required:** Manually compile in NinjaTrader, then validate in SIM by taking one trade, stopping/restarting the strategy on the same trading day, and confirming the next signal is rejected with `REJECT: reason=MaxDailyTrades`. ### DEC-20260818-20 - **ID:** DEC-20260818-20 diff --git a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs index 3074ce5..ac3047c 100644 --- a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs +++ b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs @@ -586,6 +586,16 @@ namespace NinjaTrader.NinjaScript.Strategies Print(string.Format("[SDK] ForceSessionReset: _tradeTaken cleared on live start at {0}", DateTime.Now.ToString("HH:mm:ss"))); } + if (_sdkStrategy != null && Account != null) + { + var dailyCountParams = new Dictionary(); + dailyCountParams.Add("daily_trade_count_persistence_enabled", true); + dailyCountParams.Add("daily_trade_count_account", Account.Name); + dailyCountParams.Add("daily_trade_count_strategy_name", Name); + dailyCountParams.Add("daily_trade_count_log_directory", ResolveLogDirectory(false, "daily trade count state")); + _sdkStrategy.SetParameters(dailyCountParams); + } + // TASK-00a: Write session provenance on realtime transition WriteSessionProvenance(); @@ -1786,6 +1796,10 @@ namespace NinjaTrader.NinjaScript.Strategies customData.Add("BarsRequiredToTrade", BarsRequiredToTrade); customData.Add("OrdersToday", _ordersSubmittedToday); customData.Add("AllowDailyTradeCountIncrement", ShouldAllowDailyTradeCountIncrement()); + customData.Add("daily_trade_count_persistence_enabled", State == State.Realtime && Account != null); + customData.Add("daily_trade_count_account", Account != null ? Account.Name : string.Empty); + customData.Add("daily_trade_count_strategy_name", Name); + customData.Add("daily_trade_count_log_directory", ResolveLogDirectory(false, "daily trade count state")); // GAP-010: Pass short trend filter setting to SDK strategy customData.Add("EnableShortTrendFilter", EnableShortTrendFilter); diff --git a/src/NT8.Adapters/Strategies/SimpleORBNT8.cs b/src/NT8.Adapters/Strategies/SimpleORBNT8.cs index d456a69..54f0d18 100644 --- a/src/NT8.Adapters/Strategies/SimpleORBNT8.cs +++ b/src/NT8.Adapters/Strategies/SimpleORBNT8.cs @@ -344,6 +344,10 @@ namespace NinjaTrader.NinjaScript.Strategies _strategyConfig.Parameters["MinTradeGrade"] = MinTradeGrade; _strategyConfig.Parameters["TestMode"] = TestMode; _strategyConfig.Parameters["MaxDailyTrades"] = MaxDailyTrades; + _strategyConfig.Parameters["daily_trade_count_persistence_enabled"] = Account != null; + _strategyConfig.Parameters["daily_trade_count_account"] = Account != null ? Account.Name : string.Empty; + _strategyConfig.Parameters["daily_trade_count_strategy_name"] = Name; + _strategyConfig.Parameters["daily_trade_count_log_directory"] = ResolveLogDirectory(false, "daily trade count state"); _strategyConfig.Parameters["EnableBarBasedRearm"] = EnableBarBasedRearm; _strategyConfig.Parameters["EnableShortTrendFilter"] = EnableShortTrendFilter; _strategyConfig.Parameters["EnableCMEHolidayGuard"] = EnableCMEHolidayGuard; diff --git a/src/NT8.Strategies/Examples/SimpleORBStrategy.cs b/src/NT8.Strategies/Examples/SimpleORBStrategy.cs index 5dc2aa7..94529cf 100644 --- a/src/NT8.Strategies/Examples/SimpleORBStrategy.cs +++ b/src/NT8.Strategies/Examples/SimpleORBStrategy.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using NT8.Core.Calendar; using NT8.Core.Common.Interfaces; using NT8.Core.Common.Models; @@ -41,6 +42,11 @@ namespace NT8.Strategies.Examples private int _pendingBreakoutDirection; private int _consecutiveWins; private int _consecutiveLosses; + private bool _dailyTradeCountPersistenceEnabled; + private bool _dailyTradeCountPersistenceInitialized; + private string _dailyTradeCountAccountName; + private string _dailyTradeCountStrategyName; + private string _dailyTradeCountLogDirectory; // GAP-006: Gate legacy bar-driven _tradeTaken re-arm for SIM-only mode private bool _enableBarBasedRearm = false; @@ -271,6 +277,11 @@ namespace NT8.Strategies.Examples _pendingBreakoutDirection = 0; _consecutiveWins = 0; _consecutiveLosses = 0; + _dailyTradeCountPersistenceEnabled = false; + _dailyTradeCountPersistenceInitialized = false; + _dailyTradeCountAccountName = string.Empty; + _dailyTradeCountStrategyName = string.Empty; + _dailyTradeCountLogDirectory = string.Empty; Metadata = new StrategyMetadata( "Simple ORB", @@ -466,6 +477,22 @@ namespace NT8.Strategies.Examples return null; } + EnsureDailyTradeCountPersistence(context, maxDailyTrades); + + if (_dailyTradeCount >= maxDailyTrades) + { + if (_logger != null) + _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, + bar.Time, + context.Symbol); + RecordSignalRejection(context, "MaxDailyTrades", string.Format("DailyTradeCount={0} MaxDailyTrades={1} Session={2:yyyy-MM-dd} Symbol={3}", _dailyTradeCount, maxDailyTrades, _currentSessionDate, context.Symbol), bar.Time); + return null; + } + // GAP-006: Bar-driven re-arm only when EnableBarBasedRearm is true // Default is false for live trading; position-close re-arm is now primary // After a trade completes and we are below MaxDailyTrades, reset the @@ -667,7 +694,10 @@ namespace NT8.Strategies.Examples _tradeTaken = true; if (ShouldIncrementDailyTradeCount(context)) + { _dailyTradeCount++; + PersistDailyTradeCount(context); + } if (_logger != null) _logger.LogDebug( @@ -765,6 +795,8 @@ namespace NT8.Strategies.Examples } } + ApplyDailyTradeCountPersistenceParameters(parameters); + // 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")) @@ -959,6 +991,7 @@ namespace NT8.Strategies.Examples _openingRangeReady = false; _tradeTaken = false; _dailyTradeCount = 0; + _dailyTradeCountPersistenceInitialized = false; _breakoutBarSeen = false; _pendingBreakoutDirection = 0; @@ -993,6 +1026,196 @@ namespace NT8.Strategies.Examples context.CustomData["signal_reject_line"] = string.Format("REJECT: reason={0} detail={1} bar={2:yyyy-MM-dd HH:mm:ss}", reason, detail, barTime); } + private void ApplyDailyTradeCountPersistenceParameters(Dictionary parameters) + { + if (parameters.ContainsKey("daily_trade_count_persistence_enabled")) + { + var enabled = parameters["daily_trade_count_persistence_enabled"]; + if (enabled is bool) + _dailyTradeCountPersistenceEnabled = (bool)enabled; + } + + if (parameters.ContainsKey("daily_trade_count_account")) + _dailyTradeCountAccountName = Convert.ToString(parameters["daily_trade_count_account"]); + + if (parameters.ContainsKey("daily_trade_count_strategy_name")) + _dailyTradeCountStrategyName = Convert.ToString(parameters["daily_trade_count_strategy_name"]); + + if (parameters.ContainsKey("daily_trade_count_log_directory")) + _dailyTradeCountLogDirectory = Convert.ToString(parameters["daily_trade_count_log_directory"]); + } + + private void EnsureDailyTradeCountPersistence(StrategyContext context, int maxDailyTrades) + { + if (!ShouldUseDailyTradeCountPersistence(context)) + return; + + if (_dailyTradeCountPersistenceInitialized) + return; + + _dailyTradeCountPersistenceInitialized = true; + + string path = GetDailyTradeCountFilePath(context); + if (string.IsNullOrEmpty(path)) + return; + + try + { + if (File.Exists(path)) + { + DailyTradeCountState state = JsonConvert.DeserializeObject(File.ReadAllText(path)); + DateTime persistedDate; + if (state != null && DateTime.TryParse(state.trading_date, out persistedDate)) + { + if (persistedDate.Date == _currentSessionDate.Date) + { + _dailyTradeCount = state.daily_trade_count; + if (_logger != null) + _logger.LogInformation("DAILY_TRADE_COUNT restored: date={0:yyyy-MM-dd} count={1} max={2}", _currentSessionDate, _dailyTradeCount, maxDailyTrades); + return; + } + } + } + } + catch (Exception ex) + { + if (_logger != null) + _logger.LogWarning("DAILY_TRADE_COUNT warning: could not read persisted count; starting at zero. Error={0}", ex.Message); + } + + _dailyTradeCount = 0; + PersistDailyTradeCount(context); + if (_logger != null) + _logger.LogInformation("DAILY_TRADE_COUNT reset: new trading date {0:yyyy-MM-dd}", _currentSessionDate); + } + + private void PersistDailyTradeCount(StrategyContext context) + { + if (!ShouldUseDailyTradeCountPersistence(context)) + return; + + try + { + string path = GetDailyTradeCountFilePath(context); + if (string.IsNullOrEmpty(path)) + return; + + string dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) + Directory.CreateDirectory(dir); + + DailyTradeCountState state = new DailyTradeCountState(); + state.trading_date = _currentSessionDate.ToString("yyyy-MM-dd"); + state.daily_trade_count = _dailyTradeCount; + state.account = ResolveDailyTradeCountAccountName(); + state.strategy_name = ResolveDailyTradeCountStrategyName(); + state.symbol = context != null ? context.Symbol : ResolveDailyTradeCountSymbol(); + File.WriteAllText(path, JsonConvert.SerializeObject(state, Formatting.Indented)); + } + catch (Exception ex) + { + if (_logger != null) + _logger.LogWarning("DAILY_TRADE_COUNT warning: could not write persisted count. Error={0}", ex.Message); + } + } + + private bool ShouldUseDailyTradeCountPersistence(StrategyContext context) + { + if (!_dailyTradeCountPersistenceEnabled) + return false; + + if (context == null || context.Account == null) + return false; + + if (string.IsNullOrEmpty(ResolveDailyTradeCountAccountName())) + return false; + + return true; + } + + private string GetDailyTradeCountFilePath(StrategyContext context) + { + string dir = ResolveDailyTradeCountLogDirectory(); + string safeAccount = MakeSafeFileName(ResolveDailyTradeCountAccountName()); + string safeStrategy = MakeSafeFileName(ResolveDailyTradeCountStrategyName()); + return Path.Combine(dir, string.Format("daily_trade_count_{0}_{1}.json", safeAccount, safeStrategy)); + } + + private string ResolveDailyTradeCountLogDirectory() + { + if (!string.IsNullOrEmpty(_dailyTradeCountLogDirectory)) + return _dailyTradeCountLogDirectory; + + return Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + "NinjaTrader 8", + "log", + "nt8-sdk"); + } + + private string ResolveDailyTradeCountAccountName() + { + if (!string.IsNullOrEmpty(_dailyTradeCountAccountName)) + return _dailyTradeCountAccountName; + + if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("daily_trade_count_account")) + return Convert.ToString(_config.Parameters["daily_trade_count_account"]); + + return string.Empty; + } + + private string ResolveDailyTradeCountStrategyName() + { + if (!string.IsNullOrEmpty(_dailyTradeCountStrategyName)) + return _dailyTradeCountStrategyName; + + if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("daily_trade_count_strategy_name")) + return Convert.ToString(_config.Parameters["daily_trade_count_strategy_name"]); + + return Metadata != null ? Metadata.Name : "SimpleORBStrategy"; + } + + private string ResolveDailyTradeCountSymbol() + { + if (_config != null && !string.IsNullOrEmpty(_config.Symbol)) + return _config.Symbol; + + return string.Empty; + } + + private string MakeSafeFileName(string value) + { + if (string.IsNullOrEmpty(value)) + return "value"; + + char[] invalid = Path.GetInvalidFileNameChars(); + System.Text.StringBuilder builder = new System.Text.StringBuilder(value.Length); + for (int i = 0; i < value.Length; i++) + { + char c = value[i]; + bool isInvalid = false; + for (int j = 0; j < invalid.Length; j++) + { + if (c == invalid[j]) + { + isInvalid = true; + break; + } + } + builder.Append(isInvalid ? '_' : c); + } + return builder.ToString(); + } + + private class DailyTradeCountState + { + public string trading_date { get; set; } + public int daily_trade_count { get; set; } + public string account { get; set; } + public string strategy_name { get; set; } + public string symbol { get; set; } + } + private bool ShouldIncrementDailyTradeCount(StrategyContext context) { if (context == null || context.CustomData == null) diff --git a/tests/NT8.Core.Tests/MaxDailyTradesTests.cs b/tests/NT8.Core.Tests/MaxDailyTradesTests.cs index 4b11e11..3fbce8e 100644 --- a/tests/NT8.Core.Tests/MaxDailyTradesTests.cs +++ b/tests/NT8.Core.Tests/MaxDailyTradesTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using NT8.Core.Common.Models; using NT8.Core.Logging; @@ -84,6 +85,143 @@ namespace NT8.Core.Tests Assert.AreEqual(0, strategy.DailyTradeCount); } + [TestMethod] + public void Persistence_SameTradingDateExistingFile_RestoresCount() + { + string dir = CreateTempDirectory(); + try + { + WriteDailyCountFile(dir, "SimAccount", "SimpleORB", "2026-08-17", 1); + RecordingLogger logger = new RecordingLogger(); + SimpleORBStrategy strategy = CreateStrategyWithPersistence(dir, "SimAccount", logger); + DateTime sessionStart = new DateTime(2026, 8, 17, 9, 30, 0); + StrategyContext context = CreateContext(sessionStart); + + StrategyIntent intent = strategy.OnBar(CreateBreakoutBar(sessionStart.AddMinutes(5)), context); + + Assert.IsNull(intent); + Assert.AreEqual(1, strategy.DailyTradeCount); + Assert.IsTrue(logger.Contains("DAILY_TRADE_COUNT restored: date=2026-08-17 count=1 max=1")); + Assert.IsTrue(context.CustomData.ContainsKey("signal_reject_line")); + Assert.IsTrue(context.CustomData["signal_reject_line"].ToString().Contains("REJECT: reason=MaxDailyTrades")); + } + finally + { + DeleteTempDirectory(dir); + } + } + + [TestMethod] + public void Persistence_NewTradingDateExistingFile_ResetsAndOverwritesFile() + { + string dir = CreateTempDirectory(); + try + { + WriteDailyCountFile(dir, "SimAccount", "SimpleORB", "2026-08-16", 1); + RecordingLogger logger = new RecordingLogger(); + SimpleORBStrategy strategy = CreateStrategyWithPersistence(dir, "SimAccount", logger); + DateTime sessionStart = new DateTime(2026, 8, 17, 9, 30, 0); + StrategyContext context = CreateContext(sessionStart); + + StrategyIntent intent = strategy.OnBar(CreateNonBreakoutBar(sessionStart.AddMinutes(5)), context); + + Assert.IsNull(intent); + Assert.AreEqual(0, strategy.DailyTradeCount); + Assert.IsTrue(logger.Contains("DAILY_TRADE_COUNT reset: new trading date 2026-08-17")); + string persisted = File.ReadAllText(GetDailyCountFilePath(dir, "SimAccount", "SimpleORB")); + Assert.IsTrue(persisted.Contains("\"trading_date\": \"2026-08-17\""), persisted); + Assert.IsTrue(persisted.Contains("\"daily_trade_count\": 0"), persisted); + } + finally + { + DeleteTempDirectory(dir); + } + } + + [TestMethod] + public void Persistence_CorruptFile_StartsAtZeroWarnsAndDoesNotThrow() + { + string dir = CreateTempDirectory(); + try + { + File.WriteAllText(GetDailyCountFilePath(dir, "SimAccount", "SimpleORB"), "not-json"); + RecordingLogger logger = new RecordingLogger(); + SimpleORBStrategy strategy = CreateStrategyWithPersistence(dir, "SimAccount", logger); + DateTime sessionStart = new DateTime(2026, 8, 17, 9, 30, 0); + StrategyContext context = CreateContext(sessionStart); + + StrategyIntent intent = strategy.OnBar(CreateNonBreakoutBar(sessionStart.AddMinutes(5)), context); + + Assert.IsNull(intent); + Assert.AreEqual(0, strategy.DailyTradeCount); + Assert.IsTrue(logger.Contains("DAILY_TRADE_COUNT warning: could not read persisted count")); + string persisted = File.ReadAllText(GetDailyCountFilePath(dir, "SimAccount", "SimpleORB")); + Assert.IsTrue(persisted.Contains("\"daily_trade_count\": 0"), persisted); + } + finally + { + DeleteTempDirectory(dir); + } + } + + [TestMethod] + public void Persistence_BacktestAccountNull_DoesNotReadOrWriteFile() + { + string dir = CreateTempDirectory(); + try + { + RecordingLogger logger = new RecordingLogger(); + SimpleORBStrategy strategy = CreateStrategyWithPersistence(dir, "SimAccount", logger); + DateTime sessionStart = new DateTime(2026, 8, 17, 9, 30, 0); + StrategyContext context = CreateContext(sessionStart); + context.Account = null; + + StrategyIntent intent = strategy.OnBar(CreateBreakoutBar(sessionStart.AddMinutes(5)), context); + + Assert.IsNotNull(intent); + Assert.AreEqual(1, strategy.DailyTradeCount); + Assert.IsFalse(File.Exists(GetDailyCountFilePath(dir, "SimAccount", "SimpleORB"))); + } + finally + { + DeleteTempDirectory(dir); + } + } + + [TestMethod] + public void Persistence_SundayEveningAndMondayMorning_ResolveToSameCmeTradingDate() + { + string dir = CreateTempDirectory(); + try + { + DateTime tradingSessionStart = new DateTime(2026, 8, 17, 9, 30, 0); + RecordingLogger firstLogger = new RecordingLogger(); + SimpleORBStrategy firstStrategy = CreateStrategyWithPersistence(dir, "SimAccount", firstLogger); + StrategyContext sundayEvening = CreateContext(tradingSessionStart); + sundayEvening.CurrentTime = new DateTime(2026, 8, 16, 19, 12, 0); + + StrategyIntent first = firstStrategy.OnBar(CreateBreakoutBar(new DateTime(2026, 8, 16, 19, 12, 0)), sundayEvening); + + Assert.IsNotNull(first); + Assert.AreEqual(1, firstStrategy.DailyTradeCount); + + RecordingLogger secondLogger = new RecordingLogger(); + SimpleORBStrategy secondStrategy = CreateStrategyWithPersistence(dir, "SimAccount", secondLogger); + StrategyContext mondayMorning = CreateContext(tradingSessionStart); + mondayMorning.CurrentTime = new DateTime(2026, 8, 17, 11, 4, 0); + + StrategyIntent second = secondStrategy.OnBar(CreateBreakoutBar(new DateTime(2026, 8, 17, 11, 4, 0)), mondayMorning); + + Assert.IsNull(second); + Assert.AreEqual(1, secondStrategy.DailyTradeCount); + Assert.IsTrue(secondLogger.Contains("DAILY_TRADE_COUNT restored: date=2026-08-17 count=1 max=1")); + } + finally + { + DeleteTempDirectory(dir); + } + } + private static SimpleORBStrategy CreateStrategy() { SimpleORBStrategy strategy = new SimpleORBStrategy(30, 1.0); @@ -102,6 +240,35 @@ namespace NT8.Core.Tests return strategy; } + private static SimpleORBStrategy CreateStrategyWithPersistence(string logDirectory, string accountName, ILogger logger) + { + SimpleORBStrategy strategy = new SimpleORBStrategy(30, 1.0); + StrategyConfig 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); + config.Parameters.Add("daily_trade_count_persistence_enabled", true); + config.Parameters.Add("daily_trade_count_account", accountName); + config.Parameters.Add("daily_trade_count_strategy_name", "SimpleORB"); + config.Parameters.Add("daily_trade_count_log_directory", logDirectory); + strategy.Initialize(config, null, logger); + + Dictionary parameters = new Dictionary(); + parameters.Add("daily_trade_count_persistence_enabled", true); + parameters.Add("daily_trade_count_account", accountName); + parameters.Add("daily_trade_count_strategy_name", "SimpleORB"); + parameters.Add("daily_trade_count_log_directory", logDirectory); + strategy.SetParameters(parameters); + return strategy; + } + private static StrategyContext CreateContext(DateTime sessionStart) { MarketSession session = new MarketSession(sessionStart, sessionStart.Date.AddHours(16), true, "RTH"); @@ -123,5 +290,59 @@ namespace NT8.Core.Tests { return new BarData("NQ", time, 19000, 19060, 18990, 19000, 1500, TimeSpan.FromMinutes(5)); } + + private static string CreateTempDirectory() + { + string dir = Path.Combine(Path.GetTempPath(), "nt8-gap055-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + return dir; + } + + private static void DeleteTempDirectory(string dir) + { + if (Directory.Exists(dir)) + Directory.Delete(dir, true); + } + + private static string GetDailyCountFilePath(string dir, string accountName, string strategyName) + { + return Path.Combine(dir, string.Format("daily_trade_count_{0}_{1}.json", accountName, strategyName)); + } + + private static void WriteDailyCountFile(string dir, string accountName, string strategyName, string tradingDate, int count) + { + string json = string.Format("{{\r\n \"trading_date\": \"{0}\",\r\n \"daily_trade_count\": {1},\r\n \"account\": \"{2}\",\r\n \"strategy_name\": \"{3}\",\r\n \"symbol\": \"NQ\"\r\n}}", tradingDate, count, accountName, strategyName); + File.WriteAllText(GetDailyCountFilePath(dir, accountName, strategyName), json); + } + + private class RecordingLogger : ILogger + { + private readonly List _messages = new List(); + + public bool Contains(string text) + { + foreach (string message in _messages) + { + if (message.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 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); } + public void LogException(Exception exception, string message, params object[] args) { Add(message, args); } + + private void Add(string message, params object[] args) + { + if (args != null && args.Length > 0) + _messages.Add(string.Format(message, args)); + else + _messages.Add(message); + } + } } }