Complete Educational Guide

Perpetual Futures
Explained

Everything AI agent developers need to know about perpetual futures contracts — from first principles through funding rate arbitrage. Built for builders, not traders.

What Are Perps Key Concepts Funding Mechanics Leverage Math Liquidation 275+ Markets Funding History Strategies Risk Warnings Get Started

What are perpetual futures?

Derivatives that let you speculate on any asset — with leverage, no expiry date, and a built-in mechanism that keeps the price anchored to spot.

A perpetual futures contract — or perp — is a derivative that lets you bet on an asset's price without owning it. You can go long (profit when price rises) or short (profit when price falls), with leverage up to 50x. Unlike traditional futures contracts on CME or CBOE, perps have no expiry date. There is no settlement day, no roll-over cost, no delivery. A position opened today can be held until you decide to close it — whether that is five seconds or five years.

Perpetuals were invented by BitMEX in 2016 and are now the most liquid derivative instrument in crypto. Daily trading volume in perp markets routinely exceeds the spot market by 5-10x. Hyperliquid alone clears billions of dollars in perp volume daily, and Purple Flea's Trading API exposes all 275+ of its markets through a single clean REST interface.

The core problem with a futures contract that never expires: what stops it from drifting endlessly away from the spot price? The answer is the funding rate — a periodic payment that flows between longs and shorts to align the perp price with the underlying index. When the perp trades above spot, longs pay shorts (discouraging buying). When it trades below, shorts pay longs (discouraging selling). This continuous incentive keeps the perp tethered to reality.

Why this matters for AI agents: The funding rate is a programmable, predictable cash flow. Unlike discretionary traders who must react to price moves, an agent can systematically harvest funding income with no directional exposure — collecting yield while the market moves in any direction.


Key concepts.

Six building blocks every perp trader — human or agent — must understand before opening a position.

📈

Mark Price vs Index Price

Three prices exist in any perp market. Last Price is the most recent trade — volatile and easily manipulated. Index Price is a weighted average of spot prices across major exchanges, representing true fair value. Mark Price is the index plus a decaying funding basis — the official price used for all P&L and liquidation calculations.

Example: BTC-PERP Index Price: $65,000.00
Last Price: $65,320.00
Mark Price: $65,048.00
Liq. uses mark, not last
💲

Funding Rate

Every 8 hours, a payment settles between all open longs and all open shorts based on how far the perp price has deviated from the index. Positive rate: longs pay shorts (perp above spot). Negative rate: shorts pay longs (perp below spot). Payments happen automatically — no action required from traders.

At 0.01% rate / 8h $10,000 long position
Pays: $1.00 per interval
Daily cost: $3.00
Annualized: ~10.95% APY drag

Leverage

Leverage multiplies both your gains and your losses. At 10x leverage, a $1,000 margin deposit controls a $10,000 position. A 1% favorable price move earns $100 (10% on margin). A 1% adverse move loses $100 (10% on margin). At 10x, a 10% adverse move wipes the full margin. Purple Flea supports 2x through 50x.

10x Leverage Math Capital: $1,000
Position size: $10,000
+1% price move: +$100 (+10%)
-1% price move: -$100 (-10%)
🔒

Margin

Initial margin is the collateral required to open a position (e.g., 10% for 10x leverage). Maintenance margin is the minimum to keep it open (typically 0.5–1%). When your margin ratio falls below maintenance level, the exchange liquidates your position automatically. Isolated margin caps loss at your deposited amount; cross margin uses your entire account balance.

Margin Types Initial: 10% of position
Maintenance: 0.5% of position
Isolated: safe — capped loss
Cross: risky — full account
📊

Open Interest

Open interest (OI) is the total USD value of all outstanding open positions in a market. It measures how much speculative capital is deployed. Rising OI alongside rising price suggests genuine demand. Rising OI alongside falling price signals short pressure. Extremely high OI relative to market cap is a warning sign: one large forced liquidation can cascade into a market-wide deleveraging.

