Thanks to visit codestin.com
Credit goes to github.com

Skip to content

nhaga/funding-rates

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Hyperliquid Funding Rate Tracker

A Python tool to continuously monitor and track funding rate gains/losses on Hyperliquid perpetual futures positions. The tracker automatically collects funding rate data, calculates payments for your positions, and stores everything in a local SQLite database for analysis.

Features

  • Continuous Monitoring: Polls Hyperliquid API at configurable intervals (default: 5 minutes)
  • Automatic Calculation: Computes funding payments based on your position size and current rates
  • Local Storage: Saves all data to SQLite database for historical analysis
  • Position Tracking: Manage multiple positions across different symbols
  • Comprehensive Logging: Detailed logs for tracking and debugging
  • Management CLI: Easy command-line interface for managing positions and viewing data

Installation

# Install dependencies
pip install -r requirements.txt

# Make scripts executable
chmod +x hyperliquid_funding_tracker.py
chmod +x hyperliquid_manager.py

Quick Start

1. Start the Tracker

python hyperliquid_funding_tracker.py

The tracker will:

  • Create a SQLite database (hyperliquid_funding.db)
  • Start polling Hyperliquid for funding rates every 5 minutes
  • Log all activity to hyperliquid_funding.log and console

2. Add Positions to Track

Edit hyperliquid_funding_tracker.py and uncomment/modify the position examples in the main() function:

def main():
    tracker = FundingTracker(poll_interval=300)
    
    # Add your positions here:
    tracker.add_position(symbol='BTC', size=0.1, entry_price=45000)   # Long 0.1 BTC
    tracker.add_position(symbol='ETH', size=-1.0, entry_price=2500)  # Short 1 ETH
    tracker.add_position(symbol='SOL', size=10, entry_price=100)     # Long 10 SOL
    
    tracker.run()

Or use the management CLI:

# Add a long position
python hyperliquid_manager.py add BTC 0.1 45000

# Add a short position (negative size)
python hyperliquid_manager.py add ETH -1.0 2500

Management CLI Usage

The hyperliquid_manager.py script provides commands to interact with your data:

List Positions

# List all positions
python hyperliquid_manager.py list

# List only active positions
python hyperliquid_manager.py list --active

Add Position

# Syntax: add SYMBOL SIZE ENTRY_PRICE
python hyperliquid_manager.py add BTC 0.5 42000      # Long position
python hyperliquid_manager.py add ETH -2.0 2400     # Short position

Close Position

# Close position by ID
python hyperliquid_manager.py close 1

View Funding History

# Show last 24 hours of funding rates for BTC
python hyperliquid_manager.py history BTC

# Show last 48 hours
python hyperliquid_manager.py history BTC --hours 48

View Payments for Position

# Show all funding payments for position ID 1
python hyperliquid_manager.py payments 1

View Summary

# Overall summary of all positions and PnL
python hyperliquid_manager.py summary

Understanding Funding Rates

How Funding Works

  • Funding Rate: Periodic payment between long and short positions
  • Payment Frequency: Every 8 hours on Hyperliquid (00:00, 08:00, 16:00 UTC)
  • Direction:
    • Positive rate → Longs pay shorts
    • Negative rate → Shorts pay longs
  • Calculation: Payment = Funding Rate × Position Size × Mark Price

Example

Position: Long 1 BTC at $45,000 Funding Rate: 0.01% (0.0001) Mark Price: $46,000

Payment = 0.0001 × 1 × 46,000 = $4.60

  • If rate is positive: You pay $4.60
  • If rate is negative: You receive $4.60

Database Schema

The tracker uses three main tables:

funding_rates

Stores historical funding rate data:

  • symbol: Trading pair (BTC, ETH, etc.)
  • funding_rate: Current funding rate
  • mark_price: Mark price at the time
  • predicted_rate: Predicted next funding rate
  • timestamp: When the data was collected

positions

Tracks your trading positions:

  • symbol: Trading pair
  • size: Position size (positive = long, negative = short)
  • entry_price: Entry price
  • entry_time: When position was opened
  • exit_time: When position was closed (if applicable)
  • is_active: Whether position is still open

funding_payments

Records calculated funding payments:

  • position_id: Reference to position
  • symbol: Trading pair
  • funding_rate: Rate used for calculation
  • position_size: Size at time of payment
  • mark_price: Mark price used
  • payment_amount: Calculated payment (positive = received, negative = paid)
  • timestamp: When payment occurred

Configuration

Polling Interval

Change the polling frequency by modifying the poll_interval parameter (in seconds):

tracker = FundingTracker(poll_interval=300)  # 5 minutes
tracker = FundingTracker(poll_interval=600)  # 10 minutes
tracker = FundingTracker(poll_interval=60)   # 1 minute (not recommended)

