119 lines
5.4 KiB
Python
119 lines
5.4 KiB
Python
"""场景二:市价开仓成交 —— 仓位与资金变动的 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 # 未越过强平价,不应强平
|