Trading API Trading

Access 275+ perpetual futures markets powered by Hyperliquid infrastructure. Open long and short positions with up to 50x leverage, place limit orders, and earn 20% referral commission on fee markup generated by agents you refer.

Auth Header
X-API-Key: <key>
Markets
275+ perp pairs
Max Leverage
50x
Maker Fee
0.02%
Taker Fee
0.05%
Referral Rate
20% of markup
Settlement
USDC

Authentication

All endpoints (except GET /health and POST /api/v1/register) require an API key sent in the X-API-Key header. You receive your API key upon registration.

# All authenticated requests
curl -H "X-API-Key: YOUR_API_KEY" \
     https://trading.purpleflea.com/api/v1/balance
Note: API keys do not expire but can be rotated by re-registering with the same agent identifier. Keep your key secure — it controls your trading account.

Registration & Login

POST /api/v1/register Register a new agent account

Creates a new trading account and returns your API key and referral code. No authentication required. If you have a referral code from another agent, pass it to start the referral relationship immediately.

FieldTypeDescription
agent_idrequiredstringUnique identifier for your agent (e.g. agent hostname, UUID)
emailoptionalstringContact email for account notifications
referral_codeoptionalstringReferral code from the agent that referred you
# Request
curl -X POST https://trading.purpleflea.com/api/v1/register \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "my-trading-agent-v1",
    "referral_code": "PFREF123"
  }'

# Response 200 OK
{
  "success": true,
  "api_key": "pf_live_trading_abc123xyz...",
  "referral_code": "TRADE456",
  "agent_id": "my-trading-agent-v1",
  "balance_usdc": 0.00,
  "created_at": "2026-03-06T09:00:00Z"
}
POST /api/v1/auth/login Authenticate and retrieve API key

If you have registered before and need to retrieve your API key, authenticate with your agent ID.

FieldTypeDescription
agent_idrequiredstringYour registered agent identifier
# Request
curl -X POST https://trading.purpleflea.com/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "my-trading-agent-v1"}'

# Response 200 OK
{
  "success": true,
  "api_key": "pf_live_trading_abc123xyz...",
  "agent_id": "my-trading-agent-v1",
  "referral_code": "TRADE456"
}

Markets

Purple Flea Trading provides access to 275+ perpetual futures markets. All markets are USDC-settled and offer cross-margin or isolated-margin modes.

Top Markets Overview

SymbolDescriptionMax LeverageTypical Funding24h Volume
BTC-PERPBitcoin Perpetual50x0.01%$2.1B
ETH-PERPEthereum Perpetual50x0.01%$1.4B
SOL-PERPSolana Perpetual20x0.02%$380M
BNB-PERPBNB Chain Perpetual20x0.01%$120M
MATIC-PERPPolygon Perpetual20x0.03%$45M
AVAX-PERPAvalanche Perpetual20x0.02%$62M
ARB-PERPArbitrum Perpetual20x0.02%$38M
OP-PERPOptimism Perpetual20x0.02%$22M
LINK-PERPChainlink Perpetual20x0.01%$55M
DOGE-PERPDogecoin Perpetual20x0.05%$95M
GET /api/v1/markets List all available markets

Returns all 275+ perpetual futures markets. Filter by base_asset to narrow results.

Query ParamTypeDescription
base_assetoptionalstringFilter by base asset symbol (e.g. BTC, ETH)
limitoptionalintegerMax results to return (default: 100, max: 500)
offsetoptionalintegerPagination offset (default: 0)
# List all markets
curl -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/markets

# Filter by base asset
curl -H "X-API-Key: YOUR_API_KEY" \
  "https://trading.purpleflea.com/api/v1/markets?base_asset=BTC"

# Response 200 OK
{
  "success": true,
  "total": 275,
  "markets": [
    {
      "symbol": "BTC-PERP",
      "base_asset": "BTC",
      "quote_asset": "USDC",
      "max_leverage": 50,
      "tick_size": 0.1,
      "min_size_usd": 10,
      "status": "active"
    }
  ]
}
GET /api/v1/markets/:symbol Get detailed market data

Returns real-time market data for a single symbol including current funding rate, open interest, 24h volume, and price data. Funding rates are charged every 8 hours.

# Get BTC perpetual market details
curl -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/markets/BTC-PERP

# Response 200 OK
{
  "success": true,
  "market": {
    "symbol": "BTC-PERP",
    "base_asset": "BTC",
    "mark_price": 87420.50,
    "index_price": 87415.20,
    "funding_rate": 0.000100,
    "next_funding_time": "2026-03-06T16:00:00Z",
    "open_interest_usd": 4820000000,
    "volume_24h_usd": 2100000000,
    "price_change_24h_pct": 2.34,
    "high_24h": 88100.00,
    "low_24h": 85600.00,
    "max_leverage": 50,
    "maker_fee": 0.0002,
    "taker_fee": 0.0005
  }
}

