test_exit_command.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. #!/usr/bin/env python3
  2. """
  3. Test script for new exit command functionality
  4. """
  5. import sys
  6. import os
  7. from pathlib import Path
  8. # Add the project root and src directory to the path
  9. project_root = Path(__file__).parent.parent
  10. sys.path.insert(0, str(project_root))
  11. sys.path.insert(0, str(project_root / 'src'))
  12. from hyperliquid_client import HyperliquidClient
  13. from config import Config
  14. def test_exit_command():
  15. """Test the exit command functionality."""
  16. print("🧪 Testing Exit Command Functionality")
  17. print("=" * 50)
  18. try:
  19. # Test configuration
  20. if not Config.validate():
  21. print("❌ Configuration validation failed!")
  22. return False
  23. print(f"✅ Configuration valid")
  24. print(f"🌐 Network: {'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}")
  25. print()
  26. # Initialize client
  27. print("🔧 Initializing Hyperliquid client...")
  28. client = HyperliquidClient(use_testnet=Config.HYPERLIQUID_TESTNET)
  29. if not client.sync_client:
  30. print("❌ Failed to initialize client!")
  31. return False
  32. print("✅ Client initialized successfully")
  33. print()
  34. # Test position fetching (required for exit command)
  35. print("📊 Testing position fetching...")
  36. positions = client.get_positions()
  37. if positions is not None:
  38. print(f"✅ Successfully fetched positions: {len(positions)} total")
  39. # Show open positions
  40. open_positions = [p for p in positions if float(p.get('contracts', 0)) != 0]
  41. if open_positions:
  42. print(f"📈 Found {len(open_positions)} open positions:")
  43. for pos in open_positions:
  44. symbol = pos.get('symbol', 'Unknown')
  45. contracts = float(pos.get('contracts', 0))
  46. entry_price = float(pos.get('entryPx', 0))
  47. unrealized_pnl = float(pos.get('unrealizedPnl', 0))
  48. position_type = "LONG" if contracts > 0 else "SHORT"
  49. print(f" • {symbol}: {position_type} {abs(contracts)} @ ${entry_price:.2f} (P&L: ${unrealized_pnl:.2f})")
  50. # Test token extraction
  51. if '/' in symbol:
  52. token = symbol.split('/')[0]
  53. print(f" → Token for exit command: {token}")
  54. print(f" → Exit command would be: /exit {token}")
  55. # Test what exit would do
  56. exit_side = "sell" if contracts > 0 else "buy"
  57. print(f" → Would place: {exit_side.upper()} {abs(contracts)} {token} (market order)")
  58. print()
  59. else:
  60. print("📭 No open positions found")
  61. print("💡 To test /exit command, first open a position with /long or /short")
  62. print()
  63. else:
  64. print("❌ Could not fetch positions")
  65. return False
  66. # Test market data fetching (required for current price in exit)
  67. print("💵 Testing market data fetching...")
  68. test_tokens = ['BTC', 'ETH']
  69. for token in test_tokens:
  70. symbol = f"{token}/USDC:USDC"
  71. market_data = client.get_market_data(symbol)
  72. if market_data:
  73. price = float(market_data['ticker'].get('last', 0))
  74. print(f" ✅ {token}: ${price:,.2f}")
  75. else:
  76. print(f" ❌ Failed to get price for {token}")
  77. print()
  78. print("🎉 Exit command tests completed!")
  79. print()
  80. print("📝 Exit Command Summary:")
  81. print(" • ✅ Position fetching: Working")
  82. print(" • ✅ Market data: Working")
  83. print(" • ✅ Token parsing: Working")
  84. print(" • ✅ Exit logic: Ready")
  85. print()
  86. print("🚀 Ready to test /exit commands:")
  87. print(" /exit BTC # Close Bitcoin position")
  88. print(" /exit ETH # Close Ethereum position")
  89. return True
  90. except Exception as e:
  91. print(f"💥 Test failed with error: {e}")
  92. import traceback
  93. traceback.print_exc()
  94. return False
  95. if __name__ == "__main__":
  96. success = test_exit_command()
  97. if success:
  98. print("\n🎉 Exit command test PASSED!")
  99. print("\n📱 Ready to test on Telegram:")
  100. print(" /exit BTC")
  101. print(" /exit ETH")
  102. sys.exit(0)
  103. else:
  104. print("\n💥 Exit command test FAILED!")
  105. sys.exit(1)