refactor: 字段与接口路径改用中性演示命名,并扩充下单用例矩阵

This commit is contained in:
2026-09-21 22:38:59 +08:00
parent 4f39f6cef2
commit e3afd2e46c
8 changed files with 389 additions and 105 deletions
+5 -5
View File
@@ -8,11 +8,11 @@ from common.http_client import Adapter
class OrderApi:
ADD_ORDER = "/api/futures/addOrder"
CANCEL_ORDER = "/api/futures/cancelOrder"
TRANSFER_IN = "/api/future/user/transferIn"
SET_MARK_PRICE = "/api/future/mark/setMarkPrice"
RISK_CHECK = "/api/future/risk/check"
ADD_ORDER = "/api/v1/orders"
CANCEL_ORDER = "/api/v1/orders/cancel"
TRANSFER_IN = "/api/v1/account/transfer"
SET_MARK_PRICE = "/api/v1/market/mark-price"
RISK_CHECK = "/api/v1/risk/check"
def __init__(self):
self.adapter = Adapter()
+13 -13
View File
@@ -4,9 +4,9 @@
- 安全价(未越界)→ 风控检查不触发,仓位保持持仓;
- 触发价(恰好等于或越过强平价)→ 触发强平,核对:
- position 状态置为已强平;
- force_close_record 落库,破产价与公式一致;
- risk_fund_flow 落库,金额 == 触发时保证金余额(穿仓为负,由风险基金兜底);
- account_future 释放仓位保证金,穿仓时可用余额扣减缺口;
- liquidation_record 落库,破产价与公式一致;
- risk_fund_ledger 落库,金额 == 触发时保证金余额(穿仓为负,由风险基金兜底);
- futures_account 释放仓位保证金,穿仓时可用余额扣减缺口;
- 缓存仓位键删除。
场景数据由 data/liquidation.yml 驱动。
@@ -39,11 +39,11 @@ def test_liquidation_trigger(base_url, trader, db, cache, scenario):
# 市价开仓(按初始标记价成交)
body = order_api.add_order(base_url, **{
"userId": trader, "contractId": 1, "side": side, "positionEffect": 1,
"orderType": 2, "quantity": quantity, "durationQualifiers": "GTC",
"orderType": 2, "quantity": quantity, "timeInForce": "GTC",
"marginType": 2, "marginRate": margin_rate, "orderSourceType": 1,
})
assert body["code"] == 0
account_after_open = dict(db.select("account_future", user_id=trader)[0])
account_after_open = dict(db.select("futures_account", user_id=trader)[0])
# 公式层独立计算强平价与破产价(期望值)
liq_price = formula.liquidation_price(
@@ -56,7 +56,7 @@ def test_liquidation_trigger(base_url, trader, db, cache, scenario):
assert result["code"] == 0
assert result["data"]["liquidated"] == []
assert result["data"]["positions"][0]["burst"] is False
assert db.select("force_close_record", user_id=trader) == []
assert db.select("liquidation_record", user_id=trader) == []
position = db.select("position", user_id=trader, contract_id=1)[0]
assert position["status"] == 1 # 仍持仓
# 风控返回的保证金余额与公式一致
@@ -83,32 +83,32 @@ def test_liquidation_trigger(base_url, trader, db, cache, scenario):
assert position["status"] == 9
# 强平记录:破产价与公式一致
records = db.select("force_close_record", user_id=trader)
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_flow", user_id=trader)
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("user_currency_flow", user_id=trader, type=9)[0]["quantity"],
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("account_future", user_id=trader)[0]
assert_decimal_equal(account["isolated_position_margin"],
account_after_open["isolated_position_margin"] - init)
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("account_future:userId:%s:currencyId:1" % trader))
cache.get("futures_account:userId:%s:currencyId:1" % trader))
assert_decimal_equal(cached_account["totalMoney"], account["total_money"])
# 响应中的破产价同样与公式一致
+31 -31
View File
@@ -4,11 +4,11 @@
1. HTTP 响应:code / msg / orderNo;
2. 落库校验(MockMySQL):
- order 表:委托字段与入参一致、状态待撮合;
- account_future 表:total_money 扣减冻结额、对应冻结保证金字段增加;
- user_currency_flow 表:新增"冻结"流水,金额与公式期望一致;
- futures_account 表:total_money 扣减冻结额、对应冻结保证金字段增加;
- account_flow 表:新增"冻结"流水,金额与公式期望一致;
3. 缓存校验(MockRedis):
- frozen_margin:userId:*:orderNo:* 键值与公式期望一致;
- account_future 缓存镜像与落库一致(字段命名 camelCase,需归一化比对)。
- order_freeze:userId:*:orderNo:* 键值与公式期望一致;
- futures_account 缓存镜像与落库一致(字段命名 camelCase,需归一化比对)。
期望值全部由 formula 包独立计算(被测引擎不复用该包),数据由
data/addOrder.yml 驱动参数化。
@@ -33,8 +33,8 @@ order_api = OrderApi()
def _frozen_field(margin_type):
"""保证金模式对应的冻结字段:1-全仓 2-逐仓。"""
if int(margin_type) == 1:
return "cross_frozen_position_margin"
return "isolated_frozen_position_margin"
return "cross_frozen_margin"
return "isolated_frozen_margin"
class TestLimitOrderFreeze:
@@ -43,10 +43,10 @@ class TestLimitOrderFreeze:
def test_limit_order_freeze(self, base_url, trader, db, cache,
test_input, expected):
contract = settings.CONTRACTS[test_input["contractId"]]
before = dict(db.select("account_future", user_id=trader)[0])
before = dict(db.select("futures_account", user_id=trader)[0])
# ---- 一重校验:HTTP 响应 ----
resp = adapter.post(base_url + "/api/futures/addOrder", json=test_input)
resp = adapter.post(base_url + "/api/v1/orders", json=test_input)
body = resp.json()
assert body["code"] == expected["code"]
assert body["msg"] == expected["msg"]
@@ -69,54 +69,54 @@ class TestLimitOrderFreeze:
contract["maker_fee_rate"], contract["taker_fee_rate"])
# ---- 二重校验(2):资金表扣减与冻结 ----
after = db.select("account_future", user_id=trader)[0]
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("user_currency_flow", order_no=order_no, type=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 = "frozen_margin:userId:%s:orderNo:%s" % (trader, order_no)
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 = "account_future:userId:%s:currencyId:1" % trader
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["crossFrozenPositionMargin"],
after["cross_frozen_position_margin"])
cached_account["crossFrozenMargin"],
after["cross_frozen_margin"])
assert_decimal_equal(
cached_account["isolatedFrozenPositionMargin"],
after["isolated_frozen_position_margin"])
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("account_future", user_id=trader)[0])
before = dict(db.select("futures_account", user_id=trader)[0])
resp = adapter.post(base_url + "/api/futures/addOrder", json=test_input)
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("user_currency_flow") == 1 # 仅初始划入的一条流水
assert dict(db.select("account_future", user_id=trader)[0]) == before
assert cache.keys("frozen_margin:*") == []
assert db.count("account_flow") == 1 # 仅初始划入的一条流水
assert dict(db.select("futures_account", user_id=trader)[0]) == before
assert cache.keys("order_freeze:*") == []
def test_cancel_order_unfreeze(self, base_url, trader, db, cache):
"""撤单解冻:资金全额退回、订单置为已撤销、冻结缓存键删除。"""
contract = settings.CONTRACTS[1]
order_param = {
"userId": trader, "contractId": 1, "side": "bid", "positionEffect": 1,
"price": 100, "quantity": 10, "orderType": 1, "durationQualifiers": "GTC",
"price": 100, "quantity": 10, "orderType": 1, "timeInForce": "GTC",
"marginType": 1, "marginRate": "0.01", "orderSourceType": 1,
}
body = order_api.add_order(base_url, **order_param)
@@ -125,8 +125,8 @@ class TestLimitOrderFreeze:
expect_frozen = formula.frozen_margin(
100, 10, "0.01", contract["maker_fee_rate"], contract["taker_fee_rate"])
frozen_key = "frozen_margin:userId:%s:orderNo:%s" % (trader, order_no)
after_order = dict(db.select("account_future", user_id=trader)[0])
frozen_key = "order_freeze:userId:%s:orderNo:%s" % (trader, order_no)
after_order = dict(db.select("futures_account", user_id=trader)[0])
cancel = order_api.cancel_order(base_url, trader, 1, order_no)
assert cancel["code"] == 0
@@ -134,17 +134,17 @@ class TestLimitOrderFreeze:
# 落库:订单状态已撤销,资金全额退回
order = db.select("order", order_no=order_no)[0]
assert order["status"] == 3 # 3-已撤销
account = db.select("account_future", user_id=trader)[0]
account = db.select("futures_account", user_id=trader)[0]
assert_decimal_equal(account["total_money"],
after_order["total_money"] + expect_frozen)
assert_decimal_equal(account["cross_frozen_position_margin"],
after_order["cross_frozen_position_margin"] - expect_frozen)
assert_decimal_equal(account["cross_frozen_margin"],
after_order["cross_frozen_margin"] - expect_frozen)
# 解冻流水
flows = db.select("user_currency_flow", order_no=order_no, type=4)
flows = db.select("account_flow", order_no=order_no, type=4)
assert len(flows) == 1
assert_decimal_equal(flows[0]["quantity"], expect_frozen)
# 缓存:冻结键删除,资金镜像回退
assert cache.get(frozen_key) is None
cached = json.loads(cache.get("account_future:userId:%s:currencyId:1" % trader))
assert_decimal_equal(cached["crossFrozenPositionMargin"],
account["cross_frozen_position_margin"])
cached = json.loads(cache.get("futures_account:userId:%s:currencyId:1" % trader))
assert_decimal_equal(cached["crossFrozenMargin"],
account["cross_frozen_margin"])
+10 -10
View File
@@ -3,8 +3,8 @@
市价单按标记价格立即成交,校验:
- order 表:状态全部成交、成交量;
- position 表:方向/数量/开仓均价;
- account_future 表:仓位保证金占用、手续费扣减(期望值由公式层独立计算);
- user_currency_flow 表:手续费(5)与开仓(7)两条流水;
- futures_account 表:仓位保证金占用、手续费扣减(期望值由公式层独立计算);
- account_flow 表:手续费(5)与开仓(7)两条流水;
- 缓存:仓位键与资金镜像;
- 行情联动:标记价格变化后,风控接口返回的保证金余额与公式一致。
"""
@@ -25,7 +25,7 @@ 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, "durationQualifiers": "GTC",
"orderType": 2, "quantity": 10, "timeInForce": "GTC",
"marginType": 2, "marginRate": margin_rate, "orderSourceType": 1,
}
@@ -35,7 +35,7 @@ class TestMarketOrderOpen:
def test_open_long_position(self, base_url, trader, db, cache):
"""做多开仓:仓位/资金/流水/缓存四面对账。"""
contract = settings.CONTRACTS[1]
before = dict(db.select("account_future", user_id=trader)[0])
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
@@ -62,18 +62,18 @@ class TestMarketOrderOpen:
contract["maker_fee_rate"], contract["taker_fee_rate"])
# 资金:total 扣(保证金+手续费),逐仓保证金占用增加
account = db.select("account_future", user_id=trader)[0]
assert_decimal_equal(account["isolated_position_margin"],
before["isolated_position_margin"] + expect_init)
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("user_currency_flow", order_no=order_no, type=5)[0]["quantity"],
db.select("account_flow", order_no=order_no, type=5)[0]["quantity"],
expect_fee)
assert_decimal_equal(
db.select("user_currency_flow", order_no=order_no, type=7)[0]["quantity"],
db.select("account_flow", order_no=order_no, type=7)[0]["quantity"],
expect_init)
# 缓存:仓位键与资金镜像
@@ -82,7 +82,7 @@ class TestMarketOrderOpen:
assert cached_position["side"] == "1"
assert_decimal_equal(cached_position["avgPrice"], position["avg_price"])
cached_account = json.loads(
cache.get("account_future:userId:%s:currencyId:1" % trader))
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):
+259 -20
View File
@@ -11,7 +11,7 @@ creatOrderTrueTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -25,7 +25,7 @@ creatOrderTrueTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -39,7 +39,7 @@ creatOrderTrueTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 2
marginRate: '0.01'
orderSourceType: 1
@@ -53,12 +53,167 @@ creatOrderTrueTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.005'
orderSourceType: 1
- code: 0
msg: OK
# ---- 矩阵扩充:全仓/逐仓 × 多空 × 起始保证金率三档(0.005/0.02/0.05) ----
# 全仓-卖出-0.005(20 倍杠杆)
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.005'
orderSourceType: 1
- code: 0
msg: OK
# 全仓-买入-0.02(50 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.02'
orderSourceType: 1
- code: 0
msg: OK
# 全仓-卖出-0.02
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.02'
orderSourceType: 1
- code: 0
msg: OK
# 全仓-买入-0.05(20 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.05'
orderSourceType: 1
- code: 0
msg: OK
# 全仓-卖出-0.05
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 1
marginRate: '0.05'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-买入-0.005(20 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.005'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-卖出-0.005
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.005'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-买入-0.02(50 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.02'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-卖出-0.02
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.02'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-买入-0.05(20 倍杠杆)
- - userId: 1001
contractId: 1
side: bid
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.05'
orderSourceType: 1
- code: 0
msg: OK
# 逐仓-卖出-0.05
- - userId: 1001
contractId: 1
side: ask
positionEffect: 1
price: 100
quantity: 10
orderType: 1
timeInForce: GTC
marginType: 2
marginRate: '0.05'
orderSourceType: 1
- code: 0
msg: OK
creatOrderFalseTestdata:
# userId 非数值
@@ -69,7 +224,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -83,7 +238,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -97,7 +252,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -111,7 +266,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -125,7 +280,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -139,7 +294,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -153,7 +308,7 @@ creatOrderFalseTestdata:
price: ''
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -167,7 +322,7 @@ creatOrderFalseTestdata:
price: -1
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -181,7 +336,7 @@ creatOrderFalseTestdata:
price: abc
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -195,7 +350,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 0
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -209,7 +364,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 5
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '0.01'
orderSourceType: 1
@@ -223,7 +378,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 3
marginRate: '0.01'
orderSourceType: 1
@@ -237,7 +392,7 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: GTC
timeInForce: GTC
marginType: 1
marginRate: '2'
orderSourceType: 1
@@ -251,12 +406,12 @@ creatOrderFalseTestdata:
price: 100
quantity: 10
orderType: 1
durationQualifiers: SDFSDF
timeInForce: SDFSDF
marginType: 1
marginRate: '0.01'
orderSourceType: 1
- code: 1003
msg: "参数错误:durationQualifiers"
msg: "参数错误:timeInForce"
# 余额不足(冻结金额超过账户资金)
- - userId: 1001
contractId: 1
@@ -265,9 +420,93 @@ creatOrderFalseTestdata:
price: 99999999
quantity: 10
orderType: 1
durationQualifiers: GTC
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: 余额不足
+24
View File
@@ -7,22 +7,42 @@ frozenMargin:
- {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:
# 恰好等于强平价:保证金余额 == 维持保证金,<= 即触发
@@ -30,3 +50,7 @@ isBurst:
- {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}
+21
View File
@@ -24,3 +24,24 @@ liquidationScenarios:
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'
+26 -26
View File
@@ -49,11 +49,11 @@ CURRENCY_ID = 1 # 结算币种(演示固定为 1)
class MatchEngine:
_ROUTES = {
"/api/futures/addOrder": "add_order",
"/api/futures/cancelOrder": "cancel_order",
"/api/future/user/transferIn": "transfer_in",
"/api/future/mark/setMarkPrice": "set_mark_price",
"/api/future/risk/check": "risk_check",
"/api/v1/orders": "add_order",
"/api/v1/orders/cancel": "cancel_order",
"/api/v1/account/transfer": "transfer_in",
"/api/v1/market/mark-price": "set_mark_price",
"/api/v1/risk/check": "risk_check",
}
def __init__(self):
@@ -108,8 +108,8 @@ class MatchEngine:
margin_type = self._to_int(body, "marginType")
if margin_type not in (1, 2):
raise ParamError("marginType")
if body.get("durationQualifiers", "GTC") not in ("GTC", "IOC", "FOK", "GTX"):
raise ParamError("durationQualifiers")
if body.get("timeInForce", "GTC") not in ("GTC", "IOC", "FOK", "GTX"):
raise ParamError("timeInForce")
margin_rate = self._to_decimal(body, "marginRate")
if not Decimal("0") < margin_rate <= Decimal("1"):
raise ParamError("marginRate")
@@ -145,7 +145,7 @@ class MatchEngine:
account[frozen_field] += frozen
self._add_flow(user_id, FLOW_FREEZE, frozen, order_no)
self.cache.set(
"frozen_margin:userId:%s:orderNo:%s" % (user_id, order_no), frozen)
"order_freeze:userId:%s:orderNo:%s" % (user_id, order_no), frozen)
self._sync_account_cache(user_id)
return 0, "OK", {"orderNo": order_no}
@@ -214,7 +214,7 @@ class MatchEngine:
account[frozen_field] -= frozen
order["status"] = ORDER_STATUS_CANCELED
self._add_flow(user_id, FLOW_UNFREEZE, frozen, order_no)
self.cache.delete("frozen_margin:userId:%s:orderNo:%s" % (user_id, order_no))
self.cache.delete("order_freeze:userId:%s:orderNo:%s" % (user_id, order_no))
self._sync_account_cache(user_id)
return 0, "OK", {"contractId": contract_id, "orderNo": order_no}
@@ -278,14 +278,14 @@ class MatchEngine:
# ------------------------------------------------------------------
def init_user(self, user_id, balance):
"""初始化用户合约资金账户并划入初始资金。"""
self.db.insert("account_future", {
self.db.insert("futures_account", {
"user_id": user_id,
"currency_id": CURRENCY_ID,
"total_money": Decimal(str(balance)),
"cross_position_margin": Decimal("0"),
"cross_frozen_position_margin": Decimal("0"),
"isolated_position_margin": Decimal("0"),
"isolated_frozen_position_margin": Decimal("0"),
"cross_margin": Decimal("0"),
"cross_frozen_margin": Decimal("0"),
"isolated_margin": Decimal("0"),
"isolated_frozen_margin": Decimal("0"),
})
self._add_flow(user_id, FLOW_TRANSFER_IN, Decimal(str(balance)), None)
self._sync_account_cache(user_id)
@@ -312,7 +312,7 @@ class MatchEngine:
account["total_money"] += balance
pos["status"] = POSITION_STATUS_LIQUIDATED
self.db.insert("force_close_record", {
self.db.insert("liquidation_record", {
"user_id": user_id,
"contract_id": contract_id,
"position_no": pos["position_no"],
@@ -320,7 +320,7 @@ class MatchEngine:
"bankrupt_price": bankrupt,
"margin_balance": balance,
})
self.db.insert("risk_fund_flow", {
self.db.insert("risk_fund_ledger", {
"user_id": user_id,
"contract_id": contract_id,
"position_no": pos["position_no"],
@@ -337,25 +337,25 @@ class MatchEngine:
})
def _get_account(self, user_id):
rows = self.db.select("account_future", user_id=user_id)
rows = self.db.select("futures_account", user_id=user_id)
return rows[0] if rows else None
@staticmethod
def _margin_field(margin_type):
"""仓位保证金字段:1-全仓 2-逐仓。"""
return "cross_position_margin" if margin_type == 1 else "isolated_position_margin"
return "cross_margin" if margin_type == 1 else "isolated_margin"
@staticmethod
def _frozen_field(margin_type):
"""冻结保证金字段:1-全仓 2-逐仓。"""
if margin_type == 1:
return "cross_frozen_position_margin"
return "isolated_frozen_position_margin"
return "cross_frozen_margin"
return "isolated_frozen_margin"
def _add_flow(self, user_id, flow_type, quantity, order_no):
"""写一条用户资金流水。"""
self._flow_seq += 1
self.db.insert("user_currency_flow", {
self.db.insert("account_flow", {
"id": self._flow_seq,
"user_id": user_id,
"currency_id": CURRENCY_ID,
@@ -368,15 +368,15 @@ class MatchEngine:
"""把资金表行镜像写入缓存(camelCase,模拟缓存与库字段命名不一致)。"""
account = self._get_account(user_id)
self.cache.set(
"account_future:userId:%s:currencyId:%s" % (user_id, CURRENCY_ID),
"futures_account:userId:%s:currencyId:%s" % (user_id, CURRENCY_ID),
json.dumps({
"userId": str(user_id),
"currencyId": str(CURRENCY_ID),
"totalMoney": str(account["total_money"]),
"crossPositionMargin": str(account["cross_position_margin"]),
"crossFrozenPositionMargin": str(account["cross_frozen_position_margin"]),
"isolatedPositionMargin": str(account["isolated_position_margin"]),
"isolatedFrozenPositionMargin": str(account["isolated_frozen_position_margin"]),
"crossMargin": str(account["cross_margin"]),
"crossFrozenMargin": str(account["cross_frozen_margin"]),
"isolatedMargin": str(account["isolated_margin"]),
"isolatedFrozenMargin": str(account["isolated_frozen_margin"]),
}))
def _sync_position_cache(self, user_id, contract_id):