Compare commits

...

2 Commits

Author SHA1 Message Date
baobao 7d2cc0e3d1 恢复账户累计盈亏并防止微盘重复下单 2026-11-19 16:28:37 +08:00
baobao 13028a18af 改进模拟账户量化导出表 2026-11-19 15:59:20 +08:00
26 changed files with 590 additions and 97 deletions

View File

@ -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交易员页面的微盘指标与持仓 ## 2026年11月19日 155交易员页面的微盘指标与持仓
11:38 仅重建 web,运行 `pms:micro-ui-00f72df-web`。首页和策略详情识别同一份已采用的盘中名单,首页显示红色“微盘 4.76% · 入场信号”。当日指令按逐笔受理、成交和入账进度提示,交易员和运维的持仓表沿用主观量化表格。项目规则增补提示文案和同类界面的验收要求。 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仅传递原始登记时刻),按实际角色镜像构建并继续候选断网验收;此记录时尚未部署。项目规则补充来源周期、交易时段和不可重置的等待上限。 开发机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)。 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组隔离禁网回归通过,包括页面三道护栏、跨父指令的实际发送前拦截、旧委托与新委托的日期边界、微盘收盘有效期和券商资产盈亏回归。未做候选镜像和真机验收;恢复自动建仓前,需核对券商原始委托与成交并完成账实对账。

View File

@ -62,7 +62,7 @@ def transfer(account, source, target, amount, values, key):
return True 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 key in account['fills']:
if account['fills'][key] != {'book': book, 'side': side, 'amount': amount, 'fee': fee_amount}: if account['fills'][key] != {'book': book, 'side': side, 'amount': amount, 'fee': fee_amount}:
raise ValueError('成交资金幂等键冲突') 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: if book not in BOOKS or side not in ('buy', 'sell') or amount <= 0 or fee_amount < 0:
raise ValueError('成交资金参数非法') raise ValueError('成交资金参数非法')
change = (amount if side == 'sell' else -amount)-fee_amount 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('策略现金不足,不能跨账本透支') raise ValueError('策略现金不足,不能跨账本透支')
account['cash'][book] += change account['cash'][book] += change
account['fees'][book] += fee_amount account['fees'][book] += fee_amount

View File

@ -142,6 +142,19 @@ def _float(v):
# ================================================================ trading_order # ================================================================ 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: def fetch_filled_orders(*, since_id=None, since_time=None, limit: int = 500) -> list:
"""已成交单增量拉取 (回放用)。价格口径: filled_price > order_price (下游 filled_amount 不可靠)。 """已成交单增量拉取 (回放用)。价格口径: filled_price > order_price (下游 filled_amount 不可靠)。

View File

@ -175,7 +175,8 @@ def dispatch(*, instruction_id: str, ts_code: str, side: str, qty: int, limit_pr
if m == MODE_WS: if m == MODE_WS:
with execution_orders.account_guard(): with execution_orders.account_guard():
parent = pms_repo.get_instruction(pid) 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: if blocked:
raise ValueError(blocked) raise ValueError(blocked)
if execution_orders.enabled() and not qmt_repo.get_order(instruction_id): if execution_orders.enabled() and not qmt_repo.get_order(instruction_id):

View File

@ -53,6 +53,12 @@ def effective_filled(order):
return done 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): def settlement_cutoff(order):
"""释放资金必须使用修正消息之后的快照,不能沿用早于修正的原终态时间。""" """释放资金必须使用修正消息之后的快照,不能沿用早于修正的原终态时间。"""
final = _receipt_time(order.get('final_at')) final = _receipt_time(order.get('final_at'))
@ -99,6 +105,23 @@ def correction_blocker(parent=None, *, ts_code=None, side=None):
return '' 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): def prepare_send(instruction_id):
"""与修正收件串行检查,成功标记之后才允许WS实际发送。""" """与修正收件串行检查,成功标记之后才允许WS实际发送。"""
with account_guard(), books.scope('all'): with account_guard(), books.scope('all'):
@ -106,7 +129,8 @@ def prepare_send(instruction_id):
if not order: if not order:
return {'marked': False, 'blocked': '委托不存在'} return {'marked': False, 'blocked': '委托不存在'}
parent = pms_repo.get_instruction(order['parent_id']) 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: if blocked:
return {'marked': False, 'blocked': blocked} return {'marked': False, 'blocked': blocked}
if ((parent or {}).get('progress') or {}).get('ticket'): 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: if order.get('status') not in qmt_repo.FINAL:
live.append(order) live.append(order)
booked, target = int(parent.get('exec_qty') or 0), int(parent['qty']) 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('已成交数量超出父指令,等待核对') raise ValueError('已成交数量超出父指令,等待核对')
pending_trades = execution_repo.pending_trades(list(seen)) pending_trades = execution_repo.pending_trades(list(seen))
remaining = max(0, target-max(booked, filled)) remaining = max(0, target-max(booked, filled))
@ -237,7 +262,8 @@ def should_replace(parent, desired, now=None):
return False return False
orders = qmt_repo.orders_for_parent(parent['instruction_id']) orders = qmt_repo.orders_for_parent(parent['instruction_id'])
live = [o for o in orders if o.get('status') not in qmt_repo.FINAL] 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 return False
cap = max(0, param_store.get_int('PMS_EXEC_REPRICE_MAX_ATTEMPTS', 0)) cap = max(0, param_store.get_int('PMS_EXEC_REPRICE_MAX_ATTEMPTS', 0))
if cap and len(orders) >= cap: if cap and len(orders) >= cap:

View File

@ -599,7 +599,7 @@ def _apply_action(act: dict):
if act["kind"] == "BUY": if act["kind"] == "BUY":
_remember_target_pct(code, act.get("instruction_id")) _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, 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"), instruction_id=act.get("instruction_id"),
note="外部成交并入 BASE" if not act.get("instruction_id") else None) note="外部成交并入 BASE" if not act.get("instruction_id") else None)
pms_repo.bump_position_qty(code, total_delta=qty, avail_delta=0) # T+1: 当日买入不可卖 pms_repo.bump_position_qty(code, total_delta=qty, avail_delta=0) # T+1: 当日买入不可卖

View File

