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.

100+ Exchanges Deployed
30+ Countries
50+ Blockchains
4.9/5 Operator Rating

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

Performance Benchmarks and Stress Testing

The perpetual trading engine has been benchmarked under simulated market crash conditions to validate its behavior under extreme load:

MetricNormal LoadPeak Load (10x)Stress Test (50x)
Order processing throughput5,000 orders/sec25,000 orders/sec50,000+ orders/sec
Order-to-trade latency<3ms<8ms<15ms
Liquidation scan cycle5 seconds5 seconds5 seconds
Mark price update frequency1 second1 second1 second
WebSocket broadcast latency<10ms<50ms<100ms
Concurrent open positions100,000+100,000+100,000+

The engine maintains liquidation scan consistency regardless of load — positions are evaluated every 5 seconds whether the system is processing 100 or 50,000 orders per second. This deterministic behavior is critical during cascading liquidation events when the engine is under maximum stress.

Failure Scenarios and Recovery

A production perpetual trading engine must handle every failure gracefully. Here’s how each scenario is managed:

Insurance fund depletion: If the insurance fund balance drops to zero during a liquidation cascade, the ADL (auto-deleveraging) system activates automatically. Profitable counter-positions are ranked by PnL % × leverage and closed against the bankrupt position. No losses are ever socialized across all users — only the specific ADL-targeted positions are affected.

Mark price oracle failure: If one or more of the 6 reference exchanges becomes unreachable, the mark price calculation excludes the unavailable source and continues with remaining exchanges. If fewer than 3 sources are available, the engine falls back to the exchange’s own last traded price with additional safety margins on liquidation thresholds.

Database failover: The engine writes all position and order state to the primary database with synchronous replication to a standby. On primary failure, the standby promotes automatically. No open positions are lost, no pending orders are dropped. The recovery time objective (RTO) is under 30 seconds.

Network partition: If the API layer loses connectivity to the matching engine, all new order submissions are rejected with a clear error message. Existing positions and pending orders remain intact. The system resumes normal operation automatically when connectivity is restored.

Real-World Example: Liquidation Cascade Walkthrough

Here’s a concrete example of how the engine processes a cascading liquidation event:

  1. Trigger: BTC/USDT drops from $60,000 to $54,000 (-10%) in 15 minutes
  2. Detection: Mark price updates catch the move within 1 second via 6-exchange median
  3. Scan: Liquidation engine identifies 847 positions below maintenance margin threshold
  4. Partial liquidation: 612 positions are partially liquidated (25% per cycle) — enough to bring them above maintenance margin
  5. Full liquidation: 235 positions require full liquidation at their bankruptcy prices
  6. Insurance fund: Absorbs $127,000 in losses (gap between liquidation and bankruptcy prices), fund balance remains positive
  7. ADL: Not triggered — insurance fund was sufficient
  8. Total time: 4 liquidation scan cycles (20 seconds) to process all 847 positions
  9. User notifications: All affected users received push notifications within 2 seconds of liquidation

Why Perpetual Contracts Dominate Crypto Derivatives

Perpetual futures contracts account for over 75% of all crypto trading volume globally — far exceeding spot markets. Unlike traditional futures that expire on specific dates, perpetuals have no expiry, making them the preferred instrument for both retail traders seeking leverage and institutional market makers seeking hedging tools.

For exchange operators, perpetuals represent the highest-revenue product per user. A trader using 20x leverage generates 20x the notional volume compared to the same trader in spot markets, dramatically increasing fee revenue. The funding rate mechanism (settled every 8 hours) creates an additional revenue stream that has no equivalent in spot trading — the exchange collects fees from every open position, whether the trader is actively trading or not.

The technical barrier to offering perpetuals is also the competitive moat. Building a reliable perpetual trading engine requires solving liquidation cascades, mark price manipulation resistance, insurance fund management, and auto-deleveraging — problems that take years of production testing to get right. Operators using Codono’s verified perpetual engine skip this development entirely and launch with infrastructure that has already survived real market crashes.

Deployment

The perpetual trading engine deploys alongside spot trading or as a standalone derivatives platform. It shares user accounts and wallet infrastructure with other Codono modules for a unified platform experience. The engine is included in all Codono licenses — contact us for a technical deep-dive or explore the live demo to see it in action.

Trusted by Exchange Operators Worldwide

Real feedback from licensed operators running production exchanges on Codono infrastructure.

We launched our exchange in Dubai within 3 weeks. The margin trading module handled our VARA compliance requirements without issues.

Ahmed K. Exchange Operator, Dubai

Production-grade software. We process $8M daily volume across spot and futures. The liquidity aggregation solved our cold-start problem.

Carlos M. CTO, Latin America

Full source code ownership was the deciding factor. Our team customized the KYC flow for our market in under two weeks.

Priya S. Founder, Southeast Asia

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.

No credit card required. Full-access demo environment.