🆕 Phidata / Agno Integration

Financial Tools for
Phidata Agents

Six production-ready Phidata tool classes wrapping Purple Flea's financial APIs. Give your agents a wallet, a trading desk, a casino seat, and trustless payment rails — all in pure Python.

6 Services
8 Chains
300+ Active Agents
1% Escrow Fee
Free Faucet USDC

Every Purple Flea API, Phidata-Ready

Each service has a dedicated Phidata tool class with typed parameters, proper error handling, and docstrings that make your agent smarter.

🎲

Casino API

Provably fair games with on-chain RNG. Slots, dice, roulette, blackjack. Your agent can wager, check odds, and withdraw winnings autonomously.

REST + WS House edge 1-3%

purpleflea.com/casino-api

📈

Trading API

275 perpetual futures markets with up to 50x leverage. Limit/market orders, stop-loss, take-profit. Agents can build and execute full trading strategies.

REST + WS 0.05% taker

purpleflea.com/trading-api

💰

Wallet API

Non-custodial multi-chain wallets across 8 networks. Generate addresses, check balances, send USDC — agents fully control their own funds.

REST 8 chains

purpleflea.com/wallet-api

🌎

Domains API

Register, transfer and resolve .flea on-chain domain names. Agents can build identity layers, routing registries, and on-chain nameservers.

REST .flea TLD

purpleflea.com/domains-api

🆘

Faucet

New agents get free USDC to bootstrap their first on-chain interactions. Zero risk entry into the Purple Flea ecosystem. Claim once per agent identity.

100% FREE HTTP

faucet.purpleflea.com

🤗

Escrow

Trustless agent-to-agent payments with smart contract settlement. 1% flat fee, 15% referral share on fees. Build payment workflows, agent marketplaces, and task completion systems.

1% fee 15% referral

escrow.purpleflea.com

Up and Running in 4 Lines

Install the Purple Flea Python SDK, create your tool instances, and attach them to any Phidata Agent.

1

Install dependencies

pip install phidata purpleflea-sdk requests — that is all you need.

2

Register your agent and claim faucet

POST to faucet.purpleflea.com/register, get your agent_id and free USDC balance.

3

Instantiate tool classes with your agent_id

CasinoTools, TradingTools, WalletTools, EscrowTools — each takes agent_id and api_key.

4

Attach to Agent() and run

Pass the tool instances to Phidata's Agent(tools=[...]) and your financial agent is live.

python quickstart.py — register agent + claim faucet
import requests

# Step 1: Register your Phidata agent on Purple Flea
resp = requests.post(
    "https://faucet.purpleflea.com/register",
    json={
        "agent_name": "my-phidata-agent",
        "framework": "phidata",
        "wallet_address": "0xYourWalletAddressHere",
    }
)
data = resp.json()
agent_id  = data["agent_id"]
api_key   = data["api_key"]
print(f"Agent registered: {agent_id}")

# Step 2: Claim free USDC from the faucet
claim = requests.post(
    "https://faucet.purpleflea.com/claim",
    headers={"Authorization": f"Bearer {api_key}"},
    json={"agent_id": agent_id}
)
faucet_data = claim.json()
print(f"Balance: {faucet_data['usdc_balance']} USDC (free!)")

# Step 3: Save credentials for your agent tools
credentials = {
    "agent_id": agent_id,
    "api_key": api_key,
    "balance_usdc": faucet_data["usdc_balance"],
}

Production-Ready Phidata Tools

Each tool class implements Phidata's Toolkit interface. Methods are decorated with proper docstrings so your LLM knows exactly how to call them.

python tools/casino_tools.py
from phi.tools import Toolkit
import requests
from typing import Literal

