feat: 高频交易系统的随机测试实验台(可控标记价格构造确定性爆仓边界)
This commit is contained in:
+24
@@ -0,0 +1,24 @@
|
||||
# 字节码 / 缓存
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
|
||||
# 本地 demo 运行产物(diskcache 目录、sqlite、pid、日志)
|
||||
.diskcache/
|
||||
*.db
|
||||
*.sqlite3
|
||||
.pids/
|
||||
logs/
|
||||
run/
|
||||
|
||||
# pytest 临时目录(某些环境下 tmpdir 会落在仓根)
|
||||
.pytest_tmp/
|
||||
|
||||
# 虚拟环境
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# IDE(JetBrains 的 workspace.xml 会记本机绝对路径)
|
||||
.idea/
|
||||
.vscode/
|
||||
@@ -0,0 +1,204 @@
|
||||
# trade-fuzz-demo
|
||||
|
||||
> 模拟高频用户交易行为、把被测系统推到**确定性爆仓边界**的单机随机测试实验台。
|
||||
|
||||
两个解耦的任务、一个每秒执行窗口、一个可编程改价的被测端 —— 全部跑在 `127.0.0.1`,不连任何外部服务。
|
||||
|
||||
---
|
||||
|
||||
## 这是什么
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **任务形态** | 两个**解耦**任务靠本地文件缓存交换数据:一个常驻(订阅行情 → 落缓存),一个每秒触发(读缓存 → 构造请求 → 打 HTTP)。原设计跑在 **XXL-JOB** 上,对应它的 BEAN 模式与固定频率模式 |
|
||||
| **常驻任务** | ZMQ SUB 订阅行情 → 写入本地 `diskcache`(带 TTL 与定期 `expire()`) |
|
||||
| **每秒任务** | 加权随机决定这一秒的流量形态 → 并发构造并发送请求,需在 **1 秒窗口**内完成 |
|
||||
| **被测端** | 自带最小 mock 交易所(HTTP):**可编程改价** + 条件单触发判定 + 逐仓爆仓判定 |
|
||||
| **行情源** | 就是那个 mock 交易所自己(ZMQ PUB)——**价格只有一个来源**,改价同时推动行情与判定 |
|
||||
|
||||
**这不是一套生产系统,而是一个单机实验台。** 配置、接口路径与数据全部是自造示例,跑出来的也只是单机量级;它要复现的是下面三条判断,不是复刻任何真实系统。
|
||||
|
||||
---
|
||||
|
||||
## 30 秒跑起来
|
||||
|
||||
```bash
|
||||
python3 -m venv .venv && source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
python3 -m pytest tests/ -q # 12 个用例
|
||||
python3 verify.py # 三个对照实验(判断 ③)
|
||||
bash run_local.sh # 端到端:mock + 常驻缓存 + 每秒请求器
|
||||
```
|
||||
|
||||
Python 3.9+(开发与验证在 3.13 上完成);`pyzmq` 22.3 到 27.x 均可。
|
||||
|
||||
---
|
||||
|
||||
## 跑出来是什么样
|
||||
|
||||
```
|
||||
$ python3 -m pytest tests/ -q
|
||||
12 passed in 2.10s
|
||||
```
|
||||
|
||||
**对照实验 —— 同一段代码、同一个采样器,唯一变量是「触发价锚在哪」:**
|
||||
|
||||
```
|
||||
$ python3 verify.py
|
||||
stale(触发价锚定在一个冻结参考价上)
|
||||
运行期实价 ~10.50,触发价聚在 9.00 附近
|
||||
条件单:created=100 triggered=0 触发率=0.00%
|
||||
RESULT stale_price trigger_rate=0.0000
|
||||
|
||||
live(触发价锚定在实时价上)
|
||||
实时价 ~10.50,触发价散布在 ±1%
|
||||
无控随机走之后:created=100 triggered=74 触发率=74.00%
|
||||
受控 +3% 改价后:触发率=100.00%
|
||||
RESULT live_price walk_rate=0.7400 controlled_rate=1.0000
|
||||
```
|
||||
|
||||
价格锚在冻结参考价上时**一条都不触发**(流量看着很忙,其实什么都没测到);锚在实时价上时随机走就能触发 74%,一次受控改价直接推到 100%。
|
||||
|
||||
**边界构造 —— 把「多空同时爆仓」这个 P0 稳定复现出来:**
|
||||
|
||||
```
|
||||
boundary(把价格往上操纵,穿过强平价位带)
|
||||
entry=10.5 marginRate=0.02 -> 多单强平价=10.29,空单强平价=10.71
|
||||
正确规则平掉的仓位:{'long': 0, 'short': 1} (理应只平空单)
|
||||
bug 规则平掉的仓位:{'long': 1, 'short': 1} (两边都被平了)
|
||||
bug 规则首次同时命中两边的价格:10.71
|
||||
RESULT boundary buggy_both_sides=True correct_both_sides=False price=10.71
|
||||
```
|
||||
|
||||
**端到端 —— 请求计数在 mock 侧对得上账,缓存价格与 mock 价格一致(到行情帧的 6 位小数):**
|
||||
|
||||
```
|
||||
$ bash run_local.sh
|
||||
[1/4] 启动本机回环 mock 交易所(被测系统 + 行情源)
|
||||
mock 就绪
|
||||
[2/4] 启动常驻标记价格服务(XXL-JOB BEAN 模式)
|
||||
[3/4] 触发请求压测(XXL-JOB 固定频率模式,每秒一轮)
|
||||
第 1 轮:构造=8 发送=8 耗时=0.130s
|
||||
第 2 轮:构造=8 发送=8 耗时=0.005s
|
||||
...
|
||||
burst[live] 轮数=5 构造=39 发送=39 总耗时=5.02s
|
||||
[4/4] 跑完后对账:
|
||||
缓存里的标记价格:{4: 40037.999671, 5: 10.521288, 6: 2501.611143}(存活条目 4)
|
||||
mock 侧统计:
|
||||
{
|
||||
"prices": {"4": 40037.99967104623, "5": 10.5212882891303, "6": 2501.6111434132413},
|
||||
"requests": 39,
|
||||
"condition": {"created": 1, "triggered": 1, "rate": 1.0},
|
||||
...
|
||||
}
|
||||
run_local.sh 全流程正常结束
|
||||
```
|
||||
|
||||
> 行情每次快照带小幅随机游走,所以价格与条件单计数每次跑都不同;每次稳定成立的只有
|
||||
> 「构造数 = 发送数 = mock 侧请求数」和「缓存价格 = mock 价格(到 6 位小数)」这两条。
|
||||
> 缓存侧多出的那个存活条目是 `@action` 写下的 `order_info`。
|
||||
|
||||
---
|
||||
|
||||
## 它要复现的三条判断
|
||||
|
||||
这份实验台真正要交付的是下面三条判断 —— 代码只是让它们可复现的手段:
|
||||
|
||||
| # | 判断 | 在这个仓里的落点 |
|
||||
|---|---|---|
|
||||
| **①** | **每秒执行窗口是硬约束**:把单次执行从 10s+ 压到 0.8s 的关键不是「把代码写快」,而是**消掉每秒重复付的固定成本**(建连 / 建进程 / 重复查库) | `requester.py` —— 数据源、缓存句柄、HTTP 会话一次建好并跨周期复用;`asyncio` 并发发送;`multiprocessing` 并行构造。冷启动 vs 热运行的分解见 `report.md` |
|
||||
| **②** | **常驻任务的失败是慢性的,不是崩溃的**:内存 50M→2G、连接泄漏都是跑几天才炸,监控上看不出来。能防住它们的是 TTL / 显式释放这类防腐设计 | `mark_price_service.py`(TTL + `expire()` + `finally` 关 socket)+ `tests/test_all.py` 的 `TestCacheTtl` |
|
||||
| **③** | **随机测试的杀伤力不在「随机」,在「能构造确定性边界」**:加权随机只决定流量**形态**;真正把系统逼到爆仓边界的是**可控标记价格** | `mock_exchange.py`(可编程改价)+ `verify.py`(三个对照实验) |
|
||||
|
||||
> 第 ③ 条最容易被做成一跑就完、看不出结论的样子 —— 所以它配的是**对照实验**(同一段代码只差一个变量),而不是一段演示。
|
||||
|
||||
---
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
[mock 交易所 · 行情源 ZMQ PUB] ← 价格只有一个来源,就是它
|
||||
↓ 行情
|
||||
(常驻) 标记价格缓存 ──→ [diskcache 本地文件]
|
||||
↓
|
||||
(每秒) 用户请求模拟 ──HTTP──→ [mock 交易所 · 被测端]
|
||||
```
|
||||
|
||||
两个任务之间**只通过本地文件系统通信**:
|
||||
|
||||
- **解耦**:两个任务独立部署、独立启停
|
||||
- **免跨进程通信**:文件系统共享数据,不用引入消息队列
|
||||
- **故障隔离**:缓存任务挂了,请求任务仍能用上一次的有效价格继续压测,不中断
|
||||
|
||||
调度平台本身无法随 demo 交付,`run_local.sh` 用一个脚本模拟它的两种模式(常驻后台进程 + 每秒循环)。
|
||||
|
||||
---
|
||||
|
||||
## 与原始实现的差异
|
||||
|
||||
本仓按**修好的版本**实现,与原始实现有三处差异 —— 代码注释与测试里用 `D1` / `D2` / `D3` 指代它们。
|
||||
|
||||
| # | 原始实现的问题 | 本仓的处置 |
|
||||
|---|---|---|
|
||||
| **D1** | **滑动窗口是全局的,不是按币对的**:一个模块级 `price_list` 被多个 `contractId` 交错写入,去重逻辑被其它币对污染而失效 | 窗口改为**按币对隔离**(`MarkPriceSubscriber._windows[cid]`);`TestSlidingWindow` 用交错序列断言两者互不污染 |
|
||||
| **D2** | **异常分支不关 socket**:负责关 socket 的 `else` 分支因 `while True` 永不退出而不可达,网络波动重连时旧 socket 会泄漏 | 改用 **`try/finally` 显式 close**(`MarkPriceSubscriber.run`),所有退出路径都释放。**这一处在原始实现的文档里被记为「已修复」,但代码并没有改 —— 本仓是真正改掉的那一版。** |
|
||||
| **D3** | **`eval` 动态调用**:`eval("api.{}()".format(v))`;装饰器里还拼过 `eval('func(args[0],...)')` | 全部改为 **`getattr`**(`requester._build` 分发、`action` 装饰器直接转发 `*args`),行为等价且更安全 |
|
||||
|
||||
---
|
||||
|
||||
## 数字口径
|
||||
|
||||
下面两组数字来自**完全不同的环境**,量级不可比 —— 放在一起看会得出错误结论。
|
||||
|
||||
**【生产真实业绩】**(公司环境,XXL-JOB 集群)
|
||||
|
||||
- 单次执行 **10s+ → 0.8s**,压进 1 秒执行窗口内完成
|
||||
- 常驻价格缓存任务内存 **50M → 2G**(加 TTL 与定期清理后回落)
|
||||
- **100 用户**批量初始化 **15min → 3min**
|
||||
- 1 秒 1 次连跑 1 小时 → 发现 **多空同时爆仓 P0**、**多线程并发保证金不足**
|
||||
|
||||
**【本机演示实测】**(2026-09-22,单机 macOS,Python 3.13,仅打 `127.0.0.1` mock)
|
||||
|
||||
- 12 个用例全绿(2.1s)
|
||||
- 每秒任务**热周期中位数 1.9ms**(构造 1.1ms + 发送 0.7ms,进程内夹具测法,每轮 8 个操作);**首周期 74ms** —— 判断① 说的「每秒重复付的固定成本」就是它,冷/热差约 **39x**
|
||||
- 对照实验触发率:冻结参考价 **0.00%** / 实时价随机走 **74.00%** / 受控改价 **100.00%**
|
||||
- 边界构造:错误规则在 **10.71** 同时打穿多空两侧,正确规则只平空单
|
||||
- 端到端:39 次构造 = 39 次发送 = mock 侧 39 次请求;缓存里的价格与 mock 侧的价格一致(到行情帧的 6 位小数)
|
||||
|
||||
> 本机那栏是单机小规模的真实值,**不能拿来代表生产量级**。真正可比的是「同一脚本冷启动 vs 热运行」的**倍数差**。逐条归因见 `report.md`。
|
||||
|
||||
---
|
||||
|
||||
## 已知未解问题
|
||||
|
||||
**多进程 / 多实例并行时,同一用户可能被重复操作。** 目前**没有落地实现**,只有三个备选方向:
|
||||
|
||||
1. 在缓存里用带过期时间的集合记录「本周期内已操作的用户」;
|
||||
2. 数据源加「上次测试时间」字段,只挑超时的用户;
|
||||
3. 评估是否真需要避免 —— 高频下同一用户短时间多次交易,可能正是要测的场景。
|
||||
|
||||
---
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
config.py # 全部可调项:端口、币对、权重、TTL(默认全 127.0.0.1)
|
||||
mark_price_service.py # 常驻任务:diskcache 封装(TTL + expire())+ ZMQ SUB 订阅
|
||||
# 落点:判断②、D1、D2
|
||||
requester.py # 每秒任务:SQLite 数据源 + 8 个业务操作 + 加权随机 + asyncio 并发
|
||||
# 落点:判断①、D3
|
||||
mock_exchange.py # 被测系统 + 行情源:可编程改价 + 触发/爆仓双规则模型 + ZMQ PUB
|
||||
# 落点:判断③
|
||||
verify.py # 三个对照实验(判断③ 的验证)
|
||||
tests/test_all.py # 12 个用例:TTL(判断②) / 滑动窗口(D1) / 动作缓存(D3) / 加权随机
|
||||
run_local.sh # 一键起 mock + 常驻服务 + 每秒请求器
|
||||
report.md # 两栏数字口径 + 逐条归因
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 边界
|
||||
|
||||
- 本实验台**只打本机回环 mock**(`127.0.0.1`),不连任何真实系统。对真实系统发压既违法也不道德。
|
||||
- 所有配置、接口路径与数据都是**自造示例**,与任何真实业务系统无关。
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""全部可调项。默认值一律指向本机回环,不含任何真实地址、账号或凭据。
|
||||
|
||||
这是全仓唯一的配置入口:改端口、改币对、改流量权重都只动这个文件。
|
||||
"""
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 模拟用户与币对
|
||||
# --------------------------------------------------------------------------
|
||||
USER_IDS = [str(i) for i in range(1, 51)]
|
||||
# 其中一部分走全仓保证金,其余走逐仓——只影响数据源里种子的 margin_type。
|
||||
CROSS_MARGIN_USERS = set(USER_IDS[:10])
|
||||
|
||||
CONTRACT_IDS = [4, 5, 6] # demo 轮换的币对
|
||||
DEFAULT_CONTRACT_ID = 5
|
||||
SEED_PRICES = {4: 40000.0, 5: 10.5, 6: 2500.0} # 自造示例价,不是真实行情
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 本机服务(仅回环)
|
||||
# --------------------------------------------------------------------------
|
||||
LOCALHOST = "127.0.0.1"
|
||||
|
||||
ZMQ_PUB_ADDR = f"tcp://{LOCALHOST}:5560" # 行情:发布方 bind,订阅方 connect
|
||||
MARK_PRICE_TOPIC = "mark_price"
|
||||
MARK_PRICE_DRIFT = 0.0005 # 每次快照的随机游走幅度
|
||||
|
||||
MOCK_HOST, MOCK_PORT = LOCALHOST, 18080
|
||||
MOCK_BASE_URL = f"http://{MOCK_HOST}:{MOCK_PORT}"
|
||||
|
||||
CACHE_PATH = ".diskcache" # 两个任务交换数据的本地文件缓存(已 gitignore)
|
||||
PRICE_TTL_SECONDS = 3600 # 价格键的 TTL(原实现约留 1 小时)
|
||||
SLIDING_WINDOW_LEN = 2 # 订阅端按币对去重的窗口深度
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# 业务操作 + 权重
|
||||
# --------------------------------------------------------------------------
|
||||
# 名称 -> (HTTP 方法, 接口路径)。路径是 mock 自定义的 /api/v1/... 风格,与任何真实系统无关。
|
||||
PREFIX = "/api/v1"
|
||||
OPERATIONS = {
|
||||
"open_order": ("POST", f"{PREFIX}/order/limit/open"),
|
||||
"market_open_order": ("POST", f"{PREFIX}/order/market/open"),
|
||||
"close_order": ("POST", f"{PREFIX}/order/limit/close"),
|
||||
"cancel_order": ("DELETE", f"{PREFIX}/order/cancel"),
|
||||
"condition_order": ("POST", f"{PREFIX}/condition/plan"),
|
||||
"condition_position": ("POST", f"{PREFIX}/condition/stop"),
|
||||
"reverse_position": ("POST", f"{PREFIX}/order/reverse"),
|
||||
"transfer": ("POST", f"{PREFIX}/account/margin/transfer"),
|
||||
}
|
||||
|
||||
# (操作, 权重)。权重沿用原始流量分布,保留的 8 个操作原样照搬;被砍掉的是 11 个长尾操作
|
||||
# (原权重合计 46/526 ≈ 8.7%),去掉它们不改变"开仓占大头"这个形态结论。
|
||||
# transfer 权重为 0:它是个哨兵,用来断言「零权重操作永不被采样」。
|
||||
WEIGHTED_OPS = [
|
||||
("open_order", 200),
|
||||
("market_open_order", 100), # 原 market_quantity_open_order(50) + market_amount_open_order(50)
|
||||
("close_order", 100),
|
||||
("cancel_order", 10),
|
||||
("condition_order", 50),
|
||||
("condition_position", 10),
|
||||
("reverse_position", 10),
|
||||
("transfer", 0),
|
||||
]
|
||||
|
||||
PRICE_FLOAT = 0.5 # 构造限价单时围绕标记价波动的价格窗口
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""常驻任务:订阅标记价格行情,落进本地文件缓存(原始实现里的 XXL-JOB BEAN 模式)。
|
||||
|
||||
这是**判断②** 的落点。这个任务的失败不表现为崩溃,而是**慢性**的:原实现跑了一周,
|
||||
内存从 50M 漂到 2G,因为 diskcache 从不自动淘汰、也没有任何东西去调 ``expire()``。
|
||||
本模块的两处防腐设计:
|
||||
|
||||
* 每个价格键带 TTL,并显式暴露 ``PriceCache.expire()`` 供调用方定期清理;
|
||||
* ZMQ socket 在 ``finally`` 里无条件释放(D2)。
|
||||
|
||||
它同时修掉了原实现的一处正确性缺陷(D1,见 ``MarkPriceSubscriber``)。
|
||||
|
||||
单独运行: python -m mark_price_service --duration 10 --verbose
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
import zmq
|
||||
from diskcache import Cache
|
||||
|
||||
import config
|
||||
|
||||
|
||||
def price_key(contract_id) -> str:
|
||||
return f"mark_price:{contract_id}"
|
||||
|
||||
|
||||
class PriceCache:
|
||||
"""diskcache 封装——两个任务唯一的交汇点。
|
||||
|
||||
持**单个**句柄:原实现每次 get/set 都新建一次 ``Cache()``,实测占构造耗时的 60%。
|
||||
这正是判断① 说的「每秒重复付的固定成本」里的一块,顺手在这里消掉。
|
||||
"""
|
||||
|
||||
def __init__(self, path=None, ttl=None):
|
||||
self.path = str(path or config.CACHE_PATH)
|
||||
self.ttl = config.PRICE_TTL_SECONDS if ttl is None else ttl
|
||||
self._cache = Cache(self.path)
|
||||
|
||||
def close(self):
|
||||
self._cache.close()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.close()
|
||||
|
||||
# -- 通用接口 --------------------------------------------------------------
|
||||
def set(self, key, value, ttl=None):
|
||||
self._cache.set(key, value, expire=self.ttl if ttl is None else ttl)
|
||||
|
||||
def get(self, key, default=None):
|
||||
return self._cache.get(key, default)
|
||||
|
||||
def expire(self) -> int:
|
||||
"""清掉已过 TTL 的条目,返回被删除的数量。"""
|
||||
return self._cache.expire()
|
||||
|
||||
def size(self) -> int:
|
||||
return len(self._cache)
|
||||
|
||||
# -- 价格专用接口 ----------------------------------------------------------
|
||||
def set_price(self, contract_id, price, ttl=None):
|
||||
self.set(price_key(contract_id), price, ttl=ttl)
|
||||
|
||||
def get_price(self, contract_id):
|
||||
return self.get(price_key(contract_id))
|
||||
|
||||
|
||||
def parse_frame(frame: str, topic: str):
|
||||
"""把一帧 ``'<topic> <json>'`` 解析成 (contract_id, mark_price)。"""
|
||||
payload = frame[len(topic):].strip() if frame.startswith(topic) else frame
|
||||
data = json.loads(payload)
|
||||
return int(data["contractId"]), float(data["markPrice"])
|
||||
|
||||
|
||||
class MarkPriceSubscriber:
|
||||
"""ZMQ SUB -> diskcache。
|
||||
|
||||
D1:原实现用一个**模块级** ``price_list`` 给所有币对共享去重窗口。contractId 4/5/6
|
||||
交错推送时窗口被互相污染、去重逻辑失效,合法更新会被漏掉。这里窗口**按币对隔离**。
|
||||
"""
|
||||
|
||||
def __init__(self, addr=None, topic=None, cache=None, contracts=None, window_len=None):
|
||||
self.addr = addr or config.ZMQ_PUB_ADDR
|
||||
self.topic = topic or config.MARK_PRICE_TOPIC
|
||||
self.cache = cache or PriceCache()
|
||||
self.contracts = set(contracts or config.CONTRACT_IDS)
|
||||
self.window_len = window_len or config.SLIDING_WINDOW_LEN
|
||||
self._windows: dict[int, deque] = {}
|
||||
|
||||
def handle_price(self, contract_id: int, price: float) -> bool:
|
||||
"""喂入一次观测,返回是否写入了缓存。
|
||||
|
||||
去重规则(按币对):只有价格与该币对**上一次**观测不同才写入。
|
||||
"""
|
||||
window = self._windows.setdefault(contract_id, deque(maxlen=self.window_len))
|
||||
accept = (len(window) == 0) or (window[-1] != price)
|
||||
if accept:
|
||||
self.cache.set_price(contract_id, price)
|
||||
window.append(price)
|
||||
return accept
|
||||
|
||||
def run(self, duration: float | None = None, max_messages: int | None = None) -> int:
|
||||
"""持续消费直到达到时长/条数。无论怎么退出都会释放 socket。"""
|
||||
ctx = zmq.Context()
|
||||
sock = ctx.socket(zmq.SUB)
|
||||
received = 0
|
||||
try:
|
||||
sock.connect(self.addr)
|
||||
sock.setsockopt_string(zmq.SUBSCRIBE, self.topic)
|
||||
poller = zmq.Poller()
|
||||
poller.register(sock, zmq.POLLIN)
|
||||
start = time.time()
|
||||
while True:
|
||||
if duration is not None and time.time() - start >= duration:
|
||||
break
|
||||
if max_messages is not None and received >= max_messages:
|
||||
break
|
||||
if sock not in dict(poller.poll(timeout=200)):
|
||||
continue
|
||||
try:
|
||||
contract_id, price = parse_frame(sock.recv_string(), self.topic)
|
||||
except (ValueError, KeyError):
|
||||
continue
|
||||
if contract_id in self.contracts:
|
||||
self.handle_price(contract_id, price)
|
||||
received += 1
|
||||
finally:
|
||||
sock.close(linger=0) # D2:每条退出路径都显式释放,不留泄漏
|
||||
ctx.term()
|
||||
return received
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
p = argparse.ArgumentParser(description="订阅本机标记价格行情并写入本地缓存。")
|
||||
p.add_argument("--duration", type=float, default=None, help="运行秒数(默认一直跑)")
|
||||
p.add_argument("--dump", action="store_true",
|
||||
help="不订阅,只打印缓存里当前的标记价格(用来验证两个任务确实通过文件交换数据)")
|
||||
p.add_argument("--verbose", action="store_true")
|
||||
args = p.parse_args()
|
||||
|
||||
cache = PriceCache()
|
||||
if args.dump:
|
||||
prices = {cid: cache.get_price(cid) for cid in config.CONTRACT_IDS}
|
||||
print(f"缓存里的标记价格:{prices}(存活条目 {cache.size()})")
|
||||
cache.close()
|
||||
return
|
||||
|
||||
sub = MarkPriceSubscriber(cache=cache)
|
||||
if args.verbose:
|
||||
print(f"订阅器启动:{sub.addr} topic={sub.topic} "
|
||||
f"contracts={sorted(sub.contracts)}", flush=True)
|
||||
n = sub.run(duration=args.duration)
|
||||
if args.verbose:
|
||||
print(f"订阅器共处理 {n} 条标记价格消息,缓存存活条目 {cache.size()}", flush=True)
|
||||
cache.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,311 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""被测系统 + 行情源:一个只在本机回环跑的极简 HTTP 交易所(自带 ZMQ 行情发布)。
|
||||
|
||||
这是**判断③** 的落点。它故意做成内存态,并且**价格只有一个来源**(``MockState.prices``):
|
||||
HTTP 的 ``set-price`` 改的是它,ZMQ 行情发的也是它。于是「改价」这个动作既推动行情、又
|
||||
推动条件单与爆仓判定——价格可编程,边界就可构造。这就是为什么杀伤力在可控边界,不在随机。
|
||||
|
||||
它建模的三件事:
|
||||
|
||||
1. **可编程标记价格** —— ``POST /api/v1/quotation/set-price``;
|
||||
2. **条件单触发判定** —— 每次改价都对条件单求值,于是一轮运行能报出真实的触发率;
|
||||
3. **持仓爆仓的双规则对照** —— 每个仓位带一个强平价,改价时同时记录「按正确的分边规则
|
||||
*应当* 被平掉的仓」和「按历史 bug 规则 *会被* 错误平掉的仓」。这个对照正是「多空
|
||||
同时爆仓」那个 P0 能被稳定复现的原因。
|
||||
|
||||
其余接口(开/平/撤/划转)只回一个 ok 信封并计数——请求器只需要这一趟往返。
|
||||
|
||||
单独运行:
|
||||
python -m mock_exchange --port 18080 --publish # HTTP + 行情,常驻
|
||||
python -m mock_exchange --port 18080 # 只起 HTTP
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import config
|
||||
|
||||
|
||||
class MockState:
|
||||
"""内存态。除 ``reset`` 外,各方法都假定调用方已持有 ``lock``。"""
|
||||
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self._seq = 0
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
"""清空运行态,让多个对照实验共用同一个 mock 也彼此隔离。"""
|
||||
self.prices = {int(c): float(config.SEED_PRICES[c]) for c in config.CONTRACT_IDS}
|
||||
self.positions: list[dict] = []
|
||||
self.condition_orders: list[dict] = []
|
||||
self.events: list[dict] = []
|
||||
self.request_count = 0
|
||||
|
||||
def next_id(self, prefix: str) -> str:
|
||||
self._seq += 1
|
||||
return f"{prefix}-{self._seq}"
|
||||
|
||||
# -- 价格 ------------------------------------------------------------------
|
||||
def set_price(self, contract_id: int, price: float):
|
||||
self.prices[int(contract_id)] = float(price)
|
||||
self._evaluate_triggers()
|
||||
self._evaluate_liquidations(int(contract_id), float(price))
|
||||
|
||||
# -- 条件单 ----------------------------------------------------------------
|
||||
def add_condition(self, contract_id: int, trigger_price: float):
|
||||
price = self.prices.get(int(contract_id))
|
||||
order = {
|
||||
"conditionNo": self.next_id("cond"),
|
||||
"contractId": int(contract_id),
|
||||
"triggerPrice": float(trigger_price),
|
||||
"direction": "above" if trigger_price >= price else "below",
|
||||
"triggered": False,
|
||||
}
|
||||
self.condition_orders.append(order)
|
||||
return order
|
||||
|
||||
def _evaluate_triggers(self):
|
||||
for o in self.condition_orders:
|
||||
if o["triggered"]:
|
||||
continue
|
||||
price = self.prices.get(o["contractId"])
|
||||
if price is None:
|
||||
continue
|
||||
if (o["direction"] == "above" and price >= o["triggerPrice"]) or \
|
||||
(o["direction"] == "below" and price <= o["triggerPrice"]):
|
||||
o["triggered"] = True
|
||||
|
||||
# -- 持仓 / 爆仓 -----------------------------------------------------------
|
||||
def add_position(self, contract_id, side, entry, margin_rate, quantity):
|
||||
pos = {
|
||||
"positionNo": self.next_id("pos"),
|
||||
"contractId": int(contract_id),
|
||||
"side": side, # 'long' | 'short'
|
||||
"entry": float(entry),
|
||||
"marginRate": float(margin_rate),
|
||||
"quantity": float(quantity),
|
||||
"liquidatedCorrect": False,
|
||||
"liquidatedBuggy": False,
|
||||
}
|
||||
self.positions.append(pos)
|
||||
return pos
|
||||
|
||||
def _liq_prices(self, pos):
|
||||
entry, m = pos["entry"], pos["marginRate"]
|
||||
return entry * (1 - m), entry * (1 + m) # 多单强平价、空单强平价
|
||||
|
||||
def _evaluate_liquidations(self, contract_id: int, price: float):
|
||||
for pos in self.positions:
|
||||
if pos["contractId"] != contract_id:
|
||||
continue
|
||||
long_liq, short_liq = self._liq_prices(pos)
|
||||
# 正确的分边规则:多单只在跌破强平价时爆,空单只在涨过强平价时爆。
|
||||
correct = (pos["side"] == "long" and price <= long_liq) or \
|
||||
(pos["side"] == "short" and price >= short_liq)
|
||||
# 历史 bug 规则:只看波动**幅度**,忽略方向。
|
||||
buggy = abs(price - pos["entry"]) / pos["entry"] >= pos["marginRate"]
|
||||
if correct and not pos["liquidatedCorrect"]:
|
||||
pos["liquidatedCorrect"] = True
|
||||
self.events.append({
|
||||
"rule": "correct", "positionNo": pos["positionNo"],
|
||||
"side": pos["side"], "contractId": contract_id, "price": price,
|
||||
"liqPrice": long_liq if pos["side"] == "long" else short_liq,
|
||||
})
|
||||
if buggy and not pos["liquidatedBuggy"]:
|
||||
pos["liquidatedBuggy"] = True
|
||||
self.events.append({
|
||||
"rule": "buggy", "positionNo": pos["positionNo"],
|
||||
"side": pos["side"], "contractId": contract_id, "price": price,
|
||||
})
|
||||
|
||||
# -- 统计汇报 --------------------------------------------------------------
|
||||
def _by_side(self, rule):
|
||||
return {s: sum(1 for e in self.events if e["rule"] == rule and e["side"] == s)
|
||||
for s in ("long", "short")}
|
||||
|
||||
def stats(self):
|
||||
created = len(self.condition_orders)
|
||||
triggered = sum(1 for o in self.condition_orders if o["triggered"])
|
||||
return {
|
||||
"prices": self.prices,
|
||||
"requests": self.request_count,
|
||||
"positions": len(self.positions),
|
||||
"condition": {
|
||||
"created": created,
|
||||
"triggered": triggered,
|
||||
"rate": round(triggered / created, 4) if created else 0.0,
|
||||
},
|
||||
"liquidation": {
|
||||
"correct_by_side": self._by_side("correct"),
|
||||
"buggy_by_side": self._by_side("buggy"),
|
||||
"correct_both_sides": {e["side"] for e in self.events
|
||||
if e["rule"] == "correct"} == {"long", "short"},
|
||||
"buggy_both_sides": {e["side"] for e in self.events
|
||||
if e["rule"] == "buggy"} == {"long", "short"},
|
||||
"events": self.events,
|
||||
},
|
||||
}
|
||||
|
||||
def ok(self, extra=None):
|
||||
self.request_count += 1
|
||||
body = {"code": 0, "msg": "ok", "data": dict(extra or {})}
|
||||
return body
|
||||
|
||||
|
||||
STATE = MockState()
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args): # 关掉默认的 stderr 噪声
|
||||
return
|
||||
|
||||
# -- 小工具 ----------------------------------------------------------------
|
||||
def _send(self, code, obj):
|
||||
data = json.dumps(obj).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def _read_body(self):
|
||||
length = int(self.headers.get("Content-Length", 0) or 0)
|
||||
if not length:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(self.rfile.read(length).decode("utf-8") or "{}")
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
|
||||
# -- 各 HTTP 动词 ----------------------------------------------------------
|
||||
def do_GET(self):
|
||||
url = urlparse(self.path)
|
||||
if url.path == "/health":
|
||||
return self._send(200, {"status": "ok"})
|
||||
with STATE.lock:
|
||||
if url.path == "/api/v1/market/stats":
|
||||
return self._send(200, STATE.stats())
|
||||
if url.path == "/api/v1/market/price":
|
||||
cid = int(parse_qs(url.query).get("contractId", [config.DEFAULT_CONTRACT_ID])[0])
|
||||
return self._send(200, {"contractId": cid, "price": STATE.prices.get(cid)})
|
||||
return self._send(404, {"code": 404, "msg": "not found"})
|
||||
|
||||
def do_POST(self):
|
||||
path = urlparse(self.path).path
|
||||
body = self._read_body()
|
||||
with STATE.lock:
|
||||
if path == config.PREFIX + "/quotation/set-price":
|
||||
STATE.set_price(int(body["contractId"]), float(body["markPrice"]))
|
||||
return self._send(200, STATE.ok({"price": STATE.prices[int(body["contractId"])]}))
|
||||
if path in (config.PREFIX + "/condition/plan", config.PREFIX + "/condition/stop"):
|
||||
return self._send(200, STATE.ok(
|
||||
STATE.add_condition(int(body["contractId"]), float(body.get("triggerPrice", 0)))))
|
||||
if path == config.PREFIX + "/market/positions/seed":
|
||||
return self._send(200, STATE.ok(STATE.add_position(
|
||||
body["contractId"], body["side"], body["entry"],
|
||||
body["marginRate"], body.get("quantity", 1))))
|
||||
if path == config.PREFIX + "/market/reset":
|
||||
STATE.reset()
|
||||
return self._send(200, STATE.ok())
|
||||
# 其余 POST 一律当作下单/操作:接受并回显。
|
||||
return self._send(200, STATE.ok(body))
|
||||
|
||||
def do_DELETE(self):
|
||||
with STATE.lock:
|
||||
return self._send(200, STATE.ok({"cancelled": True}))
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 行情发布:把 STATE.prices 当行情发出去(ZMQ PUB)
|
||||
# ==========================================================================
|
||||
def publish_loop(stop: threading.Event, addr: str | None = None, interval: float = 0.2,
|
||||
drift: float | None = None, verbose: bool = False) -> int:
|
||||
"""持续发布标记价格快照,直到 ``stop`` 被置位;返回已发出的帧数。
|
||||
|
||||
价格与 HTTP 侧共用同一个 dict,所以改价会立刻反映到行情上、行情游走也会推动条件单与
|
||||
爆仓判定——「价格只有一个来源」。
|
||||
"""
|
||||
import zmq
|
||||
|
||||
drift = config.MARK_PRICE_DRIFT if drift is None else drift
|
||||
ctx = zmq.Context()
|
||||
sock = ctx.socket(zmq.PUB)
|
||||
sent = 0
|
||||
try:
|
||||
sock.bind(addr or config.ZMQ_PUB_ADDR)
|
||||
time.sleep(0.3) # 给 SUB 一点时间先连上并订阅,再发第一批
|
||||
while not stop.is_set():
|
||||
with STATE.lock:
|
||||
for cid in list(STATE.prices):
|
||||
if drift:
|
||||
px = STATE.prices[cid] * (1 + random.uniform(-drift, drift))
|
||||
STATE.set_price(cid, px)
|
||||
frames = [f"{config.MARK_PRICE_TOPIC} "
|
||||
f"{json.dumps({'contractId': c, 'markPrice': round(p, 6)})}"
|
||||
for c, p in STATE.prices.items()]
|
||||
for frame in frames:
|
||||
sock.send_string(frame)
|
||||
sent += 1
|
||||
if verbose:
|
||||
print(f"已发 {sent} 帧")
|
||||
time.sleep(interval)
|
||||
finally:
|
||||
sock.close(linger=0)
|
||||
ctx.term()
|
||||
return sent
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 起服务
|
||||
# ==========================================================================
|
||||
def serve(host: str | None = None, port: int | None = None) -> ThreadingHTTPServer:
|
||||
return ThreadingHTTPServer((host or config.MOCK_HOST, port or config.MOCK_PORT), Handler)
|
||||
|
||||
|
||||
def start_in_thread(host: str | None = None, port: int | None = None):
|
||||
"""在后台守护线程里起 mock,返回 (httpd, thread)。进程内夹具用这个,不占端口。"""
|
||||
httpd = serve(host, port)
|
||||
t = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
t.start()
|
||||
return httpd, t
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="运行本机回环 mock 交易所。")
|
||||
p.add_argument("--host", default=config.MOCK_HOST)
|
||||
p.add_argument("--port", type=int, default=config.MOCK_PORT)
|
||||
p.add_argument("--publish", action="store_true", help="同时把标记价格当行情发出去(ZMQ PUB)")
|
||||
p.add_argument("--interval", type=float, default=0.2, help="行情快照的间隔秒数")
|
||||
p.add_argument("--verbose", action="store_true")
|
||||
args = p.parse_args()
|
||||
|
||||
stop = threading.Event()
|
||||
if args.publish:
|
||||
threading.Thread(target=publish_loop, kwargs={
|
||||
"stop": stop, "interval": args.interval, "verbose": args.verbose},
|
||||
daemon=True).start()
|
||||
|
||||
httpd = serve(args.host, args.port)
|
||||
print(f"mock 交易所监听于 http://{args.host}:{args.port}"
|
||||
+ ("(并发行情)" if args.publish else ""))
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
stop.set()
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
# 跑测报告 — 小规模实验台
|
||||
|
||||
这是一套用本地 mock 复现的**小规模实验台**,用来验证当初随机测试工具的三条判断。
|
||||
这里跑的是单机、本机回环、无真实撮合系统,所以绝对量级不具可比性。下面把
|
||||
**生产环境的真实业绩**与**本机演示实测**分两栏列出。
|
||||
|
||||
---
|
||||
|
||||
## 【生产真实业绩】(公司环境,XXL-JOB 集群)
|
||||
|
||||
- 单次执行 **10s+ → 0.8s**,压进 1 秒执行窗口内完成
|
||||
- 常驻价格缓存任务内存 **50M → 2G**(加 TTL 与定期清理后回落)
|
||||
- **100 用户**批量初始化 **15min → 3min**
|
||||
- 1 秒 1 次连跑 1 小时 → 发现 **多空同时爆仓 P0**、**多线程并发保证金不足**
|
||||
|
||||
> 这些是当时在公司环境测得的数字,本机实验台**不重跑、也无法**复现这个量级。
|
||||
|
||||
---
|
||||
|
||||
## 【本机演示实测】(2026-09-22,单机 macOS,Python 3.13,仅打本机回环 mock)
|
||||
|
||||
跑测命令与真实输出:
|
||||
|
||||
| 项 | 命令 | 实测结果 |
|
||||
|---|---|---|
|
||||
| 用例 | `python3 -m pytest tests/ -q` | **12 passed in 2.10s** |
|
||||
| 每秒任务耗时 | 进程内夹具(mock 起在后台线程,直接量 `build_specs` + `send_specs`) | 每轮 8 个操作;**首周期 74.4ms**,**热周期中位数 1.9ms**(构造 1.1ms + 发送 0.7ms);冷/热 **39x** |
|
||||
| 对照实验-锚点冻结 | `python3 verify.py`(stale 组) | 条件单触发率 **0.00%**(触发价锚在远离实盘的冻结参考价) |
|
||||
| 对照实验-锚点实时 | `python3 verify.py`(live 组) | 无控随机走触发率 **74.00%**;单次受控 +3% 改价后 **100.00%** |
|
||||
| 边界构造 | `python3 verify.py`(boundary 组) | 错误规则在价格 **10.71** 同时平掉多/空两侧;正确规则只平空单 |
|
||||
| 端到端 | `bash run_local.sh` | 常驻行情服务 + 每秒请求器 + mock 全链路跑通;39 次构造 = 39 次发送 = mock 侧 39 次请求;缓存价格与 mock 价格一致(到行情帧的 6 位小数) |
|
||||
|
||||
---
|
||||
|
||||
## 数字归因(本机数字各自证明了哪条判断)
|
||||
|
||||
**判断① 每秒窗口是硬约束:固定成本被一次性付掉。**
|
||||
本机每秒任务的热周期中位数 **1.9ms**(构造 1.1ms + 发送 0.7ms,每轮 8 个操作),远低于 1 秒窗口;
|
||||
唯一的高开销出现在**首个周期**(74ms,含 sqlite 种子数据、diskcache 建库、aiohttp 会话冷启动),
|
||||
冷/热差约 **39x**。判断① 说的「每秒重复付的固定成本」就是这 39 倍 —— 它跟业务逻辑无关,
|
||||
只跟「每秒重新建一遍东西」有关。
|
||||
|
||||
其中最大的一块是缓存句柄。下面这个微基准只依赖 diskcache,量的是「新建一次 `Cache(path)`
|
||||
再做一次 `get`」与「持句柄做一次 `get`」的差别:
|
||||
|
||||
| 写法 | 单次读取 |
|
||||
|---|---|
|
||||
| 每次 `get`/`set` 都新建一次 `Cache()` | **1.10 ms** |
|
||||
| 持单个句柄 | **0.002 ms** |
|
||||
|
||||
一轮 8 个操作最多要开 19 次缓存读写(每个操作的 `@action` = 一次 get + 一次 set,三个操作
|
||||
还要各读一次价格)。本仓持单个句柄。
|
||||
|
||||
**判断② 常驻任务的失败是慢性的。**
|
||||
`tests/test_all.py` 的 `TestCacheTtl` 用真实 diskcache 验证:TTL 到期后取值返回空;写入 120 个
|
||||
短 TTL 键、过期后 `expire()` 清理使**条目数不随累计写入增长**(回到上界 ~20)。这把「内存随
|
||||
运行时间悄悄膨胀」的失效模式变成了可复现断言——它不崩溃,只会慢性变大。
|
||||
|
||||
**判断③ 杀伤力在可控边界,不在随机。**
|
||||
`verify.py` 里 stale 与 live 两组走的是**同一段代码、同一个采样器**,唯一变量是传给
|
||||
`place_conditions` 的锚点:
|
||||
|
||||
- 锚点冻结在 9.0(远离实盘 10.5)→ 触发率 **0.00%**,全不触发,看似繁忙实则无效
|
||||
- 锚点在实时价上 → 随机走 **74%**、受控改价 **100%**,可被精确推到目标
|
||||
|
||||
加权随机只决定**流量形态**;真正把系统推到边界的是**可控标记价格**。boundary 组进一步证明
|
||||
「多空同时爆仓」这类场景**可以被稳定构造**(错误规则在 10.71 同时命中两侧),而不是靠随机流量
|
||||
偶然撞出来。
|
||||
|
||||
---
|
||||
|
||||
## 口径限制
|
||||
|
||||
- 本机演示是**复刻实验台**,不是当时的生产系统;上面那栏的 10s→0.8s、50M→2G 是公司环境的数字,
|
||||
这台机器上的对应值是另一栏。两栏之间唯一有意义的比较是「同一脚本冷启动 vs 热运行」的倍数差。
|
||||
- **多进程 / 多实例数据共享仍未解决**(见 README「已知未解问题」):并发下同一用户可能被重复操作,
|
||||
当前只有备选方案,没有落地实现。
|
||||
- 本机数字取自单机回环、无并发的运行;换成多核并发构造(`--workers > 1`)时,`multiprocessing`
|
||||
的启动开销会重新回到热路径上,本报告未覆盖该场景。
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""每秒任务:加权随机决定这一秒的流量形态,并发构造并发送请求(固定频率模式)。
|
||||
|
||||
这是**判断①** 的落点。每秒执行窗口是硬约束;把单次执行从 10s+ 压进 1 秒,关键不在
|
||||
「把代码写快」,而在**消掉每秒重复付的固定成本**:
|
||||
|
||||
* 数据源、缓存句柄、HTTP 会话只建一次,跨周期复用(而不是每秒重建一次);
|
||||
* 载荷构造按 ``--workers`` 摊到多个进程,让 CPU 密集的部分用上多核;
|
||||
* 发送走 asyncio + aiohttp 并发,把串行的 HTTP 等待压到重叠。
|
||||
|
||||
构造与发送刻意分开(``build_specs`` / ``send_specs``):同一套构造器既能 ``--dry-run``
|
||||
(一个请求都不发),也能真实压测。
|
||||
|
||||
D3:原实现用 ``eval("api.{}()".format(name))`` 分发操作,装饰器内部又 ``eval`` 重建调用。
|
||||
这里全部换成 ``getattr`` 与 ``*args`` 直接转发——行为等价,但不再执行字符串。
|
||||
|
||||
python -m requester --dry-run --seconds 5 # 只构造,一个请求都不发
|
||||
python -m requester --seconds 10 --verbose # 打本机 mock
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import multiprocessing as mp
|
||||
import random
|
||||
import sqlite3
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
import config
|
||||
from mark_price_service import PriceCache
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 数据源:替代原实现的 MySQL 分库 + Redis 集群
|
||||
# ==========================================================================
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS position (
|
||||
position_no TEXT PRIMARY KEY,
|
||||
user_id TEXT,
|
||||
contract_id INTEGER,
|
||||
side INTEGER, -- 1 -> ask,否则 bid(沿用原实现的约定)
|
||||
avg_price REAL,
|
||||
quantity REAL,
|
||||
margin_type INTEGER, -- 1 全仓,2 逐仓
|
||||
create_time REAL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS open_order (
|
||||
order_no TEXT PRIMARY KEY,
|
||||
user_id TEXT,
|
||||
contract_id INTEGER,
|
||||
status INTEGER -- 2 / 3 视为挂单中,原实现就是这么过滤的
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
class DataStore:
|
||||
"""请求构造器要查的那层数据的替身。
|
||||
|
||||
真实的构造器会去分库的 MySQL(订单、用户、权益各自分库,表按 user_id 取模拆分)和
|
||||
一个 Redis 集群里拉账户、持仓、挂单。这些都不该出现在便携版 demo 里,所以本类只复刻
|
||||
构造器**消费到的那层形态**——同样的 ``get_*`` 方法、同样返回带同样字段名的
|
||||
``list[dict]``,背后换成一个内存 sqlite。日后要接回真实连接,换掉引擎即可,不必动 Api。
|
||||
"""
|
||||
|
||||
def __init__(self, seed: int = 20260921):
|
||||
self.conn = sqlite3.connect(":memory:", check_same_thread=False)
|
||||
self.conn.row_factory = sqlite3.Row
|
||||
self.conn.executescript(_SCHEMA)
|
||||
self._seed(random.Random(seed))
|
||||
|
||||
def _seed(self, rng: random.Random):
|
||||
pn = on = 0
|
||||
for uid in config.USER_IDS:
|
||||
for cid in config.CONTRACT_IDS:
|
||||
if rng.random() < 0.6: # 多数用户在多数币对上持有仓位
|
||||
pn += 1
|
||||
self.conn.execute(
|
||||
"INSERT INTO position VALUES (?,?,?,?,?,?,?,?)",
|
||||
(f"POS{pn}", uid, cid, 1 if rng.random() < 0.5 else 0,
|
||||
round(config.SEED_PRICES[cid] * (1 + rng.uniform(-0.05, 0.05)), 4),
|
||||
float(rng.randint(1, 50)),
|
||||
1 if uid in config.CROSS_MARGIN_USERS else 2,
|
||||
rng.random()),
|
||||
)
|
||||
if rng.random() < 0.3:
|
||||
on += 1
|
||||
self.conn.execute("INSERT INTO open_order VALUES (?,?,?,?)",
|
||||
(f"ORD{on}", uid, cid, rng.choice([2, 3])))
|
||||
self.conn.commit()
|
||||
|
||||
@staticmethod
|
||||
def _rows(cursor) -> list[dict]:
|
||||
return [dict(r) for r in cursor.fetchall()]
|
||||
|
||||
def get_position(self, user_id):
|
||||
return self._rows(self.conn.execute(
|
||||
"SELECT * FROM position WHERE user_id=? AND quantity>0 "
|
||||
"ORDER BY create_time DESC LIMIT 5", (str(user_id),)))
|
||||
|
||||
def get_position_by_contract_id(self, contract_id, user_id):
|
||||
return self._rows(self.conn.execute(
|
||||
"SELECT * FROM position WHERE contract_id=? AND user_id=? AND quantity>0 "
|
||||
"ORDER BY create_time DESC LIMIT 5", (int(contract_id), str(user_id))))
|
||||
|
||||
def get_order_no(self, contract_id, user_id):
|
||||
return self._rows(self.conn.execute(
|
||||
"SELECT * FROM open_order WHERE contract_id=? AND user_id=? AND status IN (2,3) LIMIT 5",
|
||||
(int(contract_id), str(user_id))))
|
||||
|
||||
def close(self):
|
||||
self.conn.close()
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 业务操作
|
||||
# ==========================================================================
|
||||
def action(func):
|
||||
"""把产出的一条请求描述记进共享缓存,让一轮运行可回放(与原实现同一套机制)。"""
|
||||
|
||||
@wraps(func)
|
||||
def adapter(self, *args, **kwargs):
|
||||
result = func(self, *args, **kwargs)
|
||||
if isinstance(result, dict):
|
||||
entry = dict(result)
|
||||
entry["class_name"] = func.__name__
|
||||
cached = self.cache.get("order_info") or []
|
||||
cached.append(entry)
|
||||
self.cache.set("order_info", cached)
|
||||
return result
|
||||
|
||||
return adapter
|
||||
|
||||
|
||||
class Api:
|
||||
"""按业务操作构造请求描述 ``{method, url, json}``;实际发送交给下面 asyncio 那层。
|
||||
|
||||
每个方法返回的都是一份描述,而不是已经发出去的请求——这样同一套构造器对 dry-run 和
|
||||
真实运行都能用。
|
||||
"""
|
||||
|
||||
def __init__(self, store: DataStore | None = None, cache: PriceCache | None = None):
|
||||
self.store = store or DataStore()
|
||||
self.cache = cache or PriceCache()
|
||||
|
||||
def mark_price(self, contract_id):
|
||||
"""请求器认为的标记价:读常驻任务落下的缓存,缺价时回落到种子价。"""
|
||||
cached = self.cache.get_price(contract_id)
|
||||
return float(cached if cached is not None else config.SEED_PRICES.get(contract_id, 10.0))
|
||||
|
||||
@staticmethod
|
||||
def _spec(op, payload):
|
||||
method, path = config.OPERATIONS[op]
|
||||
return {"method": method, "url": config.MOCK_BASE_URL + path, "json": payload}
|
||||
|
||||
@staticmethod
|
||||
def _skip():
|
||||
"""构造不出合法请求(例如该用户当前无持仓)——计数上跳过,不当成失败。"""
|
||||
return {"method": "SKIP", "url": None, "json": None}
|
||||
|
||||
def _pick_position(self, user_id):
|
||||
rows = self.store.get_position(user_id)
|
||||
return random.choice(rows) if rows else None
|
||||
|
||||
# -- 8 个业务操作 ----------------------------------------------------------
|
||||
@action
|
||||
def open_order(self, user_id=None, contract_id=None):
|
||||
contract_id = contract_id or random.choice(config.CONTRACT_IDS)
|
||||
price = self.mark_price(contract_id)
|
||||
return self._spec("open_order", {
|
||||
"contractId": contract_id,
|
||||
"userId": user_id or random.choice(config.USER_IDS),
|
||||
"side": random.choice(["ask", "bid"]),
|
||||
"price": round(price + random.uniform(-config.PRICE_FLOAT, config.PRICE_FLOAT), 5),
|
||||
"quantity": random.randint(1, 50),
|
||||
"marginType": 2, "marginRate": 0.02,
|
||||
"durationQualifiers": "GTC", "txId": "burst",
|
||||
})
|
||||
|
||||
@action
|
||||
def market_open_order(self, user_id=None):
|
||||
return self._spec("market_open_order", {
|
||||
"contractId": random.choice(config.CONTRACT_IDS),
|
||||
"userId": user_id or random.choice(config.USER_IDS),
|
||||
"quantity": random.randint(1, 50),
|
||||
"marginType": 2, "marginRate": 0.02, "txId": "market_open",
|
||||
})
|
||||
|
||||
@action
|
||||
def close_order(self, user_id=None):
|
||||
pos = self._pick_position(user_id or random.choice(config.USER_IDS))
|
||||
if pos is None:
|
||||
return self._skip()
|
||||
return self._spec("close_order", {
|
||||
"userId": pos["user_id"], "contractId": pos["contract_id"],
|
||||
"side": "ask" if pos["side"] == 1 else "bid",
|
||||
"price": str(abs(pos["avg_price"])),
|
||||
"quantity": random.randint(1, int(pos["quantity"])),
|
||||
"marginType": pos["margin_type"], "positionNo": pos["position_no"],
|
||||
"txId": "close_order",
|
||||
})
|
||||
|
||||
@action
|
||||
def cancel_order(self, user_id=None):
|
||||
user_id = user_id or random.choice(config.USER_IDS)
|
||||
rows = self.store.get_order_no(random.choice(config.CONTRACT_IDS), user_id)
|
||||
if not rows:
|
||||
return self._skip()
|
||||
row = random.choice(rows)
|
||||
return self._spec("cancel_order", {
|
||||
"contractId": row["contract_id"], "userId": user_id, "orderNo": row["order_no"]})
|
||||
|
||||
@action
|
||||
def condition_order(self, user_id=None, contract_id=None):
|
||||
contract_id = contract_id or random.choice(config.CONTRACT_IDS)
|
||||
price = self.mark_price(contract_id)
|
||||
return self._spec("condition_order", {
|
||||
"contractId": contract_id, "userId": user_id or random.choice(config.USER_IDS),
|
||||
"curtPrice": price, "triggerPrice": round(price + random.uniform(0, 0.5), 5),
|
||||
"conditionOrderType": random.randint(3, 4), "triggerType": 4,
|
||||
"orderType": random.randint(1, 2), "dependencyNo": "0",
|
||||
"dependencyType": "condition", "positionEffect": 1,
|
||||
})
|
||||
|
||||
@action
|
||||
def condition_position(self, user_id=None):
|
||||
user_id = user_id or random.choice(config.USER_IDS)
|
||||
pos = self._pick_position(user_id)
|
||||
if pos is None:
|
||||
return self._skip()
|
||||
price = self.mark_price(pos["contract_id"])
|
||||
f = config.PRICE_FLOAT
|
||||
up = random.randint(1, 2) == 1
|
||||
return self._spec("condition_position", {
|
||||
"contractId": pos["contract_id"], "userId": user_id,
|
||||
"side": "ask" if pos["side"] == 1 else "bid",
|
||||
"dependencyNo": pos["position_no"], "dependencyType": "position",
|
||||
"positionEffect": 2, "orderType": 2,
|
||||
"conditionOrderType": 1 if up else 2,
|
||||
"curtPrice": price + f if up else price - f,
|
||||
"triggerPrice": price + f * (1.5 if up else -0.5),
|
||||
"amount": str(random.randint(1, 50)),
|
||||
})
|
||||
|
||||
@action
|
||||
def reverse_position(self, user_id=None):
|
||||
user_id = user_id or random.choice(config.USER_IDS)
|
||||
rows = self.store.get_position_by_contract_id(random.choice(config.CONTRACT_IDS), user_id)
|
||||
if not rows:
|
||||
return self._skip()
|
||||
pos = random.choice(rows)
|
||||
return self._spec("reverse_position", {
|
||||
"positionNo": pos["position_no"], "userId": int(pos["user_id"]),
|
||||
"contractId": pos["contract_id"],
|
||||
"quantity": random.randint(1, int(pos["quantity"]) + 1), "txId": "reverse_position",
|
||||
})
|
||||
|
||||
@action
|
||||
def transfer(self, user_id=None, quantity=10000):
|
||||
return self._spec("transfer", {
|
||||
"currencyId": 21, "quantity": str(quantity),
|
||||
"transferFrom": "burst", "transferTo": "burst", "transferType": 1, "txId": "burst",
|
||||
"userId": int(user_id or random.choice(config.USER_IDS)), "userType": 4,
|
||||
})
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 流量形态 -> 载荷 -> 发送
|
||||
# ==========================================================================
|
||||
def weighted_ops(count: int):
|
||||
"""这一秒要构造哪些操作。它只决定流量的**形态**,不是重点(见判断③)。"""
|
||||
names = [name for name, _ in config.WEIGHTED_OPS]
|
||||
weights = [w for _, w in config.WEIGHTED_OPS]
|
||||
return random.choices(names, weights=weights, k=count)
|
||||
|
||||
|
||||
def _build(api: Api, ops):
|
||||
specs = []
|
||||
for op in ops:
|
||||
fn = getattr(api, op, None) # D3:用 getattr,不用 eval
|
||||
if fn is None:
|
||||
continue
|
||||
spec = fn()
|
||||
if spec and spec.get("method") != "SKIP":
|
||||
specs.append(spec)
|
||||
return specs
|
||||
|
||||
|
||||
def _build_worker(ops):
|
||||
"""放在模块顶层是为了能被进程池 pickle。每个进程自建数据源与缓存句柄。"""
|
||||
api = Api()
|
||||
try:
|
||||
return _build(api, ops)
|
||||
finally:
|
||||
api.store.close()
|
||||
api.cache.close()
|
||||
|
||||
|
||||
def build_specs(api: Api, ops, workers: int = 1):
|
||||
if workers <= 1:
|
||||
return _build(api, ops)
|
||||
chunks = [ops[i::workers] for i in range(workers)]
|
||||
with mp.Pool(workers) as pool:
|
||||
return [spec for group in pool.map(_build_worker, chunks) for spec in group]
|
||||
|
||||
|
||||
async def _send_all(specs):
|
||||
import aiohttp
|
||||
|
||||
timeout = aiohttp.ClientTimeout(total=2)
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
tasks = [getattr(session, s["method"].lower())(url=s["url"], json=s.get("json") or {})
|
||||
for s in specs]
|
||||
responses = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
ok = 0
|
||||
for r in responses:
|
||||
if not isinstance(r, Exception):
|
||||
await r.read()
|
||||
await r.release()
|
||||
ok += 1
|
||||
return ok
|
||||
|
||||
|
||||
def send_specs(specs) -> int:
|
||||
return asyncio.run(_send_all(specs)) if specs else 0
|
||||
|
||||
|
||||
def run_cycle(api: Api, *, dry_run: bool, workers: int, verbose: bool):
|
||||
ops = weighted_ops(max(1, len(config.WEIGHTED_OPS)))
|
||||
if verbose:
|
||||
print(f" 本轮采样到的操作:{sorted(set(ops))}")
|
||||
specs = build_specs(api, ops, workers=workers)
|
||||
return {"built": len(specs), "sent": 0 if dry_run else send_specs(specs)}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="加权随机的交易请求模拟器。")
|
||||
p.add_argument("--dry-run", action="store_true", help="只构造请求,一个都不发")
|
||||
p.add_argument("--seconds", type=int, default=5, help="每秒跑一轮,共跑 N 秒")
|
||||
p.add_argument("--workers", type=int, default=1, help="构造载荷用的进程数")
|
||||
p.add_argument("--interval", type=float, default=1.0, help="两轮之间的间隔秒数")
|
||||
p.add_argument("--verbose", action="store_true")
|
||||
args = p.parse_args()
|
||||
|
||||
api = Api()
|
||||
total_built = total_sent = cycles = 0
|
||||
start = time.time()
|
||||
try:
|
||||
while time.time() - start < args.seconds:
|
||||
t0 = time.time()
|
||||
summary = run_cycle(api, dry_run=args.dry_run, workers=args.workers,
|
||||
verbose=args.verbose)
|
||||
total_built += summary["built"]
|
||||
total_sent += summary["sent"]
|
||||
cycles += 1
|
||||
elapsed = time.time() - t0
|
||||
if args.verbose:
|
||||
print(f" 第 {cycles} 轮:构造={summary['built']} 发送={summary['sent']} "
|
||||
f"耗时={elapsed:.3f}s")
|
||||
# 保持约 1 秒的节奏,模拟固定频率调度器那样触发。
|
||||
time.sleep(max(0.0, args.interval - elapsed))
|
||||
finally:
|
||||
api.store.close()
|
||||
api.cache.close()
|
||||
|
||||
mode = "dry-run" if args.dry_run else "live"
|
||||
print(f"burst[{mode}] 轮数={cycles} 构造={total_built} 发送={total_sent} "
|
||||
f"总耗时={time.time() - start:.2f}s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,10 @@
|
||||
# demo 只需要这些。原始实现还用了 SQLAlchemy + PyMySQL + DBUtils + redis-py-cluster
|
||||
# 去连真实的 MySQL / Redis 集群;demo 把这些换成了标准库 sqlite3 数据源,所以这些重依赖
|
||||
# (以及装不上 Python 3.12+ 的 redis-py-cluster)都去掉了。
|
||||
#
|
||||
# pyzmq 才是真正的绑定(原 requirements 里误写成了占位包 "zmq==0.0.0")。
|
||||
# HTTP 客户端只用标准库:verify.py 用 urllib,requester 用 aiohttp(并发发送)。
|
||||
pyzmq>=22.3
|
||||
diskcache>=5.2
|
||||
aiohttp>=3.8
|
||||
pytest>=7.0
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env bash
|
||||
# 端到端本机演示。
|
||||
#
|
||||
# 真实工具由 XXL-JOB 以两种模式驱动:
|
||||
# * BEAN(常驻):标记价格缓存任务长期运行;
|
||||
# * 固定频率: 请求任务每秒触发一次。
|
||||
# XXL-JOB 本身无法随这份 demo 交付,所以本脚本复现两种模式的**形态**:mock 交易所(自带
|
||||
# 行情发布)与订阅器常驻在后台,请求循环以约每秒一次的节奏触发。全程只打本机回环。
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
PY=${PYTHON:-python3}
|
||||
BURST_SECONDS=${BURST_SECONDS:-6}
|
||||
RESIDENT_SECONDS=${RESIDENT_SECONDS:-$((BURST_SECONDS + 2))}
|
||||
|
||||
mkdir -p run
|
||||
PIDS=()
|
||||
cleanup() {
|
||||
for pid in "${PIDS[@]:-}"; do
|
||||
kill "$pid" 2>/dev/null || true
|
||||
done
|
||||
wait 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
echo "[1/4] 启动本机回环 mock 交易所(被测系统 + 行情源)"
|
||||
$PY -m mock_exchange --port 18080 --publish > run/mock.log 2>&1 &
|
||||
PIDS+=($!)
|
||||
for _ in $(seq 1 40); do
|
||||
if curl -s http://127.0.0.1:18080/health >/dev/null 2>&1; then break; fi
|
||||
sleep 0.1
|
||||
done
|
||||
echo " mock 就绪"
|
||||
|
||||
echo "[2/4] 启动常驻标记价格服务(XXL-JOB BEAN 模式)"
|
||||
$PY -m mark_price_service --duration "$RESIDENT_SECONDS" --verbose > run/subscriber.log 2>&1 &
|
||||
PIDS+=($!)
|
||||
sleep 1 # 让行情先把缓存预热
|
||||
|
||||
echo "[3/4] 触发请求压测(XXL-JOB 固定频率模式,每秒一轮)"
|
||||
$PY -m requester --seconds "$BURST_SECONDS" --interval 1.0 --verbose
|
||||
|
||||
echo "[4/4] 跑完后对账:"
|
||||
echo -n " "
|
||||
$PY -m mark_price_service --dump
|
||||
echo " mock 侧统计:"
|
||||
curl -s http://127.0.0.1:18080/api/v1/market/stats | $PY -m json.tool | head -16
|
||||
|
||||
echo
|
||||
echo "run_local.sh 全流程正常结束"
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""单测:每条都对应一条判断或一处修复,没有为了凑数而存在的用例。
|
||||
|
||||
判断② TTL 与显式清理 -> TestCacheTtl
|
||||
D1 去重窗口按币对隔离 -> TestSlidingWindow
|
||||
D3 getattr 分发与动作缓存 -> TestActionCache
|
||||
流量形态 加权随机采样器 -> TestWeightedRandom
|
||||
|
||||
运行: python -m pytest tests/ -q
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import pytest # noqa: E402
|
||||
|
||||
import config # noqa: E402
|
||||
from mark_price_service import MarkPriceSubscriber, PriceCache # noqa: E402
|
||||
from requester import Api, weighted_ops # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def subscriber(tmp_path):
|
||||
cache = PriceCache(path=str(tmp_path / "win"))
|
||||
yield MarkPriceSubscriber(cache=cache, window_len=2), cache
|
||||
cache.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(tmp_path):
|
||||
a = Api(cache=PriceCache(path=str(tmp_path / "act")))
|
||||
yield a
|
||||
a.store.close()
|
||||
a.cache.close()
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 判断②:常驻任务的失败是慢性的——TTL 与显式清理
|
||||
# ==========================================================================
|
||||
class TestCacheTtl:
|
||||
def test_expired_price_reads_back_empty(self, tmp_path):
|
||||
with PriceCache(path=str(tmp_path / "ttl"), ttl=0.3) as cache:
|
||||
cache.set_price(5, 123.0)
|
||||
assert cache.get_price(5) == 123.0 # TTL 之前还活着
|
||||
time.sleep(0.6)
|
||||
assert cache.get_price(5) is None # TTL 之后消失
|
||||
|
||||
def test_entry_count_does_not_grow_with_runtime(self, tmp_path):
|
||||
with PriceCache(path=str(tmp_path / "grow"), ttl=0.3) as cache:
|
||||
for i in range(120): # 模拟常驻循环写入大量短命键
|
||||
cache.set(f"tick:{i}", i, ttl=0.3)
|
||||
assert cache.size() >= 100 # 过期前这些条目都在
|
||||
|
||||
time.sleep(0.6)
|
||||
assert cache.expire() >= 100
|
||||
# 清理一次后,大小只跟着**存活**条目走,而不是跟着累计写入量走。
|
||||
# 这条修复的全部意义就在这——它把「内存随运行时间悄悄膨胀」变成可复现断言。
|
||||
assert cache.size() <= 20
|
||||
|
||||
def test_live_entries_survive_expire(self, tmp_path):
|
||||
with PriceCache(path=str(tmp_path / "mix"), ttl=0.3) as cache:
|
||||
cache.set("short", 1, ttl=0.2)
|
||||
cache.set("long", 2, ttl=30)
|
||||
time.sleep(0.6)
|
||||
cache.expire()
|
||||
assert cache.get("short") is None
|
||||
assert cache.get("long") == 2
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# D1:滑动窗口去重是按币对的,不是全局的
|
||||
# ==========================================================================
|
||||
class TestSlidingWindow:
|
||||
def test_interleaved_contracts_are_independent(self, subscriber):
|
||||
sub, cache = subscriber
|
||||
accepts = [
|
||||
sub.handle_price(4, 10.0), # 币对 4 的首个观测 -> 接受
|
||||
sub.handle_price(5, 10.0), # 币对 5 的首个观测 -> 接受
|
||||
sub.handle_price(4, 10.0), # 币对 4 无变化 -> 拒绝
|
||||
]
|
||||
# 全局窗口会把第 2 个也拒掉(它上一条也是 10.0),让币对 5 留在未缓存状态。
|
||||
assert accepts == [True, True, False]
|
||||
assert cache.get_price(4) == 10.0
|
||||
assert cache.get_price(5) == 10.0
|
||||
|
||||
def test_each_contract_tracks_its_own_changes(self, subscriber):
|
||||
sub, cache = subscriber
|
||||
sub.handle_price(4, 100.0)
|
||||
sub.handle_price(5, 200.0)
|
||||
assert sub.handle_price(4, 101.0) is True # 币对 4 变了:只更新 4
|
||||
assert cache.get_price(4) == 101.0
|
||||
assert cache.get_price(5) == 200.0
|
||||
assert sub.handle_price(5, 200.0) is False # 币对 5 重复:不更新 5,也不搅动 4
|
||||
assert sub.handle_price(4, 101.0) is False
|
||||
|
||||
def test_windows_are_separate_objects(self, subscriber):
|
||||
sub, _ = subscriber
|
||||
for cid, px in ((4, 1.0), (5, 2.0), (6, 3.0)):
|
||||
sub.handle_price(cid, px)
|
||||
assert set(sub._windows) == {4, 5, 6}
|
||||
assert list(sub._windows[4]) == [1.0] # 每条窗口只装自己币对的历史
|
||||
assert list(sub._windows[5]) == [2.0]
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# D3:getattr 分发与 @action 缓存
|
||||
# ==========================================================================
|
||||
class TestActionCache:
|
||||
def test_action_records_produced_order(self, api):
|
||||
spec = api.open_order(user_id="1", contract_id=5)
|
||||
|
||||
cached = api.cache.get("order_info")
|
||||
assert len(cached) == 1
|
||||
assert cached[0]["class_name"] == "open_order"
|
||||
assert cached[0]["json"]["contractId"] == 5
|
||||
assert spec["method"] == "POST"
|
||||
|
||||
def test_action_accumulates_across_calls(self, api):
|
||||
api.open_order(user_id="1", contract_id=5)
|
||||
api.open_order(user_id="2", contract_id=6)
|
||||
api.market_open_order(user_id="3")
|
||||
|
||||
assert [c["class_name"] for c in api.cache.get("order_info")] == [
|
||||
"open_order", "open_order", "market_open_order",
|
||||
]
|
||||
|
||||
def test_dispatch_is_getattr_not_eval(self, api):
|
||||
# D3 约定:操作通过属性查找命中 Api 上的方法。
|
||||
assert callable(getattr(api, "open_order"))
|
||||
# 仅仅解析名字不应有任何副作用。
|
||||
assert api.cache.get("order_info") is None
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 流量形态:加权随机采样器
|
||||
# ==========================================================================
|
||||
class TestWeightedRandom:
|
||||
def test_only_valid_ops_emitted(self):
|
||||
assert set(weighted_ops(2000)) <= {name for name, _ in config.WEIGHTED_OPS}
|
||||
|
||||
def test_zero_weight_ops_never_sampled(self):
|
||||
zero = {name for name, w in config.WEIGHTED_OPS if w == 0}
|
||||
assert zero, "配置里应当存在权重为 0 的操作(transfer 就是那个哨兵)"
|
||||
assert set(weighted_ops(20000)) & zero == set()
|
||||
|
||||
def test_weights_drive_relative_frequency(self):
|
||||
counts = Counter(weighted_ops(20000))
|
||||
# open_order(200) > condition_order(50) > cancel_order(10)
|
||||
assert counts["open_order"] > counts["condition_order"] > counts["cancel_order"]
|
||||
assert counts["open_order"] > counts["cancel_order"] * 5
|
||||
# 权重 10 的操作罕见但非零。
|
||||
assert 0 < counts["reverse_position"] < counts["open_order"]
|
||||
@@ -0,0 +1,192 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""判断③ 的验证:三个对照实验,都用**操纵价格**把系统推到边界,而不是等随机流量去撞。
|
||||
|
||||
stale 触发价锚在一个冻结参考价上 -> 一条都不触发;流量看着很忙,其实什么都没测到
|
||||
live 触发价锚在实时价上 -> 随机走触发大部分;一次受控改价推到 100%
|
||||
boundary 把价格推过强平价位带 -> 稳定复现「多空同时爆仓」
|
||||
|
||||
前两个是**同一段代码、同一个采样器**,唯一的变量是传给 ``place_conditions`` 的锚点。
|
||||
第三个用 mock 的「正确规则 vs 历史 bug 规则」双规则对照,证明这类边界可以被精确构造。
|
||||
|
||||
三个实验共用一个进程内的 mock,每次先 ``reset()``,所以彼此隔离。
|
||||
|
||||
运行: python verify.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
import config
|
||||
from mock_exchange import start_in_thread
|
||||
|
||||
PORT = 18091
|
||||
CONTRACT = config.DEFAULT_CONTRACT_ID
|
||||
N = 100 # 每个对照组挂的条件单数量
|
||||
STALE_REF = 9.0 # 一个「过期参考价」:冻结在远离实盘(~10.5)的位置
|
||||
SPREAD = 0.01 # 触发价围绕锚点的散布——两个对照组共用,唯一的变量是锚点
|
||||
WALK_STEPS = 60 # 无控随机游走的步数
|
||||
MARGIN_RATE = 0.02 # 强平价带:多单 entry*(1-m)、空单 entry*(1+m)
|
||||
ENTRY = 10.5 # -> 多单强平价 10.29,空单强平价 10.71
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 极简同步客户端(只用标准库)
|
||||
# ==========================================================================
|
||||
class Mock:
|
||||
def __init__(self, port):
|
||||
self.base = f"http://127.0.0.1:{port}"
|
||||
|
||||
def _call(self, method, path, payload=None):
|
||||
req = Request(
|
||||
self.base + path,
|
||||
data=None if payload is None else json.dumps(payload).encode(),
|
||||
method=method,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urlopen(req, timeout=2) as resp:
|
||||
return json.loads(resp.read() or b"{}")
|
||||
|
||||
def wait_ready(self, timeout=3.0):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
self._call("GET", "/health")
|
||||
return
|
||||
except OSError:
|
||||
time.sleep(0.05)
|
||||
raise RuntimeError("mock 交易所未能就绪")
|
||||
|
||||
def reset(self):
|
||||
self._call("POST", f"{config.PREFIX}/market/reset")
|
||||
|
||||
def price(self, contract_id):
|
||||
return float(self._call(
|
||||
"GET", f"{config.PREFIX}/market/price?contractId={contract_id}")["price"])
|
||||
|
||||
def set_price(self, contract_id, price):
|
||||
self._call("POST", f"{config.PREFIX}/quotation/set-price",
|
||||
{"contractId": contract_id, "markPrice": price})
|
||||
|
||||
def place_condition(self, contract_id, trigger_price):
|
||||
self._call("POST", f"{config.PREFIX}/condition/plan",
|
||||
{"contractId": contract_id, "triggerPrice": trigger_price})
|
||||
|
||||
def seed_position(self, contract_id, side, entry, margin_rate, quantity=10):
|
||||
self._call("POST", f"{config.PREFIX}/market/positions/seed",
|
||||
{"contractId": contract_id, "side": side, "entry": entry,
|
||||
"marginRate": margin_rate, "quantity": quantity})
|
||||
|
||||
def stats(self):
|
||||
return self._call("GET", f"{config.PREFIX}/market/stats")
|
||||
|
||||
|
||||
class MockServer:
|
||||
"""在后台守护线程里跑 mock,用纯 HTTP 驱动它。"""
|
||||
|
||||
def __init__(self, port):
|
||||
self.httpd, self.thread = start_in_thread("127.0.0.1", port)
|
||||
self.client = Mock(port)
|
||||
|
||||
def __enter__(self):
|
||||
self.client.wait_ready()
|
||||
return self.client
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
|
||||
|
||||
# ==========================================================================
|
||||
# 三个实验
|
||||
# ==========================================================================
|
||||
def place_conditions(client, anchor, n, rng):
|
||||
"""把 n 张条件单的触发价锚在 anchor 上(±SPREAD)。这是两个对照组唯一的变量。"""
|
||||
for _ in range(n):
|
||||
client.place_condition(CONTRACT, round(anchor * (1 + rng.uniform(-SPREAD, SPREAD)), 4))
|
||||
|
||||
|
||||
def walk(client, steps, rng, pct=0.01):
|
||||
"""小幅无控随机游走——行情实际给你的那种价格漂移。"""
|
||||
price = client.price(CONTRACT)
|
||||
for _ in range(steps):
|
||||
price *= 1 + rng.uniform(-pct, pct)
|
||||
client.set_price(CONTRACT, price)
|
||||
return price
|
||||
|
||||
|
||||
def experiment_stale(client, rng):
|
||||
"""对照组 A:触发价锚在一个冻结参考价上。"""
|
||||
client.reset()
|
||||
live = client.price(CONTRACT)
|
||||
place_conditions(client, STALE_REF, N, rng)
|
||||
walk(client, WALK_STEPS, rng)
|
||||
cond = client.stats()["condition"]
|
||||
|
||||
print("stale(触发价锚定在一个冻结参考价上)")
|
||||
print(f" 运行期实价 ~{live:.2f},触发价聚在 {STALE_REF:.2f} 附近")
|
||||
print(f" 条件单:created={cond['created']} triggered={cond['triggered']} "
|
||||
f"触发率={cond['rate']:.2%}")
|
||||
print(f"RESULT stale_price trigger_rate={cond['rate']:.4f}")
|
||||
|
||||
|
||||
def experiment_live(client, rng):
|
||||
"""对照组 B:触发价锚在实时价上。"""
|
||||
client.reset()
|
||||
live = client.price(CONTRACT)
|
||||
place_conditions(client, live, N, rng)
|
||||
walk(client, WALK_STEPS, rng)
|
||||
after_walk = client.stats()["condition"]
|
||||
|
||||
# 受控改价:把价格一举推过整个价位带,一整侧条件单随即按需触发,而非靠运气。
|
||||
client.set_price(CONTRACT, live * 1.03)
|
||||
controlled = client.stats()["condition"]
|
||||
|
||||
print("live(触发价锚定在实时价上)")
|
||||
print(f" 实时价 ~{live:.2f},触发价散布在 ±{SPREAD:.0%}")
|
||||
print(f" 无控随机走之后:created={after_walk['created']} "
|
||||
f"triggered={after_walk['triggered']} 触发率={after_walk['rate']:.2%}")
|
||||
print(f" 受控 +3% 改价后:触发率={controlled['rate']:.2%}")
|
||||
print(f"RESULT live_price walk_rate={after_walk['rate']:.4f} "
|
||||
f"controlled_rate={controlled['rate']:.4f}")
|
||||
|
||||
|
||||
def experiment_boundary(client):
|
||||
"""边界构造:把价格往上推,穿过强平价位带。"""
|
||||
client.reset()
|
||||
client.seed_position(CONTRACT, "long", ENTRY, MARGIN_RATE, quantity=10)
|
||||
client.seed_position(CONTRACT, "short", ENTRY, MARGIN_RATE, quantity=10)
|
||||
|
||||
price, crossed = ENTRY, None
|
||||
while price <= ENTRY * (1 + MARGIN_RATE) + 0.005:
|
||||
client.set_price(CONTRACT, round(price, 4))
|
||||
if crossed is None and client.stats()["liquidation"]["buggy_both_sides"]:
|
||||
crossed = round(price, 4)
|
||||
price += 0.005
|
||||
|
||||
liq = client.stats()["liquidation"]
|
||||
print("boundary(把价格往上操纵,穿过强平价位带)")
|
||||
print(f" entry={ENTRY} marginRate={MARGIN_RATE} -> "
|
||||
f"多单强平价={ENTRY * (1 - MARGIN_RATE):.2f},空单强平价={ENTRY * (1 + MARGIN_RATE):.2f}")
|
||||
print(f" 正确规则平掉的仓位:{liq['correct_by_side']} (理应只平空单)")
|
||||
print(f" bug 规则平掉的仓位:{liq['buggy_by_side']} (两边都被平了)")
|
||||
print(f" bug 规则首次同时命中两边的价格:{crossed}")
|
||||
print(f"RESULT boundary buggy_both_sides={liq['buggy_both_sides']} "
|
||||
f"correct_both_sides={liq['correct_both_sides']} price={crossed}")
|
||||
|
||||
|
||||
def main():
|
||||
with MockServer(PORT) as client:
|
||||
experiment_stale(client, random.Random(7))
|
||||
print()
|
||||
experiment_live(client, random.Random(7))
|
||||
print()
|
||||
experiment_boundary(client)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user