浏览代码

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 6 天之前
父节点
当前提交
968e663a08
共有 1 个文件被更改,包括 25 次插入9 次删除
  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):
     async def start_order_monitoring(self):
         """Start the order monitoring background task."""
         """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:
         if self.monitoring_active:
             return
             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):
     async def stop_order_monitoring(self):
         """Stop the order monitoring background task."""
         """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...")
         logger.info("⏹️ Stopping order monitoring...")
     
     
     async def _initialize_order_tracking(self):
     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):
     async def _order_monitoring_loop(self):
         """Main monitoring loop that runs every Config.BOT_HEARTBEAT_SECONDS seconds."""
         """Main monitoring loop that runs every Config.BOT_HEARTBEAT_SECONDS seconds."""
-        while self.monitoring_active:
+        while getattr(self, 'monitoring_active', False):
             try:
             try:
                 await self._check_order_fills()
                 await self._check_order_fills()
                 await asyncio.sleep(Config.BOT_HEARTBEAT_SECONDS)  # Use configurable interval
                 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"
         last_deposit_check = "Never"
         next_deposit_check = "Unknown"
         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')
             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_check_time = self.last_deposit_withdrawal_check + timedelta(seconds=self.deposit_withdrawal_check_interval)
             next_deposit_check = next_check_time.strftime('%H:%M:%S')
             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"""
         status_text = f"""
 🔄 <b>System Monitoring Status</b>
 🔄 <b>System Monitoring Status</b>
 
 
 📊 <b>Order Monitoring:</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
 • 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>
 💰 <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}
 • Last Check: {last_deposit_check}
 • Next Check: {next_deposit_check}
 • Next Check: {next_deposit_check}
 • Total Adjustments: {adjustments_summary['adjustment_count']}
 • Total Adjustments: {adjustments_summary['adjustment_count']}
@@ -3173,6 +3185,10 @@ Will trigger when {token} price moves {alarm['direction']} ${target_price:,.2f}
             # Get stats info
             # Get stats info
             basic_stats = self.stats.get_basic_stats()
             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"""
             version_text = f"""
 🤖 <b>Trading Bot Version & System Info</b>
 🤖 <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']}
 • Start Date: {basic_stats['start_date']}
 
 
 🔄 <b>Monitoring Status:</b>
 🔄 <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
 • 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'}
 • Risk Management: {'✅ Enabled' if Config.RISK_MANAGEMENT_ENABLED else '❌ Disabled'}
 
 
 ⏰ <b>Current Time:</b> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
 ⏰ <b>Current Time:</b> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}