diff --git a/NEXT_PROMPT.md b/NEXT_PROMPT.md
index b712d23..a7bc9b6 100644
--- a/NEXT_PROMPT.md
+++ b/NEXT_PROMPT.md
@@ -1,11 +1,11 @@
-# NEXT: RB-4.1 — Gate Run #2 Configuration Freeze
-# Staged: 2026-07-14
-# Sprint: 2.7 | Estimated: ~20 min operator work
+# NEXT: RB-4.1 — Gate Run #3 Configuration Freeze
+# Staged: 2026-08-03
+# Sprint: Gate 3 Preparation | Estimated: ~20 min operator work
# ─────────────────────────────────────────────────────────────────
-This is a **human operator procedure**, not a coding task. Do not change strategy source or deploy any branch work after the configuration freeze.
+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. Before the gate begins, deploy the verified cleanup source to NinjaTrader `Custom\Strategies` and use the NinjaScript Editor to compile it.
+1. Start NinjaTrader and use the NinjaScript Editor to compile the provenance fix deployed on 2026-08-03.
2. In SimSimple ORB, set and triple-check:
- `EnableDynamicStop=TRUE`
- `RunnerActivationMode=Auto`
@@ -17,7 +17,7 @@ This is a **human operator procedure**, not a coding task. Do not change strateg
- `EnableVerboseLogging=TRUE`
- `LogDirectory=C:\\Users\\billy\\Documents\\NinjaTrader 8\\log\\nt8-sdk`
3. Export the settings file. Record both `ConfigHash` and `CodeVersion` from the export.
-4. Add `DEC-GATE2-CONFIG` to `docs/00-governance/decisions.md`, including the export location, frozen values, hashes/stamp, and gate start date.
+4. Add `DEC-GATE3-CONFIG` to `docs/00-governance/decisions.md`, including the export location, frozen values, hashes/stamp, and gate start date.
5. At gate start, apply a no-dual-deploy freeze to the gate machine. Preserve daily `provenance_*.json` and `trades_*.jsonl` artifacts and write weekly runbook heartbeats.
-Acceptance: an auditable frozen-config record exists before Gate Run #2; no branch work is deployed while the gate is active.
+Acceptance: NinjaScript compilation succeeds, an auditable frozen-config record exists before Gate Run #3, and no branch work is deployed while the gate is active.
diff --git a/SPRINT_BOARD.md b/SPRINT_BOARD.md
index 42856ca..b167cec 100644
--- a/SPRINT_BOARD.md
+++ b/SPRINT_BOARD.md
@@ -1,5 +1,5 @@
# NT8 SDK — Sprint Board
-**Last Updated:** 2026-07-14
+**Last Updated:** 2026-08-03
**Truth source:** compiler output, test output, deployed-file comparisons, and runtime artifacts override board claims.
## Current gate state
@@ -8,20 +8,21 @@
|---|---|---|
| Core source build | ✅ | `verify-build.bat`: 0 errors; 6 existing CS1998 warnings in test mocks/tests. |
| Automated tests | ✅ | 497 passed: 409 Core, 78 Integration, 10 Performance. |
-| Provenance | ✅ | Session/trade records include session, parameter hash, and compiled code-version stamp. |
+| 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 | ⏳ | Complete RB-4.1 configuration freeze, deploy/compile the cleanup source, then start the gate. |
+| 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 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.
---
-## 🔵 ACTIVE — Human Gate Preparation
+## 🔵 ACTIVE — Gate 3 Preparation
-**[RB-4.1] Gate Run #2 Configuration Freeze** | Human operator | 🔵 ACTIVE
+**[RB-4.1] Gate Run #3 Configuration Freeze** | Human operator | 🔵 ACTIVE
- In SimSimple ORB, set and verify: `EnableDynamicStop=TRUE`, `RunnerActivationMode=Auto`, `RegimeGate=GradePenalty`, `MinTradeGrade=A`, `MaxDailyTrades=1`, `TestMode=FALSE`, `EnableFileLogging=TRUE`, `EnableVerboseLogging=TRUE`, and `LogDirectory=C:\\Users\\billy\\Documents\\NinjaTrader 8\\log\\nt8-sdk`.
- Export settings, retain the parameter hash and code-version stamp, and record `DEC-GATE2-CONFIG` with the gate start date.
-- Before the gate begins, dual-deploy the completed cleanup source and run the NinjaTrader compile check.
+- The Gate 3 provenance fix was deployed on 2026-08-03; run the NinjaTrader compile check before freezing configuration.
- Acceptance: the frozen export/provenance evidence is archived and the no-deploy rule is in force at gate start.
---
@@ -47,6 +48,10 @@
## ✅ COMPLETED — Sprint 2.7
+**[GAP-031] Trade Provenance Signal/Submission Wiring** | ✅ 2026-08-03
+- 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.
+
**[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 606c358..91a5d44 100644
--- a/docs/00-governance/active_work.md
+++ b/docs/00-governance/active_work.md
@@ -1,11 +1,11 @@
# Active Work
-**Last Updated:** 2026-07-14
+**Last Updated:** 2026-08-03
-## RB-4.1 — Gate Run #2 Configuration Freeze
+## RB-4.1 — Gate Run #3 Configuration Freeze
**Owner:** Human operator
-**State:** Active; gate clock has not started.
+**State:** Active; Gate 2 was contaminated and the Gate 3 clock has not started.
-1. Deploy the verified cleanup source to NinjaTrader Custom\Strategies and run NinjaTrader's compile check.
+1. Start NinjaTrader and run the NinjaScript compile check for the provenance fix deployed on 2026-08-03.
2. In SimSimple ORB, set and triple-check:
- `EnableDynamicStop=TRUE`
- `RunnerActivationMode=Auto`
@@ -17,8 +17,8 @@
- `EnableVerboseLogging=TRUE`
- `LogDirectory=C:\\Users\\billy\\Documents\\NinjaTrader 8\\log\\nt8-sdk`
3. Export settings; preserve the parameter hash and code-version stamp.
-4. Add `DEC-GATE2-CONFIG` with the frozen configuration and planned start date.
-5. At gate start, enforce the no-dual-deploy rule. GAP-025 and GAP-022-FOLLOWUP remain branch-only work.
+4. Add `DEC-GATE3-CONFIG` with the frozen configuration and planned start date.
+5. At Gate 3 start, enforce the no-dual-deploy rule. GAP-025 and GAP-022-FOLLOWUP remain branch-only work.
## Parallel work, not a gate prerequisite
- GAP-025 runner no-fill diagnosis blocks live promotion, not Gate Run #2.
diff --git a/docs/00-governance/common_failures.md b/docs/00-governance/common_failures.md
index de45990..8f83985 100644
--- a/docs/00-governance/common_failures.md
+++ b/docs/00-governance/common_failures.md
@@ -45,4 +45,9 @@ Record concise error fingerprints and verified fixes.
- Fingerprint: `NT8StrategyBase.cs` ~line 249 (nested enum), ~line 279 (duplicate property), ~line 281 (extra `#endregion`)
- Root cause: Post-task build verification (`verify-build.bat` + `dotnet test`) was skipped after a previous task. Duplicate enum/property and unbalanced `#region`/`#endregion` compiled in IDE with Roslyn leniency but failed the strict dotnet CLI build used by NT8 SDK CI.
- Fix: Removed nested `RunnerMode` enum (keep namespace-level at line ~35), removed duplicate `RunnerActivationMode` property (keep `[NinjaScriptProperty]` version at line ~181), removed extra `#endregion` at line 281. Ran `verify-build.bat` + `dotnet test` -- 492 tests passed (10 perf + 78 integration + 404 core).
- - Prevention link: Add mandatory `verify-build.bat && dotnet test --verbosity minimal` step to every task completion checklist in `docs/00-governance/decisions.md` and sprint templates.
\ No newline at end of file
+ - Prevention link: Add mandatory `verify-build.bat && dotnet test --verbosity minimal` step to every task completion checklist in `docs/00-governance/decisions.md` and sprint templates.
+
+## 2026-08-03 [GAP-031] — Trade provenance wrote defaults instead of submitted values
+- **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.
diff --git a/docs/00-governance/current_status.md b/docs/00-governance/current_status.md
index 3e6796a..0b26494 100644
--- a/docs/00-governance/current_status.md
+++ b/docs/00-governance/current_status.md
@@ -1,22 +1,22 @@
# Current Status — NT8 SDK
-**Last Updated:** 2026-07-14
+**Last Updated:** 2026-08-03
## Verified implementation state
-- **Last completed task:** GAP-029 — Code-Version Provenance Stamp
-- **Active task:** RB-4.1 — Gate Run #2 Configuration Freeze (human operator)
+- **Last completed task:** GAP-031 — Trade Provenance Signal/Submission Wiring
+- **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
## Build and test evidence
-- `verify-build.bat` completed successfully on 2026-07-14.
-- Build: **0 errors**, **6 CS1998 warnings** in existing test mock/test methods.
-- Tests: **497 passed, 0 failed** — 409 Core, 78 Integration, 10 Performance.
+- `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.
## Gate readiness
-- Provenance records have `session_id`, `trade_seq`, parameter-only `config_hash`, exact `session_tag`, and compiled `code_version` (assembly version + MVID).
+- Trade provenance now reads grade, weighted score, and ORB ticks from the accepted intent metadata and records the exact runner mode resolved for submission.
- Every real-time signal writes its `TEST MODE ACTIVE` or `LIVE MODE` status to the session file log.
- GAP-022 has five real scenario assertions. Its remaining three requirements are deferred architecture work, not fabricated tests.
-- **Before gate start:** deploy the cleanup source to NinjaTrader Custom\Strategies and run the NinjaTrader compile check. Then freeze the configuration and enforce the no-deploy rule.
+- **Before Gate 3 start:** complete the pending NinjaTrader compile check, freeze the configuration, and enforce the no-deploy rule.
## Authoritative documents
- Master document: `docs/NT8_SDK_Master_Document_v6.1_Complete.docx`
diff --git a/docs/00-governance/patterns_and_antipatterns.md b/docs/00-governance/patterns_and_antipatterns.md
index 059d8a1..5ead913 100644
--- a/docs/00-governance/patterns_and_antipatterns.md
+++ b/docs/00-governance/patterns_and_antipatterns.md
@@ -52,4 +52,8 @@ Capture recurring implementation patterns that impact compile stability.
8. **Compiled-code provenance stamp** (2026-07-14)
- Good pattern: persist the running assembly version plus `ManifestModule.ModuleVersionId` alongside the parameter-only configuration hash.
- Anti-pattern: treat an unchanged parameter hash as proof that unchanged code is running.
- - Why it matters: a mid-gate recompile/redeploy can preserve settings while changing executable behavior; the module MVID makes that drift detectable in session and trade artifacts.
+ - Why it matters: a mid-gate recompile/redeploy can preserve settings while changing executable behavior; the module MVID makes that drift detectable in session and trade artifacts.
+
+## 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.
diff --git a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs
index c546991..0805441 100644
--- a/src/NT8.Adapters/Strategies/NT8StrategyBase.cs
+++ b/src/NT8.Adapters/Strategies/NT8StrategyBase.cs
@@ -1433,7 +1433,7 @@ namespace NinjaTrader.NinjaScript.Strategies
double atrValue = ATR(Close, AtrPeriod)[0];
atrStopTicks = System.Math.Round(atrValue / TickSize * AtrMultiplier);
}
- WriteTradeProvenance(intent, request.Quantity, atrStopTicks);
+ WriteTradeProvenance(intent, request.Quantity, atrStopTicks, resolvedMode);
}
catch (Exception ex)
{
@@ -1757,7 +1757,7 @@ namespace NinjaTrader.NinjaScript.Strategies
///
/// Writes trade provenance JSONL line for each trade.
///
- protected virtual void WriteTradeProvenance(StrategyIntent intent, int quantity, double atrStopTicks)
+ protected virtual void WriteTradeProvenance(StrategyIntent intent, int quantity, double atrStopTicks, RunnerMode resolvedMode)
{
try
{
@@ -1772,29 +1772,20 @@ namespace NinjaTrader.NinjaScript.Strategies
var dir = LogDirectory;
Directory.CreateDirectory(dir);
- var trade = new Dictionary
- {
- { "session_id", _sessionId },
- { "trade_seq", _tradeSequence },
- { "timestamp_utc", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") },
- { "symbol", intent.Symbol },
- { "side", intent.Side.ToString() },
- { "quantity", quantity },
- { "stop_ticks", intent.StopTicks },
- { "target_ticks", intent.TargetTicks },
- { "atr_stop_ticks", atrStopTicks },
- { "resolved_runner_mode", GetResolvedRunnerMode().ToString() },
- { "confluence_grade", GetConfluenceGrade().ToString() },
- { "confluence_score", GetConfluenceScore() },
- { "risk_mode", GetRiskMode().ToString() },
- { "daily_pnl_at_entry", GetDailyPnL() },
- { "session_tag", GetSessionTag() },
- { "code_version", GetCodeVersionStamp() }
- };
-
var safeName = Name.Replace(" ", "_").Replace("/", "_").Replace("\\", "_");
var path = Path.Combine(LogDirectory, string.Format("trades_{0}_{1}.jsonl", Name.Replace(" ", "_"), DateTime.Now.ToString("yyyyMMdd")));
- var json = JsonConvert.SerializeObject(trade);
+ var json = TradeProvenanceSerializer.Serialize(
+ _sessionId,
+ _tradeSequence,
+ DateTime.UtcNow,
+ intent,
+ quantity,
+ atrStopTicks,
+ resolvedMode.ToString(),
+ GetRiskMode(),
+ GetDailyPnL(),
+ GetSessionTag(),
+ GetCodeVersionStamp());
File.AppendAllText(path, json + Environment.NewLine);
}
catch (Exception ex)
@@ -1857,32 +1848,6 @@ namespace NinjaTrader.NinjaScript.Strategies
return testMode ? "TEST MODE ACTIVE" : "LIVE MODE";
}
- private RunnerMode GetResolvedRunnerMode()
- {
- // This would need to be called in context where request.Quantity is available
- return ResolveRunnerMode(RunnerActivationMode, 1);
- }
-
- private string GetConfluenceGrade()
- {
- if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("confluence_grade"))
- {
- var grade = _strategyConfig.Parameters["confluence_grade"];
- if (grade != null) return grade.ToString();
- }
- return "Unknown";
- }
-
- private double GetConfluenceScore()
- {
- if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("confluence_weighted_score"))
- {
- var score = _strategyConfig.Parameters["confluence_weighted_score"];
- if (score is double) return (double)score;
- }
- return 0.0;
- }
-
private string GetRiskMode()
{
if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("risk_mode"))
diff --git a/src/NT8.Core/Logging/TradeProvenanceSerializer.cs b/src/NT8.Core/Logging/TradeProvenanceSerializer.cs
new file mode 100644
index 0000000..7658911
--- /dev/null
+++ b/src/NT8.Core/Logging/TradeProvenanceSerializer.cs
@@ -0,0 +1,100 @@
+using System;
+using System.Collections.Generic;
+using Newtonsoft.Json;
+using NT8.Core.Common.Models;
+using NT8.Core.Intelligence;
+
+namespace NT8.Core.Logging
+{
+ ///
+ /// Serializes submitted trade provenance from the accepted strategy intent.
+ ///
+ public static class TradeProvenanceSerializer
+ {
+ ///
+ /// Creates one JSONL payload for a submitted trade.
+ ///
+ public static string Serialize(
+ string sessionId,
+ int tradeSequence,
+ DateTime timestampUtc,
+ StrategyIntent intent,
+ int quantity,
+ double atrStopTicks,
+ string resolvedRunnerMode,
+ string riskMode,
+ double dailyPnlAtEntry,
+ string sessionTag,
+ string codeVersion)
+ {
+ if (intent == null)
+ throw new ArgumentNullException("intent");
+
+ string grade = "Unknown";
+ double score = 0.0;
+ double orbRangeTicks = 0.0;
+ ConfluenceScore confluenceScore = null;
+
+ if (intent.Metadata != null)
+ {
+ if (intent.Metadata.ContainsKey("confluence_score"))
+ confluenceScore = intent.Metadata["confluence_score"] as ConfluenceScore;
+
+ if (confluenceScore != null)
+ {
+ grade = confluenceScore.Grade.ToString();
+ score = confluenceScore.WeightedScore;
+ }
+ else
+ {
+ if (intent.Metadata.ContainsKey("trade_grade") && intent.Metadata["trade_grade"] != null)
+ grade = intent.Metadata["trade_grade"].ToString();
+ score = GetDouble(intent.Metadata, "confluence_weighted_score");
+ }
+
+ orbRangeTicks = GetDouble(intent.Metadata, "orb_range_ticks");
+ }
+
+ var trade = new Dictionary();
+ trade.Add("session_id", sessionId);
+ trade.Add("trade_seq", tradeSequence);
+ trade.Add("timestamp_utc", timestampUtc.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
+ trade.Add("symbol", intent.Symbol);
+ trade.Add("side", intent.Side.ToString());
+ trade.Add("quantity", quantity);
+ trade.Add("stop_ticks", intent.StopTicks);
+ trade.Add("target_ticks", intent.TargetTicks);
+ trade.Add("atr_stop_ticks", atrStopTicks);
+ trade.Add("resolved_runner_mode", resolvedRunnerMode);
+ trade.Add("confluence_grade", grade);
+ trade.Add("confluence_score", score);
+ trade.Add("OrbRangeTicks", orbRangeTicks);
+ trade.Add("risk_mode", riskMode);
+ trade.Add("daily_pnl_at_entry", dailyPnlAtEntry);
+ trade.Add("session_tag", sessionTag);
+ trade.Add("code_version", codeVersion);
+
+ return JsonConvert.SerializeObject(trade);
+ }
+
+ private static double GetDouble(Dictionary metadata, string key)
+ {
+ object value;
+ if (!metadata.TryGetValue(key, out value) || value == null)
+ return 0.0;
+
+ if (value is double)
+ return (double)value;
+ if (value is decimal)
+ return (double)(decimal)value;
+ if (value is float)
+ return (double)(float)value;
+ if (value is int)
+ return (double)(int)value;
+ if (value is long)
+ return (double)(long)value;
+
+ return 0.0;
+ }
+ }
+}
diff --git a/tests/NT8.Core.Tests/Logging/TradeProvenanceSerializerTests.cs b/tests/NT8.Core.Tests/Logging/TradeProvenanceSerializerTests.cs
new file mode 100644
index 0000000..1ddfb5d
--- /dev/null
+++ b/tests/NT8.Core.Tests/Logging/TradeProvenanceSerializerTests.cs
@@ -0,0 +1,58 @@
+using System;
+using System.Collections.Generic;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Newtonsoft.Json.Linq;
+using NT8.Core.Common.Models;
+using NT8.Core.Intelligence;
+using NT8.Core.Logging;
+
+namespace NT8.Core.Tests.Logging
+{
+ [TestClass]
+ public class TradeProvenanceSerializerTests
+ {
+ [TestMethod]
+ public void Serialize_SubmittedIntent_WritesComputedProvenanceValues()
+ {
+ var confluence = new ConfluenceScore(
+ 0.81,
+ 0.83,
+ TradeGrade.A,
+ new List(),
+ DateTime.UtcNow,
+ new Dictionary());
+ var metadata = new Dictionary();
+ metadata.Add("confluence_score", confluence);
+ metadata.Add("orb_range_ticks", 42.5);
+ var intent = new StrategyIntent(
+ "NQ",
+ OrderSide.Buy,
+ OrderType.Market,
+ null,
+ 20,
+ 40,
+ 0.83,
+ "synthetic trade",
+ metadata);
+
+ string json = TradeProvenanceSerializer.Serialize(
+ "session-1",
+ 1,
+ new DateTime(2026, 8, 3, 12, 0, 0, DateTimeKind.Utc),
+ intent,
+ 2,
+ 20.0,
+ "Mode1DualLeg",
+ "PCP",
+ 0.0,
+ "RTH_ORB",
+ "test-version");
+ JObject result = JObject.Parse(json);
+
+ Assert.AreEqual("A", (string)result["confluence_grade"]);
+ Assert.AreEqual(0.83, (double)result["confluence_score"], 0.000001);
+ Assert.AreEqual("Mode1DualLeg", (string)result["resolved_runner_mode"]);
+ Assert.AreEqual(42.5, (double)result["OrbRangeTicks"], 0.000001);
+ }
+ }
+}