Files
nt8-sdk/src/NT8.Adapters/Strategies/NT8StrategyBase.cs

3024 lines
131 KiB
C#

// File: NT8StrategyBase.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
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;
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;
using OmsOrderRequest = NT8.Core.OMS.OrderRequest;
using OmsOrderSide = NT8.Core.OMS.OrderSide;
using OmsOrderType = NT8.Core.OMS.OrderType;
using OmsOrderState = NT8.Core.OMS.OrderState;
using OmsOrderStatus = NT8.Core.OMS.OrderStatus;
namespace NinjaTrader.NinjaScript.Strategies
{
/// <summary>
/// Runner activation mode for position management
/// </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
}
/// <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>
/// Manual risk posture tier. This is an operator setting only; code never changes it automatically.
/// </summary>
public enum RiskTier
{
/// <summary>
/// Lowest risk posture; drawdown breaches persist across restarts until the operator removes the halt file.
/// </summary>
Conservative,
/// <summary>
/// Default risk posture; drawdown breaches are in-memory only.
/// </summary>
Normal,
/// <summary>
/// Highest risk posture; drawdown breaches are in-memory only.
/// </summary>
Aggressive
}
/// <summary>
/// Base class for strategies that integrate NT8 SDK components.
/// </summary>
public abstract class NT8StrategyBase : Strategy, INT8ExecutionBridge
{
private readonly object _lock = new object();
protected IStrategy _sdkStrategy;
protected IRiskManager _riskManager;
protected IPositionSizer _positionSizer;
protected NT8ExecutionAdapter _executionAdapter;
protected ILogger _logger;
protected StrategyConfig _strategyConfig;
protected RiskConfig _riskConfig;
protected SizingConfig _sizingConfig;
private bool _sdkInitialized;
private AccountInfo _lastAccountInfo;
private SdkPosition _lastPosition;
private MarketSession _currentSession;
private int _ordersSubmittedToday;
private DateTime _lastBarTime;
private bool _killSwitchTriggered;
private readonly ConnectionStateMonitor _connectionStateMonitor = new ConnectionStateMonitor();
private bool _realtimeBarSeen;
private bool _breakevenMoved;
private string _scalerSignalName;
private string _runnerSignalName;
private bool _runnerActive;
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>();
private const int REJECT_SUMMARY_SNAPSHOT_INTERVAL_MINUTES = 15;
private const int STATE_TELEMETRY_INTERVAL_SECONDS = 30;
private DateTime _lastRejectSummarySnapshotTime = DateTime.MinValue;
private DateTime _lastStateTelemetryTime = DateTime.MinValue;
private bool _stateTelemetryChangeInitialized;
private int _lastStateTelemetryPendingBreakoutDirection;
private bool _lastStateTelemetryGradeMeetsThreshold;
private bool _orbRejectSummarySnapshotWritten;
private DateTime _rejectSummarySnapshotTradingDate = DateTime.MinValue;
private bool _microUpgradeSuggested;
private bool _microUpgradePersistenceLoaded;
private bool _trailingDrawdownHalted;
private string _trailingDrawdownAccountName;
// 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]
[Display(Name = "Enable SDK", GroupName = "SDK", Order = 1)]
public bool EnableSDK { get; set; }
[NinjaScriptProperty]
[Display(Name = "Daily Loss Limit", GroupName = "Risk", Order = 1)]
public double DailyLossLimit { get; set; }
[NinjaScriptProperty]
[Display(Name = "Max Trade Risk", GroupName = "Risk", Order = 2)]
public double MaxTradeRisk { get; set; }
[NinjaScriptProperty]
[Display(Name = "Max Positions", GroupName = "Risk", Order = 3)]
public int MaxOpenPositions { get; set; }
[NinjaScriptProperty]
[Display(Name = "Risk Tier", GroupName = "Risk Tier", Order = 1, Description = "Manual operator risk posture. This is never changed automatically by the strategy.")]
public RiskTier RiskTier { get; set; }
[NinjaScriptProperty]
[Display(Name = "Micro Upgrade Threshold", GroupName = "Risk Tier", Order = 2, Description = "Informational balance threshold. Crossing it logs a one-time suggestion only; RiskTier is not changed automatically.")]
public double MicroUpgradeThreshold { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable Trailing Drawdown", GroupName = "Trailing Drawdown", Order = 1, Description = "Opt-in account-scoped realtime trailing drawdown halt monitor.")]
public bool EnableTrailingDrawdown { get; set; }
[NinjaScriptProperty]
[Display(Name = "Account Starting Balance", GroupName = "Trailing Drawdown", Order = 2, Description = "Explicit account starting balance from funded activation; required when trailing drawdown is enabled.")]
public double AccountStartingBalance { get; set; }
[NinjaScriptProperty]
[Display(Name = "Trailing Drawdown Amount", GroupName = "Trailing Drawdown", Order = 3, Description = "Real account trailing drawdown amount. Informational for this monitor; halt uses the configured halt buffer.")]
public double TrailingDrawdownAmount { get; set; }
[NinjaScriptProperty]
[Display(Name = "Trailing Drawdown Halt Buffer", GroupName = "Trailing Drawdown", Order = 4, Description = "Halt distance below active peak/locked value. Defaults to 2000 to halt before a 2500 trail is reached.")]
public double TrailingDrawdownHaltBuffer { get; set; }
[NinjaScriptProperty]
[Display(Name = "Trailing Drawdown Lock Offset", GroupName = "Trailing Drawdown", Order = 5, Description = "Lock-in offset above starting balance. Default 100 matches Bulenox; other firms may need different values.")]
public double TrailingDrawdownLockOffset { get; set; }
[NinjaScriptProperty]
[Display(Name = "Risk Per Trade", GroupName = "Sizing", Order = 1)]
public double RiskPerTrade { get; set; }
[NinjaScriptProperty]
[Display(Name = "Min Contracts", GroupName = "Sizing", Order = 2)]
public int MinContracts { get; set; }
[NinjaScriptProperty]
[Display(Name = "Max Contracts", GroupName = "Sizing", Order = 3)]
public int MaxContracts { get; set; }
[NinjaScriptProperty]
[Display(Name = "Kill Switch (Flatten + Stop)", GroupName = "Emergency Controls", Order = 1)]
public bool EnableKillSwitch { get; set; }
[NinjaScriptProperty]
[Display(Name = "Verbose Logging", GroupName = "Debug", Order = 1)]
public bool EnableVerboseLogging { get; set; }
[NinjaScriptProperty]
[Display(Name = "Min Trade Grade (1=F,2=D,3=C,4=B,5=A,6=A+)", GroupName = "Confluence", Order = 1)]
[Range(0, 6)]
public int MinTradeGrade { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable File Logging", GroupName = "Diagnostics", Order = 10)]
public bool EnableFileLogging { get; set; }
[NinjaScriptProperty]
[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 State Telemetry", GroupName = "Diagnostics", Order = 13, Description = "When true, emits throttled realtime confluence and regime telemetry to the session log.")]
public bool EnableStateTelemetry { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable ETH Telemetry", GroupName = "Diagnostics", Order = 14, Description = "When true, emits read-only state telemetry outside RTH without running signal generation.")]
public bool EnableEthTelemetry { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable Long Trades", GroupName = "Trade Direction", Order = 1)]
public bool EnableLongTrades { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable Short Trades", GroupName = "Trade Direction", Order = 2)]
public bool EnableShortTrades { get; set; }
[NinjaScriptProperty]
[Browsable(false)]
[Display(Name = "Enable Auto Breakeven", GroupName = "Exit Management", Order = 1, Description = "Currently unused; retained for saved workspace compatibility.")]
public bool EnableAutoBreakeven { get; set; }
[NinjaScriptProperty]
[Browsable(false)]
[Display(Name = "Breakeven Trigger Ticks", GroupName = "Exit Management", Order = 2, Description = "Currently unused; retained for saved workspace compatibility.")]
[Range(1, 100)]
public int BreakevenTriggerTicks { get; set; }
[NinjaScriptProperty]
[Browsable(false)]
[Display(Name = "Breakeven Offset Ticks", GroupName = "Exit Management", Order = 3, Description = "Currently unused; retained for saved workspace compatibility.")]
[Range(0, 20)]
public int BreakevenOffsetTicks { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable Runner", GroupName = "Exit Management", Order = 4)]
public bool EnableRunner { get; set; }
[NinjaScriptProperty]
[Display(Name = "Runner Trail Ticks", GroupName = "Exit Management", Order = 5)]
[Range(4, 50)]
public int RunnerTrailTicks { 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; }
[NinjaScriptProperty]
[Display(Name = "Enable Dynamic ATR Stop", GroupName = "Exit Management", Order = 7)]
public bool EnableDynamicStop { get; set; }
[NinjaScriptProperty]
[Display(Name = "ATR Period", GroupName = "Exit Management", Order = 8)]
[Range(2, 50)]
public int AtrPeriod { get; set; }
[NinjaScriptProperty]
[Display(Name = "ATR Multiplier", GroupName = "Exit Management", Order = 9)]
[Range(0.1, 5.0)]
public double AtrMultiplier { get; set; }
[NinjaScriptProperty]
[Display(Name = "Min Stop Ticks", GroupName = "Exit Management", Order = 10)]
[Range(1, 100)]
public int MinStopTicks { get; set; }
[NinjaScriptProperty]
[Display(Name = "Max Stop Ticks", GroupName = "Exit Management", Order = 11)]
[Range(1, 200)]
public int MaxStopTicks { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable Bar-Based Re-arm (SIM only)", GroupName = "Exit Management", Order = 12, Description = "Enable legacy bar-driven _tradeTaken re-arm. Default false — position-close re-arm is now primary.")]
public bool EnableBarBasedRearm { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable Short Trend Filter", GroupName = "Trade Management", Order = 13, Description = "When true, short trades are vetoed if AVWAP slope > 0 (bullish regime).")]
public bool EnableShortTrendFilter { get; set; }
[NinjaScriptProperty]
[Display(Name = "Enable CME Holiday Guard", GroupName = "Trade Management", Order = 14, Description = "When true, strategy skips ORB window on CME holidays (New Year, MLK, Presidents, Good Friday, Memorial, July 4, Labor, Thanksgiving, Christmas).")]
public bool EnableCMEHolidayGuard { get; set; }
// GAP-009: ATR-based trailing stop
[NinjaScriptProperty]
[Display(Name = "Enable ATR Trailing", GroupName = "Exit Management", Order = 15, Description = "When true, runner trailing stop uses ATR instead of fixed RunnerTrailTicks.")]
public bool EnableATRTrailing { get; set; }
[NinjaScriptProperty]
[Display(Name = "ATR Trailing Period", GroupName = "Exit Management", Order = 16, Description = "ATR period for trailing stop calculation.")]
[Range(2, 50)]
public int ATRTrailingPeriod { get; set; }
[NinjaScriptProperty]
[Display(Name = "ATR Trailing Multiplier", GroupName = "Exit Management", Order = 17, Description = "Multiplier applied to ATR value for trail distance.")]
[Range(0.1, 5.0)]
public double ATRTrailingMultiplier { get; set; }
[NinjaScriptProperty]
[Display(Name = "ATR Trailing Min Ticks", GroupName = "Exit Management", Order = 18, Description = "Minimum trail distance in ticks.")]
[Range(1, 100)]
public int ATRTrailingMinTicks { get; set; }
[NinjaScriptProperty]
[Display(Name = "ATR Trailing Max Ticks", GroupName = "Exit Management", Order = 19, Description = "Maximum trail distance in ticks.")]
[Range(1, 200)]
public int ATRTrailingMaxTicks { get; set; }
// 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 = "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
// INT8ExecutionBridge implementation
public void EnterLongManaged(int quantity, string signalName, int stopTicks, int targetTicks, double tickSize)
{
if (stopTicks > 0)
SetStopLoss(signalName, CalculationMode.Ticks, stopTicks, false);
if (targetTicks > 0)
SetProfitTarget(signalName, CalculationMode.Ticks, targetTicks);
EnterLong(quantity, signalName);
}
public void EnterShortManaged(int quantity, string signalName, int stopTicks, int targetTicks, double tickSize)
{
if (stopTicks > 0)
SetStopLoss(signalName, CalculationMode.Ticks, stopTicks, false);
if (targetTicks > 0)
SetProfitTarget(signalName, CalculationMode.Ticks, targetTicks);
EnterShort(quantity, signalName);
}
public void ExitLongManaged(string signalName)
{
ExitLong(signalName);
}
public void ExitShortManaged(string signalName)
{
ExitShort(signalName);
}
public void FlattenAll()
{
ExitLong("EmergencyFlatten");
ExitShort("EmergencyFlatten");
}
/// <summary>
/// Returns true if the concrete strategy has ForceSessionReset enabled.
/// Override in subclass to expose the NinjaScript parameter value.
/// Default returns false so base class never forces a reset unless overridden.
/// </summary>
protected virtual bool GetForceSessionReset()
{
return false;
}
/// <summary>
/// Resolves the runner mode based on configured mode and quantity.
/// </summary>
/// <param name="configured">The configured runner mode.</param>
/// <param name="qty">The order quantity.</param>
/// <returns>The resolved runner mode.</returns>
private RunnerMode ResolveRunnerMode(RunnerMode configured, int qty)
{
if (configured == RunnerMode.Disabled)
return RunnerMode.Disabled;
if (configured == RunnerMode.Mode1DualLeg)
return RunnerMode.Mode1DualLeg;
if (configured == RunnerMode.Mode2RunnerOnly)
return RunnerMode.Mode2RunnerOnly;
if (configured == RunnerMode.Mode3ScalerOnly)
return RunnerMode.Mode3ScalerOnly;
// Auto: resolve based on quantity
if (qty >= 2)
return RunnerMode.Mode1DualLeg;
return RunnerMode.Mode2RunnerOnly;
}
/// <summary>
/// Create the SDK strategy instance.
/// </summary>
protected abstract IStrategy CreateSdkStrategy();
/// <summary>
/// Configure strategy-specific values after initialization.
/// </summary>
protected abstract void ConfigureStrategyParameters();
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = "SDK-integrated strategy base";
// Name intentionally not set - this is an abstract base class
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 2;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
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;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 1;
EnableSDK = true;
DailyLossLimit = 1000.0;
MaxTradeRisk = 200.0;
MaxOpenPositions = 3;
RiskTier = RiskTier.Normal;
MicroUpgradeThreshold = 5000.0;
EnableTrailingDrawdown = false;
AccountStartingBalance = 0.0;
TrailingDrawdownAmount = 2500.0;
TrailingDrawdownHaltBuffer = 2000.0;
TrailingDrawdownLockOffset = 100.0;
RiskPerTrade = 100.0;
MinContracts = 1;
MaxContracts = 3;
EnableKillSwitch = false;
EnableVerboseLogging = false;
MinTradeGrade = 4;
EnableFileLogging = true;
LogDirectory = string.Empty;
EnableLongTrades = true;
EnableShortTrades = true;
EnableAutoBreakeven = true;
BreakevenTriggerTicks = 20;
BreakevenOffsetTicks = 1;
EnableRunner = true;
RunnerTrailTicks = 12;
RunnerActivationMode = RunnerMode.Auto;
EnableDynamicStop = false;
AtrPeriod = 14;
AtrMultiplier = 1.5;
MinStopTicks = 12;
MaxStopTicks = 50;
EnableBarBasedRearm = false; // GAP-006: default false for live trading
EnableShortTrendFilter = true; // GAP-010: default true for short trend filtering
EnableCMEHolidayGuard = true; // GAP-008: default true for CME holiday guard
EnableATRTrailing = false; // GAP-009: default false for ATR trailing
ATRTrailingPeriod = 14; // GAP-009: default 14 period
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
EnableStateTelemetry = true; // DASH-002: additive realtime observability
EnableEthTelemetry = false; // Read-only ETH telemetry is opt-in only
_killSwitchTriggered = false;
_connectionStateMonitor.ReportConnected();
_microUpgradeSuggested = false;
_microUpgradePersistenceLoaded = false;
_trailingDrawdownHalted = false;
_trailingDrawdownAccountName = null;
// 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
}
else if (State == State.DataLoaded)
{
if (EnableSDK)
{
try
{
// DIAGNOSTIC: Print actual runtime property values to confirm
// what NT8 loaded vs what SetDefaults specified.
Print(string.Format("[SDK-DIAG] SetDefaults check: BE={0} Trail={1} MaxC={2} SB={3} EPD={4}",
BreakevenTriggerTicks,
RunnerTrailTicks,
MaxContracts,
StartBehavior,
EntriesPerDirection));
InitFileLog();
InitializeSdkComponents();
InitializeTrailingDrawdownState();
_sdkInitialized = true;
Print(string.Format("[SDK] {0} initialized successfully", Name));
WriteSettingsFile();
WriteSessionHeader();
}
catch (Exception ex)
{
Print(string.Format("[SDK ERROR] Initialization failed: {0}", ex.Message));
Log(string.Format("[SDK ERROR] {0}", ex.ToString()), NinjaTrader.Cbi.LogLevel.Error);
_sdkInitialized = false;
}
}
}
else if (State == State.Realtime)
{
_realtimeBarSeen = false;
// If ForceSessionReset is enabled, push a reset signal into the SDK strategy
// so _tradeTaken is cleared before any live bar is processed.
// This recovers from replay-burst scenarios where historical bars set _tradeTaken.
if (_sdkStrategy != null && GetForceSessionReset())
{
var resetParams = new Dictionary<string, object>();
resetParams.Add("force_session_reset", true);
_sdkStrategy.SetParameters(resetParams);
Print(string.Format("[SDK] ForceSessionReset: _tradeTaken cleared on live start at {0}", DateTime.Now.ToString("HH:mm:ss")));
}
if (_sdkStrategy != null && Account != null && !IsBacktestRun())
{
var dailyCountParams = new Dictionary<string, object>();
dailyCountParams.Add("daily_trade_count_persistence_enabled", true);
dailyCountParams.Add("daily_trade_count_account", Account.Name);
dailyCountParams.Add("daily_trade_count_strategy_name", Name);
dailyCountParams.Add("daily_trade_count_log_directory", ResolveLogDirectory(false, "daily trade count state"));
_sdkStrategy.SetParameters(dailyCountParams);
}
InitializeMicroUpgradeSuggestedState();
// TASK-00a: Write session provenance on realtime transition
WriteSessionProvenance();
WriteHistoricalReadiness("REALTIME ELIGIBILITY");
WriteSettingsFile();
}
else if (State == State.Terminated)
{
if (!string.IsNullOrEmpty(_trailingDrawdownAccountName))
TrailingDrawdownMonitor.Instance.UnregisterStrategy(_trailingDrawdownAccountName, this);
PortfolioRiskManager.Instance.UnregisterStrategy(Name);
WriteSessionFooter();
}
}
protected override void OnBarUpdate()
{
// Only process primary bar series — ignore secondary data series updates.
// 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.
// During this burst, State == Realtime but Time[0] is historical (seconds/minutes
// in the past). We detect this by comparing bar time to wall clock.
// A bar is treated as a genuine live bar only when its timestamp is within
// 5 minutes of now — catch-up bars are always older than that.
// This guard does NOT affect Strategy Analyzer backtest runs, where
// State == State.Historical and this branch is never reached.
if (State == State.Realtime)
{
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,
// but do NOT block trading. NarrowRangeFactorCalculator handles missing
// daily context gracefully by returning a neutral 0.3 score.
// Blocking all trades here caused zero signals in live/SIM where the
// secondary daily series starts empty each session.
if (BarsArray != null && BarsArray.Length > 1
&& CurrentBars != null && CurrentBars.Length > 1
&& CurrentBars[1] < 7)
{
if (CurrentBar % 100 == 0)
Print(String.Format("[SDK] NR7 warm-up: {0}/7 daily bars available — NarrowRange factor scoring as neutral until 7 bars loaded.",
CurrentBars[1] + 1));
// Do NOT return — allow trading to proceed with reduced NR7 score.
}
// GAP-008: CME Holiday Guard — skip entire bar on CME holidays
if (EnableCMEHolidayGuard && NT8.Core.Calendar.CmeHolidayCalendar.IsHoliday(Time[0].Date))
{
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)
{
_runnerActive = false;
_breakevenMoved = false;
_scalerSignalName = null;
_runnerSignalName = null;
_lastStateTelemetryTime = DateTime.MinValue;
_stateTelemetryChangeInitialized = false;
}
_lastBarTime = Time[0];
// Mark first bar seen after going realtime. Until this fires, we're
// processing catch-up replay bars and must not submit orders.
if (State == State.Realtime && !_realtimeBarSeen)
{
_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;
}
MaybeWriteRejectSummarySnapshot(Time[0]);
// Sync actual open position to portfolio manager on every bar
PortfolioRiskManager.Instance.UpdateOpenContracts(Name, Math.Abs(Position.Quantity));
MonitorMicroAccountUpgrade();
if (CheckTrailingDrawdownMonitor())
return;
// Kill switch — checked AFTER bar guards so ExitLong/ExitShort are valid
if (EnableKillSwitch)
{
if (!_killSwitchTriggered)
{
_killSwitchTriggered = true;
Print(string.Format("[SDK] KILL SWITCH ACTIVATED at {0} — flattening all positions.", Time[0]));
try
{
ExitLong("KillSwitch");
ExitShort("KillSwitch");
}
catch (Exception ex)
{
Print(string.Format("[SDK] Kill switch flatten error: {0}", ex.Message));
}
}
LogRejectRateLimited("KillSwitch", string.Format("EnableKillSwitch=True KillSwitchTriggered={0}", _killSwitchTriggered), Time[0]);
return;
}
// Connection loss guard — do not submit new orders if broker is disconnected
if (!_connectionStateMonitor.TryAllowNewEntry(Time[0], LogRejectRateLimited))
{
if (EnableVerboseLogging)
Print(string.Format("[NT8-SDK] Bar skipped — connection lost: {0}", Time[0]));
return;
}
// RTH guard: NT8 Time[0] is already in local time (ET on this machine).
// No timezone conversion needed — use it directly.
// Bypassed when TestMode is active so signals can fire any time of day.
bool isTestMode = _strategyConfig != null
&& _strategyConfig.Parameters != null
&& _strategyConfig.Parameters.ContainsKey("TestMode")
&& _strategyConfig.Parameters["TestMode"] is bool
&& (bool)_strategyConfig.Parameters["TestMode"];
bool isRthBar = Time[0].TimeOfDay >= new TimeSpan(9, 30, 0)
&& Time[0].TimeOfDay < new TimeSpan(16, 0, 0);
if (!isTestMode && !isRthBar)
{
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]);
if (EnableEthTelemetry)
{
try
{
BarData ethBarData = ConvertCurrentBar();
StrategyContext ethContext = BuildStrategyContext();
MaybeWriteStateTelemetry(ethBarData, ethContext);
DrawDiagnostics();
}
catch (Exception ex)
{
if (_logger != null)
_logger.LogWarning("ETH telemetry/diagnostics failed: {0}", ex.Message);
}
}
return;
}
// Log first processable bar and every 100th bar.
if (CurrentBar == BarsRequiredToTrade || CurrentBar % 100 == 0)
{
Print(string.Format("[SDK] Processing bar {0}: {1} O={2:F2} H={3:F2} L={4:F2} C={5:F2}",
CurrentBar,
Time[0].ToString("yyyy-MM-dd HH:mm"),
Open[0],
High[0],
Low[0],
Close[0]));
}
// Draw chart diagnostics for visual proof of every decision
DrawDiagnostics();
// --- Runner trailing monitor ---
if (_runnerActive && !string.IsNullOrEmpty(_runnerSignalName) && Position.Quantity != 0)
{
// Trailing stop is set at entry via SetTrailStop in SubmitOrderToNT8.
// NT8 manages it natively tick-by-tick. Do NOT call SetTrailStop here
// on bar close — that resets the trail anchor to bar-close price each
// bar and causes near-breakeven exits on fast reversals within a bar.
// (See session log 2026-04-13: MFE $1,127 vs exit $133 — confirmed cause.)
// Do NOT call SetStopLoss here either. In NT8 managed orders,
// SetStopLoss and SetTrailStop are signal-scoped Set() methods;
// the later call for the same runner signal replaces the earlier
// protective exit and disables the live trail for the trade.
}
// Clear runner state when flat
if (Position.Quantity == 0 && _runnerActive)
{
_runnerActive = false;
_breakevenMoved = false;
if (EnableFileLogging && State == State.Realtime && !string.IsNullOrEmpty(_runnerSignalName))
FileLog("RUNNER closed — position flat");
}
try
{
var barData = ConvertCurrentBar();
var context = BuildStrategyContext();
StrategyIntent intent;
lock (_lock)
{
intent = _sdkStrategy.OnBar(barData, context);
}
MaybeWriteStateTelemetry(barData, context);
if (intent != null)
{
Print(string.Format("[SDK] Intent generated: {0} {1} @ {2}", intent.Side, intent.Symbol, intent.EntryType));
ProcessStrategyIntent(intent, context);
}
else
{
LogSignalRejectionFromContext(context);
}
}
catch (Exception ex)
{
if (_logger != null)
_logger.LogError("OnBarUpdate failed: {0}", ex.Message);
FileLog(string.Format("SDK ONBARUPDATE FAILED: {0}: {1}", ex.GetType().Name, ex.Message));
Print(string.Format("[SDK ERROR] OnBarUpdate: {0}", ex.Message));
Log(string.Format("[SDK ERROR] {0}", ex.ToString()), NinjaTrader.Cbi.LogLevel.Error);
}
}
private void MonitorMicroAccountUpgrade()
{
if (Account == null || MicroUpgradeThreshold <= 0.0 || State != State.Realtime)
return;
InitializeMicroUpgradeSuggestedState();
if (_microUpgradeSuggested)
return;
try
{
double balance = Account.Get(AccountItem.CashValue, Currency.UsDollar);
if (balance >= MicroUpgradeThreshold)
{
_microUpgradeSuggested = true;
string message = string.Format("TIER_UPGRADE_SUGGESTED: Balance={0:F2} crossed threshold={1:F2}; review RiskTier setting.", balance, MicroUpgradeThreshold);
Print(message);
FileLog(message);
WriteMicroUpgradeSuggestedFile(balance);
}
}
catch (Exception ex)
{
if (EnableVerboseLogging)
Print(string.Format("[SDK] Micro upgrade balance check failed: {0}", ex.Message));
}
}
private void InitializeMicroUpgradeSuggestedState()
{
if (_microUpgradePersistenceLoaded || Account == null || State != State.Realtime)
return;
_microUpgradePersistenceLoaded = true;
try
{
string path = GetMicroUpgradeSuggestedFilePath(Account.Name);
if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path))
return;
Dictionary<string, object> payload = JsonConvert.DeserializeObject<Dictionary<string, object>>(System.IO.File.ReadAllText(path));
if (payload != null && payload.ContainsKey("suggested") && payload["suggested"] is bool)
_microUpgradeSuggested = (bool)payload["suggested"];
}
catch (Exception ex)
{
_microUpgradeSuggested = false;
string message = string.Format("MICRO_UPGRADE_SUGGESTED warning: could not read persisted advisory state; advisory may re-fire. Error={0}", ex.Message);
Print(message);
FileLog(message);
}
}
private string GetMicroUpgradeSuggestedFilePath(string accountName)
{
if (string.IsNullOrEmpty(accountName))
return string.Empty;
string safeAccount = MakeSafeFileName(accountName);
string dir = ResolveLogDirectory(false, "micro upgrade advisory state");
return System.IO.Path.Combine(dir, string.Format("micro_upgrade_suggested_{0}.json", safeAccount));
}
private void WriteMicroUpgradeSuggestedFile(double balance)
{
if (Account == null)
return;
try
{
string path = GetMicroUpgradeSuggestedFilePath(Account.Name);
if (string.IsNullOrEmpty(path))
return;
string dir = System.IO.Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir))
System.IO.Directory.CreateDirectory(dir);
var payload = new Dictionary<string, object>();
payload.Add("account", Account.Name);
payload.Add("strategy_name", Name);
payload.Add("suggested", true);
payload.Add("suggested_timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
payload.Add("balance", balance);
payload.Add("threshold", MicroUpgradeThreshold);
System.IO.File.WriteAllText(path, JsonConvert.SerializeObject(payload, Formatting.Indented));
}
catch (Exception ex)
{
string message = string.Format("MICRO_UPGRADE_SUGGESTED warning: could not write persisted advisory state; advisory may re-fire after restart. Error={0}", ex.Message);
Print(message);
FileLog(message);
}
}
private bool CheckTrailingDrawdownMonitor()
{
if (!EnableTrailingDrawdown || IsBacktestRun() || Account == null || State != State.Realtime)
return _trailingDrawdownHalted;
if (_trailingDrawdownHalted)
return true;
if (AccountStartingBalance <= 0.0)
{
LogRejectRateLimited("TrailingDrawdownNotConfigured", "EnableTrailingDrawdown=True but AccountStartingBalance is not configured", Time[0]);
return true;
}
try
{
string accountName = Account.Name;
double equity = Account.Get(AccountItem.NetLiquidation, Currency.UsDollar);
TrailingDrawdownStatus status = TrailingDrawdownMonitor.Instance.UpdateEquity(
accountName,
equity,
AccountStartingBalance,
TrailingDrawdownHaltBuffer,
TrailingDrawdownLockOffset,
Time[0]);
if (status != null && status.Breached)
{
HandleTrailingDrawdownBreach(status, true);
return true;
}
}
catch (Exception ex)
{
Print(string.Format("[SDK] Trailing drawdown monitor error: {0}", ex.Message));
if (_logger != null)
_logger.LogError("Trailing drawdown monitor error: {0}", ex.Message);
}
return _trailingDrawdownHalted;
}
private void HandleTrailingDrawdownBreach(TrailingDrawdownStatus status, bool flatten)
{
if (status == null)
return;
_trailingDrawdownHalted = true;
string message = string.Format("TRAILING_DRAWDOWN_BREACH: Account={0} Equity={1:F2} Peak={2:F2} Floor={3:F2} Locked={4} Time={5:yyyy-MM-dd HH:mm:ss}",
status.AccountName,
status.Equity,
status.ReferencePeak,
status.HaltThreshold,
status.Locked,
status.Time);
Print(message);
FileLog(message);
LogRejectRateLimited("TrailingDrawdownBreach", string.Format("Account={0} Equity={1:F2} Floor={2:F2} Locked={3}", status.AccountName, status.Equity, status.HaltThreshold, status.Locked), status.Time);
if (RiskTier == RiskTier.Conservative)
WriteTrailingDrawdownHaltFile(status);
if (flatten)
TrailingDrawdownMonitor.Instance.FlattenRegisteredStrategies(status.AccountName, status);
}
private void FlattenForTrailingDrawdown(TrailingDrawdownStatus status)
{
_trailingDrawdownHalted = true;
try
{
ExitLong("TrailingDrawdownHalt");
ExitShort("TrailingDrawdownHalt");
}
catch (Exception ex)
{
Print(string.Format("[SDK] Trailing drawdown flatten error: {0}", ex.Message));
}
}
private void MaybeWriteStateTelemetry(BarData barData, StrategyContext context)
{
if (!EnableStateTelemetry || !EnableFileLogging || State != State.Realtime)
return;
if (barData == null || context == null)
return;
DateTime now = DateTime.Now;
try
{
StrategyIntent telemetryIntent = BuildStateTelemetryIntent(barData, context);
if (telemetryIntent == null)
return;
ApplyDynamicStopToIntent(telemetryIntent, false);
var scorer = new ConfluenceScorer(_logger != null ? _logger : new BasicLogger(Name), 10);
var score = scorer.CalculateScore(telemetryIntent, context, barData, BuildStateTelemetryFactors());
string factors = FormatTelemetryFactors(score);
string regime = GetTelemetryRegime(context);
string directionSource = GetStateTelemetryDirectionSource(barData, context);
int pendingBreakoutDirection = GetStateTelemetryPendingBreakoutDirection(barData, context);
bool gradeMeetsThreshold = score != null && (int)score.Grade >= MinTradeGrade;
bool periodicDue = _lastStateTelemetryTime == DateTime.MinValue
|| (now - _lastStateTelemetryTime).TotalSeconds >= STATE_TELEMETRY_INTERVAL_SECONDS;
bool changed = !_stateTelemetryChangeInitialized
|| pendingBreakoutDirection != _lastStateTelemetryPendingBreakoutDirection
|| gradeMeetsThreshold != _lastStateTelemetryGradeMeetsThreshold;
if (!periodicDue && !changed)
return;
FileLog(string.Format("STATE: Regime={0} Direction={1} DirectionSource={2} Score={3:F3} Grade={4} Factors={5}",
regime,
telemetryIntent.Side,
directionSource,
score.WeightedScore,
score.Grade,
factors));
string detail = FormatFactorReasons(score);
if (!string.IsNullOrEmpty(detail))
FileLog(string.Format("STATE_DETAIL: {0}", detail));
Dictionary<string, string> contextFields = GetStateTelemetryContextFields(barData, context);
contextFields = AddRecommendedContractsContextField(contextFields, telemetryIntent, context);
string contextDetail = FormatTelemetryContextFields(contextFields);
if (!string.IsNullOrEmpty(contextDetail))
FileLog(string.Format("STATE_CONTEXT: {0}", contextDetail));
_lastStateTelemetryPendingBreakoutDirection = pendingBreakoutDirection;
_lastStateTelemetryGradeMeetsThreshold = gradeMeetsThreshold;
_stateTelemetryChangeInitialized = true;
if (periodicDue)
_lastStateTelemetryTime = now;
}
catch (Exception ex)
{
if (_logger != null)
_logger.LogWarning("State telemetry failed: {0}", ex.Message);
}
}
protected virtual StrategyIntent BuildStateTelemetryIntent(BarData barData, StrategyContext context)
{
SdkOrderSide side = SdkOrderSide.Buy;
if (Position != null && Position.MarketPosition == MarketPosition.Short)
side = SdkOrderSide.Sell;
return new StrategyIntent(
context.Symbol,
side,
SdkOrderType.Market,
null,
1,
null,
0.0,
"DASH-002 state telemetry sample",
new Dictionary<string, object>());
}
protected virtual string GetStateTelemetryDirectionSource(BarData barData, StrategyContext context)
{
if (Position != null && Position.MarketPosition != MarketPosition.Flat)
return "Position";
return "DefaultLong";
}
protected virtual int GetStateTelemetryPendingBreakoutDirection(BarData barData, StrategyContext context)
{
return 0;
}
protected virtual Dictionary<string, string> GetStateTelemetryContextFields(BarData barData, StrategyContext context)
{
return null;
}
private Dictionary<string, string> AddRecommendedContractsContextField(Dictionary<string, string> fields, StrategyIntent telemetryIntent, StrategyContext context)
{
if (_positionSizer == null || _sizingConfig == null || telemetryIntent == null || context == null)
return fields;
SizingResult sizingResult = _positionSizer.CalculateSize(telemetryIntent, context, _sizingConfig);
if (sizingResult == null)
return fields;
if (fields == null)
fields = new Dictionary<string, string>();
if (fields.ContainsKey("RecommendedContracts"))
fields["RecommendedContracts"] = sizingResult.Contracts.ToString();
else
fields.Add("RecommendedContracts", sizingResult.Contracts.ToString());
return fields;
}
protected int ResolveDynamicStopTicks(int configuredStopTicks, Dictionary<string, object> metadata, bool logCalculation)
{
if (!EnableDynamicStop || CurrentBars == null || CurrentBars.Length == 0 || CurrentBars[0] < AtrPeriod)
return configuredStopTicks;
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));
if (metadata != null)
metadata["current_atr"] = atrValue / TickSize;
if (logCalculation)
{
Print(String.Format("[SDK] Dynamic stop: ATR={0:F1}t x {1} = {2}t (${3})",
atrValue / TickSize, AtrMultiplier, dynStop, dynStop * 5));
}
return dynStop;
}
private void ApplyDynamicStopToIntent(StrategyIntent intent, bool logCalculation)
{
if (intent == null)
return;
intent.StopTicks = ResolveDynamicStopTicks((int)intent.StopTicks, intent.Metadata, logCalculation);
}
private List<IFactorCalculator> BuildStateTelemetryFactors()
{
var factors = new List<IFactorCalculator>();
factors.Add(new OrbSetupFactorCalculator());
factors.Add(new TrendAlignmentFactorCalculator());
factors.Add(new VolatilityRegimeFactorCalculator());
factors.Add(new TimeInSessionFactorCalculator());
factors.Add(new ExecutionQualityFactorCalculator());
factors.Add(new NarrowRangeFactorCalculator(_logger));
factors.Add(new OrbRangeVsAtrFactorCalculator(_logger));
factors.Add(new GapDirectionAlignmentCalculator(_logger));
factors.Add(new BreakoutVolumeStrengthCalculator(_logger));
factors.Add(new PriorDayCloseStrengthCalculator(_logger));
return factors;
}
private string FormatTelemetryFactors(ConfluenceScore score)
{
if (score == null || score.Factors == null)
return "none";
StringBuilder builder = new StringBuilder();
foreach (ConfluenceFactor factor in score.Factors)
{
if (builder.Length > 0)
builder.Append(";");
builder.Append(string.Format("{0}={1:F2}x{2:F2}", factor.Type, factor.Score, factor.Weight));
}
return builder.Length > 0 ? builder.ToString() : "none";
}
private string FormatTelemetryContextFields(Dictionary<string, string> fields)
{
if (fields == null || fields.Count == 0)
return string.Empty;
StringBuilder builder = new StringBuilder();
foreach (KeyValuePair<string, string> field in fields)
{
if (string.IsNullOrEmpty(field.Key) || string.IsNullOrEmpty(field.Value))
continue;
if (builder.Length > 0)
builder.Append(" ");
builder.Append(string.Format("{0}={1}", field.Key, field.Value));
}
return builder.ToString();
}
private string FormatFactorReasons(ConfluenceScore score)
{
if (score == null || score.Factors == null)
return string.Empty;
StringBuilder builder = new StringBuilder();
foreach (ConfluenceFactor factor in score.Factors)
{
if (builder.Length > 0)
builder.Append(" ");
builder.Append(string.Format("{0}=\"{1}\"", factor.Type, EscapeLogValue(factor.Reason)));
}
return builder.ToString();
}
private string EscapeLogValue(string value)
{
if (value == null)
return string.Empty;
return value.Replace("\\", "\\\\").Replace("\"", "\\\"");
}
private string GetMetadataText(StrategyIntent intent, string key)
{
if (intent == null || intent.Metadata == null || string.IsNullOrEmpty(key) || !intent.Metadata.ContainsKey(key) || intent.Metadata[key] == null)
return "N/A";
return intent.Metadata[key].ToString();
}
private string GetTelemetryRegime(StrategyContext context)
{
if (context != null && context.CustomData != null && context.CustomData.ContainsKey("regime_trend") && context.CustomData["regime_trend"] != null)
return context.CustomData["regime_trend"].ToString();
return "Neutral";
}
protected override void OnOrderUpdate(
Order order,
double limitPrice,
double stopPrice,
int quantity,
int filled,
double averageFillPrice,
NinjaTrader.Cbi.OrderState orderState,
DateTime time,
ErrorCode errorCode,
string nativeError)
{
if (!_sdkInitialized || _executionAdapter == null || order == null)
return;
if (string.IsNullOrEmpty(order.Name) || !order.Name.StartsWith("SDK_"))
return;
if (EnableFileLogging && State == State.Realtime)
{
FileLog(string.Format("ORDER {0} State={1} Filled={2}/{3} AvgFillPrice={4:F2}",
order.Name,
orderState,
filled,
quantity,
averageFillPrice));
}
// Record NT8 rejections in circuit breaker
if (orderState == NinjaTrader.Cbi.OrderState.Rejected && _circuitBreaker != null)
{
var reason = string.Format("{0} {1}", errorCode, nativeError ?? string.Empty);
_circuitBreaker.RecordOrderRejection(reason);
Print(string.Format("[SDK] Order rejected by NT8: {0}", reason));
}
_executionAdapter.ProcessOrderUpdate(
order.OrderId,
order.Name,
orderState.ToString(),
filled,
averageFillPrice,
(int)errorCode,
nativeError);
}
protected override void OnExecutionUpdate(
Execution execution,
string executionId,
double price,
int quantity,
MarketPosition marketPosition,
string orderId,
DateTime time)
{
if (!_sdkInitialized || _executionAdapter == null || execution == null || execution.Order == null)
return;
if (string.IsNullOrEmpty(execution.Order.Name) || !execution.Order.Name.StartsWith("SDK_"))
return;
// Only log fills during live/SIM execution. Historical backtest fills
// are simulated by NT8 and must not appear in the session log.
if (State != State.Realtime)
return;
FileLog(string.Format("FILL {0} {1} @ {2:F2} | OrderId={3} Signal={4}",
execution.MarketPosition,
execution.Quantity,
execution.Price,
execution.OrderId,
execution.Order.Name));
var fill = new NT8.Core.Common.Models.OrderFill(
orderId,
execution.Order != null ? execution.Order.Instrument.MasterInstrument.Name : string.Empty,
execution.Quantity,
execution.Price,
time,
0.0,
executionId);
PortfolioRiskManager.Instance.ReportFill(Name, fill);
_executionAdapter.ProcessExecution(orderId, executionId, price, quantity, time);
}
protected override void OnPositionUpdate(
NinjaTrader.Cbi.Position position,
double averagePrice,
int quantity,
MarketPosition marketPosition)
{
if (!_sdkInitialized || _riskManager == null)
return;
try
{
double dayPnL = 0.0;
if (Account != null)
{
try
{
dayPnL = Account.Get(AccountItem.RealizedProfitLoss, Currency.UsDollar);
}
catch
{
dayPnL = 0.0;
}
}
_riskManager.OnPnLUpdate(dayPnL, dayPnL);
PortfolioRiskManager.Instance.ReportPnL(Name, dayPnL);
if (EnableVerboseLogging)
Print(string.Format("[SDK] P&L update: DayPnL={0:C} Position={1} Qty={2}",
dayPnL, marketPosition, quantity));
if (EnableFileLogging && State == State.Realtime)
FileLog(string.Format("PNL_UPDATE DayPnL={0:C} Position={1} Qty={2}",
dayPnL, marketPosition, quantity));
// Position state must not reset the session-scoped daily trade limit.
if (marketPosition == MarketPosition.Flat || quantity == 0)
{
if (EnableVerboseLogging)
Print(string.Format("[SDK] Position flat detected — daily trade count remains active until session rollover"));
if (EnableFileLogging && State == State.Realtime)
FileLog("POSITION FLAT — daily trade count remains active until session rollover");
}
}
catch (Exception ex)
{
Print(string.Format("[SDK] OnPositionUpdate error: {0}", ex.Message));
}
}
/// <summary>
/// Handles broker connection status changes. Halts new orders on disconnect,
/// logs reconnect, and resets the connection flag when restored.
/// NinjaScript signature: single ConnectionStatusEventArgs parameter.
/// </summary>
protected override void OnConnectionStatusUpdate(
ConnectionStatusEventArgs connectionStatusUpdate)
{
if (connectionStatusUpdate == null) return;
if (connectionStatusUpdate.Status == ConnectionStatus.Connected)
{
if (_connectionStateMonitor.ReportConnected())
{
Print(string.Format("[NT8-SDK] Connection RESTORED at {0} — trading resumed.",
DateTime.Now.ToString("HH:mm:ss")));
FileLog(string.Format("CONNECTION RESTORED at {0}", DateTime.Now.ToString("HH:mm:ss")));
}
}
else if (connectionStatusUpdate.Status == ConnectionStatus.Disconnected ||
connectionStatusUpdate.Status == ConnectionStatus.ConnectionLost)
{
if (_connectionStateMonitor.ReportDisconnected())
{
Print(string.Format("[NT8-SDK] Connection LOST at {0} — halting new orders. Status={1}",
DateTime.Now.ToString("HH:mm:ss"),
connectionStatusUpdate.Status));
FileLog(string.Format("CONNECTION LOST at {0} Status={1}",
DateTime.Now.ToString("HH:mm:ss"),
connectionStatusUpdate.Status));
}
}
}
private void InitFileLog()
{
if (!EnableFileLogging)
return;
try
{
string dir = ResolveLogDirectory(false, "session file log");
System.IO.Directory.CreateDirectory(dir);
string path = System.IO.Path.Combine(
dir,
string.Format("session_{0}.log", DateTime.Now.ToString("yyyyMMdd_HHmmss")));
_fileLog = new System.IO.StreamWriter(path, false);
_fileLog.AutoFlush = true;
Print(string.Format("[NT8-SDK] File log started: {0}", path));
}
catch (Exception ex)
{
Print(string.Format("[NT8-SDK] Failed to open file log: {0}", ex.Message));
}
}
private string GetDefaultLogDirectory()
{
return System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"NinjaTrader 8", "log", "nt8-sdk");
}
protected string ResolveLogDirectory(bool warnWhenDefault, string purpose)
{
if (!string.IsNullOrEmpty(LogDirectory))
return LogDirectory;
string dir = GetDefaultLogDirectory();
if (warnWhenDefault)
{
string warning = string.Format("[NT8-SDK] WARNING: LogDirectory is blank; using default log directory for {0}: {1}", purpose, dir);
Print(warning);
FileLog(warning);
}
return dir;
}
private void FileLog(string message)
{
if (_fileLog == null)
return;
lock (_fileLock)
{
try
{
_fileLog.WriteLine(string.Format("[{0:HH:mm:ss.fff}] {1}", DateTime.Now, message));
}
catch
{
}
}
}
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)
return;
if (State != State.Realtime && !IsBacktestRun() && reason != "HistoricalReplayCatchup")
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;
MaybeWriteRejectSummarySnapshot(barTime);
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 MaybeWriteRejectSummarySnapshot(DateTime barTime)
{
if (_rejectCounts.Count == 0)
return;
if (IsRejectSummarySnapshotSuppressed(barTime))
return;
DateTime tradingDate = barTime.Date;
if (_rejectSummarySnapshotTradingDate != tradingDate)
{
_rejectSummarySnapshotTradingDate = tradingDate;
_orbRejectSummarySnapshotWritten = false;
}
if (IsBacktestRun() && _orbRejectSummarySnapshotWritten)
return;
bool dueAfterOrbWindow = !_orbRejectSummarySnapshotWritten;
bool dueInterval = _lastRejectSummarySnapshotTime != DateTime.MinValue
&& (barTime - _lastRejectSummarySnapshotTime).TotalMinutes >= REJECT_SUMMARY_SNAPSHOT_INTERVAL_MINUTES;
if (!dueAfterOrbWindow && !dueInterval)
return;
WriteRejectSummary();
_lastRejectSummarySnapshotTime = barTime;
_orbRejectSummarySnapshotWritten = true;
}
private bool IsRejectSummarySnapshotSuppressed(DateTime barTime)
{
DateTime suppressionStart;
DateTime suppressionEnd;
if (!TryGetRejectSummarySnapshotSuppressionWindow(barTime, out suppressionStart, out suppressionEnd))
return false;
return barTime >= suppressionStart && barTime < suppressionEnd;
}
protected virtual bool TryGetRejectSummarySnapshotSuppressionWindow(DateTime barTime, out DateTime suppressionStart, out DateTime suppressionEnd)
{
suppressionStart = barTime.Date.AddHours(9.5);
suppressionEnd = barTime.Date.AddHours(10.0);
return true;
}
private void ResetRejectTracking()
{
_rejectCounts.Clear();
_rejectDetailsLogged.Clear();
_lastRejectSummarySnapshotTime = DateTime.MinValue;
_orbRejectSummarySnapshotWritten = false;
_rejectSummarySnapshotTradingDate = DateTime.MinValue;
}
private void WriteSessionHeader()
{
ResetRejectTracking();
FileLog("=== SESSION START " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ===");
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"));
FileLog(string.Format("Risk : DailyLimit=${0} MaxTradeRisk=${1} RiskPerTrade=${2}",
DailyLossLimit,
MaxTradeRisk,
RiskPerTrade));
FileLog(string.Format("Sizing : MinContracts={0} MaxContracts={1}", MinContracts, MaxContracts));
FileLog(string.Format("VerboseLog : {0} FileLog: {1}", EnableVerboseLogging, EnableFileLogging));
FileLog(string.Format("ConnectionLost : {0}", _connectionStateMonitor.IsConnectionLost));
WriteHistoricalReadiness("DATA LOADED");
FileLog("---");
}
private void WriteHistoricalReadiness(string phase)
{
FileLog(string.Format("Historical readiness [{0}] : BarsRequiredToTrade={1}", phase, BarsRequiredToTrade));
int dailyBars = 0;
if (BarsArray == null || BarsArray.Length == 0)
{
FileLog(string.Format("WARNING: Historical readiness [{0}] unavailable; no data series loaded.", phase));
}
else
{
for (int i = 0; i < BarsArray.Length; i++)
{
int daysToLoad = 0;
int loadedBars = 0;
string seriesType = "Unknown";
if (BarsArray[i] != null)
{
loadedBars = BarsArray[i].Count;
if (BarsArray[i].BarsType != null)
{
daysToLoad = BarsArray[i].BarsType.DaysToLoad;
seriesType = BarsArray[i].BarsType.GetType().Name;
}
}
FileLog(string.Format("DataSeries[{0}] : Type={1} DaysToLoad={2} HistoricalBarsLoaded={3}",
i,
seriesType,
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;
}
}
bool narrowRangeReady = dailyBars >= 7;
bool orbRangeReady = dailyBars >= 5;
FileLog(string.Format("FactorWarmup : NarrowRangeFactorCalculator={0} ({1}/7 daily bars) OrbRangeVsAtrFactorCalculator={2} ({1}/5 daily bars)",
narrowRangeReady ? "SATISFIED" : "NOT SATISFIED",
dailyBars,
orbRangeReady ? "SATISFIED" : "NOT SATISFIED"));
if (!narrowRangeReady || !orbRangeReady)
{
FileLog(string.Format("WARNING: Factor warm-up not satisfied before real-time order eligibility; daily bars={0}, NarrowRange requires 7, OrbRangeVsAtr requires 5. Strategy startup is not blocked.",
dailyBars));
}
else
{
FileLog(string.Format("Factor warm-up confirmed before real-time order eligibility; daily bars={0}.", dailyBars));
}
string accountName = Account != null ? Account.Name : string.Empty;
if (!EnableKillSwitch && accountName.IndexOf("SimSimple", StringComparison.OrdinalIgnoreCase) >= 0)
{
FileLog(string.Format("WARNING: EnableKillSwitch=False for gate account {0}.", accountName));
}
}
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)
{
lock (_fileLock)
{
try
{
_fileLog.Close();
}
catch
{
}
_fileLog = null;
}
}
}
private void InitializeSdkComponents()
{
_logger = new BasicLogger(Name);
Print(string.Format("[SDK] Initializing with: DailyLoss={0:C}, TradeRisk={1:C}, MaxPos={2}",
DailyLossLimit,
MaxTradeRisk,
MaxOpenPositions));
_riskConfig = new RiskConfig(DailyLossLimit, MaxTradeRisk, MaxOpenPositions, true);
_sizingConfig = new SizingConfig(
SizingMethod.FixedDollarRisk,
MinContracts,
MaxContracts,
RiskPerTrade,
new Dictionary<string, object>());
_strategyConfig = new StrategyConfig(
Name,
Instrument.MasterInstrument.Name,
new Dictionary<string, object>(),
_riskConfig,
_sizingConfig);
ValidateStartupRiskConfiguration();
_riskManager = new BasicRiskManager(_logger, DailyLossLimit);
_positionSizer = new BasicPositionSizer(_logger);
_circuitBreaker = new ExecutionCircuitBreaker(
_logger,
failureThreshold: 3,
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");
_sdkStrategy.Initialize(_strategyConfig, null, _logger);
ConfigureStrategyParameters();
PortfolioRiskManager.Instance.RegisterStrategy(Name, _riskConfig);
Print(string.Format("[NT8-SDK] Registered with PortfolioRiskManager: {0}", PortfolioRiskManager.Instance.GetStatusSnapshot()));
if (Account != null && !IsBacktestRun())
{
_trailingDrawdownAccountName = Account.Name;
TrailingDrawdownMonitor.Instance.RegisterStrategy(_trailingDrawdownAccountName, this);
}
_ordersSubmittedToday = 0;
_lastBarTime = DateTime.MinValue;
_lastAccountInfo = null;
_lastPosition = null;
_currentSession = null;
}
private void ValidateStartupRiskConfiguration()
{
string symbol = Instrument != null && Instrument.MasterInstrument != null
? Instrument.MasterInstrument.Name
: "UNKNOWN";
double tickValue = 12.50;
if (Instrument != null && Instrument.MasterInstrument != null)
tickValue = Instrument.MasterInstrument.TickSize * Instrument.MasterInstrument.PointValue;
RiskEnvelopeValidator.ValidateStartupConfiguration(
symbol,
tickValue,
EnableTrailingDrawdown,
AccountStartingBalance,
MaxStopTicks,
MaxTradeRisk,
MinContracts,
MaxContracts,
DailyLossLimit);
}
private void InitializeTrailingDrawdownState()
{
if (Account == null || IsBacktestRun())
return;
_trailingDrawdownAccountName = Account.Name;
TrailingDrawdownMonitor.Instance.RegisterStrategy(_trailingDrawdownAccountName, this);
if (!EnableTrailingDrawdown)
return;
string haltPath = GetTrailingDrawdownHaltFilePath(_trailingDrawdownAccountName);
if (!string.IsNullOrEmpty(haltPath) && System.IO.File.Exists(haltPath))
{
_trailingDrawdownHalted = true;
string message = string.Format("TRAILING_DRAWDOWN_HALTED: Account={0} persisted halt file present at {1}; delete file manually to resume.", _trailingDrawdownAccountName, haltPath);
Print(message);
FileLog(message);
}
}
private string GetTrailingDrawdownHaltFilePath(string accountName)
{
if (string.IsNullOrEmpty(accountName))
return string.Empty;
string safeAccount = MakeSafeFileName(accountName);
string dir = ResolveLogDirectory(false, "trailing drawdown halt state");
return System.IO.Path.Combine(dir, string.Format("drawdown_halt_{0}.json", safeAccount));
}
private string MakeSafeFileName(string value)
{
if (string.IsNullOrEmpty(value))
return "account";
char[] invalid = System.IO.Path.GetInvalidFileNameChars();
StringBuilder builder = new StringBuilder(value.Length);
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
bool isInvalid = false;
for (int j = 0; j < invalid.Length; j++)
{
if (c == invalid[j])
{
isInvalid = true;
break;
}
}
builder.Append(isInvalid ? '_' : c);
}
return builder.ToString();
}
private void WriteTrailingDrawdownHaltFile(TrailingDrawdownStatus status)
{
if (status == null || string.IsNullOrEmpty(status.AccountName))
return;
try
{
string path = GetTrailingDrawdownHaltFilePath(status.AccountName);
if (string.IsNullOrEmpty(path))
return;
string dir = System.IO.Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir))
System.IO.Directory.CreateDirectory(dir);
var payload = new Dictionary<string, object>();
payload.Add("account", status.AccountName);
payload.Add("breach_timestamp", status.Time.ToString("yyyy-MM-dd HH:mm:ss"));
payload.Add("equity_at_breach", status.Equity);
payload.Add("floor_at_breach", status.HaltThreshold);
payload.Add("peak_reference", status.ReferencePeak);
payload.Add("locked", status.Locked);
System.IO.File.WriteAllText(path, JsonConvert.SerializeObject(payload, Formatting.Indented));
FileLog(string.Format("TRAILING_DRAWDOWN_HALT_FILE: Account={0} Path={1}", status.AccountName, path));
}
catch (Exception ex)
{
Print(string.Format("[SDK] Failed to write trailing drawdown halt file: {0}", ex.Message));
}
}
private BarData ConvertCurrentBar()
{
// NT8 Time[0] is already in local time (ET on this machine). Use it directly.
return NT8DataConverter.ConvertBar(
Instrument.MasterInstrument.Name,
Time[0],
Open[0],
High[0],
Low[0],
Close[0],
(long)Volume[0],
(int)BarsPeriod.Value);
}
private StrategyContext BuildStrategyContext()
{
// NT8 Time[0] is already in local time (ET on this machine). Use it directly.
var customData = new Dictionary<string, object>();
customData.Add("CurrentBar", CurrentBar);
customData.Add("BarsRequiredToTrade", BarsRequiredToTrade);
customData.Add("OrdersToday", _ordersSubmittedToday);
customData.Add("AllowDailyTradeCountIncrement", ShouldAllowDailyTradeCountIncrement());
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"));
// 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],
BuildPositionInfo(),
BuildAccountInfo(),
BuildSessionInfo(),
customData);
}
private bool ShouldAllowDailyTradeCountIncrement()
{
if (State == State.Realtime)
return _realtimeBarSeen;
if (State == State.Historical)
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;
double buyingPower = 250000.0;
try
{
if (Account != null)
{
cashValue = Account.Get(AccountItem.CashValue, Currency.UsDollar);
buyingPower = Account.Get(AccountItem.BuyingPower, Currency.UsDollar);
}
}
catch (Exception ex)
{
Print(string.Format("[NT8-SDK] WARNING: Could not read live account balance, using defaults: {0}", ex.Message));
}
var accountInfo = NT8DataConverter.ConvertAccount(cashValue, buyingPower, 0.0, 0.0, DateTime.UtcNow);
_lastAccountInfo = accountInfo;
return accountInfo;
}
private SdkPosition BuildPositionInfo()
{
var p = NT8DataConverter.ConvertPosition(
Instrument.MasterInstrument.Name,
Position.Quantity,
Position.AveragePrice,
0.0,
0.0,
DateTime.UtcNow);
_lastPosition = p;
return p;
}
private MarketSession BuildSessionInfo()
{
// NT8 Time[0] is already in local time (ET on this machine). Use it directly.
// Futures trade nearly 24 hours. Bars at/after 17:00 belong to the next
// calendar day's RTH trading session.
DateTime t = Time[0];
DateTime tradingDate = t.TimeOfDay >= new TimeSpan(17, 0, 0)
? t.Date.AddDays(1)
: t.Date;
var sessionStart = tradingDate.AddHours(9).AddMinutes(30);
var sessionEnd = tradingDate.AddHours(16);
var isRth = t.TimeOfDay >= TimeSpan.FromHours(9.5)
&& t.TimeOfDay < TimeSpan.FromHours(16.0);
_currentSession = NT8DataConverter.ConvertSession(sessionStart, sessionEnd, isRth, isRth ? "RTH" : "ETH");
return _currentSession;
}
private void ProcessStrategyIntent(StrategyIntent intent, StrategyContext context)
{
if (State == State.Historical && !IsBacktestRun())
{
LogRejectRateLimited("HistoricalReplayCatchup",
string.Format("Blocked catch-up replay order Time={0:yyyy-MM-dd HH:mm:ss}", Time[0]),
Time[0]);
return;
}
// In live/SIM: block if we haven't seen a genuine realtime bar yet (replay guard).
// 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]);
return;
}
if (!_connectionStateMonitor.TryAllowNewEntry(Time[0], LogRejectRateLimited))
return;
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]);
return;
}
ApplyDynamicStopToIntent(intent, true);
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)
{
Print(string.Format("[SDK] Portfolio blocked: {0}", portfolioDecision.RejectReason));
if (_logger != null)
_logger.LogWarning("Portfolio risk blocked order: {0}", portfolioDecision.RejectReason);
LogRejectRateLimited("PortfolioRisk", string.Format("Portfolio blocked: {0}", portfolioDecision.RejectReason), Time[0]);
return;
}
// Direction filter — checked before risk to avoid unnecessary processing
if (intent.Side == SdkOrderSide.Buy && !EnableLongTrades)
{
if (EnableVerboseLogging)
Print(string.Format("[SDK] Long trade filtered by direction setting: {0}", intent.Symbol));
LogRejectRateLimited("LongTradesDisabled", 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("ShortTradesDisabled", string.Format("EnableShortTrades=False Symbol={0}", intent.Symbol), Time[0]);
return;
}
var sizingResult = _positionSizer.CalculateSize(intent, context, _sizingConfig);
if (EnableVerboseLogging)
{
Print(string.Format("[SDK] Position size: {0} contracts (min={1}, max={2})",
sizingResult.Contracts,
MinContracts,
MaxContracts));
}
if (sizingResult.Contracts < MinContracts)
{
if (EnableVerboseLogging)
Print(string.Format("[SDK] Size too small: {0} < {1}", sizingResult.Contracts, MinContracts));
LogRejectRateLimited("SizeBelowMinContracts", string.Format("Size too small Contracts={0} MinContracts={1}", sizingResult.Contracts, MinContracts), Time[0]);
return;
}
if (EnableVerboseLogging)
Print(string.Format("[SDK] Validating sized intent: {0} {1} Qty={2}", intent.Side, intent.Symbol, sizingResult.Contracts));
var riskDecision = _riskManager.ValidateOrder(intent, context, _riskConfig, sizingResult.Contracts);
if (!riskDecision.Allow)
{
if (EnableVerboseLogging)
Print(string.Format("[SDK] Risk REJECTED: {0}", riskDecision.RejectReason));
if (_logger != null)
_logger.LogWarning("Intent rejected by risk manager: {0}", riskDecision.RejectReason);
LogRejectRateLimited("MaxTradeRisk", string.Format("Risk manager rejected: {0}", riskDecision.RejectReason), Time[0]);
return;
}
if (EnableVerboseLogging)
Print(string.Format("[SDK] Risk approved"));
var request = new OmsOrderRequest();
request.Symbol = intent.Symbol;
request.Side = MapOrderSide(intent.Side);
request.Type = MapOrderType(intent.EntryType);
request.Quantity = sizingResult.Contracts;
request.LimitPrice = intent.LimitPrice.HasValue ? (decimal?)intent.LimitPrice.Value : null;
request.StopPrice = null;
if (EnableVerboseLogging)
{
Print(string.Format("[SDK] Submitting order: {0} {1} {2} @ {3}",
request.Side,
request.Quantity,
request.Symbol,
request.Type));
}
SubmitOrderToNT8(request, intent);
_ordersSubmittedToday++;
}
private void SubmitOrderToNT8(OmsOrderRequest request, StrategyIntent intent)
{
if (State != State.Historical)
{
if (_circuitBreaker != null && !_circuitBreaker.ShouldAllowOrder())
{
var cbState = _circuitBreaker.GetState();
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("CircuitBreaker", string.Format("Circuit breaker open: {0}", cbState.Reason), Time[0]);
return;
}
}
try
{
// Resolve runner mode based on configuration and quantity
RunnerMode resolvedMode = ResolveRunnerMode(RunnerActivationMode, request.Quantity);
Print(String.Format("[SDK] Runner mode resolved: {0} (Qty={1})", resolvedMode, request.Quantity));
int scalerQty = 0;
int runnerQty = 0;
bool useRunnerLeg = false;
bool useScalerLeg = false;
switch (resolvedMode)
{
case RunnerMode.Mode1DualLeg:
// Scaler leg: Qty-1 with fixed target, Runner leg: 1 with trail stop
scalerQty = request.Quantity >= 2 ? request.Quantity - 1 : request.Quantity;
runnerQty = 1;
useScalerLeg = scalerQty > 0;
useRunnerLeg = runnerQty > 0;
break;
case RunnerMode.Mode2RunnerOnly:
// Full qty on trailing stop only, no fixed target
scalerQty = 0;
runnerQty = request.Quantity;
useScalerLeg = false;
useRunnerLeg = true;
break;
case RunnerMode.Mode3ScalerOnly:
// Full qty with fixed target, no runner
scalerQty = request.Quantity;
runnerQty = 0;
useScalerLeg = true;
useRunnerLeg = false;
break;
case RunnerMode.Disabled:
// Original single-leg behavior, no runner
scalerQty = request.Quantity;
runnerQty = 0;
useScalerLeg = true;
useRunnerLeg = false;
break;
default:
// Fallback: Auto mode default behavior (should not reach here since ResolveRunnerMode handles Auto)
scalerQty = request.Quantity;
runnerQty = 0;
useScalerLeg = true;
useRunnerLeg = false;
break;
}
string baseId = Guid.NewGuid().ToString("N").Substring(0, 12);
_scalerSignalName = useScalerLeg ? String.Format("SDK_{0}_S_{1}", intent.Symbol, baseId) : null;
_runnerSignalName = useRunnerLeg ? String.Format("SDK_{0}_R_{1}", intent.Symbol, baseId) : null;
_breakevenMoved = false;
_runnerActive = useRunnerLeg;
if (EnableFileLogging && State == State.Realtime)
{
string grade = "N/A";
string score = "N/A";
string factors = string.Empty;
string factorReasons = string.Empty;
if (intent.Metadata != null && intent.Metadata.ContainsKey("confluence_score"))
{
var cs = intent.Metadata["confluence_score"] as NT8.Core.Intelligence.ConfluenceScore;
if (cs != null)
{
grade = cs.Grade.ToString();
score = cs.WeightedScore.ToString("F3");
var sb = new System.Text.StringBuilder();
foreach (var f in cs.Factors)
sb.Append(String.Format("{0}={1:F2} ", f.Type, f.Score));
factors = sb.ToString().TrimEnd();
factorReasons = FormatFactorReasons(cs);
}
}
FileLog(String.Format("SIGNAL {0} | Grade={1} | Score={2}", intent.Side, grade, score));
if (!string.IsNullOrEmpty(factorReasons))
FileLog(String.Format("SIGNAL_DETAIL: {0}", factorReasons));
if (!string.IsNullOrEmpty(factors))
FileLog(String.Format(" Factors: {0}", factors));
FileLog(String.Format("SUBMIT Scaler={0} Runner={1} Stop={2} Target={3} Mode={4} BaseTarget={5} DynamicTarget={6} GradeMult={7} ModeMult={8} CombinedMult={9}",
scalerQty, runnerQty, intent.StopTicks,
intent.TargetTicks.HasValue ? intent.TargetTicks.Value.ToString() : "none",
resolvedMode,
GetMetadataText(intent, "base_target_ticks"),
GetMetadataText(intent, "dynamic_target_ticks"),
GetMetadataText(intent, "grade_multiplier"),
GetMetadataText(intent, "mode_multiplier"),
GetMetadataText(intent, "combined_multiplier")));
}
// --- Submit scaler leg ---
if (useScalerLeg)
{
if (intent.StopTicks > 0)
SetStopLoss(_scalerSignalName, CalculationMode.Ticks, (int)intent.StopTicks, false);
if (intent.TargetTicks.HasValue && intent.TargetTicks.Value > 0)
SetProfitTarget(_scalerSignalName, CalculationMode.Ticks, (int)intent.TargetTicks.Value);
if (request.Side == OmsOrderSide.Buy)
EnterLong(scalerQty, _scalerSignalName);
else
EnterShort(scalerQty, _scalerSignalName);
}
// --- Submit runner leg ---
// Initial stop protects from open; trail stop takes over tick-by-tick
// after entry. SetTrailStop is set BEFORE EnterLong/EnterShort so NT8
// registers it as the exit order for this signal name at fill time.
// This is the correct NT8 managed approach: one call at entry, NT8 owns
// the trail from that point. Never call SetTrailStop again in OnBarUpdate
// or it resets the anchor to bar-close price, losing intrabar tracking.
if (useRunnerLeg)
{
if (intent.StopTicks > 0)
SetStopLoss(_runnerSignalName, CalculationMode.Ticks, (int)intent.StopTicks, false);
// GAP-009: ATR-based trailing stop
if (EnableATRTrailing && CurrentBars[0] >= ATRTrailingPeriod)
{
double atrValue = ATR(Close, ATRTrailingPeriod)[0];
int atrTrailTicks = (int)System.Math.Round(atrValue / TickSize * ATRTrailingMultiplier);
atrTrailTicks = System.Math.Max(ATRTrailingMinTicks, System.Math.Min(ATRTrailingMaxTicks, atrTrailTicks));
SetTrailStop(_runnerSignalName, CalculationMode.Ticks, atrTrailTicks, false);
Print(String.Format("[SDK] ATR Trail: ATR={0:F1}t x {1} = {2}t (clamped {3}-{4})",
atrValue / TickSize, ATRTrailingMultiplier, atrTrailTicks, ATRTrailingMinTicks, ATRTrailingMaxTicks));
}
else
{
// Fixed tick trail (original behavior)
if (RunnerTrailTicks > 0)
SetTrailStop(_runnerSignalName, CalculationMode.Ticks, RunnerTrailTicks, false);
}
if (request.Side == OmsOrderSide.Buy)
EnterLong(runnerQty, _runnerSignalName);
else
EnterShort(runnerQty, _runnerSignalName);
}
_executionAdapter.SubmitOrder(request, _scalerSignalName ?? _runnerSignalName);
if (_circuitBreaker != null)
_circuitBreaker.OnSuccess();
// TASK-00a: Write trade provenance
double atrStopTicks = 0.0;
if (EnableDynamicStop)
atrStopTicks = intent.StopTicks;
WriteTradeProvenance(intent, request.Quantity, atrStopTicks, resolvedMode);
}
catch (Exception ex)
{
if (_circuitBreaker != null)
_circuitBreaker.OnFailure();
Print(String.Format("[SDK] SubmitOrderToNT8 failed: {0}", ex.Message));
if (_logger != null)
_logger.LogError("SubmitOrderToNT8 failed: {0}", ex.Message);
throw;
}
}
private static OmsOrderSide MapOrderSide(SdkOrderSide side)
{
if (side == SdkOrderSide.Buy)
return OmsOrderSide.Buy;
return OmsOrderSide.Sell;
}
private static OmsOrderType MapOrderType(SdkOrderType type)
{
if (type == SdkOrderType.Market)
return OmsOrderType.Market;
if (type == SdkOrderType.Limit)
return OmsOrderType.Limit;
if (type == SdkOrderType.StopLimit)
return OmsOrderType.StopLimit;
return OmsOrderType.StopMarket;
}
protected OmsOrderStatus GetSdkOrderStatus(string orderName)
{
if (_executionAdapter == null)
return null;
return _executionAdapter.GetOrderStatus(orderName);
}
/// <summary>
/// Returns all strategy parameter lines for the settings export file.
/// Override in subclasses to append strategy-specific parameters.
/// Call base.GetStrategySettingsLines() first then add to the list.
/// </summary>
protected virtual List<string> GetStrategySettingsLines()
{
var lines = new List<string>();
lines.Add("=== STRATEGY SETTINGS EXPORT ===");
lines.Add(string.Format("ExportTime : {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
lines.Add(string.Format("StrategyName : {0}", Name));
lines.Add(string.Format("Description : {0}", Description));
lines.Add(string.Format("Account : {0}", Account != null ? Account.Name : "N/A"));
lines.Add(string.Format("Instrument : {0}", Instrument != null ? Instrument.FullName : "N/A"));
lines.Add(string.Format("BarsPeriod : {0} {1}", BarsPeriod != null ? BarsPeriod.Value.ToString() : "N/A", BarsPeriod != null ? BarsPeriod.BarsPeriodType.ToString() : string.Empty));
lines.Add(string.Format("BarsRequiredToTrade: {0}", BarsRequiredToTrade));
lines.Add(string.Format("Calculate : {0}", Calculate));
lines.Add("--- Risk ---");
lines.Add(string.Format("DailyLossLimit : {0:C}", DailyLossLimit));
lines.Add(string.Format("MaxTradeRisk : {0:C}", MaxTradeRisk));
lines.Add(string.Format("MaxOpenPositions : {0}", MaxOpenPositions));
lines.Add(string.Format("RiskPerTrade : {0:C}", RiskPerTrade));
lines.Add(string.Format("RiskTier : {0}", RiskTier));
lines.Add(string.Format("MicroUpgradeThreshold: {0:C}", MicroUpgradeThreshold));
lines.Add("--- Trailing Drawdown ---");
lines.Add(string.Format("EnableTrailingDrawdown: {0}", EnableTrailingDrawdown));
lines.Add(string.Format("AccountStartingBalance: {0:C}", AccountStartingBalance));
lines.Add(string.Format("TrailingDrawdownAmount: {0:C}", TrailingDrawdownAmount));
lines.Add(string.Format("TrailingDrawdownHaltBuffer: {0:C}", TrailingDrawdownHaltBuffer));
lines.Add(string.Format("TrailingDrawdownLockOffset: {0:C}", TrailingDrawdownLockOffset));
lines.Add("--- Sizing ---");
lines.Add(string.Format("MinContracts : {0}", MinContracts));
lines.Add(string.Format("MaxContracts : {0}", MaxContracts));
lines.Add("--- Direction ---");
lines.Add(string.Format("EnableLongTrades : {0}", EnableLongTrades));
lines.Add(string.Format("EnableShortTrades : {0}", EnableShortTrades));
lines.Add("--- Controls ---");
lines.Add(string.Format("EnableKillSwitch : {0}", EnableKillSwitch));
lines.Add(string.Format("EnableVerboseLogging: {0}", EnableVerboseLogging));
lines.Add(string.Format("EnableStateTelemetry: {0}", EnableStateTelemetry));
lines.Add(string.Format("EnableEthTelemetry : {0}", EnableEthTelemetry));
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 ===");
return lines;
}
/// <summary>
/// Writes a settings export file to the same directory as the session log.
/// File is named settings_STRATEGYNAME_YYYYMMDD_HHmmss.txt.
/// Only writes when EnableVerboseLogging is true.
/// </summary>
private void WriteSettingsFile()
{
if (!EnableVerboseLogging) return;
try
{
string dir = ResolveLogDirectory(false, "settings export");
System.IO.Directory.CreateDirectory(dir);
string safeName = Name.Replace(" ", "_").Replace("/", "_").Replace("\\", "_");
string path = System.IO.Path.Combine(dir,
string.Format("settings_{0}_{1}.txt",
safeName,
DateTime.Now.ToString("yyyyMMdd_HHmmss")));
var lines = GetStrategySettingsLines();
System.IO.File.WriteAllLines(path, lines.ToArray());
Print(string.Format("[NT8-SDK] Settings exported: {0}", path));
FileLog(string.Format("SETTINGS FILE: {0}", path));
}
catch (Exception ex)
{
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;
var topLeftLines = new List<string>();
// 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";
topLeftLines.Add(regimeText);
}
}
}
// 2. Runner Mode Label - shows current runner mode
if (EnableRunner)
topLeftLines.Add("RUNNER: " + RunnerActivationMode.ToString());
AppendTopLeftDiagnosticLines(topLeftLines);
RemoveDrawObject("Diag_Regime");
RemoveDrawObject("Diag_Runner");
RemoveDrawObject("Diag_TradeTaken");
RemoveDrawObject("Diag_DailyCount");
if (topLeftLines.Count > 0)
Draw.TextFixed(this, "Diag_TopLeft", string.Join(Environment.NewLine, topLeftLines.ToArray()), TextPosition.TopLeft, Brushes.White, new SimpleFont("Arial", 10), Brushes.Black, Brushes.Black, 80);
else
RemoveDrawObject("Diag_TopLeft");
// 3. 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);
}
// 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);
}
RemoveDrawObject("Diag_Breakeven");
// 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);
}
/// <summary>
/// Allows derived strategies to add lines to the shared top-left diagnostics block.
/// </summary>
protected virtual void AppendTopLeftDiagnosticLines(List<string> lines)
{
}
private class TrailingDrawdownStatus
{
public string AccountName { get; set; }
public double Equity { get; set; }
public double Peak { get; set; }
public double LockedPeak { get; set; }
public bool Locked { get; set; }
public double ReferencePeak { get; set; }
public double HaltThreshold { get; set; }
public bool Breached { get; set; }
public DateTime Time { get; set; }
}
private class TrailingDrawdownAccountState
{
public double Peak { get; set; }
public double LockedPeak { get; set; }
public bool Locked { get; set; }
public bool Breached { get; set; }
public TrailingDrawdownAccountState(double startingBalance)
{
Peak = startingBalance;
LockedPeak = 0.0;
Locked = false;
Breached = false;
}
}
private class TrailingDrawdownMonitor
{
private static readonly object _instanceLock = new object();
private static TrailingDrawdownMonitor _instance;
public static TrailingDrawdownMonitor Instance
{
get
{
if (_instance == null)
{
lock (_instanceLock)
{
if (_instance == null)
_instance = new TrailingDrawdownMonitor();
}
}
return _instance;
}
}
private readonly object _lock;
private readonly Dictionary<string, TrailingDrawdownAccountState> _states;
private readonly Dictionary<string, List<NT8StrategyBase>> _strategiesByAccount;
private TrailingDrawdownMonitor()
{
_lock = new object();
_states = new Dictionary<string, TrailingDrawdownAccountState>();
_strategiesByAccount = new Dictionary<string, List<NT8StrategyBase>>();
}
public void RegisterStrategy(string accountName, NT8StrategyBase strategy)
{
if (string.IsNullOrEmpty(accountName) || strategy == null)
return;
lock (_lock)
{
List<NT8StrategyBase> strategies;
if (!_strategiesByAccount.TryGetValue(accountName, out strategies))
{
strategies = new List<NT8StrategyBase>();
_strategiesByAccount.Add(accountName, strategies);
}
if (!strategies.Contains(strategy))
strategies.Add(strategy);
}
}
public void UnregisterStrategy(string accountName, NT8StrategyBase strategy)
{
if (string.IsNullOrEmpty(accountName) || strategy == null)
return;
lock (_lock)
{
List<NT8StrategyBase> strategies;
if (_strategiesByAccount.TryGetValue(accountName, out strategies))
{
strategies.Remove(strategy);
if (strategies.Count == 0)
{
_strategiesByAccount.Remove(accountName);
_states.Remove(accountName);
}
}
}
}
public bool IsHalted(string accountName)
{
if (string.IsNullOrEmpty(accountName))
return false;
lock (_lock)
{
TrailingDrawdownAccountState state;
return _states.TryGetValue(accountName, out state) && state.Breached;
}
}
public TrailingDrawdownStatus UpdateEquity(string accountName, double equity, double startingBalance, double haltBuffer, double lockOffset, DateTime time)
{
if (string.IsNullOrEmpty(accountName))
throw new ArgumentNullException("accountName");
lock (_lock)
{
TrailingDrawdownAccountState state;
if (!_states.TryGetValue(accountName, out state))
{
state = new TrailingDrawdownAccountState(System.Math.Max(startingBalance, equity));
_states.Add(accountName, state);
}
if (equity > state.Peak)
state.Peak = equity;
if (!state.Locked && state.Peak >= startingBalance + lockOffset)
{
state.Locked = true;
state.LockedPeak = state.Peak;
}
double referencePeak = state.Locked ? state.LockedPeak : state.Peak;
double haltThreshold = referencePeak - haltBuffer;
if (equity <= haltThreshold)
state.Breached = true;
return new TrailingDrawdownStatus
{
AccountName = accountName,
Equity = equity,
Peak = state.Peak,
LockedPeak = state.LockedPeak,
Locked = state.Locked,
ReferencePeak = referencePeak,
HaltThreshold = haltThreshold,
Breached = state.Breached,
Time = time
};
}
}
public void FlattenRegisteredStrategies(string accountName, TrailingDrawdownStatus status)
{
List<NT8StrategyBase> strategies = new List<NT8StrategyBase>();
lock (_lock)
{
List<NT8StrategyBase> registered;
if (_strategiesByAccount.TryGetValue(accountName, out registered))
strategies.AddRange(registered);
}
foreach (NT8StrategyBase strategy in strategies)
{
if (strategy != null)
strategy.FlattenForTrailingDrawdown(status);
}
}
}
#region TASK-00a: Provenance Controls
/// <summary>
/// Generates a SHA256 hash of NinjaScriptProperty values plus stable settings-export fields 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"));
}
}
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>
/// 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 (_sessionId == null)
_sessionId = Guid.NewGuid().ToString();
var dir = ResolveLogDirectory(true, "session provenance");
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, RunnerMode resolvedMode)
{
if (State != State.Realtime)
return;
try
{
if (_sessionId == null)
_sessionId = Guid.NewGuid().ToString();
_tradeSequence++;
var dir = ResolveLogDirectory(true, "trade provenance");
Directory.CreateDirectory(dir);
var safeName = Name.Replace(" ", "_").Replace("/", "_").Replace("\\", "_");
var path = Path.Combine(dir, string.Format("trades_{0}_{1}.jsonl", safeName, DateTime.Now.ToString("yyyyMMdd")));
var json = TradeProvenanceSerializer.Serialize(
_sessionId,
_tradeSequence,
DateTime.UtcNow,
intent,
quantity,
atrStopTicks,
resolvedMode.ToString(),
GetRiskMode(intent),
GetDailyPnL(),
GetSessionTag(),
GetCodeVersionStamp());
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 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 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)
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
}
}