From fb23ee891ce1b90b6579c9a40f341100b86d6e12 Mon Sep 17 00:00:00 2001 From: dekun Date: Tue, 30 Jun 2026 09:59:02 +0800 Subject: [PATCH] Resolve position average entry from CTP trades and PnL instead of stale monitor cache. Co-authored-by: Cursor --- install_trading.py | 107 ++++++++++++++++++++++++++++++++++++++--- static/js/dashboard.js | 3 -- static/js/trade.js | 2 - 3 files changed, 100 insertions(+), 12 deletions(-) diff --git a/install_trading.py b/install_trading.py index 5de4c0b..7e8cc89 100644 --- a/install_trading.py +++ b/install_trading.py @@ -542,6 +542,85 @@ def install_trading(app, *, login_required, require_nav, get_db, get_setting, se pass return False + def _ctp_avg_entry_from_trades( + mode: str, sym: str, direction: str, *, expect_lots: int = 0, + ) -> Optional[float]: + """按成交回报加权计算持仓均价(与柜台一致)。""" + if not ctp_status(mode).get("connected"): + return None + try: + trades = sorted( + ctp_list_trades(mode), + key=lambda t: (t.get("datetime") or "", t.get("trade_id") or ""), + ) + except Exception: + return None + direction = (direction or "long").strip().lower() + vol = 0 + cost = 0.0 + for t in trades: + if not _match_ctp_symbol(t.get("symbol") or "", sym): + continue + off = (t.get("offset") or "").strip().lower() + pos_dir = ( + t.get("position_direction") or t.get("direction") or "long" + ).strip().lower() + if pos_dir != direction: + continue + lots = int(t.get("lots") or 0) + px = float(t.get("price") or 0) + if lots <= 0 or px <= 0: + continue + if off == "open": + cost += px * lots + vol += lots + elif off == "close" and vol > 0: + avg = cost / vol + dec = min(lots, vol) + cost -= avg * dec + vol -= dec + if vol <= 0: + return None + if expect_lots > 0 and vol != expect_lots: + return None + return round(cost / vol, 4) + + def _resolve_ctp_entry_price( + mode: str, + sym: str, + direction: str, + ctp: Optional[dict], + *, + mark: Optional[float] = None, + ) -> tuple[float, str]: + """持仓均价:成交加权 > 柜台浮盈反推 > vnpy 缓存。""" + if not ctp: + return 0.0, "none" + direction = (direction or "long").strip().lower() + lots = int(ctp.get("lots") or 0) + pos_avg = float(ctp.get("avg_price") or 0) + + trade_avg = _ctp_avg_entry_from_trades( + mode, sym, direction, expect_lots=lots, + ) + if trade_avg and trade_avg > 0: + return float(trade_avg), "trades" + + pnl = float(ctp.get("pnl") or 0) + if mark and mark > 0 and lots > 0 and pnl != 0: + mult = float(get_contract_spec(sym).get("mult") or 10) + if mult > 0: + if direction == "long": + derived = mark - pnl / (mult * lots) + else: + derived = mark + pnl / (mult * lots) + if derived > 0: + return round(derived, 2), "pnl" + + if pos_avg > 0: + return pos_avg, "ctp" + return 0.0, "none" + def _open_commission_from_ctp_trades( mode: str, sym: str, direction: str, ) -> Optional[float]: @@ -1082,6 +1161,11 @@ def install_trading(app, *, login_required, require_nav, get_db, get_setting, se mark = ctp_get_tick_price(mode, sym) if mark is None or mark <= 0: mark = entry if entry else None + resolved_entry, _src = _resolve_ctp_entry_price( + mode, sym, direction, p, mark=mark, + ) + if resolved_entry > 0: + entry = resolved_entry float_pnl = None if mark and entry and lots > 0: float_pnl = calc_position_metrics( @@ -1183,9 +1267,17 @@ def install_trading(app, *, login_required, require_nav, get_db, get_setting, se ctp_lots = int(ctp.get("lots") or 0) if ctp_lots > 0: lots = ctp_lots - ctp_avg = float(ctp.get("avg_price") or 0) - if ctp_avg > 0: - entry = ctp_avg + ths_sym = _ctp_pos_to_ths_code(ctp) or sym + mark_for_entry = mark + if (mark_for_entry is None or float(mark_for_entry or 0) <= 0) and ctp_status(mode).get("connected"): + mark_for_entry = ctp_get_tick_price(mode, ths_sym) + resolved_entry, _entry_src = _resolve_ctp_entry_price( + mode, ths_sym, direction, ctp, mark=mark_for_entry, + ) + if resolved_entry > 0: + entry = resolved_entry + elif float(ctp.get("avg_price") or 0) > 0: + entry = float(ctp.get("avg_price") or 0) ctp_margin = float(ctp.get("margin") or 0) if (margin is None or float(margin or 0) <= 0) and ctp_margin > 0: margin = ctp_margin @@ -1782,12 +1874,14 @@ def install_trading(app, *, login_required, require_nav, get_db, get_setting, se if not ths: continue direction = (p.get("direction") or "long").strip().lower() - entry = float(p.get("avg_price") or 0) - if entry <= 0: - continue mark = ctp_get_tick_price(mode, ths) if not mark or mark <= 0: continue + entry, _ = _resolve_ctp_entry_price( + mode, ths, direction, p, mark=mark, + ) + if entry <= 0: + continue mult = float(get_contract_spec(ths).get("mult") or 10) if direction == "long": float_pnl = round((mark - entry) * mult * lots, 2) @@ -1801,7 +1895,6 @@ def install_trading(app, *, login_required, require_nav, get_db, get_setting, se "position_key": row_key, "mark_price": mark, "current_price": mark, - "entry_price": entry, "float_pnl": float_pnl, }) return {"ok": True, "quotes": quotes} diff --git a/static/js/dashboard.js b/static/js/dashboard.js index 202a851..d8ae924 100644 --- a/static/js/dashboard.js +++ b/static/js/dashboard.js @@ -832,15 +832,12 @@ if (isPhoneLayout() && posMobileCache[key]) { var cached = posMobileCache[key]; if (q.mark_price != null) cached.current_price = q.mark_price; - if (q.entry_price != null) cached.entry_price = q.entry_price; if (q.float_pnl != null) cached.float_pnl = q.float_pnl; } var row = findPosRow(key); if (!row) return; - var entryEl = row.querySelector('.dash-p-entry'); var markEl = row.querySelector('.dash-p-mark'); var pnlEl = row.querySelector('.dash-p-pnl'); - if (entryEl && q.entry_price != null) entryEl.textContent = fmtNum(q.entry_price); if (markEl && q.mark_price != null) markEl.textContent = fmtNum(q.mark_price); if (pnlEl && q.float_pnl != null) { pnlEl.textContent = fmtPnl(q.float_pnl); diff --git a/static/js/trade.js b/static/js/trade.js index 60b6c12..45004d8 100644 --- a/static/js/trade.js +++ b/static/js/trade.js @@ -216,11 +216,9 @@ data.quotes.forEach(function (q) { var card = findPosCardByKey(q.key || q.position_key); if (!card) return; - var entryEl = card.querySelector('.pos-q-entry'); var markEl = card.querySelector('.pos-q-mark'); var pnlEl = card.querySelector('.pos-q-pnl'); var pnlWrap = card.querySelector('.pos-q-pnl-wrap'); - if (entryEl && q.entry_price != null) entryEl.textContent = fmtNum(q.entry_price); if (markEl && q.mark_price != null) markEl.textContent = fmtNum(q.mark_price); if (pnlEl && q.float_pnl != null) { var pnl = q.float_pnl;