From b8a74f203a8352723e3312ec1613255c17a1311f Mon Sep 17 00:00:00 2001 From: WbiubiuW Date: Tue, 22 Sep 2026 14:28:42 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=90=88=E7=BA=A6=E6=92=AE=E5=90=88=20?= =?UTF-8?q?HTTP=20=E6=8E=A5=E5=8F=A3=E8=87=AA=E5=8A=A8=E5=8C=96=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=EF=BC=88unittest=20=E6=95=B0=E6=8D=AE=E9=A9=B1?= =?UTF-8?q?=E5=8A=A8=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ._.git | Bin 0 -> 163 bytes ._.github | Bin 0 -> 163 bytes ._.gitignore | Bin 0 -> 163 bytes ._README.md | Bin 0 -> 163 bytes ._case | Bin 0 -> 163 bytes ._conftest.py | Bin 0 -> 163 bytes ._data | Bin 0 -> 163 bytes ._docs | Bin 0 -> 163 bytes ._formula | Bin 0 -> 163 bytes ._framework | Bin 0 -> 163 bytes ._mock | Bin 0 -> 163 bytes ._pytest.ini | Bin 0 -> 163 bytes ._requirements.txt | Bin 0 -> 163 bytes .github/._workflows | Bin 0 -> 163 bytes .github/workflows/._ci.yml | Bin 0 -> 163 bytes .github/workflows/ci.yml | 24 ++ .gitignore | 9 + README.md | 250 ++++++++++++++++ case/.___init__.py | Bin 0 -> 163 bytes case/._test_cancel_order.py | Bin 0 -> 163 bytes case/._test_formula.py | Bin 0 -> 163 bytes case/._test_liquidation.py | Bin 0 -> 163 bytes case/._test_order_freeze.py | Bin 0 -> 163 bytes case/._test_position_open.py | Bin 0 -> 163 bytes case/__init__.py | 0 case/test_cancel_order.py | 192 +++++++++++++ case/test_formula.py | 76 +++++ case/test_liquidation.py | 115 ++++++++ case/test_order_freeze.py | 112 ++++++++ case/test_position_open.py | 118 ++++++++ conftest.py | 58 ++++ data/._addOrder.yml | Bin 0 -> 163 bytes data/._cancelOrder.yml | Bin 0 -> 163 bytes data/._formula.yml | Bin 0 -> 163 bytes data/._liquidation.yml | Bin 0 -> 163 bytes data/addOrder.yml | 525 ++++++++++++++++++++++++++++++++++ data/cancelOrder.yml | 31 ++ data/formula.yml | 56 ++++ data/liquidation.yml | 47 +++ docs/._architecture.svg | Bin 0 -> 163 bytes docs/architecture.svg | 1 + formula/.___init__.py | Bin 0 -> 163 bytes formula/._contract_formula.py | Bin 0 -> 163 bytes formula/__init__.py | 0 formula/contract_formula.py | 123 ++++++++ framework/.___init__.py | Bin 0 -> 163 bytes framework/._decimal_assert.py | Bin 0 -> 163 bytes framework/._http_client.py | Bin 0 -> 163 bytes framework/._order_api.py | Bin 0 -> 163 bytes framework/._read_yaml.py | Bin 0 -> 163 bytes framework/._settings.py | Bin 0 -> 163 bytes framework/__init__.py | 0 framework/decimal_assert.py | 23 ++ framework/http_client.py | 27 ++ framework/order_api.py | 45 +++ framework/read_yaml.py | 18 ++ framework/settings.py | 31 ++ mock/.___init__.py | Bin 0 -> 163 bytes mock/._engine.py | Bin 0 -> 163 bytes mock/._fake_cache.py | Bin 0 -> 163 bytes mock/._fake_db.py | Bin 0 -> 163 bytes mock/._server.py | Bin 0 -> 163 bytes mock/__init__.py | 0 mock/engine.py | 415 +++++++++++++++++++++++++++ mock/fake_cache.py | 29 ++ mock/fake_db.py | 25 ++ mock/server.py | 56 ++++ pytest.ini | 3 + requirements.txt | 4 + 69 files changed, 2413 insertions(+) create mode 100755 ._.git create mode 100755 ._.github create mode 100644 ._.gitignore create mode 100644 ._README.md create mode 100755 ._case create mode 100644 ._conftest.py create mode 100755 ._data create mode 100755 ._docs create mode 100755 ._formula create mode 100755 ._framework create mode 100755 ._mock create mode 100644 ._pytest.ini create mode 100644 ._requirements.txt create mode 100755 .github/._workflows create mode 100644 .github/workflows/._ci.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 README.md create mode 100644 case/.___init__.py create mode 100644 case/._test_cancel_order.py create mode 100644 case/._test_formula.py create mode 100644 case/._test_liquidation.py create mode 100644 case/._test_order_freeze.py create mode 100644 case/._test_position_open.py create mode 100644 case/__init__.py create mode 100644 case/test_cancel_order.py create mode 100644 case/test_formula.py create mode 100644 case/test_liquidation.py create mode 100644 case/test_order_freeze.py create mode 100644 case/test_position_open.py create mode 100644 conftest.py create mode 100644 data/._addOrder.yml create mode 100644 data/._cancelOrder.yml create mode 100644 data/._formula.yml create mode 100644 data/._liquidation.yml create mode 100644 data/addOrder.yml create mode 100644 data/cancelOrder.yml create mode 100644 data/formula.yml create mode 100644 data/liquidation.yml create mode 100644 docs/._architecture.svg create mode 100644 docs/architecture.svg create mode 100644 formula/.___init__.py create mode 100644 formula/._contract_formula.py create mode 100644 formula/__init__.py create mode 100644 formula/contract_formula.py create mode 100644 framework/.___init__.py create mode 100644 framework/._decimal_assert.py create mode 100644 framework/._http_client.py create mode 100644 framework/._order_api.py create mode 100644 framework/._read_yaml.py create mode 100644 framework/._settings.py create mode 100644 framework/__init__.py create mode 100644 framework/decimal_assert.py create mode 100644 framework/http_client.py create mode 100644 framework/order_api.py create mode 100644 framework/read_yaml.py create mode 100644 framework/settings.py create mode 100644 mock/.___init__.py create mode 100644 mock/._engine.py create mode 100644 mock/._fake_cache.py create mode 100644 mock/._fake_db.py create mode 100644 mock/._server.py create mode 100644 mock/__init__.py create mode 100644 mock/engine.py create mode 100644 mock/fake_cache.py create mode 100644 mock/fake_db.py create mode 100644 mock/server.py create mode 100644 pytest.ini create mode 100644 requirements.txt diff --git a/._.git b/._.git new file mode 100755 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K= 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) diff --git a/case/test_order_freeze.py b/case/test_order_freeze.py new file mode 100644 index 0000000..8e84773 --- /dev/null +++ b/case/test_order_freeze.py @@ -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:*") == [] diff --git a/case/test_position_open.py b/case/test_position_open.py new file mode 100644 index 0000000..0da9d77 --- /dev/null +++ b/case/test_position_open.py @@ -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 # 未越过强平价,不应强平 diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..d13d788 --- /dev/null +++ b/conftest.py @@ -0,0 +1,58 @@ +"""pytest 全局 fixture:启动 mock 撮合服务,注入数据面与测试账户。 + +- match_server:会话级启动本地 mock HTTP 服务(随机端口),返回 base_url; +- base_url:函数级,每个用例前重置引擎数据,保证用例相互隔离、可重复执行; +- db / cache:注入 MockMySQL / MockRedis,做落库与缓存校验; +- trader:准备默认测试账户(划入初始资金)。 +""" + +import threading + +import pytest + +from 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 diff --git a/data/._addOrder.yml b/data/._addOrder.yml new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K1) + - - 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: 余额不足 diff --git a/data/cancelOrder.yml b/data/cancelOrder.yml new file mode 100644 index 0000000..00f53df --- /dev/null +++ b/data/cancelOrder.yml @@ -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 diff --git a/data/formula.yml b/data/formula.yml new file mode 100644 index 0000000..dd034a3 --- /dev/null +++ b/data/formula.yml @@ -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} diff --git a/data/liquidation.yml b/data/liquidation.yml new file mode 100644 index 0000000..12fb1ab --- /dev/null +++ b/data/liquidation.yml @@ -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' diff --git a/docs/._architecture.svg b/docs/._architecture.svg new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^Kpytest 用例层(case/)test_order_freeze.py下单冻结保证金(三重校验,正例/负例数据驱动)test_cancel_order.py撤单解冻(状态机/参数/无副作用)test_position_open.py市价开仓成交(仓位/资金/流水/缓存四面对账)test_liquidation.py强平触发校验(行情驱动到强平价,风险基金流水)test_formula.py合约公式层纯函数单测(期望值手算写死防自证)YAML 数据驱动期望值data/*.ymladdOrder.yml / liquidation.ymlcancelOrder.yml / formula.ymlformula/contract_formula冻结保证金 / 强平价 / 破产价未实现盈亏 / 爆仓判断HTTP 调用(用例不直接拼 URL)期望值 vs 实际值框架层(framework/)接口封装 / YAML 读取 / Decimal 断言 / 工程配置requests(HTTP)被测系统(mock/)server.pywsgiref HTTP 服务(随机端口,conftest 会话级启动)engine.py撮合引擎:下单冻结 / 市价成交 / 撤单解冻 / 标记价 / 强平风控(内部资金计算独立实现,刻意不复用 formula 包)校验面(数据面)fake_db.py 内存 MySQL:futures_account / order / account_flowfake_cache.py 内存 Redis:冻结键值 / 资金镜像 / 仓位缓存 \ No newline at end of file diff --git a/formula/.___init__.py b/formula/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K Decimal: + """把任意数值(含字符串形式的数值)转为 Decimal。 + + 走 ``str()`` 而非 ``Decimal(float)``,避免 float 先行引入精度误差。 + """ + if isinstance(value, Decimal): + return value + return Decimal(str(value)) + + +def side_to_direction(side) -> int: + """把下单方向(bid/ask 或 1/2)规整为持仓方向 1(多)/ -1(空)。""" + if side in ("bid", "BUY", 1, "1"): + return SIDE_LONG + if side in ("ask", "SELL", 2, "2"): + return SIDE_SHORT + raise ValueError("非法的持仓方向: %r" % (side,)) + + +def open_value(price, quantity) -> Decimal: + """开仓价值 = 开仓价格 * 数量。""" + return to_decimal(price) * to_decimal(quantity) + + +def init_margin(price, quantity, margin_rate) -> Decimal: + """起始(初始)保证金 = 开仓价值 * 起始保证金率(杠杆倍数取反)。""" + return open_value(price, quantity) * to_decimal(margin_rate) + + +def fee(price, quantity, maker_fee_rate, taker_fee_rate) -> Decimal: + """手续费 = 开仓价值 * max(maker 费率, taker 费率)。 + + 冻结场景按"孰高"预冻结,撮合后按实际角色多退少不补。 + """ + value = open_value(price, quantity) + maker_fee = value * to_decimal(maker_fee_rate) + taker_fee = value * to_decimal(taker_fee_rate) + return max(maker_fee, taker_fee) + + +def frozen_margin(price, quantity, margin_rate, maker_fee_rate, taker_fee_rate) -> Decimal: + """下单冻结保证金 = 起始保证金 + max(maker, taker) 手续费。 + + 对应限价委托进入订单簿后的资金冻结口径。 + """ + return ( + init_margin(price, quantity, margin_rate) + + fee(price, quantity, maker_fee_rate, taker_fee_rate) + ) + + +def maintain_margin(open_price, quantity, maintain_rate) -> Decimal: + """维持保证金 = 开仓价值 * 维持保证金率。""" + return open_value(open_price, quantity) * to_decimal(maintain_rate) + + +def unrealized_pnl(side, open_price, mark_price, quantity) -> Decimal: + """未实现盈亏 = 持仓方向 * (标记价格 - 开仓均价) * 数量。""" + direction = side_to_direction(side) + return direction * (to_decimal(mark_price) - to_decimal(open_price)) * to_decimal(quantity) + + +def margin_balance(extra_margin, side, open_price, mark_price, quantity, margin_rate) -> Decimal: + """逐仓保证金余额 = 额外保证金 + 起始保证金 + 未实现盈亏。""" + return ( + to_decimal(extra_margin) + + init_margin(open_price, quantity, margin_rate) + + unrealized_pnl(side, open_price, mark_price, quantity) + ) + + +def is_burst(extra_margin, side, open_price, mark_price, quantity, + margin_rate, maintain_rate) -> bool: + """爆仓(强平触发)判断:保证金余额 <= 维持保证金 即触发。""" + balance = margin_balance(extra_margin, side, open_price, mark_price, quantity, margin_rate) + return balance <= maintain_margin(open_price, quantity, maintain_rate) + + +def bankruptcy_price(side, open_price, quantity, margin_rate, extra_margin="0") -> Decimal: + """破产价格:保证金余额恰好归零时的标记价格(逐仓口径)。 + + 做多: p = open * (1 - margin_rate) - extra / qty + 做空: p = open * (1 + margin_rate) + extra / qty + """ + open_price = to_decimal(open_price) + quantity = to_decimal(quantity) + margin_rate = to_decimal(margin_rate) + extra = to_decimal(extra_margin) + if side_to_direction(side) == SIDE_LONG: + return open_price * (1 - margin_rate) - extra / quantity + return open_price * (1 + margin_rate) + extra / quantity + + +def liquidation_price(side, open_price, quantity, margin_rate, + maintain_rate, extra_margin="0") -> Decimal: + """强平价格:保证金余额恰好等于维持保证金时的标记价格(逐仓口径)。 + + 令 extra + init + upnl(mark) == maintain,反解 mark: + mark = open + direction * (maintain - extra - init) / qty + 标记价格越过该价位(沿亏损方向)即触发强平。 + """ + direction = side_to_direction(side) + open_price = to_decimal(open_price) + quantity = to_decimal(quantity) + init = init_margin(open_price, quantity, margin_rate) + maintain = maintain_margin(open_price, quantity, maintain_rate) + gap = (maintain - to_decimal(extra_margin) - init) / quantity + return open_price + direction * gap diff --git a/framework/.___init__.py b/framework/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K=7.0 +pytest-cov>=4.0 +requests>=2.25 +PyYAML>=5.4