|
@@ -9,6 +9,7 @@ import telegram # Import telegram to check version
|
|
from datetime import datetime
|
|
from datetime import datetime
|
|
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
|
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
|
from telegram.ext import Application, ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
|
|
from telegram.ext import Application, ContextTypes, CommandHandler, CallbackQueryHandler, MessageHandler, filters
|
|
|
|
+import signal
|
|
|
|
|
|
from src.config.config import Config
|
|
from src.config.config import Config
|
|
from src.trading.trading_engine import TradingEngine
|
|
from src.trading.trading_engine import TradingEngine
|
|
@@ -330,55 +331,41 @@ For support or issues, check the logs or contact the administrator.
|
|
logger.error(f"Error sending help message in /help: {e}")
|
|
logger.error(f"Error sending help message in /help: {e}")
|
|
|
|
|
|
async def run(self):
|
|
async def run(self):
|
|
- """Run the Telegram bot with manual initialization and shutdown (v20.x style)."""
|
|
|
|
- if not Config.TELEGRAM_BOT_TOKEN:
|
|
|
|
- logger.error("❌ TELEGRAM_BOT_TOKEN not configured")
|
|
|
|
- return
|
|
|
|
|
|
+ """Run the bot."""
|
|
|
|
+ logger.info("🚀 Initializing bot application (v20.x style)...")
|
|
|
|
+ await self.application.initialize()
|
|
|
|
|
|
- if not Config.TELEGRAM_CHAT_ID:
|
|
|
|
- logger.error("❌ TELEGRAM_CHAT_ID not configured")
|
|
|
|
- return
|
|
|
|
|
|
+ logger.info(f"🚀 Starting Telegram trading bot v{self.version} (v20.x style)...")
|
|
|
|
|
|
- logger.info(f"🔧 Using python-telegram-bot version: {telegram.__version__} (Running in v20.x style)")
|
|
|
|
-
|
|
|
|
- # Create application
|
|
|
|
- self.application = Application.builder().token(Config.TELEGRAM_BOT_TOKEN).build()
|
|
|
|
|
|
+ await self.send_message(
|
|
|
|
+ f"🤖 <b>Manual Trading Bot v{self.version} Started (v20.x style)</b>\n\n"
|
|
|
|
+ f"✅ Connected to Hyperliquid {('Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet')}\n"
|
|
|
|
+ f"📊 Default Symbol: {Config.DEFAULT_TRADING_TOKEN}\n"
|
|
|
|
+ f"🔄 All systems ready!\n\n"
|
|
|
|
+ "Use /start for quick actions or /help for all commands."
|
|
|
|
+ )
|
|
|
|
|
|
- # Connect notification manager to the bot application
|
|
|
|
- self.notification_manager.set_bot_application(self.application)
|
|
|
|
|
|
+ await self.market_monitor.start()
|
|
|
|
|
|
- # Set up handlers
|
|
|
|
- self.setup_handlers()
|
|
|
|
|
|
+ logger.info("▶️ Starting PTB application's internal tasks (update processing, job queue).")
|
|
|
|
+ await self.application.start()
|
|
|
|
+ await self.application.updater.start_polling(drop_pending_updates=Config.TELEGRAM_DROP_PENDING_UPDATES)
|
|
|
|
|
|
- try:
|
|
|
|
- logger.info("🚀 Initializing bot application (v20.x style)...")
|
|
|
|
- await self.application.initialize()
|
|
|
|
-
|
|
|
|
- logger.info(f"🚀 Starting Telegram trading bot v{self.version} (v20.x style)...")
|
|
|
|
-
|
|
|
|
- await self.send_message(
|
|
|
|
- f"🤖 <b>Manual Trading Bot v{self.version} Started (v20.x style)</b>\n\n"
|
|
|
|
- f"✅ Connected to Hyperliquid {('Testnet' if Config.HYPERLIQUID_TESTNET else 'Mainnet')}\n"
|
|
|
|
- f"📊 Default Symbol: {Config.DEFAULT_TRADING_TOKEN}\n"
|
|
|
|
- f"🔄 All systems ready!\n\n"
|
|
|
|
- "Use /start for quick actions or /help for all commands."
|
|
|
|
- )
|
|
|
|
-
|
|
|
|
- await self.market_monitor.start()
|
|
|
|
-
|
|
|
|
- logger.info("▶️ Starting PTB application's internal tasks (update processing, job queue).")
|
|
|
|
- await self.application.start()
|
|
|
|
- await self.application.updater.start_polling(drop_pending_updates=Config.TELEGRAM_DROP_PENDING_UPDATES)
|
|
|
|
-
|
|
|
|
- logger.info("✅ Bot is initialized and polling. Awaiting stop signal or Ctrl+C.")
|
|
|
|
- # No need for keep_running_future with run_polling
|
|
|
|
|
|
+ logger.info("✅ Bot is initialized and polling. Awaiting stop signal or Ctrl+C.")
|
|
|
|
+
|
|
|
|
+ # Create a future to keep the bot running
|
|
|
|
+ stop_future = asyncio.Future()
|
|
|
|
|
|
- except (KeyboardInterrupt, SystemExit) as e: # Added SystemExit here
|
|
|
|
- logger.info(f"🛑 Bot run interrupted by {type(e).__name__}. Initiating shutdown (v20.x style)...")
|
|
|
|
|
|
+ # Set up signal handlers
|
|
|
|
+ loop = asyncio.get_running_loop()
|
|
|
|
+ for sig in (signal.SIGINT, signal.SIGTERM):
|
|
|
|
+ loop.add_signal_handler(sig, lambda: stop_future.set_result(None))
|
|
|
|
+
|
|
|
|
+ try:
|
|
|
|
+ # Keep the bot running until stop_future is set
|
|
|
|
+ await stop_future
|
|
except asyncio.CancelledError:
|
|
except asyncio.CancelledError:
|
|
logger.info("🛑 Bot run task cancelled. Initiating shutdown (v20.x style)...")
|
|
logger.info("🛑 Bot run task cancelled. Initiating shutdown (v20.x style)...")
|
|
- except Exception as e:
|
|
|
|
- logger.error(f"❌ Unhandled error in bot run loop (v20.x style): {e}", exc_info=True)
|
|
|
|
finally:
|
|
finally:
|
|
logger.info("🔌 Starting graceful shutdown sequence in TelegramTradingBot.run (v20.x style)...")
|
|
logger.info("🔌 Starting graceful shutdown sequence in TelegramTradingBot.run (v20.x style)...")
|
|
try:
|
|
try:
|
|
@@ -405,8 +392,8 @@ For support or issues, check the logs or contact the administrator.
|
|
logger.info("PTB application shut down.")
|
|
logger.info("PTB application shut down.")
|
|
else:
|
|
else:
|
|
logger.warning("Application object was None during shutdown in TelegramTradingBot.run.")
|
|
logger.warning("Application object was None during shutdown in TelegramTradingBot.run.")
|
|
-
|
|
|
|
|
|
+
|
|
logger.info("✅ Graceful shutdown sequence in TelegramTradingBot.run (v20.x style) complete.")
|
|
logger.info("✅ Graceful shutdown sequence in TelegramTradingBot.run (v20.x style) complete.")
|
|
-
|
|
|
|
|
|
+
|
|
except Exception as e:
|
|
except Exception as e:
|
|
logger.error(f"💥 Error during shutdown sequence in TelegramTradingBot.run (v20.x style): {e}", exc_info=True)
|
|
logger.error(f"💥 Error during shutdown sequence in TelegramTradingBot.run (v20.x style): {e}", exc_info=True)
|