Trading Guide

Perpetual Funding Rates Explained

Everything an AI agent needs to know about funding rates on perpetual futures markets — how they work, how to read them, and how to profit from them using the Purple Flea Trading API on Hyperliquid.

Hyperliquid AI Agents Updated Feb 2026 15 min read

What Are Funding Rates?

A perpetual futures contract is a derivative that lets traders take leveraged long or short positions on an asset without an expiry date. Unlike traditional futures, perpetuals never settle — they can be held indefinitely. This creates a problem: without an expiry date forcing convergence, the perpetual price can drift significantly from the underlying spot price.

Funding rates are the mechanism that solves this. Periodically, traders on the winning side of a divergence pay traders on the losing side, creating a financial incentive for the market to self-correct. If the perpetual is trading above spot, longs pay shorts, making it more expensive to hold long positions and more attractive to hold short ones — which pushes the perpetual price back toward spot.

Key principle: Funding rates are peer-to-peer transfers between traders — the exchange does not collect them. If you are on the receiving side of a funding payment, it is pure income on your open position.

On Hyperliquid (the exchange underlying the Purple Flea Trading API), funding is settled every 8 hours, at 00:00, 08:00, and 16:00 UTC. At each settlement, the funding rate is applied to all open positions: traders holding positions in the direction that the market is leaning pay traders holding opposing positions.

Positive Rate

Longs Pay Shorts

The perpetual is trading above spot. The market is net bullish. Long holders pay a percentage of their position value to short holders every 8 hours.

Negative Rate

Shorts Pay Longs

The perpetual is trading below spot. The market is net bearish. Short holders pay a percentage of their position value to long holders every 8 hours.

How the Mechanism Works

Understanding the funding mechanism step by step is critical for any agent that operates in perpetuals markets. The flow is straightforward:

1. Price Divergence Appears

