← Back to MiaoFi

MiaoFi API Docs

Developer guide for integrating AI-powered wallet diagnostics into your app or agent.

Pricing at a glance

x402 Agent

$0.08

per diagnosis · no account

Credit Pack

$0.66

per diagnosis · API key

Free Trial

3

diagnoses free · no card

Full API reference — also available at /llms-full.txt

Download ↓
# MiaoFi API Documentation

> MiaoFi is an AI investment copilot that reads your crypto trading history like a behavioral psychologist. Paste a wallet address (or upload a Binance export) and in ~30 seconds it returns a health score (0-100), the concentration/diversification/yield problems in what you hold, the behavioral patterns in how you trade (FOMO buying, panic selling, overtrading, disposition effect), your worst trades with exact dollar losses — and, crucially, the **executable fix**: each finding ships with a ready-to-click action (swap, DCA, limit order, stake, bridge) resolved to a real DEX/CEX URL. MiaoFi doesn't tell you what the market is doing; it tells you what *you* are doing, what it's costing you, and the specific next move to fix it.

Base URL: `https://miaofi.ai`
Protocol: HTTPS REST + JSON
schema_version: `"1.0"`
Authentication: x402 (`PAYMENT-SIGNATURE`, preview) · API Key (`X-API-KEY`) · Privy JWT (`Authorization: Bearer`) · anonymous free tier
OpenAPI Spec: `GET /api/openapi`
MCP Server: `GET /api/mcp` (Streamable HTTP, stateless)
Version: 1.3 (2026-05-29)

---

## What Is MiaoFi?

Most crypto tools look **outward** — what's the market doing, which token is pumping, what are whales buying. MiaoFi looks **inward**: it reads your own trade tape and holdings and tells you what *you* keep doing wrong. Portfolio trackers (DeBank, Zerion) show what you hold; market analytics (Nansen, Dune) show what others are doing; MiaoFi is the only layer that diagnoses *your* decisions.

That position is structurally absent from the ecosystem on purpose: exchanges, aggregators, and agent platforms all earn more when you trade more, so none of them is incentivized to tell you to trade *less* or *better*. MiaoFi charges per diagnosis ($0.08 via x402, or prepaid credits) and is **read-only** — it never holds keys, signs transactions, or touches your assets — so it has no reason to do anything but give you the hard truth.

### Two co-equal diagnosis modules

**Portfolio Analysis (PA)** — what you hold. Health score (0-100, grades A-F), concentration risk, diversification gaps, idle capital, yield opportunities, correlated exposure, stablecoin/protocol risk. Example: *"96.2% of portfolio value is in a single token. A 20% drop would erase $261,000."*

**Trading Behavior Analysis (TBA)** — how you trade. Trader-type classification, behavioral pattern detection, and worst-trades analysis with dollar amounts and exact dates. Example: *"19 of your 34 trades (56%) were FOMO buys after 30%+ surges. They averaged -11.3%, costing ~$2,847."*

### What makes a MiaoFi diagnosis different

- **Executable, not just descriptive.** Every finding carries one or more *actions* with a resolved URL — a one-click swap on Unispaw/Jupiter, a DCA or limit order on Jupiter, a stake on Lido/Aave, a bridge on Jumper, or a CEX onboarding link. An agent gets `actionType` + `actionParams` + a ready `url`; a human gets a button. (See "Executable Actions" below — this is the headline feature.)
- **Specific numbers, never generic.** Every observation cites exact dollar amounts, percentages, trade counts, and dates from *your* data — never "consider diversifying."
- **Deterministic where it must be.** The health score and behavioral metrics are computed in code (not by the AI), so the same wallet yields the same score. The AI only interprets pre-computed signals — it never sees raw bytes and never improvises numbers.
- **Quality-gated.** Findings below 60% confidence are dropped. AI output passes four gates before you see it: schema compliance, dollar-impact reasonableness (< portfolio value), forbidden-phrase check (en/zh/ko), and evidence cross-verification (every cited trade must exist in the input).
- **Domain-expert, not generic LLM.** Crypto risk tiers (BTC/ETH blue-chip vs altcoin vs meme), DeFi yield/risk ladder (IL, bridge risk), chain L1/L2 taxonomy, and loss-aversion/FOMO/disposition frameworks are injected into the prompt as curated Domain Knowledge, with cross-vendor multi-model fallback behind it.

