[GAP-077]: backtest historical guard + backtest-aware reject logging
This commit is contained in:
@@ -592,7 +592,7 @@ 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)
|
||||
if (_sdkStrategy != null && Account != null && !IsBacktestRun())
|
||||
{
|
||||
var dailyCountParams = new Dictionary<string, object>();
|
||||
dailyCountParams.Add("daily_trade_count_persistence_enabled", true);
|
||||
@@ -957,7 +957,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
|
||||
private bool CheckTrailingDrawdownMonitor()
|
||||
{
|
||||
if (!EnableTrailingDrawdown || Account == null || State != State.Realtime)
|
||||
if (!EnableTrailingDrawdown || IsBacktestRun() || Account == null || State != State.Realtime)
|
||||
return _trailingDrawdownHalted;
|
||||
|
||||
if (_trailingDrawdownHalted)
|
||||
@@ -1526,7 +1526,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
if (!EnableFileLogging)
|
||||
return;
|
||||
|
||||
if (State != State.Realtime && reason != "HistoricalReplayCatchup")
|
||||
if (State != State.Realtime && !IsBacktestRun() && reason != "HistoricalReplayCatchup")
|
||||
return;
|
||||
|
||||
if (string.IsNullOrEmpty(reason))
|
||||
@@ -1576,6 +1576,9 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
_orbRejectSummarySnapshotWritten = false;
|
||||
}
|
||||
|
||||
if (IsBacktestRun() && _orbRejectSummarySnapshotWritten)
|
||||
return;
|
||||
|
||||
bool dueAfterOrbWindow = !_orbRejectSummarySnapshotWritten;
|
||||
bool dueInterval = _lastRejectSummarySnapshotTime != DateTime.MinValue
|
||||
&& (barTime - _lastRejectSummarySnapshotTime).TotalMinutes >= REJECT_SUMMARY_SNAPSHOT_INTERVAL_MINUTES;
|
||||
@@ -1618,7 +1621,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
{
|
||||
ResetRejectTracking();
|
||||
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}", IsBacktestRun() ? "BACKTEST" : "LIVE/SIM"));
|
||||
FileLog(string.Format("Strategy : {0}", Name));
|
||||
FileLog(string.Format("Account : {0}", Account != null ? Account.Name : "N/A"));
|
||||
FileLog(string.Format("Symbol : {0}", Instrument != null ? Instrument.FullName : "N/A"));
|
||||
@@ -1795,7 +1798,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
PortfolioRiskManager.Instance.RegisterStrategy(Name, _riskConfig);
|
||||
Print(string.Format("[NT8-SDK] Registered with PortfolioRiskManager: {0}", PortfolioRiskManager.Instance.GetStatusSnapshot()));
|
||||
|
||||
if (Account != null)
|
||||
if (Account != null && !IsBacktestRun())
|
||||
{
|
||||
_trailingDrawdownAccountName = Account.Name;
|
||||
TrailingDrawdownMonitor.Instance.RegisterStrategy(_trailingDrawdownAccountName, this);
|
||||
@@ -1832,7 +1835,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
|
||||
private void InitializeTrailingDrawdownState()
|
||||
{
|
||||
if (Account == null)
|
||||
if (Account == null || IsBacktestRun())
|
||||
return;
|
||||
|
||||
_trailingDrawdownAccountName = Account.Name;
|
||||
@@ -1938,7 +1941,7 @@ 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_persistence_enabled", State == State.Realtime && Account != null && !IsBacktestRun());
|
||||
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"));
|
||||
@@ -2004,11 +2007,20 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
return _realtimeBarSeen;
|
||||
|
||||
if (State == State.Historical)
|
||||
return Account == null;
|
||||
return IsBacktestRun();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool IsBacktestRun()
|
||||
{
|
||||
if (IsInStrategyAnalyzer)
|
||||
return true;
|
||||
|
||||
return Account != null
|
||||
&& string.Equals(Account.Name, "Backtest", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private AccountInfo BuildAccountInfo()
|
||||
{
|
||||
double cashValue = 100000.0;
|
||||
@@ -2067,7 +2079,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
|
||||
private void ProcessStrategyIntent(StrategyIntent intent, StrategyContext context)
|
||||
{
|
||||
if (State == State.Historical && Account != null)
|
||||
if (State == State.Historical && !IsBacktestRun())
|
||||
{
|
||||
LogRejectRateLimited("HistoricalReplayCatchup",
|
||||
string.Format("Blocked catch-up replay order Time={0:yyyy-MM-dd HH:mm:ss}", Time[0]),
|
||||
@@ -2076,7 +2088,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Strategy Analyzer backtests are not live catch-up replays and must execute normally.
|
||||
if (State == State.Realtime && !_realtimeBarSeen)
|
||||
{
|
||||
LogRejectRateLimited("WarmupIncomplete", "ProcessStrategyIntent blocked before first realtime bar", Time[0]);
|
||||
@@ -2086,7 +2098,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
if (!_connectionStateMonitor.TryAllowNewEntry(Time[0], LogRejectRateLimited))
|
||||
return;
|
||||
|
||||
if (_trailingDrawdownHalted || (EnableTrailingDrawdown && Account != null && TrailingDrawdownMonitor.Instance.IsHalted(Account.Name)))
|
||||
if (_trailingDrawdownHalted || (EnableTrailingDrawdown && !IsBacktestRun() && Account != null && TrailingDrawdownMonitor.Instance.IsHalted(Account.Name)))
|
||||
{
|
||||
_trailingDrawdownHalted = true;
|
||||
LogRejectRateLimited("TrailingDrawdownBreach", "Trailing drawdown halt active; new entries blocked for this session", Time[0]);
|
||||
|
||||
@@ -424,7 +424,8 @@ 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;
|
||||
// Persistence is enabled on the live transition; historical and Analyzer runs stay in-memory only.
|
||||
_strategyConfig.Parameters["daily_trade_count_persistence_enabled"] = false;
|
||||
_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");
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user