OI Interpretation Price ↑ + OI ↑: Bullish confirmation
Price ↓ + OI ↑: Bearish confirmation
Price ↑ + OI ↓: Short squeeze
Price ↓ + OI ↓: Long liquidation

Long vs Short

Long: you profit when price rises. You are synthetically buying the asset with borrowed capital, paying funding when rates are positive. Short: you profit when price falls. You collect funding when rates are positive (the bull market yield). Delta-neutral: long and short in equal size — you earn or pay only the funding rate, with no directional exposure.

Position Types Long: profit when price rises
Short: profit when price falls
Delta-neutral: collect funding only
No prediction required

How funding works.

A payment mechanism that fires every 8 hours, flowing automatically between longs and shorts. The heartbeat of every perpetual market.

24-Hour Funding Cycle — 3 intervals per day

00:00 UTC Funding settles
04:00 UTC Rate accrues
08:00 UTC Funding settles
12:00 UTC Rate accrues
16:00 UTC Funding settles
20:00 UTC Rate accrues
24:00 UTC Funding settles
Positive funding rate — perp above spot
Longs pay shorts · Bears earn · Bulls pay premium for leverage
+0.01% / 8h
Negative funding rate — perp below spot
Shorts pay longs · Bulls earn · Bears pay premium for leverage
-0.005% / 8h

The Funding Rate Formula

Hyperliquid (and most major perp exchanges) computes the funding rate continuously from the premium index — how far the perp mark price deviates from the spot index:

premium_index = (mark_price - index_price) / index_price
funding_rate = clamp(premium_index, -0.075%, +0.075%)

# Payment calculation at each 8h interval:
payment = position_size * funding_rate

# Example: $50,000 long at +0.01% funding rate
payment_per_8h = 50,000 * 0.0001 = $5.00 (longs pay)
payment_per_day = $5.00 * 3 = $15.00
annualized = $15.00 * 365 = $5,475 (~10.95% of $50k)

The clamped maximum of ±0.075% per interval (±82.1% annualized) prevents funding rates from becoming so extreme that positions are uneconomical. In practice, BTC rates rarely exceed 0.05% per interval except during peak market euphoria.

Funding payment = position size × funding rate. Leverage does not change the rate — it only affects how large a position your margin controls. A $10,000 position at 10x leverage pays the same funding as a $10,000 position at 2x leverage.


Leverage math.

$1,000 of capital. 10x leverage. A 1% price move. Here is exactly what happens in both directions.

Scenario: $1,000 Capital — 10x Leverage — BTC-PERP

capital = $1,000
leverage = 10x
position_size = capital * leverage = $10,000
entry_price = $65,000
btc_exposure = 10,000 / 65,000 = 0.1538 BTC

+1% Price Move → BTC hits $65,650

Price increase+$650
Your P&L (0.1538 BTC)+$100
Return on capital+10%
Effective margin$1,100

-1% Price Move → BTC hits $64,350

Price decrease-$650
Your P&L (0.1538 BTC)-$100
Return on capital-10%
Effective margin$900

Leverage Multiplier vs. Risk Table

Higher leverage amplifies returns but compresses the price move required to wipe your position. The relationship is linear — 5x leverage requires a 20% adverse move for liquidation, while 50x requires only 2%.

Leverage $1k margin controls 1% move = return Adverse move to liq.
2x$2,0002%~50%
3x$3,0003%~33%
5x$5,0005%~20%
10x$10,00010%~10%
20x$20,00020%~5%
50x$50,00050%~2%

Agent recommendation: For systematic strategies, 2x–5x leverage provides meaningful capital efficiency while keeping liquidation distances far enough to absorb normal volatility. Most of BTC's intraday moves are under 5% — a 5x long only gets liquidated on a ~20% drop, which gives an agent ample time to reduce or hedge.


Liquidation mechanics.

Understand exactly when and how positions get forcibly closed — and how to engineer agents that never get there.

Liquidation Price Formula

Liquidation occurs when your margin ratio drops to the maintenance margin level. For a long position:

# Long position liquidation price:
liq_price = entry_price * (1 - (1 / leverage) + maintenance_margin_rate)

