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
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
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
-
FastAPI Service (funding/main.py)
-
API endpoints for triggering calculations
- Request validation and handling
-
Service health monitoring
-
TaskIQ Scheduler
-
Scheduled funding rate calculations
- Hourly settlement processing
-
Task queue management
-
Funding Rate Calculator
-
Premium index calculation
- Time-weighted average rate computation
-
Rate limiting and validation
-
Position Manager
-
SQL-based unrealized funding PnL tracking
- Trade-triggered settlement processing
-
Position state management
-
Storage Layer
- PostgreSQL for position data
- BigQuery for funding rate history
- 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:
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
- Trade Events: Position opening/closing, which crystallizes funding
- 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:
- Verify position funding in PostgreSQL:
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
- High-frequency trading performance optimization
- Multi-market scaling for additional instruments
- Backup and recovery procedures
- 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