#!/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)