Portfolio Tracker

Portfolio Tracker API
for AI Agents

Track AI agent portfolio performance across all chains and protocols. Purple Flea's portfolio tracker API provides real-time balances, PnL, position history, and performance analytics for autonomous agents managing capital across 6 blockchains.

Get Your API Key → View API Reference
6
Chains tracked (ETH, BTC, TRX, XMR, SOL, BNB)
Real-time
PnL and balance updates on every block
Full history
Complete transaction and trade history API
Analytics
Sharpe, drawdown, win rate, profit factor

Track Everything Your Agent Holds

An autonomous financial agent does not just hold spot tokens. It has open perpetual futures positions, yield deposits in lending protocols, LP shares, staked assets, and pending escrow payments — spread across multiple chains. The portfolio tracker API consolidates all of these into a single USD-denominated view.

💸

Spot Holdings

USDC, BTC, ETH, XMR, TRX, and ERC-20 tokens across all 6 supported chains. Balances are returned in both native token units and USD equivalent at current market price. Updated on every confirmed block.

📈

Trading Positions

All open perpetual futures and leveraged positions on Hyperliquid via Purple Flea's trading API. Each position shows entry price, current price, unrealized PnL, leverage, and liquidation price in real time.

💲

Yield Positions

Active deposits in lending protocols, staking contracts, LP pools, and restaking vaults. Shows principal, current value, accrued yield, and time-weighted APY for each position — including Purple Flea's yield optimizer positions.

Portfolio Tracker API Endpoints

Endpoint Description
GET/v1/portfolio/balances All wallet balances across 6 chains, consolidated in USD. Returns per-chain breakdown, per-asset breakdown, and total portfolio value. Supports optional chain filter.
GET/v1/portfolio/positions All open trading positions with unrealized PnL, leverage, entry price, mark price, and estimated liquidation price. Includes both long and short positions across all 275 perpetual markets.
GET/v1/portfolio/performance Aggregate performance metrics over configurable time windows (1d, 7d, 30d, all-time). Returns total return %, annualized Sharpe ratio, max drawdown, win rate, profit factor, and average trade duration.
GET/v1/portfolio/history Full paginated transaction and trade history. Filterable by type (trade, deposit, withdrawal, casino, escrow), date range, and asset. Includes realized PnL for each closed trade.
GET/v1/portfolio/allocation Current allocation breakdown as percentages by asset, protocol, and chain. Useful for enforcing allocation constraints: stop trading if BTC exceeds 50% of portfolio, for example.
POST/v1/portfolio/snapshot Save a point-in-time portfolio snapshot for later comparison. Returns snapshot ID. Use to compute performance between two specific moments without relying on the rolling performance window.

Daily Performance Report Agent

The example below builds a daily performance report that fetches balances, open positions, and 30-day analytics — then logs everything or sends an alert if drawdown exceeds the threshold.

python — daily_report_agent.py
import requests
from datetime import datetime

PF_BASE = "https://purpleflea.com"
HEADERS = {"Authorization": "Bearer pf_live_YOUR_KEY"}

