This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+415
@@ -0,0 +1,415 @@
|
||||
"""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
|
||||
@@ -0,0 +1,29 @@
|
||||
"""内存缓存(MockRedis):模拟 Redis 的键值读写,供用例做缓存校验。"""
|
||||
|
||||
import fnmatch
|
||||
|
||||
|
||||
class MockRedis:
|
||||
|
||||
def __init__(self):
|
||||
self._data = {}
|
||||
|
||||
def get(self, key):
|
||||
"""读取键,不存在返回 None(与 redis-py 行为一致);值统一为字符串。"""
|
||||
return self._data.get(str(key))
|
||||
|
||||
def set(self, key, value):
|
||||
"""写入键,值统一转字符串(与 Redis string 类型行为一致)。"""
|
||||
self._data[str(key)] = str(value)
|
||||
|
||||
def delete(self, key):
|
||||
"""删除键(不存在时静默,与 DEL 语义一致)。"""
|
||||
self._data.pop(str(key), None)
|
||||
|
||||
def keys(self, pattern="*"):
|
||||
"""按通配符模式匹配键名(模拟 KEYS/SCAN)。"""
|
||||
return [k for k in self._data if fnmatch.fnmatch(k, pattern)]
|
||||
|
||||
def flushall(self):
|
||||
"""清空全部键。"""
|
||||
self._data.clear()
|
||||
@@ -0,0 +1,25 @@
|
||||
"""内存数据库(MockMySQL):模拟 MySQL 的表读写,供用例做落库校验。
|
||||
|
||||
只提供用例所需的最小查询能力(insert/select/count),字段命名沿用
|
||||
snake_case,贴近真实库表列名;缓存侧(MockRedis)则用 camelCase,
|
||||
模拟真实系统"库与缓存字段命名不一致、断言前需归一化"的常见情况。
|
||||
"""
|
||||
|
||||
|
||||
class MockMySQL:
|
||||
|
||||
def __init__(self):
|
||||
self._tables = {}
|
||||
|
||||
def insert(self, table, row):
|
||||
"""插入一行(dict)。"""
|
||||
self._tables.setdefault(table, []).append(dict(row))
|
||||
|
||||
def select(self, table, **where):
|
||||
"""按等值条件查询,返回匹配的行(list[dict]);无条件返回全表。"""
|
||||
rows = self._tables.get(table, [])
|
||||
return [row for row in rows if all(row.get(k) == v for k, v in where.items())]
|
||||
|
||||
def count(self, table, **where):
|
||||
"""按条件统计行数。"""
|
||||
return len(self.select(table, **where))
|
||||
@@ -0,0 +1,56 @@
|
||||
"""mock HTTP 服务:把 MatchEngine 暴露为本地 HTTP 接口(wsgiref 实现)。
|
||||
|
||||
零第三方依赖,由 conftest 以随机端口启动,用例通过 requests 访问,
|
||||
与访问真实撮合服务的代码路径完全一致。
|
||||
"""
|
||||
|
||||
import json
|
||||
import socketserver
|
||||
from wsgiref.simple_server import (
|
||||
WSGIRequestHandler,
|
||||
WSGIServer,
|
||||
make_server as wsgi_make_server,
|
||||
)
|
||||
|
||||
|
||||
class _QuietHandler(WSGIRequestHandler):
|
||||
"""关闭每请求一行的基础日志,避免干扰 pytest 输出。"""
|
||||
|
||||
def log_message(self, format, *args): # noqa: A002 - 与基类签名一致
|
||||
pass
|
||||
|
||||
|
||||
class ThreadingWSGIServer(socketserver.ThreadingMixIn, WSGIServer):
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
def make_app(engine):
|
||||
"""构造 WSGI 应用:JSON 进、JSON 出,统一返回 {code, msg, data}。"""
|
||||
|
||||
def app(environ, start_response):
|
||||
path = environ.get("PATH_INFO", "")
|
||||
try:
|
||||
length = int(environ.get("CONTENT_LENGTH") or 0)
|
||||
raw = environ["wsgi.input"].read(length) if length else b""
|
||||
payload = json.loads(raw.decode("utf-8") or "{}")
|
||||
code, msg, data = engine.handle(path, payload)
|
||||
except Exception as exc: # noqa: BLE001 - 兜底转成业务错误码
|
||||
code, msg, data = 500, "服务器内部错误", repr(exc)
|
||||
body = json.dumps(
|
||||
{"code": code, "msg": msg, "data": data}, ensure_ascii=False
|
||||
).encode("utf-8")
|
||||
start_response("200 OK", [
|
||||
("Content-Type", "application/json; charset=utf-8"),
|
||||
("Content-Length", str(len(body))),
|
||||
])
|
||||
return [body]
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def create_server(address, engine):
|
||||
"""在指定地址(端口 0 表示随机)启动 mock 服务,返回 server 对象。"""
|
||||
# 注意:这里显式传参调用 wsgiref 的 make_server(与上方同名的封装区分)
|
||||
return wsgi_make_server(
|
||||
address[0], address[1], make_app(engine),
|
||||
server_class=ThreadingWSGIServer, handler_class=_QuietHandler)
|
||||
Reference in New Issue
Block a user