fix: apply GAP-035 GAP-036 GAP-038 GAP-039 runtime remediations

This commit is contained in:
2026-08-16 16:58:31 -04:00
parent c4ad9696c0
commit 42427423ee
4 changed files with 291 additions and 16 deletions

View File

@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace NT8.Adapters
{
/// <summary>
/// Computes deterministic SHA256 hashes for strategy configuration provenance.
/// </summary>
public static class ConfigHashCalculator
{
/// <summary>
/// Computes a SHA256 hash from ordered configuration input strings.
/// </summary>
public static string Compute(IEnumerable<string> inputs)
{
if (inputs == null)
throw new ArgumentNullException("inputs");
string combined = string.Join("|", inputs);
using (SHA256 sha = SHA256.Create())
{
byte[] bytes = Encoding.UTF8.GetBytes(combined);
byte[] hash = sha.ComputeHash(bytes);
StringBuilder sb = new StringBuilder();
foreach (byte b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
}
}
}

View File

@@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.IO; using System.IO;
using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Windows.Media; using System.Windows.Media;
using NinjaTrader.Cbi; using NinjaTrader.Cbi;
@@ -16,6 +15,7 @@ using NinjaTrader.NinjaScript;
using NinjaTrader.NinjaScript.DrawingTools; using NinjaTrader.NinjaScript.DrawingTools;
using NinjaTrader.NinjaScript.Indicators; using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.Strategies; using NinjaTrader.NinjaScript.Strategies;
using NT8.Adapters;
using NT8.Adapters.NinjaTrader; using NT8.Adapters.NinjaTrader;
using NT8.Core.Common.Interfaces; using NT8.Core.Common.Interfaces;
using NT8.Core.Common.Models; using NT8.Core.Common.Models;
@@ -121,6 +121,8 @@ namespace NinjaTrader.NinjaScript.Strategies
private ExecutionCircuitBreaker _circuitBreaker; private ExecutionCircuitBreaker _circuitBreaker;
private System.IO.StreamWriter _fileLog; private System.IO.StreamWriter _fileLog;
private readonly object _fileLock = new object(); private readonly object _fileLock = new object();
private readonly Dictionary<string, int> _rejectCounts = new Dictionary<string, int>();
private readonly HashSet<string> _rejectDetailsLogged = new HashSet<string>();
// TASK-00a: Provenance Controls - session tracking // TASK-00a: Provenance Controls - session tracking
protected string _sessionId; protected string _sessionId;
@@ -396,6 +398,7 @@ namespace NinjaTrader.NinjaScript.Strategies
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix; MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
OrderFillResolution = OrderFillResolution.Standard; OrderFillResolution = OrderFillResolution.Standard;
Slippage = 0; Slippage = 0;
// AdoptAccountPosition avoids NT8 start-up synchronization submitting or flattening during historical replay bursts before the first live bar.
StartBehavior = StartBehavior.AdoptAccountPosition; StartBehavior = StartBehavior.AdoptAccountPosition;
TimeInForce = TimeInForce.Gtc; TimeInForce = TimeInForce.Gtc;
TraceOrders = false; TraceOrders = false;
@@ -521,7 +524,10 @@ namespace NinjaTrader.NinjaScript.Strategies
// Secondary series (e.g. daily bars for confluence) trigger OnBarUpdate separately // Secondary series (e.g. daily bars for confluence) trigger OnBarUpdate separately
// and must never generate strategy signals. // and must never generate strategy signals.
if (BarsInProgress != 0) if (BarsInProgress != 0)
{
LogRejectRateLimited("WarmupIncomplete", string.Format("BarsInProgress={0}; primary series only", BarsInProgress), Time[0]);
return; return;
}
// REPLAY BURST GUARD: Block all signal generation during the catch-up bar // REPLAY BURST GUARD: Block all signal generation during the catch-up bar
// replay that NT8 fires on strategy enable with AdoptAccountPosition. // replay that NT8 fires on strategy enable with AdoptAccountPosition.
@@ -535,7 +541,10 @@ namespace NinjaTrader.NinjaScript.Strategies
{ {
double ageSeconds = (DateTime.Now - Time[0]).TotalSeconds; double ageSeconds = (DateTime.Now - Time[0]).TotalSeconds;
if (ageSeconds > 300) if (ageSeconds > 300)
{
LogRejectRateLimited("WarmupIncomplete", string.Format("Replay burst guard ageSeconds={0:F0}", ageSeconds), Time[0]);
return; return;
}
} }
// NR7 warm-up advisory — log when daily series has fewer than 7 bars, // NR7 warm-up advisory — log when daily series has fewer than 7 bars,
@@ -558,21 +567,27 @@ namespace NinjaTrader.NinjaScript.Strategies
{ {
if (EnableVerboseLogging) if (EnableVerboseLogging)
Print(string.Format("[SDK] CME Holiday Guard: skipping bar {0} (holiday)", Time[0].ToString("yyyy-MM-dd"))); Print(string.Format("[SDK] CME Holiday Guard: skipping bar {0} (holiday)", Time[0].ToString("yyyy-MM-dd")));
LogRejectRateLimited("CmeHoliday", string.Format("Date={0:yyyy-MM-dd}", Time[0].Date), Time[0]);
return; return;
} }
if (!_sdkInitialized || _sdkStrategy == null) if (!_sdkInitialized || _sdkStrategy == null)
{ {
LogRejectRateLimited("WarmupIncomplete", string.Format("SdkInitialized={0} StrategyNull={1}", _sdkInitialized, _sdkStrategy == null), Time[0]);
return; return;
} }
if (CurrentBar < BarsRequiredToTrade) if (CurrentBar < BarsRequiredToTrade)
{ {
LogRejectRateLimited("WarmupIncomplete", string.Format("CurrentBar={0} BarsRequiredToTrade={1}", CurrentBar, BarsRequiredToTrade), Time[0]);
return; return;
} }
if (Time[0] == _lastBarTime) if (Time[0] == _lastBarTime)
{
LogRejectRateLimited("WarmupIncomplete", string.Format("Duplicate bar time={0:yyyy-MM-dd HH:mm:ss}", Time[0]), Time[0]);
return; return;
}
if (Time[0].Date != _lastBarTime.Date && _lastBarTime != DateTime.MinValue) if (Time[0].Date != _lastBarTime.Date && _lastBarTime != DateTime.MinValue)
{ {
@@ -590,6 +605,7 @@ namespace NinjaTrader.NinjaScript.Strategies
{ {
_realtimeBarSeen = true; _realtimeBarSeen = true;
Print(string.Format("[SDK] First realtime bar seen: {0}", Time[0])); Print(string.Format("[SDK] First realtime bar seen: {0}", Time[0]));
LogRejectRateLimited("WarmupIncomplete", "First realtime bar marks eligibility; no signal generated on this bar", Time[0]);
return; return;
} }
@@ -613,6 +629,7 @@ namespace NinjaTrader.NinjaScript.Strategies
Print(string.Format("[SDK] Kill switch flatten error: {0}", ex.Message)); Print(string.Format("[SDK] Kill switch flatten error: {0}", ex.Message));
} }
} }
LogRejectRateLimited("KillSwitch", string.Format("EnableKillSwitch=True KillSwitchTriggered={0}", _killSwitchTriggered), Time[0]);
return; return;
} }
@@ -621,6 +638,7 @@ namespace NinjaTrader.NinjaScript.Strategies
{ {
if (EnableVerboseLogging) if (EnableVerboseLogging)
Print(string.Format("[NT8-SDK] Bar skipped — connection lost: {0}", Time[0])); Print(string.Format("[NT8-SDK] Bar skipped — connection lost: {0}", Time[0]));
LogRejectRateLimited("ConnectionLost", "Broker connection lost; new orders halted", Time[0]);
return; return;
} }
@@ -641,6 +659,7 @@ namespace NinjaTrader.NinjaScript.Strategies
if (EnableVerboseLogging && CurrentBar % 500 == 0) if (EnableVerboseLogging && CurrentBar % 500 == 0)
Print(string.Format("[SDK] Skipping ETH bar {0} at {1:HH:mm}", Print(string.Format("[SDK] Skipping ETH bar {0} at {1:HH:mm}",
CurrentBar, Time[0])); CurrentBar, Time[0]));
LogRejectRateLimited("RthGuard", string.Format("Time={0:HH:mm:ss} TestMode={1}", Time[0], isTestMode), Time[0]);
return; return;
} }
@@ -719,6 +738,10 @@ namespace NinjaTrader.NinjaScript.Strategies
Print(string.Format("[SDK] Intent generated: {0} {1} @ {2}", intent.Side, intent.Symbol, intent.EntryType)); Print(string.Format("[SDK] Intent generated: {0} {1} @ {2}", intent.Side, intent.Symbol, intent.EntryType));
ProcessStrategyIntent(intent, context); ProcessStrategyIntent(intent, context);
} }
else
{
LogSignalRejectionFromContext(context);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -937,8 +960,70 @@ namespace NinjaTrader.NinjaScript.Strategies
} }
} }
private void LogSignalRejectionFromContext(StrategyContext context)
{
if (context == null || context.CustomData == null)
return;
if (!context.CustomData.ContainsKey("signal_reject_reason"))
return;
string reason = Convert.ToString(context.CustomData["signal_reject_reason"]);
string detail = context.CustomData.ContainsKey("signal_reject_detail")
? Convert.ToString(context.CustomData["signal_reject_detail"])
: string.Empty;
DateTime barTime = Time[0];
if (context.CustomData.ContainsKey("signal_reject_bar") && context.CustomData["signal_reject_bar"] is DateTime)
barTime = (DateTime)context.CustomData["signal_reject_bar"];
LogRejectRateLimited(reason, detail, barTime);
}
private void LogRejectRateLimited(string reason, string detail, DateTime barTime)
{
if (!EnableFileLogging || State != State.Realtime)
return;
if (string.IsNullOrEmpty(reason))
reason = "WarmupIncomplete";
if (detail == null)
detail = string.Empty;
if (!_rejectCounts.ContainsKey(reason))
_rejectCounts.Add(reason, 0);
_rejectCounts[reason] = _rejectCounts[reason] + 1;
if (_rejectDetailsLogged.Contains(reason))
return;
_rejectDetailsLogged.Add(reason);
FileLog(string.Format("REJECT: reason={0} detail={1} bar={2:yyyy-MM-dd HH:mm:ss}", reason, detail, barTime));
}
private void WriteRejectSummary()
{
if (_rejectCounts.Count == 0)
return;
List<string> reasons = new List<string>(_rejectCounts.Keys);
reasons.Sort(StringComparer.OrdinalIgnoreCase);
foreach (string reason in reasons)
{
FileLog(string.Format("REJECT SUMMARY: reason={0} count={1}", reason, _rejectCounts[reason]));
}
}
private void ResetRejectTracking()
{
_rejectCounts.Clear();
_rejectDetailsLogged.Clear();
}
private void WriteSessionHeader() private void WriteSessionHeader()
{ {
ResetRejectTracking();
FileLog("=== SESSION START " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ==="); FileLog("=== SESSION START " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ===");
FileLog(string.Format("Mode : {0}", State == State.Historical ? "BACKTEST" : "LIVE/SIM")); FileLog(string.Format("Mode : {0}", State == State.Historical ? "BACKTEST" : "LIVE/SIM"));
FileLog(string.Format("Strategy : {0}", Name)); FileLog(string.Format("Strategy : {0}", Name));
@@ -988,6 +1073,21 @@ namespace NinjaTrader.NinjaScript.Strategies
daysToLoad, daysToLoad,
loadedBars)); loadedBars));
if (i == 0)
{
if (!IsTimeBasedBarsType(seriesType))
{
FileLog(string.Format("WARNING: DataSeries[0] is not a recognized time-based bar type; Type={0}. Advisory only; trading is not blocked.",
seriesType));
}
if (daysToLoad < 30)
{
FileLog(string.Format("WARNING: DataSeries[0] DaysToLoad below 30; DaysToLoad={0}. Advisory only; trading is not blocked.",
daysToLoad));
}
}
if (seriesType.IndexOf("DayBarsType", StringComparison.OrdinalIgnoreCase) >= 0) if (seriesType.IndexOf("DayBarsType", StringComparison.OrdinalIgnoreCase) >= 0)
dailyBars = loadedBars; dailyBars = loadedBars;
} }
@@ -1017,9 +1117,23 @@ namespace NinjaTrader.NinjaScript.Strategies
} }
} }
private bool IsTimeBasedBarsType(string seriesType)
{
if (string.IsNullOrEmpty(seriesType))
return false;
return seriesType.IndexOf("MinuteBarsType", StringComparison.OrdinalIgnoreCase) >= 0
|| seriesType.IndexOf("SecondBarsType", StringComparison.OrdinalIgnoreCase) >= 0
|| seriesType.IndexOf("DayBarsType", StringComparison.OrdinalIgnoreCase) >= 0
|| seriesType.IndexOf("WeekBarsType", StringComparison.OrdinalIgnoreCase) >= 0
|| seriesType.IndexOf("MonthBarsType", StringComparison.OrdinalIgnoreCase) >= 0
|| seriesType.IndexOf("YearBarsType", StringComparison.OrdinalIgnoreCase) >= 0;
}
private void WriteSessionFooter() private void WriteSessionFooter()
{ {
FileLog("---"); FileLog("---");
WriteRejectSummary();
FileLog("=== SESSION END " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ==="); FileLog("=== SESSION END " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ===");
if (_fileLog != null) if (_fileLog != null)
@@ -1114,6 +1228,7 @@ namespace NinjaTrader.NinjaScript.Strategies
customData.Add("CurrentBar", CurrentBar); customData.Add("CurrentBar", CurrentBar);
customData.Add("BarsRequiredToTrade", BarsRequiredToTrade); customData.Add("BarsRequiredToTrade", BarsRequiredToTrade);
customData.Add("OrdersToday", _ordersSubmittedToday); customData.Add("OrdersToday", _ordersSubmittedToday);
customData.Add("AllowDailyTradeCountIncrement", ShouldAllowDailyTradeCountIncrement());
// GAP-010: Pass short trend filter setting to SDK strategy // GAP-010: Pass short trend filter setting to SDK strategy
customData.Add("EnableShortTrendFilter", EnableShortTrendFilter); customData.Add("EnableShortTrendFilter", EnableShortTrendFilter);
@@ -1170,6 +1285,17 @@ namespace NinjaTrader.NinjaScript.Strategies
customData); customData);
} }
private bool ShouldAllowDailyTradeCountIncrement()
{
if (State == State.Realtime)
return _realtimeBarSeen;
if (State == State.Historical)
return Account == null;
return false;
}
private AccountInfo BuildAccountInfo() private AccountInfo BuildAccountInfo()
{ {
double cashValue = 100000.0; double cashValue = 100000.0;
@@ -1231,7 +1357,10 @@ namespace NinjaTrader.NinjaScript.Strategies
// In live/SIM: block if we haven't seen a genuine realtime bar yet (replay guard). // In live/SIM: block if we haven't seen a genuine realtime bar yet (replay guard).
// In Strategy Analyzer (State.Historical): always allow — backtest must execute normally. // In Strategy Analyzer (State.Historical): always allow — backtest must execute normally.
if (State == State.Realtime && !_realtimeBarSeen) if (State == State.Realtime && !_realtimeBarSeen)
{
LogRejectRateLimited("WarmupIncomplete", "ProcessStrategyIntent blocked before first realtime bar", Time[0]);
return; return;
}
if (EnableFileLogging && State == State.Realtime) if (EnableFileLogging && State == State.Realtime)
FileLog(string.Format("SIGNAL: {0} {1} | {2}", intent.Side, intent.Symbol, GetTestModeBanner())); FileLog(string.Format("SIGNAL: {0} {1} | {2}", intent.Side, intent.Symbol, GetTestModeBanner()));
@@ -1243,6 +1372,7 @@ namespace NinjaTrader.NinjaScript.Strategies
Print(string.Format("[SDK] Portfolio blocked: {0}", portfolioDecision.RejectReason)); Print(string.Format("[SDK] Portfolio blocked: {0}", portfolioDecision.RejectReason));
if (_logger != null) if (_logger != null)
_logger.LogWarning("Portfolio risk blocked order: {0}", portfolioDecision.RejectReason); _logger.LogWarning("Portfolio risk blocked order: {0}", portfolioDecision.RejectReason);
LogRejectRateLimited("KillSwitch", string.Format("Portfolio blocked: {0}", portfolioDecision.RejectReason), Time[0]);
return; return;
} }
@@ -1251,12 +1381,14 @@ namespace NinjaTrader.NinjaScript.Strategies
{ {
if (EnableVerboseLogging) if (EnableVerboseLogging)
Print(string.Format("[SDK] Long trade filtered by direction setting: {0}", intent.Symbol)); Print(string.Format("[SDK] Long trade filtered by direction setting: {0}", intent.Symbol));
LogRejectRateLimited("GradeFilter", string.Format("EnableLongTrades=False Symbol={0}", intent.Symbol), Time[0]);
return; return;
} }
if (intent.Side == SdkOrderSide.Sell && !EnableShortTrades) if (intent.Side == SdkOrderSide.Sell && !EnableShortTrades)
{ {
if (EnableVerboseLogging) if (EnableVerboseLogging)
Print(string.Format("[SDK] Short trade filtered by direction setting: {0}", intent.Symbol)); Print(string.Format("[SDK] Short trade filtered by direction setting: {0}", intent.Symbol));
LogRejectRateLimited("GradeFilter", string.Format("EnableShortTrades=False Symbol={0}", intent.Symbol), Time[0]);
return; return;
} }
@@ -1270,6 +1402,7 @@ namespace NinjaTrader.NinjaScript.Strategies
Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason)); Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason));
if (_logger != null) if (_logger != null)
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason); _logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
LogRejectRateLimited("KillSwitch", string.Format("Risk manager rejected: {0}", riskDecision.RejectReason), Time[0]);
return; return;
} }
@@ -1289,6 +1422,7 @@ namespace NinjaTrader.NinjaScript.Strategies
{ {
if (EnableVerboseLogging) if (EnableVerboseLogging)
Print(string.Format("[SDK] Size too small: {0} < {1}", sizingResult.Contracts, MinContracts)); Print(string.Format("[SDK] Size too small: {0} < {1}", sizingResult.Contracts, MinContracts));
LogRejectRateLimited("GradeFilter", string.Format("Size too small Contracts={0} MinContracts={1}", sizingResult.Contracts, MinContracts), Time[0]);
return; return;
} }
@@ -1323,6 +1457,7 @@ namespace NinjaTrader.NinjaScript.Strategies
Print(String.Format("[SDK] Circuit breaker OPEN — order blocked: {0}", cbState.Reason)); Print(String.Format("[SDK] Circuit breaker OPEN — order blocked: {0}", cbState.Reason));
if (_logger != null) if (_logger != null)
_logger.LogWarning("Circuit breaker blocked order: {0}", cbState.Reason); _logger.LogWarning("Circuit breaker blocked order: {0}", cbState.Reason);
LogRejectRateLimited("KillSwitch", string.Format("Circuit breaker open: {0}", cbState.Reason), Time[0]);
return; return;
} }
} }
@@ -1721,7 +1856,7 @@ namespace NinjaTrader.NinjaScript.Strategies
#region TASK-00a: Provenance Controls #region TASK-00a: Provenance Controls
/// <summary> /// <summary>
/// Generates a SHA256 hash of all NinjaScriptProperty values for configuration provenance. /// Generates a SHA256 hash of NinjaScriptProperty values plus stable settings-export fields for configuration provenance.
/// </summary> /// </summary>
protected string ComputeConfigHash() protected string ComputeConfigHash()
{ {
@@ -1736,16 +1871,33 @@ namespace NinjaTrader.NinjaScript.Strategies
props.Add(prop.Name + "=" + (val != null ? val.ToString() : "null")); props.Add(prop.Name + "=" + (val != null ? val.ToString() : "null"));
} }
} }
var combined = string.Join("|", props); AddSettingsExportHashInputs(props);
using (var sha = SHA256.Create()) return ConfigHashCalculator.Compute(props);
{ }
var bytes = Encoding.UTF8.GetBytes(combined);
var hash = sha.ComputeHash(bytes); protected virtual void AddSettingsExportHashInputs(List<string> props)
var sb = new StringBuilder(); {
foreach (var b in hash) if (props == null)
sb.Append(b.ToString("x2")); throw new ArgumentNullException("props");
return sb.ToString();
} props.Add("StrategyName=" + (Name != null ? Name : "null"));
props.Add("Description=" + (Description != null ? Description : "null"));
props.Add("Account=" + (Account != null ? Account.Name : "N/A"));
props.Add("Instrument=" + (Instrument != null ? Instrument.FullName : "N/A"));
props.Add("BarsPeriodValue=" + GetBarsPeriodValueForHash());
props.Add("BarsPeriodType=" + GetBarsPeriodTypeForHash());
props.Add("BarsRequiredToTrade=" + BarsRequiredToTrade.ToString());
props.Add("Calculate=" + Calculate.ToString());
}
protected virtual string GetBarsPeriodValueForHash()
{
return BarsPeriod != null ? BarsPeriod.Value.ToString() : "N/A";
}
protected virtual string GetBarsPeriodTypeForHash()
{
return BarsPeriod != null ? BarsPeriod.BarsPeriodType.ToString() : "N/A";
} }
/// <summary> /// <summary>
@@ -1840,7 +1992,7 @@ namespace NinjaTrader.NinjaScript.Strategies
quantity, quantity,
atrStopTicks, atrStopTicks,
resolvedMode.ToString(), resolvedMode.ToString(),
GetRiskMode(), GetRiskMode(intent),
GetDailyPnL(), GetDailyPnL(),
GetSessionTag(), GetSessionTag(),
GetCodeVersionStamp()); GetCodeVersionStamp());
@@ -1916,6 +2068,18 @@ namespace NinjaTrader.NinjaScript.Strategies
return "Unknown"; return "Unknown";
} }
private string GetRiskMode(StrategyIntent intent)
{
if (intent != null && intent.Metadata != null && intent.Metadata.ContainsKey("risk_mode"))
{
var mode = intent.Metadata["risk_mode"];
if (mode != null)
return mode.ToString();
}
return GetRiskMode();
}
private double GetDailyPnL() private double GetDailyPnL()
{ {
if (_lastAccountInfo != null) if (_lastAccountInfo != null)

View File

@@ -134,8 +134,8 @@ namespace NinjaTrader.NinjaScript.Strategies
BarsRequiredToTrade = 50; BarsRequiredToTrade = 50;
MinTradeGrade = 5; MinTradeGrade = 5;
EnableLongTrades = true; EnableLongTrades = true;
// Long-only: short trades permanently disabled pending backtest confirmation // Shorts are in scope for the gate run; keep source defaults aligned with live workspace usage.
EnableShortTrades = false; EnableShortTrades = true;
EnableAutoBreakeven = true; EnableAutoBreakeven = true;
BreakevenTriggerTicks = 20; BreakevenTriggerTicks = 20;
BreakevenOffsetTicks = 1; BreakevenOffsetTicks = 1;
@@ -152,6 +152,7 @@ namespace NinjaTrader.NinjaScript.Strategies
ATRTrailingMultiplier = 2.0; // GAP-009 ATRTrailingMultiplier = 2.0; // GAP-009
ATRTrailingMinTicks = 8; // GAP-009 ATRTrailingMinTicks = 8; // GAP-009
ATRTrailingMaxTicks = 60; // GAP-009 ATRTrailingMaxTicks = 60; // GAP-009
// AdoptAccountPosition avoids NT8 start-up synchronization submitting or flattening during historical replay bursts before the first live bar.
StartBehavior = StartBehavior.AdoptAccountPosition; StartBehavior = StartBehavior.AdoptAccountPosition;
} }
else if (State == State.Configure) else if (State == State.Configure)

