From e5b35e50e57b6a435dff1628251fb061a1d7e88c Mon Sep 17 00:00:00 2001 From: "Bobby (aider)" Date: Thu, 13 Feb 2025 11:20:47 -0800 Subject: [PATCH] refactor: Improve open trades query with net shares calculation and position tracking --- src/trading/journal.py | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/trading/journal.py b/src/trading/journal.py index 591c165..68666d0 100644 --- a/src/trading/journal.py +++ b/src/trading/journal.py @@ -509,11 +509,24 @@ def get_open_trades(): print("\n=== Fetching Open Trades ===") # Debug with create_client() as client: query = """ - SELECT * - FROM stock_db.trades - WHERE (exit_price IS NULL OR exit_price = '') - AND (exit_date IS NULL) - ORDER BY entry_date DESC + 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 t.* + FROM stock_db.trades t + INNER JOIN position_totals pt + ON t.ticker = pt.ticker + AND t.position_id = pt.position_id + ORDER BY t.entry_date DESC """ print(f"Executing query: {query}") # Debug try: