Strategy Guide

Perpetual Hedging for AI Agents: Delta-Neutral Strategies and Funding Rate Capture

Build autonomous hedging bots that maintain delta-neutral portfolios, harvest positive funding rates, and execute basis trades — all with zero human intervention.

March 7, 2026 22 min read Advanced Python + Purple Flea API

What Are Perpetual Futures and Why Do Agents Need Them?

Perpetual futures are derivative contracts that never expire. Unlike quarterly futures, they track spot prices continuously through a mechanism called the funding rate — a periodic payment exchanged between long and short holders to keep the contract price anchored to the spot index.

For AI agents operating in volatile crypto markets, perpetual futures serve three critical functions:

An agent that ignores perpetuals is leaving substantial alpha on the table. This guide covers the mechanics in depth, then builds a complete PerpHedgingAgent in Python that integrates with the Purple Flea Trading API.

Funding Rate (Bull Market)
0.01%
Every 8 hrs — longs pay shorts
Annual Equivalent
10.95%
From funding alone (at 0.01% / 8h)
Basis Trade Spread
0.3–2%
Typical perp premium over spot
Liquidation Risk
Zero
On delta-neutral positions

Funding Rate Mechanics

The funding rate is calculated every 8 hours (on most exchanges) and paid between counterparties. The formula used by most perpetual exchanges is:

Funding Rate = Clamp(Premium Index + Interest Rate, -max_rate, +max_rate)

Premium Index = (Mark Price - Spot Index) / Spot Index
Interest Rate = 0.01% (fixed baseline on most venues)
max_rate = typically 0.75% per 8h period

# Payment direction: # Positive rate → longs pay shorts # Negative rate → shorts pay longs

When Bitcoin trades at a premium to spot (bull markets), longs pay shorts every 8 hours. An agent holding short perpetuals + long spot collects funding while remaining directionally neutral. This is the core of the cash-and-carry or basis trade strategy.

i
Funding Rate Aggregation

Rates vary significantly across exchanges. Binance, Bybit, OKX, and dYdX all calculate funding independently. An agent can monitor all venues and open shorts where the rate is highest, dramatically improving yield.

Building a Delta-Neutral Portfolio

Delta measures your portfolio's sensitivity to price movement. A delta of 1.0 means you gain or lose exactly $1 for every $1 the underlying moves. A delta-neutral portfolio has aggregate delta of 0 — you neither profit nor lose from directional price changes.

Delta Calculation

For a portfolio of spot holdings and perpetual positions:

Portfolio Delta = (Spot Holdings × 1.0) + (Perp Positions × perp_delta)

# For linear perps (USDT-margined): # Long 1 BTC perp → delta = +1.0 # Short 1 BTC perp → delta = -1.0 # # For inverse perps (coin-margined): # delta is non-linear — varies with price
Hedge Ratio = Spot Holdings / Contract Size
Hedge Size = round(Hedge Ratio / 0.001) × 0.001 # respect tick size

Rebalancing Triggers

A delta-neutral position drifts over time as prices move and funding accrues. Agents must define clear rebalancing triggers:

Three Core Hedging Strategies

Strategy 1: Cash-and-Carry Basis Trade

Buy spot, short the perpetual at a premium, collect the spread plus funding. The position is closed when the basis compresses.

+
Example — BTC Basis Trade

BTC spot: $95,000. BTC perp: $95,380 (+0.4% premium). Open: buy 1 BTC spot, short 1 BTC perp. Funding rate: +0.01%/8h. P&L = basis compression ($380) + 30 days funding (30 × 3 × $9.50 = $855). Total: $1,235 risk-free over 30 days on ~$95,000 capital = 15.6% APR.

Strategy 2: Dynamic Delta Hedging

Hold a volatile asset (e.g., altcoin with positive expected return) and continuously hedge directional exposure with BTC or ETH perpetuals. This captures the alpha from the altcoin's outperformance while removing macro crypto market risk.

Strategy 3: Funding Rate Farming

Monitor funding rates across all venues. When rates are unusually high (e.g., >0.05% per 8h), open a hedged position to collect funding. Exit when rates normalize. This is especially profitable during euphoric market periods when longs are highly leveraged.

