Files

312 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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()