@ -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 from config.settings import settings
empty = {"ready": False, "profit": None, "profit_pct": None, "started_at": None, empty = {"ready": False, "profit": None, "profit_pct": None, "started_at": None,
"reason": "账户收益基线尚未建立"} "reason": "账户收益基线尚未建立"}
@ -312,19 +312,29 @@ def account_performance() -> dict:
from app.services import rotation_accounting from app.services import rotation_accounting
view = rotation_accounting.view() view = rotation_accounting.view()
empty["started_at"] = view.get("started_at") 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"): if not view.get("ready"):
empty["reason"] = view.get("reason") or "账户估值待补齐" empty["reason"] = view.get("reason") or "账户估值待补齐"
return empty return empty
difference = view.get("cash_difference") if difference is not None and not reconciled:
if difference is not None and abs(difference) > .02:
empty["reason"] = "账户现金与策略账本待核对" empty["reason"] = "账户现金与策略账本待核对"
return empty return empty
metrics = view.get("metrics") or {} metrics = view.get("metrics") or {}
profit = metrics.get("account", {}).get("profit") profit = metrics.get("account", {}).get("profit")
if profit is None or not math.isfinite(profit): if profit is None or not math.isfinite(profit):
return empty 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), return {"ready": True, "profit": round(profit, 2),
"profit_pct": profit / capital if capital is not None and capital > 0 else None, "profit_pct": profit / capital if capital is not None and capital > 0 else None,
"started_at": view.get("started_at"), "reason": None} "started_at": view.get("started_at"), "reason": None}
@ -351,7 +361,7 @@ def overview() -> dict:
# 会让人以为钱多得是 (07-30: cash_est 199 万 vs 真实可用 97 万) # 会让人以为钱多得是 (07-30: cash_est 199 万 vs 真实可用 97 万)
"cash_avail": t["cash_avail"], "cash_source": t["cash_source"], "cash_avail": t["cash_avail"], "cash_source": t["cash_source"],
"total_asset": t["total_asset"], "cash_why": t["cash_why"], "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)), "holding_performance": holding_performance(position_groups(v)),
"account_market_value": t["account_market_value"], "frozen_cash": t["frozen_cash"], "account_market_value": t["account_market_value"], "frozen_cash": t["frozen_cash"],
"float_pnl": t["float_pnl"], "float_pnl": t["float_pnl"],

View File

