AI Agents Trading Derivatives: Options, Perps, and Structured Products
Derivatives amplify an agent's ability to express precise market views, hedge existing exposure, and construct asymmetric payoff structures that simple spot trading cannot achieve. On Purple Flea Trading, AI agents have access to 275+ perpetual futures markets with up to 100x leverage — the building blocks for sophisticated derivative strategies. This guide covers perpetual mechanics, options Greeks (applied via synthetic positions), delta hedging, collar strategies, and a complete DerivativesAgent class.
Perpetual Futures Mechanics
Perpetual futures differ from traditional futures in one critical way: they have no expiry date. Instead of converging to spot price at settlement, perps use a funding rate mechanism to keep their price anchored to the underlying asset. Understanding this mechanism is foundational to any derivatives strategy on Purple Flea Trading.
Leverage and Margin
When you open a leveraged perpetual position, you post margin (collateral) and control a much larger notional value. A $100 margin at 10x leverage controls $1,000 in BTC-PERP exposure. The ratio of notional to margin is your leverage ratio.
from dataclasses import dataclass
@dataclass
class PerpPosition:
market: str
side: str # 'long' or 'short'
entry_price: float
notional_usdc: float
leverage: int
liquidation_price: float
@property
def margin_usdc(self) -> float:
return self.notional_usdc / self.leverage
def unrealized_pnl(self, current_price: float) -> float:
price_change = (current_price - self.entry_price) / self.entry_price
if self.side == "short":
price_change = -price_change
return price_change * self.notional_usdc
def roi_pct(self, current_price: float) -> float:
return self.unrealized_pnl(current_price) / self.margin_usdc * 100
def distance_to_liquidation_pct(self, current_price: float) -> float:
return abs(current_price - self.liquidation_price) / current_price * 100
# Example position
pos = PerpPosition(
market="BTC-PERP",
side="long",
entry_price=65000,
notional_usdc=1000,
leverage=5,
liquidation_price=52000
)
current = 67500
print(f"PnL: ${pos.unrealized_pnl(current):.2f}") # $38.46
print(f"ROI: {pos.roi_pct(current):.2f}%") # 19.23%
print(f"Liq distance: {pos.distance_to_liquidation_pct(current):.1f}%") # 23.0%
Funding Rates: The Hidden P&L Driver
The funding rate is paid every 8 hours. Positive funding means longs pay shorts; negative means shorts pay longs. For a position held across a funding period, this can be a significant driver of total P&L — either as a cost or income:
import asyncio, httpx, os
TRADING_BASE = "https://trading.purpleflea.com"
HEADERS = {"Authorization": f"Bearer {os.getenv('PURPLE_FLEA_KEY')}"}
async def funding_impact_analysis(market: str, position_usdc: float, side: str) -> dict:
"""
Calculate the annualized funding cost/income for holding a perpetual position.
"""
async with httpx.AsyncClient() as client:
r = await client.get(f"{TRADING_BASE}/api/ticker/{market}", headers=HEADERS)
data = r.json()
funding_8h = data["funding_rate"] # e.g. 0.0003 per 8h
payments_per_year = 3 * 365
# Long pays when funding is positive, earns when negative
# Short earns when funding is positive, pays when negative
funding_sign = 1 if side == "short" else -1
income_8h = funding_sign * funding_8h * position_usdc
income_annual = income_8h * payments_per_year
return {
"market": market,
"funding_rate_8h_pct": funding_8h * 100,
"income_per_8h_usdc": income_8h,
"annualized_income_usdc": income_annual,
"annualized_yield_pct": income_annual / position_usdc * 100,
"positive_for_side": income_8h > 0
}
Options Greeks for Agents (Synthetic Application)
Purple Flea Trading offers perpetual futures, not traditional options. However, options Greeks provide a conceptual toolkit that agents can apply to perp positions — especially for risk management, position sizing, and understanding non-linear exposure via leveraged positions:
| Greek | Meaning | Application to Perp Positions |
|---|---|---|
| Delta (Δ) | Sensitivity to underlying price change | A 10x long BTC-PERP has delta 10 — price up 1% = P&L up 10% |
| Gamma (Γ) | Rate of change of delta | As positions grow / compound, effective leverage changes |
| Theta (Θ) | Time decay (cost of holding) | Funding rate payments are the "theta" of perpetual positions |
| Vega (ν) | Sensitivity to volatility changes | High-vol markets → wider bid-ask → higher execution slippage |
| Rho (ρ) | Interest rate sensitivity | Funding rate regime driven by market interest in leverage |
import math
class PerpGreeks:
"""
Pseudo-Greeks for perpetual futures positions.
Useful for portfolio risk management across multiple positions.
"""
def __init__(self, position: PerpPosition):
self.position = position
def delta(self) -> float:
"""Portfolio delta: dollar change in P&L for $1 change in asset price."""
sign = 1 if self.position.side == "long" else -1
return sign * self.position.notional_usdc / self.position.entry_price
def dollar_delta(self) -> float:
"""Dollar-denominated delta for position sizing."""
sign = 1 if self.position.side == "long" else -1
return sign * self.position.notional_usdc
def theta_daily(self, funding_rate_8h: float) -> float:
"""Daily funding cost (negative = paying, positive = earning)."""
sign = -1 if self.position.side == "long" else 1
# 3 funding payments per day
return sign * funding_rate_8h * self.position.notional_usdc * 3
def value_at_risk_95(self, daily_vol: float) -> float:
"""95% 1-day Value at Risk for this position."""
# VaR = notional * daily_vol * z_95
z_95 = 1.645
return self.position.notional_usdc * daily_vol * z_95
# Portfolio-level Greeks aggregation
class PortfolioGreeks:
def __init__(self, positions: list[PerpPosition]):
self.greeks = [PerpGreeks(p) for p in positions]
def net_delta(self) -> float:
return sum(g.dollar_delta() for g in self.greeks)
def is_delta_neutral(self, tolerance_usdc: float = 50) -> bool:
return abs(self.net_delta()) < tolerance_usdc
def hedge_required(self, asset_price: float) -> tuple[str, float]:
"""Returns (side, size_usdc) needed to neutralize net delta."""
delta = self.net_delta()
if abs(delta) < 50: return ("none", 0)
side = "short" if delta > 0 else "long"
return (side, abs(delta))
Delta Hedging for Agents
Delta hedging keeps a portfolio's net directional exposure close to zero. This isolates other sources of return — funding rate income, basis trading, or volatility premium. The key is continuous rebalancing as prices move:
class DeltaHedger:
"""
Maintains delta-neutral portfolio by dynamically hedging with perp positions.
Useful for basis traders and funding rate farmers.
"""
def __init__(
self,
primary_market: str,
hedge_market: str,
rebalance_threshold_usdc: float = 100
):
self.primary_market = primary_market
self.hedge_market = hedge_market
self.threshold = rebalance_threshold_usdc
self.hedge_order_id: str | None = None
async def check_and_rebalance(self, portfolio: PortfolioGreeks) -> dict:
"""Check net delta and place hedge if threshold exceeded."""
net_delta = portfolio.net_delta()
if abs(net_delta) < self.threshold:
return {"action": "none", "net_delta": net_delta}
side, size = portfolio.hedge_required(asset_price=0)
async with httpx.AsyncClient() as client:
# Close existing hedge if any
if self.hedge_order_id:
await client.delete(
f"{TRADING_BASE}/api/orders/{self.hedge_order_id}",
headers=HEADERS
)
# Place new hedge
r = await client.post(
f"{TRADING_BASE}/api/orders",
json={
"market": self.hedge_market,
"side": side,
"size": size,
"type": "market"
},
headers=HEADERS
)
order = r.json()
self.hedge_order_id = order["order_id"]
return {
"action": "hedged",
"hedge_side": side,
"hedge_size_usdc": size,
"delta_before": net_delta
}
Collar Strategy with Perps
A collar is a classic options strategy that caps both upside and downside. With perpetuals, you can synthesize a collar by combining a spot-equivalent long position with a short perp at an upper strike and a long perp at a lower strike — effectively bounding your exposure range:
Hold a base long position in BTC-PERP at 1x leverage. Add a 2x short BTC-PERP triggered at your "strike high" (caps profit). Add a 2x long BTC-PERP triggered at your "strike low" (caps loss). Between strikes, you hold the full directional exposure; beyond the strikes, your additional position offsets it.
class CollarStrategy:
"""
Implements a synthetic collar using perpetual futures.
Base position + cap positions at upper and lower strike prices.
"""
def __init__(
self,
market: str,
base_size_usdc: float,
lower_strike_pct: float = 0.90, # protect at -10%
upper_strike_pct: float = 1.10, # cap at +10%
entry_price: float = 0
):
self.market = market
self.base_size = base_size_usdc
self.lower_strike = entry_price * lower_strike_pct
self.upper_strike = entry_price * upper_strike_pct
self.entry_price = entry_price
self.hedge_positions: dict = {}
async def open_collar(self) -> dict:
"""Open the base position and set collar trigger levels."""
async with httpx.AsyncClient() as client:
# Base: 1x long
base = await client.post(
f"{TRADING_BASE}/api/orders",
json={"market": self.market, "side": "long",
"size": self.base_size, "leverage": 1, "type": "market"},
headers=HEADERS
)
# Upper cap: limit short to trigger at upper strike
cap = await client.post(
f"{TRADING_BASE}/api/orders",
json={"market": self.market, "side": "short",
"size": self.base_size * 2, "leverage": 1,
"type": "limit", "price": self.upper_strike},
headers=HEADERS
)
# Lower floor: stop-loss buy to trigger at lower strike
floor = await client.post(
f"{TRADING_BASE}/api/orders",
json={"market": self.market, "side": "long",
"size": self.base_size * 2, "leverage": 1,
"type": "stop", "price": self.lower_strike},
headers=HEADERS
)
return {
"base": base.json()["order_id"],
"upper_cap": cap.json()["order_id"],
"lower_floor": floor.json()["order_id"],
"collar_range": f"${self.lower_strike:.0f} — ${self.upper_strike:.0f}"
}
def payoff_at_expiry(self, settlement_price: float) -> float:
"""Calculate total P&L at a given settlement price."""
base_pnl = (settlement_price - self.entry_price) / self.entry_price * self.base_size
# Cap upside at upper strike
if settlement_price > self.upper_strike:
cap_pnl = -(2 * self.base_size) * (settlement_price - self.upper_strike) / settlement_price
return base_pnl + cap_pnl
# Floor downside at lower strike
if settlement_price < self.lower_strike:
floor_pnl = (2 * self.base_size) * (self.lower_strike - settlement_price) / settlement_price
return base_pnl + floor_pnl
return base_pnl # within collar: full exposure
Structured Notes via Purple Flea
A structured note combines a fixed-income component (capital protection) with a leveraged derivatives component (upside participation). Using Purple Flea's multi-service stack, an agent can construct a structured note: deposit most capital conservatively while using a portion for high-leverage trading exposure:
class StructuredNote:
"""
Structured note: capital preservation + leveraged upside.
90% in safe yield, 10% in high-leverage perpetual long.
"""
def __init__(self, total_capital_usdc: float, market: str = "BTC-PERP"):
self.total = total_capital_usdc
self.market = market
# Classic 90/10 split: principal protection + upside kicker
self.principal_pct = 0.90
self.risk_pct = 0.10
def allocations(self) -> dict:
return {
"principal_usdc": self.total * self.principal_pct,
"risk_tranche_usdc": self.total * self.risk_pct,
# With 10x leverage on the risk tranche, notional exposure = 100% of total
"notional_exposure": self.total * self.risk_pct * 10,
"participation_rate": "100% of BTC upside"
}
async def deploy(self) -> dict:
alloc = self.allocations()
async with httpx.AsyncClient() as client:
# Risk tranche: 10x long on BTC-PERP with risk capital
r = await client.post(
f"{TRADING_BASE}/api/orders",
json={
"market": self.market,
"side": "long",
"size": alloc["risk_tranche_usdc"],
"leverage": 10,
"type": "market"
},
headers=HEADERS
)
return {"deployed": True, "allocations": alloc, "risk_order": r.json()}
def payoff_scenarios(self) -> dict:
alloc = self.allocations()
risk = alloc["risk_tranche_usdc"]
scenarios = {}
for change_pct in [-50, -20, 0, 20, 50, 100]:
pnl = min(risk, change_pct / 100 * risk * 10) # max loss = risk tranche
total_value = alloc["principal_usdc"] + risk + pnl
scenarios[f"{change_pct:+d}%"] = {
"total_value": total_value,
"return_pct": (total_value - self.total) / self.total * 100
}
return scenarios
Complete DerivativesAgent Class
Assembling all the above into a unified DerivativesAgent that can autonomously select strategies, manage positions, and rebalance its derivative book:
class DerivativesAgent:
"""
Autonomous derivatives trading agent for Purple Flea Trading.
Selects strategy based on market regime and manages positions.
"""
def __init__(self, capital_usdc: float = 1000, market: str = "BTC-PERP"):
self.capital = capital_usdc
self.market = market
self.positions: list[PerpPosition] = []
self.hedger = DeltaHedger(market, market, rebalance_threshold_usdc=75)
self.log: list[str] = []
async def assess_regime(self) -> str:
"""Determine current market regime: trending, ranging, or volatile."""
funding = await funding_impact_analysis(self.market, self.capital, "long")
rate = funding["funding_rate_8h_pct"]
if abs(rate) > 0.05: return "high_funding"
elif abs(rate) > 0.02: return "moderate_funding"
else: return "low_funding"
async def select_strategy(self) -> str:
"""Choose optimal strategy for current regime."""
regime = await self.assess_regime()
strategy_map = {
"high_funding": "funding_harvest",
"moderate_funding": "delta_neutral_mm",
"low_funding": "directional_collar"
}
strategy = strategy_map[regime]
self.log.append(f"Regime: {regime} → Strategy: {strategy}")
return strategy
async def execute_strategy(self, strategy: str) -> dict:
if strategy == "funding_harvest":
# Short to earn positive funding
funding = await funding_impact_analysis(self.market, self.capital * 0.5, "short")
if funding["positive_for_side"]:
async with httpx.AsyncClient() as client:
r = await client.post(
f"{TRADING_BASE}/api/orders",
json={"market": self.market, "side": "short",
"size": self.capital * 0.5, "leverage": 1,
"type": "market"},
headers=HEADERS
)
return {"strategy": strategy, "order": r.json(), "funding": funding}
elif strategy == "directional_collar":
async with httpx.AsyncClient() as client:
price_r = await client.get(f"{TRADING_BASE}/api/ticker/{self.market}", headers=HEADERS)
current = price_r.json()["price"]
collar = CollarStrategy(
market=self.market,
base_size_usdc=self.capital * 0.4,
lower_strike_pct=0.92, upper_strike_pct=1.12,
entry_price=current
)
return await collar.open_collar()
return {"strategy": strategy, "status": "deployed"}
async def run_cycle(self) -> dict:
"""Full agent cycle: assess → select strategy → execute → log."""
strategy = await self.select_strategy()
result = await self.execute_strategy(strategy)
self.log.append(f"Executed: {strategy}")
return {"strategy": strategy, "result": result, "log": self.log}
# Deploy the agent
async def main():
agent = DerivativesAgent(capital_usdc=500, market="BTC-PERP")
result = await agent.run_cycle()
print(f"Strategy: {result['strategy']}")
for entry in result["log"]:
print(f" {entry}")
asyncio.run(main())
Derivatives Risk Summary
| Strategy | Risk Profile | Best Market Condition | Key Risk |
|---|---|---|---|
| Funding harvest (short) | Low directional, high funding income | High positive funding (> 0.05%/8h) | Short squeeze liquidation |
| Delta-neutral MM | Near-zero directional | Range-bound, moderate vol | Rapid trend exhausting inventory |
| Collar strategy | Bounded directional | Moderate bullish outlook | Capped upside during strong rally |
| Structured note (90/10) | Capital protected with levered kicker | Long-term bullish with risk budget | Risk tranche complete loss possible |
| High leverage directional | Maximum directional exposure | High-conviction trending market | Liquidation at small price move |
Trade Derivatives on Purple Flea Trading
Access 275+ perpetual futures markets, funding rate data, and API-driven order management. Register your agent and deploy your first derivatives strategy.
Get API Key Claim Free USDCDerivatives trading rewards agents that understand the full mechanics of the instruments they trade. Master funding rates, think in terms of Greeks even without formal options markets, manage delta exposure actively, and structure positions that match your risk tolerance. The complexity of derivatives is not a barrier — for agents that can automate the math, it is a competitive advantage.