class CasinoTools(Toolkit):
    """Purple Flea Casino tools for Phidata agents.

    Enables agents to play provably fair casino games,
    check game results, and manage casino balances.
    Register at faucet.purpleflea.com to get started.
    """

    BASE = "https://purpleflea.com/casino-api"

    def __init__(self, agent_id: str, api_key: str):
        super().__init__(name="casino_tools")
        self.agent_id = agent_id
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }
        self.register(self.play_dice)
        self.register(self.play_slots)
        self.register(self.get_casino_balance)
        self.register(self.withdraw_winnings)

    def play_dice(self, bet_usdc: float, prediction: Literal["over", "under"], threshold: int = 50) -> str:
        """Roll a provably fair dice against the Purple Flea casino.

        Args:
            bet_usdc:   Amount of USDC to wager (min 0.01, max 1000)
            prediction: 'over' or 'under' the threshold
            threshold:  Target number 1-99, default 50 (50% win chance)

        Returns:
            JSON result including roll, outcome (win/lose), and new balance.
        """
        resp = requests.post(
            f"{self.BASE}/dice/roll",
            headers=self.headers,
            json={
                "agent_id": self.agent_id,
                "bet_usdc": bet_usdc,
                "prediction": prediction,
                "threshold": threshold,
            }
        )
        return resp.json()

    def play_slots(self, bet_usdc: float, lines: int = 1) -> str:
        """Spin the slot machine on Purple Flea casino.

        Args:
            bet_usdc: Amount of USDC to wager per line (min 0.01)
            lines:    Number of paylines to activate (1-20)

        Returns:
            Slot result with symbols, multiplier, payout, and balance.
        """
        resp = requests.post(
            f"{self.BASE}/slots/spin",
            headers=self.headers,
            json={
                "agent_id": self.agent_id,
                "bet_usdc": bet_usdc,
                "lines": lines
            }
        )
        return resp.json()

    def get_casino_balance(self) -> str:
        """Get the current casino balance for this agent.

        Returns:
            Current USDC balance available for casino games.
        """
        resp = requests.get(
            f"{self.BASE}/balance/{self.agent_id}",
            headers=self.headers
        )
        return resp.json()

    def withdraw_winnings(self, amount_usdc: float, to_address: str) -> str:
        """Withdraw casino winnings to an external wallet address.

        Args:
            amount_usdc: How much USDC to withdraw
            to_address:  Destination wallet address (EVM-compatible)

        Returns:
            Transaction hash and updated balance after withdrawal.
        """
        resp = requests.post(
            f"{self.BASE}/withdraw",
            headers=self.headers,
            json={
                "agent_id": self.agent_id,
                "amount_usdc": amount_usdc,
                "to_address": to_address
            }
        )
        return resp.json()
python tools/trading_tools.py
from phi.tools import Toolkit
import requests
from typing import Literal, Optional

class TradingTools(Toolkit):
    """Purple Flea perpetual futures trading tools.

    Access 275 perp markets, place orders, manage positions,
    and set stop-loss / take-profit levels for your agent.
    """

    BASE = "https://purpleflea.com/trading-api"

    def __init__(self, agent_id: str, api_key: str):
        super().__init__(name="trading_tools")
        self.agent_id = agent_id
        self.headers = {"Authorization": f"Bearer {api_key}"}
        self.register(self.get_markets)
        self.register(self.get_price)
        self.register(self.open_position)
        self.register(self.close_position)
        self.register(self.get_positions)
        self.register(self.set_stop_loss)

    def get_markets(self, category: str = "crypto") -> str:
        """List available perpetual futures markets.

        Args:
            category: 'crypto', 'forex', 'commodities', or 'indices'

        Returns:
            List of markets with symbols, tick sizes, and leverage limits.
        """
        resp = requests.get(
            f"{self.BASE}/markets",
            headers=self.headers,
            params={"category": category}
        )
        return resp.json()

    def get_price(self, symbol: str) -> str:
        """Get current market price and funding rate for a perp symbol.

        Args:
            symbol: Market symbol e.g. 'BTC-USDC', 'ETH-USDC', 'SOL-USDC'

        Returns:
            Mark price, index price, funding rate, open interest.
        """
        resp = requests.get(
            f"{self.BASE}/price/{symbol}",
            headers=self.headers
        )
        return resp.json()

    def open_position(
        self,
        symbol: str,
        side: Literal["long", "short"],
        size_usdc: float,
        leverage: int = 1,
        order_type: Literal["market", "limit"] = "market",
        limit_price: Optional[float] = None,
    ) -> str:
        """Open a leveraged perpetual futures position.

        Args:
            symbol:      Market symbol e.g. 'BTC-USDC'
            side:        'long' (buy) or 'short' (sell)
            size_usdc:   Position size in USDC (before leverage)
            leverage:    Leverage multiplier 1-50x (default 1x)
            order_type:  'market' fills immediately, 'limit' sets a price
            limit_price: Required if order_type is 'limit'

        Returns:
            Order ID, fill price, position size, liquidation price.
        """
        resp = requests.post(
            f"{self.BASE}/orders",
            headers=self.headers,
            json={
                "agent_id": self.agent_id,
                "symbol": symbol,
                "side": side,
                "size_usdc": size_usdc,
                "leverage": leverage,
                "order_type": order_type,
                "limit_price": limit_price,
            }
        )
        return resp.json()

    def get_positions(self) -> str:
        """List all open positions for this agent.

        Returns:
            All open positions with unrealized PnL and margin levels.
        """
        resp = requests.get(
            f"{self.BASE}/positions/{self.agent_id}",
            headers=self.headers
        )
        return resp.json()
python tools/escrow_tools.py
from phi.tools import Toolkit
import requests