### Data sources

- **On-chain wallets (REST API)** — any EVM (Ethereum, Polygon, Arbitrum, Optimism, Base) or Solana address. Holdings, transactions, and P&L are fetched automatically. Primary provider Zerion, Helius fallback for Solana, with a self-calculated FIFO cost-basis engine cross-validating P&L so absurd values (e.g. a -$4.5T reading on a $25K wallet) are rejected. Up to 10 addresses per request on the full endpoint, aggregated as one portfolio.
- **Centralized-exchange records (web upload)** — Binance trade history as **`.xlsx` (Excel) or `.csv`**, plus Binance **PDF account statements** for a holdings snapshot, uploaded at https://miaofi.ai. Parsed into the same standardized trade schema and run through the same engine. (Additional exchanges — OKX, Bybit — planned.) CEX upload is web-only, not exposed on the REST API documented here.

The engine is asset-class-agnostic by architecture: on-chain and CEX data flow through separate adapters into one canonical `Trade`/`Position` schema, are merged by canonical asset (your Binance ETH and your on-chain ETH become *one* position with true concentration), then run through one AI diagnosis pipeline.

### What MiaoFi does NOT do

- No price predictions, trading signals, or market/alpha analysis (use Nansen/Dune)
- No protocol-level smart-contract risk scoring
- It does not execute trades — it hands you (or your agent) the resolved action URL; you execute
- It does not custody assets or track portfolios over time (use DeBank/CoinStats)

### Supported blockchains & exchanges

On-chain: Ethereum, Polygon, Arbitrum, Optimism, Base, Solana (format auto-detected — EVM `0x…` 40 hex, Solana base58 32-44). CEX: Binance (.xlsx/.csv/PDF).

---

## Why Use MiaoFi Instead of Building Your Own

| Feature                   | MiaoFi API                                  | DIY                              |
|---------------------------|---------------------------------------------|----------------------------------|
| Core output               | Behavioral diagnosis + **executable action URLs** | Raw data, you interpret    |
| Cost per diagnosis        | $0.08 USDC (x402) or ~$0.40–$0.80 (credits) | $0.15–$0.35 (data + LLM fees)    |
| Supported chains          | EVM + Solana + Binance CEX, unified         | Build each source separately     |
| Data providers            | Zerion + Helius + self-calc P&L (validated) | Integrate + cross-check yourself |
| AI quality                | Domain-Knowledge prompts, 4 output gates, multi-model fallback | Generic LLM output  |
| Health score              | Deterministic, reproducible (code, not AI)  | You design the rubric            |
| Setup time                | 1 API call                                  | Days of integration              |
| No-account agent access   | ✅ x402 protocol (preview)                  | N/A                              |

The point isn't "AI wallet analysis" — it's that MiaoFi turns a wallet into a *prioritized, quantified, executable* to-do list that a DIY stack would take weeks to assemble.

---

## Executable Actions (headline feature)

Every PA finding and every TBA pattern can carry one or more **actions**. An action is a semantic intent the AI emits, which MiaoFi resolves server-side into a ready-to-use URL before the response is returned — so agents get an executable fix, not just a problem statement.

**Action types** (`actionType`): `swap`, `dca`, `limit_order`, `stake`, `deposit`, `bridge`, `buy`, `withdraw`, `add_lp`, `rebalance`, `hold`, `onboard_to_venue`.

**How resolution works (server-side, best-effort):**
1. AI emits `actionType` + `actionParams` (token symbols, chain, percentage, price strategy).
2. MiaoFi resolves token *symbols* → on-chain contract/mint addresses (from your positions, no extra calls).
3. It infers the chain and selects providers, producing chain-aware URLs:
   - **Solana** → Jupiter (swap / DCA / limit order)
   - **EVM** → Uniswap, 1inch (swap), Jumper (bridge), Aave / Lido (deposit / stake)
   - **CEX** → `onboard_to_venue` links to Binance / OKX / Bybit / Kraken / Coinbase pair pages
4. Informational types (`hold`, `monitor`, `reduce_frequency`) carry no URL and are flagged `isInfo: true`.

Resolution is non-blocking: if an asset can't be resolved the finding still returns, just without a URL for that action (no silent fake links).

