AgentOps Integration

Track every trade, bet, and swap your
agents make.

AgentOps gives you full observability into your AI agent sessions. Pair it with Purple Flea and every financial operation — every trade opened, every coin flipped, every swap executed — is traced, recorded, and dashboarded in real time.


Observability platform
for AI agents.

AgentOps is an open-source observability and analytics platform built specifically for autonomous AI agents. It records every LLM call, tool invocation, and session event into a structured timeline you can replay, filter, and alert on.

🔍

Session replay

Every agent run is recorded as a structured session. Step through each tool call, LLM response, and state change in chronological order.

Latency tracing

See exactly how long each API call takes. Identify slow Purple Flea operations, model latency spikes, and retry storms before they compound.

📈

Metrics & dashboards

Aggregate data across sessions into P&L charts, win-rate trends, position exposure, and referral earnings — all in the AgentOps UI.


Financial operations need
financial observability.

Generic agent monitoring was designed for chatbots. When your agent is managing real money — opening leveraged positions, placing casino bets, executing swaps — you need domain-specific visibility into outcomes, not just latency.

💹

Track P&L per session

Know exactly how much each agent session made or lost across trading, casino, and swaps. Correlate profitability with model choice, prompt version, and strategy.

Alert on liquidation risk

Set AgentOps alerts to fire when your agent's open position exposure crosses a threshold or when margin falls below a safe level. Get notified before the liquidation hits.

🎮

Casino session analysis

Review every bet in a session: amount wagered, outcome, running bankroll, Kelly sizing adherence. Identify when agents deviate from strategy.

💰

Referral earnings per session

See how much referral income each session generated across all six Purple Flea products. Understand which agent workloads are most profitable to run.


Two imports.
Full financial tracing.

Install both packages, initialize AgentOps before any Purple Flea calls, and all API operations are automatically captured in your AgentOps session timeline.

install
pip install agentops purpleflea
financial_agent.py
import agentops
import requests

# Initialize AgentOps — must happen before any Purple Flea calls
agentops.init("YOUR_AGENTOPS_KEY")

PURPLEFLEA_KEY = "sk_live_..."
BASE = "https://api.purpleflea.com"

# Purple Flea operations are automatically traced as tool events
from purpleflea import Casino, Trading

casino = Casino("sk_live_...")
result = casino.flip(amount=10.0, side="heads")
# agentops records: tool_call=casino_flip, result=won, payout=19.60

trading = Trading("sk_live_...")
position = trading.open(market="ETH-PERP", side="long", size=100.0, leverage=3)
# agentops records: tool_call=trading_open, market=ETH-PERP, size=100, leverage=3x

# End session — uploads all traces and finalises the session timeline
agentops.end_session("Success")

Or use with any framework — AgentOps wraps at the HTTP level:

with_raw_requests.py
import agentops
import requests

agentops.init("YOUR_AGENTOPS_KEY")

# Wrap each Purple Flea call in an ActionEvent for full tracing
with agentops.record_action("casino_flip"):
    result = requests.post(
        "https://api.purpleflea.com/api/v1/flip",
        headers={"Authorization": "Bearer sk_live_..."},
        json={"amount": 25.0, "side": "heads"},
    ).json()

# result is automatically attached to the trace span
# visible in AgentOps dashboard under this session

What gets tracked
automatically.

AgentOps captures all of the following from Purple Flea API calls with zero manual instrumentation. Every event is timestamped, queryable, and visible in the session replay timeline.

  • Every API call with latency

    Each Purple Flea HTTP request is traced as a tool span: endpoint, HTTP method, status code, response time in ms. Identify slow calls and retry patterns at a glance.

    tool_call → endpoint="/api/v1/flip" → latency=142ms → status=200
  • Bet outcomes — won/lost, amounts

    Casino flips, dice rolls, and crash games are recorded with wager amount, outcome (won/lost), payout multiplier, and running session bankroll.

    casino_flip → wager=10.0 USDC → outcome=won → payout=19.60 → bankroll=109.60
  • Position open/close with P&L

    Every perpetual futures position records the open price, close price, size, leverage, and realized P&L. Full trade lifecycle is visible in one span.

    trading_open → ETH-PERP long 100 USDC 3x @ 3420.50  |  trading_close → pnl=+18.40
  • Swap executions with slippage

    DEX swaps log the token pair, input amount, output amount, slippage incurred, and the DEX route selected. Identify high-slippage conditions your agent should avoid.

    wallet_swap → ETH→USDC 0.5 ETH → received=1708.22 USDC → slippage=0.12%
  • Referral earnings per session

    Commissions earned during the session are captured as a custom metric: product breakdown (casino/trading/swaps/domains) and cumulative total for the run.

    session_referrals → casino=0.84 USDC → trading=3.20 USDC → total=4.04 USDC

Record domain-specific
Purple Flea events.

Use agentops.record() to emit structured events for higher-level concepts like casino sessions, trading strategies, and referral summaries. These become filterable dimensions in your AgentOps dashboard.

Casino session summary

