#!/usr/bin/env python3 """ Simple Hyperliquid Trading Bot This is a basic trading bot that demonstrates: - Connecting to Hyperliquid - Fetching market data - Checking account balance - Basic trading functions Run with: python simple_bot.py """ import time import json from typing import Dict, Any from hyperliquid_client import HyperliquidClient from config import Config class SimpleTradingBot: """A simple trading bot for demonstration purposes.""" def __init__(self): """Initialize the trading bot.""" print("šŸ¤– Initializing Simple Trading Bot...") self.client = HyperliquidClient(use_testnet=Config.HYPERLIQUID_TESTNET) self.symbol = Config.DEFAULT_TRADING_SYMBOL self.is_running = False def print_banner(self): """Print a welcome banner.""" print("=" * 60) print("šŸš€ HYPERLIQUID TRADING BOT") print("=" * 60) Config.print_config() print("=" * 60) def check_connection(self) -> bool: """Check if we can connect to Hyperliquid.""" print("\nšŸ”— Testing connection to Hyperliquid...") # Try to fetch market data (doesn't require private key) market_data = self.client.get_market_data(self.symbol) if market_data: ticker = market_data['ticker'] print(f"āœ… Connection successful!") print(f"šŸ“Š {self.symbol} - Price: ${ticker.get('last', 'N/A')}") return True else: print("āŒ Connection failed!") return False def show_account_info(self): """Display account information.""" print("\nšŸ’° Account Information:") # Get balance balance = self.client.get_balance() if balance: print("šŸ’³ Balance:") for asset, amount in balance.get('total', {}).items(): if float(amount) > 0: print(f" {asset}: {amount}") else: print("āŒ Could not fetch balance") # Get positions positions = self.client.get_positions() if positions and len(positions) > 0: print("šŸ“ˆ Open Positions:") for position in positions: if float(position.get('contracts', 0)) != 0: print(f" {position.get('symbol')}: {position.get('contracts')} contracts") else: print("šŸ“ˆ No open positions") # Get open orders orders = self.client.get_open_orders() if orders and len(orders) > 0: print("šŸ“‹ Open Orders:") for order in orders: print(f" {order.get('symbol')}: {order.get('side')} {order.get('amount')} @ ${order.get('price')}") else: print("šŸ“‹ No open orders") def show_market_data(self): """Display current market data.""" print(f"\nšŸ“Š Market Data for {self.symbol}:") market_data = self.client.get_market_data(self.symbol) if market_data: ticker = market_data['ticker'] orderbook = market_data['orderbook'] print(f"šŸ’µ Price: ${ticker.get('last', 'N/A')}") print(f"šŸ“ˆ 24h High: ${ticker.get('high', 'N/A')}") print(f"šŸ“‰ 24h Low: ${ticker.get('low', 'N/A')}") print(f"šŸ“Š 24h Volume: {ticker.get('baseVolume', 'N/A')}") if orderbook.get('bids') and orderbook.get('asks'): best_bid = orderbook['bids'][0][0] if orderbook['bids'] else 'N/A' best_ask = orderbook['asks'][0][0] if orderbook['asks'] else 'N/A' print(f"🟢 Best Bid: ${best_bid}") print(f"šŸ”“ Best Ask: ${best_ask}") else: print("āŒ Could not fetch market data") def demo_trading_functions(self): """Demonstrate trading functions (without actually placing orders).""" print(f"\nšŸŽÆ Trading Demo (SIMULATION ONLY):") print("This would demonstrate trading functions, but we're in safe mode.") print("To enable real trading:") print("1. Set up your .env file with a real private key") print("2. Modify this function to actually place orders") print("3. Start with small amounts on testnet!") # Get current price for reference market_data = self.client.get_market_data(self.symbol) if market_data: current_price = float(market_data['ticker'].get('last', 0)) print(f"\nšŸ“Š Current {self.symbol} price: ${current_price}") # Simulate order examples buy_price = current_price * 0.99 # 1% below market sell_price = current_price * 1.01 # 1% above market amount = Config.DEFAULT_TRADE_AMOUNT print(f"🟢 Example BUY order: {amount} {self.symbol} @ ${buy_price:.2f}") print(f"šŸ”“ Example SELL order: {amount} {self.symbol} @ ${sell_price:.2f}") def interactive_menu(self): """Show an interactive menu for the bot.""" while True: print("\n" + "=" * 40) print("šŸ¤– Trading Bot Menu") print("=" * 40) print("1. Show Account Info") print("2. Show Market Data") print("3. Demo Trading Functions") print("4. Exit") print("=" * 40) choice = input("Select an option (1-4): ").strip() if choice == "1": self.show_account_info() elif choice == "2": self.show_market_data() elif choice == "3": self.demo_trading_functions() elif choice == "4": print("šŸ‘‹ Goodbye!") break else: print("āŒ Invalid choice. Please try again.") def run(self): """Main bot execution.""" self.print_banner() # Validate configuration if not Config.validate(): print("\nāŒ Configuration validation failed!") print("Please set up your .env file based on env.example") return # Test connection if not self.check_connection(): print("āŒ Could not connect to Hyperliquid. Please check your configuration.") return # Show initial account info self.show_account_info() # Start interactive menu self.interactive_menu() def main(): """Main entry point.""" try: bot = SimpleTradingBot() bot.run() except KeyboardInterrupt: print("\n\nšŸ‘‹ Bot stopped by user") except Exception as e: print(f"\nāŒ Unexpected error: {e}") if __name__ == "__main__": main()