# Example: entry=$65,000, 10x leverage, maint_margin=0.5%
liq_price = 65,000 * (1 - 0.10 + 0.005)
liq_price = 65,000 * 0.905 = $58,825

# Short position liquidation price:
liq_price = entry_price * (1 + (1 / leverage) - maintenance_margin_rate)
liq_price = 65,000 * (1 + 0.10 - 0.005) = $71,175

Liquidation Prices — BTC Long from $65,000 Entry

Leverage Entry Price Liquidation Price Required Drop Risk Level
2x $65,000 $32,825 -49.5% Low
5x $65,000 $52,325 -19.5% Moderate
10x $65,000 $58,825 -9.5% Elevated
20x $65,000 $61,913 -4.7% High
50x $65,000 $63,765 -1.9% Very High

Isolated vs Cross Margin

Isolated margin dedicates a fixed collateral amount to one position. If that position is liquidated, only that margin is lost — the rest of your account is untouched. This is the recommended mode for AI agents running multiple parallel positions. Each position is fully scoped and its worst-case loss is bounded.

Cross margin uses your entire account balance to back all positions. Individual positions are harder to liquidate (more collateral behind each), but a single catastrophic trade can cascade across your entire portfolio. Avoid cross margin for autonomous agents unless you have explicit account-level circuit breakers in place.

Auto-Deleveraging (ADL)

When a liquidated position cannot be fully absorbed by the exchange's insurance fund — rare, but possible during violent market dislocations — the exchange triggers ADL. It forcibly closes the most profitable open positions on the opposite side, ranked by profitability and leverage, until the deficit is covered. Profitable longs get partially closed without consent when shorts are mass-liquidated. Agents should monitor the ADL queue indicator exposed in the Purple Flea API and consider reducing highly profitable positions during extreme market stress.

Programmatic Liquidation Prevention

An AI agent has one major advantage over a human: it never sleeps and can react in milliseconds. Use these patterns:

  • Poll GET /trading/positions every 10–30 seconds to monitor margin ratio
  • Trigger POST /trading/add-margin automatically when margin ratio falls below a safety threshold (e.g., 30%)
  • Programmatic stop-loss: close the position via POST /trading/order before liquidation triggers
  • Never size a single position at more than 10–20% of total capital (Kelly criterion)
  • Use lower leverage on volatile assets (SOL, smaller alts) versus BTC/ETH

275+ perpetual markets.

Every major crypto asset plus 272 altcoins — all accessible through a single REST API backed by Hyperliquid's on-chain order book.

BTC-PERP
Bitcoin
ETH-PERP
Ethereum
SOL-PERP
Solana
BNB-PERP
BNB Chain
AVAX-PERP
Avalanche
ARB-PERP
Arbitrum
OP-PERP
Optimism
DOGE-PERP
Dogecoin

+ 267 more perpetual markets: SUI, TIA, JUP, WIF, PEPE, INJ, SEI, STX, NEAR, FTM, ATOM, DOT, LINK, UNI, AAVE, and hundreds more altcoins. All markets at trading.purpleflea.com.

list_markets.py
import requests API_KEY = "pf_sk_..." BASE = "https://api.purpleflea.com" HEADERS = {"Authorization": f"Bearer {API_KEY}"} # Fetch all 275+ available perp markets markets = requests.get(f"{BASE}/trading/markets", headers=HEADERS).json() for m in markets["markets"][:5]: print(f"{m['symbol']:15} mark={m['mark_price']:>12,.2f} " f"funding={m['funding_rate']*100:+.4f}% OI=${m['open_interest']:>12,.0f}") # Output: # BTC-PERP mark= 65,048.20 funding=+0.0100% OI= 2,847,392,000 # ETH-PERP mark= 3,412.55 funding=+0.0082% OI= 934,218,000 # SOL-PERP mark= 178.34 funding=+0.0143% OI= 287,441,000 # BNB-PERP mark= 603.20 funding=+0.0071% OI= 102,875,000 # AVAX-PERP mark= 39.87 funding=-0.0023% OI= 51,220,000

Funding rate history & ranges.

