# Phase 4: Intelligence & Grading - Implementation Guide **Estimated Time:** 4-5 hours **Complexity:** High **Dependencies:** Phase 3 Complete ✅ --- ## Implementation Overview Phase 4 adds the "intelligence layer" - confluence scoring, regime detection, grade-based sizing, and risk mode automation. This transforms the system from mechanical execution to intelligent trade selection. **Core Concept:** Not all trades are equal. Grade them, size accordingly, and adapt risk based on conditions. --- ## Phase A: Confluence Scoring Foundation (60 minutes) ### Task A1: Create ConfluenceModels.cs **Location:** `src/NT8.Core/Intelligence/ConfluenceModels.cs` **Deliverables:** - `ConfluenceFactor` record - Individual factor contribution - `ConfluenceScore` record - Overall trade score - `TradeGrade` enum - A+, A, B, C, D, F - `FactorType` enum - Setup, Trend, Volatility, Timing, Quality, etc. - `FactorWeight` record - Dynamic factor weighting **ConfluenceFactor:** ```csharp public record ConfluenceFactor( FactorType Type, string Name, double Score, // 0.0 to 1.0 double Weight, // Importance weight string Reason, Dictionary Details ); ``` **ConfluenceScore:** ```csharp public record ConfluenceScore( double RawScore, // 0.0 to 1.0 double WeightedScore, // After applying weights TradeGrade Grade, // A+ to F List Factors, DateTime CalculatedAt, Dictionary Metadata ); ``` **TradeGrade Enum:** ```csharp public enum TradeGrade { APlus = 6, // 0.90+ Exceptional setup A = 5, // 0.80+ Strong setup B = 4, // 0.70+ Good setup C = 3, // 0.60+ Acceptable setup D = 2, // 0.50+ Marginal setup F = 1 // <0.50 Reject trade } ``` --- ### Task A2: Create FactorCalculators.cs **Location:** `src/NT8.Core/Intelligence/FactorCalculators.cs` **Deliverables:** Base interface and individual factor calculators for: 1. **ORB Setup Validity** (0.0 - 1.0) 2. **Trend Alignment** (0.0 - 1.0) 3. **Volatility Regime** (0.0 - 1.0) 4. **Time-in-Session** (0.0 - 1.0) 5. **Recent Execution Quality** (0.0 - 1.0) **Interface:** ```csharp public interface IFactorCalculator { FactorType Type { get; } ConfluenceFactor Calculate(StrategyIntent intent, StrategyContext context, MarketData data); } ``` **Factor 1: ORB Setup Validity** ```csharp Score Calculation: - ORB range > minimum threshold: +0.3 - Clean breakout (no wicks): +0.2 - Volume confirmation (>avg): +0.2 - Time since ORB complete < 2 hrs: +0.3 Max Score: 1.0 ``` **Factor 2: Trend Alignment** ```csharp Score Calculation: - Price above AVWAP (long): +0.4 - AVWAP slope aligned: +0.3 - Recent bars confirm trend: +0.3 Max Score: 1.0 ``` **Factor 3: Volatility Regime** ```csharp Score Calculation: Normal volatility (0.8-1.2x avg): 1.0 Low volatility (<0.8x): 0.7 High volatility (>1.2x): 0.5 Extreme volatility (>1.5x): 0.3 ``` **Factor 4: Time-in-Session** ```csharp Score Calculation: First 2 hours (9:30-11:30): 1.0 Mid-day (11:30-14:00): 0.6 Last hour (15:00-16:00): 0.8 After hours: 0.3 ``` **Factor 5: Recent Execution Quality** ```csharp Score Calculation: Last 10 trades avg quality: - Excellent: 1.0 - Good: 0.8 - Fair: 0.6 - Poor: 0.4 ``` --- ### Task A3: Create ConfluenceScorer.cs **Location:** `src/NT8.Core/Intelligence/ConfluenceScorer.cs` **Deliverables:** - Calculate overall confluence score - Aggregate factor scores with weights - Map raw score to trade grade - Thread-safe scoring - Detailed score breakdown **Key Features:** - Configurable factor weights - Dynamic weight adjustment - Score history tracking - Performance analytics **Methods:** ```csharp public ConfluenceScore CalculateScore( StrategyIntent intent, StrategyContext context, List factors); public TradeGrade MapScoreToGrade(double weightedScore); public void UpdateFactorWeights(Dictionary weights); public ConfluenceStatistics GetHistoricalStats(); ``` **Scoring Algorithm:** ```csharp WeightedScore = Sum(Factor.Score × Factor.Weight) / Sum(Weights) Grade Mapping: 0.90+ → A+ (Exceptional) 0.80+ → A (Strong) 0.70+ → B (Good) 0.60+ → C (Acceptable) 0.50+ → D (Marginal) <0.50 → F (Reject) ``` --- ## Phase B: Regime Detection (60 minutes) ### Task B1: Create RegimeModels.cs **Location:** `src/NT8.Core/Intelligence/RegimeModels.cs` **Deliverables:** - `VolatilityRegime` enum - Low/Normal/High/Extreme - `TrendRegime` enum - StrongUp/WeakUp/Range/WeakDown/StrongDown - `RegimeState` record - Current market regime - `RegimeTransition` record - Regime change event - `RegimeHistory` record - Historical regime tracking **RegimeState:** ```csharp public record RegimeState( string Symbol, VolatilityRegime VolatilityRegime, TrendRegime TrendRegime, double VolatilityScore, // Current volatility vs normal double TrendStrength, // -1.0 to +1.0 DateTime LastUpdate, TimeSpan RegimeDuration, // How long in current regime Dictionary Indicators ); ``` --- ### Task B2: Create VolatilityRegimeDetector.cs **Location:** `src/NT8.Core/Intelligence/VolatilityRegimeDetector.cs` **Deliverables:** - Calculate current volatility vs historical - Classify into regime (Low/Normal/High/Extreme) - Detect regime transitions - Track regime duration - Alert on regime changes **Volatility Calculation:** ```csharp Current ATR vs 20-day Average ATR: < 0.6x → Low (expansion likely) 0.6-0.8x → Below Normal 0.8-1.2x → Normal 1.2-1.5x → Elevated 1.5-2.0x → High > 2.0x → Extreme (reduce size) ``` **Methods:** ```csharp public VolatilityRegime DetectRegime(string symbol, double currentATR, double normalATR); public bool IsRegimeTransition(VolatilityRegime current, VolatilityRegime previous); public double CalculateVolatilityScore(double currentATR, double normalATR); public void UpdateRegimeHistory(string symbol, VolatilityRegime regime); ``` --- ### Task B3: Create TrendRegimeDetector.cs **Location:** `src/NT8.Core/Intelligence/TrendRegimeDetector.cs` **Deliverables:** - Detect trend direction and strength - Identify ranging vs trending markets - Calculate trend persistence - Measure trend quality **Trend Detection:** ```csharp Using Price vs AVWAP + Slope: Strong Uptrend: - Price > AVWAP - AVWAP slope > threshold - Higher highs, higher lows - Score: +0.8 to +1.0 Weak Uptrend: - Price > AVWAP - AVWAP slope positive but weak - Score: +0.3 to +0.7 Range: - Price oscillating around AVWAP - Low slope - Score: -0.2 to +0.2 Weak Downtrend: - Price < AVWAP - AVWAP slope negative but weak - Score: -0.7 to -0.3 Strong Downtrend: - Price < AVWAP - AVWAP slope < threshold - Lower highs, lower lows - Score: -1.0 to -0.8 ``` **Methods:** ```csharp public TrendRegime DetectTrend(string symbol, List bars, double avwap); public double CalculateTrendStrength(List bars, double avwap); public bool IsRanging(List bars, double threshold); public TrendQuality AssessTrendQuality(List bars); ``` --- ### Task B4: Create RegimeManager.cs **Location:** `src/NT8.Core/Intelligence/RegimeManager.cs` **Deliverables:** - Coordinate volatility and trend detection - Maintain current regime state per symbol - Track regime transitions - Provide regime-based recommendations - Thread-safe regime tracking **Key Features:** - Real-time regime updates - Regime change notifications - Historical regime tracking - Performance by regime **Methods:** ```csharp public void UpdateRegime(string symbol, BarData bar, double avwap, double atr, double normalATR); public RegimeState GetCurrentRegime(string symbol); public bool ShouldAdjustStrategy(string symbol, StrategyIntent intent); public List GetRecentTransitions(string symbol, TimeSpan period); ``` --- ## Phase C: Risk Mode Framework (60 minutes) ### Task C1: Create RiskModeModels.cs **Location:** `src/NT8.Core/Intelligence/RiskModeModels.cs` **Deliverables:** - `RiskMode` enum - ECP/PCP/DCP/HR - `RiskModeConfig` record - Mode-specific settings - `ModeTransitionRule` record - Transition conditions - `RiskModeState` record - Current mode state **RiskMode Enum:** ```csharp public enum RiskMode { HR = 0, // High Risk - minimal exposure DCP = 1, // Diminished Confidence Play PCP = 2, // Primary Confidence Play (default) ECP = 3 // Elevated Confidence Play } ``` **RiskModeConfig:** ```csharp public record RiskModeConfig( RiskMode Mode, double SizeMultiplier, // Position size adjustment TradeGrade MinimumGrade, // Minimum grade to trade double MaxDailyRisk, // Daily risk cap int MaxConcurrentTrades, // Max open positions bool AggressiveEntries, // Allow aggressive entries Dictionary CustomSettings ); Example Configs: ECP: 1.5x size, B+ minimum, aggressive entries PCP: 1.0x size, B minimum, normal entries DCP: 0.5x size, A- minimum, conservative only HR: 0.0x size, reject all trades ``` --- ### Task C2: Create RiskModeManager.cs **Location:** `src/NT8.Core/Intelligence/RiskModeManager.cs` **Deliverables:** - Manage current risk mode - Automatic mode transitions based on P&L - Manual mode override capability - Mode-specific trading rules - Thread-safe mode management **Mode Transition Logic:** ```csharp Start of Day: PCP (Primary Confidence Play) Transition to ECP: - Daily P&L > +$500 (or 5R) - Last 5 trades: 80%+ win rate - No recent drawdowns Transition to DCP: - Daily P&L < -$200 (or -2R) - Last 5 trades: <50% win rate - Recent execution quality declining Transition to HR: - Daily loss limit approached (80%) - 3+ consecutive losses - Extreme volatility regime - Manual override Recovery from DCP to PCP: - 2+ winning trades in a row - Execution quality improved - Volatility normalized Recovery from HR to DCP: - Next trading day (automatic reset) - Manual override after review ``` **Methods:** ```csharp public void UpdateRiskMode(double dailyPnL, int winStreak, int lossStreak); public RiskMode GetCurrentMode(); public RiskModeConfig GetModeConfig(RiskMode mode); public bool ShouldTransitionMode(RiskMode current, PerformanceMetrics metrics); public void OverrideMode(RiskMode mode, string reason); public void ResetToDefault(); ``` --- ### Task C3: Create GradeFilter.cs **Location:** `src/NT8.Core/Intelligence/GradeFilter.cs` **Deliverables:** - Filter trades by grade based on risk mode - Grade-based position sizing multipliers - Risk mode gating logic - Trade rejection reasons **Grade Filtering Rules:** ```csharp ECP Mode (Elevated Confidence): - Accept: A+, A, B+, B - Size: A+ = 1.5x, A = 1.25x, B+ = 1.1x, B = 1.0x - Reject: C and below PCP Mode (Primary Confidence): - Accept: A+, A, B+, B, C+ - Size: A+ = 1.25x, A = 1.1x, B = 1.0x, C+ = 0.9x - Reject: C and below DCP Mode (Diminished Confidence): - Accept: A+, A only - Size: A+ = 0.75x, A = 0.5x - Reject: B+ and below HR Mode (High Risk): - Accept: None - Reject: All trades ``` **Methods:** ```csharp public bool ShouldAcceptTrade(TradeGrade grade, RiskMode mode); public double GetSizeMultiplier(TradeGrade grade, RiskMode mode); public string GetRejectionReason(TradeGrade grade, RiskMode mode); public TradeGrade GetMinimumGrade(RiskMode mode); ``` --- ## Phase D: Grade-Based Sizing Integration (45 minutes) ### Task D1: Create GradeBasedSizer.cs **Location:** `src/NT8.Core/Sizing/GradeBasedSizer.cs` **Deliverables:** - Integrate confluence score with position sizing - Apply grade-based multipliers - Combine with risk mode adjustments - Override existing sizing with grade awareness **Sizing Flow:** ```csharp 1. Base Size (from Phase 2 sizer): BaseContracts = FixedRisk OR OptimalF OR VolatilityAdjusted 2. Grade Multiplier (from confluence score): GradeMultiplier = GetSizeMultiplier(grade, riskMode) 3. Risk Mode Multiplier: ModeMultiplier = riskModeConfig.SizeMultiplier 4. Final Size: FinalContracts = BaseContracts × GradeMultiplier × ModeMultiplier FinalContracts = Clamp(FinalContracts, MinContracts, MaxContracts) ``` **Methods:** ```csharp public SizingResult CalculateGradeBasedSize( StrategyIntent intent, StrategyContext context, ConfluenceScore confluenceScore, RiskMode riskMode, SizingConfig baseConfig); public double CombineMultipliers(double gradeMultiplier, double modeMultiplier); public int ApplyConstraints(int calculatedSize, int min, int max); ``` --- ### Task D2: Update AdvancedPositionSizer.cs **Location:** `src/NT8.Core/Sizing/AdvancedPositionSizer.cs` **Add method (don't modify existing):** ```csharp public SizingResult CalculateSizeWithGrade( StrategyIntent intent, StrategyContext context, SizingConfig config, ConfluenceScore confluenceScore, RiskMode riskMode); ``` **Implementation:** - Call existing CalculateSize() for base sizing - Apply grade-based multiplier - Apply risk mode multiplier - Return enhanced SizingResult with metadata --- ## Phase E: Strategy Enhancement (60 minutes) ### Task E1: Create AVWAPCalculator.cs **Location:** `src/NT8.Core/Indicators/AVWAPCalculator.cs` **Deliverables:** - Anchored VWAP calculation - Anchor points (day start, week start, custom) - Rolling VWAP updates - Slope calculation **AVWAP Formula:** ```csharp VWAP = Sum(Price × Volume) / Sum(Volume) Anchored: Reset accumulation at anchor point - Day: Reset at 9:30 AM each day - Week: Reset Monday 9:30 AM - Custom: User-specified time Slope = (Current VWAP - VWAP 10 bars ago) / 10 ``` **Methods:** ```csharp public double Calculate(List bars, DateTime anchorTime); public void Update(double price, long volume); public double GetSlope(int lookback); public void ResetAnchor(DateTime newAnchor); ``` --- ### Task E2: Create VolumeProfileAnalyzer.cs **Location:** `src/NT8.Core/Indicators/VolumeProfileAnalyzer.cs` **Deliverables:** - Volume by price level (VPOC) - High volume nodes - Low volume nodes (gaps) - Value area calculation **Volume Profile Concepts:** ```csharp VPOC (Volume Point of Control): - Price level with highest volume - Acts as magnet for price High Volume Nodes: - Volume > 1.5x average - Support/resistance levels Low Volume Nodes: - Volume < 0.5x average - Price gaps quickly through Value Area: - 70% of volume traded - Fair value range ``` **Methods:** ```csharp public double GetVPOC(List bars); public List GetHighVolumeNodes(List bars); public List GetLowVolumeNodes(List bars); public ValueArea CalculateValueArea(List bars); ``` --- ### Task E3: Enhance SimpleORBStrategy **Location:** `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` **Add confluence awareness (don't break existing):** - Calculate AVWAP filter - Check volume profile - Use confluence scorer - Apply grade-based sizing **Enhanced OnBar Logic:** ```csharp public StrategyIntent? OnBar(BarData bar, StrategyContext context) { // Existing ORB logic... if (breakoutDetected) { // NEW: Add confluence factors var factors = new List { CalculateORBValidity(), CalculateTrendAlignment(bar, avwap), CalculateVolatilityRegime(), CalculateTimingFactor(bar.Time), CalculateExecutionQuality() }; var confluenceScore = _scorer.CalculateScore(intent, context, factors); // Check grade filter if (!_gradeFilter.ShouldAcceptTrade(confluenceScore.Grade, currentRiskMode)) { _logger.LogInfo("Trade rejected: Grade {0}, Mode {1}", confluenceScore.Grade, currentRiskMode); return null; } // Add confluence metadata to intent intent.Metadata["confluence_score"] = confluenceScore; intent.Confidence = confluenceScore.WeightedScore; return intent; } } ``` --- ## Phase F: Comprehensive Testing (75 minutes) ### Task F1: ConfluenceScorerTests.cs **Location:** `tests/NT8.Core.Tests/Intelligence/ConfluenceScorerTests.cs` **Test Coverage:** - Individual factor calculations - Score aggregation logic - Grade mapping accuracy - Weight application - Edge cases (all factors 0.0, all factors 1.0) - Thread safety **Minimum:** 20 tests --- ### Task F2: RegimeDetectionTests.cs **Location:** `tests/NT8.Core.Tests/Intelligence/RegimeDetectionTests.cs` **Test Coverage:** - Volatility regime classification - Trend regime detection - Regime transitions - Historical regime tracking - Regime duration calculation **Minimum:** 18 tests --- ### Task F3: RiskModeManagerTests.cs **Location:** `tests/NT8.Core.Tests/Intelligence/RiskModeManagerTests.cs` **Test Coverage:** - Mode transitions (PCP→ECP, PCP→DCP, DCP→HR) - Automatic mode updates - Manual overrides - Grade filtering by mode - Size multipliers by mode **Minimum:** 15 tests --- ### Task F4: GradeBasedSizerTests.cs **Location:** `tests/NT8.Core.Tests/Sizing/GradeBasedSizerTests.cs` **Test Coverage:** - Base size calculation - Grade multiplier application - Risk mode multiplier - Combined multipliers - Constraint application **Minimum:** 12 tests --- ### Task F5: AVWAPCalculatorTests.cs **Location:** `tests/NT8.Core.Tests/Indicators/AVWAPCalculatorTests.cs` **Test Coverage:** - AVWAP calculation accuracy - Anchor point handling - Slope calculation - Rolling updates **Minimum:** 10 tests --- ### Task F6: Phase4IntegrationTests.cs **Location:** `tests/NT8.Integration.Tests/Phase4IntegrationTests.cs` **Test Coverage:** - Full flow: Intent → Confluence → Grade → Mode Filter → Sizing - Grade-based rejection scenarios - Risk mode transitions during trading - Enhanced strategy execution - Regime-aware trading **Minimum:** 12 tests --- ## Phase G: Integration & Verification (45 minutes) ### Task G1: Performance Benchmarks **Location:** `tests/NT8.Performance.Tests/Phase4PerformanceTests.cs` **Benchmarks:** - Confluence score calculation: <5ms - Regime detection: <3ms - Grade filtering: <1ms - Risk mode update: <2ms - Overall intelligence flow: <15ms --- ### Task G2: Build Verification **Command:** `.\verify-build.bat` **Requirements:** - Zero errors - Zero warnings for new Phase 4 code - All tests passing (150+ total) - Coverage >80% --- ### Task G3: Documentation **Files to update:** - Create Phase4_Completion_Report.md - Update API_REFERENCE.md with intelligence interfaces - Add confluence scoring examples - Document risk modes --- ## Success Criteria ### Code Quality - ✅ C# 5.0 syntax only - ✅ Thread-safe (locks on shared state) - ✅ XML docs on all public members - ✅ Comprehensive logging - ✅ No breaking changes ### Testing - ✅ >150 total tests passing - ✅ >80% code coverage - ✅ All scoring scenarios tested - ✅ All regime scenarios tested - ✅ Integration tests pass ### Performance - ✅ Confluence scoring <5ms - ✅ Regime detection <3ms - ✅ Grade filtering <1ms - ✅ Overall flow <15ms ### Integration - ✅ Works with Phase 2-3 - ✅ Grade-based sizing operational - ✅ Risk modes functional - ✅ Regime detection accurate --- ## File Creation Checklist ### New Files (18): **Intelligence (9):** - [ ] `src/NT8.Core/Intelligence/ConfluenceModels.cs` - [ ] `src/NT8.Core/Intelligence/FactorCalculators.cs` - [ ] `src/NT8.Core/Intelligence/ConfluenceScorer.cs` - [ ] `src/NT8.Core/Intelligence/RegimeModels.cs` - [ ] `src/NT8.Core/Intelligence/VolatilityRegimeDetector.cs` - [ ] `src/NT8.Core/Intelligence/TrendRegimeDetector.cs` - [ ] `src/NT8.Core/Intelligence/RegimeManager.cs` - [ ] `src/NT8.Core/Intelligence/RiskModeModels.cs` - [ ] `src/NT8.Core/Intelligence/RiskModeManager.cs` - [ ] `src/NT8.Core/Intelligence/GradeFilter.cs` **Sizing (1):** - [ ] `src/NT8.Core/Sizing/GradeBasedSizer.cs` **Indicators (2):** - [ ] `src/NT8.Core/Indicators/AVWAPCalculator.cs` - [ ] `src/NT8.Core/Indicators/VolumeProfileAnalyzer.cs` **Tests (6):** - [ ] `tests/NT8.Core.Tests/Intelligence/ConfluenceScorerTests.cs` - [ ] `tests/NT8.Core.Tests/Intelligence/RegimeDetectionTests.cs` - [ ] `tests/NT8.Core.Tests/Intelligence/RiskModeManagerTests.cs` - [ ] `tests/NT8.Core.Tests/Sizing/GradeBasedSizerTests.cs` - [ ] `tests/NT8.Core.Tests/Indicators/AVWAPCalculatorTests.cs` - [ ] `tests/NT8.Integration.Tests/Phase4IntegrationTests.cs` ### Updated Files (2): - [ ] `src/NT8.Core/Sizing/AdvancedPositionSizer.cs` - ADD grade-based method - [ ] `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` - ADD confluence awareness **Total:** 18 new files, 2 updated files --- ## Estimated Timeline | Phase | Tasks | Time | Cumulative | |-------|-------|------|------------| | **A** | Confluence Foundation | 60 min | 1:00 | | **B** | Regime Detection | 60 min | 2:00 | | **C** | Risk Mode Framework | 60 min | 3:00 | | **D** | Grade-Based Sizing | 45 min | 3:45 | | **E** | Strategy Enhancement | 60 min | 4:45 | | **F** | Testing | 75 min | 6:00 | | **G** | Verification | 45 min | 6:45 | **Total:** 6-7 hours (budget 4-5 hours for Kilocode efficiency) --- ## Critical Notes ### Modifications to Existing Code **IMPORTANT:** Only these files can be modified: - ✅ `src/NT8.Core/Sizing/AdvancedPositionSizer.cs` - ADD method only - ✅ `src/NT8.Strategies/Examples/SimpleORBStrategy.cs` - ADD features only **FORBIDDEN:** - ❌ Do NOT modify interfaces - ❌ Do NOT modify Phase 1-3 core implementations - ❌ Do NOT change existing method signatures ### Thread Safety All intelligence classes MUST use proper locking: ```csharp private readonly object _lock = new object(); lock (_lock) { // Shared state access } ``` ### C# 5.0 Compliance Verify after each file - same restrictions as Phase 2-3. --- ## Ready to Start? **Paste into Kilocode Code Mode:** ``` I'm ready to implement Phase 4: Intelligence & Grading. Follow Phase4_Implementation_Guide.md starting with Phase A, Task A1. CRITICAL REQUIREMENTS: - C# 5.0 syntax ONLY - Thread-safe with locks on shared state - XML docs on all public members - NO interface modifications - NO breaking changes to Phase 1-3 File Creation Permissions: ✅ CREATE in: src/NT8.Core/Intelligence/, src/NT8.Core/Indicators/ ✅ MODIFY (ADD ONLY): AdvancedPositionSizer.cs, SimpleORBStrategy.cs ❌ FORBIDDEN: Any interface files, Phase 1-3 core implementations Start with Task A1: Create ConfluenceModels.cs in src/NT8.Core/Intelligence/ After each file: 1. Build (Ctrl+Shift+B) 2. Verify zero errors 3. Continue to next task Let's begin with ConfluenceModels.cs! ``` --- **Phase 4 will make your system INTELLIGENT!** 🧠