"""执行依据与报价的纯规则。未知事实不能授权买入,不推测盘口。""" from datetime import datetime, timezone, timedelta, date from decimal import Decimal, ROUND_CEILING, ROUND_FLOOR import math import re BEIJING = timezone(timedelta(hours=8)) def supported_code(code): return bool(re.fullmatch(r'(?:60\d{4}\.SH|68\d{4}\.SH|00\d{4}\.SZ|30\d{4}\.SZ)', str(code or '').upper())) def local_now(now=None): value = now or datetime.now(BEIJING) return value.replace(tzinfo=BEIJING) if value.tzinfo is None else value.astimezone(BEIJING) def timestamp(value): try: parsed = datetime.fromisoformat(str(value).replace('Z', '+00:00')) return parsed.astimezone(BEIJING) if parsed.tzinfo is not None else None except (ValueError, TypeError): return None def positive(value): try: number = float(value) return number if math.isfinite(number) and number > 0 else 0. except (TypeError, ValueError): return 0. def basis_reason(basis, now=None, max_source_days=7): """空串表示依据有效;拒绝无来源、无版本、无时区和过期事实。""" if not isinstance(basis, dict): return '执行依据缺失' if basis.get('continuation') == 'STOP': return '机会已撤销:' + str(basis.get('reason') or '上游明确停止') if basis.get('quality') != 'VALID' or basis.get('continuation') != 'CONTINUE': return '执行依据不可用或机会状态未知:' + str(basis.get('reason') or '') if not str(basis.get('version') or '').strip() or not str(basis.get('source') or '').strip(): return '执行依据缺少版本或来源' generated, until = timestamp(basis.get('generated_at')), timestamp(basis.get('valid_until')) current = local_now(now) if not generated or not until or not generated <= current < until: return '执行依据时间无效或已过期' try: source_day = date.fromisoformat(str(basis.get('source_date'))) except (ValueError, TypeError): return '执行依据缺少有效数据日期' if source_day > generated.date() or not 0 <= (current.date()-source_day).days <= max_source_days: return '执行依据数据日期超出有效范围' return '' def price_order(*, side, quote, now=None, user_limit=None, anchor_price=None, params=None): """按对手盘报价;分钟行情只能显式降级,并始终遵守用户价格边界。""" prm, current = params or {}, local_now(now) def wait(why): return {'action': 'WAIT', 'limit_price': None, 'reason': why, 'degraded': False} if side not in ('buy', 'sell') or not isinstance(quote, dict): return wait('委托方向或行情无效') if quote.get('halted'): return wait('证券停牌,不报价') kind, source = quote.get('kind'), str(quote.get('source') or '') at = timestamp(quote.get('as_of')) if not source or not at or at.date() != current.date(): return wait('行情缺少当日来源或明确时间') age = (current-at).total_seconds() minute = kind == 'minute' max_age = float(prm.get('minute_max_age_sec', 90) if minute else prm.get('quote_max_age_sec', 15)) if age < 0 or age > max_age: return wait('行情已过期或时间超前') low, high, last = (positive(quote.get(k)) for k in ('limit_down', 'limit_up', 'last')) if not low or not high or low > high or not last: return wait('行情价格或当日价格上下限不可核实') tick = .01 if minute: if not prm.get('allow_minute', True): return wait('没有实时盘口,分钟行情降级未启用') offset = max(0., float(prm.get('minute_slippage_pct', .002))) proposed = last*(1+offset if side == 'buy' else 1-offset) note = '分钟行情降级报价(无实时盘口)' elif kind == 'level1': counter = positive(quote.get('ask' if side == 'buy' else 'bid')) bid, ask = positive(quote.get('bid')), positive(quote.get('ask')) if not counter or (bid and ask and bid > ask): return wait('对手盘口缺失或买卖价异常') proposed = counter + (1 if side == 'buy' else -1)*tick*max(0, int(prm.get('offset_ticks', 1))) note = '实时对手盘口报价' else: return wait('行情种类未经核实') anchor = positive(anchor_price) or last slippage = max(0., float(prm.get('max_slippage_pct', .01))) boundary = positive(user_limit) if user_limit is not None and not boundary: return wait('用户价格边界无效') if side == 'buy': ceiling = min(high, last*(1+slippage), boundary or high) price = Decimal(str(min(proposed, ceiling))).quantize(Decimal('.01'), rounding=ROUND_FLOOR) else: floor = max(low, last*(1-slippage), boundary or low) price = Decimal(str(max(proposed, floor))).quantize(Decimal('.01'), rounding=ROUND_CEILING) value = float(price) if not low <= value <= high: return wait('用户边界或报价超出当日合法价格范围') return {'action': 'FIRE', 'limit_price': value, 'reason': note, 'degraded': minute, 'quote_source': source, 'quote_as_of': at.isoformat(), 'quote_age_sec': age, 'anchor_price': anchor, 'user_limit': boundary or None}