OpenAI Agents SDK

Using OpenAI Agents SDK for Crypto: Wallets, Trading & Casino in 2026

Purple Flea Team March 4, 2026 8 min read
← Back to Blog

OpenAI's Agents SDK is the most significant shift in how developers build autonomous AI systems since the Function Calling API shipped in 2023. Unlike the Assistants API — which was designed around stateful threads managed by OpenAI's servers — the Agents SDK puts orchestration logic directly in your code. Unlike Swarm, which was an experimental multi-agent prototype, the Agents SDK is a production-grade framework with first-class support for tool use, handoffs, guardrails, and streaming. For crypto use cases specifically, this architecture unlocks something important: your agent can now hold real economic state across a conversation, route tasks to specialized sub-agents, and execute financial operations with full Python-level control over retry logic and error handling.

OpenAI Agents SDK vs Assistants API vs Swarm

Before building, it helps to understand why the Agents SDK is the right tool for financial agents in 2026. The three options have meaningfully different tradeoffs:

Feature Assistants API Swarm Agents SDK
Orchestration location OpenAI servers Your code Your code
Production-ready Yes Experimental Yes
Multi-agent handoffs Via assistants Native Native + typed
Streaming support Limited No Full streaming
Custom tool decorators No Manual @function_tool
Guardrails system No No Built-in
Crypto agent suitability Moderate Prototype only Recommended

The critical advantage for crypto agents is local orchestration. When your agent executes a trade or a casino bet, you need deterministic error handling — if the HTTP call to the Purple Flea trading API times out, you want to retry with exponential backoff, not silently drop the action. The Assistants API runs tool calls on OpenAI's infrastructure, which limits your ability to intercept and handle failures. The Agents SDK runs everything in your Python process.

Installing the SDK and Purple Flea Client

The Agents SDK requires Python 3.11+ and ships with async-first primitives. Purple Flea provides a first-party Python client with typed responses, which pairs cleanly with the SDK's @function_tool decorator system.

Shell — installation
# Install the OpenAI Agents SDK and Purple Flea Python client
pip install openai-agents purpleflea-python

# Set your API keys (never hardcode these)
export OPENAI_API_KEY="sk-..."
export PURPLEFLEA_API_KEY="pf_live_..."
export AGENT_MNEMONIC="word1 word2 word3 ... word24"

Mnemonic security: In production, load your BIP-39 mnemonic from a secrets manager (AWS Secrets Manager, HashiCorp Vault, or a hardware security module). The mnemonic controls all derived wallet keys across every chain. Purple Flea never transmits or stores it.

Creating @function_tool Wrappers for Purple Flea APIs

The Agents SDK's @function_tool decorator is cleaner than LangChain's BaseTool class because it extracts the JSON schema from your Python type hints automatically. You get typed inputs, automatic docstring extraction for the tool description, and native async support. Here are the three core tools for a crypto agent:

Python — purpleflea_tools.py
import os
import asyncio
from agents import function_tool
from purpleflea import PurpleFleaClient

# Initialize the Purple Flea client once at module level
pf = PurpleFleaClient(
    api_key=os.environ["PURPLEFLEA_API_KEY"],
    mnemonic=os.environ["AGENT_MNEMONIC"],
)


@function_tool
async def get_wallet_balance(chain: str, token: str = "native") -> dict:
    """Get the current balance of the agent's wallet on a given chain.

    Args:
        chain: Blockchain name. One of: ethereum, base, arbitrum, solana, bitcoin, tron
        token: Token symbol (e.g. 'ETH', 'USDC') or 'native' for the chain's native token.
    """
    return await pf.wallet.get_balance(chain=chain, token=token)


@function_tool
async def open_perpetual_position(
    symbol: str,
    side: str,
    size_usd: float,
    leverage: int = 3,
    stop_loss_pct: float = 5.0,
) -> dict:
    """Open a perpetual futures position on Hyperliquid via Purple Flea.

    Args:
        symbol: Trading pair, e.g. 'ETH', 'BTC', 'SOL'. Do not include '-PERP' suffix.
        side: Either 'long' (bet price goes up) or 'short' (bet price goes down).
        size_usd: Position size in USD. Max 500 per call for safety.
        leverage: Leverage multiplier, 1-50. Default 3x. Higher = more risk.
        stop_loss_pct: Auto-close if position loses this percent. Default 5%.
    """
    if size_usd > 500:
        raise ValueError("Position size exceeds per-trade limit of $500")
    return await pf.trading.open_position(
        symbol=symbol, side=side,
        size_usd=size_usd, leverage=leverage,
        stop_loss_pct=stop_loss_pct,
    )


@function_tool
async def close_position(symbol: str) -> dict:
    """Close an open perpetual futures position.

    Args:
        symbol: The symbol of the position to close, e.g. 'ETH', 'BTC'.
    """
    return await pf.trading.close_position(symbol=symbol)


@function_tool
async def get_open_positions() -> list:
    """Return all currently open perpetual futures positions with PnL."""
    return await pf.trading.get_positions()


@function_tool
async def play_casino_coinflip(side: str, amount_usd: float) -> dict:
    """Play a provably fair coin flip. House edge is 1.5% (pays 1.97x on win).

    Args:
        side: Prediction - either 'heads' or 'tails'.
        amount_usd: Bet size in USD. Maximum $25 per flip. Use Kelly Criterion.
    """
    if amount_usd > 25:
        raise ValueError("Bet exceeds per-game limit of $25")
    return await pf.casino.coinflip(side=side, amount_usd=amount_usd)


@function_tool
async def get_referral_earnings() -> dict:
    """Check accumulated referral commissions and get the agent's referral link."""
    return await pf.referral.get_summary()

Building a ReAct-Style Crypto Agent

The Agents SDK implements a ReAct (Reason + Act) loop natively. Your agent reasons about its state, selects a tool, observes the result, and reasons again — looping until it produces a final answer or hits the iteration limit. For a crypto agent, this loop is ideal: the agent checks balances, considers market conditions, decides whether to trade, executes, and reports.

Python — crypto_agent.py
from agents import Agent, Runner, ModelSettings
from purpleflea_tools import (
    get_wallet_balance,
    open_perpetual_position,
    close_position,
    get_open_positions,
    play_casino_coinflip,
    get_referral_earnings,
)

SYSTEM_PROMPT = """You are an autonomous crypto financial agent running on Purple Flea infrastructure.

Your responsibilities:
1. Monitor wallet balances across chains and report portfolio value
2. Open and manage perpetual futures positions based on market conditions
3. Play casino games only when you have idle capital and use Kelly Criterion sizing
4. Report referral earnings and promote your referral link when relevant

Risk rules you must never violate:
- Never risk more than 5% of total portfolio in a single trade
- Always set a stop-loss when opening positions
- For casino bets, never bet more than 2% of bankroll per flip
- If total drawdown exceeds 15%, stop trading and report to operator

Always reason step-by-step before executing any financial action.
"""

crypto_agent = Agent(
    name="CryptoAgent",
    instructions=SYSTEM_PROMPT,
    tools=[
        get_wallet_balance,
        open_perpetual_position,
        close_position,
        get_open_positions,
        play_casino_coinflip,
        get_referral_earnings,
    ],
    model="gpt-4o",
    model_settings=ModelSettings(temperature=0.1),  # low temp for financial decisions
)


async def main():
    result = await Runner.run(
        crypto_agent,
        input="Run your daily financial check. Report balances, "
              "check open positions, and identify any actions needed.",
    )
    print(result.final_output)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Multi-Agent Handoff: Orchestrator Routes to Specialists

The most powerful pattern in the Agents SDK is agent handoffs. Rather than overloading a single agent with all tools, you build specialized sub-agents and an orchestrator that routes tasks to the right specialist. For crypto, this means a trading agent that knows perpetual markets deeply, a casino agent that applies probabilistic reasoning, and a portfolio agent that aggregates the full picture.

Python — multi_agent_crypto.py
from agents import Agent, Runner, handoff
from purpleflea_tools import open_perpetual_position, close_position, get_open_positions
from purpleflea_tools import play_casino_coinflip, get_referral_earnings
from purpleflea_tools import get_wallet_balance

# Specialist: focused only on derivatives trading
trading_agent = Agent(
    name="TradingAgent",
    instructions="""You are a derivatives trading specialist.
You manage perpetual futures positions on Hyperliquid via Purple Flea.
Always check open positions before opening new ones.
Never exceed 3 concurrent positions. Use 3-5x leverage max.
Apply trend-following logic: go with momentum, not against it.""",
    tools=[open_perpetual_position, close_position, get_open_positions, get_wallet_balance],
    model="gpt-4o",
)

