diff --git a/DEVLOG.md b/DEVLOG.md index 7acfb26..427ac9d 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -1,5 +1,9 @@ # 开发节点记录(三系统量化交易) +## 2026年11月19日 155模拟仓差异与公示导出 + +16:07 仅重建155网页容器,运行 `pms:publish-xlsx-13028a1-web`。候选镜像在155断网回归90组通过,实际导出文件和图表均核验。16:08 只读复核仍有14项超批准数量的真实成交差异,未改账或发单,未访问188。逐股明细和发布回执见[155模拟仓重复成交与导出验收](docs/155模拟仓重复成交与导出验收_2026-11-19.md)。 + ## 2026年11月19日 155交易员页面的微盘指标与持仓 11:38 仅重建 web,运行 `pms:micro-ui-00f72df-web`。首页和策略详情识别同一份已采用的盘中名单,首页显示红色“微盘 4.76% · 入场信号”。当日指令按逐笔受理、成交和入账进度提示,交易员和运维的持仓表沿用主观量化表格。项目规则增补提示文案和同类界面的验收要求。 @@ -3300,3 +3304,13 @@ a44c994于10:53:29仅发布155的web,镜像pms:proposal-copy-a44c994。开发 开发机90组隔离禁网全量通过,含20项资金状态及25项关注发布测试。拟定向更新155 web及worker(worker仅传递原始登记时刻),按实际角色镜像构建并继续候选断网验收;此记录时尚未部署。项目规则补充来源周期、交易时段和不可重置的等待上限。 13:09补记:午后13:01:30新增603087自然接入;最初baseline_unavailable并非仍在补历史,准备实际11:53已完成,13:00属于有效分钟映射之外,13:03:31六路已全部evaluated。13:05旧版提示自然消失,不把上游自然恢复归功于部署。web89组、worker87组候选断网回归通过后,13:08:30温和排空并仅重建这两个服务,镜像fund-delay-cac3ba3;其他28容器不变、私有配置保持。13:09自然名单携带原始登记时刻并被web读取,15只优先股票及132只告警池实时资金可用、提示为空。连续确认1942098、数量和现金差零,无缺口或在途,HTTP200。午休反例使用实际响应离线回放,未制造新增关注或测试信号;下一次自然新关注等待不冒充已发生。完整回执见[接续](docs/资金提示预期延迟与故障区分_2026-11-18.md)。 + +## 2026-11-19 累计盈亏、微盘重复下单和当日有效期 + +15:25至15:35在155模拟PMS只读核验。页面、任务和通道的实际镜像提交分别为00f72df、78df266、3144661。策略账本现金较QMT多358,139元,旧页面因此隐藏累计盈亏。以QMT总资产1,947,181.74元及11月2日核实的净投入1,967,927.74元计算,该快照账户累计亏损20,746元;这不是策略账本收益。收盘复查时PMS出口无在途记录,账户与策略持仓仍有14项数量差异,未取得QMT委托快照,不能据本地出口证明券商端已无在挂单。 + +688051.SH的旧子单11:18收到零成交过期,11:21发出新子单;新子单13:03回报成交1,400股,旧子单13:16又回报成交1,400股。另有688217.SH旧单10:39收到零成交撤单终态,10:57发出新单,旧单12:15再回报成交。本端能确认终态与后续成交回报矛盾;QMT是否提前回终态、委托号映射是否正确,仍须对方按券商委托号和成交编号核实。 + +候选修复在入队及实际发送前拦截当日旧单已报撤销或过期后同股同向换编号重报,不把拦截当作成交已核对;不因普通价差撤换已发委托。新微盘建仓委托有效至北京时间当日15:00,若用户授权更早结束则以较早时间为准。保留暂停、移出名单等撤单路径。累计盈亏优先用有效券商资产与既有净投入,仍提示策略账本待核对。不追改旧委托或账本、不操作188,155尚未部署候选修复。 + +开发机91组隔离禁网回归通过,包括页面三道护栏、跨父指令的实际发送前拦截、旧委托与新委托的日期边界、微盘收盘有效期和券商资产盈亏回归。未做候选镜像和真机验收;恢复自动建仓前,需核对券商原始委托与成交并完成账实对账。 diff --git a/app/core/rotation_account.py b/app/core/rotation_account.py index f6f6245..359df44 100644 --- a/app/core/rotation_account.py +++ b/app/core/rotation_account.py @@ -62,7 +62,7 @@ def transfer(account, source, target, amount, values, key): return True -def fill(account, book, side, amount, fee_amount, key): +def fill(account, book, side, amount, fee_amount, key, *, verified_late_buy=False): if key in account['fills']: if account['fills'][key] != {'book': book, 'side': side, 'amount': amount, 'fee': fee_amount}: raise ValueError('成交资金幂等键冲突') @@ -70,7 +70,7 @@ def fill(account, book, side, amount, fee_amount, key): if book not in BOOKS or side not in ('buy', 'sell') or amount <= 0 or fee_amount < 0: raise ValueError('成交资金参数非法') change = (amount if side == 'sell' else -amount)-fee_amount - if account['cash'][book]+change < -1e-6: + if account['cash'][book]+change < -1e-6 and not (verified_late_buy and side == 'buy'): raise ValueError('策略现金不足,不能跨账本透支') account['cash'][book] += change account['fees'][book] += fee_amount diff --git a/app/repo/downstream_repo.py b/app/repo/downstream_repo.py index f93aab3..f9ef531 100644 --- a/app/repo/downstream_repo.py +++ b/app/repo/downstream_repo.py @@ -142,6 +142,19 @@ def _float(v): # ================================================================ trading_order +def sim_buy_fill_evidence(child_id, broker_id): + """仅模拟委托的源记录;不改下游数据库。""" + if T_ORDER != 'trading_order' or T_POSITION != 'trading_position': + raise ValueError('不能从非模拟表读取补账证据') + orders = fetch_all('SELECT order_id, qmt_order_id, stock_code, order_side, order_status, ' + 'order_quantity, filled_quantity FROM trading_order WHERE order_id=:child LIMIT 2', + {'child': child_id}) + logs = fetch_all("SELECT id, order_id, stock_code, extra_data FROM trading_log " + "WHERE order_id=:broker AND log_type='trade_filled' ORDER BY id LIMIT 2", + {'broker': broker_id}) + return orders, logs + + def fetch_filled_orders(*, since_id=None, since_time=None, limit: int = 500) -> list: """已成交单增量拉取 (回放用)。价格口径: filled_price > order_price (下游 filled_amount 不可靠)。 diff --git a/app/services/dispatcher.py b/app/services/dispatcher.py index 3a1dc38..a65b81c 100644 --- a/app/services/dispatcher.py +++ b/app/services/dispatcher.py @@ -175,7 +175,8 @@ def dispatch(*, instruction_id: str, ts_code: str, side: str, qty: int, limit_pr if m == MODE_WS: with execution_orders.account_guard(): parent = pms_repo.get_instruction(pid) - blocked = execution_orders.correction_blocker(parent, ts_code=ts_code, side=str(side).lower()) + blocked = (execution_orders.same_day_retry_blocker(ts_code, str(side).lower(), instruction_id) + or execution_orders.correction_blocker(parent, ts_code=ts_code, side=str(side).lower())) if blocked: raise ValueError(blocked) if execution_orders.enabled() and not qmt_repo.get_order(instruction_id): diff --git a/app/services/execution_orders.py b/app/services/execution_orders.py index 50f8d09..38aea5d 100644 --- a/app/services/execution_orders.py +++ b/app/services/execution_orders.py @@ -53,6 +53,12 @@ def effective_filled(order): return done +def reconciled_overfill_qty(parent): + from app.repo import rotation_repo + evidence, _ = rotation_repo.get('late-buy-parent:'+parent['instruction_id']) + return evidence['exec_qty'] if evidence else None + + def settlement_cutoff(order): """释放资金必须使用修正消息之后的快照,不能沿用早于修正的原终态时间。""" final = _receipt_time(order.get('final_at')) @@ -99,6 +105,23 @@ def correction_blocker(parent=None, *, ts_code=None, side=None): return '' +def same_day_retry_blocker(ts_code, side, instruction_id, now=None): + """撤单或过期回报不足以证明旧券商单不再成交,当日不另发同向新单。""" + day = policy.local_now(now).date() + orders = qmt_repo.list_orders(ts_code=ts_code, statuses=('CANCELLED', 'EXPIRED'), limit=10001) + if len(orders) >= 10001: + return '旧委托记录超过核验上限,暂不重复下单' + for order in orders: + if order['instruction_id'] == instruction_id or order['side'] != side: + continue + if not (order.get('sent_at') or order.get('broker_order_id')): + continue + dates = [_receipt_time(order.get(field)) for field in ('sent_at', 'final_at')] + if not any(dates) or any(at and at.date() >= day for at in dates): + return '该股同向旧单已报撤销或过期,当日不自动重报;请先核对券商委托和成交' + return '' + + def prepare_send(instruction_id): """与修正收件串行检查,成功标记之后才允许WS实际发送。""" with account_guard(), books.scope('all'): @@ -106,7 +129,8 @@ def prepare_send(instruction_id): if not order: return {'marked': False, 'blocked': '委托不存在'} parent = pms_repo.get_instruction(order['parent_id']) - blocked = correction_blocker(parent, ts_code=order['ts_code'], side=order['side']) + blocked = (same_day_retry_blocker(order['ts_code'], order['side'], instruction_id) + or correction_blocker(parent, ts_code=order['ts_code'], side=order['side'])) if blocked: return {'marked': False, 'blocked': blocked} if ((parent or {}).get('progress') or {}).get('ticket'): @@ -148,7 +172,8 @@ def replacement_state(parent_id): if order.get('status') not in qmt_repo.FINAL: live.append(order) booked, target = int(parent.get('exec_qty') or 0), int(parent['qty']) - if max(booked, filled) > target: + if max(booked, filled) > target and not (not live and parent.get('status') == 'CONFIRMED' + and booked == filled == reconciled_overfill_qty(parent)): raise ValueError('已成交数量超出父指令,等待核对') pending_trades = execution_repo.pending_trades(list(seen)) remaining = max(0, target-max(booked, filled)) @@ -237,7 +262,8 @@ def should_replace(parent, desired, now=None): return False orders = qmt_repo.orders_for_parent(parent['instruction_id']) live = [o for o in orders if o.get('status') not in qmt_repo.FINAL] - if not live or any(o.get('cancel_state') in ('REQUESTED', 'SENT') for o in live): + if not live or any(o.get('sent_at') or o.get('broker_order_id') or + o.get('cancel_state') in ('REQUESTED', 'SENT') for o in live): return False cap = max(0, param_store.get_int('PMS_EXEC_REPRICE_MAX_ATTEMPTS', 0)) if cap and len(orders) >= cap: diff --git a/app/services/ledger_service.py b/app/services/ledger_service.py index 5f5c067..3bc78ef 100644 --- a/app/services/ledger_service.py +++ b/app/services/ledger_service.py @@ -599,7 +599,7 @@ def _apply_action(act: dict): if act["kind"] == "BUY": _remember_target_pct(code, act.get("instruction_id")) pms_repo.insert_lot(ts_code=code, lot_type=act.get("lot_type") or "BASE", qty=qty, - open_price=px, open_date=datetime.now().date(), + open_price=px, open_date=act.get('verified_trade_date') or datetime.now().date(), instruction_id=act.get("instruction_id"), note="外部成交并入 BASE" if not act.get("instruction_id") else None) pms_repo.bump_position_qty(code, total_delta=qty, avail_delta=0) # T+1: 当日买入不可卖 diff --git a/app/services/portfolio.py b/app/services/portfolio.py index 33a958d..67f3970 100644 --- a/app/services/portfolio.py +++ b/app/services/portfolio.py @@ -301,8 +301,8 @@ def caps_ctx(view: dict, *, ts_code=None, is_new_name=False, sector=None) -> dic } -def account_performance() -> dict: - """只读账户累计盈亏,使用双策略现金账本的初始化基线。""" +def account_performance(cash=None) -> dict: + """使用账户净投入作为统一基线,券商总资产不依赖策略账本对齐。""" from config.settings import settings empty = {"ready": False, "profit": None, "profit_pct": None, "started_at": None, "reason": "账户收益基线尚未建立"} @@ -312,19 +312,29 @@ def account_performance() -> dict: from app.services import rotation_accounting view = rotation_accounting.view() empty["started_at"] = view.get("started_at") + metrics = view.get("metrics") or {} + capitals = [metrics.get(book, {}).get("net_capital") for book in (books.ORIGINAL, books.MICRO)] + capital = sum(capitals) if all(v is not None and math.isfinite(v) for v in capitals) else None + cash = cash or {} + asset, age = cash.get("total_asset"), cash.get("cash_age_sec") + difference = view.get("cash_difference") + reconciled = difference is not None and abs(difference) <= .02 + if (empty["started_at"] and capital is not None and capital > 0 and cash.get("cash_source") == CASH_WS + and age is not None and age >= 0 and asset is not None and math.isfinite(asset) and asset >= 0): + profit = asset - capital + return {**empty, "ready": True, "profit": round(profit, 2), "profit_pct": profit / capital, + "source": "qmt", "reason": ("按券商总资产计算,不等于策略收益。" if reconciled else + "按券商总资产计算,策略账本仍待核对。")} if not view.get("ready"): empty["reason"] = view.get("reason") or "账户估值待补齐" return empty - difference = view.get("cash_difference") - if difference is not None and abs(difference) > .02: + if difference is not None and not reconciled: empty["reason"] = "账户现金与策略账本待核对" return empty metrics = view.get("metrics") or {} profit = metrics.get("account", {}).get("profit") if profit is None or not math.isfinite(profit): return empty - capitals = [metrics.get(book, {}).get("net_capital") for book in (books.ORIGINAL, books.MICRO)] - capital = sum(capitals) if all(v is not None and math.isfinite(v) for v in capitals) else None return {"ready": True, "profit": round(profit, 2), "profit_pct": profit / capital if capital is not None and capital > 0 else None, "started_at": view.get("started_at"), "reason": None} @@ -351,7 +361,7 @@ def overview() -> dict: # 会让人以为钱多得是 (07-30: cash_est 199 万 vs 真实可用 97 万) "cash_avail": t["cash_avail"], "cash_source": t["cash_source"], "total_asset": t["total_asset"], "cash_why": t["cash_why"], - "account_performance": account_performance(), + "account_performance": account_performance(t), "holding_performance": holding_performance(position_groups(v)), "account_market_value": t["account_market_value"], "frozen_cash": t["frozen_cash"], "float_pnl": t["float_pnl"], diff --git a/app/services/rotation_accounting.py b/app/services/rotation_accounting.py index 97ca334..9818f7b 100644 --- a/app/services/rotation_accounting.py +++ b/app/services/rotation_accounting.py @@ -94,11 +94,11 @@ def reserve_book(book, demand, pending, phase): store.put_once('transfer:'+key, 'cash_transfer', {'key': key, **value['transfers'][key]}) -def record_fill(book, side, amount, fees, key): +def record_fill(book, side, amount, fees, key, *, verified_late_buy=False): with store.locked('capital:live', 'capital', {}) as value: if not value.get('cash'): raise ValueError('分策略现金尚未初始化') - core.fill(value, book, side, amount, fees, key) + core.fill(value, book, side, amount, fees, key, verified_late_buy=verified_late_buy) def view(): diff --git a/app/services/rotation_execution.py b/app/services/rotation_execution.py index 6da809e..3545291 100644 --- a/app/services/rotation_execution.py +++ b/app/services/rotation_execution.py @@ -169,6 +169,10 @@ def enqueue_with_reservation(payload, parent_id): intent=payload['intent'], note=payload.get('note')) +def _close_of_day(now): + return now.replace(hour=15, minute=0, second=0, microsecond=0) + + def send_intent(intent, price, now, snapshot_version): from app.services import dispatcher, execution_orders if dispatcher.mode() != 'ws': @@ -251,7 +255,7 @@ def send_intent(intent, price, now, snapshot_version): if not existing or intent.get('limits_date') != current.date().isoformat(): raise ValueError('等待核实本交易日的委托价格边界') price = rotation_day_orders.protected_price(existing,line,intent.get('day_limits') or {}) - until = min(expiry, current.replace(hour=15, minute=0, second=0, microsecond=0)) + until = min(expiry, _close_of_day(current)) else: checked = execution_orders.quote_order(intent['side'], intent.get('quote_basis'), current, user_limit=(existing or {}).get('limit_price')) @@ -260,10 +264,17 @@ def send_intent(intent, price, now, snapshot_version): price = checked['limit_price'] end = current.replace(hour=11 if current.hour < 12 else 14, minute=30 if current.hour < 12 else 57, second=0, microsecond=0) - until = min(current+dt.timedelta(minutes=10), end, expiry) + if book == books.MICRO and intent['side'] == 'buy': + until = min(_close_of_day(current), expiry) + else: + until = min(current + dt.timedelta(minutes=10), end, expiry) else: until = (now.replace(hour=10, minute=0, second=0, microsecond=0) if now.hour < 10 else min(now+dt.timedelta(minutes=10), now.replace(hour=14, minute=57, second=0, microsecond=0))) + if book == books.MICRO and intent['side'] == 'buy': + until = _close_of_day(now) + if until <= (current if progress.get('ticket') else now): + raise ValueError('本笔轮动委托已过有效期,不再下发') result = dispatcher.dispatch(instruction_id=child, parent_id=parent, intent='OPEN' if intent['side'] == 'buy' else 'EXIT', ts_code=intent['ts_code'], side=intent['side'], qty=quantity, limit_price=price, valid_until=until, note=intent['reason']) @@ -347,6 +358,8 @@ def refresh_orders(parents, quotes, now, snapshot_version, target, unavailable): continue # 当日保护限价单由逐笔账户事务接续,不因分钟行情变化撤换。 children = qmt_repo.orders_for_parent(parent['instruction_id']) live = [c for c in children if c['status'] not in TERMINAL] + if live and parent['book_id'] == books.MICRO and side == 'buy': + continue quote = quotes.get(code, {}) priced = (execution_orders.quote_order(side, quote, now, user_limit=parent.get('limit_price')) if progress.get('ticket') else execution_orders.quote_order(side, quote, now)) @@ -398,7 +411,9 @@ def cancel_expired(now): if p.get('execution_profile') != 'rotation': continue deadline = str(p.get('deadline') or '') - expired = deadline < now.date().isoformat() or (deadline == now.date().isoformat() and now.hour >= 10) + cutoff = (_close_of_day(now) if row['book_id'] == books.MICRO and row['side'] == 'buy' + else now.replace(hour=10, minute=0, second=0, microsecond=0)) + expired = deadline < now.date().isoformat() or (deadline == now.date().isoformat() and now >= cutoff) if p.get('ticket') and p.get('expires_at'): from app.core.execution_policy import local_now expired = local_now(now) >= dt.datetime.fromisoformat(p['expires_at']) @@ -424,7 +439,7 @@ def cancel_expired(now): raise RuntimeError('轮换委托撤销未确认') -def book_trade(act, fees, seq): +def book_trade(act, fees, seq, *, late_buy_evidence=None): """策略归属、批次、费用、指令进度和inbox标记同成同败。""" from app.services import ledger_service as ledger from app.services import trade_lineage @@ -441,8 +456,14 @@ def book_trade(act, fees, seq): raise ValueError('父指令策略归属不可核实') if instruction['ts_code'] != act['ts_code'] or instruction['side'] != ('buy' if act['kind'] == 'BUY' else 'sell'): raise ValueError('成交证券或方向与父指令冲突') - if int(instruction['exec_qty'])+int(act['qty']) > int(instruction['qty']): + overfill = int(instruction['exec_qty'])+int(act['qty']) > int(instruction['qty']) + if overfill and late_buy_evidence is None: raise ValueError('成交超过父指令剩余数量,等待核对') + if late_buy_evidence is not None and not ( + overfill and instruction['book_id'] == books.MICRO and act['kind'] == 'BUY' + and instruction['status'] == 'CONFIRMED' and int(instruction['exec_qty']) == int(instruction['qty']) + and act.get('verified_trade_date') and late_buy_evidence['trade_seq'] == seq): + raise ValueError('只允许按逐笔核实证据恢复已完成微盘父指令的超量买入') with books.scope(instruction['book_id']): before = pms_repo.get_position(act['ts_code']) or {} lots_before = trade_lineage.lots(act['ts_code']) @@ -458,14 +479,19 @@ def book_trade(act, fees, seq): if int(fresh['exec_qty']) != int(instruction['exec_qty'])+qty: raise ValueError('指令成交进度未原子更新') for f in fees: - pms_repo.insert_cash_flow(ymd=int(dt.datetime.now().strftime('%Y%m%d')), kind='FEE', + pms_repo.insert_cash_flow(ymd=int((act.get('verified_trade_date') or dt.datetime.now()).strftime('%Y%m%d')), kind='FEE', amount=f['amount'], ts_code=f['ts_code'], estimated=f['estimated'], trade_no=f['trade_no'], instruction_id=f['instruction_id'], note=f['note']) from app.services.rotation_accounting import record_fill + cash_kwargs = {'verified_late_buy': True} if late_buy_evidence is not None else {} record_fill(instruction['book_id'], 'buy' if act['kind'] == 'BUY' else 'sell', - qty*float(act['price']), -sum(float(f['amount']) for f in fees), str(seq)) + qty*float(act['price']), -sum(float(f['amount']) for f in fees), str(seq), **cash_kwargs) ledger.recompute_position(act['ts_code']) trade_lineage.record(act, instruction, seq, lots_before, trade_lineage.lots(act['ts_code'])) + if late_buy_evidence is not None: + store.put_once(f'late-buy:{seq}', 'verified_late_buy', late_buy_evidence) + store.put_once(f'late-buy-parent:{parent}', 'verified_late_buy_parent', + {'trade_seq': seq, 'exec_qty': int(fresh['exec_qty'])}) if not qmt_repo.inbox_mark([seq], processed=qmt_repo.PROC_BOOKED, note='按策略归属原子入账'): raise RuntimeError('逐笔成交入账标记未写入') return True diff --git a/app/services/trade_correction.py b/app/services/trade_correction.py index b20bea9..96642e2 100644 --- a/app/services/trade_correction.py +++ b/app/services/trade_correction.py @@ -237,7 +237,7 @@ def _verify_physical(code, book, projection, received_at): _need(total == physical, '更正后双策略数量与QMT实际持仓不一致') -def _cash_projection(original, book, side, projection, amended, order): +def _cash_projection(original, book, side, projection, amended, order, *, verified_price_only=False): value, _ = store.get('capital:live') _need(isinstance(value, dict) and isinstance(value.get('cash'), dict), '分策略现金尚未初始化') entry = value.get('fills', {}).get(str(original['seq'])) @@ -250,7 +250,7 @@ def _cash_projection(original, book, side, projection, amended, order): and abs(_d(entry.get('fee'))-fee) <= Decimal('.000001'), '原成交本金或费用与策略现金凭据不符') updated = copy.deepcopy(value) cash = _d(value['cash'].get(book))+_d(projection['cash_delta']) - _need(cash >= 0, '更正差额会使所属策略现金透支') + _need(cash >= 0 or verified_price_only, '更正差额会使所属策略现金透支') active = qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=10001) _need(len(active) < 10001, '在途委托超过资金核验上限') reserved = Decimal(0) @@ -270,7 +270,7 @@ def _cash_projection(original, book, side, projection, amended, order): if remaining: principal = _d(child['limit_price'])*remaining reserved += principal+_d(estimate_fee(float(principal), 'buy', **configuration()['costs'])) - _need(cash >= reserved, '更正后策略现金不足以覆盖既有在途买入占用') + _need(cash >= reserved or verified_price_only and reserved == 0, '更正后策略现金不足以覆盖既有在途买入占用') updated['cash'][book] = float(cash) return value, updated @@ -387,11 +387,17 @@ def _apply(row): children = {r['instruction_id'] for r in orders if r['parent_id'] == parent['instruction_id']} old_qty, _ = _aggregate(trades, children) new_qty, new_amount = _aggregate(trades, children, (no, payload['after'])) - _need(old_qty == _q(parent['exec_qty']) and new_qty <= _q(parent['qty']), '父指令执行量与旧逐笔合计不符或更正后超量') + from app.services.execution_orders import reconciled_overfill_qty + price_only_overfill = (old_qty == new_qty > _q(parent['qty']) and parent['status'] == 'CONFIRMED' + and payload['before']['qty'] == payload['after']['qty'] + and old_qty == reconciled_overfill_qty(parent)) + _need(old_qty == _q(parent['exec_qty']) and (new_qty <= _q(parent['qty']) or price_only_overfill), + '父指令执行量与旧逐笔合计不符或更正后超量') quantity_changed = _q(effective['qty']) != _q(payload['after']['qty']) received = max(_stamp(row['received_at']), _stamp(amendment['received_at'])) _verify_physical(code, book, projection, received) - cash_before, cash_after = _cash_projection(original, book, payload['side'], projection, am, order) + cash_options = {'verified_price_only': True} if price_only_overfill else {} + cash_before, cash_after = _cash_projection(original, book, payload['side'], projection, am, order, **cash_options) projected_orders = [{**r, **order_fields} if r['instruction_id'] == iid else r for r in orders] strategy_updates = _grid_updates(code, parents, projected_orders, projection, quantity_changed, cid) progress = copy.deepcopy(parent.get('progress') or {}) diff --git a/app/web/static/index.html b/app/web/static/index.html index 54e42a6..96cac21 100644 --- a/app/web/static/index.html +++ b/app/web/static/index.html @@ -1111,7 +1111,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
账户总资产
{{ money(ov.total_asset) }}
累计盈亏
-
{{ pnlMoney(accountPnl.profit) }}{{ pnlPercent(accountPnl.profit_pct) }}
+
{{ accountPnl.ready ? pnlMoney(accountPnl.profit) : '暂不可用' }}{{ pnlPercent(accountPnl.profit_pct) }}
可用资金 (估算)
{{ money(ov.cash_source==='ws' ? ov.cash_avail : ov.cash_est) }}
账户持仓市值
{{ money(ov.account_market_value) }}
diff --git a/docs/155模拟仓重复成交与导出验收_2026-11-19.md b/docs/155模拟仓重复成交与导出验收_2026-11-19.md new file mode 100644 index 0000000..ec04f0a --- /dev/null +++ b/docs/155模拟仓重复成交与导出验收_2026-11-19.md @@ -0,0 +1,46 @@ +# 155模拟仓重复成交与导出验收 + +2026年11月19日15:48至15:58(北京时间),只读核验155模拟PMS。确认实例表前缀为空,执行为WS,下游委托与持仓为模拟表。先用账户与策略持仓对账锁定14只沪深股票,再逐只读取QMT直写的`trading_order`和`trading_log`,以券商委托号连接原委托与原成交,再用PMS指令号和成交编号匹配出口及收件箱。 + +## 逐股核对 + +14只股票各有两笔不同的券商委托和成交,28笔成交的编号互不相同。同股两笔均指向同一个微盘轮动父指令,第一笔已用完该父指令的批准数量;第二笔会超过批准量,仍在PMS收件箱待核。晚到买入合计34,700股,按QMT日志所列成交本金合计362,209元,不含手续费。这不是页面重复显示,也不是对同一个成交编号的消息重放。 + +| 股票 | PMS账本股数 | QMT股数 | 晚到成交股数 | 晚到成交对应的PMS旧单终态 | +| --- | ---: | ---: | ---: | --- | +| 300899.SZ | 1,200 | 2,400 | 1,200 | 过期 | +| 301037.SZ | 2,700 | 5,400 | 2,700 | 撤销 | +| 600455.SH | 1,300 | 2,600 | 1,300 | 撤销 | +| 600768.SH | 2,400 | 4,800 | 2,400 | 撤销 | +| 688051.SH | 1,400 | 2,800 | 1,400 | 过期 | +| 688096.SH | 4,800 | 9,600 | 4,800 | 撤销 | +| 688118.SH | 1,700 | 3,400 | 1,700 | 撤销 | +| 688217.SH | 1,400 | 2,800 | 1,400 | 撤销 | +| 688329.SH | 1,600 | 3,200 | 1,600 | 撤销 | +| 688565.SH | 3,300 | 6,600 | 3,300 | 撤销 | +| 688613.SH 奥精医疗 | 4,300 | 8,600 | 4,300 | 撤销 | +| 688670.SH | 2,300 | 4,600 | 2,300 | 撤销 | +| 688681.SH | 2,100 | 4,200 | 2,100 | 过期 | +| 688701.SH | 4,200 | 8,400 | 4,200 | 撤销 | + +奥精医疗的两笔均为买入4,300股、成交价6.08元,两笔各26,144元。券商委托`DESK-94a7d197f8`的成交`T-DESK-a3297ca44f`在PMS入账,序号1963733;券商委托`DESK-0d9af89d91`的成交`T-DESK-94e2e3da70`已收到,序号1965356,核验时未入账。QMT原始委托表中两张均为完成。旧单为何先报撤销或过期、券商撤单回执如何映射,仍需QMT方从原始执行过程追溯;本次没有修改成交、持仓、资金或交易规则。 + +## 导出范围 + +标题和账户名只改155的运行参数。市值列以当日价乘持股数,持仓小计和总计随明细重算;已平仓行不填当前市值。图表两端与主表对齐,只给每日净值标四位小数,仓位线不新增标签。沿用原有公示净值及持仓账本口径,版式验收不等于交易账本已对齐。 + +## 部署与验收 + +2026年11月19日16:07(北京时间),检查155模拟实例后,仅重建网页容器,运行`pms:publish-xlsx-13028a1-web`(提交`13028a1`)。候选镜像在155禁网运行90组回归,全部通过;发布后健康检查和数据库探测正常。交易工作进程、唯一的QMT连接容器和其他运行容器的标识与镜像版本保持不变。没有访问188。 + +在155运行中的网页容器调用实际导出处理器,生成`量化数据2026.11.19.xlsx`。工作簿确认标题为“26年投研量化平层产品基本信息”,开单账户为“模拟账户”,市值位于交易金额与起始时间之间。用LibreOffice渲染核对折线图与主表左右对齐,14个净值点各显示一条四位小数标签,仓位线不显示数据标签。本次未在登录后的浏览器或桌面Excel中操作;中文标题与列名从工作簿内容核对。 + +16:08发布后再次只读对账,QMT持仓快照仍显示14项差异,奥精医疗仍是PMS账本4,300股、QMT 8,600股。回报连接在线,接收及确认水位均为1969120,未请求重同步。此处只证明连接和接收状态,不代表差异已经处理。网页旧配置、参数原值、测试回执及实际导出验收样本保留在155;发布备份目录为`backups/publish-xlsx-13028a1-20261119-160650`。 + +## 防重与补账接续 + +同一父指令包括多次尝试,不能以股票代码猜父指令。14笔待入账买单的旧回报是11笔`CANCELLED`(`cancel_order`)、3笔`EXPIRED`(`valid_until`),累计成交均为零;后收到相同券商委托号的工作台补记逐笔成交和全成回报(`desk_backfill`)。旧PMS看见终态和零成交后允许新子单下发,导致两个委托都进入QMT模拟成交与持仓记录。奥精医疗旧D03在11:01:33收到撤销、累计零成交;D04在11:05:32受理、11:07:42成交;旧D03在12:22:07收到工作台补记成交和全成回报。现有材料证明的是工作台补记,不证明交易所撤单确认后又发生撮合。尚未取得QMT工作台的操作审计、柜台撤单回执或底层执行代码,不能从PMS推定谁为何补记。 + +恢复边界:PMS命令仍约束下发数量;实际成交必须按原券商委托和原策略入账,即使超出授权也不能删除事实、扩大授权或再派单。防重同时作用于入队前和发往QMT前。同股同向已发委托当日报撤销或过期,不自动另发;未发即作废、其他股票与方向不因此被拦。同编号的幂等恢复仍使用原编号。微盘新建仓买单最长至北京时间当日15:00,不因分钟报价变化撤换,不突破更早的独立授权,用户撤销、标的调出和明确风控要求仍有效。 + +累计盈亏使用有效QMT账户总资产减已建立的账户净投入;账户收益不再因两策略内部现金差异而隐藏,不把策略现金差异当成策略收益。无可核实基线或估值时,页面提示暂不可用。补账仅在明确指定的155模拟范围内使用`reconcile_qmt_late_buys.py`,默认只读。待入账逐笔须与券商委托号、原始委托和成交记录、旧终态与随后全成、有效实际持仓、同方向及已确认父指令交叉吻合。校验只读证据的摘要后方允许写入,原始回报、授权数量和旧终态不覆盖。策略现金可反映实际超支,但不隐式划拨、不编造费用、不改初始本金。其余回报继续走既有更正机制。 diff --git a/docs/开发入口.md b/docs/开发入口.md index 485fc21..a121fad 100644 --- a/docs/开发入口.md +++ b/docs/开发入口.md @@ -84,6 +84,7 @@ | 盘中改价、异步研判与微盘递补发布 | [执行链路发布接续](执行报价与异步研判发布接续_2026-11-03.md),区分部署、开关与自然判收;[实施规格](执行报价与异步研判实施规格_2026-11-03.md);[当日限制价采集边界](当日限制价采集边界_2026-11-03.md) | | 策略资金缺行情提示、成本三位精度与含费口径 | [估值与成本精度修复](策略估值与成本精度修复_2026-11-04.md),含实际QMT回执、展示降级和导出舍入边界 | | QMT工作台成交修正与配套委托回报 | [成交修正接入与发布](QMT成交修正接入与发布_2026-11-05.md),含原成交保留、修正幂等、数量变化阻断续单和证据不足挂起边界 | +| 155模拟仓重复下单、补账和累计盈亏 | [故障核对及接续](155模拟仓重复成交与导出验收_2026-11-19.md),逐股证据、部署验收与未决事项;不适用于188 | | 买方评级变动与三十日排序 | [规格](评级变动记录与三十日排序规格_2026-11-05.md)及[发布接续](评级变动与三十日排序发布接续_2026-11-05.md),降级保留候选,同档升优降后;178与155已发布,13:57自然消费通过,真实升降和到期另待判收 | | 原策略两次清仓信号与买方评级下降退出 | [退出纪律接续](两次清仓信号与评级下降退出_2026-11-05.md),含第一次停买、第二次清仓、任一级评级下降、持仓轮次、重复消息和T+1收尾 | | 人工关注显示已剔除、每日选股重复与研究覆盖 | [人工关注分析链修复规格](人工关注分析链修复规格_2026-11-04.md),说明独立研究、回执与交易边界;[只读巡检及当日更正](人工关注与选股覆盖巡检_2026-11-04.md)保留历史时点证据;首次部署见[发布接续](人工关注与吸筹参考发布接续_2026-11-04.md),11月4日进度见[后续跟进](人工关注后续跟进与信号融合_2026-11-04.md),最新格式要求及计划过期恢复见[11月5日接续](信号流格式与选股恢复_2026-11-05.md) | diff --git a/scripts/reconcile_qmt_late_buys.py b/scripts/reconcile_qmt_late_buys.py new file mode 100644 index 0000000..15e3170 --- /dev/null +++ b/scripts/reconcile_qmt_late_buys.py @@ -0,0 +1,151 @@ +"""155模拟仓:凭原始逐笔、终态和实际持仓认领已成交的微盘超量买入。默认只读。""" +import argparse +import hashlib +import json +import sys +from datetime import date, datetime +from decimal import Decimal +from pathlib import Path +from zoneinfo import ZoneInfo + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.core import execution_policy, recon, strategy_book as books, ws_codec +from app.repo import downstream_repo, pms_repo, qmt_repo, rotation_repo +from app.services import dispatcher, ledger_service, param_store, rotation_execution, rotation_service +from config.settings import settings + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def check_scope(): + require(not settings.PMS_TABLE_PREFIX and settings.INFRA_STRATEGY_BOOK_SCHEMA + and dispatcher.mode() == 'ws' and downstream_repo.T_ORDER == 'trading_order' + and downstream_repo.T_POSITION == 'trading_position', '仅允许在155模拟PMS运行') + + +def raw_values(payload): + quantity, price, amount = (Decimal(str(payload[key])) for key in ('qty', 'price', 'amount')) + require(0 < quantity == int(quantity) and price > 0 and amount == quantity * price, + '成交数量、价格或金额异常') + return int(quantity), price, amount + + +def validate_trade(event, order, parent, order_rows, logs, terminal, difference, trade_day): + payload = event['payload'] + code, child, broker = (payload[key] for key in ('ts_code', 'instruction_id', 'broker_order_id')) + quantity, price, _ = raw_values(payload) + trade_date = datetime.fromtimestamp(payload['trade_time'] / 1000, ZoneInfo('Asia/Shanghai')).date() + require(trade_date == trade_day and execution_policy.supported_code(code), '成交日期或市场不在本次范围') + require(event['processed'] == qmt_repo.PROC_PENDING and payload['side'] == 'buy' + and payload.get('desk_backfill') is True + and event['dedup_key'] == ws_codec.dedup_key('trade', payload), '收件身份或状态不可核实') + require(order['instruction_id'] == child and order['broker_order_id'] == broker + and order['ts_code'] == code and order['side'] == 'buy' and int(order['qty']) == quantity + and order['status'] in ('CANCELLED', 'EXPIRED') and int(order['cum_qty']) == 0, + '待补子委托与本地记录不符') + require(parent['instruction_id'] == order['parent_id'] == recon.parent_instruction_id(child) + and parent['book_id'] == books.MICRO and parent['ts_code'] == code and parent['side'] == 'buy' + and parent['status'] == 'CONFIRMED' and int(parent['exec_qty']) == int(parent['qty']) + and difference['book_qty'] + quantity == difference['ds_qty'], '父指令或账户持仓差异不吻合') + require(len(order_rows) == len(logs) == 1 and len(terminal) == 2, '原始委托、逐笔或终态证据不唯一') + source, log = order_rows[0], logs[0] + require(source['order_id'] == child and source['qmt_order_id'] == log['order_id'] == broker + and all(downstream_repo.to_dot(item['stock_code']) == code for item in (source, log)) + and source['order_side'] == 'buy' and source['order_status'] in downstream_repo.FILLED_STATUSES + and int(source['order_quantity']) == int(source['filled_quantity']) == quantity, 'QMT原始委托与成交不互证') + body = json.loads(log['extra_data']) + require(body['trade_no'] == payload['trade_no'] and body['trade_direction'] == 'buy' + and raw_values({'qty': body['traded_volume'], 'price': body['traded_price'], + 'amount': body['traded_amount']})[0] == quantity, 'QMT交易日志不能证明同一逐笔成交') + raw = body.get('before') if body.get('corrected') else { + 'qty': body['traded_volume'], 'price': body['traded_price'], 'amount': body['traded_amount']} + require(raw_values(raw) == raw_values(payload), 'QMT原始成交价或成交款与收件不符') + earlier, later = terminal + first, last = earlier['payload'], later['payload'] + require(all(item['instruction_id'] == child and item['broker_order_id'] == broker + and item['final'] is True and int(item['leaves_qty']) == 0 for item in (first, last)) + and first['status'] == order['status'] and int(first['cum_qty']) == 0 + and earlier['seq'] < event['seq'] < later['seq'] + and last['status'] == 'FILLED' and last.get('reason') == 'desk_backfill' and int(last['cum_qty']) == quantity + and Decimal(str(last['cum_avg_price'])) == price, '缺少旧终态和其后全成的配套原始回报') + return {'trade_seq': event['seq'], 'trade': payload, 'old_terminal': first, 'filled_terminal': last, + 'terminal_seqs': [earlier['seq'], later['seq']], 'order': order, 'parent': parent, + 'source_order': source, 'source_log': log, 'position_difference': difference} + + +def plan(codes, trade_day): + require(not qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=1), '仍有在途委托,不进行补账') + snapshot = qmt_repo.latest_snapshot('positions') or {} + require(snapshot.get('age_sec', 9999) <= 60, 'QMT实际持仓超过一分钟或不可用') + result = rotation_service.reconcile_books() + require(result.get('source') == 'ws' and not result['errors'], '没有有效QMT实际持仓') + differences = {row['ts_code']: row for row in result['diffs']} + require(set(differences) == set(codes), '实际差异名单与指定范围不一致') + rows = qmt_repo.inbox_pending(limit=501, msg_type='trade') + require(len(rows) < 501, '待入账成交超出完整检查上限') + selected = [row for row in rows if (row.get('payload') or {}).get('ts_code') in differences] + require(len(selected) == len(codes) and {row['payload']['ts_code'] for row in selected} == set(codes), + '并非每个差异均可唯一匹配待入账逐笔') + evidence = [] + for row in selected: + payload = row['payload'] + child, broker, code = (payload[key] for key in ('instruction_id', 'broker_order_id', 'ts_code')) + order = qmt_repo.get_order(child) + require(order, '待核子委托不存在') + with books.scope('all'): + parent = pms_repo.get_instruction(order['parent_id']) + require(parent, '待核父指令不存在') + orders, logs = downstream_repo.sim_buy_fill_evidence(child, broker) + events = qmt_repo.inbox_list(msg_type='order_update', corr_id=child, limit=51) + require(len(events) < 51, '同一子委托的回报超出完整检查上限') + events = sorted((item for item in events if item['payload'].get('final') is True + and not item['payload'].get('amended')), key=lambda item: item['seq']) + evidence.append(validate_trade(row, order, parent, orders, logs, events, differences[code], trade_day)) + return evidence + + +def apply(evidence, trade_day): + for item in evidence: + order, parent, payload = (item[key] for key in ('order', 'parent', 'trade')) + mapped = recon.map_trades_to_book([{'seq': item['trade_seq'], 'payload': payload}], + {parent['instruction_id']: parent['action']}) + require(len(mapped['actions']) == 1 and not mapped['alerts'], '无法唯一映射原逐笔成交') + act = {**mapped['actions'][0], 'verified_trade_date': trade_day} + require(rotation_execution.book_trade(act, mapped['fees'], item['trade_seq'], late_buy_evidence=item), + '收件已变更,未重复补账') + require(qmt_repo.update_order(order['instruction_id'], cum_qty=act['qty'], + cum_avg_price=act['price'], leaves_qty=0), '未保存实成数量') + final = rotation_service.reconcile_books() + require(final['ok'] and final.get('source') == 'ws', '补记后仍存在数量差异,全部回滚') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--day', required=True, type=date.fromisoformat) + parser.add_argument('--codes', required=True, nargs='+') + parser.add_argument('--apply-evidence-sha256') + args = parser.parse_args() + check_scope() + require(len(set(args.codes)) == len(args.codes), '股票范围不能重复') + if not args.apply_evidence_sha256: + evidence = plan(args.codes, args.day) + print(rotation_repo.encode({'sha256': digest(evidence), 'evidence': evidence})) + return + with rotation_repo.account_guard(): + require(param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False), '实际写入前必须暂停执行') + evidence = plan(args.codes, args.day) + require(digest(evidence) == args.apply_evidence_sha256, '现场证据与只读备份不同') + apply(evidence, args.day) + print(rotation_repo.encode({'applied': len(evidence), 'evidence_sha256': digest(evidence)})) + + +def digest(evidence): + return hashlib.sha256(rotation_repo.encode(evidence).encode()).hexdigest() + + +if __name__ == '__main__': + main() diff --git a/scripts/run_tests.py b/scripts/run_tests.py index 2884688..ae42cb3 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -165,6 +165,7 @@ 目标价到价自决关时入队、自决开时自动清仓按可卖量夹紧、挂着方案且有在途买单时先撤再清 + 用户设的止损价与目标价单独成列显示 (72 例) 共 1154 例,49 批 + test_qmt_late_buy_reconciliation.py 逐笔补账证据、幂等及现金不足边界(4例) 2026-10-12 校正历史漏计,原有测试实际 941 例;本次新增三批共 42 例。 任一子集失败即整体失败 (退出码 1)。 @@ -207,6 +208,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) # 退出纪律专项:两次独立清仓信号、评级下降、事务、双策略隔离及撤单收尾。 SUITES = [ + 'test_qmt_late_buy_reconciliation.py', 'test_intraday_rotation.py', # 单日轮动授权、50个席位、保护限价和委托出口(11例) "test_business_evidence.py", # 历史准备覆盖与嵌套业务失败(21例) "test_signal_health.py", # 资金监测可用性与交易员提示,7例 diff --git a/scripts/test_batch47_units.py b/scripts/test_batch47_units.py index 35ca233..9d67cb3 100644 --- a/scripts/test_batch47_units.py +++ b/scripts/test_batch47_units.py @@ -160,6 +160,16 @@ class AccountPerformanceTest(unittest.TestCase): self.assertFalse(result['ready']) self.assertIsNone(result['profit']) + def test_broker_equity_keeps_account_profit_visible_during_ledger_disagreement(self): + self.fake.qmt.put_snapshot(kind='funds', data=dict(FUNDS, total_asset=14800)) + result = self.read(cash_difference=100) + self.assertTrue(result['ready']) + self.assertEqual(result['source'], 'qmt') + self.assertEqual(result['profit'], -200) + self.assertAlmostEqual(result['profit_pct'], -200 / 15000) + self.assertIn('策略账本仍待核对', result['reason']) + self.assertIsNone(self.read(started_at=None, cash_difference=100)['profit']) + def test_failure_does_not_hide_other_overview_fields(self): with patch.object(rotation_accounting, 'view', side_effect=ValueError('test only')): result = portfolio.overview() diff --git a/scripts/test_batch52_units.py b/scripts/test_batch52_units.py index 32fb063..f9bb35c 100644 --- a/scripts/test_batch52_units.py +++ b/scripts/test_batch52_units.py @@ -111,6 +111,7 @@ class ChannelTest(unittest.TestCase): self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3, valid_until=9999999999999) with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \ + patch.object(qmt_repo, 'list_orders', return_value=[]), \ patch.object(qmt_repo, 'claim_order', return_value=True), \ patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \ patch.object(qmt_repo, 'mark_send_attempt', return_value=False), \ @@ -118,12 +119,31 @@ class ChannelTest(unittest.TestCase): self.loop.run_until_complete(self.runner._drain_outbox('unused')) send.assert_not_called() + def test_cancelled_predecessor_from_another_parent_blocks_wire_send(self): + from app.services import execution_conflicts + self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3, + valid_until=9999999999999) + previous = dict(instruction_id='old_D01', parent_id='old', side='buy', + sent_at=datetime.now(), final_at=datetime.now(), status='EXPIRED') + with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \ + patch.object(qmt_repo, 'list_orders', return_value=[previous]), \ + patch.object(qmt_repo, 'claim_order', return_value=True), \ + patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \ + patch.object(qmt_repo, 'abort_order') as abort, \ + patch.object(qmt_repo, 'mark_send_attempt') as attempt, \ + patch.object(self.runner, '_send', new_callable=AsyncMock) as send: + self.loop.run_until_complete(self.runner._drain_outbox('unused')) + send.assert_not_called() + attempt.assert_not_called() + self.assertIn('当日不自动重报', abort.call_args.args[1]) + def test_send_error_after_attempt_keeps_uncertain_order_retryable(self): from app.services import execution_conflicts self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3, valid_until=9999999999999) def attempted(_): self.row['sent_at'] = datetime.now(); return True with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \ + patch.object(qmt_repo, 'list_orders', return_value=[]), \ patch.object(qmt_repo, 'claim_order', return_value=True), \ patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \ patch.object(qmt_repo, 'mark_send_attempt', side_effect=attempted), \ diff --git a/scripts/test_batch53_units.py b/scripts/test_batch53_units.py index d9ec572..53b4da9 100644 --- a/scripts/test_batch53_units.py +++ b/scripts/test_batch53_units.py @@ -74,6 +74,7 @@ class StrategyOutboxTest(unittest.TestCase): (settings, 'INFRA_STRATEGY_BOOK_SCHEMA', {'new': True}), (qmt_repo, 'next_queued', {'return_value': [row]}), (qmt_repo, 'get_order', {'return_value': row}), + (qmt_repo, 'list_orders', {'return_value': []}), (qmt_repo, 'claim_order', {'return_value': True}), (qmt_repo, 'mark_send_attempt', {'return_value': True}), (qmt_repo, 'mark_sent', {}), diff --git a/scripts/test_batch55_units.py b/scripts/test_batch55_units.py index 4d14c5f..4dfaa0c 100644 --- a/scripts/test_batch55_units.py +++ b/scripts/test_batch55_units.py @@ -280,6 +280,23 @@ class ExecutionTests(unittest.TestCase): row['created_at'] = NOW self.assertFalse(orders.should_replace(self.fake.instructions['P'], {'action': 'FIRE', 'limit_price': 10.1}, NOW)) + def test_transmitted_cancel_or_expiry_blocks_a_new_id_not_the_other_side(self): + row = self.child() + row.update(sent_at=NOW-timedelta(minutes=10), final_at=NOW) + for status in ('CANCELLED', 'EXPIRED'): + row['status'] = status + with self.subTest(status=status), patch.object(orders.policy, 'local_now', return_value=NOW): + result = dispatcher.dispatch(instruction_id='P_D02', parent_id='P', ts_code=CODE, + side='buy', qty=600, limit_price=10., valid_until=NOW+timedelta(minutes=10)) + self.assertFalse(result['ok']) + self.assertIn('当日不自动重报', result['error']) + self.assertEqual(len(self.fake.qmt.orders), 1) + self.assertFalse(orders.same_day_retry_blocker(CODE, 'sell', 'new', NOW)) + self.assertFalse(orders.same_day_retry_blocker(CODE, 'buy', 'P_D01', NOW)) + self.assertFalse(orders.same_day_retry_blocker(CODE, 'buy', 'new', NOW+timedelta(days=1))) + row.update(status='ACCEPTED') + self.assertFalse(orders.should_replace(self.fake.instructions['P'], {'action': 'FIRE', 'limit_price': 10.1}, NOW)) + def test_queued_order_rechecks_stop_before_sending(self): row = self.child() self.fake.instructions['P']['progress']['execution_basis_cache']['basis'] = fact(continuation='STOP') diff --git a/scripts/test_batch56_units.py b/scripts/test_batch56_units.py index b94cd1b..9663664 100644 --- a/scripts/test_batch56_units.py +++ b/scripts/test_batch56_units.py @@ -312,7 +312,7 @@ class ServiceBoundaries(unittest.TestCase): self.assertIn('600000.SH',s['target']) self.assertEqual(len(s['target']),50) - def test_missing_quote_cancels_live_child_without_substituting(self): + def test_missing_quote_keeps_live_buy_without_substituting(self): from app.services import rotation_execution as r, execution_orders as e, executor parent={'instruction_id':'p','book_id':'micro30','ts_code':'600000.SH','side':'buy','qty':100, 'progress':{'execution_profile':'rotation','rule_version':m.EXECUTION_RULE,'deadline':'2026-11-03'}} @@ -322,10 +322,10 @@ class ServiceBoundaries(unittest.TestCase): patch.object(executor,'cancel_instruction') as cancel, \ patch.object(r.db,'savepoint',side_effect=nullcontext): result,waits=r.refresh_orders([parent],{},dt.datetime(2026,11,3,9,40),'v',{'600000.SH'},{}) - replace.assert_called_once() + replace.assert_not_called() cancel.assert_not_called() self.assertEqual(result,[]) - self.assertTrue(waits) + self.assertEqual(waits, []) def test_missing_quote_without_live_child_only_waits(self): from app.services import rotation_execution as r, execution_orders as e diff --git a/scripts/test_intraday_rotation.py b/scripts/test_intraday_rotation.py index 1a22b00..8f1fa6b 100644 --- a/scripts/test_intraday_rotation.py +++ b/scripts/test_intraday_rotation.py @@ -85,6 +85,7 @@ class IntradayEntry(TestCase): def test_wire_freeze_then_sell(self): self.mock(eo,'account_guard',side_effect=nullcontext) self.mock(eo.qmt_repo,'get_order',return_value=self.order) + self.mock(eo.qmt_repo,'list_orders',return_value=[]) self.mock(eo.pms_repo,'get_instruction',return_value=self.parent) self.mock(eo,'correction_blocker',return_value='') self.mock(eo.policy,'local_now',return_value=self.now) @@ -187,6 +188,22 @@ class IntradayEntry(TestCase): with self.assertRaises(ValueError): trade.send_intent(intent,0,self.now,self.release['snapshot_version']) self.assertEqual(len(wire),1) + self.parent['progress'] = {'children': []} + morning = self.now.replace(hour=9, minute=40) + trade.send_intent(intent, 10., morning, self.basket['snapshot_version']) + self.assertEqual(wire[-1]['valid_until'], int(morning.replace(hour=15, minute=0).timestamp()*1000)) + with self.assertRaisesRegex(ValueError, '已过有效期'): + trade.send_intent(intent, 10., morning.replace(hour=15, minute=0), self.basket['snapshot_version']) + self.assertEqual(len(wire), 2) + + def test_regular_micro_buy_is_not_cancelled_until_close(self): + from app.services import rotation_execution as trade, executor + self.parent['progress'] = dict(execution_profile='rotation', deadline=self.day) + cancel = self.mock(executor, 'cancel_instruction', return_value={'ok': True}) + trade.cancel_expired(self.now) + cancel.assert_not_called() + trade.cancel_expired(self.now.replace(hour=15, minute=0)) + cancel.assert_called_once() def test_standing_cancel_keeps_user_controls(self): from app.services import rotation_day_orders as day diff --git a/scripts/test_qmt_late_buy_reconciliation.py b/scripts/test_qmt_late_buy_reconciliation.py new file mode 100644 index 0000000..1388bcd --- /dev/null +++ b/scripts/test_qmt_late_buy_reconciliation.py @@ -0,0 +1,75 @@ +import unit_test_guard +import copy +import json +import unittest +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from reconcile_qmt_late_buys import validate_trade +from app.core import rotation_account, ws_codec + + +class LateBuyTests(unittest.TestCase): + def setUp(self): + self.day = date(2026, 11, 19) + stamp = int(datetime(2026, 11, 19, 13, tzinfo=ZoneInfo('Asia/Shanghai')).timestamp() * 1000) + payload = dict(instruction_id='P_D01', broker_order_id='BROKER', trade_no='FILL', ts_code='688613.SH', + side='buy', qty=200, price=6.08, amount=1216, trade_time=stamp, desk_backfill=True) + self.trade = dict(seq=2, payload=payload, processed=0, dedup_key=ws_codec.dedup_key('trade', payload)) + self.order = dict(instruction_id='P_D01', broker_order_id='BROKER', ts_code='688613.SH', side='buy', + qty=200, status='CANCELLED', cum_qty=0, parent_id='P') + self.parent = dict(instruction_id='P', book_id='micro30', ts_code='688613.SH', side='buy', + status='CONFIRMED', exec_qty=200, qty=200) + self.source = dict(order_id='P_D01', qmt_order_id='BROKER', stock_code='688613.SH', order_side='buy', + order_status='completed', order_quantity=200, filled_quantity=200) + self.log = dict(order_id='BROKER', stock_code='688613.SH', extra_data=json.dumps(dict( + trade_no='FILL', trade_direction='buy', traded_volume=200, traded_price=6.10, traded_amount=1220, + corrected=True, before=dict(qty=200, price=6.08, amount=1216)))) + identity = dict(instruction_id='P_D01', broker_order_id='BROKER', final=True, leaves_qty=0) + self.terminal = [dict(seq=1, payload=dict(identity, status='CANCELLED', cum_qty=0)), + dict(seq=3, payload=dict(identity, status='FILLED', cum_qty=200, + cum_avg_price=6.08, reason='desk_backfill'))] + self.diff = dict(book_qty=200, ds_qty=400) + + def validate(self): + return validate_trade(self.trade, self.order, self.parent, [self.source], [self.log], + self.terminal, self.diff, self.day) + + def test_validates_distinct_original_and_corrected_price(self): + evidence = self.validate() + self.assertEqual(evidence['trade_seq'], 2) + self.assertEqual(evidence['terminal_seqs'], [1, 3]) + self.assertEqual(evidence['old_terminal']['status'], 'CANCELLED') + + def test_inconsistent_position_or_terminal_refuses_write(self): + self.diff['ds_qty'] = 401 + with self.assertRaisesRegex(ValueError, '持仓差异'): + self.validate() + self.diff['ds_qty'] = 400 + self.terminal[1]['seq'] = 1 + with self.assertRaisesRegex(ValueError, '配套原始回报'): + self.validate() + + def test_repeat_or_wrong_book_refuses_write(self): + self.trade['processed'] = 1 + with self.assertRaisesRegex(ValueError, '收件身份'): + self.validate() + self.trade['processed'] = 0 + self.parent['book_id'] = 'original' + with self.assertRaisesRegex(ValueError, '父指令'): + self.validate() + + def test_book_verified_shortfall_without_transferring_cash(self): + account = rotation_account.seed(500, {}) + original = copy.deepcopy(account) + with self.assertRaisesRegex(ValueError, '现金不足'): + rotation_account.fill(account, 'micro30', 'buy', 100, 0, '2') + self.assertEqual(account, original) + self.assertTrue(rotation_account.fill(account, 'micro30', 'buy', 100, 0, '2', verified_late_buy=True)) + self.assertFalse(rotation_account.fill(account, 'micro30', 'buy', 100, 0, '2', verified_late_buy=True)) + self.assertEqual(account['cash'], {'original': 500, 'micro30': -100}) + self.assertEqual(account['net_capital'], original['net_capital']) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/test_trade_lineage_units.py b/scripts/test_trade_lineage_units.py index b2a0707..28fce50 100644 --- a/scripts/test_trade_lineage_units.py +++ b/scripts/test_trade_lineage_units.py @@ -86,6 +86,32 @@ class BookingTests(unittest.TestCase): self.assertFalse(rotation_execution.book_trade(self.act, [], 1)) self.assertEqual(self.state(), before) + def test_verified_overfill_preserves_approval_and_rolls_back_failed_audit(self): + with self.engine.begin() as conn: + conn.execute(text("UPDATE pms_instruction SET book_id='micro30',status='CONFIRMED',exec_qty=qty")) + evidence = {'trade_seq': 1, 'terminal_seqs': [0, 2]} + from datetime import date + action = dict(self.act, verified_trade_date=date(2026, 11, 19)) + original = self.state() + with self.assertRaisesRegex(ValueError, '超过父指令'): + rotation_execution.book_trade(action, [], 1) + save = rotation_repo.put_once + def refuse_audit(key, kind, value): + if kind == 'verified_late_buy': + raise RuntimeError('audit failed') + return save(key, kind, value) + with patch.object(rotation_repo, 'put_once', side_effect=refuse_audit): + with self.assertRaisesRegex(RuntimeError, 'audit failed'): + rotation_execution.book_trade(action, [], 1, late_buy_evidence=evidence) + self.assertEqual(self.state(), original) + self.assertTrue(rotation_execution.book_trade(action, [], 1, late_buy_evidence=evidence)) + final = self.state() + self.assertEqual((final['parents'][0]['qty'], final['parents'][0]['exec_qty']), (100, 200)) + self.assertEqual(final['lots'][0]['open_date'], '2026-11-19') + self.assertEqual(final['inbox'][0]['processed'], 1) + self.assertFalse(rotation_execution.book_trade(action, [], 1, late_buy_evidence=evidence)) + self.assertEqual(self.state(), final) + def test_lineage_write_failure_rolls_back_entire_booking(self): before = self.state() with patch.object(trade_lineage.rotation_repo, 'put_once', side_effect=RuntimeError('storage fault')):