hyperliquid_client.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import asyncio
  2. import logging
  3. from typing import Optional, Dict, Any, List
  4. from hyperliquid import HyperliquidSync, HyperliquidAsync
  5. from config import Config
  6. # Use existing logger setup (will be configured by main application)
  7. logger = logging.getLogger(__name__)
  8. class HyperliquidClient:
  9. """Wrapper class for Hyperliquid API client with enhanced functionality."""
  10. def __init__(self, use_testnet: bool = None):
  11. """
  12. Initialize the Hyperliquid client with CCXT-style configuration.
  13. Args:
  14. use_testnet: Whether to use testnet (default: from Config.HYPERLIQUID_TESTNET)
  15. """
  16. # Use config value if not explicitly provided
  17. if use_testnet is None:
  18. use_testnet = Config.HYPERLIQUID_TESTNET
  19. self.use_testnet = use_testnet
  20. # Get CCXT-style configuration
  21. self.config = Config.get_hyperliquid_config()
  22. # Override testnet setting if provided
  23. if use_testnet is not None:
  24. self.config['testnet'] = use_testnet
  25. self.config['sandbox'] = use_testnet
  26. # Ensure proper CCXT format
  27. # Hyperliquid CCXT expects: apiKey=API_generator_key, walletAddress=wallet_address
  28. if not self.config.get('apiKey') and Config.HYPERLIQUID_SECRET_KEY:
  29. self.config['apiKey'] = Config.HYPERLIQUID_SECRET_KEY # API generator key
  30. if not self.config.get('walletAddress') and Config.HYPERLIQUID_WALLET_ADDRESS:
  31. self.config['walletAddress'] = Config.HYPERLIQUID_WALLET_ADDRESS # Wallet address
  32. if not self.config.get('secret') and Config.HYPERLIQUID_WALLET_ADDRESS:
  33. self.config['secret'] = Config.HYPERLIQUID_WALLET_ADDRESS # Wallet address as secret too
  34. # Initialize clients
  35. self.sync_client = None
  36. self.async_client = None
  37. if self.config.get('privateKey') or self.config.get('apiKey'):
  38. try:
  39. # Log configuration (safely)
  40. logger.info(f"🔧 Initializing Hyperliquid client with config: {self._safe_config_log()}")
  41. # Initialize with Hyperliquid-specific CCXT format
  42. ccxt_config = {
  43. 'privateKey': self.config.get('privateKey') or self.config.get('apiKey'),
  44. 'testnet': self.config.get('testnet', False),
  45. 'sandbox': self.config.get('sandbox', False),
  46. }
  47. # Add secret if available (though Hyperliquid might not need it)
  48. if self.config.get('secret'):
  49. ccxt_config['secret'] = self.config['secret']
  50. logger.info(f"📋 Using CCXT config structure: {self._safe_ccxt_config_log(ccxt_config)}")
  51. # Initialize with the proper CCXT format
  52. self.sync_client = HyperliquidSync(ccxt_config)
  53. logger.info(f"✅ Hyperliquid client initialized successfully")
  54. logger.info(f"🌐 Network: {'Testnet' if use_testnet else '🚨 MAINNET 🚨'}")
  55. # Test the connection
  56. self._test_connection()
  57. except Exception as e:
  58. logger.error(f"❌ Failed to initialize Hyperliquid client: {e}")
  59. logger.error(f"💡 Config used: {self._safe_config_log()}")
  60. raise
  61. else:
  62. logger.warning("⚠️ No private key provided - client will have limited functionality")
  63. def _safe_config_log(self) -> Dict[str, Any]:
  64. """Return config with sensitive data masked for logging."""
  65. safe_config = self.config.copy()
  66. if 'apiKey' in safe_config and safe_config['apiKey']:
  67. safe_config['apiKey'] = f"{safe_config['apiKey'][:8]}..."
  68. if 'walletAddress' in safe_config and safe_config['walletAddress']:
  69. safe_config['walletAddress'] = f"{safe_config['walletAddress'][:8]}..."
  70. if 'secret' in safe_config and safe_config['secret']:
  71. safe_config['secret'] = f"{safe_config['secret'][:8]}..."
  72. return safe_config
  73. def _safe_ccxt_config_log(self, config: dict) -> dict:
  74. """Return CCXT config with sensitive data masked for logging."""
  75. safe_config = config.copy()
  76. if 'apiKey' in safe_config and safe_config['apiKey']:
  77. safe_config['apiKey'] = f"{safe_config['apiKey'][:8]}..."
  78. if 'walletAddress' in safe_config and safe_config['walletAddress']:
  79. safe_config['walletAddress'] = f"{safe_config['walletAddress'][:8]}..."
  80. if 'secret' in safe_config and safe_config['secret']:
  81. safe_config['secret'] = f"{safe_config['secret'][:8]}..."
  82. return safe_config
  83. def _test_connection(self):
  84. """Test the connection to verify credentials."""
  85. try:
  86. # Try to fetch balance to test authentication
  87. # Use the same logic as get_balance for consistency
  88. params = {}
  89. if Config.HYPERLIQUID_PRIVATE_KEY:
  90. wallet_address = Config.HYPERLIQUID_PRIVATE_KEY
  91. params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
  92. balance = self.sync_client.fetch_balance(params=params)
  93. logger.info(f"🔗 Connection test successful")
  94. except Exception as e:
  95. logger.warning(f"⚠️ Connection test failed: {e}")
  96. logger.warning("💡 This might be normal if you have no positions/balance")
  97. def get_balance(self) -> Optional[Dict[str, Any]]:
  98. """Get account balance."""
  99. try:
  100. if not self.sync_client:
  101. logger.error("❌ Client not initialized")
  102. return None
  103. # For Hyperliquid, we need to pass the wallet address/user parameter
  104. # The user parameter should be the wallet address derived from private key
  105. params = {}
  106. # If we have a private key, derive the wallet address
  107. if Config.HYPERLIQUID_PRIVATE_KEY:
  108. # Extract the wallet address from the private key
  109. # For CCXT Hyperliquid, the user parameter should be the wallet address
  110. wallet_address = Config.HYPERLIQUID_PRIVATE_KEY
  111. if wallet_address.startswith('0x'):
  112. # Use the address as the user parameter
  113. params['user'] = wallet_address
  114. else:
  115. # If it's just the private key, we might need to derive the address
  116. # For now, try using the private key directly
  117. params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
  118. logger.debug(f"🔍 Fetching balance with params: {params}")
  119. balance = self.sync_client.fetch_balance(params=params)
  120. logger.info("✅ Successfully fetched balance")
  121. return balance
  122. except Exception as e:
  123. logger.error(f"❌ Error fetching balance: {e}")
  124. logger.debug(f"💡 Attempted with params: {params}")
  125. return None
  126. def get_balance_alternative(self) -> Optional[Dict[str, Any]]:
  127. """Alternative balance fetching method trying different approaches."""
  128. try:
  129. if not self.sync_client:
  130. logger.error("❌ Client not initialized")
  131. return None
  132. # Try different approaches for balance fetching
  133. approaches = [
  134. # Approach 1: No params (original)
  135. {},
  136. # Approach 2: Private key as user
  137. {'user': Config.HYPERLIQUID_PRIVATE_KEY},
  138. # Approach 3: Private key with 0x prefix
  139. {'user': f"0x{Config.HYPERLIQUID_PRIVATE_KEY}" if not Config.HYPERLIQUID_PRIVATE_KEY.startswith('0x') else Config.HYPERLIQUID_PRIVATE_KEY},
  140. # Approach 4: Empty user
  141. {'user': ''},
  142. ]
  143. for i, params in enumerate(approaches, 1):
  144. try:
  145. logger.info(f"🔍 Trying approach {i}: {params}")
  146. balance = self.sync_client.fetch_balance(params=params)
  147. logger.info(f"✅ Approach {i} successful!")
  148. return balance
  149. except Exception as e:
  150. logger.warning(f"⚠️ Approach {i} failed: {e}")
  151. continue
  152. logger.error("❌ All approaches failed")
  153. return None
  154. except Exception as e:
  155. logger.error(f"❌ Error in alternative balance fetch: {e}")
  156. return None
  157. def get_positions(self, symbol: Optional[str] = None) -> Optional[List[Dict[str, Any]]]:
  158. """Get current positions."""
  159. try:
  160. if not self.sync_client:
  161. logger.error("❌ Client not initialized")
  162. return None
  163. # Add user parameter for Hyperliquid CCXT compatibility
  164. params = {}
  165. if Config.HYPERLIQUID_PRIVATE_KEY:
  166. wallet_address = Config.HYPERLIQUID_PRIVATE_KEY
  167. params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
  168. logger.debug(f"🔍 Fetching positions with params: {params}")
  169. positions = self.sync_client.fetch_positions([symbol] if symbol else None, params=params)
  170. logger.info(f"✅ Successfully fetched positions for {symbol or 'all symbols'}")
  171. return positions
  172. except Exception as e:
  173. logger.error(f"❌ Error fetching positions: {e}")
  174. logger.debug(f"💡 Attempted with params: {params}")
  175. return None
  176. def get_market_data(self, symbol: str) -> Optional[Dict[str, Any]]:
  177. """Get market data for a symbol."""
  178. try:
  179. if not self.sync_client:
  180. logger.error("❌ Client not initialized")
  181. return None
  182. ticker = self.sync_client.fetch_ticker(symbol)
  183. orderbook = self.sync_client.fetch_order_book(symbol)
  184. market_data = {
  185. 'ticker': ticker,
  186. 'orderbook': orderbook,
  187. 'symbol': symbol
  188. }
  189. logger.info(f"✅ Successfully fetched market data for {symbol}")
  190. return market_data
  191. except Exception as e:
  192. logger.error(f"❌ Error fetching market data for {symbol}: {e}")
  193. return None
  194. def place_limit_order(self, symbol: str, side: str, amount: float, price: float, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
  195. """
  196. Place a limit order with CCXT-style parameters.
  197. Args:
  198. symbol: Trading symbol (e.g., 'BTC/USDC:USDC')
  199. side: 'buy' or 'sell'
  200. amount: Order amount
  201. price: Order price
  202. params: Additional parameters for CCXT compatibility
  203. """
  204. try:
  205. if not self.sync_client:
  206. logger.error("❌ Client not initialized")
  207. return None
  208. # CCXT-style order creation
  209. order_params = params or {}
  210. order = self.sync_client.create_limit_order(symbol, side, amount, price, params=order_params)
  211. logger.info(f"✅ Successfully placed {side} limit order for {amount} {symbol} at ${price}")
  212. logger.debug(f"📄 Order details: {order}")
  213. return order
  214. except Exception as e:
  215. logger.error(f"❌ Error placing limit order: {e}")
  216. return None
  217. def place_market_order(self, symbol: str, side: str, amount: float, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
  218. """
  219. Place a market order with CCXT-style parameters.
  220. Args:
  221. symbol: Trading symbol (e.g., 'BTC/USDC:USDC')
  222. side: 'buy' or 'sell'
  223. amount: Order amount
  224. params: Additional parameters for CCXT compatibility
  225. """
  226. try:
  227. if not self.sync_client:
  228. logger.error("❌ Client not initialized")
  229. return None
  230. # CCXT-style order creation
  231. order_params = params or {}
  232. order = self.sync_client.create_market_order(symbol, side, amount, params=order_params)
  233. logger.info(f"✅ Successfully placed {side} market order for {amount} {symbol}")
  234. logger.debug(f"📄 Order details: {order}")
  235. return order
  236. except Exception as e:
  237. logger.error(f"❌ Error placing market order: {e}")
  238. return None
  239. def get_open_orders(self, symbol: Optional[str] = None) -> Optional[List[Dict[str, Any]]]:
  240. """Get open orders."""
  241. try:
  242. if not self.sync_client:
  243. logger.error("❌ Client not initialized")
  244. return None
  245. # Add user parameter for Hyperliquid CCXT compatibility
  246. params = {}
  247. if Config.HYPERLIQUID_PRIVATE_KEY:
  248. wallet_address = Config.HYPERLIQUID_PRIVATE_KEY
  249. params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
  250. logger.debug(f"🔍 Fetching open orders with params: {params}")
  251. orders = self.sync_client.fetch_open_orders(symbol, params=params)
  252. logger.info(f"✅ Successfully fetched open orders for {symbol or 'all symbols'}")
  253. return orders
  254. except Exception as e:
  255. logger.error(f"❌ Error fetching open orders: {e}")
  256. logger.debug(f"💡 Attempted with params: {params}")
  257. return None
  258. def cancel_order(self, order_id: str, symbol: str, params: Optional[Dict] = None) -> bool:
  259. """Cancel an order with CCXT-style parameters."""
  260. try:
  261. if not self.sync_client:
  262. logger.error("❌ Client not initialized")
  263. return False
  264. cancel_params = params or {}
  265. result = self.sync_client.cancel_order(order_id, symbol, params=cancel_params)
  266. logger.info(f"✅ Successfully cancelled order {order_id}")
  267. return True
  268. except Exception as e:
  269. logger.error(f"❌ Error cancelling order {order_id}: {e}")
  270. return False
  271. def get_recent_trades(self, symbol: str, limit: int = 10) -> Optional[List[Dict[str, Any]]]:
  272. """Get recent trades for a symbol."""
  273. try:
  274. if not self.sync_client:
  275. logger.error("❌ Client not initialized")
  276. return None
  277. trades = self.sync_client.fetch_trades(symbol, limit=limit)
  278. logger.info(f"✅ Successfully fetched {len(trades)} recent trades for {symbol}")
  279. return trades
  280. except Exception as e:
  281. logger.error(f"❌ Error fetching recent trades for {symbol}: {e}")
  282. return None
  283. def get_trading_fee(self, symbol: str) -> Optional[Dict[str, Any]]:
  284. """Get trading fee for a symbol."""
  285. try:
  286. if not self.sync_client:
  287. logger.error("❌ Client not initialized")
  288. return None
  289. fee = self.sync_client.fetch_trading_fee(symbol)
  290. logger.info(f"✅ Successfully fetched trading fee for {symbol}")
  291. return fee
  292. except Exception as e:
  293. logger.error(f"❌ Error fetching trading fee for {symbol}: {e}")
  294. return None
  295. def get_markets(self) -> Optional[Dict[str, Any]]:
  296. """Get available markets/symbols."""
  297. try:
  298. if not self.sync_client:
  299. logger.error("❌ Client not initialized")
  300. return None
  301. markets = self.sync_client.load_markets()
  302. logger.info(f"✅ Successfully loaded {len(markets)} markets")
  303. return markets
  304. except Exception as e:
  305. logger.error(f"❌ Error loading markets: {e}")
  306. return None
  307. def place_stop_loss_order(self, symbol: str, side: str, amount: float, price: float, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
  308. """
  309. Place a stop loss order (implemented as a limit order).
  310. Args:
  311. symbol: Trading symbol (e.g., 'BTC/USDC:USDC')
  312. side: 'buy' or 'sell'
  313. amount: Order amount
  314. price: Stop loss price
  315. params: Additional parameters for CCXT compatibility
  316. """
  317. try:
  318. if not self.sync_client:
  319. logger.error("❌ Client not initialized")
  320. return None
  321. # Stop loss orders are implemented as limit orders
  322. # They will be filled when the market price reaches the stop price
  323. order_params = params or {}
  324. # Add order type information for clarity in logs
  325. logger.info(f"🛑 Placing stop loss order: {side} {amount} {symbol} @ ${price}")
  326. order = self.sync_client.create_limit_order(symbol, side, amount, price, params=order_params)
  327. logger.info(f"✅ Successfully placed stop loss order for {amount} {symbol} at ${price}")
  328. logger.debug(f"📄 Stop loss order details: {order}")
  329. return order
  330. except Exception as e:
  331. logger.error(f"❌ Error placing stop loss order: {e}")
  332. return None
  333. def place_take_profit_order(self, symbol: str, side: str, amount: float, price: float, params: Optional[Dict] = None) -> Optional[Dict[str, Any]]:
  334. """
  335. Place a take profit order (implemented as a limit order).
  336. Args:
  337. symbol: Trading symbol (e.g., 'BTC/USDC:USDC')
  338. side: 'buy' or 'sell'
  339. amount: Order amount
  340. price: Take profit price
  341. params: Additional parameters for CCXT compatibility
  342. """
  343. try:
  344. if not self.sync_client:
  345. logger.error("❌ Client not initialized")
  346. return None
  347. # Take profit orders are implemented as limit orders
  348. # They will be filled when the market price reaches the target price
  349. order_params = params or {}
  350. # Add order type information for clarity in logs
  351. logger.info(f"🎯 Placing take profit order: {side} {amount} {symbol} @ ${price}")
  352. order = self.sync_client.create_limit_order(symbol, side, amount, price, params=order_params)
  353. logger.info(f"✅ Successfully placed take profit order for {amount} {symbol} at ${price}")
  354. logger.debug(f"📄 Take profit order details: {order}")
  355. return order
  356. except Exception as e:
  357. logger.error(f"❌ Error placing take profit order: {e}")
  358. return None
  359. def get_recent_fills(self, limit: int = 100) -> Optional[List[Dict[str, Any]]]:
  360. """
  361. Get recent fills/trades for the account.
  362. Args:
  363. limit: Maximum number of fills to return
  364. Returns:
  365. List of recent fills/trades or None if error
  366. """
  367. try:
  368. if not self.sync_client:
  369. logger.error("❌ Client not initialized")
  370. return None
  371. # Add user parameter for Hyperliquid CCXT compatibility
  372. params = {}
  373. if Config.HYPERLIQUID_PRIVATE_KEY:
  374. wallet_address = Config.HYPERLIQUID_PRIVATE_KEY
  375. params['user'] = f"0x{wallet_address}" if not wallet_address.startswith('0x') else wallet_address
  376. # Fetch recent trades/fills for the account
  377. # Use fetch_my_trades to get account-specific trades
  378. logger.debug(f"🔍 Fetching recent fills with params: {params}")
  379. # Get recent fills across all symbols
  380. # We'll fetch trades for all symbols and merge them
  381. try:
  382. # Option 1: Try fetch_my_trades if available
  383. fills = self.sync_client.fetch_my_trades(None, limit=limit, params=params)
  384. logger.info(f"✅ Successfully fetched {len(fills)} recent fills")
  385. return fills
  386. except AttributeError:
  387. # Option 2: If fetch_my_trades not available, try alternative approach
  388. logger.debug("fetch_my_trades not available, trying alternative approach")
  389. # Get positions to determine active symbols
  390. positions = self.get_positions()
  391. if not positions:
  392. logger.info("No positions found, no recent fills to fetch")
  393. return []
  394. # Get symbols from positions
  395. symbols = list(set([pos.get('symbol') for pos in positions if pos.get('symbol')]))
  396. all_fills = []
  397. for symbol in symbols[:5]: # Limit to 5 symbols to avoid too many requests
  398. try:
  399. symbol_trades = self.sync_client.fetch_my_trades(symbol, limit=limit//len(symbols), params=params)
  400. if symbol_trades:
  401. all_fills.extend(symbol_trades)
  402. except Exception as e:
  403. logger.warning(f"Could not fetch trades for {symbol}: {e}")
  404. continue
  405. # Sort by timestamp (newest first)
  406. all_fills.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
  407. # Return only the requested limit
  408. result = all_fills[:limit]
  409. logger.info(f"✅ Successfully fetched {len(result)} recent fills from {len(symbols)} symbols")
  410. return result
  411. except Exception as e:
  412. logger.error(f"❌ Error fetching recent fills: {e}")
  413. logger.debug(f"💡 Attempted with params: {params}")
  414. return None