The perpetual contract price deviates from the index price (a volume-weighted average of the asset's spot price across major exchanges). The difference — called the premium — feeds directly into the funding rate calculation.

2. Funding Rate Is Calculated

Every funding period, an 8-hour time-weighted average of the premium index is computed. An interest rate component (usually small) is added. The result is the funding rate expressed as a percentage, typically displayed as an 8-hour rate (e.g., +0.01%).

3. Settlement at 00:00, 08:00, 16:00 UTC

At each 8-hour interval, the exchange automatically debits and credits open positions. If you hold a $10,000 long position and the rate is +0.05%, you pay $5 to short holders. If you hold a short, you receive $5.

4. Price Convergence Is Incentivized

Persistently high positive rates make longs expensive and attract new short sellers (who receive funding). This selling pressure on the perpetual closes the gap between the perpetual price and the spot index, reducing the rate over time.

⚠️
Important for agents: The funding rate displayed on the interface is the predicted rate for the upcoming settlement, not a guaranteed future rate. The actual rate at settlement is based on the premium at that moment. Rates can change significantly within the period.

The Funding Rate Formula

Hyperliquid uses a funding rate formula derived from the standard industry model. Understanding the components helps an agent reason about why a rate is high or low and predict how it might evolve.

Funding Rate Formula
Funding Rate = Premium Index + clamp(Interest Rate − Premium Index, −0.05%, +0.05%) Premium Index (8h TWAP) = (Mark Price − Index Price) / Index Price Payment = Position Value × Funding Rate
Mark Price
Fair value of the perpetual, derived from order book mid-price and oracle price to prevent manipulation.
Index Price
Volume-weighted average of the asset's spot price across multiple reference exchanges.
Interest Rate
A fixed baseline rate (typically 0.01% per 8h on most venues). Represents the cost of holding leveraged exposure.
clamp()
Caps the interest rate adjustment to ±0.05% per period, preventing runaway funding during extreme dislocations.
8h TWAP
Time-weighted average premium over the 8-hour period, sampled at regular intervals (e.g., every minute).
Position Value
Notional value of open position = quantity × mark price. Funding is on notional, not on margin posted.
Annualized equivalent: An 8-hour rate of +0.01% equates to approximately +10.95% annualized (3 periods/day × 365 days). A rate of +0.10% annualizes to ~109.5%. Rates above 0.10% per period are considered elevated and represent significant carry cost for longs.

Funding Rate Signals for AI Agents

Funding rates provide a continuous, quantitative signal about market sentiment and carry costs. An AI agent can use this signal in several ways.

Directional Signal

High Positive Rate

Consider Going Short

When longs are paying substantial funding to shorts, the market is in a crowded long position. Going short collects funding income and benefits from potential mean reversion.

High Negative Rate

Consider Going Long

When shorts are paying substantial funding to longs, the market is in a crowded short position. Going long collects funding income and may benefit from a short squeeze.

Funding Arbitrage (Delta-Neutral)

The most common institutional strategy is to collect funding without taking directional exposure. This is achieved by holding equal and opposite positions in spot and perpetuals:

Arbitrage Strategy

Cash-and-Carry (Long Spot + Short Perp)

When the perpetual funding rate is consistently positive, an agent can hold a long position in spot (or a spot-equivalent instrument) and simultaneously hold an equal short position in the perpetual. The directional exposure is hedged, and the agent simply collects the funding payments from long holders.

Net P&L: Funding received − (spot holding cost + execution slippage + exchange fees)
Break-even rate: Typically >0.02% per 8h to cover costs on most venues.

Rule of thumb for agents: A funding rate exceeding 0.05% per 8 hours (≈55% annualized) is strong enough to build a funding-collection strategy around. Below this threshold, friction costs typically erode the edge.

Threshold-Based Decision Logic

8h Funding Rate Interpretation Suggested Agent Action
+0.10%+ Extreme greed — heavily crowded longs Strong signal to short perp / open arb
+0.05% – +0.10% Elevated bullish sentiment Consider short perp; arb is economical
+0.01% – +0.05% Normal bullish conditions Monitor; arb marginal after fees
-0.01% – +0.01% Neutral / balanced market No funding signal; use other indicators
-0.05% – -0.01% Elevated bearish sentiment Consider long perp; arb marginal after fees
-0.10% or below Extreme fear — heavily crowded shorts Strong signal to long perp / reverse arb

Hyperliquid & the Purple Flea Trading API

The Purple Flea Trading API wraps Hyperliquid's exchange infrastructure in a clean REST interface designed for AI agents. All perpetuals markets are accessible via simple HTTP calls — no wallet management, no WebSocket complexity, no gas handling.

Fetching Funding Rates

Use the /v1/markets endpoint to retrieve all available markets and their current funding rates in a single call:

GET https://api.purpleflea.com/v1/markets

Returns all active perpetuals markets with current funding rate, open interest, mark price, and index price.

Response 200 OK
{
  "markets": [
    {
      "symbol":        "BTC-PERP",
      "mark_price":    97834.20,
      "index_price":   97801.55,
      "funding_rate":  0.000412,   // +0.0412% per 8h — elevated
      "funding_rate_8h_annualized": 0.4507,  // +45.1% annualized
      "next_funding_ts": 1740614400, // Unix timestamp (UTC)
      "open_interest_usd": 1482950000
    },
    {
      "symbol":        "ETH-PERP",
      "mark_price":    2714.88,
      "index_price":   2716.10,
      "funding_rate":  -0.000088,  // -0.0088% per 8h — mild bearish
      "funding_rate_8h_annualized": -0.0964,
      "next_funding_ts": 1740614400,
      "open_interest_usd": 687320000
    },
    {
      "symbol":        "SOL-PERP",
      "mark_price":    182.44,
      "index_price":   182.19,
      "funding_rate":  0.000651,   // +0.0651% per 8h — high, arb opportunity
      "funding_rate_8h_annualized": 0.7125,
      "next_funding_ts": 1740614400,
      "open_interest_usd": 298140000
    }
  ],
  "generated_at": 1740610831
}
Funding rate encoding: The funding_rate field is expressed as a decimal fraction of notional value per 8-hour period. Multiply by 100 to get a percentage. A value of 0.000651 = 0.0651% per 8h.

Placing Orders via the API

Once your agent identifies a funding opportunity, it can place orders directly:

GET https://api.purpleflea.com/v1/markets
POST https://api.purpleflea.com/v1/orders
POST https://api.purpleflea.com/v1/orders/{id}/cancel
GET https://api.purpleflea.com/v1/positions

Python Agent Code Example

The following example demonstrates an AI agent that polls funding rates every 5 minutes, identifies markets where the rate exceeds a configurable threshold, and opens a delta-neutral position (short perp + long spot equivalent) to collect funding.

Python 3.11+
"""
Funding Rate Collector — Purple Flea Trading API
Monitors Hyperliquid perpetuals and opens delta-neutral
positions when funding rates exceed the threshold.
"""

import time
import logging
import requests
from dataclasses import dataclass
from typing import Optional

# ── Configuration ──────────────────────────────────────────
API_BASE   = "https://api.purpleflea.com"
API_KEY    = "pf_YOUR_API_KEY_HERE"
THRESHOLD  = 0.0005    # 0.05% per 8h — minimum to enter
MAX_NOTIONAL = 1000   # USD notional per position
POLL_INTERVAL = 300   # seconds between funding checks

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s  %(levelname)s  %(message)s"
)
log = logging.getLogger("funding-agent")

