Pārlūkot izejas kodu

Add test script for bot configuration and format string verification - Introduce a new test file to validate the functionality of configuration changes, format strings, and timestamp handling in the Telegram bot. Ensure proper handling of new and removed configuration variables, and verify the accuracy of format strings used in bot messages.

Carles Sentis 6 dienas atpakaļ
vecāks
revīzija
be22a37823
2 mainītis faili ar 187 papildinājumiem un 11 dzēšanām
  1. 25 11
      src/telegram_bot.py
  2. 162 0
      test_bot_fixes.py

+ 25 - 11
src/telegram_bot.py

@@ -136,7 +136,7 @@ Tap the buttons below for instant access to key functions.
 • Price alarm triggers
 • External trade detection & sync
 • Auto stats synchronization
-• {Config.BOT_HEARTBEAT_SECONDS}-second monitoring interval
+• {heartbeat}-second monitoring interval
 
 <b>📊 Universal Trade Tracking:</b>
 • Bot trades: Full logging & notifications
@@ -152,7 +152,7 @@ Type /help for detailed command information.
 
 <b>⚙️ Configuration:</b>
 • Symbol: {symbol}
-• Default Amount: {amount}
+• Default Token: {symbol}
 • Network: {network}
 
 <b>🛡️ Safety Features:</b>
@@ -257,7 +257,7 @@ For support, contact your bot administrator.
 
 <b>⚙️ Configuration:</b>
 • Symbol: {symbol}
-• Default Amount: {amount}
+• Default Token: {symbol}
 • Network: {network}
 
 <b>🛡️ Safety Features:</b>
@@ -1104,7 +1104,7 @@ For support, contact your bot administrator.
                 f"✅ Connected to Hyperliquid {'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}\n"
                 f"📊 Default Symbol: {Config.DEFAULT_TRADING_TOKEN}\n"
                 f"📱 Manual trading ready!\n"
-                f"🔄 Order monitoring: Active ({Config.BOT_HEARTBEAT_SECONDS}s interval)\n"
+                f"🔄 Order monitoring: Active ({heartbeat}s interval)\n"
                 f"🔄 External trade monitoring: Active\n"
                 f"🔔 Price alarms: Active\n"
                 f"📊 Auto stats sync: Enabled\n"
@@ -1930,10 +1930,24 @@ This will place a limit {exit_side} order at ${profit_price:,.2f} to capture pro
             
             for fill in recent_fills:
                 fill_time = fill.get('timestamp')
-                if fill_time and fill_time > self.last_processed_trade_time:
-                    new_trades.append(fill)
-                    if fill_time > latest_trade_time:
-                        latest_trade_time = fill_time
+                if fill_time:
+                    # Convert timestamps to comparable format
+                    try:
+                        # Convert fill_time to string if it's not already
+                        if isinstance(fill_time, (int, float)):
+                            # Assume it's a unix timestamp
+                            fill_time_str = datetime.fromtimestamp(fill_time / 1000 if fill_time > 1e10 else fill_time).isoformat()
+                        else:
+                            fill_time_str = str(fill_time)
+                        
+                        # Compare as strings
+                        if fill_time_str > self.last_processed_trade_time:
+                            new_trades.append(fill)
+                            if fill_time_str > latest_trade_time:
+                                latest_trade_time = fill_time_str
+                    except Exception as timestamp_error:
+                        logger.warning(f"⚠️ Error processing timestamp {fill_time}: {timestamp_error}")
+                        continue
             
             if not new_trades:
                 return
@@ -2379,7 +2393,7 @@ This will place a limit {exit_side} order at ${profit_price:,.2f} to capture pro
 
 📊 <b>Order Monitoring:</b>
 • Active: {'✅ Yes' if self.monitoring_active else '❌ No'}
-• Check Interval: {Config.BOT_HEARTBEAT_SECONDS} seconds
+• Check Interval: {heartbeat} seconds
 • Orders Tracked: {len(self.last_known_orders)}
 • Positions Tracked: {len(self.last_known_positions)}
 
@@ -2505,7 +2519,7 @@ Will trigger when {token} price moves {alarm['direction']} ${target_price:,.2f}
 
 ⏰ <b>Created:</b> {datetime.now().strftime('%H:%M:%S')}
 
