惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Proofpoint News Feed
宝玉的分享
宝玉的分享
人人都是产品经理
人人都是产品经理
博客园_首页
爱范儿
爱范儿
博客园 - 叶小钗
aimingoo的专栏
aimingoo的专栏
S
SegmentFault 最新的问题
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
Microsoft Security Blog
Microsoft Security Blog
Blog — PlanetScale
Blog — PlanetScale
博客园 - 【当耐特】
Y
Y Combinator Blog
量子位
博客园 - 三生石上(FineUI控件)
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
The Blog of Author Tim Ferriss
月光博客
月光博客
有赞技术团队
有赞技术团队
Apple Machine Learning Research
Apple Machine Learning Research
A
About on SuperTechFans

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Perpetual Engine Series Part 3: Funding Rates
Sumana · 2026-05-02 · via DEV Community

In Part 2, we built the "heartbeat" of our engine: PnL Calculation. We ensured that every price tick accurately updates a trader’s equity with decimal precision. But a market cannot survive on price action alone. Without an anchor, the price of a perpetual contract would drift aimlessly away from the actual value of the underlying asset.

That anchor is Funding Rates. It is the regulatory mechanism that ensures the perpetual market remains fair, balanced, and tethered to reality. Here is how I implemented this "incentive engine" in Rust.


1. What are Funding Rates? (The Market’s Anchor)

In perpetual futures, there is no expiration date. To prevent the contract price from deviating too far from the Spot Price, the system uses a peer-to-peer payment exchange.

  • When Longs dominate (Bullish): Perpetual Price > Spot Price. Longs pay Shorts.
  • When Shorts dominate (Bearish): Perpetual Price < Spot Price. Shorts pay Longs.

This is a zero-sum game. The exchange doesn't keep the money; it simply moves it between traders to incentivize the side that helps bring the price back to equilibrium.


2. The Math: Notional Value & Payments

The funding payment isn't based on your margin; it’s based on your Notional Value (your total market exposure).

The Formulas:
Notional Value = Quantity \times Mark Price
Funding Payment = Notional Value \times Funding Rate

The Reality Check: If you are 10x leveraged, a 0.01% hourly funding rate actually costs you 0.1% of your margin every hour. Over a day, that’s 2.4% of your collateral just to keep the position open.


3. The Implementation: A Periodic Loop

In my Rust engine, funding is a discrete event. While PnL updates with every price tick, funding applies on a scheduled "heartbeat" (typically every hour).

Rust Implementation

pub fn apply_funding(&mut self) -> Result<FundingResult, String> {
    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 })
}

Enter fullscreen mode Exit fullscreen mode


4. The "Silent Killer": Funding-Triggered Liquidation

This is the most critical integration point between Part 1 (Liquidations) and Part 3. A position can be liquidated even if the price doesn't move.

If a trader is at max leverage and has very little "maintenance margin" left, a single funding payment can push their PnL into the red, triggering an immediate liquidation.

The Logic Flow:

  1. Trigger: Timer hits 3600 seconds.
  2. Apply: Subtract/Add funding from all open positions' PnL.
  3. Audit: Immediately run the should_liquidate check.
  4. Execute: Close positions that no longer meet margin requirements.

5. Multi-User Scalability with Tokio

In a production-ready engine, you can't block the order book to calculate funding. I used tokio::time::interval to run the funding logic in a background task, ensuring the engine remains responsive.

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?;
    }
});

Enter fullscreen mode Exit fullscreen mode


6. Summary Table

Concept What Why
Funding Rate % paid between traders Keeps Perp price near Spot price.
Notional Value Qty \times Price Ensures fees scale with total market exposure.
Zero-Sum Longs pay Shorts (or vice versa) The exchange remains a neutral facilitator.
Liquidation Risk Margin erosion via fees High leverage can be killed by funding alone.

Conclusion

Funding rates turn a simple "betting" engine into a sophisticated financial instrument. By implementing this in Rust, we leverage thread safety to ensure that while thousands of trades are happening, the "funding heartbeat" accurately adjusts every balance without a single cent going missing.