Funding Rate Specification

Funding Rate Specification

Overview

Kyan implements a continuous funding mechanism to ensure perpetual contract prices converge to their underlying index prices. The funding system operates through hourly settlement windows with minute-level rate calculations.

Funding Rate Calculation

Premium Index Component

The premium index measures the difference between perpetual and spot prices:

Premium Index (PI) = (Perpetual Price - Index Price) / Index Price

Where:

  • Perpetual Price: Current mark price of the perpetual contract
  • Index Price: Spot price from price feeds
  • Premium Index: Normalized price difference (percentage)

Funding Rate Formula

The funding rate is calculated using a simplified premium-based model:

Adjusted Premium = Premium Index × Premium Decay Factor
Funding Rate = clamp(Adjusted Premium, -Max Rate, +Max Rate)

Default Configuration:

  • Premium Decay Factor: 0.9 (90%)
  • Maximum Rate: ±1.0% per funding interval
  • Update Frequency: Calculated every minute, settled hourly

Price Discovery and Fallback Logic

Perpetual Price Determination

The system uses a hierarchical approach to determine perpetual prices with robust fallback mechanisms:

Primary Method: Orderbook Midpoint

  • Best Bid/Ask: Retrieved from Redis orderbook data (orders:{instrument}:buy and orders:{instrument}:sell)
  • Spread Validation: Maximum allowed spread of 1% relative to index price
  • Price Validation: All prices must be positive, finite numbers

Fallback Scenarios

1. Wide Spread Fallback

If (Ask - Bid) / Index Price > 1%:
    Use Index Price

2. Single-Sided Book

  • Bid Only: Use bid price if above index, otherwise use index price
  • Ask Only: Use ask price if below index, otherwise use index price

3. No Valid Orders

  • Degraded Mode: Fall back to index price
  • Logging: Warn-level alerts for monitoring

Index Price Source

  • Redis Key: index_price:{BASE_ASSET} (e.g., index_price:BTC)
  • Format: JSON with value field containing spot price
  • Validation: Must be positive, finite number

Settlement Mechanism

Funding Windows

  • Interval: 1 hour (24 funding periods per day)
  • Settlement Times: 00:00, 01:00, 02:00, ..., 23:00 UTC
  • Rate Calculation: Time-weighted average over the funding period

Payment Calculation

Funding payments are calculated using the time-weighted average rate for the full hour:

Funding Payment = Position Size × Final Hourly Rate

Parameters:

  • Position Size: Notional value of the perpetual position (in USD)
  • Final Hourly Rate: Time-weighted average of minute-level rates over the funding period
  • Time-Weighted Average: (minute_count × previous_avg + new_rate) / (minute_count + 1)

Settlement Events

Funding settlements are triggered by:

  1. Scheduled Events: Hourly boundaries (detected automatically when current hour > last processed hour)
  2. API Triggers: Manual settlement via /settle_funding_interval endpoint

Payment Direction

Funding Flow

The direction of funding payments depends on the funding rate sign:

  • Positive Funding Rate (Perpetual > Index):
    • Long positions pay funding to short positions
    • Incentivizes shorting to bring price down
  • Negative Funding Rate (Perpetual < Index):
    • Short positions pay funding to long positions
    • Incentivizes buying to bring price up

Real-time Accrual

  • Continuous Tracking: Funding PnL accrues in real-time
  • No Pre-allocation: No upfront funding reserves required
  • Crystallization: Pending funding is settled on position changes

Initialization and Edge Cases

Service Initialization

When the funding service starts for the first time:

Partial Funding Rate Initialization

  • Initial Value: Set to 0.0 for all instruments
  • Redis Key: current_funding:{BASE_ASSET}
  • Timestamp: Current system time
  • Purpose: Ensures stable baseline for time-weighted averaging

Last Hour Initialization

  • Initial Value: Current hour boundary (timestamp - timestamp % 3600)
  • Redis Key: last_funding_hour:{BASE_ASSET}
  • Purpose: Establishes reference point for hour transition detection

Error Recovery and Data Corruption

Corrupted Redis Data

// Automatic reset scenarios:
1. JSON parsing fails → Reset rate to 0.0, keep timestamp
2. Null/undefined values → Reset rate to 0.0, keep timestamp  
3. Invalid rates (NaN, infinite, >100%) → Reset rate to 0.0
4. Missing data entirely → Initialize with 0.0 rate

Stale Data Detection

  • Threshold: 2 hours (7200 seconds)
  • Action: Automatic reset of funding data
  • Logging: Warning-level alerts for monitoring

Invalid Price Data

  • Validation: All prices must be positive, finite numbers
  • Fallback Chain: Orderbook → Index Price → Service Error
  • Logging: Error-level alerts for invalid index prices

Hour Transition Edge Cases

Clock Synchronization

  • Detection: current_hour > last_processed_hour
  • Settlement: Process all pending funding before advancing hour
  • Reset: Partial funding rate returns to 0.0 for new hour

Missed Hours

  • Gap Detection: Hour difference > 1
  • Recovery: Process each missed hour with last known rate
  • Logging: Alert-level notifications for missed intervals

Technical Implementation

Rate Smoothing

To prevent funding rate manipulation:

  • Time-weighted averaging using running average calculation over the funding period
  • Premium decay factor (0.9) to smooth rate transitions
  • Rate capping at ±1.0% maximum per interval

Data Storage & Processing

  • Minute-level calculation: Rate computed every minute via /compute_minutely_funding
  • PostgreSQL: Position data and accrued funding balances
  • BigQuery: Historical funding rate data with timestamp, prices, and calculated rates
  • Redis: Partial funding rates and processing state tracking

Data Validation Pipeline

  1. Input Validation: Price positivity, finiteness checks
  2. Spread Validation: Maximum 1% spread tolerance

Error Handling Strategy

  • Graceful Degradation: Always fall back to index price when orderbook unavailable
  • Automatic Recovery: Reset corrupted data without manual intervention
  • Comprehensive Logging: Structured logs for debugging and monitoring
  • Circuit Breaker: Invalid data triggers safe mode (0% funding rate)

Processing Flow

  1. Minute Processing: Calculate instant rate, update time-weighted average
  2. Hour Detection: Monitor for hour boundary transitions
  3. Settlement Trigger: Process all active perpetual positions when hour completes
  4. Balance Update: Adjust accrued_funding in margin accounts
  5. State Reset: Initialize partial funding rate to 0.0 for new hour
  6. Error Recovery: Validate and clean invalid states automatically

API Integration

Available Endpoints

  • POST /compute_minutely_funding: Triggers minute-level rate calculation
  • POST /settle_funding_interval: Triggers hourly settlement process
  • Both endpoints return HTTP 202 (Accepted) for async processing

Supported Instruments

  • BTC_USDC-PERPETUAL: Bitcoin perpetual futures
  • ETH_USDC-PERPETUAL: Ethereum perpetual futures

Data Sources

  • Perpetual Prices: Primary: Orderbook midpoint from Redis (orders:{instrument}:buy/sell)
  • Fallback Logic: Index price when orderbook invalid/unavailable
  • Index Prices: Spot price feeds for underlying assets (index_price:{BASE_ASSET})
  • Validation: All prices validated for positivity and finiteness
  • Monitoring: Structured logging for price source usage and fallbacks