Files
trade-fuzz-demo/verify.py
T

193 lines
7.6 KiB
Python

#!/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()