From fde38cbef151e99d8ccce741f3028bd9544e9bcb Mon Sep 17 00:00:00 2001 From: HJ Normey Date: Thu, 4 Sep 2025 19:51:31 +0200 Subject: [PATCH] feat(data): Added BB and other indicators to output, based on an 'single point representation' of the regime value and BULL-BEAR percentages --- nautilus_actor_test_implementation_5x.py | 159 +++++++++++++++++++++++ 1 file changed, 159 insertions(+) diff --git a/nautilus_actor_test_implementation_5x.py b/nautilus_actor_test_implementation_5x.py index 529efac..43ede78 100644 --- a/nautilus_actor_test_implementation_5x.py +++ b/nautilus_actor_test_implementation_5x.py @@ -38,6 +38,10 @@ SYMBOLS_DISCOVERED_TOPIC = "SILOQY.SYMBOLS.DISCOVERED" CANDLES_INITIAL_TOPIC = "SILOQY.CANDLES.INITIAL" # ADDED LINE 18: TICK_SIZES_TOPIC = "SILOQY.TICK.SIZES" +# NEW: Enhanced indicator topics for data bus publishing +REGIME_INDICATORS_TOPIC = "DOLPHIN.REGIME.INDICATORS" +BB_METRICS_TOPIC = "DOLPHIN.BB.METRICS" +TEMPORAL_PATTERNS_TOPIC = "DOLPHIN.TEMPORAL.PATTERNS" # Rate limiting constant MIN_INTERVAL = 2.5 # seconds between API batches @@ -920,6 +924,13 @@ class DOLPHINRegimeActor(Actor): self.processed_ticks = 0 self.regime_calculations = 0 + # NEW: Enhanced indicator tracking for BB and temporal patterns + self.signal_history = deque(maxlen=100) # For BB calculations + self.bb_period = 20 # BB calculation period + self.bb_std_dev = 2.0 # BB standard deviation multiplier + self.velocity_history = deque(maxlen=10) # For regime velocity tracking + self.confidence_history = deque(maxlen=20) # For confidence trend analysis + self.log.info(f"DOLPHINRegimeActor initialized with Nautilus ActorExecutor - max_symbols: {self.max_symbols}, " f"ticks_per_analysis: {self.ticks_per_analysis}") @@ -1041,6 +1052,101 @@ class DOLPHINRegimeActor(Actor): except Exception as e: self.log.error(f"Nautilus ActorExecutor: Regime detection error: {e}") + def _calculate_enhanced_indicators(self, bull_ratio, bear_ratio, confidence, analyzed, total_symbols): + """NEW: Calculate enhanced indicators including BB metrics and temporal patterns""" + # Calculate regime momentum signal + base_momentum = (bull_ratio - bear_ratio) * 100 # -100 to +100 + sample_quality = min(analyzed / total_symbols, 1.0) if total_symbols > 0 else 0.0 + signal = base_momentum * confidence * sample_quality + + # Add to signal history + self.signal_history.append(signal) + + # Calculate velocity (rate of change in signal) + velocity = 0.0 + if len(self.signal_history) >= 2: + velocity = self.signal_history[-1] - self.signal_history[-2] + self.velocity_history.append(velocity) + + # Store confidence for trending + self.confidence_history.append(confidence) + + # Calculate Bollinger Bands if enough history + bb_metrics = {} + if len(self.signal_history) >= self.bb_period: + recent_signals = list(self.signal_history)[-self.bb_period:] + sma = sum(recent_signals) / len(recent_signals) + + # Calculate standard deviation + variance = sum((x - sma) ** 2 for x in recent_signals) / len(recent_signals) + std_dev = variance ** 0.5 + + upper_band = sma + (self.bb_std_dev * std_dev) + lower_band = sma - (self.bb_std_dev * std_dev) + + # Position within BBs (mean reversion interpretation) + if signal > upper_band: + bb_position = 'ABOVE_UPPER' + elif signal < lower_band: + bb_position = 'BELOW_LOWER' + elif signal >= sma: + bb_position = 'UPPER_HALF' + else: + bb_position = 'LOWER_HALF' + + # Momentum persistence interpretation + if signal > upper_band: + momentum_signal = 'STRONG_BULL_BREAKOUT' + elif signal < lower_band: + momentum_signal = 'STRONG_BEAR_BREAKOUT' + elif signal > sma: + momentum_signal = 'MILD_BULLISH' + else: + momentum_signal = 'MILD_BEARISH' + + bb_metrics = { + 'signal': signal, + 'sma': sma, + 'upper_band': upper_band, + 'lower_band': lower_band, + 'bb_position': bb_position, + 'momentum_signal': momentum_signal, + 'bb_ready': True + } + else: + bb_metrics = { + 'signal': signal, + 'sma': None, + 'upper_band': None, + 'lower_band': None, + 'bb_position': 'INSUFFICIENT_DATA', + 'momentum_signal': 'INSUFFICIENT_DATA', + 'bb_ready': False + } + + # Calculate temporal patterns + temporal_metrics = {} + if len(self.velocity_history) >= 3: + avg_velocity = sum(self.velocity_history) / len(self.velocity_history) + velocity_trend = 'ACCELERATING' if velocity > avg_velocity else 'DECELERATING' + else: + avg_velocity = velocity + velocity_trend = 'BUILDING_HISTORY' + + if len(self.confidence_history) >= 5: + confidence_trend = 'RISING' if confidence > sum(self.confidence_history[-5:-1])/4 else 'FALLING' + else: + confidence_trend = 'BUILDING_HISTORY' + + temporal_metrics = { + 'velocity': velocity, + 'avg_velocity': avg_velocity, + 'velocity_trend': velocity_trend, + 'confidence_trend': confidence_trend + } + + return bb_metrics, temporal_metrics + def _run_regime_detection(self): self.regime_calculations += 1 @@ -1106,6 +1212,11 @@ class DOLPHINRegimeActor(Actor): # PRESERVED: Original confidence calculation confidence = self._calculate_confidence(bull_ratio, bear_ratio, analyzed, total_symbols) + # NEW: Calculate enhanced indicators + bb_metrics, temporal_metrics = self._calculate_enhanced_indicators( + bull_ratio, bear_ratio, confidence, analyzed, total_symbols + ) + self.previous_bull_ratio = bull_ratio # Publish regime result using Nautilus message bus @@ -1124,6 +1235,41 @@ class DOLPHINRegimeActor(Actor): self.msgbus.publish(REGIME_TOPIC, regime_tuple) + # NEW: Publish enhanced indicators to data bus + indicator_data = { + 'timestamp': int(time.time() * 1000), + 'regime_momentum_signal': bb_metrics['signal'], + 'bb_ready': bb_metrics['bb_ready'], + 'velocity': temporal_metrics['velocity'], + 'velocity_trend': temporal_metrics['velocity_trend'], + 'confidence_trend': temporal_metrics['confidence_trend'] + } + self.msgbus.publish(REGIME_INDICATORS_TOPIC, indicator_data) + + # Publish BB metrics separately for specialized consumers + if bb_metrics['bb_ready']: + bb_data = { + 'timestamp': int(time.time() * 1000), + 'signal': bb_metrics['signal'], + 'sma': bb_metrics['sma'], + 'upper_band': bb_metrics['upper_band'], + 'lower_band': bb_metrics['lower_band'], + 'bb_position': bb_metrics['bb_position'], + 'momentum_signal': bb_metrics['momentum_signal'] + } + self.msgbus.publish(BB_METRICS_TOPIC, bb_data) + + # Publish temporal patterns + temporal_data = { + 'timestamp': int(time.time() * 1000), + 'velocity': temporal_metrics['velocity'], + 'avg_velocity': temporal_metrics['avg_velocity'], + 'velocity_trend': temporal_metrics['velocity_trend'], + 'confidence_trend': temporal_metrics['confidence_trend'], + 'signal_history_length': len(self.signal_history) + } + self.msgbus.publish(TEMPORAL_PATTERNS_TOPIC, temporal_data) + except Exception as e: self.log.error(f"Nautilus ActorExecutor: Failed to publish regime result: {e}") @@ -1150,6 +1296,19 @@ class DOLPHINRegimeActor(Actor): self.log.info(f"{color_code}REGIME STATUS: {regime.value} | Bull: {bull_ratio:.2%} " f"Bear: {bear_ratio:.2%} ({bullish}/{bearish}) | Processed: {self.processed_ticks} ticks{reset_code}") + # NEW: Enhanced indicator line after regime status + if bb_metrics['bb_ready']: + self.log.info(f"{color_code}INDICATORS: Signal:{bb_metrics['signal']:.1f} | " + f"SMA:{bb_metrics['sma']:.1f} | Upper:{bb_metrics['upper_band']:.1f} | " + f"Lower:{bb_metrics['lower_band']:.1f} | Pos:{bb_metrics['bb_position']} | " + f"Mom:{bb_metrics['momentum_signal']} | Vel:{temporal_metrics['velocity']:.1f} | " + f"VelTrend:{temporal_metrics['velocity_trend']} | ConfTrend:{temporal_metrics['confidence_trend']}{reset_code}") + else: + self.log.info(f"{color_code}INDICATORS: Signal:{bb_metrics['signal']:.1f} | " + f"Status:BUILDING_BB_HISTORY ({len(self.signal_history)}/{self.bb_period}) | " + f"Vel:{temporal_metrics['velocity']:.1f} | VelTrend:{temporal_metrics['velocity_trend']} | " + f"ConfTrend:{temporal_metrics['confidence_trend']}{reset_code}") + # NEW: Log symbol pattern and counts if symbol_pattern: # Only if we have symbols to show pattern_str = " ".join(symbol_pattern) + " " # Create pattern with spaces