pip install purpleflea

Purple Flea
Python SDK

The official Python client for all Purple Flea APIs. One install gives you sync and async access to crypto wallets, perpetual futures trading, provably fair casino games, and domain registration. Python 3.9+. Fully typed. Async-native.


One command.
All six APIs.

Install the base SDK with pip. Optional extras pull in framework-specific integrations for LangChain and CrewAI. The core package has zero heavyweight dependencies — just httpx, pydantic, and the Python standard library.

$ pip install purpleflea
$ pip install purpleflea[langchain]
$ pip install purpleflea[crewai]
quickstart.py
import os from purpleflea import PurpleFlea # Sync client — works anywhere, no event loop needed client = PurpleFlea(api_key=os.environ["PURPLEFLEA_API_KEY"]) # Check ETH wallet balance balance = client.wallet.balance("eth") print(balance.amount) # "1.2345" print(balance.usd_value) # "4123.67"

Sync and async.
Your choice.

The SDK ships two first-class clients. Use the synchronous PurpleFlea client for scripts and notebooks. Use AsyncPurpleFlea inside asyncio applications, FastAPI endpoints, and LangGraph agents where every network call should be non-blocking.

sync_example.py
import os from purpleflea import PurpleFlea # Sync client — simple, blocking client = PurpleFlea( api_key=os.environ["PURPLEFLEA_API_KEY"] ) balance = client.wallet.balance("eth") price = client.trading.price("ETH-PERP") result = client.casino.flip_coin("heads", 0.01) domain = client.domains.search("myagent.eth")
async_example.py
import asyncio, os from purpleflea.async_client import AsyncPurpleFlea async def main(): # Context manager handles session lifecycle async with AsyncPurpleFlea( api_key=os.environ["PURPLEFLEA_API_KEY"] ) as client: balance = await client.wallet.balance("eth") price = await client.trading.price("ETH-PERP") print(balance.amount, price.mark_price) asyncio.run(main())

Four modules.
One unified SDK.

Every Purple Flea product maps to a sub-module on the client. Each sub-module is also importable directly for use in typed function signatures and dependency injection.

Module Import path Description Tag
client.wallet purpleflea.wallet Check balances, send crypto, swap tokens across 6 chains Wallet
client.trading purpleflea.trading Open/close perpetual futures positions across 275 markets Trading
client.casino purpleflea.casino Provably fair coin flip, dice, roulette, and slots Casino
client.domains purpleflea.domains Search, register, and manage ENS and .flea domains Domains

Code for every module.

01

Wallet — check balance and send ETH

# Check balance on any supported chain eth_balance = client.wallet.balance("eth") btc_balance = client.wallet.balance("btc") sol_balance = client.wallet.balance("sol") # Send ETH to any address tx = client.wallet.send( chain="eth", to="0xAbCd...1234", amount="0.05", # in ETH ) print(tx.hash) # "0xabc123..." # Swap USDC → ETH via best DEX route swap = client.wallet.swap( from_token="USDC", to_token="ETH", amount="1000", ) print(swap.received) # "0.2987 ETH"
02

Trading — open a leveraged perpetual position

# Get current mark price price = client.trading.price("ETH-PERP") print(price.mark_price) # "3241.50" # Open a long position — 10x leverage, $100 size position = client.trading.open( market="ETH-PERP", side="long", size_usd=100, leverage=10, ) print(position.id) # "pos_abc123" print(position.entry_price) # "3241.50" # Close the position result = client.trading.close(position_id=position.id) print(result.pnl) # "+12.45" (USD)
03

Casino — provably fair coin flip

# Flip a coin — bet 0.01 ETH on heads game = client.casino.flip_coin( choice="heads", wager="0.01", currency="eth", ) print(game.outcome) # "heads" print(game.won) # True print(game.payout) # "0.0198" # Verify the result is provably fair print(game.server_seed_hash) # revealed post-game print(game.client_seed) print(game.nonce)
04

Domains — search and register

# Check domain availability result = client.domains.search("myagent.eth") print(result.available) # True print(result.price_usd) # "5.00" print(result.price_eth) # "0.0015" # Register the domain (points to agent wallet) registration = client.domains.register( name="myagent.eth", years=1, ) print(registration.tx_hash) print(registration.expires) # "2027-01-01"

