trading_stats.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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, Union
  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. async def set_initial_balance(self, balance: float):
  53. """Set initial balance."""
  54. return await 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. async 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 await 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,
  79. status: str = 'open') -> bool:
  80. """Record order placement."""
  81. result = self.order_manager.record_order_placed(
  82. symbol, side, order_type, amount_requested, price,
  83. bot_order_ref_id, exchange_order_id, status
  84. )
  85. return result is not None
  86. def update_order_exchange_id(self, bot_order_ref_id: str, exchange_order_id: str) -> bool:
  87. """Update order with exchange ID."""
  88. return self.order_manager.update_order_exchange_id(bot_order_ref_id, exchange_order_id)
  89. def record_order_filled(self, exchange_order_id: str, actual_amount: float,
  90. actual_price: float, fees: float = 0.0,
  91. timestamp: Optional[str] = None,
  92. exchange_fill_id: Optional[str] = None) -> bool:
  93. """Record order fill."""
  94. return self.order_manager.record_order_filled(
  95. exchange_order_id, actual_amount, actual_price, fees, timestamp, exchange_fill_id
  96. )
  97. def record_order_cancelled(self, exchange_order_id: str, reason: str = "user_cancelled",
  98. timestamp: Optional[str] = None) -> bool:
  99. """Record order cancellation."""
  100. return self.order_manager.record_order_cancelled(exchange_order_id, reason, timestamp)
  101. def update_order_status(self, order_db_id: Optional[int] = None, bot_order_ref_id: Optional[str] = None,
  102. exchange_order_id: Optional[str] = None, new_status: Optional[str] = None,
  103. amount_filled_increment: Optional[float] = None, set_exchange_order_id: Optional[str] = None,
  104. notes: Optional[str] = None, timestamp: Optional[str] = None) -> bool:
  105. """Update order status - delegates to OrderManager with full parameter support."""
  106. return self.order_manager.update_order_status(
  107. order_db_id=order_db_id,
  108. bot_order_ref_id=bot_order_ref_id,
  109. exchange_order_id=exchange_order_id,
  110. new_status=new_status,
  111. amount_filled_increment=amount_filled_increment,
  112. set_exchange_order_id=set_exchange_order_id
  113. )
  114. def get_order_by_exchange_id(self, exchange_order_id: str) -> Optional[Dict[str, Any]]:
  115. """Get order by exchange ID."""
  116. return self.order_manager.get_order_by_exchange_id(exchange_order_id)
  117. def get_order_by_bot_ref_id(self, bot_order_ref_id: str) -> Optional[Dict[str, Any]]:
  118. """Get order by bot reference ID."""
  119. return self.order_manager.get_order_by_bot_ref_id(bot_order_ref_id)
  120. def has_exchange_fill_been_processed(self, exchange_fill_id: str) -> bool:
  121. """Check if an exchange fill ID has already been processed."""
  122. try:
  123. # Check trades table which is the primary place where all processed fills are recorded
  124. trade_exists = self.db_manager._fetch_query(
  125. "SELECT 1 FROM trades WHERE exchange_fill_id = ? LIMIT 1",
  126. (exchange_fill_id,)
  127. )
  128. return bool(trade_exists)
  129. except Exception as e:
  130. logger.error(f"Error checking if fill {exchange_fill_id} was processed: {e}")
  131. return False
  132. def get_orders_by_symbol(self, symbol: str, limit: int = 50) -> List[Dict[str, Any]]:
  133. """Get orders by symbol."""
  134. return self.order_manager.get_orders_by_symbol(symbol, limit)
  135. def get_orders_by_status(self, status: str, limit: Optional[int] = 50,
  136. order_type_filter: Optional[str] = None,
  137. parent_bot_order_ref_id: Optional[str] = None) -> List[Dict[str, Any]]:
  138. """Get orders by status with optional filters."""
  139. # OrderManager expects (status, order_type_filter, parent_bot_order_ref_id) without limit
  140. return self.order_manager.get_orders_by_status(status, order_type_filter, parent_bot_order_ref_id)
  141. def get_recent_orders(self, limit: int = 20) -> List[Dict[str, Any]]:
  142. """Get recent orders."""
  143. return self.order_manager.get_recent_orders(limit)
  144. def cleanup_old_cancelled_orders(self, days_old: int = 7) -> int:
  145. """Clean up old cancelled orders."""
  146. return self.order_manager.cleanup_old_cancelled_orders(days_old)
  147. # =============================================================================
  148. # TRADE LIFECYCLE DELEGATION
  149. # =============================================================================
  150. def create_trade_lifecycle(self, symbol: str, side: str, entry_order_id: Optional[str] = None,
  151. entry_bot_order_ref_id: Optional[str] = None,
  152. stop_loss_price: Optional[float] = None,
  153. take_profit_price: Optional[float] = None,
  154. trade_type: str = 'manual') -> Optional[str]:
  155. """Create trade lifecycle."""
  156. return self.trade_manager.create_trade_lifecycle(
  157. symbol, side, entry_order_id, entry_bot_order_ref_id,
  158. stop_loss_price, take_profit_price, trade_type
  159. )
  160. async def update_trade_position_opened(self, lifecycle_id: str, entry_price: float,
  161. entry_amount: float, exchange_fill_id: str) -> bool:
  162. """Update trade position opened."""
  163. return await self.trade_manager.update_trade_position_opened(
  164. lifecycle_id, entry_price, entry_amount, exchange_fill_id
  165. )
  166. async def update_trade_position_closed(self, lifecycle_id: str, exit_price: float,
  167. realized_pnl: float, exchange_fill_id: str) -> bool:
  168. """Update trade position closed."""
  169. return await self.trade_manager.update_trade_position_closed(
  170. lifecycle_id, exit_price, realized_pnl, exchange_fill_id
  171. )
  172. def update_trade_cancelled(self, lifecycle_id: str, reason: str = "order_cancelled") -> bool:
  173. """Update trade cancelled."""
  174. return self.trade_manager.update_trade_cancelled(lifecycle_id, reason)
  175. async def link_stop_loss_to_trade(self, lifecycle_id: str, stop_loss_order_id: str,
  176. stop_loss_price: float) -> bool:
  177. """Link stop loss to trade."""
  178. return await self.trade_manager.link_stop_loss_to_trade(
  179. lifecycle_id, stop_loss_order_id, stop_loss_price
  180. )
  181. async def link_take_profit_to_trade(self, lifecycle_id: str, take_profit_order_id: str,
  182. take_profit_price: float) -> bool:
  183. """Link take profit to trade."""
  184. return await self.trade_manager.link_take_profit_to_trade(
  185. lifecycle_id, take_profit_order_id, take_profit_price
  186. )
  187. def get_trade_by_lifecycle_id(self, lifecycle_id: str) -> Optional[Dict[str, Any]]:
  188. """Get trade by lifecycle ID."""
  189. return self.trade_manager.get_trade_by_lifecycle_id(lifecycle_id)
  190. def get_trade_by_symbol_and_status(self, symbol: str, status: str = 'position_opened') -> Optional[Dict[str, Any]]:
  191. """Get trade by symbol and status."""
  192. return self.trade_manager.get_trade_by_symbol_and_status(symbol, status)
  193. def get_open_positions(self, symbol: Optional[str] = None) -> List[Dict[str, Any]]:
  194. """Get open positions."""
  195. return self.trade_manager.get_open_positions(symbol)
  196. def get_trades_by_status(self, status: str, limit: int = 50) -> List[Dict[str, Any]]:
  197. """Get trades by status."""
  198. return self.trade_manager.get_trades_by_status(status, limit)
  199. def get_lifecycle_by_entry_order_id(self, entry_exchange_order_id: str, status: Optional[str] = None) -> Optional[Dict[str, Any]]:
  200. """Get lifecycle by entry order ID."""
  201. return self.trade_manager.get_lifecycle_by_entry_order_id(entry_exchange_order_id, status)
  202. def get_lifecycle_by_sl_order_id(self, sl_exchange_order_id: str, status: str = 'position_opened') -> Optional[Dict[str, Any]]:
  203. """Get lifecycle by stop loss order ID."""
  204. return self.trade_manager.get_lifecycle_by_sl_order_id(sl_exchange_order_id, status)
  205. def get_lifecycle_by_tp_order_id(self, tp_exchange_order_id: str, status: str = 'position_opened') -> Optional[Dict[str, Any]]:
  206. """Get lifecycle by take profit order ID."""
  207. return self.trade_manager.get_lifecycle_by_tp_order_id(tp_exchange_order_id, status)
  208. def get_pending_stop_loss_activations(self) -> List[Dict[str, Any]]:
  209. """Get pending stop loss activations."""
  210. return self.trade_manager.get_pending_stop_loss_activations()
  211. def cleanup_old_cancelled_trades(self, days_old: int = 7) -> int:
  212. """Clean up old cancelled trades."""
  213. return self.trade_manager.cleanup_old_cancelled_trades(days_old)
  214. def confirm_position_with_exchange(self, symbol: str, exchange_position_size: float,
  215. exchange_open_orders: List[Dict]) -> bool:
  216. """Confirm position with exchange."""
  217. return self.trade_manager.confirm_position_with_exchange(
  218. symbol, exchange_position_size, exchange_open_orders
  219. )
  220. def update_trade_market_data(self, trade_lifecycle_id: str, **kwargs) -> bool:
  221. """Update trade market data."""
  222. return self.trade_manager.update_trade_market_data(trade_lifecycle_id, **kwargs)
  223. def get_recent_trades(self, limit: int = 10) -> List[Dict[str, Any]]:
  224. """Get recent trades."""
  225. return self.trade_manager.get_recent_trades(limit)
  226. def get_all_trades(self) -> List[Dict[str, Any]]:
  227. """Get all trades."""
  228. return self.trade_manager.get_all_trades()
  229. def cancel_linked_orders(self, parent_bot_order_ref_id: str, new_status: str = 'cancelled_parent_filled') -> int:
  230. """Cancel linked SL/TP orders when a parent order is filled or cancelled."""
  231. return self.trade_manager.cancel_linked_orders(parent_bot_order_ref_id, new_status)
  232. # =============================================================================
  233. # AGGREGATION MANAGEMENT DELEGATION
  234. # =============================================================================
  235. def migrate_trade_to_aggregated_stats(self, trade_lifecycle_id: str):
  236. """Migrate completed trade to aggregated stats."""
  237. return self.aggregation_manager.migrate_trade_to_aggregated_stats(trade_lifecycle_id)
  238. async def record_deposit(self, amount: float, timestamp: Optional[str] = None,
  239. deposit_id: Optional[str] = None, description: Optional[str] = None):
  240. """Record a deposit."""
  241. return await self.aggregation_manager.record_deposit(amount, timestamp, deposit_id, description)
  242. async def record_withdrawal(self, amount: float, timestamp: Optional[str] = None,
  243. withdrawal_id: Optional[str] = None, description: Optional[str] = None):
  244. """Record a withdrawal."""
  245. return await self.aggregation_manager.record_withdrawal(amount, timestamp, withdrawal_id, description)
  246. def get_balance_adjustments_summary(self) -> Dict[str, Any]:
  247. """Get summary of balance adjustments."""
  248. return self.aggregation_manager.get_balance_adjustments_summary()
  249. def get_daily_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  250. """Get daily stats."""
  251. return self.aggregation_manager.get_daily_stats(limit)
  252. def get_weekly_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  253. """Get weekly stats."""
  254. return self.aggregation_manager.get_weekly_stats(limit)
  255. def get_monthly_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  256. """Get monthly stats."""
  257. return self.aggregation_manager.get_monthly_stats(limit)
  258. # =============================================================================
  259. # PERFORMANCE CALCULATION DELEGATION
  260. # =============================================================================
  261. def get_performance_stats(self) -> Dict[str, Any]:
  262. """Get performance stats."""
  263. return self.performance_calculator.get_performance_stats()
  264. def get_token_performance(self, token: Optional[str] = None) -> Union[List[Dict[str, Any]], Dict[str, Any]]:
  265. """Get performance data for a specific token or all tokens."""
  266. try:
  267. if token:
  268. # Get performance for specific token
  269. query = """
  270. SELECT
  271. symbol,
  272. COUNT(*) as total_trades,
  273. SUM(CASE WHEN realized_pnl > 0 THEN 1 ELSE 0 END) as winning_trades,
  274. SUM(realized_pnl) as total_pnl,
  275. AVG(realized_pnl) as avg_trade,
  276. MAX(realized_pnl) as largest_win,
  277. MIN(realized_pnl) as largest_loss,
  278. AVG(CASE WHEN realized_pnl > 0 THEN realized_pnl ELSE NULL END) as avg_win,
  279. AVG(CASE WHEN realized_pnl < 0 THEN realized_pnl ELSE NULL END) as avg_loss
  280. FROM trades
  281. WHERE symbol = ? AND status = 'position_closed'
  282. GROUP BY symbol
  283. """
  284. result = self.db_manager._fetchone_query(query, (token,))
  285. if not result:
  286. return {}
  287. # Calculate win rate
  288. total_trades = result['total_trades']
  289. winning_trades = result['winning_trades']
  290. win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
  291. # Get recent trades
  292. recent_trades_query = """
  293. SELECT
  294. side,
  295. entry_price,
  296. exit_price,
  297. realized_pnl as pnl,
  298. position_opened_at,
  299. position_closed_at
  300. FROM trades
  301. WHERE symbol = ? AND status = 'position_closed'
  302. ORDER BY position_closed_at DESC
  303. LIMIT 5
  304. """
  305. recent_trades = self.db_manager._fetch_query(recent_trades_query, (token,))
  306. return {
  307. 'token': token,
  308. 'total_trades': total_trades,
  309. 'winning_trades': winning_trades,
  310. 'win_rate': win_rate,
  311. 'total_pnl': result['total_pnl'],
  312. 'avg_trade': result['avg_trade'],
  313. 'largest_win': result['largest_win'],
  314. 'largest_loss': result['largest_loss'],
  315. 'avg_win': result['avg_win'],
  316. 'avg_loss': result['avg_loss'],
  317. 'recent_trades': recent_trades
  318. }
  319. else:
  320. # Get performance for all tokens
  321. query = """
  322. SELECT
  323. symbol,
  324. COUNT(*) as total_trades,
  325. SUM(CASE WHEN realized_pnl > 0 THEN 1 ELSE 0 END) as winning_trades,
  326. SUM(realized_pnl) as total_pnl,
  327. AVG(realized_pnl) as avg_trade
  328. FROM trades
  329. WHERE status = 'position_closed'
  330. GROUP BY symbol
  331. ORDER BY total_pnl DESC
  332. """
  333. results = self.db_manager._fetch_query(query)
  334. performance_data = []
  335. for result in results:
  336. total_trades = result['total_trades']
  337. winning_trades = result['winning_trades']
  338. win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
  339. performance_data.append({
  340. 'token': result['symbol'],
  341. 'total_trades': total_trades,
  342. 'winning_trades': winning_trades,
  343. 'win_rate': win_rate,
  344. 'total_pnl': result['total_pnl'],
  345. 'avg_trade': result['avg_trade']
  346. })
  347. return performance_data
  348. except Exception as e:
  349. logger.error(f"Error getting token performance: {e}")
  350. return [] if token is None else {}
  351. def get_balance_history(self, days: int = 30) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
  352. """Get balance history."""
  353. return self.performance_calculator.get_balance_history(days)
  354. def get_live_max_drawdown(self) -> Tuple[float, float]:
  355. """Get live max drawdown."""
  356. return self.performance_calculator.get_live_max_drawdown()
  357. def update_live_max_drawdown(self, current_balance: float) -> bool:
  358. """Update live max drawdown."""
  359. return self.performance_calculator.update_live_max_drawdown(current_balance)
  360. def get_drawdown_monitor_data(self) -> Dict[str, float]:
  361. """Get drawdown data from DrawdownMonitor for external monitoring systems."""
  362. try:
  363. peak_balance = float(self._get_metadata('drawdown_peak_balance') or '0.0')
  364. max_drawdown_pct = float(self._get_metadata('drawdown_max_drawdown_pct') or '0.0')
  365. return {
  366. 'peak_balance': peak_balance,
  367. 'max_drawdown_percentage': max_drawdown_pct
  368. }
  369. except (ValueError, TypeError):
  370. return {'peak_balance': 0.0, 'max_drawdown_percentage': 0.0}
  371. def calculate_sharpe_ratio(self, days: int = 30) -> Optional[float]:
  372. """Calculate Sharpe ratio."""
  373. return self.performance_calculator.calculate_sharpe_ratio(days)
  374. def calculate_max_consecutive_losses(self) -> int:
  375. """Calculate max consecutive losses."""
  376. return self.performance_calculator.calculate_max_consecutive_losses()
  377. def get_risk_metrics(self) -> Dict[str, Any]:
  378. """Get risk metrics."""
  379. return self.performance_calculator.get_risk_metrics()
  380. def get_period_performance(self, start_date: str, end_date: str) -> Dict[str, Any]:
  381. """Get period performance."""
  382. return self.performance_calculator.get_period_performance(start_date, end_date)
  383. def get_recent_performance_trend(self, days: int = 7) -> Dict[str, Any]:
  384. """Get recent performance trend."""
  385. return self.performance_calculator.get_recent_performance_trend(days)
  386. # =============================================================================
  387. # COMPATIBILITY METHODS - Legacy API Support
  388. # =============================================================================
  389. def get_basic_stats(self, current_balance: Optional[float] = None) -> Dict[str, Any]:
  390. """Get basic trading statistics from DB, primarily using aggregated tables."""
  391. # Get counts of open positions (trades that are not yet migrated)
  392. open_positions_count = self._get_open_positions_count_from_db()
  393. # Get overall aggregated stats from token_stats table
  394. query_token_stats_summary = """
  395. SELECT
  396. SUM(total_realized_pnl) as total_pnl_from_cycles,
  397. SUM(total_completed_cycles) as total_completed_cycles_sum,
  398. MIN(first_cycle_closed_at) as overall_first_cycle_closed,
  399. MAX(last_cycle_closed_at) as overall_last_cycle_closed
  400. FROM token_stats
  401. """
  402. token_stats_summary = self.db_manager._fetchone_query(query_token_stats_summary)
  403. 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
  404. 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
  405. # Total trades considered as sum of completed cycles and currently open positions
  406. total_trades_redefined = total_completed_cycles_sum + open_positions_count
  407. initial_balance_str = self._get_metadata('initial_balance')
  408. initial_balance = float(initial_balance_str) if initial_balance_str else 0.0
  409. start_date_iso = self._get_metadata('start_date')
  410. start_date_obj = datetime.fromisoformat(start_date_iso) if start_date_iso else datetime.now(timezone.utc)
  411. days_active = (datetime.now(timezone.utc) - start_date_obj).days + 1
  412. # Get last activity timestamp
  413. last_activity_ts = None
  414. last_activity_query = """
  415. SELECT MAX(updated_at) as last_update
  416. FROM trades
  417. WHERE status IN ('position_opened', 'position_closed')
  418. """
  419. last_activity_row = self.db_manager._fetchone_query(last_activity_query)
  420. if last_activity_row and last_activity_row['last_update']:
  421. last_activity_ts = last_activity_row['last_update']
  422. # Ensure timezone-aware
  423. if isinstance(last_activity_ts, str):
  424. last_activity_ts = datetime.fromisoformat(last_activity_ts)
  425. if last_activity_ts.tzinfo is None:
  426. last_activity_ts = last_activity_ts.replace(tzinfo=timezone.utc)
  427. # Get last open trade timestamp
  428. last_open_trade_query = """
  429. SELECT MAX(updated_at) as last_update
  430. FROM trades
  431. WHERE status = 'position_opened'
  432. """
  433. last_open_trade_ts_row = self.db_manager._fetchone_query(last_open_trade_query)
  434. if last_open_trade_ts_row and last_open_trade_ts_row['last_update']:
  435. last_open_trade_ts = last_open_trade_ts_row['last_update']
  436. # Ensure timezone-aware
  437. if isinstance(last_open_trade_ts, str):
  438. last_open_trade_ts = datetime.fromisoformat(last_open_trade_ts)
  439. if last_open_trade_ts.tzinfo is None:
  440. last_open_trade_ts = last_open_trade_ts.replace(tzinfo=timezone.utc)
  441. # Now both datetimes are timezone-aware, we can compare them
  442. if not last_activity_ts or last_open_trade_ts > last_activity_ts:
  443. last_activity_ts = last_open_trade_ts
  444. return {
  445. 'total_trades': total_trades_redefined,
  446. 'completed_trades': total_completed_cycles_sum,
  447. 'initial_balance': initial_balance,
  448. 'total_pnl': total_pnl_from_cycles,
  449. 'days_active': days_active,
  450. 'start_date': start_date_obj.strftime('%Y-%m-%d'),
  451. 'last_trade': last_activity_ts,
  452. 'open_positions_count': open_positions_count
  453. }
  454. def _get_open_positions_count_from_db(self) -> int:
  455. """Get count of open positions from trades table."""
  456. row = self.db_manager._fetchone_query("SELECT COUNT(DISTINCT symbol) as count FROM trades WHERE status = 'position_opened'")
  457. return row['count'] if row else 0
  458. def get_token_detailed_stats(self, token: str) -> Dict[str, Any]:
  459. """Get detailed statistics for a specific token."""
  460. try:
  461. # Normalize token case
  462. upper_token = _normalize_token_case(token)
  463. # Get aggregated stats from token_stats table
  464. token_agg_stats = self.db_manager._fetchone_query(
  465. "SELECT * FROM token_stats WHERE token = ?", (upper_token,)
  466. )
  467. # Get open trades for this token
  468. open_trades_for_token = self.db_manager._fetch_query(
  469. "SELECT * FROM trades WHERE status = 'position_opened' AND symbol LIKE ? ORDER BY position_opened_at DESC",
  470. (f"{upper_token}/%",)
  471. )
  472. # Initialize performance stats
  473. perf_stats = {
  474. 'completed_trades': 0,
  475. 'total_pnl': 0.0,
  476. 'pnl_percentage': 0.0,
  477. 'win_rate': 0.0,
  478. 'profit_factor': 0.0,
  479. 'avg_win': 0.0,
  480. 'avg_loss': 0.0,
  481. 'largest_win': 0.0,
  482. 'largest_loss': 0.0,
  483. 'expectancy': 0.0,
  484. 'total_wins': 0,
  485. 'total_losses': 0,
  486. 'completed_entry_volume': 0.0,
  487. 'completed_exit_volume': 0.0,
  488. 'total_cancelled': 0,
  489. 'total_duration_seconds': 0,
  490. 'avg_trade_duration': "N/A"
  491. }
  492. if token_agg_stats:
  493. total_cycles = token_agg_stats.get('total_completed_cycles', 0)
  494. winning_cycles = token_agg_stats.get('winning_cycles', 0)
  495. losing_cycles = token_agg_stats.get('losing_cycles', 0)
  496. sum_winning_pnl = token_agg_stats.get('sum_of_winning_pnl', 0.0)
  497. sum_losing_pnl = token_agg_stats.get('sum_of_losing_pnl', 0.0)
  498. # Calculate percentages for largest trades
  499. largest_win_pnl = token_agg_stats.get('largest_winning_cycle_pnl', 0.0)
  500. largest_loss_pnl = token_agg_stats.get('largest_losing_cycle_pnl', 0.0)
  501. largest_win_entry_volume = token_agg_stats.get('largest_winning_cycle_entry_volume', 0.0)
  502. largest_loss_entry_volume = token_agg_stats.get('largest_losing_cycle_entry_volume', 0.0)
  503. largest_win_percentage = (largest_win_pnl / largest_win_entry_volume * 100) if largest_win_entry_volume > 0 else 0.0
  504. largest_loss_percentage = (largest_loss_pnl / largest_loss_entry_volume * 100) if largest_loss_entry_volume > 0 else 0.0
  505. perf_stats.update({
  506. 'completed_trades': total_cycles,
  507. 'total_pnl': token_agg_stats.get('total_realized_pnl', 0.0),
  508. 'win_rate': (winning_cycles / total_cycles * 100) if total_cycles > 0 else 0.0,
  509. 'profit_factor': (sum_winning_pnl / sum_losing_pnl) if sum_losing_pnl > 0 else float('inf') if sum_winning_pnl > 0 else 0.0,
  510. 'avg_win': (sum_winning_pnl / winning_cycles) if winning_cycles > 0 else 0.0,
  511. 'avg_loss': (sum_losing_pnl / losing_cycles) if losing_cycles > 0 else 0.0,
  512. 'largest_win': largest_win_pnl,
  513. 'largest_loss': largest_loss_pnl,
  514. 'largest_win_percentage': largest_win_percentage,
  515. 'largest_loss_percentage': largest_loss_percentage,
  516. 'total_wins': winning_cycles,
  517. 'total_losses': losing_cycles,
  518. 'completed_entry_volume': token_agg_stats.get('total_entry_volume', 0.0),
  519. 'completed_exit_volume': token_agg_stats.get('total_exit_volume', 0.0),
  520. 'total_cancelled': token_agg_stats.get('total_cancelled_cycles', 0),
  521. 'total_duration_seconds': token_agg_stats.get('total_duration_seconds', 0)
  522. })
  523. # Calculate expectancy
  524. win_rate_decimal = perf_stats['win_rate'] / 100
  525. perf_stats['expectancy'] = (perf_stats['avg_win'] * win_rate_decimal) - (perf_stats['avg_loss'] * (1 - win_rate_decimal))
  526. # Format average trade duration
  527. if total_cycles > 0:
  528. avg_duration_seconds = token_agg_stats.get('total_duration_seconds', 0) / total_cycles
  529. perf_stats['avg_trade_duration'] = self._format_duration(avg_duration_seconds)
  530. # Calculate open positions summary
  531. open_positions_summary = []
  532. total_open_value = 0.0
  533. total_open_unrealized_pnl = 0.0
  534. for op_trade in open_trades_for_token:
  535. open_positions_summary.append({
  536. 'lifecycle_id': op_trade.get('trade_lifecycle_id'),
  537. 'side': op_trade.get('position_side'),
  538. 'amount': op_trade.get('current_position_size'),
  539. 'entry_price': op_trade.get('entry_price'),
  540. 'mark_price': op_trade.get('mark_price'),
  541. 'unrealized_pnl': op_trade.get('unrealized_pnl'),
  542. 'opened_at': op_trade.get('position_opened_at')
  543. })
  544. total_open_value += op_trade.get('value', 0.0)
  545. total_open_unrealized_pnl += op_trade.get('unrealized_pnl', 0.0)
  546. # Get open orders count for this token
  547. open_orders_count_row = self.db_manager._fetchone_query(
  548. "SELECT COUNT(*) as count FROM orders WHERE symbol LIKE ? AND status IN ('open', 'submitted', 'pending_trigger')",
  549. (f"{upper_token}/%",)
  550. )
  551. current_open_orders_for_token = open_orders_count_row['count'] if open_orders_count_row else 0
  552. effective_total_trades = perf_stats['completed_trades'] + len(open_trades_for_token)
  553. return {
  554. 'token': upper_token,
  555. 'message': f"Statistics for {upper_token}",
  556. 'performance_summary': perf_stats, # Expected key by formatting method
  557. 'performance': perf_stats, # Legacy compatibility
  558. 'open_positions': open_positions_summary, # Direct list as expected
  559. 'summary_total_trades': effective_total_trades, # Expected by formatting method
  560. 'summary_total_unrealized_pnl': total_open_unrealized_pnl, # Expected by formatting method
  561. 'current_open_orders_count': current_open_orders_for_token, # Expected by formatting method
  562. 'summary': {
  563. 'total_trades': effective_total_trades,
  564. 'open_orders': current_open_orders_for_token,
  565. }
  566. }
  567. except Exception as e:
  568. logger.error(f"❌ Error getting detailed stats for {token}: {e}")
  569. return {}
  570. def _format_duration(self, seconds: float) -> str:
  571. """Format duration in seconds to a human-readable string."""
  572. if seconds <= 0:
  573. return "0s"
  574. days = int(seconds // 86400)
  575. hours = int((seconds % 86400) // 3600)
  576. minutes = int((seconds % 3600) // 60)
  577. secs = int(seconds % 60)
  578. parts = []
  579. if days > 0:
  580. parts.append(f"{days}d")
  581. if hours > 0:
  582. parts.append(f"{hours}h")
  583. if minutes > 0:
  584. parts.append(f"{minutes}m")
  585. if secs > 0 or not parts:
  586. parts.append(f"{secs}s")
  587. return " ".join(parts)
  588. async def format_stats_message(self, current_balance: Optional[float] = None) -> str:
  589. """Formats a comprehensive statistics message."""
  590. formatter = get_formatter()
  591. basic_stats = self.get_basic_stats(current_balance)
  592. initial_bal = basic_stats.get('initial_balance', 0.0)
  593. total_pnl_val = basic_stats.get('total_pnl', 0.0)
  594. total_return_pct = basic_stats.get('total_return_pct', 0.0)
  595. pnl_emoji = "✅" if total_pnl_val >= 0 else "🔻"
  596. stats_text_parts = [
  597. f"📊 <b>Trading Performance Summary</b>",
  598. f"• Current Balance: {await formatter.format_price_with_symbol(current_balance if current_balance is not None else (initial_bal + total_pnl_val))} ({await formatter.format_price_with_symbol(current_balance if current_balance is not None else (initial_bal + total_pnl_val) - initial_bal) if initial_bal > 0 else 'N/A'})",
  599. f"• Initial Balance: {await formatter.format_price_with_symbol(initial_bal)}",
  600. f"• Balance Change: {await formatter.format_price_with_symbol(total_pnl_val)} ({total_return_pct:+.2f}%)",
  601. f"• {pnl_emoji} Total P&L: {await formatter.format_price_with_symbol(total_pnl_val)} ({total_return_pct:+.2f}%)"
  602. ]
  603. # Performance Metrics
  604. perf = basic_stats.get('performance_metrics', {})
  605. if perf:
  606. stats_text_parts.append("\n<b>Key Metrics:</b>")
  607. stats_text_parts.append(f"• Trading Volume (Entry Vol.): {await formatter.format_price_with_symbol(perf.get('total_trading_volume', 0.0))}")
  608. if perf.get('expectancy') is not None:
  609. stats_text_parts.append(f"• Expectancy: {await formatter.format_price_with_symbol(perf['expectancy'])}")
  610. stats_text_parts.append(f"• Win Rate: {perf.get('win_rate', 0.0):.2f}% ({perf.get('num_wins', 0)} wins)")
  611. stats_text_parts.append(f"• Profit Factor: {perf.get('profit_factor', 0.0):.2f}")
  612. # Largest Trades
  613. if perf.get('largest_win') is not None:
  614. largest_win_pct_str = f" ({perf.get('largest_win_entry_pct', 0):.2f}%)" if perf.get('largest_win_entry_pct') is not None else ""
  615. largest_win_token = perf.get('largest_win_token', 'N/A')
  616. stats_text_parts.append(f"• Largest Winning Trade: {await formatter.format_price_with_symbol(perf['largest_win'])}{largest_win_pct_str} ({largest_win_token})")
  617. if perf.get('largest_loss') is not None:
  618. largest_loss_pct_str = f" ({perf.get('largest_loss_entry_pct', 0):.2f}%)" if perf.get('largest_loss_entry_pct') is not None else ""
  619. largest_loss_token = perf.get('largest_loss_token', 'N/A')
  620. stats_text_parts.append(f"• Largest Losing Trade: {await formatter.format_price_with_symbol(-perf['largest_loss'])}{largest_loss_pct_str} ({largest_loss_token})")
  621. # ROE-based metrics if available
  622. largest_win_roe = perf.get('largest_win_roe')
  623. largest_loss_roe = perf.get('largest_loss_roe')
  624. if largest_win_roe is not None:
  625. largest_win_roe_pnl = perf.get('largest_win_roe_pnl', 0.0)
  626. largest_win_roe_token = perf.get('largest_win_roe_token', 'N/A')
  627. stats_text_parts.append(f"• Best ROE Trade: {await formatter.format_price_with_symbol(largest_win_roe_pnl)} (+{largest_win_roe:.2f}%) ({largest_win_roe_token})")
  628. if largest_loss_roe is not None:
  629. largest_loss_roe_pnl = perf.get('largest_loss_roe_pnl', 0.0)
  630. largest_loss_roe_token = perf.get('largest_loss_roe_token', 'N/A')
  631. stats_text_parts.append(f"• Worst ROE Trade: {await formatter.format_price_with_symbol(-largest_loss_roe_pnl)} (-{largest_loss_roe:.2f}%) ({largest_loss_roe_token})")
  632. # Best/Worst Tokens
  633. best_token_stats = basic_stats.get('best_token')
  634. worst_token_stats = basic_stats.get('worst_token')
  635. if best_token_stats:
  636. stats_text_parts.append(f"• Best Token: {best_token_stats['name']} {await formatter.format_price_with_symbol(best_token_stats['pnl_value'])} ({best_token_stats['pnl_percentage']:+.2f}%)")
  637. if worst_token_stats:
  638. stats_text_parts.append(f"• Worst Token: {worst_token_stats['name']} {await formatter.format_price_with_symbol(worst_token_stats['pnl_value'])} ({worst_token_stats['pnl_percentage']:+.2f}%)")
  639. return "\n".join(stats_text_parts)
  640. async def format_token_stats_message(self, token: str) -> str:
  641. """Formats a statistics message for a specific token."""
  642. formatter = get_formatter()
  643. token_stats = self.get_token_detailed_stats(token)
  644. normalized_token = _normalize_token_case(token)
  645. token_name = token_stats.get('token', normalized_token.upper())
  646. if not token_stats or token_stats.get('summary_total_trades', 0) == 0:
  647. return (
  648. f"📊 <b>{token_name} Statistics</b>\n\n"
  649. f"📭 No trading data found for {token_name}.\n\n"
  650. f"💡 To trade this token, try commands like:\n"
  651. f" <code>/long {token_name} 100</code>\n"
  652. f" <code>/short {token_name} 100</code>"
  653. )
  654. perf_summary = token_stats.get('performance_summary', {})
  655. open_positions = token_stats.get('open_positions', [])
  656. parts = [f"📊 <b>{token_name.upper()} Detailed Statistics</b>\n"]
  657. # Completed Trades Summary
  658. parts.append("📈 <b>Completed Trades Summary:</b>")
  659. if perf_summary.get('completed_trades', 0) > 0:
  660. pnl_emoji = "✅" if perf_summary.get('total_pnl', 0) >= 0 else "🔻"
  661. entry_vol = perf_summary.get('completed_entry_volume', 0.0)
  662. pnl_pct = (perf_summary.get('total_pnl', 0.0) / entry_vol * 100) if entry_vol > 0 else 0.0
  663. parts.append(f"• Total Completed: {perf_summary.get('completed_trades', 0)}")
  664. parts.append(f"• {pnl_emoji} Realized P&L: {await formatter.format_price_with_symbol(perf_summary.get('total_pnl', 0.0))} ({pnl_pct:+.2f}%)")
  665. parts.append(f"• Win Rate: {perf_summary.get('win_rate', 0.0):.1f}% ({perf_summary.get('total_wins', 0)}W / {perf_summary.get('total_losses', 0)}L)")
  666. parts.append(f"• Profit Factor: {perf_summary.get('profit_factor', 0.0):.2f}")
  667. parts.append(f"• Expectancy: {await formatter.format_price_with_symbol(perf_summary.get('expectancy', 0.0))}")
  668. parts.append(f"• Avg Win: {await formatter.format_price_with_symbol(perf_summary.get('avg_win', 0.0))} | Avg Loss: {await formatter.format_price_with_symbol(perf_summary.get('avg_loss', 0.0))}")
  669. # Format largest trades with percentages
  670. largest_win_pct_str = f" ({perf_summary.get('largest_win_entry_pct', 0):.2f}%)" if perf_summary.get('largest_win_entry_pct') is not None else ""
  671. largest_loss_pct_str = f" ({perf_summary.get('largest_loss_entry_pct', 0):.2f}%)" if perf_summary.get('largest_loss_entry_pct') is not None else ""
  672. parts.append(f"• Largest Win: {await formatter.format_price_with_symbol(perf_summary.get('largest_win', 0.0))}{largest_win_pct_str} | Largest Loss: {await formatter.format_price_with_symbol(perf_summary.get('largest_loss', 0.0))}{largest_loss_pct_str}")
  673. parts.append(f"• Entry Volume: {await formatter.format_price_with_symbol(perf_summary.get('completed_entry_volume', 0.0))}")
  674. parts.append(f"• Exit Volume: {await formatter.format_price_with_symbol(perf_summary.get('completed_exit_volume', 0.0))}")
  675. parts.append(f"• Average Trade Duration: {perf_summary.get('avg_trade_duration', 'N/A')}")
  676. parts.append(f"• Cancelled Cycles: {perf_summary.get('total_cancelled', 0)}")
  677. else:
  678. parts.append("• No completed trades for this token yet.")
  679. parts.append("")
  680. # Open Positions
  681. parts.append("📉 <b>Current Open Positions:</b>")
  682. if open_positions:
  683. total_open_unrealized_pnl = token_stats.get('summary_total_unrealized_pnl', 0.0)
  684. open_pnl_emoji = "✅" if total_open_unrealized_pnl >= 0 else "🔻"
  685. for pos in open_positions:
  686. pos_side_emoji = "🔼" if pos.get('side', 'buy').lower() == 'buy' else "🔽"
  687. pos_pnl_emoji = "✅" if pos.get('unrealized_pnl', 0) >= 0 else "🔻"
  688. opened_at_str = "N/A"
  689. if pos.get('opened_at'):
  690. try:
  691. from datetime import datetime
  692. opened_at_dt = datetime.fromisoformat(pos['opened_at'])
  693. opened_at_str = opened_at_dt.strftime('%Y-%m-%d %H:%M')
  694. except:
  695. pass
  696. parts.append(f"• {pos_side_emoji} {pos.get('side', '').upper()} {await formatter.format_amount(abs(pos.get('amount',0)), token_name)} {token_name}")
  697. parts.append(f" Entry: {await formatter.format_price_with_symbol(pos.get('entry_price',0), token_name)} | Mark: {await formatter.format_price_with_symbol(pos.get('mark_price',0), token_name)}")
  698. parts.append(f" {pos_pnl_emoji} Unrealized P&L: {await formatter.format_price_with_symbol(pos.get('unrealized_pnl',0))}")
  699. parts.append(f" Opened: {opened_at_str} | ID: ...{pos.get('lifecycle_id', '')[-6:]}")
  700. parts.append(f" {open_pnl_emoji} <b>Total Open P&L: {await formatter.format_price_with_symbol(total_open_unrealized_pnl)}</b>")
  701. else:
  702. parts.append("• No open positions for this token.")
  703. parts.append("")
  704. parts.append(f"📋 Open Orders (Exchange): {token_stats.get('current_open_orders_count', 0)}")
  705. parts.append(f"💡 Use <code>/performance {token_name}</code> for another view including recent trades.")
  706. return "\n".join(parts)
  707. # =============================================================================
  708. # CONVENIENCE METHODS & HIGH-LEVEL OPERATIONS
  709. # =============================================================================
  710. def process_trade_complete_cycle(self, symbol: str, side: str, entry_price: float,
  711. exit_price: float, amount: float,
  712. timestamp: Optional[str] = None) -> str:
  713. """Process a complete trade cycle in one operation."""
  714. # Create lifecycle
  715. lifecycle_id = self.create_trade_lifecycle(symbol, side, trade_type='complete_cycle')
  716. if not lifecycle_id:
  717. raise Exception("Failed to create trade lifecycle")
  718. # Update to position opened
  719. success = self.update_trade_position_opened(lifecycle_id, entry_price, amount, "manual_entry")
  720. if not success:
  721. raise Exception("Failed to update position opened")
  722. # Calculate PnL
  723. if side.lower() == 'buy':
  724. realized_pnl = (exit_price - entry_price) * amount
  725. else: # sell
  726. realized_pnl = (entry_price - exit_price) * amount
  727. # Update to position closed
  728. success = self.update_trade_position_closed(lifecycle_id, exit_price, realized_pnl, "manual_exit")
  729. if not success:
  730. raise Exception("Failed to update position closed")
  731. # Migrate to aggregated stats
  732. self.migrate_trade_to_aggregated_stats(lifecycle_id)
  733. logger.info(f"✅ Processed complete trade cycle: {symbol} {side.upper()} P&L: ${realized_pnl:.2f}")
  734. return lifecycle_id
  735. def get_summary_report(self) -> Dict[str, Any]:
  736. """Get comprehensive summary report."""
  737. try:
  738. perf_stats = self.get_performance_stats()
  739. token_performance = self.get_token_performance(limit=10)
  740. daily_stats = self.get_daily_stats(limit=7)
  741. risk_metrics = self.get_risk_metrics()
  742. balance_adjustments = self.get_balance_adjustments_summary()
  743. # Get current positions
  744. open_positions = self.get_open_positions()
  745. return {
  746. 'performance_stats': perf_stats,
  747. 'top_tokens': token_performance,
  748. 'recent_daily_stats': daily_stats,
  749. 'risk_metrics': risk_metrics,
  750. 'balance_adjustments': balance_adjustments,
  751. 'open_positions_count': len(open_positions),
  752. 'open_positions': open_positions,
  753. 'generated_at': datetime.now(timezone.utc).isoformat()
  754. }
  755. except Exception as e:
  756. logger.error(f"❌ Error generating summary report: {e}")
  757. return {'error': str(e)}
  758. async def record_trade(self, symbol: str, side: str, amount: float, price: float,
  759. exchange_fill_id: Optional[str] = None, trade_type: str = "manual",
  760. pnl: Optional[float] = None, timestamp: Optional[str] = None,
  761. linked_order_table_id_to_link: Optional[int] = None):
  762. """DEPRECATED - use trade lifecycle methods instead."""
  763. if timestamp is None:
  764. timestamp = datetime.now(timezone.utc).isoformat()
  765. value = amount * price
  766. formatter = get_formatter()
  767. ts = timestamp or datetime.now(timezone.utc).isoformat()
  768. base_asset_for_amount = symbol.split('/')[0]
  769. logger.info(f"📈 Trade recorded: {side.upper()} {await formatter.format_amount(amount, base_asset_for_amount)} {symbol} @ {await formatter.format_price(price, symbol)} ({await formatter.format_price(value, symbol)}) [{trade_type}]")
  770. self.db_manager._execute_query(
  771. "INSERT OR IGNORE INTO trades (symbol, side, amount, price, value, trade_type, timestamp, exchange_fill_id, pnl, linked_order_table_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
  772. (symbol, side, amount, price, value, trade_type, ts, exchange_fill_id, pnl or 0.0, linked_order_table_id_to_link)
  773. )
  774. def health_check(self) -> Dict[str, Any]:
  775. """Perform health check on all components."""
  776. try:
  777. health = {
  778. 'database': 'ok',
  779. 'order_manager': 'ok',
  780. 'trade_manager': 'ok',
  781. 'aggregation_manager': 'ok',
  782. 'performance_calculator': 'ok',
  783. 'overall': 'ok'
  784. }
  785. # Test database connection
  786. self.db_manager._fetch_query("SELECT 1")
  787. # Test each component with basic operations
  788. self.get_recent_orders(limit=1)
  789. self.get_recent_trades(limit=1)
  790. self.get_daily_stats(limit=1)
  791. self.get_performance_stats()
  792. return health
  793. except Exception as e:
  794. logger.error(f"❌ Health check failed: {e}")
  795. return {'overall': 'error', 'error': str(e)}