Ver Fonte

Implement safety checks for order monitoring attributes in Telegram bot - Add checks to ensure that monitoring attributes are initialized before use, preventing potential errors. Update status reporting to utilize these attributes safely, enhancing the robustness of the bot's monitoring functionality.

Carles Sentis há 6 dias atrás
pai
commit
968e663a08
1 ficheiros alterados com 25 adições e 9 exclusões
  1. 25 9
      src/telegram_bot.py

+ 25 - 9
src/telegram_bot.py

@@ -1888,6 +1888,10 @@ This will place a limit {exit_side} order at ${profit_price:,.2f} to capture pro
 
     async def start_order_monitoring(self):
         """Start the order monitoring background task."""
+        # Safety check in case this is called before initialization is complete
+        if not hasattr(self, 'monitoring_active'):
+            self.monitoring_active = False
+            
         if self.monitoring_active:
             return
         
@@ -1902,7 +1906,9 @@ This will place a limit {exit_side} order at ${profit_price:,.2f} to capture pro
     
     async def stop_order_monitoring(self):
         """Stop the order monitoring background task."""
-        self.monitoring_active = False
+        # Safety check in case this is called before initialization is complete
+        if hasattr(self, 'monitoring_active'):
+            self.monitoring_active = False
         logger.info("⏹️ Stopping order monitoring...")
     
     async def _initialize_order_tracking(self):
@@ -1934,7 +1940,7 @@ This will place a limit {exit_side} order at ${profit_price:,.2f} to capture pro
     
     async def _order_monitoring_loop(self):
         """Main monitoring loop that runs every Config.BOT_HEARTBEAT_SECONDS seconds."""
-        while self.monitoring_active:
+        while getattr(self, 'monitoring_active', False):
             try:
                 await self._check_order_fills()
                 await asyncio.sleep(Config.BOT_HEARTBEAT_SECONDS)  # Use configurable interval
@@ -2463,22 +2469,28 @@ This will place a limit {exit_side} order at ${profit_price:,.2f} to capture pro
         last_deposit_check = "Never"
         next_deposit_check = "Unknown"
         
-        if self.last_deposit_withdrawal_check:
+        if hasattr(self, 'last_deposit_withdrawal_check') and self.last_deposit_withdrawal_check:
             last_deposit_check = self.last_deposit_withdrawal_check.strftime('%H:%M:%S')
             next_check_time = self.last_deposit_withdrawal_check + timedelta(seconds=self.deposit_withdrawal_check_interval)
             next_deposit_check = next_check_time.strftime('%H:%M:%S')
         
+        # Safety checks for monitoring attributes
+        monitoring_active = getattr(self, 'monitoring_active', False)
+        last_known_orders = getattr(self, 'last_known_orders', set())
+        last_known_positions = getattr(self, 'last_known_positions', {})
+        deposit_withdrawal_check_interval = getattr(self, 'deposit_withdrawal_check_interval', 3600)
+        
         status_text = f"""
 🔄 <b>System Monitoring Status</b>
 
 📊 <b>Order Monitoring:</b>
-• Active: {'✅ Yes' if self.monitoring_active else '❌ No'}
+• Active: {'✅ Yes' if monitoring_active else '❌ No'}
 • Check Interval: {Config.BOT_HEARTBEAT_SECONDS} seconds
-• Orders Tracked: {len(self.last_known_orders)}
-• Positions Tracked: {len(self.last_known_positions)}
+• Orders Tracked: {len(last_known_orders)}
+• Positions Tracked: {len(last_known_positions)}
 
 💰 <b>Deposit/Withdrawal Monitoring:</b>
-• Check Interval: {self.deposit_withdrawal_check_interval // 3600} hour(s)
+• Check Interval: {deposit_withdrawal_check_interval // 3600} hour(s)
 • Last Check: {last_deposit_check}
 • Next Check: {next_deposit_check}
 • Total Adjustments: {adjustments_summary['adjustment_count']}
@@ -3173,6 +3185,10 @@ Will trigger when {token} price moves {alarm['direction']} ${target_price:,.2f}
             # Get stats info
             basic_stats = self.stats.get_basic_stats()
             
+            # Safety checks for monitoring attributes
+            order_monitoring_task = getattr(self, 'order_monitoring_task', None)
+            alarms = getattr(self, 'alarms', [])
+            
             version_text = f"""
 🤖 <b>Trading Bot Version & System Info</b>
 
@@ -3194,9 +3210,9 @@ Will trigger when {token} price moves {alarm['direction']} ${target_price:,.2f}
 • Start Date: {basic_stats['start_date']}
 
 🔄 <b>Monitoring Status:</b>
-• Order Monitoring: {'✅ Active' if self.order_monitoring_task and not self.order_monitoring_task.done() else '❌ Inactive'}
+• Order Monitoring: {'✅ Active' if order_monitoring_task and not order_monitoring_task.done() else '❌ Inactive'}
 • External Trades: ✅ Active
-• Price Alarms: ✅ Active ({len(self.alarms)} active)
+• Price Alarms: ✅ Active ({len(alarms)} active)
 • Risk Management: {'✅ Enabled' if Config.RISK_MANAGEMENT_ENABLED else '❌ Disabled'}
 
 ⏰ <b>Current Time:</b> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}