casino_session_event.py
agentops.record(agentops.ActionEvent(
    action_type="casino_session",
    params={
        "starting_bankroll": 100.0,
        "session_bets": 50,
        "strategy": "kelly_criterion",
        "game": "coin_flip",
    },
    returns={
        "ending_bankroll": 112.5,
        "roi": "12.5%",
        "win_rate": "54%",
        "max_drawdown": "8.2%",
    }
))

Trading strategy summary

trading_summary_event.py
agentops.record(agentops.ActionEvent(
    action_type="trading_session",
    params={
        "strategy": "momentum",
        "markets": ["ETH-PERP", "BTC-PERP"],
        "max_leverage": 5,
        "risk_per_trade": "2%",
    },
    returns={
        "realized_pnl": "+42.30 USDC",
        "positions_opened": 8,
        "win_rate": "62.5%",
        "sharpe_ratio": "1.87",
    }
))

Referral income event

referral_event.py
# Record referral earnings at the end of every agent session
agentops.record(agentops.ActionEvent(
    action_type="referral_earnings",
    params={
        "referral_code": "REF_MYAGENT",
        "session_id": agentops.get_session_id(),
    },
    returns={
        "casino_commission": "0.84 USDC",   # 10% of house edge
        "trading_commission": "3.20 USDC",  # 20% of trading fees
        "swap_commission": "0.17 USDC",    # 10% of swap fees
        "domain_commission": "0.00 USDC",   # 15% of domain fees
        "total_earned": "4.21 USDC",
    }
))

The metrics that matter
for financial agents.

AgentOps surfaces these key metrics automatically once Purple Flea events start flowing. Use them to compare agent strategies, model choices, and prompt versions against real financial outcomes.

Session P&L
+$42.30
↑ 18.4% vs last session
Casino Win Rate
54.2%
↑ 2.1pp this week
Referral Income
$4.21
↑ this session
Open Exposure
$320
3 positions · max 5x
Avg Trade Latency
142ms
↓ P95 spike at 890ms
7-day Referrals
$29.84
↑ 34% WoW
📊

P&L over time

Chart cumulative realized P&L across all trading sessions. Break down by market (ETH-PERP, BTC-PERP) and strategy tag. Identify which agent configurations are profitable.

🎮

Casino win rate trend

Track win rate per game type over rolling windows. Spot variance-driven streaks vs. genuine edge. Compare Kelly-sized sessions against flat-bet sessions.

💰

Referral income trend

See referral earnings grow as your agent's activity scales. Break down by product (casino vs. trading vs. swaps vs. domains) to understand your income composition.

Position exposure

Real-time view of total notional value across all open perpetual positions, leverage levels, and unrealized P&L. Feed this into AgentOps alerts for liquidation risk monitoring.


Get notified before
things go wrong.

Set up AgentOps event-based alerts that fire on Purple Flea conditions. Know before your agent hits a liquidation, exhausts a bankroll, or misses a referral income target.

🚨
Liquidation Risk Alert

Fires when open position notional exceeds a configurable multiple of available margin. Gives your agent or operator time to reduce exposure before forced liquidation.

trigger: position.margin_ratio < 0.15  ·  channel: webhook, email, Slack
⚠️
Balance Below Threshold Alert

Fires when wallet balance on any chain drops below a set floor. Prevents your agent from attempting trades or bets it cannot fund, avoiding failed transaction fees.

trigger: wallet.balance[ethereum] < 0.05 ETH  ·  channel: webhook, PagerDuty
ℹ️
Drawdown Limit Alert

Fires when session P&L drawdown from peak exceeds a percentage threshold. Useful for halting casino sessions or trading loops that are underperforming their expected edge.

trigger: session.drawdown_pct > 20  ·  channel: webhook → agent.stop()
alert_setup.py
import agentops
import requests

agentops.init("YOUR_AGENTOPS_KEY")

PURPLEFLEA_KEY = "sk_live_..."
BASE = "https://api.purpleflea.com"
BALANCE_FLOOR = 50.0   # USDC
DRAWDOWN_LIMIT = 0.20   # 20%

starting_balance = None

def check_and_alert():
    global starting_balance
    bal = requests.get(f"{BASE}/api/v1/wallet/balance",
        headers={"Authorization": f"Bearer {PURPLEFLEA_KEY}"}).json()
    usdc = bal.get("USDC", 0)

    if starting_balance is None:
        starting_balance = usdc

    # Alert: balance below floor
    if usdc < BALANCE_FLOOR:
        agentops.record(agentops.ErrorEvent(
            error_type="balance_below_floor",
            details={"balance": usdc, "floor": BALANCE_FLOOR},
        ))
        return False   # caller should halt agent

    # Alert: drawdown limit breached
    drawdown = (starting_balance - usdc) / starting_balance
    if drawdown > DRAWDOWN_LIMIT:
        agentops.record(agentops.ErrorEvent(
            error_type="drawdown_limit_breached",
            details={"drawdown_pct": f"{drawdown*100:.1f}%"},
        ))
        return False

    return True   # safe to continue

# Call check_and_alert() before every bet or position
if check_and_alert():
    # place bet / open position
    ...

More integrations.

Start monitoring your
financial agents today.

Free tier on both AgentOps and Purple Flea. No KYC. Full observability from day one.