Positions

Positions represent open perpetual futures contracts. Positions are settled in USDC and can be partially or fully closed at any time. Liquidation occurs when margin falls below the maintenance margin threshold.

Leverage Table

LeverageRisk LevelMargin RequiredRecommended Use
1x – 3xLow33–100% of positionConservative directional bets, hedging
4x – 10xMedium10–25% of positionTrend following, swing trading
11x – 25xHigh4–9% of positionShort-term momentum, scalping
26x – 50xVery High2–3.8% of positionExpert only — tight stop losses required

Position Status Types

StatusDescription
openPosition is active and accruing funding fees
closedPosition was manually closed by the agent
liquidatedPosition was automatically closed due to margin falling below threshold
pendingLimit order placed, waiting for price to be reached
POST /api/v1/positions/open Open a new perpetual position

Opens a long or short perpetual futures position. For market orders, the position opens immediately at the current mark price. For limit orders, the order is placed in the order book and fills when the price is reached.

FieldTypeDescription
marketrequiredstringMarket symbol, e.g. BTC-PERP
siderequiredstringlong or short
size_usdrequirednumberNotional size in USD (min $10)
leveragerequiredintegerLeverage multiplier (1–50)
order_typeoptionalstringmarket (default) or limit
limit_priceoptionalnumberRequired when order_type=limit. Entry price for limit order.
reduce_onlyoptionalbooleanIf true, order can only reduce an existing position (default: false)
stop_lossoptionalnumberAuto-close price if loss threshold is hit
take_profitoptionalnumberAuto-close price if profit threshold is hit
# Open a long BTC position with 5x leverage
curl -X POST https://trading.purpleflea.com/api/v1/positions/open \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "market": "BTC-PERP",
    "side": "long",
    "size_usd": 500,
    "leverage": 5,
    "order_type": "market",
    "stop_loss": 85000,
    "take_profit": 92000
  }'

# Response 200 OK
{
  "success": true,
  "position": {
    "id": "pos_7f3a9b2c",
    "market": "BTC-PERP",
    "side": "long",
    "size_usd": 500,
    "leverage": 5,
    "margin_usd": 100,
    "entry_price": 87420.50,
    "liquidation_price": 70120.40,
    "stop_loss": 85000,
    "take_profit": 92000,
    "status": "open",
    "opened_at": "2026-03-06T09:12:00Z",
    "fee_usdc": 0.25
  }
}
GET /api/v1/positions List all open positions

Returns all currently open positions for your account. Includes unrealised PnL calculated at current mark price and accrued funding fees.

# Get all open positions
curl -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/positions

# Response 200 OK
{
  "success": true,
  "positions": [
    {
      "id": "pos_7f3a9b2c",
      "market": "BTC-PERP",
      "side": "long",
      "size_usd": 500,
      "leverage": 5,
      "entry_price": 87420.50,
      "mark_price": 88100.00,
      "unrealised_pnl": 3.88,
      "pnl_pct": 3.88,
      "funding_fee_total": -0.05,
      "liquidation_price": 70120.40,
      "status": "open",
      "opened_at": "2026-03-06T09:12:00Z"
    }
  ],
  "total_unrealised_pnl": 3.88
}
GET /api/v1/positions/:id Get position details

Returns full detail for a single position including entry price, current size, leverage, real-time PnL, liquidation price, and cumulative funding fees paid.

# Get a specific position
curl -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/positions/pos_7f3a9b2c

# Response 200 OK
{
  "success": true,
  "position": {
    "id": "pos_7f3a9b2c",
    "market": "BTC-PERP",
    "side": "long",
    "size_usd": 500,
    "leverage": 5,
    "margin_usd": 100,
    "entry_price": 87420.50,
    "mark_price": 88100.00,
    "liquidation_price": 70120.40,
    "unrealised_pnl": 3.88,
    "realised_pnl": 0.00,
    "funding_fee_total": -0.05,
    "stop_loss": 85000,
    "take_profit": 92000,
    "status": "open",
    "opened_at": "2026-03-06T09:12:00Z",
    "last_funding_time": "2026-03-06T08:00:00Z"
  }
}
POST /api/v1/positions/close/:id Close a position (full or partial)

Closes an open position at the current market price. Pass size_usd to partially close a position, or omit it to close the entire position.

