# AI Copy Trading System - API Documentation

This document outlines the API contract between the **Frontend** (Crypto Analysis Website) and the **Backend** (AI Agent Server).

## 1. System Overview
- **Backend URL**: `http://localhost:5001`
- **Base API Path**: `/api`
- **Data Format**: JSON for all endpoints.

---

## 2. API Endpoints Summary

| Method | Endpoint | Description | Frontend Component |
|--------|----------|-------------|-------------------|
| `GET` | `/api/summary` | Portfolio NAV, Total PnL, Start Time | `AICopyTrading.tsx` (Summary Card) |
| `GET` | `/api/positions` | Current active positions detailed list | `AICopyTrading.tsx` (Positions Tab) |
| `GET` | `/api/history` | Historical trade records | `AICopyTrading.tsx` (History Tab) |
| `GET` | `/api/agent-decision` | Logs of AI Agent thinking process & actions | `AICopyTrading.tsx` (Agent Tab) |
| `GET` | `/api/nav-history` | Time-series data for NAV vs BTC benchmark | `ProfitCurve.tsx` (Chart) |
| `GET` | `/api/market-stats` | Global macro, news, fear/greed index | `NewsFeed.tsx`, `MarketAnalysis.tsx` |
| `GET` | `/api/crypto-data` | Real-time price, RSI, Funding Rate for tokens | `App.tsx`, `CryptoCard.tsx` |

---

## 3. Data Structures Detail

### 3.1. Portfolio Summary
**Endpoint**: `/api/summary`
**Response**:
```json
{
  "nav": 10500.25,        // Current Net Asset Value (USDT)
  "totalPnl": 500.25,     // Total Profit/Loss since start
  "pnlPercent": 5.00,     // Total ROI (%)
  "startTime": "2024-11-15 00:00:00" // Tracking start date
}
```

### 3.2. Positions
**Endpoint**: `/api/positions`
**Response**: Array of objects.
```json
[
  {
    "symbol": "BTC",
    "name": "Bitcoin",
    "entryPrice": 98000.50,
    "currentPrice": 99000.00,
    "stopLoss": 95000,
    "takeProfit": 105000,
    "amount": 0.1,
    "pnl": 100.00,        // Unrealized PnL (USDT)
    "pnlPercent": 1.02,   // Unrealized ROI (%)
    "type": "long",       // "long" or "short"
    "leverage": 1         // Leverage multiplier
  }
]
```

### 3.3. Trade History
**Endpoint**: `/api/history`
**Response**: Array of objects.
```json
[
  {
    "id": "2025-01-01 10:00:00-BTC",
    "symbol": "BTC",
    "type": "long",
    "entryPrice": 90000,
    "exitPrice": 92000,
    "amount": 0.1,
    "pnl": 200,           // Realized PnL
    "pnlPercent": 2.22,
    "entryTime": "2024-12-30 09:00:00",
    "exitTime": "2025-01-01 10:00:00",
    "leverage": 1
  }
]
```

### 3.4. NAV History (Chart Data)
**Endpoint**: `/api/nav-history`
**Response**:
```json
[
  {
    "timestamp": "2024-11-15 00:00:00",
    "nav": 10000.0,
    "btc_price": 65000.0  // Optional, used for benchmark comparison
  },
  ...
]
```

### 3.5. Agent Decision Logs
**Endpoint**: `/api/agent-decision`
**Response**: Array of decision cycles.
```json
[
  {
    "timestamp": "2025-02-05 10:00:00",
    "analysis_summary": {
      "zh": "市场趋势看涨，RSI健康，资金费率正常...",
      "en": "Market trend bullish, RSI healthy..."
    },
    "actions": [
      {
        "action": "ENTRY_LONG", // or "EXIT", "HOLD"
        "symbol": "ETH",
        "entry_reason": {
          "zh": "ETH突破关键阻力位...",
          "en": "ETH broke resistance..."
        },
        "price": 2800.0,
        "amount": 1.5
      }
    ]
  }
]
```

### 3.6. Market Stats (Macro & News)
**Endpoint**: `/api/market-stats`
**Response** (Partial view):
```json
{
  "fed_futures": { "implied_rate": 4.5, "trend": "Neutral" },
  "fear_greed": { "latest": { "value": "75", "value_classification": "Greed" } },
  "ai_analysis": {  // NEW: Generated by LLM
    "global_summary_cn": "当前市场流动性充裕...",
    "news_analysis": [
      {
        "title_cn": "美联储暗示降息",
        "reason_cn": "利好风险资产",
        "sentiment": "Bullish"
      }
    ]
  },
  "news": { ...raw RSS items... }
}
```

### 3.7. Crypto Live Data
**Endpoint**: `/api/crypto-data`
**Response**:
```json
{
  "data": {
    "BTC": {
      "price": 99500.0,
      "change_24h": 1.5,
      "rsi_4h": 55.0,
      "funding_rate": 0.01,
      "funding_rate_status": "NORMAL",
      "sentiment": "NEUTRAL",  // NEUTRAL, OVERSOLD, OVERBOUGHT
      "sentimentScore": 50,
      "description": "..."     // Optional: Overridden by Agent reason
    },
    "ETH": { ... }
  },
  "lastUpdated": 1700000000 // Unix timestamp
}
```
