using System; using System.Collections.Generic; using NT8.Core.Common.Models; using NT8.Core.Logging; namespace NT8.Core.Intelligence { /// /// Historical statistics for confluence scoring. /// public class ConfluenceStatistics { /// /// Total number of score calculations observed. /// public int TotalCalculations { get; set; } /// /// Average weighted score across history. /// public double AverageWeightedScore { get; set; } /// /// Average raw score across history. /// public double AverageRawScore { get; set; } /// /// Best weighted score seen in history. /// public double BestWeightedScore { get; set; } /// /// Worst weighted score seen in history. /// public double WorstWeightedScore { get; set; } /// /// Grade distribution counts for historical scores. /// public Dictionary GradeDistribution { get; set; } /// /// Last calculation timestamp in UTC. /// public DateTime LastCalculatedAtUtc { get; set; } /// /// Creates a new statistics model. /// /// Total number of calculations. /// Average weighted score. /// Average raw score. /// Best weighted score. /// Worst weighted score. /// Grade distribution map. /// Last calculation time. public ConfluenceStatistics( int totalCalculations, double averageWeightedScore, double averageRawScore, double bestWeightedScore, double worstWeightedScore, Dictionary gradeDistribution, DateTime lastCalculatedAtUtc) { TotalCalculations = totalCalculations; AverageWeightedScore = averageWeightedScore; AverageRawScore = averageRawScore; BestWeightedScore = bestWeightedScore; WorstWeightedScore = worstWeightedScore; GradeDistribution = gradeDistribution ?? new Dictionary(); LastCalculatedAtUtc = lastCalculatedAtUtc; } } /// /// Calculates weighted confluence score and trade grade from factor calculators. /// Thread-safe for weight updates and score history tracking. /// public class ConfluenceScorer { private readonly ILogger _logger; private readonly object _lock = new object(); private readonly Dictionary _factorWeights; private readonly Queue _history; private readonly int _maxHistory; /// /// Creates a new confluence scorer instance. /// /// Logger instance. /// Maximum historical score entries to keep. /// Logger is null. /// Max history is not positive. public ConfluenceScorer(ILogger logger, int maxHistory) { if (logger == null) throw new ArgumentNullException("logger"); if (maxHistory <= 0) throw new ArgumentException("maxHistory must be greater than zero", "maxHistory"); _logger = logger; _maxHistory = maxHistory; _factorWeights = new Dictionary(); _history = new Queue(); _factorWeights.Add(FactorType.Setup, 1.0); _factorWeights.Add(FactorType.Trend, 1.0); _factorWeights.Add(FactorType.Volatility, 1.0); _factorWeights.Add(FactorType.Timing, 1.0); _factorWeights.Add(FactorType.ExecutionQuality, 1.0); _factorWeights.Add(FactorType.NarrowRange, 0.20); _factorWeights.Add(FactorType.OrbRangeVsAtr, 0.15); _factorWeights.Add(FactorType.GapDirectionAlignment, 0.15); _factorWeights.Add(FactorType.BreakoutVolumeStrength, 0.20); _factorWeights.Add(FactorType.PriorDayCloseStrength, 0.15); } /// /// Calculates a confluence score from calculators and the current bar. /// /// Strategy intent under evaluation. /// Strategy context and market/session state. /// Current bar used for factor calculations. /// Factor calculator collection. /// Calculated confluence score with grade and factor breakdown. /// Any required parameter is null. public ConfluenceScore CalculateScore( StrategyIntent intent, StrategyContext context, BarData bar, List factors) { if (intent == null) throw new ArgumentNullException("intent"); if (context == null) throw new ArgumentNullException("context"); if (bar == null) throw new ArgumentNullException("bar"); if (factors == null) throw new ArgumentNullException("factors"); try { var calculatedFactors = new List(); var rawScoreSum = 0.0; var weightedScoreSum = 0.0; var totalWeight = 0.0; for (var i = 0; i < factors.Count; i++) { var calculator = factors[i]; if (calculator == null) { continue; } var factor = calculator.Calculate(intent, context, bar); if (factor == null) { continue; } var effectiveWeight = ResolveWeight(factor.Type, factor.Weight); var weightedFactor = new ConfluenceFactor( factor.Type, factor.Name, factor.Score, effectiveWeight, factor.Reason, factor.Details); calculatedFactors.Add(weightedFactor); rawScoreSum += weightedFactor.Score; weightedScoreSum += (weightedFactor.Score * weightedFactor.Weight); totalWeight += weightedFactor.Weight; } var rawScore = calculatedFactors.Count > 0 ? rawScoreSum / calculatedFactors.Count : 0.0; var weightedScore = totalWeight > 0.0 ? weightedScoreSum / totalWeight : 0.0; weightedScore = ClampScore(weightedScore); rawScore = ClampScore(rawScore); var grade = MapScoreToGrade(weightedScore); var metadata = new Dictionary(); metadata.Add("factor_count", calculatedFactors.Count); metadata.Add("total_weight", totalWeight); metadata.Add("raw_score_sum", rawScoreSum); metadata.Add("weighted_score_sum", weightedScoreSum); var result = new ConfluenceScore( rawScore, weightedScore, grade, calculatedFactors, DateTime.UtcNow, metadata); lock (_lock) { _history.Enqueue(result); while (_history.Count > _maxHistory) { _history.Dequeue(); } } _logger.LogDebug( "Confluence score calculated: Symbol={0}, Raw={1:F4}, Weighted={2:F4}, Grade={3}, Factors={4}", intent.Symbol, rawScore, weightedScore, grade, calculatedFactors.Count); return result; } catch (Exception ex) { _logger.LogError("Confluence scoring failed: {0}", ex.Message); throw; } } /// /// Calculates a confluence score using the current bar in context custom data. /// /// Strategy intent under evaluation. /// Strategy context that contains current bar in custom data key 'current_bar'. /// Factor calculator collection. /// Calculated confluence score. /// Any required parameter is null. /// Current bar is missing in context custom data. public ConfluenceScore CalculateScore( StrategyIntent intent, StrategyContext context, List factors) { if (intent == null) throw new ArgumentNullException("intent"); if (context == null) throw new ArgumentNullException("context"); if (factors == null) throw new ArgumentNullException("factors"); try { BarData bar = null; if (context.CustomData != null && context.CustomData.ContainsKey("current_bar")) { bar = context.CustomData["current_bar"] as BarData; } if (bar == null) throw new ArgumentException("context.CustomData must include key 'current_bar' with BarData value", "context"); return CalculateScore(intent, context, bar, factors); } catch (Exception ex) { _logger.LogError("Confluence scoring failed when reading current_bar: {0}", ex.Message); throw; } } /// /// Maps weighted score to trade grade. /// /// Weighted score in range [0.0, 1.0]. /// Mapped trade grade. public TradeGrade MapScoreToGrade(double weightedScore) { try { var score = ClampScore(weightedScore); if (score >= 0.90) return TradeGrade.APlus; if (score >= 0.80) return TradeGrade.A; if (score >= 0.70) return TradeGrade.B; if (score >= 0.60) return TradeGrade.C; if (score >= 0.50) return TradeGrade.D; return TradeGrade.F; } catch (Exception ex) { _logger.LogError("MapScoreToGrade failed: {0}", ex.Message); throw; } } /// /// Updates factor weights for one or more factor types. /// /// Weight overrides by factor type. /// Weights dictionary is null. /// Any weight is not positive. public void UpdateFactorWeights(Dictionary weights) { if (weights == null) throw new ArgumentNullException("weights"); try { lock (_lock) { foreach (var pair in weights) { if (pair.Value <= 0.0) throw new ArgumentException("All weights must be greater than zero", "weights"); if (_factorWeights.ContainsKey(pair.Key)) { _factorWeights[pair.Key] = pair.Value; } else { _factorWeights.Add(pair.Key, pair.Value); } } } _logger.LogInformation("Confluence factor weights updated. Count={0}", weights.Count); } catch (Exception ex) { _logger.LogError("UpdateFactorWeights failed: {0}", ex.Message); throw; } } /// /// Returns historical confluence scoring statistics. /// /// Historical confluence statistics snapshot. public ConfluenceStatistics GetHistoricalStats() { try { lock (_lock) { if (_history.Count == 0) { return CreateEmptyStatistics(); } var total = _history.Count; var weightedSum = 0.0; var rawSum = 0.0; var best = 0.0; var worst = 1.0; var gradeDistribution = InitializeGradeDistribution(); DateTime last = DateTime.MinValue; foreach (var score in _history) { weightedSum += score.WeightedScore; rawSum += score.RawScore; if (score.WeightedScore > best) best = score.WeightedScore; if (score.WeightedScore < worst) worst = score.WeightedScore; if (!gradeDistribution.ContainsKey(score.Grade)) gradeDistribution.Add(score.Grade, 0); gradeDistribution[score.Grade] = gradeDistribution[score.Grade] + 1; if (score.CalculatedAt > last) last = score.CalculatedAt; } return new ConfluenceStatistics( total, weightedSum / total, rawSum / total, best, worst, gradeDistribution, last); } } catch (Exception ex) { _logger.LogError("GetHistoricalStats failed: {0}", ex.Message); throw; } } private static double ClampScore(double score) { if (score < 0.0) return 0.0; if (score > 1.0) return 1.0; return score; } private double ResolveWeight(FactorType type, double fallbackWeight) { lock (_lock) { if (_factorWeights.ContainsKey(type)) return _factorWeights[type]; } return fallbackWeight > 0.0 ? fallbackWeight : 1.0; } private ConfluenceStatistics CreateEmptyStatistics() { return new ConfluenceStatistics( 0, 0.0, 0.0, 0.0, 0.0, InitializeGradeDistribution(), DateTime.MinValue); } private Dictionary InitializeGradeDistribution() { var distribution = new Dictionary(); distribution.Add(TradeGrade.APlus, 0); distribution.Add(TradeGrade.A, 0); distribution.Add(TradeGrade.B, 0); distribution.Add(TradeGrade.C, 0); distribution.Add(TradeGrade.D, 0); distribution.Add(TradeGrade.F, 0); return distribution; } } }