commit cb7b49a4de5e11e824fb42f4a796b044b6a74305 Author: WbiubiuW <1218949863@qq.com> Date: Sat Sep 19 23:10:32 2026 +0800 chore: 初始化版本控制,添加 .gitignore 纳入撮合自动化测试工程 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12369e8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +__pycache__/ +*.pyc +.pytest_cache/ +.venv/ +venv/ +.coverage +htmlcov/ +*.db +.DS_Store diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..9afa476 --- /dev/null +++ b/README.en.md @@ -0,0 +1,77 @@ +# contract-match-http-autotest — HTTP API Automated Testing Demo for a Perpetual Contract Matching System + +## 1. What Problem This Project Solves + +A perpetual contract matching system is composed of multiple microservices—order acceptance, matching engine, risk control, clearing, etc.—with numerous APIs and complex business states. Asserting only HTTP status codes is far from enough: when an order request is submitted, the system actually performs four things behind the scenes—**funds freezing, order persistence, position changes, and cache updates**—and any failure in any one of them can lead to capital loss incidents. + +This project demonstrates a methodology for API automated testing of such systems. It focuses on three core aspects: + +1. **Triple Assertions**: HTTP response + database persistence + cache, all three are asserted simultaneously, not just the return value; +2. **Formula Layer for Expected Values**: Matching formulas such as margin, fees, liquidation price, bankruptcy price are implemented independently as pure functions. Expected values are **calculated**, not “run once and copy down” — if the formula is wrong, the test fails; if the system is wrong, the test also fails; +3. **YAML Data-Driven Testing**: Test cases are separated from data; a single test function covers normal, negative, and boundary value cases in one go. + +To allow the project to run **without a real environment**, the system under test is implemented as a local mock engine substitute (standard library `wsgiref` HTTP server + in-memory MySQL/Redis). The verification chain is completely isomorphic to a real project, and `pytest` runs all green without connecting to any external network, database, or middleware. + +## 2. Architecture + +``` +┌────────────────────────── pytest Test Case Layer (case/) ──────────────────────────┐ +│ test_order_freeze.py Order placement freezes margin (triple assertions, data-driven with positive/negative cases) │ +│ test_position_open.py Market order opens position (reconciliation of position/funds/ledger/cache) │ +│ test_liquidation.py Liquidation trigger verification (price feed to liquidation price, risk fund ledger) │ +│ test_formula.py Pure function unit tests for the contract formula layer (expected values hand-calculated to prevent self-deception) │ +└───────────────┬──────────────────────────────┬───────────────────────────┘ + │ YAML data-driven │ Expected values +┌───────────────▼──────────────┐ ┌───────────▼──────────────┐ +│ data/*.yml │ │ formula/contract_formula │ +│ addOrder.yml / liquidation.yml│ │ frozen margin/liquidation price/bankruptcy price │ +│ formula.yml │ │ unrealized PnL/forced liquidation detection │ +└───────────────────────────────┘ └──────────────────────────┘ + │ requests(HTTP) ▲ Expected vs actual +┌───────────────▼──────────────────────────────▼───────────────────────────┐ +│ System Under Test Substitute (mock/) │ +│ server.py wsgiref HTTP server (random port, session-level startup in conftest) │ +│ engine.py Matching engine: order freeze/market order fill/cancel unfreeze/mark price/liquidation risk control │ +│ (internal fund calculation independently implemented, intentionally not reusing formula package) │ +│ fake_db.py / fake_cache.py In-memory MySQL / Redis (data plane for triple assertions) │ +└───────────────────────────────────────────────────────────────────────────┘ +``` + +Layer Responsibilities: + +| Layer | Directory | Responsibilities | +| --- | --- | --- | +| Test Case Layer | `case/` | Organizes business assertions; only cares about “what is given, what is expected” | +| Data Layer | `data/` | Case parameters and expected values, `[param dict, expected dict]` structure for parametrize unpacking | +| Formula Layer | `formula/` | Pure functions for matching business formulas, all in Decimal, the sole source of expected values | +| API Wrapper Layer | `api/` | Secondary encapsulation of the system’s HTTP APIs; test cases do not construct URLs directly | +| Common Layer | `common/` | YAML reading, HTTP client, Decimal assertion utilities | +| System Substitute | `mock/` | Local matching engine + HTTP server + in-memory DB/cache | +| Configuration Layer | `config/` | Contract parameters, fee rates, precision, etc. (all placeholder demo values) | + +## 3. How to Run + +```bash +cd contract-match-http-autotest +python -m venv venv && source venv/bin/activate # optional +pip install -r requirements.txt # only pytest / requests / PyYAML +python -m pytest # run all tests +python -m pytest case/test_liquidation.py -v # run a single scenario +python -m pytest -k liquidation # filter by keyword +``` + +No environment setup is required: `conftest` automatically starts the mock matching service on a random port at `127.0.0.1`, and resets engine data **before each test case**, so cases are isolated, repeatable, and can be executed in any order. + +### What Triple Assertions Look Like in a Test Case + +Take `case/test_order_freeze.py::test_limit_order_freeze` as an example: + +```python +# Expected values: independently calculated by the formula layer, independent of the system implementation +expect_frozen = formula.frozen_margin(price, quantity, marginRate, maker, taker) + +# First: HTTP response +assert body["code"] == 0 + +# Second: Database persistence — order fields / fund deduction and freezing / freeze ledger +assert_decimal_equal(after["total_money"], \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e096f9 --- /dev/null +++ b/README.md @@ -0,0 +1,233 @@ +# contract-match-http-autotest —— 永续合约撮合系统 HTTP 接口自动化测试演示工程 + +## 一、5 分钟读法(给面试官的导览) + +如果时间只有 5 分钟,建议按这个顺序看: + +1. **先往下看「二、架构」的 ASCII 图** —— 30 秒看懂分层:用例层、接口层、被测系统、 + 校验面、公式层各就各位; +2. **再看「三、用例覆盖清单」** —— 一张表说清测了什么场景、多少用例、断言到哪几面, + 这是测试工程师最该拿出的东西; +3. **然后读 `case/test_liquidation.py`** —— 最能体现三重校验(HTTP 响应 + 落库 + + 缓存)的用例,行情驱动到强平价,断言风险基金流水; +4. **最后看 `formula/contract_formula.py`** —— 为什么期望值要独立计算而不是抄被测 + 系统的返回值。 + +### 为什么用 mock 而不是真环境 + +- **脱敏**:真实撮合系统的参数、接口路径、资金口径属前雇主资产,演示工程全部用 + 占位值重建,不出现任何真实公司信息; +- **可复现**:面试官 clone 下来 `pytest` 一把全绿,不需要申请环境、不需要 VPN、 + 不需要外网; +- **校验链路同构**:mock 的 HTTP 服务、落库、缓存的交互形态与真实微服务工程一致, + 换真环境只需替换 `conftest.py` 的 fixture,用例代码一行不改; +- **故意不复用**:mock 引擎内部的资金计算刻意独立于 `formula/` 包实现,保持 + 「被测系统 vs 测试侧期望值」两条独立计算链,避免同一份代码自证。 + +## 二、这个工程解决什么问题 + +永续合约撮合系统由订单受理、撮合引擎、风控、清算等多个微服务组成,接口数量多、 +业务状态复杂。只断言 HTTP 返回码远远不够 —— 一笔下单请求,系统侧真实发生的是 +**资金冻结、订单落库、仓位变更、缓存更新**四件事,任何一环出错都是资损事故。 + +本工程演示针对这类系统的接口自动化测试方法论,核心是三件事: + +1. **三重校验**:HTTP 响应 + 数据库落库 + 缓存,三面同时断言,而不是只看返回值; +2. **公式层计算期望值**:保证金、手续费、强平价、破产价等撮合公式以纯函数独立 + 实现,期望值不靠"先跑一遍抄下来",而是算出来 —— 公式错了测试会红,系统错 + 了测试也会红; +3. **YAML 数据驱动**:用例与数据分离,一个用例函数覆盖正例/负例/边界值全家桶。 + +为了让工程**脱离真实环境也能跑通**,被测撮合系统以本地 mock 引擎替身实现 +(标准库 wsgiref HTTP 服务 + 内存 MySQL/Redis),校验链路与真实工程完全同构, +`pytest` 一把全绿,不连任何外网、数据库与中间件。 + +## 三、用例覆盖清单 + +共 **45** 条用例,全部通过(数据来源:`pytest --collect-only -q`,2026-09-19 实测): + +| 业务场景 | 用例数 | 断言面(HTTP / 落库 / 缓存) | 覆盖的关键点 | +| --- | --- | --- | --- | +| 下单冻结保证金(正例,数据驱动) | 4 | HTTP + 落库 + 缓存 | 全仓限价买/卖开仓;冻结 = 起始保证金 + 孰高手续费;订单字段 / 资金扣减 / 冻结流水 / 冻结键值四面对账 | +| 下单非法入参(负例,数据驱动) | 15 | HTTP + 落库 + 缓存 | 价格/数量为 0 或负数、保证金率非法、余额不足等;**额外断言「无副作用」**:订单表无新增、资金无变动、缓存无残留 | +| 撤单解冻 | 1 | HTTP + 落库 + 缓存 | 冻结全额解冻回可用;解冻流水;冻结键值清理 | +| 市价开仓成交 | 2 | HTTP + 落库 + 缓存 | 多/空两个方向;按 taker 费率立即成交;仓位 / 手续费流水 / 仓位缓存;标记价移动后未实现盈亏 | +| 强平触发校验(数据驱动) | 3 | HTTP + 落库 + 缓存 | 行情驱动到强平价触发;剩余保证金入风险基金;穿仓缺口由风险基金兜底并扣减可用;仓位清零 | +| 公式层纯函数单测(数据驱动) | 20 | 纯函数(无 IO) | 冻结保证金 / 未实现盈亏 / 破产价 / 强平价 / 爆仓判断,期望值**手算写死**防自证;含强平边界(`<=` 闭区间)与 float 精度反例 | + +> 说明:`mock/` 目录下的 `test_*_gen.py` 是早期用生成工具产出的辅助单测草稿, +> 不在 pytest 收集范围内(`pytest.ini` 的 `testpaths = case`),不参与上述统计。 + +## 四、架构 + +``` +┌────────────────────────── pytest 用例层 (case/) ──────────────────────────┐ +│ test_order_freeze.py 下单冻结保证金(三重校验,正例/负例数据驱动) │ +│ test_position_open.py 市价开仓成交(仓位/资金/流水/缓存四面对账) │ +│ test_liquidation.py 强平触发校验(行情驱动到强平价,风险基金流水) │ +│ test_formula.py 合约公式层纯函数单测(期望值手算写死防自证) │ +└───────────────┬──────────────────────────────┬───────────────────────────┘ + │ YAML 数据驱动 │ 期望值 +┌───────────────▼──────────────┐ ┌───────────▼──────────────┐ +│ data/*.yml │ │ formula/contract_formula │ +│ addOrder.yml / liquidation.yml│ │ 冻结保证金/强平价/破产价 │ +│ formula.yml │ │ 未实现盈亏/爆仓判断 │ +└───────────────────────────────┘ └──────────────────────────┘ + │ requests(HTTP) ▲ 期望值 vs 实际值 +┌───────────────▼──────────────────────────────▼───────────────────────────┐ +│ 被测系统替身 (mock/) │ +│ server.py wsgiref HTTP 服务(随机端口,conftest 会话级启动) │ +│ engine.py 撮合引擎:下单冻结/市价成交/撤单解冻/标记价/强平风控 │ +│ (内部资金计算独立实现,刻意不复用 formula 包) │ +│ fake_db.py / fake_cache.py 内存 MySQL / Redis(三重校验的数据面) │ +└───────────────────────────────────────────────────────────────────────────┘ +``` + +分层职责: + +| 层 | 目录 | 职责 | +| --- | --- | --- | +| 用例层 | `case/` | 业务断言的组织,只关心"给什么、期望什么" | +| 数据层 | `data/` | 用例参数与期望值,`[参数dict, 期望dict]` 结构供 parametrize 解包 | +| 公式层 | `formula/` | 撮合业务公式纯函数,全部 Decimal,是期望值的唯一来源 | +| 接口封装层 | `api/` | 对被测系统 HTTP 接口的二次封装,用例不直接拼 URL | +| 通用层 | `common/` | YAML 读取、HTTP 客户端、Decimal 断言工具 | +| 被测替身 | `mock/` | 本地撮合引擎 + HTTP 服务 + 内存库/缓存 | +| 配置层 | `config/` | 合约参数、费率、精度等(全部为演示占位值) | + +## 三、怎么跑 + +```bash +cd contract-match-http-autotest +python -m venv venv && source venv/bin/activate # 可选 +pip install -r requirements.txt # 仅 pytest / requests / PyYAML +python -m pytest # 全部用例 +python -m pytest case/test_liquidation.py -v # 单个场景 +python -m pytest -k liquidation # 按关键字筛选 +``` + +无需任何环境准备:conftest 会自动在 `127.0.0.1` 随机端口拉起 mock 撮合服务, +并在**每个用例前重置引擎数据**,用例相互隔离、可重复执行、可乱序执行。 + +### 三重校验在用例里的样子 + +以 `case/test_order_freeze.py::test_limit_order_freeze` 为例: + +```python +# 期望值:公式层独立计算,与被测系统实现无关 +expect_frozen = formula.frozen_margin(price, quantity, marginRate, maker, taker) + +# 一重:HTTP 响应 +assert body["code"] == 0 + +# 二重:落库 —— 订单字段 / 资金扣减与冻结 / 冻结流水 +assert_decimal_equal(after["total_money"], before["total_money"] - expect_frozen) +assert_decimal_equal(flow["quantity"], expect_frozen) + +# 三重:缓存 —— 冻结键值、资金镜像(与落库字段命名不同,归一化后比对) +assert_decimal_equal(cache.get("frozen_margin:userId:...:orderNo:..."), expect_frozen) +``` + +### mock 说明(重要) + +- mock 撮合引擎(`mock/engine.py`)**刻意不复用** `formula/` 包,内部独立实现一份 + Decimal 资金运算 —— 保持与真实工程相同的形态:被测系统是独立服务,期望值由 + 测试侧公式层独立算出后比对,而不是同一份代码自证; +- MockMySQL 字段用 snake_case、MockRedis 用 camelCase,还原真实系统"库与缓存 + 字段命名不一致、断言前需归一化"的常见工程现实; +- 引擎实现了真实撮合系统的关键资金口径:限价冻结(起始保证金 + 孰高手续费)、 + 市价按 taker 费率立即成交、撤单全额解冻、强平剩余保证金入风险基金、穿仓缺口 + 由风险基金兜底并扣减可用余额。 + +## 四、关键难点及我的处理 + +### 1. 金额精度:一律 Decimal,禁止 float + +合约资金字段动辄 8 位小数,`0.1 + 0.2 != 0.3` 的 float 陷阱在资金断言里就是 +误报/漏报事故。处理: + +- 公式层与断言工具全部走 `Decimal(str(value))` 转换(不走 `Decimal(float)`, + 避免 float 先行引入误差); +- `common/decimal_assert.py::assert_decimal_equal` 统一按 8 位小数量化比较, + 既不逐位较真浮点表示,也不放过真实精度丢失; +- `test_formula.py::test_decimal_precision_over_float` 用 float 反例固化这条规约。 + +### 2. 期望值从哪来:公式层纯函数,手算用例防自证 + +- 保证金/手续费/强平价/破产价等公式抽成 `formula/` 纯函数(无 IO、无状态), + 场景用例一律调它算期望值; +- 公式层自身另有单测(`data/formula.yml`),期望值是**手算写死**的,防止公式 + 实现自证清白; +- 强平边界语义(保证金余额恰好等于维持保证金时 `<=` 判定触发)单独用边界用例 + 固化,这是生产上最容易扯皮的一格。 + +### 3. 三重校验的落地:落库与缓存字段不一致 + +- 落库校验断言 `account_future` / `order` / `user_currency_flow` 三张表, + 缓存校验断言 `frozen_margin:*` / `account_future:*` / `position:*` 三类键; +- 库(snake_case)与缓存(camelCase)命名不一致,比对前做字段归一化 —— 还原 + 真实工程的脏活,也是缓存校验最容易踩的坑; +- 缓存值统一转字符串(模拟 Redis string 类型),断言时再转回 Decimal。 + +### 4. 用例隔离与可重复执行 + +- 每个用例前 `engine.reset()`(conftest 的函数级 `base_url` fixture),杜绝 + 用例间数据串扰,任意顺序、任意次数执行结果一致; +- 负例额外断言"**无副作用**":非法请求不仅返回错误码,还必须保证订单表无 + 新增、资金表无变动、缓存无残留 —— 接口测试里负例只看返回码是不够的。 + +### 5. 环境解耦:mock 替身保持与真实被测系统同构 + +- 真实工程里被测系统是独立微服务集群 + MySQL + Redis 集群;演示工程用 + wsgiref 服务 + 内存库/缓存替身,**用例代码一行不改**即可在两种形态间切换 + (只需替换 conftest 的 fixture 实现); +- mock 服务与数据面共享同一个引擎实例,HTTP 请求改的内存态就是"落库/缓存" + 校验读到的内存态,与真实系统的因果链一致。 + +## 五、目录结构 + +``` +contract-match-http-autotest/ +├── README.md # 本文档 +├── requirements.txt # pytest / requests / PyYAML +├── pytest.ini # testpaths = case +├── conftest.py # fixture:启动 mock 服务、注入数据面、用例隔离 +├── config/ +│ └── settings.py # 合约参数/费率/精度(演示占位值) +├── formula/ +│ └── contract_formula.py # 合约公式层(纯函数,全 Decimal) +├── common/ +│ ├── read_yaml.py # YAML 数据读取 +│ ├── http_client.py # requests 封装 +│ └── decimal_assert.py # Decimal 金额断言工具 +├── api/ +│ └── order_api.py # 下单/撤单/划转/标记价/风控接口封装 +├── mock/ +│ ├── engine.py # 撮合引擎(被测系统替身) +│ ├── server.py # wsgiref HTTP 服务 +│ ├── fake_db.py # 内存 MySQL +│ └── fake_cache.py # 内存 Redis +├── case/ +│ ├── test_order_freeze.py # 场景一:下单冻结保证金(三重校验) +│ ├── test_position_open.py # 场景二:市价开仓成交 +│ ├── test_liquidation.py # 场景三:强平触发校验 +│ └── test_formula.py # 公式层纯函数单测 +└── data/ + ├── addOrder.yml # 下单正例/负例(数据驱动) + ├── liquidation.yml # 强平场景数据 + └── formula.yml # 公式期望值(手算写死) +``` + +## 六、业务口径速查(演示参数) + +| 口径 | 值/规则 | +| --- | --- | +| 合约 | 1 号合约 BTCUSDT(演示),初始标记价 100 | +| 费率 | maker 0.0002 / taker 0.0005;限价冻结取孰高,市价成交按 taker | +| 冻结保证金 | 开仓价值 × 起始保证金率 + 开仓价值 × max(maker, taker) | +| 维持保证金率 | 0.005 | +| 强平条件 | 额外保证金 + 起始保证金 + 未实现盈亏 ≤ 维持保证金 | +| 强平价(逐仓) | `open + direction × (maintain − extra − init) / qty` | +| 破产价(逐仓) | 多:`open×(1−rate) − extra/qty`;空:`open×(1+rate) + extra/qty` | +| 穿仓 | 强平后保证金余额为负:缺口扣减可用余额,由风险基金兜底 | +| 资金流水类型 | 1 划入 / 3 冻结 / 4 解冻 / 5 手续费 / 7 开仓 / 9 强平 | diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/order_api.py b/api/order_api.py new file mode 100644 index 0000000..c097e2c --- /dev/null +++ b/api/order_api.py @@ -0,0 +1,52 @@ +"""接口封装层:对被测撮合系统 HTTP 接口的二次封装。 + +用例/场景代码只面对这一层,不直接拼 URL —— 换被测环境时只改配置。 +""" + +from common.http_client import Adapter + + +class OrderApi: + + ADD_ORDER = "/api/futures/addOrder" + CANCEL_ORDER = "/api/futures/cancelOrder" + TRANSFER_IN = "/api/future/user/transferIn" + SET_MARK_PRICE = "/api/future/mark/setMarkPrice" + RISK_CHECK = "/api/future/risk/check" + + def __init__(self): + self.adapter = Adapter() + + def add_order(self, base_url, **params): + """下单,返回响应 dict。""" + return self._post(base_url, self.ADD_ORDER, params) + + def cancel_order(self, base_url, user_id, contract_id, order_no): + """按订单号撤单,返回响应 dict。""" + return self._post(base_url, self.CANCEL_ORDER, { + "userId": user_id, + "contractId": contract_id, + "orderNo": order_no, + }) + + def transfer_in(self, base_url, user_id, amount): + """划入资金(测试数据准备),返回响应 dict。""" + return self._post(base_url, self.TRANSFER_IN, { + "userId": user_id, "amount": amount, + }) + + def set_mark_price(self, base_url, contract_id, price): + """设置标记价格(行情驱动),返回响应 dict。""" + return self._post(base_url, self.SET_MARK_PRICE, { + "contractId": contract_id, "price": price, + }) + + def risk_check(self, base_url, user_id, contract_id): + """触发风控检查(强平判定),返回响应 dict。""" + return self._post(base_url, self.RISK_CHECK, { + "userId": user_id, "contractId": contract_id, + }) + + def _post(self, base_url, path, payload): + resp = self.adapter.post(base_url + path, json=payload) + return resp.json() diff --git a/case/__init__.py b/case/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/case/test_formula.py b/case/test_formula.py new file mode 100644 index 0000000..f47fb44 --- /dev/null +++ b/case/test_formula.py @@ -0,0 +1,70 @@ +"""合约公式层纯函数单测:数据驱动 + Decimal 精度演示。 + +公式层是全部业务断言的"期望值来源",本身必须先被验证: +- 期望值手算写死在 data/formula.yml,防公式实现自证; +- 金额全部 Decimal,顺带用 float 反例说明为什么禁止 float。 +""" + +import pytest + +from common.decimal_assert import assert_decimal_equal +from common.read_yaml import read_yaml +from formula.contract_formula import to_decimal, unrealized_pnl +from formula import contract_formula as formula + +DATA = read_yaml("data/formula.yml") +MAKER = "0.0002" +TAKER = "0.0005" + + +class TestFormula: + + @pytest.mark.parametrize("case", DATA["frozenMargin"]) + def test_frozen_margin(self, case): + actual = formula.frozen_margin( + case["price"], case["quantity"], case["margin_rate"], MAKER, TAKER) + assert_decimal_equal(actual, case["expected"]) + + @pytest.mark.parametrize("case", DATA["unrealizedPnl"]) + def test_unrealized_pnl(self, case): + actual = unrealized_pnl( + case["side"], case["open_price"], case["mark_price"], case["quantity"]) + assert_decimal_equal(actual, case["expected"]) + + @pytest.mark.parametrize("case", DATA["bankruptcyPrice"]) + def test_bankruptcy_price(self, case): + actual = formula.bankruptcy_price( + case["side"], case["open_price"], case["quantity"], + case["margin_rate"], case["extra_margin"]) + assert_decimal_equal(actual, case["expected"]) + + @pytest.mark.parametrize("case", DATA["liquidationPrice"]) + def test_liquidation_price(self, case): + actual = formula.liquidation_price( + case["side"], case["open_price"], case["quantity"], + case["margin_rate"], case["maintain_rate"], case["extra_margin"]) + assert_decimal_equal(actual, case["expected"]) + + @pytest.mark.parametrize("case", DATA["isBurst"]) + def test_is_burst(self, case): + actual = formula.is_burst( + case["extra_margin"], case["side"], case["open_price"], + case["mark_price"], case["quantity"], + case["margin_rate"], case["maintain_rate"]) + assert actual is case["expected"] + + def test_is_burst_boundary_is_closed(self): + """边界语义:保证金余额恰好等于维持保证金时,<= 判定触发强平。""" + # 做多 10 倍杠杆、强平价 90.5,恰好触及即触发 + assert formula.is_burst("0", "bid", 100, "90.5", 10, "0.1", "0.005") is True + # 高出强平价一线即安全 + assert formula.is_burst("0", "bid", 100, "90.6", 10, "0.1", "0.005") is False + + def test_decimal_precision_over_float(self): + """为什么金额断言必须用 Decimal:float 存在二进制精度误差。""" + # float:0.1 + 0.2 != 0.3(经典精度陷阱) + assert 0.1 + 0.2 != 0.3 + # Decimal:精确相等 + assert to_decimal("0.1") + to_decimal("0.2") == to_decimal("0.3") + # 大额乘法同理,float 末位会漂移 + assert to_decimal("95.5") * to_decimal("2") * to_decimal("0.1") == to_decimal("19.1") diff --git a/case/test_liquidation.py b/case/test_liquidation.py new file mode 100644 index 0000000..ed8f66f --- /dev/null +++ b/case/test_liquidation.py @@ -0,0 +1,115 @@ +"""场景三:强平触发校验 —— 行情驱动到强平价,核对爆仓判定与风险基金流水。 + +方法论:强平价/破产价由公式层**独立**计算,用例据此选择标记价格: +- 安全价(未越界)→ 风控检查不触发,仓位保持持仓; +- 触发价(恰好等于或越过强平价)→ 触发强平,核对: + - position 状态置为已强平; + - force_close_record 落库,破产价与公式一致; + - risk_fund_flow 落库,金额 == 触发时保证金余额(穿仓为负,由风险基金兜底); + - account_future 释放仓位保证金,穿仓时可用余额扣减缺口; + - 缓存仓位键删除。 + +场景数据由 data/liquidation.yml 驱动。 +""" + +import json +from decimal import Decimal + +import pytest + +from api.order_api import OrderApi +from common.decimal_assert import assert_decimal_equal +from common.read_yaml import read_yaml +from config import settings +from formula import contract_formula as formula + +SCENARIOS = read_yaml("data/liquidation.yml")["liquidationScenarios"] +order_api = OrderApi() + +OPEN_PRICE = Decimal(settings.CONTRACTS[1]["mark_price"]) # 开仓时标记价 + + +@pytest.mark.parametrize("scenario", SCENARIOS) +def test_liquidation_trigger(base_url, trader, db, cache, scenario): + contract = settings.CONTRACTS[1] + side = scenario["side"] + quantity = scenario["quantity"] + margin_rate = scenario["marginRate"] + + # 市价开仓(按初始标记价成交) + body = order_api.add_order(base_url, **{ + "userId": trader, "contractId": 1, "side": side, "positionEffect": 1, + "orderType": 2, "quantity": quantity, "durationQualifiers": "GTC", + "marginType": 2, "marginRate": margin_rate, "orderSourceType": 1, + }) + assert body["code"] == 0 + account_after_open = dict(db.select("account_future", user_id=trader)[0]) + + # 公式层独立计算强平价与破产价(期望值) + liq_price = formula.liquidation_price( + side, OPEN_PRICE, quantity, margin_rate, contract["maintain_rate"]) + bankrupt_price = formula.bankruptcy_price(side, OPEN_PRICE, quantity, margin_rate) + + # ---- 1) 安全价:不触发强平 ---- + assert order_api.set_mark_price(base_url, 1, scenario["safeMark"])["code"] == 0 + result = order_api.risk_check(base_url, trader, 1) + assert result["code"] == 0 + assert result["data"]["liquidated"] == [] + assert result["data"]["positions"][0]["burst"] is False + assert db.select("force_close_record", user_id=trader) == [] + position = db.select("position", user_id=trader, contract_id=1)[0] + assert position["status"] == 1 # 仍持仓 + # 风控返回的保证金余额与公式一致 + expect_balance = formula.margin_balance( + "0", side, OPEN_PRICE, scenario["safeMark"], quantity, margin_rate) + assert_decimal_equal(result["data"]["positions"][0]["balance"], expect_balance) + + # ---- 2) 触发价:触发强平 ---- + # 触发价不早于(做多则不高于)公式强平价 + trigger = Decimal(scenario["triggerMark"]) + if side == "bid": + assert trigger <= liq_price + else: + assert trigger >= liq_price + + assert order_api.set_mark_price(base_url, 1, scenario["triggerMark"])["code"] == 0 + result = order_api.risk_check(base_url, trader, 1) + assert result["code"] == 0 + liquidated = result["data"]["liquidated"] + assert len(liquidated) == 1 + + # 仓位:已强平 + position = db.select("position", user_id=trader, contract_id=1)[0] + assert position["status"] == 9 + + # 强平记录:破产价与公式一致 + records = db.select("force_close_record", user_id=trader) + assert len(records) == 1 + assert_decimal_equal(records[0]["bankrupt_price"], bankrupt_price) + + # 风险基金流水:金额 == 触发时保证金余额(穿仓为负) + trigger_balance = formula.margin_balance( + "0", side, OPEN_PRICE, scenario["triggerMark"], quantity, margin_rate) + risk_flows = db.select("risk_fund_flow", user_id=trader) + assert len(risk_flows) == 1 + assert_decimal_equal(risk_flows[0]["quantity"], trigger_balance) + assert_decimal_equal( + db.select("user_currency_flow", user_id=trader, type=9)[0]["quantity"], + trigger_balance) + + # 资金:释放仓位保证金;穿仓时可用余额扣减缺口(负余额) + init = formula.init_margin(OPEN_PRICE, quantity, margin_rate) + account = db.select("account_future", user_id=trader)[0] + assert_decimal_equal(account["isolated_position_margin"], + account_after_open["isolated_position_margin"] - init) + expect_total = account_after_open["total_money"] + min(trigger_balance, Decimal("0")) + assert_decimal_equal(account["total_money"], expect_total) + + # 缓存:仓位键删除,资金镜像同步 + assert cache.get("position:userId:%s:contractId:1" % trader) is None + cached_account = json.loads( + cache.get("account_future:userId:%s:currencyId:1" % trader)) + assert_decimal_equal(cached_account["totalMoney"], account["total_money"]) + + # 响应中的破产价同样与公式一致 + assert_decimal_equal(liquidated[0]["bankruptPrice"], bankrupt_price) diff --git a/case/test_order_freeze.py b/case/test_order_freeze.py new file mode 100644 index 0000000..90f6c91 --- /dev/null +++ b/case/test_order_freeze.py @@ -0,0 +1,150 @@ +"""场景一:下单冻结保证金 —— 三重校验方法论的核心演示。 + +校验链路(与真实工程对 MySQL + Redis 的双重落库校验同构): +1. HTTP 响应:code / msg / orderNo; +2. 落库校验(MockMySQL): + - order 表:委托字段与入参一致、状态待撮合; + - account_future 表:total_money 扣减冻结额、对应冻结保证金字段增加; + - user_currency_flow 表:新增"冻结"流水,金额与公式期望一致; +3. 缓存校验(MockRedis): + - frozen_margin:userId:*:orderNo:* 键值与公式期望一致; + - account_future 缓存镜像与落库一致(字段命名 camelCase,需归一化比对)。 + +期望值全部由 formula 包独立计算(被测引擎不复用该包),数据由 +data/addOrder.yml 驱动参数化。 +""" + +import json + +import pytest + +from api.order_api import OrderApi +from common.decimal_assert import assert_decimal_equal +from common.http_client import Adapter +from common.read_yaml import read_yaml +from config import settings +from formula import contract_formula as formula + +DATA = read_yaml("data/addOrder.yml") +adapter = Adapter() +order_api = OrderApi() + + +def _frozen_field(margin_type): + """保证金模式对应的冻结字段:1-全仓 2-逐仓。""" + if int(margin_type) == 1: + return "cross_frozen_position_margin" + return "isolated_frozen_position_margin" + + +class TestLimitOrderFreeze: + + @pytest.mark.parametrize("test_input,expected", DATA["creatOrderTrueTestdata"]) + def test_limit_order_freeze(self, base_url, trader, db, cache, + test_input, expected): + contract = settings.CONTRACTS[test_input["contractId"]] + before = dict(db.select("account_future", user_id=trader)[0]) + + # ---- 一重校验:HTTP 响应 ---- + resp = adapter.post(base_url + "/api/futures/addOrder", json=test_input) + body = resp.json() + assert body["code"] == expected["code"] + assert body["msg"] == expected["msg"] + order_no = body["data"]["orderNo"] + + # ---- 二重校验(1):订单落库字段 ---- + orders = db.select("order", order_no=order_no) + assert len(orders) == 1 + order = orders[0] + assert order["user_id"] == trader + assert order["side"] == test_input["side"] + assert order["status"] == 2 # 2-待撮合 + assert order["filled_quantity"] == 0 + assert_decimal_equal(order["price"], test_input["price"]) + assert_decimal_equal(order["quantity"], test_input["quantity"]) + + # 期望冻结金额:公式层独立计算(起始保证金 + 孰高手续费) + expect_frozen = formula.frozen_margin( + test_input["price"], test_input["quantity"], test_input["marginRate"], + contract["maker_fee_rate"], contract["taker_fee_rate"]) + + # ---- 二重校验(2):资金表扣减与冻结 ---- + after = db.select("account_future", user_id=trader)[0] + field = _frozen_field(test_input["marginType"]) + assert_decimal_equal(after[field], before[field] + expect_frozen) + assert_decimal_equal(after["total_money"], before["total_money"] - expect_frozen) + + # ---- 二重校验(3):冻结流水 ---- + flows = db.select("user_currency_flow", order_no=order_no, type=3) + assert len(flows) == 1 + assert_decimal_equal(flows[0]["quantity"], expect_frozen) + + # ---- 三重校验:缓存与落库一致 ---- + frozen_key = "frozen_margin:userId:%s:orderNo:%s" % (trader, order_no) + assert cache.get(frozen_key) is not None + assert_decimal_equal(cache.get(frozen_key), expect_frozen) + + # 缓存中的资金镜像(camelCase)与落库(snake_case)归一化后比对 + account_key = "account_future:userId:%s:currencyId:1" % trader + cached_account = json.loads(cache.get(account_key)) + assert_decimal_equal(cached_account["totalMoney"], after["total_money"]) + assert_decimal_equal( + cached_account["crossFrozenPositionMargin"], + after["cross_frozen_position_margin"]) + assert_decimal_equal( + cached_account["isolatedFrozenPositionMargin"], + after["isolated_frozen_position_margin"]) + + @pytest.mark.parametrize("test_input,expected", DATA["creatOrderFalseTestdata"]) + def test_invalid_order_has_no_side_effect(self, base_url, trader, db, cache, + test_input, expected): + """负例:非法请求被拒绝,且不得产生任何落库/缓存副作用。""" + before = dict(db.select("account_future", user_id=trader)[0]) + + resp = adapter.post(base_url + "/api/futures/addOrder", json=test_input) + body = resp.json() + assert body["code"] == expected["code"] + assert body["msg"] == expected["msg"] + + assert db.select("order", user_id=trader) == [] + assert db.count("user_currency_flow") == 1 # 仅初始划入的一条流水 + assert dict(db.select("account_future", user_id=trader)[0]) == before + assert cache.keys("frozen_margin:*") == [] + + def test_cancel_order_unfreeze(self, base_url, trader, db, cache): + """撤单解冻:资金全额退回、订单置为已撤销、冻结缓存键删除。""" + contract = settings.CONTRACTS[1] + order_param = { + "userId": trader, "contractId": 1, "side": "bid", "positionEffect": 1, + "price": 100, "quantity": 10, "orderType": 1, "durationQualifiers": "GTC", + "marginType": 1, "marginRate": "0.01", "orderSourceType": 1, + } + body = order_api.add_order(base_url, **order_param) + assert body["code"] == 0 + order_no = body["data"]["orderNo"] + + expect_frozen = formula.frozen_margin( + 100, 10, "0.01", contract["maker_fee_rate"], contract["taker_fee_rate"]) + frozen_key = "frozen_margin:userId:%s:orderNo:%s" % (trader, order_no) + after_order = dict(db.select("account_future", user_id=trader)[0]) + + cancel = order_api.cancel_order(base_url, trader, 1, order_no) + assert cancel["code"] == 0 + + # 落库:订单状态已撤销,资金全额退回 + order = db.select("order", order_no=order_no)[0] + assert order["status"] == 3 # 3-已撤销 + account = db.select("account_future", user_id=trader)[0] + assert_decimal_equal(account["total_money"], + after_order["total_money"] + expect_frozen) + assert_decimal_equal(account["cross_frozen_position_margin"], + after_order["cross_frozen_position_margin"] - expect_frozen) + # 解冻流水 + flows = db.select("user_currency_flow", order_no=order_no, type=4) + assert len(flows) == 1 + assert_decimal_equal(flows[0]["quantity"], expect_frozen) + # 缓存:冻结键删除,资金镜像回退 + assert cache.get(frozen_key) is None + cached = json.loads(cache.get("account_future:userId:%s:currencyId:1" % trader)) + assert_decimal_equal(cached["crossFrozenPositionMargin"], + account["cross_frozen_position_margin"]) diff --git a/case/test_position_open.py b/case/test_position_open.py new file mode 100644 index 0000000..7b344d3 --- /dev/null +++ b/case/test_position_open.py @@ -0,0 +1,118 @@ +"""场景二:市价开仓成交 —— 仓位与资金变动的 Decimal 断言。 + +市价单按标记价格立即成交,校验: +- order 表:状态全部成交、成交量; +- position 表:方向/数量/开仓均价; +- account_future 表:仓位保证金占用、手续费扣减(期望值由公式层独立计算); +- user_currency_flow 表:手续费(5)与开仓(7)两条流水; +- 缓存:仓位键与资金镜像; +- 行情联动:标记价格变化后,风控接口返回的保证金余额与公式一致。 +""" + +import json +from decimal import Decimal + +from api.order_api import OrderApi +from common.decimal_assert import assert_decimal_equal +from config import settings +from formula import contract_formula as formula + +order_api = OrderApi() + +MARK_PRICE = Decimal(settings.CONTRACTS[1]["mark_price"]) + + +def _market_order_param(user_id, side, margin_rate="0.1"): + return { + "userId": user_id, "contractId": 1, "side": side, "positionEffect": 1, + "orderType": 2, "quantity": 10, "durationQualifiers": "GTC", + "marginType": 2, "marginRate": margin_rate, "orderSourceType": 1, + } + + +class TestMarketOrderOpen: + + def test_open_long_position(self, base_url, trader, db, cache): + """做多开仓:仓位/资金/流水/缓存四面对账。""" + contract = settings.CONTRACTS[1] + before = dict(db.select("account_future", user_id=trader)[0]) + + body = order_api.add_order(base_url, **_market_order_param(trader, "bid")) + assert body["code"] == 0 + order_no = body["data"]["orderNo"] + + # 订单:市价单立即全部成交 + order = db.select("order", order_no=order_no)[0] + assert order["status"] == 22 # 22-全部成交 + assert_decimal_equal(order["filled_quantity"], order["quantity"]) + assert_decimal_equal(order["price"], MARK_PRICE) # 成交价记标记价 + + # 仓位:方向/数量/均价 + positions = db.select("position", user_id=trader, contract_id=1) + assert len(positions) == 1 + position = positions[0] + assert position["side"] == 1 # 1-做多 + assert position["status"] == 1 # 1-持仓 + assert_decimal_equal(position["quantity"], 10) + assert_decimal_equal(position["avg_price"], MARK_PRICE) + + # 期望值:公式层独立计算(逐仓保证金 + taker 手续费) + expect_init = formula.init_margin(MARK_PRICE, 10, "0.1") + expect_fee = formula.fee(MARK_PRICE, 10, + contract["maker_fee_rate"], contract["taker_fee_rate"]) + + # 资金:total 扣(保证金+手续费),逐仓保证金占用增加 + account = db.select("account_future", user_id=trader)[0] + assert_decimal_equal(account["isolated_position_margin"], + before["isolated_position_margin"] + expect_init) + assert_decimal_equal(account["total_money"], + before["total_money"] - expect_init - expect_fee) + + # 流水:手续费(5)与开仓(7) + assert_decimal_equal( + db.select("user_currency_flow", order_no=order_no, type=5)[0]["quantity"], + expect_fee) + assert_decimal_equal( + db.select("user_currency_flow", order_no=order_no, type=7)[0]["quantity"], + expect_init) + + # 缓存:仓位键与资金镜像 + cached_position = json.loads( + cache.get("position:userId:%s:contractId:1" % trader)) + assert cached_position["side"] == "1" + assert_decimal_equal(cached_position["avgPrice"], position["avg_price"]) + cached_account = json.loads( + cache.get("account_future:userId:%s:currencyId:1" % trader)) + assert_decimal_equal(cached_account["totalMoney"], account["total_money"]) + + def test_open_short_position_and_mark_price_move(self, base_url, trader, db): + """做空开仓后行情下跌:浮盈,风控返回的保证金余额与公式一致、不触发强平。""" + body = order_api.add_order(base_url, **_market_order_param(trader, "ask")) + assert body["code"] == 0 + + # 行情:标记价格 100 -> 90(做空浮盈) + assert order_api.set_mark_price(base_url, 1, "90")["code"] == 0 + + result = order_api.risk_check(base_url, trader, 1) + assert result["code"] == 0 + assert result["data"]["liquidated"] == [] + + expect_balance = formula.margin_balance("0", "ask", MARK_PRICE, "90", 10, "0.1") + report = result["data"]["positions"][0] + assert report["burst"] is False + assert_decimal_equal(report["balance"], expect_balance) + # 未实现盈亏 = (开仓价 - 标记价) * 数量 = 100 + assert_decimal_equal( + formula.unrealized_pnl("ask", MARK_PRICE, "90", 10), Decimal("100")) + + # 行情反转上涨到 105:做空浮亏,但仍未越过强平价(109.5),不应触发 + assert order_api.set_mark_price(base_url, 1, "105")["code"] == 0 + result = order_api.risk_check(base_url, trader, 1) + assert result["data"]["positions"][0]["burst"] is False + expect_balance = formula.margin_balance("0", "ask", MARK_PRICE, "105", 10, "0.1") + assert_decimal_equal(result["data"]["positions"][0]["balance"], expect_balance) + # 强平价由公式层独立计算,用于核对行情是否越界 + liq_price = formula.liquidation_price( + "ask", MARK_PRICE, 10, "0.1", settings.CONTRACTS[1]["maintain_rate"]) + assert_decimal_equal(liq_price, Decimal("109.5")) + assert Decimal("105") < liq_price # 未越过强平价,不应强平 diff --git a/common/__init__.py b/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/common/decimal_assert.py b/common/decimal_assert.py new file mode 100644 index 0000000..50180ae --- /dev/null +++ b/common/decimal_assert.py @@ -0,0 +1,30 @@ +"""资金类字段断言工具:全部走 Decimal,杜绝 float 精度误差。""" + +from decimal import Decimal + +from formula.contract_formula import to_decimal + + +def assert_decimal_equal(actual, expected, places=8): + """断言两个金额/数量在指定精度下相等。 + + 金额字段统一按 ``places`` 位小数(默认 8 位,撮合系统常用精度)量化后 + 比较,既避免逐位浮点比较的脆弱性,又不放过真实精度丢失。 + + :param actual: 实际值(HTTP 响应/落库/缓存中的值,可为字符串) + :param expected: 期望值(公式层计算结果) + :param places: 比较小数位数 + """ + quantum = Decimal(1).scaleb(-places) + actual_q = to_decimal(actual).quantize(quantum) + expected_q = to_decimal(expected).quantize(quantum) + assert actual_q == expected_q, ( + "金额不一致: actual=%s, expected=%s (精度 %d 位)" % (actual, expected, places) + ) + + +def assert_decimal_ge(actual, expected): + """断言 actual >= expected(Decimal 口径)。""" + assert to_decimal(actual) >= to_decimal(expected), ( + "断言失败: %s 应大于等于 %s" % (actual, expected) + ) diff --git a/common/http_client.py b/common/http_client.py new file mode 100644 index 0000000..2951bdf --- /dev/null +++ b/common/http_client.py @@ -0,0 +1,27 @@ +"""HTTP 客户端封装:统一请求头、统一入口,供接口封装层(api/)复用。""" + +import requests + + +class Adapter: + """对 requests 的薄封装,统一 JSON 请求头与异常口径。""" + + HEADERS = {"Content-Type": "application/json"} + + def request(self, method, url, **kwargs): + kwargs.setdefault("headers", self.HEADERS) + kwargs.setdefault("timeout", 10) + with requests.sessions.Session() as session: + return session.request(method=method, url=url, **kwargs) + + def get(self, url, params=None, **kwargs): + return self.request("get", url, params=params, **kwargs) + + def post(self, url, json=None, **kwargs): + return self.request("post", url, json=json, **kwargs) + + def put(self, url, json=None, **kwargs): + return self.request("put", url, json=json, **kwargs) + + def delete(self, url, json=None, **kwargs): + return self.request("delete", url, json=json, **kwargs) diff --git a/common/read_yaml.py b/common/read_yaml.py new file mode 100644 index 0000000..29bfeae --- /dev/null +++ b/common/read_yaml.py @@ -0,0 +1,18 @@ +"""YAML 测试数据读取器(数据驱动的数据面)。""" + +import os + +import yaml + +ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def read_yaml(filepath): + """读取 YAML 文件并返回解析后的 dict。 + + :param filepath: YAML 文件路径(绝对路径,或相对工程根目录的路径) + """ + if not os.path.isabs(filepath): + filepath = os.path.join(ROOT_DIR, filepath) + with open(filepath, encoding="utf-8") as f: + return yaml.safe_load(f.read()) diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/settings.py b/config/settings.py new file mode 100644 index 0000000..61dffaa --- /dev/null +++ b/config/settings.py @@ -0,0 +1,31 @@ +"""工程配置(演示环境)。 + +全部为本地地址/占位符,不含任何真实环境的 IP、账号、口令。 +""" + +import os + +ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +# mock 撮合服务监听地址;端口 0 表示由操作系统随机分配(由 conftest 启动) +MOCK_HOST = "127.0.0.1" +MOCK_PORT = 0 + +# 金额比较精度(小数位),与撮合系统的资金字段精度对齐 +MONEY_PRECISION = 8 + +# 演示合约参数(费率/维持保证金率均为演示值) +CONTRACTS = { + 1: { + "symbol": "BTCUSDT", + "contract_size": "1", + "mark_price": "100", # 初始标记价格 + "maintain_rate": "0.005", # 维持保证金率 + "maker_fee_rate": "0.0002", + "taker_fee_rate": "0.0005", + } +} + +# 默认测试账户(演示数据) +DEFAULT_USER_ID = 1001 +DEFAULT_BALANCE = "1000000" diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..c4c0dcf --- /dev/null +++ b/conftest.py @@ -0,0 +1,58 @@ +"""pytest 全局 fixture:启动 mock 撮合服务,注入数据面与测试账户。 + +- match_server:会话级启动本地 mock HTTP 服务(随机端口),返回 base_url; +- base_url:函数级,每个用例前重置引擎数据,保证用例相互隔离、可重复执行; +- db / cache:注入 MockMySQL / MockRedis,做落库与缓存校验; +- trader:准备默认测试账户(划入初始资金)。 +""" + +import threading + +import pytest + +from config import settings +from mock.engine import MatchEngine +from mock.server import create_server + + +@pytest.fixture(scope="session") +def engine(): + """mock 撮合引擎(会话级单例,HTTP 服务与数据面共享同一实例)。""" + return MatchEngine() + + +@pytest.fixture(scope="session") +def match_server(engine): + """启动本地 mock HTTP 服务,yield base_url。""" + server = create_server((settings.MOCK_HOST, settings.MOCK_PORT), engine) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield "http://%s:%s" % server.server_address + server.shutdown() + + +@pytest.fixture() +def base_url(match_server, engine): + """每个用例执行前重置引擎数据,返回被测服务地址。""" + engine.reset() + return match_server + + +@pytest.fixture() +def db(engine): + """落库校验数据面(内存 MySQL)。""" + return engine.db + + +@pytest.fixture() +def cache(engine): + """缓存校验数据面(内存 Redis)。""" + return engine.cache + + +@pytest.fixture() +def trader(base_url, engine): + """准备默认测试账户并划入初始资金,返回用户 ID。""" + user_id = settings.DEFAULT_USER_ID + engine.init_user(user_id, settings.DEFAULT_BALANCE) + return user_id diff --git a/data/addOrder.yml b/data/addOrder.yml new file mode 100644 index 0000000..db4a02e --- /dev/null +++ b/data/addOrder.yml @@ -0,0 +1,273 @@ +# 下单接口用例数据(数据驱动) +# 结构:[参数 dict, 期望 dict],与 @pytest.mark.parametrize("test_input,expected", ...) 按位解包 +# 正例:限价开仓冻结保证金;负例:各类非法入参 + 余额不足 + +creatOrderTrueTestdata: + # 全仓-限价-买入开仓 + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 0 + msg: OK + # 全仓-限价-卖出开仓 + - - userId: 1001 + contractId: 1 + side: ask + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 0 + msg: OK + # 逐仓-限价开仓(冻结走逐仓冻结字段) + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 2 + marginRate: '0.01' + orderSourceType: 1 + - code: 0 + msg: OK + # 更低起始保证金率(5 倍杠杆) + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.005' + orderSourceType: 1 + - code: 0 + msg: OK + +creatOrderFalseTestdata: + # userId 非数值 + - - userId: '' + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:userId" + # userId 特殊字符 + - - userId: '!@#$' + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:userId" + # 用户不存在 + - - userId: 9999 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1001 + msg: 用户不存在 + # 合约不存在 + - - userId: 1001 + contractId: 20 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1002 + msg: 合约不存在 + # side 非法枚举(数值) + - - userId: 1001 + contractId: 1 + side: 111 + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:side" + # side 非法字符串 + - - userId: 1001 + contractId: 1 + side: asdd + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:side" + # 价格为空 + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: '' + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:price" + # 价格非正数 + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: -1 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:price" + # 价格非数值 + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: abc + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:price" + # 数量为 0 + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 0 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:quantity" + # 委托类型非法 + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 5 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:orderType" + # 保证金模式非法 + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 3 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:marginType" + # 保证金率超上限(>1) + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '2' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:marginRate" + # 有效期非法 + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 100 + quantity: 10 + orderType: 1 + durationQualifiers: SDFSDF + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 1003 + msg: "参数错误:durationQualifiers" + # 余额不足(冻结金额超过账户资金) + - - userId: 1001 + contractId: 1 + side: bid + positionEffect: 1 + price: 99999999 + quantity: 10 + orderType: 1 + durationQualifiers: GTC + marginType: 1 + marginRate: '0.01' + orderSourceType: 1 + - code: 2001 + msg: 余额不足 diff --git a/data/formula.yml b/data/formula.yml new file mode 100644 index 0000000..08dba97 --- /dev/null +++ b/data/formula.yml @@ -0,0 +1,32 @@ +# 合约公式层纯函数用例数据(数据驱动) +# 期望值均为 Decimal 精确结果;费率用合约参数(maker=0.0002, taker=0.0005) + +frozenMargin: + - {price: 100, quantity: 10, margin_rate: '0.01', expected: '10.5'} + - {price: 100, quantity: 10, margin_rate: '0.005', expected: '5.5'} + - {price: '95.5', quantity: '2', margin_rate: '0.1', expected: '19.1955'} + # 精度演示:float 下 0.1*3=0.30000000000000004,Decimal 精确 + - {price: '0.1', quantity: '3', margin_rate: '1', expected: '0.30015'} + +unrealizedPnl: + - {side: bid, open_price: 100, mark_price: 110, quantity: 10, expected: '100'} + - {side: bid, open_price: 100, mark_price: 90, quantity: 10, expected: '-100'} + - {side: ask, open_price: 100, mark_price: 90, quantity: 10, expected: '100'} + - {side: ask, open_price: 100, mark_price: 110, quantity: 10, expected: '-100'} + +bankruptcyPrice: + - {side: bid, open_price: 100, quantity: 10, margin_rate: '0.1', extra_margin: '0', expected: '90'} + - {side: ask, open_price: 100, quantity: 10, margin_rate: '0.1', extra_margin: '0', expected: '110'} + - {side: bid, open_price: 100, quantity: 10, margin_rate: '0.1', extra_margin: '20', expected: '88'} + +liquidationPrice: + - {side: bid, open_price: 100, quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '0', expected: '90.5'} + - {side: ask, open_price: 100, quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '0', expected: '109.5'} + - {side: bid, open_price: 100, quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '20', expected: '88.5'} + +isBurst: + # 恰好等于强平价:保证金余额 == 维持保证金,<= 即触发 + - {side: bid, open_price: 100, mark_price: '90.5', quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '0', expected: true} + - {side: bid, open_price: 100, mark_price: '91', quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '0', expected: false} + - {side: ask, open_price: 100, mark_price: '109.5', quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '0', expected: true} + - {side: ask, open_price: 100, mark_price: '109', quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '0', expected: false} diff --git a/data/liquidation.yml b/data/liquidation.yml new file mode 100644 index 0000000..5ec3804 --- /dev/null +++ b/data/liquidation.yml @@ -0,0 +1,26 @@ +# 强平场景用例数据(数据驱动) +# 每行一个场景:市价开仓(开仓时标记价 100)→ 设安全标记价(不触发) +# → 设触发标记价(触发强平)。期望的强平价/破产价由公式层独立计算。 + +liquidationScenarios: + # 做多 10 倍杠杆:强平价 90.5,破产价 90 + - name: 做多-触及强平价触发 + side: bid + quantity: 10 + marginRate: '0.1' + safeMark: '91' + triggerMark: '90.5' + # 做空 10 倍杠杆:强平价 109.5,破产价 110 + - name: 做空-触及强平价触发 + side: ask + quantity: 10 + marginRate: '0.1' + safeMark: '109' + triggerMark: '109.5' + # 做多且标记价跌破破产价:穿仓,缺口由风险基金兜底 + - name: 做多-穿仓由风险基金兜底 + side: bid + quantity: 10 + marginRate: '0.1' + safeMark: '91' + triggerMark: '85' diff --git a/formula/__init__.py b/formula/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/formula/contract_formula.py b/formula/contract_formula.py new file mode 100644 index 0000000..cb84726 --- /dev/null +++ b/formula/contract_formula.py @@ -0,0 +1,123 @@ +"""合约公式层:永续合约撮合核心业务公式的纯函数实现。 + +本模块全部为无副作用纯函数,入参/out 参一律使用 Decimal(通过 ``to_decimal`` +转换),杜绝 float 二进制精度误差 —— 这是合约资金类断言的正确性前提。 +用例侧用这些函数计算"期望值",再与被测系统(HTTP 响应/落库/缓存)比对。 +""" + +from decimal import Decimal + +#: 持仓方向:做多( bid / side == 1) +SIDE_LONG = 1 +#: 持仓方向:做空( ask / side == 2) +SIDE_SHORT = -1 + + +def to_decimal(value) -> Decimal: + """把任意数值(含字符串形式的数值)转为 Decimal。 + + 走 ``str()`` 而非 ``Decimal(float)``,避免 float 先行引入精度误差。 + """ + if isinstance(value, Decimal): + return value + return Decimal(str(value)) + + +def side_to_direction(side) -> int: + """把下单方向(bid/ask 或 1/2)规整为持仓方向 1(多)/ -1(空)。""" + if side in ("bid", "BUY", 1, "1"): + return SIDE_LONG + if side in ("ask", "SELL", 2, "2"): + return SIDE_SHORT + raise ValueError("非法的持仓方向: %r" % (side,)) + + +def open_value(price, quantity) -> Decimal: + """开仓价值 = 开仓价格 * 数量。""" + return to_decimal(price) * to_decimal(quantity) + + +def init_margin(price, quantity, margin_rate) -> Decimal: + """起始(初始)保证金 = 开仓价值 * 起始保证金率(杠杆倍数取反)。""" + return open_value(price, quantity) * to_decimal(margin_rate) + + +def fee(price, quantity, maker_fee_rate, taker_fee_rate) -> Decimal: + """手续费 = 开仓价值 * max(maker 费率, taker 费率)。 + + 冻结场景按"孰高"预冻结,撮合后按实际角色多退少不补。 + """ + value = open_value(price, quantity) + maker_fee = value * to_decimal(maker_fee_rate) + taker_fee = value * to_decimal(taker_fee_rate) + return max(maker_fee, taker_fee) + + +def frozen_margin(price, quantity, margin_rate, maker_fee_rate, taker_fee_rate) -> Decimal: + """下单冻结保证金 = 起始保证金 + max(maker, taker) 手续费。 + + 对应限价委托进入订单簿后的资金冻结口径。 + """ + return ( + init_margin(price, quantity, margin_rate) + + fee(price, quantity, maker_fee_rate, taker_fee_rate) + ) + + +def maintain_margin(open_price, quantity, maintain_rate) -> Decimal: + """维持保证金 = 开仓价值 * 维持保证金率。""" + return open_value(open_price, quantity) * to_decimal(maintain_rate) + + +def unrealized_pnl(side, open_price, mark_price, quantity) -> Decimal: + """未实现盈亏 = 持仓方向 * (标记价格 - 开仓均价) * 数量。""" + direction = side_to_direction(side) + return direction * (to_decimal(mark_price) - to_decimal(open_price)) * to_decimal(quantity) + + +def margin_balance(extra_margin, side, open_price, mark_price, quantity, margin_rate) -> Decimal: + """逐仓保证金余额 = 额外保证金 + 起始保证金 + 未实现盈亏。""" + return ( + to_decimal(extra_margin) + + init_margin(open_price, quantity, margin_rate) + + unrealized_pnl(side, open_price, mark_price, quantity) + ) + + +def is_burst(extra_margin, side, open_price, mark_price, quantity, + margin_rate, maintain_rate) -> bool: + """爆仓(强平触发)判断:保证金余额 <= 维持保证金 即触发。""" + balance = margin_balance(extra_margin, side, open_price, mark_price, quantity, margin_rate) + return balance <= maintain_margin(open_price, quantity, maintain_rate) + + +def bankruptcy_price(side, open_price, quantity, margin_rate, extra_margin="0") -> Decimal: + """破产价格:保证金余额恰好归零时的标记价格(逐仓口径)。 + + 做多: p = open * (1 - margin_rate) - extra / qty + 做空: p = open * (1 + margin_rate) + extra / qty + """ + open_price = to_decimal(open_price) + quantity = to_decimal(quantity) + margin_rate = to_decimal(margin_rate) + extra = to_decimal(extra_margin) + if side_to_direction(side) == SIDE_LONG: + return open_price * (1 - margin_rate) - extra / quantity + return open_price * (1 + margin_rate) + extra / quantity + + +def liquidation_price(side, open_price, quantity, margin_rate, + maintain_rate, extra_margin="0") -> Decimal: + """强平价格:保证金余额恰好等于维持保证金时的标记价格(逐仓口径)。 + + 令 extra + init + upnl(mark) == maintain,反解 mark: + mark = open + direction * (maintain - extra - init) / qty + 标记价格越过该价位(沿亏损方向)即触发强平。 + """ + direction = side_to_direction(side) + open_price = to_decimal(open_price) + quantity = to_decimal(quantity) + init = init_margin(open_price, quantity, margin_rate) + maintain = maintain_margin(open_price, quantity, maintain_rate) + gap = (maintain - to_decimal(extra_margin) - init) / quantity + return open_price + direction * gap diff --git a/mock/__init__.py b/mock/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mock/engine.py b/mock/engine.py new file mode 100644 index 0000000..de2acaa --- /dev/null +++ b/mock/engine.py @@ -0,0 +1,428 @@ +"""mock 撮合引擎:以内存态模拟永续合约撮合系统的核心业务行为。 + +本模块是"被测系统"的替身,实现下单冻结、市价成交开仓、撤单解冻、 +标记价格设置与强平风控检查等行为,并同步写入 MockMySQL(落库)与 +MockRedis(缓存),为用例的"三重校验"提供数据面。 + +注意:引擎内部的资金计算刻意**不复用** formula 包,而是独立实现一份 +Decimal 运算 —— 与真实工程保持同一形态:被测系统是独立服务,期望值 +由测试侧公式层独立计算后再与系统行为比对。 +""" + +import json +from decimal import Decimal + +from config 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/futures/addOrder": "add_order", + "/api/futures/cancelOrder": "cancel_order", + "/api/future/user/transferIn": "transfer_in", + "/api/future/mark/setMarkPrice": "set_mark_price", + "/api/future/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("durationQualifiers", "GTC") not in ("GTC", "IOC", "FOK", "GTX"): + raise ParamError("durationQualifiers") + 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( + "frozen_margin: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("frozen_margin:userId:%s:orderNo:%s" % (user_id, order_no)) + self._sync_account_cache(user_id) + return 0, "OK", {"contractId": contract_id, "orderNo": order_no} + + def transfer_in(self, body): + """测试辅助:给用户账户划入资金。""" + user_id = self._to_int(body, "userId") + amount = self._to_positive_decimal(body, "amount") + account = self._get_account(user_id) + if account is None: + return 1001, "用户不存在", None + account["total_money"] += amount + self._add_flow(user_id, FLOW_TRANSFER_IN, amount, None) + self._sync_account_cache(user_id) + return 0, "OK", {"totalMoney": str(account["total_money"])} + + 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("account_future", { + "user_id": user_id, + "currency_id": CURRENCY_ID, + "total_money": Decimal(str(balance)), + "cross_position_margin": Decimal("0"), + "cross_frozen_position_margin": Decimal("0"), + "isolated_position_margin": Decimal("0"), + "isolated_frozen_position_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("force_close_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_flow", { + "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("account_future", user_id=user_id) + return rows[0] if rows else None + + @staticmethod + def _margin_field(margin_type): + """仓位保证金字段:1-全仓 2-逐仓。""" + return "cross_position_margin" if margin_type == 1 else "isolated_position_margin" + + @staticmethod + def _frozen_field(margin_type): + """冻结保证金字段:1-全仓 2-逐仓。""" + if margin_type == 1: + return "cross_frozen_position_margin" + return "isolated_frozen_position_margin" + + def _add_flow(self, user_id, flow_type, quantity, order_no): + """写一条用户资金流水。""" + self._flow_seq += 1 + self.db.insert("user_currency_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( + "account_future:userId:%s:currencyId:%s" % (user_id, CURRENCY_ID), + json.dumps({ + "userId": str(user_id), + "currencyId": str(CURRENCY_ID), + "totalMoney": str(account["total_money"]), + "crossPositionMargin": str(account["cross_position_margin"]), + "crossFrozenPositionMargin": str(account["cross_frozen_position_margin"]), + "isolatedPositionMargin": str(account["isolated_position_margin"]), + "isolatedFrozenPositionMargin": str(account["isolated_frozen_position_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 diff --git a/mock/fake_cache.py b/mock/fake_cache.py new file mode 100644 index 0000000..cc28fe0 --- /dev/null +++ b/mock/fake_cache.py @@ -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() diff --git a/mock/fake_db.py b/mock/fake_db.py new file mode 100644 index 0000000..77310d9 --- /dev/null +++ b/mock/fake_db.py @@ -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)) diff --git a/mock/server.py b/mock/server.py new file mode 100644 index 0000000..060c5de --- /dev/null +++ b/mock/server.py @@ -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) diff --git a/mock/test_api_client_gen.py b/mock/test_api_client_gen.py new file mode 100644 index 0000000..d7e569f --- /dev/null +++ b/mock/test_api_client_gen.py @@ -0,0 +1,84 @@ +import pytest +from unittest.mock import patch, MagicMock +from api.order_api import OrderApi + + +class TestOrderApi: + @patch('api.order_api.Adapter') + def test_add_order_parameters(self, mock_adapter_cls): + """验证 add_order 参数映射到 payload""" + mock_adapter = MagicMock() + mock_adapter_cls.return_value = mock_adapter + mock_adapter.post.return_value.json.return_value = {"success": True} + + api = OrderApi() + base_url = "http://test" + params = {"symbol": "BTCUSDT", "price": 50000, "qty": 1} + api.add_order(base_url, **params) + + expected_url = base_url + OrderApi.ADD_ORDER + mock_adapter.post.assert_called_once_with(expected_url, json=params) + + @patch('api.order_api.Adapter') + def test_cancel_order_payload(self, mock_adapter_cls): + """验证 cancel_order 构造的 payload""" + mock_adapter = MagicMock() + mock_adapter_cls.return_value = mock_adapter + mock_adapter.post.return_value.json.return_value = {"success": True} + + api = OrderApi() + base_url = "http://test" + user_id = "user1" + contract_id = "BTC" + order_no = "ord123" + api.cancel_order(base_url, user_id, contract_id, order_no) + + expected_url = base_url + OrderApi.CANCEL_ORDER + expected_payload = { + "userId": user_id, + "contractId": contract_id, + "orderNo": order_no, + } + mock_adapter.post.assert_called_once_with(expected_url, json=expected_payload) + + @patch('api.order_api.Adapter') + def test_post_returns_json(self, mock_adapter_cls): + """验证 _post 方法返回响应的 json""" + mock_adapter = MagicMock() + mock_adapter_cls.return_value = mock_adapter + mock_response = MagicMock() + mock_response.json.return_value = {"status": "ok"} + mock_adapter.post.return_value = mock_response + + api = OrderApi() + base_url = "http://test" + path = "/api/test" + payload = {"a": 1} + result = api._post(base_url, path, payload) + + assert result == {"status": "ok"} + mock_adapter.post.assert_called_once_with(base_url + path, json=payload) + + @patch('api.order_api.Adapter') + def test_network_error_propagates(self, mock_adapter_cls): + """验证网络异常时异常传播""" + mock_adapter = MagicMock() + mock_adapter_cls.return_value = mock_adapter + mock_adapter.post.side_effect = ConnectionError("Network error") + + api = OrderApi() + with pytest.raises(ConnectionError, match="Network error"): + api._post("http://test", "/api/test", {}) + + @patch('api.order_api.Adapter') + def test_add_order_returns_correct_result(self, mock_adapter_cls): + """验证 add_order 返回正确的 json 结果""" + mock_adapter = MagicMock() + mock_adapter_cls.return_value = mock_adapter + mock_adapter.post.return_value.json.return_value = {"orderId": "12345", "status": "filled"} + + api = OrderApi() + result = api.add_order("http://test", symbol="ETH", price=2000, qty=2) + + assert result == {"orderId": "12345", "status": "filled"} + mock_adapter.post.assert_called_once() \ No newline at end of file diff --git a/mock/test_formula_gen.py b/mock/test_formula_gen.py new file mode 100644 index 0000000..ef774f3 --- /dev/null +++ b/mock/test_formula_gen.py @@ -0,0 +1,89 @@ +import pytest +from decimal import Decimal +from unittest.mock import patch, MagicMock +from formula.contract_formula import ( + to_decimal, side_to_direction, open_value, init_margin, fee, + frozen_margin, maintain_margin, unrealized_pnl, margin_balance, + is_burst, bankruptcy_price, liquidation_price, SIDE_LONG, SIDE_SHORT +) + + +class TestContractFormula: + + @patch("formula.contract_formula.init_margin") + @patch("formula.contract_formula.fee") + def test_frozen_margin_returns_sum_of_init_margin_and_fee(self, mock_fee, mock_init_margin): + """验证 frozen_margin 返回 init_margin 和 fee 的和,且参数正确传递。""" + # 模拟 init_margin 返回 Decimal('100') + mock_init_margin.return_value = Decimal('100') + # 模拟 fee 返回 Decimal('20') + mock_fee.return_value = Decimal('20') + + result = frozen_margin(price="10", quantity="5", margin_rate="0.1", + maker_fee_rate="0.001", taker_fee_rate="0.002") + assert result == Decimal('120') + + # 验证 init_margin 被用正确参数调用 + mock_init_margin.assert_called_once_with("10", "5", "0.1") + # 验证 fee 被用正确参数调用 + mock_fee.assert_called_once_with("10", "5", "0.001", "0.002") + + @patch("formula.contract_formula.side_to_direction") + @patch("formula.contract_formula.to_decimal") + def test_unrealized_pnl_calculates_correctly(self, mock_to_decimal, mock_side_to_direction): + """验证 unrealized_pnl 返回正确的未实现盈亏,并使用了方向转换。""" + # 模拟 side_to_direction 返回 1(做多) + mock_side_to_direction.return_value = SIDE_LONG + # 模拟 to_decimal 依次返回 Decimal('10'), Decimal('12'), Decimal('5') + # 注意 to_decimal 会被调用多次(mark_price, open_price, quantity) + mock_to_decimal.side_effect = [Decimal('12'), Decimal('10'), Decimal('5')] + + result = unrealized_pnl(side="bid", open_price="10", mark_price="12", quantity="5") + assert result == Decimal('10') + + # 验证 side_to_direction 被调用 + mock_side_to_direction.assert_called_once_with("bid") + # 验证 to_decimal 被调用了三次 + assert mock_to_decimal.call_count == 3 + + def test_is_burst_returns_true_when_margin_balance_less_or_equal_maintain(self): + """验证保证金余额 <= 维持保证金时返回 True,否则返回 False。""" + # 针对爆仓场景:合理设置参数使得余额小于维持保证金 + # 使用真实计算,不 mock 内部函数,以验证整体逻辑 + # 做多,开仓价10,数量1,保证金率0.1,维持率0.05,额外保证金0 + # 标记价格跌至0,未实现盈亏为 -10,起始保证金1,余额=0+1-10=-9,维持保证金=10*1*0.05=0.5,-9 <= 0.5 → True + assert is_burst(extra_margin="0", side="bid", open_price="10", mark_price="0", + quantity="1", margin_rate="0.1", maintain_rate="0.05") is True + + # 标记价格未跌,未实现盈亏0,余额=1,维持保证金=0.5,1 > 0.5 → False + assert is_burst(extra_margin="0", side="bid", open_price="10", mark_price="10", + quantity="1", margin_rate="0.1", maintain_rate="0.05") is False + + @patch("formula.contract_formula.side_to_direction") + def test_bankruptcy_price_returns_correct_formula(self, mock_side_to_direction): + """验证破产价格公式,做多和做空方向分别计算。""" + # 测试做多方向 + mock_side_to_direction.return_value = SIDE_LONG + result_long = bankruptcy_price(side="bid", open_price="100", quantity="10", + margin_rate="0.2", extra_margin="5") + # 期望:100 * (1 - 0.2) - 5/10 = 80 - 0.5 = 79.5 + assert result_long == Decimal('79.5') + + # 测试做空方向 + mock_side_to_direction.return_value = SIDE_SHORT + result_short = bankruptcy_price(side="ask", open_price="100", quantity="10", + margin_rate="0.2", extra_margin="5") + # 期望:100 * (1 + 0.2) + 5/10 = 120 + 0.5 = 120.5 + assert result_short == Decimal('120.5') + + # 验证 side_to_direction 被调用了两次 + assert mock_side_to_direction.call_count == 2 + + def test_side_to_direction_raises_value_error_for_invalid_side(self): + """验证 side_to_direction 对非法输入抛出 ValueError。""" + with pytest.raises(ValueError, match="非法的持仓方向"): + side_to_direction("invalid") + with pytest.raises(ValueError, match="非法的持仓方向"): + side_to_direction(3) + with pytest.raises(ValueError, match="非法的持仓方向"): + side_to_direction(None) \ No newline at end of file diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..3125a27 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +testpaths = case +addopts = -ra --strict-markers diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a5b6118 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +pytest>=7.0 +pytest-cov>=4.0 +requests>=2.25 +PyYAML>=5.4