import logging from typing import Dict, Any, Optional from telegram import Update from telegram.ext import ContextTypes from .base import InfoCommandsBase logger = logging.getLogger(__name__) class BalanceCommands(InfoCommandsBase): """Handles all balance-related commands.""" async def balance_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Handle the /balance command.""" try: if not self._is_authorized(update): await self._reply(update, "❌ Unauthorized access.") return stats = self.trading_engine.get_stats() if not stats: await self._reply(update, "❌ Trading stats not available.") return # Get balance info balance_info = stats.get_balance_info() if not balance_info: await self._reply(update, "❌ Balance information not available.") return # Format balance text balance_text = "💰 Account Balance\n\n" # Add total balance total_balance = balance_info.get('total_balance', 0.0) balance_text += f"💵 Total Balance: ${total_balance:,.2f}\n" # Add available balance available_balance = balance_info.get('available_balance', 0.0) balance_text += f"💳 Available Balance: ${available_balance:,.2f}\n" # Add margin used margin_used = balance_info.get('margin_used', 0.0) if margin_used > 0: balance_text += f"📊 Margin Used: ${margin_used:,.2f}\n" margin_ratio = (margin_used / total_balance) * 100 if total_balance > 0 else 0 balance_text += f"⚖️ Margin Ratio: {margin_ratio:.2f}%\n" # Add unrealized P&L unrealized_pnl = balance_info.get('unrealized_pnl', 0.0) pnl_emoji = "🟢" if unrealized_pnl >= 0 else "🔴" balance_text += f"{pnl_emoji} Unrealized P&L: ${unrealized_pnl:,.2f}\n" # Add realized P&L if available realized_pnl = balance_info.get('realized_pnl', 0.0) if realized_pnl != 0: realized_emoji = "🟢" if realized_pnl >= 0 else "🔴" balance_text += f"{realized_emoji} Realized P&L: ${realized_pnl:,.2f}\n" # Add total P&L total_pnl = unrealized_pnl + realized_pnl total_pnl_emoji = "🟢" if total_pnl >= 0 else "🔴" balance_text += f"{total_pnl_emoji} Total P&L: ${total_pnl:,.2f}\n" # Add P&L percentage if margin is used if margin_used > 0: pnl_percentage = (total_pnl / margin_used) * 100 balance_text += f"📈 Return on Margin: {pnl_percentage:+.2f}%\n" await self._reply(update, balance_text.strip()) except Exception as e: logger.error(f"Error in balance command: {e}") await self._reply(update, "❌ Error retrieving balance information.")