Skill: okx-smc-dca (version 1.0.0)

--- name: openclaw-smc-dca description: | Multi-timeframe Smart Money Concepts (SMC) DCA trading skill for OKX Spot. Detects Order Blocks, CHoCH, Liquidity sweeps across HTF (4H/D1/W1/M1) and LTF (15m). Supports ANY OKX Spot pair — configure SYMBOLS env var to add/remove coins. Multi-tier capital allocation: each HTF tier has its own budget, TP%, step%, N_CAP. Full DRY_RUN paper trading simulation with virtual $10k per symbol (zero real orders). Runs entirely on a single Mac Mini — no external server or webhook needed. Invoke when asked to scan market structure, check DCA status, manage capital, or run demo. user-invocable: true disable-model-invocation: false --- # OpenClaw SMC-DCA Skill ## Overview 6 files. All scripts run as cron jobs on the same Mac Mini as OpenClaw. | Script / File | Role | Runs | |---|---|---| | `tier_config.py` | Strategy config: ratios, TP%, step%, N_CAP per tier | import only | | `capital_manager.py` | Capital engine: status, rebalance, deposit, withdraw | cron 1h + on demand | | `htf_scanner.py` | HTF OB detection, dynamic N, kill-switch | cron per tier | | `ltf_and_execute.py` | LTF signal + DCA order execution | cron 5m | | `state_manager.py` | Cycle guardian: invalidation + take profit | cron 15m | | `paper_exchange.py` | DRY_RUN simulation engine | auto-loaded when DRY_RUN=true | **No Flask, no webhook, no HTTP. Everything in-process on Mac Mini.** --- ## When to Use This Skill - Scan Smart Money zones on **any OKX Spot pair** - Check capital allocation, DCA status, or equity breakdown - Handle deposit / withdrawal and rebalance tiers - Add a new coin to trade: update `SYMBOLS` in `.env`, run `capital_manager --action rebalance` - Run in demo mode without touching real OKX account --- ## Prerequisites ### Python packages ```bash pip install ccxt smartmoneyconcepts pandas python-dotenv ``` ### Environment variables (`.env`) ```bash # ── OKX API ──────────────────────────────────────────────────────────────── OKX_API_KEY=<sub-account API key> # NO withdraw permission required OKX_SECRET=<sub-account secret> OKX_PASSPHRASE=<sub-account passphrase> # ── Symbols to trade ────────────────────────────────────────────────────── # Add ANY OKX Spot pair here. Capital is shared and rebalanced automatically. SYMBOLS=ETH/USDT,BTC/USDT # comma-separated, no spaces # ── State file paths ─────────────────────────────────────────────────────── POI_STATE_PATH=./state/poi_state.json DCA_STATE_PATH=./state/dca_state.json CAPITAL_STATE_PATH=./state/capital_state.json PAPER_STATE_PATH=./state/paper_state.json # DRY_RUN paper balance file # ── LTF scan config ──────────────────────────────────────────────────────── LTF_TIMEFRAME=15m LTF_SWING_LENGTH=5 LTF_CANDLE_LIMIT=200 LTF_LOOKBACK_CANDLES=3 SPRING_VOLUME_RATIO=0.8 # ── Capital Manager ──────────────────────────────────────────────────────── MIN_RESERVE_RATIO=0.05 # 5% equity always kept as reserve REBALANCE_DRIFT_THRESHOLD=0.10 # rebalance when tier drifts >10% from ideal # ── DCA limits (global fallback — overridden per-tier by tier_config.py) ── DCA_MAX_LEGS=10 MIN_STEP_PCT=5.0 # Layer 1 fallback (actual from poi_state per-tier) # ── DRY_RUN simulation ───────────────────────────────────────────────────── DRY_RUN=false # set to true for paper trading PAPER_INITIAL_USDT=10000.0 # starting paper capital per symbol # ── Default tier for htf_scanner if --tier not provided ─────────────────── TIER=4H # ── Telegram ─────────────────────────────────────────────────────────────── TELEGRAM_ENABLED=true ``` --- ## Tier Strategy — `tier_config.py` This is the **only file** to edit when adjusting the capital allocation strategy. | Tier | HTF | Capital | TP% | Min Step | N_CAP | |------|-----|---------|-----|----------|-------| | `4H` | 4h | 25% | 10% | 5% | 10 | | `D1` | 1d | 35% | 15% | 4% | 8 | | `W1` | 1w | 30% | 25% | 3% | 6 | | `M1` | 1M | 10% | 40% | 3% | 4 | > **Rule**: Ratios must sum exactly to 1.0. File validates this on import and raises `ValueError` if wrong. After editing: always run `python scripts/capital_manager.py --action rebalance` --- ## Cron Setup (Mac Mini) — Multi-Tier Example ```bash # ── Capital Manager: rebalance every hour ───────────────────────────────── 0 * * * * cd /opt/openclaw && python scripts/capital_manager.py --action rebalance >> logs/capital.log 2>&1 # ── HTF Scanner: one job per (symbol × tier) ────────────────────────────── # Tier 4H — every 4h 0 */4 * * * cd /opt/openclaw && python scripts/htf_scanner.py --symbol ETH/USDT --tier 4H >> logs/eth_4h.log 2>&1 0 */4 * * * cd /opt/openclaw && python scripts/htf_scanner.py --symbol BTC/USDT --tier 4H >> logs/btc_4h.log 2>&1 # Tier D1 — daily at midnight 0 0 * * * cd /opt/openclaw && python scripts/htf_scanner.py --symbol ETH/USDT --tier D1 >> logs/eth_d1.log 2>&1 # Tier W1 — weekly (Monday midnight) 0 0 * * 1 cd /opt/openclaw && python scripts/htf_scanner.py --symbol ETH/USDT --tier W1 >> logs/eth_w1.log 2>&1 # Tier M1 — monthly (1st of month) 0 0 1 * * cd /opt/openclaw && python scripts/htf_scanner.py --symbol ETH/USDT --tier M1 >> logs/eth_m1.log 2>&1 # ── LTF + Execute: every 5m per symbol ─────────────────────────────────── */5 * * * * cd /opt/openclaw && python scripts/ltf_and_execute.py --symbol ETH/USDT >> logs/eth_ltf.log 2>&1 */5 * * * * cd /opt/openclaw && python scripts/ltf_and_execute.py --symbol BTC/USDT >> logs/btc_ltf.log 2>&1 # ── State Manager: every 15m per symbol ────────────────────────────────── */15 * * * * cd /opt/openclaw && python scripts/state_manager.py --symbol ETH/USDT >> logs/eth_state.log 2>&1 */15 * * * * cd /opt/openclaw && python scripts/state_manager.py --symbol BTC/USDT >> logs/btc_state.log 2>&1 ``` --- ## DRY_RUN / Paper Trading Mode Set `DRY_RUN=true` in `.env` or as a shell prefix to enable **full simulation**. | Aspect | DRY_RUN behaviour | |--------|------------------| | Order placement | `paper_exchange.py` — **zero real OKX orders** | | Balance reads | `state/paper_state_<SYMBOL>.json` | | Price data | Real OKX (read-only ticker) | | OHLCV candles | Real OKX (read-only) | | Starting capital | `$10,000 USDT` per symbol (set `PAPER_INITIAL_USDT` to change) | | poi_state / dca_state | Written normally (locally only) | | capital_state | Logged only, not written | ### Thử nghiệm DRY_RUN ```bash # Chạy toàn bộ pipeline demo DRY_RUN=true python scripts/capital_manager.py --action rebalance DRY_RUN=true python scripts/htf_scanner.py --symbol ETH/USDT --tier 4H DRY_RUN=true python scripts/ltf_and_execute.py --symbol ETH/USDT DRY_RUN=true python scripts/state_manager.py --symbol ETH/USDT DRY_RUN=true python scripts/capital_manager.py --action status # Reset paper account về $10k python scripts/capital_manager.py --reset-demo # tất cả SYMBOLS python scripts/capital_manager.py --reset-demo --symbol ETH/USDT # chỉ 1 coin ``` --- ## Capital Manager CLI ```bash # Xem trạng thái phân bổ vốn python scripts/capital_manager.py --action status # Cân bằng lại theo equity thực (chạy tự động mỗi giờ) python scripts/capital_manager.py --action rebalance # Nạp thêm 500$ (sau khi đã nạp trên OKX) python scripts/capital_manager.py --action deposit --amount 500 # Kiểm tra trước khi rút python scripts/capital_manager.py --action withdraw-check --amount 300 # → { "is_safe": true/false, "max_safe_withdrawal": 245.0, "reason": "..." } # Ghi nhận rút vốn (sau khi đã rút trên OKX) python scripts/capital_manager.py --action withdraw --amount 300 ``` **Output `status`:** ```json { "total_equity": 3000.00, "usdt_free": 2200.00, "min_reserve": 150.00, "tiers": [ { "tier": "4H", "ratio": "25%", "ideal_budget": 750.00, "cycle_budget_limit": 750.00, "locked_invested": 250.00, "available": 500.00, "tp_pct": 10.0, "needs_rebalance": false }, ... ] } ``` --- ## HTF Scanner **Chạy:** `python scripts/htf_scanner.py --symbol ETH/USDT --tier 4H` What it does: 1. Đọc `tier_config` → lấy `htf`, `n_method`, `n_cap`, `min_step_pct`, `tp_pct` 2. Đọc `capital_state.json` → lấy `cycle_budget_limit` cho tier 3. Fetch HTF OHLCV candles từ OKX 4. `smc.swing_highs_lows()` → tìm swing 5. `smc.ob()` → phát hiện Order Blocks, chọn Bullish OB gần nhất dưới giá hiện tại 6. **Kill-switch check**: nếu `current_price < ob_bottom` → set `ob_invalidated=true`, gửi Telegram khẩn cấp 7. `smc.liquidity()` → lấy swept liquidity levels (Spring confirmation) 8. Tính `n_dynamic` (số DCA legs) theo OB width / ATR 9. Ghi `poi_state_<SYM>.json` với đầy đủ: OB boundaries, tier_name, cycle_budget_limit, tp_pct, min_step_pct --- ## LTF Execution Engine **Chạy:** `python scripts/ltf_and_execute.py --symbol ETH/USDT` Flow (chạy mỗi 5 phút): ``` 1. GATE CHECK: đọc poi_state ├── Nếu không có poi → skip ├── Nếu price_in_ob = false → skip (giá chưa vào OB) └── Nếu ob_invalidated = true → kill (LAYER 3) 2. LTF SIGNAL SCAN: fetch 15m candles ├── detect_choch() → Bullish CHoCH (Break of Structure) └── detect_spring() → Wyckoff Spring (SSL sweep + low volume + close above) 3. Nếu có tín hiệu → RISK CHECK ├── get_equity() → USDT_free + coin_held × price = E_total ├── S = E_total / n_dynamic (leg size) │ ├── LAYER 2: cap S by remaining cycle budget │ cycle_budget = poi_state["cycle_budget_limit"] │ remaining = cycle_budget - total_invested │ nếu remaining ≤ 0 → skip "budget_exhausted" │ S = min(S, remaining) │ ├── LAYER 1: step cooldown │ min_step_pct từ poi_state (per-tier) │ nếu price > last_buy × (1 - min_step%) → skip "step_cooldown" │ ├── Cash check: base_free ≥ S? └── Price still in OB? 4. PLACE ORDER (hoặc PaperExchange nếu DRY_RUN) → coin_qty = S / current_price → exchange.create_market_buy_order(symbol, coin_qty) 5. UPDATE dca_state → legs_done, total_qty, total_invested, avg_entry_price, last_buy_price 6. Telegram: entry alert ``` --- ## State Manager (Cycle Guardian) **Chạy:** `python scripts/state_manager.py --symbol ETH/USDT [--tier 4H]` Flow (chạy mỗi 15 phút): ``` A. INVALIDATION CHECK nếu current_price < ob_bottom: → ghi ob_invalidated=true vào poi_state → Telegram "OB INVALIDATED" alert → Bot NGƯNG DCA cho chu kỳ này. Giữ coin, chờ OB mới. B. TAKE PROFIT CHECK tp_pct đọc từ tier_cfg (per-tier) → fallback poi_state → fallback env tp_price = avg_entry × (1 + tp_pct / 100) nếu legs_done > 0 AND current_price ≥ tp_price: → exchange.create_market_sell_order(all coin) → Archive poi_state + dca_state (rename với timestamp) → Telegram "TAKE PROFIT" với PnL chi tiết C. Nếu không có gì → "Cycle healthy", không làm gì ``` Tier detection: `--tier 4H` arg → nếu không có, đọc `tier_name` từ `poi_state`. --- ## 3 Lớp Bảo Vệ (Layers of Protection) ``` LAYER 1 — Step Cooldown (ltf_and_execute) min_step_pct đọc từ poi_state → tier_config Ngăn DCA thêm khi giá chưa xuống đủ % Chống: double-fire khi LTF nhiễu LAYER 2 — Cycle Budget (ltf_and_execute) cycle_budget_limit từ capital_manager → poi_state Mỗi tier có ngân sách riêng, không bao giờ vượt quá S = min(E_total/n_dynamic, remaining_budget) LAYER 3 — OB Kill-Switch (htf_scanner + ltf_and_execute + state_manager) Nếu price < ob_bottom: ob_invalidated = true ltf_and_execute đọc cờ này → từ chối mọi lệnh mua state_manager phát hiện trước → gửi alert ngay lập tức ``` --- ## Adding a New Coin ```bash # 1. Thêm vào .env SYMBOLS=ETH/USDT,BTC/USDT,SOL/USDT # 2. Rebalance vốn python scripts/capital_manager.py --action rebalance # 3. Chạy HTF scan cho coin mới python scripts/htf_scanner.py --symbol SOL/USDT --tier 4H # 4. Thêm cron entries (xem mẫu ở phần Cron Setup) # 5. DRY RUN thử trước DRY_RUN=true python scripts/ltf_and_execute.py --symbol SOL/USDT ``` --- ## Risk Rules 1. **OKX API key không có quyền rút tiền** (chỉ trade + read). 2. Mỗi tier có `cycle_budget_limit` riêng — không bao giờ đi quá. 3. `MIN_RESERVE_RATIO=5%` — luôn giữ lại tối thiểu 5% equity làm cash reserve. 4. OB Invalidation → ngừng mua ngay, không cắt lỗ tự động (giữ coin chờ OB D1/W1 cao hơn). 5. Take Profit bán **toàn bộ** vị thế tại một lệnh market sell. 6. Sau TP/Invalidation → state files được archived, chu kỳ mới bắt đầu khi htf_scanner chạy lại. --- ## Directory Layout ``` scripts/ tier_config.py # 🔧 Strategy config — EDIT HERE capital_manager.py # 💰 Capital engine (cron 1h) htf_scanner.py # 🔭 HTF OB detection (cron per tier) ltf_and_execute.py # ⚡ LTF signal + orders (cron 5m) state_manager.py # 🛡️ Invalidation + TP (cron 15m) paper_exchange.py # 🧪 DRY_RUN simulation (auto-loaded) utils.py # 🔧 Shared: ccxt, N calc, state_path, Telegram state/ poi_state_ETH_USDT.json # HTF scan result per symbol (updated every 4h) dca_state_ETH_USDT.json # DCA cycle state per symbol (updated on each buy) capital_state.json # Capital allocation per tier (updated hourly) paper_state_ETH_USDT.json # DRY_RUN paper balance per symbol logs/ eth_4h.log btc_4h.log eth_ltf.log eth_state.log capital.log ... ``` --- ## State File Schemas ### `capital_state.json` ```json { "last_rebalance": "2026-03-17T13:00:00Z", "total_equity_at_rebalance": 3000.0, "tiers": { "4H": { "ideal_budget": 750.0, "cycle_budget_limit": 750.0, "locked_invested": 250.0, "ratio": 0.25, "tp_pct": 10.0 }, "D1": { "ideal_budget": 1050.0, "cycle_budget_limit": 1050.0, "locked_invested": 0.0, "ratio": 0.35, "tp_pct": 15.0 }, "W1": { "ideal_budget": 900.0, "cycle_budget_limit": 900.0, "locked_invested": 0.0, "ratio": 0.30, "tp_pct": 25.0 }, "M1": { "ideal_budget": 300.0, "cycle_budget_limit": 300.0, "locked_invested": 0.0, "ratio": 0.10, "tp_pct": 40.0 } } } ``` ### `poi_state_<SYM>.json` ```json { "symbol": "ETH/USDT", "tier_name": "4H", "htf": "4h", "ob_top": 2920.0, "ob_bottom": 2880.0, "current_price": 2895.0, "price_in_ob": true, "ob_invalidated": false, "cycle_budget_limit": 750.0, "tp_pct": 10.0, "min_step_pct": 5.0, "n_dynamic": 5, "n_method": "ob", "liquidity_levels": [2850.0, 2870.0], "ob_range_pct": 1.37, "updated_at": "2026-03-17T06:00:00Z" } ``` ### `dca_state_<SYM>.json` ```json { "cycle_id": "2026-03-17", "legs_done": 2, "total_qty": 0.12345, "total_invested": 300.0, "avg_entry_price": 2430.5, "last_buy_price": 2410.0, "last_trigger": "2026-03-17T08:30:00Z" } ``` ### `paper_state_<SYM>.json` ```json { "symbol": "ETH/USDT", "usdt_balance": 9650.0, "coin_balance": 0.14328, "total_trades": 3, "created_at": "2026-03-17T00:00:00Z", "last_updated": "2026-03-17T09:00:00Z" } ``` --- ## Verification (Dry-Run Full Pipeline) ```bash cd /opt/openclaw && source venv/bin/activate # Step 1: init capital DRY_RUN=true python scripts/capital_manager.py --action rebalance # Step 2: HTF scan (all tiers) DRY_RUN=true python scripts/htf_scanner.py --symbol ETH/USDT --tier 4H DRY_RUN=true python scripts/htf_scanner.py --symbol ETH/USDT --tier D1 # Step 3: LTF execution DRY_RUN=true python scripts/ltf_and_execute.py --symbol ETH/USDT # Step 4: State check DRY_RUN=true python scripts/state_manager.py --symbol ETH/USDT # Step 5: Capital status DRY_RUN=true python scripts/capital_manager.py --action status # Step 6: Reset demo if needed python scripts/capital_manager.py --reset-demo --symbol ETH/USDT ```


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