Skill: tinkle-community/nofx (version 1.1.0)

--- name: nofx description: NOFX AI Trading OS integration - crypto market data, AI trading signals, strategy management, trader control, and automated reporting. Use when working with NOFX platform (nofxai.com, nofxos.ai) for crypto trading, market analysis, AI500/AI300 signals, fund flow tracking, OI monitoring, strategy creation, trader management, backtesting, or AI debate arena. --- # NOFX AI Trading Skill Integrate with NOFX - the open-source AI-powered crypto trading operating system. ## Quick Reference | Resource | URL | |----------|-----| | Web Dashboard | https://nofxai.com | | Data API | https://nofxos.ai | | API Docs | https://nofxos.ai/api-docs | | GitHub | https://github.com/NoFxAiOS/nofx | ## Deployment For installation and deployment instructions, see `references/deployment.md`: - One-click install (Linux/macOS/Docker) - Windows installation (Docker Desktop / WSL2) - Railway cloud deployment - Manual installation for developers - Server deployment with HTTPS ## Supported Exchanges For exchange registration links (with fee discounts) and API setup, see `references/exchanges.md`: **CEX**: Binance, Bybit, OKX, Bitget, KuCoin, Gate.io **DEX**: Hyperliquid, Aster DEX, Lighter **AI Models**: DeepSeek, Qwen, OpenAI, Claude, Gemini, Grok, Kimi ## Configuration Store credentials in workspace `skills/nofx/config.json`: ```json { "api_key": "cm_xxxxxx", "web_email": "[REDACTED_SECRET]", "browser_profile": "clawd" } ``` ## 1. Market Data (API) Base URL: `https://nofxos.ai` Auth: `?auth=API_KEY` or `Authorization: Bearer API_KEY` ### AI Signals ```bash # AI500 - High potential coins (score > 70) curl "https://nofxos.ai/api/ai500/list?auth=$KEY" # AI300 - Quantitative flow signals (S/A/B levels) curl "https://nofxos.ai/api/ai300/list?auth=$KEY&limit=10" # Single coin AI analysis curl "https://nofxos.ai/api/ai500/{symbol}?auth=$KEY" ``` ### Fund Flow ```bash # Institution inflow ranking curl "https://nofxos.ai/api/netflow/top-ranking?auth=$KEY&limit=10&duration=1h&type=institution" # Outflow ranking curl "https://nofxos.ai/api/netflow/low-ranking?auth=$KEY&limit=10&duration=1h&type=institution" ``` ### Open Interest ```bash # OI increase ranking curl "https://nofxos.ai/api/oi/top-ranking?auth=$KEY&limit=10&duration=1h" # OI decrease ranking curl "https://nofxos.ai/api/oi/low-ranking?auth=$KEY&limit=10&duration=1h" # OI market cap ranking curl "https://nofxos.ai/api/oi-cap/ranking?auth=$KEY&limit=10" ``` ### Price & Rates ```bash # Price ranking (gainers/losers) curl "https://nofxos.ai/api/price/ranking?auth=$KEY&duration=1h" # Funding rate top (crowded longs) curl "https://nofxos.ai/api/funding-rate/top?auth=$KEY&limit=10" # Funding rate low (crowded shorts) curl "https://nofxos.ai/api/funding-rate/low?auth=$KEY&limit=10" # Long-short ratio anomalies curl "https://nofxos.ai/api/long-short/list?auth=$KEY&limit=10" ``` ### Single Coin Data ```bash # Comprehensive coin data curl "https://nofxos.ai/api/coin/{symbol}?auth=$KEY&include=all" # Order book heatmap curl "https://nofxos.ai/api/heatmap/future/{symbol}?auth=$KEY" ``` Duration options: `1m, 5m, 15m, 30m, 1h, 4h, 8h, 12h, 24h, 2d, 3d, 5d, 7d` ## 2. Strategy Management (Browser) Use browser automation on https://nofxai.com/strategy ### Strategy Structure ```json { "strategy_type": "ai_trading", "language": "en", "coin_source": { "source_type": "ai500|static|oi_top|oi_low|mixed", "static_coins": ["BTC", "ETH"], "use_ai500": true, "ai500_limit": 10 }, "indicators": { "enable_ema": true, "enable_rsi": true, "enable_atr": true, "enable_boll": true, "enable_oi": true, "enable_funding_rate": true, "enable_quant_data": true, "nofxos_api_key": "cm_xxx" }, "risk_control": { "max_position_pct": 10, "stop_loss_pct": 3, "take_profit_pct": 5 }, "prompt_sections": { "role_definition": "...", "entry_standards": "...", "decision_process": "..." } } ``` ### Natural Language Strategy Creation When user describes a strategy in natural language: 1. Parse requirements (coins, indicators, entry/exit rules, risk) 2. Generate StrategyConfig JSON 3. Navigate to Strategy Studio 4. Create new strategy and fill in fields 5. Save and activate ## 3. Trader Management (Browser) Use browser automation on https://nofxai.com/traders ### Actions - **List**: Navigate to /traders, parse trader list - **Create**: Click "Create Trader", select model/exchange/strategy - **Start/Stop**: Click Start/Stop button on trader card - **View**: Click "View" for details and logs ### Trader Config ``` Model: claude|deepseek|gpt|gemini|grok|kimi|qwen Exchange: binance|bybit|okx|bitget|kucoin|gate|hyperliquid|aster|lighter Strategy: Select from strategy list ``` ## 4. Dashboard (Browser) Navigate to https://nofxai.com/dashboard ### Available Data - Account equity and balance - Total P/L (absolute and percentage) - Current positions - Equity curve chart - Trade history - AI decision logs ## 5. Arena - AI Debate (Browser) Navigate to https://nofxai.com/debate ### Create Debate 1. Click "New Debate" 2. Select symbol 3. Select AI models and roles: - Bull: Finds long opportunities - Bear: Finds short opportunities - Analyst: Neutral analysis 4. Run debate rounds 5. Get consensus recommendation ## 6. Backtest (Browser) Navigate to https://nofxai.com/backtest ### Run Backtest 1. Select AI model 2. Select strategy (optional) 3. Enter symbols (comma-separated) 4. Set time range 5. Run and analyze results ## 7. Monitoring & Alerts ### Cron Job for Market Reports ```json { "name": "NOFX Market Report", "schedule": {"kind": "cron", "expr": "*/30 * * * *"}, "sessionTarget": "isolated", "payload": { "kind": "agentTurn", "message": "Fetch NOFX data and generate market report...", "deliver": true, "channel": "telegram", "to": "USER_ID" } } ``` ### Report Contents - 🤖 AI500 signals (coin + score + gain) - 💰 Institution flow TOP10 - 🚀 Price gainers TOP10 - 📈 OI increase TOP10 - 📉 OI decrease TOP10 - ⚠️ Drop alerts ## 8. Common Workflows ### Daily Market Check 1. Fetch AI500/AI300 signals 2. Check institution fund flow 3. Monitor OI changes 4. Identify opportunities ### Strategy Development 1. Analyze market data 2. Define entry/exit rules 3. Create strategy in Studio 4. Backtest with historical data 5. Create trader and start ### Risk Monitoring 1. Check dashboard P/L 2. Review positions 3. Monitor drawdown 4. Adjust or stop traders if needed ## API Response Examples See `references/api-examples.md` for detailed response structures. ## Additional References | Reference | Description | |-----------|-------------| | `references/grid-trading.md` | Grid trading detailed guide with examples | | `references/market-charts.md` | Market page and chart analysis | | `references/multi-account.md` | Multi-account management | | `references/webhooks.md` | Telegram/Discord/Slack notifications | | `references/faq.md` | Frequently asked questions |

