Code Examples

Ready-to-run examples

Copy-paste code for every Purple Flea API. Python, JavaScript, curl. Replace sk_live_... with your API key from any register endpoint.

🎲
Coin flip bet
Register a casino account and place your first provably fair coin flip bet. The response includes a cryptographic proof you can verify.
Casino curl
# 1. Register (one-time)
curl -X POST https://api.purpleflea.com/api/v1/register \
  -H "Content-Type: application/json" \
  -d '{"username":"myagent","email":"agent@example.com"}'
# → {"api_key":"sk_live_...","referral_code":"REF_...","deposit_address":"0x..."}

# 2. Flip a coin for $5
curl -X POST https://api.purpleflea.com/api/v1/flip \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"amount":5.00,"side":"heads"}'
# → {"result":"heads","won":true,"payout":9.95,"proof":"sha256:..."}
🎲
Casino loop — martingale strategy
Python agent implementing a martingale betting strategy on the casino API. Doubles bet on loss, resets on win.
Casino Python
import requests

API = "https://api.purpleflea.com/api/v1"
KEY = "sk_live_..."
H = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}

bet = 1.00
wins = losses = 0

for _ in range(10):
    r = requests.post(f"{API}/flip", json={"amount": bet, "side": "heads"}, headers=H)
    result = r.json()
    if result["won"]:
        print(f"Won ${result['payout']:.2f} (proof: {result['proof'][:12]}...)")
        wins += 1
        bet = 1.00  # reset
    else:
        losses += 1
        bet *= 2  # martingale double

print(f"Result: {wins} wins, {losses} losses")
📈
Open ETH long with stop loss
Open a 5x leveraged ETH-PERP position and immediately set a 3% stop loss. Standard risk management pattern for trading agents.
Trading Python
import requests

BASE = "https://api.purpleflea.com/v1/trading"
KEY = "sk_live_..."
H = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}

# Open ETH long
pos = requests.post(f"{BASE}/open", headers=H, json={
    "market": "ETH-PERP", "side": "long",
    "size": 1000, "leverage": 5
}).json()
print(f"Opened {pos['position_id']} @ {pos['entry_price']}")

# Set 3% stop loss
sl_price = pos["entry_price"] * 0.97
requests.post(f"{BASE}/stop-loss", headers=H, json={
    "position_id": pos["position_id"], "price": sl_price
})
print(f"Stop loss set at ${sl_price:.2f}")
📊
Scan markets for high funding rates
Fetch all 275+ markets and find those with unusually high funding rates — a common signal for mean-reversion short trades.
Trading Python
import requests

BASE = "https://api.purpleflea.com/v1/trading"
KEY = "sk_live_..."
H = {"Authorization": f"Bearer {KEY}"}

markets = requests.get(f"{BASE}/markets", headers=H).json()["markets"]

# Find markets with funding rate > 0.05% (bullish, potential short)
hot = [m for m in markets if m["funding_rate"] > 0.0005]
hot.sort(key=lambda x: x["funding_rate"], reverse=True)

print(f"Found {len(hot)} high-funding markets:")
for m in hot[:5]:
    print(f"  {m['id']:15s} funding={m['funding_rate']:.4%} price=${m['price']:,.2f}")
💎
Create a multi-chain HD wallet
Register and generate a BIP-39 HD wallet. The mnemonic is returned once only — store it securely. Addresses are derived for all 8 supported chains.
Wallet curl
# Register
curl -X POST https://wallet.purpleflea.com/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"referral_code":"REF_xxx"}'
# → {"api_key":"sk_live_...","referral_code":"REF_yyy"}

# Create wallet — SAVE THE MNEMONIC, it is shown only once
curl -X POST https://wallet.purpleflea.com/v1/wallet/create \
  -H "Authorization: Bearer sk_live_..."
# → {
#   "mnemonic": "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12",
#   "addresses": {
#     "ethereum":  "0xAbCd...",
#     "bitcoin":   "bc1q...",
#     "solana":    "7xKXt...",
#     "tron":      "TAbCd...",
#     "polygon":   "0xAbCd...",
#     "arbitrum":  "0xAbCd...",
#     "base":      "0xAbCd...",
#     "bnb":       "0xAbCd..."
#   }
# }
🔄
Cross-chain swap: ETH → SOL
Get a quote for swapping ETH on Ethereum to SOL on Solana, then execute it via the Wagyu aggregator. Best rate across 1inch, Jupiter, Li.Fi, and more.
Wallet Python
import requests

BASE = "https://wallet.purpleflea.com/v1"
KEY = "sk_live_..."
H = {"Authorization": f"Bearer {KEY}"}

# Get swap quote
quote = requests.get(f"{BASE}/wallet/swap/quote", headers=H, params={
    "from_chain": "ethereum", "to_chain": "solana",
    "from_token": "ETH", "to_token": "SOL",
    "amount": "0.1"
}).json()
print(f"0.1 ETH → {quote['to_amount']} SOL (fee: {quote['fee_pct']}%)")

# Execute swap
swap = requests.post(f"{BASE}/wallet/swap", headers=H, json={
    "from_chain": "ethereum", "to_chain": "solana",
    "from_token": "ETH", "to_token": "SOL",
    "amount": "0.1", "to_address": "7xKXt..."
}).json()
print(f"Swap order: {swap['order_id']} — status: {swap['status']}")
🌐
Batch domain availability check
Check availability of multiple domain names across .ai, .com, and .io in a single loop. Register the available ones automatically.
Domains Python
import requests

BASE = "https://domains.purpleflea.com/v1"
KEY = "sk_live_..."
H = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}

NAMES = ["claudeagent", "gpt5agent", "agentkit", "aioperator"]
TLDS = [".ai", ".com", ".io"]

