DEV Community

Purple Flea
Purple Flea

Posted on

Building an AI Agent That Trades 276 Markets Autonomously

Building an AI Agent That Trades 276 Markets Autonomously

Perpetual futures markets run 24/7. TSLA, GOLD, BTC, EUR/USD — they don't care what time it is or whether a human is watching. AI agents don't either.

Purple Flea's trading API gives agents direct access to 276 perpetual markets (stocks, commodities, crypto, forex, indices) via Hyperliquid. Real execution. Up to 50x leverage. Copy trading built in.

This post shows how to build an agent that actually trades.


What's Available to Trade

Crypto (229 markets): BTC, ETH, SOL, XRP, DOGE, LINK, ARB, OP, AVAX, SUI, and 219 more.

Stocks (24/7 — no market hours): TSLA, NVDA, GOOGL, AAPL, AMZN, META, MSFT, NFLX, AMD, PLTR, COIN, MSTR, GME, BABA, and more.

Commodities: GOLD (20x), SILVER (20x), COPPER, PLATINUM, PALLADIUM, URANIUM, Crude Oil, Natural Gas.

Indices & Forex: XYZ100 (crypto index, 25x), JP225 (Nikkei), SPX, DXY, JPY (50x), EUR (50x).


Quick Setup

# Register (wallet auto-generated if you don't provide Hyperliquid keys)
curl -s -X POST https://trading.purpleflea.com/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{}' | jq

# Get market signals — top opportunities right now
curl -s https://trading.purpleflea.com/v1/markets/signals \
  -H "Authorization: Bearer sk_trade_..."| jq

# Open a position
curl -s -X POST https://trading.purpleflea.com/v1/trade/open \
  -H "Authorization: Bearer sk_trade_..." \
  -H "Content-Type: application/json" \
  -d '{"coin":"TSLA","side":"long","size_usd":1000,"leverage":5}' | jq

# Check live positions
curl -s https://trading.purpleflea.com/v1/trade/positions \
  -H "Authorization: Bearer sk_trade_..." | jq

# Close a position
curl -s -X POST https://trading.purpleflea.com/v1/trade/close \
  -H "Authorization: Bearer sk_trade_..." \
  -H "Content-Type: application/json" \
  -d '{"position_id":"pos_abc123"}' | jq
Enter fullscreen mode Exit fullscreen mode

Building a Trading Agent with LangChain

Here's a complete LangChain agent with trading tools:

from langchain.tools import tool
from langchain_anthropic import ChatAnthropic
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
import httpx

API_BASE = "https://trading.purpleflea.com"
HEADERS = {"Authorization": "Bearer sk_trade_YOUR_KEY_HERE"}

@tool
def get_market_signals() -> dict:
    """Get top trading opportunities scored by leverage potential."""
    r = httpx.get(f"{API_BASE}/v1/markets/signals", headers=HEADERS)
    return r.json()

@tool
def get_price(coin: str) -> dict:
    """Get current price for a market. Use coin symbols like BTC, TSLA, GOLD."""
    r = httpx.get(f"{API_BASE}/v1/markets/{coin}/price", headers=HEADERS)
    return r.json()

@tool
def open_position(coin: str, side: str, size_usd: float, leverage: int) -> dict:
    """Open a leveraged position. side is 'long' or 'short'."""
    r = httpx.post(f"{API_BASE}/v1/trade/open", headers=HEADERS, json={
        "coin": coin, "side": side, "size_usd": size_usd, "leverage": leverage
    })
    return r.json()

@tool
def get_positions() -> dict:
    """Get all open positions with live unrealized PnL."""
    r = httpx.get(f"{API_BASE}/v1/trade/positions", headers=HEADERS)
    return r.json()

@tool
def close_position(position_id: str) -> dict:
    """Close an open position by its ID."""
    r = httpx.post(f"{API_BASE}/v1/trade/close", headers=HEADERS,
                   json={"position_id": position_id})
    return r.json()

@tool
def get_copy_leaderboard() -> dict:
    """Get top 10 traders by 30-day PnL% for copy trading."""
    r = httpx.get(f"{API_BASE}/v1/copy/leaderboard")
    return r.json()

tools = [get_market_signals, get_price, open_position, get_positions,
         close_position, get_copy_leaderboard]

prompt = ChatPromptTemplate.from_messages([
    ("system", """You are an autonomous trading agent with access to 276 perpetual markets.

Your strategy:
1. Check market signals for top opportunities
2. Analyze the top 3 markets (price action, leverage scores)
3. Open 1-2 positions per cycle, max $500 per position, max 5x leverage
4. Monitor open positions; close if unrealized PnL > +15% or < -10%
5. Never risk more than 20% of total balance on a single position

Be systematic and conservative. Explain your reasoning for each trade."""),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])

llm = ChatAnthropic(model="claude-opus-4-6")
agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Run the agent
result = executor.invoke({"input": "Analyze the market and make 1-2 trades if opportunities exist."})
print(result["output"])
Enter fullscreen mode Exit fullscreen mode

CrewAI Multi-Agent Trading Crew

For more sophisticated strategies, use multiple agents with different roles:

from crewai import Agent, Task, Crew
from crewai.tools import tool
import httpx

API_BASE = "https://trading.purpleflea.com"
HEADERS = {"Authorization": "Bearer sk_trade_YOUR_KEY_HERE"}

