simple_bot.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. #!/usr/bin/env python3
  2. """
  3. Simple Hyperliquid Trading Bot
  4. This is a basic trading bot that demonstrates:
  5. - Connecting to Hyperliquid
  6. - Fetching market data
  7. - Checking account balance
  8. - Basic trading functions
  9. Run with: python simple_bot.py
  10. """
  11. import time
  12. import json
  13. from typing import Dict, Any
  14. from hyperliquid_client import HyperliquidClient
  15. from config import Config
  16. class SimpleTradingBot:
  17. """A simple trading bot for demonstration purposes."""
  18. def __init__(self):
  19. """Initialize the trading bot."""
  20. print("🤖 Initializing Simple Trading Bot...")
  21. self.client = HyperliquidClient(use_testnet=Config.HYPERLIQUID_TESTNET)
  22. self.symbol = Config.DEFAULT_TRADING_SYMBOL
  23. self.is_running = False
  24. def print_banner(self):
  25. """Print a welcome banner."""
  26. print("=" * 60)
  27. print("🚀 HYPERLIQUID TRADING BOT")
  28. print("=" * 60)
  29. Config.print_config()
  30. print("=" * 60)
  31. def check_connection(self) -> bool:
  32. """Check if we can connect to Hyperliquid."""
  33. print("\n🔗 Testing connection to Hyperliquid...")
  34. # Try to fetch market data (doesn't require private key)
  35. market_data = self.client.get_market_data(self.symbol)
  36. if market_data:
  37. ticker = market_data['ticker']
  38. print(f"✅ Connection successful!")
  39. print(f"📊 {self.symbol} - Price: ${ticker.get('last', 'N/A')}")
  40. return True
  41. else:
  42. print("❌ Connection failed!")
  43. return False
  44. def show_account_info(self):
  45. """Display account information."""
  46. print("\n💰 Account Information:")
  47. # Get balance
  48. balance = self.client.get_balance()
  49. if balance:
  50. print("💳 Balance:")
  51. for asset, amount in balance.get('total', {}).items():
  52. if float(amount) > 0:
  53. print(f" {asset}: {amount}")
  54. else:
  55. print("❌ Could not fetch balance")
  56. # Get positions
  57. positions = self.client.get_positions()
  58. if positions and len(positions) > 0:
  59. print("📈 Open Positions:")
  60. for position in positions:
  61. if float(position.get('contracts', 0)) != 0:
  62. print(f" {position.get('symbol')}: {position.get('contracts')} contracts")
  63. else:
  64. print("📈 No open positions")
  65. # Get open orders
  66. orders = self.client.get_open_orders()
  67. if orders and len(orders) > 0:
  68. print("📋 Open Orders:")
  69. for order in orders:
  70. print(f" {order.get('symbol')}: {order.get('side')} {order.get('amount')} @ ${order.get('price')}")
  71. else:
  72. print("📋 No open orders")
  73. def show_market_data(self):
  74. """Display current market data."""
  75. print(f"\n📊 Market Data for {self.symbol}:")
  76. market_data = self.client.get_market_data(self.symbol)
  77. if market_data:
  78. ticker = market_data['ticker']
  79. orderbook = market_data['orderbook']
  80. print(f"💵 Price: ${ticker.get('last', 'N/A')}")
  81. print(f"📈 24h High: ${ticker.get('high', 'N/A')}")
  82. print(f"📉 24h Low: ${ticker.get('low', 'N/A')}")
  83. print(f"📊 24h Volume: {ticker.get('baseVolume', 'N/A')}")
  84. if orderbook.get('bids') and orderbook.get('asks'):
  85. best_bid = orderbook['bids'][0][0] if orderbook['bids'] else 'N/A'
  86. best_ask = orderbook['asks'][0][0] if orderbook['asks'] else 'N/A'
  87. print(f"🟢 Best Bid: ${best_bid}")
  88. print(f"🔴 Best Ask: ${best_ask}")
  89. else:
  90. print("❌ Could not fetch market data")
  91. def demo_trading_functions(self):
  92. """Demonstrate trading functions (without actually placing orders)."""
  93. print(f"\n🎯 Trading Demo (SIMULATION ONLY):")
  94. print("This would demonstrate trading functions, but we're in safe mode.")
  95. print("To enable real trading:")
  96. print("1. Set up your .env file with a real private key")
  97. print("2. Modify this function to actually place orders")
  98. print("3. Start with small amounts on testnet!")
  99. # Get current price for reference
  100. market_data = self.client.get_market_data(self.symbol)
  101. if market_data:
  102. current_price = float(market_data['ticker'].get('last', 0))
  103. print(f"\n📊 Current {self.symbol} price: ${current_price}")
  104. # Simulate order examples
  105. buy_price = current_price * 0.99 # 1% below market
  106. sell_price = current_price * 1.01 # 1% above market
  107. amount = Config.DEFAULT_TRADE_AMOUNT
  108. print(f"🟢 Example BUY order: {amount} {self.symbol} @ ${buy_price:.2f}")
  109. print(f"🔴 Example SELL order: {amount} {self.symbol} @ ${sell_price:.2f}")
  110. def interactive_menu(self):
  111. """Show an interactive menu for the bot."""
  112. while True:
  113. print("\n" + "=" * 40)
  114. print("🤖 Trading Bot Menu")
  115. print("=" * 40)
  116. print("1. Show Account Info")
  117. print("2. Show Market Data")
  118. print("3. Demo Trading Functions")
  119. print("4. Exit")
  120. print("=" * 40)
  121. choice = input("Select an option (1-4): ").strip()
  122. if choice == "1":
  123. self.show_account_info()
  124. elif choice == "2":
  125. self.show_market_data()
  126. elif choice == "3":
  127. self.demo_trading_functions()
  128. elif choice == "4":
  129. print("👋 Goodbye!")
  130. break
  131. else:
  132. print("❌ Invalid choice. Please try again.")
  133. def run(self):
  134. """Main bot execution."""
  135. self.print_banner()
  136. # Validate configuration
  137. if not Config.validate():
  138. print("\n❌ Configuration validation failed!")
  139. print("Please set up your .env file based on env.example")
  140. return
  141. # Test connection
  142. if not self.check_connection():
  143. print("❌ Could not connect to Hyperliquid. Please check your configuration.")
  144. return
  145. # Show initial account info
  146. self.show_account_info()
  147. # Start interactive menu
  148. self.interactive_menu()
  149. def main():
  150. """Main entry point."""
  151. try:
  152. bot = SimpleTradingBot()
  153. bot.run()
  154. except KeyboardInterrupt:
  155. print("\n\n👋 Bot stopped by user")
  156. except Exception as e:
  157. print(f"\n❌ Unexpected error: {e}")
  158. if __name__ == "__main__":
  159. main()