Funding rates follow market sentiment cycles. Understanding the typical range tells you when an opportunity is normal, elevated, or extreme.

Illustrative Funding Rate Bars — BTC-PERP (30-day sample)

Day 1Day 8Day 15Day 22Day 30
Condition Rate / 8h Annualized What it signals
Neutral market 0.005% – 0.01% 5.5% – 11% Normal longs premium — balanced sentiment
Moderate bull 0.01% – 0.03% 11% – 33% Elevated but sustainable — decent funding harvest
Strong bull run 0.03% – 0.075% 33% – 82% Crowded longs — excellent funding harvest, high cascade risk
Negative (bear) -0.075% – -0.01% -82% – -11% Crowded shorts — longs collect funding, capitulation risk

Historically, BTC-PERP has averaged approximately +0.01% per interval over long periods — reflecting the inherent demand for leveraged long exposure in a generally appreciating asset. Extreme rates above 0.05% per interval are a contrarian warning signal: markets are extremely crowded, and a sudden reversal will trigger cascading liquidations.

Altcoin funding rates are more volatile and can swing between +0.075% and -0.075% within a single day during narrative-driven rallies. AI agents monitoring funding rate extremes across 275 markets have an informational advantage: a sudden spike to +0.075% in a mid-cap alt suggests imminent mean reversion.


Strategies for AI agents.

Three systematic approaches well-suited to always-on agents trading perpetual futures. No intuition required — just signals, rules, and execution.

Strategy 01

Trend Following

Go long in uptrends, short in downtrends. Perps are ideal for trend strategies because there are no borrowing costs or expiry constraints — you hold the position as long as the trend persists.

  • Use EMA crossovers (e.g., 20/50) or momentum signals as entry triggers
  • Size position proportionally to trend strength (ATR-based sizing)
  • Exit on trend reversal or when funding becomes excessively negative to your direction
  • Apply 3x–5x leverage for meaningful returns with survivable drawdowns
Entry: EMA crossover up Exit: EMA crossover down Filter: OI confirmation
Strategy 02

Mean Reversion

When an asset deviates far from its mean — measured by funding rate extremes, OI spikes, or Bollinger Band excursions — bet on reversion. Perps allow both directions with equal ease.

  • Monitor funding rate extremes (>0.05% / interval) as a reversal signal
  • Enter a contrarian position when the rate hits max cap (0.075%)
  • Use tight stop-losses — mean reversion can be a falling knife
  • Combine with RSI overbought/oversold (e.g., RSI > 80 / < 20 on 4h)
Entry: Funding extreme Entry: RSI divergence Exit: Rate normalizes
Strategy 03

Funding Rate Harvesting

The most agent-friendly strategy: earn the funding rate with zero directional exposure. Hold equal notional long (spot or spot-equivalent) and short (perp) positions. Collect the rate every 8 hours. No price prediction required.

  • Identify markets with persistently positive funding (>0.01%/interval)
  • Open a delta-neutral position: long spot + short equal notional perp
  • Rebalance periodically to maintain delta neutrality as prices move
  • Unwind when funding drops below your break-even cost
Entry: Rate > 0.015% Exit: Rate < 0.005% Direction: None needed
funding_harvester.py
import requests, time API_KEY = "pf_sk_..." BASE = "https://api.purpleflea.com" HEADERS = {"Authorization": f"Bearer {API_KEY}"} ENTRY_THRESHOLD = 0.00015 # enter if funding_rate >= 0.015% per 8h EXIT_THRESHOLD = 0.00005 # exit if funding_rate <= 0.005% per 8h SIZE_USD = 10000 # $10k notional per leg def get_funding(symbol): r = requests.get(f"{BASE}/trading/price", params={"market": symbol}, headers=HEADERS) return r.json()["funding_rate"] def open_delta_neutral_short(symbol): # Open short perp (collect funding when positive) return requests.post(f"{BASE}/trading/order", json={ "market": symbol, "side": "short", "size_usd": SIZE_USD, "leverage": 1, # 1x — no amplification needed "margin_mode": "isolated" }, headers=HEADERS).json() # Scan all markets every hour for opportunities while True: markets = requests.get(f"{BASE}/trading/markets", headers=HEADERS).json() for m in markets["markets"]: rate = m["funding_rate"] if rate >= ENTRY_THRESHOLD: print(f"Harvesting {m['symbol']} at {rate*100:.4f}% / 8h") open_delta_neutral_short(m["symbol"]) time.sleep(3600)

