refactor: Optimize open trades summary query with position totals subquery
This commit is contained in:
parent
e5b35e50e5
commit
85c8f97cc5
@ -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:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user