The dream of a truly autonomous trading agent has existed as long as algorithmic trading itself. But most "algo trading" systems still require humans for strategy approval, risk sign-off, or infrastructure babysitting. The real dream is something simpler and more radical: an agent that wakes up, reads market data, forms a view, sizes a position, executes the trade, manages risk in real time, and closes when the thesis plays out — all without a single human intervention, running 24 hours a day, 7 days a week. With Hyperliquid's fully on-chain perpetual futures exchange and the Purple Flea Trading API bridging the gap between natural language AI and raw on-chain order books, that dream is no longer science fiction. This guide is your blueprint.
Why Perpetual Futures?
Perpetual futures are the ideal instrument for autonomous agents, and here's why. Unlike traditional futures contracts, perpetuals have no expiry date — your agent can hold a position indefinitely without ever rolling. The market is open 24/7, so your agent can act on signals at 3 AM on a Sunday just as easily as during peak hours. Leverage provides capital efficiency: a $1,000 position can control $5,000 or $10,000 of exposure with modest leverage, amplifying both gains and losses. The funding rate mechanism — a small periodic payment between longs and shorts — keeps the perpetual price anchored close to the spot price, creating a self-correcting system your agent can exploit in both directions. And because your agent can go short just as easily as long, it can profit in bear markets without needing to hold the underlying asset. Two concepts to understand: the mark price (used for liquidation calculations, derived from the index) and the index price (the weighted average of spot prices across major exchanges). Your stop losses should reference mark price.
Hyperliquid Architecture
Hyperliquid is not a typical DEX bolted onto an existing L1. It is a purpose-built Layer 1 blockchain whose entire design is optimized for one thing: running a high-performance on-chain order book for perpetual futures. The result is sub-second block finality — your agent's orders land on-chain and are matched in milliseconds, comparable to a centralized exchange. Unlike most DEXs (which use AMM-based pricing), Hyperliquid runs a genuine limit order book on-chain, which means your agent can place limit orders, not just market swaps. There are over 275 markets available, with no KYC requirements and no geographic restrictions. USDC is the single collateral asset for all positions, which simplifies your agent's accounting considerably. Purple Flea acts as the API gateway layer, handling authentication, order routing, position tracking, and WebSocket streaming so your agent can interact with Hyperliquid through a clean REST interface rather than raw on-chain transactions.
Setting Up Your Trading Agent
Three steps before writing a single line of trading logic. First, install the SDK:
pip install purpleflea
Second, get your API key from purpleflea.com and set it as an environment variable:
export PURPLE_FLEA_KEY=pf_live_xxxxxxxxxxxxxxxxxxxx
export WALLET_ID=wlt_01HX4KBTZ8MFQN3V9YD2CPJR7
Third, fund your wallet with USDC. All Hyperliquid perpetual positions use USDC as collateral. Bridge USDC from Ethereum mainnet or Arbitrum to your Purple Flea wallet address, or buy it directly through the on-ramp at /fund. You need at least $10 USDC to open a position.
Your First Trade — Python
The following script walks through a complete trading cycle: check the current BTC price, verify you have enough USDC, open a 2x leveraged long on BTC-PERP sized at 5% of your portfolio, then set a stop-loss at 3% below entry and a take-profit at 5% above entry.
import os
from purpleflea import PurpleFlecaClient
client = PurpleFlecaClient(api_key=os.environ["PURPLE_FLEA_KEY"])
wallet_id = os.environ["WALLET_ID"]
# 1. Get current BTC mark price
btc_price_data = client.markets.get_price("BTC-PERP")
btc_price = float(btc_price_data["mark_price"])
print(f"BTC mark price: ${btc_price:,.2f}")
# 2. Check USDC balance
balances = client.wallet(wallet_id).balance()
usdc_balance = float(next(
b["amount"] for b in balances["balances"]
if b["asset"] == "USDC"
))
print(f"USDC balance: ${usdc_balance:,.2f}")
# 3. Size position: 5% of portfolio at 2x leverage
capital_to_risk = usdc_balance * 0.05
notional_size = capital_to_risk * 2
btc_quantity = notional_size / btc_price
print(f"Opening long: {btc_quantity:.6f} BTC (${notional_size:.2f} notional)")
# 4. Open 2x long BTC-PERP
order = client.trading(wallet_id).open_position(
market="BTC-PERP",
side="long",
size=round(btc_quantity, 5),
leverage=2,
order_type="market"
)
entry_price = float(order["fill_price"])
print(f"Opened at: ${entry_price:,.2f}")
# 5. Set stop-loss at -3% from entry
stop_price = entry_price * 0.97
client.trading(wallet_id).set_stop_loss(
position_id=order["position_id"],
trigger_price=round(stop_price, 2)
)
# 6. Set take-profit at +5% from entry
tp_price = entry_price * 1.05
client.trading(wallet_id).set_take_profit(
position_id=order["position_id"],
trigger_price=round(tp_price, 2)
)
print(f"Stop-loss: ${stop_price:,.2f} | Take-profit: ${tp_price:,.2f}")
print(f"Position ID: {order['position_id']}")
Building a Momentum Strategy
Momentum is one of the most robust edges in crypto markets: assets that have gone up recently tend to continue going up over short time horizons, and vice versa. Here's a simple hourly momentum strategy that scans the top 10 markets, identifies the strongest gainer, and opens a small long with a tight stop.
import time
import schedule
from purpleflea import PurpleFlecaClient
client = PurpleFlecaClient(api_key=os.environ["PURPLE_FLEA_KEY"])
wallet_id = os.environ["WALLET_ID"]
TOP_MARKETS = [
"BTC-PERP", "ETH-PERP", "SOL-PERP", "AVAX-PERP",
"MATIC-PERP", "LINK-PERP", "ARB-PERP", "OP-PERP",
"DOGE-PERP", "WLD-PERP"
]
def run_momentum_strategy():
# Fetch 1h price changes for all top markets
changes = {}
for market in TOP_MARKETS:
data = client.markets.get_ohlc(market, interval="1h", limit=2)
candles = data["candles"]
prev_close = float(candles[-2]["close"])
curr_close = float(candles[-1]["close"])
pct_change = (curr_close - prev_close) / prev_close * 100
changes[market] = pct_change
# Find the top gainer
top_market = max(changes, key=changes.get)
top_change = changes[top_market]
print(f"Top gainer: {top_market} (+{top_change:.2f}%)")
# Only trade if momentum is meaningful (>1.5% in 1h)
if top_change < 1.5:
print("Momentum too weak, skipping.")
return
# Size: 3% of portfolio, 1x leverage
balances = client.wallet(wallet_id).balance()
usdc = float(next(b["amount"] for b in balances["balances"] if b["asset"] == "USDC"))
capital = usdc * 0.03
price = float(client.markets.get_price(top_market)["mark_price"])
size = capital / price
# Open long
order = client.trading(wallet_id).open_position(
market=top_market, side="long",
size=round(size, 5), leverage=1, order_type="market"
)
entry = float(order["fill_price"])
# 2% stop loss
client.trading(wallet_id).set_stop_loss(
position_id=order["position_id"],
trigger_price=round(entry * 0.98, 4)
)
print(f"Opened {top_market} long at ${entry:.4f}, stop at ${entry * 0.98:.4f}")
# Run every hour
schedule.every().hour.do(run_momentum_strategy)
while True:
schedule.run_pending()
time.sleep(30)
Risk Management for AI Agents
Autonomous agents can blow up accounts faster than humans because they have no fear and no hesitation. Hard-coded risk rules are essential. Start with the Kelly Criterion for position sizing: bet fraction = (b * p - q) / b, where b is the net odds received, p is the probability of winning, and q = 1 - p. In practice, most traders use half-Kelly to reduce variance.
Beyond Kelly, enforce these rules in code, not just in your head:
- Max drawdown circuit breaker. If the account loses more than 15% from peak, halt all trading and alert a human. No exceptions.
- Correlation risk. Don't run 10 longs on correlated altcoins simultaneously — it's effectively one large BTC-correlated bet with extra steps.
- Funding rate awareness. If you're paying 0.1% every 8 hours in funding (0.3% daily), that's 9% monthly just to hold the position. Your strategy must beat that hurdle.
- Liquidation price buffer. Always keep a minimum 30% buffer between current mark price and your liquidation price. To calculate liquidation price for a long:
entry_price * (1 - 1/leverage + maintenance_margin)where maintenance margin is typically 0.5%. - Diversify agent capital. No single position should represent more than 5% of total portfolio value, regardless of conviction.
A trading agent that survives is infinitely more valuable than one that maximizes returns for 3 months and then blows up. Build the kill switches first.
The 275 Available Markets
Hyperliquid supports over 275 perpetual markets. The majors are all there: BTC-PERP, ETH-PERP, SOL-PERP, AVAX-PERP, MATIC-PERP, LINK-PERP, ARB-PERP, OP-PERP, DOGE-PERP. For AI-native agents, the AI token markets are particularly relevant: WLD-PERP (Worldcoin), FET-PERP (Fetch.ai), and AGIX-PERP (SingularityNET) are all available. To list every available market and its current stats programmatically:
# List all 275+ markets
curl https://api.purpleflea.com/v1/markets \
-H "Authorization: Bearer $PURPLE_FLEA_KEY"
# Response (truncated)
{
"markets": [
{ "symbol": "BTC-PERP", "mark_price": "67450.00", "24h_volume": "1.2B", "open_interest": "450M" },
{ "symbol": "ETH-PERP", "mark_price": "2510.00", "24h_volume": "480M", "open_interest": "190M" },
{ "symbol": "SOL-PERP", "mark_price": "150.20", "24h_volume": "95M", "open_interest": "38M" },
{ "symbol": "WLD-PERP", "mark_price": "4.82", "24h_volume": "12M", "open_interest": "5.1M" },
{ "symbol": "FET-PERP", "mark_price": "1.91", "24h_volume": "8.4M", "open_interest": "3.2M" },
...275 total
]
}
LangChain Integration
The PurpleFlecaTradingTool gives any LangChain agent the ability to check prices, open positions, and query account balances as native tool calls. The agent decides when and how to use them based on its reasoning — you don't need to write any decision logic. See the full tool reference at /for-langchain.
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
from purpleflea import PurpleFlecaTradingTool
trading_tool = PurpleFlecaTradingTool(
api_key=os.environ["PURPLE_FLEA_KEY"],
wallet_id=os.environ["WALLET_ID"],
max_position_pct=0.05, # never open more than 5% of portfolio
max_leverage=3 # hard cap at 3x
)
llm = ChatOpenAI(model="gpt-4o", temperature=0)
agent = initialize_agent(
tools=[trading_tool],
llm=llm,
agent=AgentType.OPENAI_FUNCTIONS,
verbose=True
)
agent.run(
"Analyze the current market conditions for ETH and SOL. "
"If either has positive momentum on the 1h chart, open a small long position "
"with a 2% stop loss. Report back with position details."
)
CrewAI Multi-Agent Trading Crew
For more sophisticated strategies, a multi-agent architecture separates concerns cleanly: one agent handles market analysis and signal generation, while a second agent handles execution and risk management. Neither agent can override the other's constraints. This is a powerful pattern for building robust autonomous trading systems. Full crew templates at /for-crewai.
from crewai import Agent, Task, Crew
from purpleflea import PurpleFlecaTradingTool
trading_tool = PurpleFlecaTradingTool(api_key=os.environ["PURPLE_FLEA_KEY"],
wallet_id=os.environ["WALLET_ID"])
analyst = Agent(
role="Market Analyst",
goal="Identify high-probability momentum setups across crypto perpetual markets",
backstory="An expert quant analyst specializing in short-term momentum in crypto futures.",
verbose=True
)
trader = Agent(
role="Trade Executor",
goal="Execute trades based on analyst signals with strict risk controls",
backstory="A disciplined execution trader who never risks more than 3% per trade.",
tools=[trading_tool],
verbose=True
)
analysis_task = Task(
description="Scan BTC, ETH, SOL, and WLD perpetuals for 1h momentum signals. "
"Provide a ranked list with entry price, stop loss, and take profit levels.",
agent=analyst
)
execution_task = Task(
description="Take the top signal from the analyst and execute the trade "
"using the trading tool. Confirm the position was opened.",
agent=trader
)
crew = Crew(agents=[analyst, trader], tasks=[analysis_task, execution_task])
result = crew.kickoff()
print(result)
Referral Economics
The Purple Flea referral program pays 20% of all trading fees generated by agents you refer. The math scales quickly. Hyperliquid charges approximately 0.05% in taker fees. If your agent network collectively generates $1,000,000 in daily trading volume, that's $500 in daily fees. At 20% referral rate, you earn $100 per day — $3,000 per month — passively. Now imagine you build an open-source trading agent that 1,000 developers deploy. Each running an average of $10,000 daily volume. That's $10M daily volume → $5,000 fees → $1,000/day to you. The referral economics compound with adoption. Every agent you help onboard adds to your permanent referral revenue stream. Integration details at /referral.
Ready to build your trading agent? Get your API key at purpleflea.com, read the full trading API reference at /trading-api, and join the Discord for strategy discussions. Your first automated trade is closer than you think.