fix: tighten max-hold session countdown

This commit is contained in:
2026-08-04 08:07:10 +02:00
parent 4c0c0579f5
commit e0f3d43efb
3 changed files with 76 additions and 20 deletions
+24 -15
View File
@@ -441,22 +441,31 @@ async def list_trades(
holding_sessions: dict[int, tuple[int, int]] = {}
if policy["mode"] in ("time", "atr_trailing"):
hold_days = int(policy["hold_days"])
for t, _ in rows:
if t.status != "open":
continue
held = int(
(
await db.execute(
select(func.count())
.select_from(OHLCVRecord)
.where(
OHLCVRecord.ticker_id == t.ticker_id,
OHLCVRecord.date > t.opened_at.date(),
)
open_trades = [trade for trade, _ in rows if trade.status == "open"]
if open_trades:
ticker_ids = {trade.ticker_id for trade in open_trades}
earliest_opened = min(trade.opened_at.date() for trade in open_trades)
session_rows = (
await db.execute(
select(OHLCVRecord.ticker_id, OHLCVRecord.date)
.where(
OHLCVRecord.ticker_id.in_(ticker_ids),
OHLCVRecord.date > earliest_opened,
)
).scalar_one()
)
holding_sessions[t.id] = (held, max(0, hold_days - held))
.order_by(OHLCVRecord.ticker_id, OHLCVRecord.date)
)
).all()
dates_by_ticker: dict[int, list[date]] = {}
for ticker_id, session_date in session_rows:
dates_by_ticker.setdefault(int(ticker_id), []).append(session_date)
for trade in open_trades:
dates = dates_by_ticker.get(trade.ticker_id, [])
held = len(dates) - bisect.bisect_right(
dates, trade.opened_at.date()
)
# Do not clamp: a policy shortened below the current holding
# period must remain visible as overdue until the exit pass runs.
holding_sessions[trade.id] = (held, hold_days - held)
trailing_info: dict[int, tuple[float, float | None]] = {}
if policy["mode"] == "trailing":