FieldTypeDescription
size_usdoptionalnumberUSD amount to close. Omit to close the full position.
# Close full position
curl -X POST https://trading.purpleflea.com/api/v1/positions/close/pos_7f3a9b2c \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'

# Partially close $200 of a $500 position
curl -X POST https://trading.purpleflea.com/api/v1/positions/close/pos_7f3a9b2c \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"size_usd": 200}'

# Response 200 OK
{
  "success": true,
  "closed": {
    "position_id": "pos_7f3a9b2c",
    "close_price": 88100.00,
    "size_closed_usd": 500,
    "realised_pnl": 3.88,
    "fee_usdc": 0.25,
    "net_pnl": 3.63,
    "status": "closed",
    "closed_at": "2026-03-06T11:45:00Z"
  }
}

Limit Orders

Limit orders allow you to specify an exact entry price. The order rests in the book until the market reaches your price, earning the maker fee rate (0.02%) instead of the taker fee (0.05%).

POST /api/v1/orders/limit Place a limit order
FieldTypeDescription
marketrequiredstringMarket symbol, e.g. ETH-PERP
siderequiredstringlong or short
size_usdrequirednumberNotional position size in USD
leveragerequiredintegerLeverage multiplier (1–50)
limit_pricerequirednumberTarget entry price in USD
reduce_onlyoptionalbooleanReduce-only mode (default: false)
time_in_forceoptionalstringGTC (Good Till Cancel, default) or IOC (Immediate or Cancel)
# Place a limit buy for ETH at $3,200
curl -X POST https://trading.purpleflea.com/api/v1/orders/limit \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "market": "ETH-PERP",
    "side": "long",
    "size_usd": 1000,
    "leverage": 3,
    "limit_price": 3200.00,
    "time_in_force": "GTC"
  }'

# Response 200 OK
{
  "success": true,
  "order": {
    "id": "ord_4c8d1e2f",
    "market": "ETH-PERP",
    "side": "long",
    "type": "limit",
    "size_usd": 1000,
    "leverage": 3,
    "limit_price": 3200.00,
    "status": "pending",
    "time_in_force": "GTC",
    "created_at": "2026-03-06T09:30:00Z"
  }
}
GET /api/v1/orders List all orders

Returns all pending and recently filled limit orders.

# Get all orders
curl -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/orders

# Response 200 OK
{
  "success": true,
  "orders": [
    {
      "id": "ord_4c8d1e2f",
      "market": "ETH-PERP",
      "side": "long",
      "type": "limit",
      "size_usd": 1000,
      "limit_price": 3200.00,
      "status": "pending",
      "created_at": "2026-03-06T09:30:00Z"
    }
  ]
}
DELETE /api/v1/orders/:id Cancel a pending order

Cancels a pending limit order. Only orders in pending status can be cancelled.

# Cancel order
curl -X DELETE \
  -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/orders/ord_4c8d1e2f

# Response 200 OK
{
  "success": true,
  "order_id": "ord_4c8d1e2f",
  "status": "cancelled",
  "cancelled_at": "2026-03-06T10:05:00Z"
}

Balance & Transfer

GET /api/v1/balance Get trading account balance

Returns your current trading balance including available margin, reserved margin (in open positions), and total account equity including unrealised PnL.

# Get balance
curl -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/balance

# Response 200 OK
{
  "success": true,
  "balance": {
    "usdc_available": 892.45,
    "usdc_in_positions": 100.00,
    "unrealised_pnl": 3.88,
    "total_equity": 996.33,
    "total_deposited": 1000.00,
    "total_realised_pnl": -7.55,
    "total_fees_paid": 3.88
  }
}
POST /api/v1/transfer Transfer USDC from casino balance to trading

Moves USDC from your Purple Flea casino balance into your trading account. Both accounts use the same agent identity. Transfers are instant and do not incur a fee.

FieldTypeDescription
amount_usdcrequirednumberAmount to transfer in USDC (min: 1.00)
directionoptionalstringcasino_to_trading (default) or trading_to_casino
# Transfer $100 from casino to trading
curl -X POST https://trading.purpleflea.com/api/v1/transfer \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "amount_usdc": 100,
    "direction": "casino_to_trading"
  }'

# Response 200 OK
{
  "success": true,
  "transfer_id": "txfr_9a1b3d4e",
  "amount_usdc": 100.00,
  "direction": "casino_to_trading",
  "new_trading_balance": 100.00,
  "completed_at": "2026-03-06T09:00:05Z"
}

Trade History

GET /api/v1/history Get trade and position history

Returns a paginated list of all closed positions and fills. Useful for computing realised PnL, analysing strategy performance, and tax reporting.

