Skill: yashagarwal1994/supurr-hyperliquid (version 1.0.0)

--- name: supurr description: Backtest, deploy, and monitor trading bots on Hyperliquid. Supports Grid, DCA, and Spot-Perp Arbitrage strategies across Native Perps, Spot markets (USDC/USDH), and HIP-3 sub-DEXes. --- # Supurr CLI — Complete Command Reference > **For LLMs**: This is the authoritative reference. Use exact syntax. Config files are in `~/.supurr/configs/`. --- ## Quick Reference | Command | Purpose | | ---------------------- | ----------------------------- | | `supurr init` | Setup wallet credentials | | `supurr whoami` | Show current wallet | | `supurr new grid` | Generate grid strategy config | | `supurr new arb` | Generate spot-perp arb config | | `supurr new dca` | Generate DCA strategy config | | `supurr configs` | List saved configs | | `supurr config <name>` | View config details | | `supurr backtest` | Run historical simulation | | `supurr deploy` | Deploy bot to production | | `supurr monitor` | View active bots | | `supurr history` | View historical bot sessions | | `supurr stop` | Stop a running bot (signed) | | `supurr prices` | Debug price data | | `supurr update` | Update CLI to latest | --- ## Global Options ```bash supurr --help # Show all commands supurr --version, -V # Show CLI version supurr -d, --debug # Enable debug logging (any command) ``` --- ## 1. `supurr init` — Credential Setup ```bash # Interactive supurr init # Non-interactive supurr init --address 0x... --api-wallet 0x... # Overwrite existing supurr init --force ``` | Option | Description | | --------------------- | ------------------------------ | | `-f, --force` | Overwrite existing credentials | | `--address <address>` | Wallet address (0x...) | | `--api-wallet <key>` | API wallet private key | --- ## 2. `supurr whoami` — Show Identity ```bash supurr whoami # Shows: Address + masked key ``` --- ## 3. `supurr new <strategy>` — Config Generator Supports three strategies: `grid`, `arb`, `dca`. ```bash supurr new grid [options] # Grid trading supurr new arb [options] # Spot-perp arbitrage supurr new dca [options] # Dollar-cost averaging ``` --- ### 3a. `supurr new grid` — Grid Strategy #### Market Types | Type | Quote | Requires | Example | | -------- | -------- | --------- | --------------------------------------- | | `native` | USDC | — | `--asset BTC` | | `spot` | Variable | `--quote` | `--asset HYPE --type spot --quote USDC` | | `hip3` | Per-DEX | `--dex` | `--asset BTC --type hip3 --dex hyna` | #### Grid Options | Option | Default | Description | | ----------------------- | ------------- | ---------------------------------------------- | | `-a, --asset <symbol>` | `BTC` | Base asset (BTC, ETH, HYPE, etc.) | | `-o, --output <file>` | `config.json` | Output filename | | `--type <type>` | `native` | Market type: native, spot, hip3 | | `--dex <dex>` | — | **Required for hip3**: hyna, xyz, km, vntl | | `--quote <quote>` | — | **Required for spot**: USDC, USDE, USDT0, USDH | | `--mode <mode>` | `long` | Grid mode: long, short, neutral | | `--levels <n>` | `20` | Number of grid levels | | `--start-price <price>` | — | Grid start price | | `--end-price <price>` | — | Grid end price | | `--investment <amount>` | `1000` | Max investment in quote currency | | `--leverage <n>` | `2` | Leverage (1 for spot) | | `--testnet` | false | Use Hyperliquid testnet | #### Grid Examples ```bash # Native Perp (BTC-USDC) supurr new grid --asset BTC --levels 4 --start-price 88000 --end-price 92000 --investment 100 --leverage 20 # USDC Spot (HYPE/USDC) supurr new grid --asset HYPE --type spot --quote USDC --levels 3 --start-price 29 --end-price 32 --investment 100 # Non-USDC Spot (HYPE/USDH) supurr new grid --asset HYPE --type spot --quote USDH --levels 3 --start-price 29 --end-price 32 --investment 100 # HIP-3 (hyna:BTC) supurr new grid --asset BTC --type hip3 --dex hyna --levels 4 --start-price 88000 --end-price 92000 --investment 100 --leverage 20 ``` #### HIP-3 DEXes | DEX | Quote | Assets | | ------ | ----- | ----------------------------------- | | `hyna` | USDE | Crypto perps (BTC, ETH, HYPE, etc.) | | `xyz` | USDE | Stocks (AAPL, TSLA, etc.) | | `km` | USDT | Kinetiq Markets | | `vntl` | USDE | AI/tech tokens | --- ### 3b. `supurr new arb` — Spot-Perp Arbitrage Strategy Generates a config that simultaneously trades the **spot** and **perp** legs of the same asset, capturing spread differentials. > **Market Constraint**: Only assets that have **both** a spot token AND a perp market on Hyperliquid are eligible. The CLI auto-resolves the spot counterpart. #### Spot Resolution Logic Hyperliquid spot tokens for major assets use a `U`-prefix naming convention: | You pass `--asset` | CLI resolves spot token | Spot pair | Perp pair | | ------------------ | ----------------------- | ---------- | ---------- | | `BTC` | `UBTC` | UBTC/USDC | BTC perp | | `ETH` | `UETH` | UETH/USDC | ETH perp | | `SOL` | `USOL` | USOL/USDC | SOL perp | | `ENA` | `UENA` | UENA/USDC | ENA perp | | `WLD` | `UWLD` | UWLD/USDC | WLD perp | | `MON` | `UMON` | UMON/USDC | MON perp | | `MEGA` | `UMEGA` | UMEGA/USDC | MEGA perp | | `ZEC` | `UZEC` | UZEC/USDC | ZEC perp | | `XPL` | `UXPL` | UXPL/USDC | XPL perp | | `PUMP` | `UPUMP` | UPUMP/USDC | PUMP perp | | `HYPE` | `HYPE` (exact name) | HYPE/USDC | HYPE perp | | `TRUMP` | `TRUMP` (exact name) | TRUMP/USDC | TRUMP perp | | `PURR` | `PURR` (exact name) | PURR/USDC | PURR perp | | `BERA` | `BERA` (exact name) | BERA/USDC | BERA perp | Resolution order: try `U{ASSET}` first → fallback to exact name → fail if neither exists. > **⚠️ U-prefix Hazard**: Do NOT pass asset names that already start with `U` (e.g., `UNIT`). The CLI will prepend another `U` and look for `UUNIT`, which doesn't exist. Always use the **perp ticker name** (e.g., `BTC`, not `UBTC`). #### Arb Options | Option | Default | Description | | ---------------------- | ------------------ | -------------------------------------------- | | `-a, --asset <symbol>` | `BTC` | Perp asset name (BTC, ETH, HYPE, etc.) | | `--amount <usdc>` | `100` | Order amount in USDC per leg | | `--leverage <n>` | `1` | Leverage for perp leg | | `--open-spread <pct>` | `0.003` | Min opening spread (0.003 = 0.3%) | | `--close-spread <pct>` | `-0.001` | Min closing spread (-0.001 = -0.1%) | | `--slippage <pct>` | `0.001` | Slippage buffer for both legs (0.001 = 0.1%) | | `-o, --output <file>` | `{asset}-arb.json` | Output filename | | `--testnet` | false | Use Hyperliquid testnet | #### Arb Examples ```bash # BTC spot-perp arb (default $100/leg) supurr new arb --asset BTC # HYPE arb with $50 per leg, 2x leverage on perp supurr new arb --asset HYPE --amount 50 --leverage 2 # ETH arb with tighter spreads supurr new arb --asset ETH --open-spread 0.002 --close-spread -0.0005 --slippage 0.0005 # SOL arb on testnet supurr new arb --asset SOL --testnet ``` > **Balance Requirement**: Arb bots require USDC balance in **both** Spot and Perps wallets on Hyperliquid, since the bot trades on both sides simultaneously. --- ### 3c. `supurr new dca` — DCA Strategy Generates a Dollar-Cost Averaging config that opens positions in steps when price deviates, then takes profit on the averaged entry. #### DCA Options | Option | Default | Description | | ---------------------------- | ------------- | -------------------------------------------------- | | `-a, --asset <symbol>` | `BTC` | Base asset | | `--mode <mode>` | `long` | Direction: long or short | | `--type <type>` | `native` | Market type: native, spot, hip3 | | `--trigger-price <price>` | `100000` | Price to trigger base order | | `--base-order <size>` | `0.001` | Base order size in base asset | | `--dca-order <size>` | `0.001` | DCA order size in base asset | | `--max-orders <n>` | `5` | Max number of DCA orders | | `--size-multiplier <x>` | `2.0` | Size multiplier per DCA step | | `--deviation <pct>` | `0.01` | Price deviation % to trigger first DCA (0.01 = 1%) | | `--deviation-multiplier <x>` | `1.0` | Deviation multiplier for subsequent steps | | `--take-profit <pct>` | `0.02` | Take profit % from avg entry (0.02 = 2%) | | `--stop-loss <pnl>` | — | Optional stop loss as absolute PnL threshold | | `--leverage <n>` | `2` | Leverage (1 for spot) | | `--restart` | false | Restart cycle after take profit | | `--cooldown <secs>` | `60` | Cooldown between cycles in seconds | | `-o, --output <file>` | `config.json` | Output filename | | `--testnet` | false | Use Hyperliquid testnet | #### DCA Examples ```bash # BTC DCA long, trigger at $95k supurr new dca --asset BTC --trigger-price 95000 # ETH DCA short with custom deviation supurr new dca --asset ETH --mode short --deviation 0.02 # HYPE DCA with auto-restart supurr new dca --asset HYPE --restart --cooldown 120 --take-profit 0.03 # DCA on spot market supurr new dca --asset HYPE --type spot --quote USDC --trigger-price 25 ``` --- ## 4. `supurr configs` — List Saved Configs ```bash supurr configs # Lists all configs in ~/.supurr/configs/ ``` **Output:** ``` 📁 Configs (/Users/you/.supurr/configs): btc-grid.json grid BTC-USDC hype-usdc-spot.json grid HYPE-USDC hyna-btc.json grid BTC-USDE ``` --- ## 5. `supurr config <name>` — View Config ```bash supurr config btc-grid # View btc-grid.json supurr config btc-grid.json # Same ``` --- ## 6. `supurr backtest` — Run Backtest ### Syntax ```bash supurr backtest -c <config> [options] ``` ### Options | Option | Description | | --------------------- | ---------------------------------------- | | `-c, --config <file>` | **Required.** Config file (name or path) | | `-s, --start <date>` | Start date (YYYY-MM-DD) | | `-e, --end <date>` | End date (YYYY-MM-DD) | | `-p, --prices <file>` | Use local prices file | | `-o, --output <file>` | Save results to JSON | | `--no-cache` | Disable price caching | ### Examples ```bash # By config name (looks in ~/.supurr/configs/) supurr backtest -c btc-grid.json -s 2026-01-28 -e 2026-02-01 # By full path supurr backtest -c ~/.supurr/configs/btc-grid.json -s 2026-01-28 -e 2026-02-01 # Save results supurr backtest -c btc-grid.json -s 2026-01-28 -e 2026-02-01 -o results.json ``` ### Archive Data Availability | Dex | Asset Format | Example | | ------------- | ---------------------- | ------------------ | | `hyperliquid` | `BTC`, `HYPE` | Native perp + Spot | | `hyna` | `hyna:BTC`, `hyna:ETH` | HIP-3 DEX | > **Note**: Archive data available from 2026-01-28 onwards. > > **Important**: Backtests use Supurr's price archive (tick-level) or a user-provided prices file (`-p`). Do **not** use Hyperliquid Info API mids/candles for backtests; they don't provide tick-level historical data and will produce inaccurate results. --- ## 7. `supurr deploy` — Deploy Bot ```bash supurr deploy -c <config> [-s <address> | -v <address>] ``` | Option | Description | | ---------------------------- | ------------------------------------------------------- | | `-c, --config <file>` | **Required.** Config file (name or path) | | `-s, --subaccount <address>` | Trade from a subaccount (validates master ownership) | | `-v, --vault <address>` | Trade from a vault (validates you are the vault leader) | > **Subaccount vs Vault:** > > - **Subaccount** = personal trading account under your master wallet. Verified via `subAccounts` API (checks `master` field). > - **Vault** = shared investment pool you manage. Verified via `vaultDetails` API (checks `leader` field). > - Both set `vault_address` in the bot config on success. > - **Cannot use both** `--subaccount` and `--vault` simultaneously. ### Examples ```bash # Deploy from main wallet supurr deploy -c btc-grid.json # Deploy from subaccount supurr deploy -c btc-grid.json -s 0x804e57d7baeca937d4b30d3cbe017f8d73c21f1b # Deploy from vault (you must be the vault leader) supurr deploy -c config.json --vault 0xdc89f67e74098dd93a1476f7da79747f71ccb5d9 # HL: prefix is auto-stripped (copy-paste from Hyperliquid UI) supurr deploy -c config.json -s HL:0x804e57d7baeca937d4b30d3cbe017f8d73c21f1b ``` **Output:** ``` ✔ Loaded config for grid strategy ✔ Subaccount verified: 0x804e57d7... ✔ Bot deployed successfully! 📦 Deployment Details Bot ID: 217 Pod Name: bot-217 Bot Type: grid Market: BTC-USDC ``` ### Gotchas | Issue | Solution | | ---------------------------- | -------------------------------------------------------------------------- | | `HL:` prefix in address | Auto-stripped — safe to paste from Hyperliquid explorer | | "Subaccount not owned" | Ensure the subaccount's `master` matches your `supurr whoami` address | | "Vault not found" | Check the vault address exists on the correct network (mainnet vs testnet) | | "Vault leader mismatch" | Only the vault leader can deploy — check `vaultDetails` API | | `subAccounts` returns `null` | Normal — means no subaccounts exist for that address | --- ## 8. `supurr monitor` — View Active Bots ### Syntax ```bash supurr monitor [options] ``` ### Options | Option | Description | | ------------------------ | ------------------------------ | | `-w, --wallet <address>` | Filter by wallet address | | `--watch` | Live mode (refreshes every 2s) | ### Examples ```bash supurr monitor # List all active bots supurr monitor --watch # Live monitoring (Ctrl+C to exit) supurr monitor -w 0x1234... # Filter by wallet ``` **Output Columns:** - **ID** — Bot identifier - **Type** — Strategy (grid, dca, mm, arb) - **Market** — Trading pair (BTC-USDC, HYPE-USDH) - **Position** — Size + direction (L=Long, S=Short) - **PnL** — Total profit/loss --- ## 9. `supurr history` — View Bot History ```bash supurr history # Show last 20 bot sessions supurr history -n 50 # Show last 50 bot sessions ``` | Option | Default | Description | | --------------------- | ------- | ---------------------- | | `-n, --limit <count>` | `20` | Number of bots to show | **Output Columns:** - **ID** — Bot identifier - **Market** — Trading pair (from `config.markets[0]`) - **Type** — Strategy (grid, dca, mm, arb) - **PnL** — Total profit/loss (realized + unrealized) - **Stop Reason** — Why the bot stopped (`shutdown:graceful` → "User stopped the bot Successfully") --- ## 10. `supurr stop` — Stop Bot (Signature Auth) Signs `Stop <bot-id>` with your API wallet private key (EIP-191 personal_sign) and sends the signature to the bot API. ```bash supurr stop # Interactive - select from list supurr stop --id 217 # Stop specific bot by ID ``` | Option | Description | | --------------- | -------------------------------------- | | `--id <bot_id>` | Bot ID to stop (from `supurr monitor`) | > **Crypto:** Uses `@noble/curves/secp256k1` + `@noble/hashes/sha3` (pure JS, no native deps). Signature format: `0x{r}{s}{v}` (65 bytes). --- ## 11. `supurr prices` — Debug Price Data ```bash supurr prices -a BTC # Fetch BTC prices (7 days) supurr prices -a hyna:BTC --dex hyna # HIP-3 prices supurr prices -a HYPE -s 2026-01-28 # From specific date ``` | Option | Description | | ---------------------- | ------------------------------- | | `-a, --asset <symbol>` | **Required.** Asset symbol | | `--dex <dex>` | DEX name (default: hyperliquid) | | `-s, --start <date>` | Start date | | `-e, --end <date>` | End date | | `--no-cache` | Disable caching | --- ## 12. `supurr update` — Self-Update ```bash supurr update # Check and install latest version ``` --- ## Complete Workflows ### Workflow 1: Grid — Backtest → Deploy → Monitor ```bash # 1. Initialize (first time only) supurr init --address 0x... --api-wallet 0x... # 2. Create config supurr new grid --asset BTC --levels 4 --start-price 88000 --end-price 92000 --investment 100 --leverage 20 --output btc-grid.json # 3. Backtest supurr backtest -c btc-grid.json -s 2026-01-28 -e 2026-02-01 # 4. Deploy supurr deploy -c btc-grid.json # 5. Monitor supurr monitor --watch # 6. Stop when done supurr stop --id <bot_id> ``` ### Workflow 2: Arb — Setup → Deploy → Monitor ```bash # 1. Initialize supurr init --address 0x... --api-wallet 0x... # 2. Generate arb config (auto-resolves spot counterpart) supurr new arb --asset BTC --amount 200 --leverage 1 --output btc-arb.json # 3. Review the generated config supurr config btc-arb # 4. Ensure USDC balance in BOTH Spot and Perps wallets on Hyperliquid # 5. Deploy supurr deploy -c btc-arb.json # 6. Monitor supurr monitor --watch ``` ### Workflow 3: DCA — Configure → Deploy ```bash # 1. Create DCA config supurr new dca --asset BTC --trigger-price 95000 --base-order 0.001 --max-orders 5 --take-profit 0.02 --output btc-dca.json # 2. Deploy supurr deploy -c btc-dca.json # 3. Monitor supurr monitor --watch ``` ### Workflow 4: Test All Market Types ```bash # Native Perp supurr new grid --asset BTC --output native-btc.json supurr backtest -c native-btc.json -s 2026-01-28 -e 2026-02-01 # USDC Spot supurr new grid --asset HYPE --type spot --quote USDC --output hype-usdc.json supurr backtest -c hype-usdc.json -s 2026-01-30 -e 2026-01-31 # Non-USDC Spot supurr new grid --asset HYPE --type spot --quote USDH --output hype-usdh.json supurr backtest -c hype-usdh.json -s 2026-01-30 -e 2026-01-31 # HIP-3 supurr new grid --asset BTC --type hip3 --dex hyna --output hyna-btc.json supurr backtest -c hyna-btc.json -s 2026-01-28 -e 2026-02-01 ``` --- ## Config Storage ``` ~/.supurr/ ├── credentials.json # { address, private_key } ├── configs/ # Saved bot configs │ ├── btc-grid.json │ ├── hype-usdc.json │ └── ... └── cache/ # Price data cache └── hyperliquid/ ├── BTC/ └── HYPE/ ``` --- ## API Endpoints Used | Purpose | Endpoint | Auth | | ------------- | --------------------------------------------- | ----------------- | | Bot Deploy | `POST /bots/create/<wallet>` | — | | Active Bots | `GET /dashboard/active_bots` | — | | Bot History | `GET /dashboard/user_bots/<address>` (Python) | — | | Stop Bot | `POST /bots/<bot_id>/stop` (Node) | EIP-191 signature | | Price Data | `GET /prices?dex=X&asset=Y&start_time=Z` | — | | Price Archive | `GET /{dex}/{asset}/{date}.json` | — | --- ## Troubleshooting | Issue | Solution | | ------------------------- | ---------------------------------------------------------------- | | "Config not found" | Use `supurr configs` to list available configs | | "No credentials" | Run `supurr init` first | | "0 prices fetched" | Check date range (data from 2026-01-28+) | | "API wallet not valid" | Register API wallet on Hyperliquid first | | HIP-3 backtest fails | Use format `--dex hyna --asset BTC` | | "No spot market found" | Asset has no spot counterpart — arb not available for this asset | | Arb asset starts with `U` | Use the perp name (e.g., `BTC` not `UBTC`) — CLI adds `U` prefix | --- # Appendix: Hyperliquid Info API > **Backtesting note**: This appendix is for live metadata and user state lookups. It is **not** a source of tick-level historical data for `supurr backtest`. > **Get address via**: `supurr whoami` — returns the configured wallet address. All endpoints use `POST https://api.hyperliquid.xyz/info` with `Content-Type: application/json`. ## Market Data (No Address Required) | Query | Request Body | | ---------------- | ------------------------------------ | | All Mid Prices | `{"type": "allMids"}` | | Sub-DEX Prices | `{"type": "allMids", "dex": "hyna"}` | | Perp Metadata | `{"type": "metaAndAssetCtxs"}` | | Spot Metadata | `{"type": "spotMeta"}` | | L2 Order Book | `{"type": "l2Book", "coin": "BTC"}` | | List HIP-3 DEXes | `{"type": "perpDexs"}` | ## User Data (Address Required) | Query | Request Body | | --------------- | ------------------------------------------------------------------------------ | | Perp Positions | `{"type": "clearinghouseState", "user": "0x..."}` | | Spot Balances | `{"type": "spotClearinghouseState", "user": "0x..."}` | | Open Orders | `{"type": "openOrders", "user": "0x..."}` | | Order History | `{"type": "historicalOrders", "user": "0x..."}` | | Trade Fills | `{"type": "userFills", "user": "0x...", "aggregateByTime": true}` | | Funding History | `{"type": "userFunding", "user": "0x...", "startTime": <ts>, "endTime": <ts>}` | | Sub-Accounts | `{"type": "subAccounts", "user": "0x..."}` | | Vault Details | `{"type": "vaultDetails", "vaultAddress": "0x..."}` | ## HIP-3 Sub-DEXes | DEX | Quote | Assets | | ------ | ----- | ----------------------------- | | `hyna` | USDE | Crypto perps (BTC, ETH, HYPE) | | `xyz` | USDE | Stocks (AAPL, TSLA, NVDA) | | `vntl` | USDE | AI/tech tokens | | `km` | USDT | Kinetiq Markets | | `cash` | USDC | Tech stocks | ## TypeScript Helper ```typescript const HL = "https://api.hyperliquid.xyz/info"; async function query<T>(body: object): Promise<T> { const res = await fetch(HL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); return res.json(); } // Examples const mids = await query({ type: "allMids" }); const positions = await query({ type: "clearinghouseState", user: "0x..." }); const spotBal = await query({ type: "spotClearinghouseState", user: "0x..." }); const dexes = await query({ type: "perpDexs" }); ``` ## Common Hazards | Issue | Solution | | ----------------------- | ------------------------------------------------- | | `szDecimals` truncation | Truncate qty to `szDecimals` before submit | | HIP-3 price prefix | Sub-DEX prices keyed as `hyna:BTC`, not `BTC` | | Sub-DEX asset index | Use local index from DEX's `universe`, not global | | Fill limits | `userFills` max 2000 — paginate with time ranges | --- ## Tutorials Step-by-step deployment guides with parameter selection advice and practical tips: - [Grid Bot Tutorial](tutorials/grid.md) — Range trading with buy/sell grids - [Arb Bot Tutorial](tutorials/arb.md) — Market-neutral spot-perp arbitrage - [DCA Bot Tutorial](tutorials/dca.md) — Dollar-cost averaging with auto-restart

