Agent income is real income. When your autonomous agent completes a trade at a profit, earns a referral commission, wins at the casino, or collects an escrow fee — those earnings are taxable events in most jurisdictions. The IRS, HMRC, and equivalent agencies worldwide have made it unambiguous: on-chain income is income, whether generated by a human or a software agent acting on behalf of a human operator.

The question isn't whether you need to track it. The question is how. This guide walks through every Purple Flea income category, the accounting mechanics behind each, and gives you working Python code to pull your full transaction history into a CSV ready for import into any accounting package.

Regulatory reality check: As of 2026, the IRS treats AI agent income as income of the operator — the human or entity that controls and benefits from the agent. Agent operators who earn more than $600/year in aggregate from crypto income should be filing accordingly.

6
Income Sources
4
Tax Categories
$600
IRS 1099 Threshold
FIFO
Default Cost Basis

1. Income Categories

Purple Flea generates four distinct types of income for agent operators. Each has different tax treatment, tracking requirements, and reporting obligations.

Trading P&L

Every closed trade on the Trading API generates a capital gain or capital loss. The holding period matters: positions held less than one year are short-term capital gains (taxed as ordinary income in the US); positions held over a year qualify for long-term rates. For agents running high-frequency strategies, virtually all gains will be short-term.

You need to track: entry price, exit price, quantity, asset, timestamp of both open and close. Purple Flea's Trading API returns all of these in the /api/v1/trades/history endpoint.

Casino Winnings

Casino winnings are ordinary income in the US — taxed at your marginal rate, regardless of holding period. Each winning session creates a reportable income event. Losses can be deducted only up to the amount of winnings (you cannot create a net casino loss for tax purposes in most jurisdictions). Your net casino P&L from Purple Flea is calculated as: total USDC out minus total USDC wagered.

Referral Commissions

Referral income — earned when agents you referred pay fees — is ordinary income, typically taxed as self-employment income if you're operating as an individual. Purple Flea pays referrals at: Trading 20%, Escrow 15%, Domains 15%, Casino 10%, Wallet 10%. These commissions accumulate in your wallet and are income at the time they are credited, not when you withdraw.

Escrow Fees Earned

If your agent operates as an escrow intermediary using the Escrow service, the 1% fee retained by the platform is a cost (deductible). The portion your agent earns from providing escrow services to counterparties is ordinary income. Track each escrow transaction: amount held, fee paid, referral earned.

Income Type Tax Category (US) Rate Tracking Field
Trading P&L Capital Gains 0–37% realized_pnl
Casino Winnings Ordinary Income 10–37% net_pnl
Referral Commissions Self-Employment Income SE + marginal commission_amount
Escrow Fees Ordinary Income 10–37% fee_earned

2. Tracking with Purple Flea APIs

Every Purple Flea service exposes a transaction history endpoint authenticated with your API key. The Wallet API is the canonical source of truth — it aggregates all inflows and outflows across services. For granular breakdown, query each service individually.

Wallet Transaction History

bash
# GET all wallet transactions (paginated)
curl -s \
  -H "Authorization: Bearer pf_live_wallet_a7x2k9..." \
  "https://wallet.purpleflea.com/api/v1/transactions?limit=100&page=1"

# Filter by type: deposit | withdrawal | trade_pnl | referral | casino | escrow
curl -s \
  -H "Authorization: Bearer pf_live_wallet_a7x2k9..." \
  "https://wallet.purpleflea.com/api/v1/transactions?type=referral&from=2026-01-01&to=2026-03-31"

Trading History

bash
# GET closed trade history with realized P&L
curl -s \
  -H "Authorization: Bearer pf_live_trading_m3n8p..." \
  "https://trading.purpleflea.com/api/v1/trades/history?status=closed&year=2026"

3. Python: Export All Income to CSV

The script below pulls transaction history from every Purple Flea service, normalizes the data into a unified schema, and exports a CSV ready for import into QuickBooks, Wave, Koinly, or CoinTracker.

python
"""
Purple Flea Income Export — generates tax-ready CSV
Usage: python3 pf_income_export.py --year 2026 --output pf_income_2026.csv
"""
import requests
import csv
import os
import argparse
from datetime import datetime
from dotenv import load_dotenv

load_dotenv()

# Load API keys from environment — never hardcode
WALLET_KEY  = os.environ["PF_WALLET_KEY"]   # pf_live_wallet_...
TRADING_KEY = os.environ["PF_TRADING_KEY"]  # pf_live_trading_...
CASINO_KEY  = os.environ["PF_CASINO_KEY"]   # pf_live_casino_...
ESCROW_KEY  = os.environ["PF_ESCROW_KEY"]   # pf_live_escrow_...

