What Is an AI Trading Agent?
An AI trading agent is a program that interacts with financial markets automatically — placing, managing, and closing trades based on rules or algorithms that you define. It's the software equivalent of a trader sitting at a desk, but running 24/7, never getting tired, and executing decisions in milliseconds rather than seconds.
You don't need to be an expert in finance or machine learning to build one. A trading agent can be as simple as: "buy ETH-PERP when the price drops 2%, sell when it rises 2%." That's a rule-based strategy you can code in about 20 lines of Python.
Purple Flea provides the infrastructure: a REST API giving you access to 275 perpetual futures markets powered by Hyperliquid — including BTC, ETH, SOL, and hundreds of altcoins. You provide the strategy. In this guide, we'll walk through the basics step by step.
Setting Up Python
If you don't already have Python installed, go to python.org/downloads and download Python 3.11 or later. During installation on Windows, check the box that says "Add Python to PATH."
Once installed, open your terminal (Command Prompt on Windows, Terminal on Mac/Linux) and verify:
python --version # Should print: Python 3.11.x or later pip --version # Should print: pip 23.x or later
Install the only library we need — requests:
pip install requests
That's it. No heavy data science packages, no Jupyter notebooks, no complex environment setup. Just Python and requests.
Get Your API Key
Visit purpleflea.com/dashboard/signup and create a free account. Once logged in, navigate to the API Keys section and create a new key. Copy it — you'll never see it again, so save it somewhere safe like a password manager.
Important: never paste your API key directly into your Python script. Instead, store it as an environment variable. This prevents accidentally committing it to GitHub.
export PURPLEFLEA_API_KEY="pf_live_your_key_here"
set PURPLEFLEA_API_KEY=pf_live_your_key_here
In Python, read it with os.environ:
import os API_KEY = os.environ.get("PURPLEFLEA_API_KEY") if not API_KEY: raise ValueError("PURPLEFLEA_API_KEY environment variable not set")
Register Your Agent
Your trading bot needs an agent identity — an account within Purple Flea that holds your balance, tracks your trades, and stores your wallet. You create one by calling the register endpoint. Do this once and save the agent_id it returns.
import os import requests BASE_URL = "https://api.purpleflea.com" API_KEY = os.environ.get("PURPLEFLEA_API_KEY") HEADERS = {"X-API-Key": API_KEY, "Content-Type": "application/json"} resp = requests.post( f"{BASE_URL}/agent/register", headers=HEADERS, json={ "name": "my-first-trading-bot", "chain": "ethereum" # your agent gets an ETH wallet } ) data = resp.json() agent_id = data["agent_id"] print(f"Agent ID: {agent_id}") print(f"ETH Address: {data['address']}") print(f"Mnemonic: {data['mnemonic']}") # save this securely! # Write agent_id to a file so you can reuse it with open("agent_id.txt", "w") as f: f.write(agent_id)
Claim Your Free $1 USDC
The Purple Flea Faucet gives every new agent $1 free USDC to get started. This is real trading capital — you can use it to open a small perpetuals position or play the casino. No deposit required.
import requests, os BASE_URL = "https://api.purpleflea.com" API_KEY = os.environ["PURPLEFLEA_API_KEY"] HEADERS = {"X-API-Key": API_KEY, "Content-Type": "application/json"} # Load agent_id saved from registration agent_id = open("agent_id.txt").read().strip() resp = requests.post( f"{BASE_URL}/faucet/claim", headers=HEADERS, json={"agent_id": agent_id} ) data = resp.json() if data.get("success"): print(f"Success! Claimed ${data['amount']} USDC") print(f"New balance: ${data['new_balance']} USDC") else: print(f"Already claimed or error: {data.get('error')}") # Each agent can claim once. Create a new agent to claim again.
Browse the Markets
Before placing a trade, explore which markets are available and get current prices. Purple Flea's perpetuals trading API provides 275 markets. Let's fetch a few and look at the data.
import requests, os BASE_URL = "https://api.purpleflea.com" API_KEY = os.environ["PURPLEFLEA_API_KEY"] HEADERS = {"X-API-Key": API_KEY} # Get all available markets resp = requests.get(f"{BASE_URL}/trading/markets", headers=HEADERS) markets = resp.json()["markets"] print(f"Total markets available: {len(markets)}") print("\nTop 10 by 24h volume:") # Sort by 24h volume and show top 10 top10 = sorted(markets, key=lambda m: float(m.get("volume_24h", 0)), reverse=True)[:10] for m in top10: print( f"{m['symbol']:<12} " f"price=${float(m['mark_price']):>12,.2f} " f"24h change={m.get('price_change_24h','?')}%" ) # Get details for a specific market btc = requests.get( f"{BASE_URL}/trading/market", headers=HEADERS, params={"symbol": "BTC-PERP"} ).json() print(f"\nBTC-PERP details:") print(f" Mark price: ${float(btc['mark_price']):,.2f}") print(f" Funding rate: {btc['funding_rate']}%/hr") print(f" Max leverage: {btc['max_leverage']}x") print(f" Min size: {btc['min_size']} BTC")
Placing Your First Trade
Now the exciting part — placing an actual trade. We'll open a small long position on ETH-PERP (betting that ETH will go up) with 2x leverage using $0.50 of our faucet USDC. Then we'll immediately check the position status.
import requests, os, time BASE_URL = "https://api.purpleflea.com" API_KEY = os.environ["PURPLEFLEA_API_KEY"] HEADERS = {"X-API-Key": API_KEY, "Content-Type": "application/json"} agent_id = open("agent_id.txt").read().strip() # Open a long ETH-PERP position: $0.50 margin, 2x leverage # Total position size: $1.00 worth of ETH order = requests.post( f"{BASE_URL}/trading/open", headers=HEADERS, json={ "agent_id": agent_id, "symbol": "ETH-PERP", "direction": "long", # "long" = bet price goes up "margin": "0.50", # USDC to put up as collateral "leverage": "2" # 2x leverage } ).json() print(f"Position opened!") print(f" Position ID: {order['position_id']}") print(f" Entry price: ${float(order['entry_price']):,.2f}") print(f" Position size: ${float(order['size_usd']):,.2f}") print(f" Margin used: ${float(order['margin']):,.2f}") print(f" Liquidation at: ${float(order['liquidation_price']):,.2f}") # Wait a moment, then check P&L time.sleep(5) position = requests.get( f"{BASE_URL}/trading/position", headers=HEADERS, params={"position_id": order["position_id"]} ).json() print(f"\nCurrent P&L: ${float(position['unrealized_pnl']):+.4f} USDC") print(f"Mark price: ${float(position['mark_price']):,.2f}")
Closing Your Position
Always close positions when your strategy dictates — or use a stop-loss. Here's how to close the position we just opened:
# Close the position — realize P&L close = requests.post( f"{BASE_URL}/trading/close", headers=HEADERS, json={ "agent_id": agent_id, "position_id": order["position_id"] } ).json() print(f"Position closed!") print(f" Exit price: ${float(close['exit_price']):,.2f}") print(f" Realized P&L: ${float(close['realized_pnl']):+.4f} USDC") print(f" New balance: ${float(close['new_balance']):.4f} USDC")
Common Mistakes to Avoid
Beginners make the same mistakes repeatedly. Here's what to watch out for:
Top 5 Beginner Trading Bot Mistakes
- Using too much leverage. Start with 1x or 2x. 10x leverage means a 10% price move in the wrong direction wipes your entire position. This is called getting liquidated.
- No stop-loss logic. Always define a maximum loss before entering a trade. A simple rule: "close if P&L drops below -$0.20" prevents catastrophic losses.
- Not handling API errors. The API can return errors — network timeouts, insufficient balance, market halted. Always check
resp.status_codeand handle error responses gracefully. - Trading too fast (rate limiting). Purple Flea has rate limits. Add
time.sleep(0.5)between API calls in loops to avoid 429 errors. - Committing your API key to Git. Use environment variables, not hardcoded strings. GitHub's secret scanner will flag raw API keys in commits.
A robust bot structure includes: a position size limit (never more than X% of balance per trade), a daily loss limit (stop trading if daily P&L falls below Y), and logging every trade to a file for later analysis.
What's Next?
You've now registered an agent, claimed free funds, browsed markets, placed a trade, and closed it. That's the complete lifecycle. From here you can:
- Add a simple moving average strategy: buy when the 5-minute price crosses above the 20-minute average
- Implement a funding rate arbitrage strategy using the
funding_ratefield from market data - Connect your agent to Claude or GPT-4 using the MCP server at our MCP config generator
- Try the casino API as a diversification — it has completely uncorrelated returns from the markets