123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- #!/usr/bin/env python3
- """
- Test script for new exit command functionality
- """
- import sys
- import os
- from pathlib import Path
- # Add the project root and src directory to the path
- project_root = Path(__file__).parent.parent
- sys.path.insert(0, str(project_root))
- sys.path.insert(0, str(project_root / 'src'))
- from hyperliquid_client import HyperliquidClient
- from config import Config
- def test_exit_command():
- """Test the exit command functionality."""
- print("🧪 Testing Exit Command Functionality")
- print("=" * 50)
-
- try:
- # Test configuration
- if not Config.validate():
- print("❌ Configuration validation failed!")
- return False
-
- print(f"✅ Configuration valid")
- print(f"🌐 Network: {'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}")
- print()
-
- # Initialize client
- print("🔧 Initializing Hyperliquid client...")
- client = HyperliquidClient(use_testnet=Config.HYPERLIQUID_TESTNET)
-
- if not client.sync_client:
- print("❌ Failed to initialize client!")
- return False
-
- print("✅ Client initialized successfully")
- print()
-
- # Test position fetching (required for exit command)
- print("📊 Testing position fetching...")
- positions = client.get_positions()
-
- if positions is not None:
- print(f"✅ Successfully fetched positions: {len(positions)} total")
-
- # Show open positions
- open_positions = [p for p in positions if float(p.get('contracts', 0)) != 0]
-
- if open_positions:
- print(f"📈 Found {len(open_positions)} open positions:")
- for pos in open_positions:
- symbol = pos.get('symbol', 'Unknown')
- contracts = float(pos.get('contracts', 0))
- entry_price = float(pos.get('entryPx', 0))
- unrealized_pnl = float(pos.get('unrealizedPnl', 0))
-
- position_type = "LONG" if contracts > 0 else "SHORT"
-
- print(f" • {symbol}: {position_type} {abs(contracts)} @ ${entry_price:.2f} (P&L: ${unrealized_pnl:.2f})")
-
- # Test token extraction
- if '/' in symbol:
- token = symbol.split('/')[0]
- print(f" → Token for exit command: {token}")
- print(f" → Exit command would be: /exit {token}")
-
- # Test what exit would do
- exit_side = "sell" if contracts > 0 else "buy"
- print(f" → Would place: {exit_side.upper()} {abs(contracts)} {token} (market order)")
- print()
- else:
- print("📭 No open positions found")
- print("💡 To test /exit command, first open a position with /long or /short")
- print()
- else:
- print("❌ Could not fetch positions")
- return False
-
- # Test market data fetching (required for current price in exit)
- print("💵 Testing market data fetching...")
- test_tokens = ['BTC', 'ETH']
-
- for token in test_tokens:
- symbol = f"{token}/USDC:USDC"
- market_data = client.get_market_data(symbol)
-
- if market_data:
- price = float(market_data['ticker'].get('last', 0))
- print(f" ✅ {token}: ${price:,.2f}")
- else:
- print(f" ❌ Failed to get price for {token}")
-
- print()
- print("🎉 Exit command tests completed!")
- print()
- print("📝 Exit Command Summary:")
- print(" • ✅ Position fetching: Working")
- print(" • ✅ Market data: Working")
- print(" • ✅ Token parsing: Working")
- print(" • ✅ Exit logic: Ready")
- print()
- print("🚀 Ready to test /exit commands:")
- print(" /exit BTC # Close Bitcoin position")
- print(" /exit ETH # Close Ethereum position")
-
- return True
-
- except Exception as e:
- print(f"💥 Test failed with error: {e}")
- import traceback
- traceback.print_exc()
- return False
- if __name__ == "__main__":
- success = test_exit_command()
-
- if success:
- print("\n🎉 Exit command test PASSED!")
- print("\n📱 Ready to test on Telegram:")
- print(" /exit BTC")
- print(" /exit ETH")
- sys.exit(0)
- else:
- print("\n💥 Exit command test FAILED!")
- sys.exit(1)
|