chore: checkpoint contaminated Gate 2 findings
This commit is contained in:
@@ -3,21 +3,28 @@ using System;
|
||||
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;
|
||||
using NinjaTrader.Data;
|
||||
using NinjaTrader.Gui;
|
||||
using NinjaTrader.Gui.Chart;
|
||||
using NinjaTrader.Gui.Tools;
|
||||
using NinjaTrader.NinjaScript;
|
||||
using NinjaTrader.NinjaScript.DrawingTools;
|
||||
using NinjaTrader.NinjaScript.Indicators;
|
||||
using NinjaTrader.NinjaScript.Strategies;
|
||||
using NT8.Adapters.NinjaTrader;
|
||||
using NT8.Core.Common.Interfaces;
|
||||
using NT8.Core.Common.Models;
|
||||
using NT8.Core.Execution;
|
||||
using NT8.Core.Intelligence;
|
||||
using NT8.Core.Logging;
|
||||
using NT8.Core.Risk;
|
||||
using NT8.Core.Sizing;
|
||||
using Newtonsoft.Json;
|
||||
using SdkPosition = NT8.Core.Common.Models.Position;
|
||||
using SdkOrderSide = NT8.Core.Common.Models.OrderSide;
|
||||
using SdkOrderType = NT8.Core.Common.Models.OrderType;
|
||||
@@ -60,6 +67,27 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
Disabled
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Regime gate mode for trend regime filtering
|
||||
/// </summary>
|
||||
public enum RegimeGateMode
|
||||
{
|
||||
/// <summary>
|
||||
/// No regime gating (legacy behavior)
|
||||
/// </summary>
|
||||
Disabled = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Downgrade confluence grade by 1 when trend is against trade direction
|
||||
/// </summary>
|
||||
GradePenalty = 1,
|
||||
|
||||
/// <summary>
|
||||
/// Block trade when trend is against trade direction (subsumes EnableShortTrendFilter)
|
||||
/// </summary>
|
||||
HardVeto = 2
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base class for strategies that integrate NT8 SDK components.
|
||||
/// </summary>
|
||||
@@ -94,6 +122,19 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
private System.IO.StreamWriter _fileLog;
|
||||
private readonly object _fileLock = new object();
|
||||
|
||||
// TASK-00a: Provenance Controls - session tracking
|
||||
protected string _sessionId;
|
||||
private int _tradeSequence;
|
||||
|
||||
// TASK-06c: TrendRegime Gate - RegimeManager for daily SMA trend detection
|
||||
private RegimeManager _regimeManager;
|
||||
private TrendRegimeDetector _trendDetector;
|
||||
private VolatilityRegimeDetector _volatilityDetector;
|
||||
private double _dailySmaShort;
|
||||
private double _dailySmaLong;
|
||||
private string _regimeTrend;
|
||||
private int _dailyBarCount;
|
||||
|
||||
#region User-Configurable Properties
|
||||
|
||||
[NinjaScriptProperty]
|
||||
@@ -142,9 +183,13 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
public bool EnableFileLogging { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Log Directory", GroupName = "Diagnostics", Order = 11)]
|
||||
[Display(Name = "Log Directory", GroupName = "Diagnostics", Order = 11, Description = "Directory for provenance JSON/JSONL exports. Default: C:\\NT8Logs\\Provenance")]
|
||||
public string LogDirectory { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Enable Chart Diagnostics", GroupName = "Diagnostics", Order = 12, Description = "When true, draws visual diagnostic elements on the chart for every decision.")]
|
||||
public bool EnableChartDiagnostics { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Enable Long Trades", GroupName = "Trade Direction", Order = 1)]
|
||||
public bool EnableLongTrades { get; set; }
|
||||
@@ -241,42 +286,20 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
[Range(1, 200)]
|
||||
public int ATRTrailingMaxTicks { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Runner activation mode for position management (defined locally for NinjaScript compilation)
|
||||
/// </summary>
|
||||
public enum RunnerMode
|
||||
{
|
||||
/// <summary>
|
||||
/// Automatically resolve based on quantity: Qty>=2 => Mode1DualLeg, Qty=1 => Mode2RunnerOnly
|
||||
/// </summary>
|
||||
Auto,
|
||||
|
||||
/// <summary>
|
||||
/// Dual-leg: scaler leg with fixed target + runner leg with trailing stop
|
||||
/// </summary>
|
||||
Mode1DualLeg,
|
||||
|
||||
/// <summary>
|
||||
/// Runner-only: full position on trailing stop, no fixed target
|
||||
/// </summary>
|
||||
Mode2RunnerOnly,
|
||||
|
||||
/// <summary>
|
||||
/// Scaler-only: full position with fixed target, no runner
|
||||
/// </summary>
|
||||
Mode3ScalerOnly,
|
||||
|
||||
/// <summary>
|
||||
/// Disabled: original single-leg behavior, no runner
|
||||
/// </summary>
|
||||
Disabled
|
||||
}
|
||||
// TASK-06c: TrendRegime Gate
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Regime Gate Mode", GroupName = "Regime Gate", Order = 1, Description = "Controls how trend regime affects trades: Disabled=legacy, GradePenalty=downgrade grade by 1, HardVeto=block trade when trend against direction.")]
|
||||
public RegimeGateMode RegimeGate { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "Runner Activation Mode", GroupName = "Exit Management", Order = 6, Description = "Auto: Qty>=2=Mode1, Qty=1=Mode2")]
|
||||
public RunnerMode RunnerActivationMode { get; set; }
|
||||
[Display(Name = "SMA Period Short", GroupName = "Regime Gate", Order = 2, Description = "Short SMA period for daily trend detection (default 20).")]
|
||||
[Range(5, 100)]
|
||||
public int SmaPeriodShort { get; set; }
|
||||
|
||||
[NinjaScriptProperty]
|
||||
[Display(Name = "SMA Period Long", GroupName = "Regime Gate", Order = 3, Description = "Long SMA period for daily trend detection (default 50).")]
|
||||
[Range(10, 200)]
|
||||
public int SmaPeriodLong { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -399,7 +422,7 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
BreakevenOffsetTicks = 1;
|
||||
EnableRunner = true;
|
||||
RunnerTrailTicks = 12;
|
||||
RunnerActivationMode = NT8.Core.Common.Models.RunnerMode.Auto;
|
||||
RunnerActivationMode = RunnerMode.Auto;
|
||||
EnableDynamicStop = false;
|
||||
AtrPeriod = 14;
|
||||
AtrMultiplier = 1.5;
|
||||
@@ -413,11 +436,24 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
ATRTrailingMultiplier = 2.0; // GAP-009: default 2.0 multiplier
|
||||
ATRTrailingMinTicks = 8; // GAP-009: default min 8 ticks
|
||||
ATRTrailingMaxTicks = 60; // GAP-009: default max 60 ticks
|
||||
EnableChartDiagnostics = false; // Chart diagnostics disabled by default
|
||||
_killSwitchTriggered = false;
|
||||
_connectionLost = false;
|
||||
|
||||
// TASK-00a: Generate session ID for provenance tracking
|
||||
_sessionId = System.Guid.NewGuid().ToString("N");
|
||||
_tradeSequence = 0;
|
||||
|
||||
// TASK-06c: TrendRegime Gate defaults
|
||||
RegimeGate = RegimeGateMode.GradePenalty;
|
||||
SmaPeriodShort = 20;
|
||||
SmaPeriodLong = 50;
|
||||
}
|
||||
else if (State == State.Configure)
|
||||
{
|
||||
// TASK-06c: Add daily bar series for SMA20/50 trend regime detection
|
||||
AddDataSeries(BarsPeriodType.Day, 1);
|
||||
|
||||
// Register ATR indicator series for dynamic stop calculation
|
||||
// ATR is accessed via ATR(Close, AtrPeriod)[0] in NinjaScript
|
||||
// No separate AddDataSeries needed - ATR uses the primary bar series
|
||||
@@ -466,6 +502,9 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
Print(string.Format("[SDK] ForceSessionReset: _tradeTaken cleared on live start at {0}", DateTime.Now.ToString("HH:mm:ss")));
|
||||
}
|
||||
|
||||
// TASK-00a: Write session provenance on realtime transition
|
||||
WriteSessionProvenance();
|
||||
|
||||
WriteSettingsFile();
|
||||
}
|
||||
else if (State == State.Terminated)
|
||||
@@ -616,6 +655,9 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
Close[0]));
|
||||
}
|
||||
|
||||
// Draw chart diagnostics for visual proof of every decision
|
||||
DrawDiagnostics();
|
||||
|
||||
// --- Breakeven and runner trailing monitor ---
|
||||
if (_runnerActive && !string.IsNullOrEmpty(_runnerSignalName) && Position.Quantity != 0)
|
||||
{
|
||||
@@ -971,6 +1013,12 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
timeout: TimeSpan.FromSeconds(30));
|
||||
_executionAdapter = new NT8ExecutionAdapter();
|
||||
|
||||
// TASK-06c: Initialize RegimeManager for trend regime detection
|
||||
ILogger regimeLogger = new BasicLogger(Name + "_Regime");
|
||||
_volatilityDetector = new VolatilityRegimeDetector(regimeLogger, 50);
|
||||
_trendDetector = new TrendRegimeDetector(regimeLogger);
|
||||
_regimeManager = new RegimeManager(regimeLogger, _volatilityDetector, _trendDetector, 100, 50);
|
||||
|
||||
_sdkStrategy = CreateSdkStrategy();
|
||||
if (_sdkStrategy == null)
|
||||
throw new InvalidOperationException("CreateSdkStrategy returned null");
|
||||
@@ -1011,6 +1059,50 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
// GAP-010: Pass short trend filter setting to SDK strategy
|
||||
customData.Add("EnableShortTrendFilter", EnableShortTrendFilter);
|
||||
|
||||
// TASK-06c: Regime Gate - compute daily SMA20/50 trend from daily series (BarsArray[1])
|
||||
if (RegimeGate != RegimeGateMode.Disabled && BarsArray != null && BarsArray.Length > 1
|
||||
&& CurrentBars != null && CurrentBars.Length > 1 && CurrentBars[1] >= SmaPeriodLong)
|
||||
{
|
||||
double sumShort = 0.0;
|
||||
double sumLong = 0.0;
|
||||
int dailyIndex = 1; // BarsArray[1] is daily series
|
||||
for (int i = 0; i < SmaPeriodShort; i++)
|
||||
{
|
||||
sumShort += Closes[dailyIndex][i];
|
||||
}
|
||||
for (int i = 0; i < SmaPeriodLong; i++)
|
||||
{
|
||||
sumLong += Closes[dailyIndex][i];
|
||||
}
|
||||
_dailySmaShort = sumShort / SmaPeriodShort;
|
||||
_dailySmaLong = sumLong / SmaPeriodLong;
|
||||
|
||||
if (_dailySmaShort > _dailySmaLong)
|
||||
_regimeTrend = "Bullish";
|
||||
else if (_dailySmaShort < _dailySmaLong)
|
||||
_regimeTrend = "Bearish";
|
||||
else
|
||||
_regimeTrend = "Neutral";
|
||||
|
||||
_dailyBarCount = CurrentBars[1] + 1;
|
||||
|
||||
customData.Add("regime_trend", _regimeTrend);
|
||||
customData.Add("regime_sma20", _dailySmaShort);
|
||||
customData.Add("regime_sma50", _dailySmaLong);
|
||||
customData.Add("regime_gate_mode", (int)RegimeGate);
|
||||
customData.Add("regime_sma_period_short", SmaPeriodShort);
|
||||
customData.Add("regime_sma_period_long", SmaPeriodLong);
|
||||
}
|
||||
else
|
||||
{
|
||||
customData.Add("regime_trend", "Neutral");
|
||||
customData.Add("regime_sma20", 0.0);
|
||||
customData.Add("regime_sma50", 0.0);
|
||||
customData.Add("regime_gate_mode", (int)RegimeGateMode.Disabled);
|
||||
customData.Add("regime_sma_period_short", SmaPeriodShort);
|
||||
customData.Add("regime_sma_period_long", SmaPeriodLong);
|
||||
}
|
||||
|
||||
return NT8DataConverter.ConvertContext(
|
||||
Instrument.MasterInstrument.Name,
|
||||
Time[0],
|
||||
@@ -1083,6 +1175,9 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
if (State == State.Realtime && !_realtimeBarSeen)
|
||||
return;
|
||||
|
||||
if (EnableFileLogging && State == State.Realtime)
|
||||
FileLog(string.Format("SIGNAL: {0} {1} | {2}", intent.Side, intent.Symbol, GetTestModeBanner()));
|
||||
|
||||
// Portfolio-level risk check — runs before per-strategy risk validation
|
||||
var portfolioDecision = PortfolioRiskManager.Instance.ValidatePortfolioRisk(Name, intent);
|
||||
if (!portfolioDecision.Allow)
|
||||
@@ -1330,6 +1425,15 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
|
||||
if (_circuitBreaker != null)
|
||||
_circuitBreaker.OnSuccess();
|
||||
|
||||
// TASK-00a: Write trade provenance
|
||||
double atrStopTicks = 0.0;
|
||||
if (EnableDynamicStop && CurrentBars[0] >= AtrPeriod)
|
||||
{
|
||||
double atrValue = ATR(Close, AtrPeriod)[0];
|
||||
atrStopTicks = System.Math.Round(atrValue / TickSize * AtrMultiplier);
|
||||
}
|
||||
WriteTradeProvenance(intent, request.Quantity, atrStopTicks);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -1401,6 +1505,38 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
lines.Add(string.Format("MinTradeGrade : {0}", MinTradeGrade));
|
||||
lines.Add(string.Format("EnableFileLogging : {0}", EnableFileLogging));
|
||||
lines.Add(string.Format("LogDirectory : {0}", string.IsNullOrEmpty(LogDirectory) ? "(default)" : LogDirectory));
|
||||
lines.Add("--- July 11 Sprint 2 Params ---");
|
||||
lines.Add(string.Format("RunnerActivationMode: {0}", RunnerActivationMode.ToString()));
|
||||
lines.Add(string.Format("EnableDynamicStop : {0}", EnableDynamicStop));
|
||||
lines.Add(string.Format("AtrMultiplier : {0:F2}", AtrMultiplier));
|
||||
lines.Add(string.Format("EnableShortTrendFilter: {0}", EnableShortTrendFilter));
|
||||
lines.Add(string.Format("EnableATRTrailing : {0}", EnableATRTrailing));
|
||||
lines.Add(string.Format("ATRTrailingMultiplier: {0:F2}", ATRTrailingMultiplier));
|
||||
lines.Add(string.Format("EnableCMEHolidayGuard: {0}", EnableCMEHolidayGuard));
|
||||
lines.Add(string.Format("EnableBarBasedRearm : {0}", EnableBarBasedRearm));
|
||||
|
||||
// TestMode and ForceSessionReset from strategy config
|
||||
bool testMode = false;
|
||||
if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode"))
|
||||
{
|
||||
var tm = _strategyConfig.Parameters["TestMode"];
|
||||
if (tm is bool)
|
||||
testMode = (bool)tm;
|
||||
}
|
||||
lines.Add(string.Format("TestMode : {0}", testMode));
|
||||
|
||||
bool forceSessionReset = false;
|
||||
if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("ForceSessionReset"))
|
||||
{
|
||||
var fsr = _strategyConfig.Parameters["ForceSessionReset"];
|
||||
if (fsr is bool)
|
||||
forceSessionReset = (bool)fsr;
|
||||
}
|
||||
lines.Add(string.Format("ForceSessionReset : {0}", forceSessionReset));
|
||||
|
||||
lines.Add(string.Format("ConfigHash : {0}", ComputeConfigHash()));
|
||||
lines.Add(string.Format("CodeVersion : {0}", GetCodeVersionStamp()));
|
||||
|
||||
lines.Add("--- Portfolio ---");
|
||||
lines.Add(string.Format("PortfolioStatus : {0}", PortfolioRiskManager.Instance.GetStatusSnapshot()));
|
||||
lines.Add("=== END SETTINGS ===");
|
||||
@@ -1444,5 +1580,339 @@ namespace NinjaTrader.NinjaScript.Strategies
|
||||
Print(string.Format("[NT8-SDK] WARNING: Could not write settings file: {0}", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Draws visual diagnostic elements on the chart to provide visual proof of every decision.
|
||||
/// Override in derived classes to add strategy-specific diagnostic elements.
|
||||
/// Called from OnBarUpdate when EnableChartDiagnostics is true.
|
||||
/// </summary>
|
||||
protected virtual void DrawDiagnostics()
|
||||
{
|
||||
if (!EnableChartDiagnostics)
|
||||
return;
|
||||
|
||||
// 1. Regime Indicator - AVWAP slope banner in top-left
|
||||
if (_currentSession != null && _strategyConfig != null && _strategyConfig.Parameters != null)
|
||||
{
|
||||
if (_strategyConfig.Parameters.ContainsKey("avwap_slope"))
|
||||
{
|
||||
var slope = _strategyConfig.Parameters["avwap_slope"];
|
||||
if (slope is double)
|
||||
{
|
||||
double slopeVal = (double)slope;
|
||||
string regimeText = slopeVal > 0 ? "REGIME: BULLISH" : "REGIME: BEARISH";
|
||||
Brush regimeBrush = slopeVal > 0 ? Brushes.LimeGreen : Brushes.Red;
|
||||
Draw.TextFixed(this, "Diag_Regime", regimeText, TextPosition.TopLeft, regimeBrush, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Session Tag - RTH/ETH tag in top-right
|
||||
if (_currentSession != null)
|
||||
{
|
||||
string sessionTag = _currentSession.IsRth ? "SESSION: RTH" : "SESSION: ETH";
|
||||
Brush sessionBrush = _currentSession.IsRth ? Brushes.DodgerBlue : Brushes.Orange;
|
||||
Draw.TextFixed(this, "Diag_Session", sessionTag, TextPosition.TopRight, sessionBrush, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100);
|
||||
}
|
||||
|
||||
// 3. Runner Mode Label - shows current runner mode
|
||||
if (EnableRunner)
|
||||
{
|
||||
string runnerText = "RUNNER: " + RunnerActivationMode.ToString();
|
||||
Draw.TextFixed(this, "Diag_Runner", runnerText, TextPosition.TopLeft, Brushes.Yellow, new SimpleFont("Arial", 10), Brushes.Transparent, Brushes.Transparent, 100);
|
||||
}
|
||||
|
||||
// 4. TestMode Banner - prominent when TestMode is active
|
||||
bool testMode = false;
|
||||
if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode"))
|
||||
{
|
||||
var tm = _strategyConfig.Parameters["TestMode"];
|
||||
if (tm is bool)
|
||||
testMode = (bool)tm;
|
||||
}
|
||||
if (testMode)
|
||||
{
|
||||
Draw.TextFixed(this, "Diag_TestMode", "TEST MODE ACTIVE", TextPosition.Center, Brushes.White, new SimpleFont("Arial", 14), Brushes.Red, Brushes.Red, 100);
|
||||
}
|
||||
|
||||
// 5. ATR Stop Line - current dynamic stop level
|
||||
if (EnableDynamicStop && CurrentBars[0] >= AtrPeriod)
|
||||
{
|
||||
double atrValue = ATR(Close, AtrPeriod)[0];
|
||||
int dynStop = (int)System.Math.Round(atrValue / TickSize * AtrMultiplier);
|
||||
dynStop = System.Math.Max(MinStopTicks, System.Math.Min(MaxStopTicks, dynStop));
|
||||
double stopPrice = Position.MarketPosition == MarketPosition.Long
|
||||
? Position.AveragePrice - (dynStop * TickSize)
|
||||
: Position.AveragePrice + (dynStop * TickSize);
|
||||
Draw.Line(this, "Diag_ATRStop", false, CurrentBar - 1, stopPrice, CurrentBar, stopPrice, Brushes.Cyan, DashStyleHelper.Dash, 2);
|
||||
}
|
||||
|
||||
// 6. Breakeven Level - visual line when breakeven is triggered
|
||||
if (EnableAutoBreakeven && _breakevenMoved && !string.IsNullOrEmpty(_runnerSignalName))
|
||||
{
|
||||
double bePrice = Position.MarketPosition == MarketPosition.Long
|
||||
? Position.AveragePrice + (BreakevenOffsetTicks * TickSize)
|
||||
: Position.AveragePrice - (BreakevenOffsetTicks * TickSize);
|
||||
Draw.Line(this, "Diag_Breakeven", false, CurrentBar - 1, bePrice, CurrentBar, bePrice, Brushes.LimeGreen, DashStyleHelper.Dot, 2);
|
||||
}
|
||||
|
||||
// 7. Provenance Link - subtle text with settings file reference
|
||||
Draw.TextFixed(this, "Diag_Prov", "Prov: settings_" + Name.Replace(" ", "_") + "_" + DateTime.Now.ToString("yyyyMMdd"), TextPosition.BottomRight, Brushes.Gray, new SimpleFont("Arial", 8), Brushes.Transparent, Brushes.Transparent, 50);
|
||||
}
|
||||
|
||||
#region TASK-00a: Provenance Controls
|
||||
|
||||
/// <summary>
|
||||
/// Generates a SHA256 hash of all NinjaScriptProperty values for configuration provenance.
|
||||
/// </summary>
|
||||
protected string ComputeConfigHash()
|
||||
{
|
||||
var props = new List<string>();
|
||||
var propsList = this.GetType().GetProperties();
|
||||
foreach (var prop in propsList)
|
||||
{
|
||||
var attr = prop.GetCustomAttributes(typeof(NinjaScriptPropertyAttribute), true);
|
||||
if (attr.Length > 0)
|
||||
{
|
||||
var val = prop.GetValue(this, null);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Identifies the compiled strategy assembly so a mid-gate redeploy is detectable
|
||||
/// even when the NinjaScript parameter hash is unchanged.
|
||||
/// </summary>
|
||||
protected virtual string GetCodeVersionStamp()
|
||||
{
|
||||
try
|
||||
{
|
||||
var assembly = GetType().Assembly;
|
||||
string version = assembly.GetName().Version != null
|
||||
? assembly.GetName().Version.ToString()
|
||||
: "unknown";
|
||||
return version + ":" + assembly.ManifestModule.ModuleVersionId.ToString("N");
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes session provenance JSON file at session start and realtime transition.
|
||||
/// </summary>
|
||||
protected virtual void WriteSessionProvenance()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(LogDirectory))
|
||||
return;
|
||||
|
||||
if (_sessionId == null)
|
||||
_sessionId = Guid.NewGuid().ToString();
|
||||
|
||||
var dir = LogDirectory;
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
var provenance = new Dictionary<string, object>
|
||||
{
|
||||
{ "session_id", _sessionId },
|
||||
{ "strategy_name", Name },
|
||||
{ "timestamp_utc", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") },
|
||||
{ "nt8_version", "NinjaTrader 8" },
|
||||
{ "sdk_version", "6.1" },
|
||||
{ "config_hash", ComputeConfigHash() },
|
||||
{ "code_version", GetCodeVersionStamp() },
|
||||
{ "ninjascript_properties", GetNinjaScriptProperties() },
|
||||
{ "sdk_parameters", GetSdkParameters() },
|
||||
{ "july_11_params", GetJuly11Params() },
|
||||
{ "test_mode_banner", GetTestModeBanner() },
|
||||
{ "session_tag", GetSessionTag() }
|
||||
};
|
||||
|
||||
var safeName = Name.Replace(" ", "_").Replace("/", "_").Replace("\\", "_");
|
||||
var path = Path.Combine(dir, string.Format("provenance_{0}_{1}.json", safeName, DateTime.Now.ToString("yyyyMMdd_HHmmss")));
|
||||
var json = JsonConvert.SerializeObject(provenance, Formatting.Indented);
|
||||
File.WriteAllText(path, json);
|
||||
Print(string.Format("[NT8-SDK] Session provenance exported: {0}", path));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Print(string.Format("[NT8-SDK] WARNING: Could not write session provenance: {0}", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes trade provenance JSONL line for each trade.
|
||||
/// </summary>
|
||||
protected virtual void WriteTradeProvenance(StrategyIntent intent, int quantity, double atrStopTicks)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(LogDirectory))
|
||||
return;
|
||||
|
||||
if (_sessionId == null)
|
||||
_sessionId = Guid.NewGuid().ToString();
|
||||
|
||||
_tradeSequence++;
|
||||
|
||||
var dir = LogDirectory;
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
var trade = new Dictionary<string, object>
|
||||
{
|
||||
{ "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);
|
||||
File.AppendAllText(path, json + Environment.NewLine);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Print(string.Format("[NT8-SDK] WARNING: Could not write trade provenance: {0}", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
protected Dictionary<string, object> GetNinjaScriptProperties()
|
||||
{
|
||||
var dict = new Dictionary<string, object>();
|
||||
var props = this.GetType().GetProperties();
|
||||
foreach (var prop in props)
|
||||
{
|
||||
var attr = prop.GetCustomAttributes(typeof(NinjaScriptPropertyAttribute), true);
|
||||
if (attr.Length > 0)
|
||||
{
|
||||
var val = prop.GetValue(this, null);
|
||||
dict[prop.Name] = val;
|
||||
}
|
||||
}
|
||||
return dict;
|
||||
}
|
||||
|
||||
protected Dictionary<string, object> GetSdkParameters()
|
||||
{
|
||||
var dict = new Dictionary<string, object>();
|
||||
if (_strategyConfig != null && _strategyConfig.Parameters != null)
|
||||
{
|
||||
foreach (var kvp in _strategyConfig.Parameters)
|
||||
dict[kvp.Key] = kvp.Value;
|
||||
}
|
||||
return dict;
|
||||
}
|
||||
|
||||
protected Dictionary<string, object> GetJuly11Params()
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
{ "RunnerActivationMode", RunnerActivationMode.ToString() },
|
||||
{ "EnableDynamicStop", EnableDynamicStop },
|
||||
{ "AtrMultiplier", AtrMultiplier },
|
||||
{ "EnableShortTrendFilter", EnableShortTrendFilter },
|
||||
{ "EnableATRTrailing", EnableATRTrailing },
|
||||
{ "ATRTrailingMultiplier", ATRTrailingMultiplier },
|
||||
{ "EnableCMEHolidayGuard", EnableCMEHolidayGuard },
|
||||
{ "EnableBarBasedRearm", EnableBarBasedRearm }
|
||||
};
|
||||
}
|
||||
|
||||
protected string GetTestModeBanner()
|
||||
{
|
||||
bool testMode = false;
|
||||
if (_strategyConfig != null && _strategyConfig.Parameters != null && _strategyConfig.Parameters.ContainsKey("TestMode"))
|
||||
{
|
||||
var tm = _strategyConfig.Parameters["TestMode"];
|
||||
if (tm is bool)
|
||||
testMode = (bool)tm;
|
||||
}
|
||||
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"))
|
||||
{
|
||||
var mode = _strategyConfig.Parameters["risk_mode"];
|
||||
if (mode != null) return mode.ToString();
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
private double GetDailyPnL()
|
||||
{
|
||||
if (_lastAccountInfo != null)
|
||||
return _lastAccountInfo.DailyPnL;
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
protected virtual string GetSessionTag()
|
||||
{
|
||||
if (_currentSession != null)
|
||||
{
|
||||
if (NT8.Core.Calendar.CmeHolidayCalendar.IsHoliday(Time[0].Date))
|
||||
return "HOLIDAY";
|
||||
if (NT8.Core.Calendar.CmeHolidayCalendar.IsEarlyClose(Time[0].Date))
|
||||
return "EARLY_CLOSE";
|
||||
return _currentSession.IsRth ? "RTH_ORB" : "ETH";
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user