path: README.md
content: # Supurr Skills

> Backtest, deploy, and monitor grid trading bots on Hyperliquid. Supports Native Perps, Spot markets (USDC/USDH), and HIP-3 sub-DEXes.

## Installation

### Option 1: skills.sh (Recommended)

```bash
npx skills add Supurr-App/supurr_skill
```

Supports Claude Code, Cursor, OpenCode, Antigravity, and more.

### Option 2: Direct Install

```bash
# Install AI skill to your tools
curl -fsSL https://cli.supurr.app/skill-install | bash
```

## Also Install: Supurr CLI

The skill teaches AI assistants to use the CLI. The skill installer automatically installs the CLI, but you can also install it manually:

```bash
curl -fsSL https://cli.supurr.app/install | bash
```

## Available Skills

| Skill                | Description                                                       |
| -------------------- | ----------------------------------------------------------------- |
| [supurr](./SKILL.md) | Complete CLI for backtesting, deploying, and monitoring grid bots |

## Quick Start

```bash
# 1. Install CLI
curl -fsSL https://cli.supurr.app/install | bash

# 2. Setup credentials
supurr init --address 0x... --api-wallet 0x...

# 3. Create config
supurr new grid --asset BTC --levels 4 --start-price 88000 --end-price 92000

# 4. Backtest
supurr backtest -c config.json -s 2026-01-28 -e 2026-02-01

# 5. Deploy
supurr deploy -c config.json

# 6. Monitor
supurr monitor --watch
```

