From 5c303736a05f3ef8e5276b875d839503c65b96e9 Mon Sep 17 00:00:00 2001 From: baobao Date: Mon, 9 Nov 2026 12:40:37 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E7=BD=91=E6=A0=BC=E6=A0=B8?= =?UTF-8?q?=E9=94=80=E6=89=B9=E6=AC=A1=E5=B9=B6=E8=A1=A5=E9=BD=90=E6=8A=A5?= =?UTF-8?q?=E4=BB=B7=E4=B8=8E=E9=80=80=E5=87=BA=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DEVLOG.md | 5 ++ app/core/grid_inventory.py | 47 +++++++++++- app/services/exec_advisor.py | 14 +++- app/services/grid_inventory.py | 3 + app/services/strategy_runner.py | 61 ++++++++-------- docs/网格档距与成交余量修复_2026-11-09.md | 13 ++++ scripts/run_tests.py | 2 +- scripts/test_batch17_units.py | 2 +- scripts/test_grid_execution.py | 88 ++++++++++++++++++++++- 9 files changed, 198 insertions(+), 37 deletions(-) diff --git a/DEVLOG.md b/DEVLOG.md index ca22156..1a6da88 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -2937,3 +2937,8 @@ PMS最终代码56db0fd已推送,155 web/WS/beat为execution-2b1c447,worker ### 2026-11-09 12:24 4%网格发布及迁移完成 155仅web、worker发布3ca6819,候选pms:grid-four-3ca6819完成81批断网全量。排空目标worker后,12:23将默认及两条生效网格迁移到4%,真实库存与参数原子留审计,恢复策略调度true,原暂停与风险退出保持。17个其他容器未变、唯一WS未动。12:24确认1734071连续、pending/orphan为0,双策略数量和现金差0。雷赛1500股网格余量下限49.18元、四方1000股下限32.63元,底仓与历史成交保留。自然任务已恢复,盘中执行在午间按规则跳过;新规则自然成交仍未判收。首次维护审计标识超长被校验中止,缩短后成功,没有改表或业务数据。详情见[发布接续](docs/网格档距与成交余量修复_2026-11-09.md)。 + + +## 2026-11-09 代码再次复核(开发) + +针对用户追问,沿策略评估、实际卖出核销和全部报价模式复核,找到多批次网格顺序与账本不一致、零散成交不足申报单位、旧报价分支丢失父价格边界,另补部分止盈向整仓风险退出升级。已统一调用实际核销函数、透传批次清单及价格边界,专项50例通过。当前两条网格均为单批次,未出现上述多批次影响;候选和发布结果随后记录于[接续](docs/网格档距与成交余量修复_2026-11-09.md)。 diff --git a/app/core/grid_inventory.py b/app/core/grid_inventory.py index af77f0a..58105dc 100644 --- a/app/core/grid_inventory.py +++ b/app/core/grid_inventory.py @@ -1,5 +1,8 @@ """网格只认已入账的剩余批次;几何档位与实际成交价各司其职。""" from decimal import Decimal, ROUND_CEILING, ROUND_FLOOR +from datetime import datetime +from app.core.cushion import sell_allocation +from app.core.execution_policy import supported_code def price_tick(value, *, sell=False): @@ -12,13 +15,33 @@ def price_tick(value, *, sell=False): def project(strategy, lots, parents): """输入同证券、同账本剩余批次及父指令,输出本网格真实库存。无网络与写入。""" sid, code = strategy['strategy_id'], strategy['ts_code'] + if not supported_code(code): + raise ValueError('网格仅支持沪深A股') params = strategy.get('params') or {} pct = Decimal(str(params.get('step_pct') or 0)) step = Decimal(str(params.get('step') or 0)) if not pct.is_finite() or not step.is_finite() or (pct <= 0 and step <= 0): raise ValueError('网格档距无法核实') + # 与真实成交及成交修正共用核销顺序:增量按开仓日新→旧,同日按批次编号。 + # 做T批次的核销优先级更高,未平时不能将网格卖单误记入做T。 + open_lots = [lot for lot in lots if int(lot.get('qty') or 0) > 0] + if any(lot.get('lot_type') == 'T0' for lot in open_lots): + raise ValueError('同股仍有未平做T批次,网格等待核对') + candidates, by_id = [], {} + for lot in open_lots: + if lot.get('lot_type') != 'ADD': + continue + lid = int(lot['id']) + if lid in by_id: + raise ValueError('网格批次重复') + day = datetime.strptime(str(lot.get('open_date'))[:10].replace('-', ''), '%Y%m%d') + candidates.append({'lot_id':lid, 'lot_type':'ADD', 'qty':int(lot['qty']), 'open_date':int(day.strftime('%Y%m%d'))}) + by_id[lid] = lot + candidates.sort(key=lambda row:(row['open_date'], row['lot_id'])) + ordered = sell_allocation(candidates, sum(row['qty'] for row in candidates)) filled, invested = {}, Decimal(0) - for lot in lots: + for allocation in ordered: + lot = by_id[allocation['lot_id']] qty = int(lot.get('qty') or 0) if qty <= 0 or lot.get('lot_type') != 'ADD': continue @@ -48,3 +71,25 @@ def project(strategy, lots, parents): 'buy_instruction_id': parent['instruction_id'], 'lot_id': lot['id']} invested += qty * cost return {'filled_levels': filled, 'invested': float(invested), 'inventory_source': 'booked_lots'} + + +def sell_slice(filled, qty, *, price=None): + """按账本顺序取连续的可卖批次;任一批未到价便停止,不跨过它核销后面的批次。""" + remaining = int(qty) + slices, floor = [], 0. + for key, row in filled.items(): + available = int(row.get('qty') or 0) + if available <= 0: + continue + target = float(row.get('sell_target') or 0) + price_tick(target, sell=True) # 同时拒绝未知、无穷或NaN边界。 + if price is not None and price < target: + break + take = min(remaining, available) + if take > 0: + slices.append({'lot_id':row.get('lot_id'), 'qty':take}) + floor = max(floor, target) + remaining -= take + if remaining <= 0: + break + return {'qty':int(qty)-remaining, 'lots':slices, 'limit_price':floor} diff --git a/app/services/exec_advisor.py b/app/services/exec_advisor.py index cfdff23..c06bd5f 100644 --- a/app/services/exec_advisor.py +++ b/app/services/exec_advisor.py @@ -83,7 +83,7 @@ def _post(url: str, payload: dict, timeout: int) -> dict: def _strategy_immediate(*, side, now, day, quota, fired_today, - is_last_day: bool = True, urgent: bool = False) -> dict: + is_last_day: bool = True, urgent: bool = False, instruction_limit=None) -> dict: """网格/跟踪止盈的到价即成交决策: 只做硬事实检查(配额/时段/停牌/一字板), 不做 vwap 择时, 不做 14:45 强制。真正的合规(单股上限/T+1/暂停买入等)由 run_tick 随后的 rule_gate 终检兜底。 这样网格是"到档位价才成交、当日没成交则由窗口收口作废", 不会像命令那样被收盘强平成市价单。 @@ -111,7 +111,15 @@ def _strategy_immediate(*, side, now, day, quota, fired_today, if str(side).lower() == "sell" and day.get("limit_down"): return _o(et.ACT_WAIT, "跌停封板, 挂单等回封") disc = 1.002 if str(side).lower() == "buy" else 0.998 - return _o(et.ACT_FIRE, f"按档触发即时成交, 现价 {price}", round(price * disc, 2)) + limit = round(price * disc, 2) + if instruction_limit is not None: + from app.core.execution_policy import positive + from app.core.grid_inventory import price_tick + bound = positive(instruction_limit) + if not bound: + return _o(et.ACT_WAIT, '策略价格边界无效') + limit = price_tick(min(limit,bound) if side == 'buy' else max(limit,bound), sell=side == 'sell') + return _o(et.ACT_FIRE, f"按档触发即时成交, 现价 {price}", limit) def decide(*, side: str, action: str, ts_code: str, now, day: dict, params: dict, @@ -142,7 +150,7 @@ def decide(*, side: str, action: str, ts_code: str, now, day: dict, params: dict # 只识别策略来源且类型为 GRID/TRAIL 的指令; 做T(T0)与其余来源一律走原有逻辑, 不受影响。 if (prog or {}).get("origin") == "strategy" and str((prog or {}).get("stype")) in ("GRID", "TRAIL"): return _strategy_immediate(side=side, now=now, day=day, quota=quota, fired_today=fired_today, - is_last_day=is_last_day, urgent=urgent) + is_last_day=is_last_day, urgent=urgent, instruction_limit=instruction_limit) if not available(): d = et.decide(side=side, now=now, day=day, params=params, is_last_day=is_last_day, diff --git a/app/services/grid_inventory.py b/app/services/grid_inventory.py index 2155240..86caad7 100644 --- a/app/services/grid_inventory.py +++ b/app/services/grid_inventory.py @@ -4,6 +4,9 @@ from app.repo import pms_repo def snapshot(strategy, position): + from app.core.execution_policy import supported_code + if not supported_code(strategy.get('ts_code')): + raise ValueError('网格仅支持沪深A股') with books.scope('original'): lots = pms_repo.list_lots(strategy['ts_code'], limit=10001) if len(lots) >= 10001: diff --git a/app/services/strategy_runner.py b/app/services/strategy_runner.py index fb956fa..6a80d98 100644 --- a/app/services/strategy_runner.py +++ b/app/services/strategy_runner.py @@ -172,7 +172,7 @@ def _emit_instruction(st: dict, dec: dict, *, forced: bool = False) -> str: "strategy_correction_id": _correction_id(st), "leg": dec["leg"], "reason": dec.get("reason"), "forced": bool(forced)} if st.get('type') == 'GRID': - prog.update({k: deepcopy(dec.get(k)) for k in ('grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id')}) + 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 st.get('type') == 'GRID': _validate_grid_decision(st, dec) @@ -195,7 +195,7 @@ def _emit_proposal(st: dict, dec: dict) -> str: "strategy_correction_id": _correction_id(st), "side": dec["side"], "leg": dec["leg"], "action": dec["action"], "qty": int(dec["qty"]), "reason": dec.get("reason"), "entry": dec.get("entry")} - hard.update({k: deepcopy(dec.get(k)) for k in ('dir', 'limit_price', 'grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id')}) + hard.update({k: deepcopy(dec.get(k)) for k in ('dir', 'limit_price', 'grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id', 'grid_lots')}) expire = now.replace(hour=15, minute=0, second=0, microsecond=0) with _current_strategy(st): if pms_repo.insert_proposal(proposal_id=pid, ts_code=code, action=dec["action"], @@ -222,7 +222,7 @@ def emit_from_spec(spec: dict) -> dict: dec = {"side": spec["side"], "action": spec["action"], "qty": int(spec["qty"]), "leg": spec.get("leg") or "open", "reason": spec.get("reason"), "entry": spec.get("entry")} - dec.update({k: deepcopy(spec.get(k)) for k in ('dir', 'limit_price', 'grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id')}) + dec.update({k: deepcopy(spec.get(k)) for k in ('dir', 'limit_price', 'grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id', 'grid_lots')}) iid = _emit_instruction(st, dec) state = dict(st.get("state") or {}) state["pending"] = {"iid": iid, "leg": dec["leg"], "dir": spec.get("dir"), @@ -439,24 +439,21 @@ def _eval_grid(st, pos, day, now, ctx): raise ValueError('网格库存超过实际增量,等待批次核对') per_lot = max(_min_lot(st.get('ts_code')), _round_lot(params.get('per_lot')) or LOT) cur, last = _band(levels, price), state.get('last_band') - # 批次按账本FIFO顺序处理,避免TRIM核销另一档尚未到价的库存。 - for key, info in filled.items(): - qty = int(info.get('qty') or 0) - if not qty: - continue - target = _f(info.get('sell_target')) - if target <= 0: - raise ValueError('网格批次缺少实际成本对应的卖出下限') - if price < target: - break - q = min(per_lot, _round_lot(qty), _round_lot(actual_add), _round_lot(avail)) - if q < _min_lot(st.get('ts_code')): - return None + # 按账本实际核销顺序取连续批次,可合并零散成交,但不借用底仓凑申报数量。 + from app.core.grid_inventory import sell_slice + offered = sell_slice(filled, min(per_lot, actual_add, avail), price=price) + q = _round_lot(offered['qty']) + if q >= _min_lot(st.get('ts_code')): + selected = sell_slice(filled, q, price=price) state['last_band'] = cur - return {'side': 'sell', 'action': A_SELL, 'qty': q, 'leg': f'grid_sell:{key}', - 'grid_lot_id': info.get('lot_id'), 'grid_params': deepcopy(params), - 'limit_price': target, - 'reason': f'网格卖: 现价 {price} 达已成交批次卖出线 {target},余量 {qty} 股,本次卖 {q} 股'} + first = selected['lots'][0]['lot_id'] + target = selected['limit_price'] + return {'side':'sell', 'action':A_SELL, 'qty':q, 'leg':f'grid_sell:{first}', + 'grid_lot_id':first, 'grid_lots':selected['lots'], 'grid_params':deepcopy(params), + 'limit_price':target, + 'reason':f'网格卖: 现价 {price} 达实际核销批次卖出线 {target},本次卖 {q} 股'} + if offered['qty'] > 0: + return None if price < levels[0]: state['below_floor'] = True state['last_band'] = cur @@ -505,9 +502,13 @@ def _validate_grid_decision(st, dec): if qty <= 0 or qty > ceiling_qty: raise ValueError('网格委托数量无效') if dec['side'] == 'sell': - first = next(iter(inventory['filled_levels'].values()), {}) - if (first.get('lot_id') != dec.get('grid_lot_id') or qty > int(first.get('qty') or 0) - or _f(dec['limit_price']) < _f(first.get('sell_target'))): + from app.core.grid_inventory import sell_slice + selected = sell_slice(inventory['filled_levels'], qty) + # 旧单批提议仅在仍然恰好核销同一批次时兼容;不能自动扩展到另一批。 + expected = dec.get('grid_lots') or [{'lot_id':dec.get('grid_lot_id'), 'qty':qty}] + if (qty > int(pos.get('avail_qty') or 0) or qty % LOT or qty < _min_lot(st['ts_code']) + or selected['qty'] != qty or selected['lots'] != expected + or _f(dec['limit_price']) < selected['limit_price']): raise ValueError('网格卖出批次、数量或价格下限已变化') else: paused = _buypause_codes() @@ -592,14 +593,16 @@ def _eval_trail(st, pos, day, now, ctx): if profit >= start: state['armed'] = True due = state.get('trail_due') - if not due: + sar = _f(params.get('sar_line')) + sar_exit = (sar > 0 and now is not None and now.hour*100+now.minute >= 945 + and param_store.get_bool('PMS_TECH_SAR_STOP_ON_TRAIL', True) + and price <= sar*(1-param_store.get_float('PMS_TECH_SAR_STOP_BUFFER', .003))) + hard_exit = hard > 0 and profit >= hard + if not due or (due.get('partial') and (sar_exit or hard_exit)): leg, qty, partial, why = '', 0, False, '' - sar = _f(params.get('sar_line')) - if (sar > 0 and now is not None and now.hour*100+now.minute >= 945 - and param_store.get_bool('PMS_TECH_SAR_STOP_ON_TRAIL', True) - and price <= sar * (1-param_store.get_float('PMS_TECH_SAR_STOP_BUFFER', .003))): + if sar_exit: leg, qty, why = 'trail_sar', total, f'现价 {price} 跌破SAR止损线 {sar}' - elif hard > 0 and profit >= hard: + elif hard_exit: leg, qty, why = 'trail_hard', total, f'浮盈 {profit:.1%} 达硬目标 {hard:.1%}' elif state.get('armed') and giveback > 0 and price <= hw*(1-giveback) and (ratio >= 1 or hw > _f(state.get('trail_fired_hw'))+1e-9): partial = ratio < 1 diff --git a/docs/网格档距与成交余量修复_2026-11-09.md b/docs/网格档距与成交余量修复_2026-11-09.md index 3ca9f8c..d74e3f6 100644 --- a/docs/网格档距与成交余量修复_2026-11-09.md +++ b/docs/网格档距与成交余量修复_2026-11-09.md @@ -48,3 +48,16 @@ 退出纪律仍开启,原起算时间不变。六只当前原策略持仓中,雷赛与宁德均为一次有效信号后的STOP_BUY,其他四只为WATCH;既有评级记录没有新下降事件。雷赛最新有效评级为“好”,当前符合只停买、保留正常网格卖出的规则。首次停买、第二次独立信号整仓退出、任一级正式评级下降退出继续沿既有逻辑执行。 尚未自然判收:发布在午间,无新鲜开市行情,也没有新4%网格的自然委托或成交。本次没有手动调用实盘tick、注入模型请求或制造回报;37项专项和迁移成功不能冒充自然成交。下次自然交易时段按新行情、实际可卖量及正式报价边界执行。当前没有生效TRAIL或T0,本次相关修复仅有隔离回归证据。未知费用保持未知,4%不宣称扣费后收益保证。未开启新的定期观察或自动任务。 + + +## 12:39代码再次复核 + +用户要求再检查代码正确性。本轮沿实际核销函数逐层复核,不把81批测试通过当作所有路径已覆盖。确认前一版本还有三个边界缺陷,已在开发机修复,待最终候选通过后定向发布: + +1. 网格投影按旧批次优先,但实际账本`cushion.sell_allocation`对ADD按开仓日新到旧核销,同日保持批次编号顺序。跨日多批次会出现成本下限与实际被卖批次不符。改为投影直接调用同一核销函数;卖出指令、提议带明确批次数量清单,采纳时再次核对。上一版本文中“FIFO”描述不成立,以本节为准。当前雷赛、四方各只有一个网格批次,因此尚不受该顺序问题影响。 +2. 单个成交批次小于申报单位会挡住后续已到价批次。改为按核销顺序合并连续且已到价的批次,再按当前申报单位取整;卖出下限取所涉批次中最高者,不跨过未到价批次,不借底仓凑数量。同股如仍有优先核销的做T批次则网格等待,防止错归属。 +3. 关闭改价与QMT限价监控后,旧即时执行分支未接收父指令价格边界。现将边界透传并按方向取整;三种执行模式均不得突破网格买入上限或卖出下限。当前155仍开着新报价模式,没有因此产生越界报价。 + +另外,跟踪止盈已有未完成部分减持时,新的SAR退出或硬目标应升级为整仓退出,不能继续只处理原部分目标。现按剩余实际持仓升级,仍受可卖量限制。当前没有生效TRAIL,这一项仅由隔离用例验证。 + +专项由37例增至50例,新增覆盖跨日及同日真实核销顺序、调用实际卖出记账函数核对批次清单、零散成交合并、不得借底仓、部分成交余量、未平做T隔离、三种报价路径、风险退出升级及父指令/提议元数据。没有改账本核销规则、旧成交或4%存量迁移记录;新的库存仍在正常调度中从真实批次重建。 diff --git a/scripts/run_tests.py b/scripts/run_tests.py index da89d51..7a13e2e 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -6,7 +6,7 @@ test_batch54_units.py 用户候选来源、到期核验、权限、显式取用、技术面补读及评级排序透传 (10例) -4%网格真实批次、完整价差、未成交重试及迁移事务专项37例。 +4%网格真实批次、账本核销顺序、零散成交合并、三种报价边界、退出升级及迁移事务专项50例。 成交修正专项:批次投影36例、传输与执行保护29例、服务事务36例、 普通成交凭据与仓储13例、网格更正版本与并发20例。 diff --git a/scripts/test_batch17_units.py b/scripts/test_batch17_units.py index ec983db..cc9bd44 100644 --- a/scripts/test_batch17_units.py +++ b/scripts/test_batch17_units.py @@ -861,7 +861,7 @@ def _(): def _book_grid_remainder(st, state, qty, band): from app.core.grid_inventory import project code = st['ts_code'] - lots = [{'id':band, 'ts_code':code, 'lot_type':'ADD', 'qty':qty, 'open_price':9.8, 'instruction_id':'buy'}] + lots = [{'id':band, 'ts_code':code, 'lot_type':'ADD', 'qty':qty, 'open_price':9.8, 'open_date':'2026-11-04', 'instruction_id':'buy'}] parents = {'buy': {'instruction_id':'buy','ts_code':code,'origin_type':'strategy','origin_id':st['strategy_id'],'side':'buy','action':'ADD','progress':{'leg':'grid_buy:1'}}} state.update(project(st, lots, parents)) diff --git a/scripts/test_grid_execution.py b/scripts/test_grid_execution.py index 6b8cc25..b47692c 100644 --- a/scripts/test_grid_execution.py +++ b/scripts/test_grid_execution.py @@ -18,7 +18,7 @@ def strategy(params=None): return dict(strategy_id='grid', ts_code='002979.SZ', type='GRID', status='ACTIVE', params=copy.deepcopy(params or P), state={}) def records(qty=1500, price=47.28): parent = dict(instruction_id='buy',ts_code='002979.SZ',origin_type='strategy',origin_id='grid',side='buy',action='ADD',book_id='original',progress={'leg':'grid_buy:1'}) - lot = dict(id=1,ts_code='002979.SZ',lot_type='ADD',qty=qty,open_price=price,instruction_id='buy',book_id='original') + lot = dict(id=1,ts_code='002979.SZ',lot_type='ADD',qty=qty,open_price=price,open_date='2026-11-04',instruction_id='buy',book_id='original') return [lot], {'buy':parent} def pos(qty=1500, avail=1600): return dict(total_qty=qty+100,add_qty=qty,avail_qty=avail) @@ -78,7 +78,7 @@ class EvaluationTests(unittest.TestCase): def test_does_not_sell_base_or_borrow_another_lot(self): self.state.update(core.project(self.st,*records(qty=300)));self.st['params']['per_lot']=1600 self.assertEqual(evaluate(self.st,self.state,pos(qty=300,avail=800),51.87)['qty'],300) - def test_fifo_lot_not_yet_ready_blocks_later_lot_sale(self): + def test_next_accounting_lot_not_yet_ready_blocks_later_lot_sale(self): self.state['filled_levels']['1']['sell_target']=53 self.state['filled_levels']['2']={'qty':100,'price':40,'sell_target':42,'lot_id':2} self.assertIsNone(evaluate(self.st,self.state,pos(qty=1600),51.87)) @@ -237,4 +237,88 @@ class AdditionalBoundaryTests(unittest.TestCase): self.assertTrue(runner._reconcile(st,state,{})) self.assertIsNone(runner._eval_trail(st,{'total_qty':100,'avail_qty':100,'avg_cost':11},{'price':9},dt.datetime(2026,11,9,10),{'state':state})) + +class AccountingOrderReviewTests(unittest.TestCase): + def fixture(self, code='002979.SZ', quantities=(100,100), prices=(10,12)): + st=strategy(dict(center=11,lower=8,upper=14,step_pct=.04,per_lot=1000,max_capital=100000));st['ts_code']=code + lots, parents=records(quantities[0],prices[0]);lots[0]['ts_code']=code;parents['buy']['ts_code']=code + lots.append({**lots[0],'id':2,'qty':quantities[1],'open_price':prices[1],'open_date':'2026-11-06'}) + return st,lots,parents + def test_ledger_and_grid_use_identical_newest_day_first_order(self): + st,lots,parents=self.fixture();snap=core.project(st,list(reversed(lots)),parents) + self.assertEqual(list(snap['filled_levels']),['2','1']) + from app.core.cushion import sell_allocation + actual=sell_allocation([{'lot_id':l['id'],'lot_type':'ADD','qty':l['qty'],'open_date':int(l['open_date'].replace('-',''))} for l in lots],200) + self.assertEqual(core.sell_slice(snap['filled_levels'],200)['lots'],actual) + def test_newer_expensive_lot_cannot_be_sold_using_old_cheaper_cost(self): + st,lots,parents=self.fixture();snap=core.project(st,lots,parents) + self.assertIsNone(evaluate(st,snap,pos(200,300),11.5)) + def test_same_day_uses_id_order_even_if_input_reversed(self): + st,lots,parents=self.fixture();lots[0]['open_date']=lots[1]['open_date'] + snap=core.project(st,list(reversed(lots)),parents) + self.assertEqual(list(snap['filled_levels']),['1','2']) + def test_split_star_fills_combine_to_legal_quantity_and_keep_base(self): + st,lots,parents=self.fixture('688100.SH');snap=core.project(st,lots,parents) + d=evaluate(st,snap,pos(200,300),13) + self.assertEqual(d['qty'],200);self.assertEqual(d['grid_lots'],[{'lot_id':2,'qty':100},{'lot_id':1,'qty':100}]) + self.assertEqual(d['limit_price'],12.48) + with patch.object(pms_repo,'list_instructions',return_value=[]),patch.object(pms_repo,'get_position',return_value=pos(200,300)),patch.object(service,'snapshot',return_value=snap): + runner._validate_grid_decision(st,d) + with self.assertRaises(ValueError):runner._validate_grid_decision(st,{**d,'limit_price':10.4}) + with self.assertRaises(ValueError):runner._validate_grid_decision(st,{**d,'grid_lots':list(reversed(d['grid_lots']))}) + def test_unready_second_piece_is_not_borrowed_to_reach_minimum(self): + st,lots,parents=self.fixture('688100.SH',prices=(12,10));snap=core.project(st,lots,parents) + self.assertIsNone(evaluate(st,snap,pos(200,300),11)) + def test_one_hundred_star_add_does_not_borrow_base(self): + st,lots,parents=self.fixture('688100.SH',quantities=(0,100));snap=core.project(st,lots,parents) + self.assertIsNone(evaluate(st,snap,pos(100,300),13)) + def test_small_fills_form_one_lot_without_rounding_each_piece_away(self): + st,lots,parents=self.fixture(quantities=(75,25));snap=core.project(st,lots,parents) + d=evaluate(st,snap,pos(100,200),13) + self.assertEqual(d['qty'],100);self.assertEqual([r['qty'] for r in d['grid_lots']],[25,75]) + def test_partial_sale_keeps_actual_remaining_lots(self): + st,lots,parents=self.fixture(quantities=(150,150));snap=core.project(st,lots,parents) + st['params']['per_lot']=200 + d=evaluate(st,snap,pos(300,400),13);self.assertEqual(d['grid_lots'],[{'lot_id':2,'qty':150},{'lot_id':1,'qty':50}]) + lots[1]['qty']=0;lots[0]['qty']=100;snap=core.project(st,lots,parents) + remaining=evaluate(st,snap,pos(100,200),13);self.assertEqual(remaining['qty'],100);self.assertEqual(remaining['grid_lot_id'],1) + def test_open_t0_and_missing_dates_fail_closed(self): + st,lots,parents=self.fixture();lots.append({**lots[0],'id':3,'lot_type':'T0'}) + with self.assertRaisesRegex(ValueError,'做T'):core.project(st,lots,parents) + lots.pop();lots[0].pop('open_date') + with self.assertRaises(ValueError):core.project(st,lots,parents) + def test_actual_sell_accounting_closes_the_same_pieces(self): + from app.services import ledger_service + st,lots,parents=self.fixture(quantities=(150,150));snap=core.project(st,lots,parents) + st['params']['per_lot']=200;d=evaluate(st,snap,pos(300,400),13);closed=[] + with patch.object(pms_repo,'ensure_position'),patch.object(pms_repo,'list_lots',return_value=lots),patch.object(pms_repo,'close_lot_qty',side_effect=lambda lid,**kw:closed.append({'lot_id':lid,'qty':kw['qty']})),patch.object(pms_repo,'bump_position_qty'): + ledger_service._apply_action({'kind':'SELL','ts_code':st['ts_code'],'qty':d['qty'],'price':d['limit_price']}) + self.assertEqual(closed,d['grid_lots']) + +class ExitBoundaryReviewTests(unittest.TestCase): + def test_all_three_execution_modes_preserve_grid_price_boundary(self): + from app.services import exec_advisor, market + now=dt.datetime(2026,11,9,10);quote={'kind':'minute','source':'recorded-test','as_of':'2026-11-09T10:00:00+08:00','last':10,'limit_down':9,'limit_up':11} + for mode in ['legacy','monitor','reprice']: + flags={'PMS_EXEC_REPRICE_ENABLED':mode=='reprice','PMS_EXEC_QMT_PRICE_MONITOR':mode=='monitor','PMS_EXEC_ALLOW_MINUTE_QUOTE':True} + with patch.object(exec_advisor.param_store,'get_bool',side_effect=lambda k,d=False:flags.get(k,d)),patch.object(exec_advisor.param_store,'get_float',side_effect=lambda k,d=0:d),patch.object(exec_advisor.param_store,'get_int',side_effect=lambda k,d=0:d),patch.object(market,'execution_quote',return_value=quote): + for side,limit in [('buy',9.99),('sell',10.01)]: + result=exec_advisor.decide(side=side,action='ADD' if side=='buy' else 'TRIM',ts_code='600000.SH',now=now,day={'price':10},params={},is_last_day=True,is_command=False,quota=100,prog={'origin':'strategy','stype':'GRID'},instruction_limit=limit) + self.assertEqual(result['action'],'FIRE',(mode,result)) + self.assertTrue(result['limit_price']<=limit if side=='buy' else result['limit_price']>=limit,(mode,side,result)) + def test_sar_upgrades_partial_profit_target_to_whole_remaining_position(self): + for hard in [False,True]: + st={'type':'TRAIL','ts_code':'600000.SH','params':{'sar_line':0 if hard else 10,'hard_target':.2 if hard else 0,'giveback':.05,'sell_ratio':.5}} + state={'high_water':12,'trail_due':{'qty':200,'partial':True,'leg':'trail_sell','high_water':12,'reason':'old'}} + with patch.object(runner.param_store,'get_bool',return_value=True),patch.object(runner.param_store,'get_float',side_effect=lambda k,d:d): + d=runner._eval_trail(st,{'total_qty':800,'avail_qty':700,'avg_cost':10},{'price':13 if hard else 9},dt.datetime(2026,11,9,10),{'state':state}) + self.assertEqual(d['action'],'EXIT');self.assertEqual(d['qty'],700) + self.assertEqual(state['trail_due']['qty'],800);self.assertFalse(state['trail_due']['partial']) + def test_parent_and_proposal_keep_exact_piece_list(self): + st=strategy();d={'side':'sell','action':'TRIM','qty':200,'leg':'grid_sell:2','grid_lots':[{'lot_id':2,'qty':100},{'lot_id':1,'qty':100}],'grid_lot_id':2,'grid_params':P,'limit_price':49.18} + with patch.object(runner,'_current_strategy',return_value=nullcontext(st)),patch.object(runner,'_validate_grid_decision'),patch.object(pms_repo,'insert_instruction',return_value=1) as ins,patch.object(pms_repo,'insert_proposal',return_value=1) as prop: + runner._emit_instruction(st,d);runner._emit_proposal(st,d) + self.assertEqual(ins.call_args.kwargs['progress']['grid_lots'],d['grid_lots']) + self.assertEqual(prop.call_args.kwargs['hard_numbers']['grid_lots'],d['grid_lots']) + if __name__=='__main__':unittest.main()