Note: Hyperliquid funding occurs every 8 hours. Polling more frequently than every 5 minutes provides marginal benefit.

Database Location

Specify a custom database path:

tracker = FundingTracker(db_path="/path/to/my/funding_data.db")

Or via CLI:

python hyperliquid_manager.py list --db /path/to/my/funding_data.db

Running as a Background Service

Using nohup (Linux/Mac)

nohup python hyperliquid_funding_tracker.py > output.log 2>&1 &

Using screen (Linux/Mac)

screen -S funding_tracker
python hyperliquid_funding_tracker.py
# Press Ctrl+A then D to detach
# Reattach with: screen -r funding_tracker

Using systemd (Linux)

Create /etc/systemd/system/hyperliquid-tracker.service:

[Unit]
Description=Hyperliquid Funding Tracker
After=network.target

[Service]
Type=simple
User=youruser
WorkingDirectory=/path/to/tracker
ExecStart=/usr/bin/python3 hyperliquid_funding_tracker.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Then:

sudo systemctl enable hyperliquid-tracker
sudo systemctl start hyperliquid-tracker
sudo systemctl status hyperliquid-tracker

Analyzing Data

Direct SQL Queries

You can query the database directly for custom analysis:

sqlite3 hyperliquid_funding.db

Example queries:

-- Total funding PnL by symbol
SELECT 
    symbol, 
    SUM(payment_amount) as total_pnl,
    COUNT(*) as num_payments
FROM funding_payments
GROUP BY symbol;

-- Average funding rate over last 24 hours
SELECT 
    symbol,
    AVG(funding_rate) * 100 as avg_rate_pct,
    MIN(funding_rate) * 100 as min_rate_pct,
    MAX(funding_rate) * 100 as max_rate_pct
FROM funding_rates
WHERE timestamp >= datetime('now', '-24 hours')
GROUP BY symbol;

-- Daily funding earned per position
SELECT 
    DATE(timestamp) as date,
    symbol,
    SUM(payment_amount) as daily_pnl
FROM funding_payments
GROUP BY DATE(timestamp), symbol
ORDER BY date DESC;

Export to CSV

sqlite3 -header -csv hyperliquid_funding.db \
  "SELECT * FROM funding_payments" > funding_payments.csv

Troubleshooting

No Data Being Collected

  • Check network connectivity
  • Verify Hyperliquid API is accessible: curl https://api.hyperliquid.xyz/info
  • Check logs: tail -f hyperliquid_funding.log

Database Locked Error

  • Ensure only one instance of the tracker is running
  • Close any SQLite browser connections to the database

Incorrect Funding Calculations

  • Verify position sizes are correct (negative for shorts)
  • Check that funding rates are being recorded properly
  • Review the funding_payments table for payment history

API Rate Limits

Hyperliquid's public API has rate limits. The default 5-minute polling interval stays well within limits. If you encounter rate limiting:

  • Increase poll_interval to 10+ minutes
  • Ensure you're not running multiple instances
  • Check logs for HTTP 429 errors

Limitations

  • Public Data Only: Uses Hyperliquid's public API (no authentication required)
  • Manual Position Entry: Positions must be manually added to the tracker
  • Payment Calculation: Calculates expected payments based on funding rates; actual exchange payments may vary slightly
  • No Trade Execution: This is a monitoring tool only; it does not execute trades

Advanced Usage

Custom Funding Calculation

Modify the record_funding_payment method in FundingDatabase class to implement custom payment logic:

def record_funding_payment(self, position_id: int, symbol: str, funding_rate: float,
                           position_size: float, mark_price: float, timestamp: datetime):
    # Custom calculation here
    payment_amount = your_custom_calculation(funding_rate, position_size, mark_price)
    # ... rest of the method

Backtesting

Use historical funding data to backtest position performance:

def backtest_position(db, symbol, size, start_time, end_time):
    cursor = db.conn.cursor()
    cursor.execute("""
        SELECT funding_rate, mark_price
        FROM funding_rates
        WHERE symbol = ?
        AND timestamp BETWEEN ? AND ?
    """, (symbol, start_time, end_time))
    
    total_pnl = 0
    for rate, price in cursor.fetchall():
        payment = rate * abs(size) * price
        if size < 0:  # Short
            payment = -payment
        total_pnl += payment
    
    return total_pnl

Contributing

Feel free to extend this tool with:

  • Support for additional exchanges
  • Web dashboard for visualization
  • Telegram/Discord notifications
  • Portfolio optimization based on funding rates
  • Machine learning for funding rate prediction

License

MIT License - feel free to use and modify for your trading needs.

Disclaimer

This tool is for informational and educational purposes only. It does not constitute financial advice. Always verify funding calculations independently and understand the risks of leveraged trading. Cryptocurrency trading involves substantial risk of loss.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published