web_start.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #!/usr/bin/env python3
  2. """
  3. Web Server Entry Point for Hyperliquid Trading Bot
  4. This script starts the FastAPI web server that provides a web interface
  5. for the trading bot. It can be run alongside the existing Telegram bot.
  6. """
  7. import asyncio
  8. import logging
  9. import uvicorn
  10. from contextlib import asynccontextmanager
  11. from src.config.config import Config
  12. from src.config.logging_config import setup_logging
  13. from src.trading.trading_engine import TradingEngine
  14. from src.monitoring.monitoring_coordinator import MonitoringCoordinator
  15. from src.notifications.notification_manager import NotificationManager
  16. from src.web.app import create_app, initialize_app_dependencies
  17. # Setup logging
  18. setup_logging()
  19. logger = logging.getLogger(__name__)
  20. @asynccontextmanager
  21. async def lifespan(app):
  22. """Application lifespan context manager."""
  23. logger.info("🚀 Starting Hyperliquid Trading Bot Web UI...")
  24. # Validate configuration
  25. if not Config.validate():
  26. logger.error("❌ Configuration validation failed")
  27. raise SystemExit(1)
  28. if not Config.WEB_ENABLED:
  29. logger.error("❌ Web UI is disabled in configuration")
  30. raise SystemExit(1)
  31. # Initialize core components
  32. logger.info("🔧 Initializing trading engine...")
  33. trading_engine = TradingEngine()
  34. await trading_engine.async_init()
  35. logger.info("🔧 Initializing monitoring coordinator...")
  36. notification_manager = NotificationManager()
  37. monitoring_coordinator = MonitoringCoordinator(
  38. trading_engine.client,
  39. notification_manager,
  40. Config
  41. )
  42. # Initialize web app dependencies
  43. initialize_app_dependencies(trading_engine, monitoring_coordinator)
  44. logger.info("✅ Web UI startup complete")
  45. yield
  46. # Cleanup
  47. logger.info("🛑 Shutting down Web UI...")
  48. # Stop monitoring if running
  49. try:
  50. await monitoring_coordinator.stop()
  51. except Exception as e:
  52. logger.warning(f"Error stopping monitoring coordinator: {e}")
  53. # Close trading engine
  54. try:
  55. if hasattr(trading_engine, 'close'):
  56. trading_engine.close()
  57. except Exception as e:
  58. logger.warning(f"Error closing trading engine: {e}")
  59. logger.info("✅ Web UI shutdown complete")
  60. def main():
  61. """Main function to start the web server."""
  62. # Validate configuration first
  63. if not Config.WEB_ENABLED:
  64. print("❌ Web UI is disabled. Set WEB_ENABLED=true in your .env file")
  65. return
  66. if not Config.WEB_API_KEY:
  67. print("❌ WEB_API_KEY is required. Please set it in your .env file")
  68. return
  69. # Create FastAPI app with lifespan
  70. app = create_app()
  71. app.router.lifespan_context = lifespan
  72. # Print startup info
  73. print("\n" + "="*50)
  74. print("🚀 HYPERLIQUID TRADING BOT WEB UI")
  75. print("="*50)
  76. print(f"📍 URL: http://{Config.WEB_HOST}:{Config.WEB_PORT}")
  77. print(f"🔑 API Key: {Config.WEB_API_KEY[:8]}..." if Config.WEB_API_KEY else "🔑 API Key: Not set")
  78. print(f"🌐 Network: {'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}")
  79. print(f"📊 Default Token: {Config.DEFAULT_TRADING_TOKEN}")
  80. print("="*50)
  81. print("💡 Quick Start:")
  82. print("1. Open the URL above in your browser")
  83. print("2. Enter your API key in the dashboard")
  84. print("3. View your trading performance and positions")
  85. print("="*50)
  86. print("\n🔄 Starting web server...\n")
  87. # Run the server
  88. uvicorn.run(
  89. app,
  90. host=Config.WEB_HOST,
  91. port=Config.WEB_PORT,
  92. log_level="info",
  93. access_log=True,
  94. lifespan="on"
  95. )
  96. if __name__ == "__main__":
  97. try:
  98. main()
  99. except KeyboardInterrupt:
  100. print("\n👋 Web server stopped by user")
  101. except Exception as e:
  102. print(f"\n❌ Error starting web server: {e}")
  103. logger.error(f"Error starting web server: {e}", exc_info=True)