feat: 合约撮合 HTTP 接口自动化测试(unittest 数据驱动)
CI / test (push) Canceled after 4m26s

This commit is contained in:
WbiubiuW
2026-09-22 14:28:42 +08:00
commit b8a74f203a
69 changed files with 2413 additions and 0 deletions
Executable
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
Executable
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
+24
View File
@@ -0,0 +1,24 @@
name: CI
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python 3.13
uses: actions/setup-python@v5
with:
python-version: "3.13"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run tests
run: python -m pytest -q
+9
View File
@@ -0,0 +1,9 @@
__pycache__/
*.pyc
.pytest_cache/
.venv/
venv/
.coverage
htmlcov/
*.db
.DS_Store
+250
View File
@@ -0,0 +1,250 @@
# contract-match-http-autotest —— 永续合约撮合系统 HTTP 接口自动化测试演示工程
## 一、5 分钟快速导览
如果时间只有 5 分钟,建议按这个顺序看:
1. **先往下看「四、架构」的架构图** —— 30 秒看懂分层:用例层、数据层、公式层、框架层、
被测系统、校验面各就各位;
2. **再看「三、用例覆盖清单」** —— 一张表说清测了什么场景、多少用例、断言到哪几面,
这是测试工程师最该拿出的东西;
3. **然后读 `case/test_liquidation.py`** —— 最能体现三重校验(HTTP 响应 + 落库 +
缓存)的用例,行情驱动到强平价,断言风险基金流水;
4. **最后看 `formula/contract_formula.py`** —— 为什么期望值要独立计算而不是抄被测
系统的返回值。
### 为什么用 mock 而不是真环境
- **脱敏**:本工程不含任何真实企业信息 —— 合约参数、费率、字段命名、接口路径
全部是占位值与中性演示路径,由 mock 引擎在本地重建;
- **可复现**:clone 下来 `pytest` 一把全绿,不需要申请环境、不需要 VPN、
不需要外网;
- **校验链路同构**:mock 的 HTTP 服务、落库、缓存的交互形态与真实微服务工程一致,
换真环境只需替换 `conftest.py` 的 fixture,用例代码一行不改;
- **故意不复用**:mock 引擎内部的资金计算刻意独立于 `formula/` 包实现,保持
「被测系统 vs 测试侧期望值」两条独立计算链,避免同一份代码自证。
## 二、这个工程解决什么问题
永续合约撮合系统由订单受理、撮合引擎、风控、清算等多个微服务组成,接口数量多、
业务状态复杂。只断言 HTTP 返回码远远不够 —— 一笔下单请求,系统侧真实发生的是
**资金冻结、订单落库、仓位变更、缓存更新**四件事,任何一环出错都是资损事故。
本工程演示针对这类系统的接口自动化测试方法论,核心是三件事:
1. **三重校验**:HTTP 响应 + 数据库落库 + 缓存,三面同时断言,而不是只看返回值;
2. **公式层计算期望值**:保证金、手续费、强平价、破产价等撮合公式以纯函数独立
实现,期望值不靠"先跑一遍抄下来",而是算出来 —— 公式错了测试会红,系统错
了测试也会红;
3. **YAML 数据驱动**:用例与数据分离,一个用例函数覆盖正例/负例/边界值全家桶。
为了让工程**脱离真实环境也能跑通**,被测撮合系统以本地 mock 引擎实现
(标准库 wsgiref HTTP 服务 + 内存 MySQL/Redis),校验链路与真实工程完全同构,
`pytest` 一把全绿,不连任何外网、数据库与中间件。
## 三、用例覆盖清单
共 **85** 条用例,全部通过(数据来源:`pytest --collect-only -q`,2026-09-22 实测)。
| 业务场景 | 用例数 | 断言面(HTTP / 落库 / 缓存) | 覆盖的关键点 |
| --- | --- | --- | --- |
| 下单冻结保证金(正例,数据驱动) | 15 | HTTP + 落库 + 缓存 | 全仓/逐仓 × 买/卖 × 起始保证金率三档;冻结 = 起始保证金 + 孰高手续费;订单字段 / 资金扣减 / 冻结流水 / 冻结键值四面对账 |
| 下单非法入参(负例,数据驱动) | 22 | HTTP + 落库 + 缓存 | 价格/数量为 0 或负数、保证金率非法、缺字段、参数非法值;限价与市价两条路径各自的余额不足;**额外断言「无副作用」**:订单表无新增、资金无变动、缓存无残留 |
| 撤单解冻(含状态机) | 7 | HTTP + 落库 + 缓存 | 冻结全额解冻回可用;解冻流水;冻结键值清理;重复撤单 / 撤已成交单 / 撤不存在单 / 缺单号的状态机与参数校验;解冻后可再次下单 |
| 市价开仓成交 | 2 | HTTP + 落库 + 缓存 | 多/空两个方向;按 taker 费率立即成交;仓位 / 手续费流水 / 仓位缓存;标记价移动后未实现盈亏 |
| 强平触发校验(数据驱动) | 6 | HTTP + 落库 + 缓存 | 安全价不触发、触发价强平两段式;破产价与公式一致;剩余保证金入风险基金;穿仓缺口由风险基金兜底并扣减可用;仓位清零、缓存键删除 |
| 公式层纯函数单测(数据驱动) | 33 | 纯函数(无 IO) | 冻结保证金 / 未实现盈亏 / 破产价 / 强平价 / 爆仓判断,期望值**手算写死**防自证;含强平边界(`<=` 闭区间)、非法方向抛错与 float 精度反例 |
## 四、架构
![系统架构](docs/architecture.svg)
分层职责:
| 层 | 目录 | 职责 |
| --- | --- | --- |
| 用例层 | `case/` | 业务断言的组织,只关心"给什么、期望什么" |
| 数据层 | `data/` | 用例参数与期望值,`[参数dict, 期望dict]` 结构供 parametrize 解包 |
| 公式层 | `formula/` | 撮合业务公式纯函数,全部 Decimal,是期望值的唯一来源 |
| 框架层 | `framework/` | 接口封装、YAML 读取、Decimal 断言、HTTP 客户端与工程配置 |
| 被测系统 | `mock/` | 本地撮合引擎 + HTTP 服务 + 内存库/缓存 |
| 文档 | `docs/` | 架构图(矢量) |
## 五、怎么跑
```bash
cd contract-match-http-autotest
python -m venv venv && source venv/bin/activate # 可选
pip install -r requirements.txt # pytest / pytest-cov / requests / PyYAML
python -m pytest # 全部用例
python -m pytest case/test_liquidation.py -v # 单个场景
python -m pytest -k liquidation # 按关键字筛选
```
### 覆盖率
```bash
python -m pytest --cov=formula --cov=mock --cov=framework --cov-report=term-missing
```
2026-09-22 实测输出(macOS / Python 3.13.12 / pytest 9.1.1):
```
Name Stmts Miss Cover Missing
-----------------------------------------------------------
formula/contract_formula.py 50 0 100%
framework/decimal_assert.py 7 0 100%
framework/http_client.py 16 3 81% 18, 24, 27
framework/order_api.py 19 0 100%
framework/read_yaml.py 8 0 100%
framework/settings.py 8 0 100%
mock/engine.py 228 6 97% 79, 225, 234, 237, 375-376
mock/fake_cache.py 14 1 93% 29
mock/fake_db.py 10 0 100%
mock/server.py 24 2 92% 37-38
-----------------------------------------------------------
TOTAL 384 12 97%
```
**TOTAL line coverage = 97%**,如实说明未覆盖部分及原因:
- `formula/contract_formula.py` 50 条语句 **100% 覆盖** —— 公式层是期望值的唯一
来源,不留未覆盖分支是刻意要求;
- `framework/` 下四个模块 **100% 覆盖**;`http_client.py` 未覆盖的 18/24/27 三行是
`Adapter` 的 `get` / `put` / `delete` —— 本工程只发 POST,其余动词是通用 HTTP
封装的正常 API 面,不构造用例去凑数字;
- `mock/engine.py` 未覆盖的 6 行是**防御性分支**:第 79 行是路由表兜底(未知路径
返回 404),225 / 234 / 237 是「合约不存在」「用户不存在」的入参防御,375-376 是
`_sync_position_cache` 的「无持仓 → 删缓存」分支 —— 该方法唯一调用点是市价开仓
(必然有持仓),强平路径另行直接删除缓存键,故这条分支未被用例触达;
- `mock/server.py` 未覆盖的 37-38 行是服务启动入口的异常兜底,只在进程直接运行
时触发,conftest 以函数调用方式拉起服务所以走不到;
- `mock/fake_cache.py` 第 29 行是 `flushall`(用例靠 `engine.reset()` 做隔离,不用它)。
无需任何环境准备: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("order_freeze: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 先行引入误差);
- `framework/decimal_assert.py::assert_decimal_equal` 统一按 8 位小数量化比较,
既不逐位较真浮点表示,也不放过真实精度丢失;
- `case/test_formula.py::test_decimal_precision_over_float` 用 float 反例固化这条规约。
### 2. 期望值从哪来:公式层纯函数,手算用例防自证
- 保证金/手续费/强平价/破产价等公式抽成 `formula/` 纯函数(无 IO、无状态),
场景用例一律调它算期望值;
- 公式层自身另有单测(`data/formula.yml`),期望值是**手算写死**的,防止公式
实现自证清白;
- 强平边界语义(保证金余额恰好等于维持保证金时 `<=` 判定触发)单独用边界用例
固化,这是生产上最容易扯皮的一格。
### 3. 三重校验的落地:落库与缓存字段不一致
- 落库校验断言 `futures_account` / `order` / `account_flow` 三张表,
缓存校验断言 `order_freeze:*` / `futures_account:*` / `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 / pytest-cov / requests / PyYAML
├── pytest.ini # testpaths = case
├── conftest.py # fixture:启动 mock 服务、注入数据面、用例隔离
├── framework/ # 框架层
│ ├── order_api.py # 下单/撤单/标记价/风控接口封装
│ ├── http_client.py # requests 薄封装(统一 JSON 头与超时)
│ ├── read_yaml.py # YAML 数据读取
│ ├── decimal_assert.py # Decimal 金额断言工具
│ └── settings.py # 合约参数/费率/精度(演示占位值)
├── formula/
│ └── contract_formula.py # 合约公式层(纯函数,全 Decimal)
├── mock/ # 被测系统
│ ├── engine.py # 撮合引擎(下单冻结/市价成交/撤单解冻/强平风控)
│ ├── server.py # wsgiref HTTP 服务
│ ├── fake_db.py # 内存 MySQL
│ └── fake_cache.py # 内存 Redis
├── case/
│ ├── test_order_freeze.py # 场景一:下单冻结保证金(三重校验)
│ ├── test_cancel_order.py # 场景四:撤单解冻(状态机/参数/无副作用)
│ ├── test_position_open.py # 场景二:市价开仓成交
│ ├── test_liquidation.py # 场景三:强平触发校验
│ └── test_formula.py # 公式层纯函数单测
├── data/
│ ├── addOrder.yml # 下单正例/负例(数据驱动)
│ ├── cancelOrder.yml # 撤单场景数据
│ ├── liquidation.yml # 强平场景数据
│ └── formula.yml # 公式期望值(手算写死)
└── docs/
└── architecture.svg # 架构图(矢量)
```
## 八、业务口径速查(演示参数)
| 口径 | 值/规则 |
| --- | --- |
| 合约 | 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` |
| 穿仓 | 强平后保证金余额为负:缺口扣减可用余额,由风险基金兜底 |
| 资金流水类型 | 划入 / 划出 / 冻结 / 解冻 / 手续费 / 开仓 / 强平(枚举值见 `mock/engine.py` 的 `FLOW_*` 常量,均为演示值) |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
View File
+192
View File
@@ -0,0 +1,192 @@
"""场景四:撤单解冻 —— 资损高发链路的三重校验。
撤单是把"冻结保证金"完整退回"可用余额"的资金链路,任何一环(落库状态、
资金回退、流水、缓存键)出错都是资损事故。本文件对照 mock 引擎的撤单实现逐条
校验:
- 正常撤单:订单置已撤销、资金全额退回、冻结字段归零、解冻流水、缓存键删除;
- 状态机:重复撤单 / 撤已成交单返回 2003(状态不允许);撤不存在的单返回 2002;
- 参数:缺 orderNo 返回参数错误;
- 副作用:解冻确实回补可用额度 —— 撤单后同样的资金可再次下单成功。
期望冻结金额由 formula 层独立计算(formula.frozen_margin),与被测引擎的
内部实现无关;场景数据由 data/cancelOrder.yml 驱动。
"""
import json
import pytest
from framework.order_api import OrderApi
from framework.decimal_assert import assert_decimal_equal
from framework.read_yaml import read_yaml
from framework import settings
from formula import contract_formula as formula
DATA = read_yaml("data/cancelOrder.yml")
order_api = OrderApi()
ACCOUNT_KEY = "futures_account:userId:%s:currencyId:1"
def _frozen_field(margin_type):
"""保证金模式对应的冻结字段:1-全仓 2-逐仓。"""
if int(margin_type) == 1:
return "cross_frozen_margin"
return "isolated_frozen_margin"
def _frozen_cache_field(margin_type):
"""保证金模式对应的冻结字段(camelCase,缓存镜像用)。"""
if int(margin_type) == 1:
return "crossFrozenMargin"
return "isolatedFrozenMargin"
class TestCancelOrder:
@pytest.mark.parametrize("scenario", DATA["cancelScenarios"])
def test_cancel_order_unfreeze(self, base_url, trader, db, cache, scenario):
"""正常撤单:资金全额退回、订单置已撤销、冻结缓存键删除、解冻流水落库。"""
contract = settings.CONTRACTS[scenario["order"]["contractId"]]
order_param = dict(scenario["order"], userId=trader)
margin_type = order_param["marginType"]
db_field = _frozen_field(margin_type)
cache_field = _frozen_cache_field(margin_type)
# 下单挂单(限价单进入订单簿,冻结保证金)
body = order_api.add_order(base_url, **order_param)
assert body["code"] == 0
order_no = body["data"]["orderNo"]
# 期望冻结金额:公式层独立计算(起始保证金 + 孰高手续费)
expect_frozen = formula.frozen_margin(
order_param["price"], order_param["quantity"], order_param["marginRate"],
contract["maker_fee_rate"], contract["taker_fee_rate"])
frozen_key = "order_freeze:userId:%s:orderNo:%s" % (trader, order_no)
after_order = dict(db.select("futures_account", user_id=trader)[0])
# ---- 一重校验:HTTP 响应 ----
cancel = order_api.cancel_order(
base_url, trader, order_param["contractId"], order_no)
assert cancel["code"] == 0
assert cancel["msg"] == "OK"
# ---- 二重校验(1):订单落库,状态置为已撤销 ----
order = db.select("order", order_no=order_no)[0]
assert order["status"] == 3 # 3-已撤销
# ---- 二重校验(2):资金全额退回,冻结字段回退 ----
account = db.select("futures_account", user_id=trader)[0]
assert_decimal_equal(account["total_money"],
after_order["total_money"] + expect_frozen)
assert_decimal_equal(account[db_field],
after_order[db_field] - expect_frozen)
assert_decimal_equal(account[db_field], 0) # 冻结归零
# ---- 二重校验(3):解冻流水,金额 == 原冻结额 ----
flows = db.select("account_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_KEY % trader))
assert_decimal_equal(cached["totalMoney"], account["total_money"])
assert_decimal_equal(cached[cache_field], account[db_field])
def test_repeat_cancel_rejected(self, base_url, trader, db, cache):
"""重复撤单:第一次成功后,第二次返回 2003,且不产生第二条解冻流水。"""
order_param = {
"userId": trader, "contractId": 1, "side": "bid", "positionEffect": 1,
"price": 100, "quantity": 10, "orderType": 1, "timeInForce": "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"]
first = order_api.cancel_order(base_url, trader, 1, order_no)
assert first["code"] == 0
after_first = dict(db.select("futures_account", user_id=trader)[0])
second = order_api.cancel_order(base_url, trader, 1, order_no)
assert second["code"] == 2003
assert second["msg"] == "订单状态不允许撤单"
# 无副作用:资金不变、解冻流水只有第一次那一条
assert dict(db.select("futures_account", user_id=trader)[0]) == after_first
assert len(db.select("account_flow", order_no=order_no, type=4)) == 1
assert cache.get(
"order_freeze:userId:%s:orderNo:%s" % (trader, order_no)) is None
def test_cancel_filled_order_rejected(self, base_url, trader, db):
"""市价单立即全部成交(状态 22),对其撤单应返回 2003 且无副作用。"""
body = order_api.add_order(base_url, **{
"userId": trader, "contractId": 1, "side": "bid", "positionEffect": 1,
"orderType": 2, "quantity": 10, "timeInForce": "GTC",
"marginType": 2, "marginRate": "0.1", "orderSourceType": 1,
})
assert body["code"] == 0
order_no = body["data"]["orderNo"]
before = dict(db.select("futures_account", user_id=trader)[0])
cancel = order_api.cancel_order(base_url, trader, 1, order_no)
assert cancel["code"] == 2003
assert cancel["msg"] == "订单状态不允许撤单"
# 无副作用:资金不变、无解冻流水
assert dict(db.select("futures_account", user_id=trader)[0]) == before
assert db.select("account_flow", order_no=order_no, type=4) == []
def test_cancel_nonexistent_order(self, base_url, trader, db):
"""撤不存在的订单号:返回 2002,账户与流水无任何变动。"""
before = dict(db.select("futures_account", user_id=trader)[0])
cancel = order_api.cancel_order(base_url, trader, 1, "NOT-EXIST-ORDER")
assert cancel["code"] == 2002
assert cancel["msg"] == "订单不存在"
assert dict(db.select("futures_account", user_id=trader)[0]) == before
assert db.count("account_flow") == 1 # 仅初始划入的一条流水
def test_cancel_without_order_no_is_param_error(self, base_url, trader, db):
"""缺 orderNo:返回参数错误 1003。"""
before = dict(db.select("futures_account", user_id=trader)[0])
cancel = order_api.cancel_order(base_url, trader, 1, None)
assert cancel["code"] == 1003
assert cancel["msg"] == "参数错误:orderNo"
assert dict(db.select("futures_account", user_id=trader)[0]) == before
def test_reorder_with_unfrozen_funds(self, base_url, trader, db):
"""撤单解冻后,同样的资金可再次下单成功(验证解冻确实回补了可用额度)。"""
contract = settings.CONTRACTS[1]
order_param = {
"userId": trader, "contractId": 1, "side": "bid", "positionEffect": 1,
"price": 100, "quantity": 10, "orderType": 1, "timeInForce": "GTC",
"marginType": 1, "marginRate": "0.01", "orderSourceType": 1,
}
expect_frozen = formula.frozen_margin(
100, 10, "0.01", contract["maker_fee_rate"], contract["taker_fee_rate"])
# 第一次下单 → 撤单
first = order_api.add_order(base_url, **order_param)
assert first["code"] == 0
first_no = first["data"]["orderNo"]
assert order_api.cancel_order(base_url, trader, 1, first_no)["code"] == 0
# 用解冻回来的资金再次下单同额委托
second = order_api.add_order(base_url, **order_param)
assert second["code"] == 0
second_no = second["data"]["orderNo"]
assert second_no != first_no
# 新订单的冻结金额与公式期望一致,撤掉的旧单不再占用资金
account = db.select("futures_account", user_id=trader)[0]
assert_decimal_equal(account["cross_frozen_margin"], expect_frozen)
assert db.select("order", order_no=first_no)[0]["status"] == 3 # 3-已撤销
assert db.select("order", order_no=second_no)[0]["status"] == 2 # 2-待撮合
+76
View File
@@ -0,0 +1,76 @@
"""合约公式层纯函数单测:数据驱动 + Decimal 精度演示。
公式层是全部业务断言的"期望值来源",本身必须先被验证:
- 期望值手算写死在 data/formula.yml,防公式实现自证;
- 金额全部 Decimal,顺带用 float 反例说明为什么禁止 float。
"""
import pytest
from framework.decimal_assert import assert_decimal_equal
from framework.read_yaml import read_yaml
from formula.contract_formula import side_to_direction, 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")
def test_side_to_direction_rejects_invalid_input(self):
"""非法方向必须抛 ValueError,不允许静默归一到多空任一侧。"""
for bad in ("invalid", 3, None, ""):
with pytest.raises(ValueError, match="非法的持仓方向"):
side_to_direction(bad)
+115
View File
@@ -0,0 +1,115 @@
"""场景三:强平触发校验 —— 行情驱动到强平价,核对爆仓判定与风险基金流水。
方法论:强平价/破产价由公式层**独立**计算,用例据此选择标记价格:
- 安全价(未越界)→ 风控检查不触发,仓位保持持仓;
- 触发价(恰好等于或越过强平价)→ 触发强平,核对:
- position 状态置为已强平;
- liquidation_record 落库,破产价与公式一致;
- risk_fund_ledger 落库,金额 == 触发时保证金余额(穿仓为负,由风险基金兜底);
- futures_account 释放仓位保证金,穿仓时可用余额扣减缺口;
- 缓存仓位键删除。
场景数据由 data/liquidation.yml 驱动。
"""
import json
from decimal import Decimal
import pytest
from framework.order_api import OrderApi
from framework.decimal_assert import assert_decimal_equal
from framework.read_yaml import read_yaml
from framework 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, "timeInForce": "GTC",
"marginType": 2, "marginRate": margin_rate, "orderSourceType": 1,
})
assert body["code"] == 0
account_after_open = dict(db.select("futures_account", 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("liquidation_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("liquidation_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_ledger", user_id=trader)
assert len(risk_flows) == 1
assert_decimal_equal(risk_flows[0]["quantity"], trigger_balance)
assert_decimal_equal(
db.select("account_flow", user_id=trader, type=9)[0]["quantity"],
trigger_balance)
# 资金:释放仓位保证金;穿仓时可用余额扣减缺口(负余额)
init = formula.init_margin(OPEN_PRICE, quantity, margin_rate)
account = db.select("futures_account", user_id=trader)[0]
assert_decimal_equal(account["isolated_margin"],
account_after_open["isolated_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("futures_account:userId:%s:currencyId:1" % trader))
assert_decimal_equal(cached_account["totalMoney"], account["total_money"])
# 响应中的破产价同样与公式一致
assert_decimal_equal(liquidated[0]["bankruptPrice"], bankrupt_price)
+112
View File
@@ -0,0 +1,112 @@
"""场景一:下单冻结保证金 —— 三重校验方法论的核心演示。
校验链路(与真实工程对 MySQL + Redis 的双重落库校验同构):
1. HTTP 响应:code / msg / orderNo;
2. 落库校验(MockMySQL):
- order 表:委托字段与入参一致、状态待撮合;
- futures_account 表:total_money 扣减冻结额、对应冻结保证金字段增加;
- account_flow 表:新增"冻结"流水,金额与公式期望一致;
3. 缓存校验(MockRedis):
- order_freeze:userId:*:orderNo:* 键值与公式期望一致;
- futures_account 缓存镜像与落库一致(字段命名 camelCase,需归一化比对)。
期望值全部由 formula 包独立计算(被测引擎不复用该包),数据由
data/addOrder.yml 驱动参数化。
"""
import json
import pytest
from framework.order_api import OrderApi
from framework.decimal_assert import assert_decimal_equal
from framework.http_client import Adapter
from framework.read_yaml import read_yaml
from framework 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_margin"
return "isolated_frozen_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("futures_account", user_id=trader)[0])
# ---- 一重校验:HTTP 响应 ----
resp = adapter.post(base_url + "/api/v1/orders", 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("futures_account", 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("account_flow", order_no=order_no, type=3)
assert len(flows) == 1
assert_decimal_equal(flows[0]["quantity"], expect_frozen)
# ---- 三重校验:缓存与落库一致 ----
frozen_key = "order_freeze: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 = "futures_account: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["crossFrozenMargin"],
after["cross_frozen_margin"])
assert_decimal_equal(
cached_account["isolatedFrozenMargin"],
after["isolated_frozen_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("futures_account", user_id=trader)[0])
resp = adapter.post(base_url + "/api/v1/orders", 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("account_flow") == 1 # 仅初始划入的一条流水
assert dict(db.select("futures_account", user_id=trader)[0]) == before
assert cache.keys("order_freeze:*") == []
+118
View File
@@ -0,0 +1,118 @@
"""场景二:市价开仓成交 —— 仓位与资金变动的 Decimal 断言。
市价单按标记价格立即成交,校验:
- order 表:状态全部成交、成交量;
- position 表:方向/数量/开仓均价;
- futures_account 表:仓位保证金占用、手续费扣减(期望值由公式层独立计算);
- account_flow 表:手续费(5)与开仓(7)两条流水;
- 缓存:仓位键与资金镜像;
- 行情联动:标记价格变化后,风控接口返回的保证金余额与公式一致。
"""
import json
from decimal import Decimal
from framework.order_api import OrderApi
from framework.decimal_assert import assert_decimal_equal
from framework 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, "timeInForce": "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("futures_account", 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("futures_account", user_id=trader)[0]
assert_decimal_equal(account["isolated_margin"],
before["isolated_margin"] + expect_init)
assert_decimal_equal(account["total_money"],
before["total_money"] - expect_init - expect_fee)
# 流水:手续费(5)与开仓(7)
assert_decimal_equal(
db.select("account_flow", order_no=order_no, type=5)[0]["quantity"],
expect_fee)
assert_decimal_equal(
db.select("account_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("futures_account: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 # 未越过强平价,不应强平
+58
View File
@@ -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 framework 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
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+525
View File
@@ -0,0 +1,525 @@
# 下单接口用例数据(数据驱动)
# 结构:[参数 dict, 期望 dict],与 @pytest.mark.parametrize("test_input,expected", ...) 按位解包
# 正例:限价开仓冻结保证金;负例:各类非法入参 + 余额不足
creatOrderTrueTestdata:
# 全仓-限价-买入开仓
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: GTC
marginType: 1
marginRate: '0.005'
orderSourceType: 1
- code: 0
msg: OK
# ---- 矩阵扩充:全仓/逐仓 × 多空 × 起始保证金率三档(0.005/0.02/0.05) ----
# 全仓-卖出-0.005(20 倍杠杆)
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.005'
orderSourceType: 1
- code: 0
msg: OK
# 全仓-买入-0.02(50 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.02'
orderSourceType: 1
- code: 0
msg: OK
# 全仓-卖出-0.02
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.02'
orderSourceType: 1
- code: 0
msg: OK
# 全仓-买入-0.05(20 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.05'
orderSourceType: 1
- code: 0
msg: OK
# 全仓-卖出-0.05
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.05'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-买入-0.005(20 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.005'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-卖出-0.005
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.005'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-买入-0.02(50 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.02'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-卖出-0.02
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.02'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-买入-0.05(20 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.05'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-卖出-0.05
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.05'
orderSourceType: 1
- code: 0
msg: OK
creatOrderFalseTestdata:
# userId 非数值
- - userId: ''
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: 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
timeInForce: SDFSDF
marginType: 1
marginRate: '0.01'
orderSourceType: 1
- code: 1003
msg: "参数错误:timeInForce"
# 余额不足(冻结金额超过账户资金)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 99999999
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
- code: 2001
msg: 余额不足
# 余额不足(市价单路径:起始保证金 + taker 手续费超过账户资金)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
quantity: 2000000
orderType: 2
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
- code: 2001
msg: 余额不足
# ---- 负例扩充 ----
# 数量为负数
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: -10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
- code: 1003
msg: "参数错误:quantity"
# 保证金率为 0
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0'
orderSourceType: 1
- code: 1003
msg: "参数错误:marginRate"
# 保证金率非法字符串
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: abc
orderSourceType: 1
- code: 1003
msg: "参数错误:marginRate"
# 平仓方向(positionEffect != 1)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 2
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
- code: 1003
msg: "参数错误:positionEffect"
# 缺 price 参数(限价单必传)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
- code: 1003
msg: "参数错误:price"
# 余额不足边界:冻结额(本金+孰高手续费)恰好略超账户总资金
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100001
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '1'
orderSourceType: 1
- code: 2001
msg: 余额不足
+31
View File
@@ -0,0 +1,31 @@
# 撤单解冻场景用例数据(数据驱动)
# 每行一个场景:限价开仓挂单 → 撤单 → 三重校验(响应 / 落库 / 缓存)。
# 期望冻结金额由公式层独立计算(formula.frozen_margin),不抄被测系统返回值。
cancelScenarios:
# 全仓-限价-买入开仓后撤单(冻结走全仓冻结字段)
- name: 全仓限价买入撤单解冻
order:
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
# 逐仓-限价-卖出开仓后撤单(冻结走逐仓冻结字段)
- name: 逐仓限价卖出撤单解冻
order:
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.02'
orderSourceType: 1
+56
View File
@@ -0,0 +1,56 @@
# 合约公式层纯函数用例数据(数据驱动)
# 期望值均为 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'}
# 高杠杆:1000*50*0.02=1000,手续费孰高 1000*50*0.0005=25
- {price: 1000, quantity: 50, margin_rate: '0.02', expected: '1025'}
# 整仓(margin_rate=1):125*8*1 + 125*8*0.0005 = 1000 + 0.5
- {price: 125, quantity: 8, margin_rate: '1', expected: '1000.5'}
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'}
# 标记价不变:盈亏为 0
- {side: bid, open_price: 100, mark_price: 100, quantity: 10, expected: '0'}
# 小数价格:3.5*(100.25-95.5)=16.625
- {side: bid, open_price: '95.5', mark_price: '100.25', quantity: '3.5', expected: '16.625'}
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'}
# 做空追加保证金:100*1.1 + 20/10 = 112
- {side: ask, open_price: 100, quantity: 10, margin_rate: '0.1', extra_margin: '20', expected: '112'}
# 高杠杆做多 20 倍:100*(1-0.05) = 95
- {side: bid, open_price: 100, quantity: 10, margin_rate: '0.05', extra_margin: '0', expected: '95'}
# 高杠杆做空 50 倍:100*(1+0.02) = 102
- {side: ask, open_price: 100, quantity: 10, margin_rate: '0.02', extra_margin: '0', expected: '102'}
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'}
# 做空追加保证金:需亏 115,价格上涨 11.5 → 100 + 11.5 = 111.5
- {side: ask, open_price: 100, quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '20', expected: '111.5'}
# 高杠杆做多 20 倍:100 + (5-0-50)/10 = 95.5
- {side: bid, open_price: 100, quantity: 10, margin_rate: '0.05', maintain_rate: '0.005', extra_margin: '0', expected: '95.5'}
# 高杠杆做空 50 倍:需亏 15,价格上涨 1.5 → 100 + 1.5 = 101.5
- {side: ask, open_price: 100, quantity: 10, margin_rate: '0.02', maintain_rate: '0.005', extra_margin: '0', expected: '101.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}
# 穿仓:标记价跌破破产价,余额为负仍判定触发
- {side: bid, open_price: 100, mark_price: '85', quantity: 10, margin_rate: '0.1', maintain_rate: '0.005', extra_margin: '0', expected: true}
# 高杠杆做空 50 倍:余额 20+(100-103.5)*10=-15 <= 维持保证金 5,触发(103.5 已越过强平价 101.5)
- {side: ask, open_price: 100, mark_price: '103.5', quantity: 10, margin_rate: '0.02', maintain_rate: '0.005', extra_margin: '0', expected: true}
+47
View File
@@ -0,0 +1,47 @@
# 强平场景用例数据(数据驱动)
# 每行一个场景:市价开仓(开仓时标记价 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'
# 逐仓 20 倍杠杆做多:强平价 95.5,破产价 95
- name: 高杠杆20x做多-触及强平价触发
side: bid
quantity: 10
marginRate: '0.05'
safeMark: '96'
triggerMark: '95.5'
# 逐仓 50 倍杠杆做空:强平价 101.5,破产价 102
- name: 高杠杆50x做空-触及强平价触发
side: ask
quantity: 10
marginRate: '0.02'
safeMark: '101'
triggerMark: '101.5'
# 做空且标记价涨破破产价 110:穿仓,缺口由风险基金兜底
- name: 做空-穿仓由风险基金兜底
side: ask
quantity: 10
marginRate: '0.1'
safeMark: '109'
triggerMark: '115'
Binary file not shown.
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.
Binary file not shown.
View File
+123
View File
@@ -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
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
View File
+23
View File
@@ -0,0 +1,23 @@
"""资金类字段断言工具:全部走 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)
)
+27
View File
@@ -0,0 +1,27 @@
"""HTTP 客户端封装:统一请求头、统一入口,供框架层的接口封装复用。"""
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)
+45
View File
@@ -0,0 +1,45 @@
"""接口封装:对被测撮合系统 HTTP 接口的二次封装。
用例/场景代码只面对这一层,不直接拼 URL —— 换被测环境时只改配置。
"""
from framework.http_client import Adapter
class OrderApi:
ADD_ORDER = "/api/v1/orders"
CANCEL_ORDER = "/api/v1/orders/cancel"
SET_MARK_PRICE = "/api/v1/market/mark-price"
RISK_CHECK = "/api/v1/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 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()
+18
View File
@@ -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())
+31
View File
@@ -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"
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
View File
+415
View File
@@ -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
+29
View File
@@ -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()
+25
View File
@@ -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))
+56
View File
@@ -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)
+3
View File
@@ -0,0 +1,3 @@
[pytest]
testpaths = case
addopts = -ra --strict-markers
+4
View File
@@ -0,0 +1,4 @@
pytest>=7.0
pytest-cov>=4.0
requests>=2.25
PyYAML>=5.4