Skip to content

Funding Rate Service

Overview

The Funding Rate Service is a critical component of the Kyan exchange that calculates, accrues, and settles funding rates for perpetual futures contracts. It implements a real-time funding rate system with event-based settlement, replacing the previous model with a more accurate and timely approach that focuses on continuous funding accrual and eliminates pre-allocations.

💡 Beginner Tip: Think of funding rates as the "interest payments" between traders in perpetual futures markets. When the perpetual price is above the spot price, long positions pay shorts (positive rate), and when it's below, shorts pay longs (negative rate). This service calculates these rates and ensures they're applied correctly to all positions.

Features

  • Real-time funding accrual - Continuous calculation without pre-allocations
  • Hourly settlement intervals - More frequent settlements for accurate position valuation
  • Event-triggered settlement - Processes funding at trade events and time-based intervals
  • Premium index calculation - Derives funding rates from market price deviations
  • Trailing average funding - Implements time-weighted average rate calculations
  • Position-level tracking - Maintains unrealized funding PnL per position

Technical Specifications

Core Technology Stack

  • Runtime: Python 3.9+
  • Primary Frameworks: FastAPI, TaskIQ, SQLAlchemy
  • Build System: Poetry with NX
  • Testing: Pytest
  • Formatting: Ruff, Black
  • Database: PostgreSQL (positions), BigQuery (rate history)
  • Version: 0.1.0

Dependencies

  • Core:

  • fastapi - API framework for endpoints

  • taskiq - Background task processing
  • faststream - Stream processing with Redis
  • sqlalchemy/sqlmodel - Database ORM
  • psycopg2-binary - PostgreSQL driver
  • pydantic - Data validation
  • httpx - HTTP client for service communication

  • Testing:

  • pytest - Testing framework

  • pytest-cov - Test coverage

  • Internal Libraries:

  • commons - Shared Python utilities
  • chainpyon - Blockchain interaction utilities

Getting Started

Prerequisites

  • Python 3.9-3.10
  • Poetry package manager
  • PostgreSQL database
  • Redis instance
  • Google Cloud access (for BigQuery)

Environment Setup

# Copy and configure environment variables
cp .env.example .env
# Edit .env with appropriate values

Required environment variables:

DATABASE_URL=postgresql://postgres:postgres@localhost:5432/exchange # Database URL
REDIS_URL=redis://localhost:6379/0 # Redis URL
SEQUENCER_URL=http://localhost:8000 # Sequencer service URL
FUNDING_INTERVAL=1 # Hours between funding rate calculations
MAX_FUNDING_RATE=0.01 # Maximum funding rate magnitude (1%)
INSTRUMENTS=BTC_USDC-PERPETUAL,ETH_USDC-PERPETUAL # Supported instruments

Installation

# Install dependencies
nx run funding:install

# Run tests
nx run funding:test

Development

# Run linting
nx run funding:lint

# Run type checking
nx run funding:typecheck

# Start development server
nx run funding:serve

Service Architecture

Component Overview

┌───────────────┐         ┌───────────────┐         ┌───────────────┐
│               │         │               │         │               │
│  FastAPI      │◄───────►│  TaskIQ       │◄───────►│  PostgreSQL   │
│  Service      │         │  Scheduler    │         │  Database     │
│               │         │               │         │               │
└───────────────┘         └───────────────┘         └───────────────┘
        │                         │                         │
        │                         │                         │
        ▼                         ▼                         ▼
┌───────────────┐         ┌───────────────┐         ┌───────────────┐
│               │         │               │         │               │
│  Redis        │         │  Funding Rate │         │  BigQuery     │
│  Pub/Sub      │         │  Calculator   │         │  Storage      │
│               │         │               │         │               │
└───────────────┘         └───────────────┘         └───────────────┘