path: _meta.json
content: ownerId: kn758k02csbqctt7xcntz6kcfh8106by
slug: nofx
version: 1.0.0
publishedAt: 1770870946306

path: config.example.json
content: {
  "api_key": "cm_xxxxxxxxxxxxxx",
  "web": {
    "url": "https://nofxai.com",
    "email": "[REDACTED_SECRET]",
    "browser_profile": "clawd"
  },
  "report": {
    "enabled": true,
    "interval": "30m",
    "sections": [
      "ai500",
      "ai300",
      "flow",
      "oi_up",
      "oi_down",
      "price_gainers",
      "price_losers"
    ],
    "limits": {
      "ai500": 10,
      "ai300": 10,
      "flow": 10,
      "oi": 10,
      "price": 10
    }
  },
  "alerts": {
    "ai500_new_coin": true,
    "flow_threshold_usd": 10000000,
    "oi_change_threshold_pct": 10,
    "price_change_threshold_pct": 10,
    "pnl_loss_threshold_pct": -5
  },
  "telegram": {
    "enabled": true,
    "chat_id": "YOUR_CHAT_ID"
  }
}


path: references/api-examples.md
content: # NOFX API Response Examples

## AI500 List

```json
{
  "success": true,
  "data": {
    "coins": [
      {
        "pair": "POWERUSDT",
        "score": 87.385,
        "start_time": 1770683700,
        "start_price": 0.25585,
        "last_score": 81.21,
        "max_score": 88.66,
        "max_price": 0.41825,
        "increase_percent": 63.47
      }
    ],
    "count": 3
  }
}
```

## AI300 List

```json
{
  "success": true,
  "data": {
    "coins": [
      {
        "rank": 1,
        "symbol": "ASTER",
        "future_flow": 3341335.19,
        "spot_flow": 525990.18,
        "level": "S"
      },
      {
        "rank": 2,
        "symbol": "BCH",
        "future_flow": 964889.28,
        "spot_flow": 6132.01,
        "level": "A"
      }
    ],
    "count": 10
  }
}
```

## Netflow Ranking

```json
{
  "success": true,
  "data": {
    "count": 10,
    "limit": 10,
    "netflows": [
      {
        "amount": 132692732.74,
        "price": 1950.41,
        "rank": 1,
        "symbol": "ETHUSDT"
      }
    ],
    "rank_type": "top",
    "time_range": "1h",
    "trade": "future",
    "type": "institution"
  }
}
```

## OI Ranking

```json
{
  "success": true,
  "data": {
    "count": 10,
    "exchange": "binance",
    "positions": [
      {
        "current_oi": 1773693.274,
        "net_long": -855488.22,
        "net_short": 647034.16,
        "oi_delta": 11245.82,
        "oi_delta_percent": 0.63,
        "oi_delta_value": 81088700.36,
        "price_delta_percent": 1.74,
        "rank": 1,
        "symbol": "ETHUSDT"
      }
    ],
    "rank_type": "top",
    "time_range": "1h"
  }
}
```

## Price Ranking

```json
{
  "success": true,
  "data": {
    "data": {
      "1h": {
        "top": [
          {
            "pair": "YALAUSDT",
            "symbol": "YALA",
            "price_delta": 0.299,
            "price": 0.01445,
            "future_flow": 10419171.3,
            "spot_flow": 0,
            "oi": 542674993,
            "oi_delta": -144774990,
            "oi_delta_value": -284890.88
          }
        ]
      }
    }
  }
}
```

## Funding Rate

```json
{
  "success": true,
  "data": {
    "count": 10,
    "desc": "Positive funding rate ranking (crowded longs)",
    "rank_type": "top",
    "rates": [
      {
        "rank": 1,
        "symbol": "1000000BOB",
        "funding_rate": 0.160772,
        "mark_price": 0.01228,
        "index_price": 0.01211714,
        "next_funding_time": 1770840000000
      }
    ]
  }
}
```

## Long-Short List

```json
{
  "success": true,
  "data": {
    "coins": [
      {
        "rank": 1,
        "symbol": "POWER",
        "score": 87.385,
        "start_time": 1770683700,
        "start_price": 0.25585,
        "current_price": 0.37214,
        "price_change_pct": 45.45,
        "max_price": 0.41825,
        "max_score": 88.66
      }
    ]
  }
}
```

## OI Market Cap Ranking

```json
{
  "success": true,
  "data": {
    "count": 10,
    "exchange": "binance",
    "rankings": [
      {
        "rank": 1,
        "symbol": "BTC",
        "oi": 81014.876,
        "oi_value": 5427696936.96,
        "price": 66996.3,
        "net_long": -46092.98,
        "net_short": 37709.32
      }
    ]
  }
}
```

## Heatmap

```json
{
  "success": true,
  "data": {
    "count": 10,
    "heatmaps": [
      {
        "rank": 1,
        "symbol": "ETH",
        "bid_volume": 48294621.13,
        "ask_volume": 59703654.08,
        "delta": -11409032.95
      }
    ],
    "trade": "future"
  }
}
```

## Single Coin Data

```json
{
  "success": true,
  "data": {
    "symbol": "BTCUSDT",
    "price": 67106.6,
    "price_change": {
      "1h": 0.015,
      "4h": 0.023,
      "24h": 0.045
    },
    "netflow": {
      "institution": {
        "1h": 26510000,
        "4h": 85000000
      },
      "personal": {
        "1h": -5000000
      }
    },
    "oi": {
      "binance": {
        "oi": 81000,
        "oi_delta_percent": 0.5,
        "oi_delta_value": 37000000
      }
    },
    "ai500": {
      "score": 72.5,
      "is_active": true
    }
  }
}
```


path: references/browser-automation.md
content: # NOFX Browser Automation Guide

## Prerequisites

- Browser profile `clawd` should be logged into nofxai.com
- Use `browser` tool with `profile: "clawd"`

## Page Navigation

| Page | URL | Purpose |
|------|-----|---------|
| Dashboard | /traders | Main dashboard, trader list |
| Data | /data | Real-time data terminal |
| Market | /market | Market charts |
| Config | /config | AI models & exchanges |
| Strategy | /strategy | Strategy studio |
| Leaderboard | /leaderboard | Competition ranking |
| Arena | /debate | AI debate sessions |
| Backtest | /backtest | Backtest lab |

## Common Actions

### List Traders

```javascript
// Navigate to dashboard
browser.navigate("https://nofxai.com/traders")
browser.snapshot()
// Parse trader cards from snapshot
```

### Start/Stop Trader

```javascript
// Find trader card by name
// Look for "Start" or "Stop" button ref
browser.act({kind: "click", ref: "startButtonRef"})
```

### Create New Trader

1. Navigate to /traders
2. Click "Create Trader" button
3. Fill in form:
   - Select AI Model (dropdown)
   - Select Exchange (dropdown)
   - Select Strategy (dropdown)
   - Enter name
4. Click Create

### View Dashboard

1. Navigate to /dashboard
2. Select trader from dropdown
3. Read equity, P/L, positions from snapshot

### Create Strategy

1. Navigate to /strategy
2. Click "New Strategy"
3. Fill in:
   - Strategy name
   - Description
   - Strategy type (AI Trading / Grid Trading)
   - Coin source configuration
   - Indicators
   - Risk control
   - Custom prompt
