fix: apply GAP-035 GAP-036 GAP-038 GAP-039 runtime remediations
This commit is contained in:
@@ -4,7 +4,6 @@ using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Windows.Media;
|
||||
using NinjaTrader.Cbi;
|
||||
@@ -16,6 +15,7 @@ using NinjaTrader.NinjaScript;
|
||||
using NinjaTrader.NinjaScript.DrawingTools;
|
||||
using NinjaTrader.NinjaScript.Indicators;
|
||||
using NinjaTrader.NinjaScript.Strategies;
|
||||
using NT8.Adapters;
|
||||
using NT8.Adapters.NinjaTrader;
|
||||
using NT8.Core.Common.Interfaces;
|
||||
using NT8.Core.Common.Models;
|
||||
@@ -121,6 +121,8 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
private ExecutionCircuitBreaker _circuitBreaker;
|
||||
private System.IO.StreamWriter _fileLog;
|
||||
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
|
||||
protected string _sessionId;
|
||||
@@ -396,6 +398,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
|
||||
OrderFillResolution = OrderFillResolution.Standard;
|
||||
Slippage = 0;
|
||||
// AdoptAccountPosition avoids NT8 start-up synchronization submitting or flattening during historical replay bursts before the first live bar.
|
||||
StartBehavior = StartBehavior.AdoptAccountPosition;
|
||||
TimeInForce = TimeInForce.Gtc;
|
||||
TraceOrders = false;
|
||||
@@ -521,7 +524,10 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
// Secondary series (e.g. daily bars for confluence) trigger OnBarUpdate separately
|
||||
// and must never generate strategy signals.
|
||||
if (BarsInProgress != 0)
|
||||
{
|
||||
LogRejectRateLimited("WarmupIncomplete", string.Format("BarsInProgress={0}; primary series only", BarsInProgress), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
// REPLAY BURST GUARD: Block all signal generation during the catch-up bar
|
||||
// replay that NT8 fires on strategy enable with AdoptAccountPosition.
|
||||
@@ -535,7 +541,10 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
{
|
||||
double ageSeconds = (DateTime.Now - Time[0]).TotalSeconds;
|
||||
if (ageSeconds > 300)
|
||||
{
|
||||
LogRejectRateLimited("WarmupIncomplete", string.Format("Replay burst guard ageSeconds={0:F0}", ageSeconds), Time[0]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// NR7 warm-up advisory — log when daily series has fewer than 7 bars,
|
||||
@@ -558,21 +567,27 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
{
|
||||
if (EnableVerboseLogging)
|
||||
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;
|
||||
}
|
||||
|
||||
if (!_sdkInitialized || _sdkStrategy == null)
|
||||
{
|
||||
LogRejectRateLimited("WarmupIncomplete", string.Format("SdkInitialized={0} StrategyNull={1}", _sdkInitialized, _sdkStrategy == null), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (CurrentBar < BarsRequiredToTrade)
|
||||
{
|
||||
LogRejectRateLimited("WarmupIncomplete", string.Format("CurrentBar={0} BarsRequiredToTrade={1}", CurrentBar, BarsRequiredToTrade), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Time[0] == _lastBarTime)
|
||||
{
|
||||
LogRejectRateLimited("WarmupIncomplete", string.Format("Duplicate bar time={0:yyyy-MM-dd HH:mm:ss}", Time[0]), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Time[0].Date != _lastBarTime.Date && _lastBarTime != DateTime.MinValue)
|
||||
{
|
||||
@@ -590,6 +605,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
{
|
||||
_realtimeBarSeen = true;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -613,6 +629,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
Print(string.Format("[SDK] Kill switch flatten error: {0}", ex.Message));
|
||||
}
|
||||
}
|
||||
LogRejectRateLimited("KillSwitch", string.Format("EnableKillSwitch=True KillSwitchTriggered={0}", _killSwitchTriggered), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -621,6 +638,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -641,6 +659,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
if (EnableVerboseLogging && CurrentBar % 500 == 0)
|
||||
Print(string.Format("[SDK] Skipping ETH bar {0} at {1:HH:mm}",
|
||||
CurrentBar, Time[0]));
|
||||
LogRejectRateLimited("RthGuard", string.Format("Time={0:HH:mm:ss} TestMode={1}", Time[0], isTestMode), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -719,6 +738,10 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
Print(string.Format("[SDK] Intent generated: {0} {1} @ {2}", intent.Side, intent.Symbol, intent.EntryType));
|
||||
ProcessStrategyIntent(intent, context);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogSignalRejectionFromContext(context);
|
||||
}
|
||||
}
|
||||
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()
|
||||
{
|
||||
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("Strategy : {0}", Name));
|
||||
@@ -988,6 +1073,21 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
daysToLoad,
|
||||
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)
|
||||
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()
|
||||
{
|
||||
FileLog("---");
|
||||
WriteRejectSummary();
|
||||
FileLog("=== SESSION END " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ===");
|
||||
|
||||
if (_fileLog != null)
|
||||
@@ -1114,6 +1228,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
customData.Add("CurrentBar", CurrentBar);
|
||||
customData.Add("BarsRequiredToTrade", BarsRequiredToTrade);
|
||||
customData.Add("OrdersToday", _ordersSubmittedToday);
|
||||
customData.Add("AllowDailyTradeCountIncrement", ShouldAllowDailyTradeCountIncrement());
|
||||
// GAP-010: Pass short trend filter setting to SDK strategy
|
||||
customData.Add("EnableShortTrendFilter", EnableShortTrendFilter);
|
||||
|
||||
@@ -1170,6 +1285,17 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
customData);
|
||||
}
|
||||
|
||||
private bool ShouldAllowDailyTradeCountIncrement()
|
||||
{
|
||||
if (State == State.Realtime)
|
||||
return _realtimeBarSeen;
|
||||
|
||||
if (State == State.Historical)
|
||||
return Account == null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private AccountInfo BuildAccountInfo()
|
||||
{
|
||||
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 Strategy Analyzer (State.Historical): always allow — backtest must execute normally.
|
||||
if (State == State.Realtime && !_realtimeBarSeen)
|
||||
{
|
||||
LogRejectRateLimited("WarmupIncomplete", "ProcessStrategyIntent blocked before first realtime bar", Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (EnableFileLogging && State == State.Realtime)
|
||||
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));
|
||||
if (_logger != null)
|
||||
_logger.LogWarning("Portfolio risk blocked order: {0}", portfolioDecision.RejectReason);
|
||||
LogRejectRateLimited("KillSwitch", string.Format("Portfolio blocked: {0}", portfolioDecision.RejectReason), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1251,12 +1381,14 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
{
|
||||
if (EnableVerboseLogging)
|
||||
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;
|
||||
}
|
||||
if (intent.Side == SdkOrderSide.Sell && !EnableShortTrades)
|
||||
{
|
||||
if (EnableVerboseLogging)
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1270,6 +1402,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason));
|
||||
if (_logger != null)
|
||||
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
|
||||
LogRejectRateLimited("KillSwitch", string.Format("Risk manager rejected: {0}", riskDecision.RejectReason), Time[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1289,6 +1422,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
{
|
||||
if (EnableVerboseLogging)
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1323,6 +1457,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
Print(String.Format("[SDK] Circuit breaker OPEN — order blocked: {0}", cbState.Reason));
|
||||
if (_logger != null)
|
||||
_logger.LogWarning("Circuit breaker blocked order: {0}", cbState.Reason);
|
||||
LogRejectRateLimited("KillSwitch", string.Format("Circuit breaker open: {0}", cbState.Reason), Time[0]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1721,7 +1856,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
#region TASK-00a: Provenance Controls
|
||||
|
||||
/// <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>
|
||||
protected string ComputeConfigHash()
|
||||
{
|
||||
@@ -1736,16 +1871,33 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
props.Add(prop.Name + "=" + (val != null ? val.ToString() : "null"));
|
||||
}
|
||||
}
|
||||
var combined = string.Join("|", props);
|
||||
using (var sha = SHA256.Create())
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(combined);
|
||||
var hash = sha.ComputeHash(bytes);
|
||||
var sb = new StringBuilder();
|
||||
foreach (var b in hash)
|
||||
sb.Append(b.ToString("x2"));
|
||||
return sb.ToString();
|
||||
}
|
||||
AddSettingsExportHashInputs(props);
|
||||
return ConfigHashCalculator.Compute(props);
|
||||
}
|
||||
|
||||
protected virtual void AddSettingsExportHashInputs(List<string> props)
|
||||
{
|
||||
if (props == null)
|
||||
throw new ArgumentNullException("props");
|
||||
|
||||
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>
|
||||
@@ -1840,7 +1992,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
quantity,
|
||||
atrStopTicks,
|
||||
resolvedMode.ToString(),
|
||||
GetRiskMode(),
|
||||
GetRiskMode(intent),
|
||||
GetDailyPnL(),
|
||||
GetSessionTag(),
|
||||
GetCodeVersionStamp());
|
||||
@@ -1916,6 +2068,18 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
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()
|
||||
{
|
||||
if (_lastAccountInfo != null)
|
||||
|
||||
Reference in New Issue
Block a user