## Repository Structure

```
supurr_skill/
├── .claude-plugin/
│   └── plugin.json       # Claude plugin manifest
├── scripts/
│   ├── install.sh        # CLI binary installer
│   └── skill-install.sh  # AI skill installer
├── SKILL.md              # Main skill documentation
└── README.md             # This file
```

## License

MIT


path: tutorials/dca.md
content: # DCA Bot Tutorial

Step-by-step guide to deploying a Dollar-Cost Averaging bot on Hyperliquid.

---

## What is DCA?

A DCA bot opens a base position, then adds to it ("averages in") each time the price moves against you by a set deviation. Once the averaged entry hits your take-profit target, it closes everything and optionally restarts.

**When to use DCA:**

- You have a directional view (bullish or bearish) but uncertain about entry timing
- You want to accumulate during dips (long) or rally fades (short)
- You want automatic position management with defined risk

**When NOT to use DCA:**

- Strong persistent trends against your direction (price keeps falling for long, rising for short)
- You can't afford the max position size at full DCA depth

---

## 1️⃣ Setup Credentials

```bash
supurr init --address 0xYOUR_WALLET --api-wallet 0xYOUR_API_KEY
```

---

## 2️⃣ Understand the DCA Mechanics

DCA works in **cycles**:

```
Trigger Price hit → Base Order → Price drops → DCA Order 1 → Drops more → DCA Order 2 → ... → Take Profit → (restart?)
```

