From 85c8f97cc5f8fb2572a4b803fc99f728a427fdaf Mon Sep 17 00:00:00 2001 From: "Bobby (aider)" Date: Thu, 13 Feb 2025 11:21:04 -0800 Subject: [PATCH] refactor: Optimize open trades summary query with position totals subquery --- src/trading/journal.py | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/src/trading/journal.py b/src/trading/journal.py index 68666d0..1030716 100644 --- a/src/trading/journal.py +++ b/src/trading/journal.py @@ -473,23 +473,36 @@ def get_open_trades_summary() -> dict: print("\n=== Fetching Open Trades Summary ===") # Debug with create_client() as client: query = """ + WITH position_totals AS ( + SELECT + ticker, + position_id, + sum(CASE + WHEN direction = 'sell' THEN -shares + ELSE shares + END) as net_shares + FROM stock_db.trades + GROUP BY ticker, position_id + HAVING net_shares > 0 + ) SELECT - ticker, + t.ticker, sum(CASE - WHEN direction = 'sell' THEN -shares - ELSE shares + WHEN t.direction = 'sell' THEN -t.shares + ELSE t.shares END) as total_shares, - avg(entry_price) as avg_entry_price, - min(entry_date) as first_entry, - max(entry_date) as last_entry, + avg(t.entry_price) as avg_entry_price, + min(t.entry_date) as first_entry, + max(t.entry_date) as last_entry, count() as num_orders, - groupArray(position_id) as position_ids - FROM stock_db.trades - WHERE (exit_price IS NULL OR exit_price = '') - AND (exit_date IS NULL) - GROUP BY ticker + groupArray(t.position_id) as position_ids + FROM stock_db.trades t + INNER JOIN position_totals pt + ON t.ticker = pt.ticker + AND t.position_id = pt.position_id + GROUP BY t.ticker HAVING total_shares > 0 - ORDER BY ticker ASC + ORDER BY t.ticker ASC """ print(f"Executing summary query: {query}") # Debug try: