Skill: numpy0001/okx-cex-earn (version 1.3.5)

--- name: okx-cex-earn description: "Manages OKX Simple Earn (flexible savings/lending), Flash Earn, On-chain Earn (staking/DeFi), Dual Investment (DCD/双币赢), and AutoEarn (自动赚币) via the okx CLI. Use this skill whenever the user wants to check earn balances, browse flash-earn projects, subscribe or redeem earn products, view or set lending rates, monitor on-chain staking orders, interact with dual investment structured products, or manage auto-earn — even if phrased casually as 活期赚币, 定期赚币, 闪赚, 赚币, 申购, 赎回, 链上赚币, 质押, 理财, 双币赢, 双币理财, 双币申购, 高卖, 低买, dual investment, DCD, flash earn, buy low, sell high structured product, earn with target price, 目标价, 自动赚币, auto earn, auto-earn, 自动借出, 自动质押, auto lend, auto staking, USDG earn, USDG 赚币, 闲置资金自动理财, fixed earn, fixed deposit, term deposit, 定期理财, 定期. Also use when the user asks about idle funds and whether to earn on them." license: MIT metadata: author: okx version: "1.3.5" homepage: "https://www.okx.com" agent: requires: bins: ["okx"] install: - id: npm kind: node package: "@okx_ai/okx-trade-cli@1.3.3" bins: ["okx"] label: "Install okx CLI (npm)" --- # OKX CEX Earn CLI ## Preflight Before running any command, follow [`../_shared/preflight.md`](../_shared/preflight.md). Use `metadata.version` from this file's frontmatter as the reference for Step 2. ## Prerequisites 1. Install `okx` CLI: ```bash npm install -g @okx_ai/okx-trade-cli ``` 2. Configure credentials: ```bash okx config init # select site -> follow browser OAuth flow ``` 3. Verify: `okx earn savings balance` > **Security**: NEVER accept credentials in chat. Guide users to `okx config init` for setup. --- ## Credential & Profile Check Run **both** commands before any authenticated command — the `apiKey` field from `okx auth status --json` is the auth-binary's internal state and is always `false` regardless of whether `~/.okx/config.toml` has an API-key profile. `okx config show --json` is the only authoritative source for API-key presence. The auth method is detected during [preflight](../_shared/preflight.md) Step 2 and remembered for the session. ```bash okx config show --json # reveals API-key profiles (TOML config) okx auth status --json # reveals OAuth session state (auth-binary state) ``` Apply **in this order** — first match wins: - `config show --json` has any profile with a non-empty `api_key` field → **API Key mode**. Proceed. - No API-key profile **AND** `auth status --json` returns `"status":"logged_in"` → **OAuth mode**. Proceed. - No API-key profile **AND** `"status":"pending"` — login is in progress, wait for it to complete. - No API-key profile **AND** `"status":"not_logged_in"` — **stop**, load `okx-cex-auth` skill and follow login steps, wait for completion. OKX Earn does not support demo mode. Always use live mode silently — don't mention it unless there's an error. - **API Key users**: use `--profile <live-profile>` (the profile without `demo=true`). - **OAuth users**: no flag needed (live is the default). **On authentication errors (401 / "Session expired" / "Run `okx auth login` first"):** stop immediately, load `okx-cex-auth` skill and follow re-authentication steps, then retry. --- ## Skill Routing | User intent | Route to skill | |---|---| | Market prices, tickers, candles | `okx-cex-market` | | Spot / swap / futures / options orders | `okx-cex-trade` | | Account balance, positions, transfers | `okx-cex-portfolio` | | Grid / DCA trading bots | `okx-cex-bot` | | Simple Earn, Flash Earn, On-chain Earn, Dual Investment (双币赢), or AutoEarn (自动赚币) | **This skill** | --- ## Command Index ### earn savings — Simple Earn (9 commands) | Command | Type | Auth | Description | |---|---|---|---| | `earn savings balance [ccy]` | READ | Required | Savings balance (all or specific currency). Also fetch fixed-term orders for a complete picture. | | `earn savings purchase --ccy --amt [--rate]` | WRITE | Required | Subscribe funds to Simple Earn (活期) | | `earn savings redeem --ccy --amt` | WRITE | Required | Redeem funds from Simple Earn (活期) | | `earn savings set-rate --ccy --rate` | WRITE | Required | Set minimum lending rate | | `earn savings lending-history` | READ | Required | User's personal lending records with earnings detail | | `earn savings rate-history` | READ | Required | Simple Earn lending rates and fixed-term offers (require auth) | | `earn savings fixed-orders [--ccy] [--state]` | READ | Required | Query fixed-term (定期) orders. States: pending/earning/expired/settled/cancelled | | `earn savings fixed-purchase --ccy --amt --term [--confirm]` | WRITE | Required | Subscribe to Simple Earn Fixed (定期). Without `--confirm`: preview only | | `earn savings fixed-redeem <reqId>` | WRITE | Required | Redeem a fixed-term order (full amount). Only `pending` state orders can be redeemed early | For full command syntax, rate field semantics, and confirmation templates, read `{baseDir}/references/savings-commands.md`. ### earn dcd — Dual Investment / 双币赢 (6 commands) | Command | Type | Auth | Description | |---|---|---|---| | `earn dcd pairs` | READ | Required | Available DCD currency pairs | | `earn dcd products` | READ | Required | Active products with filters | | `earn dcd quote-and-buy --productId --sz --notionalCcy` | WRITE | Required | Atomic subscribe: quote + execute in one step | | `earn dcd order --ordId` | READ | Required | Quick state check for a single order | | `earn dcd orders` | READ | Required | Full order list / history | | `earn dcd redeem-execute --ordId` | WRITE | Required | Two-step early redemption: preview then execute | > DCD does **not** support demo/simulated trading mode. Always use live mode (API Key: `--profile <live-profile>`; OAuth: no flag needed). For full command syntax, product concepts, and error codes, read `{baseDir}/references/dcd-commands.md`. ### earn onchain — On-chain Earn (6 commands) | Command | Type | Auth | Description | |---|---|---|---| | `earn onchain offers` | READ | Required | Available staking/DeFi products | | `earn onchain purchase --productId --ccy --amt` | WRITE | Required | Subscribe to on-chain product | | `earn onchain redeem --ordId --protocolType` | WRITE | Required | Redeem on-chain investment | | `earn onchain cancel --ordId --protocolType` | WRITE | Required | Cancel pending on-chain order | | `earn onchain orders` | READ | Required | Active on-chain orders | | `earn onchain history` | READ | Required | Historical on-chain orders | For full command syntax and parameters, read `{baseDir}/references/onchain-commands.md`. ### earn auto-earn — AutoEarn / 自动赚币 (3 commands) | Command | Type | Auth | Description | |---|---|---|---| | `earn auto-earn status [CCY]` | READ | Required | Query currencies supporting auto-earn and their status | | `earn auto-earn on <CCY>` | WRITE | Required | Enable auto-earn for a currency | | `earn auto-earn off <CCY>` | WRITE | Required | Disable auto-earn for a currency | > **24h restriction:** Cannot disable within 24 hours of enabling (API hard limit). Always warn user before enabling. For full command syntax, earnType inference rules, and MCP tool reference, read `{baseDir}/references/autoearn-commands.md`. ### earn flash-earn — Flash Earn / 闪赚 (1 command) | Command | Type | Auth | Description | |---|---|---|---| | `earn flash-earn projects [--status <0\|100\|0,100>]` | READ | Required | Browse Flash Earn projects by status. `0`=upcoming, `100`=in-progress, default is both | --- ## Operation Flow ### Step 0 — Credential & Profile Check Before any authenticated command: see [Credential & Profile Check](#credential--profile-check). Always use live mode silently. ### Step 1 — Identify earn intent **Simple Earn Flexible (活期):** - Query balance / history / rates → READ command, proceed directly. - Subscribe / redeem / set-rate → WRITE command, go to Step 2. **Simple Earn Fixed (定期):** - Query offers / order list → READ command, proceed directly. - Subscribe (two-step: preview then confirm) / redeem (pending state only) → WRITE command, go to Step 2. Read `{baseDir}/references/savings-commands.md` for pre-execution checklists and confirmation templates. - For multi-step workflows (subscribe with preview, early redemption), read `{baseDir}/references/workflows.md`. **On-chain Earn:** - Query offers / orders / history → READ command, proceed directly. - Purchase / redeem / cancel → WRITE command, go to Step 2. **AutoEarn (自动赚币):** - Query auto-earn status → READ, proceed directly. - Enable / disable auto-earn → WRITE, go to Step 2. Read `{baseDir}/references/autoearn-commands.md` for confirmation templates and earnType inference. **Flash Earn (闪赚):** - Browse projects → READ, proceed directly. - Use `--status 0` for upcoming projects, `--status 100` for in-progress projects, or omit the flag to view both. When user asks to view "earn positions" or "赚币持仓" (regardless of whether they mention DCD explicitly), query all position-bearing sub-modules simultaneously (Flash Earn is query-only, no positions): ```bash okx earn savings balance --json # Simple Earn Flexible (活期) okx earn savings fixed-orders --json # Simple Earn Fixed (定期) okx earn onchain orders --json # On-chain Earn okx earn dcd orders --json # Dual Investment (双币赢) ``` Only present sections that have actual holdings. For DCD: translate state codes using the table in `{baseDir}/references/dcd-commands.md`. **Dual Investment (DCD / 双币赢):** - Browse products / pairs → READ; when user specifies a currency, read `{baseDir}/references/workflows.md` (DCD browse flow) for the mandatory parallel pre-fetch before rendering the product table - Subscribe (quote-and-buy) → WRITE → see `{baseDir}/references/workflows.md` (DCD subscribe flow) - Early redeem → WRITE → see `{baseDir}/references/workflows.md` (DCD early redeem flow) For multi-step workflows (idle fund analysis, subscribe + verify, redeem + transfer, on-chain subscribe), read `{baseDir}/references/workflows.md`. ### Step 2 — Confirm write operation For all WRITE commands, present a summary and wait for explicit confirmation. > "just do it" / "直接搞" is NOT valid confirmation — the user must see the summary first. For Simple Earn confirmation dialog format, read `{baseDir}/references/savings-commands.md`. For On-chain confirmation, read `{baseDir}/references/onchain-commands.md`. ### Step 3 — Execute and verify After any purchase, verify based on product type: - **DCD** `quote-and-buy` succeeded → run `earn dcd orders --json`, show only the matching order. - **On-chain** purchase (response contains `ordId`) → run `earn onchain orders --json`, show only the matching order. - **Simple Earn Flexible** purchase (no `ordId` in response) → run `earn savings balance --ccy <ccy> --json`. - **Simple Earn Fixed** purchase → run `earn savings fixed-orders --ccy <ccy> --state pending --json`, show the new order. **Simple Earn Flexible purchase:** Run in parallel — `earn savings balance --ccy <ccy>` and `earn savings rate-history --ccy <ccy> --limit 1 --json`. For output format, read `{baseDir}/references/savings-commands.md`. **Simple Earn Flexible redeem:** Run `earn savings balance --ccy <ccy>` to confirm updated balance. Inform user funds returned to funding account. **Simple Earn Fixed purchase:** Run `earn savings fixed-orders --ccy <ccy> --state pending --json` to confirm the order was created. Show order details including APR, term, and expected expiry date. **Simple Earn Fixed redeem:** Run `earn savings fixed-orders --json` to confirm the order state changed to `cancelled`. Inform user full principal returned to funding account — no interest earned for early cancellation. **On-chain redeem:** Query `earn onchain orders` to confirm state. Show `estSettlementTime` as estimated arrival time. **On-chain cancel:** Query `earn onchain orders` after submission: - Order gone from list → inform user: cancellation complete, funds returned to funding account. - `state: 3` (cancelling) → inform user: cancellation in progress, funds will return to funding account shortly. --- ## Global Notes - **Security:** Never ask users to paste API keys or secrets into chat. - **Output:** Always pass `--json` to list/query commands and render results as a Markdown table — never paste raw terminal output. - **Network errors:** If commands fail with a connection error, prompt user to check VPN: `curl -I https://www.okx.com` - **Language:** Always respond in the user's language. For number/time formatting and response structure conventions, read `{baseDir}/references/templates.md`.

path: references/workflows.md
content: # Multi-Step Workflows

## Idle fund analysis — check and subscribe

"我有多少闲置资金可以赚币？"

1. `okx --profile live account asset-balance <ccy>` → idle funds in funding account
2. `okx --profile live account balance <ccy>` → idle funds in trading account
3. `okx --profile live earn savings balance <ccy>` → already in earn
4. `okx --profile live earn savings rate-history --ccy <ccy> --limit 1 --json` → current `lendingRate` (actual yield)
→ summarize idle funds and suggest subscribing if lendingRate is acceptable

---

## Subscribe earn then verify

"帮我把资金账户里的 1000 USDT 申购赚币"

1. Run in parallel:
   - `okx --profile live account asset-balance USDT` → verify balance ≥ 1000
   - `okx --profile live earn savings rate-history --ccy USDT --limit 1 --json` → current APY
2. Show confirmation summary (see savings-commands.md), wait for user confirmation
3. `okx --profile live earn savings purchase --ccy USDT --amt 1000`
4. Run in parallel to verify:
   - `okx --profile live earn savings balance USDT --json` → confirm position updated
   - `okx --profile live earn savings rate-history --ccy USDT --limit 1 --json` → show current lendingRate in position summary

---

## Redeem earn and transfer to trading account

"赎回我的 USDT 赚币，划转到交易账户"

1. `okx --profile live earn savings balance USDT` → check redeemable amount; show summary, wait for confirmation
2. `okx --profile live earn savings redeem --ccy USDT --amt <amt>`
3. _(Optional — requires **Withdraw** permission on the API key)_
   `okx --profile live account transfer --ccy USDT --amt <amt> --from 6 --to 18` (CLI account type IDs: 6=funding, 18=trading)

   If step 3 fails with a permission error, inform the user that their API key does not have Withdraw permission and they should complete the transfer manually in the OKX app.

---

## Simple Earn Fixed — subscribe with preview

"帮我申购 USDT 定期赚币，7天" / "subscribe USDT fixed earn for 7 days"

1. Run in parallel:
   - `okx --profile live earn savings rate-history --ccy USDT --json` → verify 7-day term exists and has quota
   - `okx --profile live account asset-balance USDT` → verify balance ≥ requested amount
2. If term not available or sold out → inform user, suggest alternative terms from offers list
3. Preview: `okx --profile live earn savings fixed-purchase --ccy USDT --amt 1000 --term 7D --json` (without `--confirm`)
4. Show confirmation summary (see `savings-commands.md` Fixed-Term Confirmation Templates), wait for user confirmation
5. Execute: `okx --profile live earn savings fixed-purchase --ccy USDT --amt 1000 --term 7D --confirm --json`
6. Verify: `okx --profile live earn savings fixed-orders --ccy USDT --state pending --json` → confirm order created

---

## Simple Earn Fixed — early redemption