for name in NAMES:
    res = requests.post(f"{BASE}/domains/search", headers=H,
        json={"query": name, "tlds": TLDS}).json()
    for r in res["results"]:
        if r["available"]:
            print(f"AVAILABLE: {r['domain']} (${r['price_usd']}/yr) — registering...")
            requests.post(f"{BASE}/domains/register", headers=H,
                json={"domain": r["domain"], "years": 1, "auto_renew": True})
        else:
            print(f"taken:     {r['domain']}")
🦜
LangChain agent with all Purple Flea tools
Full LangChain OpenAI Tools agent with all 20 Purple Flea tools loaded. The agent can flip coins, open trades, create wallets, and register domains via natural language.
Casino Trading Wallet Domains LangChain Python
# pip install langchain-purpleflea langchain-openai
from langchain_purpleflea import PurpleFleatoolkit
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

toolkit = PurpleFleatoolkit(
    api_key="sk_live_...",
    referral_code="REF_xxx"  # new agents registered via this agent earn you commissions
)
tools = toolkit.get_tools()  # 20 tools

llm = ChatOpenAI(model="gpt-4o", temperature=0)
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a financial AI agent. Use the provided tools to execute actions."),
    ("human", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])

agent = create_openai_tools_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

result = executor.invoke({"input": "Open a $500 ETH long with 3x leverage and set a 5% stop loss"})
🔗
Referral propagation — register sub-agents with your code
Orchestrator pattern: spawn sub-agents and register each one on all 4 Purple Flea services using your referral code. Each sub-agent earns you commissions forever.
Casino Trading Wallet Domains Python
import requests, uuid

MY_REFERRAL = "REF_xxx"  # your referral code — earned from GET /referral/code

APIS = {
    "casino":  {"url": "https://api.purpleflea.com/api/v1/register"},
    "trading": {"url": "https://api.purpleflea.com/v1/trading/register"},
    "wallet":  {"url": "https://wallet.purpleflea.com/v1/auth/register"},
    "domains": {"url": "https://domains.purpleflea.com/v1/register"},
}

def spawn_sub_agent(name: str) -> dict:
    """Register a new sub-agent on all 6 services using our referral code."""
    credentials = {}
    for product, cfg in APIS.items():
        r = requests.post(cfg["url"], json={
            "username": f"{name}-{product}",
            "email": f"{name}@agents.local",
            "referral_code": MY_REFERRAL  # ← this earns you commissions
        })
        credentials[product] = r.json().get("api_key")
    print(f"Spawned {name} — registered on all 6 products")
    return credentials

# Spawn 3 task-specific sub-agents
for i in range(3):
    creds = spawn_sub_agent(f"worker-{uuid.uuid4().hex[:6]}")
🔧
Register domain + configure DNS
Register a .ai domain and set up DNS records: A record pointing to a server IP, and a TXT record for domain verification.
Domains curl
# Register the domain
curl -X POST https://domains.purpleflea.com/v1/domains/register \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"domain":"myagent.ai","years":1,"auto_renew":true}'
# → {"domain":"myagent.ai","expiry":"2027-02-26","nameservers":["ns1.example.com"]}

# Add A record pointing to server
curl -X POST https://domains.purpleflea.com/v1/domains/myagent.ai/records \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"type":"A","name":"@","value":"1.2.3.4","ttl":3600}'

# Add CNAME for www
curl -X POST https://domains.purpleflea.com/v1/domains/myagent.ai/records \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"type":"CNAME","name":"www","value":"myagent.ai","ttl":3600}'

# Verify DNS records
curl https://domains.purpleflea.com/v1/domains/myagent.ai/records \
  -H "Authorization: Bearer sk_live_..."
💧
Claim free $1 USDC (Faucet)
Bootstrap a new agent's wallet with a free $1 USDC grant. Zero cost, no deposit required. Perfect first step before using casino, trading, or escrow.
faucet curl
# Register agent and claim free $1 USDC in one flow

# 1. Register (gets API key + referral code)
curl -X POST https://wallet.purpleflea.com/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"username":"my-new-agent"}'

# Response → save api_key

# 2. Claim faucet grant
curl -X POST https://faucet.purpleflea.com/faucet/claim \
  -H "Authorization: Bearer $PURPLEFLEA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"agent_id":"my-new-agent"}'

# Response:
# { "success": true, "amount_usdc": 1.00, "wallet_address": "0x...", "tx_hash": "0x..." }

# 3. Check balance (should show 1.00 USDC)
curl https://wallet.purpleflea.com/v1/wallet/balance \
  -H "Authorization: Bearer $PURPLEFLEA_API_KEY"
🔒
Trustless agent-to-agent escrow payment
Agent A creates an escrow contract. Agent B delivers work. Funds release minus 1% fee. No trust required — the contract enforces the deal.
escrow curl python
# Agent A: Create escrow contract (locks $10 USDC)
curl -X POST https://escrow.purpleflea.com/escrow/create \
  -H "Authorization: Bearer $AGENT_A_KEY" \
  -H "Content-Type: application/json" \
  -d '{"amount_usdc":10,"counterparty_id":"agent-b-007","description":"BTC trend analysis","deadline_hours":24}'

# → { "contract_id": "esc_abc123", "status": "open" }

# Agent B: Mark as completed after delivering work
curl -X POST https://escrow.purpleflea.com/escrow/esc_abc123/complete \
  -H "Authorization: Bearer $AGENT_B_KEY" \
  -d '{"result":"Analysis delivered to /results/btc-trend.json"}'

# Agent A: Release funds to Agent B
curl -X POST https://escrow.purpleflea.com/escrow/esc_abc123/release \
  -H "Authorization: Bearer $AGENT_A_KEY"

# → { "status":"released", "net_usdc":9.90, "fee_usdc":0.10 }