### Key Parameters Explained

| Parameter              | What it Does                          | How to Think About It                                                  |
| ---------------------- | ------------------------------------- | ---------------------------------------------------------------------- |
| `trigger-price`        | Price to start the cycle              | For longs: set at or below current price. For shorts: at or above.     |
| `base-order`           | Initial position size (in base asset) | Your starter position. E.g., 0.001 BTC.                                |
| `dca-order`            | Size of each DCA step                 | Usually same as base order, or slightly larger.                        |
| `max-orders`           | How many DCA steps max                | More orders = deeper averaging but larger total position.              |
| `size-multiplier`      | Multiply DCA size at each step        | `1.0` = flat sizing. `2.0` = each DCA is 2x the previous (aggressive). |
| `deviation`            | Price drop % to trigger first DCA     | `0.01` = 1% drop from entry triggers first DCA.                        |
| `deviation-multiplier` | Widen gaps between DCAs               | `1.0` = equal spacing. `1.5` = each gap 50% wider than previous.       |
| `take-profit`          | % above avg entry to close            | `0.02` = close at 2% profit from averaged entry.                       |
| `stop-loss`            | Absolute PnL to cut losses            | Optional hard stop. Omit to rely only on DCA depth.                    |

### Position Size Planning

Before deploying, calculate your maximum possible position:

```
Max Position = base_order + Σ(dca_order × size_multiplier^i) for i = 0 to max_orders-1
```

**Example with 2x multiplier, 5 max orders:**

