diff --git a/src/trading/journal.py b/src/trading/journal.py index 04a52aa..1f74d71 100644 --- a/src/trading/journal.py +++ b/src/trading/journal.py @@ -300,8 +300,15 @@ def get_position_summary(ticker: str) -> dict: query = f""" SELECT position_id, - sum(shares) as total_shares, - sum(shares * entry_price) / sum(shares) as avg_entry_price, + sum(CASE WHEN direction = 'buy' THEN shares + WHEN direction = 'sell' THEN -shares + ELSE 0 END) as total_shares, + sum(CASE WHEN direction = 'buy' THEN shares * entry_price + WHEN direction = 'sell' THEN -shares * entry_price + ELSE 0 END) / + abs(sum(CASE WHEN direction = 'buy' THEN shares + WHEN direction = 'sell' THEN -shares + ELSE 0 END)) as avg_entry_price, min(entry_date) as first_entry, max(entry_date) as last_entry, count() as num_orders, @@ -312,6 +319,7 @@ def get_position_summary(ticker: str) -> dict: WHERE ticker = '{ticker}' AND exit_price IS NULL GROUP BY position_id + HAVING total_shares > 0 ORDER BY first_entry DESC """ result = client.query(query).result_rows @@ -447,8 +455,15 @@ def get_open_trades_summary() -> dict: query = """ SELECT ticker, - sum(shares) as total_shares, - sum(shares * entry_price) / sum(shares) as avg_entry_price, + sum(CASE WHEN direction = 'buy' THEN shares + WHEN direction = 'sell' THEN -shares + ELSE 0 END) as total_shares, + sum(CASE WHEN direction = 'buy' THEN shares * entry_price + WHEN direction = 'sell' THEN -shares * entry_price + ELSE 0 END) / + abs(sum(CASE WHEN direction = 'buy' THEN shares + WHEN direction = 'sell' THEN -shares + ELSE 0 END)) as avg_entry_price, min(entry_date) as first_entry, max(entry_date) as last_entry, count() as num_orders, @@ -456,6 +471,7 @@ def get_open_trades_summary() -> dict: FROM stock_db.trades WHERE exit_price IS NULL GROUP BY ticker + HAVING total_shares > 0 ORDER BY ticker ASC """ result = client.query(query).result_rows