123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528 |
- import logging
- from typing import Optional, Dict, Any, List
- from hyperliquid import HyperliquidSync
- from config import Config
- logger = logging.getLogger(__name__)
- class HyperliquidClient:
- """Wrapper class for Hyperliquid API client with enhanced functionality."""
-
- def __init__(self, use_testnet: bool = None):
- """
- Initialize the Hyperliquid client with CCXT-style configuration.
-
- Args:
- use_testnet: Whether to use testnet (default: from Config.HYPERLIQUID_TESTNET)
- """
-
- if use_testnet is None:
- use_testnet = Config.HYPERLIQUID_TESTNET
-
- self.use_testnet = use_testnet
-
-
- self.config = Config.get_hyperliquid_config()
-
-
- if use_testnet is not None:
- self.config['testnet'] = use_testnet
- self.config['sandbox'] = use_testnet
-
-
-
- if not self.config.get('apiKey') and Config.HYPERLIQUID_SECRET_KEY:
- self.config['apiKey'] = Config.HYPERLIQUID_SECRET_KEY
-
- if not self.config.get('walletAddress') and Config.HYPERLIQUID_WALLET_ADDRESS:
- self.config['walletAddress'] = Config.HYPERLIQUID_WALLET_ADDRESS
-
- if not self.config.get('secret') and Config.HYPERLIQUID_WALLET_ADDRESS:
- self.config['secret'] = Config.HYPERLIQUID_WALLET_ADDRESS
-
-
- self.sync_client = None
- self.async_client = None
-
- if self.config.get('privateKey') or self.config.get('apiKey'):
- try:
-
- logger.info(f"🔧 Initializing Hyperliquid client with config: {self._safe_config_log()}")
-
-
- ccxt_config = {
- 'apiKey': self.config.get('apiKey'),
- 'privateKey': self.config.get('apiKey'),
- 'testnet': self.config.get('testnet', False),
- 'sandbox': self.config.get('sandbox', False),
- }
-
-
- if self.config.get('walletAddress'):
- ccxt_config['walletAddress'] = self.config['walletAddress']
-
-
- if self.config.get('secret'):
- ccxt_config['secret'] = self.config['secret']
-
- logger.info(f"📋 Using CCXT config structure: {self._safe_ccxt_config_log(ccxt_config)}")
-
-
- self.sync_client = HyperliquidSync(ccxt_config)
-
- logger.info(f"✅ Hyperliquid client initialized successfully")
- logger.info(f"🌐 Network: {'Testnet' if use_testnet else '🚨 MAINNET 🚨'}")
-
-
- self._test_connection()
-
- except Exception as e:
- logger.error(f"❌ Failed to initialize Hyperliquid client: {e}")
- logger.error(f"💡 Config used: {self._safe_config_log()}")
- raise
- else:
- logger.warning("⚠️ No private key provided - client will have limited functionality")
-
- def _safe_config_log(self) -> Dict[str, Any]:
- """Return config with sensitive data masked for logging."""
- safe_config = self.config.copy()
- if 'apiKey' in safe_config and safe_config['apiKey']:
- safe_config['apiKey'] = f"{safe_config['apiKey'][:8]}..."
- if 'walletAddress' in safe_config and safe_config['walletAddress']:
- safe_config['walletAddress'] = f"{safe_config['walletAddress'][:8]}..."
- if 'secret' in safe_config and safe_config['secret']:
- safe_config['secret'] = f"{safe_config['secret'][:8]}..."
- return safe_config
-
- def _safe_ccxt_config_log(self, config: dict) -> dict:
- """Return CCXT config with sensitive data masked for logging."""
- safe_config = config.copy()
- if 'apiKey' in safe_config and safe_config['apiKey']:
- safe_config['apiKey'] = f"{safe_config['apiKey'][:8]}..."
- if 'walletAddress' in safe_config and safe_config['walletAddress']:
- safe_config['walletAddress'] = f"{safe_config['walletAddress'][:8]}..."
- if 'secret' in safe_config and safe_config['secret']:
- safe_config['secret'] = f"{safe_config['secret'][:8]}..."
- return safe_config
-
- def _test_connection(self):
- """Test the connection to verify credentials."""
- try:
-
-
- params = {}
- if Config.HYPERLIQUID_WALLET_ADDRESS:
- wallet_address = Config.HYPERLIQUID_WALLET_ADDRESS
- params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
-
- balance = self.sync_client.fetch_balance(params=params)
- logger.info(f"🔗 Connection test successful")
- except Exception as e:
- logger.warning(f"⚠️ Connection test failed: {e}")
- logger.warning("💡 This might be normal if you have no positions/balance")
-
- def get_balance(self) -> Optional[Dict[str, Any]]:
- """Get account balance."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
-
- params = {}
-
-
- if Config.HYPERLIQUID_WALLET_ADDRESS:
-
-
- wallet_address = Config.HYPERLIQUID_WALLET_ADDRESS
- if wallet_address.startswith('0x'):
-
- params['user'] = wallet_address
- else:
-
- params['user'] = f"0x{wallet_address}"
-
- logger.debug(f"🔍 Fetching balance with params: {params}")
- balance = self.sync_client.fetch_balance(params=params)
- logger.info("✅ Successfully fetched balance")
- return balance
- except Exception as e:
- logger.error(f"❌ Error fetching balance: {e}")
- logger.debug(f"💡 Attempted with params: {params}")
- return None
-
- def get_balance_alternative(self) -> Optional[Dict[str, Any]]:
- """Alternative balance fetching method trying different approaches."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
- approaches = [
-
- {},
-
- {'user': Config.HYPERLIQUID_WALLET_ADDRESS},
-
- {'user': f"0x{Config.HYPERLIQUID_WALLET_ADDRESS}" if Config.HYPERLIQUID_WALLET_ADDRESS and not Config.HYPERLIQUID_WALLET_ADDRESS.startswith('0x') else Config.HYPERLIQUID_WALLET_ADDRESS},
-
- {'user': ''},
- ]
-
- for i, params in enumerate(approaches, 1):
- try:
- logger.info(f"🔍 Trying approach {i}: {params}")
- balance = self.sync_client.fetch_balance(params=params)
- logger.info(f"✅ Approach {i} successful!")
- return balance
- except Exception as e:
- logger.warning(f"⚠️ Approach {i} failed: {e}")
- continue
-
- logger.error("❌ All approaches failed")
- return None
-
- except Exception as e:
- logger.error(f"❌ Error in alternative balance fetch: {e}")
- return None
-
- def get_positions(self, symbol: Optional[str] = None) -> Optional[List[Dict[str, Any]]]:
- """Get current positions."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
- params = {}
- if Config.HYPERLIQUID_WALLET_ADDRESS:
- wallet_address = Config.HYPERLIQUID_WALLET_ADDRESS
- params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
-
- logger.debug(f"🔍 Fetching positions with params: {params}")
- positions = self.sync_client.fetch_positions([symbol] if symbol else None, params=params)
- logger.info(f"✅ Successfully fetched positions for {symbol or 'all symbols'}")
- return positions
- except Exception as e:
- logger.error(f"❌ Error fetching positions: {e}")
- logger.debug(f"💡 Attempted with params: {params}")
- return None
-
- def get_market_data(self, symbol: str) -> Optional[Dict[str, Any]]:
- """Get market data for a symbol."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
- ticker = self.sync_client.fetch_ticker(symbol)
- orderbook = self.sync_client.fetch_order_book(symbol)
-
- market_data = {
- 'ticker': ticker,
- 'orderbook': orderbook,
- 'symbol': symbol
- }
-
- logger.info(f"✅ Successfully fetched market data for {symbol}")
- return market_data
- except Exception as e:
- logger.error(f"❌ Error fetching market data for {symbol}: {e}")
- return None
-
- def place_limit_order(self, symbol: str, side: str, amount: float, price: float, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
- """
- Place a limit order with CCXT-style parameters.
-
- Args:
- symbol: Trading symbol (e.g., 'BTC/USDC:USDC')
- side: 'buy' or 'sell'
- amount: Order amount
- price: Order price
- params: Additional parameters for CCXT compatibility
- """
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
- order_params = params or {}
- order = self.sync_client.create_limit_order(symbol, side, amount, price, params=order_params)
-
- logger.info(f"✅ Successfully placed {side} limit order for {amount} {symbol} at ${price}")
- logger.debug(f"📄 Order details: {order}")
-
- return order
- except Exception as e:
- logger.error(f"❌ Error placing limit order: {e}")
- return None
-
- def place_market_order(self, symbol: str, side: str, amount: float, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
- """
- Place a market order with CCXT-style parameters.
-
- Args:
- symbol: Trading symbol (e.g., 'BTC/USDC:USDC')
- side: 'buy' or 'sell'
- amount: Order amount
- params: Additional parameters for CCXT compatibility
- """
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
- ticker = self.sync_client.fetch_ticker(symbol)
- if not ticker:
- logger.error(f"❌ Could not fetch ticker for {symbol}")
- return None
-
- current_price = ticker.get('last')
- if not current_price:
- logger.error(f"❌ Could not get current price for {symbol}")
- return None
-
-
- slippage_percent = 0.5
- if side == 'buy':
-
- slippage_price = current_price * (1 + slippage_percent / 100)
- else:
-
- slippage_price = current_price * (1 - slippage_percent / 100)
-
- logger.info(f"🔄 Market order: {side} {amount} {symbol} @ current ${current_price:.2f} (slippage price: ${slippage_price:.2f})")
-
-
- order_params = params or {}
- order_params['price'] = slippage_price
-
- order = self.sync_client.create_market_order(symbol, side, amount, price=slippage_price, params=order_params)
-
- logger.info(f"✅ Successfully placed {side} market order for {amount} {symbol}")
- logger.debug(f"📄 Order details: {order}")
-
- return order
- except Exception as e:
- logger.error(f"❌ Error placing market order: {e}")
- return None
-
- def get_open_orders(self, symbol: Optional[str] = None) -> Optional[List[Dict[str, Any]]]:
- """Get open orders."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
- params = {}
- if Config.HYPERLIQUID_WALLET_ADDRESS:
- wallet_address = Config.HYPERLIQUID_WALLET_ADDRESS
- params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
-
- logger.debug(f"🔍 Fetching open orders with params: {params}")
- orders = self.sync_client.fetch_open_orders(symbol, params=params)
- logger.info(f"✅ Successfully fetched open orders for {symbol or 'all symbols'}")
- return orders
- except Exception as e:
- logger.error(f"❌ Error fetching open orders: {e}")
- logger.debug(f"💡 Attempted with params: {params}")
- return None
-
- def cancel_order(self, order_id: str, symbol: str, params: Optional[Dict] = None) -> bool:
- """Cancel an order with CCXT-style parameters."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return False
-
- cancel_params = params or {}
- result = self.sync_client.cancel_order(order_id, symbol, params=cancel_params)
-
- logger.info(f"✅ Successfully cancelled order {order_id}")
- return True
- except Exception as e:
- logger.error(f"❌ Error cancelling order {order_id}: {e}")
- return False
-
- def get_recent_trades(self, symbol: str, limit: int = 10) -> Optional[List[Dict[str, Any]]]:
- """Get recent trades for a symbol."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
- trades = self.sync_client.fetch_trades(symbol, limit=limit)
- logger.info(f"✅ Successfully fetched {len(trades)} recent trades for {symbol}")
- return trades
- except Exception as e:
- logger.error(f"❌ Error fetching recent trades for {symbol}: {e}")
- return None
-
- def get_trading_fee(self, symbol: str) -> Optional[Dict[str, Any]]:
- """Get trading fee for a symbol."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
- fee = self.sync_client.fetch_trading_fee(symbol)
- logger.info(f"✅ Successfully fetched trading fee for {symbol}")
- return fee
- except Exception as e:
- logger.error(f"❌ Error fetching trading fee for {symbol}: {e}")
- return None
-
- def get_markets(self) -> Optional[Dict[str, Any]]:
- """Get available markets/symbols."""
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
- markets = self.sync_client.load_markets()
- logger.info(f"✅ Successfully loaded {len(markets)} markets")
- return markets
- except Exception as e:
- logger.error(f"❌ Error loading markets: {e}")
- return None
-
- def place_stop_loss_order(self, symbol: str, side: str, amount: float, price: float, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
- """
- Place a stop loss order (implemented as a limit order).
-
- Args:
- symbol: Trading symbol (e.g., 'BTC/USDC:USDC')
- side: 'buy' or 'sell'
- amount: Order amount
- price: Stop loss price
- params: Additional parameters for CCXT compatibility
- """
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
-
- order_params = params or {}
-
-
- logger.info(f"🛑 Placing stop loss order: {side} {amount} {symbol} @ ${price}")
-
- order = self.sync_client.create_limit_order(symbol, side, amount, price, params=order_params)
-
- logger.info(f"✅ Successfully placed stop loss order for {amount} {symbol} at ${price}")
- logger.debug(f"📄 Stop loss order details: {order}")
-
- return order
- except Exception as e:
- logger.error(f"❌ Error placing stop loss order: {e}")
- return None
-
- def place_take_profit_order(self, symbol: str, side: str, amount: float, price: float, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
- """
- Place a take profit order (implemented as a limit order).
-
- Args:
- symbol: Trading symbol (e.g., 'BTC/USDC:USDC')
- side: 'buy' or 'sell'
- amount: Order amount
- price: Take profit price
- params: Additional parameters for CCXT compatibility
- """
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
-
- order_params = params or {}
-
-
- logger.info(f"🎯 Placing take profit order: {side} {amount} {symbol} @ ${price}")
-
- order = self.sync_client.create_limit_order(symbol, side, amount, price, params=order_params)
-
- logger.info(f"✅ Successfully placed take profit order for {amount} {symbol} at ${price}")
- logger.debug(f"📄 Take profit order details: {order}")
-
- return order
- except Exception as e:
- logger.error(f"❌ Error placing take profit order: {e}")
- return None
- def get_recent_fills(self, limit: int = 100) -> Optional[List[Dict[str, Any]]]:
- """
- Get recent fills/trades for the account.
-
- Args:
- limit: Maximum number of fills to return
-
- Returns:
- List of recent fills/trades or None if error
- """
- try:
- if not self.sync_client:
- logger.error("❌ Client not initialized")
- return None
-
-
- params = {}
- if Config.HYPERLIQUID_WALLET_ADDRESS:
- wallet_address = Config.HYPERLIQUID_WALLET_ADDRESS
- params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
-
-
-
- logger.debug(f"🔍 Fetching recent fills with params: {params}")
-
-
-
- try:
-
- fills = self.sync_client.fetch_my_trades(None, limit=limit, params=params)
- logger.info(f"✅ Successfully fetched {len(fills)} recent fills")
- return fills
- except AttributeError:
-
- logger.debug("fetch_my_trades not available, trying alternative approach")
-
-
- positions = self.get_positions()
- if not positions:
- logger.info("No positions found, no recent fills to fetch")
- return []
-
-
- symbols = list(set([pos.get('symbol') for pos in positions if pos.get('symbol')]))
-
- all_fills = []
- for symbol in symbols[:5]:
- try:
- symbol_trades = self.sync_client.fetch_my_trades(symbol, limit=limit//len(symbols), params=params)
- if symbol_trades:
- all_fills.extend(symbol_trades)
- except Exception as e:
- logger.warning(f"Could not fetch trades for {symbol}: {e}")
- continue
-
-
- all_fills.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
-
-
- result = all_fills[:limit]
- logger.info(f"✅ Successfully fetched {len(result)} recent fills from {len(symbols)} symbols")
- return result
-
- except Exception as e:
- logger.error(f"❌ Error fetching recent fills: {e}")
- logger.debug(f"💡 Attempted with params: {params}")
- return None
|