trading_stats.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. #!/usr/bin/env python3
  2. """
  3. Trading Statistics Tracker (Refactored Version)
  4. Main class that coordinates between specialized manager components.
  5. """
  6. import logging
  7. from datetime import datetime, timezone
  8. from typing import Dict, List, Any, Optional, Tuple
  9. import math
  10. import numpy as np
  11. import uuid
  12. from .database_manager import DatabaseManager
  13. from .order_manager import OrderManager
  14. from .trade_lifecycle_manager import TradeLifecycleManager
  15. from .aggregation_manager import AggregationManager
  16. from .performance_calculator import PerformanceCalculator
  17. from src.utils.token_display_formatter import get_formatter
  18. logger = logging.getLogger(__name__)
  19. def _normalize_token_case(token: str) -> str:
  20. """Normalize token case for consistency."""
  21. if any(c.isupper() for c in token):
  22. return token # Keep original case for mixed-case tokens
  23. else:
  24. return token.upper() # Convert to uppercase for all-lowercase
  25. class TradingStats:
  26. """Refactored trading statistics tracker using modular components."""
  27. def __init__(self, db_path: str = "data/trading_stats.sqlite"):
  28. """Initialize with all manager components."""
  29. # Initialize core database manager
  30. self.db_manager = DatabaseManager(db_path)
  31. # Initialize specialized managers
  32. self.order_manager = OrderManager(self.db_manager)
  33. self.trade_manager = TradeLifecycleManager(self.db_manager)
  34. self.aggregation_manager = AggregationManager(self.db_manager)
  35. self.performance_calculator = PerformanceCalculator(self.db_manager)
  36. logger.info("🚀 TradingStats initialized with modular components")
  37. def close(self):
  38. """Close database connection."""
  39. self.db_manager.close()
  40. # =============================================================================
  41. # COMPATIBILITY METHODS - Direct exposure of internal methods
  42. # =============================================================================
  43. def _get_metadata(self, key: str) -> Optional[str]:
  44. """Get metadata from database."""
  45. return self.db_manager._get_metadata(key)
  46. def _set_metadata(self, key: str, value: str):
  47. """Set metadata in database."""
  48. return self.db_manager._set_metadata(key, value)
  49. # =============================================================================
  50. # DATABASE MANAGEMENT DELEGATION
  51. # =============================================================================
  52. def set_initial_balance(self, balance: float):
  53. """Set initial balance."""
  54. return self.db_manager.set_initial_balance(balance)
  55. def get_initial_balance(self) -> float:
  56. """Get initial balance."""
  57. return self.db_manager.get_initial_balance()
  58. def record_balance_snapshot(self, balance: float, unrealized_pnl: float = 0.0,
  59. timestamp: Optional[str] = None, notes: Optional[str] = None):
  60. """Record balance snapshot."""
  61. return self.db_manager.record_balance_snapshot(balance, unrealized_pnl, timestamp, notes)
  62. def purge_old_balance_history(self, days_to_keep: int = 30) -> int:
  63. """Purge old balance history."""
  64. return self.db_manager.purge_old_balance_history(days_to_keep)
  65. def get_balance_history_record_count(self) -> int:
  66. """Get balance history record count."""
  67. return self.db_manager.get_balance_history_record_count()
  68. def purge_old_daily_aggregated_stats(self, days_to_keep: int = 365) -> int:
  69. """Purge old daily aggregated stats."""
  70. return self.db_manager.purge_old_daily_aggregated_stats(days_to_keep)
  71. # =============================================================================
  72. # ORDER MANAGEMENT DELEGATION
  73. # =============================================================================
  74. def record_order_placed(self, symbol: str, side: str, order_type: str,
  75. amount_requested: float, price: Optional[float] = None,
  76. bot_order_ref_id: Optional[str] = None,
  77. exchange_order_id: Optional[str] = None,
  78. timestamp: Optional[str] = None) -> bool:
  79. """Record order placement."""
  80. result = self.order_manager.record_order_placed(
  81. symbol, side, order_type, amount_requested, price,
  82. bot_order_ref_id, exchange_order_id
  83. )
  84. return result is not None
  85. def update_order_exchange_id(self, bot_order_ref_id: str, exchange_order_id: str) -> bool:
  86. """Update order with exchange ID."""
  87. return self.order_manager.update_order_exchange_id(bot_order_ref_id, exchange_order_id)
  88. def record_order_filled(self, exchange_order_id: str, actual_amount: float,
  89. actual_price: float, fees: float = 0.0,
  90. timestamp: Optional[str] = None,
  91. exchange_fill_id: Optional[str] = None) -> bool:
  92. """Record order fill."""
  93. return self.order_manager.record_order_filled(
  94. exchange_order_id, actual_amount, actual_price, fees, timestamp, exchange_fill_id
  95. )
  96. def record_order_cancelled(self, exchange_order_id: str, reason: str = "user_cancelled",
  97. timestamp: Optional[str] = None) -> bool:
  98. """Record order cancellation."""
  99. return self.order_manager.record_order_cancelled(exchange_order_id, reason, timestamp)
  100. def update_order_status(self, exchange_order_id: str, new_status: str,
  101. notes: Optional[str] = None, timestamp: Optional[str] = None) -> bool:
  102. """Update order status."""
  103. return self.order_manager.update_order_status(exchange_order_id, new_status, notes, timestamp)
  104. def get_order_by_exchange_id(self, exchange_order_id: str) -> Optional[Dict[str, Any]]:
  105. """Get order by exchange ID."""
  106. return self.order_manager.get_order_by_exchange_id(exchange_order_id)
  107. def get_order_by_bot_ref_id(self, bot_order_ref_id: str) -> Optional[Dict[str, Any]]:
  108. """Get order by bot reference ID."""
  109. return self.order_manager.get_order_by_bot_ref_id(bot_order_ref_id)
  110. def get_orders_by_symbol(self, symbol: str, limit: int = 50) -> List[Dict[str, Any]]:
  111. """Get orders by symbol."""
  112. return self.order_manager.get_orders_by_symbol(symbol, limit)
  113. def get_orders_by_status(self, status: str, limit: Optional[int] = 50,
  114. order_type_filter: Optional[str] = None,
  115. parent_bot_order_ref_id: Optional[str] = None) -> List[Dict[str, Any]]:
  116. """Get orders by status with optional filters."""
  117. # OrderManager expects (status, order_type_filter, parent_bot_order_ref_id) without limit
  118. return self.order_manager.get_orders_by_status(status, order_type_filter, parent_bot_order_ref_id)
  119. def get_recent_orders(self, limit: int = 20) -> List[Dict[str, Any]]:
  120. """Get recent orders."""
  121. return self.order_manager.get_recent_orders(limit)
  122. def cleanup_old_cancelled_orders(self, days_old: int = 7) -> int:
  123. """Clean up old cancelled orders."""
  124. return self.order_manager.cleanup_old_cancelled_orders(days_old)
  125. # =============================================================================
  126. # TRADE LIFECYCLE DELEGATION
  127. # =============================================================================
  128. def create_trade_lifecycle(self, symbol: str, side: str, entry_order_id: Optional[str] = None,
  129. entry_bot_order_ref_id: Optional[str] = None,
  130. stop_loss_price: Optional[float] = None,
  131. take_profit_price: Optional[float] = None,
  132. trade_type: str = 'manual') -> Optional[str]:
  133. """Create trade lifecycle."""
  134. return self.trade_manager.create_trade_lifecycle(
  135. symbol, side, entry_order_id, entry_bot_order_ref_id,
  136. stop_loss_price, take_profit_price, trade_type
  137. )
  138. def update_trade_position_opened(self, lifecycle_id: str, entry_price: float,
  139. entry_amount: float, exchange_fill_id: str) -> bool:
  140. """Update trade position opened."""
  141. return self.trade_manager.update_trade_position_opened(
  142. lifecycle_id, entry_price, entry_amount, exchange_fill_id
  143. )
  144. def update_trade_position_closed(self, lifecycle_id: str, exit_price: float,
  145. realized_pnl: float, exchange_fill_id: str) -> bool:
  146. """Update trade position closed."""
  147. return self.trade_manager.update_trade_position_closed(
  148. lifecycle_id, exit_price, realized_pnl, exchange_fill_id
  149. )
  150. def update_trade_cancelled(self, lifecycle_id: str, reason: str = "order_cancelled") -> bool:
  151. """Update trade cancelled."""
  152. return self.trade_manager.update_trade_cancelled(lifecycle_id, reason)
  153. def link_stop_loss_to_trade(self, lifecycle_id: str, stop_loss_order_id: str,
  154. stop_loss_price: float) -> bool:
  155. """Link stop loss to trade."""
  156. return self.trade_manager.link_stop_loss_to_trade(
  157. lifecycle_id, stop_loss_order_id, stop_loss_price
  158. )
  159. def link_take_profit_to_trade(self, lifecycle_id: str, take_profit_order_id: str,
  160. take_profit_price: float) -> bool:
  161. """Link take profit to trade."""
  162. return self.trade_manager.link_take_profit_to_trade(
  163. lifecycle_id, take_profit_order_id, take_profit_price
  164. )
  165. def get_trade_by_lifecycle_id(self, lifecycle_id: str) -> Optional[Dict[str, Any]]:
  166. """Get trade by lifecycle ID."""
  167. return self.trade_manager.get_trade_by_lifecycle_id(lifecycle_id)
  168. def get_trade_by_symbol_and_status(self, symbol: str, status: str = 'position_opened') -> Optional[Dict[str, Any]]:
  169. """Get trade by symbol and status."""
  170. return self.trade_manager.get_trade_by_symbol_and_status(symbol, status)
  171. def get_open_positions(self, symbol: Optional[str] = None) -> List[Dict[str, Any]]:
  172. """Get open positions."""
  173. return self.trade_manager.get_open_positions(symbol)
  174. def get_trades_by_status(self, status: str, limit: int = 50) -> List[Dict[str, Any]]:
  175. """Get trades by status."""
  176. return self.trade_manager.get_trades_by_status(status, limit)
  177. def get_lifecycle_by_entry_order_id(self, entry_exchange_order_id: str, status: Optional[str] = None) -> Optional[Dict[str, Any]]:
  178. """Get lifecycle by entry order ID."""
  179. return self.trade_manager.get_lifecycle_by_entry_order_id(entry_exchange_order_id, status)
  180. def get_lifecycle_by_sl_order_id(self, sl_exchange_order_id: str, status: str = 'position_opened') -> Optional[Dict[str, Any]]:
  181. """Get lifecycle by stop loss order ID."""
  182. return self.trade_manager.get_lifecycle_by_sl_order_id(sl_exchange_order_id, status)
  183. def get_lifecycle_by_tp_order_id(self, tp_exchange_order_id: str, status: str = 'position_opened') -> Optional[Dict[str, Any]]:
  184. """Get lifecycle by take profit order ID."""
  185. return self.trade_manager.get_lifecycle_by_tp_order_id(tp_exchange_order_id, status)
  186. def get_pending_stop_loss_activations(self) -> List[Dict[str, Any]]:
  187. """Get pending stop loss activations."""
  188. return self.trade_manager.get_pending_stop_loss_activations()
  189. def cleanup_old_cancelled_trades(self, days_old: int = 7) -> int:
  190. """Clean up old cancelled trades."""
  191. return self.trade_manager.cleanup_old_cancelled_trades(days_old)
  192. def confirm_position_with_exchange(self, symbol: str, exchange_position_size: float,
  193. exchange_open_orders: List[Dict]) -> bool:
  194. """Confirm position with exchange."""
  195. return self.trade_manager.confirm_position_with_exchange(
  196. symbol, exchange_position_size, exchange_open_orders
  197. )
  198. def update_trade_market_data(self, trade_lifecycle_id: str, **kwargs) -> bool:
  199. """Update trade market data."""
  200. return self.trade_manager.update_trade_market_data(trade_lifecycle_id, **kwargs)
  201. def get_recent_trades(self, limit: int = 10) -> List[Dict[str, Any]]:
  202. """Get recent trades."""
  203. return self.trade_manager.get_recent_trades(limit)
  204. def get_all_trades(self) -> List[Dict[str, Any]]:
  205. """Get all trades."""
  206. return self.trade_manager.get_all_trades()
  207. # =============================================================================
  208. # AGGREGATION MANAGEMENT DELEGATION
  209. # =============================================================================
  210. def migrate_trade_to_aggregated_stats(self, trade_lifecycle_id: str):
  211. """Migrate trade to aggregated stats."""
  212. return self.aggregation_manager.migrate_trade_to_aggregated_stats(trade_lifecycle_id)
  213. def record_deposit(self, amount: float, timestamp: Optional[str] = None,
  214. deposit_id: Optional[str] = None, description: Optional[str] = None):
  215. """Record deposit."""
  216. return self.aggregation_manager.record_deposit(amount, timestamp, deposit_id, description)
  217. def record_withdrawal(self, amount: float, timestamp: Optional[str] = None,
  218. withdrawal_id: Optional[str] = None, description: Optional[str] = None):
  219. """Record withdrawal."""
  220. return self.aggregation_manager.record_withdrawal(amount, timestamp, withdrawal_id, description)
  221. def get_balance_adjustments_summary(self) -> Dict[str, Any]:
  222. """Get balance adjustments summary."""
  223. return self.aggregation_manager.get_balance_adjustments_summary()
  224. def get_daily_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  225. """Get daily stats."""
  226. return self.aggregation_manager.get_daily_stats(limit)
  227. def get_weekly_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  228. """Get weekly stats."""
  229. return self.aggregation_manager.get_weekly_stats(limit)
  230. def get_monthly_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  231. """Get monthly stats."""
  232. return self.aggregation_manager.get_monthly_stats(limit)
  233. # =============================================================================
  234. # PERFORMANCE CALCULATION DELEGATION
  235. # =============================================================================
  236. def get_performance_stats(self) -> Dict[str, Any]:
  237. """Get performance stats."""
  238. return self.performance_calculator.get_performance_stats()
  239. def get_token_performance(self, limit: int = 20) -> List[Dict[str, Any]]:
  240. """Get token performance."""
  241. return self.performance_calculator.get_token_performance(limit)
  242. def get_balance_history(self, days: int = 30) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
  243. """Get balance history."""
  244. return self.performance_calculator.get_balance_history(days)
  245. def get_live_max_drawdown(self) -> Tuple[float, float]:
  246. """Get live max drawdown."""
  247. return self.performance_calculator.get_live_max_drawdown()
  248. def update_live_max_drawdown(self, current_balance: float) -> bool:
  249. """Update live max drawdown."""
  250. return self.performance_calculator.update_live_max_drawdown(current_balance)
  251. def calculate_sharpe_ratio(self, days: int = 30) -> Optional[float]:
  252. """Calculate Sharpe ratio."""
  253. return self.performance_calculator.calculate_sharpe_ratio(days)
  254. def calculate_max_consecutive_losses(self) -> int:
  255. """Calculate max consecutive losses."""
  256. return self.performance_calculator.calculate_max_consecutive_losses()
  257. def get_risk_metrics(self) -> Dict[str, Any]:
  258. """Get risk metrics."""
  259. return self.performance_calculator.get_risk_metrics()
  260. def get_period_performance(self, start_date: str, end_date: str) -> Dict[str, Any]:
  261. """Get period performance."""
  262. return self.performance_calculator.get_period_performance(start_date, end_date)
  263. def get_recent_performance_trend(self, days: int = 7) -> Dict[str, Any]:
  264. """Get recent performance trend."""
  265. return self.performance_calculator.get_recent_performance_trend(days)
  266. # =============================================================================
  267. # COMPATIBILITY METHODS - Legacy API Support
  268. # =============================================================================
  269. def get_basic_stats(self, current_balance: Optional[float] = None) -> Dict[str, Any]:
  270. """Get basic trading statistics from DB, primarily using aggregated tables."""
  271. # Get counts of open positions (trades that are not yet migrated)
  272. open_positions_count = self._get_open_positions_count_from_db()
  273. # Get overall aggregated stats from token_stats table
  274. query_token_stats_summary = """
  275. SELECT
  276. SUM(total_realized_pnl) as total_pnl_from_cycles,
  277. SUM(total_completed_cycles) as total_completed_cycles_sum,
  278. MIN(first_cycle_closed_at) as overall_first_cycle_closed,
  279. MAX(last_cycle_closed_at) as overall_last_cycle_closed
  280. FROM token_stats
  281. """
  282. token_stats_summary = self.db_manager._fetchone_query(query_token_stats_summary)
  283. total_pnl_from_cycles = token_stats_summary['total_pnl_from_cycles'] if token_stats_summary and token_stats_summary['total_pnl_from_cycles'] is not None else 0.0
  284. total_completed_cycles_sum = token_stats_summary['total_completed_cycles_sum'] if token_stats_summary and token_stats_summary['total_completed_cycles_sum'] is not None else 0
  285. # Total trades considered as sum of completed cycles and currently open positions
  286. total_trades_redefined = total_completed_cycles_sum + open_positions_count
  287. initial_balance_str = self._get_metadata('initial_balance')
  288. initial_balance = float(initial_balance_str) if initial_balance_str else 0.0
  289. start_date_iso = self._get_metadata('start_date')
  290. start_date_obj = datetime.fromisoformat(start_date_iso) if start_date_iso else datetime.now(timezone.utc)
  291. days_active = (datetime.now(timezone.utc) - start_date_obj).days + 1
  292. # 'last_trade' timestamp could be the last update to token_stats or an open trade
  293. last_activity_ts = token_stats_summary['overall_last_cycle_closed'] if token_stats_summary else None
  294. last_open_trade_ts_row = self.db_manager._fetchone_query("SELECT MAX(updated_at) as last_update FROM trades WHERE status = 'position_opened'")
  295. if last_open_trade_ts_row and last_open_trade_ts_row['last_update']:
  296. if not last_activity_ts or datetime.fromisoformat(last_open_trade_ts_row['last_update']) > datetime.fromisoformat(last_activity_ts):
  297. last_activity_ts = last_open_trade_ts_row['last_update']
  298. return {
  299. 'total_trades': total_trades_redefined,
  300. 'completed_trades': total_completed_cycles_sum,
  301. 'initial_balance': initial_balance,
  302. 'total_pnl': total_pnl_from_cycles,
  303. 'days_active': days_active,
  304. 'start_date': start_date_obj.strftime('%Y-%m-%d'),
  305. 'last_trade': last_activity_ts,
  306. 'open_positions_count': open_positions_count
  307. }
  308. def _get_open_positions_count_from_db(self) -> int:
  309. """Get count of open positions from trades table."""
  310. row = self.db_manager._fetchone_query("SELECT COUNT(DISTINCT symbol) as count FROM trades WHERE status = 'position_opened'")
  311. return row['count'] if row else 0
  312. def get_token_detailed_stats(self, token: str) -> Dict[str, Any]:
  313. """Get detailed statistics for a specific token."""
  314. try:
  315. # Normalize token case
  316. upper_token = _normalize_token_case(token)
  317. # Get aggregated stats from token_stats table
  318. token_agg_stats = self.db_manager._fetchone_query(
  319. "SELECT * FROM token_stats WHERE token = ?", (upper_token,)
  320. )
  321. # Get open trades for this token
  322. open_trades_for_token = self.db_manager._fetch_query(
  323. "SELECT * FROM trades WHERE status = 'position_opened' AND symbol LIKE ? ORDER BY position_opened_at DESC",
  324. (f"{upper_token}/%",)
  325. )
  326. # Initialize performance stats
  327. perf_stats = {
  328. 'completed_trades': 0,
  329. 'total_pnl': 0.0,
  330. 'pnl_percentage': 0.0,
  331. 'win_rate': 0.0,
  332. 'profit_factor': 0.0,
  333. 'avg_win': 0.0,
  334. 'avg_loss': 0.0,
  335. 'largest_win': 0.0,
  336. 'largest_loss': 0.0,
  337. 'expectancy': 0.0,
  338. 'total_wins': 0,
  339. 'total_losses': 0,
  340. 'completed_entry_volume': 0.0,
  341. 'completed_exit_volume': 0.0,
  342. 'total_cancelled': 0,
  343. 'total_duration_seconds': 0,
  344. 'avg_trade_duration': "N/A"
  345. }
  346. if token_agg_stats:
  347. total_cycles = token_agg_stats.get('total_completed_cycles', 0)
  348. winning_cycles = token_agg_stats.get('winning_cycles', 0)
  349. losing_cycles = token_agg_stats.get('losing_cycles', 0)
  350. sum_winning_pnl = token_agg_stats.get('sum_of_winning_pnl', 0.0)
  351. sum_losing_pnl = token_agg_stats.get('sum_of_losing_pnl', 0.0)
  352. perf_stats.update({
  353. 'completed_trades': total_cycles,
  354. 'total_pnl': token_agg_stats.get('total_realized_pnl', 0.0),
  355. 'win_rate': (winning_cycles / total_cycles * 100) if total_cycles > 0 else 0.0,
  356. 'profit_factor': (sum_winning_pnl / sum_losing_pnl) if sum_losing_pnl > 0 else float('inf') if sum_winning_pnl > 0 else 0.0,
  357. 'avg_win': (sum_winning_pnl / winning_cycles) if winning_cycles > 0 else 0.0,
  358. 'avg_loss': (sum_losing_pnl / losing_cycles) if losing_cycles > 0 else 0.0,
  359. 'largest_win': token_agg_stats.get('largest_winning_cycle_pnl', 0.0),
  360. 'largest_loss': token_agg_stats.get('largest_losing_cycle_pnl', 0.0),
  361. 'total_wins': winning_cycles,
  362. 'total_losses': losing_cycles,
  363. 'completed_entry_volume': token_agg_stats.get('total_entry_volume', 0.0),
  364. 'completed_exit_volume': token_agg_stats.get('total_exit_volume', 0.0),
  365. 'total_cancelled': token_agg_stats.get('total_cancelled_cycles', 0),
  366. 'total_duration_seconds': token_agg_stats.get('total_duration_seconds', 0)
  367. })
  368. # Calculate expectancy
  369. win_rate_decimal = perf_stats['win_rate'] / 100
  370. perf_stats['expectancy'] = (perf_stats['avg_win'] * win_rate_decimal) - (perf_stats['avg_loss'] * (1 - win_rate_decimal))
  371. # Format average trade duration
  372. if total_cycles > 0:
  373. avg_duration_seconds = token_agg_stats.get('total_duration_seconds', 0) / total_cycles
  374. perf_stats['avg_trade_duration'] = self._format_duration(avg_duration_seconds)
  375. # Calculate open positions summary
  376. open_positions_summary = []
  377. total_open_value = 0.0
  378. total_open_unrealized_pnl = 0.0
  379. for op_trade in open_trades_for_token:
  380. open_positions_summary.append({
  381. 'lifecycle_id': op_trade.get('trade_lifecycle_id'),
  382. 'side': op_trade.get('position_side'),
  383. 'amount': op_trade.get('current_position_size'),
  384. 'entry_price': op_trade.get('entry_price'),
  385. 'mark_price': op_trade.get('mark_price'),
  386. 'unrealized_pnl': op_trade.get('unrealized_pnl'),
  387. 'opened_at': op_trade.get('position_opened_at')
  388. })
  389. total_open_value += op_trade.get('value', 0.0)
  390. total_open_unrealized_pnl += op_trade.get('unrealized_pnl', 0.0)
  391. # Get open orders count for this token
  392. open_orders_count_row = self.db_manager._fetchone_query(
  393. "SELECT COUNT(*) as count FROM orders WHERE symbol LIKE ? AND status IN ('open', 'submitted', 'pending_trigger')",
  394. (f"{upper_token}/%",)
  395. )
  396. current_open_orders_for_token = open_orders_count_row['count'] if open_orders_count_row else 0
  397. effective_total_trades = perf_stats['completed_trades'] + len(open_trades_for_token)
  398. return {
  399. 'token': upper_token,
  400. 'performance': perf_stats,
  401. 'open_positions': {
  402. 'count': len(open_trades_for_token),
  403. 'total_value': total_open_value,
  404. 'total_unrealized_pnl': total_open_unrealized_pnl,
  405. 'positions': open_positions_summary
  406. },
  407. 'summary': {
  408. 'total_trades': effective_total_trades,
  409. 'open_orders': current_open_orders_for_token,
  410. }
  411. }
  412. except Exception as e:
  413. logger.error(f"❌ Error getting detailed stats for {token}: {e}")
  414. return {}
  415. def _format_duration(self, seconds: float) -> str:
  416. """Format duration in seconds to a human-readable string."""
  417. if seconds <= 0:
  418. return "0s"
  419. days = int(seconds // 86400)
  420. hours = int((seconds % 86400) // 3600)
  421. minutes = int((seconds % 3600) // 60)
  422. secs = int(seconds % 60)
  423. parts = []
  424. if days > 0:
  425. parts.append(f"{days}d")
  426. if hours > 0:
  427. parts.append(f"{hours}h")
  428. if minutes > 0:
  429. parts.append(f"{minutes}m")
  430. if secs > 0 or not parts:
  431. parts.append(f"{secs}s")
  432. return " ".join(parts)
  433. def format_stats_message(self, current_balance: Optional[float] = None) -> str:
  434. """Format stats for Telegram display using data from DB."""
  435. try:
  436. basic = self.get_basic_stats(current_balance)
  437. perf = self.get_performance_stats()
  438. risk = self.get_risk_metrics()
  439. formatter = get_formatter()
  440. effective_current_balance = current_balance if current_balance is not None else (basic['initial_balance'] + basic['total_pnl'])
  441. initial_bal = basic['initial_balance']
  442. total_pnl_val = effective_current_balance - initial_bal if initial_bal > 0 and current_balance is not None else basic['total_pnl']
  443. total_return_pct = (total_pnl_val / initial_bal * 100) if initial_bal > 0 else 0.0
  444. pnl_emoji = "🟢" if total_pnl_val >= 0 else "🔴"
  445. open_positions_count = basic['open_positions_count']
  446. stats_text_parts = []
  447. stats_text_parts.append(f"📊 <b>Trading Statistics</b>\n")
  448. # Account Overview
  449. stats_text_parts.append(f"\n💰 <b>Account Overview:</b>")
  450. stats_text_parts.append(f"• Current Balance: {formatter.format_price_with_symbol(effective_current_balance)}")
  451. stats_text_parts.append(f"• Initial Balance: {formatter.format_price_with_symbol(initial_bal)}")
  452. stats_text_parts.append(f"• Open Positions: {open_positions_count}")
  453. stats_text_parts.append(f"• {pnl_emoji} Total P&L: {formatter.format_price_with_symbol(total_pnl_val)} ({total_return_pct:+.2f}%)")
  454. stats_text_parts.append(f"• Days Active: {basic['days_active']}\n")
  455. # Trading Performance
  456. stats_text_parts.append(f"📈 <b>Trading Performance:</b>")
  457. stats_text_parts.append(f"• Total Cycles: {perf['total_completed_cycles']}")
  458. stats_text_parts.append(f"• Win Rate: {perf['win_rate']:.1f}% ({perf['total_winning_cycles']}/{perf['total_completed_cycles']})")
  459. stats_text_parts.append(f"• Profit Factor: {perf['profit_factor']:.2f}")
  460. stats_text_parts.append(f"• Expectancy: {formatter.format_price_with_symbol(perf['expectancy'])}")
  461. return "\n".join(stats_text_parts)
  462. except Exception as e:
  463. logger.error(f"❌ Error formatting stats message: {e}")
  464. return f"❌ Error generating statistics: {str(e)}"
  465. # =============================================================================
  466. # CONVENIENCE METHODS & HIGH-LEVEL OPERATIONS
  467. # =============================================================================
  468. def process_trade_complete_cycle(self, symbol: str, side: str, entry_price: float,
  469. exit_price: float, amount: float,
  470. timestamp: Optional[str] = None) -> str:
  471. """Process a complete trade cycle in one operation."""
  472. # Create lifecycle
  473. lifecycle_id = self.create_trade_lifecycle(symbol, side, trade_type='complete_cycle')
  474. if not lifecycle_id:
  475. raise Exception("Failed to create trade lifecycle")
  476. # Update to position opened
  477. success = self.update_trade_position_opened(lifecycle_id, entry_price, amount, "manual_entry")
  478. if not success:
  479. raise Exception("Failed to update position opened")
  480. # Calculate PnL
  481. if side.lower() == 'buy':
  482. realized_pnl = (exit_price - entry_price) * amount
  483. else: # sell
  484. realized_pnl = (entry_price - exit_price) * amount
  485. # Update to position closed
  486. success = self.update_trade_position_closed(lifecycle_id, exit_price, realized_pnl, "manual_exit")
  487. if not success:
  488. raise Exception("Failed to update position closed")
  489. # Migrate to aggregated stats
  490. self.migrate_trade_to_aggregated_stats(lifecycle_id)
  491. logger.info(f"✅ Processed complete trade cycle: {symbol} {side.upper()} P&L: ${realized_pnl:.2f}")
  492. return lifecycle_id
  493. def get_summary_report(self) -> Dict[str, Any]:
  494. """Get comprehensive summary report."""
  495. try:
  496. perf_stats = self.get_performance_stats()
  497. token_performance = self.get_token_performance(limit=10)
  498. daily_stats = self.get_daily_stats(limit=7)
  499. risk_metrics = self.get_risk_metrics()
  500. balance_adjustments = self.get_balance_adjustments_summary()
  501. # Get current positions
  502. open_positions = self.get_open_positions()
  503. return {
  504. 'performance_stats': perf_stats,
  505. 'top_tokens': token_performance,
  506. 'recent_daily_stats': daily_stats,
  507. 'risk_metrics': risk_metrics,
  508. 'balance_adjustments': balance_adjustments,
  509. 'open_positions_count': len(open_positions),
  510. 'open_positions': open_positions,
  511. 'generated_at': datetime.now(timezone.utc).isoformat()
  512. }
  513. except Exception as e:
  514. logger.error(f"❌ Error generating summary report: {e}")
  515. return {'error': str(e)}
  516. def health_check(self) -> Dict[str, Any]:
  517. """Perform health check on all components."""
  518. try:
  519. health = {
  520. 'database': 'ok',
  521. 'order_manager': 'ok',
  522. 'trade_manager': 'ok',
  523. 'aggregation_manager': 'ok',
  524. 'performance_calculator': 'ok',
  525. 'overall': 'ok'
  526. }
  527. # Test database connection
  528. self.db_manager._fetch_query("SELECT 1")
  529. # Test each component with basic operations
  530. self.get_recent_orders(limit=1)
  531. self.get_recent_trades(limit=1)
  532. self.get_daily_stats(limit=1)
  533. self.get_performance_stats()
  534. return health
  535. except Exception as e:
  536. logger.error(f"❌ Health check failed: {e}")
  537. return {'overall': 'error', 'error': str(e)}