Preflight options position limit for dual-leg OO hedges.
Reject OO start when max active is under 2 free slots so limit=1 cannot open a half straddle. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Optional, Sequence
|
||||
|
||||
|
||||
def options_max_active_positions() -> int:
|
||||
@@ -41,17 +41,36 @@ def _inst_already_open(rows: list[dict[str, Any]], inst_id: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_inst_ids(
|
||||
opening_inst_id: str = "",
|
||||
opening_inst_ids: Optional[Sequence[str]] = None,
|
||||
) -> list[str]:
|
||||
out: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in list(opening_inst_ids or []) + ([opening_inst_id] if opening_inst_id else []):
|
||||
iid = str(raw or "").strip()
|
||||
if not iid or iid in seen:
|
||||
continue
|
||||
seen.add(iid)
|
||||
out.append(iid)
|
||||
return out
|
||||
|
||||
|
||||
def option_position_limit_block_msg(
|
||||
ex: Any,
|
||||
*,
|
||||
opening_inst_id: str = "",
|
||||
opening_inst_ids: Optional[Sequence[str]] = None,
|
||||
new_positions: Optional[int] = None,
|
||||
max_active: Optional[int] = None,
|
||||
fetch_positions=None,
|
||||
) -> Optional[str]:
|
||||
"""若禁止新开买期权则返回中文原因,否则 None.
|
||||
|
||||
- max_active<=0:不限制
|
||||
- 加仓已有合约(opening_inst_id 已在持仓中):不占新笔数,放行
|
||||
- opening_inst_ids:本次要开的合约;已在持仓中的不占新笔数
|
||||
- new_positions:显式指定还需新占几笔(默认按 opening_inst_ids 推算)
|
||||
- 期期两腿应一次传入两个 inst_id,在开仓前预检,避免上限=1 时开出半边仓
|
||||
- 拉持仓失败:拒绝开仓(避免绕过上限)
|
||||
"""
|
||||
mx = options_max_active_positions() if max_active is None else int(max_active)
|
||||
@@ -69,8 +88,26 @@ def option_position_limit_block_msg(
|
||||
if rows is None:
|
||||
return f"无法获取期权持仓,暂不可开仓(上限 {mx} 笔)"
|
||||
active = count_live_option_positions(rows)
|
||||
if _inst_already_open(rows, opening_inst_id):
|
||||
ids = _normalize_inst_ids(opening_inst_id, opening_inst_ids)
|
||||
|
||||
if new_positions is None:
|
||||
if ids:
|
||||
already = sum(1 for i in ids if _inst_already_open(rows, i))
|
||||
need = max(0, len(ids) - already)
|
||||
else:
|
||||
need = 1
|
||||
else:
|
||||
need = max(0, int(new_positions))
|
||||
if need <= 1 and len(ids) == 1 and _inst_already_open(rows, ids[0]):
|
||||
return None
|
||||
|
||||
if need <= 0:
|
||||
return None
|
||||
if active >= mx:
|
||||
return f"期权持仓已达上限({active}/{mx}),请先平仓后再开"
|
||||
return None
|
||||
if active + need <= mx:
|
||||
return None
|
||||
if need >= 2:
|
||||
return (
|
||||
f"期期对冲需新开 {need} 笔期权,当前已有 {active} 笔、上限 {mx};"
|
||||
f"请将 OKX_OPTIONS_MAX_ACTIVE_POSITIONS 设为 0(不限制)或不小于 {active + need},或先平仓"
|
||||
)
|
||||
return f"期权持仓已达上限({active}/{mx}),请先平仓后再开"
|
||||
|
||||
Reference in New Issue
Block a user