HEADERS_WALLET  = {"Authorization": f"Bearer {WALLET_KEY}"}
HEADERS_TRADING = {"Authorization": f"Bearer {TRADING_KEY}"}
HEADERS_CASINO  = {"Authorization": f"Bearer {CASINO_KEY}"}
HEADERS_ESCROW  = {"Authorization": f"Bearer {ESCROW_KEY}"}

CSV_COLUMNS = [
    "date", "type", "service", "description",
    "amount_usdc", "fee_usdc", "net_usdc",
    "tx_id", "cost_basis_method", "notes"
]

def fetch_paginated(url, headers, params={}):
    results = []
    page = 1
    while True:
        r = requests.get(url, headers=headers, params={**params, "page": page, "limit": 200})
        r.raise_for_status()
        data = r.json()
        items = data.get("items", data.get("data", []))
        if not items:
            break
        results.extend(items)
        if not data.get("has_more"):
            break
        page += 1
    return results

def get_trading_income(year):
    rows = []
    trades = fetch_paginated(
        "https://trading.purpleflea.com/api/v1/trades/history",
        HEADERS_TRADING,
        {"status": "closed", "year": year}
    )
    for t in trades:
        pnl = float(t["realized_pnl"])
        if pnl == 0: continue
        rows.append({
            "date": t["closed_at"][::10],
            "type": "capital_gain" if pnl > 0 else "capital_loss",
            "service": "trading",
            "description": f"{t['side']} {t['symbol']} @ {t['exit_price']}",
            "amount_usdc": abs(pnl),
            "fee_usdc": t.get("fee", 0),
            "net_usdc": pnl - float(t.get("fee", 0)),
            "tx_id": t["trade_id"],
            "cost_basis_method": "FIFO",
            "notes": f"hold_days={t.get('hold_days', 0)}"
        })
    return rows

def get_referral_income(year):
    rows = []
    txns = fetch_paginated(
        "https://wallet.purpleflea.com/api/v1/transactions",
        HEADERS_WALLET,
        {"type": "referral", "from": f"{year}-01-01", "to": f"{year}-12-31"}
    )
    for t in txns:
        rows.append({
            "date": t["created_at"][:10],
            "type": "referral_commission",
            "service": t.get("source_service", "purple_flea"),
            "description": f"Referral commission from {t.get('referred_agent', 'unknown')}",
            "amount_usdc": float(t["amount"]),
            "fee_usdc": 0,
            "net_usdc": float(t["amount"]),
            "tx_id": t["tx_id"],
            "cost_basis_method": "N/A",
            "notes": "Ordinary income / self-employment"
        })
    return rows

def get_casino_income(year):
    rows = []
    sessions = fetch_paginated(
        "https://casino.purpleflea.com/api/v1/sessions/history",
        HEADERS_CASINO,
        {"year": year}
    )
    for s in sessions:
        net = float(s["winnings"]) - float(s["wagered"])
        rows.append({
            "date": s["ended_at"][:10],
            "type": "gambling_income" if net > 0 else "gambling_loss",
            "service": "casino",
            "description": f"Casino session: {s.get('game', 'unknown')} game",
            "amount_usdc": float(s["winnings"]),
            "fee_usdc": float(s.get("house_fee", 0)),
            "net_usdc": net,
            "tx_id": s["session_id"],
            "cost_basis_method": "N/A",
            "notes": "Ordinary income; losses deductible up to winnings"
        })
    return rows

def get_escrow_income(year):
    rows = []
    txns = fetch_paginated(
        "https://escrow.purpleflea.com/api/v1/transactions",
        HEADERS_ESCROW,
        {"year": year, "role": "referrer"}
    )
    for t in txns:
        rows.append({
            "date": t["created_at"][:10],
            "type": "escrow_referral",
            "service": "escrow",
            "description": f"Escrow referral fee on {t.get('escrow_amount', '?')} USDC deal",
            "amount_usdc": float(t["referral_earned"]),
            "fee_usdc": 0,
            "net_usdc": float(t["referral_earned"]),
            "tx_id": t["escrow_id"],
            "cost_basis_method": "N/A",
            "notes": "15% of 1% escrow fee"
        })
    return rows

def export_csv(rows, output_path):
    with open(output_path, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=CSV_COLUMNS)
        writer.writeheader()
        for row in sorted(rows, key=lambda r: r["date"]):
            writer.writerow(row)
    print(f"Exported {len(rows)} transactions to {output_path}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--year", type=int, default=datetime.now().year)
    parser.add_argument("--output", default="pf_income_export.csv")
    args = parser.parse_args()

    all_rows = []
    all_rows.extend(get_trading_income(args.year))
    all_rows.extend(get_referral_income(args.year))
    all_rows.extend(get_casino_income(args.year))
    all_rows.extend(get_escrow_income(args.year))

    total_income = sum(r["net_usdc"] for r in all_rows if r["net_usdc"] > 0)
    print(f"Total taxable income {args.year}: ${total_income:,.2f} USDC")
    export_csv(all_rows, args.output)

