balance.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import logging
  2. from typing import Dict, Any, Optional
  3. from telegram import Update
  4. from telegram.ext import ContextTypes
  5. from .base import InfoCommandsBase
  6. logger = logging.getLogger(__name__)
  7. class BalanceCommands(InfoCommandsBase):
  8. """Handles all balance-related commands."""
  9. async def balance_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
  10. """Handle the /balance command."""
  11. try:
  12. if not self._is_authorized(update):
  13. await self._reply(update, "❌ Unauthorized access.")
  14. return
  15. stats = self.trading_engine.get_stats()
  16. if not stats:
  17. await self._reply(update, "❌ Trading stats not available.")
  18. return
  19. # Get balance info
  20. balance_info = stats.get_balance_info()
  21. if not balance_info:
  22. await self._reply(update, "❌ Balance information not available.")
  23. return
  24. # Format balance text
  25. balance_text = "💰 <b>Account Balance</b>\n\n"
  26. # Add total balance
  27. total_balance = balance_info.get('total_balance', 0.0)
  28. balance_text += f"💵 Total Balance: ${total_balance:,.2f}\n"
  29. # Add available balance
  30. available_balance = balance_info.get('available_balance', 0.0)
  31. balance_text += f"💳 Available Balance: ${available_balance:,.2f}\n"
  32. # Add margin used
  33. margin_used = balance_info.get('margin_used', 0.0)
  34. if margin_used > 0:
  35. balance_text += f"📊 Margin Used: ${margin_used:,.2f}\n"
  36. margin_ratio = (margin_used / total_balance) * 100 if total_balance > 0 else 0
  37. balance_text += f"⚖️ Margin Ratio: {margin_ratio:.2f}%\n"
  38. # Add unrealized P&L
  39. unrealized_pnl = balance_info.get('unrealized_pnl', 0.0)
  40. pnl_emoji = "🟢" if unrealized_pnl >= 0 else "🔴"
  41. balance_text += f"{pnl_emoji} Unrealized P&L: ${unrealized_pnl:,.2f}\n"
  42. # Add realized P&L if available
  43. realized_pnl = balance_info.get('realized_pnl', 0.0)
  44. if realized_pnl != 0:
  45. realized_emoji = "🟢" if realized_pnl >= 0 else "🔴"
  46. balance_text += f"{realized_emoji} Realized P&L: ${realized_pnl:,.2f}\n"
  47. # Add total P&L
  48. total_pnl = unrealized_pnl + realized_pnl
  49. total_pnl_emoji = "🟢" if total_pnl >= 0 else "🔴"
  50. balance_text += f"{total_pnl_emoji} Total P&L: ${total_pnl:,.2f}\n"
  51. # Add P&L percentage if margin is used
  52. if margin_used > 0:
  53. pnl_percentage = (total_pnl / margin_used) * 100
  54. balance_text += f"📈 Return on Margin: {pnl_percentage:+.2f}%\n"
  55. await self._reply(update, balance_text.strip())
  56. except Exception as e:
  57. logger.error(f"Error in balance command: {e}")
  58. await self._reply(update, "❌ Error retrieving balance information.")