Strategy Directional Risk Primary Yield Source Best Market Typical APR
Cash-and-Carry None Basis + Funding Bull markets 8–20%
Dynamic Hedge Low (idiosyncratic only) Altcoin alpha Any trending Variable
Funding Farming None Funding payments High funding 10–40%
Short Gamma Hedge Moderate Theta decay + funding Low volatility 5–15%

Full Python PerpHedgingAgent Implementation

The following agent monitors funding rates, manages a delta-neutral portfolio, and executes rebalancing trades automatically via the Purple Flea Trading API.

perpetual_hedging_agent.py Python 3.11+
import asyncio
import time
import json
import httpx
from dataclasses import dataclass, field
from typing import Optional
from enum import Enum

# ── Configuration ──────────────────────────────────────────────────────────
API_BASE = "https://purpleflea.com/api"
API_KEY  = "pf_live_your_key_here"   # Register at purpleflea.com/for-agents
WALLET_API = "https://purpleflea.com/api/wallet"

class Venue(Enum):
    BINANCE  = "binance"
    BYBIT    = "bybit"
    OKX      = "okx"
    DYDX     = "dydx"

@dataclass
class Position:
    symbol: str
    side: str              # "long" or "short"
    size: float            # in base asset units
    entry_price: float
    venue: Venue
    unrealized_pnl: float  = 0.0
    funding_collected: float = 0.0

@dataclass
class Portfolio:
    spot_holdings: dict[str, float] = field(default_factory=dict)
    perp_positions: list[Position]  = field(default_factory=list)
    total_delta: float              = 0.0
    total_funding_earned: float     = 0.0

    def compute_delta(self, prices: dict[str, float]) -> float:
        """Compute aggregate portfolio delta in USD."""
        delta = 0.0
        for symbol, qty in self.spot_holdings.items():
            price = prices.get(symbol, 0)
            delta += qty * price                    # spot = +1 delta per unit
        for pos in self.perp_positions:
            price = prices.get(pos.symbol, 0)
            sign = 1.0 if pos.side == "long" else -1.0
            delta += sign * pos.size * price        # linear perp delta
        self.total_delta = delta
        return delta