- Base: 0.001 BTC
- DCA 1: 0.001 BTC
- DCA 2: 0.002 BTC
- DCA 3: 0.004 BTC
- DCA 4: 0.008 BTC
- DCA 5: 0.016 BTC
- **Total max: 0.032 BTC**

Make sure your account can handle this at max leverage.

---

## 3️⃣ Generate Config

**Example — BTC long DCA, buy dips from $95k:**

```bash
supurr new dca \
  --asset BTC \
  --mode long \
  --trigger-price 95000 \
  --base-order 0.001 \
  --dca-order 0.001 \
  --max-orders 5 \
  --size-multiplier 2.0 \
  --deviation 0.01 \
  --take-profit 0.02 \
  --leverage 5 \
  --restart \
  --cooldown 120 \
  --output btc-dca.json
```

**Example — ETH short DCA, fade rallies:**

```bash
supurr new dca \
  --asset ETH \
  --mode short \
  --trigger-price 4000 \
  --base-order 0.01 \
  --dca-order 0.01 \
  --max-orders 3 \
  --size-multiplier 1.5 \
  --deviation 0.02 \
  --take-profit 0.03 \
  --leverage 3 \
  --output eth-dca-short.json
```

**Example — HYPE spot DCA (no liquidation risk):**

```bash
supurr new dca \
  --asset HYPE \
  --type spot \
  --quote USDC \
  --trigger-price 25 \
  --base-order 10 \
  --dca-order 10 \
  --max-orders 5 \
  --deviation 0.03 \
  --take-profit 0.05 \
  --output hype-dca-spot.json
```

---

## 4️⃣ Deploy

```bash
supurr deploy -c btc-dca.json
```

---

## 5️⃣ Monitor

```bash
supurr monitor --watch
```

DCA bots show one position that grows as DCA orders fill.

---

## Choosing Direction

| Mode    | Direction    | You Expect                  | Trigger Price             |
| ------- | ------------ | --------------------------- | ------------------------- |
| `long`  | Buy dips     | Price to eventually go UP   | At or below current price |
| `short` | Sell rallies | Price to eventually go DOWN | At or above current price |

---

## Restart Behavior

With `--restart`:

- After take-profit, the bot waits `--cooldown` seconds, then starts a new cycle
- Useful for range-bound markets where you want to keep catching bounces

Without `--restart`:

- Bot stops after first take-profit or stop-loss
- Use for one-shot accumulation plays

---

## Tips

- **Start conservative** — use `1.0` size multiplier and `3-5` max orders first
- **2x size multiplier is aggressive** — total position grows exponentially, ensure your margin can handle it
- **Deviation of 1-2%** works well for majors (BTC, ETH). Use 3-5% for higher-volatility assets
- **Always calculate max position** before deploying — the last DCA order is the biggest
- **Use spot for safer DCA** — no liquidation risk, just hold through drawdowns
- **Cooldown of 60-300s** prevents rapid re-entries in choppy markets when using `--restart`


path: tutorials/arb.md
content: # Arb Bot Tutorial

Step-by-step guide to deploying a spot-perp arbitrage bot on Hyperliquid.

---

## What is Spot-Perp Arbitrage?

A spot-perp arb bot exploits price differences between the **spot** and **perpetual futures** market for the same asset. When spot is cheaper than perp (positive spread), it buys spot and shorts perp. When the spread narrows or reverses, it closes both positions for a profit.

This is a **market-neutral** strategy — you're not betting on price direction, only on the spread between two markets.

**When to use Arb:**

- You want low-risk, market-neutral returns
- The asset has consistent spread between spot and perp
- You have capital to allocate to both spot and perp wallets

**When NOT to use Arb:**

- Very tight spreads (fees eat into profits)
- Low-liquidity spot markets (high slippage on entry/exit)

---

## 1️⃣ Setup Credentials

```bash
supurr init --address 0xYOUR_WALLET --api-wallet 0xYOUR_API_KEY
```

---

## 2️⃣ Check Eligible Markets

Not all assets support arb. You need **both** a spot and perp market on Hyperliquid for the same asset.

### Available Arb Pairs (verified)

**U-prefix tokens** (majors with wrapped spot):

| Asset | Spot Token | Spot Pair  | Perp |
| ----- | ---------- | ---------- | ---- |
| BTC   | UBTC       | UBTC/USDC  | BTC  |
| ETH   | UETH       | UETH/USDC  | ETH  |
| SOL   | USOL       | USOL/USDC  | SOL  |
| ENA   | UENA       | UENA/USDC  | ENA  |
| WLD   | UWLD       | UWLD/USDC  | WLD  |
| MON   | UMON       | UMON/USDC  | MON  |
| MEGA  | UMEGA      | UMEGA/USDC | MEGA |
| ZEC   | UZEC       | UZEC/USDC  | ZEC  |
| XPL   | UXPL       | UXPL/USDC  | XPL  |
| PUMP  | UPUMP      | UPUMP/USDC | PUMP |

**Exact-name tokens** (spot name = perp name):

| Asset | Spot Pair  | Perp  |
| ----- | ---------- | ----- |
| HYPE  | HYPE/USDC  | HYPE  |
| TRUMP | TRUMP/USDC | TRUMP |
| PURR  | PURR/USDC  | PURR  |
| BERA  | BERA/USDC  | BERA  |

> **⚠️ Don't pass the spot name directly.** Always use the **perp ticker** (e.g., `--asset BTC`, not `--asset UBTC`). The CLI resolves the spot counterpart automatically.

---

## 3️⃣ Fund Both Wallets

Arb bots trade on **two sides simultaneously**, so you need USDC in both wallets:

1. **Spot wallet** — for buying the spot token
2. **Perps wallet** — for shorting the perpetual

On Hyperliquid, transfer USDC between wallets via: Portfolio → Transfer → Spot ↔ Perps.

> **Rule of thumb**: Split your allocation roughly 50/50 between spot and perps wallets.

---

## 4️⃣ Generate Config

Understand the key parameters:

| Parameter        | What it Controls                | Guidance                                                                                 |
| ---------------- | ------------------------------- | ---------------------------------------------------------------------------------------- |
| `--amount`       | USDC per leg per trade          | Start small ($50-100). This is per-side, so $100 means $100 spot + $100 perp.            |
| `--open-spread`  | Min spread to open a position   | Higher = fewer but safer trades. `0.003` (0.3%) is a good start.                         |
| `--close-spread` | Spread to close the position    | Can be negative (close at a loss on spread if funding compensates). `-0.001` is typical. |
| `--slippage`     | Max acceptable slippage per leg | Keep tight for liquid assets (`0.001`), wider for illiquid (`0.002`+).                   |
| `--leverage`     | Perp leverage                   | `1x` is safest. Higher leverage = more capital efficient but adds liquidation risk.      |

**Example — BTC arb with $200 per leg:**

```bash
supurr new arb \
  --asset BTC \
  --amount 200 \
  --leverage 1 \
  --open-spread 0.003 \
  --close-spread -0.001 \
  --slippage 0.001 \
  --output btc-arb.json
```

**Example — HYPE arb (smaller, tighter spreads):**