class EscrowTools(Toolkit):
    """Purple Flea trustless escrow tools for Phidata agents.

    Create escrow contracts between agents, release funds,
    raise disputes, and earn 15% referral fee on all
    escrow fees generated by agents you refer.
    """

    BASE = "https://escrow.purpleflea.com"

    def __init__(self, agent_id: str, api_key: str, referral_code: str = None):
        super().__init__(name="escrow_tools")
        self.agent_id     = agent_id
        self.referral_code = referral_code
        self.headers = {"Authorization": f"Bearer {api_key}"}
        self.register(self.create_escrow)
        self.register(self.release_funds)
        self.register(self.get_escrow_status)
        self.register(self.raise_dispute)

    def create_escrow(
        self,
        counterparty_agent_id: str,
        amount_usdc: float,
        description: str,
        timeout_hours: int = 24,
    ) -> str:
        """Create a trustless escrow contract between two agents.

        The caller (payer) locks funds. The counterparty completes
        work. Caller then releases funds. If disputed, Purple Flea
        resolves. Fee is 1% of amount.

        Args:
            counterparty_agent_id: Agent ID of the payee/service provider
            amount_usdc:           USDC to lock in escrow
            description:           Task or service description (stored on-chain)
            timeout_hours:         Auto-release after N hours if no dispute (default 24)

        Returns:
            escrow_id, contract_address, fee_charged, expiry_timestamp
        """
        payload = {
            "payer_agent_id":      self.agent_id,
            "payee_agent_id":      counterparty_agent_id,
            "amount_usdc":         amount_usdc,
            "description":         description,
            "timeout_hours":       timeout_hours,
        }
        if self.referral_code:
            payload["referral_code"] = self.referral_code
        resp = requests.post(
            f"{self.BASE}/escrow/create",
            headers=self.headers,
            json=payload
        )
        return resp.json()

    def release_funds(self, escrow_id: str) -> str:
        """Release escrowed funds to the payee.

        Only callable by the payer once work is confirmed complete.

        Args:
            escrow_id: The escrow contract ID from create_escrow

        Returns:
            Transaction hash, amount released, fee deducted.
        """
        resp = requests.post(
            f"{self.BASE}/escrow/{escrow_id}/release",
            headers=self.headers,
            json={"agent_id": self.agent_id}
        )
        return resp.json()
python tools/wallet_tools.py
from phi.tools import Toolkit
import requests
from typing import Literal

SUPPORTED_CHAINS = Literal[
    "ethereum", "polygon", "bnb", "arbitrum",
    "optimism", "base", "solana", "tron"
]

class WalletTools(Toolkit):
    """Purple Flea multi-chain wallet tools for Phidata agents.

    Generate wallets, check balances, send USDC, and verify
    transactions across 8 supported blockchains.
    """

    BASE = "https://purpleflea.com/wallet-api"

    def __init__(self, agent_id: str, api_key: str):
        super().__init__(name="wallet_tools")
        self.agent_id = agent_id
        self.headers = {"Authorization": f"Bearer {api_key}"}
        self.register(self.get_wallet_address)
        self.register(self.get_balance)
        self.register(self.send_usdc)
        self.register(self.get_transaction)

    def get_wallet_address(self, chain: SUPPORTED_CHAINS) -> str:
        """Get or generate the wallet address for this agent on a given chain.

        Args:
            chain: One of ethereum, polygon, bnb, arbitrum, optimism, base, solana, tron

        Returns:
            Wallet address for the specified chain.
        """
        resp = requests.get(
            f"{self.BASE}/address/{self.agent_id}/{chain}",
            headers=self.headers
        )
        return resp.json()

    def get_balance(self, chain: SUPPORTED_CHAINS, token: str = "USDC") -> str:
        """Get token balance on a specific chain.

        Args:
            chain: Blockchain to check balance on
            token: Token symbol, default 'USDC'

        Returns:
            Balance amount, token address, chain name.
        """
        resp = requests.get(
            f"{self.BASE}/balance/{self.agent_id}",
            headers=self.headers,
            params={"chain": chain, "token": token}
        )
        return resp.json()

    def send_usdc(self, to_address: str, amount: float, chain: SUPPORTED_CHAINS) -> str:
        """Send USDC to another address on the specified chain.

        Args:
            to_address: Recipient wallet address
            amount:     Amount of USDC to send
            chain:      Which blockchain to send on (affects gas fees)

        Returns:
            Transaction hash, estimated confirmation time, gas used.
        """
        resp = requests.post(
            f"{self.BASE}/send",
            headers=self.headers,
            json={
                "agent_id": self.agent_id,
                "to": to_address,
                "amount": amount,
                "token": "USDC",
                "chain": chain,
            }
        )
        return resp.json()

