using System; using System.Collections.Generic; using System.IO; using NT8.Core.Calendar; using NT8.Core.Common.Interfaces; using NT8.Core.Common.Models; using NT8.Core.Indicators; using NT8.Core.Intelligence; using NT8.Core.Logging; using Newtonsoft.Json; namespace NT8.Strategies.Examples { /// /// Opening Range Breakout strategy with Phase 4 confluence and grade-aware intent metadata. /// public class SimpleORBStrategy : IStrategy { private readonly object _lock = new object(); private readonly int _openingRangeMinutes; private readonly double _stdDevMultiplier; private ILogger _logger; private StrategyConfig _config; private ConfluenceScorer _scorer; private GradeFilter _gradeFilter; private RiskModeManager _riskModeManager; private AVWAPCalculator _avwapCalculator; private VolumeProfileAnalyzer _volumeProfileAnalyzer; private List _factorCalculators; private DateTime _currentSessionDate; private DateTime _openingRangeStart; private DateTime _openingRangeEnd; private double _openingRangeHigh; private double _openingRangeLow; private bool _openingRangeReady; private bool _tradeTaken; private int _dailyTradeCount; private bool _breakoutBarSeen; private int _pendingBreakoutDirection; private int _consecutiveWins; private int _consecutiveLosses; private bool _dailyTradeCountPersistenceEnabled; private bool _dailyTradeCountPersistenceInitialized; private string _dailyTradeCountAccountName; private string _dailyTradeCountStrategyName; private string _dailyTradeCountLogDirectory; // GAP-006: Gate legacy bar-driven _tradeTaken re-arm for SIM-only mode private bool _enableBarBasedRearm = false; /// /// Gets or sets whether bar-driven _tradeTaken re-arm is enabled. /// Default is false — position-close re-arm is primary for live trading. /// public bool EnableBarBasedRearm { get { return _enableBarBasedRearm; } set { _enableBarBasedRearm = value; } } // GAP-010: Short-side regime filter private bool _enableShortTrendFilter = true; /// /// Gets or sets whether short trades are vetoed when AVWAP slope > 0 (bullish regime). /// Default is true — short trades are blocked in bullish regime. /// public bool EnableShortTrendFilter { get { return _enableShortTrendFilter; } set { _enableShortTrendFilter = value; } } // GAP-008: CME Holiday Guard private bool _enableCmeHolidayGuard = true; /// /// Gets or sets whether strategy skips ORB window on CME holidays. /// Default is true — strategy skips trading on CME holidays. /// public bool EnableCMEHolidayGuard { get { return _enableCmeHolidayGuard; } set { _enableCmeHolidayGuard = value; } } // GAP-009: ATR-based trailing stop private bool _enableAtrTrailing = false; /// /// Gets or sets whether runner trailing stop uses ATR instead of fixed RunnerTrailTicks. /// Default is false — uses fixed RunnerTrailTicks. /// public bool EnableATRTrailing { get { return _enableAtrTrailing; } set { _enableAtrTrailing = value; } } private int _atrTrailingPeriod = 14; /// /// Gets or sets ATR period for trailing stop calculation. /// Default is 14. /// public int ATRTrailingPeriod { get { return _atrTrailingPeriod; } set { _atrTrailingPeriod = value; } } private double _atrTrailingMultiplier = 2.0; /// /// Gets or sets multiplier applied to ATR value for trail distance. /// Default is 2.0. /// public double ATRTrailingMultiplier { get { return _atrTrailingMultiplier; } set { _atrTrailingMultiplier = value; } } private int _atrTrailingMinTicks = 8; /// /// Gets or sets minimum trail distance in ticks. /// Default is 8. /// public int ATRTrailingMinTicks { get { return _atrTrailingMinTicks; } set { _atrTrailingMinTicks = value; } } private int _atrTrailingMaxTicks = 60; /// /// Gets or sets maximum trail distance in ticks. /// Default is 60. /// public int ATRTrailingMaxTicks { get { return _atrTrailingMaxTicks; } set { _atrTrailingMaxTicks = value; } } /// /// Gets the current opening range high for chart diagnostics. /// public double OpeningRangeHigh { get { return _openingRangeHigh; } } /// /// Gets the current opening range low for chart diagnostics. /// public double OpeningRangeLow { get { return _openingRangeLow; } } /// /// Gets whether the opening range is ready for chart diagnostics. /// public bool OpeningRangeReady { get { return _openingRangeReady; } } /// /// Gets whether a breakout bar has been seen for chart diagnostics. /// public bool BreakoutBarSeen { get { return _breakoutBarSeen; } } /// /// Gets the pending breakout direction for chart diagnostics (1=Long, -1=Short, 0=None). /// public int PendingBreakoutDirection { get { return _pendingBreakoutDirection; } } /// /// Gets whether a trade has been taken for chart diagnostics. /// public bool TradeTaken { get { return _tradeTaken; } } /// /// Gets the opening range start time for chart diagnostics. /// public DateTime OpeningRangeStart { get { return _openingRangeStart; } } /// /// Gets the opening range end time for chart diagnostics. /// public DateTime OpeningRangeEnd { get { return _openingRangeEnd; } } /// /// Gets the current daily trade count for chart diagnostics. /// public int DailyTradeCount { get { return _dailyTradeCount; } } /// /// Gets the std dev multiplier for chart diagnostics. /// public double StdDevMultiplier { get { return _stdDevMultiplier; } } /// /// Gets the opening range minutes for chart diagnostics. /// public int OpeningRangeMinutes { get { return _openingRangeMinutes; } } /// /// Gets strategy metadata. /// public StrategyMetadata Metadata { get; private set; } /// /// Creates a new strategy with default ORB configuration. /// public SimpleORBStrategy() : this(30, 1.0) { } /// /// Creates a new strategy with custom ORB configuration. /// /// Opening range period in minutes. /// Breakout volatility multiplier. public SimpleORBStrategy(int openingRangeMinutes, double stdDevMultiplier) { if (openingRangeMinutes <= 0) throw new ArgumentException("openingRangeMinutes must be greater than zero", "openingRangeMinutes"); if (stdDevMultiplier <= 0.0) throw new ArgumentException("stdDevMultiplier must be greater than zero", "stdDevMultiplier"); _openingRangeMinutes = openingRangeMinutes; _stdDevMultiplier = stdDevMultiplier; _currentSessionDate = DateTime.MinValue; _openingRangeStart = DateTime.MinValue; _openingRangeEnd = DateTime.MinValue; _openingRangeHigh = Double.MinValue; _openingRangeLow = Double.MaxValue; _openingRangeReady = false; _tradeTaken = false; _dailyTradeCount = 0; _breakoutBarSeen = false; _pendingBreakoutDirection = 0; _consecutiveWins = 0; _consecutiveLosses = 0; _dailyTradeCountPersistenceEnabled = false; _dailyTradeCountPersistenceInitialized = false; _dailyTradeCountAccountName = string.Empty; _dailyTradeCountStrategyName = string.Empty; _dailyTradeCountLogDirectory = string.Empty; Metadata = new StrategyMetadata( "Simple ORB", "Opening Range Breakout strategy with confluence scoring", "2.0", "NT8 SDK Team", new string[] { "ES", "NQ", "YM" }, 20); } /// /// Initializes strategy dependencies. /// /// Strategy configuration. /// Market data provider. /// Logger instance. public void Initialize(StrategyConfig config, IMarketDataProvider dataProvider, ILogger logger) { if (logger == null) throw new ArgumentNullException("logger"); try { _logger = logger; _config = config; _scorer = new ConfluenceScorer(_logger, 500); _gradeFilter = new GradeFilter(); _riskModeManager = new RiskModeManager(_logger); _avwapCalculator = new AVWAPCalculator(AVWAPAnchorMode.Day, DateTime.UtcNow); _volumeProfileAnalyzer = new VolumeProfileAnalyzer(); _factorCalculators = new List(); _factorCalculators.Add(new OrbSetupFactorCalculator()); _factorCalculators.Add(new TrendAlignmentFactorCalculator()); _factorCalculators.Add(new VolatilityRegimeFactorCalculator()); _factorCalculators.Add(new TimeInSessionFactorCalculator()); _factorCalculators.Add(new ExecutionQualityFactorCalculator()); _factorCalculators.Add(new NarrowRangeFactorCalculator(_logger)); _factorCalculators.Add(new OrbRangeVsAtrFactorCalculator(_logger)); _factorCalculators.Add(new GapDirectionAlignmentCalculator(_logger)); _factorCalculators.Add(new BreakoutVolumeStrengthCalculator(_logger)); _factorCalculators.Add(new PriorDayCloseStrengthCalculator(_logger)); _logger.LogInformation( "SimpleORBStrategy initialized with OR period {0} minutes and multiplier {1:F2}", _openingRangeMinutes, _stdDevMultiplier); } catch (Exception ex) { if (_logger != null) _logger.LogError("SimpleORBStrategy Initialize failed: {0}", ex.Message); throw; } } /// /// Processes bar data and returns a trade intent when breakout and confluence criteria pass. /// /// Current bar. /// Strategy context. /// Trade intent when signal is accepted; otherwise null. public StrategyIntent OnBar(BarData bar, StrategyContext context) { if (bar == null) throw new ArgumentNullException("bar"); if (context == null) throw new ArgumentNullException("context"); try { lock (_lock) { EnsureInitialized(); ClearSignalRejection(context); UpdateRiskMode(context); UpdateConfluenceInputs(bar, context); DateTime thisSessionStart = context.Session != null ? context.Session.SessionStart : context.CurrentTime.Date.AddHours(9.5); // Guard: only reset when the TRADING DATE has changed, not just the session // start timestamp. Using trading date prevents mid-session resets caused by // _openingRangeStart holding a stale value from a previous day. DateTime thisTradingDate = thisSessionStart.Date; TimeSpan sessionStartTime = thisSessionStart.TimeOfDay; bool isValidRthSessionStart = sessionStartTime >= new TimeSpan(8, 0, 0) && sessionStartTime <= new TimeSpan(10, 30, 0); if (isValidRthSessionStart && thisTradingDate != _currentSessionDate) { ResetSession(thisSessionStart); if (context.CustomData != null && context.CustomData.ContainsKey("session_open_price")) context.CustomData.Remove("session_open_price"); } bool testMode = false; if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("TestMode")) { var tm = _config.Parameters["TestMode"]; if (tm is bool) testMode = (bool)tm; } // Only trade during RTH — bypassed in TestMode if (!testMode && (context.Session == null || !context.Session.IsRth)) { RecordSignalRejection(context, "RthGuard", string.Format("SessionIsRth={0}", context.Session != null ? context.Session.IsRth.ToString() : "null"), bar.Time); return null; } // GAP-008: CME Holiday Guard — skip ORB window on CME holidays if (!testMode && EnableCMEHolidayGuard) { if (CmeHolidayCalendar.ShouldSkipOrbWindow(bar.Time.Date)) { if (_logger != null) _logger.LogInformation("Skipping ORB window on CME holiday: {0:yyyy-MM-dd}", bar.Time.Date); RecordSignalRejection(context, "CmeHoliday", string.Format("Date={0:yyyy-MM-dd}", bar.Time.Date), bar.Time); return null; } } // In TestMode: skip ORB window check so signal can fire any time. // Synthetic ORB range is set ONCE from the first bar seen. // _tradeTaken is NOT reset every bar — normal re-entry blocking applies, // so only one trade fires per strategy enable. This prevents the // infinite re-entry loop where every bar generates a new signal. if (testMode) { if (!_openingRangeReady) { _openingRangeHigh = bar.High; _openingRangeLow = bar.Low; _openingRangeReady = true; _tradeTaken = false; } } else { if (bar.Time <= _openingRangeEnd) { UpdateOpeningRange(bar); RecordSignalRejection(context, "OrbRangeNotEstablished", string.Format("ORB window still building start={0:HH:mm} end={1:HH:mm} high={2:F2} low={3:F2}", _openingRangeStart, _openingRangeEnd, _openingRangeHigh, _openingRangeLow), bar.Time); return null; } if (!_openingRangeReady) { if (_openingRangeHigh > _openingRangeLow) _openingRangeReady = true; else { RecordSignalRejection(context, "OrbRangeNotEstablished", string.Format("Invalid ORB high={0:F2} low={1:F2}", _openingRangeHigh, _openingRangeLow), bar.Time); return null; } } } if (_logger != null && _openingRangeReady) { _logger.LogDebug( "ORB ready: High={0:F2} Low={1:F2} Range={2:F2} TradeTaken={3}", _openingRangeHigh, _openingRangeLow, _openingRangeHigh - _openingRangeLow, _tradeTaken); } int maxDailyTrades = 1; if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("MaxDailyTrades")) { var mdv = _config.Parameters["MaxDailyTrades"]; if (mdv is int) maxDailyTrades = (int)mdv; } if (_dailyTradeCount >= maxDailyTrades) { if (_logger != null) _logger.LogInformation( "MaxDailyTrades reached ({0}/{1}) for session {2:yyyy-MM-dd}; rejecting signal at {3:yyyy-MM-dd HH:mm}; symbol={4}", _dailyTradeCount, maxDailyTrades, _currentSessionDate, bar.Time, context.Symbol); RecordSignalRejection(context, "MaxDailyTrades", string.Format("DailyTradeCount={0} MaxDailyTrades={1} Session={2:yyyy-MM-dd} Symbol={3}", _dailyTradeCount, maxDailyTrades, _currentSessionDate, context.Symbol), bar.Time); return null; } EnsureDailyTradeCountPersistence(context, maxDailyTrades); if (_dailyTradeCount >= maxDailyTrades) { if (_logger != null) _logger.LogInformation( "MaxDailyTrades reached ({0}/{1}) for session {2:yyyy-MM-dd}; rejecting signal at {3:yyyy-MM-dd HH:mm}; symbol={4}", _dailyTradeCount, maxDailyTrades, _currentSessionDate, bar.Time, context.Symbol); RecordSignalRejection(context, "MaxDailyTrades", string.Format("DailyTradeCount={0} MaxDailyTrades={1} Session={2:yyyy-MM-dd} Symbol={3}", _dailyTradeCount, maxDailyTrades, _currentSessionDate, context.Symbol), bar.Time); return null; } // GAP-006: Bar-driven re-arm only when EnableBarBasedRearm is true // Default is false for live trading; position-close re-arm is now primary // After a trade completes and we are below MaxDailyTrades, reset the // pullback confirmation state so a fresh breakout can be detected. if (EnableBarBasedRearm) { if (_tradeTaken && _dailyTradeCount < maxDailyTrades) { _tradeTaken = false; _breakoutBarSeen = false; _pendingBreakoutDirection = 0; } } var openingRange = _openingRangeHigh - _openingRangeLow; var volatilityBuffer = openingRange * (_stdDevMultiplier - 1.0); if (volatilityBuffer < 0.0) volatilityBuffer = 0.0; var longTrigger = _openingRangeHigh + volatilityBuffer; var shortTrigger = _openingRangeLow - volatilityBuffer; // Pullback confirmation: two-bar entry filter. // Bar 1 (breakout bar): price closes beyond ORB level — set flag, do NOT enter. // Bar 2 (confirmation bar): price closes beyond ORB level again — enter. // If price pulls back below the ORB level between bar 1 and bar 2, reset. // TestMode bypasses confirmation so unit tests using single-bar injection work. StrategyIntent candidate = null; bool longBreak = bar.Close > longTrigger; bool shortBreak = bar.Close < shortTrigger; if (testMode) { if (longBreak) candidate = CreateIntent(context.Symbol, OrderSide.Buy, openingRange, bar.Close); else if (shortBreak) candidate = CreateIntent(context.Symbol, OrderSide.Sell, openingRange, bar.Close); } else if (!_breakoutBarSeen) { if (longBreak) { _breakoutBarSeen = true; _pendingBreakoutDirection = 1; if (_logger != null) _logger.LogInformation( "Pullback confirmation: breakout bar Long @ {0:F2} - waiting for confirmation bar", bar.Close); } else if (shortBreak) { _breakoutBarSeen = true; _pendingBreakoutDirection = -1; if (_logger != null) _logger.LogInformation( "Pullback confirmation: breakout bar Short @ {0:F2} - waiting for confirmation bar", bar.Close); } } else { if (_pendingBreakoutDirection == 1) { if (bar.Close > longTrigger) { candidate = CreateIntent(context.Symbol, OrderSide.Buy, openingRange, bar.Close); if (_logger != null) _logger.LogInformation( "Pullback confirmation: Long confirmed @ {0:F2}", bar.Close); } else { _breakoutBarSeen = false; _pendingBreakoutDirection = 0; if (_logger != null) _logger.LogInformation( "Pullback confirmation: Long breakout failed - pulled back to {0:F2}, reset", bar.Close); } } else if (_pendingBreakoutDirection == -1) { if (bar.Close < shortTrigger) { candidate = CreateIntent(context.Symbol, OrderSide.Sell, openingRange, bar.Close); if (_logger != null) _logger.LogInformation( "Pullback confirmation: Short confirmed @ {0:F2}", bar.Close); } else { _breakoutBarSeen = false; _pendingBreakoutDirection = 0; if (_logger != null) _logger.LogInformation( "Pullback confirmation: Short breakout failed - pulled back to {0:F2}, reset", bar.Close); } } } if (candidate == null) { RecordSignalRejection(context, "OrbRangeNotEstablished", string.Format("No confirmed breakout close={0:F2} longTrigger={1:F2} shortTrigger={2:F2} breakoutBarSeen={3} pendingDirection={4}", bar.Close, longTrigger, shortTrigger, _breakoutBarSeen, _pendingBreakoutDirection), bar.Time); return null; } AttachDailyBarContext(candidate, bar, context); // Hard veto: Trend against trade direction is a disqualifying condition. // AVWAP trend alignment is checked before confluence scoring to prevent // high scores from other factors masking a directionally broken setup. if (_config != null && _config.Parameters != null) { if (context.CustomData != null && context.CustomData.ContainsKey("avwap_slope")) { var slope = context.CustomData["avwap_slope"]; if (slope is double) { double slopeVal = (double)slope; bool longTrade = candidate.Side == OrderSide.Buy; bool trendAgainst = (longTrade && slopeVal < 0) || (!longTrade && slopeVal > 0); if (trendAgainst) { // GAP-010: Short trend filter is configurable // For shorts in bullish regime (slope > 0), respect EnableShortTrendFilter if (!longTrade && slopeVal > 0) { bool enableShortFilter = true; if (_config.Parameters.ContainsKey("EnableShortTrendFilter")) { var esf = _config.Parameters["EnableShortTrendFilter"]; if (esf is bool) enableShortFilter = (bool)esf; } if (!enableShortFilter) { // Filter disabled - allow the short despite bullish regime } else { if (_logger != null) _logger.LogInformation("Short vetoed by regime filter: AVWAP slope {0:F4} > 0 (bullish)", slopeVal); RecordSignalRejection(context, "RegimeVeto", string.Format("Regime veto before score; Side={0} AVWAPSlope={1:F4} EnableShortTrendFilter=True", candidate.Side, slopeVal), bar.Time); return null; } } else if (longTrade && slopeVal < 0) { // Long veto in bearish regime - always enforced (no parameter for this yet) if (_logger != null) _logger.LogInformation("Trade vetoed: AVWAP slope {0:F4} against {1} direction", slopeVal, candidate.Side); RecordSignalRejection(context, "RegimeVeto", string.Format("Regime veto before score; Side={0} AVWAPSlope={1:F4}", candidate.Side, slopeVal), bar.Time); return null; } } } } } var score = _scorer.CalculateScore(candidate, context, bar, _factorCalculators); var mode = _riskModeManager.GetCurrentMode(); int minGradeValue = 5; if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("MinTradeGrade")) { var mgv = _config.Parameters["MinTradeGrade"]; if (mgv is int) minGradeValue = (int)mgv; } TradeGrade minGrade = (TradeGrade)minGradeValue; if ((int)score.Grade < (int)minGrade) { if (_logger != null) _logger.LogInformation( "SimpleORBStrategy filtered by grade: Score={0:F3} Grade={1} MinGrade={2}", score.WeightedScore, score.Grade, minGrade); RecordSignalRejection(context, "GradeFilter", string.Format("Score={0:F3} Grade={1} MinTradeGrade={2} Factors={3}", score.WeightedScore, score.Grade, minGrade, FormatFactorBreakdown(score)), bar.Time); return null; } var gradeMultiplier = _gradeFilter.GetSizeMultiplier(score.Grade, mode); var modeConfig = _riskModeManager.GetModeConfig(mode); var combinedMultiplier = gradeMultiplier * modeConfig.SizeMultiplier; candidate.Confidence = score.WeightedScore; candidate.Reason = string.Format("{0}; grade={1}; mode={2}", candidate.Reason, score.Grade, mode); candidate.Metadata["confluence_score"] = score; candidate.Metadata["confluence_weighted_score"] = score.WeightedScore; candidate.Metadata["trade_grade"] = score.Grade.ToString(); candidate.Metadata["risk_mode"] = mode.ToString(); candidate.Metadata["grade_multiplier"] = gradeMultiplier; candidate.Metadata["mode_multiplier"] = modeConfig.SizeMultiplier; candidate.Metadata["combined_multiplier"] = combinedMultiplier; _tradeTaken = true; if (ShouldIncrementDailyTradeCount(context)) { _dailyTradeCount++; PersistDailyTradeCount(context); } if (_logger != null) _logger.LogDebug( "SimpleORBStrategy flag set: tradeTaken={0} dailyCount={1} session={2:yyyy-MM-dd}; bar={3:yyyy-MM-dd HH:mm}; side={4}; symbol={5}", _tradeTaken, _dailyTradeCount, _currentSessionDate, bar.Time, candidate.Side, candidate.Symbol); if (_logger != null && score.Factors != null) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("Factors: "); foreach (ConfluenceFactor f in score.Factors) sb.Append(string.Format("{0}={1:F2}({2}) ", f.Type, f.Score, f.Weight.ToString("F2"))); _logger.LogInformation("Confluence detail: {0}", sb.ToString().TrimEnd()); } _logger.LogInformation( "SimpleORBStrategy accepted intent for {0}: Side={1}, Grade={2}, Mode={3}, Score={4:F3}, Mult={5:F2}", candidate.Symbol, candidate.Side, score.Grade, mode, score.WeightedScore, combinedMultiplier); return candidate; } } catch (Exception ex) { if (_logger != null) _logger.LogError("SimpleORBStrategy OnBar failed: {0}", ex.Message); throw; } } /// /// Processes tick data. This strategy does not use tick-level logic. /// /// Tick data. /// Strategy context. /// Always null for this strategy. public StrategyIntent OnTick(TickData tick, StrategyContext context) { return null; } /// /// Returns current strategy parameters. /// /// Parameter map. public Dictionary GetParameters() { lock (_lock) { var parameters = new Dictionary(); parameters.Add("opening_range_minutes", _openingRangeMinutes); parameters.Add("std_dev_multiplier", _stdDevMultiplier); return parameters; } } /// /// Updates strategy parameters. /// /// Parameter map. public void SetParameters(Dictionary parameters) { if (parameters == null) return; // force_session_reset: clear _tradeTaken and ORB state so a fresh live session // can trade even if historical replay set _tradeTaken before going realtime. if (parameters.ContainsKey("force_session_reset")) { var val = parameters["force_session_reset"]; if (val is bool && (bool)val) { lock (_lock) { _tradeTaken = false; _dailyTradeCount = 0; _breakoutBarSeen = false; _pendingBreakoutDirection = 0; _openingRangeReady = false; _openingRangeHigh = Double.MinValue; _openingRangeLow = Double.MaxValue; if (_logger != null) _logger.LogInformation("ForceSessionReset: _tradeTaken cleared, ORB state reset for live session"); } } } ApplyDailyTradeCountPersistenceParameters(parameters); // Retained for compatibility with older adapters. Position-flat state must not // reset session-scoped trade eligibility; ResetSession owns the daily reset. if (parameters.ContainsKey("clear_trade_taken")) { var val = parameters["clear_trade_taken"]; if (val is bool && (bool)val) { lock (_lock) { _breakoutBarSeen = false; _pendingBreakoutDirection = 0; if (_logger != null) _logger.LogInformation("Position flat: MaxDailyTrades count retained until session rollover"); } } } // GAP-006: EnableBarBasedRearm parameter from NT8 adapter if (parameters.ContainsKey("EnableBarBasedRearm")) { var val = parameters["EnableBarBasedRearm"]; if (val is bool) { _enableBarBasedRearm = (bool)val; if (_logger != null) _logger.LogInformation("EnableBarBasedRearm set to {0}", _enableBarBasedRearm); } } // GAP-010: EnableShortTrendFilter parameter from NT8 adapter if (parameters.ContainsKey("EnableShortTrendFilter")) { var val = parameters["EnableShortTrendFilter"]; if (val is bool) { _enableShortTrendFilter = (bool)val; if (_logger != null) _logger.LogInformation("EnableShortTrendFilter set to {0}", _enableShortTrendFilter); } } // GAP-008: EnableCMEHolidayGuard parameter from NT8 adapter if (parameters.ContainsKey("EnableCMEHolidayGuard")) { var val = parameters["EnableCMEHolidayGuard"]; if (val is bool) { _enableCmeHolidayGuard = (bool)val; if (_logger != null) _logger.LogInformation("EnableCMEHolidayGuard set to {0}", _enableCmeHolidayGuard); } } // GAP-009: EnableATRTrailing parameter from NT8 adapter if (parameters.ContainsKey("EnableATRTrailing")) { var val = parameters["EnableATRTrailing"]; if (val is bool) { _enableAtrTrailing = (bool)val; if (_logger != null) _logger.LogInformation("EnableATRTrailing set to {0}", _enableAtrTrailing); } } if (parameters.ContainsKey("ATRTrailingPeriod")) { var val = parameters["ATRTrailingPeriod"]; if (val is int) { _atrTrailingPeriod = (int)val; if (_logger != null) _logger.LogInformation("ATRTrailingPeriod set to {0}", _atrTrailingPeriod); } } if (parameters.ContainsKey("ATRTrailingMultiplier")) { var val = parameters["ATRTrailingMultiplier"]; if (val is double) { _atrTrailingMultiplier = (double)val; if (_logger != null) _logger.LogInformation("ATRTrailingMultiplier set to {0}", _atrTrailingMultiplier); } } if (parameters.ContainsKey("ATRTrailingMinTicks")) { var val = parameters["ATRTrailingMinTicks"]; if (val is int) { _atrTrailingMinTicks = (int)val; if (_logger != null) _logger.LogInformation("ATRTrailingMinTicks set to {0}", _atrTrailingMinTicks); } } if (parameters.ContainsKey("ATRTrailingMaxTicks")) { var val = parameters["ATRTrailingMaxTicks"]; if (val is int) { _atrTrailingMaxTicks = (int)val; if (_logger != null) _logger.LogInformation("ATRTrailingMaxTicks set to {0}", _atrTrailingMaxTicks); } } } private void EnsureInitialized() { if (_logger == null) throw new InvalidOperationException("Strategy must be initialized before OnBar processing"); if (_scorer == null || _gradeFilter == null || _riskModeManager == null) throw new InvalidOperationException("Intelligence components are not initialized"); } private void UpdateRiskMode(StrategyContext context) { var dailyPnl = 0.0; if (context.Account != null) dailyPnl = context.Account.DailyPnL; _riskModeManager.UpdateRiskMode(dailyPnl, _consecutiveWins, _consecutiveLosses); } private void UpdateConfluenceInputs(BarData bar, StrategyContext context) { _avwapCalculator.Update(bar.Close, bar.Volume); var avwap = _avwapCalculator.GetCurrentValue(); var avwapSlope = _avwapCalculator.GetSlope(10); if (context.CustomData == null) context.CustomData = new Dictionary(); // Use pre-calculated intraday average from daily bar context when available. // Fall back to current bar volume only if daily context is not yet populated. double avgVol = (double)bar.Volume; double normalAtr = bar.High - bar.Low; if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("daily_bars")) { var src = _config.Parameters["daily_bars"]; if (src is DailyBarContext) { DailyBarContext dc = (DailyBarContext)src; if (dc.AvgIntradayBarVolume > 0.0) avgVol = dc.AvgIntradayBarVolume; // Use 10-day average daily range as the volatility baseline. if (dc.Count >= 5 && dc.Highs != null && dc.Lows != null) { double sumRanges = 0.0; int lookback = Math.Min(10, dc.Count - 1); int start = dc.Count - 1 - lookback; int end = dc.Count - 2; for (int i = start; i <= end; i++) sumRanges += dc.Highs[i] - dc.Lows[i]; if (lookback > 0) normalAtr = sumRanges / lookback; } } } context.CustomData["current_bar"] = bar; context.CustomData["avwap"] = avwap; context.CustomData["avwap_slope"] = avwapSlope; context.CustomData["trend_confirm_long"] = avwapSlope > 0.0 ? 1.0 : 0.0; context.CustomData["trend_confirm_short"] = avwapSlope < 0.0 ? 1.0 : 0.0; context.CustomData["trend_confirm"] = ResolveTrendConfirmForTelemetry(bar, avwapSlope); context.CustomData["current_atr"] = Math.Max(0.01, bar.High - bar.Low); context.CustomData["normal_atr"] = Math.Max(0.01, normalAtr); context.CustomData["recent_execution_quality"] = 0.8; context.CustomData["avg_volume"] = avgVol; // Track the first bar open of the RTH session as the session open price. // Only set once per session (when session_open_price is not yet in custom data). if (!context.CustomData.ContainsKey("session_open_price")) { context.CustomData["session_open_price"] = bar.Open; } } private double ResolveTrendConfirmForTelemetry(BarData bar, double avwapSlope) { int direction = _pendingBreakoutDirection; if (direction == 0 && _openingRangeReady) { double openingRange = _openingRangeHigh - _openingRangeLow; double volatilityBuffer = openingRange * (_stdDevMultiplier - 1.0); if (volatilityBuffer < 0.0) volatilityBuffer = 0.0; if (bar.Close > _openingRangeHigh + volatilityBuffer) direction = 1; else if (bar.Close < _openingRangeLow - volatilityBuffer) direction = -1; } if (direction < 0) return avwapSlope < 0.0 ? 1.0 : 0.0; return avwapSlope > 0.0 ? 1.0 : 0.0; } private void ResetSession(DateTime sessionStart) { _currentSessionDate = sessionStart.Date; _openingRangeStart = sessionStart; _openingRangeEnd = sessionStart.AddMinutes(_openingRangeMinutes); _openingRangeHigh = Double.MinValue; _openingRangeLow = Double.MaxValue; _openingRangeReady = false; _tradeTaken = false; _dailyTradeCount = 0; _dailyTradeCountPersistenceInitialized = false; _breakoutBarSeen = false; _pendingBreakoutDirection = 0; if (_logger != null) _logger.LogInformation( "Session reset: Date={0:yyyy-MM-dd} ORB window={1:HH:mm}-{2:HH:mm}", _currentSessionDate, _openingRangeStart, _openingRangeEnd); } private void UpdateOpeningRange(BarData bar) { if (bar.High > _openingRangeHigh) _openingRangeHigh = bar.High; if (bar.Low < _openingRangeLow) _openingRangeLow = bar.Low; } private void RecordSignalRejection(StrategyContext context, string reason, string detail, DateTime barTime) { if (context == null) return; if (context.CustomData == null) context.CustomData = new Dictionary(); context.CustomData["signal_reject_reason"] = reason; context.CustomData["signal_reject_detail"] = detail; context.CustomData["signal_reject_bar"] = barTime; context.CustomData["signal_reject_line"] = string.Format("REJECT: reason={0} detail={1} bar={2:yyyy-MM-dd HH:mm:ss}", reason, detail, barTime); } private void ApplyDailyTradeCountPersistenceParameters(Dictionary parameters) { if (parameters.ContainsKey("daily_trade_count_persistence_enabled")) { var enabled = parameters["daily_trade_count_persistence_enabled"]; if (enabled is bool) _dailyTradeCountPersistenceEnabled = (bool)enabled; } if (parameters.ContainsKey("daily_trade_count_account")) _dailyTradeCountAccountName = Convert.ToString(parameters["daily_trade_count_account"]); if (parameters.ContainsKey("daily_trade_count_strategy_name")) _dailyTradeCountStrategyName = Convert.ToString(parameters["daily_trade_count_strategy_name"]); if (parameters.ContainsKey("daily_trade_count_log_directory")) _dailyTradeCountLogDirectory = Convert.ToString(parameters["daily_trade_count_log_directory"]); } private void EnsureDailyTradeCountPersistence(StrategyContext context, int maxDailyTrades) { if (!ShouldUseDailyTradeCountPersistence(context)) return; if (_dailyTradeCountPersistenceInitialized) return; _dailyTradeCountPersistenceInitialized = true; string path = GetDailyTradeCountFilePath(context); if (string.IsNullOrEmpty(path)) return; try { if (File.Exists(path)) { DailyTradeCountState state = JsonConvert.DeserializeObject(File.ReadAllText(path)); DateTime persistedDate; if (state != null && DateTime.TryParse(state.trading_date, out persistedDate)) { if (persistedDate.Date == _currentSessionDate.Date) { _dailyTradeCount = state.daily_trade_count; if (_logger != null) _logger.LogInformation("DAILY_TRADE_COUNT restored: date={0:yyyy-MM-dd} count={1} max={2}", _currentSessionDate, _dailyTradeCount, maxDailyTrades); return; } } } } catch (Exception ex) { if (_logger != null) _logger.LogWarning("DAILY_TRADE_COUNT warning: could not read persisted count; starting at zero. Error={0}", ex.Message); } _dailyTradeCount = 0; PersistDailyTradeCount(context); if (_logger != null) _logger.LogInformation("DAILY_TRADE_COUNT reset: new trading date {0:yyyy-MM-dd}", _currentSessionDate); } private void PersistDailyTradeCount(StrategyContext context) { if (!ShouldUseDailyTradeCountPersistence(context)) return; try { string path = GetDailyTradeCountFilePath(context); if (string.IsNullOrEmpty(path)) return; string dir = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); DailyTradeCountState state = new DailyTradeCountState(); state.trading_date = _currentSessionDate.ToString("yyyy-MM-dd"); state.daily_trade_count = _dailyTradeCount; state.account = ResolveDailyTradeCountAccountName(); state.strategy_name = ResolveDailyTradeCountStrategyName(); state.symbol = context != null ? context.Symbol : ResolveDailyTradeCountSymbol(); File.WriteAllText(path, JsonConvert.SerializeObject(state, Formatting.Indented)); } catch (Exception ex) { if (_logger != null) _logger.LogWarning("DAILY_TRADE_COUNT warning: could not write persisted count. Error={0}", ex.Message); } } private bool ShouldUseDailyTradeCountPersistence(StrategyContext context) { if (!_dailyTradeCountPersistenceEnabled) return false; if (context == null || context.Account == null) return false; if (string.IsNullOrEmpty(ResolveDailyTradeCountAccountName())) return false; return true; } private string GetDailyTradeCountFilePath(StrategyContext context) { string dir = ResolveDailyTradeCountLogDirectory(); string safeAccount = MakeSafeFileName(ResolveDailyTradeCountAccountName()); string safeStrategy = MakeSafeFileName(ResolveDailyTradeCountStrategyName()); return Path.Combine(dir, string.Format("daily_trade_count_{0}_{1}.json", safeAccount, safeStrategy)); } private string ResolveDailyTradeCountLogDirectory() { if (!string.IsNullOrEmpty(_dailyTradeCountLogDirectory)) return _dailyTradeCountLogDirectory; return Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "NinjaTrader 8", "log", "nt8-sdk"); } private string ResolveDailyTradeCountAccountName() { if (!string.IsNullOrEmpty(_dailyTradeCountAccountName)) return _dailyTradeCountAccountName; if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("daily_trade_count_account")) return Convert.ToString(_config.Parameters["daily_trade_count_account"]); return string.Empty; } private string ResolveDailyTradeCountStrategyName() { if (!string.IsNullOrEmpty(_dailyTradeCountStrategyName)) return _dailyTradeCountStrategyName; if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("daily_trade_count_strategy_name")) return Convert.ToString(_config.Parameters["daily_trade_count_strategy_name"]); return Metadata != null ? Metadata.Name : "SimpleORBStrategy"; } private string ResolveDailyTradeCountSymbol() { if (_config != null && !string.IsNullOrEmpty(_config.Symbol)) return _config.Symbol; return string.Empty; } private string MakeSafeFileName(string value) { if (string.IsNullOrEmpty(value)) return "value"; char[] invalid = Path.GetInvalidFileNameChars(); System.Text.StringBuilder builder = new System.Text.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 class DailyTradeCountState { public string trading_date { get; set; } public int daily_trade_count { get; set; } public string account { get; set; } public string strategy_name { get; set; } public string symbol { get; set; } } private bool ShouldIncrementDailyTradeCount(StrategyContext context) { if (context == null || context.CustomData == null) return true; if (!context.CustomData.ContainsKey("AllowDailyTradeCountIncrement")) return true; object value = context.CustomData["AllowDailyTradeCountIncrement"]; if (value is bool) return (bool)value; return true; } private void ClearSignalRejection(StrategyContext context) { if (context == null || context.CustomData == null) return; if (context.CustomData.ContainsKey("signal_reject_reason")) context.CustomData.Remove("signal_reject_reason"); if (context.CustomData.ContainsKey("signal_reject_detail")) context.CustomData.Remove("signal_reject_detail"); if (context.CustomData.ContainsKey("signal_reject_bar")) context.CustomData.Remove("signal_reject_bar"); if (context.CustomData.ContainsKey("signal_reject_line")) context.CustomData.Remove("signal_reject_line"); } private string FormatFactorBreakdown(ConfluenceScore score) { if (score == null || score.Factors == null) return "none"; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (ConfluenceFactor factor in score.Factors) { if (sb.Length > 0) sb.Append(";"); sb.Append(string.Format("{0}={1:F2}x{2:F2}", factor.Type, factor.Score, factor.Weight)); } return sb.Length > 0 ? sb.ToString() : "none"; } private StrategyIntent CreateIntent(string symbol, OrderSide side, double openingRange, double lastPrice) { var stopTicks = _config != null && _config.Parameters.ContainsKey("StopTicks") ? (int)_config.Parameters["StopTicks"] : 8; int baseTargetTicks = _config != null && _config.Parameters.ContainsKey("TargetTicks") ? (int)_config.Parameters["TargetTicks"] : 16; var metadata = new Dictionary(); metadata.Add("orb_high", _openingRangeHigh); metadata.Add("orb_low", _openingRangeLow); metadata.Add("orb_range", openingRange); double tickSize = 0.25; if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("TickSize")) { var tickValue = _config.Parameters["TickSize"]; if (tickValue is double) tickSize = (double)tickValue; else if (tickValue is decimal) tickSize = (double)(decimal)tickValue; else if (tickValue is float) tickSize = (double)(float)tickValue; } if (tickSize <= 0.0) tickSize = 0.25; // Scale target dynamically based on ORB range vs average daily range. // Tight ORBs (< 20% of daily ATR) leave the most room — extend target. // Wide ORBs (> 50% of daily ATR) have consumed range — keep target tight. // Requires daily bar context with at least 5 bars; falls back to base target otherwise. int targetTicks = baseTargetTicks; if (_config != null && _config.Parameters != null && _config.Parameters.ContainsKey("daily_bars")) { var dailySrc = _config.Parameters["daily_bars"]; if (dailySrc is DailyBarContext) { DailyBarContext dc = (DailyBarContext)dailySrc; if (dc.Count >= 5 && dc.Highs != null && dc.Lows != null && tickSize > 0.0) { double sumAtr = 0.0; int lookback = Math.Min(10, dc.Count - 1); int start = dc.Count - 1 - lookback; int end = dc.Count - 2; for (int i = start; i <= end; i++) sumAtr += dc.Highs[i] - dc.Lows[i]; double avgDailyRange = lookback > 0 ? sumAtr / lookback : 0.0; double orbRangePoints = openingRange; double ratio = avgDailyRange > 0.0 ? orbRangePoints / avgDailyRange : 0.5; // Ratio tiers map to target multipliers: // <= 0.20 (tight ORB) → 1.75x (28 ticks on 16-tick base) // <= 0.30 → 1.50x (24 ticks) // <= 0.45 → 1.25x (20 ticks) // <= 0.60 → 1.00x (16 ticks — base, no change) // > 0.60 (wide ORB) → 0.75x (12 ticks — tighten) double multiplier; if (ratio <= 0.20) multiplier = 1.75; else if (ratio <= 0.30) multiplier = 1.50; else if (ratio <= 0.45) multiplier = 1.25; else if (ratio <= 0.60) multiplier = 1.00; else multiplier = 0.75; targetTicks = (int)Math.Round(baseTargetTicks * multiplier); // Enforce hard floor of stopTicks + 4 (minimum 1:1 R plus 4 ticks) int minTarget = stopTicks + 4; if (targetTicks < minTarget) targetTicks = minTarget; } } } if (_logger != null && targetTicks != baseTargetTicks) _logger.LogInformation( "Dynamic target: base={0} adjusted={1} (ORB/ATR scaling)", baseTargetTicks, targetTicks); var orbRangeTicks = openingRange / tickSize; metadata.Add("orb_range_ticks", orbRangeTicks); metadata.Add("trigger_price", lastPrice); metadata.Add("multiplier", _stdDevMultiplier); metadata.Add("opening_range_start", _openingRangeStart); metadata.Add("opening_range_end", _openingRangeEnd); metadata.Add("base_target_ticks", baseTargetTicks); metadata.Add("dynamic_target_ticks", targetTicks); return new StrategyIntent( symbol, side, OrderType.Market, null, stopTicks, targetTicks, 0.75, "ORB breakout signal", metadata); } private void AttachDailyBarContext(StrategyIntent intent, BarData bar, StrategyContext context) { if (intent == null || intent.Metadata == null) return; if (_config == null || _config.Parameters == null || !_config.Parameters.ContainsKey("daily_bars")) return; var source = _config.Parameters["daily_bars"]; if (!(source is DailyBarContext)) return; DailyBarContext baseContext = (DailyBarContext)source; DailyBarContext daily = baseContext; daily.TradeDirection = intent.Side == OrderSide.Buy ? 1 : -1; daily.BreakoutBarVolume = (double)bar.Volume; double todayOpen = bar.Open; if (context != null && context.CustomData != null && context.CustomData.ContainsKey("session_open_price")) { object sop = context.CustomData["session_open_price"]; if (sop is double) todayOpen = (double)sop; } daily.TodayOpen = todayOpen; if (context != null && context.CustomData != null && context.CustomData.ContainsKey("avg_volume")) { var avg = context.CustomData["avg_volume"]; if (avg is double) daily.AvgIntradayBarVolume = (double)avg; else if (avg is float) daily.AvgIntradayBarVolume = (double)(float)avg; else if (avg is int) daily.AvgIntradayBarVolume = (double)(int)avg; else if (avg is long) daily.AvgIntradayBarVolume = (double)(long)avg; } // orb_range_ticks is set in CreateIntent() and preserved here. if (intent.Metadata != null && intent.Metadata.ContainsKey("orb_range_ticks")) { daily.OrbRangeTicks = (double)intent.Metadata["orb_range_ticks"]; } intent.Metadata["daily_bars"] = daily; } /// /// Returns diagnostic state for chart visualization. /// Called by NT8 adapter to draw chart diagnostics. /// /// Diagnostic state object. public Dictionary GetDiagnostics() { var diag = new Dictionary(); diag.Add("openingRangeHigh", _openingRangeHigh); diag.Add("openingRangeLow", _openingRangeLow); diag.Add("openingRangeReady", _openingRangeReady); diag.Add("breakoutBarSeen", _breakoutBarSeen); diag.Add("pendingBreakoutDirection", _pendingBreakoutDirection); diag.Add("tradeTaken", _tradeTaken); diag.Add("openingRangeStart", _openingRangeStart); diag.Add("openingRangeEnd", _openingRangeEnd); diag.Add("dailyTradeCount", _dailyTradeCount); diag.Add("stdDevMultiplier", _stdDevMultiplier); diag.Add("openingRangeMinutes", _openingRangeMinutes); return diag; } /// /// Returns a JSON snapshot of internal strategy state for provenance tracking. /// /// JSON string of internal state. public string GetProvenanceSnapshot() { try { string sessionTag = "UNKNOWN"; try { if (_currentSessionDate != DateTime.MinValue) { if (CmeHolidayCalendar.IsHoliday(_currentSessionDate)) sessionTag = "HOLIDAY"; else if (CmeHolidayCalendar.IsEarlyClose(_currentSessionDate)) sessionTag = "EARLY_CLOSE"; else sessionTag = "RTH_ORB"; // SimpleORBStrategy only trades RTH } } catch { } var snapshot = new Dictionary { { "tradeTaken", _tradeTaken }, { "dailyTradeCount", _dailyTradeCount }, { "openingRangeHigh", _openingRangeHigh }, { "openingRangeLow", _openingRangeLow }, { "currentSessionDate", _currentSessionDate.ToString("yyyy-MM-dd") }, { "breakoutBarSeen", _breakoutBarSeen }, { "pendingBreakoutDirection", _pendingBreakoutDirection }, { "openingRangeStart", _openingRangeStart.ToString("yyyy-MM-dd HH:mm:ss") }, { "openingRangeEnd", _openingRangeEnd.ToString("yyyy-MM-dd HH:mm:ss") }, { "stdDevMultiplier", _stdDevMultiplier }, { "openingRangeMinutes", _openingRangeMinutes }, { "session_tag", sessionTag }, { "code_version", GetCodeVersionStamp() } }; return JsonConvert.SerializeObject(snapshot, Newtonsoft.Json.Formatting.Indented); } catch (Exception ex) { return "{\"error\": \"" + ex.Message + "\"}"; } } private 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"; } } } }