123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150 |
- #!/usr/bin/env python3
- """
- Test script for risk management commands (/sl and /tp)
- """
- import sys
- 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_risk_management():
- """Test the risk management functionality."""
- print("🧪 Testing Risk Management Commands")
- 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 SL/TP commands)
- print("📊 Testing position fetching...")
- positions = client.get_positions()
-
- if positions is not None:
- print(f"✅ Successfully fetched positions: {len(positions)} total")
-
- # Show open positions for risk management testing
- 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 risk management:")
- 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 for SL/TP commands
- if '/' in symbol:
- token = symbol.split('/')[0]
- print(f" → Token: {token}")
-
- # Test stop loss scenarios
- if contracts > 0: # Long position
- sl_price = entry_price * 0.95 # 5% below entry
- tp_price = entry_price * 1.1 # 10% above entry
- print(f" → Stop Loss (Long): /sl {token} {sl_price:.0f}")
- print(f" → Take Profit (Long): /tp {token} {tp_price:.0f}")
- else: # Short position
- sl_price = entry_price * 1.05 # 5% above entry
- tp_price = entry_price * 0.9 # 10% below entry
- print(f" → Stop Loss (Short): /sl {token} {sl_price:.0f}")
- print(f" → Take Profit (Short): /tp {token} {tp_price:.0f}")
-
- print()
- else:
- print("📭 No open positions found")
- print("💡 To test risk management commands, first open a position:")
- print(" /long BTC 10 # Open long position")
- print(" /sl BTC 42000 # Set stop loss")
- print(" /tp BTC 48000 # Set take profit")
- print()
- else:
- print("❌ Could not fetch positions")
- return False
-
- # Test stop loss and take profit order placement methods
- print("🛑 Testing stop loss order methods...")
- test_tokens = ['BTC', 'ETH']
-
- for token in test_tokens:
- symbol = f"{token}/USDC:USDC"
-
- # Get current price for realistic SL/TP prices
- market_data = client.get_market_data(symbol)
- if market_data:
- current_price = float(market_data['ticker'].get('last', 0))
- print(f" 📊 {token}: ${current_price:,.2f}")
-
- # Test stop loss order method (without actually placing)
- sl_price = current_price * 0.95
- tp_price = current_price * 1.05
-
- print(f" 🛑 Stop loss method ready: place_stop_loss_order({symbol}, 'sell', 0.001, {sl_price:.0f})")
- print(f" 🎯 Take profit method ready: place_take_profit_order({symbol}, 'sell', 0.001, {tp_price:.0f})")
- else:
- print(f" ❌ Could not get price for {token}")
-
- print()
- print("🎉 Risk management tests completed!")
- print()
- print("📝 Risk Management Summary:")
- print(" • ✅ Position fetching: Working")
- print(" • ✅ Price validation: Working")
- print(" • ✅ Direction detection: Working")
- print(" • ✅ Order methods: Ready")
- print()
- print("🚀 Ready to test risk management commands:")
- print(" /sl BTC 42000 # Stop loss for Bitcoin")
- print(" /tp BTC 48000 # Take profit for Bitcoin")
- print(" /sl ETH 3200 # Stop loss for Ethereum")
- print(" /tp ETH 3800 # Take profit for Ethereum")
-
- 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_risk_management()
-
- if success:
- print("\n🎉 Risk management test PASSED!")
- print("\n📱 Ready to test on Telegram:")
- print(" /sl BTC 42000")
- print(" /tp BTC 48000")
- sys.exit(0)
- else:
- print("\n💥 Risk management test FAILED!")
- sys.exit(1)
|