"""mock 撮合引擎:以内存态模拟永续合约撮合系统的核心业务行为。 本模块是"被测系统"的替身,实现下单冻结、市价成交开仓、撤单解冻、 标记价格设置与强平风控检查等行为,并同步写入 MockMySQL(落库)与 MockRedis(缓存),为用例的"三重校验"提供数据面。 注意:引擎内部的资金计算刻意**不复用** formula 包,而是独立实现一份 Decimal 运算 —— 与真实工程保持同一形态:被测系统是独立服务,期望值 由测试侧公式层独立计算后再与系统行为比对。 """ import json from decimal import Decimal from framework import settings from mock.fake_cache import MockRedis from mock.fake_db import MockMySQL class ParamError(Exception): """请求参数非法;field 属性携带出错的字段名。""" def __init__(self, field): super().__init__(field) self.field = field # 订单状态:2-待撮合 3-已撤销 22-全部成交 ORDER_STATUS_WAIT = 2 ORDER_STATUS_CANCELED = 3 ORDER_STATUS_FILLED = 22 # 仓位状态:1-持仓 9-已强平 POSITION_STATUS_OPEN = 1 POSITION_STATUS_LIQUIDATED = 9 # 资金流水类型:1-划入 2-划出 3-冻结 4-解冻 5-手续费 7-开仓 9-强平 FLOW_TRANSFER_IN = 1 FLOW_TRANSFER_OUT = 2 FLOW_FREEZE = 3 FLOW_UNFREEZE = 4 FLOW_FEE = 5 FLOW_OPEN = 7 FLOW_FORCE_CLOSE = 9 CURRENCY_ID = 1 # 结算币种(演示固定为 1) class MatchEngine: _ROUTES = { "/api/v1/orders": "add_order", "/api/v1/orders/cancel": "cancel_order", "/api/v1/market/mark-price": "set_mark_price", "/api/v1/risk/check": "risk_check", } def __init__(self): self.reset() def reset(self): """清空全部数据,恢复初始合约/标记价格(用例隔离用)。""" self.db = MockMySQL() self.cache = MockRedis() self._order_seq = 0 self._position_seq = 0 self._flow_seq = 0 self.mark_prices = { cid: Decimal(str(c["mark_price"])) for cid, c in settings.CONTRACTS.items() } # ------------------------------------------------------------------ # HTTP 分发 # ------------------------------------------------------------------ def handle(self, path, payload): """按路径分发到对应业务方法,返回 (code, msg, data)。""" name = self._ROUTES.get((path or "").rstrip("/")) if not name: return 404, "接口不存在", None try: return getattr(self, name)(payload or {}) except ParamError as err: return 1003, "参数错误:%s" % err.field, None # ------------------------------------------------------------------ # 业务接口 # ------------------------------------------------------------------ def add_order(self, body): """下单:限价单(orderType=1)冻结保证金挂单;市价单(orderType=2)按标记价立即成交。""" user_id = self._to_int(body, "userId") contract_id = self._to_int(body, "contractId") account = self._get_account(user_id) if account is None: return 1001, "用户不存在", None contract = settings.CONTRACTS.get(contract_id) if contract is None: return 1002, "合约不存在", None side = body.get("side") if side not in ("bid", "ask"): raise ParamError("side") if self._to_int(body, "positionEffect") != 1: raise ParamError("positionEffect") order_type = self._to_int(body, "orderType") if order_type not in (1, 2): raise ParamError("orderType") margin_type = self._to_int(body, "marginType") if margin_type not in (1, 2): raise ParamError("marginType") if body.get("timeInForce", "GTC") not in ("GTC", "IOC", "FOK", "GTX"): raise ParamError("timeInForce") margin_rate = self._to_decimal(body, "marginRate") if not Decimal("0") < margin_rate <= Decimal("1"): raise ParamError("marginRate") quantity = self._to_positive_decimal(body, "quantity") maker = Decimal(str(contract["maker_fee_rate"])) taker = Decimal(str(contract["taker_fee_rate"])) # ---- 限价开仓:冻结保证金(起始保证金 + 孰高手续费) ---- if order_type == 1: price = self._to_positive_decimal(body, "price") value = price * quantity frozen = value * margin_rate + max(value * maker, value * taker) if account["total_money"] < frozen: return 2001, "余额不足", None order_no = self._next_order_no() self.db.insert("order", { "order_no": order_no, "user_id": user_id, "contract_id": contract_id, "side": side, "price": price, "quantity": quantity, "order_type": order_type, "margin_type": margin_type, "margin_rate": margin_rate, "status": ORDER_STATUS_WAIT, "filled_quantity": Decimal("0"), "frozen_amount": frozen, }) frozen_field = self._frozen_field(margin_type) account["total_money"] -= frozen account[frozen_field] += frozen self._add_flow(user_id, FLOW_FREEZE, frozen, order_no) self.cache.set( "order_freeze:userId:%s:orderNo:%s" % (user_id, order_no), frozen) self._sync_account_cache(user_id) return 0, "OK", {"orderNo": order_no} # ---- 市价开仓:按标记价格立即全部成交(演示简化) ---- mark = self.mark_prices[contract_id] value = mark * quantity init = value * margin_rate fee = value * taker # 市价单按 taker 费率 if account["total_money"] < init + fee: return 2001, "余额不足", None order_no = self._next_order_no() position_no = self._next_position_no() direction = 1 if side == "bid" else -1 self.db.insert("order", { "order_no": order_no, "user_id": user_id, "contract_id": contract_id, "side": side, "price": mark, "quantity": quantity, "order_type": order_type, "margin_type": margin_type, "margin_rate": margin_rate, "status": ORDER_STATUS_FILLED, "filled_quantity": quantity, "frozen_amount": Decimal("0"), }) self.db.insert("position", { "position_no": position_no, "user_id": user_id, "contract_id": contract_id, "side": direction, "quantity": quantity, "avg_price": mark, "margin_type": margin_type, "margin_rate": margin_rate, "extra_margin": Decimal("0"), "status": POSITION_STATUS_OPEN, }) margin_field = self._margin_field(margin_type) account["total_money"] -= init + fee account[margin_field] += init self._add_flow(user_id, FLOW_FEE, fee, order_no) self._add_flow(user_id, FLOW_OPEN, init, order_no) self._sync_position_cache(user_id, contract_id) self._sync_account_cache(user_id) return 0, "OK", {"orderNo": order_no} def cancel_order(self, body): """撤单:解冻资金、订单置为已撤销、删除冻结缓存键。""" user_id = self._to_int(body, "userId") contract_id = self._to_int(body, "contractId") order_no = str(body.get("orderNo") or "") if not order_no: raise ParamError("orderNo") orders = self.db.select("order", order_no=order_no, user_id=user_id) if not orders: return 2002, "订单不存在", None order = orders[0] if order["status"] != ORDER_STATUS_WAIT: return 2003, "订单状态不允许撤单", None frozen = order["frozen_amount"] account = self._get_account(user_id) frozen_field = self._frozen_field(order["margin_type"]) account["total_money"] += frozen account[frozen_field] -= frozen order["status"] = ORDER_STATUS_CANCELED self._add_flow(user_id, FLOW_UNFREEZE, frozen, order_no) self.cache.delete("order_freeze:userId:%s:orderNo:%s" % (user_id, order_no)) self._sync_account_cache(user_id) return 0, "OK", {"contractId": contract_id, "orderNo": order_no} def set_mark_price(self, body): """测试辅助:设置合约标记价格(行情驱动)。""" contract_id = self._to_int(body, "contractId") price = self._to_positive_decimal(body, "price") if contract_id not in settings.CONTRACTS: return 1002, "合约不存在", None self.mark_prices[contract_id] = price return 0, "OK", {"contractId": contract_id, "markPrice": str(price)} def risk_check(self, body): """风控检查:逐仓位计算保证金余额,余额 <= 维持保证金即触发强平。""" user_id = self._to_int(body, "userId") contract_id = self._to_int(body, "contractId") if self._get_account(user_id) is None: return 1001, "用户不存在", None contract = settings.CONTRACTS.get(contract_id) if contract is None: return 1002, "合约不存在", None mark = self.mark_prices[contract_id] maintain_rate = Decimal(str(contract["maintain_rate"])) report = {"positions": [], "liquidated": []} positions = self.db.select( "position", user_id=user_id, contract_id=contract_id, status=POSITION_STATUS_OPEN) for pos in positions: direction = pos["side"] qty = pos["quantity"] avg = pos["avg_price"] init = avg * qty * pos["margin_rate"] upnl = direction * (mark - avg) * qty balance = pos["extra_margin"] + init + upnl maintain = avg * qty * maintain_rate report["positions"].append({ "positionNo": pos["position_no"], "balance": str(balance), "maintain": str(maintain), "burst": balance <= maintain, }) if balance <= maintain: self._liquidate(user_id, contract_id, pos, balance, init, report) return 0, "OK", report # ------------------------------------------------------------------ # 测试数据准备 # ------------------------------------------------------------------ def init_user(self, user_id, balance): """初始化用户合约资金账户并划入初始资金。""" self.db.insert("futures_account", { "user_id": user_id, "currency_id": CURRENCY_ID, "total_money": Decimal(str(balance)), "cross_margin": Decimal("0"), "cross_frozen_margin": Decimal("0"), "isolated_margin": Decimal("0"), "isolated_frozen_margin": Decimal("0"), }) self._add_flow(user_id, FLOW_TRANSFER_IN, Decimal(str(balance)), None) self._sync_account_cache(user_id) # ------------------------------------------------------------------ # 内部工具 # ------------------------------------------------------------------ def _liquidate(self, user_id, contract_id, pos, balance, init, report): """强平:仓位置为已强平,剩余保证金划入风险基金,穿仓部分由风险基金兜底。""" direction = pos["side"] qty = pos["quantity"] avg = pos["avg_price"] rate = pos["margin_rate"] extra = pos["extra_margin"] if direction == 1: bankrupt = avg * (1 - rate) - extra / qty else: bankrupt = avg * (1 + rate) + extra / qty account = self._get_account(user_id) account[self._margin_field(pos["margin_type"])] -= init if balance < 0: # 穿仓:亏损超过仓位保证金,缺口从可用余额扣除,由风险基金承担 account["total_money"] += balance pos["status"] = POSITION_STATUS_LIQUIDATED self.db.insert("liquidation_record", { "user_id": user_id, "contract_id": contract_id, "position_no": pos["position_no"], "quantity": qty, "bankrupt_price": bankrupt, "margin_balance": balance, }) self.db.insert("risk_fund_ledger", { "user_id": user_id, "contract_id": contract_id, "position_no": pos["position_no"], "quantity": balance, }) self._add_flow(user_id, FLOW_FORCE_CLOSE, balance, None) self.cache.delete("position:userId:%s:contractId:%s" % (user_id, contract_id)) self._sync_account_cache(user_id) report["liquidated"].append({ "positionNo": pos["position_no"], "quantity": str(qty), "bankruptPrice": str(bankrupt), "marginBalance": str(balance), }) def _get_account(self, user_id): rows = self.db.select("futures_account", user_id=user_id) return rows[0] if rows else None @staticmethod def _margin_field(margin_type): """仓位保证金字段:1-全仓 2-逐仓。""" return "cross_margin" if margin_type == 1 else "isolated_margin" @staticmethod def _frozen_field(margin_type): """冻结保证金字段:1-全仓 2-逐仓。""" if margin_type == 1: return "cross_frozen_margin" return "isolated_frozen_margin" def _add_flow(self, user_id, flow_type, quantity, order_no): """写一条用户资金流水。""" self._flow_seq += 1 self.db.insert("account_flow", { "id": self._flow_seq, "user_id": user_id, "currency_id": CURRENCY_ID, "type": flow_type, "quantity": quantity, "order_no": order_no, }) def _sync_account_cache(self, user_id): """把资金表行镜像写入缓存(camelCase,模拟缓存与库字段命名不一致)。""" account = self._get_account(user_id) self.cache.set( "futures_account:userId:%s:currencyId:%s" % (user_id, CURRENCY_ID), json.dumps({ "userId": str(user_id), "currencyId": str(CURRENCY_ID), "totalMoney": str(account["total_money"]), "crossMargin": str(account["cross_margin"]), "crossFrozenMargin": str(account["cross_frozen_margin"]), "isolatedMargin": str(account["isolated_margin"]), "isolatedFrozenMargin": str(account["isolated_frozen_margin"]), })) def _sync_position_cache(self, user_id, contract_id): """把仓位行镜像写入缓存。""" rows = self.db.select( "position", user_id=user_id, contract_id=contract_id, status=POSITION_STATUS_OPEN) if not rows: self.cache.delete("position:userId:%s:contractId:%s" % (user_id, contract_id)) return pos = rows[0] self.cache.set( "position:userId:%s:contractId:%s" % (user_id, contract_id), json.dumps({ "positionNo": str(pos["position_no"]), "side": str(pos["side"]), "quantity": str(pos["quantity"]), "avgPrice": str(pos["avg_price"]), "status": str(pos["status"]), })) def _next_order_no(self): self._order_seq += 1 return "NO%010d" % self._order_seq def _next_position_no(self): self._position_seq += 1 return self._position_seq @staticmethod def _to_int(body, field): try: return int(body.get(field)) except (TypeError, ValueError): raise ParamError(field) @staticmethod def _to_decimal(body, field): try: return Decimal(str(body.get(field))) except Exception: raise ParamError(field) @classmethod def _to_positive_decimal(cls, body, field): value = cls._to_decimal(body, field) if value <= 0: raise ParamError(field) return value