refactor: Improve open trades query with net shares calculation and position tracking

This commit is contained in:
Bobby (aider) 2025-02-13 11:20:47 -08:00
parent 4196a61b99
commit e5b35e50e5

View File

@ -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: