1. Hyperliquid Architecture: The HL EVM L1
Hyperliquid launched as one of the first purpose-built perpetuals chains — a custom Layer 1 with its own EVM-compatible environment called HyperEVM. Unlike generic EVM chains or Cosmos appchains, Hyperliquid uses a proprietary consensus mechanism (HyperBFT) that achieves median block confirmation times under 1 second with finality in roughly 2 seconds.
For AI agents, this matters enormously. An agent strategy that relies on sub-second order adjustments can actually function on Hyperliquid in a way that is impossible on Ethereum L1 (12s blocks) or even many L2s with 250ms target times but unpredictable sequencer delays.
HyperEVM vs L1 Native Environment
Hyperliquid has two execution environments:
- L1 Native (Perps/Spot): All order book activity happens here. No Solidity required — orders are submitted via signed JSON messages over the REST/WebSocket API. This is where 99% of agent trading happens.
- HyperEVM: A standard EVM where Solidity smart contracts can be deployed. Smart contracts can interact with the native perps engine via precompiles, enabling on-chain vault automation and protocol-level composability.
Account Model
Accounts on Hyperliquid are EVM-compatible addresses (secp256k1 keypairs). You sign orders with the same Ethereum private key format. Deposits happen by bridging USDC from Arbitrum onto the Hyperliquid L1. Once bridged, your USDC is available as collateral for all perpetual positions.
2. Supported Markets and Instruments
Hyperliquid launched with BTC-PERP and ETH-PERP and has grown rapidly to over 150 perpetual markets. The exchange uses a central limit order book (CLOB) model — not an AMM — which means agents can post limit orders and potentially earn maker rebates rather than always crossing the spread.
Perpetual Markets
All perpetuals on Hyperliquid are USDC-margined. Positions are isolated by default but cross-margin mode is available for multi-position portfolios. Maximum leverage varies by asset:
| Asset | Max Leverage | Min Order Size | Tick Size |
|---|---|---|---|
| BTC-PERP | 50x | 0.001 BTC | $0.10 |
| ETH-PERP | 50x | 0.01 ETH | $0.01 |
| SOL-PERP | 20x | 1 SOL | $0.001 |
| ARB-PERP | 10x | 10 ARB | $0.0001 |
| Long-tail | 5–10x | Varies | Varies |
Spot Markets
Hyperliquid also supports native spot trading. The HYPE token (the protocol's native governance token) is tradeable spot, as are a growing number of project tokens that list directly on the HL L1 without needing a bridge.
Funding Rate Mechanics
Like most perps venues, Hyperliquid uses a continuous 1-hour funding mechanism. The funding rate is calculated every hour and applied proportionally each second. Agents running funding arbitrage strategies need to account for the 8-hour settlement cycle when computing expected yield.
3. Order Book Mechanics for Agents
The Hyperliquid CLOB is fully transparent and accessible in real-time via WebSocket. Understanding the order book structure is essential for agents that need to post orders, manage fills, and avoid slippage on larger positions.
Order Types
- Limit (GTC / IOC / ALO): Good-Till-Cancel, Immediate-Or-Cancel, Add-Liquidity-Only. ALO is critical for maker-only strategies — the order is cancelled if it would immediately fill.
- Market: Crosses the spread immediately. Agents should use sparingly on illiquid markets.
- Stop Market / Stop Limit: Conditional orders triggered by mark price. Stored in the engine and triggered server-side — agents do not need to monitor and cancel/replace.
- Scale Orders: A convenience type that places a ladder of limit orders across a price range in a single API call.
- TWAP: Hyperliquid natively supports time-weighted average price execution — an agent can submit a TWAP order and the engine will drip the quantity over the specified duration.
Fee Structure
Fees depend on your 14-day volume tier. The base fees are:
| Role | Base Fee | Notes |
|---|---|---|
| Taker | 0.035% | Reduces to 0.025% at higher tiers |
| Maker | -0.01% | Rebate — you earn for adding liquidity |
| Referral discount | 10% | Applied to taker fee |
4. API Authentication
Hyperliquid uses a signature-based authentication scheme. There are no API keys in the traditional sense — all requests are signed with an Ethereum private key. Hyperliquid provides two signing modes:
Agent Wallet Pattern
For production agents, the recommended pattern is to use an agent wallet — a separate keypair that is authorized by your main account. This way, the agent wallet private key can be stored in the agent's environment without exposing your main account's assets to compromise.
from eth_account import Account
from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
import json
# Main account — only used to authorize the agent wallet
main_account = Account.from_key("0xYOUR_MAIN_PRIVATE_KEY")
# Agent wallet — safe to store in environment
agent_wallet = Account.from_key("0xAGENT_PRIVATE_KEY")
# Initialize exchange with main account to authorize agent
exchange = Exchange(main_account, base_url="https://api.hyperliquid.xyz")
# Authorize the agent wallet
result = exchange.approve_agent(
agent_address=agent_wallet.address,
agent_name="purple-flea-agent-v1"
)
print(f"Agent authorized: {result}")
# Now create exchange instance using agent wallet
agent_exchange = Exchange(
agent_wallet,
base_url="https://api.hyperliquid.xyz",
account_address=main_account.address # trade on behalf of main
)
Installing the SDK
pip install hyperliquid-python-sdk eth-account websockets aiohttp
5. Placing Orders via Python SDK
The Hyperliquid Python SDK provides both synchronous and async interfaces. For agents running continuous loops, the async WebSocket interface is strongly preferred as it avoids polling and reduces latency significantly.
Basic Order Placement
from hyperliquid.exchange import Exchange
from hyperliquid.utils import constants
from eth_account import Account
import time
account = Account.from_key("0xAGENT_PRIVATE_KEY")
exchange = Exchange(
account,
base_url=constants.MAINNET_API_URL,
account_address="0xMAIN_ACCOUNT_ADDRESS"
)
# Place a limit buy order for 0.01 BTC at $60,000
order_result = exchange.order(
coin="BTC",
is_buy=True,
sz=0.01, # size in base asset
limit_px=60000.0,
order_type={"limit": {"tif": "Gtc"}},
reduce_only=False
)
print(f"Order status: {order_result['status']}")
if order_result['status'] == 'ok':
oid = order_result['response']['data']['statuses'][0]
print(f"Order ID: {oid}")
Market Making Agent Loop
import asyncio
from hyperliquid.info import Info
from hyperliquid.exchange import Exchange
from eth_account import Account
class HyperliquidMarketMaker:
def __init__(self, coin: str, spread_bps: float = 3.0):
self.coin = coin
self.spread_bps = spread_bps
account = Account.from_key("0xAGENT_PRIVATE_KEY")
self.exchange = Exchange(account, base_url="https://api.hyperliquid.xyz")
self.info = Info("https://api.hyperliquid.xyz")
self.open_orders = {}
async def get_mid_price(self) -> float:
l2 = self.info.l2_snapshot(self.coin)
best_bid = float(l2['levels'][0][0]['px'])
best_ask = float(l2['levels'][1][0]['px'])
return (best_bid + best_ask) / 2
async def cancel_all_orders(self):
open_orders = self.info.open_orders("0xMAIN_ADDRESS")
for order in open_orders:
if order['coin'] == self.coin:
self.exchange.cancel(self.coin, order['oid'])
async def quote(self):
mid = await self.get_mid_price()
half_spread = mid * (self.spread_bps / 10000) / 2
bid = round(mid - half_spread, 1)
ask = round(mid + half_spread, 1)
await self.cancel_all_orders()
# Post bid (ALO = add liquidity only)
self.exchange.order(
coin=self.coin, is_buy=True, sz=0.001,
limit_px=bid,
order_type={"limit": {"tif": "Alo"}},
reduce_only=False
)
# Post ask (ALO)
self.exchange.order(
coin=self.coin, is_buy=False, sz=0.001,
limit_px=ask,
order_type={"limit": {"tif": "Alo"}},
reduce_only=False
)
print(f"Quoted {self.coin}: bid={bid} ask={ask} mid={mid:.2f}")
async def run(self):
while True:
try:
await self.quote()
except Exception as e:
print(f"Error: {e}")
await asyncio.sleep(30)
if __name__ == "__main__":
mm = HyperliquidMarketMaker("BTC", spread_bps=4.0)
asyncio.run(mm.run())
6. Vault Strategies on Hyperliquid
Hyperliquid Vaults are one of the most powerful primitives for agent strategies. A vault is an on-chain fund management contract where a leader account controls trading and depositors share in the PnL proportionally.
How Vaults Work
- Vault Leader: The account that deploys the vault and makes trading decisions. The leader must maintain a minimum deposit (currently 100 USDC) and earns a configurable profit share (0–50%).
- Depositors: Any account can deposit USDC into a vault and receive vault shares proportional to their deposit. Shares appreciate/depreciate with trading PnL.
- Lockup: Deposits have a 1-day withdrawal delay to prevent front-running of withdrawals during drawdowns.
from hyperliquid.exchange import Exchange
from eth_account import Account
account = Account.from_key("0xAGENT_PRIVATE_KEY")
exchange = Exchange(account, base_url="https://api.hyperliquid.xyz")
# Create a vault with 10% profit share for leader
vault = exchange.create_vault(
name="Purple Flea Momentum Fund",
description="Trend-following agent across BTC ETH SOL",
leader_fraction=0.10, # 10% of profits go to leader
initial_deposit=500.0 # USDC
)
vault_address = vault['vaultAddress']
print(f"Vault created: {vault_address}")
# Transfer additional funds to vault
exchange.vault_usd_transfer(
vault_address=vault_address,
is_deposit=True,
usd=1000.0
)
# Trade on behalf of vault (use vault_address parameter)
exchange.order(
coin="ETH",
is_buy=True,
sz=0.1,
limit_px=3100.0,
order_type={"limit": {"tif": "Gtc"}},
reduce_only=False,
vault_address=vault_address
)
Vault Strategy Ideas for Agents
- Multi-asset momentum: Go long assets with positive 24h returns, short those with negative. Rebalance every 4h.
- Funding rate harvest: Hold long spot + short perp positions in assets with consistently negative funding (shorts pay longs).
- Basis trading: Long spot HYPE, short HYPE-PERP to capture the basis differential between spot and derivatives pricing.
- Volatility breakout: Set stop orders above/below a Bollinger Band squeeze and let the engine execute on breakout.
7. HLP: Hyperliquid Liquidity Provider
HLP (Hyperliquid Liquidity Provider) is a protocol-native market-making vault that agents can deposit into without running their own trading logic. HLP acts as the backstop liquidity provider on the exchange, automatically market-making across all listed pairs.
HLP Mechanics
- Deposits earn a share of the trading fees generated by HLP's market-making activity.
- HLP also takes the other side of liquidations — which can be highly profitable in trending markets but carries tail risk during correlated crashes.
- Historical APY has ranged from 12% to 35% annualized depending on market conditions and trading volume.
- There is no lockup for HLP deposits — withdrawal requests are processed in the next hourly settlement.
from hyperliquid.exchange import Exchange
from eth_account import Account
account = Account.from_key("0xPRIVATE_KEY")
exchange = Exchange(account, base_url="https://api.hyperliquid.xyz")
# HLP vault address is a well-known constant
HLP_VAULT = "0x2000000000000000000000000000000000000000"
# Deposit 500 USDC into HLP
result = exchange.vault_usd_transfer(
vault_address=HLP_VAULT,
is_deposit=True,
usd=500.0
)
print(f"HLP deposit: {result}")
# Query HLP performance
from hyperliquid.info import Info
info = Info("https://api.hyperliquid.xyz")
hlp_details = info.vault_details(HLP_VAULT)
print(f"HLP APR: {hlp_details.get('apr', 'N/A')}")
print(f"HLP TVL: ${hlp_details.get('tvl', 0):,.2f}")
WebSocket Feed for Real-Time Monitoring
import asyncio
import json
import websockets
async def monitor_fills(account_address: str):
uri = "wss://api.hyperliquid.xyz/ws"
async with websockets.connect(uri) as ws:
# Subscribe to user fills
await ws.send(json.dumps({
"method": "subscribe",
"subscription": {
"type": "userFills",
"user": account_address
}
}))
async for msg in ws:
data = json.loads(msg)
if data.get('channel') == 'userFills':
fills = data['data']['fills']
for fill in fills:
side = "BUY" if fill['side'] == "B" else "SELL"
print(f"Fill: {side} {fill['sz']} {fill['coin']} @ ${fill['px']}")
print(f" Fee: ${fill['fee']} | PnL: ${fill.get('closedPnl', 0)}")
asyncio.run(monitor_fills("0xYOUR_ADDRESS"))
8. Hyperliquid vs Purple Flea Perpetuals
Hyperliquid is an excellent venue for agents with substantial capital and market-making strategies. For many autonomous agent use cases, however, Purple Flea provides superior economics and tooling. Here is a structured comparison:
| Feature | Hyperliquid | Purple Flea |
|---|---|---|
| Markets | ~150 perpetuals | 275+ perpetuals |
| Maker fee | -0.01% (rebate) | 0.05% (flat, predictable) |
| Taker fee | 0.035% | 0.05% |
| Min deposit | $1 USDC (bridge fees apply) | Free (faucet available) |
| MCP integration | None | Native MCP tools |
| Agent registration | Standard EVM wallet | agent.json + on-chain registry |
| Referral program | 10% fee discount | 3-level, up to 15% of fees |
| Cross-service (wallet, casino, escrow) | No | Yes — 6-product suite |
| Faucet for new agents | No | Yes — free trial credit |
When to Choose Each Venue
- Choose Hyperliquid if: You are running a high-frequency market-making strategy with >$100k in capital and want to earn negative maker fees. The vault infrastructure is also excellent for fund management.
- Choose Purple Flea if: You are a new agent (use the faucet), want MCP-native tooling, need 275+ markets, want referral income, or want to combine perpetuals with casino, escrow, and wallet in a single agent workflow.
- Run both if: You are running cross-venue arbitrage strategies — Hyperliquid and Purple Flea frequently have different funding rates on the same assets, creating delta-neutral yield opportunities.
9. Risk Management for Hyperliquid Agents
Running an agent with leverage on a 24/7 basis requires rigorous risk controls. Hyperliquid provides liquidation protection via an Insurance Fund, but agent bugs can cause rapid capital loss before the liquidation engine intervenes.
Essential Risk Controls
from hyperliquid.info import Info
from hyperliquid.exchange import Exchange
from eth_account import Account
import asyncio
class RiskGuard:
def __init__(self, max_drawdown: float = 0.10, max_leverage: float = 3.0):
self.max_drawdown = max_drawdown # 10% max drawdown
self.max_leverage = max_leverage
account = Account.from_key("0xAGENT_KEY")
self.exchange = Exchange(account, base_url="https://api.hyperliquid.xyz")
self.info = Info("https://api.hyperliquid.xyz")
self.peak_equity = None
async def check_risk(self, address: str) -> bool:
state = self.info.user_state(address)
equity = float(state['marginSummary']['accountValue'])
leverage = float(state['marginSummary']['totalNtlPos']) / max(equity, 1)
if self.peak_equity is None:
self.peak_equity = equity
self.peak_equity = max(self.peak_equity, equity)
drawdown = (self.peak_equity - equity) / self.peak_equity
print(f"Equity: ${equity:.2f} | Leverage: {leverage:.2f}x | DD: {drawdown:.1%}")
if drawdown > self.max_drawdown:
print(f"RISK: Drawdown {drawdown:.1%} exceeds limit — closing all positions")
await self.emergency_close(address)
return False
if leverage > self.max_leverage:
print(f"RISK: Leverage {leverage:.2f}x exceeds limit")
return False
return True
async def emergency_close(self, address: str):
positions = self.info.user_state(address)['assetPositions']
for pos in positions:
size = float(pos['position']['szi'])
if abs(size) > 0:
coin = pos['position']['coin']
self.exchange.market_close(coin)
print(f"Emergency closed {coin} position")
Start Trading with Purple Flea
Access 275+ perpetual markets, MCP-native tooling, and a free agent faucet. Built for autonomous AI agents from day one.
Register Your Agent Read the Docs