"赎回我的定期赚币订单" / "redeem my fixed earn order"

1. `okx --profile live earn savings fixed-orders --json` → display numbered order list; let user pick by number (do not expect them to type reqId manually)
2. Check order state:
   - `pending` → proceed to step 3
   - `earning` → inform user: locked period active, cannot redeem early. Show expiry date.
   - `settled` / `cancelled` → inform user: order already completed
3. Show redemption summary (see `savings-commands.md` Fixed-Term Confirmation Templates), wait for confirmation
4. `okx --profile live earn savings fixed-redeem <id> --json`
5. `okx --profile live earn savings fixed-orders --json` → confirm order cancelled

---

## On-chain earn — subscribe with balance check

"帮我申购 ETH 链上赚币"

1. `okx --profile live account asset-balance ETH` → verify available balance
2. `okx --profile live earn onchain offers --ccy ETH` → show products, compare APY; show summary with risk disclaimer, wait for confirmation
3. `okx --profile live earn onchain purchase --productId <id> --ccy ETH --amt <amt>`
4. `okx --profile live earn onchain orders` → confirm order created

---

## DCD — Browse products with live spot price

"看看双币赢产品" / "看看BTC双币赢"

When user does **not** specify a currency pair, run in parallel:

```bash
okx --profile live earn dcd pairs                                              # supported pairs
okx --profile live market ticker BTC-USDT                                     # spot price
okx --profile live earn dcd products --baseCcy BTC --quoteCcy USDT --optType <C|P>  # default BTC-USDT
```

- Show BTC-USDT as default result
- After table, briefly mention up to 3 other available pairs (e.g. ETH-USDT, XRP-USDT) and ask if the user wants to view them. Respond in the user's language.

When user **specifies** a currency (e.g. "BTC高卖"), run ALL three in parallel **before rendering the table**:

```bash
okx --profile live market ticker {baseCcy}-USDT               # 1. Spot price (MUST)
okx --profile live account asset-balance {ccy}                # 2. Balance (MUST): CALL→baseCcy, PUT→quoteCcy
okx --profile live earn dcd products --baseCcy {baseCcy} --quoteCcy {quoteCcy} --optType {C|P} --json  # 3. Products
```

> ⚠️ Do NOT render the product table until all three are complete. Show spot price and balance above the table.
>
> If balance query fails (e.g. 401 / no credentials): show the product table anyway with spot price, omit the balance line, and note that balance check requires API credentials. Respond in the user's language.

Cross-skill: `okx-cex-market` for spot price, `okx-cex-portfolio` for balance if needed.

---

## DCD — Subscribe (quote-and-buy)

"我想申购高卖BTC，5%的价差，7天以内" / "帮我买这个双币产品"

1. Run parallel pre-display fetch (spot price + balance + products) as above
2. Show product table with ↑X.XX% / ↓X.XX% (2 decimal places) relative to spot, reference APR, term
3. Explain settlement scenarios **before** user selects — fill in ALL placeholders with real values. Respond in the user's language. Example structure (CALL / 高卖):

   ```
   You invest {sz} {notionalCcy} at target price ${strike}:

   ✅ Expiry price < ${strike} (not triggered — not sold):
      Receive {sz} × (1 + yield rate) {baseCcy}

   ⚠️ Expiry price ≥ ${strike} (triggered — sold at target price):
      Receive {sz} × {strike} × (1 + yield rate) {quoteCcy}
      Both principal and yield convert to {quoteCcy}

   The above APR is indicative; actual yield is locked at quote execution.
   ```

4. After user selects product and confirms amount, execute `earn dcd quote-and-buy` immediately — quote and execution happen atomically, no separate confirmation step needed. Respond in the user's language.

5. After `quote-and-buy`: wait 3–5 seconds, then query `earn dcd orders` to confirm. Show locked-in APR and order state.

---

## DCD — Early redemption (two-phase)

"提前赎回第1个订单"

This is the **only DCD WRITE operation requiring explicit user confirmation**.

**Phase 1 — Preview (indicative):**

1. `okx --profile live earn dcd redeem-execute --ordId <id>` — **do NOT run yet**, use `--json` to preview output first if needed, or explain to the user what will happen:
   - Show estimated `redeemSz`, `redeemCcy`, `termRate` (positive = gain, negative = loss) from a prior `earn dcd orders` query
