fix: Correct trade summary calculations for buy and sell directions
This commit is contained in:
parent
e60f18e41a
commit
bc064fc011
@ -300,8 +300,15 @@ def get_position_summary(ticker: str) -> dict:
|
|||||||
query = f"""
|
query = f"""
|
||||||
SELECT
|
SELECT
|
||||||
position_id,
|
position_id,
|
||||||
sum(shares) as total_shares,
|
sum(CASE WHEN direction = 'buy' THEN shares
|
||||||
sum(shares * entry_price) / sum(shares) as avg_entry_price,
|
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,
|
min(entry_date) as first_entry,
|
||||||
max(entry_date) as last_entry,
|
max(entry_date) as last_entry,
|
||||||
count() as num_orders,
|
count() as num_orders,
|
||||||
@ -312,6 +319,7 @@ def get_position_summary(ticker: str) -> dict:
|
|||||||
WHERE ticker = '{ticker}'
|
WHERE ticker = '{ticker}'
|
||||||
AND exit_price IS NULL
|
AND exit_price IS NULL
|
||||||
GROUP BY position_id
|
GROUP BY position_id
|
||||||
|
HAVING total_shares > 0
|
||||||
ORDER BY first_entry DESC
|
ORDER BY first_entry DESC
|
||||||
"""
|
"""
|
||||||
result = client.query(query).result_rows
|
result = client.query(query).result_rows
|
||||||
@ -447,8 +455,15 @@ def get_open_trades_summary() -> dict:
|
|||||||
query = """
|
query = """
|
||||||
SELECT
|
SELECT
|
||||||
ticker,
|
ticker,
|
||||||
sum(shares) as total_shares,
|
sum(CASE WHEN direction = 'buy' THEN shares
|
||||||
sum(shares * entry_price) / sum(shares) as avg_entry_price,
|
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,
|
min(entry_date) as first_entry,
|
||||||
max(entry_date) as last_entry,
|
max(entry_date) as last_entry,
|
||||||
count() as num_orders,
|
count() as num_orders,
|
||||||
@ -456,6 +471,7 @@ def get_open_trades_summary() -> dict:
|
|||||||
FROM stock_db.trades
|
FROM stock_db.trades
|
||||||
WHERE exit_price IS NULL
|
WHERE exit_price IS NULL
|
||||||
GROUP BY ticker
|
GROUP BY ticker
|
||||||
|
HAVING total_shares > 0
|
||||||
ORDER BY ticker ASC
|
ORDER BY ticker ASC
|
||||||
"""
|
"""
|
||||||
result = client.query(query).result_rows
|
result = client.query(query).result_rows
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user