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