diff --git a/DEVLOG.md b/DEVLOG.md index 3a80d77..3ab9e14 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -1,5 +1,11 @@ # 开发节点记录(三系统量化交易) +## 2026年11月16日 试探预算工作包实现 + +按用户“开始推进”实施预算01至09:原预算独立保存、最低申报不扩大、强制试探同步重算、自动与人工采纳共用约束、报价和部分成交重新核算、账户锁内落单复核、旧进度回写保留已批准预算。历史试探本轮暂停自动新增,真实用户命令独立核验,正常卖出和既有做T回补继续。无DDL,无参数或账本迁移。 + +开发机Python3.12预算专项41项、batch51的38项隔离通过;全量及候选发布回执后续追加。10:43只读当前持仓及旧计划并断网计算影响:雷赛、宁德、药明本轮自动加仓暂停,中文在线既有待复核计划受预算约束,四方标准仓网格保留原规则。宁德旧记录试探标签与标准比例不一致,药明曾抬最低股数,均用原记录保守约束且不改历史。细节见[实现与验收](docs/试探预算约束实现与验收_2026-11-16.md)。 + ## 2026年11月12日14:56 统一入池历史补齐发布 用户要求机器选入与人工关注都经过数据补齐完成资金相关准备。核实gp_stk_mins_1min足以重建分钟量价及成交额,独立分钟资金净额来自另一数据源;纠正此前“分钟历史不足”的泛化表述。188三个ITD服务发布a217dac,共用持久任务、后台逐票构建、重启恢复、失败退避及按项读取,盘中循环不等待历史构建;原阈值及权重保持。 diff --git a/app/core/action_engine.py b/app/core/action_engine.py index 738580e..b129eb1 100644 --- a/app/core/action_engine.py +++ b/app/core/action_engine.py @@ -895,6 +895,7 @@ def eval_open(c: dict, params: dict, caps: dict, room_amt: float): # ---- 仓位口径: 只进评审账本做判分锚。judge.py 送研判时会把这几项过滤掉, # 理由见那边的 OPEN_JUDGE_KEYS —— 决策系统本来就不管仓位, 别送过去带偏它。 "target_pct": target_pct, "target_amount": round(full_amt, 2), + "sizing_scale": scale, "requested_budget": round(want, 2), "base_amount": round(qty * price, 2), "batch_scheme": ",".join(str(x) for x in (sp.get("scheme") or ())), "names_before": caps.get("names_count"), "max_names": caps.get("max_names"), diff --git a/app/core/buy_budget.py b/app/core/buy_budget.py new file mode 100644 index 0000000..735eed4 --- /dev/null +++ b/app/core/buy_budget.py @@ -0,0 +1,95 @@ +"""建仓资金预算。金额与股数分开保存;预算不因取整、报价或重评而增加。""" +from decimal import Decimal, InvalidOperation, ROUND_FLOOR +from hashlib import sha256 +import json +from app.core.sizer import lot_of + +VERSION = 1 + + +def number(value, label, *, zero=False): + try: + result = Decimal(str(value)) + except (InvalidOperation, ValueError, TypeError): + raise ValueError(label+'不可核实') from None + if not result.is_finite() or (result < 0 if zero else result <= 0): + raise ValueError(label+'不可核实') + return result + + +def quantity(amount, price, code): + value = int((number(amount, '剩余预算', zero=True) / number(price, '买入价格') / 100).to_integral_value(rounding=ROUND_FLOOR)) * 100 + return value if value >= lot_of(code) else 0 + + +def identity(value): + body = {k: v for k, v in value.items() if k != 'revision'} + return sha256(json.dumps(body, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()).hexdigest()[:24] + + +def validate(value, code): + if not isinstance(value, dict) or value.get('version') != VERSION or value.get('ts_code') != code: + raise ValueError('建仓预算版本或证券不一致,等待核实') + number(value.get('amount'), '原建仓预算') + number(value.get('scale'), '原建仓规模') + number(value.get('target_pct'), '原目标比例') + q = number(value.get('quantity_limit'), '计划数量', zero=True) + if q != int(q) or int(q) % 100 or value.get('revision') != identity(value): + raise ValueError('建仓预算内容已变化,等待重新核实') + return value + + +def resize(advice, hard, code): + """返回完整重算结果;数量0是明确不建仓,必要读数缺失则抛错。""" + from app.core.execution_policy import supported_code + if not supported_code(code): + raise ValueError('建仓预算只适用于沪深合资格证券') + price = number(hard.get('price'), '买入价格') + pct = number(advice.get('target_pct'), '目标比例') + if pct > 1: + raise ValueError('目标比例超出有效范围,暂不建仓') + if advice.get('tier') == '试探仓': + # 旧 force_trial 只换标签,曾保留标准仓比例;按保存的原机械比例核实。 + mechanical = number((advice.get('mechanical') or {}).get('target_pct'), '原机械目标比例') + pct = min(pct, mechanical / 6) + old = hard.get('buy_budget') + if old is not None: + validate(old, code) + scale = number(old['scale'], '原建仓规模') + amount = min(number(old['amount'], '原建仓预算'), scale * pct) + else: + scale = (number(hard['sizing_scale'], '原建仓规模') if hard.get('sizing_scale') is not None + else number(hard.get('target_amount'), '目标金额') / number(hard.get('target_pct'), '原目标比例')) + amount = scale * pct + amount = amount.quantize(Decimal('.01'), rounding=ROUND_FLOOR) + if amount <= 0: + raise ValueError('建仓预算不足一分钱,暂不建仓') + trial = advice.get('tier') == '试探仓' or (old and old.get('tier') == '试探仓') + splits = (1.0,) if trial else tuple(advice.get('splits') or (1.0,)) + ratios = [number(v, '分批比例') for v in splits] + if abs(sum(ratios)-1) > Decimal('.00000001'): + raise ValueError('分批比例不完整,暂不建仓') + quantities = [quantity(amount*r, price, code) for r in ratios] + executable = all(quantities) + first = quantities[0] if executable else 0 + maximum = sum(quantities) if executable else 0 + budget = {'version': VERSION, 'ts_code': code, 'amount': str(amount), 'scale': str(scale), + 'target_pct': str(amount/scale), 'quantity_limit': maximum, + 'tier': old['tier'] if old and old.get('tier') == '试探仓' else advice.get('tier'), + 'basis': '买入成交金额,不含另记的交易费用'} + budget['revision'] = identity(budget) + minimum_amount = price * lot_of(code) + reason = '' if first else f'当前预算{amount:.2f}元不足分批最低买入量,暂不建仓(每批最低{lot_of(code)}股,需{minimum_amount:.2f}元)' + return {'qty': first, 'target_pct': float(amount/scale), 'target_amount': float(amount), + 'minimum_order_amount': float(minimum_amount), + 'base_amount': float(first*price), 'batch_scheme': ','.join(str(v) for v in splits), + 'buy_budget': budget, 'note': reason} + + +def check_quantity(budget, code, qty, price): + validate(budget, code) + count = number(qty, '计划数量') + if count != int(count) or int(count) % 100 or int(count) < lot_of(code): + raise ValueError('预算内数量不足最低买入量,暂不建仓') + if count > int(budget['quantity_limit']) or count*number(price, '买入价格') > number(budget['amount'], '原建仓预算'): + raise ValueError('计划数量或金额超过原建仓预算,需重新明确预算后再参与') diff --git a/app/db/session.py b/app/db/session.py index 97f3ea1..b7b2d2d 100644 --- a/app/db/session.py +++ b/app/db/session.py @@ -381,6 +381,13 @@ def publish_prepared_proposal(old, candidate, verdict): if (hard.get('preparation') or {}).get('status') != 'ready' or not hard.get('consumption_id'): raise ValueError('准备结果缺少完整依据或消费凭据') old_hard = old.get('hard_numbers') or {} + if old_hard.get('buy_budget') is not None: + from app.core.buy_budget import validate, number + previous = validate(old_hard['buy_budget'], old['ts_code']) + current = validate(hard.get('buy_budget'), old['ts_code']) + if (number(current['amount'], '建仓预算') > number(previous['amount'], '原建仓预算') + or (previous.get('tier') == '试探仓' and current.get('tier') != '试探仓')): + raise ValueError('后台更新不能提高原建仓预算或升级试探仓') audit = dict(hard, previous_proposal={'qty': old['qty'], 'decision': old_hard.get('decision'), 'consumption_id': old_hard.get('consumption_id'), 'proposal_revision': old_hard.get('proposal_revision'), 'judge_verdict': old.get('judge_verdict'), 'judge_reason': old.get('judge_reason')}) @@ -414,7 +421,7 @@ def accept_open_proposal(old, hard, instruction, reason): encode = lambda v: json.dumps(v, ensure_ascii=False, default=str) now = datetime.now() _check_cooldown('proxy') - with get_engine('proxy').begin() as c: + with transaction() as c: def query(sql, params): sql = map_tables(sql) assert_single_table(sql) diff --git a/app/repo/pms_repo.py b/app/repo/pms_repo.py index 26a6495..351c82b 100644 --- a/app/repo/pms_repo.py +++ b/app/repo/pms_repo.py @@ -230,6 +230,10 @@ def list_plans(*, command_id=None, statuses=None, ts_code=None, limit: int = 500 return fetch_all(sql, p) +def get_plan(plan_id: str): + return fetch_one('SELECT * FROM pms_plan WHERE plan_id=:pid', {'pid': plan_id}) + + def update_plan(plan_id: str, *, status=None, filled_qty=None) -> int: sets, p = ["updated_at = :ts"], {"pid": plan_id, "ts": _NOW()} if status is not None: @@ -478,10 +482,12 @@ def update_instruction(instruction_id: str, *, status=None, exec_qty=None, exec_ body = ("CASE WHEN JSON_CONTAINS_PATH(COALESCE(progress_json,JSON_OBJECT())," f"'one','$.{key}') THEN JSON_SET(JSON_EXTRACT({body},'$')," f"'$.{key}',JSON_EXTRACT(progress_json,'$.{key}')) ELSE {body} END") - body = ("CASE WHEN JSON_CONTAINS_PATH(COALESCE(progress_json,JSON_OBJECT())," - "'one','$.execution_basis_cache') THEN JSON_SET(JSON_EXTRACT("+body+",'$')," - "'$.execution_basis_cache',JSON_EXTRACT(progress_json,'$.execution_basis_cache')) " - 'ELSE '+body+' END') + # 已批准预算不可由执行回写或次日重评改大;显式新命令使用新的父指令。 + for key in ('execution_basis_cache', 'buy_budget'): + body = ("CASE WHEN JSON_CONTAINS_PATH(COALESCE(progress_json,JSON_OBJECT())," + f"'one','$.{key}') THEN JSON_SET(JSON_EXTRACT("+body+",'$')," + f"'$.{key}',JSON_EXTRACT(progress_json,'$.{key}')) " + 'ELSE '+body+' END') sets.append('progress_json = '+body) p["pg"] = _dumps(progress) guard = " AND status IN ('PROPOSED','RULE_PASSED','JUDGE_PASSED','DISPATCHED')" if status == 'DISPATCHED' else '' diff --git a/app/services/advice_service.py b/app/services/advice_service.py index e34a62d..e9b578e 100644 --- a/app/services/advice_service.py +++ b/app/services/advice_service.py @@ -197,68 +197,14 @@ def apply_judge(adv: Optional[dict], judge: Optional[dict], conf_min: int = 60) def resize_to_advice(adv: Optional[dict], hn: Optional[dict], ts_code: str) -> tuple: - """按建议档位把这一批的股数重算一遍。返回 (改动字典, 说明);不该改或算不出时返回 (None, 原因)。 - - ## 为什么需要它 - - 候选产出时 advise() 的档位是**进过**数量的(params_for 把 target_pct 塞进 - stock_target_default,action_engine 据此拆批)。但研判回来之后 apply_judge 还会 - 再降一档 —— 把握度低或结论不可用就降成试探仓 —— 而那一步只改档位文字,数量已经 - 算完了,于是卡上写的和真下的对不上。 - - 2026-09-10 实测:155 上 8 张待确认提议,7 张写着「试探仓(目标 1.0%)」, - 而每一张实际都会买 3.00%(标准仓 6% 的第一批),正好三倍。 - apply_judge 的函数说明原文是「不改数量, 数量交人」,但页面上采纳按钮根本没有 - 填数量的地方,这个「交人」无处兑现;采纳时后端直接抄提议里的股数原样落单。 - - ## 总规模从哪来 - - 不另外去读参数表,直接从硬数字里已有的两个数反推:target_amount 是整只目标金额、 - target_pct 是它占的比例,相除就是总规模。这样不会出现「重算用的规模」与 - 「当初算数量用的规模」不是同一个数的情况。 - - ## 买不足一手怎么办 - - 抬到一手,但一手的金额不许超过机械档的目标金额。试探仓的本意是小仓位试水, - 100 股 264 元的票是 1.32%(仍远小于 6%),抬上去是合理的;而如果一手就已经 - 超过机械档,说明这只票对当前规模本来就太贵,那就不改数量、交回调用方处置。 - """ - from app.core.sizer import lot_of, split_batches - + """按原资金预算向下取整;失败必须由调用方阻断,不再沿用旧数量。""" if not isinstance(adv, dict) or not isinstance(hn, dict): return None, "没有建议方案或硬数字" - new_pct = _f(adv.get("target_pct")) - old_pct = _f(hn.get("target_pct")) - price = _f(hn.get("price")) - old_amt = _f(hn.get("target_amount")) - if new_pct <= 0 or old_pct <= 0 or price <= 0 or old_amt <= 0: - return None, "缺少重算所需的读数(现价、目标金额或目标仓位)" - if abs(new_pct - old_pct) < 1e-9: - return None, "档位没变,不用重算" - - scale = old_amt / old_pct - want = scale * new_pct - lot = lot_of(ts_code) - splits = tuple(adv.get("splits") or (1.0,)) - # merge=False: 试探仓本来就是一次买满 (splits=(1.0,)), 不要让降档梯子把它改成别的分批。 - sp = split_batches(want, price, splits=splits, merge=False, min_lot=lot) - if sp.get("ok"): - qty = int(sp["batches"][0]["qty"]) - full = sum(b["qty"] * price for b in sp["batches"]) - return {"qty": qty, "target_pct": round(new_pct, 4), "target_amount": round(full, 2), - "base_amount": round(qty * price, 2), - "batch_scheme": ",".join(str(x) for x in splits), "note": ""}, "" - - mech_pct = _f((adv.get("mechanical") or {}).get("target_pct"), old_pct) - mech_amt = scale * mech_pct - one_lot_amt = lot * price - if one_lot_amt > mech_amt: - return None, (f"一手 {lot} 股就要 {one_lot_amt:,.0f} 元," - f"超过机械档的 {mech_amt:,.0f} 元({mech_pct:.0%}),这只票对当前规模太贵") - return {"qty": lot, "target_pct": round(one_lot_amt / scale, 4), - "target_amount": round(one_lot_amt, 2), "base_amount": round(one_lot_amt, 2), - "batch_scheme": "1.0", - "note": f"目标 {want:,.0f} 元买不足一手,抬到一手 {lot} 股({one_lot_amt / scale:.2%})"}, "" + from app.core.buy_budget import resize + try: + return resize(adv, hn, ts_code), "" + except ValueError as exc: + return None, "缺少重算所需的读数或预算无法核实:" + str(exc) def params_for(adv: dict, params: dict) -> dict: diff --git a/app/services/buy_budget.py b/app/services/buy_budget.py new file mode 100644 index 0000000..6fdd34d --- /dev/null +++ b/app/services/buy_budget.py @@ -0,0 +1,236 @@ +"""试探预算贯穿提议、父指令和真实委托;不另外冻结或重复扣账户现金。""" +from copy import deepcopy +from decimal import Decimal +from app.core import buy_budget as core, strategy_book as books +from app.repo import pms_repo, qmt_repo +from config.settings import settings + +LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW') + + +def from_hard(hard, code): + if hard.get('buy_budget') is not None: + return deepcopy(core.validate(hard['buy_budget'], code)) + advice = hard.get('advice') + if advice is None and hard.get('sizing_scale') is not None: + advice = {'tier': '标准仓', 'target_pct': hard.get('target_pct'), + 'splits': tuple(str(hard.get('batch_scheme') or '1.0').split(','))} + if isinstance(advice, dict): + return core.resize(advice, hard, code)['buy_budget'] + return None + + +def candidate(hard, code, qty, price=None): + budget = from_hard(hard, code) + if budget is not None: + core.check_quantity(budget, code, qty, price if price is not None else hard.get('price')) + elif settings.INFRA_STRATEGY_BOOK_SCHEMA: + raise ValueError('缺少可追溯的建仓预算,暂不建仓') + return budget + + +def _source_hard(parent): + prog = parent.get('progress') or {} + refs = [parent['instruction_id']] + if parent.get('origin_type') == 'proposal' and parent.get('origin_id'): + refs.append(parent['origin_id']) + if prog.get('from_proposal'): + refs.append(prog['from_proposal']) + rows = pms_repo.ledger_by_ref(refs, limit=1001) + if len(rows) >= 1001: + raise ValueError('原建仓审计超过核验范围,暂停新增买入') + values = [r.get('hard_numbers') or {} for r in rows + if r.get('verdict') == 'PASS' and r.get('action') == 'OPEN'] + values = [v for v in values if v.get('advice') or v.get('buy_budget')] + if not values: + # 老提议的保存内容只能用于已明确关联的父指令,不能拿当天新建议补旧预算。 + for ref in dict.fromkeys(refs[1:]): + p = pms_repo.get_proposal(ref) + if p and p.get('status') == 'ACCEPTED' and p.get('ts_code') == parent['ts_code']: + h = p.get('hard_numbers') or {} + if h.get('advice') or h.get('buy_budget'): + values.append(h) + if not values: + return None + # 同一来源有试探证据时采用较小预算,重评不能把旧试探变成标准仓。 + trials = [h for h in values if (h.get('advice') or h.get('buy_budget') or {}).get('tier') == '试探仓'] + if trials: + return min(trials, key=lambda h: core.number(from_hard(h, parent['ts_code'])['amount'], '原建仓预算')) + return values[0] + + +def explicit_command(parent): + """命令身份来自真实命令和方案;网格、做T的is_command不构成扩大预算授权。""" + if parent.get('origin_type') != 'plan' or not parent.get('origin_id'): + return False + plan = pms_repo.get_plan(parent['origin_id']) + if not plan or plan.get('ts_code') != parent['ts_code']: + return False + command = pms_repo.get_command(plan.get('command_id')) + issuer = str((command or {}).get('issued_by') or '') + return bool(command and issuer and issuer not in ('rotation', 'system', 'auto') + and not issuer.startswith('macro') + and command.get('cmd_type') in ('OPEN_TARGET', 'INCREASE_EXPOSURE')) + + +def parent_budget(parent): + if parent.get('side') != 'buy' or parent.get('book_id', books.ORIGINAL) != books.ORIGINAL: + return None + prog = parent.get('progress') or {} + if prog.get('buy_budget') is not None: + return deepcopy(core.validate(prog['buy_budget'], parent['ts_code'])) + if explicit_command(parent): + plan = pms_repo.get_plan(parent['origin_id']) + amount = core.number(plan.get('amount'), '命令计划预算') + value = {'version': core.VERSION, 'ts_code': parent['ts_code'], 'amount': str(amount), + 'scale': str(amount), 'target_pct': '1', 'quantity_limit': int(plan['qty']), + 'tier': '用户命令', 'command_id': plan['command_id'], 'plan_id': parent['origin_id'], + 'basis': '命令批准的买入成交金额,不含另记的交易费用'} + value['revision'] = core.identity(value) + return core.validate(value, parent['ts_code']) + if not settings.INFRA_STRATEGY_BOOK_SCHEMA: + return None + if parent.get('action') == 'OPEN' and parent.get('origin_type') != 'strategy': + hard = _source_hard(parent) + if hard is None: + raise ValueError('旧建仓指令的原预算无法核实,停止续买,等待重新明确计划') + return from_hard(hard, parent['ts_code']) + return None + + +def _holding_blocker(code, *, parent_id=None): + """当前轮次只要仍有试探仓,不经明确新命令扩大;底仓卖光也不解除。""" + if not settings.INFRA_STRATEGY_BOOK_SCHEMA or books.CURRENT.get() != books.ORIGINAL: + return '' + pending = pms_repo.list_instructions(ts_code=code, side='buy', statuses=LIVE, limit=1001) + if len(pending) >= 1001: + return '买入安排超过完整核验范围,暂停自动加仓' + for other in pending: + if other['instruction_id'] == parent_id or other.get('action') != 'OPEN': + continue + limit = parent_budget(other) + if limit and limit.get('tier') == '试探仓': + return '该股已有试探建仓安排,不能从其他路径重复增加投入' + position = pms_repo.get_position(code) or {} + if int(position.get('total_qty') or 0) <= 0: + return '' + opened = str(position.get('opened_date') or '')[:10] + if not opened: + return '本轮持仓的建仓预算尚未核实,暂停自动加仓' + lots = pms_repo.list_lots(code, status='', limit=2001) + if len(lots) >= 2001: + return '持仓批次超过完整核验范围,暂停自动加仓' + active = [r for r in lots if r.get('status') == 'OPEN' and int(r.get('qty') or 0) > 0] + if sum(int(r['qty']) for r in active) != int(position['total_qty']): + return '持仓与批次数量待核对,暂停自动加仓' + roots = {} + for lot in lots: + if str(lot.get('open_date') or '')[:10] < opened or lot.get('lot_type') != 'BASE': + continue + pid = lot.get('instruction_id') + if not pid: + return '本轮底仓来源无法核实,暂停自动加仓' + parent = pms_repo.get_instruction(pid) + if not parent or parent.get('book_id', books.ORIGINAL) != books.ORIGINAL or parent.get('ts_code') != code: + return '本轮底仓归属无法核实,暂停自动加仓' + roots[pid] = parent + if not roots: + return '本轮建仓依据尚未核实,暂停自动加仓' + for pid, parent in roots.items(): + if explicit_command(parent): + continue + budget = parent_budget(parent) + if budget is None: + return '本轮原建仓预算尚未核实,暂停自动加仓' + if budget.get('tier') == '试探仓' and pid != parent_id: + return '本轮为试探仓,暂停网格及其他自动加仓;扩大投入须明确新的买入命令' + return '' + + +def holding_blocker(code, *, parent_id=None): + # 缺预算只暂停新增;不得因为查询失败而挡住同一轮的正常网格卖出。 + try: + return _holding_blocker(code, parent_id=parent_id) + except ValueError as exc: + return str(exc) + except Exception: + import logging + logging.getLogger('pms.buy_budget').exception('核对持仓建仓预算失败 %s', code) + return '本轮建仓预算暂不可核实,暂停自动加仓;已有卖出安排继续' + + +def before_parent(code, *, action='OPEN', exclude=None): + blocked = holding_blocker(code) + if blocked: + raise ValueError(blocked) + if settings.INFRA_STRATEGY_BOOK_SCHEMA and action == 'OPEN': + parents = pms_repo.list_instructions(ts_code=code, side='buy', statuses=LIVE, limit=1001) + if len(parents) >= 1001 or any(p['instruction_id'] != exclude for p in parents): + raise ValueError('该股已有买入安排,不能重复分配建仓预算') + + +def allowed_quantity(parent, price, requested): + """按已确认成交与原预算限制本次报价;调用方在落单锁内再次执行。""" + if parent.get('side') != 'buy' or parent.get('book_id', books.ORIGINAL) != books.ORIGINAL: + return int(requested), '' + from app.services import execution_orders + code = parent['ts_code'] + prog = parent.get('progress') or {} + budget = parent_budget(parent) + # 平回做T只恢复先前卖出的库存;新增腿仍受持仓预算约束。 + closing = prog.get('stype') == 'T0' and prog.get('leg') == 'close' + if not explicit_command(parent) and not closing: + blocked = holding_blocker(code, parent_id=parent['instruction_id']) + if blocked: + return 0, blocked + if budget is None: + return int(requested), '' + state = execution_orders.replacement_state(parent['instruction_id']) + if not state['ready']: + return 0, '原委托或成交尚未结清,不能释放建仓预算' + spent = Decimal(0) + if state['confirmed_filled']: + # 逐笔批次保留实际成交价,包含已卖出的份额;不以当前市值或四舍五入的均价释放额度。 + lots = pms_repo.list_lots(code, status='', limit=2001) + if len(lots) >= 2001: + raise ValueError('实际成交批次超过完整核验范围,停止续买') + filled = 0 + for lot in lots: + if lot.get('instruction_id') != parent['instruction_id']: + continue + remaining_qty = core.number(lot.get('qty'), '批次剩余数量', zero=True) + closed_qty = core.number(lot.get('closed_qty', 0), '批次已卖数量', zero=True) + done = remaining_qty + closed_qty + if done != int(done): + raise ValueError('批次数量不可核实,停止续买') + if done: + spent += done * core.number(lot.get('open_price'), '实际成交价格') + filled += int(done) + if filled != state['confirmed_filled']: + raise ValueError('实际成交批次与委托累计量不一致,停止释放预算') + remaining = max(Decimal(0), core.number(budget['amount'], '原建仓预算') - spent) + count = min(int(requested), state['remaining'], core.quantity(remaining, price, code), + max(0, int(budget['quantity_limit']) - state['confirmed_filled'])) + from app.core.sizer import lot_of + count = count // 100 * 100 + if count < lot_of(code): + return 0, '原建仓预算的剩余额度不足最低买入量,停止续买' + return count, '' + + +def check_order(parent, payload): + count, reason = allowed_quantity(parent, payload['limit_price'], payload['qty']) + if count != int(payload['qty']): + raise ValueError(reason or '本次报价超过原建仓预算,需减少数量后重新检查') + + +def accept_open(old, hard, instruction, reason): + from app.services import execution_orders + with execution_orders.account_guard(): + budget = candidate(hard, old['ts_code'], old['qty']) + before_parent(old['ts_code']) + if budget is not None: + hard = dict(hard, buy_budget=budget) + instruction = deepcopy(instruction) + instruction['progress']['buy_budget'] = budget + return pms_repo.accept_open_proposal(old, hard, instruction, reason) diff --git a/app/services/dispatcher.py b/app/services/dispatcher.py index 851f490..3a1dc38 100644 --- a/app/services/dispatcher.py +++ b/app/services/dispatcher.py @@ -205,9 +205,15 @@ def dispatch(*, instruction_id: str, ts_code: str, side: str, qty: int, limit_pr if boundary is not None and ((side == 'buy' and float(limit_price) > float(boundary)) or (side == 'sell' and float(limit_price) < float(boundary))): raise ValueError('报价突破用户指定价格边界') + if side == 'buy' and not settings.INFRA_STRATEGY_BOOK_SCHEMA and parent: + from app.services.buy_budget import check_order + check_order(parent, {'qty': qty, 'limit_price': limit_price}) return _ws(instruction_id=instruction_id, ts_code=ts_code, side=side, qty=qty, limit_price=limit_price, valid_until=valid_until, intent=intent, parent_id=parent_id, note=note) + if side == 'buy' and parent: + from app.services.buy_budget import check_order + check_order(parent, {'qty': qty, 'limit_price': limit_price}) return _shadow(instruction_id, side) except Exception as e: logger.exception("下发失败 %s", instruction_id) diff --git a/app/services/executor.py b/app/services/executor.py index d2cf20d..047d11b 100644 --- a/app/services/executor.py +++ b/app/services/executor.py @@ -325,13 +325,18 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict: qty = slice_list[0] if slice_list else 0 if side == "sell": qty = min(qty, int(pos.get("avail_qty") or 0)) + budget_reason = None + if side == 'buy' and qty > 0: + from app.services.buy_budget import allowed_quantity + qty, budget_reason = allowed_quantity(ins, d['limit_price'], qty) if qty <= 0: + wait_reason = budget_reason or ("可卖量不足, 顺延" if side == 'sell' else "预算内没有可买数量") prog["last_decision"] = {"at": now.strftime("%H:%M"), "action": et.ACT_WAIT, - "reason": "可卖量不足, 顺延"} + "reason": wait_reason} if not dry_run: pms_repo.update_instruction(ins["instruction_id"], progress=prog) out["waited"].append({"instruction_id": ins["instruction_id"], "code": code, - "action": et.ACT_WAIT, "reason": "可卖量不足, 顺延"}) + "action": et.ACT_WAIT, "reason": wait_reason}) continue ma5 = market.get_ma5(code) if side == "buy" and not d.get("qmt_price_monitor") else None diff --git a/app/services/plan_recheck.py b/app/services/plan_recheck.py index 62eb4c1..7548559 100644 --- a/app/services/plan_recheck.py +++ b/app/services/plan_recheck.py @@ -134,6 +134,11 @@ def fast_checks(p, check): if int(vp['max_names']) - int(t['names_count']) - len(inflight['names']) <= 0: return '可用持仓名额不足,后台将重新安排建议' price = float(market.get_price(code) or 0) + from app.services.buy_budget import candidate + try: + candidate(h, code, p['qty'], price) + except ValueError as exc: + return str(exc) amount = int(p['qty']) * price room = float(vp['portfolio_cap']) * float(vp['scale']) - float(t['portfolio_mv']) - inflight['amount'] if amount > room: @@ -276,6 +281,10 @@ def refresh_one(p, *, now=None, deadline=None): if not fresh: return _failed_recheck(p, out) c = fresh[0] + from app.services.buy_budget import from_hard + previous_budget = from_hard(hard, p['ts_code']) + if previous_budget is not None: + c.setdefault('hard_numbers', {})['buy_budget'] = previous_budget c['_plan_recheck'] = needs_model verdict = None if needs_model else _judgement(p) result = ps._route_one(c, check['view'], params, check['stock'], diff --git a/app/services/proposal_service.py b/app/services/proposal_service.py index e9c72c5..1e47e39 100644 --- a/app/services/proposal_service.py +++ b/app/services/proposal_service.py @@ -1105,9 +1105,19 @@ def _route_one(c, view, params, stock_params, brake_active, now, dry_run, out, if auto_why: auto_exec = True + if is_open: + hard = c.setdefault('hard_numbers', {}) + hard['price'] = price + try: + _apply_advice_tier(c, hard, verdict, force_trial=(sd.get('tier') == 'trial')) + if int(c.get('qty') or 0) <= 0: + raise ValueError(hard.get('advice_resize_note') or '预算内没有可买数量') + except Exception as exc: + out['rejected'].append({**_brief(c), 'by': 'budget', 'failed': [str(exc)], + 'hard_numbers': hard}) + return + if review_only: - _apply_advice_tier(c, c.setdefault('hard_numbers', {}), verdict, - force_trial=(sd.get('tier') == 'trial')) c['hard_numbers'].update(judge_verdict=verdict.get('verdict'), judge_conf=verdict.get('confidence'), price=price, reason=c['reason']) @@ -1261,23 +1271,32 @@ def _make_instruction(c, price, now) -> str: window = param_store.get_int("PMS_EXEC_WINDOW_TDAYS", 3) iid = None last_err = None - for salt in range(3): - try_iid = cs.make_instruction_id(ymd, c["ts_code"], c["action"], seq + salt) - try: - pms_repo.insert_instruction( - instruction_id=try_iid, origin_type="proposal", origin_id=None, - ts_code=c["ts_code"], - action=c["action"], side=c["side"], qty=c["qty"], limit_price=None, - window_tdays=window, status=executor.ST_PROPOSED, - progress={"deadline": str(td.window_deadline(now.date(), window)), - "is_command": False, "children": [], "auto": True, - "reason": c["reason"], - 'plan': {k: (c.get('hard_numbers') or {}).get(k) for k in - ('decision', 'consumption_id', 'review_ref', 'execution_rank', 'priority_reason')}}) - iid = try_iid - break - except Exception as e: - last_err = e + from app.services import buy_budget, execution_orders + with execution_orders.account_guard(): + budget = None + if c['side'] == 'buy': + buy_budget.before_parent(c['ts_code'], action=c['action']) + if c['action'] == 'OPEN': + budget = buy_budget.candidate(c.get('hard_numbers') or {}, c['ts_code'], c['qty'], price) + for salt in range(3): + try_iid = cs.make_instruction_id(ymd, c["ts_code"], c["action"], seq + salt) + try: + affected = pms_repo.insert_instruction( + instruction_id=try_iid, origin_type="proposal", origin_id=None, + ts_code=c["ts_code"], + action=c["action"], side=c["side"], qty=c["qty"], limit_price=None, + window_tdays=window, status=executor.ST_PROPOSED, + progress={"deadline": str(td.window_deadline(now.date(), window)), + "is_command": False, "children": [], "auto": True, + "reason": c["reason"], "buy_budget": budget, + 'plan': {k: (c.get('hard_numbers') or {}).get(k) for k in + ('decision', 'consumption_id', 'review_ref', 'execution_rank', 'priority_reason')}}) + if affected != 1: + raise RuntimeError("建仓指令未成功保存") + iid = try_iid + break + except Exception as e: + last_err = e if iid is None: raise last_err g = bump_once_guards(c["ts_code"], c["action"], c.get("hard_numbers"), now) or {} @@ -1337,46 +1356,42 @@ def bump_once_guards(ts_code: str, action: str, hard_numbers=None, now=None): def _apply_advice_tier(c, hn, verdict, *, force_trial=False): - """按建议档位补研判一档、重算数量与仓位 (原 _make_proposal 内联那段抽出, 2026-09-14)。 - - 自动路在落指令前也调它, 让自动采纳的试探仓真下的是试探仓的股数与分批, 弱基本面那类还带上 - 紧止盈标记 (advice.tight_trail)。force_trial=True 时把建议直接压到试探仓 —— 系统自决按 - decide_kind 判要试探仓时, 研判把握度未必低, apply_judge 不会降档, 所以显式压一次。 - 原地改 hn 与 c["qty"], 返回 (hn, qty, is_trial)。建议算不出不拦 (与从前一样吞掉异常)。 - """ - is_trial = False - try: - from app.services import advice_service as _adv - adv2 = _adv.apply_judge(hn.get("advice"), verdict, - param_store.get_int("PMS_ADVICE_TRIAL_CONF_MIN", 60)) - if force_trial and isinstance(adv2, dict) \ - and adv2.get("tier") not in (_adv.TIER_NONE, _adv.TIER_TRIAL): - adv2 = {**adv2, "tier": _adv.TIER_TRIAL, "factor": 1.0 / 6.0, "splits": (1.0,)} - if isinstance(adv2, dict): - hn["advice"], hn["advice_text"] = adv2, adv2.get("text") - is_trial = adv2.get("tier") == _adv.TIER_TRIAL - if adv2.get("needs_user_confirm"): - hn["needs_user_confirm"] = True - fix, resize_why = _adv.resize_to_advice(adv2, hn, c["ts_code"]) - if fix: - old_qty = c.get("qty") - c["qty"] = fix["qty"] - hn["target_pct"] = fix["target_pct"] - hn["target_amount"] = fix["target_amount"] - hn["base_amount"] = fix["base_amount"] - hn["batch_scheme"] = fix["batch_scheme"] - hn["advice_resized"] = {"from_qty": old_qty, "to_qty": fix["qty"], - "tier": adv2.get("tier"), "note": fix.get("note") or ""} - logger.info("提议按建议档位重算数量 %s: %s → %s 股 (%s)%s", - c["ts_code"], old_qty, fix["qty"], adv2.get("tier"), - "; " + fix["note"] if fix.get("note") else "") - elif resize_why and "档位没变" not in resize_why: - # 算不出来要留痕, 让人在卡上看得见「为什么数量还是原来那个」, - # 而不是默默按旧数量下单。 - hn["advice_resize_note"] = resize_why - except Exception: # noqa: BLE001 —— 建议方案出错不拦 - pass - return hn, c.get("qty"), is_trial + """建仓档位、原预算和数量同步更新;重算失败不允许沿用旧数量。""" + from app.services import advice_service as adv + if c.get('action') != 'OPEN': + return hn, c.get('qty'), False + value = adv.apply_judge(hn.get('advice'), verdict, + param_store.get_int('PMS_ADVICE_TRIAL_CONF_MIN', 60)) + if not isinstance(value, dict): + if force_trial: + raise ValueError('试探仓缺少原预算依据,暂不建仓') + return hn, c.get('qty'), False + if force_trial and value.get('tier') != adv.TIER_NONE: + from app.core.buy_budget import number + pct = number((value.get('mechanical') or {}).get('target_pct'), '原目标比例') / 6 + value = dict(value, tier=adv.TIER_TRIAL, factor=1.0/6.0, splits=(1.0,), + target_pct=float(pct), hold_type='试探仓') + value['text'] = adv.text(value) + if value.get('tier') == adv.TIER_NONE: + raise ValueError('当前方案不允许建仓') + fix, reason = adv.resize_to_advice(value, hn, c['ts_code']) + if fix is None: + raise ValueError(reason or '建仓预算无法核实,暂不建仓') + old_qty = c.get('qty') + c['qty'] = fix['qty'] + hn.update({k: fix[k] for k in ('target_pct', 'target_amount', 'base_amount', 'batch_scheme', 'buy_budget', 'minimum_order_amount')}) + value = dict(value, target_pct=fix['target_pct'], tier=fix['buy_budget']['tier']) + if value['tier'] == adv.TIER_TRIAL: + value['splits'] = (1.0,) + value['hold_type'] = '试探仓' + value['conditions'] = [v for v in value.get('conditions', []) + if not str(v).startswith(('第二批', '后两批'))] + value['text'] = adv.text(value) + hn.update(advice=value, advice_text=value['text'], advice_resize_note=fix['note'], + advice_resized={'from_qty': old_qty, 'to_qty': fix['qty'], 'tier': value['tier'], 'note': fix['note']}) + if value.get('needs_user_confirm'): + hn['needs_user_confirm'] = True + return hn, c['qty'], value['tier'] == adv.TIER_TRIAL def _self_decide(c, verdict, params, today_auto_count) -> dict: @@ -1542,6 +1557,9 @@ def _make_proposal(c, price, verdict) -> str: # 采纳按钮那边直接抄提议里的股数原样落单 (只有卖出侧会按可卖量重算), 所以不在这里 # 改, 后面就没有第二次机会了。 _apply_advice_tier(c, hn, verdict) + if c['action'] == 'OPEN': + from app.services.buy_budget import candidate + candidate(hn, c['ts_code'], c['qty'], price) if c['action'] == ae.A_OPEN and param_store.get_bool('PMS_PLAN_VERSION_RECHECK', False): from app.services.plan_recheck import prepare_new hn = prepare_new(hn, c['ts_code'], verdict) diff --git a/app/services/rotation_execution.py b/app/services/rotation_execution.py index d4d4330..5ae1d42 100644 --- a/app/services/rotation_execution.py +++ b/app/services/rotation_execution.py @@ -75,6 +75,10 @@ def enqueue_with_reservation(payload, parent_id): if blocked: raise ValueError(blocked) book = parent['book_id'] + if side == 'buy': + from app.services.buy_budget import check_order + with books.scope(book): + check_order(parent, payload) if side == 'buy': if param_store.get_bool('PMS_GLOBAL_BUY_HALT', False): raise ValueError('用户暂停买入') diff --git a/app/services/strategy_advisor.py b/app/services/strategy_advisor.py index 978a96b..4a0459e 100644 --- a/app/services/strategy_advisor.py +++ b/app/services/strategy_advisor.py @@ -779,6 +779,11 @@ def _attach_one(edge, why, p, a, hv, prm, view, black, live_codes, optout, prm_view = view["params"] if edge == R_GRID: + from app.services.buy_budget import holding_blocker + budget_wait = holding_blocker(code) + if budget_wait: + out['blocked'].append({'ts_code': code, 'edge': edge, 'why': budget_wait}) + return cap_room = max(0.0, _f(prm_view.get("stock_cap"), 0.08) * _f(prm_view.get("scale"), 0.0) - _f(p.get("market_value"), 0.0)) diff --git a/app/services/strategy_runner.py b/app/services/strategy_runner.py index 13d9d7b..3035dfa 100644 --- a/app/services/strategy_runner.py +++ b/app/services/strategy_runner.py @@ -174,6 +174,9 @@ def _emit_instruction(st: dict, dec: dict, *, forced: bool = False) -> str: if st.get('type') == 'GRID': prog.update({k: deepcopy(dec.get(k)) for k in ('grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id', 'grid_lots')}) with _current_strategy(st): + if dec.get('side') == 'buy' and dec.get('leg') != 'close': + from app.services.buy_budget import before_parent + before_parent(code, action=dec['action']) if st.get('type') == 'GRID': _validate_grid_decision(st, dec) if pms_repo.insert_instruction( @@ -566,6 +569,11 @@ def _tick_grid(st, pos, now, dry_run, out, buy_paused): out['skipped'].append({'strategy_id': st['strategy_id'], 'why': blocker}) return state.update(grid_inventory.snapshot(st, pos)) + from app.services.buy_budget import holding_blocker + budget_wait = holding_blocker(st['ts_code']) + if budget_wait: + buy_paused = True + out['notes'].append(st['ts_code'] + ' ' + budget_wait) dec = EVALUATORS['GRID'](st, pos, day, now, {'state': state, 'notes': out['notes'], 'buy_paused': buy_paused}) if dec: if dry_run: diff --git a/app/web/main.py b/app/web/main.py index d58df41..e6a17da 100644 --- a/app/web/main.py +++ b/app/web/main.py @@ -601,7 +601,9 @@ def api_decide(request: Request, proposal_id: str, payload: dict = Body(default= hn0 = p.get('hard_numbers') or {} side0 = hn0.get('side') if hn0.get('kind') == 'strategy' else ('sell' if p['action'] in ('TRIM', 'EXIT') else 'buy') if side0 == 'buy': - blocked = buy_blocker(p['ts_code']) + from app.services.buy_budget import holding_blocker + closing_t0 = hn0.get('kind') == 'strategy' and hn0.get('stype') == 'T0' and hn0.get('leg') == 'close' + blocked = ('' if closing_t0 else holding_blocker(p['ts_code'])) or buy_blocker(p['ts_code']) if blocked: return {'ok': False, 'error': blocked, 'proposal_id': proposal_id} expected_hard = None @@ -628,7 +630,8 @@ def api_decide(request: Request, proposal_id: str, payload: dict = Body(default= 'execution_rank', 'priority_reason', 'version_check', 'candidate_source','dividend_ref','dividend_policy_version')}, 'deadline': str(td.window_deadline(None, window))}} - if pms_repo.accept_open_proposal(p, hn, instruction, reason): + from app.services.buy_budget import accept_open + if accept_open(p, hn, instruction, reason): return {'ok': True, 'decision': decision, 'instruction_id': iid} latest = pms_repo.get_proposal(proposal_id) existing = (pms_repo.accepted_open_instruction(proposal_id) diff --git a/docs/evidence/trading_budget_impact_20261116.json b/docs/evidence/trading_budget_impact_20261116.json new file mode 100644 index 0000000..ee686b7 --- /dev/null +++ b/docs/evidence/trading_budget_impact_20261116.json @@ -0,0 +1,104 @@ +{ + "snapshot_at": "2026-11-16T10:43:53.091130", + "scope": "pms-sim-155", + "method": "只读历史快照在断网环境计算,不触发交易", + "positions": { + "002979.SZ": { + "qty": 100, + "buy_restriction": "本轮为试探仓,暂停网格及其他自动加仓;扩大投入须明确新的买入命令" + }, + "300364.SZ": { + "qty": 0, + "buy_restriction": "该股已有试探建仓安排,不能从其他路径重复增加投入" + }, + "300750.SZ": { + "qty": 100, + "buy_restriction": "本轮为试探仓,暂停网格及其他自动加仓;扩大投入须明确新的买入命令" + }, + "601126.SH": { + "qty": 2700, + "buy_restriction": "" + }, + "603259.SH": { + "qty": 100, + "buy_restriction": "本轮为试探仓,暂停网格及其他自动加仓;扩大投入须明确新的买入命令" + } + }, + "parents": { + "INS_20261103_002979SZ_OPEN_001_134e680ae814": { + "code": "002979.SZ", + "status": "EXPIRED", + "budget": { + "version": 1, + "ts_code": "002979.SZ", + "amount": "15048.00", + "scale": "1.50480E+6", + "target_pct": "0.010", + "quantity_limit": 300, + "tier": "试探仓", + "basis": "买入成交金额,不含另记的交易费用", + "revision": "a4bd43540ba3e96607285599" + } + }, + "INS_20261112_300364SZ_OPEN_001_b8a67bfde6f2": { + "code": "300364.SZ", + "status": "WAIT_REVIEW", + "budget": { + "version": 1, + "ts_code": "300364.SZ", + "amount": "17226.00", + "scale": "1.72260E+6", + "target_pct": "0.010", + "quantity_limit": 600, + "tier": "试探仓", + "basis": "买入成交金额,不含另记的交易费用", + "revision": "9d406551056d9ac5fe97a5ec" + } + }, + "INS_20261109_300750SZ_OPEN_93201": { + "code": "300750.SZ", + "status": "CANCELLED", + "budget": { + "version": 1, + "ts_code": "300750.SZ", + "amount": "16988.66", + "scale": "1698866.666666666666666666667", + "target_pct": "0.009999996075815249381940901776", + "quantity_limit": 0, + "tier": "试探仓", + "basis": "买入成交金额,不含另记的交易费用", + "revision": "d3877a9e588cc3d8d3d24ee9" + } + }, + "INS_20261106_601126SH_OPEN_93200": { + "code": "601126.SH", + "status": "EXPIRED", + "budget": { + "version": 1, + "ts_code": "601126.SH", + "amount": "112813.00", + "scale": "1880216.666666666666666666667", + "target_pct": "0.05999999999999999999999999999", + "quantity_limit": 3600, + "tier": "标准仓", + "basis": "买入成交金额,不含另记的交易费用", + "revision": "92c0dbbdb65cd0f6b1828c6c" + } + }, + "INS_20261106_603259SH_OPEN_001_feed045bd695": { + "code": "603259.SH", + "status": "CONFIRMED", + "budget": { + "version": 1, + "ts_code": "603259.SH", + "amount": "12568.33", + "scale": "1256833.333333333333333333333", + "target_pct": "0.009999997347831852539451001196", + "quantity_limit": 0, + "tier": "试探仓", + "basis": "买入成交金额,不含另记的交易费用", + "revision": "297ae9b3c933637ccb0d08ba" + } + } + } +} diff --git a/docs/交易计划与风险约束整改接续_2026-11-16.md b/docs/交易计划与风险约束整改接续_2026-11-16.md index 5bc62fe..3e3a30d 100644 --- a/docs/交易计划与风险约束整改接续_2026-11-16.md +++ b/docs/交易计划与风险约束整改接续_2026-11-16.md @@ -1,6 +1,6 @@ # 交易计划与风险约束整改接续 -最新运行核验时间:2026年11月16日09:52:39,北京时间。首个网格工作包已发布155模拟PMS,下一工作包为试探预算约束。 +最新运行核验时间:2026年11月16日09:52:39,北京时间。首个网格工作包已发布155模拟PMS;试探预算约束已实现,候选发布与自然判收尚待完成。 ## 当前工作 @@ -17,7 +17,7 @@ | 工作包 | 状态 | 下一项证据 | | --- | --- | --- | | 关键交易核验 | 主要路径已确认 | 杰普特两次模型完整输入仍缺;不阻塞确定性数量与库存修复 | -| 试探预算约束 | 待开发 | 全路径预算传递及最低数量拒绝用例 | +| 试探预算约束 | 已开发,准备独立发布 | 候选镜像断网全量、155健康与自然回执 | | 网格库存约束 | 已开发并发布155,隔离回归与自然调度通过 | 自然行情触发库存限制,以及卖出入账后恢复同价循环 | | 退出方案 | 待核验与设计 | 二次确认可达性和价格失效比较 | | 分层评价与产品验收 | 待实施 | 历史冻结名单覆盖与当前页面任务检查 | @@ -41,6 +41,6 @@ ## 下一步开发入口 -按规格工作包二的五步顺序实施试探预算约束,完成预算01至09再作为独立版本发布。先建立原预算与明确阻断结果,然后贯穿自动/人工采纳、报价与有效预留、网格和补仓、旧提议与在手轮次。不得只删掉最低股数向上取整就认定问题解决。退出工作包继续做证据独立性和等待可达性核验,新止损阈值尚未确定,不能擅自上线。 +工作包二实现与预算01至09映射见[试探预算约束实现与验收](试探预算约束实现与验收_2026-11-16.md)。开发机预算专项41项和batch51共38项隔离通过,完整代码候选仍须断网全量后发布。退出工作包继续做证据独立性和等待可达性核验,新止损阈值尚未确定,不能擅自上线。 -本轮已修改网格业务代码、测试和文档并完成上述定向发布,没有修改运行参数、人工触发模型或交易tick、注入测试委托。预算约束、退出方案和分层评价仍未完成,不能因网格发布成功而标为整项完成。 +本轮已修改网格业务代码、测试和文档并完成上述定向发布,没有修改运行参数、人工触发模型或交易tick、注入测试委托。预算约束正在准备发布,退出方案和分层评价仍未完成,不能因网格发布成功而标为整项完成。 diff --git a/docs/开发入口.md b/docs/开发入口.md index da4c34a..d40ace8 100644 --- a/docs/开发入口.md +++ b/docs/开发入口.md @@ -1,5 +1,7 @@ # 开发资料入口 +11月16日试探预算工作包已实现,范围与逐项验收见[试探预算约束实现与验收](试探预算约束实现与验收_2026-11-16.md)。候选构建、155发布与自然判收以[整改接续](交易计划与风险约束整改接续_2026-11-16.md)最新时间为准。 + 11月13日宽基查询、当日分时和类别简称见[最新接续](宽基查询接口与分时展示接续_2026-11-13.md)。13:17仅更新web为etf-names-975fa5a,177只ETF按8类跟踪指数显示简称,取消前置标签和名称悬停,点击保留原基金详情。日内只显示北京时间当日,每日净额与60日趋势保持;13:18线上映射、页面及只读对账通过。 11月12日按最新意见改为[宽基紧凑汇总与15分钟方向图](宽基紧凑汇总与十五分钟方向图_2026-11-12.md),取代下方双入口方案;顶部单标签,日内信息及分时柱图并入原悬浮框。 diff --git a/docs/试探预算约束实现与验收_2026-11-16.md b/docs/试探预算约束实现与验收_2026-11-16.md new file mode 100644 index 0000000..99afb0f --- /dev/null +++ b/docs/试探预算约束实现与验收_2026-11-16.md @@ -0,0 +1,61 @@ +# 试探预算约束实现与验收 + +本记录对应[整改规格](交易计划与风险约束整改规格_2026-11-16.md)工作包二。11月16日完成实现和只读影响核验;发布状态以[整改接续](交易计划与风险约束整改接续_2026-11-16.md)的最新时间为准。 + +## 交易行为 + +试探预算不足最低申报数量时不建仓。杰普特原15695元预算、313.90元价格的场景,可买数量为0,不再抬到200股62780元。强制降为试探时,同时更新比例、金额、数量、分批与文字;旧记录只有标签降档、比例仍为标准仓时,使用原记录的机械比例核实,无法核实则停止新增。 + +预算记录在提议依据和已批准父指令内,保存金额、原规模、数量上限、仓位类型、证券、版本和内容摘要。报价下降可以让尚未采纳的计划达到最低买入量,但不会提高金额;报价上涨时缩减可执行数量。已经批准的父指令数量上限不能因后续报价、重评或卖出盈利提高。执行进度回写保留数据库中的原预算,旧任务不能覆盖它。 + +本轮仍有试探持仓,或已有待执行的试探建仓计划时,网格、补仓及做T新增买入不能另开额度。底仓卖完但本轮附加仓尚未结束,约束继续;全部清仓后的新轮次重新评估。旧预算或归属无法核实时只暂停新增,正常卖出和已有做T回补继续。明确的用户买入命令按实际命令与方案验证,使用其独立金额和数量上限;策略内部的`is_command`字段不构成扩大投入授权,也不会升级旧试探计划。 + +这是资金投入约束,金额口径是实际买入成交金额,交易费用仍由既有账户资金预留统一计入。它不等于可承受亏损上限,没有新增失效价、止损比例、试探升级界面或统一风险计划表。工作包四仍需设计亏损预算和退出纪律。 + +## 开发落点 + +| 落点 | 责任 | +| --- | --- | +| `app/core/buy_budget.py` | Decimal金额、合法数量向下取整、试探比例核实、版本摘要及金额上限校验 | +| `app/services/buy_budget.py` | 原提议追溯、持仓轮次识别、真实命令识别、剩余额度与最终校验 | +| `action_engine`、`advice_service`、`proposal_service` | 原规模独立保存;自动、人工候选共用预算;异常和零数量明确拒绝 | +| `plan_recheck`、`db.session`、`web.main.api_decide` | 重评保留原预算;异步发布禁止扩大;账户事务内原子采纳;沿用现有错误反馈 | +| `executor`、`rotation_execution`、`dispatcher` | 实际限价重算;最终落单锁内重新读取父指令并验证;保留原账户预留算法 | +| `strategy_runner`、`strategy_advisor` | 策略挂载、评估和落父指令前拦截试探新增;卖出继续 | +| `pms_repo.update_instruction` | SQL层保留已批准预算,防止旧执行进度整体回写覆盖 | + +无建表、清账或历史批次迁移。旧指令只用其原始PASS建仓依据或明确关联的已采纳提议重建约束,不调用当前模型替换历史。读取设有完整性上限,达到上限或数量无法对齐时停止续买。 + +## 验收映射 + +预算专项为`scripts/test_buy_budget.py`,所有外部仓储、行情和锁均隔离。全量入口同时包含页面三道护栏与原策略执行回归。 + +| 规格编号 | 证据与预期 | +| --- | --- | +| 预算01、02 | 杰普特15695元返回0;恰好够100股与差一分钱;零、负数、空值、NaN、无穷值不能放行 | +| 预算03、04 | 强制试探比例、数量与文字一致;同档仍重算;历史宁德“试探标签、标准比例”收紧为原机械比例的六分之一 | +| 预算05 | 重算异常不沿用旧股数;原预算缺失暂停新增;卖出不受买入预算查询失败影响 | +| 预算06 | 自动建仓与人工原子采纳拒绝超预算;缓存提议继承原预算;异步发布不能删除预算、提高金额或升级试探类型;旧进度回写SQL保留已批准值 | +| 预算07 | 涨价、真实成交价、部分成交、撤单未确认、迟到成交、子委托缺失和未入账均覆盖;已卖部分仍计原累计投入;费用仍走已有预留,不二次扣本金 | +| 预算08 | 试探未成交时其他路径不能抢先买入;持仓轮次的网格、普通加仓和做T新增被限制;清仓新轮次、标准仓、其他策略账本、真实用户命令及做T回补保持各自规则 | +| 预算09 | 两个并发采纳只有一个父指令;真实最终落单入口在账户锁内读取变化后的预算,超限时不写委托或资金预留;数据库原子采纳复用外层事务 | + +41项预算专项和38项batch51测试已在开发机Python3.12隔离通过。最终全量及服务器候选镜像结果需在发布记录中补充,不把单机通过当作155判收。`test_batch26_units.py`原来要求最低数量向上抬仓的断言,已改为预算不足零数量;其他策略的标准仓测试使用可追溯预算桩。 + +## 11月16日10:43只读快照的影响 + +只读读取155当前持仓、相关历史父指令、提议与PASS依据,随后在断网环境运行新约束,未触发模型、交易tick或数据库写入。脱敏结果见[预算影响快照](evidence/trading_budget_impact_20261116.json)。 + +| 股票 | 实际状态 | 新规则对新增买入的影响 | +| --- | --- | --- | +| 雷赛智能 | 剩100股,原试探依据可追溯 | 本轮自动加仓暂停,卖出继续 | +| 中文在线 | 未持仓,600股试探父指令待当日复核 | 原计划继续受复核和17226元预算限制;其他路径不能另开试探额度 | +| 宁德时代 | 100股,原父指令已取消 | 历史记录将试探标签与6%比例混用;按原机械比例核实为16988.66元,暂停本轮自动加仓,不强卖历史成交 | +| 四方股份 | 2700股,原标准仓 | 本预算工作包不阻断原标准仓网格;继续受已有择时、破位停止买入与跨版本库存约束 | +| 药明康德 | 100股,原试探预算曾向上抬量 | 可追溯保守预算12568.33元,不足原价最低100股;暂停本轮自动加仓,不改历史成交 | + +这些金额是依据旧保存比例与金额重建的保守约束。历史比例有四舍五入,不能声称精确恢复当时未保存的账户规模。它们用于禁止继续扩大,未改写原始提议或账本。 + +## 尚未完成的判收 + +真实行情自然触发新预算拦截、自然报价变化与成交后续买,需要单独记录。发布后的接口健康、调度成功不能代替这些交易场景。新的可承受亏损预算、显式计划升级产品流程、网格适用性研究、退出证据独立性和等待期限仍属于后续工作包。 diff --git a/scripts/run_tests.py b/scripts/run_tests.py index 7d561a6..9d5f7b4 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -7,6 +7,7 @@ test_batch54_units.py 用户候选来源、到期核验、权限、显式取用、技术面补读及评级排序透传 (10例) 4%网格真实批次、核销顺序、报价边界、迁移事务与跨版本库存重复准入专项62例。 +试探仓原预算、最低申报、实际成交占用与并发准入专项见test_buy_budget.py。 成交修正专项:批次投影36例、传输与执行保护29例、服务事务36例、 普通成交凭据与仓储13例、网格更正版本与并发20例。 @@ -209,6 +210,7 @@ SUITES = [ "test_timing_fusion.py", # 三组证据契约、二次清仓与恢复(14例) "test_signal_recovery.py", # 最新方向、停买恢复、网格合议、关注入口与负净成本(16例) "test_grid_execution.py", + "test_buy_budget.py", "test_broad_funds.py", "test_etf_observation.py", "test_etf_query.py", "test_risk_exit.py", "test_rotation_accounting_units.py", "test_cost_precision.py", "test_execution_basis_decimal.py", "test_trade_correction_units.py", "test_trade_correction_transport.py", "test_trade_correction_service.py", "test_trade_lineage_units.py", diff --git a/scripts/test_batch10_units.py b/scripts/test_batch10_units.py index 1948d12..f8b98a0 100644 --- a/scripts/test_batch10_units.py +++ b/scripts/test_batch10_units.py @@ -50,6 +50,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 这些函数**写失败时不抛异常**, 只把失败写在返回值里。调用点必须接住。 # key = 函数名, value = 允许的调用者模块名 (None = 不限, 用于 _db(f, ...) 这种间接调用) SOFT_FAIL = { + "accept_open": {"buy_budget"}, "consume_once": {"etf_query"}, "scan": {"risk_exit"}, "refresh_reviews": {"risk_exit"}, diff --git a/scripts/test_batch26_units.py b/scripts/test_batch26_units.py index eac6e9a..1e7a887 100644 --- a/scripts/test_batch26_units.py +++ b/scripts/test_batch26_units.py @@ -17,8 +17,8 @@ stock_target_default),但研判回来之后 apply_judge 还会再降一档 根本没有填数量的地方,这个「交人」无处兑现 —— 采纳时后端直接抄提议里的股数原样落单。 A 按建议档位重算:正常降档、总规模从硬数字反推、批次比例跟着换。 - B 买不足一手:抬到一手;一手就超过机械档的不改、交回调用方,并说清原因。 - C 不该改的不改:档位没变、缺读数、没有建议方案。 + B 最低申报量超过原预算:明确零数量,不向上扩大。 + C 同档也重算;缺读数明确失败,由调用方停止建仓。 D 方向只能是变小:重算之后的金额不许超过原来那一笔。 E 上游标了硬风险的候选一律交人 —— 哪怕档位是 full。 F 持仓的目标仓位在建仓成交入账时记一次,且只记第一次。 @@ -103,40 +103,34 @@ def _(): assert fix["batch_scheme"] == "0.5,0.5", fix -# ============================================================ B 买不足一手 -@case("B1 高价票买不足一手 → 抬到一手(300604.SZ 现价 264.81 的真实情形)") +# ============================================================ B 最低申报不扩大预算 +@case("B1 高价票不足100股时保留原预算并给出零数量") def _(): fix, why = adv.resize_to_advice(_adv("试探仓", 0.01, (1.0,)), _hn(264.81), "300604.SZ") - assert fix, why - # 1% = 20000 元 ÷ 264.81 = 75 股,不足一手 → 抬到 100 股 - assert fix["qty"] == 100, fix - assert "买不足一手" in (fix.get("note") or ""), fix - # 抬上去之后实际占比 1.32%,仍远小于机械档 6% - assert 0.013 < fix["target_pct"] < 0.014, fix + assert fix and fix['qty'] == 0, (fix, why) + assert fix['target_amount'] == 20000 and fix['target_pct'] == .01 + assert '最低买入量' in fix['note'] -@case("B2 科创板一手是 200 股,不是 100 股") +@case("B2 科创板不足200股时不向上扩大") def _(): fix, why = adv.resize_to_advice(_adv("试探仓", 0.01, (1.0,)), _hn(150.0), "688001.SH") - assert fix, why - # 1% = 20000 元 ÷ 150 = 133 股 < 200 股 → 抬到 200 股 - assert fix["qty"] == 200, fix + assert fix and fix['qty'] == 0, (fix, why) + assert fix['buy_budget']['amount'] == '20000.00' -@case("B3 一手就超过机械档 → 不改数量,交回调用方并说清原因") +@case("B3 最低申报超过机械档同样明确零数量") def _(): - # 一股 1500 元,一手 15 万;机械档 6% 是 12 万 —— 这只票对当前规模本来就太贵 fix, why = adv.resize_to_advice(_adv("试探仓", 0.01, (1.0,)), _hn(1500.0), "600000.SH") - assert fix is None, fix - assert "太贵" in why and "一手" in why, why + assert fix and fix['qty'] == 0 and fix['base_amount'] == 0, (fix, why) # ============================================================ C 不该改的不改 -@case("C1 档位没变就不重算(标准仓那张卡本来就是自洽的)") +@case("C1 档位没变也重新核对数量并保存原预算") def _(): fix, why = adv.resize_to_advice(_adv("标准仓", 0.06, (0.5, 0.25, 0.25)), _hn(9.27), "300118.SZ") - assert fix is None, fix - assert "档位没变" in why, why + assert fix and fix["qty"] == 6400, (fix, why) + assert fix["target_amount"] == 120000 and fix["buy_budget"]["quantity_limit"] == 12800 @case("C2 缺现价、缺目标金额、缺目标仓位,一律不改") @@ -169,12 +163,12 @@ def _(): assert fix["base_amount"] <= old_base + 0.01, (price, fix["base_amount"], old_base) -@case("D2 抬到一手也不许超过机械档的整只目标金额") +@case("D2 原试探预算始终是上限") def _(): for price in (200.0, 264.81, 500.0, 1000.0, 1199.0): fix, _why = adv.resize_to_advice(_adv("试探仓", 0.01, (1.0,)), _hn(price), "600000.SH") if fix: - assert fix["base_amount"] <= SCALE * 0.06 + 0.01, (price, fix) + assert fix["base_amount"] <= SCALE * 0.01, (price, fix) # ============================================================ E 硬风险一律交人 diff --git a/scripts/test_batch51_units.py b/scripts/test_batch51_units.py index 607e100..a214080 100644 --- a/scripts/test_batch51_units.py +++ b/scripts/test_batch51_units.py @@ -18,6 +18,19 @@ CODE = '300693.SZ' class DailyReviewTests(unittest.TestCase): + def test_stale_execution_write_cannot_change_approved_budget(self): + from app.core import buy_budget + value={'version':1,'ts_code':CODE,'amount':'10000.00','scale':'1000000', + 'target_pct':'.01','quantity_limit':300,'tier':'试探仓'} + value['revision']=buy_budget.identity(value) + original=pms_repo.get_instruction('P')['progress'] + self.assertEqual(pms_repo.update_instruction('P',progress=dict(original,buy_budget=value)),1) + self.assertEqual(pms_repo.update_instruction('P',progress=original),1) + changed=dict(value,amount='60000.00',tier='标准仓') + changed['revision']=buy_budget.identity(changed) + self.assertEqual(pms_repo.update_instruction('P',progress=dict(original,buy_budget=changed)),1) + self.assertEqual(pms_repo.get_instruction('P')['progress']['buy_budget'],value) + def setUp(self): self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup) self.engine = create_engine('sqlite:///' + self.tmp.name + '/state.sqlite') diff --git a/scripts/test_buy_budget.py b/scripts/test_buy_budget.py new file mode 100644 index 0000000..05df9f3 --- /dev/null +++ b/scripts/test_buy_budget.py @@ -0,0 +1,343 @@ +"""试探资金预算端到端边界:所有仓储、行情及账户锁均隔离。""" +import unit_test_guard +import copy +import datetime as dt +import sys +import threading +import unittest +from concurrent.futures import ThreadPoolExecutor +from contextlib import nullcontext, contextmanager +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from app.core import buy_budget as core, strategy_book as books +from app.services import buy_budget as service, advice_service, proposal_service as ps, execution_orders +from app.repo import pms_repo, qmt_repo, execution_repo +from config.settings import settings + +CODE = '600000.SH' + + +def hard(price=50, amount=60000, pct=.06, target=.01, tier='试探仓'): + return {'price': price, 'target_amount': amount, 'target_pct': pct, + 'advice': {'tier': tier, 'target_pct': target, 'splits': (1.0,), + 'mechanical': {'target_pct': .06, 'splits': (.5,.25,.25)}}} + + +def budget(code=CODE, price=50, amount=60000): + h = hard(price, amount) + return core.resize(h['advice'], h, code)['buy_budget'] + + +class BudgetMath(unittest.TestCase): + def test_jpt_minimum_returns_zero_and_preserves_15695(self): + h=hard(313.9,94170) + r=core.resize(h['advice'],h,'688025.SH') + self.assertEqual((r['qty'],r['target_amount'],r['base_amount']),(0,15695,0)) + self.assertEqual(r['buy_budget']['amount'],'15695.00') + self.assertEqual(r['minimum_order_amount'],62780) + self.assertIn('需62780.00元',r['note']) + + def test_exact_hundred_and_one_cent_short(self): + for amount,expected in [('407.00',100),('406.99',0)]: + h=hard('4.07',amount,.01) + self.assertEqual(core.resize(h['advice'],h,CODE)['qty'],expected) + + def test_same_tier_rechecks_oversized_quantity(self): + h=hard(50,10000,.01) + r=core.resize(h['advice'],h,CODE) + with self.assertRaises(ValueError):core.check_quantity(r['buy_budget'],CODE,800,50) + + def test_bad_numeric_inputs_cannot_produce_quantity(self): + for key in ('price','target_amount','target_pct'): + for value in (None,0,-1,'NaN','Infinity','bad'): + h=hard();h[key]=value + with self.subTest(key=key,value=value),self.assertRaises(ValueError):core.resize(h['advice'],h,CODE) + + def test_original_budget_not_rounded_down_to_executable_cost(self): + h=hard(48.55,120000) + r=core.resize(h['advice'],h,CODE) + self.assertEqual((r['qty'],r['base_amount'],r['target_amount']),(400,19420,20000)) + + def test_refresh_price_scale_or_tier_cannot_raise_budget(self): + h=hard();h['buy_budget']=budget();h.update(sizing_scale=3000000,target_amount=180000) + h['advice'].update(tier='标准仓',target_pct=.06,splits=(.5,.25,.25)) + r=core.resize(h['advice'],h,CODE) + self.assertEqual((r['buy_budget']['amount'],r['buy_budget']['tier'],r['batch_scheme']),('10000.00','试探仓','1.0')) + + def test_unaccepted_zero_quantity_can_be_repriced_within_same_budget(self): + h=hard(150,120000) + h['buy_budget']=core.resize(h['advice'],h,'688001.SH')['buy_budget'] + h['price']=90 + r=core.resize(h['advice'],h,'688001.SH') + self.assertEqual((r['qty'],r['target_amount']),(200,20000)) + + def test_tampered_revision_and_wrong_symbol_refuse(self): + b=budget();b['amount']='50000' + with self.assertRaises(ValueError):core.validate(b,CODE) + with self.assertRaises(ValueError):core.validate(budget(),'688025.SH') + + def test_force_trial_updates_text_ratio_amount_quantity(self): + h=hard(tier='标准仓',target=.06) + c={'action':'OPEN','ts_code':CODE,'qty':600} + with patch.object(ps.param_store,'get_int',return_value=60): + ps._apply_advice_tier(c,h,{'verdict':'PASS','confidence':90},force_trial=True) + self.assertEqual((c['qty'],h['target_pct'],h['target_amount'],h['batch_scheme']),(200,.01,10000,'1.0')) + self.assertIn('1.0%',h['advice_text']) + + def test_resize_exception_does_not_keep_old_buy(self): + c={'action':'OPEN','ts_code':CODE,'qty':1000} + with patch.object(ps.param_store,'get_int',return_value=60),patch.object(advice_service,'resize_to_advice',side_effect=RuntimeError('failure')): + with self.assertRaises(RuntimeError):ps._apply_advice_tier(c,hard(),{'verdict':'PASS'}) + + def test_sell_does_not_consult_buy_budget(self): + c={'action':'EXIT','ts_code':CODE,'qty':100} + self.assertEqual(ps._apply_advice_tier(c,{},{}),({},100,False)) + + +class ServiceBudget(unittest.TestCase): + def setUp(self): + self.parents={};self.orders=[];self.rows=[];self.ledger=[];self.pos={};self.plans={};self.commands={} + self.lock=threading.RLock() + self.mock(settings,'INFRA_STRATEGY_BOOK_SCHEMA',True) + self.mock(execution_orders,'account_guard',side_effect=lambda:self.lock) + self.mock(pms_repo,'get_position',side_effect=lambda code:copy.deepcopy(self.pos)) + self.mock(pms_repo,'list_lots',side_effect=lambda *a,**kw:copy.deepcopy(self.rows)) + self.mock(pms_repo,'get_instruction',side_effect=lambda iid:copy.deepcopy(self.parents.get(iid))) + self.mock(pms_repo,'list_instructions',side_effect=lambda **kw:[copy.deepcopy(p) for p in self.parents.values() if p.get('status') in kw.get('statuses',service.LIVE)]) + self.mock(pms_repo,'ledger_by_ref',side_effect=lambda refs,**kw:copy.deepcopy([r for r in self.ledger if r['ref_id'] in refs])) + self.mock(pms_repo,'get_proposal',return_value=None) + self.mock(pms_repo,'get_plan',side_effect=lambda pid:copy.deepcopy(self.plans.get(pid))) + self.mock(pms_repo,'get_command',side_effect=lambda cid:copy.deepcopy(self.commands.get(cid))) + self.mock(qmt_repo,'orders_for_parent',side_effect=lambda pid:copy.deepcopy([o for o in self.orders if o['parent_id']==pid])) + self.pending=self.mock(execution_repo,'pending_trades',return_value=0) + self.mock(ps.param_store,'get_int',return_value=3) + self.mock(ps.td,'ymd',return_value=20261116) + self.mock(ps.td,'window_deadline',return_value=dt.date(2026,11,18)) + self.mock(pms_repo,'insert_instruction',side_effect=self.insert) + self.token=books.CURRENT.set(books.ORIGINAL);self.addCleanup(books.CURRENT.reset,self.token) + + def mock(self,obj,name,*args,**kw): + p=patch.object(obj,name,*args,**kw);value=p.start();self.addCleanup(p.stop);return value + + def insert(self,**kw): + iid=kw['instruction_id'] + if iid in self.parents:raise ValueError('duplicate') + self.parents[iid]=copy.deepcopy(dict(kw,book_id='original',exec_qty=0)) + return 1 + + def root(self,*,b=None,holding=100): + p={'instruction_id':'P','ts_code':CODE,'side':'buy','action':'OPEN','origin_type':'proposal', + 'book_id':'original','qty':200,'exec_qty':100,'status':'PROPOSED','progress':{'buy_budget':b or budget()}} + self.parents['P']=p + if holding: + self.pos={'total_qty':holding,'opened_date':'2026-11-05'} + self.rows=[{'id':1,'ts_code':CODE,'lot_type':'BASE','qty':holding,'open_date':'2026-11-05','instruction_id':'P','status':'OPEN'}] + return p + + def filled(self,qty=100,price=50,status='CANCELLED'): + self.orders.append({'instruction_id':'P_D01','parent_id':'P','qty':200,'cum_qty':qty, + 'cum_avg_price':price,'limit_price':50,'status':status}) + for row in self.rows: + if row['instruction_id']=='P':row.update(open_price=price,closed_qty=max(0,qty-row['qty'])) + + def test_part_fill_then_price_rise_caps_remaining_money(self): + p=self.root();self.filled() + self.assertEqual(service.allowed_quantity(p,51,100)[0],0) + self.assertEqual(service.allowed_quantity(p,50,100),(100,'')) + + def test_filled_amount_is_not_double_counted_with_booked_quantity(self): + p=self.root();self.filled(100,49) + self.assertEqual(service.allowed_quantity(p,51,100),(100,'')) + + def test_live_partial_and_unconfirmed_cancel_do_not_release(self): + for status in ('PARTIAL','ACCEPTED','SENT'): + self.orders=[];p=self.root();self.filled(status=status) + self.assertEqual(service.allowed_quantity(p,1,100)[0],0) + + def test_late_trade_and_missing_child_block(self): + p=self.root();self.filled();self.pending.return_value=1 + self.assertEqual(service.allowed_quantity(p,1,100)[0],0) + self.pending.return_value=0;p['progress']['children']=[{'ref':'P_D99'}] + self.assertEqual(service.allowed_quantity(p,1,100)[0],0) + + def test_fill_received_before_bookkeeping_blocks(self): + p=self.root();p['exec_qty']=0;self.filled() + self.assertEqual(service.allowed_quantity(p,1,100)[0],0) + + def test_missing_actual_booked_fill_price_fails_closed(self): + p=self.root();self.filled(price=None) + with self.assertRaises(ValueError):service.allowed_quantity(p,1,100) + + def test_qty_increase_in_parent_cannot_expand_original_plan(self): + p=self.root(holding=0);p['qty']=1000;p['exec_qty']=0 + self.assertEqual(service.allowed_quantity(p,1,1000),(200,'')) + + def test_flat_then_new_round_does_not_inherit_old_trial(self): + self.root()['status']='CONFIRMED';self.pos={};self.rows[0].update(status='CLOSED',qty=0) + self.assertEqual(service.holding_blocker(CODE),'') + + def test_trial_blocks_new_grid_or_add_even_if_price_fell(self): + self.root()['status']='EXPIRED' + for action in ('ADD','FILL','DCA','OPEN'): + with self.assertRaisesRegex(ValueError,'试探仓'):service.before_parent(CODE,action=action) + + def test_closed_base_with_remaining_add_still_restricts_trial_round(self): + self.root()['status']='EXPIRED';self.rows[0].update(qty=0,status='CLOSED') + self.rows.append(dict(self.rows[0],id=2,qty=100,status='OPEN',lot_type='ADD',instruction_id='GRID')) + self.assertIn('试探仓',service.holding_blocker(CODE)) + + def test_unknown_origin_or_budget_blocks_instead_of_standard_default(self): + p=self.root();p['progress']={};p['status']='EXPIRED' + self.assertIn('无法核实',service.holding_blocker(CODE)) + + def test_query_failure_restricts_buy_but_sell_continues(self): + p=self.root();p['status']='EXPIRED' + with patch.object(pms_repo,'list_lots',side_effect=RuntimeError('offline')): + self.assertIn('暂停自动加仓',service.holding_blocker(CODE)) + self.assertEqual(service.allowed_quantity(dict(p,side='sell'),50,100),(100,'')) + + def test_new_parent_keeps_budget_in_progress(self): + h=hard();h['buy_budget']=budget() + c={'ts_code':CODE,'action':'OPEN','side':'buy','qty':200,'reason':'test','hard_numbers':h} + iid=ps._make_instruction(c,50,dt.datetime(2026,11,16,10)) + self.assertEqual(self.parents[iid]['progress']['buy_budget'],h['buy_budget']) + + def test_jpt_oversized_auto_and_manual_create_no_parent(self): + h=hard(313.9,62780,.04);code='688025.SH' + c={'ts_code':code,'action':'OPEN','side':'buy','qty':200,'reason':'test','hard_numbers':h} + with self.assertRaises(ValueError):ps._make_instruction(c,313.9,dt.datetime(2026,11,16,10)) + with patch.object(pms_repo,'accept_open_proposal') as write: + with self.assertRaises(ValueError):service.accept_open({'ts_code':code,'qty':200},h,{'progress':{}},'confirm') + write.assert_not_called() + self.assertEqual(self.parents,{}) + + def test_two_concurrent_proposals_allocate_only_one_budget(self): + h=hard();h['buy_budget']=budget() + def create(second): + c={'ts_code':CODE,'action':'OPEN','side':'buy','qty':200,'reason':'test','hard_numbers':copy.deepcopy(h)} + try:return ps._make_instruction(c,50,dt.datetime(2026,11,16,10,0,second)) + except ValueError:return None + with ThreadPoolExecutor(max_workers=2) as pool:result=list(pool.map(create,[1,2])) + self.assertEqual(sum(bool(x) for x in result),1) + self.assertEqual(len(self.parents),1) + + def test_locked_enqueue_rechecks_updated_budget_and_leaves_no_order(self): + from app.services import rotation_execution as execution + p=self.root(holding=0);p['exec_qty']=0 + payload={'instruction_id':'P_D01','ts_code':CODE,'side':'buy','qty':200,'limit_price':50} + # 报价完成后,落单前看到较小的当前预算;只能在锁内读取并拒绝。 + p['progress']['buy_budget']=budget(amount=30000) + account={'orders':{}};locked=[] + @contextmanager + def guard(*args): + with self.lock: + locked.append(True) + try:yield account + finally:locked.pop() + def current(iid): + self.assertTrue(locked) + return copy.deepcopy(self.parents[iid]) + with patch.object(execution.store,'locked',side_effect=guard),patch.object(qmt_repo,'get_order',return_value=None), \ + patch.object(execution.param_store,'get_bool',return_value=False),patch.object(execution_orders,'correction_blocker',return_value=''), \ + patch.object(pms_repo,'get_instruction',side_effect=current),patch.object(execution.db,'fetch_all') as further: + with self.assertRaises(ValueError):execution.enqueue_with_reservation(payload,'P') + further.assert_not_called() + self.assertEqual(account,{'orders':{}}) + self.assertEqual(self.orders,[]) + + def test_legacy_jpt_uses_original_trial_amount_not_actual_oversized_parent(self): + p=self.root(holding=0);p.update(ts_code='688025.SH',exec_qty=0);p['progress']={} + self.ledger=[{'ref_id':'P','action':'OPEN','verdict':'PASS','hard_numbers':hard(313.9,62780,.04)}] + b=service.parent_budget(p) + self.assertEqual((b['amount'],b['quantity_limit']),('15695.00',0)) + self.assertEqual(service.allowed_quantity(p,300,200)[0],0) + + def test_legacy_trial_label_with_standard_ratio_cannot_keep_standard_budget(self): + p=self.root(holding=0);p.update(ts_code='300750.SZ',exec_qty=0);p['progress']={} + self.ledger=[{'ref_id':'P','action':'OPEN','verdict':'PASS', + 'hard_numbers':hard(254.83,101932,.06,target=.06)}] + b=service.parent_budget(p) + self.assertEqual((b['amount'],b['quantity_limit']),('16988.66',0)) + + def test_legacy_trial_without_original_mechanical_ratio_requires_review(self): + h=hard();h['advice'].pop('mechanical') + with self.assertRaisesRegex(ValueError,'原机械目标比例'):service.from_hard(h,CODE) + + def test_standard_holding_keeps_original_grid_permission(self): + h=hard(target=.06,tier='标准仓');b=core.resize(h['advice'],h,CODE)['buy_budget'] + self.root(b=b) + self.assertEqual(service.holding_blocker(CODE),'') + + def test_pending_trial_prevents_grid_preempting_before_first_fill(self): + p=self.root(holding=0);p['exec_qty']=0 + with self.assertRaisesRegex(ValueError,'试探建仓安排'):service.before_parent(CODE,action='ADD') + + def test_verified_user_command_has_separate_explicit_budget(self): + self.root()['status']='EXPIRED' + p=dict(self.parents['P'],instruction_id='C',origin_type='plan',origin_id='CP',exec_qty=0,progress={}) + self.parents['C']=p;self.plans['CP']={'ts_code':CODE,'command_id':'CMD','amount':12000,'qty':200} + self.commands['CMD']={'issued_by':'trader','cmd_type':'OPEN_TARGET'} + self.assertEqual(service.allowed_quantity(p,60,200),(200,'')) + self.assertEqual(service.allowed_quantity(p,61,200)[0],100) + self.assertIn('试探仓',service.holding_blocker(CODE),'明确命令不自动升级其他策略额度') + + def test_fake_command_flag_cannot_bypass_trial(self): + self.root() + p=dict(self.parents['P'],instruction_id='G',origin_type='strategy',action='ADD',progress={'is_command':True,'stype':'GRID'}) + self.assertEqual(service.allowed_quantity(p,1,100)[0],0) + + def test_other_strategy_book_keeps_its_own_budget_path(self): + p=self.root();p['book_id']='micro30' + self.assertEqual(service.allowed_quantity(p,100,200),(200,'')) + + def test_completed_trial_does_not_get_more_after_sale_profit(self): + p=self.root();p['exec_qty']=200;self.filled(200,45,'FILLED') + self.assertEqual(service.allowed_quantity(p,1,100)[0],0) + + def test_actual_lot_total_must_match_booked_fills(self): + p=self.root();self.filled();self.rows[0]['qty']=50;self.pos['total_qty']=50 + with self.assertRaisesRegex(ValueError,'累计量不一致'):service.allowed_quantity(p,1,100) + + def test_current_plan_budget_wins_over_prepared_quantity(self): + p=self.root(holding=0);p['exec_qty']=0 + prepared={'qty':200,'limit_price':50} + smaller=budget(amount=30000);p['progress']['buy_budget']=smaller + with self.assertRaises(ValueError):service.check_order(p,prepared) + + def test_t0_cover_does_not_open_a_new_trial_leg(self): + self.root() + p=dict(self.parents['P'],instruction_id='T',origin_type='strategy',action='T0', + progress={'stype':'T0','leg':'close'}) + self.assertEqual(service.allowed_quantity(p,50,100),(100,'')) + p['progress']['leg']='open' + self.assertEqual(service.allowed_quantity(p,50,100)[0],0) + + +class AtomicAccept(unittest.TestCase): + def test_background_refresh_cannot_enlarge_or_remove_budget(self): + from app.db import session as db + old={'ts_code':CODE,'qty':200,'hard_numbers':{'buy_budget':budget()}} + for updated in (None,budget(amount=120000)): + hard={'preparation':{'status':'ready'},'consumption_id':1} + if updated is not None:hard['buy_budget']=updated + with patch.object(db,'get_engine',side_effect=AssertionError('must reject before write')): + with self.assertRaises(ValueError):db.publish_prepared_proposal(old,{'hard_numbers':hard}, {}) + + def test_accept_reuses_outer_account_transaction(self): + from app.db import session as db + calls=[] + class Connection: + def execute(self,sql,params): + calls.append(str(sql));return SimpleNamespace(rowcount=1) + token=db._TRANSACTION.set(Connection()) + try: + with patch.object(db,'get_engine',side_effect=AssertionError('must reuse outer transaction')),patch.object(db,'_check_cooldown'),patch.object(db,'map_tables',side_effect=lambda sql:sql): + r=db.accept_open_proposal({'action':'OPEN','ts_code':CODE,'qty':200,'proposal_id':'PR','hard_numbers_json':'{}'}, + {'price':50}, {'id':'P','window':3,'progress':{}},'test') + self.assertTrue(r);self.assertEqual(len(calls),3) + finally:db._TRANSACTION.reset(token) + + +if __name__=='__main__':unittest.main() diff --git a/scripts/test_trade_correction_strategy.py b/scripts/test_trade_correction_strategy.py index db4761b..42f6435 100644 --- a/scripts/test_trade_correction_strategy.py +++ b/scripts/test_trade_correction_strategy.py @@ -14,7 +14,7 @@ from sqlalchemy import create_engine, event, text from app.core import strategy_book as books from app.db import session as db from app.repo import pms_repo -from app.services import strategy_runner as runner, rotation_service, grid_inventory +from app.services import strategy_runner as runner, rotation_service, grid_inventory, buy_budget from config.settings import settings CODE = '600001.SH' @@ -60,6 +60,8 @@ class StrategyCorrectionTests(unittest.TestCase): (runner.market, 'day_snapshot', lambda code: {'price': 10, 'bar_time': self.now.isoformat()}), (pms_repo, 'get_position', lambda code: {'total_qty':100, 'add_qty':100, 'avail_qty':100}), (grid_inventory, 'snapshot', lambda st, pos: {'invested':1000, 'filled_levels':{'0':{'price':10,'qty':100,'sell_target':10.4}}}), + # 本套为有明确标准仓预算的事务夹具;试探、未知及跨轮预算由test_buy_budget独立验证。 + (buy_budget, 'holding_blocker', lambda code, **kw: ''), # 此套只测事务与更正交错;真实批次和报价校验由 test_grid_execution 覆盖。 (runner, '_validate_grid_decision', lambda st, dec: None), ]: diff --git a/scripts/test_wiring.py b/scripts/test_wiring.py index fa2bf09..874419b 100644 --- a/scripts/test_wiring.py +++ b/scripts/test_wiring.py @@ -131,6 +131,9 @@ class FakeRepo: and (not ts_code or p["ts_code"] == ts_code)] return sorted(out, key=lambda p: p.get("priority", 100))[:limit] + def get_plan(self, plan_id): + return next((dict(p) for p in self.plans if p['plan_id'] == plan_id), None) + def update_plan(self, plan_id, *, status=None, filled_qty=None): for p in self.plans: if p["plan_id"] == plan_id: