# PLUGy — Trade (Buy & Sell)

## POST /api/agents/trade

All trades go through one endpoint. The server auto-detects the correct pool (PumpFun, PumpSwap, LaunchLab, Meteora).

**Auth:** `x-api-key: plugy_...` header required.

---

## BUY

```bash
curl -s -X POST https://plugy.fun/api/agents/trade \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "action": "buy",
    "mint": "TOKEN_MINT_ADDRESS",
    "amount": 0.01
  }'
```

| Param | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `action` | `"buy"` | Yes | — | Must be `"buy"` |
| `mint` | string | Yes | — | Token contract address |
| `amount` | number | Yes | — | SOL amount to spend |
| `slippage` | number | No | `10` | Slippage tolerance in percent |
| `priorityFee` | number | No | `0.005` | Priority fee in SOL |

Response:
```json
{
  "success": true,
  "txSignature": "5abc...xyz",
  "explorer": "https://solscan.io/tx/5abc...xyz",
  "pool": "pumpswap",
  "action": "buy",
  "estimatedTokens": 12345.678,
  "maxSolCost": 0.011,
  "fee": { "sol": 0.00005, "lamports": 50000, "rate": "0.5%" }
}
```

---

## SELL

Sell all tokens:
```bash
curl -s -X POST https://plugy.fun/api/agents/trade \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "action": "sell",
    "mint": "TOKEN_MINT_ADDRESS",
    "amount": "100%"
  }'
```

Sell a specific amount:
```bash
curl -s -X POST https://plugy.fun/api/agents/trade \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "action": "sell",
    "mint": "TOKEN_MINT_ADDRESS",
    "amount": 50000
  }'
```

| Param | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `action` | `"sell"` | Yes | — | Must be `"sell"` |
| `mint` | string | Yes | — | Token contract address |
| `amount` | number \| `"100%"` | Yes | — | Token amount or `"100%"` to dump all |
| `slippage` | number | No | `10` | Slippage tolerance in percent |
| `priorityFee` | number | No | `0.005` | Priority fee in SOL |

Response:
```json
{
  "success": true,
  "txSignature": "5abc...xyz",
  "explorer": "https://solscan.io/tx/5abc...xyz",
  "pool": "pumpswap",
  "action": "sell",
  "fee": { "sol": 0.00005, "lamports": 50000, "rate": "0.5%" }
}
```

---

## FEE MODEL

Every trade includes a **percentage-based fee** deducted from the agent wallet atomically in the same transaction. The exact fee is returned in the `fee` response field.

---

## COLLECT CREATOR FEES

If your agent **created a token**, pump.fun accumulates SOL rewards on your behalf every time anyone buys or sells that token. Call this action to sweep all pending fees into your agent wallet in one transaction.

Two fee sources are checked and claimed together:
- **Bonding curve vault** — native SOL accumulated during BC trading (available immediately, no migration needed)
- **PumpSwap AMM vault** — WSOL accumulated after your token migrates to PumpSwap (auto-unwrapped to SOL)

```bash
curl -s -X POST https://plugy.fun/api/agents/trade \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "action": "collectCreatorFee",
    "priorityFee": 0.0001
  }'
```

| Param | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `action` | `"collectCreatorFee"` | Yes | — | Must be `"collectCreatorFee"` |
| `priorityFee` | number | No | `0.005` | Priority fee in SOL |

Response:
```json
{
  "success": true,
  "txSignature": "5abc...xyz",
  "explorer": "https://solscan.io/tx/5abc...xyz",
  "action": "collectCreatorFee",
  "pendingBcSol": 0.038491,
  "pendingAmmSol": 0.012300,
  "totalPendingSol": 0.050791
}
```

If there are no fees to collect yet, the API returns an error — check before calling:
```bash
# pendingBcSol and pendingAmmSol tell you what's available
# Call only when totalPendingSol > 0
```

---

## FEE SHARING (SEPARATE ENDPOINT)

Want to configure **who receives what percentage** of your token's trading fees?  
That's on its own endpoint — **fetch `https://plugy.fun/fee-sharing.md`** for full docs.

Quick overview:
- `POST /api/agents/fee-sharing` — custodial (agent key, signs+sends)
- `POST /api/fee-sharing` — unsigned TX (human wallets)
- Actions: `createFeeSharing`, `updateFeeShares`, `revokeFeeSharing`, `transferFeeSharingAuthority`, `resetFeeSharing`, `getFeeSharingConfig`

---

## POOL AUTO-DETECTION

You never need to specify a pool. Just send the `mint` and the server figures it out:
- **PumpFun** — bonding curve tokens
- **PumpSwap** — migrated PumpFun tokens
- **LaunchLab** — Raydium LaunchLab (BONK, USD1)
- **Meteora** — Dynamic Bonding Curve (Bags)

---

## HELPER ENDPOINTS

### GET /api/agents/me

Agent info and SOL balance.

```bash
curl -s -H "x-api-key: YOUR_API_KEY" https://plugy.fun/api/agents/me
```

```json
{
  "publicKey": "SolanaAddress...",
  "balance": 1.5,
  "tradeCount": 42,
  "createdAt": "2026-02-19T..."
}
```

### GET /api/agents/balance

SOL balance + all token holdings.

```bash
curl -s -H "x-api-key: YOUR_API_KEY" https://plugy.fun/api/agents/balance
```

```json
{
  "publicKey": "SolanaAddress...",
  "sol": 1.5,
  "tokens": [
    { "mint": "TokenMint...", "balance": 50000.0, "decimals": 6, "tokenAccount": "ATA..." }
  ]
}
```

### GET /api/agents/positions

Live positions with PnL data. Use for take-profit / stop-loss.

```bash
curl -s -H "x-api-key: YOUR_API_KEY" https://plugy.fun/api/agents/positions
```

```json
{
  "publicKey": "SolanaAddress...",
  "sol": 1.45,
  "positions": [
    {
      "mint": "TokenMint...",
      "balance": 50000,
      "tokenName": "ExampleCoin",
      "tokenSymbol": "EXC",
      "currentPriceUsd": 0.000312,
      "entryPriceUsd": 0.000106,
      "currentValueUsd": 15.60,
      "pnlPercent": 194.34,
      "pnlMultiplier": 2.94
    }
  ],
  "summary": { "totalValueUsd": 15.60, "positionCount": 1 }
}
```

### GET /api/signals/public

AI-generated trading signals. **No auth needed.**

```bash
curl -s "https://plugy.fun/api/signals/public?limit=10&minOpportunityScore=70&maxRiskScore=40"
```

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `limit` | number | 30 | Max results (1-50) |
| `minOpportunityScore` | number | — | Min opportunity score (0-100) |
| `maxRiskScore` | number | — | Max risk score (0-100) |
| `sentiment` | string | — | `bullish`, `bearish`, `neutral` |
| `conviction` | string | — | `low`, `medium`, `high` |

Key response fields:
- `decision.opportunityScore` — 0-100, higher = better opportunity
- `decision.riskScore` — 0-100, higher = riskier
- `decision.conviction` — `low`, `medium`, `high`
- `decision.greenFlags` / `decision.redFlags` — qualitative analysis

---

## ERROR HANDLING

If the API returns an error, show the **exact error message** to the user. Do NOT paraphrase.

Common errors:
- `"Insufficient balance"` — user needs to send more SOL
- `"Invalid API key"` — wrong key, check stored key
- `"No bonding curve found"` — token may have migrated, retry

**NEVER fabricate transaction signatures or claim a trade succeeded without a real `txSignature` from the API.**

---

## COMMON MISTAKES

❌ Inventing your own endpoint like `/api/agents/buy` → WRONG
❌ Sending `"pool": "pumpfun"` manually → UNNECESSARY, auto-detected
❌ Using `"denominatedInSol": "true"` → NOT NEEDED for agent API (amount is always SOL for buys)
❌ Sending `mint` with `collectCreatorFee` → NOT NEEDED, fees are per-wallet not per-token
✅ `POST /api/agents/trade` with `"action": "buy"` or `"action": "sell"` → CORRECT
✅ `POST /api/agents/trade` with `"action": "collectCreatorFee"` → CORRECT (no `mint` required)
