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
|
print("\n=== Fetching Open Trades Summary ===") # Debug
|
||||||
with create_client() as client:
|
with create_client() as client:
|
||||||
query = """
|
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
|
SELECT
|
||||||
ticker,
|
t.ticker,
|
||||||
sum(CASE
|
sum(CASE
|
||||||
WHEN direction = 'sell' THEN -shares
|
WHEN t.direction = 'sell' THEN -t.shares
|
||||||
ELSE shares
|
ELSE t.shares
|
||||||
END) as total_shares,
|
END) as total_shares,
|
||||||
avg(entry_price) as avg_entry_price,
|
avg(t.entry_price) as avg_entry_price,
|
||||||
min(entry_date) as first_entry,
|
min(t.entry_date) as first_entry,
|
||||||
max(entry_date) as last_entry,
|
max(t.entry_date) as last_entry,
|
||||||
count() as num_orders,
|
count() as num_orders,
|
||||||
groupArray(position_id) as position_ids
|
groupArray(t.position_id) as position_ids
|
||||||
FROM stock_db.trades
|
FROM stock_db.trades t
|
||||||
WHERE (exit_price IS NULL OR exit_price = '')
|
INNER JOIN position_totals pt
|
||||||
AND (exit_date IS NULL)
|
ON t.ticker = pt.ticker
|
||||||
GROUP BY ticker
|
AND t.position_id = pt.position_id
|
||||||
|
GROUP BY t.ticker
|
||||||
HAVING total_shares > 0
|
HAVING total_shares > 0
|
||||||
ORDER BY ticker ASC
|
ORDER BY t.ticker ASC
|
||||||
"""
|
"""
|
||||||
print(f"Executing summary query: {query}") # Debug
|
print(f"Executing summary query: {query}") # Debug
|
||||||
try:
|
try:
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user