```bash
supurr new arb \
  --asset HYPE \
  --amount 50 \
  --leverage 2 \
  --open-spread 0.005 \
  --close-spread 0.001 \
  --slippage 0.002 \
  --output hype-arb.json
```

---

## 5️⃣ Review Config

Before deploying, review the generated config:

```bash
supurr config btc-arb
```

Verify:

- ✅ Two markets listed (spot + perp)
- ✅ Spot token resolved correctly (e.g., `UBTC` for BTC)
- ✅ Spread thresholds match your expectations
- ✅ Environment is `mainnet` (not `testnet`)

---

## 6️⃣ Deploy

```bash
supurr deploy -c btc-arb.json
```

The bot will start monitoring the spread between spot and perp, and execute trades when the spread exceeds your `--open-spread` threshold.

---

## 7️⃣ Monitor

```bash
supurr monitor --watch
```

Arb bots show **two positions** — one spot (long) and one perp (short). The combined PnL is what matters.

---

## Understanding Spreads

```
Spread = (Perp Price - Spot Price) / Spot Price
```

- **Positive spread** (perp > spot): Bot buys spot, shorts perp → earns when spread narrows
- **Negative spread** (perp < spot): Opposite direction

The `open-spread` threshold prevents trading on tiny, unprofitable spreads. The `close-spread` threshold determines when to take profit.

**Example flow:**

1. Spread hits +0.4% → bot opens (buys UBTC spot, shorts BTC perp)
2. Spread narrows to -0.1% → bot closes both positions
3. Net profit ≈ 0.4% + 0.1% = 0.5% minus fees and slippage

---

## Tips

- **BTC and ETH** have the deepest spot liquidity — best for arb
- **Start with 1x leverage** on perps — arb is about consistency, not big swings
- **Watch spot liquidity** — if the spot order book is thin, slippage can kill profits
- **Funding rates matter** — when you're short perp, you receive/pay funding. Positive funding = bonus income for short perp positions
- **Scale gradually** — start with $50-100 per leg, monitor for a day, then increase


path: tutorials/grid.md
content: # Grid Bot Tutorial

Step-by-step guide to deploying a grid trading bot on Hyperliquid.

---

## What is Grid Trading?

A grid bot places a series of buy and sell orders at fixed price intervals (the "grid"), profiting from price oscillations within a range. It earns on every bounce between grid levels — the more the price oscillates, the more it earns.

**When to use Grid:**

- You expect the price to range-bound (move sideways within a band)
- You want passive, automated trading without directional bias
- You want to profit from volatility, not direction

**When NOT to use Grid:**

- Strong trending markets (price breaks out of your grid range)
- Very low volatility (few grid fills = low returns)

---

## 1️⃣ Setup Credentials

```bash
# First time only — saves to ~/.supurr/credentials.json
supurr init --address 0xYOUR_WALLET --api-wallet 0xYOUR_API_KEY
```

> Your API wallet must be registered on Hyperliquid first. Go to Hyperliquid → Settings → API Wallets.

---

## 2️⃣ Choose Your Market

Grid supports 4 market types. Pick based on what you want to trade:

| Market Type     | When to Use                                 | Example                                 |
| --------------- | ------------------------------------------- | --------------------------------------- |
| **Native Perp** | Most liquid markets (BTC, ETH, SOL)         | `--asset BTC`                           |
| **Spot**        | You want spot exposure, no liquidation risk | `--asset HYPE --type spot --quote USDC` |
| **HIP-3**       | Sub-DEX perps (stocks, alt tokens)          | `--asset BTC --type hip3 --dex hyna`    |

---

## 3️⃣ Generate Config

Pick your grid parameters:

| Parameter                       | How to Think About It                                                                                      |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `--start-price` / `--end-price` | The range you expect price to stay in. Check recent support/resistance.                                    |
| `--levels`                      | More levels = more orders = smaller profit per fill but more frequent fills. 10-30 is typical.             |
| `--investment`                  | Total USDC to allocate. Split across all grid levels.                                                      |
| `--leverage`                    | Higher = more capital efficient but higher liquidation risk. Start with 2-5x.                              |
| `--mode`                        | `long` (buy-heavy), `short` (sell-heavy), `neutral` (balanced). Use `long` if bullish, `short` if bearish. |

**Example — BTC range trading between $90k-$100k:**

```bash
supurr new grid \
  --asset BTC \
  --start-price 90000 \
  --end-price 100000 \
  --levels 20 \
  --investment 500 \
  --leverage 5 \
  --mode neutral \
  --output btc-grid.json
```

---

## 4️⃣ Backtest (Recommended)

Before deploying real money, test against historical data:

```bash
supurr backtest -c btc-grid.json -s 2026-01-28 -e 2026-02-01
```

**What to look for in results:**

- **Total PnL** — is the strategy profitable in this range?
- **Number of fills** — more fills = grid is active, few fills = range might be wrong
- **Max drawdown** — can you stomach this risk?

Adjust parameters and re-run until you're satisfied.

---

## 5️⃣ Deploy

```bash
# Deploy from main wallet
supurr deploy -c btc-grid.json

# Or from a subaccount (recommended for isolation)
supurr deploy -c btc-grid.json -s 0xYOUR_SUBACCOUNT

# Or from a vault
supurr deploy -c btc-grid.json -v 0xYOUR_VAULT
```

The CLI will output a Bot ID and Pod Name on success.

---

## 6️⃣ Monitor & Manage

```bash
# Live monitoring (refreshes every 2s)
supurr monitor --watch

# Stop when done
supurr stop --id <bot_id>
```

---

## Tips

- **Tighter range + more levels** = more fills but risk of breakout
- **Wider range + fewer levels** = safer but less frequent fills
- **Use subaccounts** to isolate grid bot funds from your main trading
- **Watch funding rates** on perps — if you're net long/short, funding can eat into profits
- Start with small `--investment` to validate your range, then scale up


path: .claude-plugin/plugin.json
content: name: supurr
version: 0.2.0
description: Supurr Trading Bot CLI - Backtest, Deploy, and Monitor grid trading bots on Hyperliquid

path: scripts/skill-install.sh
content: #!/usr/bin/env bash
# =============================================================================
# Supurr Skill Installer
# Usage: curl -fsSL https://cli.supurr.app/skill-install | bash
# =============================================================================
set -e

REPO="https://github.com/Supurr-App/supurr_skill"

# ANSI colors
BOLD=$'\033[1m'
GREY=$'\033[90m'
RED=$'\033[31m'
GREEN=$'\033[32m'
YELLOW=$'\033[33m'
MAGENTA=$'\033[35m'
CYAN=$'\033[36m'
NC=$'\033[0m'

info() { printf "${BOLD}${GREY}>${NC} %s\n" "$*"; }
warn() { printf "${YELLOW}! %s${NC}\n" "$*"; }
error() { printf "${RED}x %s${NC}\n" "$*" >&2; }
completed() { printf "${GREEN}✓${NC} %s\n" "$*"; }

