manual_trading_bot.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. #!/usr/bin/env python3
  2. """
  3. Manual Trading Bot Launcher
  4. A focused launcher for manual Hyperliquid trading via Telegram.
  5. This script sets up comprehensive statistics tracking and phone-friendly controls.
  6. """
  7. import logging
  8. import asyncio
  9. import sys
  10. from datetime import datetime
  11. from config import Config
  12. from telegram_bot import TelegramTradingBot
  13. # Set up logging
  14. logging.basicConfig(
  15. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  16. level=getattr(logging, Config.LOG_LEVEL)
  17. )
  18. logger = logging.getLogger(__name__)
  19. def print_banner():
  20. """Print a nice startup banner."""
  21. banner = """
  22. ╔══════════════════════════════════════════════════════════════╗
  23. ║ 📱 MANUAL TRADING BOT ║
  24. ║ for Hyperliquid ║
  25. ╠══════════════════════════════════════════════════════════════╣
  26. ║ ║
  27. ║ 🤖 Control your account from your phone via Telegram ║
  28. ║ 📊 Comprehensive trading statistics tracking ║
  29. ║ 📈 Real-time P&L monitoring ║
  30. ║ 🛡️ Risk metrics (Sharpe, Sortino, VaR) ║
  31. ║ 📱 Mobile-optimized interface ║
  32. ║ ║
  33. ╚══════════════════════════════════════════════════════════════╝
  34. """
  35. print(banner)
  36. def validate_setup():
  37. """Validate that everything is set up correctly."""
  38. print("🔍 Validating configuration...")
  39. # Check configuration
  40. if not Config.validate():
  41. print("❌ Configuration validation failed!")
  42. return False
  43. # Check Telegram setup
  44. if not Config.TELEGRAM_ENABLED:
  45. print("❌ Telegram is not enabled in configuration")
  46. print("💡 Please set TELEGRAM_ENABLED=true in your .env file")
  47. return False
  48. if not Config.TELEGRAM_BOT_TOKEN:
  49. print("❌ TELEGRAM_BOT_TOKEN not configured")
  50. print("💡 Please add your Telegram bot token to .env file")
  51. return False
  52. if not Config.TELEGRAM_CHAT_ID:
  53. print("❌ TELEGRAM_CHAT_ID not configured")
  54. print("💡 Please run: python get_telegram_chat_id.py")
  55. return False
  56. # Check Hyperliquid setup
  57. if not Config.HYPERLIQUID_PRIVATE_KEY:
  58. print("❌ HYPERLIQUID_PRIVATE_KEY not configured")
  59. print("💡 Please add your private key to .env file")
  60. return False
  61. print("✅ Configuration validation passed!")
  62. return True
  63. def print_configuration():
  64. """Print current configuration."""
  65. print("\n📋 Current Configuration:")
  66. print(f"🌐 Network: {'Testnet' if Config.HYPERLIQUID_TESTNET else '🚨 MAINNET 🚨'}")
  67. print(f"📊 Trading Symbol: {Config.DEFAULT_TRADING_SYMBOL}")
  68. print(f"💰 Default Amount: {Config.DEFAULT_TRADE_AMOUNT}")
  69. print(f"💬 Telegram Bot: @{Config.TELEGRAM_BOT_TOKEN.split(':')[0] if Config.TELEGRAM_BOT_TOKEN else 'Not configured'}")
  70. print(f"🔑 Chat ID: {Config.TELEGRAM_CHAT_ID}")
  71. print(f"📈 Statistics: Enabled (saved to trading_stats.json)")
  72. if not Config.HYPERLIQUID_TESTNET:
  73. print("\n⚠️ WARNING: You are running on MAINNET!")
  74. print("💸 Real money will be used for trading!")
  75. response = input("Are you sure you want to continue? (type 'YES' to confirm): ")
  76. if response != 'YES':
  77. print("❌ Cancelled by user")
  78. return False
  79. return True
  80. def print_usage_guide():
  81. """Print usage guide."""
  82. print("""
  83. 📱 How to Use Your Manual Trading Bot:
  84. 1️⃣ Start Telegram and find your bot
  85. 2️⃣ Send /start to see quick action buttons
  86. 3️⃣ Use these commands for manual trading:
  87. 💼 ACCOUNT MONITORING:
  88. • /balance - Check your account balance
  89. • /positions - View open positions
  90. • /orders - See pending orders
  91. • /stats - Full trading statistics
  92. 🔄 MANUAL TRADING:
  93. • /buy 0.001 50000 - Buy 0.001 BTC at $50,000
  94. • /sell 0.001 55000 - Sell 0.001 BTC at $55,000
  95. • /trades - View recent trade history
  96. 📊 STATISTICS TRACKED:
  97. • 💰 Starting vs Current Balance
  98. • 📈 Total P&L and Return %
  99. • 🏆 Win Rate and Profit Factor
  100. • 📊 Sharpe & Sortino Ratios
  101. • 🎯 Max Drawdown and VaR
  102. • 🔄 Trade Count and Expectancy
  103. 🛡️ SAFETY FEATURES:
  104. • All trades require confirmation
  105. • Comprehensive logging
  106. • Real-time balance tracking
  107. • Risk metrics calculation
  108. • Order confirmations
  109. ⚠️ IMPORTANT:
  110. • Bot starts statistics tracking from first launch
  111. • All manual trades are automatically recorded
  112. • Statistics persist between bot restarts
  113. • Use /stats to see comprehensive performance metrics
  114. Ready to start manual trading from your phone! 🚀
  115. """)
  116. async def main():
  117. """Main function to start the manual trading bot."""
  118. try:
  119. print_banner()
  120. # Validate setup
  121. if not validate_setup():
  122. sys.exit(1)
  123. # Print configuration
  124. if not print_configuration():
  125. sys.exit(1)
  126. print_usage_guide()
  127. print("🚀 Starting Manual Trading Bot...")
  128. print("📱 Your phone controls are ready!")
  129. print("🔄 Statistics tracking initialized")
  130. print("⏰ Started at:", datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
  131. print("\n💡 Open Telegram and send /start to your bot!")
  132. print("🛑 Press Ctrl+C to stop the bot\n")
  133. # Create and run the bot
  134. bot = TelegramTradingBot()
  135. await bot.run()
  136. except KeyboardInterrupt:
  137. print("\n👋 Manual Trading Bot stopped by user")
  138. print("📊 Your trading statistics have been saved")
  139. print("🔄 Restart anytime to continue tracking!")
  140. except Exception as e:
  141. logger.error(f"❌ Unexpected error: {e}")
  142. print(f"\n❌ Error: {e}")
  143. print("💡 Check your configuration and try again")
  144. if __name__ == "__main__":
  145. asyncio.run(main())