trading_stats_original_backup.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. #!/usr/bin/env python3
  2. # MOVED TO src/trading/stats/ - This file kept for reference
  3. # Use: from src.stats import TradingStats
  4. #!/usr/bin/env python3
  5. """
  6. Trading Statistics Tracker (SQLite Version)
  7. Tracks and calculates comprehensive trading statistics using an SQLite database.
  8. """
  9. import sqlite3
  10. import os
  11. import logging
  12. from datetime import datetime, timedelta, timezone
  13. from typing import Dict, List, Any, Optional, Tuple, Union
  14. import math
  15. from collections import defaultdict
  16. import uuid
  17. import numpy as np # Ensure numpy is imported as np
  18. # 🆕 Import the migration runner
  19. from src.migrations.migrate_db import run_migrations as run_db_migrations
  20. from src.utils.token_display_formatter import get_formatter # Added import
  21. from src.config.config import Config
  22. logger = logging.getLogger(__name__)
  23. def _normalize_token_case(token: str) -> str:
  24. """
  25. Normalize token case: if any characters are already uppercase, keep as-is.
  26. Otherwise, convert to uppercase. This handles mixed-case tokens like kPEPE, kBONK.
  27. """
  28. # Check if any character is already uppercase
  29. if any(c.isupper() for c in token):
  30. return token # Keep original case for mixed-case tokens
  31. else:
  32. return token.upper() # Convert to uppercase for all-lowercase input
  33. class TradingStats:
  34. """Comprehensive trading statistics tracker using SQLite."""
  35. def __init__(self, db_path: str = "data/trading_stats.sqlite"):
  36. """Initialize the stats tracker and connect to SQLite DB."""
  37. self.db_path = db_path
  38. self._ensure_data_directory()
  39. # 🆕 Run database migrations before connecting and creating tables
  40. # This ensures the schema is up-to-date when the connection is made
  41. # and tables are potentially created for the first time.
  42. logger.info("Running database migrations if needed...")
  43. run_db_migrations(self.db_path) # Pass the correct db_path
  44. logger.info("Database migration check complete.")
  45. self.conn = sqlite3.connect(self.db_path, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
  46. self.conn.row_factory = self._dict_factory
  47. self._create_tables() # CREATE IF NOT EXISTS will still be useful for first-time setup
  48. self._initialize_metadata() # Also potentially sets schema_version if DB was just created
  49. # 🆕 Purge old daily aggregated stats on startup
  50. self.purge_old_daily_aggregated_stats()
  51. # 🆕 Purge old balance history on startup
  52. self.purge_old_balance_history()
  53. def _dict_factory(self, cursor, row):
  54. """Convert SQLite rows to dictionaries."""
  55. d = {}
  56. for idx, col in enumerate(cursor.description):
  57. d[col[0]] = row[idx]
  58. return d
  59. def _ensure_data_directory(self):
  60. """Ensure the data directory for the SQLite file exists."""
  61. data_dir = os.path.dirname(self.db_path)
  62. if data_dir and not os.path.exists(data_dir):
  63. os.makedirs(data_dir)
  64. logger.info(f"Created data directory for TradingStats DB: {data_dir}")
  65. def _execute_query(self, query: str, params: tuple = ()):
  66. """Execute a query (INSERT, UPDATE, DELETE)."""
  67. with self.conn:
  68. self.conn.execute(query, params)
  69. def _fetch_query(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
  70. """Execute a SELECT query and fetch all results."""
  71. cur = self.conn.cursor()
  72. cur.execute(query, params)
  73. return cur.fetchall()
  74. def _fetchone_query(self, query: str, params: tuple = ()) -> Optional[Dict[str, Any]]:
  75. """Execute a SELECT query and fetch one result."""
  76. cur = self.conn.cursor()
  77. cur.execute(query, params)
  78. return cur.fetchone()
  79. def _create_tables(self):
  80. """Create SQLite tables if they don't exist."""
  81. queries = [
  82. """
  83. CREATE TABLE IF NOT EXISTS metadata (
  84. key TEXT PRIMARY KEY,
  85. value TEXT
  86. )
  87. """,
  88. """
  89. CREATE TABLE IF NOT EXISTS trades (
  90. id INTEGER PRIMARY KEY AUTOINCREMENT,
  91. exchange_fill_id TEXT UNIQUE,
  92. timestamp TEXT NOT NULL,
  93. symbol TEXT NOT NULL,
  94. side TEXT NOT NULL,
  95. amount REAL NOT NULL,
  96. price REAL NOT NULL,
  97. value REAL NOT NULL,
  98. trade_type TEXT NOT NULL,
  99. pnl REAL DEFAULT 0.0,
  100. linked_order_table_id INTEGER,
  101. -- 🆕 PHASE 4: Lifecycle tracking fields (merged from active_trades)
  102. status TEXT DEFAULT 'executed', -- 'pending', 'executed', 'position_opened', 'position_closed', 'cancelled'
  103. trade_lifecycle_id TEXT, -- Groups related trades into one lifecycle
  104. position_side TEXT, -- 'long', 'short', 'flat' - the resulting position side
  105. -- Position tracking
  106. entry_price REAL,
  107. current_position_size REAL DEFAULT 0,
  108. -- Order IDs (exchange IDs)
  109. entry_order_id TEXT,
  110. stop_loss_order_id TEXT,
  111. take_profit_order_id TEXT,
  112. -- Risk management
  113. stop_loss_price REAL,
  114. take_profit_price REAL,
  115. -- P&L tracking
  116. realized_pnl REAL DEFAULT 0,
  117. unrealized_pnl REAL DEFAULT 0,
  118. mark_price REAL DEFAULT 0,
  119. position_value REAL DEFAULT NULL,
  120. unrealized_pnl_percentage REAL DEFAULT NULL,
  121. -- Risk Info from Exchange
  122. liquidation_price REAL DEFAULT NULL,
  123. margin_used REAL DEFAULT NULL,
  124. leverage REAL DEFAULT NULL,
  125. -- Timestamps
  126. position_opened_at TEXT,
  127. position_closed_at TEXT,
  128. updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
  129. -- Notes
  130. notes TEXT
  131. )
  132. """,
  133. """
  134. CREATE TABLE IF NOT EXISTS balance_history (
  135. timestamp TEXT PRIMARY KEY,
  136. balance REAL NOT NULL
  137. )
  138. """,
  139. """
  140. CREATE TABLE IF NOT EXISTS balance_adjustments (
  141. id INTEGER PRIMARY KEY AUTOINCREMENT,
  142. adjustment_id TEXT UNIQUE,
  143. timestamp TEXT NOT NULL,
  144. type TEXT NOT NULL, -- 'deposit' or 'withdrawal'
  145. amount REAL NOT NULL, -- Always positive, type indicates direction
  146. description TEXT
  147. )
  148. """,
  149. """
  150. CREATE TABLE IF NOT EXISTS orders (
  151. id INTEGER PRIMARY KEY AUTOINCREMENT,
  152. bot_order_ref_id TEXT UNIQUE,
  153. exchange_order_id TEXT UNIQUE,
  154. symbol TEXT NOT NULL,
  155. side TEXT NOT NULL,
  156. type TEXT NOT NULL,
  157. amount_requested REAL NOT NULL,
  158. amount_filled REAL DEFAULT 0.0,
  159. price REAL, -- For limit, stop, etc.
  160. status TEXT NOT NULL, -- e.g., 'open', 'partially_filled', 'filled', 'cancelled', 'rejected', 'expired', 'pending_trigger'
  161. timestamp_created TEXT NOT NULL,
  162. timestamp_updated TEXT NOT NULL,
  163. parent_bot_order_ref_id TEXT NULLABLE -- To link conditional orders (like SL triggers) to their parent order
  164. )
  165. """,
  166. """
  167. CREATE INDEX IF NOT EXISTS idx_orders_bot_order_ref_id ON orders (bot_order_ref_id);
  168. """,
  169. """
  170. CREATE INDEX IF NOT EXISTS idx_orders_exchange_order_id ON orders (exchange_order_id);
  171. """,
  172. """
  173. CREATE INDEX IF NOT EXISTS idx_trades_exchange_fill_id ON trades (exchange_fill_id);
  174. """,
  175. """
  176. CREATE INDEX IF NOT EXISTS idx_trades_linked_order_table_id ON trades (linked_order_table_id);
  177. """,
  178. """
  179. CREATE INDEX IF NOT EXISTS idx_orders_parent_bot_order_ref_id ON orders (parent_bot_order_ref_id);
  180. """,
  181. """
  182. CREATE INDEX IF NOT EXISTS idx_orders_status_type ON orders (status, type);
  183. """,
  184. """
  185. CREATE INDEX IF NOT EXISTS idx_trades_status ON trades (status);
  186. """,
  187. """
  188. CREATE INDEX IF NOT EXISTS idx_trades_lifecycle_id ON trades (trade_lifecycle_id);
  189. """,
  190. """
  191. CREATE INDEX IF NOT EXISTS idx_trades_position_side ON trades (position_side);
  192. """,
  193. """
  194. CREATE INDEX IF NOT EXISTS idx_trades_symbol_status ON trades (symbol, status);
  195. """,
  196. """
  197. CREATE TABLE IF NOT EXISTS daily_balances (
  198. date TEXT PRIMARY KEY,
  199. balance REAL NOT NULL,
  200. timestamp TEXT NOT NULL
  201. )
  202. """,
  203. ]
  204. # 🆕 Add new table creation queries
  205. queries.extend([
  206. """
  207. CREATE TABLE IF NOT EXISTS token_stats (
  208. token TEXT PRIMARY KEY,
  209. total_realized_pnl REAL DEFAULT 0.0,
  210. total_completed_cycles INTEGER DEFAULT 0,
  211. winning_cycles INTEGER DEFAULT 0,
  212. losing_cycles INTEGER DEFAULT 0,
  213. total_entry_volume REAL DEFAULT 0.0, -- Sum of (amount * entry_price) for completed cycles
  214. total_exit_volume REAL DEFAULT 0.0, -- Sum of (amount * exit_price) for completed cycles
  215. sum_of_winning_pnl REAL DEFAULT 0.0,
  216. sum_of_losing_pnl REAL DEFAULT 0.0, -- Stored as a positive value
  217. largest_winning_cycle_pnl REAL DEFAULT 0.0,
  218. largest_losing_cycle_pnl REAL DEFAULT 0.0, -- Stored as a positive value
  219. first_cycle_closed_at TEXT,
  220. last_cycle_closed_at TEXT,
  221. total_cancelled_cycles INTEGER DEFAULT 0, -- Count of lifecycles that ended in 'cancelled'
  222. updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
  223. total_duration_seconds INTEGER DEFAULT 0
  224. )
  225. """,
  226. """
  227. CREATE TABLE IF NOT EXISTS daily_aggregated_stats (
  228. date TEXT NOT NULL, -- YYYY-MM-DD
  229. token TEXT NOT NULL, -- Specific token or a general identifier like '_OVERALL_'
  230. realized_pnl REAL DEFAULT 0.0,
  231. completed_cycles INTEGER DEFAULT 0,
  232. entry_volume REAL DEFAULT 0.0,
  233. exit_volume REAL DEFAULT 0.0,
  234. PRIMARY KEY (date, token)
  235. )
  236. """,
  237. """
  238. CREATE INDEX IF NOT EXISTS idx_daily_stats_date_token ON daily_aggregated_stats (date, token);
  239. """
  240. ])
  241. for query in queries:
  242. self._execute_query(query)
  243. logger.info("SQLite tables ensured for TradingStats.")
  244. def _initialize_metadata(self):
  245. """Initialize metadata if not already present."""
  246. start_date = self._get_metadata('start_date')
  247. initial_balance = self._get_metadata('initial_balance')
  248. if start_date is None:
  249. self._set_metadata('start_date', datetime.now(timezone.utc).isoformat())
  250. logger.info("Initialized 'start_date' in metadata.")
  251. if initial_balance is None:
  252. self._set_metadata('initial_balance', '0.0')
  253. logger.info("Initialized 'initial_balance' in metadata.")
  254. logger.info(f"TradingStats initialized. Start Date: {self._get_metadata('start_date')}, Initial Balance: {self._get_metadata('initial_balance')}")
  255. def _get_metadata(self, key: str) -> Optional[str]:
  256. """Retrieve a value from the metadata table."""
  257. row = self._fetchone_query("SELECT value FROM metadata WHERE key = ?", (key,))
  258. return row['value'] if row else None
  259. def _set_metadata(self, key: str, value: str):
  260. """Set a value in the metadata table."""
  261. self._execute_query("INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)", (key, value))
  262. def set_initial_balance(self, balance: float):
  263. """Set the initial balance if not already set or zero."""
  264. current_initial_balance_str = self._get_metadata('initial_balance')
  265. current_initial_balance = float(current_initial_balance_str) if current_initial_balance_str else 0.0
  266. if current_initial_balance == 0.0: # Only set if it's effectively unset
  267. self._set_metadata('initial_balance', str(balance))
  268. # Also set start_date if it's the first time setting balance
  269. if self._get_metadata('start_date') is None or float(current_initial_balance_str if current_initial_balance_str else '0.0') == 0.0:
  270. self._set_metadata('start_date', datetime.now(timezone.utc).isoformat())
  271. formatter = get_formatter()
  272. logger.info(f"Initial balance set to: {formatter.format_price_with_symbol(balance)}")
  273. else:
  274. formatter = get_formatter()
  275. logger.info(f"Initial balance already set to {formatter.format_price_with_symbol(current_initial_balance)}. Not changing.")
  276. def record_balance(self, balance: float):
  277. """Record daily balance snapshot."""
  278. today_iso = datetime.now(timezone.utc).date().isoformat()
  279. now_iso = datetime.now(timezone.utc).isoformat()
  280. existing_entry = self._fetchone_query("SELECT date FROM daily_balances WHERE date = ?", (today_iso,))
  281. if existing_entry:
  282. self._execute_query("UPDATE daily_balances SET balance = ?, timestamp = ? WHERE date = ?",
  283. (balance, now_iso, today_iso))
  284. else:
  285. self._execute_query("INSERT INTO daily_balances (date, balance, timestamp) VALUES (?, ?, ?)",
  286. (today_iso, balance, now_iso))
  287. # logger.debug(f"Recorded balance for {today_iso}: ${balance:.2f}") # Potentially too verbose
  288. def record_trade(self, symbol: str, side: str, amount: float, price: float,
  289. exchange_fill_id: Optional[str] = None, trade_type: str = "manual",
  290. pnl: Optional[float] = None, timestamp: Optional[str] = None,
  291. linked_order_table_id_to_link: Optional[int] = None):
  292. """Record a trade in the database."""
  293. if timestamp is None:
  294. timestamp = datetime.now(timezone.utc).isoformat()
  295. value = amount * price
  296. self._execute_query(
  297. "INSERT OR IGNORE INTO trades (symbol, side, amount, price, value, trade_type, timestamp, exchange_fill_id, pnl, linked_order_table_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
  298. (symbol, side, amount, price, value, trade_type, timestamp, exchange_fill_id, pnl or 0.0, linked_order_table_id_to_link)
  299. )
  300. formatter = get_formatter()
  301. # Assuming symbol's base asset for amount formatting. If symbol is like BTC/USDT, base is BTC.
  302. base_asset_for_amount = symbol.split('/')[0] if '/' in symbol else symbol
  303. logger.info(f"📈 Trade recorded: {side.upper()} {formatter.format_amount(amount, base_asset_for_amount)} {symbol} @ {formatter.format_price(price, symbol)} ({formatter.format_price(value, symbol)}) [{trade_type}]")
  304. def get_all_trades(self) -> List[Dict[str, Any]]:
  305. """Fetch all trades from the database, ordered by timestamp."""
  306. return self._fetch_query("SELECT * FROM trades ORDER BY timestamp ASC")
  307. def get_trade_by_symbol_and_status(self, symbol: str, status: str) -> Optional[Dict[str, Any]]:
  308. """
  309. Fetches a single trade record for a given symbol and status.
  310. Typically used to find an open position master record.
  311. Assumes that for a given symbol, there's at most one trade record with a specific
  312. active status like 'position_opened'. If multiple could exist, this fetches the most recent.
  313. """
  314. query = "SELECT * FROM trades WHERE symbol = ? AND status = ? ORDER BY id DESC LIMIT 1"
  315. trade = self._fetchone_query(query, (symbol, status))
  316. if trade:
  317. logger.debug(f"Found trade for {symbol} with status {status}: ID {trade.get('id')}")
  318. # else: # Can be noisy if not finding a trade is a common occurrence
  319. # logger.debug(f"No trade found for {symbol} with status {status}")
  320. return trade
  321. def get_basic_stats(self, current_balance: Optional[float] = None) -> Dict[str, Any]:
  322. """Get basic trading statistics from DB, primarily using aggregated tables."""
  323. # Get counts of open positions (trades that are not yet migrated)
  324. open_positions_count = self._get_open_positions_count_from_db()
  325. # Get overall aggregated stats from token_stats table
  326. query_token_stats_summary = """
  327. SELECT
  328. SUM(total_realized_pnl) as total_pnl_from_cycles,
  329. SUM(total_completed_cycles) as total_completed_cycles_sum,
  330. MIN(first_cycle_closed_at) as overall_first_cycle_closed,
  331. MAX(last_cycle_closed_at) as overall_last_cycle_closed
  332. FROM token_stats
  333. """
  334. token_stats_summary = self._fetchone_query(query_token_stats_summary)
  335. 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
  336. 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
  337. # Total trades considered as sum of completed cycles and currently open positions
  338. # This redefines 'total_trades' from its previous meaning of individual fills.
  339. total_trades_redefined = total_completed_cycles_sum + open_positions_count
  340. initial_balance_str = self._get_metadata('initial_balance')
  341. initial_balance = float(initial_balance_str) if initial_balance_str else 0.0
  342. start_date_iso = self._get_metadata('start_date')
  343. start_date_obj = datetime.fromisoformat(start_date_iso) if start_date_iso else datetime.now(timezone.utc)
  344. days_active = (datetime.now(timezone.utc) - start_date_obj).days + 1
  345. # 'last_trade' timestamp could be the last update to token_stats or an open trade
  346. last_activity_ts = token_stats_summary['overall_last_cycle_closed'] if token_stats_summary else None
  347. last_open_trade_ts_row = self._fetchone_query("SELECT MAX(updated_at) as last_update FROM trades WHERE status = 'position_opened'")
  348. if last_open_trade_ts_row and last_open_trade_ts_row['last_update']:
  349. if not last_activity_ts or datetime.fromisoformat(last_open_trade_ts_row['last_update']) > datetime.fromisoformat(last_activity_ts):
  350. last_activity_ts = last_open_trade_ts_row['last_update']
  351. # Buy/Sell trades count from individual fills is no longer directly available for completed cycles.
  352. # If needed, this requires schema change in token_stats or a different approach.
  353. # For now, these are omitted from basic_stats.
  354. return {
  355. 'total_trades': total_trades_redefined, # This is now cycles + open positions
  356. 'completed_trades': total_completed_cycles_sum, # This is sum of total_completed_cycles from token_stats
  357. # 'buy_trades': buy_trades_count, # Omitted
  358. # 'sell_trades': sell_trades_count, # Omitted
  359. 'initial_balance': initial_balance,
  360. 'total_pnl': total_pnl_from_cycles, # PNL from closed cycles via token_stats
  361. 'days_active': days_active,
  362. 'start_date': start_date_obj.strftime('%Y-%m-%d'),
  363. 'last_trade': last_activity_ts, # Reflects last known activity (cycle close or open trade update)
  364. 'open_positions_count': open_positions_count
  365. }
  366. def get_performance_stats(self) -> Dict[str, Any]:
  367. """Calculate advanced performance statistics using aggregated data from token_stats."""
  368. query = """
  369. SELECT
  370. SUM(total_completed_cycles) as total_cycles,
  371. SUM(winning_cycles) as total_wins,
  372. SUM(losing_cycles) as total_losses,
  373. SUM(sum_of_winning_pnl) as total_winning_pnl,
  374. SUM(sum_of_losing_pnl) as total_losing_pnl, -- Stored positive
  375. MAX(largest_winning_cycle_pnl) as overall_largest_win,
  376. MAX(largest_losing_cycle_pnl) as overall_largest_loss -- Stored positive
  377. FROM token_stats
  378. """
  379. summary = self._fetchone_query(query)
  380. # Add total volume
  381. volume_summary = self._fetchone_query("SELECT SUM(total_entry_volume) as total_volume FROM token_stats")
  382. total_trading_volume = volume_summary['total_volume'] if volume_summary and volume_summary['total_volume'] is not None else 0.0
  383. # 🆕 Calculate Average Trade Duration
  384. duration_summary = self._fetchone_query("SELECT SUM(total_duration_seconds) as total_seconds, SUM(total_completed_cycles) as total_cycles FROM token_stats")
  385. avg_trade_duration_formatted = "N/A"
  386. if duration_summary and duration_summary['total_cycles'] and duration_summary['total_cycles'] > 0:
  387. avg_seconds = duration_summary['total_seconds'] / duration_summary['total_cycles']
  388. avg_trade_duration_formatted = self._format_duration(avg_seconds)
  389. # Get individual token performances for best/worst
  390. all_token_perf_stats = self.get_token_performance()
  391. best_token_pnl_pct = -float('inf')
  392. best_token_name = "N/A"
  393. worst_token_pnl_pct = float('inf')
  394. worst_token_name = "N/A"
  395. if all_token_perf_stats:
  396. for token_name_iter, stats_data in all_token_perf_stats.items():
  397. pnl_pct = stats_data.get('pnl_percentage', 0.0)
  398. # Ensure token has completed trades and pnl_pct is a valid number
  399. if stats_data.get('completed_trades', 0) > 0 and isinstance(pnl_pct, (int, float)) and not math.isinf(pnl_pct) and not math.isnan(pnl_pct):
  400. if pnl_pct > best_token_pnl_pct:
  401. best_token_pnl_pct = pnl_pct
  402. best_token_name = token_name_iter
  403. if pnl_pct < worst_token_pnl_pct:
  404. worst_token_pnl_pct = pnl_pct
  405. worst_token_name = token_name_iter
  406. # Handle cases where no valid tokens were found for best/worst
  407. if best_token_name == "N/A":
  408. best_token_pnl_pct = 0.0
  409. if worst_token_name == "N/A":
  410. worst_token_pnl_pct = 0.0
  411. if not summary or summary['total_cycles'] is None or summary['total_cycles'] == 0:
  412. return {
  413. 'win_rate': 0.0, 'profit_factor': 0.0, 'avg_win': 0.0, 'avg_loss': 0.0,
  414. 'largest_win': 0.0, 'largest_loss': 0.0,
  415. 'total_wins': 0, 'total_losses': 0, 'expectancy': 0.0,
  416. 'total_trading_volume': total_trading_volume,
  417. 'best_performing_token': {'name': best_token_name, 'pnl_percentage': best_token_pnl_pct},
  418. 'worst_performing_token': {'name': worst_token_name, 'pnl_percentage': worst_token_pnl_pct},
  419. 'avg_trade_duration': avg_trade_duration_formatted,
  420. }
  421. total_completed_count = summary['total_cycles']
  422. total_wins_count = summary['total_wins'] if summary['total_wins'] is not None else 0
  423. total_losses_count = summary['total_losses'] if summary['total_losses'] is not None else 0
  424. win_rate = (total_wins_count / total_completed_count * 100) if total_completed_count > 0 else 0.0
  425. sum_of_wins = summary['total_winning_pnl'] if summary['total_winning_pnl'] is not None else 0.0
  426. sum_of_losses = summary['total_losing_pnl'] if summary['total_losing_pnl'] is not None else 0.0 # This is sum of absolute losses
  427. profit_factor = (sum_of_wins / sum_of_losses) if sum_of_losses > 0 else float('inf') if sum_of_wins > 0 else 0.0
  428. avg_win = (sum_of_wins / total_wins_count) if total_wins_count > 0 else 0.0
  429. avg_loss = (sum_of_losses / total_losses_count) if total_losses_count > 0 else 0.0 # Avg of absolute losses
  430. largest_win = summary['overall_largest_win'] if summary['overall_largest_win'] is not None else 0.0
  431. largest_loss = summary['overall_largest_loss'] if summary['overall_largest_loss'] is not None else 0.0 # Largest absolute loss
  432. # Consecutive wins/losses removed as it's hard to track with this aggregation model.
  433. expectancy = (avg_win * (win_rate / 100)) - (avg_loss * (1 - (win_rate / 100)))
  434. return {
  435. 'win_rate': win_rate, 'profit_factor': profit_factor, 'avg_win': avg_win, 'avg_loss': avg_loss,
  436. 'largest_win': largest_win, 'largest_loss': largest_loss,
  437. 'total_wins': total_wins_count, 'total_losses': total_losses_count, 'expectancy': expectancy,
  438. 'total_trading_volume': total_trading_volume,
  439. 'best_performing_token': {'name': best_token_name, 'pnl_percentage': best_token_pnl_pct},
  440. 'worst_performing_token': {'name': worst_token_name, 'pnl_percentage': worst_token_pnl_pct},
  441. 'avg_trade_duration': avg_trade_duration_formatted,
  442. }
  443. def get_risk_metrics(self) -> Dict[str, Any]:
  444. """Calculate risk-adjusted metrics from daily balances."""
  445. # Get live max drawdown from metadata
  446. max_drawdown_live_str = self._get_metadata('drawdown_max_drawdown_pct')
  447. max_drawdown_live = float(max_drawdown_live_str) if max_drawdown_live_str else 0.0
  448. daily_balances_data = self._fetch_query("SELECT balance FROM daily_balances ORDER BY date ASC")
  449. if not daily_balances_data or len(daily_balances_data) < 2:
  450. return {'sharpe_ratio': 0.0, 'sortino_ratio': 0.0, 'max_drawdown': 0.0, 'volatility': 0.0, 'var_95': 0.0, 'max_drawdown_live': max_drawdown_live}
  451. balances = [entry['balance'] for entry in daily_balances_data]
  452. returns = np.diff(balances) / balances[:-1] # Calculate daily returns
  453. returns = returns[np.isfinite(returns)] # Remove NaNs or Infs if any balance was 0
  454. if returns.size == 0:
  455. return {'sharpe_ratio': 0.0, 'sortino_ratio': 0.0, 'max_drawdown': 0.0, 'volatility': 0.0, 'var_95': 0.0, 'max_drawdown_live': max_drawdown_live}
  456. risk_free_rate_daily = (1 + 0.02)**(1/365) - 1 # Approx 2% annual risk-free rate, daily
  457. excess_returns = returns - risk_free_rate_daily
  458. sharpe_ratio = np.mean(excess_returns) / np.std(returns) * np.sqrt(365) if np.std(returns) > 0 else 0.0
  459. downside_returns = returns[returns < 0]
  460. downside_std = np.std(downside_returns) if len(downside_returns) > 0 else 0.0
  461. sortino_ratio = np.mean(excess_returns) / downside_std * np.sqrt(365) if downside_std > 0 else 0.0
  462. cumulative_returns = np.cumprod(1 + returns)
  463. peak = np.maximum.accumulate(cumulative_returns)
  464. drawdown = (cumulative_returns - peak) / peak
  465. max_drawdown_daily_pct = abs(np.min(drawdown) * 100) if drawdown.size > 0 else 0.0
  466. volatility_pct = np.std(returns) * np.sqrt(365) * 100
  467. var_95_pct = abs(np.percentile(returns, 5) * 100) if returns.size > 0 else 0.0
  468. return {
  469. 'sharpe_ratio': sharpe_ratio, 'sortino_ratio': sortino_ratio,
  470. 'max_drawdown': max_drawdown_daily_pct, 'volatility': volatility_pct,
  471. 'var_95': var_95_pct, 'max_drawdown_live': max_drawdown_live
  472. }
  473. def get_comprehensive_stats(self, current_balance: Optional[float] = None) -> Dict[str, Any]:
  474. """Get all statistics combined."""
  475. if current_balance is not None: # Ensure it's not just None, but explicitly provided
  476. self.record_balance(current_balance) # Record current balance for today
  477. basic = self.get_basic_stats(current_balance) # Pass current_balance for P&L context if needed
  478. performance = self.get_performance_stats()
  479. risk = self.get_risk_metrics()
  480. initial_balance = basic['initial_balance']
  481. total_return_pct = 0.0
  482. # Use current_balance if available and valid for total return calculation
  483. # Otherwise, PNL from basic_stats (closed trades) is the primary PNL source
  484. # This needs careful thought: current_balance reflects unrealized PNL too.
  485. # The original code used current_balance - initial_balance for total_pnl if current_balance provided.
  486. effective_balance_for_return = current_balance if current_balance is not None else (initial_balance + basic['total_pnl'])
  487. if initial_balance > 0:
  488. total_return_pct = ((effective_balance_for_return - initial_balance) / initial_balance) * 100
  489. return {
  490. 'basic': basic,
  491. 'performance': performance,
  492. 'risk': risk,
  493. 'current_balance': current_balance if current_balance is not None else initial_balance + basic['total_pnl'], # Best estimate
  494. 'total_return': total_return_pct, # Percentage
  495. 'last_updated': datetime.now(timezone.utc).isoformat()
  496. }
  497. def _get_open_positions_count_from_db(self) -> int:
  498. """🧹 PHASE 4: Get count of open positions from enhanced trades table."""
  499. row = self._fetchone_query("SELECT COUNT(DISTINCT symbol) as count FROM trades WHERE status = 'position_opened'")
  500. return row['count'] if row else 0
  501. def format_stats_message(self, current_balance: Optional[float] = None) -> str:
  502. """Format stats for Telegram display using data from DB."""
  503. try:
  504. stats = self.get_comprehensive_stats(current_balance)
  505. formatter = get_formatter()
  506. basic = stats['basic']
  507. perf = stats['performance']
  508. risk = stats['risk'] # For portfolio drawdown
  509. effective_current_balance = stats['current_balance']
  510. initial_bal = basic['initial_balance']
  511. total_pnl_val = effective_current_balance - initial_bal if initial_bal > 0 and current_balance is not None else basic['total_pnl']
  512. total_return_pct = (total_pnl_val / initial_bal * 100) if initial_bal > 0 else 0.0
  513. pnl_emoji = "🟢" if total_pnl_val >= 0 else "🔴"
  514. open_positions_count = basic['open_positions_count']
  515. stats_text_parts = []
  516. stats_text_parts.append(f"📊 <b>Trading Statistics</b>\n")
  517. # Account Overview
  518. stats_text_parts.append(f"\n💰 <b>Account Overview:</b>")
  519. stats_text_parts.append(f"• Current Balance: {formatter.format_price_with_symbol(effective_current_balance)}")
  520. stats_text_parts.append(f"• Initial Balance: {formatter.format_price_with_symbol(initial_bal)}")
  521. stats_text_parts.append(f"• Open Positions: {open_positions_count}")
  522. stats_text_parts.append(f"• {pnl_emoji} Total P&L: {formatter.format_price_with_symbol(total_pnl_val)} ({total_return_pct:+.2f}%)")
  523. stats_text_parts.append(f"• Days Active: {basic['days_active']}\n")
  524. # Performance Metrics
  525. stats_text_parts.append(f"\n🏆 <b>Performance Metrics:</b>")
  526. stats_text_parts.append(f"• Total Completed Trades: {basic['completed_trades']}")
  527. stats_text_parts.append(f"• Trading Volume (Entry Vol.): {formatter.format_price_with_symbol(perf.get('total_trading_volume', 0.0))}")
  528. stats_text_parts.append(f"• Profit Factor: {perf['profit_factor']:.2f}")
  529. stats_text_parts.append(f"• Expectancy: {formatter.format_price_with_symbol(perf['expectancy'])} (Value per trade)")
  530. # Note for Expectancy Percentage: \"[Info: Percentage representation requires further definition]\" might be too verbose for typical display.
  531. stats_text_parts.append(f"• Largest Winning Trade: {formatter.format_price_with_symbol(perf['largest_win'])} (Value)")
  532. stats_text_parts.append(f"• Largest Losing Trade: {formatter.format_price_with_symbol(-perf['largest_loss'])} (Value)")
  533. # Note for Largest Trade P&L %: Similar to expectancy, noting \"[Info: P&L % for specific trades requires data enhancement]\" in the bot message might be too much.
  534. best_token_stats = perf.get('best_performing_token', {'name': 'N/A', 'pnl_percentage': 0.0})
  535. worst_token_stats = perf.get('worst_performing_token', {'name': 'N/A', 'pnl_percentage': 0.0})
  536. stats_text_parts.append(f"• Best Performing Token: {best_token_stats['name']} ({best_token_stats['pnl_percentage']:+.2f}%)")
  537. stats_text_parts.append(f"• Worst Performing Token: {worst_token_stats['name']} ({worst_token_stats['pnl_percentage']:+.2f}%)")
  538. stats_text_parts.append(f"• Average Trade Duration: {perf.get('avg_trade_duration', 'N/A')}")
  539. stats_text_parts.append(f"• Portfolio Max Drawdown: {risk.get('max_drawdown_live', 0.0):.2f}% <i>(Live)</i>")
  540. # Future note: \"[Info: Trading P&L specific drawdown analysis planned]\"
  541. # Session Info
  542. stats_text_parts.append(f"\n\n⏰ <b>Session Info:</b>")
  543. stats_text_parts.append(f"• Bot Started: {basic['start_date']}")
  544. stats_text_parts.append(f"• Stats Last Updated: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}")
  545. return "\n".join(stats_text_parts).strip()
  546. except Exception as e:
  547. logger.error(f"Error formatting stats message: {e}", exc_info=True)
  548. return f"""📊 <b>Trading Statistics</b>\n\n❌ <b>Error loading statistics</b>\n\n🔧 <b>Debug info:</b> {str(e)[:100]}"""
  549. def get_recent_trades(self, limit: int = 10) -> List[Dict[str, Any]]:
  550. """Get recent trades from DB (these are active/open trades, as completed ones are migrated)."""
  551. return self._fetch_query("SELECT * FROM trades WHERE status = 'position_opened' ORDER BY updated_at DESC LIMIT ?", (limit,))
  552. def get_token_performance(self) -> Dict[str, Dict[str, Any]]:
  553. """Get performance statistics grouped by token using the token_stats table."""
  554. all_token_stats = self._fetch_query("SELECT * FROM token_stats ORDER BY token ASC")
  555. token_performance_map = {}
  556. for record in all_token_stats:
  557. token = record['token']
  558. total_pnl = record.get('total_realized_pnl', 0.0)
  559. # total_volume_sold now refers to total_exit_volume from token_stats
  560. total_volume = record.get('total_entry_volume', 0.0)
  561. pnl_percentage = (total_pnl / total_volume * 100) if total_volume > 0 else 0.0
  562. total_completed_count = record.get('total_completed_cycles', 0)
  563. total_wins_count = record.get('winning_cycles', 0)
  564. total_losses_count = record.get('losing_cycles', 0)
  565. win_rate = (total_wins_count / total_completed_count * 100) if total_completed_count > 0 else 0.0
  566. sum_of_wins = record.get('sum_of_winning_pnl', 0.0)
  567. sum_of_losses = record.get('sum_of_losing_pnl', 0.0) # Stored positive
  568. profit_factor = (sum_of_wins / sum_of_losses) if sum_of_losses > 0 else float('inf') if sum_of_wins > 0 else 0.0
  569. avg_win = (sum_of_wins / total_wins_count) if total_wins_count > 0 else 0.0
  570. avg_loss = (sum_of_losses / total_losses_count) if total_losses_count > 0 else 0.0
  571. expectancy = (avg_win * (win_rate / 100)) - (avg_loss * (1 - (win_rate / 100)))
  572. largest_win = record.get('largest_winning_cycle_pnl', 0.0)
  573. largest_loss = record.get('largest_losing_cycle_pnl', 0.0) # Stored positive
  574. token_performance_map[token] = {
  575. 'token': token, # Added for easier access if iterating over values
  576. 'total_pnl': total_pnl,
  577. 'pnl_percentage': pnl_percentage,
  578. 'completed_trades': total_completed_count,
  579. 'total_volume': total_volume, # This is total_entry_volume
  580. 'win_rate': win_rate,
  581. 'total_wins': total_wins_count,
  582. 'total_losses': total_losses_count,
  583. 'profit_factor': profit_factor,
  584. 'expectancy': expectancy,
  585. 'largest_win': largest_win,
  586. 'largest_loss': largest_loss,
  587. 'avg_win': avg_win,
  588. 'avg_loss': avg_loss,
  589. 'first_cycle_closed_at': record.get('first_cycle_closed_at'),
  590. 'last_cycle_closed_at': record.get('last_cycle_closed_at'),
  591. 'total_cancelled': record.get('total_cancelled_cycles', 0),
  592. 'total_duration_seconds': record.get('total_duration_seconds', 0),
  593. 'avg_trade_duration': self._format_duration(record.get('total_duration_seconds', 0) / total_completed_count) if total_completed_count > 0 else "N/A"
  594. }
  595. return token_performance_map
  596. def get_token_detailed_stats(self, token: str) -> Dict[str, Any]:
  597. """Get detailed statistics for a specific token using token_stats and current open trades."""
  598. upper_token = _normalize_token_case(token)
  599. # Get aggregated performance from token_stats
  600. token_agg_stats = self._fetchone_query("SELECT * FROM token_stats WHERE token = ?", (upper_token,))
  601. # Get currently open trades for this token from the 'trades' table (not yet migrated)
  602. # These are not completed cycles but represent current exposure.
  603. open_trades_for_token = self._fetch_query(
  604. "SELECT * FROM trades WHERE symbol LIKE ? AND status = 'position_opened' ORDER BY timestamp ASC",
  605. (f"{upper_token}/%",)
  606. )
  607. if not token_agg_stats and not open_trades_for_token:
  608. return {
  609. 'token': upper_token, 'total_trades': 0, 'total_pnl': 0.0, 'win_rate': 0.0,
  610. 'message': f"No trading history or open positions found for {upper_token}"
  611. }
  612. # Initialize with empty performance if no aggregated data
  613. perf_stats = {}
  614. if token_agg_stats:
  615. perf_stats = {
  616. 'completed_trades': token_agg_stats.get('total_completed_cycles', 0),
  617. 'total_pnl': token_agg_stats.get('total_realized_pnl', 0.0),
  618. 'pnl_percentage': 0.0, # Recalculate if needed, or store avg pnl_percentage
  619. 'win_rate': 0.0,
  620. 'profit_factor': token_agg_stats.get('profit_factor'), # Placeholder, need to calc from sums
  621. 'avg_win': 0.0,
  622. 'avg_loss': 0.0,
  623. 'largest_win': token_agg_stats.get('largest_winning_cycle_pnl', 0.0),
  624. 'largest_loss': token_agg_stats.get('largest_losing_cycle_pnl', 0.0),
  625. 'expectancy': 0.0,
  626. 'total_wins': token_agg_stats.get('winning_cycles',0),
  627. 'total_losses': token_agg_stats.get('losing_cycles',0),
  628. 'completed_entry_volume': token_agg_stats.get('total_entry_volume', 0.0),
  629. 'completed_exit_volume': token_agg_stats.get('total_exit_volume', 0.0),
  630. 'total_cancelled': token_agg_stats.get('total_cancelled_cycles', 0),
  631. 'total_duration_seconds': token_agg_stats.get('total_duration_seconds', 0),
  632. 'avg_trade_duration': self._format_duration(token_agg_stats.get('total_duration_seconds', 0) / token_agg_stats.get('total_completed_cycles', 0)) if token_agg_stats.get('total_completed_cycles', 0) > 0 else "N/A"
  633. }
  634. if perf_stats['completed_trades'] > 0:
  635. perf_stats['win_rate'] = (perf_stats['total_wins'] / perf_stats['completed_trades'] * 100) if perf_stats['completed_trades'] > 0 else 0.0
  636. sum_wins = token_agg_stats.get('sum_of_winning_pnl', 0.0)
  637. sum_losses = token_agg_stats.get('sum_of_losing_pnl', 0.0)
  638. perf_stats['profit_factor'] = (sum_wins / sum_losses) if sum_losses > 0 else float('inf') if sum_wins > 0 else 0.0
  639. perf_stats['avg_win'] = (sum_wins / perf_stats['total_wins']) if perf_stats['total_wins'] > 0 else 0.0
  640. perf_stats['avg_loss'] = (sum_losses / perf_stats['total_losses']) if perf_stats['total_losses'] > 0 else 0.0
  641. perf_stats['expectancy'] = (perf_stats['avg_win'] * (perf_stats['win_rate'] / 100)) - (perf_stats['avg_loss'] * (1 - (perf_stats['win_rate'] / 100)))
  642. if perf_stats['completed_entry_volume'] > 0:
  643. perf_stats['pnl_percentage'] = (perf_stats['total_pnl'] / perf_stats['completed_entry_volume'] * 100)
  644. else: # No completed cycles for this token yet
  645. perf_stats = {
  646. 'completed_trades': 0, 'total_pnl': 0.0, 'pnl_percentage': 0.0, 'win_rate': 0.0,
  647. 'profit_factor': 0.0, 'avg_win': 0.0, 'avg_loss': 0.0, 'largest_win': 0.0, 'largest_loss': 0.0,
  648. 'expectancy': 0.0, 'total_wins':0, 'total_losses':0,
  649. 'completed_entry_volume': 0.0, 'completed_exit_volume': 0.0, 'total_cancelled': 0,
  650. 'total_duration_seconds': 0, 'avg_trade_duration': "N/A"
  651. }
  652. # Info about open positions for this token (raw trades, not cycles)
  653. open_positions_summary = []
  654. total_open_value = 0.0
  655. total_open_unrealized_pnl = 0.0
  656. for op_trade in open_trades_for_token:
  657. open_positions_summary.append({
  658. 'lifecycle_id': op_trade.get('trade_lifecycle_id'),
  659. 'side': op_trade.get('position_side'),
  660. 'amount': op_trade.get('current_position_size'),
  661. 'entry_price': op_trade.get('entry_price'),
  662. 'mark_price': op_trade.get('mark_price'),
  663. 'unrealized_pnl': op_trade.get('unrealized_pnl'),
  664. 'opened_at': op_trade.get('position_opened_at')
  665. })
  666. total_open_value += op_trade.get('value', 0.0) # Initial value of open positions
  667. total_open_unrealized_pnl += op_trade.get('unrealized_pnl', 0.0)
  668. # Raw individual orders from 'orders' table for this token can be complex to summarize here
  669. # The old version counted 'buy_orders' and 'sell_orders' from all trades for the token.
  670. # This is no longer straightforward for completed cycles.
  671. # We can count open orders for this token.
  672. open_orders_count_row = self._fetchone_query(
  673. "SELECT COUNT(*) as count FROM orders WHERE symbol LIKE ? AND status IN ('open', 'submitted', 'pending_trigger')",
  674. (f"{upper_token}/%",)
  675. )
  676. current_open_orders_for_token = open_orders_count_row['count'] if open_orders_count_row else 0
  677. # 'total_trades' here could mean total orders ever placed for this token, or completed cycles + open positions
  678. # Let's define it as completed cycles + number of currently open positions for consistency with get_basic_stats
  679. effective_total_trades = perf_stats['completed_trades'] + len(open_trades_for_token)
  680. return {
  681. 'token': upper_token,
  682. 'message': f"Statistics for {upper_token}",
  683. 'performance_summary': perf_stats, # From token_stats table
  684. 'open_positions': open_positions_summary, # List of currently open positions
  685. 'open_positions_count': len(open_trades_for_token),
  686. 'current_open_orders_count': current_open_orders_for_token,
  687. 'summary_total_trades': effective_total_trades, # Completed cycles + open positions
  688. 'summary_total_realized_pnl': perf_stats['total_pnl'],
  689. 'summary_total_unrealized_pnl': total_open_unrealized_pnl,
  690. # 'cycles': token_cycles # Raw cycle data for completed trades is no longer stored directly after migration
  691. }
  692. def get_daily_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  693. """Get daily performance stats for the last N days from daily_aggregated_stats."""
  694. daily_stats_list = []
  695. today_utc = datetime.now(timezone.utc).date()
  696. for i in range(limit):
  697. target_date = today_utc - timedelta(days=i)
  698. date_str = target_date.strftime('%Y-%m-%d')
  699. date_formatted = target_date.strftime('%m/%d') # For display
  700. # Query for all tokens for that day and sum them up
  701. # Or, if daily_aggregated_stats stores an _OVERALL_ record, query that.
  702. # Assuming for now we sum up all token records for a given day.
  703. day_aggregated_data = self._fetch_query(
  704. "SELECT SUM(realized_pnl) as pnl, SUM(completed_cycles) as trades, SUM(exit_volume) as volume FROM daily_aggregated_stats WHERE date = ?",
  705. (date_str,)
  706. )
  707. stats_for_day = None
  708. if day_aggregated_data and len(day_aggregated_data) > 0 and day_aggregated_data[0]['trades'] is not None:
  709. stats_for_day = day_aggregated_data[0]
  710. # Calculate pnl_pct if volume is present and positive
  711. pnl = stats_for_day.get('pnl', 0.0) or 0.0
  712. volume = stats_for_day.get('volume', 0.0) or 0.0
  713. stats_for_day['pnl_pct'] = (pnl / volume * 100) if volume > 0 else 0.0
  714. # Ensure trades is an int
  715. stats_for_day['trades'] = int(stats_for_day.get('trades', 0) or 0)
  716. if stats_for_day and stats_for_day['trades'] > 0:
  717. daily_stats_list.append({
  718. 'date': date_str, 'date_formatted': date_formatted, 'has_trades': True,
  719. **stats_for_day
  720. })
  721. else:
  722. daily_stats_list.append({
  723. 'date': date_str, 'date_formatted': date_formatted, 'has_trades': False,
  724. 'trades': 0, 'pnl': 0.0, 'volume': 0.0, 'pnl_pct': 0.0
  725. })
  726. return daily_stats_list
  727. def get_weekly_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  728. """Get weekly performance stats for the last N weeks by aggregating daily_aggregated_stats."""
  729. weekly_stats_list = []
  730. today_utc = datetime.now(timezone.utc).date()
  731. for i in range(limit):
  732. target_monday = today_utc - timedelta(days=today_utc.weekday() + (i * 7))
  733. target_sunday = target_monday + timedelta(days=6)
  734. week_key_display = f"{target_monday.strftime('%Y-W%W')}" # For internal key if needed
  735. week_formatted_display = f"{target_monday.strftime('%m/%d')}-{target_sunday.strftime('%m/%d/%y')}"
  736. # Fetch daily records for this week range
  737. daily_records_for_week = self._fetch_query(
  738. "SELECT date, realized_pnl, completed_cycles, exit_volume FROM daily_aggregated_stats WHERE date BETWEEN ? AND ?",
  739. (target_monday.strftime('%Y-%m-%d'), target_sunday.strftime('%Y-%m-%d'))
  740. )
  741. if daily_records_for_week:
  742. total_pnl_week = sum(d.get('realized_pnl', 0.0) or 0.0 for d in daily_records_for_week)
  743. total_trades_week = sum(d.get('completed_cycles', 0) or 0 for d in daily_records_for_week)
  744. total_volume_week = sum(d.get('exit_volume', 0.0) or 0.0 for d in daily_records_for_week)
  745. pnl_pct_week = (total_pnl_week / total_volume_week * 100) if total_volume_week > 0 else 0.0
  746. if total_trades_week > 0:
  747. weekly_stats_list.append({
  748. 'week': week_key_display,
  749. 'week_formatted': week_formatted_display,
  750. 'has_trades': True,
  751. 'pnl': total_pnl_week,
  752. 'trades': total_trades_week,
  753. 'volume': total_volume_week,
  754. 'pnl_pct': pnl_pct_week
  755. })
  756. else:
  757. weekly_stats_list.append({
  758. 'week': week_key_display, 'week_formatted': week_formatted_display, 'has_trades': False,
  759. 'trades': 0, 'pnl': 0.0, 'volume': 0.0, 'pnl_pct': 0.0
  760. })
  761. else:
  762. weekly_stats_list.append({
  763. 'week': week_key_display, 'week_formatted': week_formatted_display, 'has_trades': False,
  764. 'trades': 0, 'pnl': 0.0, 'volume': 0.0, 'pnl_pct': 0.0
  765. })
  766. return weekly_stats_list
  767. def get_monthly_stats(self, limit: int = 10) -> List[Dict[str, Any]]:
  768. """Get monthly performance stats for the last N months by aggregating daily_aggregated_stats."""
  769. monthly_stats_list = []
  770. current_month_start_utc = datetime.now(timezone.utc).date().replace(day=1)
  771. for i in range(limit):
  772. year = current_month_start_utc.year
  773. month = current_month_start_utc.month - i
  774. while month <= 0:
  775. month += 12
  776. year -= 1
  777. target_month_start_date = datetime(year, month, 1, tzinfo=timezone.utc).date()
  778. # Find end of target month
  779. next_month_start_date = datetime(year + (month // 12), (month % 12) + 1, 1, tzinfo=timezone.utc).date() if month < 12 else datetime(year + 1, 1, 1, tzinfo=timezone.utc).date()
  780. target_month_end_date = next_month_start_date - timedelta(days=1)
  781. month_key_display = target_month_start_date.strftime('%Y-%m')
  782. month_formatted_display = target_month_start_date.strftime('%b %Y')
  783. daily_records_for_month = self._fetch_query(
  784. "SELECT date, realized_pnl, completed_cycles, exit_volume FROM daily_aggregated_stats WHERE date BETWEEN ? AND ?",
  785. (target_month_start_date.strftime('%Y-%m-%d'), target_month_end_date.strftime('%Y-%m-%d'))
  786. )
  787. if daily_records_for_month:
  788. total_pnl_month = sum(d.get('realized_pnl', 0.0) or 0.0 for d in daily_records_for_month)
  789. total_trades_month = sum(d.get('completed_cycles', 0) or 0 for d in daily_records_for_month)
  790. total_volume_month = sum(d.get('exit_volume', 0.0) or 0.0 for d in daily_records_for_month)
  791. pnl_pct_month = (total_pnl_month / total_volume_month * 100) if total_volume_month > 0 else 0.0
  792. if total_trades_month > 0:
  793. monthly_stats_list.append({
  794. 'month': month_key_display,
  795. 'month_formatted': month_formatted_display,
  796. 'has_trades': True,
  797. 'pnl': total_pnl_month,
  798. 'trades': total_trades_month,
  799. 'volume': total_volume_month,
  800. 'pnl_pct': pnl_pct_month
  801. })
  802. else:
  803. monthly_stats_list.append({
  804. 'month': month_key_display, 'month_formatted': month_formatted_display, 'has_trades': False,
  805. 'trades': 0, 'pnl': 0.0, 'volume': 0.0, 'pnl_pct': 0.0
  806. })
  807. else:
  808. monthly_stats_list.append({
  809. 'month': month_key_display, 'month_formatted': month_formatted_display, 'has_trades': False,
  810. 'trades': 0, 'pnl': 0.0, 'volume': 0.0, 'pnl_pct': 0.0
  811. })
  812. return monthly_stats_list
  813. def record_deposit(self, amount: float, timestamp: Optional[str] = None,
  814. deposit_id: Optional[str] = None, description: Optional[str] = None):
  815. """Record a deposit."""
  816. ts = timestamp if timestamp else datetime.now(timezone.utc).isoformat()
  817. formatter = get_formatter()
  818. formatted_amount_str = formatter.format_price_with_symbol(amount)
  819. desc = description if description else f'Deposit of {formatted_amount_str}'
  820. self._execute_query(
  821. "INSERT INTO balance_adjustments (adjustment_id, timestamp, type, amount, description) VALUES (?, ?, ?, ?, ?)",
  822. (deposit_id or str(uuid.uuid4()), ts, 'deposit', amount, desc) # Ensured uuid is string
  823. )
  824. # Adjust initial_balance in metadata to reflect capital changes
  825. current_initial = float(self._get_metadata('initial_balance') or '0.0')
  826. self._set_metadata('initial_balance', str(current_initial + amount))
  827. logger.info(f"💰 Recorded deposit: {formatted_amount_str}. New effective initial balance: {formatter.format_price_with_symbol(current_initial + amount)}")
  828. def record_withdrawal(self, amount: float, timestamp: Optional[str] = None,
  829. withdrawal_id: Optional[str] = None, description: Optional[str] = None):
  830. """Record a withdrawal."""
  831. ts = timestamp if timestamp else datetime.now(timezone.utc).isoformat()
  832. formatter = get_formatter()
  833. formatted_amount_str = formatter.format_price_with_symbol(amount)
  834. desc = description if description else f'Withdrawal of {formatted_amount_str}'
  835. self._execute_query(
  836. "INSERT INTO balance_adjustments (adjustment_id, timestamp, type, amount, description) VALUES (?, ?, ?, ?, ?)",
  837. (withdrawal_id or str(uuid.uuid4()), ts, 'withdrawal', amount, desc) # Ensured uuid is string
  838. )
  839. current_initial = float(self._get_metadata('initial_balance') or '0.0')
  840. self._set_metadata('initial_balance', str(current_initial - amount))
  841. logger.info(f"💸 Recorded withdrawal: {formatted_amount_str}. New effective initial balance: {formatter.format_price_with_symbol(current_initial - amount)}")
  842. def get_balance_adjustments_summary(self) -> Dict[str, Any]:
  843. """Get summary of all balance adjustments from DB."""
  844. adjustments = self._fetch_query("SELECT type, amount, timestamp FROM balance_adjustments ORDER BY timestamp ASC")
  845. if not adjustments:
  846. return {'total_deposits': 0.0, 'total_withdrawals': 0.0, 'net_adjustment': 0.0,
  847. 'adjustment_count': 0, 'last_adjustment': None}
  848. total_deposits = sum(adj['amount'] for adj in adjustments if adj['type'] == 'deposit')
  849. total_withdrawals = sum(adj['amount'] for adj in adjustments if adj['type'] == 'withdrawal') # Amounts stored positive
  850. net_adjustment = total_deposits - total_withdrawals
  851. return {
  852. 'total_deposits': total_deposits, 'total_withdrawals': total_withdrawals,
  853. 'net_adjustment': net_adjustment, 'adjustment_count': len(adjustments),
  854. 'last_adjustment': adjustments[-1]['timestamp'] if adjustments else None
  855. }
  856. def close_connection(self):
  857. """Close the SQLite database connection."""
  858. if self.conn:
  859. self.conn.close()
  860. logger.info("TradingStats SQLite connection closed.")
  861. def __del__(self):
  862. """Ensure connection is closed when object is deleted."""
  863. self.close_connection()
  864. # --- Order Table Management ---
  865. def record_order_placed(self, symbol: str, side: str, order_type: str,
  866. amount_requested: float, price: Optional[float] = None,
  867. bot_order_ref_id: Optional[str] = None,
  868. exchange_order_id: Optional[str] = None,
  869. status: str = 'open',
  870. parent_bot_order_ref_id: Optional[str] = None) -> Optional[int]:
  871. """Record a newly placed order in the 'orders' table. Returns the ID of the inserted order or None on failure."""
  872. now_iso = datetime.now(timezone.utc).isoformat()
  873. query = """
  874. INSERT INTO orders (bot_order_ref_id, exchange_order_id, symbol, side, type,
  875. amount_requested, price, status, timestamp_created, timestamp_updated, parent_bot_order_ref_id)
  876. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  877. """
  878. params = (bot_order_ref_id, exchange_order_id, symbol, side.lower(), order_type.lower(),
  879. amount_requested, price, status.lower(), now_iso, now_iso, parent_bot_order_ref_id)
  880. try:
  881. cur = self.conn.cursor()
  882. cur.execute(query, params)
  883. self.conn.commit()
  884. order_db_id = cur.lastrowid
  885. logger.info(f"Recorded order placed: ID {order_db_id}, Symbol {symbol}, Side {side}, Type {order_type}, Amount {amount_requested}, BotRef {bot_order_ref_id}, ExchID {exchange_order_id}")
  886. return order_db_id
  887. except sqlite3.IntegrityError as e:
  888. logger.error(f"Failed to record order due to IntegrityError (likely duplicate bot_order_ref_id '{bot_order_ref_id}' or exchange_order_id '{exchange_order_id}'): {e}")
  889. return None
  890. except Exception as e:
  891. logger.error(f"Failed to record order: {e}")
  892. return None
  893. def update_order_status(self, order_db_id: Optional[int] = None, bot_order_ref_id: Optional[str] = None, exchange_order_id: Optional[str] = None,
  894. new_status: Optional[str] = None, amount_filled_increment: Optional[float] = None, set_exchange_order_id: Optional[str] = None) -> bool:
  895. """Update an existing order's status and/or amount_filled. Identify order by order_db_id, bot_order_ref_id, or exchange_order_id.
  896. Args:
  897. order_db_id: Database ID to identify the order
  898. bot_order_ref_id: Bot's internal reference ID to identify the order
  899. exchange_order_id: Exchange's order ID to identify the order
  900. new_status: New status to set
  901. amount_filled_increment: Amount to add to current filled amount
  902. set_exchange_order_id: If provided, sets/updates the exchange_order_id field in the database
  903. """
  904. if not any([order_db_id, bot_order_ref_id, exchange_order_id]):
  905. logger.error("Must provide one of order_db_id, bot_order_ref_id, or exchange_order_id to update order.")
  906. return False
  907. now_iso = datetime.now(timezone.utc).isoformat()
  908. set_clauses = []
  909. params = []
  910. if new_status:
  911. set_clauses.append("status = ?")
  912. params.append(new_status.lower())
  913. if set_exchange_order_id is not None:
  914. set_clauses.append("exchange_order_id = ?")
  915. params.append(set_exchange_order_id)
  916. current_amount_filled = 0.0
  917. identifier_clause = ""
  918. identifier_param = None
  919. if order_db_id:
  920. identifier_clause = "id = ?"
  921. identifier_param = order_db_id
  922. elif bot_order_ref_id:
  923. identifier_clause = "bot_order_ref_id = ?"
  924. identifier_param = bot_order_ref_id
  925. elif exchange_order_id:
  926. identifier_clause = "exchange_order_id = ?"
  927. identifier_param = exchange_order_id
  928. if amount_filled_increment is not None and amount_filled_increment > 0:
  929. # To correctly increment, we might need to fetch current filled amount first if DB doesn't support direct increment easily or atomically with other updates.
  930. # For simplicity here, assuming we can use SQL's increment if other fields are not changing, or we do it in two steps.
  931. # Let's assume we fetch first then update to be safe and clear.
  932. order_data = self._fetchone_query(f"SELECT amount_filled FROM orders WHERE {identifier_clause}", (identifier_param,))
  933. if order_data:
  934. current_amount_filled = order_data.get('amount_filled', 0.0)
  935. else:
  936. logger.warning(f"Order not found by {identifier_clause}={identifier_param} when trying to increment amount_filled.")
  937. # Potentially still update status if new_status is provided, but amount_filled won't be right.
  938. # For now, let's proceed with update if status is there.
  939. set_clauses.append("amount_filled = ?")
  940. params.append(current_amount_filled + amount_filled_increment)
  941. if not set_clauses:
  942. logger.info("No fields to update for order.")
  943. return True # No update needed, not an error
  944. set_clauses.append("timestamp_updated = ?")
  945. params.append(now_iso)
  946. params.append(identifier_param) # Add identifier param at the end for WHERE clause
  947. query = f"UPDATE orders SET { ', '.join(set_clauses) } WHERE {identifier_clause}"
  948. try:
  949. self._execute_query(query, tuple(params))
  950. log_msg = f"Updated order ({identifier_clause}={identifier_param}): Status to '{new_status or 'N/A'}', Filled increment {amount_filled_increment or 0.0}"
  951. if set_exchange_order_id is not None:
  952. log_msg += f", Exchange ID set to '{set_exchange_order_id}'"
  953. logger.info(log_msg)
  954. return True
  955. except Exception as e:
  956. logger.error(f"Failed to update order ({identifier_clause}={identifier_param}): {e}")
  957. return False
  958. def get_order_by_db_id(self, order_db_id: int) -> Optional[Dict[str, Any]]:
  959. """Fetch an order by its database primary key ID."""
  960. return self._fetchone_query("SELECT * FROM orders WHERE id = ?", (order_db_id,))
  961. def get_order_by_bot_ref_id(self, bot_order_ref_id: str) -> Optional[Dict[str, Any]]:
  962. """Fetch an order by the bot's internal reference ID."""
  963. return self._fetchone_query("SELECT * FROM orders WHERE bot_order_ref_id = ?", (bot_order_ref_id,))
  964. def get_order_by_exchange_id(self, exchange_order_id: str) -> Optional[Dict[str, Any]]:
  965. """Fetch an order by the exchange's order ID."""
  966. return self._fetchone_query("SELECT * FROM orders WHERE exchange_order_id = ?", (exchange_order_id,))
  967. def get_orders_by_status(self, status: str, order_type_filter: Optional[str] = None, parent_bot_order_ref_id: Optional[str] = None) -> List[Dict[str, Any]]:
  968. """Fetch all orders with a specific status, optionally filtering by order_type and parent_bot_order_ref_id."""
  969. query = "SELECT * FROM orders WHERE status = ?"
  970. params = [status.lower()]
  971. if order_type_filter:
  972. query += " AND type = ?"
  973. params.append(order_type_filter.lower())
  974. if parent_bot_order_ref_id:
  975. query += " AND parent_bot_order_ref_id = ?"
  976. params.append(parent_bot_order_ref_id)
  977. query += " ORDER BY timestamp_created ASC"
  978. return self._fetch_query(query, tuple(params))
  979. def cancel_linked_orders(self, parent_bot_order_ref_id: str, new_status: str = 'cancelled_parent_filled') -> int:
  980. """Cancel all orders linked to a parent order (e.g., pending stop losses when parent order fills or gets cancelled).
  981. Returns the number of orders that were cancelled."""
  982. linked_orders = self.get_orders_by_status('pending_trigger', parent_bot_order_ref_id=parent_bot_order_ref_id)
  983. cancelled_count = 0
  984. for order in linked_orders:
  985. order_db_id = order.get('id')
  986. if order_db_id:
  987. success = self.update_order_status(order_db_id=order_db_id, new_status=new_status)
  988. if success:
  989. cancelled_count += 1
  990. logger.info(f"Cancelled linked order ID {order_db_id} (parent: {parent_bot_order_ref_id}) -> status: {new_status}")
  991. return cancelled_count
  992. def cancel_pending_stop_losses_by_symbol(self, symbol: str, new_status: str = 'cancelled_position_closed') -> int:
  993. """Cancel all pending stop loss orders for a specific symbol (when position is closed).
  994. Returns the number of stop loss orders that were cancelled."""
  995. query = "SELECT * FROM orders WHERE symbol = ? AND status = 'pending_trigger' AND type = 'stop_limit_trigger'"
  996. pending_stop_losses = self._fetch_query(query, (symbol,))
  997. cancelled_count = 0
  998. for order in pending_stop_losses:
  999. order_db_id = order.get('id')
  1000. if order_db_id:
  1001. success = self.update_order_status(order_db_id=order_db_id, new_status=new_status)
  1002. if success:
  1003. cancelled_count += 1
  1004. logger.info(f"Cancelled pending SL order ID {order_db_id} for {symbol} -> status: {new_status}")
  1005. return cancelled_count
  1006. def get_order_cleanup_summary(self) -> Dict[str, Any]:
  1007. """Get summary of order cleanup actions for monitoring and debugging."""
  1008. try:
  1009. # Get counts of different cancellation types
  1010. cleanup_stats = {}
  1011. cancellation_types = [
  1012. 'cancelled_parent_cancelled',
  1013. 'cancelled_parent_disappeared',
  1014. 'cancelled_manual_exit',
  1015. 'cancelled_auto_exit',
  1016. 'cancelled_no_position',
  1017. 'cancelled_external_position_close',
  1018. 'cancelled_orphaned_no_position',
  1019. 'cancelled_externally',
  1020. 'immediately_executed_on_activation',
  1021. 'activation_execution_failed',
  1022. 'activation_execution_error'
  1023. ]
  1024. for cancel_type in cancellation_types:
  1025. count_result = self._fetchone_query(
  1026. "SELECT COUNT(*) as count FROM orders WHERE status = ?",
  1027. (cancel_type,)
  1028. )
  1029. cleanup_stats[cancel_type] = count_result['count'] if count_result else 0
  1030. # Get currently pending stop losses
  1031. pending_sls = self.get_orders_by_status('pending_trigger', 'stop_limit_trigger')
  1032. cleanup_stats['currently_pending_stop_losses'] = len(pending_sls)
  1033. # Get total orders in various states
  1034. active_orders = self._fetchone_query(
  1035. "SELECT COUNT(*) as count FROM orders WHERE status IN ('open', 'submitted', 'partially_filled')",
  1036. ()
  1037. )
  1038. cleanup_stats['currently_active_orders'] = active_orders['count'] if active_orders else 0
  1039. return cleanup_stats
  1040. except Exception as e:
  1041. logger.error(f"Error getting order cleanup summary: {e}")
  1042. return {}
  1043. def get_external_activity_summary(self, days: int = 7) -> Dict[str, Any]:
  1044. """Get summary of external activity (trades and cancellations) over the last N days."""
  1045. try:
  1046. from datetime import timedelta
  1047. cutoff_date = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
  1048. # External trades
  1049. external_trades = self._fetch_query(
  1050. "SELECT COUNT(*) as count, side FROM trades WHERE trade_type = 'external' AND timestamp >= ? GROUP BY side",
  1051. (cutoff_date,)
  1052. )
  1053. external_trade_summary = {
  1054. 'external_buy_trades': 0,
  1055. 'external_sell_trades': 0,
  1056. 'total_external_trades': 0
  1057. }
  1058. for trade_group in external_trades:
  1059. side = trade_group['side']
  1060. count = trade_group['count']
  1061. external_trade_summary['total_external_trades'] += count
  1062. if side == 'buy':
  1063. external_trade_summary['external_buy_trades'] = count
  1064. elif side == 'sell':
  1065. external_trade_summary['external_sell_trades'] = count
  1066. # External cancellations
  1067. external_cancellations = self._fetchone_query(
  1068. "SELECT COUNT(*) as count FROM orders WHERE status = 'cancelled_externally' AND timestamp_updated >= ?",
  1069. (cutoff_date,)
  1070. )
  1071. external_trade_summary['external_cancellations'] = external_cancellations['count'] if external_cancellations else 0
  1072. # Cleanup actions
  1073. cleanup_cancellations = self._fetchone_query(
  1074. """SELECT COUNT(*) as count FROM orders
  1075. WHERE status LIKE 'cancelled_%'
  1076. AND status != 'cancelled_externally'
  1077. AND timestamp_updated >= ?""",
  1078. (cutoff_date,)
  1079. )
  1080. external_trade_summary['cleanup_cancellations'] = cleanup_cancellations['count'] if cleanup_cancellations else 0
  1081. external_trade_summary['period_days'] = days
  1082. return external_trade_summary
  1083. except Exception as e:
  1084. logger.error(f"Error getting external activity summary: {e}")
  1085. return {'period_days': days, 'total_external_trades': 0, 'external_cancellations': 0}
  1086. # --- End Order Table Management ---
  1087. # =============================================================================
  1088. # TRADE LIFECYCLE MANAGEMENT - PHASE 4: UNIFIED TRADES TABLE
  1089. # =============================================================================
  1090. def create_trade_lifecycle(self, symbol: str, side: str, entry_order_id: Optional[str] = None,
  1091. entry_bot_order_ref_id: Optional[str] = None, # New parameter
  1092. stop_loss_price: Optional[float] = None,
  1093. take_profit_price: Optional[float] = None,
  1094. trade_type: str = 'manual') -> Optional[str]:
  1095. """Create a new trade lifecycle.
  1096. If stop_loss_price is provided, also creates a conceptual 'pending_sl_activation' order.
  1097. """
  1098. try:
  1099. lifecycle_id = str(uuid.uuid4())
  1100. # Main lifecycle record in 'trades' table
  1101. query = """
  1102. INSERT INTO trades (
  1103. symbol, side, amount, price, value, trade_type, timestamp,
  1104. status, trade_lifecycle_id, position_side, entry_order_id,
  1105. stop_loss_price, take_profit_price, updated_at
  1106. ) VALUES (?, ?, 0, 0, 0, ?, ?, 'pending', ?, 'flat', ?, ?, ?, ?)
  1107. """
  1108. timestamp = datetime.now(timezone.utc).isoformat()
  1109. params = (symbol, side.lower(), trade_type, timestamp, lifecycle_id,
  1110. entry_order_id, stop_loss_price, take_profit_price, timestamp)
  1111. self._execute_query(query, params)
  1112. logger.info(f"📊 Created trade lifecycle {lifecycle_id}: {side.upper()} {symbol} (pending for exch_id: {entry_order_id or 'N/A'})")
  1113. # If SL price is provided, create a conceptual pending SL order in 'orders' table
  1114. if stop_loss_price is not None and entry_bot_order_ref_id is not None:
  1115. sl_order_side = 'sell' if side.lower() == 'buy' else 'buy'
  1116. # Using entry_bot_order_ref_id ensures this conceptual SL is linked to the specific entry attempt
  1117. conceptual_sl_bot_ref_id = f"pending_sl_activation_{entry_bot_order_ref_id}"
  1118. # Record this conceptual order. Amount is 0 for now.
  1119. # The actual amount will be determined when the SL is placed after entry fill.
  1120. sl_order_db_id = self.record_order_placed(
  1121. symbol=symbol,
  1122. side=sl_order_side,
  1123. order_type='pending_sl_activation', # New conceptual type
  1124. amount_requested=0, # Placeholder amount
  1125. price=stop_loss_price,
  1126. bot_order_ref_id=conceptual_sl_bot_ref_id,
  1127. status='pending_activation', # New conceptual status
  1128. parent_bot_order_ref_id=entry_bot_order_ref_id, # Link to the main entry order
  1129. exchange_order_id=None # Not on exchange yet
  1130. )
  1131. if sl_order_db_id:
  1132. logger.info(f"💡 Recorded conceptual 'pending_sl_activation' order (DB ID: {sl_order_db_id}, BotRef: {conceptual_sl_bot_ref_id}) for lifecycle {lifecycle_id} at SL price {stop_loss_price}.")
  1133. else:
  1134. logger.error(f"⚠️ Failed to record conceptual 'pending_sl_activation' order for lifecycle {lifecycle_id} (Entry BotRef: {entry_bot_order_ref_id}).")
  1135. return lifecycle_id
  1136. except Exception as e:
  1137. logger.error(f"❌ Error creating trade lifecycle: {e}")
  1138. return None
  1139. def update_trade_position_opened(self, lifecycle_id: str, entry_price: float,
  1140. entry_amount: float, exchange_fill_id: str) -> bool:
  1141. """Update trade when position is opened (entry order filled)."""
  1142. try:
  1143. query = """
  1144. UPDATE trades
  1145. SET status = 'position_opened',
  1146. amount = ?,
  1147. price = ?,
  1148. value = ?,
  1149. entry_price = ?,
  1150. current_position_size = ?,
  1151. position_side = CASE
  1152. WHEN side = 'buy' THEN 'long'
  1153. WHEN side = 'sell' THEN 'short'
  1154. ELSE position_side
  1155. END,
  1156. exchange_fill_id = ?,
  1157. position_opened_at = ?,
  1158. updated_at = ?
  1159. WHERE trade_lifecycle_id = ? AND status = 'pending'
  1160. """
  1161. timestamp = datetime.now(timezone.utc).isoformat()
  1162. value = entry_amount * entry_price
  1163. params = (entry_amount, entry_price, value, entry_price, entry_amount,
  1164. exchange_fill_id, timestamp, timestamp, lifecycle_id)
  1165. self._execute_query(query, params)
  1166. formatter = get_formatter()
  1167. trade_info = self.get_trade_by_lifecycle_id(lifecycle_id) # Fetch to get symbol for formatting
  1168. symbol_for_formatting = trade_info.get('symbol', 'UNKNOWN_SYMBOL') if trade_info else 'UNKNOWN_SYMBOL'
  1169. base_asset_for_amount = symbol_for_formatting.split('/')[0] if '/' in symbol_for_formatting else symbol_for_formatting
  1170. logger.info(f"📈 Trade lifecycle {lifecycle_id} position opened: {formatter.format_amount(entry_amount, base_asset_for_amount)} {symbol_for_formatting} @ {formatter.format_price(entry_price, symbol_for_formatting)}")
  1171. return True
  1172. except Exception as e:
  1173. logger.error(f"❌ Error updating trade position opened: {e}")
  1174. return False
  1175. def update_trade_position_closed(self, lifecycle_id: str, exit_price: float,
  1176. realized_pnl: float, exchange_fill_id: str) -> bool:
  1177. """Update trade when position is fully closed."""
  1178. try:
  1179. query = """
  1180. UPDATE trades
  1181. SET status = 'position_closed',
  1182. current_position_size = 0,
  1183. position_side = 'flat',
  1184. realized_pnl = ?,
  1185. position_closed_at = ?,
  1186. updated_at = ?
  1187. WHERE trade_lifecycle_id = ? AND status = 'position_opened'
  1188. """
  1189. timestamp = datetime.now(timezone.utc).isoformat()
  1190. params = (realized_pnl, timestamp, timestamp, lifecycle_id)
  1191. self._execute_query(query, params)
  1192. formatter = get_formatter()
  1193. trade_info = self.get_trade_by_lifecycle_id(lifecycle_id) # Fetch to get symbol for P&L formatting context
  1194. symbol_for_formatting = trade_info.get('symbol', 'USD') # Default to USD for PNL if symbol unknown
  1195. pnl_emoji = "🟢" if realized_pnl >= 0 else "🔴"
  1196. logger.info(f"{pnl_emoji} Trade lifecycle {lifecycle_id} position closed: P&L {formatter.format_price_with_symbol(realized_pnl)}")
  1197. return True
  1198. except Exception as e:
  1199. logger.error(f"❌ Error updating trade position closed: {e}")
  1200. return False
  1201. def update_trade_cancelled(self, lifecycle_id: str, reason: str = "order_cancelled") -> bool:
  1202. """Update trade when entry order is cancelled (never opened)."""
  1203. try:
  1204. query = """
  1205. UPDATE trades
  1206. SET status = 'cancelled',
  1207. notes = ?,
  1208. updated_at = ?
  1209. WHERE trade_lifecycle_id = ? AND status = 'pending'
  1210. """
  1211. timestamp = datetime.now(timezone.utc).isoformat()
  1212. params = (f"Cancelled: {reason}", timestamp, lifecycle_id)
  1213. self._execute_query(query, params)
  1214. logger.info(f"❌ Trade lifecycle {lifecycle_id} cancelled: {reason}")
  1215. return True
  1216. except Exception as e:
  1217. logger.error(f"❌ Error updating trade cancelled: {e}")
  1218. return False
  1219. def link_stop_loss_to_trade(self, lifecycle_id: str, stop_loss_order_id: str,
  1220. stop_loss_price: float) -> bool:
  1221. """Link a stop loss order to a trade lifecycle."""
  1222. try:
  1223. query = """
  1224. UPDATE trades
  1225. SET stop_loss_order_id = ?,
  1226. stop_loss_price = ?,
  1227. updated_at = ?
  1228. WHERE trade_lifecycle_id = ? AND status = 'position_opened'
  1229. """
  1230. timestamp = datetime.now(timezone.utc).isoformat()
  1231. params = (stop_loss_order_id, stop_loss_price, timestamp, lifecycle_id)
  1232. self._execute_query(query, params)
  1233. formatter = get_formatter()
  1234. trade_info = self.get_trade_by_lifecycle_id(lifecycle_id) # Fetch to get symbol for formatting
  1235. symbol_for_formatting = trade_info.get('symbol', 'UNKNOWN_SYMBOL') if trade_info else 'UNKNOWN_SYMBOL'
  1236. logger.info(f"🛑 Linked stop loss order {stop_loss_order_id} ({formatter.format_price(stop_loss_price, symbol_for_formatting)}) to trade {lifecycle_id}")
  1237. return True
  1238. except Exception as e:
  1239. logger.error(f"❌ Error linking stop loss to trade: {e}")
  1240. return False
  1241. def link_take_profit_to_trade(self, lifecycle_id: str, take_profit_order_id: str,
  1242. take_profit_price: float) -> bool:
  1243. """Link a take profit order to a trade lifecycle."""
  1244. try:
  1245. query = """
  1246. UPDATE trades
  1247. SET take_profit_order_id = ?,
  1248. take_profit_price = ?,
  1249. updated_at = ?
  1250. WHERE trade_lifecycle_id = ? AND status = 'position_opened'
  1251. """
  1252. timestamp = datetime.now(timezone.utc).isoformat()
  1253. params = (take_profit_order_id, take_profit_price, timestamp, lifecycle_id)
  1254. self._execute_query(query, params)
  1255. formatter = get_formatter()
  1256. trade_info = self.get_trade_by_lifecycle_id(lifecycle_id) # Fetch to get symbol for formatting
  1257. symbol_for_formatting = trade_info.get('symbol', 'UNKNOWN_SYMBOL') if trade_info else 'UNKNOWN_SYMBOL'
  1258. logger.info(f"🎯 Linked take profit order {take_profit_order_id} ({formatter.format_price(take_profit_price, symbol_for_formatting)}) to trade {lifecycle_id}")
  1259. return True
  1260. except Exception as e:
  1261. logger.error(f"❌ Error linking take profit to trade: {e}")
  1262. return False
  1263. def get_trade_by_lifecycle_id(self, lifecycle_id: str) -> Optional[Dict[str, Any]]:
  1264. """Get trade by lifecycle ID."""
  1265. query = "SELECT * FROM trades WHERE trade_lifecycle_id = ?"
  1266. return self._fetchone_query(query, (lifecycle_id,))
  1267. # Re-instating the correct get_trade_by_symbol_and_status from earlier version in case it was overwritten by file read
  1268. def get_trade_by_symbol_and_status(self, symbol: str, status: str = 'position_opened') -> Optional[Dict[str, Any]]: # Copied from earlier state
  1269. """Get trade by symbol and status."""
  1270. query = "SELECT * FROM trades WHERE symbol = ? AND status = ? ORDER BY updated_at DESC LIMIT 1"
  1271. return self._fetchone_query(query, (symbol, status))
  1272. def get_open_positions(self, symbol: Optional[str] = None) -> List[Dict[str, Any]]:
  1273. """Get all open positions, optionally filtered by symbol."""
  1274. if symbol:
  1275. query = "SELECT * FROM trades WHERE status = 'position_opened' AND symbol = ? ORDER BY position_opened_at DESC"
  1276. return self._fetch_query(query, (symbol,))
  1277. else:
  1278. query = "SELECT * FROM trades WHERE status = 'position_opened' ORDER BY position_opened_at DESC"
  1279. return self._fetch_query(query)
  1280. def get_trades_by_status(self, status: str, limit: int = 50) -> List[Dict[str, Any]]:
  1281. """Get trades by status."""
  1282. query = "SELECT * FROM trades WHERE status = ? ORDER BY updated_at DESC LIMIT ?"
  1283. return self._fetch_query(query, (status, limit))
  1284. def _format_duration(self, seconds: float) -> str:
  1285. """Formats a duration in seconds into a human-readable string (e.g., 1h 25m 3s)."""
  1286. hours = int(seconds // 3600)
  1287. minutes = int((seconds % 3600) // 60)
  1288. remaining_seconds = int(seconds % 60)
  1289. return f"{hours}h {minutes}m {remaining_seconds}s"
  1290. # --- End Trade Lifecycle Management ---
  1291. def get_balance_history_record_count(self) -> int:
  1292. """Get the total number of balance history records."""
  1293. row = self._fetchone_query("SELECT COUNT(*) as count FROM balance_history")
  1294. return row['count'] if row and 'count' in row else 0
  1295. # 🆕 PHASE 5: AGGREGATION AND PURGING LOGIC
  1296. def _migrate_trade_to_aggregated_stats(self, trade_lifecycle_id: str):
  1297. """Migrate a completed/cancelled trade's stats to aggregate tables and delete the original trade."""
  1298. # Implement the logic to migrate trade stats to aggregate tables and delete the original trade
  1299. pass
  1300. def purge_old_daily_aggregated_stats(self, months_to_keep: int = 10):
  1301. """Purge records from daily_aggregated_stats older than a specified number of months."""
  1302. try:
  1303. cutoff_date = datetime.now(timezone.utc).date() - timedelta(days=months_to_keep * 30)
  1304. cutoff_datetime_str = cutoff_date.isoformat()
  1305. query = "DELETE FROM daily_aggregated_stats WHERE date < ?"
  1306. with self.conn:
  1307. cursor = self.conn.cursor()
  1308. cursor.execute(query, (cutoff_datetime_str,))
  1309. rows_deleted = cursor.rowcount
  1310. if rows_deleted > 0:
  1311. logger.info(f"Purged {rows_deleted} old records from daily_aggregated_stats (older than {months_to_keep} months).")
  1312. else:
  1313. logger.debug(f"No old records found in daily_aggregated_stats to purge (older than {months_to_keep} months).")
  1314. except sqlite3.Error as e:
  1315. logger.error(f"Database error purging old daily_aggregated_stats: {e}", exc_info=True)
  1316. except Exception as e:
  1317. logger.error(f"Unexpected error purging old daily_aggregated_stats: {e}", exc_info=True)
  1318. def purge_old_balance_history(self):
  1319. """Purge records from balance_history older than the configured retention period."""
  1320. days_to_keep = Config.BALANCE_HISTORY_RETENTION_DAYS
  1321. if days_to_keep <= 0:
  1322. logger.info("Not purging balance_history as retention days is not positive.")
  1323. return
  1324. try:
  1325. cutoff_date = datetime.now(timezone.utc).date() - timedelta(days=days_to_keep)
  1326. cutoff_datetime_str = cutoff_date.isoformat()
  1327. query = "DELETE FROM balance_history WHERE timestamp < ?"
  1328. with self.conn:
  1329. cursor = self.conn.cursor()
  1330. cursor.execute(query, (cutoff_datetime_str,))
  1331. rows_deleted = cursor.rowcount
  1332. if rows_deleted > 0:
  1333. logger.info(f"Purged {rows_deleted} old records from balance_history (older than {days_to_keep} days).")
  1334. else:
  1335. logger.debug(f"No old records found in balance_history to purge (older than {days_to_keep} days).")
  1336. except sqlite3.Error as e:
  1337. logger.error(f"Database error purging old balance_history: {e}", exc_info=True)
  1338. except Exception as e:
  1339. logger.error(f"Unexpected error purging old balance_history: {e}", exc_info=True)
  1340. def get_daily_balance_record_count(self) -> int:
  1341. """Get the total number of daily balance records."""
  1342. row = self._fetchone_query("SELECT COUNT(*) as count FROM daily_balances")
  1343. return row['count'] if row and 'count' in row else 0