@ -276,7 +276,7 @@ def _nav_series(snapshot: dict) -> list:
# ---------------------------------------------------------------- 版式 (模板填充) # ---------------------------------------------------------------- 版式 (模板填充)
def _copy_row_style(ws, src_row: int, dst_row: int, cols=range(2, 22)): def _copy_row_style(ws, src_row: int, dst_row: int, cols=range(2, 23)):
"""只拷单元格样式。行高不在这拷 —— openpyxl 插行不搬 row_dimensions, 拷邻行行高 """只拷单元格样式。行高不在这拷 —— openpyxl 插行不搬 row_dimensions, 拷邻行行高
等于拷一个错位的旧值, 行高在 build_workbook 里按最终行位统一重排。""" 等于拷一个错位的旧值, 行高在 build_workbook 里按最终行位统一重排。"""
for col in cols: for col in cols:
@ -292,41 +292,43 @@ def _put(ws, row, col, value, fmt=None):
def _entry_row(ws, row, seq, e, *, date2, px): def _entry_row(ws, row, seq, e, *, date2, px):
vals = [seq, e["account"], e["code"], e["name"], e["amount"], e["open_date"], vals = [seq, e["account"], e["code"], e["name"], e["amount"], None, e["open_date"],
date2, e["structure"], e["cost"], e["qty"], px, e["days"], date2, e["structure"], e["cost"], e["qty"], px, e["days"],
_FIN_NONE, _FIN_NONE, _FIN_NONE, _FIN_NONE,
f"=M{row}-K{row}", # Q 每股较期初价盈 f"=N{row}-L{row}",
f"=IF(K{row}=0,0,Q{row}/K{row})"] # R 较期初价涨跌幅 f"=IF(L{row}=0,0,R{row}/L{row})"]
for i, v in enumerate(vals): for i, v in enumerate(vals):
_put(ws, row, 3 + i, v) _put(ws, row, 3 + i, v)
# 均价统一显示三位、金额两位;格式不能反过来截断原始数值。 # 均价统一显示三位、金额两位;格式不能反过来截断原始数值。
for col in (11, 13, 17): for col in (12, 14, 18):
ws.cell(row=row, column=col).number_format = "0.000" ws.cell(row=row, column=col).number_format = "0.000"
for col in (7, 19): for col in (7, 8, 20):
ws.cell(row=row, column=col).number_format = "#,##0.00" ws.cell(row=row, column=col).number_format = "#,##0.00"
# 表格里手动修订成本或股数后,成本金额和持仓盈亏必须一起重算。 # 表格里手动修订成本或股数后,成本金额和持仓盈亏必须一起重算。
_put(ws, row, 7, f"=ROUND(K{row}*L{row},2)") _put(ws, row, 7, f"=ROUND(L{row}*M{row},2)")
# S 总持股浮动盈亏: 持仓 = 市值减成本金额;平仓 = 含费实得,沿用账本数值
if e.get("pnl") is None: if e.get("pnl") is None:
_put(ws, row, 19, f"=ROUND(ROUND(M{row}*L{row},2)-G{row},2)") _put(ws, row, 8, f"=ROUND(N{row}*M{row},2)")
_put(ws, row, 20, f"=ROUND(H{row}-G{row},2)")
else: else:
_put(ws, row, 19, e["pnl"]) _put(ws, row, 20, e["pnl"])
_put(ws, row, 20, f"=IF(G{row}=0,0,S{row}/G{row})") # T 持有收益率 _put(ws, row, 21, f"=IF(G{row}=0,0,T{row}/G{row})")
_put(ws, row, 21, f"=1+T{row}") # U 净值估算 _put(ws, row, 22, f"=1+U{row}")
def _subtotal(ws, row, top, bottom, has_rows): def _subtotal(ws, row, top, bottom, has_rows):
_put(ws, row, 7, f"=SUM(G{top}:G{bottom})" if has_rows else 0) _put(ws, row, 7, f"=SUM(G{top}:G{bottom})" if has_rows else 0)
_put(ws, row, 19, f"=SUM(S{top}:S{bottom})" if has_rows else 0) _put(ws, row, 20, f"=SUM(T{top}:T{bottom})" if has_rows else 0)
_put(ws, row, 20, f"=IF(G{row}=0,0,S{row}/G{row})") _put(ws, row, 21, f"=IF(G{row}=0,0,T{row}/G{row})")
_put(ws, row, 21, f"=1+T{row}") _put(ws, row, 22, f"=1+U{row}")
def build_workbook(s: dict, nav_rows: list) -> bytes: def build_workbook(s: dict, nav_rows: list) -> bytes:
"""把快照填进公司模板。纯函数 (不碰库), 可离线测试。""" """把快照填进公司模板。纯函数 (不碰库), 可离线测试。"""
import openpyxl import openpyxl
from openpyxl.chart import LineChart, Reference from openpyxl.chart import LineChart, Reference
from openpyxl.chart.label import DataLabelList
from openpyxl.chart.marker import Marker from openpyxl.chart.marker import Marker
from openpyxl.drawing.spreadsheet_drawing import AnchorMarker, TwoCellAnchor
from openpyxl.formatting.formatting import ConditionalFormattingList from openpyxl.formatting.formatting import ConditionalFormattingList
from openpyxl.formatting.rule import CellIsRule from openpyxl.formatting.rule import CellIsRule
from openpyxl.styles import Font, PatternFill from openpyxl.styles import Font, PatternFill
@ -351,6 +353,15 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
# openpyxl 的插行不搬合并区 —— 先全拆, 插完行按最终行位重新合并 # openpyxl 的插行不搬合并区 —— 先全拆, 插完行按最终行位重新合并
for rng in list(ws.merged_cells.ranges): for rng in list(ws.merged_cells.ranges):
ws.unmerge_cells(str(rng)) ws.unmerge_cells(str(rng))
ws.insert_cols(8)
for key, dim in reversed(list(ws.column_dimensions.items())):
if dim.min >= 8:
del ws.column_dimensions[key]
dim.min += 1
dim.max += 1
dim.index = get_column_letter(dim.min)
ws.column_dimensions[dim.index] = dim
ws.column_dimensions['H'].width = ws.column_dimensions['G'].width
if n_c > 1: # 自底向上插, 行号才不互相踩 if n_c > 1: # 自底向上插, 行号才不互相踩
ws.insert_rows(_R_CPROTO + 1, n_c - 1) ws.insert_rows(_R_CPROTO + 1, n_c - 1)
if n_h > 1: if n_h > 1:
@ -371,8 +382,12 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
# ---- 标题与时间 ---- # ---- 标题与时间 ----
_put(ws, 1, 2, s["title"]) _put(ws, 1, 2, s["title"])
start = nav_rows[0]["ymd"] if nav_rows else int(s["today"].strftime("%Y%m%d")) start = nav_rows[0]["ymd"] if nav_rows else int(s["today"].strftime("%Y%m%d"))
_put(ws, 2, 20, datetime.strptime(str(start), "%Y%m%d").date()) _put(ws, 2, 21, datetime.strptime(str(start), "%Y%m%d").date())
_put(ws, 3, 20, s["today"]) _put(ws, 3, 21, s["today"])
for row in (4, chead, *range(hold_top, hsub + 1), *range(close_top, csub + 1), sum1):
ws.cell(row, 8)._style = copy(ws.cell(row, 7)._style)
for row in (4, chead):
_put(ws, row, 8, "市值(元)")
# ---- 明细与小计 ---- # ---- 明细与小计 ----
if s["holdings"]: if s["holdings"]:
@ -381,6 +396,7 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
else: else:
_put(ws, hold_top, 6, "(当前无持仓)") _put(ws, hold_top, 6, "(当前无持仓)")
_subtotal(ws, hsub, hold_top, hsub - 1, bool(s["holdings"])) _subtotal(ws, hsub, hold_top, hsub - 1, bool(s["holdings"]))
_put(ws, hsub, 8, f"=SUM(H{hold_top}:H{hsub - 1})", fmt="#,##0.00")
if s["closed"]: if s["closed"]:
for i, e in enumerate(s["closed"]): for i, e in enumerate(s["closed"]):
_entry_row(ws, close_top + i, i + 1, e, date2=e["close_date"], px=e["settle"]) _entry_row(ws, close_top + i, i + 1, e, date2=e["close_date"], px=e["settle"])
@ -390,20 +406,21 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
# ---- 汇总两行 (公式引用两张小计, 口径同模板) ---- # ---- 汇总两行 (公式引用两张小计, 口径同模板) ----
_put(ws, sum1, 7, f"=G{hsub}") _put(ws, sum1, 7, f"=G{hsub}")
_put(ws, sum1, 19, f"=S{hsub}+S{csub}") _put(ws, sum1, 8, f"=H{hsub}", fmt="#,##0.00")
_put(ws, sum1, 20, f"=S{sum1}/{s['scale']}") _put(ws, sum1, 20, f"=T{hsub}+T{csub}")
_put(ws, sum1, 21, f"=1+T{sum1}") _put(ws, sum1, 21, f"=T{sum1}/{s['scale']}")
_put(ws, sum2, 6, f"={s['scale']}+S{csub}") _put(ws, sum1, 22, f"=1+U{sum1}")
_put(ws, sum2, 10, f"=F{sum2}-G{sum1}") _put(ws, sum2, 6, f"={s['scale']}+T{csub}")
_put(ws, sum2, 12, f"=IF(F{sum2}=0,0,G{sum1}/F{sum2})") _put(ws, sum2, 11, f"=F{sum2}-G{sum1}")
_put(ws, sum2, 15, f"=U{sum1}") _put(ws, sum2, 13, f"=IF(F{sum2}=0,0,G{sum1}/F{sum2})")
_put(ws, sum2, 17, f"=U{sum1}") _put(ws, sum2, 16, f"=V{sum1}")
_put(ws, sum2, 18, f"=V{sum1}")
# ---- 合并区按最终行位重排 (与模板同构) ---- # ---- 合并区按最终行位重排 (与模板同构) ----
for rng in ([f"B1:T1", f"B4:B{hsub}", f"B{chead}:B{csub}", for rng in (["B1:V1", f"B4:B{hsub}", f"B{chead}:B{csub}",
f"B{sum1}:F{sum1}", f"H{sum1}:I{sum1}", f"Q{sum1}:R{sum1}", f"B{sum1}:F{sum1}", f"I{sum1}:J{sum1}", f"R{sum1}:S{sum1}",
f"B{sum2}:E{sum2}", f"F{sum2}:G{sum2}", f"H{sum2}:I{sum2}", f"B{sum2}:E{sum2}", f"F{sum2}:H{sum2}", f"I{sum2}:J{sum2}",
f"M{sum2}:N{sum2}", f"R{sum2}:T{sum2}"]): f"N{sum2}:O{sum2}", f"S{sum2}:U{sum2}"]):
ws.merge_cells(rng) ws.merge_cells(rng)
# ---- 行高按最终行位重排 (openpyxl 插行不搬行高, 与合并区同病同治) ---- # ---- 行高按最终行位重排 (openpyxl 插行不搬行高, 与合并区同病同治) ----
@ -415,21 +432,20 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
rd.height = h0 rd.height = h0
rd.hidden = False rd.hidden = False
# ---- 红涨绿跌条件格式 (原表样式按最终行位重建: Q/R/S 红涨绿跌字色, # ---- 红涨绿跌条件格式按最终行列重建。 ----
# 持仓 S 列独一份用红绿底色, 0 也算红; 颜色与原表 dxf 逐字节同) ----
def _font_rule(op, color): def _font_rule(op, color):
return CellIsRule(operator=op, formula=["0"], font=Font(color=color)) return CellIsRule(operator=op, formula=["0"], font=Font(color=color))
for rng in (f"Q{hold_top}:R{hsub - 1}", f"Q{close_top}:S{csub - 1}", for rng in (f"R{hold_top}:S{hsub - 1}", f"R{close_top}:T{csub - 1}",
f"S{hsub} S{csub}"): f"T{hsub} T{csub}"):
ws.conditional_formatting.add(rng, _font_rule("greaterThan", "FFFF0000")) ws.conditional_formatting.add(rng, _font_rule("greaterThan", "FFFF0000"))
ws.conditional_formatting.add(rng, _font_rule("lessThan", "FF00B050")) ws.conditional_formatting.add(rng, _font_rule("lessThan", "FF00B050"))
ws.conditional_formatting.add( ws.conditional_formatting.add(
f"S{hold_top}:S{hsub - 1}", f"T{hold_top}:T{hsub - 1}",
CellIsRule(operator="lessThan", formula=["0"], CellIsRule(operator="lessThan", formula=["0"],
fill=PatternFill(fill_type="solid", bgColor="FF00B050"))) fill=PatternFill(fill_type="solid", bgColor="FF00B050")))
ws.conditional_formatting.add( ws.conditional_formatting.add(
f"S{hold_top}:S{hsub - 1}", f"T{hold_top}:T{hsub - 1}",
CellIsRule(operator="greaterThanOrEqual", formula=["0"], CellIsRule(operator="greaterThanOrEqual", formula=["0"],
fill=PatternFill(fill_type="solid", bgColor="FFFF0000"))) fill=PatternFill(fill_type="solid", bgColor="FFFF0000")))
@ -451,7 +467,7 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
# ---- 净值序列 + 折线图 (双系列同原表: 净值主轴 + 仓位占比副轴, 标题同原图; # ---- 净值序列 + 折线图 (双系列同原表: 净值主轴 + 仓位占比副轴, 标题同原图;
# 每个数据点带标记, 首日只有一个点也看得见; plotVisOnly=0 隐藏单元格照画) ---- # 每个数据点带标记, 首日只有一个点也看得见; plotVisOnly=0 隐藏单元格照画) ----
base = note_row + 1 base = note_row + 1
NC = 25 # Y 列起三列数据, 在图区右侧, 不碰表体 NC = 26
hd = Font(name="宋体", size=10, bold=True) hd = Font(name="宋体", size=10, bold=True)
for j, h in enumerate(["时间", "净值数据", "仓位占比"]): for j, h in enumerate(["时间", "净值数据", "仓位占比"]):
_put(ws, base, NC + j, h).font = hd _put(ws, base, NC + j, h).font = hd
@ -466,11 +482,13 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
cats = Reference(ws, min_col=NC, min_row=base + 1, max_row=last) cats = Reference(ws, min_col=NC, min_row=base + 1, max_row=last)
nav_c = LineChart() nav_c = LineChart()
nav_c.title = "量化净值数据及持仓仓位变化" nav_c.title = "量化净值数据及持仓仓位变化"
nav_c.height, nav_c.width = 9.0, 30.0 # 与模板图区 (B..U 宽 × 16 行) 相当
nav_c.add_data(Reference(ws, min_col=NC + 1, min_row=base, max_row=last), nav_c.add_data(Reference(ws, min_col=NC + 1, min_row=base, max_row=last),
titles_from_data=True) titles_from_data=True)
nav_c.set_categories(cats) nav_c.set_categories(cats)
nav_c.y_axis.number_format = "0.000" nav_c.y_axis.number_format = "0.000"
nav_c.series[0].dLbls = DataLabelList(showVal=True, numFmt="0.0000", dLblPos="t",
showCatName=False, showSerName=False, showLegendKey=False,
showPercent=False, showBubbleSize=False)
pos_c = LineChart() pos_c = LineChart()
pos_c.add_data(Reference(ws, min_col=NC + 2, min_row=base, max_row=last), pos_c.add_data(Reference(ws, min_col=NC + 2, min_row=base, max_row=last),
titles_from_data=True) titles_from_data=True)
@ -485,8 +503,10 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
ser.marker = Marker(symbol=sym, size=7) ser.marker = Marker(symbol=sym, size=7)
nav_c += pos_c nav_c += pos_c
nav_c.visible_cells_only = False nav_c.visible_cells_only = False
ws.add_chart(nav_c, f"B{base}") nav_c.anchor = TwoCellAnchor(_from=AnchorMarker(col=1, row=base - 1),
for col, w in {25: 11, 26: 10, 27: 10}.items(): to=AnchorMarker(col=22, row=base + 16))
ws.add_chart(nav_c)
for col, w in {NC: 11, NC + 1: 10, NC + 2: 10}.items():
ws.column_dimensions[get_column_letter(col)].width = w ws.column_dimensions[get_column_letter(col)].width = w
buf = io.BytesIO() buf = io.BytesIO()

View File

@ -94,11 +94,11 @@ def reserve_book(book, demand, pending, phase):
store.put_once('transfer:'+key, 'cash_transfer', {'key': key, **value['transfers'][key]}) 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: with store.locked('capital:live', 'capital', {}) as value:
if not value.get('cash'): if not value.get('cash'):
raise ValueError('分策略现金尚未初始化') 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(): def view():

View File

@ -169,6 +169,10 @@ def enqueue_with_reservation(payload, parent_id):
intent=payload['intent'], note=payload.get('note')) 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): def send_intent(intent, price, now, snapshot_version):
from app.services import dispatcher, execution_orders from app.services import dispatcher, execution_orders
if dispatcher.mode() != 'ws': 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(): if not existing or intent.get('limits_date') != current.date().isoformat():
raise ValueError('等待核实本交易日的委托价格边界') raise ValueError('等待核实本交易日的委托价格边界')
price = rotation_day_orders.protected_price(existing,line,intent.get('day_limits') or {}) 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: else:
checked = execution_orders.quote_order(intent['side'], intent.get('quote_basis'), current, checked = execution_orders.quote_order(intent['side'], intent.get('quote_basis'), current,
user_limit=(existing or {}).get('limit_price')) user_limit=(existing or {}).get('limit_price'))
@ -260,10 +264,17 @@ def send_intent(intent, price, now, snapshot_version):
price = checked['limit_price'] price = checked['limit_price']
end = current.replace(hour=11 if current.hour < 12 else 14, minute=30 if current.hour < 12 else 57, end = current.replace(hour=11 if current.hour < 12 else 14, minute=30 if current.hour < 12 else 57,
second=0, microsecond=0) 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: else:
until = (now.replace(hour=10, minute=0, second=0, microsecond=0) if now.hour < 10 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))) 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', 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, ts_code=intent['ts_code'], side=intent['side'], qty=quantity, limit_price=price,
valid_until=until, note=intent['reason']) valid_until=until, note=intent['reason'])
@ -347,6 +358,8 @@ def refresh_orders(parents, quotes, now, snapshot_version, target, unavailable):
continue # 当日保护限价单由逐笔账户事务接续,不因分钟行情变化撤换。 continue # 当日保护限价单由逐笔账户事务接续,不因分钟行情变化撤换。
children = qmt_repo.orders_for_parent(parent['instruction_id']) children = qmt_repo.orders_for_parent(parent['instruction_id'])
live = [c for c in children if c['status'] not in TERMINAL] 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, {}) quote = quotes.get(code, {})
priced = (execution_orders.quote_order(side, quote, now, user_limit=parent.get('limit_price')) 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)) 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': if p.get('execution_profile') != 'rotation':
continue continue
deadline = str(p.get('deadline') or '') 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'): if p.get('ticket') and p.get('expires_at'):
from app.core.execution_policy import local_now from app.core.execution_policy import local_now
expired = local_now(now) >= dt.datetime.fromisoformat(p['expires_at']) expired = local_now(now) >= dt.datetime.fromisoformat(p['expires_at'])
@ -424,7 +439,7 @@ def cancel_expired(now):
raise RuntimeError('轮换委托撤销未确认') raise RuntimeError('轮换委托撤销未确认')
def book_trade(act, fees, seq): def book_trade(act, fees, seq, *, late_buy_evidence=None):
"""策略归属、批次、费用、指令进度和inbox标记同成同败。""" """策略归属、批次、费用、指令进度和inbox标记同成同败。"""
from app.services import ledger_service as ledger from app.services import ledger_service as ledger
from app.services import trade_lineage from app.services import trade_lineage
@ -441,8 +456,14 @@ def book_trade(act, fees, seq):
raise ValueError('父指令策略归属不可核实') raise ValueError('父指令策略归属不可核实')
if instruction['ts_code'] != act['ts_code'] or instruction['side'] != ('buy' if act['kind'] == 'BUY' else 'sell'): if instruction['ts_code'] != act['ts_code'] or instruction['side'] != ('buy' if act['kind'] == 'BUY' else 'sell'):
raise ValueError('成交证券或方向与父指令冲突') 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('成交超过父指令剩余数量,等待核对') 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']): with books.scope(instruction['book_id']):
before = pms_repo.get_position(act['ts_code']) or {} before = pms_repo.get_position(act['ts_code']) or {}
lots_before = trade_lineage.lots(act['ts_code']) 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: if int(fresh['exec_qty']) != int(instruction['exec_qty'])+qty:
raise ValueError('指令成交进度未原子更新') raise ValueError('指令成交进度未原子更新')
for f in fees: 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'], amount=f['amount'], ts_code=f['ts_code'], estimated=f['estimated'],
trade_no=f['trade_no'], instruction_id=f['instruction_id'], note=f['note']) trade_no=f['trade_no'], instruction_id=f['instruction_id'], note=f['note'])
from app.services.rotation_accounting import record_fill 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', 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']) ledger.recompute_position(act['ts_code'])
trade_lineage.record(act, instruction, seq, lots_before, trade_lineage.lots(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='按策略归属原子入账'): if not qmt_repo.inbox_mark([seq], processed=qmt_repo.PROC_BOOKED, note='按策略归属原子入账'):
raise RuntimeError('逐笔成交入账标记未写入') raise RuntimeError('逐笔成交入账标记未写入')
return True return True

View File

@ -237,7 +237,7 @@ def _verify_physical(code, book, projection, received_at):
_need(total == physical, '更正后双策略数量与QMT实际持仓不一致') _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') value, _ = store.get('capital:live')
_need(isinstance(value, dict) and isinstance(value.get('cash'), dict), '分策略现金尚未初始化') _need(isinstance(value, dict) and isinstance(value.get('cash'), dict), '分策略现金尚未初始化')
entry = value.get('fills', {}).get(str(original['seq'])) 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'), '原成交本金或费用与策略现金凭据不符') and abs(_d(entry.get('fee'))-fee) <= Decimal('.000001'), '原成交本金或费用与策略现金凭据不符')
updated = copy.deepcopy(value) updated = copy.deepcopy(value)
cash = _d(value['cash'].get(book))+_d(projection['cash_delta']) 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) active = qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=10001)
_need(len(active) < 10001, '在途委托超过资金核验上限') _need(len(active) < 10001, '在途委托超过资金核验上限')
reserved = Decimal(0) reserved = Decimal(0)
@ -270,7 +270,7 @@ def _cash_projection(original, book, side, projection, amended, order):
if remaining: if remaining:
principal = _d(child['limit_price'])*remaining principal = _d(child['limit_price'])*remaining
reserved += principal+_d(estimate_fee(float(principal), 'buy', **configuration()['costs'])) 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) updated['cash'][book] = float(cash)
return value, updated 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']} children = {r['instruction_id'] for r in orders if r['parent_id'] == parent['instruction_id']}
old_qty, _ = _aggregate(trades, children) old_qty, _ = _aggregate(trades, children)
new_qty, new_amount = _aggregate(trades, children, (no, payload['after'])) 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']) quantity_changed = _q(effective['qty']) != _q(payload['after']['qty'])
received = max(_stamp(row['received_at']), _stamp(amendment['received_at'])) received = max(_stamp(row['received_at']), _stamp(amendment['received_at']))
_verify_physical(code, book, projection, received) _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] 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) strategy_updates = _grid_updates(code, parents, projected_orders, projection, quantity_changed, cid)
progress = copy.deepcopy(parent.get('progress') or {}) progress = copy.deepcopy(parent.get('progress') or {})