-💡 The alarm will be checked every {Config.BOT_HEARTBEAT_SECONDS} seconds and you'll receive a notification when triggered.
+💡 The alarm will be checked every {heartbeat} seconds and you'll receive a notification when triggered.
                 """
                 
                 await update.message.reply_text(message.strip(), parse_mode='HTML')
@@ -2563,7 +2577,7 @@ Will trigger when {token} price moves {alarm['direction']} ${target_price:,.2f}
 
 📈 <b>Log Configuration:</b>
 • Log Level: {Config.LOG_LEVEL}
-• Heartbeat Interval: {Config.BOT_HEARTBEAT_SECONDS}s
+• Heartbeat Interval: {heartbeat}s
 • Bot Uptime: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
 
 💡 <b>Log Management:</b>

+ 162 - 0
test_bot_fixes.py

@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""
+Test script to verify that the bot configuration and format string fixes work correctly.
+"""
+
+import sys
+import os
+sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
+
+from config import Config
+
+def test_config_fixes():
+    """Test that the configuration changes work correctly."""
+    print("🔧 Configuration Fixes Test")
+    print("=" * 50)
+    
+    # Test that the new configuration variables exist
+    try:
+        token = Config.DEFAULT_TRADING_TOKEN
+        risk_enabled = Config.RISK_MANAGEMENT_ENABLED
+        stop_loss = Config.STOP_LOSS_PERCENTAGE
+        heartbeat = Config.BOT_HEARTBEAT_SECONDS
+        
+        print(f"✅ DEFAULT_TRADING_TOKEN: {token}")
+        print(f"✅ RISK_MANAGEMENT_ENABLED: {risk_enabled}")
+        print(f"✅ STOP_LOSS_PERCENTAGE: {stop_loss}%")
+        print(f"✅ BOT_HEARTBEAT_SECONDS: {heartbeat}")
+        
+        # Test that old variables are gone
+        try:
+            amount = Config.DEFAULT_TRADE_AMOUNT
+            print(f"❌ DEFAULT_TRADE_AMOUNT still exists: {amount}")
+        except AttributeError:
+            print("✅ DEFAULT_TRADE_AMOUNT properly removed")
+        
+        try:
+            symbol = Config.DEFAULT_TRADING_SYMBOL
+            print(f"❌ DEFAULT_TRADING_SYMBOL still exists: {symbol}")
+        except AttributeError:
+            print("✅ DEFAULT_TRADING_SYMBOL properly removed")
+            
+    except AttributeError as e:
+        print(f"❌ Configuration error: {e}")
+        return False
+    
+    return True
+
+def test_format_strings():
+    """Test that format strings work correctly."""
+    print("\n📝 Format String Test")
+    print("=" * 50)
+    
+    try:
+        # Test the format parameters that would be used in telegram bot
+        symbol = Config.DEFAULT_TRADING_TOKEN
+        network = "Testnet" if Config.HYPERLIQUID_TESTNET else "Mainnet"
+        risk_enabled = Config.RISK_MANAGEMENT_ENABLED
+        stop_loss = Config.STOP_LOSS_PERCENTAGE
+        heartbeat = Config.BOT_HEARTBEAT_SECONDS
+        
+        # Test format string similar to what's used in the bot
+        test_format = """
+⚙️ Configuration:
+• Default Token: {symbol}
+• Network: {network}
+• Risk Management: {risk_enabled}
+• Stop Loss: {stop_loss}%
+• Monitoring: Every {heartbeat} seconds
+        """.format(
+            symbol=symbol,
+            network=network,
+            risk_enabled=risk_enabled,
+            stop_loss=stop_loss,
+            heartbeat=heartbeat
+        )
+        
+        print("✅ Format string test successful:")
+        print(test_format.strip())
+        
+    except KeyError as e:
+        print(f"❌ Format string error: {e}")
+        return False
+    except Exception as e:
+        print(f"❌ Unexpected error: {e}")
+        return False
+    
+    return True
+
+def test_timestamp_handling():
+    """Test timestamp handling for external trades."""
+    print("\n⏰ Timestamp Handling Test")
+    print("=" * 50)
+    
+    from datetime import datetime, timedelta
+    
+    try:
+        # Test different timestamp formats
+        test_timestamps = [
+            1733155660,  # Unix timestamp (seconds)
+            1733155660000,  # Unix timestamp (milliseconds)
+            "2024-12-02T15:47:40",  # ISO format
+            "2024-12-02T15:47:40.123Z",  # ISO with Z
+        ]
+        
+        base_time = (datetime.now() - timedelta(hours=1)).isoformat()
+        
+        for ts in test_timestamps:
+            try:
+                # Test the conversion logic from the bot
+                if isinstance(ts, (int, float)):
+                    # Assume it's a unix timestamp
+                    ts_str = datetime.fromtimestamp(ts / 1000 if ts > 1e10 else ts).isoformat()
+                else:
+                    ts_str = str(ts)
+                
+                # Test comparison
+                comparison_result = ts_str > base_time
+                print(f"✅ Timestamp {ts} -> {ts_str} (comparison: {comparison_result})")
+                
+            except Exception as e:
+                print(f"❌ Error processing timestamp {ts}: {e}")
+                return False
+                
+        print("✅ All timestamp formats handled correctly")
+        
+    except Exception as e:
+        print(f"❌ Timestamp handling error: {e}")
+        return False
+    
+    return True
+
+if __name__ == "__main__":
+    print("🚀 Bot Fixes Verification Test")
+    print("=" * 60)
+    
+    # Run all tests
+    tests = [
+        test_config_fixes,
+        test_format_strings,
+        test_timestamp_handling
+    ]
+    
+    results = []
+    for test in tests:
+        try:
+            result = test()
+            results.append(result)
+        except Exception as e:
+            print(f"❌ Test failed with exception: {e}")
+            results.append(False)
+    
+    print("\n" + "=" * 60)
+    
+    if all(results):
+        print("🎉 All tests passed! Bot fixes are working correctly.")
+        print("✅ Configuration cleanup successful")
+        print("✅ Format string errors fixed")
+        print("✅ Timestamp comparison issues resolved")
+    else:
+        print("⚠️ Some tests failed. Please check the issues above.")
+        failed_count = len([r for r in results if not r])
+        print(f"❌ {failed_count}/{len(results)} tests failed")