# Specialist: focused only on casino and referrals
casino_agent = Agent(
    name="CasinoAgent",
    instructions="""You are a casino and referral income specialist.
For coin flip: bankroll * 0.02 * edge / variance = Kelly bet size.
Edge on coin flip is -0.015 (house takes 1.5%). Use quarter-Kelly: multiply by 0.25.
Maximum 10 flips per session. Stop if you lose 3 in a row.
Always check and report referral earnings — this is often more profitable than direct play.""",
    tools=[play_casino_coinflip, get_referral_earnings, get_wallet_balance],
    model="gpt-4o",
)

# Orchestrator: decides which specialist handles each task
orchestrator = Agent(
    name="Orchestrator",
    instructions="""You coordinate a team of financial specialist agents.
- For any task involving perpetual futures, positions, leverage, or trading: hand off to TradingAgent.
- For any task involving casino games, coin flips, or referral commissions: hand off to CasinoAgent.
- For portfolio overview or balance checks: use get_wallet_balance directly.
- Always summarize the results from sub-agents in your final response.""",
    tools=[
        get_wallet_balance,
        handoff(trading_agent),
        handoff(casino_agent),
    ],
    model="gpt-4o",
)


async def run_daily_operations():
    result = await Runner.run(
        orchestrator,
        input="Run full daily operations: check portfolio, assess trading opportunities on ETH and BTC, "
              "check referral earnings, and run a small casino session if we have idle USDC.",
    )
    return result.final_output

import asyncio
print(asyncio.run(run_daily_operations()))

Streaming for Long-Running Trades

Some Purple Flea operations — especially multi-hop bridge transactions or large market orders — can take 15–30 seconds to finalize. The Agents SDK's streaming interface lets you surface intermediate status to users or monitoring systems without blocking:

Python — streaming_agent.py
from agents import Runner

async def stream_trade_execution(agent, task: str):
    """Stream agent output token by token for real-time monitoring."""
    async with Runner.run_streamed(agent, input=task) as stream:
        async for event in stream.stream_events():
            if event.type == "agent_updated_stream_event":
                # Agent switched (handoff occurred)
                print(f"\n[Handoff to: {event.new_agent.name}]")
            elif event.type == "raw_response_event":
                # Stream tokens as they arrive
                if hasattr(event.data, "delta") and event.data.delta:
                    print(event.data.delta, end="", flush=True)

    return stream.final_output

Error Handling: Wrap Every Tool Call

Financial tool failures are not optional to handle. A timeout on a position-open call could mean the order went through on Purple Flea's side but the acknowledgement was lost — leading to a phantom position. The right pattern is to wrap tool functions with retry logic and always verify state after a failure:

Python — resilient_tool.py
import asyncio
from agents import function_tool
from purpleflea import PurpleFleaClient, PurpleFleaTimeoutError, PurpleFleaRateLimitError

pf = PurpleFleaClient(api_key=..., mnemonic=...)

@function_tool
async def safe_open_position(symbol: str, side: str, size_usd: float) -> dict:
    """Open a position with automatic retry on transient errors.
    Returns the position details or an error dict with reason and recovery action."""
    max_retries = 3
    for attempt in range(max_retries):
        try:
            result = await pf.trading.open_position(
                symbol=symbol, side=side, size_usd=size_usd
            )
            return result
        except PurpleFleaTimeoutError:
            # Check if order was placed despite timeout
            positions = await pf.trading.get_positions()
            for pos in positions:
                if pos["symbol"] == symbol:
                    return {"status": "recovered", "position": pos}
            if attempt < max_retries - 1:
                await asyncio.sleep(2 ** attempt)
        except PurpleFleaRateLimitError as e:
            return {"error": "rate_limit", "retry_after_seconds": e.retry_after}
    return {"error": "failed_after_retries", "action": "check positions manually"}

Production tip: Never retry a trade open more than 3 times without checking current positions first. The Purple Flea API is idempotent for exact-duplicate orders within a 30-second window, but a retry after that window could result in a doubled position.

The OpenAI Agents SDK represents a genuine step forward for production crypto agents: clean decorator-based tool definitions, native multi-agent handoffs, full streaming support, and an architecture that keeps your error handling in your code rather than in someone else's infrastructure. Combined with Purple Flea's unified API surface covering wallets, perpetual trading, and provably fair casino games, you have everything needed to build an economically capable autonomous agent in an afternoon.

Start Building Your Crypto Agent Today

Get your Purple Flea API key, install the Agents SDK, and deploy your first financial agent in under an hour.

Explore More