class PerpHedgingAgent:
    """
    Autonomous perpetual hedging agent for Purple Flea.
    Maintains delta-neutral portfolios and harvests funding rates.
    """

    FUNDING_INTERVAL   = 28_800          # 8 hours in seconds
    REBALANCE_INTERVAL = 3_600           # check every 1 hour
    DELTA_THRESHOLD    = 0.05            # rebalance if |delta| > 5% of portfolio
    MIN_FUNDING_RATE   = 0.0002          # 0.02% per 8h = ~9% APR minimum threshold
    MAX_LEVERAGE       = 3.0             # never exceed 3x

    def __init__(self):
        self.portfolio   = Portfolio()
        self.client      = httpx.AsyncClient(
            headers={"Authorization": f"Bearer {API_KEY}",
                     "Content-Type": "application/json"},
            timeout=30
        )
        self.last_funding_check = 0.0
        self.positions_log: list[dict] = []

    # ── Market Data ────────────────────────────────────────────────────────

    async def get_prices(self, symbols: list[str]) -> dict[str, float]:
        """Fetch current spot prices from Purple Flea price feed."""
        r = await self.client.get(
            f"{API_BASE}/prices",
            params={"symbols": ",".join(symbols)}
        )
        r.raise_for_status()
        data = r.json()
        return {item["symbol"]: float(item["price"]) for item in data["prices"]}

    async def get_funding_rates(self) -> list[dict]:
        """
        Fetch funding rates from all supported venues.
        Returns sorted list by rate descending.
        """
        r = await self.client.get(f"{API_BASE}/perps/funding-rates")
        r.raise_for_status()
        rates = r.json()["rates"]
        # Sort by funding rate descending — highest yield first
        return sorted(rates, key=lambda x: x["rate"], reverse=True)

    async def get_basis(self, symbol: str) -> dict:
        """Get spot vs perp basis for a symbol across all venues."""
        r = await self.client.get(
            f"{API_BASE}/perps/basis",
            params={"symbol": symbol}
        )
        r.raise_for_status()
        return r.json()

    # ── Trade Execution ────────────────────────────────────────────────────

    async def open_short_perp(
        self,
        symbol: str,
        size: float,
        venue: Venue,
        reason: str = "hedge"
    ) -> Optional[Position]:
        """Open a short perpetual position on the specified venue."""
        payload = {
            "symbol":    symbol,
            "side":      "sell",
            "type":      "market",
            "size":      size,
            "venue":     venue.value,
            "reduce_only": False,
            "leverage":  1.0,          # 1x — delta-neutral never needs leverage
            "metadata":  {"strategy": "perp_hedge", "reason": reason}
        }
        try:
            r = await self.client.post(f"{API_BASE}/perps/order", json=payload)
            r.raise_for_status()
            data = r.json()
            pos = Position(
                symbol       = symbol,
                side         = "short",
                size         = size,
                entry_price  = float(data["fill_price"]),
                venue        = venue
            )
            self.portfolio.perp_positions.append(pos)
            print(f"[HEDGE] Opened short {size} {symbol} @ {pos.entry_price:.2f} on {venue.value}")
            return pos
        except Exception as e:
            print(f"[ERROR] Failed to open short perp: {e}")
            return None

    async def close_position(self, position: Position) -> float:
        """Close an existing perpetual position. Returns realized PnL."""
        payload = {
            "symbol":    position.symbol,
            "side":      "buy" if position.side == "short" else "sell",
            "type":      "market",
            "size":      position.size,
            "venue":     position.venue.value,
            "reduce_only": True
        }
        try:
            r = await self.client.post(f"{API_BASE}/perps/order", json=payload)
            r.raise_for_status()
            data = r.json()
            exit_price = float(data["fill_price"])
            pnl = (position.entry_price - exit_price) * position.size  # short pnl
            self.portfolio.perp_positions.remove(position)
            print(f"[CLOSE] Closed {position.symbol} short. PnL: ${pnl:.2f}")
            await self.log_income(pnl, "perpetual_hedge_pnl", position.symbol)
            return pnl
        except Exception as e:
            print(f"[ERROR] Failed to close position: {e}")
            return 0.0

    async def adjust_hedge(self, symbol: str, target_delta: float, current_delta: float):
        """Adjust perp size to bring delta closer to target (usually 0)."""
        delta_gap = target_delta - current_delta
        prices = await self.get_prices([symbol])
        price = prices.get(symbol, 0)
        if price == 0:
            return
        size_adj = abs(delta_gap) / price
        size_adj = round(size_adj / 0.001) * 0.001  # round to tick size

        if size_adj < 0.001:
            return  # below minimum order size

        if delta_gap < 0:
            # Portfolio is too long — add short
            await self.open_short_perp(symbol, size_adj, Venue.BYBIT, reason="rebalance")
        else:
            # Portfolio is too short — close some shorts
            for pos in self.portfolio.perp_positions:
                if pos.symbol == symbol and pos.side == "short":
                    if pos.size <= size_adj:
                        await self.close_position(pos)
                        size_adj -= pos.size
                    else:
                        # Partial close via reduce_only order
                        await self.partial_close(pos, size_adj)
                    break

    async def partial_close(self, position: Position, size: float):
        """Partially close a position by specified size."""
        payload = {
            "symbol":      position.symbol,
            "side":        "buy",
            "type":        "market",
            "size":        size,
            "venue":       position.venue.value,
            "reduce_only": True
        }
        r = await self.client.post(f"{API_BASE}/perps/order", json=payload)
        r.raise_for_status()
        position.size -= size
        print(f"[PARTIAL] Reduced {position.symbol} short by {size}")

    # ── Funding Rate Strategy ──────────────────────────────────────────────

    async def find_best_funding_opportunity(self) -> Optional[dict]:
        """
        Scan funding rates across venues. Return the best opportunity
        if rate exceeds minimum threshold.
        """
        rates = await self.get_funding_rates()
        if not rates:
            return None
        best = rates[0]
        if float(best["rate"]) >= self.MIN_FUNDING_RATE:
            annual_equiv = float(best["rate"]) * 3 * 365 * 100
            print(
                f"[FUNDING] Best: {best['symbol']} on {best['venue']} "
                f"rate={float(best['rate'])*100:.4f}%/8h "
                f"(~{annual_equiv:.1f}% APR)"
            )
            return best
        return None

    async def execute_funding_harvest(self, opportunity: dict):
        """
        Execute a funding rate harvest:
        1. Buy spot on cheapest venue
        2. Short perp on venue with highest funding
        """
        symbol  = opportunity["symbol"]
        venue   = Venue(opportunity["venue"])
        rate    = float(opportunity["rate"])
        capital = 10_000  # USD to deploy

        prices = await self.get_prices([symbol])
        price  = prices.get(symbol, 0)
        if price == 0:
            return

        size = round((capital / price) / 0.001) * 0.001

        # In a real implementation, buy spot separately
        self.portfolio.spot_holdings[symbol] = self.portfolio.spot_holdings.get(symbol, 0) + size
        print(f"[SPOT] Acquired {size} {symbol} @ {price:.2f}")

        # Short perp to hedge
        await self.open_short_perp(symbol, size, venue, reason="funding_harvest")

        # Track expected funding income
        funding_per_8h = rate * size * price
        print(
            f"[HARVEST] Funding harvest open. "
            f"Expected: ${funding_per_8h:.2f} per 8h / "
            f"${funding_per_8h * 3 * 30:.2f} monthly"
        )

    # ── Basis Trade ────────────────────────────────────────────────────────

    async def execute_basis_trade(self, symbol: str, min_basis_pct: float = 0.2):
        """
        Execute basis trade if perp premium exceeds threshold.
        Buy spot, short perp, collect basis as it compresses.
        """
        basis_data = await self.get_basis(symbol)
        best_venue = max(basis_data["venues"], key=lambda v: v["basis_pct"])
        basis_pct  = float(best_venue["basis_pct"])

        if basis_pct < min_basis_pct:
            print(f"[BASIS] {symbol} basis {basis_pct:.3f}% below threshold {min_basis_pct}%. Skip.")
            return

        spot_price = float(basis_data["spot_price"])
        capital    = 5_000
        size       = round((capital / spot_price) / 0.001) * 0.001

        self.portfolio.spot_holdings[symbol] = self.portfolio.spot_holdings.get(symbol, 0) + size
        print(f"[BASIS] Bought {size} {symbol} spot @ {spot_price:.2f}")

        venue = Venue(best_venue["venue"])
        await self.open_short_perp(symbol, size, venue, reason="basis_trade")

        expected_pnl = size * spot_price * (basis_pct / 100)
        print(f"[BASIS] Trade open. Basis: {basis_pct:.3f}%. Expected P&L: ${expected_pnl:.2f}")

    # ── Rebalancing ────────────────────────────────────────────────────────

    async def rebalance_portfolio(self):
        """Check delta and rebalance if threshold exceeded."""
        symbols = list(self.portfolio.spot_holdings.keys())
        if not symbols:
            return

        prices = await self.get_prices(symbols)
        delta  = self.portfolio.compute_delta(prices)

        total_value = sum(
            qty * prices.get(sym, 0)
            for sym, qty in self.portfolio.spot_holdings.items()
        )
        delta_ratio = abs(delta) / total_value if total_value > 0 else 0

        print(f"[DELTA] Portfolio delta: ${delta:.2f} ({delta_ratio*100:.2f}% of AUM)")

        if delta_ratio > self.DELTA_THRESHOLD:
            print(f"[REBALANCE] Delta {delta_ratio*100:.2f}% exceeds threshold. Rebalancing...")
            for symbol in symbols:
                spot_val = self.portfolio.spot_holdings[symbol] * prices.get(symbol, 0)
                if spot_val > 1000:  # Only hedge meaningful positions
                    await self.adjust_hedge(symbol, 0, delta)
        else:
            print(f"[OK] Delta within threshold. No rebalance needed.")

    # ── Logging ────────────────────────────────────────────────────────────

    async def log_income(self, amount: float, income_type: str, symbol: str):
        """Log income to Purple Flea Wallet API for tracking."""
        payload = {
            "type":     income_type,
            "amount":   amount,
            "currency": "USDC",
            "symbol":   symbol,
            "strategy": "perp_hedging",
            "timestamp": int(time.time())
        }
        try:
            r = await self.client.post(f"{WALLET_API}/log-income", json=payload)
            r.raise_for_status()
            self.portfolio.total_funding_earned += amount
        except Exception as e:
            print(f"[WARN] Failed to log income: {e}")

    def print_portfolio_summary(self):
        """Print current portfolio state."""
        print("\n" + "="*60)
        print("PORTFOLIO SUMMARY")
        print("="*60)
        print(f"Spot Holdings:    {self.portfolio.spot_holdings}")
        print(f"Perp Positions:   {len(self.portfolio.perp_positions)}")
        print(f"Total Delta:      ${self.portfolio.total_delta:.2f}")
        print(f"Funding Earned:   ${self.portfolio.total_funding_earned:.2f}")
        for pos in self.portfolio.perp_positions:
            print(
                f"  {pos.side.upper()} {pos.size} {pos.symbol} "
                f"@ {pos.entry_price:.2f} [{pos.venue.value}]"
            )
        print("="*60 + "\n")

    # ── Main Loop ──────────────────────────────────────────────────────────

    async def run(self):
        """Main agent loop — runs indefinitely."""
        print("[START] PerpHedgingAgent starting...")

        # Initial strategy selection
        await self.execute_basis_trade("BTC")

        opp = await self.find_best_funding_opportunity()
        if opp:
            await self.execute_funding_harvest(opp)

        while True:
            try:
                # Periodic rebalance
                await self.rebalance_portfolio()
                self.print_portfolio_summary()

                # Re-evaluate funding opportunities every 8 hours
                now = time.time()
                if now - self.last_funding_check > self.FUNDING_INTERVAL:
                    opp = await self.find_best_funding_opportunity()
                    if opp:
                        await self.execute_funding_harvest(opp)
                    self.last_funding_check = now

                await asyncio.sleep(self.REBALANCE_INTERVAL)

            except KeyboardInterrupt:
                print("[STOP] Agent shutting down...")
                break
            except Exception as e:
                print(f"[ERROR] Main loop error: {e}")
                await asyncio.sleep(60)


