Fix ghost open positions: dedupe tickets and reconcile against MT5.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-10-21 18:03:48 +08:00
parent e2847c90df
commit 391851a2b0
4 changed files with 71 additions and 33 deletions
+27 -14
View File
@@ -305,20 +305,33 @@ def list_trades(
open_only: bool = False,
) -> list[dict]:
clause, params = _trades_where(account_id, machine_id, open_only=open_only)
order = (
"ORDER BY COALESCE(t.open_time, t.created_at) DESC"
if open_only
else "ORDER BY COALESCE(t.close_time, t.open_time, t.created_at) DESC"
)
sql = f"""
SELECT t.*, a.name AS account_name, m.name AS machine_name
FROM trades t
LEFT JOIN accounts a ON a.id = t.account_id
LEFT JOIN machines m ON m.id = t.machine_id
{clause}
{order}
LIMIT ? OFFSET ?
"""
if open_only:
# 持仓列表:同一账户+单号只显示最新一条
sql = f"""
SELECT t.*, a.name AS account_name, m.name AS machine_name
FROM trades t
LEFT JOIN accounts a ON a.id = t.account_id
LEFT JOIN machines m ON m.id = t.machine_id
{clause}
AND t.id = (
SELECT MAX(t2.id) FROM trades t2
WHERE t2.account_id = t.account_id
AND t2.ticket = t.ticket
AND (t2.close_time IS NULL OR t2.close_time='')
)
ORDER BY COALESCE(t.open_time, t.created_at) DESC
LIMIT ? OFFSET ?
"""
else:
sql = f"""
SELECT t.*, a.name AS account_name, m.name AS machine_name
FROM trades t
LEFT JOIN accounts a ON a.id = t.account_id
LEFT JOIN machines m ON m.id = t.machine_id
{clause}
ORDER BY COALESCE(t.close_time, t.open_time, t.created_at) DESC
LIMIT ? OFFSET ?
"""
params.extend([limit, max(0, int(offset))])
cur = conn.execute(sql, tuple(params))
rows = []