**What an agent receives** (inside each finding, in the `/api/diagnosis` response):

```json
"recommendedActions": [
  {
    "id": "act_1",
    "label": "Trim WHITE into USDC",
    "actionType": "swap",
    "actionParams": { "fromToken": "WHITE", "toToken": "USDC", "percentage": 50, "chain": "ethereum" },
    "resolvedProviders": [
      { "providerName": "uniswap", "providerType": "dex", "label": "Swap on Uniswap", "url": "https://app.uniswap.org/swap?inputCurrency=0x…&outputCurrency=0xa0b8…", "priority": 1 },
      { "providerName": "1inch",   "providerType": "dex", "label": "Swap on 1inch",   "url": "https://app.1inch.io/…", "priority": 2 }
    ]
  }
],
"renderableActions": [
  { "actionId": "ra_1", "actionType": "swap", "label": "Swap WHITE → USDC on Uniswap",
    "execution": { "type": "redirect", "url": "https://app.uniswap.org/swap?…" }, "providerName": "uniswap" }
]
```

An autonomous agent reads `resolvedProviders[0].url` (or `renderableActions[].execution.url`) and either redirects the user or drives the swap programmatically. (Note: these action fields are in the live response but are not yet in the OpenAPI spec — rely on this document for their shape.)

---

## Quick Start

No API key needed for your first call — the anonymous free tier covers evaluation (1 diagnosis for anonymous IPs; 5/month for agents identifying via User-Agent).

### Diagnose a wallet in one command

```bash
curl -X POST https://miaofi.ai/api/diagnosis \
  -H "Content-Type: application/json" \
  -d '{"walletAddresses": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"]}'
```

Returns a full diagnosis: health score, portfolio findings (each with executable actions), trader type, behavioral patterns, and worst trades.

### Portfolio analysis only (PA)

```bash
curl -X POST https://miaofi.ai/api/diagnosis/portfolio \
  -H "Content-Type: application/json" \
  -d '{"walletAddresses": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"]}'
```

### Trading behavior analysis only (TBA)

```bash
curl -X POST https://miaofi.ai/api/diagnosis/behavior \
  -H "Content-Type: application/json" \
  -d '{"walletAddresses": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"]}'
```

### With API key (production)

```bash
curl -X POST https://miaofi.ai/api/diagnosis \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: mk_live_xxxxxxxxxxxx" \
  -d '{"walletAddresses": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"]}'
```

---

## Which Endpoint Should I Use?

**"Is this portfolio healthy?"** → `POST /api/diagnosis/portfolio` — health score + portfolio findings + actions. Single wallet.

**"What kind of trader is this, and what are they doing wrong?"** → `POST /api/diagnosis/behavior` — trader type, behavioral patterns, worst trades + actions. Single wallet.

**"Give me everything."** → `POST /api/diagnosis` — both modules, 1–10 wallets aggregated. Most comprehensive.

**"Should my agent execute this trade?"** → `POST /api/agent/pre-trade-check` — go/no-go risk signal before a swap.

**"Any behavioral red flags?"** → `POST /api/agent/behavior-flags`.

**"How concentrated is one token?"** → `GET /api/agent/token-exposure`.

**"Just basic wallet info, free."** → `GET /api/agent/free/wallet-overview?address=0x…` — token count + total value, no AI, no auth.

---

## Authentication

Resolved in priority order (first match wins): x402 → API Key → Privy JWT → anonymous.

### Method 1: x402 Payment (agent-native, preview)

> **Status: preview.** The x402 code path is live and accepts `PAYMENT-SIGNATURE`, but native on-chain settlement verification is still rolling out (the discovery manifest marks x402 `coming-soon`). For production billing today, prefer an API key. x402 is the intended agent-native rail and is safe to integrate against now.

Lets autonomous agents pay per diagnosis with no account: $0.08 USDC on Base.
1. POST to `/api/diagnosis` with no auth → server replies HTTP 402 with a payment payload.
2. Agent broadcasts USDC on Base, retries with the proof in `PAYMENT-SIGNATURE`.
3. Server verifies and returns the diagnosis.

```
PAYMENT-SIGNATURE: <base64-encoded payment proof>
Content-Type: application/json
```

Details: $0.08 USDC · Base (eip155:8453, chain ID 8453) · USDC `0x833589fcd6edb6e08f4c7c32d4f71b54bda02913` · discovery at `GET /.well-known/x402.json`.