if __name__ == "__main__":
    agent = PerpHedgingAgent()
    asyncio.run(agent.run())

Advanced Funding Rate Farming

Funding rate farming becomes highly profitable during speculative bull runs when retail traders are massively leveraged long. During Bitcoin's parabolic moves, funding rates can reach 0.1–0.3% per 8 hours — equivalent to 110–328% APR.

Multi-Venue Funding Arbitrage

Even more sophisticated agents can simultaneously be long on one venue (receiving funding) and short on another (paying lower funding), capturing the cross-venue spread. This requires careful collateral management.

funding_arb.py Cross-venue funding arbitrage
async def find_cross_venue_funding_arb(agent: PerpHedgingAgent) -> Optional[dict]:
    """
    Find cases where funding rate diverges between venues.
    E.g., Binance BTC funding: +0.08% / Bybit BTC funding: +0.03%
    → Long on Bybit (pay 0.03%), short on Binance (receive 0.08%)
    → Net: +0.05% per 8h = +54.7% APR, zero directional risk
    """
    rates = await agent.get_funding_rates()

    # Group by symbol
    by_symbol: dict[str, list] = {}
    for rate in rates:
        sym = rate["symbol"]
        by_symbol.setdefault(sym, []).append(rate)

    best_opp = None
    best_spread = 0.0

    for symbol, venues in by_symbol.items():
        if len(venues) < 2:
            continue
        venues_sorted = sorted(venues, key=lambda v: float(v["rate"]))
        lowest   = venues_sorted[0]   # pay this (long side)
        highest  = venues_sorted[-1]  # receive this (short side)
        spread   = float(highest["rate"]) - float(lowest["rate"])

        if spread > best_spread and spread > 0.0003:  # 0.03% minimum spread
            best_spread = spread
            best_opp = {
                "symbol":   symbol,
                "long_venue":  lowest["venue"],
                "short_venue": highest["venue"],
                "long_rate":   float(lowest["rate"]),
                "short_rate":  float(highest["rate"]),
                "spread":      spread,
                "annual_equiv": spread * 3 * 365 * 100
            }

    if best_opp:
        print(
            f"[XVENUE] Best cross-venue arb: {best_opp['symbol']} "
            f"Long {best_opp['long_venue']} ({best_opp['long_rate']*100:.4f}%/8h) "
            f"Short {best_opp['short_venue']} ({best_opp['short_rate']*100:.4f}%/8h) "
            f"Spread: {best_opp['spread']*100:.4f}%/8h "
            f"(~{best_opp['annual_equiv']:.1f}% APR)"
        )
    return best_opp

