Fix CTP exchange routing for non-SHFE contracts and duplicate trade closes.
Resolve CZCE/DCE symbols to the correct exchange for orders, dedupe stop-loss closes and trade logs, and rely on CTP sync for authoritative records. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+71
-15
@@ -39,6 +39,7 @@ PLACE_COOLDOWN_SEC = 3
|
||||
|
||||
_last_close_attempt: dict[int, float] = {}
|
||||
_closing_monitors: set[int] = set()
|
||||
_closing_symbol_keys: set[str] = set()
|
||||
_closing_lock = threading.Lock()
|
||||
|
||||
MONITOR_ORDER_COLUMNS = (
|
||||
@@ -137,6 +138,69 @@ def _find_position(positions: list[dict], ths_code: str, direction: str) -> Opti
|
||||
return None
|
||||
|
||||
|
||||
def _position_key(sym: str, direction: str) -> str:
|
||||
return f"{(sym or '').strip().lower()}|{(direction or 'long').strip().lower()}"
|
||||
|
||||
|
||||
def _try_acquire_close_symbol(sym: str, direction: str) -> bool:
|
||||
key = _position_key(sym, direction)
|
||||
with _closing_lock:
|
||||
if key in _closing_symbol_keys:
|
||||
return False
|
||||
_closing_symbol_keys.add(key)
|
||||
return True
|
||||
|
||||
|
||||
def _release_close_symbol(sym: str, direction: str) -> None:
|
||||
key = _position_key(sym, direction)
|
||||
with _closing_lock:
|
||||
_closing_symbol_keys.discard(key)
|
||||
|
||||
|
||||
def _close_all_monitors_for_symbol(conn, sym: str, direction: str) -> None:
|
||||
direction = (direction or "long").strip().lower()
|
||||
for r in conn.execute(
|
||||
"SELECT id, symbol, direction FROM trade_order_monitors WHERE status='active'"
|
||||
).fetchall():
|
||||
if (r["direction"] or "long") != direction:
|
||||
continue
|
||||
if _match_symbol(sym, r["symbol"] or ""):
|
||||
conn.execute(
|
||||
"UPDATE trade_order_monitors SET status='closed' WHERE id=?",
|
||||
(r["id"],),
|
||||
)
|
||||
|
||||
|
||||
def _dedupe_active_monitors(conn) -> None:
|
||||
"""同一品种方向只保留一条 active 监控,避免重复触发平仓。"""
|
||||
groups: dict[str, list[dict]] = {}
|
||||
for r in conn.execute(
|
||||
"SELECT * FROM trade_order_monitors WHERE status='active' ORDER BY id ASC"
|
||||
).fetchall():
|
||||
row = dict(r)
|
||||
key = _position_key(row.get("symbol") or "", row.get("direction") or "long")
|
||||
groups.setdefault(key, []).append(row)
|
||||
for items in groups.values():
|
||||
if len(items) <= 1:
|
||||
continue
|
||||
|
||||
def _keep_score(m: dict) -> tuple:
|
||||
mt = (m.get("monitor_type") or "").lower()
|
||||
score = 0
|
||||
if mt != "ctp_sync":
|
||||
score += 10
|
||||
if m.get("stop_loss") is not None:
|
||||
score += 5
|
||||
return (score, int(m.get("id") or 0))
|
||||
|
||||
items.sort(key=_keep_score, reverse=True)
|
||||
for dup in items[1:]:
|
||||
conn.execute(
|
||||
"UPDATE trade_order_monitors SET status='closed' WHERE id=?",
|
||||
(dup["id"],),
|
||||
)
|
||||
|
||||
|
||||
def _can_close_now(monitor_id: int, *, cooldown: int = PLACE_COOLDOWN_SEC) -> bool:
|
||||
last = _last_close_attempt.get(monitor_id, 0.0)
|
||||
return (time.time() - last) >= cooldown
|
||||
@@ -575,6 +639,7 @@ def _execute_local_close(
|
||||
positions = ctp_list_positions(mode)
|
||||
pos = _find_position(positions, sym, direction)
|
||||
if not pos:
|
||||
_close_all_monitors_for_symbol(conn, sym, direction)
|
||||
reconcile_monitors_without_position(conn, mode)
|
||||
return
|
||||
lots = int(pos.get("lots") or mon.get("lots") or 1)
|
||||
@@ -590,24 +655,16 @@ def _execute_local_close(
|
||||
price=mark,
|
||||
order_type="market",
|
||||
)
|
||||
_write_trade_log(
|
||||
conn,
|
||||
mon,
|
||||
close_price=mark,
|
||||
reason=reason,
|
||||
trading_mode=mode,
|
||||
capital=capital,
|
||||
)
|
||||
conn.execute("UPDATE trade_order_monitors SET status='closed' WHERE id=?", (mon["id"],))
|
||||
_close_all_monitors_for_symbol(conn, sym, direction)
|
||||
conn.commit()
|
||||
result_label = _result_for_close(mon, reason)
|
||||
logger.info(
|
||||
"止盈止损本地触发 monitor=%s result=%s %s %s %d手 @%s",
|
||||
"止盈止损本地触发 monitor=%s result=%s %s %s %d手 @%s(待 CTP 成交同步写入交易记录)",
|
||||
mon.get("id"), result_label, sym, direction, lots, mark,
|
||||
)
|
||||
if notify_fn:
|
||||
try:
|
||||
notify_fn(f"{result_label} {sym} {direction} {lots}手 @{mark},已记入交易记录")
|
||||
notify_fn(f"{result_label} {sym} {direction} {lots}手 @{mark},平仓委托已提交")
|
||||
except Exception as exc:
|
||||
logger.debug("SL/TP notify failed: %s", exc)
|
||||
|
||||
@@ -627,12 +684,12 @@ def check_monitors_locally(
|
||||
if not is_trading_session():
|
||||
return 0
|
||||
reconcile_monitors_without_position(conn, mode)
|
||||
_dedupe_active_monitors(conn)
|
||||
conn.commit()
|
||||
closed = 0
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT * FROM trade_order_monitors WHERE status='active'"
|
||||
).fetchall()]
|
||||
conn.commit()
|
||||
for mon in rows:
|
||||
mid = int(mon.get("id") or 0)
|
||||
sym = (mon.get("symbol") or "").strip()
|
||||
@@ -677,7 +734,7 @@ def check_monitors_locally(
|
||||
continue
|
||||
if mid > 0 and not _can_close_now(mid):
|
||||
continue
|
||||
if mid > 0 and not _try_acquire_close(mid):
|
||||
if not _try_acquire_close_symbol(sym, direction):
|
||||
continue
|
||||
try:
|
||||
_execute_local_close(
|
||||
@@ -695,8 +752,7 @@ def check_monitors_locally(
|
||||
except Exception as exc:
|
||||
logger.warning("SL/TP local close failed monitor=%s: %s", mid, exc)
|
||||
finally:
|
||||
if mid > 0:
|
||||
_release_close(mid)
|
||||
_release_close_symbol(sym, direction)
|
||||
return closed
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user