Typed exceptions.
Structured errors.

Every SDK method raises a typed exception on failure. All exceptions inherit from PurpleFleaError so you can catch broadly or handle specific cases. Each exception carries a machine-readable code field, an HTTP status, and a human-readable message.

error_handling.py
from purpleflea import PurpleFlea from purpleflea.exceptions import ( PurpleFleaError, InsufficientFundsError, RateLimitError, AuthenticationError, ValidationError, ) client = PurpleFlea(api_key="pf_sk_...") try: tx = client.wallet.send( chain="eth", to="0xAbCd...1234", amount="999", # more than balance ) except InsufficientFundsError as e: print(f"Not enough ETH: {e.available} available, {e.required} required") except RateLimitError as e: print(f"Rate limited — retry after {e.retry_after}s") except AuthenticationError: print("Invalid API key — check PURPLEFLEA_API_KEY") except PurpleFleaError as e: # Catch-all for any Purple Flea error print(f"API error [{e.code}]: {e.message}")

Verify signatures.
Trust every event.

Purple Flea sends signed webhooks for transaction confirmations, trade settlements, game outcomes, and domain events. The SDK ships a helper that verifies the HMAC-SHA256 signature in one line — use it in any web framework.

webhook_handler.py
from fastapi import FastAPI, Request, HTTPException from purpleflea.webhooks import verify_signature, WebhookEvent app = FastAPI() @app.post("/webhooks/purpleflea") async def handle_webhook(request: Request): payload = await request.body() signature = request.headers.get("X-PurpleFlea-Signature") secret = os.environ["PURPLEFLEA_WEBHOOK_SECRET"] # Raises InvalidSignatureError if signature is bad event: WebhookEvent = verify_signature(payload, signature, secret) if event.type == "wallet.transaction.confirmed": print(f"TX confirmed: {event.data['hash']}") elif event.type == "trading.position.closed": print(f"Position closed. PnL: {event.data['pnl']}") return {"status": "ok"}

Fully typed.
Pydantic-powered.

Every SDK method is annotated with precise input and return types. All API responses are deserialized into Pydantic v2 models — you get IDE autocompletion, runtime validation, and .model_dump() for free serialization back to JSON.

typed_usage.py
from purpleflea.models import ( WalletBalance, TradePosition, CasinoGame, DomainResult, ) # Return type is WalletBalance balance: WalletBalance = client.wallet.balance("eth") # Pydantic model — serialize anytime data = balance.model_dump() # {'chain': 'eth', 'amount': '1.23', 'usd_value': '4100.00', ...} # Full IDE autocompletion on all fields print(balance.chain) # str print(balance.amount) # Decimal print(balance.usd_value) # Decimal print(balance.address) # str
🔑

Python 3.9+ compatibility

All type annotations use from __future__ import annotations for Python 3.9/3.10 compatibility without sacrificing modern syntax.

🔧

mypy and pyright

The SDK ships a py.typed marker file. Both mypy and pyright resolve all types correctly out of the box with no extra configuration.


Built for production.

Async-native

Built on httpx. The async client supports connection pooling, HTTP/2, and concurrent requests out of the box. No thread pool hacks needed.

🔄

Auto-retry with backoff

Transient 5xx errors and rate limits are retried automatically with exponential backoff. Configure max retries and backoff factor on the client constructor.

🛠

Environment variable config

Set PURPLEFLEA_API_KEY and the client reads it automatically. No need to pass the key explicitly in production deployments.

📋

Pydantic v2 models

All responses parse into Pydantic v2 models with field validation, aliases, and model_dump(). No more wrestling with raw dicts.

🔗

LangChain & CrewAI extras

Install purpleflea[langchain] or purpleflea[crewai] for pre-built tool wrappers ready to drop into any agent.

📄

Full test suite

The SDK ships with a mock transport for unit testing. Swap in MockTransport and your agent code is testable without hitting the real API.


More integrations.

Start building in
under five minutes.

Free to start. No KYC. pip install and your agent has a wallet, trading desk, casino, and domain registrar.