Core Components

  1. FastAPI Service (funding/main.py)

  2. API endpoints for triggering calculations

  3. Request validation and handling
  4. Service health monitoring

  5. TaskIQ Scheduler

  6. Scheduled funding rate calculations

  7. Hourly settlement processing
  8. Task queue management

  9. Funding Rate Calculator

  10. Premium index calculation

  11. Time-weighted average rate computation
  12. Rate limiting and validation

  13. Position Manager

  14. SQL-based unrealized funding PnL tracking

  15. Trade-triggered settlement processing
  16. Position state management

  17. Storage Layer

  18. PostgreSQL for position data
  19. BigQuery for funding rate history
  20. Redis for event streaming

Project Structure

funding/
├── funding/              # Source code
│   ├── dependencies/     # Dependency injection
│   ├── models/           # Data models
│   ├── config.py         # Configuration settings
│   ├── main.py           # FastAPI application
│   ├── tasks.py          # Background tasks
│   └── utils.py          # Utility functions
├── tests/                # Test suite
│   ├── test_tasks.py     # Task tests
│   └── test_models.py    # Model tests
├── pyproject.toml        # Poetry configuration
└── pyrightconfig.json    # Type checking configuration

Funding Rate Mechanics

Premium Index (PI)

The Premium Index is calculated every minute using the formula:

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

Time Windows

  • 24 hourly funding windows per day
  • Windows start at the hour (00:00, 01:00, etc.)
  • Settlement occurs at window end or trade events

Settlement Triggers

  1. Trade Events: Position opening/closing, which crystallizes funding
  2. Time Events: Hourly window completion for periodic settlement

Calculation Example

For a position held between 00:30 - 00:36:

Position: 1 BTC at $50,000
Rate at 00:30: 0.01%
Rate at 00:36: 0.02%

Time-weighted average = 0.015%
Funding Payment = Position Size * Contract Value * Time-Weighted Average Rate * (Time Held / Hours in Year)

API Reference

Endpoint Method Description Request Body Response
/private/compute_minutely_funding POST Calculate minute-by-minute funding rates { "timestamp": int } Status 202
/private/settle_funding_interval POST Trigger funding settlement Complex object (see below) Status 202

Settlement request format:

{
  "timestamp": 1714598400,
  "type": "hourly",
  "previous_hour": 1714594800,
  "final_rate": 0.0001,
  "instrument": "BTC_USDC-PERPETUAL"
}

Integration Points

External Dependencies

  • Sequencer Service: Account position data
  • Datastream Service: Index price feeds
  • BigQuery: Historical rate storage

Internal Dependencies

  • Risk Engine: Uses funding data for liquidation calculations
  • UI Components: Display unrealized and realized funding

Monitoring and Health

  • FastAPI built-in health check endpoint: /health
  • Structured logging with correlation IDs
  • Error monitoring and alerting

Troubleshooting

Common Issues

Issue Possible Cause Solution
Missing funding settlement Scheduler failure 1. Check TaskIQ logs
2. Verify Redis connectivity
3. Manually trigger settlement
Incorrect funding rates Index price issues 1. Verify index price feed
2. Check premium calculation
3. Validate rate caps
Database connection errors PostgreSQL unavailable 1. Check connection string
2. Verify database service status
3. Check network connectivity

Debugging Tips

  • Enable debug logging by setting DEBUG=True in .env
  • Check historical rates in BigQuery:
    SELECT * FROM `funding_rates.minutely_rates`
    WHERE instrument = 'BTC_USDC-PERPETUAL'
    ORDER BY timestamp DESC LIMIT 10
    
  • Verify position funding in PostgreSQL:
    SELECT * FROM position
    WHERE instrument LIKE '%PERPETUAL%'
    

Performance Considerations

  • Minutely calculations are optimized for minimal latency
  • Database operations use connection pooling for efficiency
  • Rate calculations are capped and validated to prevent extreme values
  • Historical data is stored in BigQuery for efficient querying

Future Optimizations

  1. High-frequency trading performance optimization
  2. Multi-market scaling for additional instruments
  3. Backup and recovery procedures
  4. Enhanced monitoring and alerting system

Contributing

For guidelines on contributing to this project, please see the CLAUDE.md file in the repository root.

License

Proprietary - All rights reserved


This documentation is generated from the service README. For the most up-to-date information, refer to the original README