123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- #!/usr/bin/env python3
- """
- Web Server Entry Point for Hyperliquid Trading Bot
- This script starts the FastAPI web server that provides a web interface
- for the trading bot. It can be run alongside the existing Telegram bot.
- """
- import asyncio
- import logging
- import uvicorn
- from contextlib import asynccontextmanager
- from src.config.config import Config
- from src.config.logging_config import setup_logging
- from src.trading.trading_engine import TradingEngine
- from src.monitoring.monitoring_coordinator import MonitoringCoordinator
- from src.notifications.notification_manager import NotificationManager
- from src.web.app import create_app, initialize_app_dependencies
- # Setup logging
- setup_logging()
- logger = logging.getLogger(__name__)
- @asynccontextmanager
- async def lifespan(app):
- """Application lifespan context manager."""
- logger.info("🚀 Starting Hyperliquid Trading Bot Web UI...")
-
- # Validate configuration
- if not Config.validate():
- logger.error("❌ Configuration validation failed")
- raise SystemExit(1)
-
- if not Config.WEB_ENABLED:
- logger.error("❌ Web UI is disabled in configuration")
- raise SystemExit(1)
-
- # Initialize core components
- logger.info("🔧 Initializing trading engine...")
- trading_engine = TradingEngine()
- await trading_engine.async_init()
-
- logger.info("🔧 Initializing monitoring coordinator...")
- notification_manager = NotificationManager()
- monitoring_coordinator = MonitoringCoordinator(
- trading_engine.client,
- notification_manager,
- Config
- )
-
- # Initialize web app dependencies
- initialize_app_dependencies(trading_engine, monitoring_coordinator)
-
- logger.info("✅ Web UI startup complete")
-
- yield
-
- # Cleanup
- logger.info("🛑 Shutting down Web UI...")
-
- # Stop monitoring if running
- try:
- await monitoring_coordinator.stop()
- except Exception as e:
- logger.warning(f"Error stopping monitoring coordinator: {e}")
-
- # Close trading engine
- try:
- if hasattr(trading_engine, 'close'):
- trading_engine.close()
- except Exception as e:
- logger.warning(f"Error closing trading engine: {e}")
-
- logger.info("✅ Web UI shutdown complete")
- def main():
- """Main function to start the web server."""
-
- # Validate configuration first
- if not Config.WEB_ENABLED:
- print("❌ Web UI is disabled. Set WEB_ENABLED=true in your .env file")
- return
-
- if not Config.WEB_API_KEY:
- print("❌ WEB_API_KEY is required. Please set it in your .env file")
- return
-
- # Create FastAPI app with lifespan
- app = create_app()
- app.router.lifespan_context = lifespan
-
- # Print startup info
- print("\n" + "="*50)
- print("🚀 HYPERLIQUID TRADING BOT WEB UI")
- print("="*50)
- print(f"📍 URL: http://{Config.WEB_HOST}:{Config.WEB_PORT}")
- print(f"🔑 API Key: {Config.WEB_API_KEY[:8]}..." if Config.WEB_API_KEY else "🔑 API Key: Not set")
- print(f"🌐 Network: {'Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet'}")
- print(f"📊 Default Token: {Config.DEFAULT_TRADING_TOKEN}")
- print("="*50)
- print("💡 Quick Start:")
- print("1. Open the URL above in your browser")
- print("2. Enter your API key in the dashboard")
- print("3. View your trading performance and positions")
- print("="*50)
- print("\n🔄 Starting web server...\n")
-
- # Run the server
- uvicorn.run(
- app,
- host=Config.WEB_HOST,
- port=Config.WEB_PORT,
- log_level="info",
- access_log=True,
- lifespan="on"
- )
- if __name__ == "__main__":
- try:
- main()
- except KeyboardInterrupt:
- print("\n👋 Web server stopped by user")
- except Exception as e:
- print(f"\n❌ Error starting web server: {e}")
- logger.error(f"Error starting web server: {e}", exc_info=True)
|