Risk Management for Hedged Positions

While delta-neutral positions eliminate directional risk, they introduce other risks that agents must manage:

Funding Rate Flip Risk

If market sentiment reverses, funding rates can flip negative — meaning shorts pay longs. An agent collecting funding from a short position would suddenly be paying. The mitigation is to set a stop-loss on funding yield: if the rate drops below 0, close the hedge and redeploy capital.

funding_monitor.py Funding flip detection
async def monitor_funding_flip(agent: PerpHedgingAgent):
    """Monitor and react to funding rate flips."""
    while True:
        rates = await agent.get_funding_rates()
        rate_map = {r["symbol"]: float(r["rate"]) for r in rates}

        for pos in list(agent.portfolio.perp_positions):
            if pos.side != "short":
                continue
            rate = rate_map.get(pos.symbol, 0)
            if rate < 0:
                print(
                    f"[FLIP] {pos.symbol} funding flipped to {rate*100:.4f}%/8h. "
                    f"Closing short to stop paying funding."
                )
                pnl = await agent.close_position(pos)
                print(f"[FLIP] Closed with PnL ${pnl:.2f}")

        await asyncio.sleep(3600)  # check hourly

Margin Utilization Risk

Even at 1x leverage, cross-margin accounts can face liquidation if unrealized losses elsewhere drain the margin pool. Agents should:

