Perpetual Trading

Perpetual Trading Engine: How the Liquidation, ADL & Funding Systems Work

Technical architecture of a production perpetual trading engine -- liquidation cascade mechanics, insurance fund accounting, auto-deleveraging ranking, funding rate formulas, and risk controls. Written for CTOs and engineers evaluating derivatives infrastructure.

Verified Enterprise Features

Our perpetual trading engine includes fully implemented, production-ready risk management:

ComponentStatusImplementation
Insurance FundProduction ReadyPer-asset tracking with contribution/payout history
Auto-Deleveraging (ADL)Production ReadyRank-based selection with user indicators
Liquidation EngineProduction Ready5-second monitoring with partial liquidation
Cross MarginProduction ReadyShared balance across positions
Isolated MarginProduction ReadyDedicated margin per position
Funding RatesProduction Ready8-hour settlement with automatic payments
Mark Price OracleProduction Ready6-exchange aggregation with outlier filtering

These aren’t marketing claims - they’re verified through code audit and database analysis.


What is a Perpetual Trading Engine

A perpetual trading engine is the core system that powers cryptocurrency futures exchanges. Unlike spot trading engines that simply match buyers and sellers, perpetual engines must handle:

  • Leveraged position management
  • Continuous margin monitoring
  • Automated liquidation processing
  • Funding rate calculations
  • Insurance fund operations
  • Auto-deleveraging mechanisms

Our perpetual trading engine provides all these capabilities in a production-ready package.

Core Engine Components

Order Matching

The order book processes incoming orders with deterministic matching:

Matching Logic

  • Price-time priority for fair execution
  • Support for all order types (limit, market, stop, etc.)
  • Immediate-or-cancel and fill-or-kill options
  • Post-only flag for maker orders
  • Reduce-only flag for closing positions

Order Management

  • Real-time order status updates
  • Partial fill handling
  • Order amendment without losing queue position
  • Bulk cancellation capabilities

Position Management

Positions are tracked and updated in real-time:

Position Tracking

  • Entry price calculation (average cost basis)
  • Unrealized and realized P&L
  • Position size in contracts and notional value
  • Liquidation price per position
  • Margin allocation (cross or isolated)

Position Operations

  • Open new positions (long or short)
  • Add to existing positions
  • Reduce or close positions
  • Transfer margin between positions

Margin System

The margin system determines trading capacity and risk:

Margin Calculations

  • Initial margin for opening positions
  • Maintenance margin for holding positions
  • Available margin for new orders
  • Margin ratio (current margin / maintenance)

Margin Modes

  • Cross margin pools all available balance
  • Isolated margin dedicates funds per position
  • Mode switching for existing positions

Liquidation Engine

Production-ready continuous monitoring protects platform solvency:

Liquidation Process

  1. Background worker monitors all positions every 5 seconds
  2. Compares mark price against calculated liquidation price
  3. Position locked for atomic updates when triggered
  4. 1.5% liquidation fee deducted from notional value
  5. Insurance fund receives surplus or covers deficit
  6. WebSocket events published for real-time updates

Partial Liquidation

  • Enabled by default with 25% threshold
  • Large positions liquidated incrementally
  • Reduces market impact during volatility
  • Gives traders time to add margin
  • Configurable threshold per symbol

Insurance Fund

The insurance fund provides loss protection and is fully implemented:

Fund Operations

  • Accumulates surplus from profitable liquidations (50% contribution rate)
  • Covers negative equity when positions liquidate below bankruptcy price
  • Prevents socialized losses - only triggers ADL when fund insufficient
  • Per-asset balance tracking with complete audit trail

Fund Management

  • Automatic contribution from liquidation surplus
  • Automatic payout for negative equity coverage
  • Admin dashboard for fund monitoring and injection
  • Historical tracking with contribution/payout records
  • Alert thresholds for low balance warnings

Auto-Deleveraging (ADL)

When insurance fund is insufficient, fully implemented ADL protects platform solvency:

ADL Mechanism

  1. Calculates ADL score: PnL Percentage × Position Leverage
  2. Ranks all opposing positions by score (highest first)
  3. Deleverages profitable positions to recover losses
  4. Closes at bankruptcy price of liquidated position
  5. Processes up to 10 positions per execution cycle

User Experience

  • 0-5 light indicator showing ADL priority ranking
  • Higher lights = higher chance of deleveraging
  • Real-time WebSocket updates on ranking changes
  • Notification after deleveraging occurs

Funding Rate System

Perpetual price convergence mechanism:

Rate Calculation

  • Computed every 8 hours
  • Based on premium/discount to spot index
  • Clamp mechanisms prevent extreme rates
  • Historical rate data available

Payment Processing

  • Automatic collection from paying side
  • Distribution to receiving side
  • No platform fee on funding
  • Applied to all open positions

Mark Price Oracle

Fair price for liquidation calculations:

Price Sources

  • Aggregated from major spot exchanges
  • Outlier filtering for manipulation resistance
  • Time-weighted averaging
  • Fallback mechanisms for outages

Usage

  • Liquidation trigger price
  • Unrealized P&L display
  • Separate from last traded price
  • Protects against wicks

Admin Capabilities

Symbol Configuration

  • Create perpetual contracts
  • Set leverage brackets
  • Configure margin requirements
  • Define position limits
  • Enable/disable trading

Risk Dashboard

  • Platform exposure monitoring
  • Large position alerts
  • Liquidation queue visibility
  • Insurance fund status
  • System health metrics

Manual Intervention

  • Force-close positions
  • Adjust user balances
  • Modify leverage limits
  • Pause trading markets
  • Insurance fund injection

Integration APIs

Trading API

  • Order placement and management
  • Position queries
  • Account balance information
  • Trade history retrieval

Market Data API

  • Real-time price streams
  • Order book snapshots
  • Recent trades feed
  • Funding rate information

Admin API

  • User management operations
  • Symbol configuration
  • Risk parameter adjustment
  • Report generation

Deployment

The perpetual trading engine deploys alongside spot trading or as a standalone system. It shares user accounts and wallet infrastructure with other modules for a unified platform experience.

Contact us for a technical deep-dive and live demonstration of the perpetual trading engine.

Frequently Asked Questions

What makes a perpetual trading engine different from spot trading?
Perpetual trading engines handle leverage, margin calculations, position tracking, liquidation, and funding rate mechanisms. Unlike spot trading where you simply exchange assets, perpetual engines must continuously monitor positions and execute liquidations to maintain platform solvency.
How fast is order matching?
The engine processes orders with price-time priority at high throughput. Order matching occurs in real-time with position updates reflected immediately in user interfaces and API responses.
Can the engine handle market volatility?
Yes. The engine is designed for extreme market conditions with circuit breakers, position limits, and auto-deleveraging systems. The liquidation engine can process high volumes of positions during market crashes without system degradation.
Is the funding rate calculation automatic?
Funding rates are calculated and applied automatically every 8 hours. The system handles payment collection and distribution between long and short traders without manual intervention.
Can I modify the leverage tiers?
Yes. Leverage tiers, maintenance margin rates, and position limits are all configurable through the admin panel. You can set different parameters for each trading pair.

Ready to Launch Your Exchange?

Get a personalized demo and see how Codono can power your crypto exchange business.