Fix options add-on premium to sum all open legs for the contract.
Display, close gate, alerts, and full-close accounting no longer use only the latest fill row. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -31,15 +31,10 @@ def _open_premium_paid(cfg: dict[str, Any], inst_id: str) -> float | None:
|
||||
try:
|
||||
conn = cfg["get_db"]()
|
||||
try:
|
||||
from lib.options.options_db import init_options_tables
|
||||
from lib.options.options_db import init_options_tables, sum_open_premium_paid
|
||||
|
||||
init_options_tables(conn)
|
||||
row = conn.execute(
|
||||
"SELECT premium_paid FROM options_trades WHERE inst_id = ? AND status = 'open' ORDER BY id DESC LIMIT 1",
|
||||
(inst_id,),
|
||||
).fetchone()
|
||||
if row and row["premium_paid"] is not None:
|
||||
return float(row["premium_paid"])
|
||||
return sum_open_premium_paid(conn, inst_id)
|
||||
finally:
|
||||
conn.close()
|
||||
except Exception:
|
||||
@@ -299,16 +294,30 @@ def close_option_by_bid1(
|
||||
from lib.options.options_db import init_options_tables
|
||||
|
||||
init_options_tables(conn)
|
||||
row = conn.execute(
|
||||
"SELECT id, premium_paid FROM options_trades WHERE inst_id = ? AND status = 'open' ORDER BY id DESC LIMIT 1",
|
||||
open_rows = conn.execute(
|
||||
"""
|
||||
SELECT id, premium_paid FROM options_trades
|
||||
WHERE inst_id = ? AND status = 'open'
|
||||
ORDER BY id ASC
|
||||
""",
|
||||
(inst_id,),
|
||||
).fetchone()
|
||||
if row:
|
||||
).fetchall()
|
||||
total_paid = sum(float(r["premium_paid"] or 0) for r in open_rows)
|
||||
allocated = 0.0
|
||||
for i, row in enumerate(open_rows):
|
||||
paid = float(row["premium_paid"] or 0)
|
||||
pnl = prem_recv - paid
|
||||
if i == len(open_rows) - 1:
|
||||
recv = round(prem_recv - allocated, 4)
|
||||
elif total_paid > 0:
|
||||
recv = round(prem_recv * (paid / total_paid), 4)
|
||||
allocated += recv
|
||||
else:
|
||||
recv = round(prem_recv / len(open_rows), 4)
|
||||
allocated += recv
|
||||
pnl = round(recv - paid, 4)
|
||||
note_sql = ""
|
||||
params: list[Any] = [px, prem_recv, pnl, oid or None]
|
||||
if signal_note:
|
||||
params: list[Any] = [px, recv, pnl, oid or None]
|
||||
if signal_note and i == len(open_rows) - 1:
|
||||
note_sql = """,
|
||||
signal_note = CASE
|
||||
WHEN signal_note IS NULL OR TRIM(signal_note) = '' THEN ?
|
||||
@@ -326,7 +335,7 @@ def close_option_by_bid1(
|
||||
""",
|
||||
tuple(params),
|
||||
)
|
||||
conn.commit()
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
elif require_recycle_gate:
|
||||
|
||||
Reference in New Issue
Block a user