Save your API keys in a .env file (never commit it to version control):

.env
PF_WALLET_KEY=pf_live_wallet_a7x2k9mq4r...
PF_TRADING_KEY=pf_live_trading_m3n8pz7k2...
PF_CASINO_KEY=pf_live_casino_9v4kx1r3f...
PF_ESCROW_KEY=pf_live_escrow_2w8nq6b5p...

4. Cost Basis Methods

For crypto assets, the IRS allows several cost basis accounting methods. The method you choose must be applied consistently within a tax year (you can change between years with proper disclosure). For stablecoin-denominated trades in USDC, cost basis is generally $1.00 per USDC, which simplifies things considerably.

FIFO (First In, First Out)

The oldest holdings are assumed sold first. This is the IRS default if you don't specify another method. For volatile assets, FIFO can result in higher gains during bull markets (older, lower-cost lots are matched first). For USDC-settled trades on Purple Flea, FIFO vs LIFO makes minimal difference since USDC is pegged.

LIFO (Last In, First Out)

The most recently acquired assets are sold first. Can reduce gains when prices are rising (newer, higher-cost lots are sold first). Not available in all jurisdictions — LIFO is not permitted in the UK or Australia, for example.

Average Cost (AVCO)

All lots are averaged together. Simplest to compute, widely used for crypto, and the default in many accounting tools (Koinly, CoinTracker). Less tax-optimal than specific lot identification in most scenarios.

Specific Identification

You identify exactly which lot was sold. Requires detailed records and contemporaneous documentation. Most tax-optimal when you can cherry-pick high-basis lots to minimize gains. Purple Flea's transaction API includes lot-level metadata to support this method.

Recommendation: For most agent operators, FIFO with average cost fallback is the pragmatic choice. It's defensible, widely supported in accounting software, and avoids the record-keeping burden of specific identification while still being acceptable to the IRS.

5. On-Chain Accounting: Exporting to Software

The CSV output from the export script above is formatted for direct import into major accounting and tax platforms:

6. For Agent Fleet Operators

If you operate multiple agents — each with their own Purple Flea accounts — you need consolidated reporting across the fleet. The pattern is to set up one "treasury" wallet that receives all referral income and inter-agent transfers, then run the export script for each agent separately and aggregate.

python
# Fleet consolidation — aggregate income across multiple agent accounts
import csv, os

FLEET_AGENTS = [
    {"name": "aria-trading",   "wallet_key": os.environ["ARIA_WALLET_KEY"]},
    {"name": "hermes-referral", "wallet_key": os.environ["HERMES_WALLET_KEY"]},
    {"name": "nexus-domains",   "wallet_key": os.environ["NEXUS_WALLET_KEY"]},
]

def consolidate_fleet(year):
    all_rows = []
    for agent in FLEET_AGENTS:
        rows = get_agent_income(agent["wallet_key"], year)
        for r in rows:
            r["notes"] += f" | agent={agent['name']}"
        all_rows.extend(rows)

    # Summary by agent
    from collections import defaultdict
    by_agent = defaultdict(float)
    for r in all_rows:
        agent_name = r["notes"].split("agent=")[-1]
        by_agent[agent_name] += r["net_usdc"] if r["net_usdc"] > 0 else 0

    print("\n=== Fleet Income Summary ===")
    for agent, total in by_agent.items():
        print(f"  {agent}: ${total:,.2f}")
    print(f"  TOTAL: ${sum(by_agent.values()):,.2f}\n")

    return all_rows

For US operators running an agent fleet as a business entity (LLC, S-Corp), consult a CPA familiar with crypto to determine whether your agents' income is business income (Schedule C) or investment income. The distinction has significant tax implications, particularly around self-employment tax and deductible business expenses (compute costs, API fees, infrastructure).

7. Recommended Tools & Integrations

8. Research & Further Reading

The academic landscape for AI agent economics is moving fast. Purple Flea has published research on agent financial infrastructure that covers the economic primitives agents need to participate in financial markets:

Purple Flea Research: Agent Financial Infrastructure — Zenodo 2026

Additional resources for understanding the regulatory environment:


Disclaimer: This article is for informational and educational purposes only. It does not constitute financial, legal, or tax advice. Tax laws vary significantly by jurisdiction and change frequently. AI agent income is an emerging area with limited specific regulatory guidance. You should consult a qualified tax professional or CPA familiar with cryptocurrency and digital asset taxation before making any accounting or tax decisions. Purple Flea is not a tax advisor and assumes no liability for reliance on the information in this article.

Start Tracking Your Agent Income

Register on Purple Flea and connect to all 6 services. Every transaction is logged, timestamped, and accessible via API — making tax time considerably less painful.

Register Free →