Basis Risk on Exit

A basis trade assumes the premium will compress to zero over time. In highly trending markets, the basis can persist or even widen before compressing. Set a maximum holding period and exit at a predefined stop-loss if basis widens beyond 2x your entry level.

!
Exchange Counterparty Risk

Perpetual positions are custodied on centralized exchanges. An agent should never keep more than 30% of total capital on any single venue. Distribute positions across Binance, Bybit, OKX, and dYdX to minimize concentration risk.

P&L Calculation and Tracking

A hedging agent must track multiple income streams simultaneously:

# Total P&L Components for a Cash-and-Carry Position:

spot_pnl = (spot_exit_price - spot_entry_price) × size
perp_pnl = (perp_entry_price - perp_exit_price) × size # short
funding_pnl = Σ (funding_rate × notional_value) # collected every 8h
fee_cost = (spot_fees + perp_fees) × total_notional

net_pnl = spot_pnl + perp_pnl + funding_pnl - fee_cost

# Break-even funding rate (must collect at least this to cover fees): # break_even_rate = (2 × taker_fee) / periods_per_year # With 0.05% taker fee: 2×0.05% / (365×3) = 0.0000913% per 8h

Logging to Purple Flea Wallet API

All income streams are logged to the Purple Flea Wallet API, which provides a unified ledger for tax reporting and performance attribution.

pnl_tracker.py Multi-stream P&L tracking
@dataclass
class PnLRecord:
    timestamp: int
    strategy:  str
    symbol:    str
    spot_pnl:  float
    perp_pnl:  float
    funding_pnl: float
    fees:      float
    net_pnl:   float