4. Click Save

### Export Strategy

1. Navigate to /strategy
2. Find strategy in list
3. Click Export button
4. Strategy JSON is downloaded

### Import Strategy

1. Navigate to /strategy
2. Click Import button
3. Paste or upload JSON
4. Click Import

### Create Debate

1. Navigate to /debate
2. Click "New Debate"
3. Select symbol
4. Configure AI models and roles
5. Start debate

### Run Backtest

1. Navigate to /backtest
2. Click "New Backtest"
3. Select AI model
4. Select strategy (optional)
5. Enter symbols
6. Set time range
7. Click Run

## Element Reference Patterns

### Navigation Buttons

```
button "Data" [ref=eXX]
button "Market" [ref=eXX]
button "Config" [ref=eXX]
button "Dashboard" [ref=eXX]
button "Strategy" [ref=eXX]
button "Leaderboard" [ref=eXX]
button "Arena" [ref=eXX]
button "Backtest" [ref=eXX]
```

### Trader Card Actions

```
button "View" [ref=eXX]
button "Edit" [ref=eXX]
button "Start" [ref=eXX]
button "Stop" [ref=eXX]
```

### Form Elements

```
textbox [ref=eXX]: Input field
combobox [ref=eXX]: Dropdown select
button [ref=eXX]: Action button
```

## Tips

1. Always use `snapshot()` after navigation to get current page state
2. Look for `[active]` attribute to identify selected items
3. Check for `[disabled]` before clicking buttons
4. Use `maxChars` parameter to limit snapshot size for large pages
5. Parse text content from snapshot to extract data


path: references/deployment.md
content: # NOFX 部署指南

## 快速部署

### 一键安装 (Linux/macOS)

```bash
curl -fsSL https://raw.githubusercontent.com/NoFxAiOS/nofx/main/install.sh | bash
```

安装完成后访问: **http://127.0.0.1:3000**

### Docker Compose

```bash
# 下载并启动
curl -O https://raw.githubusercontent.com/NoFxAiOS/nofx/main/docker-compose.prod.yml
docker compose -f docker-compose.prod.yml up -d

# 管理命令
docker compose -f docker-compose.prod.yml logs -f      # 查看日志
docker compose -f docker-compose.prod.yml restart      # 重启
docker compose -f docker-compose.prod.yml down         # 停止
docker compose -f docker-compose.prod.yml pull && docker compose -f docker-compose.prod.yml up -d  # 更新
```

### Railway 一键云部署

[![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/nofx?referralCode=nofx)

## Windows 安装

### 方法 1: Docker Desktop (推荐)

1. 下载安装 [Docker Desktop](https://www.docker.com/products/docker-desktop/)
2. 启动 Docker Desktop
3. PowerShell 运行:
```powershell
curl -o docker-compose.prod.yml https://raw.githubusercontent.com/NoFxAiOS/nofx/main/docker-compose.prod.yml
docker compose -f docker-compose.prod.yml up -d
```

### 方法 2: WSL2

1. 安装 WSL2:
```powershell
wsl --install
```

2. 安装 Ubuntu，然后在 WSL2 中运行一键安装脚本

## 手动安装 (开发者)

### 前置要求

- Go 1.21+
- Node.js 18+
- TA-Lib

```bash
# macOS
brew install ta-lib

# Ubuntu/Debian
sudo apt-get install libta-lib0-dev
```

### 安装步骤

```bash
# 1. 克隆仓库
git clone https://github.com/NoFxAiOS/nofx.git
cd nofx

# 2. 安装后端依赖
go mod download

# 3. 安装前端依赖
cd web && npm install && cd ..

# 4. 构建并启动后端
go build -o nofx && ./nofx

# 5. 启动前端 (新终端)
cd web && npm run dev
```

## 服务器部署

### 快速部署 (HTTP)

默认禁用传输加密，可直接通过 IP 访问:

```bash
curl -fsSL https://raw.githubusercontent.com/NoFxAiOS/nofx/main/install.sh | bash
# 访问: http://YOUR_SERVER_IP:3000
```

### HTTPS (Cloudflare)

1. 添加域名到 Cloudflare
2. 创建 DNS A 记录指向服务器 IP，开启代理 (橙色云)
3. SSL/TLS 设置为 Flexible
4. 编辑 `.env` 设置 `TRANSPORT_ENCRYPTION=true`
5. 访问: `https://nofx.yourdomain.com`

## 更新

每日运行以获取最新版本:

```bash
curl -fsSL https://raw.githubusercontent.com/NoFxAiOS/nofx/main/install.sh | bash
```

## 初始配置

1. **配置 AI 模型** - 添加 API Key
2. **配置交易所** - 设置交易所 API
3. **创建策略** - 在 Strategy Studio 配置
4. **创建 Trader** - 组合 AI + 交易所 + 策略
5. **开始交易** - 启动 Trader


path: references/exchanges.md
content: # NOFX Supported Exchanges

## CEX Centralized Exchanges

| Exchange | Registration Link (Referral) | Status |
|----------|------------------------------|--------|
| **Binance** | [Register](https://www.binance.com/join?ref=NOFXENG) | ✅ Supported |
| **Bybit** | [Register](https://partner.bybit.com/b/83856) | ✅ Supported |
| **OKX** | [Register](https://www.okx.com/join/1865360) | ✅ Supported |
| **Bitget** | [Register](https://www.bitget.com/referral/register?from=referral&clacCode=c8a43172) | ✅ Supported |
| **KuCoin** | [Register](https://www.kucoin.com/r/broker/CXEV7XKK) | ✅ Supported |
| **Gate.io** | [Register](https://www.gatenode.xyz/share/VQBGUAxY) | ✅ Supported |

## DEX Decentralized Perpetual Exchanges

| Exchange | Registration Link | Status |
|----------|------------------|--------|
| **Hyperliquid** | [Register](https://app.hyperliquid.xyz/join/AITRADING) | ✅ Supported |
| **Aster DEX** | [Register](https://www.asterdex.com/en/referral/fdfc0e) | ✅ Supported |
| **Lighter** | [Register](https://app.lighter.xyz/?referral=68151432) | ✅ Supported |

## Supported AI Models

| Model | Get API Key | Recommendation |
|-------|------------|----------------|
| **DeepSeek** | [Get](https://platform.deepseek.com) | ⭐ High cost-effectiveness |
| **Qwen** | [Get](https://dashscope.console.aliyun.com) | Chinese optimized |
| **OpenAI (GPT)** | [Get](https://platform.openai.com) | General purpose strong |
| **Claude** | [Get](https://console.anthropic.com) | Strong reasoning |
| **Gemini** | [Get](https://aistudio.google.com) | Free quota |
| **Grok** | [Get](https://console.x.ai) | Emerging |
| **Kimi** | [Get](https://platform.moonshot.cn) | Strong Chinese |

## Exchange API Configuration

### Binance

1. Login to Binance
2. Go to API Management: User Center → API Management
3. Create API → System Generated
4. Enable permissions:
   - ✅ Read
   - ✅ Spot & Margin Trading
   - ✅ Futures Trading
5. IP Whitelist (recommended): Add server IP
6. Copy API Key and Secret

### Bybit

1. Login to Bybit
2. Go to API: Account → API Management
3. Create New API
4. Permission settings:
   - ✅ Derivatives - Order
   - ✅ Derivatives - Position
5. Bind IP (optional)

### OKX

1. Login to OKX
2. Go to API: User Center → API
3. Create V5 API
4. Permissions:
   - ✅ Read
   - ✅ Trade
5. Set Passphrase (must remember)

### Gate.io

1. Login to Gate.io
2. Go to API: User Center → API Management
3. Create API Key
4. Permissions:
   - ✅ Spot Trading
   - ✅ Futures Trading
   - ✅ Withdrawal (optional, recommended to disable)

### Hyperliquid

1. Visit [Hyperliquid](https://app.hyperliquid.xyz)
2. Connect wallet
3. Go to API: Settings → API
4. Create API Key (requires signature authorization)

### Aster DEX

1. Visit [Aster DEX](https://www.asterdex.com)
2. Connect wallet
3. Settings → API Management
4. Create Trading API

## Security Recommendations

1. **Enable IP Whitelist** - Only allow server IP access
2. **Principle of Least Privilege** - Only enable necessary permissions
3. **Disable Withdrawal Permission** - Unless absolutely necessary
4. **Regular API Key Rotation** - Update monthly
5. **Use Independent Sub-accounts** - Isolate trading funds
6. **Set Reasonable Leverage** - Recommend ≤5x

path: references/faq.md
content: # NOFX Frequently Asked Questions (FAQ)

## Installation & Deployment

### Q: What to do if installation fails?

**Checklist:**
1. Is Docker installed and running?
2. Is port 3000 occupied?
3. Can network access GitHub?

**Solutions:**
```bash
# Check Docker
docker --version

# Check port
lsof -i :3000

# Manually pull image
docker pull nofxai/nofx:latest
```

### Q: How to update to latest version?

```bash
# Re-run installation script
curl -fsSL https://raw.githubusercontent.com/NoFxAiOS/nofx/main/install.sh | bash
```

### Q: Will data be lost?

No. Data is stored in Docker volume, updates don't affect data.

---

## API Issues

### Q: API returns 403 Forbidden?

**Reasons:**
1. API Key invalid or expired
2. Request rate exceeded (>30/s)
3. IP temporarily banned

**Solutions:**
1. Check if API Key is correct
2. Reduce request frequency
3. Wait a few minutes then retry

### Q: Where to get API Key?

Visit https://nofxos.ai/api-docs, displayed at top of page.

### Q: API request timeout?

1. Check network connection
2. Use proxy (if necessary)
3. Increase timeout duration

---

## Exchange Configuration

### Q: Error after configuring API Key?

**Check:**
1. Are API Key and Secret copied completely
2. Are permissions enabled (read + trade)
3. Is IP whitelist configured
4. OKX requires additional Passphrase

### Q: Why "Insufficient Balance" error?

1. Account balance insufficient
2. Margin insufficient
3. Position limit exceeded

### Q: Does it support demo trading?

Some exchanges support it:
- Binance: Need to apply for testnet API
- Bybit: Supports demo trading mode
- OKX: Supports demo trading

---

## Strategy Issues

### Q: Strategy doesn't trigger trades?

**Check:**
1. Is Trader started?
2. Is strategy activated?
3. Are market conditions met?
4. Check AI decision logs

### Q: How to optimize strategy?

1. Backtest different parameters
2. Analyze historical trades
3. Adjust risk control parameters
4. Reference AI suggestions

### Q: What to do if strategy loses money?

1. Check strategy logic
2. Analyze loss reasons
3. Reduce position/leverage
4. Consider pausing trading

---

## Trader Issues

### Q: Trader fails to start?

**Common reasons:**
1. Exchange API configuration error
2. AI model API Key invalid
3. Strategy configuration issues

**Troubleshooting steps:**
1. Check Trader logs
2. Verify exchange connection
3. Test AI model response

### Q: Trader doesn't place orders?

1. Check account balance
2. Check AI decision logs
3. Confirm market conditions
4. Check risk control limits

### Q: How to view Trader logs?

Dashboard → Select Trader → View AI Decision Logs

---

## Grid Trading

### Q: Grid profit not ideal?

1. Check price range settings
2. Adjust grid quantity
3. Consider if market suits grid

### Q: What if price breaks boundaries?

1. System auto stop-loss (if configured)
2. Manually adjust boundaries
3. Consider pausing grid

### Q: Do grid and AI strategy conflict?

No conflict. Can run simultaneously:
- Grid strategy for ranging
- AI strategy for trending

---

## Security Issues

### Q: Is funding safe?

1. NOFX doesn't custody funds
2. Funds always remain at exchange
3. Recommend disabling withdrawal permissions
4. Use IP whitelist

### Q: How to protect API Key?

1. Don't share API Key
2. Enable IP whitelist
3. Regularly change Key
4. Use sub-accounts

### Q: Discovered abnormal trades?

1. Immediately stop Trader
2. Check exchange account
3. Change API Key
4. Check server security

---

## Performance Issues

### Q: System is slow?

1. Check server resources
2. Reduce concurrent Traders
3. Clear historical logs
4. Consider upgrading configuration

**Recommended configuration:**
- CPU: 2 cores+
- Memory: 4GB+
- Storage: 20GB+

### Q: High latency?

1. Choose server close to exchange
2. Use low-latency network
3. Reduce unnecessary data requests

---

## Other Issues

### Q: How to join community?

- Telegram: https://t.me/nofx_dev_community
- Twitter: https://x.com/nofx_official
- GitHub: https://github.com/NoFxAiOS/nofx

### Q: How to report bugs?

GitHub Issues: https://github.com/NoFxAiOS/nofx/issues

### Q: Are there tutorial videos?

Check pinned messages in official Twitter and Telegram groups.

### Q: Is it free?

NOFX is completely open source and free.
- Exchange fees are your responsibility
- AI API costs are your responsibility
- Server costs are your responsibility

path: references/grid-trading.md
content: # NOFX Grid Trading Detailed Guide

## Grid Trading Principles

Grid trading automatically buys low and sells high within a set price range, suitable for ranging markets.

```
Upper $2200 ─────────────────
         │  Sell │  Sell │
         ├───────┼───────┤
         │       │       │
         ├───────┼───────┤  ← Grid
         │       │       │
         ├───────┼───────┤
         │  Buy  │  Buy  │
Lower $1800 ─────────────────
```

## Complete Configuration Examples

### Example 1: ETH Uniform Grid

```json
{
  "strategy_type": "grid_trading",
  "grid_config": {
    "symbol": "ETHUSDT",
    "grid_count": 20,
    "total_investment": 5000,
    "leverage": 3,
    "upper_price": 2200,
    "lower_price": 1800,
    "use_atr_bounds": false,
    "distribution": "uniform",
    "max_drawdown_pct": 10,
    "stop_loss_pct": 5,
    "daily_loss_limit_pct": 8,
    "use_maker_only": true,
    "enable_direction_adjust": false
  }
}
```

### Example 2: BTC Adaptive Boundaries

```json
{
  "strategy_type": "grid_trading",
  "grid_config": {
    "symbol": "BTCUSDT",
    "grid_count": 30,
    "total_investment": 10000,
    "leverage": 2,
    "use_atr_bounds": true,
    "atr_multiplier": 2.5,
    "distribution": "gaussian",
    "max_drawdown_pct": 15,
    "stop_loss_pct": 3,
    "use_maker_only": true,
    "enable_direction_adjust": true,
    "direction_bias_ratio": 0.6
  }
}
```

### Example 3: Long-Biased Grid

```json
{
  "strategy_type": "grid_trading",
  "grid_config": {
    "symbol": "SOLUSDT",
    "grid_count": 15,
    "total_investment": 3000,
    "leverage": 5,
    "upper_price": 90,
    "lower_price": 70,
    "distribution": "pyramid",
    "enable_direction_adjust": true,
    "direction_bias_ratio": 0.7
  }
}
```

## Parameter Details

### Basic Parameters

| Parameter | Description | Suggested Value |
|-----------|-------------|-----------------|
| `symbol` | Trading pair | BTCUSDT, ETHUSDT etc. |
| `grid_count` | Grid quantity | 10-50, more for precision |
| `total_investment` | Total investment (USDT) | Based on capital |
| `leverage` | Leverage multiplier | 1-5x recommended |

### Boundary Settings

| Parameter | Description |
|-----------|-------------|
| `upper_price` | Upper boundary price |
| `lower_price` | Lower boundary price |
| `use_atr_bounds` | Use ATR to auto-calculate boundaries |
| `atr_multiplier` | ATR multiplier (default 2.0) |

### Distribution Types

| Type | Description | Use Case |
|------|-------------|----------|
| `uniform` | Even distribution | No clear direction bias |
| `gaussian` | Dense in middle | Expect price to range in center |
| `pyramid` | Dense at current price | Expect small range |

### Risk Control Parameters

| Parameter | Description | Suggested Value |
|-----------|-------------|-----------------|
| `max_drawdown_pct` | Max drawdown stop-loss | 10-20% |
| `stop_loss_pct` | Single position stop-loss | 3-5% |
| `daily_loss_limit_pct` | Daily loss limit | 5-10% |

### Advanced Parameters

| Parameter | Description |
|-----------|-------------|
| `use_maker_only` | Only place Maker orders, lower fees |
| `enable_direction_adjust` | Auto-adjust grid direction |
| `direction_bias_ratio` | Direction bias ratio (0.7 = 70% long/30% short) |

## Grid Calculations

### Grid Spacing

```
Spacing = (Upper - Lower) / Grid Count
Example: (2200 - 1800) / 20 = $20/grid
```

### Position per Grid

```
Per Grid Investment = Total Investment / Grid Count * Leverage
Example: 5000 / 20 * 3 = $750/grid
```

### Expected Return

```
Single Arbitrage = Per Grid Investment * Spacing%
Example: 750 * (20/2000) = $7.5/trade
```

## Suitable Market Conditions

| Market Type | Grid Suitable | Recommendation |
|-------------|---------------|----------------|
| Range-bound | ✅ Very suitable | Standard grid |
| Slow uptrend | ✅ Suitable | Long-biased grid |
| Slow downtrend | ⚠️ Cautious | Short-bias + small position |
| High volatility | ❌ Not suitable | Pause grid |
| Trending market | ❌ Not suitable | Use trend strategy |

## Common Questions

### Q: How to choose grid count?

- High volatility: 10-15 grids, large spacing
- Low volatility: 25-50 grids, small spacing
- Small capital: 10-20 grids
- Large capital: 30-50 grids

### Q: How to set boundaries?

1. Look at recent support/resistance levels
2. Use ATR auto-calculation (recommended)
3. Leave 10-20% buffer above and below

### Q: When to stop?

- Price breaks boundaries
- Reaches maximum drawdown
- Trending market appears
- Before major news events

path: references/market-charts.md
content: # NOFX Market Page Usage

## Access Method

URL: `https://nofxai.com/market`

## Feature Overview

### K-line Charts

- TradingView style K-line charts
- Supports multiple timeframes: 1m, 5m, 15m, 30m, 1h, 4h, 1d
- Real-time price updates

### Technical Indicators

| Indicator | Description | Usage |
|-----------|-------------|-------|
| EMA | Exponential Moving Average | Trend direction |
| MACD | Moving Average Convergence Divergence | Momentum/divergence |
| RSI | Relative Strength Index | Overbought/oversold |
| BOLL | Bollinger Bands | Support/resistance/volatility |
| Volume | Trading volume | Price-volume relationship |

### Order Book Depth

- Buy/sell order distribution
- Large order marking
- Buy/sell pressure comparison

### Real-time Data

- Current price
- 24h change percentage
- 24h trading volume
- Funding rate
- Open interest

## Browser Automation

### Open Market Page

```javascript
browser.navigate("https://nofxai.com/market")
browser.snapshot()
```

### Switch Trading Pair

```javascript
// Click trading pair selector
// Input or select target trading pair
browser.act({kind: "click", ref: "symbolSelector"})
browser.act({kind: "type", ref: "searchBox", text: "ETHUSDT"})
```

### Switch Timeframe

```javascript
// Click corresponding time button
browser.act({kind: "click", ref: "timeframe1h"})
```

## Data Interpretation

### K-line Patterns

| Pattern | Meaning | Trading Suggestion |
|---------|---------|-------------------|
| Large bullish candle | Strong uptrend | Go long with trend |
| Large bearish candle | Strong downtrend | Go short with trend |
| Doji | Hesitation/reversal | Wait for confirmation |
| Hammer | Bottom reversal | Consider going long |
| Inverted hammer | Top reversal | Consider going short |

### RSI Signals

| Value | Status | Action |
|-------|---------|--------|
| > 70 | Overbought | Consider short/take profit |
| < 30 | Oversold | Consider long/buy dip |
| Around 50 | Neutral | Wait for direction |

### MACD Signals

| Signal | Meaning |
|--------|---------|
| Golden cross | DIF crosses above DEA, bullish |
| Death cross | DIF crosses below DEA, bearish |
| Top divergence | Price makes new high but MACD doesn't, beware pullback |
| Bottom divergence | Price makes new low but MACD doesn't, possible bounce |

### Bollinger Bands Usage

| Position | Meaning |
|----------|---------|
| Touch upper band | Overbought, possible pullback |
| Touch lower band | Oversold, possible bounce |
| Bands narrowing | Breakout approaching |
| Bands widening | Increasing volatility |

path: references/multi-account.md
content: # NOFX Multi-Account Management

## Multi-Account Scenarios

1. **Risk Isolation** - Different strategies use different accounts
2. **Multiple Exchanges** - Use multiple exchanges simultaneously
3. **Capital Allocation** - Spread risk
4. **Test Environment** - Main account + test account

## Configuration Methods

### Multi-Accounts on Same Exchange

Add multiple exchange configurations in Config page, distinguished by different names:

```
binance-main       → Main account
binance-test       → Test account
binance-grid       → Grid trading dedicated
```

### Multiple Exchanges

```
binance   → Primary trading
bybit     → Backup
okx       → Arbitrage
gate      → Altcoins
```

## Account Naming Suggestions

| Naming Pattern | Example | Purpose |
|----------------|---------|---------|
| `{exchange}-{purpose}` | binance-main | Distinguish purpose |
| `{exchange}-{strategy}` | binance-grid | Distinguish strategy |
| `{exchange}-{capital}` | binance-10k | Distinguish capital amount |

## Trader & Account Binding

Select corresponding account when creating Trader:

```
Trader: eth-hunter
├── AI Model: Claude
├── Exchange: binance-main    ← Select account
└── Strategy: ai500 strategy
```

## Capital Allocation Recommendations

| Account Type | Capital Ratio | Risk Level |
|--------------|---------------|-------------|
| Main Account | 50-60% | Low risk strategy |
| Aggressive Account | 20-30% | High return strategy |
| Test Account | 10-20% | New strategy testing |

## Risk Management

### Single Account Limits

- Max position: 50% of account capital
- Max single coin: 20% of account capital
- Daily loss limit: 10% of account capital

### Multi-Account Total Limits

- Total exposure: 70% of total capital
- Correlation: Avoid all accounts holding highly correlated positions
- Monitoring: View all accounts P&L in aggregate

## Dashboard Switching

Switch Trader/account in dropdown menu at top of Dashboard page:

```javascript
// Browser automation to switch account
browser.act({kind: "click", ref: "traderSelector"})
browser.act({kind: "click", ref: "targetTrader"})
```

## Multi-Account API

When calling APIs for different accounts, use corresponding API Keys:

```bash
# Account A
curl -H "Authorization: Bearer $KEY_A" ...

# Account B
curl -H "Authorization: Bearer $KEY_B" ...
```

## Sub-Account Features (Exchange)

### Binance Sub-Accounts

1. User Center → Sub-Accounts
2. Create sub-account
3. Transfer funds
4. Generate sub-account API

### OKX Sub-Accounts

1. User Center → Sub-Account Management
2. Create trading sub-account
3. Set permissions and limits

## Security Recommendations

1. **Different IP Whitelist** - Each account uses different server
2. **Independent 2FA** - Each account has independent verification
3. **Minimal Permissions** - Only enable necessary permissions
4. **Regular Auditing** - Check for abnormal trades

path: references/strategy-schema.md
content: # NOFX Strategy Configuration Schema

## Full Strategy Config

```json
{
  "strategy_type": "ai_trading",
  "language": "zh",
  
  "coin_source": {
    "source_type": "mixed",
    "static_coins": ["BTCUSDT", "ETHUSDT"],
    "excluded_coins": ["LUNAUSDT"],
    "use_ai500": true,
    "ai500_limit": 10,
    "use_oi_top": true,
    "oi_top_limit": 5,
    "use_oi_low": false,
    "oi_low_limit": 5
  },
  
  "indicators": {
    "klines": {
      "intervals": ["5m", "15m", "1h", "4h"],
      "limit": 100
    },
    "enable_raw_klines": true,
    "enable_ema": true,
    "enable_macd": true,
    "enable_rsi": true,
    "enable_atr": true,
    "enable_boll": true,
    "enable_volume": true,
    "enable_oi": true,
    "enable_funding_rate": true,
    "ema_periods": [20, 50],
    "rsi_periods": [7, 14],
    "atr_periods": [14],
    "boll_periods": [20],
    
    "nofxos_api_key": "cm_xxx",
    "enable_quant_data": true,
    "enable_quant_oi": true,
    "enable_quant_netflow": true,
    "enable_oi_ranking": true,
    "oi_ranking_duration": "1h",
    "oi_ranking_limit": 10,
    "enable_netflow_ranking": true,
    "netflow_ranking_duration": "1h",
    "netflow_ranking_limit": 10,
    "enable_price_ranking": true,
    "price_ranking_duration": "1h",
    "price_ranking_limit": 10
  },
  
  "risk_control": {
    "max_position_pct": 10,
    "max_total_position_pct": 50,
    "stop_loss_pct": 3,
    "take_profit_pct": 5,
    "max_daily_loss_pct": 10,
    "max_drawdown_pct": 15
  },
  
  "prompt_sections": {
    "role_definition": "You are a professional cryptocurrency trading AI, focused on medium-short term trend trading.",
    "trading_frequency": "Analyze the market every 4 hours, seeking high-certainty opportunities.",
    "entry_standards": "Only consider long when RSI<30 oversold or breaking key resistance levels, consider short when RSI>70 overbought.",
    "decision_process": "1. Analyze major timeframe trends 2. Confirm fund flow direction 3. Evaluate risk-reward ratio 4. Determine position size"
  },
  
  "custom_prompt": "Additional note: Avoid trading before and after major news announcements."
}
```

## Grid Trading Strategy

```json
{
  "strategy_type": "grid_trading",
  "language": "zh",
  
  "grid_config": {
    "symbol": "ETHUSDT",
    "grid_count": 20,
    "total_investment": 5000,
    "leverage": 3,
    "upper_price": 2200,
    "lower_price": 1800,
    "use_atr_bounds": false,
    "atr_multiplier": 2.0,
    "distribution": "uniform",
    "max_drawdown_pct": 10,
    "stop_loss_pct": 5,
    "daily_loss_limit_pct": 8,
    "use_maker_only": true,
    "enable_direction_adjust": true,
    "direction_bias_ratio": 0.7
  }
}
```

## Coin Source Types

| Type | Description | Use Case |
|------|-------------|----------|
| `static` | Fixed coin list | Known coins to trade |
| `ai500` | AI high potential coins | Follow AI signals |
| `oi_top` | OI increase ranking | Trending coins (long bias) |
| `oi_low` | OI decrease ranking | Declining coins (short bias) |
| `mixed` | Combination of sources | Diversified approach |

## Indicator Options

| Indicator | Periods | Description |
|-----------|---------|-------------|
| EMA | [20, 50] | Trend direction |
| RSI | [7, 14] | Overbought/oversold |
| MACD | default | Momentum |
| ATR | [14] | Volatility |
| BOLL | [20] | Support/resistance |

## Grid Distribution Types

| Type | Description |
|------|-------------|
| `uniform` | Equal spacing between grids |
| `gaussian` | Denser in the middle |
| `pyramid` | Denser at current price |

## Natural Language to Strategy Mapping

### Example 1: "Create a strategy for AI500 coins with RSI oversold entry"

```json
{
  "coin_source": {
    "source_type": "ai500",
    "use_ai500": true,
    "ai500_limit": 10
  },
  "indicators": {
    "enable_rsi": true,
    "rsi_periods": [14]
  },
  "prompt_sections": {
    "entry_standards": "Enter long when RSI < 30 (oversold)"
  }
}
```

### Example 2: "ETH grid trading between 1800-2200 with 20 grids"

```json
{
  "strategy_type": "grid_trading",
  "grid_config": {
    "symbol": "ETHUSDT",
    "grid_count": 20,
    "upper_price": 2200,
    "lower_price": 1800,
    "distribution": "uniform"
  }
}
```

### Example 3: "Track coins with large institution inflows"

```json
{
  "coin_source": {
    "source_type": "mixed",
    "use_ai500": false
  },
  "indicators": {
    "enable_quant_netflow": true,
    "enable_netflow_ranking": true,
    "netflow_ranking_duration": "1h",
    "netflow_ranking_limit": 10
  },
  "prompt_sections": {
    "entry_standards": "Focus on coins with institution inflow > $1M in the last hour"
  }
}
```


path: references/webhooks.md
content: # NOFX Webhook Notification Integration

## Supported Notification Channels

| Channel | Purpose | Configuration |
|---------|---------|---------------|
| Telegram | Instant messaging | Bot Token + Chat ID |
| Discord | Team collaboration | Webhook URL |
| Slack | Work notifications | Webhook URL |
| Custom | Third-party systems | HTTP POST |

## Telegram Notifications

### Via Clawdbot

Clawdbot is integrated, use cron job to send directly:

```json
{
  "payload": {
    "deliver": true,
    "channel": "telegram",
    "to": "YOUR_CHAT_ID"
  }
}
```

### Direct Telegram API Call

```bash
TELEGRAM_BOT_TOKEN="your_bot_token"
CHAT_ID="your_chat_id"
MESSAGE="🚀 NOFX Alert: ETH breaks $2000"

curl -s -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
  -d "chat_id=$CHAT_ID" \
  -d "text=$MESSAGE" \
  -d "parse_mode=Markdown"
```

## Discord Webhook

### Create Webhook

1. Server Settings → Integrations → Webhooks
2. Create Webhook, copy URL

### Send Notification

```bash
DISCORD_WEBHOOK="https://discord.com/api/webhooks/xxx/yyy"

curl -H "Content-Type: application/json" \
  -X POST "$DISCORD_WEBHOOK" \
  -d '{
    "content": "🚀 NOFX Alert",
    "embeds": [{
      "title": "AI500 New Signal",
      "description": "POWER enters ranking, score 88.5",
      "color": 5763719
    }]
  }'
```

## Slack Webhook

### Create Webhook

1. Slack App → Incoming Webhooks
2. Add to channel, copy URL

### Send Notification

```bash
SLACK_WEBHOOK="https://hooks.slack.com/services/xxx/yyy/zzz"

curl -X POST "$SLACK_WEBHOOK" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "🚀 NOFX Alert: ETH institutional inflow $10M"
  }'
```

## Custom Webhook

### Generic HTTP POST

```bash
WEBHOOK_URL="https://your-server.com/webhook"

curl -X POST "$WEBHOOK_URL" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "ai500_signal",
    "symbol": "POWER",
    "score": 88.5,
    "timestamp": "2026-02-12T12:00:00Z"
  }'
```

## Clawdbot Integration Examples

### Price Alert

```bash
# Monitor BTC price, notify when breaks 70000
if [ $(curl -s "https://nofxos.ai/api/coin/BTC?auth=$KEY" | jq '.data.price') -gt 70000 ]; then
  # Send Telegram notification
  curl -s "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
    -d "chat_id=$CHAT_ID" \
    -d "text=🚀 BTC breaks $70,000!"
fi
```

### AI500 New Coin Alert

```bash
# Check AI500 new coins
NEW_COINS=$(curl -s "https://nofxos.ai/api/ai500/list?auth=$KEY" | \
  jq -r '.data.coins[] | select(.start_time > (now - 3600)) | .pair')

if [ -n "$NEW_COINS" ]; then
  # Send notification
  MESSAGE="🆕 AI500 new entry: $NEW_COINS"
  # ... send to Telegram/Discord/Slack
fi
```

### Large Fund Flow Alert

```bash
# Check institutional inflow > $10M
BIG_FLOWS=$(curl -s "https://nofxos.ai/api/netflow/top-ranking?auth=$KEY&limit=5&duration=1h&type=institution" | \
  jq -r '.data.netflows[] | select(.amount > 10000000) | "\(.symbol): $\(.amount/1000000)M"')

if [ -n "$BIG_FLOWS" ]; then
  MESSAGE="💰 Large institutional inflow:\n$BIG_FLOWS"
  # ... send notification
fi
```

## Notification Templates

### Market Report Template

```
📊 NOFX Market Report | {time}

🤖 AI500 Signals
{ai500_list}

💰 Institutional Inflow TOP5
{flow_list}

🚀 1h Gainers TOP5
{gainers_list}

⚠️ Risk Alert
{alerts}
```

### Trading Signal Template

```
🎯 Trading Signal | {symbol}

Direction: {direction}
Entry: ${entry_price}
Stop Loss: ${stop_loss}
Take Profit: ${take_profit}
Position: {position_size}%

AI Score: {ai_score}
Fund Flow: {fund_flow}
```

### P&L Report Template

```
💰 {trader_name} Daily Report

Equity: ${equity}
P&L: ${pnl} ({pnl_pct}%)
Positions: {positions_count}

Today's Trades: {trades_count}
Win Rate: {win_rate}%
```

path: scripts/generate-report.sh
content: #!/bin/bash
# NOFX Market Report Generator
# Usage: ./generate-report.sh [format]
# format: brief | full (default: brief)

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
API_SCRIPT="$SCRIPT_DIR/nofx-api.sh"

format="${1:-brief}"

# Fetch all data
ai500=$("$API_SCRIPT" ai500 2>/dev/null)
ai300=$("$API_SCRIPT" ai300 10 2>/dev/null)
flow_in=$("$API_SCRIPT" flow-in 10 1h institution 2>/dev/null)
oi_up=$("$API_SCRIPT" oi-up 10 1h 2>/dev/null)
oi_down=$("$API_SCRIPT" oi-down 10 1h 2>/dev/null)
price=$("$API_SCRIPT" price 1h 2>/dev/null)

# Get current time
timestamp=$(date "+%Y-%m-%d %H:%M")

# Generate report
cat << EOF
📊 **NOFX Market Report | $timestamp**

---

🤖 **AI500 High Potential Signals**
EOF

echo "$ai500" | jq -r '
  .data.coins[:5] | 
  "| Coin | AI Score | Cumulative Gain |",
  "|------|----------|-----------------|",
  (.[] | "| \(.pair | gsub("USDT$";"")) | \(.score | . * 100 | floor / 100) | +\(.increase_percent | . * 100 | floor / 100)% |")
' 2>/dev/null || echo "No AI500 data"

cat << EOF

---

💰 **Institutional Inflow TOP10** (1h)
EOF

echo "$flow_in" | jq -r '
  .data.netflows[:10] | to_entries | 
  .[] | 
  "\(.key + 1). \(.value.symbol | gsub("USDT$";"")) +$\((.value.amount / 1000000) | . * 100 | floor / 100)M"
' 2>/dev/null || echo "No flow data"

cat << EOF

---

🚀 **1h Gainers TOP10**
EOF

echo "$price" | jq -r '
  .data.data["1h"].top[:10] | to_entries |
  .[] |
  "\(.key + 1). \(.value.symbol) +\((.value.price_delta * 100) | . * 100 | floor / 100)%"
' 2>/dev/null || echo "No price data"

cat << EOF

---

📈 **1h OI Increase TOP10**
EOF

echo "$oi_up" | jq -r '
  .data.positions[:10] | to_entries |
  .[] |
  "\(.key + 1). \(.value.symbol | gsub("USDT$";"")) +$\((.value.oi_delta_value / 1000000) | . * 100 | floor / 100)M"
' 2>/dev/null || echo "No OI data"

cat << EOF

---

📉 **1h OI Decrease TOP10**
EOF

echo "$oi_down" | jq -r '
  .data.positions[:10] | to_entries |
  .[] |
  "\(.key + 1). \(.value.symbol | gsub("USDT$";"")) $\((.value.oi_delta_value / 1000000) | . * 100 | floor / 100)M"
' 2>/dev/null || echo "No OI data"

# Price losers / alerts
losers=$(echo "$price" | jq -r '.data.data["1h"].top | map(select(.price_delta < -0.05)) | .[:5]' 2>/dev/null)
if [ -n "$losers" ] && [ "$losers" != "[]" ]; then
cat << EOF

---

⚠️ **Drop Alert**
EOF
echo "$losers" | jq -r '.[] | "- 🔴 \(.symbol) \((.price_delta * 100) | . * 100 | floor / 100)%"' 2>/dev/null
fi

echo ""
echo "---"


path: scripts/nofx-api.sh
content: #!/bin/bash
# NOFX API Helper Script
# Usage: ./nofx-api.sh <endpoint> [params]

set -e

# Configuration
CONFIG_FILE="${NOFX_CONFIG:-$HOME/clawd/skills/nofx/config.json}"
BASE_URL="https://nofxos.ai"

# Load API key from config
if [ -f "$CONFIG_FILE" ]; then
    API_KEY=$(jq -r '.api_key // empty' "$CONFIG_FILE" 2>/dev/null)
fi

# Override with environment variable if set
[REDACTED_SECRET]"

if [ -z "$API_KEY" ]; then
    echo "Error: API key not found. Set NOFX_API_KEY or configure config.json" >&2
    exit 1
fi

# Endpoints
endpoint="$1"
shift || true

case "$endpoint" in
    # AI Signals
    ai500)
        curl -s "$BASE_URL/api/ai500/list?auth=$API_KEY"
        ;;
    ai500-stats)
        curl -s "$BASE_URL/api/ai500/stats?auth=$API_KEY"
        ;;
    ai500-coin)
        symbol="${1:-BTC}"
        curl -s "$BASE_URL/api/ai500/$symbol?auth=$API_KEY"
        ;;
    ai300)
        limit="${1:-10}"
        curl -s "$BASE_URL/api/ai300/list?auth=$API_KEY&limit=$limit"
        ;;
    ai300-stats)
        curl -s "$BASE_URL/api/ai300/stats?auth=$API_KEY"
        ;;
    
    # Fund Flow
    flow-in)
        limit="${1:-10}"
        duration="${2:-1h}"
        type="${3:-institution}"
        curl -s "$BASE_URL/api/netflow/top-ranking?auth=$API_KEY&limit=$limit&duration=$duration&type=$type"
        ;;
    flow-out)
        limit="${1:-10}"
        duration="${2:-1h}"
        type="${3:-institution}"
        curl -s "$BASE_URL/api/netflow/low-ranking?auth=$API_KEY&limit=$limit&duration=$duration&type=$type"
        ;;
    
    # Open Interest
    oi-up)
        limit="${1:-10}"
        duration="${2:-1h}"
        curl -s "$BASE_URL/api/oi/top-ranking?auth=$API_KEY&limit=$limit&duration=$duration"
        ;;
    oi-down)
        limit="${1:-10}"
        duration="${2:-1h}"
        curl -s "$BASE_URL/api/oi/low-ranking?auth=$API_KEY&limit=$limit&duration=$duration"
        ;;
    oi-cap)
        limit="${1:-10}"
        curl -s "$BASE_URL/api/oi-cap/ranking?auth=$API_KEY&limit=$limit"
        ;;
    
    # Price
    price)
        duration="${1:-1h}"
        curl -s "$BASE_URL/api/price/ranking?auth=$API_KEY&duration=$duration"
        ;;
    
    # Funding Rate
    funding-high)
        limit="${1:-10}"
        curl -s "$BASE_URL/api/funding-rate/top?auth=$API_KEY&limit=$limit"
        ;;
    funding-low)
        limit="${1:-10}"
        curl -s "$BASE_URL/api/funding-rate/low?auth=$API_KEY&limit=$limit"
        ;;
    funding)
        symbol="${1:-BTC}"
        curl -s "$BASE_URL/api/funding-rate/$symbol?auth=$API_KEY"
        ;;
    
    # Long-Short Ratio
    long-short)
        limit="${1:-10}"
        curl -s "$BASE_URL/api/long-short/list?auth=$API_KEY&limit=$limit"
        ;;
    long-short-coin)
        symbol="${1:-BTC}"
        curl -s "$BASE_URL/api/long-short/$symbol?auth=$API_KEY"
        ;;
    
    # Heatmap
    heatmap)
        limit="${1:-10}"
        trade="${2:-future}"
        curl -s "$BASE_URL/api/heatmap/list?auth=$API_KEY&limit=$limit&trade=$trade"
        ;;
    heatmap-future)
        symbol="${1:-BTC}"
        curl -s "$BASE_URL/api/heatmap/future/$symbol?auth=$API_KEY"
        ;;
    heatmap-spot)
        symbol="${1:-BTC}"
        curl -s "$BASE_URL/api/heatmap/spot/$symbol?auth=$API_KEY"
        ;;
    
    # Single Coin
    coin)
        symbol="${1:-BTC}"
        include="${2:-all}"
        curl -s "$BASE_URL/api/coin/$symbol?auth=$API_KEY&include=$include"
        ;;
    
    # Upbit
    upbit-hot)
        limit="${1:-10}"
        curl -s "$BASE_URL/api/upbit/hot?auth=$API_KEY&limit=$limit"
        ;;
    upbit-flow-in)
        limit="${1:-10}"
        duration="${2:-1h}"
        curl -s "$BASE_URL/api/upbit/netflow/top-ranking?auth=$API_KEY&limit=$limit&duration=$duration"
        ;;
    upbit-flow-out)
        limit="${1:-10}"
        duration="${2:-1h}"
        curl -s "$BASE_URL/api/upbit/netflow/low-ranking?auth=$API_KEY&limit=$limit&duration=$duration"
        ;;
    
    # Query Ranking
    query-rank)
        limit="${1:-10}"
        curl -s "$BASE_URL/api/query-rank/list?auth=$API_KEY&limit=$limit"
        ;;
    
    # Help
    help|--help|-h)
        cat << EOF
NOFX API Helper

Usage: ./nofx-api.sh <endpoint> [params]

Endpoints:
  AI Signals:
    ai500                     AI500 high potential coins
    ai500-stats               AI500 statistics
    ai500-coin <symbol>       Single coin AI analysis
    ai300 [limit]             AI300 quantitative signals
    ai300-stats               AI300 statistics

  Fund Flow:
    flow-in [limit] [duration] [type]    Inflow ranking
    flow-out [limit] [duration] [type]   Outflow ranking

  Open Interest:
    oi-up [limit] [duration]   OI increase ranking
    oi-down [limit] [duration] OI decrease ranking
    oi-cap [limit]             OI market cap ranking

  Price:
    price [duration]           Price gainers/losers

  Funding Rate:
    funding-high [limit]       High funding rate (crowded longs)
    funding-low [limit]        Low funding rate (crowded shorts)
    funding <symbol>           Single coin funding rate

  Long-Short:
    long-short [limit]         Long-short ratio anomalies
    long-short-coin <symbol>   Single coin long-short history

  Heatmap:
    heatmap [limit] [trade]    Order book heatmap list
    heatmap-future <symbol>    Future order book heatmap
    heatmap-spot <symbol>      Spot order book heatmap

  Single Coin:
    coin <symbol> [include]    Comprehensive coin data

  Upbit:
    upbit-hot [limit]          Upbit hot coins
    upbit-flow-in [limit] [duration]   Upbit inflow
    upbit-flow-out [limit] [duration]  Upbit outflow

  Other:
    query-rank [limit]         Query ranking

Parameters:
  limit: Number of results (default: 10)
  duration: 1m, 5m, 15m, 30m, 1h, 4h, 8h, 12h, 24h, 2d, 3d, 5d, 7d
  type: institution, personal
  trade: future, spot
  include: all, price, netflow, oi, ai500

Environment:
  NOFX_API_KEY: API key (overrides config)
  NOFX_CONFIG: Config file path (default: ~/clawd/skills/nofx/config.json)
EOF
        ;;
    
    *)
        echo "Unknown endpoint: $endpoint" >&2
        echo "Run './nofx-api.sh help' for usage" >&2
        exit 1
        ;;
esac


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