Risk warnings.

Perpetual futures with leverage are among the most efficient instruments for destroying capital. Read this section before building any agent that opens real positions.

Leverage Amplifies Losses Symmetrically

The same multiplier that turns a 1% gain into a 10% return also turns a 1% loss into a 10% drawdown. At 10x leverage, a 10% adverse move wipes your entire margin. Crypto assets routinely move 5–15% in a single day. High leverage on volatile assets is not risk management — it is a countdown timer.

Liquidation is Irreversible

Once your margin ratio hits the maintenance threshold, the exchange liquidates your position without asking. There is no "wait and see." The position is gone, and the margin is consumed. An agent that does not actively monitor its margin ratio will eventually be liquidated — not if, but when.

Funding Drains Positions Silently

A position held for weeks in a persistent positive-funding environment pays funding every 8 hours. At 0.03% per interval (moderate bull), a $50,000 long pays $15 per interval — $45/day, $16,425/year. The position can be losing money even when the asset price is flat. Always account for funding cost in any strategy's expected return.

Cascading Liquidations & Slippage

During extreme volatility, many leveraged positions get liquidated simultaneously. The exchange sells them all at market, driving price further down, triggering more liquidations. This cascade can move price 10–20% in minutes. Agents that rely on stop-losses during a cascade may get filled far from their target price. Size conservatively and maintain a cash buffer.

Infinite Loss Potential on Shorts

A long position can lose at most 100% of margin — the asset cannot go below zero. A short position, in theory, has unlimited loss: if an asset 10x's from your entry, a 10x short with 10x leverage would owe 100x your margin (though liquidation triggers long before that). Short squeezes in small-cap alts can be violent and swift.

Agent Bugs Have Real Consequences

A trading agent with a logic bug — an off-by-one in position size, a missed edge case in the funding rate comparison, a crash that leaves a position open — can lose real money in seconds. Always start with paper trading or tiny real positions. Build explicit circuit breakers: maximum position size, maximum daily loss, automated kill switch.

Regulatory notice: Perpetual futures trading may be restricted or illegal in your jurisdiction. Purple Flea does not provide financial advice. This guide is educational only. Never risk capital you cannot afford to lose entirely.


Register for the Trading API.

Your agent can be trading 275 perp markets in under 10 minutes. No KYC. No withdrawal limits. Instant on-chain settlement via Hyperliquid.

1

Create a wallet

Register at wallet.purpleflea.com to create your agent's on-chain wallet. Funds are self-custodied — Purple Flea never holds your assets. Deposit USDC on Arbitrum to fund your trading account.

2

Generate a Trading API key

From your wallet dashboard, navigate to API Keys and create a new Trading API key. The key format is pf_sk_.... Scope it to trading only — no withdrawal permissions needed for most agent use cases.

3

Read the API documentation

Full endpoint reference at purpleflea.com/trading-api. Key endpoints: GET /trading/markets (list all 275+ perps), GET /trading/price (mark price + funding rate), POST /trading/order (open/close positions), GET /trading/positions (current open positions + margin ratios).

4

Start small and iterate

Begin with 1x–2x leverage and small position sizes (under 5% of capital per trade). Test your strategy logic with live data but minimal capital. Add automated circuit breakers before increasing size. Only scale up after confirming your agent handles edge cases: failed orders, network timeouts, unexpected funding rate changes.

5

Deploy and monitor

Run your agent on a cloud server or serverless function with an uptime monitor. Log all trades, funding payments, and margin ratio snapshots. Set up alerting on drawdown thresholds. The agent that survives long enough to compound is the agent that wins.


Related guides.

Ready to trade perps
with your AI agent?

275+ markets. No KYC. Instant on-chain settlement. Free to start.