View File

@@ -345,6 +345,7 @@ namespace NT8.Strategies.Examples
lock (_lock) lock (_lock)
{ {
EnsureInitialized(); EnsureInitialized();
ClearSignalRejection(context);
UpdateRiskMode(context); UpdateRiskMode(context);
UpdateConfluenceInputs(bar, context); UpdateConfluenceInputs(bar, context);
@@ -380,7 +381,10 @@ namespace NT8.Strategies.Examples
// Only trade during RTH — bypassed in TestMode // Only trade during RTH — bypassed in TestMode
if (!testMode && (context.Session == null || !context.Session.IsRth)) if (!testMode && (context.Session == null || !context.Session.IsRth))
{
RecordSignalRejection(context, "RthGuard", string.Format("SessionIsRth={0}", context.Session != null ? context.Session.IsRth.ToString() : "null"), bar.Time);
return null; return null;
}
// GAP-008: CME Holiday Guard — skip ORB window on CME holidays // GAP-008: CME Holiday Guard — skip ORB window on CME holidays
if (!testMode && EnableCMEHolidayGuard) if (!testMode && EnableCMEHolidayGuard)
@@ -389,6 +393,7 @@ namespace NT8.Strategies.Examples
{ {
if (_logger != null) if (_logger != null)
_logger.LogInformation("Skipping ORB window on CME holiday: {0:yyyy-MM-dd}", bar.Time.Date); _logger.LogInformation("Skipping ORB window on CME holiday: {0:yyyy-MM-dd}", bar.Time.Date);
RecordSignalRejection(context, "CmeHoliday", string.Format("Date={0:yyyy-MM-dd}", bar.Time.Date), bar.Time);
return null; return null;
} }
} }
@@ -413,6 +418,7 @@ namespace NT8.Strategies.Examples
if (bar.Time <= _openingRangeEnd) if (bar.Time <= _openingRangeEnd)
{ {
UpdateOpeningRange(bar); UpdateOpeningRange(bar);
RecordSignalRejection(context, "OrbRangeNotEstablished", string.Format("ORB window still building start={0:HH:mm} end={1:HH:mm} high={2:F2} low={3:F2}", _openingRangeStart, _openingRangeEnd, _openingRangeHigh, _openingRangeLow), bar.Time);
return null; return null;
} }
@@ -421,7 +427,10 @@ namespace NT8.Strategies.Examples
if (_openingRangeHigh > _openingRangeLow) if (_openingRangeHigh > _openingRangeLow)
_openingRangeReady = true; _openingRangeReady = true;
else else
{
RecordSignalRejection(context, "OrbRangeNotEstablished", string.Format("Invalid ORB high={0:F2} low={1:F2}", _openingRangeHigh, _openingRangeLow), bar.Time);
return null; return null;
}
} }
} }
@@ -453,6 +462,7 @@ namespace NT8.Strategies.Examples
_currentSessionDate, _currentSessionDate,
bar.Time, bar.Time,
context.Symbol); 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; return null;
} }
@@ -559,7 +569,10 @@ namespace NT8.Strategies.Examples
} }
if (candidate == null) if (candidate == null)
{
RecordSignalRejection(context, "OrbRangeNotEstablished", string.Format("No confirmed breakout close={0:F2} longTrigger={1:F2} shortTrigger={2:F2} breakoutBarSeen={3} pendingDirection={4}", bar.Close, longTrigger, shortTrigger, _breakoutBarSeen, _pendingBreakoutDirection), bar.Time);
return null; return null;
}
AttachDailyBarContext(candidate, bar, context); AttachDailyBarContext(candidate, bar, context);
@@ -597,6 +610,7 @@ namespace NT8.Strategies.Examples
{ {
if (_logger != null) if (_logger != null)
_logger.LogInformation("Short vetoed by regime filter: AVWAP slope {0:F4} > 0 (bullish)", slopeVal); _logger.LogInformation("Short vetoed by regime filter: AVWAP slope {0:F4} > 0 (bullish)", slopeVal);
RecordSignalRejection(context, "GradeFilter", string.Format("Regime veto before score; Side={0} AVWAPSlope={1:F4} EnableShortTrendFilter=True", candidate.Side, slopeVal), bar.Time);
return null; return null;
} }
} }
@@ -605,6 +619,7 @@ namespace NT8.Strategies.Examples
// Long veto in bearish regime - always enforced (no parameter for this yet) // Long veto in bearish regime - always enforced (no parameter for this yet)
if (_logger != null) if (_logger != null)
_logger.LogInformation("Trade vetoed: AVWAP slope {0:F4} against {1} direction", slopeVal, candidate.Side); _logger.LogInformation("Trade vetoed: AVWAP slope {0:F4} against {1} direction", slopeVal, candidate.Side);
RecordSignalRejection(context, "GradeFilter", string.Format("Regime veto before score; Side={0} AVWAPSlope={1:F4}", candidate.Side, slopeVal), bar.Time);
return null; return null;
} }
} }
@@ -632,6 +647,7 @@ namespace NT8.Strategies.Examples
score.WeightedScore, score.WeightedScore,
score.Grade, score.Grade,
minGrade); minGrade);
RecordSignalRejection(context, "GradeFilter", string.Format("Score={0:F3} Grade={1} MinTradeGrade={2} Factors={3}", score.WeightedScore, score.Grade, minGrade, FormatFactorBreakdown(score)), bar.Time);
return null; return null;
} }
@@ -650,7 +666,8 @@ namespace NT8.Strategies.Examples
candidate.Metadata["combined_multiplier"] = combinedMultiplier; candidate.Metadata["combined_multiplier"] = combinedMultiplier;
_tradeTaken = true; _tradeTaken = true;
_dailyTradeCount++; if (ShouldIncrementDailyTradeCount(context))
_dailyTradeCount++;
if (_logger != null) if (_logger != null)
_logger.LogDebug( _logger.LogDebug(
@@ -962,6 +979,66 @@ namespace NT8.Strategies.Examples
_openingRangeLow = bar.Low; _openingRangeLow = bar.Low;
} }
private void RecordSignalRejection(StrategyContext context, string reason, string detail, DateTime barTime)
{
if (context == null)
return;
if (context.CustomData == null)
context.CustomData = new Dictionary<string, object>();
context.CustomData["signal_reject_reason"] = reason;
context.CustomData["signal_reject_detail"] = detail;
context.CustomData["signal_reject_bar"] = barTime;
context.CustomData["signal_reject_line"] = string.Format("REJECT: reason={0} detail={1} bar={2:yyyy-MM-dd HH:mm:ss}", reason, detail, barTime);
}
private bool ShouldIncrementDailyTradeCount(StrategyContext context)
{
if (context == null || context.CustomData == null)
return true;
if (!context.CustomData.ContainsKey("AllowDailyTradeCountIncrement"))
return true;
object value = context.CustomData["AllowDailyTradeCountIncrement"];
if (value is bool)
return (bool)value;
return true;
}
private void ClearSignalRejection(StrategyContext context)
{
if (context == null || context.CustomData == null)
return;
if (context.CustomData.ContainsKey("signal_reject_reason"))
context.CustomData.Remove("signal_reject_reason");
if (context.CustomData.ContainsKey("signal_reject_detail"))
context.CustomData.Remove("signal_reject_detail");
if (context.CustomData.ContainsKey("signal_reject_bar"))
context.CustomData.Remove("signal_reject_bar");
if (context.CustomData.ContainsKey("signal_reject_line"))
context.CustomData.Remove("signal_reject_line");
}
private string FormatFactorBreakdown(ConfluenceScore score)
{
if (score == null || score.Factors == null)
return "none";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (ConfluenceFactor factor in score.Factors)
{
if (sb.Length > 0)
sb.Append(";");
sb.Append(string.Format("{0}={1:F2}x{2:F2}", factor.Type, factor.Score, factor.Weight));
}
return sb.Length > 0 ? sb.ToString() : "none";
}
private StrategyIntent CreateIntent(string symbol, OrderSide side, double openingRange, double lastPrice) private StrategyIntent CreateIntent(string symbol, OrderSide side, double openingRange, double lastPrice)
{ {
var stopTicks = _config != null && _config.Parameters.ContainsKey("StopTicks") var stopTicks = _config != null && _config.Parameters.ContainsKey("StopTicks")