2. Explicitly state (in user's language) that figures are indicative — actual amount is based on the live quote at execution time.
3. Wait for user confirmation

**Phase 2 — Execute (after confirmation):**

4. `okx --profile live earn dcd redeem-execute --ordId <id>`
   - Internally fetches a fresh quote and executes atomically
5. Wait 3–5 seconds, then query `earn dcd orders --ordId <id> --json` to confirm. Show the estimated settlement time from the order response as the expected arrival time. Respond in the user's language.

---

## DCD — Cross-skill: target-price sell workflow

"我想在72000卖出BTC"

1. `okx-cex-market` `okx --profile live market ticker BTC-USDT`
2. `okx --profile live earn dcd products --baseCcy BTC --quoteCcy USDT --optType C --strikeNear 72000`
   → explain CALL mechanics, show table, guide user to select term
3. `okx --profile live earn dcd quote-and-buy --productId <id> --sz <sz> --notionalCcy BTC`

---

## AutoEarn — Check and enable for idle funds

"帮我看看哪些币种可以自动赚币" / "开启 USDT 自动赚币"

1. Run in parallel:
   - `okx --profile live earn auto-earn status --json` → list currencies supporting auto-earn
   - `okx --profile live account balance --json` → get available balance per currency
2. Present as Markdown table, highlight currencies with `off` status that have available balance (from `account balance`)
3. If user wants to enable:
   - Show confirmation with 24h restriction warning (see `autoearn-commands.md`)
   - `okx --profile live earn auto-earn on <ccy>`
   - `okx --profile live earn auto-earn status <ccy> --json` → verify status changed

---

## AutoEarn — Disable

"关闭 SOL 自动赚币"

1. `okx --profile live earn auto-earn status <ccy> --json` → verify currently enabled
2. Show confirmation (see `autoearn-commands.md`)
3. `okx --profile live earn auto-earn off <ccy>`
4. If 24h error → parse timestamp, tell user when they can retry
5. If success → `okx --profile live earn auto-earn status <ccy> --json` → verify

---

## Scheduled Fixed Earn check — periodic monitor and subscribe

"帮我定时检查定期赚币" / "monitor fixed earn for me"

Set up a recurring task (every 4 hours) that checks for available fixed-term offers and recommends fund reallocation. Default currency: USDT; can be customized per user request — replace `<ccy>` below with the target currency.

**Each cycle executes:**

1. `okx --profile live earn savings rate-history --ccy <ccy> --json` → extract fixed-term offers (entries with `term` field); if no offers available or all `soldOut`, end cycle silently
2. If offers exist, run in parallel:
   - `okx --profile live account balance --json` → idle `<ccy>` in trading account
   - `okx --profile live earn savings balance <ccy> --json` → current simple earn position and `lendingRate`
   - `okx --profile live account asset-balance <ccy> --json` → idle `<ccy>` in funding account
3. Compare APY:
   - Fixed-term `rate` vs simple earn `lendingRate` → if fixed-term rate > lendingRate, simple earn funds are candidates
   - Trading account idle `<ccy>` → always a candidate (earning 0%)
   - Funding account idle `<ccy>` → always a candidate (earning 0%)
4. If no candidate funds (all balances are 0, or simple earn lendingRate ≥ all fixed-term rates) → end cycle silently
5. **Notify user** with a summary table:

   Example (USDT):

   ```
   📋 Fixed Earn Opportunity

   Available fixed-term products:
   | Term | APR   | Min Amount | Remaining Quota |
   |------|-------|-----------|-----------------|
   | 7D   | 4.50% | 100       | 50,000          |

   Recommended fund sources:
   | Source               | Available | Current Yield     |
   |----------------------|-----------|-------------------|
   | Trading account USDT | 5,000     | 0% (idle)         |
   | Simple Earn USDT     | 10,000    | 1.82% (flexible)  |
   | Funding account USDT | 2,000     | 0% (idle)         |

   Fixed earn APR 4.50% > current flexible yield 1.82%. Recommend moving idle/low-yield funds into fixed earn.

   Subscribe? Please confirm amount and term.
   ⚠️ Note: Moving funds from the trading account requires **Withdraw** permission on the API key. If your key lacks this permission, you'll need to transfer manually in the OKX app.
   ```

6. Wait for user confirmation (amount, term selection)
7. _(Optional — requires **Withdraw** permission on the API key)_
   If funds are in trading account → `okx --profile live account transfer --ccy <ccy> --amt <amt> --from 18 --to 6` (trading→funding)

   If transfer fails with a permission error, inform the user that their API key does not have Withdraw permission and they should complete the transfer manually in the OKX app.
8. If funds are in simple earn → `okx --profile live earn savings redeem --ccy <ccy> --amt <amt>` (redeem first, funds return to funding account)
9. `okx --profile live earn savings fixed-purchase --ccy <ccy> --amt <amt> --term <term> --json` → preview
10. Show fixed-term confirmation (see `savings-commands.md` Fixed-Term Confirmation Templates), wait for final confirmation
11. `okx --profile live earn savings fixed-purchase --ccy <ccy> --amt <amt> --term <term> --confirm --json`
12. `okx --profile live earn savings fixed-orders --ccy <ccy> --state pending --json` → verify order created

**Setup via `/loop`:** `/loop 4h` then instruct to run this workflow each cycle.

---

## Flash Earn monitor — periodic notification

"有闪赚的时候通知我" / "notify me when flash earn is available"

Set up a recurring task (every 1 hour) that checks for flash earn projects and notifies only when opportunities exist.

**Each cycle executes:**

1. `okx --profile live earn flash-earn projects --status 0,100 --json` → check for upcoming or in-progress projects
2. If result is empty (`[]` or "No flash earn projects") → end cycle silently (**no output**)
3. To avoid duplicate notifications, track previously notified project IDs within the loop session. Only notify for newly appeared projects — skip any project ID already notified in a prior cycle.
4. If new projects exist, notify user:

   ```
   ⚡ Flash Earn Available

   | Project ID | Status      | Start Time        | End Time          | Rewards      |
   |------------|-------------|-------------------|-------------------|-------------|
   | 12345      | In Progress | 2026/4/9 10:00    | 2026/4/9 12:00    | 500 USDT    |

   Go to OKX App to participate in Flash Earn.
   ```

   - Status `0` → Upcoming
   - Status `100` → In Progress, highlight `canPurchase` = true projects
   - For `canPurchase = true` projects, add note: "🟢 Available now"
   - For upcoming projects, show countdown to `beginTime`

**Setup via `/loop`:** `/loop 1h` then instruct to run this workflow each cycle.


path: references/templates.md
content: # Templates & Reference

> All templates below are examples. Translate column names, labels, and notes to the user's language before rendering.

## DCD Product Table Template

```
{baseCcy} current price: ${spotPrice}
Available balance: {balance} {ccy}

Found the following {CALL/PUT} Dual Investment products:

| # | Product | Target Price | vs Spot | Ref APR | Term | Expiry | Min. Size |
|---|---------|-------------|---------|---------|------|--------|-----------|
| 1 | BTC-USDT-260319-72000-C | $72,000 | ↑3.63% | 26.4% | 7d | Mar 19 | 0.001 BTC |
| 2 | BTC-USDT-260319-73000-C | $73,000 | ↑5.08% | 8.3% | 7d | Mar 19 | 0.001 BTC |

Notes:
- Target price closer to spot → higher trigger probability, higher ref APR
- Target price further from spot → lower trigger probability, lower ref APR
- Yield is locked at subscription time regardless of trigger outcome
- APR shown is indicative; actual yield is locked at quote execution and may vary before final confirmation
```

---

## DCD Order List Template

```
| # | Order ID | Product | Term | Invested | Ref APR | Yield | Settlement Amt | Status |
|---|----------|---------|------|---------|---------|-------|---------------|--------|
| 1 | 123 | BTC-USDT-260320-72000-C | 8d | 0.001 BTC | 83.4% | — | — | Active |
```

- Status: always translate using state table in `dcd-commands.md` — never show raw enum
- Settlement amount: show `—` if not yet settled

---

## Simple Earn Fixed Order List Template

```
| # | Order ID | Currency | Amount | Term | APR | Earnings | Status | Purchase Time | Expiry Time |
|---|----------|----------|--------|------|-----|----------|--------|---------------|-------------|
| 1 | req123 | USDT | 1,000 USDT | 7d | 4.50% | 0.86 USDT | Earning | 2026/3/18 10:00 | 2026/3/25 10:00 |
```

- Status: always translate using state table in `savings-commands.md` — never show raw state value
- For `pending` orders: note that early redemption is available
- Earnings: show `—` if not yet accrued

---

## Formatting Reference

- **Numbers:** Full precision with currency unit — e.g. `1,234.567890 USDT`
- **Rates:** As percentage — e.g. `1.16%`
- **Timestamps:** All `ts` fields are Unix ms (UTC). Convert to user's timezone before displaying. If unknown, default to UTC+8 and note it. Format: `YYYY/M/D HH:MM` (e.g. `2026/3/11 14:30`)
- **Response structure:** Conclusion → Evidence → Recommended action
- **Rate limits:** Public endpoints are not rate-limited under normal use. Authenticated endpoints follow standard OKX API limits.


path: references/savings-commands.md
content: # Simple Earn (Savings) Command Reference

## earn savings balance

```bash
okx --profile live earn savings balance           # all currencies
okx --profile live earn savings balance USDT      # specific currency
okx --profile live earn savings balance --json
```

Output fields: `ccy` · `amt` (total held) · `earnings` (cumulative) · `rate` (user's minimum lending rate) · `loanAmt` (actively lent) · `pendingAmt` (awaiting match)

---

## earn savings purchase

Subscribe funds into Simple Earn. Moves real funds.

```bash
okx --profile live earn savings purchase --ccy USDT --amt 1000
okx --profile live earn savings purchase --ccy USDT --amt 1000 --rate 0.02
```

| Parameter | Required | Description |
|---|---|---|
| `--ccy` | Yes | Currency, e.g. USDT |
| `--amt` | Yes | Amount to subscribe |
| `--rate` | No | Minimum acceptable lending rate (decimal). Default: 0.01 (1%, the absolute minimum). |

**Pre-execution checklist:**
1. Check balance: `okx --profile live account asset-balance <ccy>` — verify user has sufficient funds; if insufficient, inform user and stop
2. Fetch rates (in parallel with step 1): `okx --profile live earn savings rate-history --ccy <ccy> --limit 1 --json`
3. Show confirmation summary (see [Confirmation Templates](#confirmation-templates))
4. Wait for user confirmation — if user declines, acknowledge and offer to adjust the amount or currency

---

## earn savings redeem

Withdraw funds from Simple Earn. Moves real funds.

```bash
okx --profile live earn savings redeem --ccy USDT --amt 500
```

| Parameter | Required | Description |
|---|---|---|
| `--ccy` | Yes | Currency to redeem |
| `--amt` | Yes | Amount to redeem |

Pre-execution: show redemption summary (currency, amount, current APY, destination: funding account). Wait for confirmation.

---

## earn savings set-rate

Set the minimum acceptable lending rate.

```bash
okx --profile live earn savings set-rate --ccy USDT --rate 0.01
```

`--rate` is the user's minimum matching threshold — funds are lent only when the market lending rate ≥ this value. The actual yield is always `lendingRate`. Never tell users that lowering their minimum rate reduces earnings — this is incorrect.

---

## earn savings lending-history

Returns the **user's personal lending records** — transactions where the user lent coins and earned interest. This is NOT for querying market rates; use `earn savings rate-history` for market rate data.

```bash
okx --profile live earn savings lending-history
okx --profile live earn savings lending-history --ccy USDT --limit 10
```

Output fields: `ccy` · `amt` (amount lent) · `earnings` (interest earned) · `rate` (rate applied to this record — same as `rate` in rate-history: the market threshold for that period) · `ts`

---

## earn savings rate-history

Requires `--profile live`.

```bash
okx --profile live earn savings rate-history --ccy USDT --limit 1 --json   # current real APY
okx --profile live earn savings rate-history --ccy USDT --limit 30         # recent trend
```

| Parameter | Required | Description |
|---|---|---|
| `--ccy` | No | Filter by currency |
| `--limit` | No | Max results (default 100) |

This endpoint returns both flexible lending rates and fixed-term product offers:

- **Flexible (活期):** `ccy` · `lendingRate` · `ts`
- **Fixed-term (定期):** `ccy` · `term` · `rate` · `minLend` · `lendQuota` (remaining subscribable amount) · `soldOut`

Use this endpoint to check available fixed-term offers before subscribing (verify term exists and has remaining quota).

### Rate Field Semantics

| Field | Meaning |
|---|---|
| `rate` | User's minimum lending rate threshold (set via `set-rate`). Funds are only lent when the market lending rate ≥ this value. This is a filter, not a yield — do NOT display it as APY. |
| `lendingRate` | Actual yield received by lenders. **Always use `lendingRate` as the true APY to show users.** For stablecoins (e.g. USDT/USDC): subject to pro-rata dilution — when eligible supply exceeds borrowing demand, total interest is shared among all eligible lenders. For non-stablecoins: no dilution. |
| `term` | Lock period for fixed-term offers, e.g. `7D`. |
| `rate` (fixed-term) | Annualized rate for fixed-term offers. |
| `minLend` | Minimum subscription amount for a fixed-term offer. |
| `lendQuota` | Remaining subscribable amount for a fixed-term offer. |
| `soldOut` | Whether the offer is sold out (`lendQuota` is `0`). |

For flexible: always display `lendingRate` as the actual yield. Do NOT raise the minimum rate (`rate`) to increase yield — the actual yield (`lendingRate`) is determined by market supply/demand, not the minimum rate setting.
For fixed-term: display `rate` and `term`, check `soldOut` is false (or `lendQuota` > 0) before subscribing.

---

## Confirmation Templates

### Subscribe to Simple Earn

Respond in the user's language. Template (translate fields as needed):

```
Operation: Subscribe to Simple Earn
Currency: USDT
Amount: 1,000 USDT
Actual yield once matched (lendingRate): X.XX%
Your minimum lending rate: 1% (recommended)

Funds are only lent when the market lending rate ≥ your minimum rate.
Once matched, you earn lendingRate (actual yield).

Confirm? (yes / no)
```

### Redeem from Simple Earn

```
Operation: Redeem from Simple Earn
Currency: USDC
Amount: 10.00 USDC
Current actual yield (lendingRate): X.XX% (yield you will stop earning)
Funds will be returned to: funding account (资金账户)

Confirm? (yes / no)
```

---

## Position Summary Template

After Simple Earn purchase, present (translate column names and descriptions to user's language):

| Field | Value |
|---|---|
| Total held | X USDC |
| Cumulative earnings | X USDC |
| Status | Pending match / Lending |
| Amount lent | X USDC |
| Pending match | X USDC |
| Actual yield (lendingRate) | X.XX% |
| Your minimum lending rate | X.XX% (from balance.rate) |

Plain-language status explanations (translate to user's language):
- `pendingAmt > 0`, `loanAmt = 0` → funds are waiting to be matched. The system matches every hour; interest starts accruing in the same hour a match is found.
- `loanAmt > 0` → funds are lent and earning interest; yield settles every hour.

---

# Simple Earn Fixed (定期) Command Reference

## earn savings fixed-orders

Query fixed-term (定期) orders. Returns all orders or filtered by currency/state.

```bash
okx --profile live earn savings fixed-orders --json
okx --profile live earn savings fixed-orders --ccy USDT --json
okx --profile live earn savings fixed-orders --state earning --json
okx --profile live earn savings fixed-orders --ccy USDT --state pending --json
```

| Parameter | Required | Description |
|---|---|---|
| `--ccy` | No | Filter by currency |
| `--state` | No | Filter by order state (see below) |

Output fields: `reqId` · `ccy` · `amt` · `rate` · `term` · `state` · `accruedInterest` · `cTime`

### Order States

| State | 中文 | English | Description |
|---|---|---|---|
| `pending` | 匹配中 | Pending | Order placed, not yet earning. Can be redeemed early (full refund). |
| `earning` | 赚币中 | Earning | Lock period active, earning interest. Cannot be redeemed early. |
| `expired` | 逾期 | Expired | Lock period ended, awaiting settlement. |
| `settled` | 已结算 | Settled | Principal + interest returned to funding account. |
| `cancelled` | 已撤销 | Cancelled | Order was cancelled before it started earning. |

**NEVER expose raw state values** to the user — always translate using the table above.

**Display rules:**
- Render as Markdown table with columns: # · reqId · Currency · Amount · Rate · Term · Status · Accrued Interest · Create Time
- Format timestamps using `YYYY/M/D HH:MM`
- For `pending` orders, note that early redemption is available

---

## earn savings fixed-purchase

Subscribe to Simple Earn Fixed (定期). Two-step process: preview first, then confirm to execute.

```bash
# Step 1: Preview (default — no --confirm flag)
okx --profile live earn savings fixed-purchase --ccy USDT --amt 1000 --term 7D --json

# Step 2: Confirm and execute
okx --profile live earn savings fixed-purchase --ccy USDT --amt 1000 --term 7D --confirm --json
```

| Parameter | Required | Description |
|---|---|---|
| `--ccy` | Yes | Currency to subscribe, e.g. USDT |
| `--amt` | Yes | Amount to subscribe |
| `--term` | Yes | Lock period, e.g. `7D` (must match an available offer term from `rate-history`) |
| `--confirm` | No | Execute the subscription. Without this flag, only a preview is returned. |

**Pre-execution checklist:**
1. Check available offers: `okx --profile live earn savings rate-history --ccy <ccy> --json` — verify the requested term exists and has remaining quota
2. Check balance (in parallel with step 1): `okx --profile live account asset-balance <ccy>` — verify user has sufficient funds in funding account; if insufficient, inform user and stop
3. Preview the order (without `--confirm`): show the locked APR, term, and expected earnings. **Must** include this warning in the preview output: "⚠️ Orders still in 'pending' state can be cancelled before matching completes. Once the status changes to 'earning', funds are LOCKED until maturity — early redemption is NOT allowed."
4. Show confirmation summary (see [Fixed-Term Confirmation Templates](#fixed-term-confirmation-templates))
5. Wait for user confirmation — if user declines, acknowledge and offer to adjust amount or term

**After successful purchase:** Run `okx --profile live earn savings fixed-orders --ccy <ccy> --state pending --json` to verify the order was created. Show the new order details.

---

## earn savings fixed-redeem

Redeem a fixed-term order. Redeems the full amount — partial redemption is not supported. Only orders in `pending` state can be redeemed early.

```bash
okx --profile live earn savings fixed-redeem <reqId> --json
```

| Parameter | Required | Description |
|---|---|---|
| `<reqId>` | Yes | Order ID (positional) from `earn savings fixed-orders` |

**Pre-execution checklist:**
1. Check order state: `okx --profile live earn savings fixed-orders --json` — find the order and verify `state` is `pending`
2. If state is `earning`: inform the user that orders in earning state cannot be redeemed early — they must wait until expiry
3. If state is `pending`: show redemption summary (see [Fixed-Term Confirmation Templates](#fixed-term-confirmation-templates)), wait for confirmation

**After successful redemption:** Run `okx --profile live earn savings fixed-orders --json` to confirm the order state changed to `cancelled`. Inform user that full principal has been returned to the funding account (资金账户). No interest is earned for cancelled orders.

---

## Fixed-Term Confirmation Templates

### Subscribe to Simple Earn Fixed (定期)

Respond in the user's language. Template (translate fields as needed):

```
Operation: Subscribe to Simple Earn Fixed (定期)
Currency: USDT
Amount: 1,000 USDT
Lock period: 7 days
APR: 4.50%
Expected earnings: ≈ X.XX USDT (estimated, based on current APR)
Expiry date: YYYY/M/D (approximate)
Source: Funding account (资金账户)

⚠️ Orders still in 'pending' state can be cancelled before matching completes. Once the status changes to 'earning', funds are LOCKED until maturity — early redemption is NOT allowed.

Confirm? (yes / no)
```

### Redeem Fixed-Term Order (early — pending state only)

```
Operation: Early redemption of Simple Earn Fixed order
Order ID: <reqId>
Currency: USDT
Amount: 1,000 USDT (full refund)
Interest earned: 0 USDT (no interest for early redemption)
Funds will be returned to: Funding account (资金账户)

Note: This order has not yet started earning. Full principal will be refunded.

Confirm? (yes / no)
```

---

## Fixed-Term Position Summary Template

After viewing fixed-term orders, present (translate column names and descriptions to user's language):

| Field | Value |
|---|---|
| Order ID | reqId |
| Currency | USDT |
| Amount | 1,000 USDT |
| Term | 7 days |
| APR | 4.50% |
| Accrued earnings | X.XX USDT |
| Status | Earning (赚币中) |
| Purchase time | YYYY/M/D HH:MM |
| Expiry time | YYYY/M/D HH:MM |

When user asks to view "earn positions" or "赚币持仓", see `SKILL.md` Step 1 for the full query list (includes all earn types).


path: references/dcd-commands.md
content: # DCD Command Reference

## Product Concepts

### Direction

| optType | 中文 | User deposits | Triggered when | If triggered |
|---|---|---|---|---|
| C | 高卖 | baseCcy (e.g. BTC) | expiry price ≥ strike | principal + yield → quoteCcy (USDT) |
| P | 低买 | quoteCcy (e.g. USDT) | expiry price ≤ strike | principal + yield → baseCcy (BTC) |

When triggered, **both principal and yield** are converted — yield does not stay in the original currency.

### Settlement formula

| Direction | Not triggered | Triggered |
|---|---|---|
| C | sz × (1 + rate) in baseCcy | sz × strike × (1 + rate) in quoteCcy |
| P | sz × (1 + rate) in quoteCcy | sz / strike × (1 + rate) in baseCcy |

### Expiry price

Average index price between 15:00–16:00 (UTC+8) on the expiry date — not real-time spot price at expiry.

### Yield vs. probability

- Strike closer to spot → higher trigger probability, higher reference APR
- Strike further from spot → lower trigger probability, lower reference APR
- Reference APR is indicative; actual yield locked at quote execution time

---

## earn dcd pairs

```bash
okx --profile live earn dcd pairs
```

Output fields: `baseCcy` · `quoteCcy` · `optType`
> The API may return duplicate entries for the same (baseCcy, quoteCcy, optType) combination. Deduplicate client-side before displaying.

---

## earn dcd products

```bash
okx --profile live earn dcd products --baseCcy BTC --quoteCcy USDT --optType C
okx --profile live earn dcd products --baseCcy BTC --quoteCcy USDT --optType C --strikeNear 72000 --minYield 0.05 --maxTermDays 7
```

| Parameter | Required | Description |
|---|---|---|
| `--baseCcy` | Yes | Base currency, e.g. BTC |
| `--quoteCcy` | Yes | Quote currency, e.g. USDT |
| `--optType` | Yes | `C` (高卖) or `P` (低买) |
| `--minYield` | No | Minimum annualized yield, e.g. 0.05 = 5% |
| `--strikeNear` | No | Filter strikes within ±10% of this price |
| `--termDays` | No | Exact term in days |
| `--minTermDays` | No | Minimum term in days |
| `--maxTermDays` | No | Maximum term in days |
| `--expDate` | No | YYYY-MM-DD or YYYY-MM-DDTHH:mm |

**User intent → CLI params mapping:**

| User says | CLI params |
|---|---|
| "5%价差" | `--strikeNear <spot × 1.05>` (CALL) / `--strikeNear <spot × 0.95>` (PUT) |
| "年化至少5%" | `--minYield 0.05` |
| "7天以内" | `--maxTermDays 7` |
| "7到30天" | `--minTermDays 7 --maxTermDays 30` |
| "3月27日到期" | `--expDate 2026-03-27` |

**Always use `--json` flag** — parse JSON and render as Markdown table.

**⚠️ Pre-display mandatory (when user specifies a currency):** Before rendering the product table, you MUST fetch all three in parallel — see `{baseDir}/references/workflows.md` "DCD — Browse products" for the complete checklist. The table must not render until spot price AND account balance are both ready.

**Client-side filter:** Remove products where `absYield === ""` or `annualizedYield === ""` — subscription window closed.

**↑/↓ distance from spot calculation:**
- CALL (高卖): `↑ = (strike - spotPrice) / spotPrice × 100`  → e.g. strike $72,000, spot $69,476 → ↑3.63%
- PUT (低买): `↓ = (spotPrice - strike) / spotPrice × 100` → e.g. strike $65,000, spot $69,476 → ↓6.44%
- Always 2 decimal places with ↑ or ↓ prefix

**Default display & sorting:**
- Group by expiry date (nearest first)
- Within each group: CALL → strike ascending; PUT → strike descending
- Show first 20 products; note if more exist
- Use client-side filters to reduce API response (unfiltered can return 120+ items)

**After displaying**, provide a recommendation of exactly 1–2 sentences (not more) covering yield/safety balance, framed as suggestion ("仅供参考"). Do not write a full analysis. If no products match, suggest relaxing `--maxTermDays`, adjusting `--strikeNear`, or removing `--minYield`.

---

## earn dcd quote-and-buy

```bash
okx --profile live earn dcd quote-and-buy --productId BTC-USDT-260327-72000-C --sz 100 --notionalCcy USDT
```

| Parameter | Required | Description |
|---|---|---|
| `--productId` | Yes | From `earn dcd products` |
| `--sz` | Yes | Notional size |
| `--notionalCcy` | Yes | baseCcy or quoteCcy of the product |
| `--clOrdId` | No | Client order ID for idempotency |
| `--minAnnualizedYield` | No | Minimum yield in percent (e.g. 18 = 18%). Order rejected if quote yield is below this. |

**`--json` output structure:**

```json
{
  "quote": { "quoteId": "...", "annualizedYield": "0.185", "absYield": "0.00356", "notionalSz": "0.1", "notionalCcy": "BTC" },
  "order": { "ordId": "...", "state": "initial" },
  "state": { "ordId": "...", "state": "initial", "productId": "...", "strike": "72000", "notionalSz": "0.1", "settleTime": "..." }
}
```

- `quote` — locked yield at time of execution
- `order` — minimal trade confirmation from the placement API (ordId + state only)
- `state` — full order detail from order-status API (adds productId, strike, settleTime, etc.)

> `order` and `state` both contain `ordId` and `state`; `state` is richer and subsumes `order`. Use `state` for display. `order` is included only as a raw trade confirmation in case the follow-up status query fails.

---

## earn dcd order

Quick state check for a single order. Returns lightweight status only — use `earn dcd orders --ordId` for full detail.

```bash
okx --profile live earn dcd order --ordId <id>
```

| Parameter | Required | Description |
|---|---|---|
| `--ordId` | Yes | Order ID to check |

Output fields: `ordId` · `state`

> Prefer `earn dcd orders --ordId <id> --json` for user-facing detail (returns full fields). Use `earn dcd order` only when a quick post-trade state check is needed and full fields are not required.

---

## earn dcd orders

```bash
okx --profile live earn dcd orders --json
okx --profile live earn dcd orders --ordId <id> --json
```

| Parameter | Required | Description |
|---|---|---|
| `--ordId` | No | Specific order (ignores other filters) |
| `--state` | No | Filter by order state (see State translation table below) |
| `--limit` | No | Max results (default 100) |

**Always use `--json` flag** — render JSON as Markdown table, never paste raw CLI output.

**Display columns** (translate to user's language): index · order ID · product · term · invested amount · reference APR · yield · settlement amount (— if not settled) · status

After list: prompt user they can ask to view details or request early redemption for any specific order.

### State translation

| state | 中文 | English |
|---|---|---|
| `initial` | 处理中 | Processing |
| `live` | 待生息 | Active |
| `pending_settle` | 结算中 | Settling |
| `settled` | 已结算 | Settled |
| `pending_redeem` | 赎回处理中 | Redeeming |
| `pending_redeem_booking` | 赎回处理中 | Redeeming |
| `redeemed` | 已赎回 | Redeemed |
| `rejected` | 已拒绝（显示 errorMsg） | Rejected |

**NEVER expose raw state enum values** (e.g. `LIVE`, `SETTLED`) to the user.

---

## earn dcd redeem-execute

```bash
okx --profile live earn dcd redeem-execute --ordId <id>
```

Two-step flow (handled internally):
1. Fetches a fresh redemption quote
2. Immediately executes — no need to manage `quoteId` manually

Output fields: `redeemSz` · `redeemCcy` · `termRate` (positive = gain, negative = loss)

- `redeem-execute` always fetches a fresh quote internally — do NOT pass a `quoteId`
- Check early redemption support: if `redeemStartTime` / `redeemEndTime` are empty → not supported

**Error: "Redemption request isn't within the redemption window."**

When this error occurs, the order exists but the current time is outside the allowed redemption window. Do NOT just surface the raw error. Instead:

1. Run `okx --profile live earn dcd orders --ordId <id> --json` to fetch the order's `redeemStartTime` and `redeemEndTime`
2. Tell the user when the window opens: "Early redemption for this order is available from `{redeemStartTime}` to `{redeemEndTime}`. Please try again after that time."
3. If `redeemStartTime` is empty, the product does not support early redemption at all — inform the user accordingly.

---

## MCP Tool Reference

| Tool | CLI Command |
|---|---|
| `dcd_get_currency_pairs` | `earn dcd pairs` |
| `dcd_get_products` | `earn dcd products` |
| `dcd_subscribe` | `earn dcd quote-and-buy` |
| `dcd_redeem` | `earn dcd redeem-execute` |
| `dcd_get_order_state` | `earn dcd order` (post-buy state check only) |
| `dcd_get_orders` | `earn dcd orders` |

---

## Error Handling

| Error code | Meaning | Retry |
|---|---|---|
| **504** | **Gateway timeout — server may have executed the request** | **NEVER retry WRITE ops. Query `earn dcd orders` first to verify.** |
| 50001 | Service temporarily unavailable | Retry in a few minutes |
| 50026 | System error | Retry in a few minutes |
| 50030 | Account not authorized for DCD | Guide user to complete verification in OKX app |
| 50038 | DCD API feature disabled | Contact OKX support |
| 58004 | Account frozen/blocked | Contact OKX support |
| 58102 | Rate limit exceeded | Back off and retry |
| Other | Explain `msg` field in user's language | — |


path: references/flash-earn-commands.md
content: # Flash Earn (闪赚) Command Reference

## earn flash-earn projects

Browse upcoming or in-progress Flash Earn projects.

```bash
okx --profile live earn flash-earn projects                  # all (upcoming + in-progress)
okx --profile live earn flash-earn projects --status 0       # upcoming only
okx --profile live earn flash-earn projects --status 100     # in-progress only
okx --profile live earn flash-earn projects --status 0,100   # both (explicit)
okx --profile live earn flash-earn projects --json
```

| Parameter | Required | Description |
|---|---|---|
| `--status` | No | Filter by status: `0`=upcoming, `100`=in-progress. Comma-separated for multiple. Defaults to both |
| `--json` | No | Output raw JSON |

### Output fields

`id` · `status` (0=upcoming, 100=in-progress) · `canPurchase` (boolean) · `beginTime` (formatted) · `endTime` (formatted) · `rewards` (array of reward objects with `amt` and `ccy`)

### Edge cases

- **No projects available**: outputs "No flash earn projects" (table mode) or empty JSON array (`[]` in `--json` mode)
- **Invalid status value**: CLI rejects with error message; only `0` and `100` are accepted
- **Empty `--status` flag**: CLI rejects (e.g. `--status ""` is not allowed)
- **Trailing comma**: CLI rejects (e.g. `--status 0,` is not allowed)

---

## MCP Tool Reference

| CLI Command | MCP Tool | Parameters |
|---|---|---|
| `earn flash-earn projects` | `earn_get_flash_earn_projects` | `status` (optional, integer array) — defaults to `[0, 100]` |

### MCP-specific behavior

- The MCP tool accepts `status` as an integer array (e.g. `[0, 100]`), not a comma-separated string
- If `status` is omitted or invalid, the tool defaults to `[0, 100]`
- Response includes enriched `beginTime` / `endTime` fields (formatted from raw `beginTs` / `endTs` timestamps)


path: references/onchain-commands.md
content: # On-chain Earn Command Reference

## earn onchain offers

```bash
okx --profile live earn onchain offers
okx --profile live earn onchain offers --ccy ETH
okx --profile live earn onchain offers --protocolType staking
```

| Parameter | Required | Description |
|---|---|---|
| `--ccy` | No | Filter by currency |
| `--protocolType` | No | `staking` or `defi` |
| `--productId` | No | Specific product |

Key output fields: `productId` · `ccy` · `protocol` · `protocolType` · `apy` · `term` · `minAmt` · `redeemPeriod` · `earningData`

When multiple products exist for the same currency, compare and highlight: APY, protocol, reward structure (`earningData`), redemption period.

---

## earn onchain purchase

Subscribe to an on-chain earn product. Moves real funds to on-chain protocol.

```bash
okx --profile live earn onchain purchase --productId 4013 --ccy ETH --amt 1
okx --profile live earn onchain purchase --productId 4013 --ccy ETH --amt 1 --term 30
```

| Parameter | Required | Description |
|---|---|---|
| `--productId` | Yes | Product ID from `offers` |
| `--ccy` | Yes | Currency to invest |
| `--amt` | Yes | Amount |
| `--term` | Conditional | Days; required for fixed-term products |

**Pre-execution checklist:**
1. Show summary: protocol, currency, amount, lock period, total APY (net of fees), reward breakdown (`earningData`)
2. Show risk disclaimer (mandatory):
   > ⚠️ OKX connects to third-party DeFi protocols and only provides information display and earnings distribution services. OKX is not liable for asset losses caused by smart contract vulnerabilities, hacking, or DeFi project failures.
3. Wait for explicit user confirmation

---

## earn onchain redeem

```bash
okx --profile live earn onchain redeem --ordId 12345 --protocolType staking
okx --profile live earn onchain redeem --ordId 12345 --protocolType staking --allowEarlyRedeem
```

| Parameter | Required | Description |
|---|---|---|
| `--ordId` | Yes | Order ID |
| `--protocolType` | Yes | `staking` or `defi` |
| `--allowEarlyRedeem` | No | Force early exit from a fixed-term product before maturity (may incur penalty) |

### `earlyRedeem` field semantics

`earlyRedeem` is a field on the **order or product**, not the redeem command itself:

| Value | Meaning |
|---|---|
| `false` | No forced-early-exit option available. For **flexible products** (`term: 0`) this is irrelevant — normal redemption is always supported. For **fixed-term products** (`term > 0`) this means the lock cannot be broken early. |
| `true` | Fixed-term product supports forced early exit via `--allowEarlyRedeem`, but a penalty applies. |

**Do NOT show an "early redemption not supported" warning** unless:
- The product is **fixed-term** (`term > 0`), AND
- The user explicitly wants to exit **before maturity**

For **flexible/open-ended products** (`term: 0`), normal redemption is always available — do not mention `earlyRedeem` at all.

**Pre-redeem confirmation** — include in the summary:
- `estSettlementTime` → estimated arrival time
- If `--allowEarlyRedeem` is used on a fixed-term product: explicitly state the penalty applies
- For flexible products: no penalty note needed

> `cancelRedemptionDeadline` is returned by the API but cancelling a redemption is not supported — do not show this field.

---

## earn onchain cancel

Cancel a pending on-chain order (not yet on-chain).

```bash
okx --profile live earn onchain cancel --ordId 12345 --protocolType defi
```

Only for `state: 8` (pending). Orders already on-chain cannot be cancelled — use redeem instead.

---

## earn onchain orders

```bash
okx --profile live earn onchain orders --json
okx --profile live earn onchain orders --ccy ETH --protocolType staking --json
```

Always use `--json` and render results as a Markdown table. Show reward breakdown from `earningData`. Translate state codes using the table below.

### Order States

| State | Meaning |
|---|---|
| `8` | Pending (not yet on-chain) — can be cancelled |
| `9` | On-chain (processing) — cannot be cancelled, use redeem |
| `1` | Earning (active) |
| `2` | Redeeming |
| `3` | Cancelling (cancel submitted, not yet complete) |

---

## earn onchain history

```bash
okx --profile live earn onchain history --json
okx --profile live earn onchain history --ccy ETH --json
okx --profile live earn onchain history --ccy ETH --limit 20 --json
```

| Parameter | Required | Description |
|---|---|---|
| `--ccy` | No | Filter by currency |
| `--limit` | No | Max results (default 100) |

Output fields: `ordId` · `productId` · `ccy` · `amt` · `apy` · `protocol` · `protocolType` · `state` · `earningData` · `redeemAmt` · `redeemTs`


path: references/autoearn-commands.md
content: # AutoEarn (自动赚币) Command Reference

## earn auto-earn status

Query currencies that support auto-earn and their current status.

```bash
okx --profile live earn auto-earn status              # all currencies
okx --profile live earn auto-earn status USDT          # specific currency
okx --profile live earn auto-earn status --ccy USDT    # --ccy flag form
okx --profile live earn auto-earn status --json
```

Output fields: `ccy` · `earnType` (lend+stake or USDG earn) · `autoLend` (status) · `autoStaking` (status) · `invested` (amount in earn) · `matched` (matched amount) · `apr` (annual rate)

---

## earn auto-earn on

Enable auto-earn for a currency. CLI auto-infers earnType — no manual input needed.

```bash
okx --profile live earn auto-earn on USDT
okx --profile live earn auto-earn on --ccy USDT
okx --profile live earn auto-earn on USDG
```

| Parameter | Required | Description |
|---|---|---|
| `CCY` (positional) or `--ccy` | Yes | Currency, e.g. USDT, SOL, USDG |

**Pre-execution checklist:**
1. `okx --profile live earn auto-earn status <ccy> --json` — verify currency supports auto-earn and is not already enabled
2. Show confirmation summary (see [Confirmation Templates](#confirmation-templates))
3. **Warn about 24h restriction** — once enabled, cannot disable for 24 hours
4. Wait for user confirmation

---

## earn auto-earn off

Disable auto-earn for a currency. **Will fail if enabled less than 24 hours ago.**

```bash
okx --profile live earn auto-earn off USDT
okx --profile live earn auto-earn off --ccy USDT
```

| Parameter | Required | Description |
|---|---|---|
| `CCY` (positional) or `--ccy` | Yes | Currency to disable |

**Pre-execution checklist:**
1. `okx --profile live earn auto-earn status <ccy> --json` — verify auto-earn is currently enabled
2. Show confirmation summary
3. Mention 24h restriction — if user just recently enabled, the operation may fail
4. Wait for user confirmation

**On 24h restriction error:** Parse the error message for the unlock timestamp. Tell the user when they can retry.

---

## earnType Inference Rules

The CLI auto-infers earnType. When using the MCP tool `earn_auto_set` directly, the caller must determine earnType:

1. Call `account_get_balance` for the currency
2. Check `autoLendStatus` and `autoStakingStatus` in the balance details:
   - Currency is USDG or BUIDL → `earnType = "1"` (USDG earn)
   - Otherwise, either is NOT `"unsupported"` → `earnType = "0"` (auto-lend+stake)
   - Neither condition met → currency does not support auto-earn

**Invested amount field difference:**
- `earnType = "0"` (normal currencies): read `autoLendAmt` field
- `earnType = "1"` (USDG/BUIDL): read `eq` (equity) field

---

## MCP Tool Reference

| CLI Command | MCP Tool | Parameters |
|---|---|---|
| `earn auto-earn status` | `account_get_balance` | `ccy` (optional) — filter by `autoLendStatus`/`autoStakingStatus` |
| `earn auto-earn on <CCY>` | `earn_auto_set` | `ccy`, `action: "turn_on"`, `earnType` |
| `earn auto-earn off <CCY>` | `earn_auto_set` | `ccy`, `action: "turn_off"`, `earnType` |

---

## Confirmation Templates

Respond in the user's language. Below are the required data points — adapt phrasing to match the conversation language.

### Enable auto-earn

Present before executing `earn auto-earn on`:

- **Currency**: {ccy}
- **Type**: {earnTypeLabel} (auto-lend+stake / USDG earn)
- **Effect**: idle {ccy} will automatically participate in lending/staking
- **⚠️ 24h lock**: cannot disable within 24 hours of enabling

Wait for explicit confirmation.

### Disable auto-earn

Present before executing `earn auto-earn off`:

- **Currency**: {ccy}
- **Type**: {earnTypeLabel}
- **⚠️ 24h restriction**: if enabled less than 24 hours ago, this will fail

Wait for explicit confirmation.


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)