### Method 2: API Key (recommended for production)

Get a key at https://miaofi.ai/api-key (Privy login). Credits purchased via Stripe.

```
X-API-KEY: mk_live_xxxxxxxxxxxx
```

100 requests/hour; tied to a credit balance; 1 credit per diagnosis on any endpoint.

### Method 3: Privy JWT (web login)

```
Authorization: Bearer <privy_jwt>
```

For human web users — registered free tier (3 diagnoses) then purchased credits.

### Anonymous tier

Omit all auth headers. Anonymous IPs get 1 free diagnosis; agents on a recognized User-Agent get 5/month. Agents that omit auth still get results up to the free limit instead of failing.

---

## Core Endpoints

### POST /api/diagnosis — Full Diagnosis

Runs both PA and TBA. The flagship endpoint; the only one supporting multi-wallet aggregation (1–10 addresses).

**Request body:**

```json
{ "walletAddresses": ["0x..."], "locale": "en", "force": false }
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| walletAddresses | string[] | Yes | 1–10 EVM (`0x...`) or Solana (base58) addresses |
| locale | string | No | `"en"` (default), `"zh"`, or `"ko"` |
| force | boolean | No | Bypass cache, force fresh analysis (still consumes credit/free tier) |
| cexUploadIds | string[] | No | Up to 10 CEX-upload UUIDs for cross-source TBA |

> The field is `walletAddresses` (camelCase array). Sending `addresses` fails validation (HTTP 400).

**Successful response (HTTP 200):**

```json
{
  "success": true,
  "schema_version": "1.0",
  "latencyMs": 42000,
  "data": {
    "healthScore": { "score": 72, "grade": "B", "summary": "Your portfolio has 1 critical issue that needs attention." },
    "findings": [
      {
        "id": "finding_001",
        "type": "concentration_risk",
        "severity": "critical",
        "title": "Extreme concentration in WHITE",
        "description": "96.2% of portfolio value is in a single token. A 20% drop in WHITE would erase $261,000.",
        "relatedAssets": ["WHITE"],
        "recommendedActions": [
          { "id": "act_1", "label": "Trim WHITE into USDC", "actionType": "swap",
            "actionParams": { "fromToken": "WHITE", "toToken": "USDC", "percentage": 50, "chain": "ethereum" },
            "resolvedProviders": [
              { "providerName": "uniswap", "providerType": "dex", "label": "Swap on Uniswap", "url": "https://app.uniswap.org/swap?…", "priority": 1 }
            ] }
        ]
      }
    ],
    "reportSummary": {},
    "tradingBehaviorDiagnosis": {
      "traderType": { "id": "concentration_holder", "label": "Concentration Holder", "description": "Holds large concentrated positions in a few tokens" },
      "patterns": [
        { "id": "fomo_buyer", "label": "FOMO Buyer", "confidence": 78, "impactUsd": -2847,
          "actions": [ { "type": "limit_order", "label": "Set a Jupiter limit order", "url": "https://jup.ag/limit?…", "isInfo": false } ] }
      ],
      "worstTrades": [ { "symbol": "PEPE", "buyDate": "2026-02-10", "sellDate": "2026-02-12", "pnlUsd": -1240, "pnlPercent": -34 } ]
    },
    "metadata": { "diagnosedAt": "2026-05-29T10:00:00Z", "aiModel": "gpt-5.4-mini", "modelTier": "standard" }
  },
  "meta": { "walletCount": 1, "warnings": [], "sessionId": "sess_abc123", "modelTier": "standard", "auth_method": "api_key" }
}
```

**Key fields:**
- `data.healthScore.score`: integer 0-100, computed deterministically in code (not by AI). Base 80; each finding adjusts it (critical -15, warning -8, info -3, positive +5), clamped 1-100.
- `data.healthScore.grade`: **A ≥85, B ≥70, C ≥55, D ≥40, F <40.**
- `data.findings[].type`: one of `concentration_risk`, `loss_position`, `idle_asset`, `yield_opportunity`, `correlated_exposure`, `protocol_risk`, `stablecoin_risk`, `positive_pattern`, `system_fallback`.
- `data.findings[].severity`: `critical` / `warning` / `info` / `positive`. Only findings with ≥60% confidence are returned.
- `data.findings[].recommendedActions[]`: executable actions (see "Executable Actions").
- `data.tradingBehaviorDiagnosis.traderType` / `patterns[]` / `worstTrades[]`: TBA output (see below).
- `meta.sessionId`: log it for support. `meta.modelTier`: `flash` / `standard` / `premium`. The `X-Request-Id` header carries the request ID.

**Cost:** 1 credit (or $0.08 via x402).

---

### POST /api/diagnosis/portfolio — Portfolio Analysis Only

Health score + portfolio findings (each with actions), no behavior analysis. Single wallet. Same request shape; `meta.modules = ["pa"]`; `tradingBehaviorDiagnosis` absent. A recent full diagnosis for the same wallet is served from cache. **Cost:** 1 credit.

### POST /api/diagnosis/behavior — Trading Behavior Analysis Only

Trader type, behavioral patterns, worst trades (with actions), no health score. Single wallet. `meta.modules = ["tba"]`; `data.tradingBehaviorDiagnosis` + `data.behaviorPatternDetails`; `healthScore`/`findings` absent. **Cost:** 1 credit.

**Behavioral patterns detected:** `fomo_buyer`, `panic_seller`, `overtrader` (20+ trades/30D), `low_conviction_trap` (many sub-2% positions), `roundtrip_trader`, `revenge_trader`, `sunk_cost_averager`, plus `balanced` (no extremes) and positive patterns (profit_taker, diamond_hands, dip_buyer). Each pattern carries a confidence (≥60), a dollar impact, evidence trades, and actions. `worstTrades` excludes stablecoin swaps (those are liquidity ops, not investment decisions).

---

## Agent Micro-Endpoints

Lightweight endpoints for high-frequency agent use. All `/api/agent/*` are CORS-enabled and return the structured error envelope. All except the free tier require API key (or x402).

### POST /api/agent/pre-trade-check
Go/no-go risk signal before a swap. Body: `{ "wallet_address": "0x…", "trade": { "from_token": "ETH", "to_token": "PEPE", "amount_usd": 5000 } }` → `{ "risk_level", "risk_score", "reason", "should_proceed", "flags": [...] }`. API key. 1 credit.

### POST /api/agent/behavior-flags
Behavioral red flags without a full diagnosis. Body: `{ "wallet_address": "0x…", "lookback_days": 30 }`. API key. 1 credit.

### GET /api/agent/token-exposure
`?address=0x…&token=WHITE` → single-token concentration + risk. API key. 1 credit.

### GET /api/agent/stats
`?address=0x…` → trade count, win rate, avg trade size, frequency. API key. 1 credit.

### GET /api/agent/referral-stats
Referral stats for the authenticated key. API key. Free.

### GET /api/agent/free/wallet-overview
`?address=0x…` → `{ address, token_count, total_value_usd, chain_distribution, detailed_diagnosis_available, diagnosis_endpoint, diagnosis_price_usd }`. **No auth.** 100 req/hour per IP. Free. (GET with a query param — not POST.)

---

## Error Handling

Two envelopes. Branch on the HTTP status code; structured `code` values are stable.

| Endpoint(s) | Error envelope |
|-------------|----------------|
| `POST /api/diagnosis/portfolio`, `POST /api/diagnosis/behavior`, all `/api/agent/*` | **Structured** `{ "error": { "code", "message", "request_id", "retry_after"?, "details"? } }` |
| `POST /api/diagnosis` (flagship) | **Legacy** `{ "error": "<message>" }` — branch on HTTP status |

Across all endpoints, a malformed request body (invalid JSON, missing/oversized `walletAddresses`) returns a plain `{ "error": "<message>" }` with HTTP 400.

**Codes:** `invalid_input` / `invalid_address` (400) · `insufficient_credits` (402) · `rate_limited` (429, with `retry_after` + `Retry-After`) · `internal_error` (500) · `data_fetch_failed` (502). **You are not charged for failed diagnoses** — credits/free-tier are consumed only after a successful AI result, so a 500 never consumes your balance. Retry 500s with exponential backoff (5s, 15s, 45s).

---

## Caching & Request Correlation

Results are cached per (wallet set + locale); cached responses return near-instantly at no AI cost. A full-diagnosis cache also serves later PA-only / TBA-only requests for the same wallet. Set `"force": true` to bypass. Every response carries `X-Request-Id` (and `meta.request_id` / `error.request_id`) — log it.

---

## Pricing

| Method | Cost per diagnosis | Auth | Rate limit |
|--------|--------------------|------|------------|
| Anonymous (human) | Free (1 total) | none | per-IP |
| Anonymous (agent) | Free (5/month) | User-Agent | per-agent |
| x402 (agent, preview) | $0.08 USDC on Base | `PAYMENT-SIGNATURE` | 100/hour |
| API key (credits) | ~$0.40–$0.80 | `X-API-KEY` | 100/hour |
| Registered (web) | Free (3 total), then credits | Privy JWT | per-account |

Every diagnosis costs 1 credit regardless of endpoint (`/api/agent/referral-stats` and `/api/agent/free/wallet-overview` are free). **Credit packs** (one-time via Stripe, valid 6 months): Experience 5/$3.99 · Standard 15/$8.99 (most popular) · Professional 40/$15.99 (includes Claude Opus premium model + savings calculator). Purchase at https://miaofi.ai/api-key.

---

## Rate Limits

| Tier | Limit |
|------|-------|
| Anonymous human | 1 free diagnosis (total) |
| Anonymous agent | 5 free diagnoses / month |
| API Key | 100 requests/hour |
| x402 agent | 100 requests/hour |
| Free wallet-overview | 100 requests/hour per IP |

HTTP 429 includes `retry_after` (seconds) and a `Retry-After` header.

---

## Response Times

AI-inference time by model tier (auto-selected by auth/credit tier). End-to-end latency — live multi-source data fetch plus, on the full endpoint, both PA + TBA — is longer; set client timeouts to ~120s (the diagnosis endpoints allow 75–90s server-side for the pipeline plus AI fallback).

| Model Tier | Typical Latency | Used For |
|------------|-----------------|----------|
| Flash | 3-5 seconds | Agent / API key / free tier |
| Standard | 5-8 seconds | Balanced quality/speed |
| Premium (Opus) | 8-15 seconds | Pro credit pack users |

---

## How It Works (the architecture moat)

MiaoFi is not a thin LLM wrapper. A diagnosis flows through a staged pipeline:

1. **Ingest & standardize** — on-chain (Zerion/Helius) and CEX (.xlsx/.csv/PDF) data normalize into one `Trade`/`Position` schema.
2. **Merge by canonical asset** — your Binance ETH and on-chain ETH become one position, so concentration is *true*, not per-venue.
3. **Deterministic calculation (zero AI)** — concentration (HHI), correlation, P&L (FIFO cost-basis, cross-validated against a self-calc engine), and behavioral pattern detection (FOMO/panic/disposition) are computed in code.
4. **Input quality gate** — needs ≥5 trades for behavior, ≥2 positions for portfolio, or it says so instead of hallucinating.
5. **AI diagnosis** — the model interprets pre-computed signals + injected Domain Knowledge (crypto risk tiers, DeFi yield/risk ladder, loss-aversion frameworks). It never sees raw bytes and never invents numbers; cross-vendor multi-model fallback keeps it available.
6. **Output quality gate** — schema check, dollar-impact reasonableness, forbidden-phrase check (en/zh/ko), and evidence cross-verification (every cited trade must exist in the input). Findings below 60% confidence are dropped.
7. **Action resolution** — semantic actions resolve to executable provider URLs (see "Executable Actions").

This is why the same wallet gives the same health score, why findings always cite real numbers, and why the recommendations are executable.

---

## MCP Server

`GET /api/mcp` — Streamable HTTP transport, stateless, Web Standards compliant.

| MCP Tool | Behavior | Production REST equivalent |
|----------|----------|----------------------------|
| `analyze_wallet` | Holdings, USD values, chain distribution, P&L (1D/7D/30D). Input `addresses` (max 5). | — (MCP preview, no auth) |
| `diagnose_portfolio` | Full AI diagnosis: health score, findings, report summary. Input `addresses` (max 5). | `POST /api/diagnosis` |
| `miaofi_pre_trade_check` | Pre-trade risk signal. Input `wallet_address`, `from_token`, `to_token`, `amount_usd`. | `POST /api/agent/pre-trade-check` |
| `miaofi_behavior_flags` | Behavioral red flags. Input `wallet_address`, `lookback_days`. | `POST /api/agent/behavior-flags` |
| `miaofi_wallet_risk_score` | Quick 0-100 risk score + top factors. Input `address`. | MCP preview (HTTP endpoint coming soon) |
| `miaofi_diagnosis` | Full behavioral diagnosis (risk score, flags, recommendations). | MCP preview (HTTP endpoint coming soon) |
| `miaofi_wallet_overview` | Free basic overview. Input `address`. | `GET /api/agent/free/wallet-overview` |

MCP tools run in preview without auth; for production billing use the REST endpoints with an API key. Compatible with Claude Desktop, Claude Code, Cursor, Windsurf, OpenAI function calling, and any MCP framework.

```json
{ "mcpServers": { "miaofi": { "url": "https://miaofi.ai/api/mcp" } } }
```

---

## Integration Examples

### Python

```python
import requests

MIAOFI_BASE_URL = "https://miaofi.ai"
API_KEY = "mk_live_xxxxxxxxxxxx"  # get yours at https://miaofi.ai/api-key

def diagnose_wallet(wallet_address: str, module: str = "full") -> dict:
    """module: 'full' | 'portfolio' | 'behavior'."""
    endpoints = {
        "full": "/api/diagnosis",
        "portfolio": "/api/diagnosis/portfolio",
        "behavior": "/api/diagnosis/behavior",
    }
    resp = requests.post(
        f"{MIAOFI_BASE_URL}{endpoints.get(module, '/api/diagnosis')}",
        headers={"Content-Type": "application/json", "X-API-KEY": API_KEY},
        json={"walletAddresses": [wallet_address]},
        timeout=120,
    )
    resp.raise_for_status()
    body = resp.json()
    if not body.get("success"):
        err = body["error"]
        raise RuntimeError(err if isinstance(err, str) else f"{err['code']}: {err['message']}")
    return body["data"]


if __name__ == "__main__":
    data = diagnose_wallet("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "portfolio")
    score = data["healthScore"]
    print(f"Health: {score['score']}/100 (Grade {score['grade']}) — {score['summary']}")
    for f in data.get("findings", []):
        print(f"  [{f['severity']}] {f['title']}")
        for a in f.get("recommendedActions", []):
            url = (a.get("resolvedProviders") or [{}])[0].get("url")
            if url:
                print(f"     → {a['label']}: {url}")   # executable action URL
```

### JavaScript / TypeScript

```typescript
const MIAOFI_BASE_URL = 'https://miaofi.ai'
const API_KEY = process.env.MIAOFI_API_KEY ?? 'mk_live_xxxxxxxxxxxx'

interface DiagnosisResult {
  healthScore?: { score: number; grade: string; summary: string }
  findings?: Array<{
    severity: string; title: string; description: string
    recommendedActions?: Array<{ label: string; actionType?: string; resolvedProviders?: Array<{ url: string | null }> }>
  }>
  tradingBehaviorDiagnosis?: { traderType: { label: string }; worstTrades: unknown[] }
}

async function diagnoseWallet(
  walletAddresses: string[],
  module: 'full' | 'portfolio' | 'behavior' = 'full',
): Promise<DiagnosisResult> {
  const endpoints = { full: '/api/diagnosis', portfolio: '/api/diagnosis/portfolio', behavior: '/api/diagnosis/behavior' }
  const resp = await fetch(`${MIAOFI_BASE_URL}${endpoints[module]}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-API-KEY': API_KEY },
    body: JSON.stringify({ walletAddresses }),
    signal: AbortSignal.timeout(120_000),
  })
  const body = await resp.json()
  if (!body.success) {
    const err = body.error
    throw new Error(typeof err === 'string' ? err : `${err.code}: ${err.message}`)
  }
  return body.data
}

const data = await diagnoseWallet(['0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'], 'full')
console.log(`Health: ${data.healthScore?.score}/100 (${data.healthScore?.grade})`)
// each finding's first resolved action URL is ready to open or execute:
data.findings?.forEach(f => {
  const url = f.recommendedActions?.[0]?.resolvedProviders?.[0]?.url
  if (url) console.log(`  → ${f.title}: ${url}`)
})
```

### SuperIntern / Agent Skill Wrapper

Wrap `diagnose_wallet` as a tool `miaofi_diagnose(wallet_address, module)`. The anonymous free tier lets an agent make its first call with no key, then upgrade to `X-API-KEY` (or x402). Because each finding ships a resolved action URL, an agent can go from "diagnose" to "propose the exact swap/DCA/limit-order link" in one call.

---

## Agent Referral Program

1. **Refer** — pass `X-Referrer: <your agent id>` when a referred agent makes its first `/api/diagnosis` call.
2. **Earn** — $0.02 USDC per successful diagnosis by the referred agent (first 10 calls).
3. **Cap** — $0.20 per referred agent; no cap on number referred.

Check stats: `GET /api/agent/referral-stats` with `X-API-KEY`. Self-referral rejected; only successful diagnoses accrue; x402 agents identified by payer wallet, API-key agents by key prefix.

---

## Agent Discovery

`/.well-known/x402.json` (x402 v2) for machine-readable endpoint/pricing/auth discovery; `GET /api/openapi` (OpenAPI 3.1) for the full REST surface; this file at `/llms-full.txt`.

---

## Frequently Asked Questions

### How is MiaoFi different from portfolio trackers and market analytics?
Trackers (DeBank, Zerion, CoinStats) show what you hold; analytics (Nansen, Dune, Arkham) show what the market/others do. MiaoFi reads *your* trade tape and tells you what *you* keep doing wrong — concentration, FOMO, panic selling, disposition effect — with exact dollar costs and an executable fix per finding. It's inward, not outward.

### Does the response really give my agent something to execute?
Yes. Each finding's `recommendedActions[].resolvedProviders[].url` (and `renderableActions[].execution.url`) is a resolved DEX/CEX URL (Jupiter on Solana; Uniswap/1inch/Jumper/Aave/Lido on EVM; CEX onboarding links). TBA patterns carry the same under `actions[].url`. Informational actions (hold/monitor) have no URL and are flagged `isInfo`.

### What file formats can I upload for CEX analysis?
Binance trade history as `.xlsx` (Excel) or `.csv`, plus Binance PDF account statements for a holdings snapshot — via the web app at https://miaofi.ai. OKX/Bybit planned. CEX upload is web-only (not on the REST API).

### Is the health score AI-generated?
No — it's computed deterministically in code (base 80; critical -15, warning -8, info -3, positive +5; clamped 1-100; A ≥85 / B ≥70 / C ≥55 / D ≥40 / F <40), so the same wallet always yields the same score. The AI writes the narrative; the numbers are code.

### Am I charged if the diagnosis fails (500)?
No. Credits/free-tier are consumed only after a successful AI result.

### Can I diagnose multiple wallets at once?
Up to 10 on `POST /api/diagnosis`, aggregated and merged by canonical asset as one portfolio. PA-only and TBA-only take a single wallet.

### How long does it take?
AI inference 3-15s by tier (Flash 3-5s, Standard 5-8s, Premium 8-15s); end-to-end (live fetch + PA + TBA) longer — set timeouts ~120s. Cached responses are near-instant.

### Which chains/exchanges are supported?
On-chain: Ethereum, Polygon, Arbitrum, Optimism, Base, Solana (auto-detected). CEX: Binance (.xlsx/.csv/PDF).

### How do I get an API key?
https://miaofi.ai/api-key (Privy login), then buy a credit pack via Stripe.

### Can AI agents use MiaoFi without human setup?
Yes — the MCP server (`GET /api/mcp`) auto-discovers tools; the OpenAPI spec is at `/api/openapi`; the anonymous free tier means a first call needs no key.

---

## Changelog

- 2026-05-29 (v1.3): Documented the executable-action system (actionType/actionParams/resolvedProviders URLs across PA findings + TBA patterns) — the headline feature. Added the full finding-type (9) and behavior-pattern (8) taxonomies, the deterministic code-computed health score (corrected grade bands A≥85/B≥70/C≥55/D≥40/F<40), the architecture/quality-gate moat, and multi-source data resilience. Corrected CEX formats to .xlsx/.csv + PDF.
- 2026-05-29 (v1.2): Added PA-only and TBA-only endpoints; structured-vs-legacy error table; `walletAddresses`; full-endpoint 10-wallet cap; x402 marked preview; 7-tool MCP table; wallet-overview as GET.
- 2026-03-01: Initial agent API documentation.