1
Fork 0
crypto_bot_training/trading_bot/main.py
2025-07-15 08:18:00 +07:00

145 lines
No EOL
4.4 KiB
Python

#!/usr/bin/env python3
"""
Binance Trading Bot - Main Entry Point
Advanced crypto trading bot with WebSocket connection, technical indicators,
and automated trading capabilities.
Features:
- Real-time Binance WebSocket connection
- Bollinger Bands & Moving Average indicators
- Automated buy/sell execution
- Risk management with stop-loss/take-profit
- Performance tracking system
- Docker deployment ready
- Environment variable configuration
"""
import asyncio
import logging
import signal
import sys
from datetime import datetime
from typing import Dict, Any
from bot_core.bot import TradingBot
from bot_core.config import Config
from bot_core.logger import setup_logger
class BotManager:
"""Main bot manager that handles lifecycle and signals"""
def __init__(self):
self.bot: TradingBot = None
self.config: Config = None
self.logger = None
self.running = False
async def initialize(self):
"""Initialize bot configuration and components"""
try:
# Load configuration
self.config = Config()
# Setup logging
self.logger = setup_logger(
name="TradingBot",
level=self.config.LOG_LEVEL,
log_file=self.config.LOG_FILE
)
self.logger.info("=" * 60)
self.logger.info("🚀 BINANCE TRADING BOT STARTING")
self.logger.info("=" * 60)
# Log configuration
self.logger.info(f"Trading Symbol: {self.config.SYMBOL}")
self.logger.info(f"Position Size: {self.config.POSITION_SIZE}")
self.logger.info(f"Risk Management: SL={self.config.STOP_LOSS_PERCENT}%, TP={self.config.TAKE_PROFIT_PERCENT}%")
self.logger.info(f"Bollinger Bands: Period={self.config.BOLLINGER_PERIOD}, STD={self.config.BOLLINGER_STD}")
self.logger.info(f"Moving Average: Period={self.config.MA_PERIOD}")
# Initialize trading bot
self.bot = TradingBot(self.config, self.logger)
await self.bot.initialize()
self.logger.info("✅ Bot initialization completed successfully")
except Exception as e:
if self.logger:
self.logger.error(f"❌ Failed to initialize bot: {e}")
else:
print(f"❌ Failed to initialize bot: {e}")
raise
async def start(self):
"""Start the trading bot"""
try:
self.running = True
self.logger.info("🎯 Starting trading bot...")
# Start bot
await self.bot.start()
# Keep running until stopped
while self.running:
await asyncio.sleep(1)
except Exception as e:
self.logger.error(f"❌ Bot encountered error: {e}")
await self.stop()
raise
async def stop(self):
"""Stop the trading bot gracefully"""
if not self.running:
return
self.logger.info("🛑 Stopping trading bot...")
self.running = False
if self.bot:
await self.bot.stop()
self.logger.info("✅ Bot stopped successfully")
def setup_signal_handlers(self):
"""Setup signal handlers for graceful shutdown"""
def signal_handler(signum, frame):
self.logger.info(f"📡 Received signal {signum}, initiating graceful shutdown...")
asyncio.create_task(self.stop())
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
async def main():
"""Main function"""
bot_manager = BotManager()
try:
# Setup signal handlers
bot_manager.setup_signal_handlers()
# Initialize and start bot
await bot_manager.initialize()
await bot_manager.start()
except KeyboardInterrupt:
print("\n🔴 KeyboardInterrupt received")
await bot_manager.stop()
except Exception as e:
print(f"❌ Critical error: {e}")
await bot_manager.stop()
sys.exit(1)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n👋 Bot shutdown complete")
except Exception as e:
print(f"❌ Fatal error: {e}")
sys.exit(1)