View File

@ -1111,7 +1111,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
<div class="metrics"> <div class="metrics">
<div class="m"><div class="k">账户总资产</div><div class="v">{{ money(ov.total_asset) }}</div></div> <div class="m"><div class="k">账户总资产</div><div class="v">{{ money(ov.total_asset) }}</div></div>
<div class="m"><div class="k">累计盈亏</div> <div class="m"><div class="k">累计盈亏</div>
<div class="v pnl-value" :class="pnlColor(accountPnl.profit)">{{ pnlMoney(accountPnl.profit) }}<span class="pnl-rate">{{ pnlPercent(accountPnl.profit_pct) }}</span></div></div> <div class="v pnl-value" :class="pnlColor(accountPnl.profit)" :title="accountPnl.reason || ''">{{ accountPnl.ready ? pnlMoney(accountPnl.profit) : '暂不可用' }}<span class="pnl-rate" v-if="accountPnl.ready">{{ pnlPercent(accountPnl.profit_pct) }}</span></div></div>
<div class="m"><div class="k">可用资金<span class="muted" v-if="ov.cash_source!=='ws'"> (估算)</span></div> <div class="m"><div class="k">可用资金<span class="muted" v-if="ov.cash_source!=='ws'"> (估算)</span></div>
<div class="v" :class="ov.cash_source==='ws'?'':'muted'">{{ money(ov.cash_source==='ws' ? ov.cash_avail : ov.cash_est) }}</div></div> <div class="v" :class="ov.cash_source==='ws'?'':'muted'">{{ money(ov.cash_source==='ws' ? ov.cash_avail : ov.cash_est) }}</div></div>
<div class="m"><div class="k">账户持仓市值</div><div class="v">{{ money(ov.account_market_value) }}</div></div> <div class="m"><div class="k">账户持仓市值</div><div class="v">{{ money(ov.account_market_value) }}</div></div>