def daily_portfolio_report(
    max_drawdown_alert: float = -0.10,
    max_position_pct: float = 0.30
):
    print(f"=== Portfolio Report {datetime.now():%Y-%m-%d %H:%M} ===")

    # 1. Total balances across all chains
    balances = requests.get(f"{PF_BASE}/v1/portfolio/balances", headers=HEADERS).json()
    total_usd = balances["total_usd"]
    print(f"Total Portfolio: ${total_usd:,.2f}")
    for chain in balances["by_chain"]:
        print(f"  {chain['chain']}: ${chain['usd']:,.2f} ({chain['usd']/total_usd:.1%})")

    # 2. Open positions with unrealized PnL
    positions = requests.get(f"{PF_BASE}/v1/portfolio/positions", headers=HEADERS).json()
    if positions["open_count"] > 0:
        print(f"\nOpen Positions ({positions['open_count']}):")
        for pos in positions["positions"]:
            pnl_sign = "+" if pos["unrealized_pnl"] >= 0 else ""
            print(f"  {pos['symbol']} {pos['side'].upper()} x{pos['leverage']}: "
                  f"{pnl_sign}${pos['unrealized_pnl']:,.2f} | Liq: ${pos['liq_price']:,.0f}")

    # 3. 30-day performance metrics
    perf = requests.get(
        f"{PF_BASE}/v1/portfolio/performance",
        params={"window": "30d"},
        headers=HEADERS
    ).json()
    print(f"\n30-Day Performance:")
    print(f"  Total Return: {perf['total_return']:+.2%}")
    print(f"  Sharpe Ratio: {perf['sharpe_ratio']:.2f}")
    print(f"  Max Drawdown: {perf['max_drawdown']:.2%}")
    print(f"  Win Rate:     {perf['win_rate']:.1%}")
    print(f"  Profit Factor:{perf['profit_factor']:.2f}")

    # 4. Allocation check — enforce concentration limits
    alloc = requests.get(f"{PF_BASE}/v1/portfolio/allocation", headers=HEADERS).json()
    for asset in alloc["by_asset"]:
        if asset["pct"] > max_position_pct:
            print(f"  ALERT: {asset['symbol']} exceeds concentration limit ({asset['pct']:.1%} > {max_position_pct:.0%})")

    # 5. Drawdown alert
    if perf["max_drawdown"] < max_drawdown_alert:
        print(f"  ALERT: Max drawdown {perf['max_drawdown']:.2%} exceeds limit {max_drawdown_alert:.2%}")
        print(f"  Consider reducing position sizes or closing losing trades.")

    # 6. Save snapshot for tomorrow's comparison
    snap = requests.post(f"{PF_BASE}/v1/portfolio/snapshot", headers=HEADERS).json()
    print(f"\nSnapshot saved: {snap['snapshot_id']}")

if __name__ == "__main__":
    daily_portfolio_report()

Performance Metrics Returned by the API

The /v1/portfolio/performance endpoint returns a comprehensive set of trading analytics computed from the agent's trade history. All metrics are computed server-side — no client-side calculation required.

total_return

Cumulative percentage return over the selected window. Accounts for realized and unrealized PnL, yield income, casino winnings, and fee deductions.

sharpe_ratio

Annualized Sharpe ratio using daily return volatility. Values above 1.0 indicate risk-adjusted outperformance. Computed on daily PnL, not on trade-by-trade basis.

max_drawdown

Peak-to-trough decline over the selected window. Expressed as a negative percentage. Use as a stop condition: halt trading if drawdown exceeds your risk limit.

win_rate

Fraction of closed trades with positive realized PnL. Useful for strategy diagnostics but must be read alongside profit factor — a 40% win rate with 3:1 R/R is profitable.

profit_factor

Ratio of gross profit to gross loss. Values above 1.5 are generally desirable. Below 1.0 means the strategy is losing money overall despite any positive win rate.

avg_trade_duration

Average holding period per closed trade in seconds. Helps classify the agent's strategy type: scalper (<60s), day trader (<8h), swing trader (1-7d).

Build a Monitoring Dashboard

The portfolio tracker API is designed to be consumed by dashboards. All responses are JSON, all endpoints support CORS, and authentication uses Bearer tokens. You can build a real-time agent monitoring UI in any framework by polling the API every 30 seconds.

A minimal dashboard polls three endpoints: /v1/portfolio/balances for total value, /v1/portfolio/positions for live PnL, and /v1/portfolio/performance for analytics. Render the results as a live-updating card UI using vanilla JS, React, or any visualization library.

📐

Total Value Over Time

Use /v1/portfolio/history?type=snapshot to pull a time series of portfolio snapshots and render as a line chart. Compare against BTC and ETH benchmarks to show alpha generation.

📊

Live Position Monitor

Poll /v1/portfolio/positions every 30 seconds and color-code open positions green (positive PnL) or red (negative). Show liquidation price as a visual warning bar below current price.

☷️

Chain Allocation Donut

Use /v1/portfolio/allocation to drive a donut chart showing capital distribution across chains and asset types. Alert if any single asset exceeds your concentration limit.

MCP Tools for Portfolio Tracker

All portfolio tracker endpoints are available as MCP tools. An LLM with Purple Flea's MCP server configured can call these tools to understand its own financial position before making trading decisions.

portfolio_balances
Fetch total portfolio value and per-chain balance breakdown in USD.
portfolio_positions
Get all open trading positions with unrealized PnL and liquidation prices.
portfolio_performance
Retrieve Sharpe ratio, max drawdown, win rate, and profit factor for any window.
portfolio_history
Query paginated trade and transaction history with realized PnL per trade.

Continue Building

Know Your Position
Across Every Chain, In Real Time.

Register your agent, and the portfolio tracker API immediately starts recording balances, trades, and performance metrics. Your agent always knows exactly where it stands.