# ── Data Model ─────────────────────────────────────────────
@dataclass
class Market:
    symbol: str
    mark_price: float
    funding_rate: float
    open_interest_usd: float
    next_funding_ts: int

# ── API Helpers ────────────────────────────────────────────
def get_markets() -> list[Market]:
    """Fetch all perpetuals markets with current funding rates."""
    headers = {"X-API-Key": API_KEY}
    resp = requests.get(
        f"{API_BASE}/v1/markets",
        headers=headers,
        timeout=10
    )
    resp.raise_for_status()
    data = resp.json()
    return [
        Market(
            symbol=m["symbol"],
            mark_price=m["mark_price"],
            funding_rate=m["funding_rate"],
            open_interest_usd=m["open_interest_usd"],
            next_funding_ts=m["next_funding_ts"],
        )
        for m in data["markets"]
    ]

def place_order(
    symbol: str,
    side: str,          # "buy" | "sell"
    notional_usd: float,
    order_type: str = "market",
) -> dict:
    """Place a market order on the perpetuals market."""
    headers = {
        "X-API-Key": API_KEY,
        "Content-Type": "application/json",
    }
    payload = {
        "symbol":       symbol,
        "side":         side,
        "type":         order_type,
        "notional_usd": notional_usd,
    }
    resp = requests.post(
        f"{API_BASE}/v1/orders",
        headers=headers,
        json=payload,
        timeout=10
    )
    resp.raise_for_status()
    return resp.json()

def get_open_positions() -> dict[str, dict]:
    """Return open positions keyed by symbol."""
    headers = {"X-API-Key": API_KEY}
    resp = requests.get(
        f"{API_BASE}/v1/positions",
        headers=headers,
        timeout=10
    )
    resp.raise_for_status()
    positions = resp.json().get("positions", [])
    return {p["symbol"]: p for p in positions}

# ── Strategy Logic ─────────────────────────────────────────
def evaluate_market(
    market: Market,
    open_positions: dict[str, dict],
) -> Optional[str]:
    """
    Return a trade action or None.
    Returns:
        "short"  — open short perp to collect positive funding
        "long"   — open long perp to collect negative funding
        None     — no action warranted
    """
    already_open = market.symbol in open_positions
    rate = market.funding_rate
    annualized = rate * 3 * 365   # 3 periods/day × 365

    if already_open:
        log.debug(f"  {market.symbol}: position already open, skipping")
        return None

    if rate >= THRESHOLD:
        log.info(
            f"  OPPORTUNITY {market.symbol}: funding={rate:.4%}/8h "
            f"({annualized:.1%} annualized) — SHORT PERP"
        )
        return "short"

    if rate <= -THRESHOLD:
        log.info(
            f"  OPPORTUNITY {market.symbol}: funding={rate:.4%}/8h "
            f"({annualized:.1%} annualized) — LONG PERP"
        )
        return "long"

    log.debug(
        f"  {market.symbol}: rate={rate:.4%} below threshold, skipping"
    )
    return None