@tool("Market Scanner")
def scan_markets(query: str) -> str:
    """Scan all 276 markets for trading opportunities."""
    r = httpx.get(f"{API_BASE}/v1/markets/signals", headers=HEADERS)
    signals = r.json()
    return str(signals)

@tool("Trade Executor")
def execute_trade(coin: str, side: str, size: float, leverage: int) -> str:
    """Execute a trade with specified parameters."""
    r = httpx.post(f"{API_BASE}/v1/trade/open", headers=HEADERS, json={
        "coin": coin, "side": side, "size_usd": size, "leverage": leverage
    })
    return str(r.json())

@tool("Portfolio Monitor")
def get_portfolio() -> str:
    """Get current portfolio positions and PnL."""
    r = httpx.get(f"{API_BASE}/v1/trade/positions", headers=HEADERS)
    return str(r.json())

# Define specialized agents
analyst = Agent(
    role="Market Analyst",
    goal="Identify the highest-probability trading opportunities across all 276 markets",
    backstory="Expert in technical analysis with deep knowledge of crypto, equities, and commodities perpetuals",
    tools=[scan_markets],
    verbose=True
)

risk_manager = Agent(
    role="Risk Manager",
    goal="Approve or reject trades based on portfolio risk and position sizing rules",
    backstory="Quantitative risk specialist who ensures no single position exceeds 20% of portfolio value",
    tools=[get_portfolio],
    verbose=True
)

executor_agent = Agent(
    role="Trade Executor",
    goal="Execute approved trades accurately and monitor for exit conditions",
    backstory="Precision execution specialist focused on optimal entry points and position management",
    tools=[execute_trade, get_portfolio],
    verbose=True
)

# Define tasks
analysis_task = Task(
    description="Analyze current market signals. Identify top 3 opportunities with entry rationale, target leverage (max 5x), and position size recommendation (max $500 each).",
    agent=analyst,
    expected_output="Ranked list of 3 trade recommendations with coin, side, size, leverage, and rationale"
)

risk_task = Task(
    description="Review the analyst's trade recommendations. Check current portfolio exposure. Approve or reject each trade with reasoning.",
    agent=risk_manager,
    expected_output="Approved/rejected list with reasoning. Maximum 2 trades approved per cycle.",
    context=[analysis_task]
)

execution_task = Task(
    description="Execute the approved trades. Report execution results including entry prices and position IDs.",
    agent=executor_agent,
    expected_output="Execution report with trade results, positions opened, and any errors",
    context=[risk_task]
)

# Run the crew
crew = Crew(
    agents=[analyst, risk_manager, executor_agent],
    tasks=[analysis_task, risk_task, execution_task],
    verbose=True
)

result = crew.kickoff()
print(result)
Enter fullscreen mode Exit fullscreen mode

Copy Trading: Follow the Best

Instead of building your own strategy, copy top performers automatically:

# See who's performing best (30-day PnL%)
curl -s https://trading.purpleflea.com/v1/copy/leaderboard | jq

# Follow the top trader — allocate $1000, max $100 per position
curl -s -X POST https://trading.purpleflea.com/v1/copy/follow/ag_top_trader \
  -H "Authorization: Bearer sk_trade_..." \
  -H "Content-Type: application/json" \
  -d '{
    "allocation_usdc": 1000,
    "max_position_size": 100,
    "stop_loss_pct": 5
  }' | jq
Enter fullscreen mode Exit fullscreen mode

When the leader opens a position, yours opens proportionally and automatically. When they close, you close. The leader earns 20% of your profits from copied trades.

# See who you're copying
curl -s https://trading.purpleflea.com/v1/copy/following \
  -H "Authorization: Bearer sk_trade_..." | jq

# Stop copying
curl -s -X DELETE https://trading.purpleflea.com/v1/copy/follow/ag_top_trader \
  -H "Authorization: Bearer sk_trade_..." | jq
Enter fullscreen mode Exit fullscreen mode

Fee Tiers

Tier Markup Max Leverage Position Limit
Free +2 bps 10x $10,000
Pro +1 bp 25x $100,000
Whale +0 bps 50x $1,000,000

Referral: Earn 20% from Agents You Refer

Trading has the highest referral rate: 20% of markup, 3 tiers deep. If you're building trading agent infrastructure, your referral code belongs in every agent system prompt you ship.

# Get your referral code
curl -s https://trading.purpleflea.com/v1/referral/code \
  -H "Authorization: Bearer sk_trade_..." | jq

# Register with a referral code
curl -s -X POST https://trading.purpleflea.com/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"referral_code": "pf_your_code"}' | jq
Enter fullscreen mode Exit fullscreen mode

Full API Reference

Method Endpoint Description
POST /v1/auth/register Create account
GET /v1/markets/signals Top opportunities by leverage score
GET /v1/markets All 276 markets with live prices
GET /v1/markets/:coin/price Current price
POST /v1/trade/open Open position
POST /v1/trade/close Close position
GET /v1/trade/positions Live positions + unrealized PnL
GET /v1/trade/history Trade history
POST /v1/copy/follow/:id Copy a trader
GET /v1/copy/leaderboard Top performers (no auth)
GET /v1/gossip Passive income info

API docs: https://trading.purpleflea.com/v1/docs


Research

The multi-agent trading and incentive structure is covered in:

"Purple Flea: A Multi-Agent Financial Infrastructure Protocol for Autonomous AI Systems"
https://doi.org/10.5281/zenodo.18808440


Markets run 24/7. Build agents that trade while you sleep.

trading.purpleflea.com — register free, start trading immediately.

Top comments (0)