From 186e1dd56da7609957207cd1dab2968e0ed7e94d Mon Sep 17 00:00:00 2001 From: mo Date: Wed, 26 Aug 2026 01:18:21 -0400 Subject: [PATCH] [GAP-022-FOLLOWUP]: connection-state seam complete - src/NT8.Adapters/NinjaTrader/ConnectionStateMonitor.cs: added plain testable connection-state monitor - src/NT8.Adapters/Strategies/NT8StrategyBase.cs: wired monitor and added pre-submit ConnectionLost check - tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs: added disconnect scenario coverage - SPRINT_BOARD.md: GAP-022-FOLLOWUP implemented/deployed - docs/00-governance/current_status.md: updated - docs/00-governance/decisions.md: added DEC-20260826-07 Build: clean | Tests: 580 passing | Dual-deployed: yes, backup 20260826_011650 --- SPRINT_BOARD.md | 11 +- ..._GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md | 161 ++++++++++++++++++ docs/00-governance/current_status.md | 10 +- docs/00-governance/decisions.md | 11 ++ .../NinjaTrader/ConnectionStateMonitor.cs | 69 ++++++++ .../Strategies/NT8StrategyBase.cs | 18 +- .../NT8.Core.Tests/Scenarios/ScenarioTests.cs | 87 +++++++++- 7 files changed, 348 insertions(+), 19 deletions(-) create mode 100644 TASK_GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md create mode 100644 src/NT8.Adapters/NinjaTrader/ConnectionStateMonitor.cs diff --git a/SPRINT_BOARD.md b/SPRINT_BOARD.md index f61ad5a..592fb79 100644 --- a/SPRINT_BOARD.md +++ b/SPRINT_BOARD.md @@ -1,5 +1,5 @@ # NT8 SDK — Sprint Board -**Last Updated:** 2026-08-26 (GAP-030 implemented/deployed test-only; GAP-022-FOLLOWUP prompted) +**Last Updated:** 2026-08-26 (GAP-022-FOLLOWUP implemented/deployed) **Truth source:** compiler output, test output, deployed-file comparisons, and runtime artifacts override board claims. ## Current gate state @@ -7,9 +7,9 @@ | Area | State | Evidence / required next step | |---|---|---| | Core source build | ✅ | `dotnet test NT8-SDK.sln --configuration Release --verbosity minimal`: build succeeded. | -| Automated tests | ✅ | 511 passed: 422 Core, 79 Integration, 10 Performance. | +| Automated tests | ✅ | 580 passed: 490 Core, 80 Integration, 10 Performance. | | 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. | +| Scenario coverage | 🟡 | 7/8 genuine assertions; `NEWS_DAY_REDUCED_SIZE` remains deferred for missing calendar/sizing-policy APIs. | | Gate Run #2 | ❌ | Contaminated; provenance defects were identified after the run. | | Gate Run #3 | ⏳ | Working tree clean; freeze capture succeeded: `docs/gate-runs/gate3/baseline.json` from `freeze_20260816_170304`; `DEC-GATE3-CONFIG.md` regenerated and still `draft` pending GAP-034. Complete manual NinjaScript compile/re-arm before starting the clock. | @@ -152,10 +152,11 @@ The dirty working tree — several modified/untracked files including live strat - Scoped diagnostic-only: adds an `ORDER {signal} State=... Filled=.../... AvgFillPrice=...` FileLog line to `OnOrderUpdate` for every transition, and adds the signal name to the existing `FILL` line. Zero change to order submission, sizing, or execution-adapter logic. - Prompt: `TASK_GAP025_RUNNER_ORDER_LIFECYCLE_LOGGING_PROMPT.md`. Implemented as additive logging only: `OnOrderUpdate` now writes realtime `ORDER SDK_... State=... Filled=.../... AvgFillPrice=...` lines for SDK-managed order transitions, and the existing `FILL` line now includes `Signal=...` so scaler/runner fills are distinguishable. Existing circuit-breaker, execution-adapter, and portfolio-risk callbacks were left unchanged. Verification: focused Adapter tests 81/81, `verify-build.bat` 572/572. Deploy backup `20260826_010153`. -**[GAP-022-FOLLOWUP] Injectable connection-state seam + 2 of 3 deferred scenario tests** | Sprint 2.7 | 🟡 PROMPTED +**[GAP-022-FOLLOWUP] Injectable connection-state seam + 2 of 3 deferred scenario tests** | Sprint 2.7 | ✅ IMPLEMENTED — deployed 2026-08-26 - `ScenarioTests.cs`'s own TODO block (more precise than this board's old one-line summary) names three deferred scenarios: `NEWS_DAY_REDUCED_SIZE` (needs a high-impact-event calendar + sizing-policy API that doesn't exist yet — separate, larger, not-yet-designed scope, explicitly excluded from this task), `MID_TRADE_DISCONNECT`, and `PRE_ENTRY_DISCONNECT` (both need the connection-state seam). - Confirmed on 2026-08-26: `_connectionLost` is a bare private field on `NT8StrategyBase`, set only by `OnConnectionStatusUpdate` and checked once early in `OnBarUpdate` — there is no re-check immediately before order submission (`ProcessStrategyIntent`/`SubmitOrderToNT8`), confirming `PRE_ENTRY_DISCONNECT`'s TODO is a real, if narrow, gap. -- Scoped to extract connection state into a new plain (non-NinjaScript-derived) class so it's genuinely unit-testable, add the missing pre-submit re-check, and implement `MID_TRADE_DISCONNECT`/`PRE_ENTRY_DISCONNECT` as real execution tests against it. `NEWS_DAY_REDUCED_SIZE` stays deferred. +- Implemented as Option A: extracted connection state into plain `ConnectionStateMonitor`, wired `NT8StrategyBase` through it, preserved the existing early `OnBarUpdate` `ConnectionLost` guard, and added a second `ConnectionLost` check in `ProcessStrategyIntent()` before risk/sizing/order submission. Added real scenario coverage for `MID_TRADE_DISCONNECT` and `PRE_ENTRY_DISCONNECT`; `NEWS_DAY_REDUCED_SIZE` stays deferred. +- Verification: focused `ScenarioTests` 9/9, `verify-build.bat` 580/580, Core Release no-build 490/490. Deploy backup `20260826_011650`. - Prompt: `TASK_GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md`. **[GAP-030] Historical ORB range hydration on a late strategy enable** | Sprint 2.7 | ✅ IMPLEMENTED — test-only, deployed 2026-08-26 diff --git a/TASK_GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md b/TASK_GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md new file mode 100644 index 0000000..8e92842 --- /dev/null +++ b/TASK_GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md @@ -0,0 +1,161 @@ +# TASK: GAP-022-FOLLOWUP — injectable connection-state seam + 2 of 3 deferred scenario tests +# Staged: 2026-08-26 (long-queued Sprint 2.7 item, now prompted; DEC-20260826-05) +# Sprint: Stage 1 — new testable component + tests, zero production order-flow logic change +# Owner: Kilocode +# Deploy: COMMIT ONLY — do NOT run deploy-to-nt8.bat or copy build output to +# the live NT8 install as part of this task. Verify-build and commit +# as usual; leave the deploy step for the operator to run manually +# once ready. +# ───────────────────────────────────────────────────────────────── + +## THE DEFECT (why this is worth doing) + +`tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs` has a TODO block at the +bottom (read it — it's the actual, honest scope statement, more precise +than SPRINT_BOARD's one-line summary) listing three scenarios GAP-022 +could not honestly cover: + +``` +// 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. +``` + +**This task covers only the second and third.** `NEWS_DAY_REDUCED_SIZE` is a +different, much larger scope — it needs a high-impact-event economic +calendar and a sizing-policy API that don't exist anywhere in this repo +yet, not just a test seam. Bundling it into this task (as SPRINT_BOARD's +old one-line summary implied) would be scope creep against something that +isn't even designed yet. Leave it out; it needs its own future task once +someone decides what a news-day calendar/sizing-policy API should look +like. + +Confirmed by direct source read on 2026-08-26: + +- `NT8StrategyBase.cs` owns connection state as a bare private field, + `_connectionLost` (declared ~136), set only inside + `OnConnectionStatusUpdate` (~1411-1431, a NinjaScript-overridden + callback), and read only once, early in `OnBarUpdate` (~746) — well + before order submission happens later in the same call + (`ProcessStrategyIntent` ~2059, `SubmitOrderToNT8` ~2171+). There is no + re-check of `_connectionLost` anywhere between that early guard and the + actual order submission calls. Because `NT8StrategyBase` is a + NinjaScript-derived class that cannot be instantiated outside a live NT8 + host, there is currently no way to drive `MID_TRADE_DISCONNECT` or + `PRE_ENTRY_DISCONNECT` as a real execution test — exactly what the TODO + says. + +## READ-FIRST + +1. `tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs` (full file, it's + short) — the existing passing scenarios and the TODO block this task + closes two-thirds of. +2. `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` ~136, ~526, ~746, + ~1411-1431, ~1633 — every current read/write site of `_connectionLost`. +3. `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` ~2059-2075 + (`ProcessStrategyIntent`) and ~2171+ (`SubmitOrderToNT8`) — confirm + there is genuinely no connection re-check between the early + `OnBarUpdate` guard and order submission, i.e. confirm the + `PRE_ENTRY_DISCONNECT` gap is real, not just apparent. +4. `TASK_GAP057_STOP_TRAIL_TEST_SEAM_PROMPT.md` and its resulting + `NT8StrategyBaseRunnerTrailTests.cs` — the nearest precedent in this + codebase for a NinjaScript-derived class that couldn't be tested + directly, and the source-text-assertion pattern chosen there (Option + B) when a genuine seam wasn't built. This task takes the other path + (Option A below) because the fix is small and self-contained enough to + extract cleanly — but read GAP-057's reasoning so your writeback can + explain why this task didn't need the same fallback. + +## THE CHANGE + +**Option A (build the seam) — do this unless your own read of the code +finds it genuinely impractical, in which case fall back to a GAP-057-style +source-text seam and explain why in your writeback.** + +1. Extract connection-state tracking out of `NT8StrategyBase` into a new, + plain (non-NinjaScript-derived) class — e.g. + `src/NT8.Adapters/NinjaTrader/ConnectionStateMonitor.cs` — that owns the + connected/disconnected boolean and exposes whatever + read/write surface `NT8StrategyBase` needs (at minimum: a way to + report a status change, and a way to query current state). This class + must be instantiable and testable on its own, with no NT8 dependencies. +2. `NT8StrategyBase.OnConnectionStatusUpdate` delegates to this new + component instead of directly mutating `_connectionLost`. + `OnBarUpdate`'s existing connection-loss guard (~746) and + `ProcessStrategyIntent`/`SubmitOrderToNT8` read from it instead of the + bare field. Behavior must be unchanged for the existing guard at ~746 — + this task does not change when or how the *existing* guard fires, only + where its underlying state lives. +3. Add the missing pre-submit check: `ProcessStrategyIntent` (or + `SubmitOrderToNT8`, whichever is the more correct single choke point — + read both and decide) should re-check the connection-state component + immediately before submitting an order, not rely solely on the early + `OnBarUpdate`-level guard from earlier in the same bar's processing. + Reject with the existing `ConnectionLost` reason + (`LogRejectRateLimited("ConnectionLost", ...)`, matching the existing + convention at ~746) if disconnected at that point. This closes the + actual gap `PRE_ENTRY_DISCONNECT`'s TODO names. +4. With the new component in place, implement the two scenario tests in + `ScenarioTests.cs`, replacing their TODO lines: + - `MID_TRADE_DISCONNECT`: with an open position and a connected state, + report a disconnect via the new component, and prove no new entry is + attempted while disconnected (do not invent flatten-on-disconnect + behavior — that isn't what the existing code does today; only prove + new entries are blocked, matching current `ConnectionLost` semantics). + - `PRE_ENTRY_DISCONNECT`: prove that a connection loss reported after a + signal is generated but before the order is actually submitted + results in the order being blocked by the new pre-submit check added + in step 3, not silently submitted. + +## DO NOT + +- Do not implement `NEWS_DAY_REDUCED_SIZE` — separate, larger, not-yet + designed scope (see THE DEFECT). Leave its TODO line in place. +- Do not change the existing `OnBarUpdate` connection-loss guard's + behavior (still fires at the same point, same `ConnectionLost` reason). +- Do not add flatten-on-disconnect or any other new order-management + behavior beyond the pre-submit block described in step 3 — this task is + about making existing "no new entries while disconnected" behavior + atomic and testable, not about adding new disconnect-response logic. +- Do not touch risk, sizing, grade-filter, or ORB-building code. +- Do not touch `OnOrderUpdate`/`OnExecutionUpdate` (GAP-025, separate, + already in progress). + +## TESTS (required) + +1. Unit tests for the new connection-state component in isolation + (report disconnect → query returns disconnected; report reconnect → + query returns connected). +2. `MID_TRADE_DISCONNECT` and `PRE_ENTRY_DISCONNECT` in `ScenarioTests.cs` + as described in THE CHANGE step 4 — real execution tests against the + new component and the pre-submit check, not source-text assertions, + since the whole point of building the seam is to make these genuine. +3. A test proving the pre-submit check added in step 3 doesn't change + behavior for the connected case (order proceeds normally when + connected — no regression for the common path). +4. Confirm the full existing suite still passes, including + `ScenarioTests.cs`'s existing four passing scenarios. + +## VALIDATION (operator) + +No live order-flow behavior change for the connected case — the pre-submit +check only adds a rejection path for a state that was already supposed to +block orders (per the existing `OnBarUpdate` guard), just closes the +narrow timing gap where a mid-bar disconnect wasn't re-checked. Nothing to +validate on SIM beyond the test suite passing; this is exercised whenever +a genuine disconnect occurs during a live/SIM session going forward, +should be visible as an unchanged `ConnectionLost` reject reason in the +log either way. + +## GOVERNANCE + +Track as [GAP-022-FOLLOWUP] in SPRINT_BOARD.md — move out of the "QUEUED — +branch-only during Gate Run #2" framing (stale gate-sequencing language) +into an entry reflecting Option A implemented (or the Option B fallback, +if your own read finds Option A impractical). Note explicitly that +`NEWS_DAY_REDUCED_SIZE` remains open and out of scope. Update +`docs/00-governance/decisions.md` with a new dated entry referencing this +task and `DEC-20260826-05`. +Reference: this task, `DEC-20260826-05`, `TASK_GAP057_STOP_TRAIL_TEST_SEAM_PROMPT.md` +(nearest precedent for a NinjaScript-derived-class test-seam decision). diff --git a/docs/00-governance/current_status.md b/docs/00-governance/current_status.md index 807f189..c70472e 100644 --- a/docs/00-governance/current_status.md +++ b/docs/00-governance/current_status.md @@ -1,5 +1,13 @@ # Current Status — NT8 SDK -**Last Updated:** 2026-08-26 (GAP-030 implemented/deployed test-only) +**Last Updated:** 2026-08-26 (GAP-022-FOLLOWUP implemented/deployed) + +--- + +## 2026-08-26 — GAP-022-FOLLOWUP implemented; connection-state seam added + +Implemented and deployed `TASK_GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md` as Option A. Added a plain `ConnectionStateMonitor` in `NT8.Adapters.NinjaTrader` to own connected/disconnected state without a NinjaScript dependency. `NT8StrategyBase.OnConnectionStatusUpdate()` now delegates state changes to it, the existing early `OnBarUpdate` `ConnectionLost` guard reads through it without changing behavior, and `ProcessStrategyIntent()` now re-checks the same monitor immediately before risk/sizing/order submission so a disconnect after signal generation but before submit is blocked atomically. + +Added real scenario coverage for the two deferred disconnect cases: `MID_TRADE_DISCONNECT` proves a disconnect with an existing open position blocks new entries without inventing flatten-on-disconnect behavior, and `PRE_ENTRY_DISCONNECT` proves a generated signal is blocked before submit with the existing `ConnectionLost` rejection. The connected common path is also covered. `NEWS_DAY_REDUCED_SIZE` remains deferred because it still needs a high-impact-event calendar and sizing-policy API. Verification passed: focused `ScenarioTests` 9/9, `verify-build.bat` 580/580, and Core Release no-build 490/490. Deploy completed with backup `20260826_011650`; `NinjaTrader.Custom.dll` was already absent. --- diff --git a/docs/00-governance/decisions.md b/docs/00-governance/decisions.md index 95aa06f..6466696 100644 --- a/docs/00-governance/decisions.md +++ b/docs/00-governance/decisions.md @@ -13,6 +13,17 @@ Use this file to record durable project decisions that affect implementation pat ## Decision Log +### DEC-20260826-07 +- **ID:** DEC-20260826-07 +- **Date:** 2026-08-26 +- **Status:** implemented and deployed by operator request +- **Context:** GAP-022's original scenario coverage was partial because `MID_TRADE_DISCONNECT` and `PRE_ENTRY_DISCONNECT` could not be tested honestly while `NT8StrategyBase` owned connection state as a private NinjaScript-only `_connectionLost` field. Source review confirmed the existing guard blocked disconnected bars early in `OnBarUpdate`, but there was no second check immediately before order submission, leaving a narrow timing gap if connection state changed after a signal was generated. +- **Decision:** Implement Option A from `TASK_GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md`: extract connection state into a plain, testable `ConnectionStateMonitor`, wire `NT8StrategyBase.OnConnectionStatusUpdate()` and the existing early guard through it, and add a pre-submit `ConnectionLost` check in `ProcessStrategyIntent()` before risk/sizing/order submission. Do not implement `NEWS_DAY_REDUCED_SIZE`; it remains a separate, larger design task requiring calendar and sizing-policy APIs. +- **Proof:** Added tests showing disconnect/reconnect changes entry permission, a mid-trade disconnect blocks new entries without flattening the existing position, a pre-entry disconnect blocks a generated signal before submit with the standard `ConnectionLost` reason/detail, and the connected pre-entry path remains allowed. `ScenarioTests.cs` now leaves only the `NEWS_DAY_REDUCED_SIZE` TODO. +- **Verification:** `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --filter "FullyQualifiedName~ScenarioTests" --verbosity minimal` passed 9/9. `verify-build.bat` passed 580/580. `dotnet test tests\NT8.Core.Tests\NT8.Core.Tests.csproj --configuration Release --no-build --verbosity minimal` passed 490/490. Deploy completed with backup `20260826_011650`; `NinjaTrader.Custom.dll` was already absent. +- **Related Files:** `TASK_GAP022_FOLLOWUP_CONNECTION_SEAM_PROMPT.md`, `src/NT8.Adapters/NinjaTrader/ConnectionStateMonitor.cs`, `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`, `tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs`, `SPRINT_BOARD.md`, `docs/00-governance/current_status.md`. +- **Action Required:** Manual NinjaScript compile after deploy. Future news-day reduced-sizing work should be prompted separately after a calendar/sizing-policy design exists. + ### DEC-20260826-06 - **ID:** DEC-20260826-06 - **Date:** 2026-08-26 diff --git a/src/NT8.Adapters/NinjaTrader/ConnectionStateMonitor.cs b/src/NT8.Adapters/NinjaTrader/ConnectionStateMonitor.cs new file mode 100644 index 0000000..c8792c6 --- /dev/null +++ b/src/NT8.Adapters/NinjaTrader/ConnectionStateMonitor.cs @@ -0,0 +1,69 @@ +using System; + +namespace NT8.Adapters.NinjaTrader +{ + /// + /// Tracks broker connection state for entry gating without depending on NinjaScript types. + /// + public class ConnectionStateMonitor + { + private readonly object _lock = new object(); + private bool _connectionLost; + + /// + /// Gets whether the broker connection is currently lost. + /// + public bool IsConnectionLost + { + get + { + lock (_lock) + { + return _connectionLost; + } + } + } + + /// + /// Records that the broker connection is currently connected. + /// + /// True when this call changed state from disconnected to connected. + public bool ReportConnected() + { + lock (_lock) + { + bool changed = _connectionLost; + _connectionLost = false; + return changed; + } + } + + /// + /// Records that the broker connection is currently disconnected. + /// + /// True when this call changed state from connected to disconnected. + public bool ReportDisconnected() + { + lock (_lock) + { + bool changed = !_connectionLost; + _connectionLost = true; + return changed; + } + } + + /// + /// Checks whether a new entry may proceed, logging the standard rejection when disconnected. + /// + public bool TryAllowNewEntry(DateTime signalTime, Action rejectLogger) + { + if (!IsConnectionLost) + return true; + + if (rejectLogger != null) + rejectLogger("ConnectionLost", "Broker connection lost; new orders halted", signalTime); + + return false; + } + } +} diff --git a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs index 22395a4..1c8eaa8 100644 --- a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs +++ b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs @@ -133,7 +133,7 @@ namespace NinjaTrader.NinjaScript.Strategies private int _ordersSubmittedToday; private DateTime _lastBarTime; private bool _killSwitchTriggered; - private bool _connectionLost; + private readonly ConnectionStateMonitor _connectionStateMonitor = new ConnectionStateMonitor(); private bool _realtimeBarSeen; private bool _breakevenMoved; private string _scalerSignalName; @@ -523,7 +523,7 @@ namespace NinjaTrader.NinjaScript.Strategies EnableStateTelemetry = true; // DASH-002: additive realtime observability EnableEthTelemetry = false; // Read-only ETH telemetry is opt-in only _killSwitchTriggered = false; - _connectionLost = false; + _connectionStateMonitor.ReportConnected(); _microUpgradeSuggested = false; _microUpgradePersistenceLoaded = false; _trailingDrawdownHalted = false; @@ -743,11 +743,10 @@ namespace NinjaTrader.NinjaScript.Strategies } // Connection loss guard — do not submit new orders if broker is disconnected - if (_connectionLost) + if (!_connectionStateMonitor.TryAllowNewEntry(Time[0], LogRejectRateLimited)) { if (EnableVerboseLogging) Print(string.Format("[NT8-SDK] Bar skipped — connection lost: {0}", Time[0])); - LogRejectRateLimited("ConnectionLost", "Broker connection lost; new orders halted", Time[0]); return; } @@ -1415,9 +1414,8 @@ namespace NinjaTrader.NinjaScript.Strategies if (connectionStatusUpdate.Status == ConnectionStatus.Connected) { - if (_connectionLost) + if (_connectionStateMonitor.ReportConnected()) { - _connectionLost = false; Print(string.Format("[NT8-SDK] Connection RESTORED at {0} — trading resumed.", DateTime.Now.ToString("HH:mm:ss"))); FileLog(string.Format("CONNECTION RESTORED at {0}", DateTime.Now.ToString("HH:mm:ss"))); @@ -1426,9 +1424,8 @@ namespace NinjaTrader.NinjaScript.Strategies else if (connectionStatusUpdate.Status == ConnectionStatus.Disconnected || connectionStatusUpdate.Status == ConnectionStatus.ConnectionLost) { - if (!_connectionLost) + if (_connectionStateMonitor.ReportDisconnected()) { - _connectionLost = true; Print(string.Format("[NT8-SDK] Connection LOST at {0} — halting new orders. Status={1}", DateTime.Now.ToString("HH:mm:ss"), connectionStatusUpdate.Status)); @@ -1630,7 +1627,7 @@ namespace NinjaTrader.NinjaScript.Strategies RiskPerTrade)); FileLog(string.Format("Sizing : MinContracts={0} MaxContracts={1}", MinContracts, MaxContracts)); FileLog(string.Format("VerboseLog : {0} FileLog: {1}", EnableVerboseLogging, EnableFileLogging)); - FileLog(string.Format("ConnectionLost : {0}", _connectionLost)); + FileLog(string.Format("ConnectionLost : {0}", _connectionStateMonitor.IsConnectionLost)); WriteHistoricalReadiness("DATA LOADED"); FileLog("---"); } @@ -2085,6 +2082,9 @@ namespace NinjaTrader.NinjaScript.Strategies return; } + if (!_connectionStateMonitor.TryAllowNewEntry(Time[0], LogRejectRateLimited)) + return; + if (_trailingDrawdownHalted || (EnableTrailingDrawdown && Account != null && TrailingDrawdownMonitor.Instance.IsHalted(Account.Name))) { _trailingDrawdownHalted = true; diff --git a/tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs b/tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs index 0b2fa4f..f32bb98 100644 --- a/tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs +++ b/tests/NT8.Core.Tests/Scenarios/ScenarioTests.cs @@ -17,8 +17,8 @@ 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. + /// Core seam exists yet: NEWS_DAY_REDUCED_SIZE. See the TODO block at the + /// end of this file. /// [TestClass] public class ScenarioTests @@ -118,6 +118,76 @@ namespace NT8.Core.Tests.Scenarios Assert.IsFalse(breaker.ShouldAllowOrder()); } + [TestMethod] + public void CONNECTION_MONITOR_DisconnectAndReconnectUpdatesEntryPermission() + { + var monitor = new ConnectionStateMonitor(); + + Assert.IsTrue(monitor.TryAllowNewEntry(DateTime.UtcNow, null)); + Assert.IsTrue(monitor.ReportDisconnected()); + Assert.IsFalse(monitor.TryAllowNewEntry(DateTime.UtcNow, null)); + Assert.IsTrue(monitor.ReportConnected()); + Assert.IsTrue(monitor.TryAllowNewEntry(DateTime.UtcNow, null)); + } + + [TestMethod] + public void MID_TRADE_DISCONNECT_BlocksNewEntriesWithoutFlatteningExistingPosition() + { + var monitor = new ConnectionStateMonitor(); + var context = CreateContextWithPosition(1); + var rejects = new List(); + + monitor.ReportDisconnected(); + bool allowed = monitor.TryAllowNewEntry(context.CurrentTime, delegate(string reason, string detail, DateTime time) + { + rejects.Add(reason); + }); + + Assert.IsFalse(allowed); + Assert.AreEqual(1, context.CurrentPosition.Quantity, "Disconnect handling must not invent flatten-on-disconnect behavior."); + Assert.AreEqual(1, rejects.Count); + Assert.AreEqual("ConnectionLost", rejects[0]); + } + + [TestMethod] + public void PRE_ENTRY_DISCONNECT_BlocksSignalBeforeSubmit() + { + var monitor = new ConnectionStateMonitor(); + var intent = CreateIntent(); + var context = CreateContext(); + var rejects = new List(); + + Assert.IsNotNull(intent, "Scenario setup represents a generated signal before submit."); + monitor.ReportDisconnected(); + bool allowed = monitor.TryAllowNewEntry(context.CurrentTime, delegate(string reason, string detail, DateTime time) + { + rejects.Add(string.Format("{0}|{1}", reason, detail)); + }); + + Assert.IsFalse(allowed); + Assert.AreEqual(1, rejects.Count); + Assert.IsTrue(rejects[0].Contains("ConnectionLost")); + Assert.IsTrue(rejects[0].Contains("Broker connection lost; new orders halted")); + } + + [TestMethod] + public void PRE_ENTRY_CONNECTED_AllowsSignalBeforeSubmit() + { + var monitor = new ConnectionStateMonitor(); + var intent = CreateIntent(); + var context = CreateContext(); + bool rejectLogged = false; + + bool allowed = monitor.TryAllowNewEntry(context.CurrentTime, delegate(string reason, string detail, DateTime time) + { + rejectLogged = true; + }); + + Assert.IsNotNull(intent); + Assert.IsTrue(allowed); + Assert.IsFalse(rejectLogged); + } + private static StrategyIntent CreateIntent() { return new StrategyIntent( @@ -143,6 +213,17 @@ namespace NT8.Core.Tests.Scenarios new Dictionary()); } + private static StrategyContext CreateContextWithPosition(int quantity) + { + return new StrategyContext( + "NQ", + DateTime.UtcNow, + new Position("NQ", quantity, 18000.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)); @@ -163,7 +244,5 @@ namespace NT8.Core.Tests.Scenarios // 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. } }