print_banner() {
  printf "${MAGENTA}"
  cat <<'EOF'
    /\_____/\
   /  o   o  \      ███████╗██╗   ██╗██████╗ ██╗   ██╗██████╗ ██████╗ 
  ( ==  ^  == )     ██╔════╝██║   ██║██╔══██╗██║   ██║██╔══██╗██╔══██╗
   )         (      ███████╗██║   ██║██████╔╝██║   ██║██████╔╝██████╔╝
  (           )     ╚════██║██║   ██║██╔═══╝ ██║   ██║██╔══██╗██╔══██╗
 ( (  )   (  ) )    ███████║╚██████╔╝██║     ╚██████╔╝██║  ██║██║  ██║
(__(__)___(__)__)   ╚══════╝ ╚═════╝ ╚═╝      ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝
EOF
  printf "${NC}\n"
  printf "${BOLD}  Supurr AI Skill Installer${NC}\n\n"
}

print_success() {
  printf "\n${MAGENTA}    /\\_/\\  ${GREEN}═══════════════════════════════════════${NC}\n"
  printf "${MAGENTA}   ( o.o ) ${GREEN}  ✨ Skills Installed Successfully!${NC}\n"
  printf "${MAGENTA}    > ^ <  ${GREEN}═══════════════════════════════════════${NC}\n\n"
}

install_skill() {
  local skills_dir="$1"
  local name="$2"
  local temp_dir="$3"

  mkdir -p "$skills_dir"
  rm -rf "$skills_dir/supurr" 2>/dev/null || true

  if [ -f "$temp_dir/SKILL.md" ]; then
    mkdir -p "$skills_dir/supurr"
    cp "$temp_dir/SKILL.md" "$skills_dir/supurr/"
    cp "$temp_dir/README.md" "$skills_dir/supurr/" 2>/dev/null || true
    completed "$name → ${CYAN}$skills_dir/supurr${NC}"
    return 0
  fi
  return 1
}

# Targets: [dir, name]
declare -a TARGETS=(
  # Universal agents
  "$HOME/.agents/skills|Universal Agents"
  # Individual agents
  "$HOME/.agent/skills|Antigravity"
  "$HOME/.amp/skills|Amp"
  "$HOME/.augment/skills|Augment"
  "$HOME/.claude/skills|Claude Code"
  "$HOME/.cline/skills|Cline"
  "$HOME/.codebuddy/skills|CodeBuddy"
  "$HOME/.codex/skills|OpenAI Codex"
  "$HOME/.commandcode/skills|Command Code"
  "$HOME/.continue/skills|Continue"
  "$HOME/.cursor/skills|Cursor"
  "$HOME/.gemini-cli/skills|Gemini CLI"
  "$HOME/.github-copilot/skills|GitHub Copilot"
  "$HOME/.kimi-code-cli/skills|Kimi Code CLI"
  "$HOME/.config/opencode/skill|OpenCode"
  "$HOME/.openclaw/skills|OpenClaw"
  "$HOME/.roo/skills|Roo"
  "$HOME/.trae/skills|Trae"
  "$HOME/.void/skills|Void"
  "$HOME/.windsurf/skills|Windsurf"
  "$HOME/.zed/skills|Zed"
)

print_banner

# Detect available tools
declare -a FOUND=()
for target in "${TARGETS[@]}"; do
  dir="${target%%|*}"
  parent="${dir%/*}"
  [ -d "$parent" ] && FOUND+=("$target")
done