View File

@ -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`,默认只读。待入账逐笔须与券商委托号、原始委托和成交记录、旧终态与随后全成、有效实际持仓、同方向及已确认父指令交叉吻合。校验只读证据的摘要后方允许写入,原始回报、授权数量和旧终态不覆盖。策略现金可反映实际超支,但不隐式划拨、不编造费用、不改初始本金。其余回报继续走既有更正机制。

View File

@ -84,6 +84,7 @@
| 盘中改价、异步研判与微盘递补发布 | [执行链路发布接续](执行报价与异步研判发布接续_2026-11-03.md),区分部署、开关与自然判收;[实施规格](执行报价与异步研判实施规格_2026-11-03.md);[当日限制价采集边界](当日限制价采集边界_2026-11-03.md) | | 盘中改价、异步研判与微盘递补发布 | [执行链路发布接续](执行报价与异步研判发布接续_2026-11-03.md),区分部署、开关与自然判收;[实施规格](执行报价与异步研判实施规格_2026-11-03.md);[当日限制价采集边界](当日限制价采集边界_2026-11-03.md) |
| 策略资金缺行情提示、成本三位精度与含费口径 | [估值与成本精度修复](策略估值与成本精度修复_2026-11-04.md),含实际QMT回执、展示降级和导出舍入边界 | | 策略资金缺行情提示、成本三位精度与含费口径 | [估值与成本精度修复](策略估值与成本精度修复_2026-11-04.md),含实际QMT回执、展示降级和导出舍入边界 |
| QMT工作台成交修正与配套委托回报 | [成交修正接入与发布](QMT成交修正接入与发布_2026-11-05.md),含原成交保留、修正幂等、数量变化阻断续单和证据不足挂起边界 | | 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)及[发布接续](评级变动与三十日排序发布接续_2026-11-05.md),降级保留候选,同档升优降后;178与155已发布,13:57自然消费通过,真实升降和到期另待判收 |
| 原策略两次清仓信号与买方评级下降退出 | [退出纪律接续](两次清仓信号与评级下降退出_2026-11-05.md),含第一次停买、第二次清仓、任一级评级下降、持仓轮次、重复消息和T+1收尾 | | 原策略两次清仓信号与买方评级下降退出 | [退出纪律接续](两次清仓信号与评级下降退出_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) | | 人工关注显示已剔除、每日选股重复与研究覆盖 | [人工关注分析链修复规格](人工关注分析链修复规格_2026-11-04.md),说明独立研究、回执与交易边界;[只读巡检及当日更正](人工关注与选股覆盖巡检_2026-11-04.md)保留历史时点证据;首次部署见[发布接续](人工关注与吸筹参考发布接续_2026-11-04.md),11月4日进度见[后续跟进](人工关注后续跟进与信号融合_2026-11-04.md),最新格式要求及计划过期恢复见[11月5日接续](信号流格式与选股恢复_2026-11-05.md) |

View File

@ -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()

View File

@ -165,6 +165,7 @@
目标价到价自决关时入队、自决开时自动清仓按可卖量夹紧、挂着方案且有在途买单时先撤再清 + 目标价到价自决关时入队、自决开时自动清仓按可卖量夹紧、挂着方案且有在途买单时先撤再清 +
用户设的止损价与目标价单独成列显示 (72 例) 用户设的止损价与目标价单独成列显示 (72 例)
共 1154 例,49 批 共 1154 例,49 批
test_qmt_late_buy_reconciliation.py 逐笔补账证据、幂等及现金不足边界(4例)
2026-10-12 校正历史漏计,原有测试实际 941 例;本次新增三批共 42 例。 2026-10-12 校正历史漏计,原有测试实际 941 例;本次新增三批共 42 例。
任一子集失败即整体失败 (退出码 1)。 任一子集失败即整体失败 (退出码 1)。
@ -207,6 +208,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE) ROOT = os.path.dirname(HERE)
# 退出纪律专项:两次独立清仓信号、评级下降、事务、双策略隔离及撤单收尾。 # 退出纪律专项:两次独立清仓信号、评级下降、事务、双策略隔离及撤单收尾。
SUITES = [ SUITES = [
'test_qmt_late_buy_reconciliation.py',
'test_intraday_rotation.py', # 单日轮动授权、50个席位、保护限价和委托出口(11例) 'test_intraday_rotation.py', # 单日轮动授权、50个席位、保护限价和委托出口(11例)
"test_business_evidence.py", # 历史准备覆盖与嵌套业务失败(21例) "test_business_evidence.py", # 历史准备覆盖与嵌套业务失败(21例)
"test_signal_health.py", # 资金监测可用性与交易员提示,7例 "test_signal_health.py", # 资金监测可用性与交易员提示,7例

View File

@ -160,6 +160,16 @@ class AccountPerformanceTest(unittest.TestCase):
self.assertFalse(result['ready']) self.assertFalse(result['ready'])
self.assertIsNone(result['profit']) 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): def test_failure_does_not_hide_other_overview_fields(self):
with patch.object(rotation_accounting, 'view', side_effect=ValueError('test only')): with patch.object(rotation_accounting, 'view', side_effect=ValueError('test only')):
result = portfolio.overview() result = portfolio.overview()

View File

@ -111,6 +111,7 @@ class ChannelTest(unittest.TestCase):
self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3, self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3,
valid_until=9999999999999) valid_until=9999999999999)
with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \ 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(qmt_repo, 'claim_order', return_value=True), \
patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \ patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \
patch.object(qmt_repo, 'mark_send_attempt', return_value=False), \ 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')) self.loop.run_until_complete(self.runner._drain_outbox('unused'))
send.assert_not_called() 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): def test_send_error_after_attempt_keeps_uncertain_order_retryable(self):
from app.services import execution_conflicts from app.services import execution_conflicts
self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3, self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3,
valid_until=9999999999999) valid_until=9999999999999)
def attempted(_): self.row['sent_at'] = datetime.now(); return True def attempted(_): self.row['sent_at'] = datetime.now(); return True
with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \ 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(qmt_repo, 'claim_order', return_value=True), \
patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \ patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \
patch.object(qmt_repo, 'mark_send_attempt', side_effect=attempted), \ patch.object(qmt_repo, 'mark_send_attempt', side_effect=attempted), \

View File

@ -74,6 +74,7 @@ class StrategyOutboxTest(unittest.TestCase):
(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', {'new': True}), (settings, 'INFRA_STRATEGY_BOOK_SCHEMA', {'new': True}),
(qmt_repo, 'next_queued', {'return_value': [row]}), (qmt_repo, 'next_queued', {'return_value': [row]}),
(qmt_repo, 'get_order', {'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, 'claim_order', {'return_value': True}),
(qmt_repo, 'mark_send_attempt', {'return_value': True}), (qmt_repo, 'mark_send_attempt', {'return_value': True}),
(qmt_repo, 'mark_sent', {}), (qmt_repo, 'mark_sent', {}),

View File

@ -280,6 +280,23 @@ class ExecutionTests(unittest.TestCase):
row['created_at'] = NOW row['created_at'] = NOW
self.assertFalse(orders.should_replace(self.fake.instructions['P'], {'action': 'FIRE', 'limit_price': 10.1}, 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): def test_queued_order_rechecks_stop_before_sending(self):
row = self.child() row = self.child()
self.fake.instructions['P']['progress']['execution_basis_cache']['basis'] = fact(continuation='STOP') self.fake.instructions['P']['progress']['execution_basis_cache']['basis'] = fact(continuation='STOP')

View File

@ -312,7 +312,7 @@ class ServiceBoundaries(unittest.TestCase):
self.assertIn('600000.SH',s['target']) self.assertIn('600000.SH',s['target'])
self.assertEqual(len(s['target']),50) 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 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, 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'}} '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(executor,'cancel_instruction') as cancel, \
patch.object(r.db,'savepoint',side_effect=nullcontext): patch.object(r.db,'savepoint',side_effect=nullcontext):
result,waits=r.refresh_orders([parent],{},dt.datetime(2026,11,3,9,40),'v',{'600000.SH'},{}) 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() cancel.assert_not_called()
self.assertEqual(result,[]) self.assertEqual(result,[])
self.assertTrue(waits) self.assertEqual(waits, [])
def test_missing_quote_without_live_child_only_waits(self): def test_missing_quote_without_live_child_only_waits(self):
from app.services import rotation_execution as r, execution_orders as e from app.services import rotation_execution as r, execution_orders as e

View File

@ -39,11 +39,11 @@ class CostPrecisionTests(unittest.TestCase):
workbook = openpyxl.load_workbook(io.BytesIO( workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot)))) publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1'] sheet = workbook['Sheet1']
self.assertAlmostEqual(sheet['K5'].value, 48.296) self.assertAlmostEqual(sheet['L5'].value, 48.296)
self.assertEqual(sheet['K5'].number_format, '0.000') self.assertEqual(sheet['L5'].number_format, '0.000')
self.assertEqual(sheet['M5'].number_format, '0.000') self.assertEqual(sheet['N5'].number_format, '0.000')
self.assertEqual(sheet['G5'].number_format, '#,##0.00') self.assertEqual(sheet['G5'].number_format, '#,##0.00')
self.assertEqual(sheet['S5'].number_format, '#,##0.00') self.assertEqual(sheet['T5'].number_format, '#,##0.00')
self.assertTrue(any('未回报费用不视为零' in str(cell.value or '') self.assertTrue(any('未回报费用不视为零' in str(cell.value or '')
for row in sheet for cell in row)) for row in sheet for cell in row))
@ -111,14 +111,14 @@ class CostPrecisionTests(unittest.TestCase):
workbook = openpyxl.load_workbook(io.BytesIO( workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot)))) publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1'] sheet = workbook['Sheet1']
self.assertAlmostEqual(sheet['K5'].value * sheet['L5'].value, 14487.20) self.assertAlmostEqual(sheet['L5'].value * sheet['M5'].value, 14487.20)
self.assertEqual(sheet['K5'].number_format, '0.000') self.assertEqual(sheet['L5'].number_format, '0.000')
# 表格可编辑:成本、股数变化同时进入成本金额与盈亏,再进入小计和净值。 # 表格可编辑:成本、股数变化同时进入成本金额与盈亏,再进入小计和净值。
self.assertEqual(sheet['G5'].value, '=ROUND(K5*L5,2)') self.assertEqual(sheet['G5'].value, '=ROUND(L5*M5,2)')
self.assertEqual(sheet['Q5'].value, '=M5-K5') self.assertEqual(sheet['R5'].value, '=N5-L5')
self.assertEqual(sheet['S5'].value, '=ROUND(ROUND(M5*L5,2)-G5,2)') self.assertEqual(sheet['T5'].value, '=ROUND(H5-G5,2)')
self.assertEqual(sheet['G6'].value, '=SUM(G5:G5)') self.assertEqual(sheet['G6'].value, '=SUM(G5:G5)')
self.assertEqual(sheet['S6'].value, '=SUM(S5:S5)') self.assertEqual(sheet['T6'].value, '=SUM(T5:T5)')
def test_closed_average_keeps_amount_precision(self): def test_closed_average_keeps_amount_precision(self):
for qty, price, close_price in ((100, 48.290, 49.010), (200, 48.291, 49.011)): for qty, price, close_price in ((100, 48.290, 49.010), (200, 48.291, 49.011)):
@ -148,9 +148,9 @@ class CostPrecisionTests(unittest.TestCase):
workbook = openpyxl.load_workbook(io.BytesIO( workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot)))) publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1'] sheet = workbook['Sheet1']
self.assertEqual(sheet['K5'].value, 48.296) self.assertEqual(sheet['L5'].value, 48.296)
self.assertEqual(sheet['K8'].value, 48.296) self.assertEqual(sheet['L8'].value, 48.296)
self.assertEqual(sheet['M8'].value, 49.011) self.assertEqual(sheet['N8'].value, 49.011)
def test_half_cent_cost_matches_workbook_round_without_rounding_unit_cost(self): def test_half_cent_cost_matches_workbook_round_without_rounding_unit_cost(self):
self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1, self.fake.insert_lot(ts_code='002979.SZ', lot_type='BASE', qty=1,
@ -164,9 +164,9 @@ class CostPrecisionTests(unittest.TestCase):
workbook = openpyxl.load_workbook(io.BytesIO( workbook = openpyxl.load_workbook(io.BytesIO(
publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot)))) publish_export.build_workbook(snapshot, publish_export._nav_series(snapshot))))
sheet = workbook['Sheet1'] sheet = workbook['Sheet1']
self.assertEqual(sheet['K5'].value, 48.285) self.assertEqual(sheet['L5'].value, 48.285)
self.assertEqual(sheet['G5'].value, '=ROUND(K5*L5,2)') self.assertEqual(sheet['G5'].value, '=ROUND(L5*M5,2)')
self.assertEqual(sheet['S5'].value, '=ROUND(ROUND(M5*L5,2)-G5,2)') self.assertEqual(sheet['T5'].value, '=ROUND(H5-G5,2)')
def test_multiple_lots_accumulate_before_half_cent_rounding(self): def test_multiple_lots_accumulate_before_half_cent_rounding(self):
for price in (48.281, 48.284): for price in (48.281, 48.284):

View File

@ -85,6 +85,7 @@ class IntradayEntry(TestCase):
def test_wire_freeze_then_sell(self): def test_wire_freeze_then_sell(self):
self.mock(eo,'account_guard',side_effect=nullcontext) self.mock(eo,'account_guard',side_effect=nullcontext)
self.mock(eo.qmt_repo,'get_order',return_value=self.order) 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.pms_repo,'get_instruction',return_value=self.parent)
self.mock(eo,'correction_blocker',return_value='') self.mock(eo,'correction_blocker',return_value='')
self.mock(eo.policy,'local_now',return_value=self.now) self.mock(eo.policy,'local_now',return_value=self.now)
@ -187,6 +188,22 @@ class IntradayEntry(TestCase):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
trade.send_intent(intent,0,self.now,self.release['snapshot_version']) trade.send_intent(intent,0,self.now,self.release['snapshot_version'])
self.assertEqual(len(wire),1) 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): def test_standing_cancel_keeps_user_controls(self):
from app.services import rotation_day_orders as day from app.services import rotation_day_orders as day

View File

@ -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()

View File

@ -86,6 +86,32 @@ class BookingTests(unittest.TestCase):
self.assertFalse(rotation_execution.book_trade(self.act, [], 1)) self.assertFalse(rotation_execution.book_trade(self.act, [], 1))
self.assertEqual(self.state(), before) 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): def test_lineage_write_failure_rolls_back_entire_booking(self):
before = self.state() before = self.state()
with patch.object(trade_lineage.rotation_repo, 'put_once', side_effect=RuntimeError('storage fault')): with patch.object(trade_lineage.rotation_repo, 'put_once', side_effect=RuntimeError('storage fault')):

View File

@ -2876,15 +2876,18 @@ def _():
# 2 行持仓 → 5,6 行; 小计 7; 卖出头 8; 明细 9; 小计 10; 汇总 11/12 # 2 行持仓 → 5,6 行; 小计 7; 卖出头 8; 明细 9; 小计 10; 汇总 11/12
assert ws["E5"].value == "000001" and ws["E6"].value == "600000", ( assert ws["E5"].value == "000001" and ws["E6"].value == "600000", (
ws["E5"].value, ws["E6"].value) # 按最早开仓日排序 ws["E5"].value, ws["E6"].value) # 按最早开仓日排序
assert ws["L6"].value == 2000 and ws["D5"].value == "测试账户" assert ws["M6"].value == 2000 and ws["D5"].value == "测试账户"
assert ws["U5"].value == "=1+T5" and ws["S5"].value == "=ROUND(ROUND(M5*L5,2)-G5,2)" assert [ws[f"{col}4"].value for col in 'GHI'] == ['交易金额(元)', '市值(元)', '起始时间']
assert ws["V5"].value == "=1+U5" and ws["T5"].value == "=ROUND(H5-G5,2)"
assert ws["H5"].value == "=ROUND(N5*M5,2)" and ws["H7"].value == "=SUM(H5:H6)"
assert ws["H9"].value is None and ws["H11"].value == "=H7"
assert ws["C8"].value == "序" + chr(10) + "号", repr(ws["C8"].value) assert ws["C8"].value == "序" + chr(10) + "号", repr(ws["C8"].value)
assert ws["S9"].value == 987.5 and ws["T9"].value == "=IF(G9=0,0,S9/G9)" assert ws["T9"].value == 987.5 and ws["U9"].value == "=IF(G9=0,0,T9/G9)"
assert ws["G7"].value == "=SUM(G5:G6)" and ws["G10"].value == "=SUM(G9:G9)" assert ws["G7"].value == "=SUM(G5:G6)" and ws["G10"].value == "=SUM(G9:G9)"
assert ws["S11"].value == "=S7+S10" and ws["F12"].value.startswith("=1000000") assert ws["T11"].value == "=T7+T10" and ws["F12"].value.startswith("=1000000")
assert ws["O12"].value == "=U11" and ws["Q12"].value == "=U11" assert ws["P12"].value == "=V11" and ws["R12"].value == "=V11"
merges = {str(r) for r in ws.merged_cells.ranges} merges = {str(r) for r in ws.merged_cells.ranges}
assert {"B1:T1", "B4:B7", "B8:B10", "B11:F11", "B12:E12"} <= merges, merges assert {"B1:V1", "B4:B7", "B8:B10", "B11:F11", "B12:E12"} <= merges, merges
# 两个竖排段落标签必须都在 (模板裁剪曾把「平层卖出」丢过一次, 钉死) # 两个竖排段落标签必须都在 (模板裁剪曾把「平层卖出」丢过一次, 钉死)
assert ws["B4"].value == "平层" + chr(10) + "持仓", repr(ws["B4"].value) assert ws["B4"].value == "平层" + chr(10) + "持仓", repr(ws["B4"].value)
assert ws["B8"].value == "平层" + chr(10) + "卖出", repr(ws["B8"].value) assert ws["B8"].value == "平层" + chr(10) + "卖出", repr(ws["B8"].value)
@ -2916,20 +2919,21 @@ def _():
open_date=d0, close_date=d1, structure="平层", cost=8.0, qty=1000, open_date=d0, close_date=d1, structure="平层", cost=8.0, qty=1000,
settle=8.2, days=6, pnl=200.0 - 40.0 * i) for i in range(10)] settle=8.2, days=6, pnl=200.0 - 40.0 * i) for i in range(10)]
s2 = dict(s, holdings=mkh, closed=mkc, price_missing=[], fee_resid=0.0) s2 = dict(s, holdings=mkh, closed=mkc, price_missing=[], fee_resid=0.0)
blob2 = pub.build_workbook(s2, [{"ymd": ymd, "nav": 1.001, "pos_ratio": 0.35}]) blob2 = pub.build_workbook(s2, [{"ymd": int(d1.strftime('%Y%m%d')), "nav": 1.001, "pos_ratio": 0.35},
{"ymd": ymd, "nav": 1.002, "pos_ratio": 0.40}])
wb2 = openpyxl.load_workbook(_io.BytesIO(blob2)) wb2 = openpyxl.load_workbook(_io.BytesIO(blob2))
ws2 = wb2["Sheet1"] ws2 = wb2["Sheet1"]
# 行位: 持仓 5..11, 小计 12, 卖出头 13, 明细 14..23, 小计 24, 存量 25, 底行 26 # 行位: 持仓 5..11, 小计 12, 卖出头 13, 明细 14..23, 小计 24, 存量 25, 底行 26
assert ws2.cell(row=24, column=7).value == "=SUM(G14:G23)", ws2.cell(row=24, column=7).value assert ws2.cell(row=24, column=7).value == "=SUM(G14:G23)", ws2.cell(row=24, column=7).value
assert ws2.cell(row=25, column=2).value == "存量合计", ws2.cell(row=25, column=2).value assert ws2.cell(row=25, column=2).value == "存量合计", ws2.cell(row=25, column=2).value
assert ws2.cell(row=25, column=19).value == "=S12+S24" assert ws2.cell(row=25, column=20).value == "=T12+T24"
assert ws2.cell(row=26, column=2).value == "初始规模+已回收益后可开仓总金额" assert ws2.cell(row=26, column=2).value == "初始规模+已回收益后可开仓总金额"
assert ws2.cell(row=26, column=17).value == "=U25" assert ws2.cell(row=26, column=18).value == "=V25"
assert not [r0 for r0, dd in ws2.row_dimensions.items() if dd.hidden], "行不许隐藏" assert not [r0 for r0, dd in ws2.row_dimensions.items() if dd.hidden], "行不许隐藏"
assert max(ws2.row_dimensions) <= 26, max(ws2.row_dimensions) assert max(ws2.row_dimensions) <= 26, max(ws2.row_dimensions)
assert ws2.row_dimensions[25].height == 18.0 and ws2.row_dimensions[26].height == 40.5 assert ws2.row_dimensions[25].height == 18.0 and ws2.row_dimensions[26].height == 40.5
cfsq = sorted(str(cf.sqref) for cf in ws2.conditional_formatting) cfsq = sorted(str(cf.sqref) for cf in ws2.conditional_formatting)
assert cfsq == sorted(["Q5:R11", "S5:S11", "Q14:S23", "S12 S24"]), cfsq assert cfsq == sorted(["R5:S11", "T5:T11", "R14:T23", "T12 T24"]), cfsq
zf2 = _zip.ZipFile(_io.BytesIO(blob2)) zf2 = _zip.ZipFile(_io.BytesIO(blob2))
sx2 = zf2.read("xl/worksheets/sheet1.xml").decode("utf-8") sx2 = zf2.read("xl/worksheets/sheet1.xml").decode("utf-8")
assert not _re.search('<row [^>]*hidden="1"', sx2), "导出的行带着隐藏标记" assert not _re.search('<row [^>]*hidden="1"', sx2), "导出的行带着隐藏标记"
@ -2938,6 +2942,13 @@ def _():
assert 'symbol val="circle"' in cx2 and 'symbol val="diamond"' in cx2 assert 'symbol val="circle"' in cx2 and 'symbol val="diamond"' in cx2
assert '<plotVisOnly val="0"' in cx2, "隐藏单元格也必须照画" assert '<plotVisOnly val="0"' in cx2, "隐藏单元格也必须照画"
assert cx2.count("<valAx>") == 2 # 仓位占比走副轴 assert cx2.count("<valAx>") == 2 # 仓位占比走副轴
chart = ws2._charts[0]
assert (chart.anchor._from.col, chart.anchor.to.col) == (1, 22)
assert chart.series[0].dLbls.showVal and chart.series[0].dLbls.numFmt == '0.0000'
assert chart.series[0].dLbls.showCatName is False and chart.series[0].dLbls.showLegendKey is False
assert chart._charts[1].series[0].dLbls is None
nav_formula = chart.series[0].val.numRef.f
assert nav_formula.endswith('$AA$30:$AA$31'), nav_formula
def main(): def main():