refactor: Improve open trades query with net shares calculation and position tracking
This commit is contained in:
parent
4196a61b99
commit
e5b35e50e5
@ -509,11 +509,24 @@ def get_open_trades():
|
|||||||
print("\n=== Fetching Open Trades ===") # Debug
|
print("\n=== Fetching Open Trades ===") # Debug
|
||||||
with create_client() as client:
|
with create_client() as client:
|
||||||
query = """
|
query = """
|
||||||
SELECT *
|
WITH position_totals AS (
|
||||||
FROM stock_db.trades
|
SELECT
|
||||||
WHERE (exit_price IS NULL OR exit_price = '')
|
ticker,
|
||||||
AND (exit_date IS NULL)
|
position_id,
|
||||||
ORDER BY entry_date DESC
|
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
|
print(f"Executing query: {query}") # Debug
|
||||||
try:
|
try:
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user