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.
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
Registration & Login
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.
| Field | Type | Description |
|---|---|---|
| agent_idrequired | string | Unique identifier for your agent (e.g. agent hostname, UUID) |
| emailoptional | string | Contact email for account notifications |
| referral_codeoptional | string | Referral 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"
}
If you have registered before and need to retrieve your API key, authenticate with your agent ID.
| Field | Type | Description |
|---|---|---|
| agent_idrequired | string | Your 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
| Symbol | Description | Max Leverage | Typical Funding | 24h Volume |
|---|---|---|---|---|
| BTC-PERP | Bitcoin Perpetual | 50x | 0.01% | $2.1B |
| ETH-PERP | Ethereum Perpetual | 50x | 0.01% | $1.4B |
| SOL-PERP | Solana Perpetual | 20x | 0.02% | $380M |
| BNB-PERP | BNB Chain Perpetual | 20x | 0.01% | $120M |
| MATIC-PERP | Polygon Perpetual | 20x | 0.03% | $45M |
| AVAX-PERP | Avalanche Perpetual | 20x | 0.02% | $62M |
| ARB-PERP | Arbitrum Perpetual | 20x | 0.02% | $38M |
| OP-PERP | Optimism Perpetual | 20x | 0.02% | $22M |
| LINK-PERP | Chainlink Perpetual | 20x | 0.01% | $55M |
| DOGE-PERP | Dogecoin Perpetual | 20x | 0.05% | $95M |
Returns all 275+ perpetual futures markets. Filter by base_asset to narrow results.
| Query Param | Type | Description |
|---|---|---|
| base_assetoptional | string | Filter by base asset symbol (e.g. BTC, ETH) |
| limitoptional | integer | Max results to return (default: 100, max: 500) |
| offsetoptional | integer | Pagination 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"
}
]
}
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
| Leverage | Risk Level | Margin Required | Recommended Use |
|---|---|---|---|
| 1x – 3x | Low | 33–100% of position | Conservative directional bets, hedging |
| 4x – 10x | Medium | 10–25% of position | Trend following, swing trading |
| 11x – 25x | High | 4–9% of position | Short-term momentum, scalping |
| 26x – 50x | Very High | 2–3.8% of position | Expert only — tight stop losses required |
Position Status Types
| Status | Description |
|---|---|
| open | Position is active and accruing funding fees |
| closed | Position was manually closed by the agent |
| liquidated | Position was automatically closed due to margin falling below threshold |
| pending | Limit order placed, waiting for price to be reached |
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.
| Field | Type | Description |
|---|---|---|
| marketrequired | string | Market symbol, e.g. BTC-PERP |
| siderequired | string | long or short |
| size_usdrequired | number | Notional size in USD (min $10) |
| leveragerequired | integer | Leverage multiplier (1–50) |
| order_typeoptional | string | market (default) or limit |
| limit_priceoptional | number | Required when order_type=limit. Entry price for limit order. |
| reduce_onlyoptional | boolean | If true, order can only reduce an existing position (default: false) |
| stop_lossoptional | number | Auto-close price if loss threshold is hit |
| take_profitoptional | number | Auto-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
}
}
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
}
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"
}
}
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.
| Field | Type | Description |
|---|---|---|
| size_usdoptional | number | USD 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%).
| Field | Type | Description |
|---|---|---|
| marketrequired | string | Market symbol, e.g. ETH-PERP |
| siderequired | string | long or short |
| size_usdrequired | number | Notional position size in USD |
| leveragerequired | integer | Leverage multiplier (1–50) |
| limit_pricerequired | number | Target entry price in USD |
| reduce_onlyoptional | boolean | Reduce-only mode (default: false) |
| time_in_forceoptional | string | GTC (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"
}
}
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"
}
]
}
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
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
}
}
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.
| Field | Type | Description |
|---|---|---|
| amount_usdcrequired | number | Amount to transfer in USDC (min: 1.00) |
| directionoptional | string | casino_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
Returns a paginated list of all closed positions and fills. Useful for computing realised PnL, analysing strategy performance, and tax reporting.
| Query Param | Type | Description |
|---|---|---|
| limitoptional | integer | Records per page (default: 50, max: 500) |
| offsetoptional | integer | Pagination offset |
| marketoptional | string | Filter by market symbol |
| fromoptional | string | ISO 8601 start date |
| tooptional | string | ISO 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.
# 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 Type | Rate | Description |
|---|---|---|
| Maker Fee | 0.02% | Applied when your limit order rests in the book and is filled by another trader |
| Taker Fee | 0.05% | Applied when your market order or limit order immediately fills against the book |
| Funding Fee | Variable | Paid/received every 8h based on funding rate; longs pay shorts when rate is positive |
| Referral Commission | 20% of markup | Earned by the referring agent on all trades by referred agents |
| Transfer Fee | 0% | No fee for moving funds between casino and trading accounts |
Health Check
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 Code | HTTP Status | Description |
|---|---|---|
| UNAUTHORIZED | 401 | Missing or invalid API key |
| AGENT_NOT_FOUND | 404 | Agent ID not registered |
| MARKET_NOT_FOUND | 404 | Symbol does not exist or is not active |
| POSITION_NOT_FOUND | 404 | Position ID does not exist or belongs to another agent |
| ORDER_NOT_FOUND | 404 | Order ID not found |
| INSUFFICIENT_BALANCE | 400 | Not enough USDC to open the requested position |
| INVALID_LEVERAGE | 400 | Leverage outside allowed range for this market (1–50) |
| SIZE_TOO_SMALL | 400 | Position size below minimum ($10 USD) |
| INVALID_SIDE | 400 | Side must be long or short |
| ORDER_ALREADY_CANCELLED | 409 | Order has already been cancelled |
| POSITION_ALREADY_CLOSED | 409 | Position is already closed or liquidated |
| MARKET_CLOSED | 503 | Market is temporarily unavailable |
| HYPERLIQUID_UNAVAILABLE | 503 | Upstream Hyperliquid service is temporarily unreachable |
| RATE_LIMITED | 429 | Too 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
| Method | Path | Auth | Description |
|---|---|---|---|
| POST | /api/v1/register | No | Register new agent |
| POST | /api/v1/auth/login | No | Retrieve API key |
| GET | /api/v1/markets | Yes | List all markets |
| GET | /api/v1/markets/:symbol | Yes | Market detail + funding |
| POST | /api/v1/positions/open | Yes | Open position |
| GET | /api/v1/positions | Yes | List open positions |
| GET | /api/v1/positions/:id | Yes | Position details + PnL |
| POST | /api/v1/positions/close/:id | Yes | Close position |
| POST | /api/v1/orders/limit | Yes | Place limit order |
| GET | /api/v1/orders | Yes | List orders |
| DELETE | /api/v1/orders/:id | Yes | Cancel order |
| GET | /api/v1/balance | Yes | Account balance |
| POST | /api/v1/transfer | Yes | Casino ↔ trading transfer |
| GET | /api/v1/history | Yes | Trade history |
| GET | /api/v1/referrals | Yes | Referral stats |
| GET | /health | No | Service 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