class PnLTracker:
    def __init__(self, wallet_api: str, api_key: str):
        self.wallet_api = wallet_api
        self.records: list[PnLRecord] = []
        self.client = httpx.AsyncClient(
            headers={"Authorization": f"Bearer {api_key}"}
        )

    async def record_trade(
        self,
        strategy: str,
        symbol: str,
        spot_pnl: float,
        perp_pnl: float,
        funding_pnl: float,
        fees: float
    ) -> PnLRecord:
        net = spot_pnl + perp_pnl + funding_pnl - fees
        rec = PnLRecord(
            timestamp   = int(time.time()),
            strategy    = strategy,
            symbol      = symbol,
            spot_pnl    = spot_pnl,
            perp_pnl    = perp_pnl,
            funding_pnl = funding_pnl,
            fees        = fees,
            net_pnl     = net
        )
        self.records.append(rec)
        await self._push_to_wallet(rec)
        return rec

    async def _push_to_wallet(self, rec: PnLRecord):
        payload = {
            "type":      "hedging_pnl",
            "amount":    rec.net_pnl,
            "currency":  "USDC",
            "breakdown": {
                "spot_pnl":    rec.spot_pnl,
                "perp_pnl":    rec.perp_pnl,
                "funding_pnl": rec.funding_pnl,
                "fees":        rec.fees
            },
            "strategy":  rec.strategy,
            "symbol":    rec.symbol,
            "timestamp": rec.timestamp
        }
        await self.client.post(f"{self.wallet_api}/transactions", json=payload)

    def summary(self) -> dict:
        """Compute aggregate P&L statistics."""
        total_net     = sum(r.net_pnl for r in self.records)
        total_funding = sum(r.funding_pnl for r in self.records)
        total_fees    = sum(r.fees for r in self.records)
        win_rate      = sum(1 for r in self.records if r.net_pnl > 0) / max(len(self.records), 1)
        return {
            "total_net_pnl":     total_net,
            "total_funding_pnl": total_funding,
            "total_fees":        total_fees,
            "trade_count":       len(self.records),
            "win_rate":          win_rate
        }

Purple Flea Integration

The perpetual hedging agent integrates with multiple Purple Flea services to form a complete autonomous financial unit:

*
Start with the Faucet

New agents can claim free USDC from faucet.purpleflea.com to experiment with hedging positions at small sizes before deploying real capital. The faucet also demonstrates registration with the Purple Flea Wallet API — the same flow used in production hedging bots.

Deploying the Agent

Running a perpetual hedging agent in production requires careful infrastructure setup. The agent must be available 24/7 to react to funding rate windows and rebalance drift promptly.

  1. 1
    Register API keys

    Create your account at purpleflea.com/for-agents and generate a Trading API key (prefix: pf_live_). Add exchange API keys for each venue you will trade on.

  2. 2
    Fund with stablecoins

    Deposit USDC to your Wallet. Alternatively, claim from the Faucet for a no-risk trial. Minimum recommended starting capital: $1,000 USDC per venue.

  3. 3
    Deploy with PM2

    Run pm2 start perpetual_hedging_agent.py --name hedge-agent --interpreter python3 on a VPS. Use PM2's built-in process resurrection to ensure the agent restarts after crashes.

  4. 4
    Set monitoring alerts

    Configure alerts for: margin ratio below 50%, funding rate flip, basis wider than 2x entry, and any unhandled exceptions in the agent loop.

  5. 5
    Review P&L weekly

    Use the Wallet API's /analytics endpoint to export weekly P&L breakdowns by stream (spot, perp, funding). Adjust minimum funding rate thresholds based on realized performance.

Strategy Comparison Summary

Perpetual hedging strategies span a wide risk-return spectrum. The right choice depends on current market conditions, available capital, and the agent's risk tolerance:

Strategy Capital Required Risk Level Best When Monthly Yield
Funding harvest (single venue) $1,000+ Very Low Rate > 0.05%/8h 0.6–3%
Basis trade (cash-and-carry) $5,000+ Very Low Premium > 0.3% 0.7–1.5%
Cross-venue funding arb $10,000+ Low Spread > 0.03%/8h 1–4.5%
Dynamic altcoin hedge $2,000+ Moderate Strong altcoin signal Variable
Negative funding harvest $1,000+ Very Low Bear markets 0.3–2%
+
Get Started Today

Register your agent at purpleflea.com/for-agents, claim free USDC from faucet.purpleflea.com, and deploy the PerpHedgingAgent. Questions? Open an issue on the agent-starter-kit GitHub repo.