def run_cycle() -> None:
    """Execute one full scan-and-trade cycle."""
    log.info("=== Starting funding scan ===")

    markets = get_markets()
    open_positions = get_open_positions()
    log.info(
        f"Fetched {len(markets)} markets, {len(open_positions)} open positions"
    )

    for market in markets:
        action = evaluate_market(market, open_positions)
        if action == "short":
            result = place_order(
                symbol=market.symbol,
                side="sell",
                notional_usd=MAX_NOTIONAL,
            )
            log.info(f"Opened short on {market.symbol}: {result}")
        elif action == "long":
            result = place_order(
                symbol=market.symbol,
                side="buy",
                notional_usd=MAX_NOTIONAL,
            )
            log.info(f"Opened long on {market.symbol}: {result}")

# ── Entry Point ────────────────────────────────────────────
if __name__ == "__main__":
    log.info(f"Funding agent started. Threshold: {THRESHOLD:.4%}/8h")
    while True:
        try:
            run_cycle()
        except Exception as exc:
            log.error(f"Cycle error: {exc}", exc_info=True)
        log.info(f"Sleeping {POLL_INTERVAL}s until next scan...")
        time.sleep(POLL_INTERVAL)
⚠️
Production considerations: The example above opens perp-only positions (not a fully delta-neutral arb). For a complete arb, the agent must also hold the equivalent long spot position. The agent above is suitable for directional funding-collection strategies but carries mark-to-market risk on the position.

Historical Context and Rate Interpretation

Understanding where current funding rates sit relative to historical norms is essential for calibrating strategy thresholds and risk tolerances.

Typical Range

+0.005% to +0.02%

Most markets spend the majority of time in this range during neutral-to-mildly-bullish conditions. This reflects the baseline interest rate component.

Bull Market Peak

+0.10% to +0.30%

During strong bull runs (e.g., late 2021, Q4 2024), BTC and ETH perpetuals regularly sustained rates in this range. These periods represent exceptional funding income opportunities.

Capitulation Events

-0.10% to -0.15%

During rapid sell-offs or liquidation cascades (e.g., May 2021, FTX collapse), negative funding reached extreme levels for short periods, offering the reverse arb opportunity.

Flash Extremes

Temporarily beyond ±0.30%

During black-swan events or listing surges on small caps, rates can spike to extreme levels for 1-2 periods before snapping back. These carry very high risk.

How to Interpret Extremes

An extremely high positive funding rate is a double-edged signal. On one hand, it means significant income for short positions. On the other, it often occurs during strong upward price momentum — meaning the market may continue to rally even as shorts collect funding. An agent should weigh funding income against the mark-to-market risk of fighting the trend.

Open interest data (returned alongside funding rates in the /v1/markets response) provides additional context. A high funding rate combined with rising open interest indicates that new leveraged longs are still entering — the positioning is not yet unwinding. A high funding rate alongside falling open interest often signals the start of a deleveraging event and potential mean reversion.

Risk Warnings

Funding collection strategies carry real financial risk. Past funding rates are not indicative of future rates. Agents must be designed to handle adverse conditions. Never operate without position size limits, stop-loss logic, and liquidation monitoring.
  • Funding Rate Reversal A rate can flip from strongly positive to strongly negative within a single 8-hour period. An agent that opened a short to collect +0.10% funding may suddenly owe funding the next period while also facing a price move against its position.
  • Liquidation Risk Perpetual positions use leverage. A short opened to collect funding can be liquidated if the price rallies sharply. Funding income collected over 10 periods can be wiped out by a single liquidation event. Always set appropriate leverage and maintain sufficient margin.
  • 📈
    Compounding Costs Funding is charged on the full notional value of the position, not just the margin. A 0.01% rate on a $10,000 position costs $1 every 8 hours, or $3/day, or approximately $1,095 per year — equivalent to a 10.95% annual drag on a $10,000 position held as a long in neutral conditions.
  • 🔒
    Imperfect Delta Hedge In a cash-and-carry strategy, the spot and perp legs do not always move in perfect lockstep. Basis risk — the difference between spot and perp price — can erode arb profits, especially during high-volatility periods or exchange outages.
  • 📶
    Exchange and API Risk Agents relying on automated API execution are exposed to downtime, latency, and order rejection. Build retry logic, circuit breakers, and state recovery into your agent. A failed close order on a leveraged position is a serious risk event.

Start Trading with the Purple Flea Trading API

Access all Hyperliquid perpetuals markets, real-time funding rates, and order execution through a single REST API built for AI agents.