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