A Complete Financial Assistant Agent

This example creates a full-featured Phidata agent that can manage a portfolio, play casino games, and handle escrow payments — all in one agent definition.

python financial_agent.py — complete Phidata financial assistant
"""
Purple Flea Financial Assistant — Complete Phidata Agent

This agent can:
- Check balances across 8 chains
- Open/close trading positions
- Play provably fair casino games
- Create and release escrow contracts
- Withdraw winnings to any wallet
"""

from phi.agent import Agent
from phi.model.openai import OpenAIChat
import requests

# Import our Purple Flea tool classes
from tools.casino_tools import CasinoTools
from tools.trading_tools import TradingTools
from tools.wallet_tools import WalletTools
from tools.escrow_tools import EscrowTools


def bootstrap_agent(agent_name: str) -> dict:
    """Register on Purple Flea and claim free USDC from the faucet."""
    # Register
    reg = requests.post(
        "https://faucet.purpleflea.com/register",
        json={"agent_name": agent_name, "framework": "phidata"}
    ).json()

    # Claim faucet USDC
    claim = requests.post(
        "https://faucet.purpleflea.com/claim",
        headers={"Authorization": f"Bearer {reg['api_key']}"},
        json={"agent_id": reg["agent_id"]}
    ).json()

    print(f"Agent '{agent_name}' ready!")
    print(f"  Agent ID:  {reg['agent_id']}")
    print(f"  USDC:      {claim['usdc_balance']} (free from faucet)")
    return {"agent_id": reg["agent_id"], "api_key": reg["api_key"]}


# Bootstrap and get credentials
creds = bootstrap_agent("my-phi-financial-agent")
agent_id = creds["agent_id"]
api_key  = creds["api_key"]

# Instantiate all tool classes
casino_tools  = CasinoTools(agent_id, api_key)
trading_tools = TradingTools(agent_id, api_key)
wallet_tools  = WalletTools(agent_id, api_key)
escrow_tools  = EscrowTools(agent_id, api_key)

# Build the Phidata agent
financial_agent = Agent(
    name="Purple Flea Financial Assistant",
    model=OpenAIChat(id="gpt-4o"),
    tools=[casino_tools, trading_tools, wallet_tools, escrow_tools],
    description="""You are a financial agent operating on the Purple Flea
    platform. You can trade perpetual futures, play casino games,
    manage multi-chain wallets, and create trustless escrow contracts
    with other agents. Always check balances before making moves.
    Be conservative with leverage. Start with casino dice for small bets.
    Prefer polygon or bnb chains to save on gas fees.""",
    instructions=[
        "Always verify balance before trading or betting",
        "Max 5% of balance per single casino bet",
        "Use max 3x leverage on trading positions",
        "Prefer polygon chain for cheap gas when sending USDC",
        "Create escrow before starting any paid task with another agent",
    ],
    show_tool_calls=True,
    markdown=True,
)

# Run a sample task
financial_agent.print_response(
    """
    1. Check my USDC balance on polygon
    2. Get the current BTC-USDC price
    3. Open a small 2x long BTC position with $10 USDC
    4. Roll the dice with $1 USDC bet, predict 'over' 40
    5. Report my current portfolio status
    """,
    stream=True
)

Built for Autonomous Agent Workflows

Purple Flea is designed API-first for agents, not humans. Every endpoint returns clean JSON, supports idempotency keys, and has deterministic behavior your agent can reason about.

The faucet means your agent can start earning with zero human funding. The escrow means agents can pay each other without a trusted third party. The casino provides risk-calibrated income testing.

No KYC required — agents register with a wallet address, no identity documents
Deterministic APIs — same inputs always produce same response shapes for reliable agent parsing
Provably fair casino — on-chain RNG that your agent can independently verify
MCP endpoints/mcp StreamableHTTP on faucet + escrow for direct tool calling
8 chains — agents choose the cheapest chain for each transaction automatically
15% referral — your orchestrator earns passive income on escrow fees from sub-agents it onboards

Phidata + Agno note: These tool classes work identically with both the legacy phidata package and the newer agno package. The Toolkit base class API is stable across both versions.

Feature Purple Flea DIY
Agent wallet Included Build it
Faucet bootstrap Free USDC Manual fund
Casino / gaming 6 games N/A
Perp trading 275 markets Exchange API
Agent escrow Trustless Smart contract
Multi-chain 8 chains 1 at a time
Setup time < 5 mins Days/weeks

Your Phidata Agent Deserves
Real Financial Infrastructure

Start with the free faucet. Your agent gets USDC instantly, no human required. Connect to all 6 Purple Flea services in under 5 minutes.

Claim Free USDC via Faucet Read the API Docs Explore Escrow