if [ ${#FOUND[@]} -eq 0 ]; then
  error "No supported AI tools found."
  printf "\nSupported:\n"
  printf "  • Antigravity (~/.agent)\n"
  printf "  • Amp (~/.amp)\n"
  printf "  • Claude Code (~/.claude)\n"
  printf "  • Cline (~/.cline)\n"
  printf "  • Cursor (~/.cursor)\n"
  printf "  • Gemini CLI (~/.gemini-cli)\n"
  printf "  • GitHub Copilot (~/.github-copilot)\n"
  printf "  • OpenAI Codex (~/.codex)\n"
  printf "  • OpenCode (~/.config/opencode)\n"
  printf "  • Windsurf (~/.windsurf)\n"
  printf "  • Zed (~/.zed)\n"
  printf "  • And more...\n"
  exit 1
fi

info "Downloading from ${CYAN}$REPO${NC}..."
temp_dir=$(mktemp -d)
git clone --depth 1 --quiet "$REPO" "$temp_dir"
printf "\n"

installed=0
for target in "${FOUND[@]}"; do
  dir="${target%%|*}"
  name="${target##*|}"
  if install_skill "$dir" "$name" "$temp_dir"; then
    installed=$((installed + 1))
  fi
done

# Local installs (if in a project directory)
if [ "$(pwd)" != "$HOME" ]; then
  declare -a LOCAL_TARGETS=(
    ".claude/skills|Claude Code (local)"
    ".agent/skills|Antigravity (local)"
    ".cursor/skills|Cursor (local)"
  )
  for target in "${LOCAL_TARGETS[@]}"; do
    dir="${target%%|*}"
    name="${target##*|}"
    parent="${dir%/*}"
    if [ -d "./$parent" ]; then
      install_skill "./$dir" "$name" "$temp_dir" && installed=$((installed + 1))
    fi
  done
fi

rm -rf "$temp_dir"

print_success
printf "  ${BOLD}What's installed:${NC}\n"
printf "    • ${CYAN}supurr${NC} skill for Hyperliquid trading bots\n\n"

# Install CLI if not present
if ! command -v supurr &>/dev/null; then
  info "Installing Supurr CLI..."
  curl -fsSL https://cli.supurr.app/install | bash
else
  completed "Supurr CLI already installed: $(supurr --version 2>/dev/null || echo 'unknown')"
fi

printf "\n"
warn "Restart your AI tool(s) to load the skill."
printf "\n"
info "Re-run anytime to update: ${CYAN}curl -fsSL https://cli.supurr.app/skill-install | bash${NC}"
printf "\n"



path: scripts/install.sh
content: #!/usr/bin/env bash
# =============================================================================
# Supurr CLI Installer
# Usage: curl -fsSL https://cli.supurr.app/install | bash
# =============================================================================
set -euo pipefail

# Configuration
SUPURR_DOWNLOAD_URL="${SUPURR_DOWNLOAD_URL:-https://cli.supurr.app/releases}"
INSTALL_DIR="${SUPURR_INSTALL_DIR:-$HOME/.supurr/bin}"

# Colors (only if terminal supports it)
if [[ -t 1 ]]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[0;33m'
    CYAN='\033[0;36m'
    MAGENTA='\033[0;35m'
    BOLD='\033[1m'
    DIM='\033[2m'
    NC='\033[0m'
else
    RED='' GREEN='' YELLOW='' CYAN='' MAGENTA='' BOLD='' DIM='' NC=''
fi

info() { echo -e "${CYAN}→${NC} $1"; }
success() { echo -e "${GREEN}✓${NC} $1"; }
warn() { echo -e "${YELLOW}!${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1" >&2; exit 1; }

# =============================================================================
# Banner with Cat
# =============================================================================

echo ""
echo -e "${MAGENTA}"
cat << 'EOF'
    /\_____/\
   /  o   o  \      ███████╗██╗   ██╗██████╗ ██╗   ██╗██████╗ ██████╗ 
  ( ==  ^  == )     ██╔════╝██║   ██║██╔══██╗██║   ██║██╔══██╗██╔══██╗
   )         (      ███████╗██║   ██║██████╔╝██║   ██║██████╔╝██████╔╝
  (           )     ╚════██║██║   ██║██╔═══╝ ██║   ██║██╔══██╗██╔══██╗
 ( (  )   (  ) )    ███████║╚██████╔╝██║     ╚██████╔╝██║  ██║██║  ██║
(__(__)___(__)__)   ╚══════╝ ╚═════╝ ╚═╝      ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝
EOF
echo -e "${NC}"
echo -e "${BOLD}  ⚡ Trading Bot CLI${NC} ${DIM}— Backtest → Deploy → Monitor${NC}"
echo ""

# =============================================================================
# Detect Platform
# =============================================================================

detect_platform() {
    local os arch
    
    os="$(uname -s)"
    arch="$(uname -m)"
    
    case "$os" in
        Darwin) os="darwin" ;;
        Linux)  os="linux" ;;
        MINGW*|MSYS*|CYGWIN*) error "Windows is not yet supported. Use WSL instead." ;;
        *) error "Unsupported operating system: $os" ;;
    esac
    
    case "$arch" in
        x86_64|amd64) arch="x64" ;;
        arm64|aarch64) arch="arm64" ;;
        *) error "Unsupported architecture: $arch" ;;
    esac
    
    # Check for Rosetta on macOS
    if [[ "$os" == "darwin" && "$arch" == "x64" ]]; then
        if [[ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" == "1" ]]; then
            arch="arm64"
            info "Running under Rosetta, using arm64 binary"
        fi
    fi
    
    echo "${os}-${arch}"
}

# =============================================================================
# Install
# =============================================================================

main() {
    local platform binary_name download_url
    
    platform=$(detect_platform)
    binary_name="supurr-${platform}"
    download_url="${SUPURR_DOWNLOAD_URL}/${binary_name}"
    
    info "Detected platform: ${BOLD}${platform}${NC}"
    info "Downloading from: ${download_url}"
    
    # Create install directory
    mkdir -p "$INSTALL_DIR"
    
    # Download CLI binary
    info "Downloading supurr CLI..."
    if command -v curl &>/dev/null; then
        curl -fsSL "$download_url" -o "$INSTALL_DIR/supurr" || error "Download failed. Check if binary exists at $download_url"
    elif command -v wget &>/dev/null; then
        wget -q "$download_url" -O "$INSTALL_DIR/supurr" || error "Download failed. Check if binary exists at $download_url"
    else
        error "Neither curl nor wget found. Please install one of them."
    fi
    
    # Make executable
    chmod +x "$INSTALL_DIR/supurr"
    success "CLI installed: $INSTALL_DIR/supurr"
    
    # Download bot engine binary
    local bot_download_url="${SUPURR_DOWNLOAD_URL}/bot-${platform}"
    info "Downloading backtest engine..."
    if command -v curl &>/dev/null; then
        curl -fsSL "$bot_download_url" -o "$INSTALL_DIR/bot" 2>/dev/null && {
            chmod +x "$INSTALL_DIR/bot"
            success "Engine installed: $INSTALL_DIR/bot"
        } || {
            warn "Backtest engine not available for $platform (optional)"
        }
    elif command -v wget &>/dev/null; then
        wget -q "$bot_download_url" -O "$INSTALL_DIR/bot" 2>/dev/null && {
            chmod +x "$INSTALL_DIR/bot"
            success "Engine installed: $INSTALL_DIR/bot"
        } || {
            warn "Backtest engine not available for $platform (optional)"
        }
    fi
    
    # =============================================================================
    # Setup PATH
    # =============================================================================
    
    setup_path() {
        local shell_rc=""
        local shell_name=""
        
        # Detect shell config file
        case "${SHELL:-}" in
            */zsh)  shell_rc="$HOME/.zshrc"; shell_name="zsh" ;;
            */bash) shell_rc="$HOME/.bashrc"; shell_name="bash" ;;
            */fish) shell_rc="$HOME/.config/fish/config.fish"; shell_name="fish" ;;
            *) 
                # Try common files
                if [[ -f "$HOME/.zshrc" ]]; then
                    shell_rc="$HOME/.zshrc"; shell_name="zsh"
                elif [[ -f "$HOME/.bashrc" ]]; then
                    shell_rc="$HOME/.bashrc"; shell_name="bash"
                fi
                ;;
        esac
        
        if [[ -z "$shell_rc" ]]; then
            warn "Could not detect shell config. Add this to your shell profile:"
            echo -e "  ${CYAN}export PATH=\"\$HOME/.supurr/bin:\$PATH\"${NC}"
            return
        fi
        
        # Check if already in PATH
        if [[ ":$PATH:" == *":$INSTALL_DIR:"* ]]; then
            success "Already in PATH"
            return
        fi
        
        # Check if already added to rc file
        if grep -q "\.supurr/bin" "$shell_rc" 2>/dev/null; then
            success "PATH entry already in $shell_rc"
            return
        fi
        
        # Add to shell config
        local path_export
        if [[ "$shell_name" == "fish" ]]; then
            path_export='set -gx PATH "$HOME/.supurr/bin" $PATH'
        else
            path_export='export PATH="$HOME/.supurr/bin:$PATH"'
        fi
        
        echo "" >> "$shell_rc"
        echo "# Supurr CLI" >> "$shell_rc"
        echo "$path_export" >> "$shell_rc"
        
        success "Added to $shell_rc"
    }
    
    setup_path
    
    # =============================================================================
    # Verify installation
    # =============================================================================
    
    export PATH="$INSTALL_DIR:$PATH"
    
    if "$INSTALL_DIR/supurr" --version &>/dev/null; then
        success "Installation verified!"
    else
        warn "Binary downloaded but may need additional dependencies"
    fi
    
    # =============================================================================
    # Done!
    # =============================================================================
    
    echo ""
    echo -e "${MAGENTA}    /\\_/\\  ${GREEN}═══════════════════════════════════════${NC}"
    echo -e "${MAGENTA}   ( o.o ) ${GREEN}  ✨ Installation Complete!${NC}"
    echo -e "${MAGENTA}    > ^ <  ${GREEN}═══════════════════════════════════════${NC}"
    echo ""
    echo -e "  ${BOLD}Quick Start:${NC}"
    echo -e "    ${CYAN}supurr init${NC}           ${DIM}# Setup wallet${NC}"
    echo -e "    ${CYAN}supurr new grid${NC}       ${DIM}# Create config${NC}"
    echo -e "    ${CYAN}supurr backtest${NC}       ${DIM}# Test strategy${NC}"
    echo -e "    ${CYAN}supurr deploy${NC}         ${DIM}# Go live!${NC}"
    echo ""
    echo -e "  ${YELLOW}⚠${NC}  Open a new terminal or run: ${CYAN}source ~/.zshrc${NC}"
    echo ""
}

main "$@"


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