Query ParamTypeDescription
limitoptionalintegerRecords per page (default: 50, max: 500)
offsetoptionalintegerPagination offset
marketoptionalstringFilter by market symbol
fromoptionalstringISO 8601 start date
tooptionalstringISO 8601 end date
# Get last 50 closed positions
curl -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/history

# Filter by market and date range
curl -H "X-API-Key: YOUR_API_KEY" \
  "https://trading.purpleflea.com/api/v1/history?market=BTC-PERP&from=2026-03-01&to=2026-03-06"

# Response 200 OK
{
  "success": true,
  "total": 42,
  "history": [
    {
      "position_id": "pos_7f3a9b2c",
      "market": "BTC-PERP",
      "side": "long",
      "entry_price": 87420.50,
      "close_price": 88100.00,
      "size_usd": 500,
      "leverage": 5,
      "realised_pnl": 3.88,
      "fees_paid": 0.50,
      "funding_fees": -0.05,
      "net_pnl": 3.33,
      "close_reason": "manual",
      "opened_at": "2026-03-06T09:12:00Z",
      "closed_at": "2026-03-06T11:45:00Z"
    }
  ]
}

Referral System

Every registered agent receives a unique referral code. When other agents register using your code, you earn 20% of the fee markup generated by their trades — forever. There is no cap on referral earnings.

How it works: Purple Flea charges a small markup on top of Hyperliquid's base fees. 20% of that markup is distributed to the referring agent. Referrals are tracked automatically from the moment of registration.
GET /api/v1/referrals Get referral stats and earnings
# Get referral stats
curl -H "X-API-Key: YOUR_API_KEY" \
  https://trading.purpleflea.com/api/v1/referrals

# Response 200 OK
{
  "success": true,
  "referral_code": "TRADE456",
  "referral_url": "https://trading.purpleflea.com?ref=TRADE456",
  "referred_agents": 3,
  "earnings_total_usdc": 12.45,
  "earnings_pending_usdc": 2.10,
  "earnings_paid_usdc": 10.35,
  "commission_rate": 0.20,
  "referrals": [
    {
      "agent_id": "agent-xyz",
      "joined_at": "2026-02-15T14:00:00Z",
      "volume_usd": 45000,
      "fees_generated_usdc": 22.50,
      "your_earnings_usdc": 4.50
    }
  ]
}

Fee Structure

Fee TypeRateDescription
Maker Fee0.02%Applied when your limit order rests in the book and is filled by another trader
Taker Fee0.05%Applied when your market order or limit order immediately fills against the book
Funding FeeVariablePaid/received every 8h based on funding rate; longs pay shorts when rate is positive
Referral Commission20% of markupEarned by the referring agent on all trades by referred agents
Transfer Fee0%No fee for moving funds between casino and trading accounts
Fee example: On a $10,000 taker trade, fee is $5.00 USDC. If your referrer's commission is 20% of the markup, they earn approximately $1.00 for that single trade.

Health Check

GET /health Service health status

Returns the current status of the trading service. No authentication required. Use this endpoint to verify connectivity before placing orders.

# Check health
curl https://trading.purpleflea.com/health

# Response 200 OK
{
  "status": "ok",
  "service": "purple-flea-trading",
  "markets_active": 275,
  "hyperliquid_connected": true,
  "uptime_seconds": 604800,
  "version": "1.3.0",
  "timestamp": "2026-03-06T09:00:00Z"
}

Error Codes

All errors return a JSON body with success: false, an error string, and an error_code for programmatic handling.

# Example error response
{
  "success": false,
  "error": "Insufficient balance: need 100.00 USDC, have 42.50",
  "error_code": "INSUFFICIENT_BALANCE"
}
Error CodeHTTP StatusDescription
UNAUTHORIZED401Missing or invalid API key
AGENT_NOT_FOUND404Agent ID not registered
MARKET_NOT_FOUND404Symbol does not exist or is not active
POSITION_NOT_FOUND404Position ID does not exist or belongs to another agent
ORDER_NOT_FOUND404Order ID not found
INSUFFICIENT_BALANCE400Not enough USDC to open the requested position
INVALID_LEVERAGE400Leverage outside allowed range for this market (1–50)
SIZE_TOO_SMALL400Position size below minimum ($10 USD)
INVALID_SIDE400Side must be long or short
ORDER_ALREADY_CANCELLED409Order has already been cancelled
POSITION_ALREADY_CLOSED409Position is already closed or liquidated
MARKET_CLOSED503Market is temporarily unavailable
HYPERLIQUID_UNAVAILABLE503Upstream Hyperliquid service is temporarily unreachable
RATE_LIMITED429Too many requests; back off and retry after the indicated delay

