[GAP-077]: backtest historical guard + backtest-aware reject logging

This commit is contained in:
2026-10-26 12:45:30 -04:00
parent b20b621c45
commit e2439c0adf
3 changed files with 129 additions and 16 deletions

View File

@@ -27,29 +27,129 @@ namespace NT8.Core.Tests.Adapters
string source = File.ReadAllText(FindStrategyBaseSourceFile());
string method = ExtractMethodBlock(source, "private void ProcessStrategyIntent");
int historicalGuard = method.IndexOf("if (State == State.Historical && Account != null)", StringComparison.Ordinal);
int historicalGuard = method.IndexOf("if (State == State.Historical && !IsBacktestRun())", StringComparison.Ordinal);
int portfolioRisk = method.IndexOf("Portfolio-level risk check", StringComparison.Ordinal);
int submit = method.IndexOf("SubmitOrderToNT8", StringComparison.Ordinal);
Assert.IsTrue(historicalGuard >= 0, "ProcessStrategyIntent must retain the live-account historical guard.");
Assert.IsTrue(historicalGuard >= 0, "ProcessStrategyIntent must block historical catch-up orders only outside backtests.");
Assert.IsTrue(method.Contains("HistoricalReplayCatchup"), "Historical catch-up rejections must remain diagnosable.");
Assert.IsTrue(method.Contains("return;"), "Historical catch-up guard must return before order processing.");
Assert.IsTrue(portfolioRisk > historicalGuard, "Historical guard must run before portfolio risk.");
Assert.IsTrue(submit > historicalGuard, "Historical guard must run before order submission.");
Assert.IsFalse(method.Contains("State == State.Historical && Account != null"), "A non-null Strategy Analyzer account must not be treated as live catch-up.");
}
[TestMethod]
public void IsBacktestRun_UsesAnalyzerPropertyAndNamedAccountFallback()
{
string source = File.ReadAllText(FindStrategyBaseSourceFile());
string method = ExtractMethodBlock(source, "private bool IsBacktestRun");
Assert.IsTrue(method.Contains("if (IsInStrategyAnalyzer)"), "Strategy Analyzer execution must be recognized directly.");
Assert.IsTrue(method.Contains("string.Equals(Account.Name, \"Backtest\", StringComparison.OrdinalIgnoreCase)"), "The evidence-backed Backtest account-name fallback must remain.");
}
[TestMethod]
public void NT8StrategyBase_HasNoAccountPresenceHistoricalCatchupGuard()
{
string source = File.ReadAllText(FindStrategyBaseSourceFile());
Assert.IsFalse(source.Contains("State == State.Historical && Account != null"), "Historical catch-up must be distinguished from Strategy Analyzer by IsBacktestRun, not account presence.");
}
[TestMethod]
public void ShouldAllowDailyTradeCountIncrement_HistoricalUsesBacktestPredicate()
{
string source = File.ReadAllText(FindStrategyBaseSourceFile());
string method = ExtractMethodBlock(source, "private bool ShouldAllowDailyTradeCountIncrement");
int historical = method.IndexOf("if (State == State.Historical)", StringComparison.Ordinal);
Assert.IsTrue(historical >= 0, "Historical daily-trade counting branch must remain.");
Assert.IsTrue(method.IndexOf("return IsBacktestRun();", historical, StringComparison.Ordinal) > historical, "Backtest daily trade counts must increment in the Analyzer.");
Assert.IsFalse(method.Contains("return Account == null;"), "Analyzer account presence must not disable daily trade counting.");
}
[TestMethod]
public void WriteSessionHeader_LabelsAnalyzerExecutionAsBacktest()
{
string source = File.ReadAllText(FindStrategyBaseSourceFile());
string method = ExtractMethodBlock(source, "private void WriteSessionHeader");
Assert.IsTrue(method.Contains("IsBacktestRun() ? \"BACKTEST\" : \"LIVE/SIM\""), "The session header must identify Strategy Analyzer execution before OnBarUpdate.");
}
[TestMethod]
public void DailyTradeCountPersistence_IsDisabledUntilEligibleRealtimeExecution()
{
string source = File.ReadAllText(FindStrategyBaseSourceFile());
string realtimeState = ExtractMethodBlock(source, "protected override void OnStateChange");
string context = ExtractMethodBlock(source, "private StrategyContext BuildStrategyContext");
string orbSource = File.ReadAllText(FindSourceFile("SimpleORBNT8.cs"));
string orbParameters = ExtractMethodBlock(orbSource, "protected override void ConfigureStrategyParameters");
Assert.IsTrue(realtimeState.Contains("_sdkStrategy != null && Account != null && !IsBacktestRun()"), "Persistence must only be enabled on the realtime transition for non-backtest accounts.");
Assert.IsTrue(context.Contains("State == State.Realtime && Account != null && !IsBacktestRun()"), "Historical/backtest contexts must not enable persistence.");
Assert.IsTrue(orbParameters.Contains("daily_trade_count_persistence_enabled\"] = false;"), "Initial strategy configuration must not load or write an account-scoped backtest file.");
}
[TestMethod]
public void TrailingDrawdownRegistrationAndHaltChecks_ExcludeBacktests()
{
string source = File.ReadAllText(FindStrategyBaseSourceFile());
string initializeComponents = ExtractMethodBlock(source, "private void InitializeSdkComponents");
string initializeDrawdown = ExtractMethodBlock(source, "private void InitializeTrailingDrawdownState");
string checkDrawdown = ExtractMethodBlock(source, "private bool CheckTrailingDrawdownMonitor");
string processIntent = ExtractMethodBlock(source, "private void ProcessStrategyIntent");
Assert.IsTrue(initializeComponents.Contains("Account != null && !IsBacktestRun()"), "The base SDK initialization must not register a Backtest account with the trailing monitor.");
Assert.IsTrue(initializeDrawdown.Contains("Account == null || IsBacktestRun()"), "Backtests must not register or read trailing-drawdown state.");
Assert.IsTrue(checkDrawdown.Contains("!EnableTrailingDrawdown || IsBacktestRun() || Account == null"), "Backtests must not query live trailing-drawdown account state.");
Assert.IsTrue(processIntent.Contains("EnableTrailingDrawdown && !IsBacktestRun() && Account != null"), "Backtests must not consult the live account trailing-drawdown monitor.");
}
[TestMethod]
public void LogRejectRateLimited_CountsBacktestReasonsAndKeepsFirstDetailOnly()
{
string source = File.ReadAllText(FindStrategyBaseSourceFile());
string method = ExtractMethodBlock(source, "private void LogRejectRateLimited");
int gate = method.IndexOf("State != State.Realtime && !IsBacktestRun() && reason != \"HistoricalReplayCatchup\"", StringComparison.Ordinal);
int count = method.IndexOf("_rejectCounts[reason] = _rejectCounts[reason] + 1;", StringComparison.Ordinal);
int firstDetail = method.IndexOf("if (_rejectDetailsLogged.Contains(reason))", StringComparison.Ordinal);
Assert.IsTrue(gate >= 0, "Non-realtime backtests must pass the logging gate while live historical catch-up remains diagnosable.");
Assert.IsTrue(count > gate, "Backtest rejection counts must be incremented after the mode gate.");
Assert.IsTrue(firstDetail > count, "Only the first detail for each rejection reason should be logged.");
}
[TestMethod]
public void MaybeWriteRejectSummarySnapshot_LimitsBacktestsToOneSnapshotPerTradingDate()
{
string source = File.ReadAllText(FindStrategyBaseSourceFile());
string method = ExtractMethodBlock(source, "private void MaybeWriteRejectSummarySnapshot");
int perDayGate = method.IndexOf("if (IsBacktestRun() && _orbRejectSummarySnapshotWritten)", StringComparison.Ordinal);
int write = method.IndexOf("WriteRejectSummary();", StringComparison.Ordinal);
Assert.IsTrue(perDayGate >= 0, "Backtests need a once-per-trading-date snapshot cap.");
Assert.IsTrue(write > perDayGate, "The cap must run before writing a backtest summary snapshot.");
}
private static string FindStrategyBaseSourceFile()
{
return FindSourceFile("NT8StrategyBase.cs");
}
private static string FindSourceFile(string fileName)
{
DirectoryInfo dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
while (dir != null)
{
string candidate = Path.Combine(dir.FullName, "src", "NT8.Adapters", "Strategies", "NT8StrategyBase.cs");
string candidate = Path.Combine(dir.FullName, "src", "NT8.Adapters", "Strategies", fileName);
if (File.Exists(candidate))
return candidate;
dir = dir.Parent;
}
throw new FileNotFoundException("Could not locate src\\NT8.Adapters\\Strategies\\NT8StrategyBase.cs from test output directory.");
throw new FileNotFoundException("Could not locate src\\NT8.Adapters\\Strategies\\" + fileName + " from test output directory.");
}
private static string ExtractMethodBlock(string source, string signature)