Perpetual Engine 系列 第3部分:融资利率
Source: Dev.to
介绍

在 第 2 部分 中,我们构建了引擎的“心跳”:盈亏计算。我们确保每一次价格跳动都能以小数精度准确更新交易者的权益。但仅靠价格行为,市场是无法存活的。若没有锚点,永续合约的价格将会毫无方向地偏离标的资产的实际价值。
这个锚点就是 资金费率。它是一种监管机制,确保永续市场保持公平、平衡,并与现实挂钩。下面是我在 Rust 中实现这个“激励引擎”的方式。
1. 什么是资金费率?(市场的锚点)
在永续合约中没有到期日。为防止合约价格与 Spot Price 偏离过大,系统采用点对点的付款交换机制。
- 当多头占优势(看涨)时: 永续价格 > 现货价格 → 多头支付给空头。
- 当空头占优势(看跌)时: 永续价格 < 现货价格 → 空头支付给多头。
Implementation in Rust
Result {
let rate = self.funding_rate; // e.g., 0.0001 for 0.01%
let mut total_applied = Decimal::ZERO;
for position in self.positions.values_mut() {
let notional_value = position.quantity * self.mark_price;
let funding_amount = notional_value * rate;
// Longs pay when rate is positive, Shorts receive
if position.position_type == PositionType::Long {
position.pnl -= funding_amount;
total_applied += funding_amount;
} else {
position.pnl += funding_amount;
total_applied -= funding_amount;
}
}
self.last_funding_time = std::time::Instant::now();
Ok(FundingResult { total_applied, rate })
}
4. “沉默的杀手”:资金触发的清算
这是第 1 部分(Liquidations)和第 3 部分之间最关键的集成点。即使价格没有波动,仓位也可能被清算。
如果交易者已使用最大杠杆且剩余的“maintenance margin”极少,一笔资金费用就可能把其 PnL 推入亏损,从而触发立即清算。
Logic Flow
- Trigger: Timer hits 3600 seconds.
- Apply: Subtract/add funding from all open positions’ PnL.
- Audit: Immediately run the
should_liquidatecheck. - Execute: Close positions that no longer meet margin requirements.
5. 多用户可扩展性与 Tokio
在面向生产的引擎中,不能阻塞订单簿来计算资金。使用 tokio::time::interval 可以在后台任务中运行资金逻辑,从而保持引擎的响应性。
后台任务
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(3600));
loop {
interval.tick().await;
// Acquire write lock and apply funding to all users
engine.apply_funding().await?;
}
});
6. 摘要表
| 概念 | 内容 | 原因 |
|---|---|---|
| Funding Rate | 交易者之间支付的百分比 | 使永续合约价格接近现货价格。 |
| Notional Value | 数量 × 价格 | 确保费用随整体市场敞口成比例。 |
| Zero‑Sum | 多头支付给空头(或反之) | 交易所保持中立的撮合角色。 |
| Liquidation Risk | 通过费用导致保证金侵蚀 | 高杠杆可能仅因资金费率而被清算。 |
结论
Funding rates 将一个简单的“betting” 引擎转变为复杂的金融工具。通过在 Rust 中实现它,我们利用 thread safety 来确保在成千上万的交易进行时,“funding heartbeat” 能够准确地调整每个余额,且没有一分钱会丢失。