Python Example: Open, Monitor & Close a Position

This complete example demonstrates a simple trading loop using the Trading API: register, deposit funds, open a long BTC position with a trailing stop, poll for status, and close when profit target is hit.

import requests
import time
import json

BASE_URL = "https://trading.purpleflea.com"

# Step 1: Register agent
def register(agent_id, referral_code=None):
    payload = {"agent_id": agent_id}
    if referral_code:
        payload["referral_code"] = referral_code
    r = requests.post(f"{BASE_URL}/api/v1/register", json=payload)
    data = r.json()
    return data["api_key"], data["referral_code"]

# Step 2: Authenticated helper
def api(method, path, api_key, **kwargs):
    headers = {"X-API-Key": api_key, "Content-Type": "application/json"}
    url = f"{BASE_URL}{path}"
    r = getattr(requests, method)(url, headers=headers, **kwargs)
    r.raise_for_status()
    return r.json()

def main():
    # Register (or re-use existing key)
    agent_id = "btc-momentum-bot-v1"
    api_key, ref_code = register(agent_id, referral_code="PFSTART")
    print(f"Registered. API key: {api_key[:20]}... Ref code: {ref_code}")

    # Check balance
    balance = api("get", "/api/v1/balance", api_key)["balance"]
    print(f"Available: ${balance['usdc_available']:.2f} USDC")

    # Check BTC market conditions
    market = api("get", "/api/v1/markets/BTC-PERP", api_key)["market"]
    mark_price = market["mark_price"]
    funding = market["funding_rate"]
    print(f"BTC mark price: ${mark_price:,.2f} | Funding: {funding*100:.4f}%")

    # Only go long if funding is not too expensive
    if funding > 0.001:
        print("Funding too high, skipping long")
        return

    # Open a $200 long with 5x leverage
    stop_loss = round(mark_price * 0.97, 1)   # 3% stop
    take_profit = round(mark_price * 1.05, 1) # 5% target
    pos_result = api("post", "/api/v1/positions/open", api_key, json={
        "market": "BTC-PERP",
        "side": "long",
        "size_usd": 200,
        "leverage": 5,
        "order_type": "market",
        "stop_loss": stop_loss,
        "take_profit": take_profit
    })
    position = pos_result["position"]
    pos_id = position["id"]
    print(f"Opened position {pos_id} at ${position['entry_price']:,.2f}")
    print(f"SL: ${stop_loss:,.2f} | TP: ${take_profit:,.2f}")

    # Monitor position every 30 seconds
    for _ in range(20):  # max 10 minutes
        time.sleep(30)
        pos = api("get", f"/api/v1/positions/{pos_id}", api_key)
        if pos["position"]["status"] != "open":
            print(f"Position closed automatically: {pos['position']['status']}")
            break
        pnl = pos["position"]["unrealised_pnl"]
        pnl_pct = pos["position"]["pnl_pct"]
        print(f"PnL: ${pnl:.2f} ({pnl_pct:.2f}%)")

        # Manual exit if PnL exceeds 4% (take_profit handles 5%)
        if pnl_pct >= 4.0:
            close = api("post", f"/api/v1/positions/close/{pos_id}", api_key, json={})
            print(f"Closed at profit: ${close['closed']['net_pnl']:.2f} USDC")
            break

    # Print referral stats
    refs = api("get", "/api/v1/referrals", api_key)
    print(f"Referral earnings: ${refs['earnings_total_usdc']:.2f} USDC")

if __name__ == "__main__":
    main()

Endpoint Index

MethodPathAuthDescription
POST/api/v1/registerNoRegister new agent
POST/api/v1/auth/loginNoRetrieve API key
GET/api/v1/marketsYesList all markets
GET/api/v1/markets/:symbolYesMarket detail + funding
POST/api/v1/positions/openYesOpen position
GET/api/v1/positionsYesList open positions
GET/api/v1/positions/:idYesPosition details + PnL
POST/api/v1/positions/close/:idYesClose position
POST/api/v1/orders/limitYesPlace limit order
GET/api/v1/ordersYesList orders
DELETE/api/v1/orders/:idYesCancel order
GET/api/v1/balanceYesAccount balance
POST/api/v1/transferYesCasino ↔ trading transfer
GET/api/v1/historyYesTrade history
GET/api/v1/referralsYesReferral stats
GET/healthNoService health

Get Started

Ready to start trading? Register your agent and get your API key in seconds. Pair the Trading API with the Wallet API to automate deposits, or use the Casino API to transfer winnings into trading capital.

Open Trading Account   Try in Playground