{"id":"fc6d429e-415e-487e-b783-43c324ec6ca9","entityType":"agent","slug":"clawhub-procaross-aicoin-freqtrade","name":"Aicoin Freqtrade","canonicalUrl":"https://www.xpersona.co/agent/clawhub-procaross-aicoin-freqtrade","canonicalPath":"/agent/clawhub-procaross-aicoin-freqtrade","generatedAt":"2026-10-11T15:26:02.620Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-11T12:14:35.491Z","emptyReason":null},"description":"Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance /... Skill: Aicoin Freqtrade Owner: procaross Summary: Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance /... Tags: aicoin:1.0.0, bot:1.0.0, crypto:1.0.0, freqtrade:1.0.0, latest:3.5.4 Version history: v3.5.4 | 2026-05-21T07:35:48.973Z | user 同步最新仓库变更:set-key 支持直接喂后台 JSON + install-test 实测修正 (catalog 分组冲突 / 403 信封归一)","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.","installCommand":"clawhub skill install s175bxjmb4brzmpkpbfqaqpc3d872sdw:aicoin-freqtrade","sourceUrl":"https://clawhub.ai/procaross/aicoin-freqtrade","homepage":"https://clawhub.ai/procaross/skills/aicoin-freqtrade","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/procaross/aicoin-freqtrade","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/procaross/skills/aicoin-freqtrade","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":61,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance /..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-11T12:14:35.491Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T12:14:35.491Z","emptyReason":null},"stars":null,"forks":null,"downloads":1067,"packageName":null,"latestVersion":"3.5.4","tractionLabel":"1.1K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T12:14:35.422Z","emptyReason":null},"lastUpdatedAt":"2026-10-11T12:14:35.491Z","lastCrawledAt":"2026-10-11T12:14:35.422Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-12T12:14:35.422Z","lastVerifiedAt":null,"highlights":[{"version":"3.5.4","createdAt":"2026-05-21T07:35:48.973Z","changelog":"同步最新仓库变更:set-key 支持直接喂后台 JSON + install-test 实测修正 (catalog 分组冲突 / 403 信封归一)","fileCount":15,"zipByteSize":48452},{"version":"3.5.3","createdAt":"2026-03-10T19:19:31.702Z","changelog":"- Added support for \"limit\" parameter in AiCoin funding_rate API call within strategy templates. - Updated SKILL.md examples and references to use funding_rate(symbol, weighted=True, limit='5') for more accurate and up-to-date AiCoin data integration in custom strategies.","fileCount":13,"zipByteSize":38523},{"version":"3.5.2","createdAt":"2026-03-10T19:00:22.041Z","changelog":"Version 3.5.2 - Updated package dependency versions in package.json. - No functional changes to code or documentation. - Maintenance update; ensures compatibility and stability.","fileCount":13,"zipByteSize":38224},{"version":"3.5.1","createdAt":"2026-03-10T18:59:40.171Z","changelog":"Version 3.5.1 - Updated package.json with new version information. - No functional or behavioral changes to the skill itself.","fileCount":13,"zipByteSize":38224},{"version":"3.5.0","createdAt":"2026-03-10T18:59:01.832Z","changelog":"- Added explicit notice: Freqtrade does not support grid strategies (“网格策略”). - Updated documentation to advise users to use trend-following or range-bound strategies instead, if grid strategies are requested. - No code logic changes; this update improves clarity for users regarding strategy support limits.","fileCount":13,"zipByteSize":38224},{"version":"3.4.9","createdAt":"2026-03-10T17:24:25.971Z","changelog":"- Now explicitly recommends using only ft-deploy.mjs or ft.mjs for all Freqtrade actions, including status and backtesting. - Updated critical rules section in documentation to clarify not to run freqtrade commands directly (e.g., freqtrade status, freqtrade backtesting). - Minor documentation clarifications and emphasis in SKILL.md for safer and more standardized workflow.","fileCount":13,"zipByteSize":38107},{"version":"3.4.8","createdAt":"2026-03-10T16:58:12.560Z","changelog":"- Clarified instructions: now explicitly require users to `cd` to the skill's directory before running any script (especially `ft-deploy.mjs`). - Updated warning at the top of SKILL.md to emphasize changing to the correct working directory for all script operations. - No changes to logic or features; documentation improvement only.","fileCount":13,"zipByteSize":37865},{"version":"3.4.7","createdAt":"2026-03-10T16:50:42.225Z","changelog":"- Improved reliability of the ft-deploy.mjs deployment script. - Updated package dependencies in package.json for enhanced stability.","fileCount":13,"zipByteSize":37716}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s175bxjmb4brzmpkpbfqaqpc3d872sdw:aicoin-freqtrade","setupComplexity":"low","setupSteps":["Node.js workspace detected. Install dependencies securely: run `npm ci --ignore-scripts` to prevent post-install lifecycle triggers from running arbitrary code, then selectively audit the dependency tree.","Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-11T15:26:02.616Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-procaross-aicoin-freqtrade/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-11T12:14:35.491Z","emptyReason":null},"readme":"Skill: Aicoin Freqtrade\n\nOwner: procaross\n\nSummary: Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance /...\n\nTags: aicoin:1.0.0, bot:1.0.0, crypto:1.0.0, freqtrade:1.0.0, latest:3.5.4\n\nVersion history:\n\nv3.5.4 | 2026-05-21T07:35:48.973Z | user\n\n同步最新仓库变更:set-key 支持直接喂后台 JSON + install-test 实测修正 (catalog 分组冲突 / 403 信封归一)\n\nv3.5.3 | 2026-03-10T19:19:31.702Z | auto\n\n- Added support for \"limit\" parameter in AiCoin funding_rate API call within strategy templates.\n- Updated SKILL.md examples and references to use funding_rate(symbol, weighted=True, limit='5') for more accurate and up-to-date AiCoin data integration in custom strategies.\n\nv3.5.2 | 2026-03-10T19:00:22.041Z | auto\n\nVersion 3.5.2\n\n- Updated package dependency versions in package.json.\n- No functional changes to code or documentation.\n- Maintenance update; ensures compatibility and stability.\n\nv3.5.1 | 2026-03-10T18:59:40.171Z | auto\n\nVersion 3.5.1\n\n- Updated package.json with new version information.\n- No functional or behavioral changes to the skill itself.\n\nv3.5.0 | 2026-03-10T18:59:01.832Z | auto\n\n- Added explicit notice: Freqtrade does not support grid strategies (“网格策略”). \n- Updated documentation to advise users to use trend-following or range-bound strategies instead, if grid strategies are requested.\n- No code logic changes; this update improves clarity for users regarding strategy support limits.\n\nv3.4.9 | 2026-03-10T17:24:25.971Z | auto\n\n- Now explicitly recommends using only ft-deploy.mjs or ft.mjs for all Freqtrade actions, including status and backtesting.\n- Updated critical rules section in documentation to clarify not to run freqtrade commands directly (e.g., freqtrade status, freqtrade backtesting).\n- Minor documentation clarifications and emphasis in SKILL.md for safer and more standardized workflow.\n\nv3.4.8 | 2026-03-10T16:58:12.560Z | auto\n\n- Clarified instructions: now explicitly require users to `cd` to the skill's directory before running any script (especially `ft-deploy.mjs`).\n- Updated warning at the top of SKILL.md to emphasize changing to the correct working directory for all script operations.\n- No changes to logic or features; documentation improvement only.\n\nv3.4.7 | 2026-03-10T16:50:42.225Z | auto\n\n- Improved reliability of the ft-deploy.mjs deployment script.\n- Updated package dependencies in package.json for enhanced stability.\n\nv3.4.6 | 2026-03-10T16:10:47.270Z | auto\n\nNo changes detected in this release.\n\nv3.4.5 | 2026-03-10T15:31:27.398Z | auto\n\n- Documentation updated for clarity and formatting in SKILL.md.\n- No functional or API changes; only doc improvements. \n- Usage instructions and SDK reference remain unchanged.\n- No changes to scripts or logic.\n\nv3.4.4 | 2026-03-10T09:21:31.427Z | auto\n\n- Added improved error handling and messaging in deployment and backtest scripts.\n- Updated dependencies in package.json for better reliability.\n- Minor internal refactoring in scripts/ft-deploy.mjs for maintainability.\n\nv3.4.3 | 2026-03-09T09:26:37.817Z | auto\n\n- Added a prominent notice specifying all `node scripts/...` commands must be run from the skill directory.\n- No code or functionality changes; documentation update for correct script execution.\n\nv3.4.2 | 2026-03-09T08:26:54.788Z | auto\n\nNo changes detected in this version.\n\n- Version number updated to 3.4.2\n- No modifications to code or documentation\n\nv3.4.1 | 2026-03-09T08:25:26.449Z | auto\n\n- Updated SDK usage comments in the documentation to use Chinese tier names (基础版, 标准版, 高级版, 专业版) instead of English.\n- No changes to application logic; documentation and sample code only updated for localization/consistency.\n- No changes required for existing strategies or user integration.\n\nv3.3.1 | 2026-03-09T07:36:14.037Z | auto\n\n- Minor internal update to `lib/aicoin-api.mjs`.\n- No changes to skill features or user-facing behavior.\n\nv3.3.0 | 2026-03-09T07:29:34.740Z | auto\n\naicoin-freqtrade 3.3.0\n\n- Updated internal dependencies as reflected in package.json.\n- Minor updates to lib/aicoin-api.mjs.\n- No user-facing changes documented in SKILL.md.\n\nv3.2.0 | 2026-03-09T04:03:50.982Z | user\n\nrework SKILL.md: enable custom strategy code, add AiCoin Python SDK reference, integration patterns\n\nv3.1.0 | 2026-03-09T03:36:36.170Z | user\n\nexpand create_strategy with 17 indicators, stronger anti-bypass rules\n\nv3.0.9 | 2026-03-06T11:13:21.217Z | user\n\nProactive security notice on every script execution\n\nv3.0.8 | 2026-03-06T10:46:31.273Z | user\n\nAdd security notice to Paid Feature Guide\n\nv3.0.7 | 2026-03-06T10:08:46.038Z | user\n\nAdd API key security notice\n\nv3.0.6 | 2026-03-06T10:03:07.822Z | user\n\nAdd API key security notice in Setup section\n\nv3.0.3 | 2026-03-06T02:54:33.892Z | auto\n\n- Bumped package version to 3.0.3 (package.json update).\n- No user-facing features or documentation changes.\n\nv3.0.2 | 2026-03-06T02:42:13.968Z | auto\n\n- Removed the _meta.json file from the project.\n- Updated dependencies and/or metadata in package.json.\n- No changes to core logic or documented functionality.\n\nv2.3.2 | 2026-03-06T02:36:11.499Z | auto\n\n- Maintenance update: SKILL.md unchanged; no user-facing skill behavior or documentation updates.\n- No functional or interface/application changes.\n\nv2.3.1 | 2026-03-06T02:33:52.091Z | auto\n\nVersion 2.3.1\n\n- Added _meta.json file to the repository for enhanced metadata management.\n- No changes to core logic or user-facing functionality.\n\nv2.3.0 | 2026-03-06T02:31:37.784Z | auto\n\n- Added explicit instructions for handling AiCoin paid data when generating strategies—now requires user confirmation and guidance before inclusion.\n- Documented environment variable loading order and clarified API key setup for paid features.\n- Updated strategy generation rules to distinguish between pure technical strategies and paid AiCoin data requirements.\n- Improved documentation for prerequisites and setup, aligning with internal environment loading standards.\n- Removed deprecated file (_meta.json) for cleanup.\n\nv2.2.0 | 2026-03-06T02:28:50.638Z | user\n\nv2.2.0: CLI structured JSON errors for invalid params\n\nv2.1.0 | 2026-03-06T02:02:39.006Z | user\n\nv2.1.0: Add Setup section with env guide, Paid Feature Guide with strategy tier table, fix tier labels\n\nv2.0.0 | 2026-03-06T01:34:34.820Z | user\n\nv2.0: Split from unified aicoin skill. Strategy creation, backtesting, deployment with paid-key detection.\n\nv1.0.0 | 2026-03-03T00:43:44.388Z | user\n\nInitial release\n\nArchive index:\n\nArchive v3.5.4: 15 files, 48452 bytes\n\nFiles: lib/aicoin_data.py (14399b), lib/coinclaw-env.mjs (5225b), lib/defaults.json (227b), lib/freqtrade-api.mjs (4056b), lib/strategy-builder.mjs (24520b), package.json (93b), scripts/ft-deploy.mjs (39953b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (9251b), skill-card.md (2896b), SKILL.md (18939b), strategies/FundingRateStrategy.py (6272b), strategies/LiquidationHunterStrategy.py (7464b), strategies/WhaleFollowStrategy.py (6338b), _meta.json (135b)\n\nFile v3.5.4:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance / open positions / 盈亏. Trigger words: 'write strategy', 'create strategy', 'backtest', 'switch strategy', 'switch to live', 'open positions', 'P&L', '写策略', '创建策略', '回测', '部署策略', '切策略', '切实盘', '当前持仓', '今天赚多少', '盈亏'. In CoinClaw containers (OpenClaw / Hermes / Claude Code) freqtrade is a supervisord-managed daemon on :8080 — this skill auto-detects engine + paths via lib/coinclaw-env.mjs and never spawns competing freqtrade processes. Outside CoinClaw it falls back to host mode (clone freqtrade + nohup). For prices/charts use aicoin-market. For exchange trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n# AiCoin Freqtrade\n\nFreqtrade 策略 / 回测 / 部署 / 实时控制 — 跨 CoinClaw 三引擎自动适配。\n\n## 关键原则(读完再动手)\n\n### 一、CoinClaw 容器里 freqtrade 是常驻 daemon\n\nOpenClaw / Hermes / Claude Code 三个引擎容器都通过 supervisord 把 freqtrade 起为常驻进程, 监听 `127.0.0.1:8080`, 默认跑 `NoOpStrategy`(空跑). **不要自己起 freqtrade 进程** — 会跟 daemon 抢端口, dashboard 立刻 offline.\n\n正确流程是: 写策略文件 → 调 `ft-deploy.mjs deploy {\"strategy\":\"...\"}` → 脚本改 config + 重启 daemon. dashboard 会自动刷出新策略.\n\n`scripts/ft.mjs` + `scripts/ft-deploy.mjs` 内置三引擎自动识别(`lib/coinclaw-env.mjs`), 路径 / auth / supervisord socket 都自动解析, **agent 不用关心是哪个引擎**.\n\n### 二、永远先调 freqtrade REST API, 不要\"自己计算\"\n\n| 用户问 | 必须先调 |\n|---|---|\n| 现在赚多少 / 总盈亏 / 今天涨了多少 | `ft.mjs profit` (`/api/v1/profit`) |\n| 持仓 / 现在开了哪些 | `ft.mjs trades_open` (`/api/v1/status`) |\n| 余额 / 资金多少 | `ft.mjs balance` (`/api/v1/balance`) |\n| 跑的什么策略 / 当前模式 | `ft.mjs daemon_info` 或 `config` |\n| 历史交易 / 已平仓 | `ft.mjs trades_history` |\n| 单交易对绩效 | `ft.mjs profit_per_pair` |\n\n**dashboard 数字对齐规则(关键)**: 用户问\"赚了多少\"必须报告**两个数字**:\n- **已平仓累计盈亏** = `profit_closed_coin` (USDT) — **dashboard 顶栏的累计盈亏 = 这个**\n- **含浮动总盈亏** = `profit_all_coin` (USDT) — 已平仓 + 当前持仓的浮动盈亏\n\n只调 `/status` 拿持仓浮动盈亏会漏掉已平仓部分, 导致跟 dashboard 数字不一致 — 用户立刻发现, 信任度归零.\n\n### 三、切策略 / 切实盘 / 切交易对必须走脚本\n\nconfig.json 是 daemon 启动时读一次, 手动改完不会自动生效. 必须用:\n\n| 操作 | 命令 | 是否需要 daemon 重启 |\n|---|---|---|\n| 切策略 | `ft.mjs set_strategy {\"strategy\":\"X\"}` | 必须重启 (~30s) |\n| 切交易对 | `ft.mjs set_pairs {\"pairs\":[...]}` | 不重启, `reload_config` 即可 |\n| 切实盘/模拟 | `ft.mjs set_dry_run {\"dry_run\":false}` | 必须重启 |\n| reload 配置 | `ft.mjs reload` | 不重启 |\n\n或者一次完成所有变更: `ft-deploy.mjs deploy {\"strategy\":\"X\",\"pairs\":[\"BTC/USDT:USDT\"],\"dry_run\":false}`.\n\n**任何直接修改 config.json 的操作(包括手动编辑 pair_whitelist / minimal_roi / stoploss 等), 改完后必须立即调 `ft.mjs reload`** — 否则 daemon 仍用内存里的旧配置运行, 白名单/止损等改动不会生效. 忘了 reload 是最常见的\"改了但没用\"的原因.\n\n**chat 主动发起的高 stake 操作必须强 confirm**(违反即错):\n\n适用: 用户在 chat 里说\"平掉\"、\"切实盘\"、\"卖了\"、\"开仓\"等 — 通过 agent 调用 `force_exit` / `force_enter` / `set_dry_run` 的操作.\n\n流程:\n1. **先列预览**: 动哪个 trade / pair / 当前盈亏 / 估算损益 / dry_run vs live / 余额状况\n2. **明确等用户输\"确认\"或\"yes\"** 才真调 `force_exit` / `set_dry_run` / `force_enter`\n3. 即使用户语气笃定(\"平了\",\"直接切\"), 也必须先预览等确认\n\n**不需要 confirm 的**:\n- 查询类(查持仓 / 盈亏 / 状态) — 直接读\n- **freqtrade daemon 自己根据策略信号自动开/平仓** — 这是 daemon 本职工作, 用户切实盘那一刻就授权了, agent 不在这个链路里, 不要拦也不需要 confirm\n- 非破坏性配置(`set_pairs` 加币对、`reload`) — 列改动表然后直接执行\n\n**违反规则的反例**:\n- ❌ 用户说\"平掉\", 你直接调 `force_exit` 平了真持仓 (K-Live-3 dogfood 抓到的真 bug)\n- ❌ 用户说\"切实盘\", 你不列 .env key / 余额 / 风险就直接 `set_dry_run {\"dry_run\":false}`\n- ✅ 用户说\"平掉\", 你列\"持仓: BNB/USDT 0.05 +$1.07, 平这单吗? dry_run=true 模拟盘\", 等用户确认\n\n**写策略 + 切策略 倾向分两轮**(create_strategy 一轮, set_strategy 一轮). 不是技术限制,是 UX 选择:\n1. 第一轮: 写完策略文件 → 告诉用户\"已生成 X.py, 要切上去吗?\"\n2. 用户确认后第二轮: `set_strategy` 切策略 + 重启 daemon (~30s)\n\n这样用户切策略前能 review 生成文件; daemon 重启 30s 期间用户对状态有预期, 不会误判 chat 卡死. 用户明确说\"一气呵成做完\"也可以单 turn 跑完两步, 但默认分轮.\n\n### 四、Freqtrade 不支持网格策略 (grid)\n\n用户问网格时直接说明限制 + 建议趋势跟踪 / 区间策略 / 网格回报模拟器替代. 不要硬写一个伪网格.\n\n## 快速参考\n\n| 任务 | 命令 |\n|------|------|\n| 看 daemon 状态 + 配置 | `node scripts/ft-deploy.mjs check` 或 `ft.mjs daemon_info` |\n| 看策略列表 | `node scripts/ft-deploy.mjs strategy_list` |\n| 创建策略(快速生成器) | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\",\"ema\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| 部署策略到 daemon | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\"}'` |\n| 部署+切实盘 | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false}'` |\n| 回测 | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\"}'` |\n| Hyperopt 调参 | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"epochs\":100}'` |\n| 看盈亏 | `node scripts/ft.mjs profit` |\n| 看持仓 | `node scripts/ft.mjs trades_open` |\n| 看余额 | `node scripts/ft.mjs balance` |\n| 切交易对 | `node scripts/ft.mjs set_pairs '{\"pairs\":[\"BTC/USDT:USDT\",\"ETH/USDT:USDT\"]}'` |\n| 重启 daemon | `node scripts/ft.mjs restart` |\n| 看日志 | `node scripts/ft-deploy.mjs logs '{\"lines\":100}'` |\n\n## 创建策略：先判断走哪条路\n\n**判断规则**：\n- 用户只给了笼统描述（\"RSI 策略\"、\"均线交叉\"、\"布林带回归\"）且没指定具体参数细节 → **A. 快速生成器**\n- 用户给了具体逻辑（自定义入场/出场条件、跨周期共振、多币种轮动、复合指标、自定义仓位管理）→ **B. 直接写 Python**\n- 用 A 生成后用户要改细节 → 直接编辑生成的 .py 文件，不要重新 create_strategy 覆盖\n\n### A. 快速生成器(简单策略)\n\n`create_strategy` 一条命令生成一个可跑的策略文件。适合\"先跑起来再调\"的场景：\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"RSILong\",\"timeframe\":\"1h\",\"indicators\":[\"rsi\"],\"direction\":\"long\"}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\n可选 `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`.\n\n可选 `direction`: `\"long\"` (默认,只做多) | `\"short\"` (只做空) | `\"both\"` (双向)。\n**用户说\"RSI<30 买入, RSI>70 卖出\"→ direction=\"long\"**(RSI>70 = 平多, 不是开空)。只有用户明确说\"做空 / 双向 / 多空都做\"时才用 `\"both\"` 或 `\"short\"`。\n\n可选 `aicoin_data`: `funding_rate`、`ls_ratio`、`big_orders`、`liquidation_map`（都需付费套餐），`open_interest`（v3 聚合 OI 历史暂未接通，会自动降级到默认值）。\n\n**生成器的局限**：只能组合预设指标，不支持跨周期、多币种轮动、自定义复合指标。遇到这些需求直接走 B。\n\n### B. 自定义 Python 策略 (复杂逻辑)\n\n直接写 `.py` 文件到 daemon 的 strategy 目录。用这条路可以实现任何 freqtrade 支持的策略逻辑（跨周期 informative pairs、自定义仓位管理、多指标复合条件等）。\n\n三引擎该目录不同, **从 `daemon_info` 拿**或用 `Write` 工具写到下面任一路径(脚本会自动用 `/api/v1/show_config` 验证):\n\n| 引擎 | strategy 目录 |\n|---|---|\n| OpenClaw | `~/.openclaw/workspace/strategies/` |\n| Hermes | `/workspace/strategies/` |\n| Claude Code | `/workspace/strategies/` |\n\n用 AiCoin Python SDK (`aicoin_data.py`, image build 时已复制到上面目录, 也由 `create_strategy` 兜底拷贝):\n\n它封装了 AiCoin Open API v3：\n\n```python\nfrom aicoin_data import AiCoinData\n\nac = AiCoinData(cache_ttl=300)   # 自动从 .env 读 key，内置 5 分钟缓存\n\n# 高层信号 —— 直接返回能用的数字，丢进策略即可\nac.whale_signal(\"BTC/USDT:USDT\", \"binance\")        # 大单买卖压力 -1..+1\nac.ls_ratio_norm()                                 # 多空比 0..1（>0.5 偏多）\nac.funding_rate_pct(\"BTC/USDT:USDT\", \"binance\")    # 最新资金费率（百分比）\nac.liq_bias(\"BTC/USDT:USDT\", \"binance\")            # 清算图方向偏向 -1..+1\n\n# 原始数据\nac.coin_ticker(\"bitcoin,ethereum\")                 # 实时行情\nac.klines(\"BTC/USDT\", \"binance\", interval=\"1h\", limit=100)\n\n# 任意 v3 接口 —— path 是 /api/v3/ 后那段，清单见 https://open.aicoin.com/api/v3/_catalog\nac.get(\"markets/hot-coins\", {\"tab_key\": \"defi\"})\nac.get(\"hyperliquid/whales/open-positions\", {\"coin\": \"BTC\"})\n```\n\n回测期 AiCoin 实时数据不可用，高层信号会抛异常 —— 策略里要 `try/except` 兜底用默认值。资金费率、大单、清算等需要付费套餐，没权限同样抛异常（一样兜底）。\n\n#### 完整模板\n\n```python\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    _ac_funding_rate = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # AiCoin 数据 (live/dry_run only, backtest 用默认值 0.0)\n        dataframe['funding_rate'] = 0.0\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            self._ac_funding_rate = ac.funding_rate_pct(pair, exchange)\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n写完后用 `deploy {\"strategy\":\"MyStrategy\"}` 让 daemon 切到这个策略.\n\n### AiCoin 数据集成模式\n\n| AiCoin 数据 | 信号逻辑 | 套餐 |\n|---|---|---|\n| `funding_rate` | 大于 0.01% → 多头过度 → 空信号; 小于 -0.01% → 多信号 | 基础版 |\n| `ls_ratio` | 小于 0.45 (空头多) → 反向做多; 大于 0.55 → 反向做空 | 基础版 |\n| `big_orders` | `(buy_vol-sell_vol)/total > 0.3` → 鲸鱼买入做多 | 标准版 |\n| `open_interest` | OI 涨 + 价涨 = 健康趋势; OI 涨 + 价跌 = 反转 | 专业版 |\n| `liquidation_map` | 上方爆仓多 → 多头挤压 → 做多 | 高级版 |\n\n### 回测注意事项\n\nAiCoin 实时数据**不在历史区间内可用**. 回测时:\n\n- AiCoin 列用默认值 (`funding_rate=0.0`, `ls_ratio=0.5`, `whale_signal=0.0`)\n- 回测结果只反映**技术指标**部分\n- live/dry_run 跑的时候才用真实 AiCoin 数据, 表现应该比回测好\n\n向用户报告回测结果时必须主动说明这点, 不要让用户以为回测包含了 AiCoin 信号.\n\n## 脚本 API\n\n### `scripts/ft-deploy.mjs` — 策略 / 回测 / 部署\n\n| Action | 参数示例 |\n|---|---|\n| `check` | (无) — 返回 daemon 状态 + 配置 + 余额 |\n| `daemon_info`(在 ft.mjs) | (无) — 单调用拿全 |\n| `deploy` | `{\"strategy\":\"MyStrat\"}` 或 `{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}` |\n| `create_strategy` | `{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"direction\":\"long\",\"aicoin_data\":[\"funding_rate\"]}` |\n| `backtest` | `{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}` |\n| `hyperopt` | `{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `download_data` | `{\"timeframe\":\"1h\",\"timerange\":\"20250101-\"}` |\n| `strategy_list` | (无) |\n| `backtest_results` | (无) — 列最近 10 个回测结果文件名 |\n| `start` / `stop` | (无) — coinclaw 模式调 supervisorctl, host 模式管 PID |\n| `status` / `logs` | `{\"lines\":100}` |\n| `update` / `remove` | coinclaw 模式 no-op (提示用 helm upgrade / web UI 删 instance) |\n\n### `scripts/ft.mjs` — 实时控制 (REST + 配置变更)\n\n| Action | 用途 |\n|---|---|\n| `daemon_info` | 一次拿 strategy / mode / pairs / open trades 数量 |\n| `profit` | 已平仓累计 + 含浮动总盈亏 (回答盈亏类问题必须先调) |\n| `trades_open` | 当前持仓 (调 /status) |\n| `trades_history` | 已平仓交易 |\n| `balance` | 余额 |\n| `profit_per_pair` | 每交易对绩效 |\n| `daily` / `weekly` / `monthly` | 时间维度统计 |\n| `force_enter` / `force_exit` | 手动开/平仓 |\n| `set_strategy` | 切策略 (改 config + 重启 daemon) |\n| `set_pairs` | 改交易对白名单 (reload, 不重启) |\n| `set_dry_run` | 切实盘/模拟 (改 config + 重启 daemon) |\n| `restart` | 重启 freqtrade daemon (supervisorctl + kill 兜底) |\n| `reload` | reload_config 而不重启 |\n| `start` / `stop` / `ping` / `version` / `health` | 标准 REST |\n| `logs` | freqtrade 自带 /logs 接口 |\n\n### `scripts/ft-dev.mjs` — 调试 (回测 / 蜡烛 / 策略详情)\n\n`backtest_start` / `backtest_status` / `backtest_history` / `candles_live` / `candles_analyzed` / `strategy_list` / `strategy_get` / `whitelist` / `blacklist` 等.\n\n## 环境变量与认证\n\n`.env` 自动加载顺序:\n\n- coinclaw 容器内: `/workspace/.env` (Hermes/CC) 或 `/home/node/.openclaw/workspace/.env` (OpenClaw)\n- host 模式: cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\nfreqtrade REST 认证: `freqtrade-api.mjs` 自动从容器内 `.ft_api_pass` 文件读密码, **agent 不用配 FREQTRADE_USERNAME / FREQTRADE_PASSWORD**. 用户也可以通过 `.env` 覆盖.\n\n交易所 key 在 web UI 的 EnvSection 里配置, 写到 .env 后 entrypoint 会自动 patch 进 freqtrade `config.json`. **agent 不要直接读 .env 给用户看交易所 key**.\n\nAiCoin Open API key (用于策略集成 AiCoin 数据):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\n\n## 付费功能引导\n\n返回 304 / 403 时 **不要重试**, 直接告诉用户:\n\n| 套餐 | 价格 | 用途 |\n|---|---|---|\n| 免费版 | $0 | 纯技术指标 |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\n获取地址: https://www.aicoin.com/opendata\n\n## 跨 skill 引用\n\n| 用户问 | 用 |\n|---|---|\n| 单纯查行情 / K 线 / 新闻 / 资金费率 (不开仓) | **aicoin-market** |\n| 直接下单 / 开仓 / 平仓 (不通过 freqtrade) | **aicoin-trading** |\n| Hyperliquid 鲸鱼 / 持仓 / 清算 | **aicoin-hyperliquid** |\n| 链上 DEX swap / 钱包余额 / gas | **aicoin-onchain** |\n| 余额 / 持仓 / 注册 / API key 配置 (账户类) | **aicoin-account** |\n\n## 常见 pitfall\n\n- **不要 `cat /workspace/.ft_api_pass`** 把内部 daemon 密码贴到 chat — 直接用 `ft.mjs` 调 REST, 脚本内部读密码不会泄漏.\n- **不要在 chat 里 echo 用户的交易所 key** — 这些是高敏数据, 引导用户去 EnvSection 配置.\n- **不要自己心算 RSI / MACD / EMA** — freqtrade 算出的值跟你心算结果会差, 用 `ft-dev.mjs candles_analyzed` 拿 daemon 的真实指标.\n- **不要\"先 stop daemon 再 freqtrade trade ... &\"** — 那是绕过 supervisord, 下次 dashboard 看到的还是老的 daemon 状态. 必须用 `set_strategy` / `deploy` / `restart`.\n- **回测拿不到 AiCoin 数据是正常的** — 不要造假 CSV 喂回测, 直接告诉用户回测只反映技术指标. 见根 AGENTS.md 的\"数据准确性铁则\".\n\nFile v3.5.4:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.4\",\n  \"publishedAt\": 1779348948973\n}\n\nFile v3.5.4:skill-card.md\n\n## Description:\n\nHelps agents create, backtest, tune, deploy, and operate Freqtrade strategies with AiCoin market data integrations across CoinClaw-style agent containers and host-mode environments.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[procaross](https://clawhub.ai/user/procaross)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nExternal developers and trading-bot operators use this skill to generate and manage Freqtrade strategies, run backtests and hyperopt, switch strategies or trading pairs, and query live bot status, balances, positions, and profit/loss. It is intended for users who understand the risks of automated cryptocurrency trading and can review generated strategy files before deployment.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The skill can control a Freqtrade bot and may interact with configured exchange credentials, which can lead to real trading losses if used in live mode.\n\nMitigation: Start in dry-run mode, verify exchange credentials and balances separately, and require explicit confirmation before live-mode or manual open/close actions.\n\nRisk: Generated or modified strategy files can affect automated trading behavior.\n\nMitigation: Review strategy code and configuration changes before deployment, then backtest or dry-run before allowing live trading.\n\nRisk: Crafted action parameters or host-mode setup paths can run unintended commands or code.\n\nMitigation: Avoid untrusted action inputs, prefer the managed CoinClaw daemon path, and install host prerequisites independently instead of relying on host-mode auto-install.\n\nRisk: Pointing AICOIN_BASE_URL at a non-AiCoin host can redirect API traffic and credentials.\n\nMitigation: Keep AICOIN_BASE_URL unset or set only to an AiCoin-controlled endpoint.\n\n## Reference(s):\n\n- [AiCoin Open Data](https://www.aicoin.com/opendata)\n- [AiCoin Open API v3 Catalog](https://open.aicoin.com/api/v3/_catalog)\n- [ClawHub skill page](https://clawhub.ai/procaross/skills/aicoin-freqtrade)\n- [Publisher profile](https://clawhub.ai/user/procaross)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with inline shell commands, JSON parameters, and generated Python strategy code]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May create or modify Freqtrade strategy and configuration files when used by an agent with filesystem and command execution access.]\n\n## Skill Version(s):\n\n3.5.4 (source: ClawHub release evidence; artifact package.json reports 3.5.2)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nFile v3.5.4:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}\n\nFile v3.5.4:package.json\n\n{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.2\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n\nArchive v3.5.3: 13 files, 38523 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (53930b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (15367b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)\n\nFile v3.5.3:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about writing trading strategies, backtesting, deploying Freqtrade bots, quantitative trading, or strategy optimization. Trigger words: 'write strategy', 'create strategy', 'backtest', 'deploy Freqtrade', 'deploy bot', 'quantitative', 'hyperopt', '写策略', '创建策略', '回测', '部署', '量化', '策略优化'. This skill provides: (1) create_strategy quick generator with 17 indicators, (2) AiCoin Python SDK (aicoin_data.py) for integrating real market data into custom strategies, (3) deploy/backtest/hyperopt tools. ALWAYS actively use AiCoin data (funding rate, L/S ratio, whale orders, etc.) in strategies when the user's API key supports it. For prices/charts use aicoin-market. For trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n> **⚠️ 运行脚本: 必须先 cd 到本 SKILL.md 所在目录再执行。示例: `cd ~/.openclaw/workspace/skills/aicoin-freqtrade && node scripts/ft-deploy.mjs ...`**\n\n# AiCoin Freqtrade\n\nFreqtrade strategy creation, backtesting, and deployment powered by [AiCoin Open API](https://www.aicoin.com/opendata).\n\n## Critical Rules\n\n1. **ALWAYS use `ft-deploy.mjs backtest`** for backtesting. NEVER write custom backtest scripts. NEVER use simulated/fabricated data.\n2. **ALWAYS use `ft-deploy.mjs deploy`** for deployment. NEVER use Docker. NEVER manually run `freqtrade` commands.\n3. **NEVER manually edit Freqtrade config files.** Use `ft-deploy.mjs` actions.\n4. **NEVER manually run `freqtrade trade`, `freqtrade status`, `freqtrade backtesting`, `source .venv/bin/activate`, or `pip install freqtrade`.** Always use ft-deploy.mjs or ft.mjs instead.\n5. **ACTIVELY use AiCoin data** in strategies. Check what data the user's API key supports and integrate it. Don't only use basic indicators when richer data is available.\n6. **Freqtrade 不支持网格策略(grid)。** 用户问网格时，说明限制并建议用趋势跟踪或区间策略替代。\n\n## Two Ways to Create Strategies\n\n### Option A: Quick Generator (for simple strategies)\n\n`create_strategy` generates a ready-to-backtest strategy file with selected indicators and optional AiCoin data:\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\nAvailable `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`\n\n### Option B: Write Custom Strategy Code (for complex/custom strategies)\n\nWhen users need custom logic beyond what `create_strategy` offers, write a Python strategy file directly. **Use the AiCoin Python SDK** (`aicoin_data.py`, auto-installed at `~/.freqtrade/user_data/strategies/`) to integrate real market data.\n\nStrategy file location: `~/.freqtrade/user_data/strategies/YourStrategyName.py`\n\n#### AiCoin Python SDK Reference\n\n```python\nfrom aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis\n```\n\n#### Complete Strategy Template (copy and customize)\n\n```python\n# MyCustomStrategy - Description\n# Uses AiCoin data in live/dry_run mode\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyCustomStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    # Hyperopt parameters\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    # AiCoin data cache\n    _ac_funding_rate = 0.0\n    _ac_ls_ratio = 0.5\n    _ac_whale_signal = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # === Technical Indicators (always available) ===\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # MACD\n        ema12 = dataframe['close'].ewm(span=12, adjust=False).mean()\n        ema26 = dataframe['close'].ewm(span=26, adjust=False).mean()\n        dataframe['macd'] = ema12 - ema26\n        dataframe['macd_signal'] = dataframe['macd'].ewm(span=9, adjust=False).mean()\n\n        # EMA\n        dataframe['ema_fast'] = dataframe['close'].ewm(span=8, adjust=False).mean()\n        dataframe['ema_slow'] = dataframe['close'].ewm(span=21, adjust=False).mean()\n\n        # === AiCoin Data (live/dry_run only) ===\n        dataframe['funding_rate'] = 0.0\n        dataframe['ls_ratio'] = 0.5\n        dataframe['whale_signal'] = 0.0\n\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:  # Update every 5 min\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            # Apply latest AiCoin data to current candle\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n            dataframe.iloc[-1, dataframe.columns.get_loc('ls_ratio')] = self._ac_ls_ratio\n            dataframe.iloc[-1, dataframe.columns.get_loc('whale_signal')] = self._ac_whale_signal\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        \"\"\"Fetch latest AiCoin data. Called every 5 min in live mode.\"\"\"\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData, ccxt_to_aicoin\n\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            symbol = ccxt_to_aicoin(pair, exchange)\n\n            # Funding rate (基础版)\n            try:\n                data = ac.funding_rate(symbol, weighted=True, limit='5')\n                items = data.get('data', [])\n                if isinstance(items, list) and items:\n                    latest = items[0]\n                    if isinstance(latest, dict) and 'close' in latest:\n                        self._ac_funding_rate = float(latest['close']) * 100\n            except Exception as e:\n                logger.debug(f\"AiCoin funding_rate unavailable: {e}\")\n\n            # Long/short ratio (基础版)\n            try:\n                ls = ac.ls_ratio()\n                detail = ls.get('data', {}).get('detail', {})\n                if detail:\n                    ratio = float(detail.get('last', 1.0))\n                    self._ac_ls_ratio = max(0.0, min(1.0, ratio / (1.0 + ratio)))\n            except Exception as e:\n                logger.debug(f\"AiCoin ls_ratio unavailable: {e}\")\n\n            # Whale orders (标准版)\n            try:\n                orders = ac.big_orders(symbol)\n                if 'data' in orders and isinstance(orders['data'], list):\n                    buy_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                 if o.get('side', '').lower() in ('buy', 'bid', 'long'))\n                    sell_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                  if o.get('side', '').lower() in ('sell', 'ask', 'short'))\n                    total = buy_vol + sell_vol\n                    if total > 0:\n                        self._ac_whale_signal = (buy_vol - sell_vol) / total\n            except Exception as e:\n                logger.debug(f\"AiCoin big_orders unavailable: {e}\")\n\n        except ImportError:\n            logger.warning(\"aicoin_data module not found. Run ft-deploy.mjs deploy to install.\")\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Long: RSI oversold + MACD bullish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['macd'] > dataframe['macd_signal']) &\n            (dataframe['ema_fast'] > dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] <= 0.55) &        # More shorts = contrarian long\n            (dataframe['whale_signal'] >= -0.3) &     # Whales not heavily selling\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n\n        # Short: RSI overbought + MACD bearish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['macd'] < dataframe['macd_signal']) &\n            (dataframe['ema_fast'] < dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] >= 0.45) &        # More longs = contrarian short\n            (dataframe['whale_signal'] <= 0.3) &      # Whales not heavily buying\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n### AiCoin Data Integration Patterns\n\nUse these patterns to integrate specific AiCoin data into entry/exit conditions:\n\n| AiCoin Data | Signal Logic | Tier |\n|-------------|-------------|------|\n| `funding_rate` | Rate > 0.01% → market over-leveraged long → short signal; Rate < -0.01% → long signal | 基础版 |\n| `ls_ratio` | Ratio < 0.45 (more shorts) → contrarian long; Ratio > 0.55 (more longs) → contrarian short | 基础版 |\n| `big_orders` | `(buy_vol - sell_vol) / total > 0.3` → whale buying → long; `< -0.3` → short | 标准版 |\n| `open_interest` | OI rising + price rising = healthy trend; OI rising + price falling = weak, likely reversal | 专业版 |\n| `liquidation_map` | More short liquidations above → short squeeze likely → long; vice versa | 高级版 |\n\n### Key Rule: Backtest Behavior\n\nAiCoin real-time data is **NOT available for historical periods**. In backtest mode:\n- AiCoin columns use **default values** (funding_rate=0.0, ls_ratio=0.5, whale_signal=0.0)\n- This means backtest results reflect **technical indicators only**\n- Live/dry_run trading uses **real AiCoin data**, which should improve performance vs backtest\n\nAlways explain this to the user when showing backtest results.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Quick-generate strategy | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| Backtest | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}'` |\n| Deploy (dry-run) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Deploy (live) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Hyperopt | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"epochs\":100}'` |\n| Strategy list | `node scripts/ft-deploy.mjs strategy_list` |\n| Bot status | `node scripts/ft-deploy.mjs status` |\n| Bot logs | `node scripts/ft-deploy.mjs logs '{\"lines\":50}'` |\n\n## Setup\n\n**Prerequisites:** Python 3.11+ and git.\n\n`.env` auto-loaded from (first found wins): cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\n**Exchange keys** (for live/dry-run):\n```\nBINANCE_API_KEY=xxx\nBINANCE_API_SECRET=xxx\n```\n\n**AiCoin API key** (for AiCoin data in strategies):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\nGet at https://www.aicoin.com/opendata\n\n## Scripts\n\n### ft-deploy.mjs — Deployment & Strategy\n\n| Action | Params |\n|--------|--------|\n| `check` | None |\n| `deploy` | `{\"strategy\":\"MACDKDJStrategy\",\"dry_run\":true,\"pairs\":[\"BTC/USDT:USDT\"]}` — **strategy 必填，指定策略名** |\n| `backtest` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}` — pairs 可选，默认用 config 中的交易对 |\n| `hyperopt` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `create_strategy` | `{\"name\":\"Name\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}` |\n| `strategy_list` | None |\n| `backtest_results` | None — lists recent backtest result files |\n| `start` / `stop` / `status` / `logs` | None / `{\"lines\":50}` |\n\n### ft.mjs — Bot Control (requires running process)\n\n`ping`, `start`, `stop`, `balance`, `profit`, `trades_open`, `trades_history`, `force_enter`, `force_exit`, `daily`, `weekly`, `monthly`, `stats`\n\n### ft-dev.mjs — Dev Tools (requires running process)\n\n`backtest_start`, `backtest_status`, `candles_live`, `candles_analyzed`, `strategy_list`, `strategy_get`\n\n## Cross-Skill References\n\n| Need | Use |\n|------|-----|\n| Prices, K-lines, market data | **aicoin-market** |\n| Exchange trading (buy/sell) | **aicoin-trading** |\n| Hyperliquid whale tracking | **aicoin-hyperliquid** |\n\n## Paid Feature Guide\n\nWhen 304/403: **Do NOT retry.** Guide the user:\n\n| Tier | Price | Data for Strategies |\n|------|-------|---------------------|\n| 免费版 | $0 | Pure technical indicators |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\nConfigure: `AICOIN_ACCESS_KEY_ID` + `AICOIN_ACCESS_SECRET` in `.env`\n\nFile v3.5.3:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.3\",\n  \"publishedAt\": 1773170371702\n}\n\nFile v3.5.3:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}\n\nFile v3.5.3:package.json\n\n{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.2\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n\nArchive v3.5.2: 13 files, 38224 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (52874b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (15298b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)\n\nFile v3.5.2:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about writing trading strategies, backtesting, deploying Freqtrade bots, quantitative trading, or strategy optimization. Trigger words: 'write strategy', 'create strategy', 'backtest', 'deploy Freqtrade', 'deploy bot', 'quantitative', 'hyperopt', '写策略', '创建策略', '回测', '部署', '量化', '策略优化'. This skill provides: (1) create_strategy quick generator with 17 indicators, (2) AiCoin Python SDK (aicoin_data.py) for integrating real market data into custom strategies, (3) deploy/backtest/hyperopt tools. ALWAYS actively use AiCoin data (funding rate, L/S ratio, whale orders, etc.) in strategies when the user's API key supports it. For prices/charts use aicoin-market. For trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n> **⚠️ 运行脚本: 必须先 cd 到本 SKILL.md 所在目录再执行。示例: `cd ~/.openclaw/workspace/skills/aicoin-freqtrade && node scripts/ft-deploy.mjs ...`**\n\n# AiCoin Freqtrade\n\nFreqtrade strategy creation, backtesting, and deployment powered by [AiCoin Open API](https://www.aicoin.com/opendata).\n\n## Critical Rules\n\n1. **ALWAYS use `ft-deploy.mjs backtest`** for backtesting. NEVER write custom backtest scripts. NEVER use simulated/fabricated data.\n2. **ALWAYS use `ft-deploy.mjs deploy`** for deployment. NEVER use Docker. NEVER manually run `freqtrade` commands.\n3. **NEVER manually edit Freqtrade config files.** Use `ft-deploy.mjs` actions.\n4. **NEVER manually run `freqtrade trade`, `freqtrade status`, `freqtrade backtesting`, `source .venv/bin/activate`, or `pip install freqtrade`.** Always use ft-deploy.mjs or ft.mjs instead.\n5. **ACTIVELY use AiCoin data** in strategies. Check what data the user's API key supports and integrate it. Don't only use basic indicators when richer data is available.\n6. **Freqtrade 不支持网格策略(grid)。** 用户问网格时，说明限制并建议用趋势跟踪或区间策略替代。\n\n## Two Ways to Create Strategies\n\n### Option A: Quick Generator (for simple strategies)\n\n`create_strategy` generates a ready-to-backtest strategy file with selected indicators and optional AiCoin data:\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\nAvailable `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`\n\n### Option B: Write Custom Strategy Code (for complex/custom strategies)\n\nWhen users need custom logic beyond what `create_strategy` offers, write a Python strategy file directly. **Use the AiCoin Python SDK** (`aicoin_data.py`, auto-installed at `~/.freqtrade/user_data/strategies/`) to integrate real market data.\n\nStrategy file location: `~/.freqtrade/user_data/strategies/YourStrategyName.py`\n\n#### AiCoin Python SDK Reference\n\n```python\nfrom aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis\n```\n\n#### Complete Strategy Template (copy and customize)\n\n```python\n# MyCustomStrategy - Description\n# Uses AiCoin data in live/dry_run mode\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyCustomStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    # Hyperopt parameters\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    # AiCoin data cache\n    _ac_funding_rate = 0.0\n    _ac_ls_ratio = 0.5\n    _ac_whale_signal = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # === Technical Indicators (always available) ===\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # MACD\n        ema12 = dataframe['close'].ewm(span=12, adjust=False).mean()\n        ema26 = dataframe['close'].ewm(span=26, adjust=False).mean()\n        dataframe['macd'] = ema12 - ema26\n        dataframe['macd_signal'] = dataframe['macd'].ewm(span=9, adjust=False).mean()\n\n        # EMA\n        dataframe['ema_fast'] = dataframe['close'].ewm(span=8, adjust=False).mean()\n        dataframe['ema_slow'] = dataframe['close'].ewm(span=21, adjust=False).mean()\n\n        # === AiCoin Data (live/dry_run only) ===\n        dataframe['funding_rate'] = 0.0\n        dataframe['ls_ratio'] = 0.5\n        dataframe['whale_signal'] = 0.0\n\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:  # Update every 5 min\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            # Apply latest AiCoin data to current candle\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n            dataframe.iloc[-1, dataframe.columns.get_loc('ls_ratio')] = self._ac_ls_ratio\n            dataframe.iloc[-1, dataframe.columns.get_loc('whale_signal')] = self._ac_whale_signal\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        \"\"\"Fetch latest AiCoin data. Called every 5 min in live mode.\"\"\"\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData, ccxt_to_aicoin\n\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            symbol = ccxt_to_aicoin(pair, exchange)\n\n            # Funding rate (基础版)\n            try:\n                data = ac.funding_rate(symbol, weighted=True, limit='5')\n                items = data.get('data', [])\n                if isinstance(items, list) and items:\n                    latest = items[0]\n                    if isinstance(latest, dict) and 'close' in latest:\n                        self._ac_funding_rate = float(latest['close']) * 100\n            except Exception as e:\n                logger.debug(f\"AiCoin funding_rate unavailable: {e}\")\n\n            # Long/short ratio (基础版)\n            try:\n                ls = ac.ls_ratio()\n                detail = ls.get('data', {}).get('detail', {})\n                if detail:\n                    ratio = float(detail.get('last', 1.0))\n                    self._ac_ls_ratio = max(0.0, min(1.0, ratio / (1.0 + ratio)))\n            except Exception as e:\n                logger.debug(f\"AiCoin ls_ratio unavailable: {e}\")\n\n            # Whale orders (标准版)\n            try:\n                orders = ac.big_orders(symbol)\n                if 'data' in orders and isinstance(orders['data'], list):\n                    buy_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                 if o.get('side', '').lower() in ('buy', 'bid', 'long'))\n                    sell_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                  if o.get('side', '').lower() in ('sell', 'ask', 'short'))\n                    total = buy_vol + sell_vol\n                    if total > 0:\n                        self._ac_whale_signal = (buy_vol - sell_vol) / total\n            except Exception as e:\n                logger.debug(f\"AiCoin big_orders unavailable: {e}\")\n\n        except ImportError:\n            logger.warning(\"aicoin_data module not found. Run ft-deploy.mjs deploy to install.\")\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Long: RSI oversold + MACD bullish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['macd'] > dataframe['macd_signal']) &\n            (dataframe['ema_fast'] > dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] <= 0.55) &        # More shorts = contrarian long\n            (dataframe['whale_signal'] >= -0.3) &     # Whales not heavily selling\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n\n        # Short: RSI overbought + MACD bearish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['macd'] < dataframe['macd_signal']) &\n            (dataframe['ema_fast'] < dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] >= 0.45) &        # More longs = contrarian short\n            (dataframe['whale_signal'] <= 0.3) &      # Whales not heavily buying\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n### AiCoin Data Integration Patterns\n\nUse these patterns to integrate specific AiCoin data into entry/exit conditions:\n\n| AiCoin Data | Signal Logic | Tier |\n|-------------|-------------|------|\n| `funding_rate` | Rate > 0.01% → market over-leveraged long → short signal; Rate < -0.01% → long signal | 基础版 |\n| `ls_ratio` | Ratio < 0.45 (more shorts) → contrarian long; Ratio > 0.55 (more longs) → contrarian short | 基础版 |\n| `big_orders` | `(buy_vol - sell_vol) / total > 0.3` → whale buying → long; `< -0.3` → short | 标准版 |\n| `open_interest` | OI rising + price rising = healthy trend; OI rising + price falling = weak, likely reversal | 专业版 |\n| `liquidation_map` | More short liquidations above → short squeeze likely → long; vice versa | 高级版 |\n\n### Key Rule: Backtest Behavior\n\nAiCoin real-time data is **NOT available for historical periods**. In backtest mode:\n- AiCoin columns use **default values** (funding_rate=0.0, ls_ratio=0.5, whale_signal=0.0)\n- This means backtest results reflect **technical indicators only**\n- Live/dry_run trading uses **real AiCoin data**, which should improve performance vs backtest\n\nAlways explain this to the user when showing backtest results.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Quick-generate strategy | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| Backtest | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}'` |\n| Deploy (dry-run) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Deploy (live) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Hyperopt | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"epochs\":100}'` |\n| Strategy list | `node scripts/ft-deploy.mjs strategy_list` |\n| Bot status | `node scripts/ft-deploy.mjs status` |\n| Bot logs | `node scripts/ft-deploy.mjs logs '{\"lines\":50}'` |\n\n## Setup\n\n**Prerequisites:** Python 3.11+ and git.\n\n`.env` auto-loaded from (first found wins): cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\n**Exchange keys** (for live/dry-run):\n```\nBINANCE_API_KEY=xxx\nBINANCE_API_SECRET=xxx\n```\n\n**AiCoin API key** (for AiCoin data in strategies):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\nGet at https://www.aicoin.com/opendata\n\n## Scripts\n\n### ft-deploy.mjs — Deployment & Strategy\n\n| Action | Params |\n|--------|--------|\n| `check` | None |\n| `deploy` | `{\"strategy\":\"MACDKDJStrategy\",\"dry_run\":true,\"pairs\":[\"BTC/USDT:USDT\"]}` — **strategy 必填，指定策略名** |\n| `backtest` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}` — pairs 可选，默认用 config 中的交易对 |\n| `hyperopt` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `create_strategy` | `{\"name\":\"Name\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}` |\n| `strategy_list` | None |\n| `start` / `stop` / `status` / `logs` | None / `{\"lines\":50}` |\n\n### ft.mjs — Bot Control (requires running process)\n\n`ping`, `start`, `stop`, `balance`, `profit`, `trades_open`, `trades_history`, `force_enter`, `force_exit`, `daily`, `weekly`, `monthly`, `stats`\n\n### ft-dev.mjs — Dev Tools (requires running process)\n\n`backtest_start`, `backtest_status`, `candles_live`, `candles_analyzed`, `strategy_list`, `strategy_get`\n\n## Cross-Skill References\n\n| Need | Use |\n|------|-----|\n| Prices, K-lines, market data | **aicoin-market** |\n| Exchange trading (buy/sell) | **aicoin-trading** |\n| Hyperliquid whale tracking | **aicoin-hyperliquid** |\n\n## Paid Feature Guide\n\nWhen 304/403: **Do NOT retry.** Guide the user:\n\n| Tier | Price | Data for Strategies |\n|------|-------|---------------------|\n| 免费版 | $0 | Pure technical indicators |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\nConfigure: `AICOIN_ACCESS_KEY_ID` + `AICOIN_ACCESS_SECRET` in `.env`\n\nFile v3.5.2:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.2\",\n  \"publishedAt\": 1773169222041\n}\n\nFile v3.5.2:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}\n\nFile v3.5.2:package.json\n\n{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.2\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n\nArchive v3.5.1: 13 files, 38224 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (52874b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (15298b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)\n\nFile v3.5.1:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about writing trading strategies, backtesting, deploying Freqtrade bots, quantitative trading, or strategy optimization. Trigger words: 'write strategy', 'create strategy', 'backtest', 'deploy Freqtrade', 'deploy bot', 'quantitative', 'hyperopt', '写策略', '创建策略', '回测', '部署', '量化', '策略优化'. This skill provides: (1) create_strategy quick generator with 17 indicators, (2) AiCoin Python SDK (aicoin_data.py) for integrating real market data into custom strategies, (3) deploy/backtest/hyperopt tools. ALWAYS actively use AiCoin data (funding rate, L/S ratio, whale orders, etc.) in strategies when the user's API key supports it. For prices/charts use aicoin-market. For trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n> **⚠️ 运行脚本: 必须先 cd 到本 SKILL.md 所在目录再执行。示例: `cd ~/.openclaw/workspace/skills/aicoin-freqtrade && node scripts/ft-deploy.mjs ...`**\n\n# AiCoin Freqtrade\n\nFreqtrade strategy creation, backtesting, and deployment powered by [AiCoin Open API](https://www.aicoin.com/opendata).\n\n## Critical Rules\n\n1. **ALWAYS use `ft-deploy.mjs backtest`** for backtesting. NEVER write custom backtest scripts. NEVER use simulated/fabricated data.\n2. **ALWAYS use `ft-deploy.mjs deploy`** for deployment. NEVER use Docker. NEVER manually run `freqtrade` commands.\n3. **NEVER manually edit Freqtrade config files.** Use `ft-deploy.mjs` actions.\n4. **NEVER manually run `freqtrade trade`, `freqtrade status`, `freqtrade backtesting`, `source .venv/bin/activate`, or `pip install freqtrade`.** Always use ft-deploy.mjs or ft.mjs instead.\n5. **ACTIVELY use AiCoin data** in strategies. Check what data the user's API key supports and integrate it. Don't only use basic indicators when richer data is available.\n6. **Freqtrade 不支持网格策略(grid)。** 用户问网格时，说明限制并建议用趋势跟踪或区间策略替代。\n\n## Two Ways to Create Strategies\n\n### Option A: Quick Generator (for simple strategies)\n\n`create_strategy` generates a ready-to-backtest strategy file with selected indicators and optional AiCoin data:\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\nAvailable `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`\n\n### Option B: Write Custom Strategy Code (for complex/custom strategies)\n\nWhen users need custom logic beyond what `create_strategy` offers, write a Python strategy file directly. **Use the AiCoin Python SDK** (`aicoin_data.py`, auto-installed at `~/.freqtrade/user_data/strategies/`) to integrate real market data.\n\nStrategy file location: `~/.freqtrade/user_data/strategies/YourStrategyName.py`\n\n#### AiCoin Python SDK Reference\n\n```python\nfrom aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis\n```\n\n#### Complete Strategy Template (copy and customize)\n\n```python\n# MyCustomStrategy - Description\n# Uses AiCoin data in live/dry_run mode\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyCustomStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    # Hyperopt parameters\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    # AiCoin data cache\n    _ac_funding_rate = 0.0\n    _ac_ls_ratio = 0.5\n    _ac_whale_signal = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # === Technical Indicators (always available) ===\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # MACD\n        ema12 = dataframe['close'].ewm(span=12, adjust=False).mean()\n        ema26 = dataframe['close'].ewm(span=26, adjust=False).mean()\n        dataframe['macd'] = ema12 - ema26\n        dataframe['macd_signal'] = dataframe['macd'].ewm(span=9, adjust=False).mean()\n\n        # EMA\n        dataframe['ema_fast'] = dataframe['close'].ewm(span=8, adjust=False).mean()\n        dataframe['ema_slow'] = dataframe['close'].ewm(span=21, adjust=False).mean()\n\n        # === AiCoin Data (live/dry_run only) ===\n        dataframe['funding_rate'] = 0.0\n        dataframe['ls_ratio'] = 0.5\n        dataframe['whale_signal'] = 0.0\n\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:  # Update every 5 min\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            # Apply latest AiCoin data to current candle\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n            dataframe.iloc[-1, dataframe.columns.get_loc('ls_ratio')] = self._ac_ls_ratio\n            dataframe.iloc[-1, dataframe.columns.get_loc('whale_signal')] = self._ac_whale_signal\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        \"\"\"Fetch latest AiCoin data. Called every 5 min in live mode.\"\"\"\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData, ccxt_to_aicoin\n\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            symbol = ccxt_to_aicoin(pair, exchange)\n\n            # Funding rate (基础版)\n            try:\n                data = ac.funding_rate(symbol, weighted=True, limit='5')\n                items = data.get('data', [])\n                if isinstance(items, list) and items:\n                    latest = items[0]\n                    if isinstance(latest, dict) and 'close' in latest:\n                        self._ac_funding_rate = float(latest['close']) * 100\n            except Exception as e:\n                logger.debug(f\"AiCoin funding_rate unavailable: {e}\")\n\n            # Long/short ratio (基础版)\n            try:\n                ls = ac.ls_ratio()\n                detail = ls.get('data', {}).get('detail', {})\n                if detail:\n                    ratio = float(detail.get('last', 1.0))\n                    self._ac_ls_ratio = max(0.0, min(1.0, ratio / (1.0 + ratio)))\n            except Exception as e:\n                logger.debug(f\"AiCoin ls_ratio unavailable: {e}\")\n\n            # Whale orders (标准版)\n            try:\n                orders = ac.big_orders(symbol)\n                if 'data' in orders and isinstance(orders['data'], list):\n                    buy_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                 if o.get('side', '').lower() in ('buy', 'bid', 'long'))\n                    sell_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                  if o.get('side', '').lower() in ('sell', 'ask', 'short'))\n                    total = buy_vol + sell_vol\n                    if total > 0:\n                        self._ac_whale_signal = (buy_vol - sell_vol) / total\n            except Exception as e:\n                logger.debug(f\"AiCoin big_orders unavailable: {e}\")\n\n        except ImportError:\n            logger.warning(\"aicoin_data module not found. Run ft-deploy.mjs deploy to install.\")\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Long: RSI oversold + MACD bullish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['macd'] > dataframe['macd_signal']) &\n            (dataframe['ema_fast'] > dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] <= 0.55) &        # More shorts = contrarian long\n            (dataframe['whale_signal'] >= -0.3) &     # Whales not heavily selling\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n\n        # Short: RSI overbought + MACD bearish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['macd'] < dataframe['macd_signal']) &\n            (dataframe['ema_fast'] < dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] >= 0.45) &        # More longs = contrarian short\n            (dataframe['whale_signal'] <= 0.3) &      # Whales not heavily buying\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n### AiCoin Data Integration Patterns\n\nUse these patterns to integrate specific AiCoin data into entry/exit conditions:\n\n| AiCoin Data | Signal Logic | Tier |\n|-------------|-------------|------|\n| `funding_rate` | Rate > 0.01% → market over-leveraged long → short signal; Rate < -0.01% → long signal | 基础版 |\n| `ls_ratio` | Ratio < 0.45 (more shorts) → contrarian long; Ratio > 0.55 (more longs) → contrarian short | 基础版 |\n| `big_orders` | `(buy_vol - sell_vol) / total > 0.3` → whale buying → long; `< -0.3` → short | 标准版 |\n| `open_interest` | OI rising + price rising = healthy trend; OI rising + price falling = weak, likely reversal | 专业版 |\n| `liquidation_map` | More short liquidations above → short squeeze likely → long; vice versa | 高级版 |\n\n### Key Rule: Backtest Behavior\n\nAiCoin real-time data is **NOT available for historical periods**. In backtest mode:\n- AiCoin columns use **default values** (funding_rate=0.0, ls_ratio=0.5, whale_signal=0.0)\n- This means backtest results reflect **technical indicators only**\n- Live/dry_run trading uses **real AiCoin data**, which should improve performance vs backtest\n\nAlways explain this to the user when showing backtest results.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Quick-generate strategy | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| Backtest | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}'` |\n| Deploy (dry-run) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Deploy (live) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Hyperopt | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"epochs\":100}'` |\n| Strategy list | `node scripts/ft-deploy.mjs strategy_list` |\n| Bot status | `node scripts/ft-deploy.mjs status` |\n| Bot logs | `node scripts/ft-deploy.mjs logs '{\"lines\":50}'` |\n\n## Setup\n\n**Prerequisites:** Python 3.11+ and git.\n\n`.env` auto-loaded from (first found wins): cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\n**Exchange keys** (for live/dry-run):\n```\nBINANCE_API_KEY=xxx\nBINANCE_API_SECRET=xxx\n```\n\n**AiCoin API key** (for AiCoin data in strategies):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\nGet at https://www.aicoin.com/opendata\n\n## Scripts\n\n### ft-deploy.mjs — Deployment & Strategy\n\n| Action | Params |\n|--------|--------|\n| `check` | None |\n| `deploy` | `{\"strategy\":\"MACDKDJStrategy\",\"dry_run\":true,\"pairs\":[\"BTC/USDT:USDT\"]}` — **strategy 必填，指定策略名** |\n| `backtest` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}` — pairs 可选，默认用 config 中的交易对 |\n| `hyperopt` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `create_strategy` | `{\"name\":\"Name\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}` |\n| `strategy_list` | None |\n| `start` / `stop` / `status` / `logs` | None / `{\"lines\":50}` |\n\n### ft.mjs — Bot Control (requires running process)\n\n`ping`, `start`, `stop`, `balance`, `profit`, `trades_open`, `trades_history`, `force_enter`, `force_exit`, `daily`, `weekly`, `monthly`, `stats`\n\n### ft-dev.mjs — Dev Tools (requires running process)\n\n`backtest_start`, `backtest_status`, `candles_live`, `candles_analyzed`, `strategy_list`, `strategy_get`\n\n## Cross-Skill References\n\n| Need | Use |\n|------|-----|\n| Prices, K-lines, market data | **aicoin-market** |\n| Exchange trading (buy/sell) | **aicoin-trading** |\n| Hyperliquid whale tracking | **aicoin-hyperliquid** |\n\n## Paid Feature Guide\n\nWhen 304/403: **Do NOT retry.** Guide the user:\n\n| Tier | Price | Data for Strategies |\n|------|-------|---------------------|\n| 免费版 | $0 | Pure technical indicators |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\nConfigure: `AICOIN_ACCESS_KEY_ID` + `AICOIN_ACCESS_SECRET` in `.env`\n\nFile v3.5.1:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.1\",\n  \"publishedAt\": 1773169180171\n}\n\nFile v3.5.1:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}\n\nFile v3.5.1:package.json\n\n{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.1\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n\nArchive v3.5.0: 13 files, 38224 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (52874b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (15298b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)\n\nFile v3.5.0:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about writing trading strategies, backtesting, deploying Freqtrade bots, quantitative trading, or strategy optimization. Trigger words: 'write strategy', 'create strategy', 'backtest', 'deploy Freqtrade', 'deploy bot', 'quantitative', 'hyperopt', '写策略', '创建策略', '回测', '部署', '量化', '策略优化'. This skill provides: (1) create_strategy quick generator with 17 indicators, (2) AiCoin Python SDK (aicoin_data.py) for integrating real market data into custom strategies, (3) deploy/backtest/hyperopt tools. ALWAYS actively use AiCoin data (funding rate, L/S ratio, whale orders, etc.) in strategies when the user's API key supports it. For prices/charts use aicoin-market. For trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n> **⚠️ 运行脚本: 必须先 cd 到本 SKILL.md 所在目录再执行。示例: `cd ~/.openclaw/workspace/skills/aicoin-freqtrade && node scripts/ft-deploy.mjs ...`**\n\n# AiCoin Freqtrade\n\nFreqtrade strategy creation, backtesting, and deployment powered by [AiCoin Open API](https://www.aicoin.com/opendata).\n\n## Critical Rules\n\n1. **ALWAYS use `ft-deploy.mjs backtest`** for backtesting. NEVER write custom backtest scripts. NEVER use simulated/fabricated data.\n2. **ALWAYS use `ft-deploy.mjs deploy`** for deployment. NEVER use Docker. NEVER manually run `freqtrade` commands.\n3. **NEVER manually edit Freqtrade config files.** Use `ft-deploy.mjs` actions.\n4. **NEVER manually run `freqtrade trade`, `freqtrade status`, `freqtrade backtesting`, `source .venv/bin/activate`, or `pip install freqtrade`.** Always use ft-deploy.mjs or ft.mjs instead.\n5. **ACTIVELY use AiCoin data** in strategies. Check what data the user's API key supports and integrate it. Don't only use basic indicators when richer data is available.\n6. **Freqtrade 不支持网格策略(grid)。** 用户问网格时，说明限制并建议用趋势跟踪或区间策略替代。\n\n## Two Ways to Create Strategies\n\n### Option A: Quick Generator (for simple strategies)\n\n`create_strategy` generates a ready-to-backtest strategy file with selected indicators and optional AiCoin data:\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\nAvailable `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`\n\n### Option B: Write Custom Strategy Code (for complex/custom strategies)\n\nWhen users need custom logic beyond what `create_strategy` offers, write a Python strategy file directly. **Use the AiCoin Python SDK** (`aicoin_data.py`, auto-installed at `~/.freqtrade/user_data/strategies/`) to integrate real market data.\n\nStrategy file location: `~/.freqtrade/user_data/strategies/YourStrategyName.py`\n\n#### AiCoin Python SDK Reference\n\n```python\nfrom aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis\n```\n\n#### Complete Strategy Template (copy and customize)\n\n```python\n# MyCustomStrategy - Description\n# Uses AiCoin data in live/dry_run mode\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyCustomStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    # Hyperopt parameters\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    # AiCoin data cache\n    _ac_funding_rate = 0.0\n    _ac_ls_ratio = 0.5\n    _ac_whale_signal = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # === Technical Indicators (always available) ===\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # MACD\n        ema12 = dataframe['close'].ewm(span=12, adjust=False).mean()\n        ema26 = dataframe['close'].ewm(span=26, adjust=False).mean()\n        dataframe['macd'] = ema12 - ema26\n        dataframe['macd_signal'] = dataframe['macd'].ewm(span=9, adjust=False).mean()\n\n        # EMA\n        dataframe['ema_fast'] = dataframe['close'].ewm(span=8, adjust=False).mean()\n        dataframe['ema_slow'] = dataframe['close'].ewm(span=21, adjust=False).mean()\n\n        # === AiCoin Data (live/dry_run only) ===\n        dataframe['funding_rate'] = 0.0\n        dataframe['ls_ratio'] = 0.5\n        dataframe['whale_signal'] = 0.0\n\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:  # Update every 5 min\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            # Apply latest AiCoin data to current candle\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n            dataframe.iloc[-1, dataframe.columns.get_loc('ls_ratio')] = self._ac_ls_ratio\n            dataframe.iloc[-1, dataframe.columns.get_loc('whale_signal')] = self._ac_whale_signal\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        \"\"\"Fetch latest AiCoin data. Called every 5 min in live mode.\"\"\"\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData, ccxt_to_aicoin\n\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            symbol = ccxt_to_aicoin(pair, exchange)\n\n            # Funding rate (基础版)\n            try:\n                data = ac.funding_rate(symbol, weighted=True, limit='5')\n                items = data.get('data', [])\n                if isinstance(items, list) and items:\n                    latest = items[0]\n                    if isinstance(latest, dict) and 'close' in latest:\n                        self._ac_funding_rate = float(latest['close']) * 100\n            except Exception as e:\n                logger.debug(f\"AiCoin funding_rate unavailable: {e}\")\n\n            # Long/short ratio (基础版)\n            try:\n                ls = ac.ls_ratio()\n                detail = ls.get('data', {}).get('detail', {})\n                if detail:\n                    ratio = float(detail.get('last', 1.0))\n                    self._ac_ls_ratio = max(0.0, min(1.0, ratio / (1.0 + ratio)))\n            except Exception as e:\n                logger.debug(f\"AiCoin ls_ratio unavailable: {e}\")\n\n            # Whale orders (标准版)\n            try:\n                orders = ac.big_orders(symbol)\n                if 'data' in orders and isinstance(orders['data'], list):\n                    buy_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                 if o.get('side', '').lower() in ('buy', 'bid', 'long'))\n                    sell_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                  if o.get('side', '').lower() in ('sell', 'ask', 'short'))\n                    total = buy_vol + sell_vol\n                    if total > 0:\n                        self._ac_whale_signal = (buy_vol - sell_vol) / total\n            except Exception as e:\n                logger.debug(f\"AiCoin big_orders unavailable: {e}\")\n\n        except ImportError:\n            logger.warning(\"aicoin_data module not found. Run ft-deploy.mjs deploy to install.\")\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Long: RSI oversold + MACD bullish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['macd'] > dataframe['macd_signal']) &\n            (dataframe['ema_fast'] > dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] <= 0.55) &        # More shorts = contrarian long\n            (dataframe['whale_signal'] >= -0.3) &     # Whales not heavily selling\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n\n        # Short: RSI overbought + MACD bearish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['macd'] < dataframe['macd_signal']) &\n            (dataframe['ema_fast'] < dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] >= 0.45) &        # More longs = contrarian short\n            (dataframe['whale_signal'] <= 0.3) &      # Whales not heavily buying\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n### AiCoin Data Integration Patterns\n\nUse these patterns to integrate specific AiCoin data into entry/exit conditions:\n\n| AiCoin Data | Signal Logic | Tier |\n|-------------|-------------|------|\n| `funding_rate` | Rate > 0.01% → market over-leveraged long → short signal; Rate < -0.01% → long signal | 基础版 |\n| `ls_ratio` | Ratio < 0.45 (more shorts) → contrarian long; Ratio > 0.55 (more longs) → contrarian short | 基础版 |\n| `big_orders` | `(buy_vol - sell_vol) / total > 0.3` → whale buying → long; `< -0.3` → short | 标准版 |\n| `open_interest` | OI rising + price rising = healthy trend; OI rising + price falling = weak, likely reversal | 专业版 |\n| `liquidation_map` | More short liquidations above → short squeeze likely → long; vice versa | 高级版 |\n\n### Key Rule: Backtest Behavior\n\nAiCoin real-time data is **NOT available for historical periods**. In backtest mode:\n- AiCoin columns use **default values** (funding_rate=0.0, ls_ratio=0.5, whale_signal=0.0)\n- This means backtest results reflect **technical indicators only**\n- Live/dry_run trading uses **real AiCoin data**, which should improve performance vs backtest\n\nAlways explain this to the user when showing backtest results.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Quick-generate strategy | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| Backtest | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}'` |\n| Deploy (dry-run) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Deploy (live) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Hyperopt | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"epochs\":100}'` |\n| Strategy list | `node scripts/ft-deploy.mjs strategy_list` |\n| Bot status | `node scripts/ft-deploy.mjs status` |\n| Bot logs | `node scripts/ft-deploy.mjs logs '{\"lines\":50}'` |\n\n## Setup\n\n**Prerequisites:** Python 3.11+ and git.\n\n`.env` auto-loaded from (first found wins): cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\n**Exchange keys** (for live/dry-run):\n```\nBINANCE_API_KEY=xxx\nBINANCE_API_SECRET=xxx\n```\n\n**AiCoin API key** (for AiCoin data in strategies):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\nGet at https://www.aicoin.com/opendata\n\n## Scripts\n\n### ft-deploy.mjs — Deployment & Strategy\n\n| Action | Params |\n|--------|--------|\n| `check` | None |\n| `deploy` | `{\"strategy\":\"MACDKDJStrategy\",\"dry_run\":true,\"pairs\":[\"BTC/USDT:USDT\"]}` — **strategy 必填，指定策略名** |\n| `backtest` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}` — pairs 可选，默认用 config 中的交易对 |\n| `hyperopt` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `create_strategy` | `{\"name\":\"Name\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}` |\n| `strategy_list` | None |\n| `start` / `stop` / `status` / `logs` | None / `{\"lines\":50}` |\n\n### ft.mjs — Bot Control (requires running process)\n\n`ping`, `start`, `stop`, `balance`, `profit`, `trades_open`, `trades_history`, `force_enter`, `force_exit`, `daily`, `weekly`, `monthly`, `stats`\n\n### ft-dev.mjs — Dev Tools (requires running process)\n\n`backtest_start`, `backtest_status`, `candles_live`, `candles_analyzed`, `strategy_list`, `strategy_get`\n\n## Cross-Skill References\n\n| Need | Use |\n|------|-----|\n| Prices, K-lines, market data | **aicoin-market** |\n| Exchange trading (buy/sell) | **aicoin-trading** |\n| Hyperliquid whale tracking | **aicoin-hyperliquid** |\n\n## Paid Feature Guide\n\nWhen 304/403: **Do NOT retry.** Guide the user:\n\n| Tier | Price | Data for Strategies |\n|------|-------|---------------------|\n| 免费版 | $0 | Pure technical indicators |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\nConfigure: `AICOIN_ACCESS_KEY_ID` + `AICOIN_ACCESS_SECRET` in `.env`\n\nFile v3.5.0:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.0\",\n  \"publishedAt\": 1773169141832\n}\n\nFile v3.5.0:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}\n\nFile v3.5.0:package.json\n\n{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.0\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n\nArchive v3.4.9: 13 files, 38107 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (52874b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (15168b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)\n\nFile v3.4.9:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about writing trading strategies, backtesting, deploying Freqtrade bots, quantitative trading, or strategy optimization. Trigger words: 'write strategy', 'create strategy', 'backtest', 'deploy Freqtrade', 'deploy bot', 'quantitative', 'hyperopt', '写策略', '创建策略', '回测', '部署', '量化', '策略优化'. This skill provides: (1) create_strategy quick generator with 17 indicators, (2) AiCoin Python SDK (aicoin_data.py) for integrating real market data into custom strategies, (3) deploy/backtest/hyperopt tools. ALWAYS actively use AiCoin data (funding rate, L/S ratio, whale orders, etc.) in strategies when the user's API key supports it. For prices/charts use aicoin-market. For trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n> **⚠️ 运行脚本: 必须先 cd 到本 SKILL.md 所在目录再执行。示例: `cd ~/.openclaw/workspace/skills/aicoin-freqtrade && node scripts/ft-deploy.mjs ...`**\n\n# AiCoin Freqtrade\n\nFreqtrade strategy creation, backtesting, and deployment powered by [AiCoin Open API](https://www.aicoin.com/opendata).\n\n## Critical Rules\n\n1. **ALWAYS use `ft-deploy.mjs backtest`** for backtesting. NEVER write custom backtest scripts. NEVER use simulated/fabricated data.\n2. **ALWAYS use `ft-deploy.mjs deploy`** for deployment. NEVER use Docker. NEVER manually run `freqtrade` commands.\n3. **NEVER manually edit Freqtrade config files.** Use `ft-deploy.mjs` actions.\n4. **NEVER manually run `freqtrade trade`, `freqtrade status`, `freqtrade backtesting`, `source .venv/bin/activate`, or `pip install freqtrade`.** Always use ft-deploy.mjs or ft.mjs instead.\n5. **ACTIVELY use AiCoin data** in strategies. Check what data the user's API key supports and integrate it. Don't only use basic indicators when richer data is available.\n\n## Two Ways to Create Strategies\n\n### Option A: Quick Generator (for simple strategies)\n\n`create_strategy` generates a ready-to-backtest strategy file with selected indicators and optional AiCoin data:\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\nAvailable `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`\n\n### Option B: Write Custom Strategy Code (for complex/custom strategies)\n\nWhen users need custom logic beyond what `create_strategy` offers, write a Python strategy file directly. **Use the AiCoin Python SDK** (`aicoin_data.py`, auto-installed at `~/.freqtrade/user_data/strategies/`) to integrate real market data.\n\nStrategy file location: `~/.freqtrade/user_data/strategies/YourStrategyName.py`\n\n#### AiCoin Python SDK Reference\n\n```python\nfrom aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis\n```\n\n#### Complete Strategy Template (copy and customize)\n\n```python\n# MyCustomStrategy - Description\n# Uses AiCoin data in live/dry_run mode\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyCustomStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    # Hyperopt parameters\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    # AiCoin data cache\n    _ac_funding_rate = 0.0\n    _ac_ls_ratio = 0.5\n    _ac_whale_signal = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # === Technical Indicators (always available) ===\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # MACD\n        ema12 = dataframe['close'].ewm(span=12, adjust=False).mean()\n        ema26 = dataframe['close'].ewm(span=26, adjust=False).mean()\n        dataframe['macd'] = ema12 - ema26\n        dataframe['macd_signal'] = dataframe['macd'].ewm(span=9, adjust=False).mean()\n\n        # EMA\n        dataframe['ema_fast'] = dataframe['close'].ewm(span=8, adjust=False).mean()\n        dataframe['ema_slow'] = dataframe['close'].ewm(span=21, adjust=False).mean()\n\n        # === AiCoin Data (live/dry_run only) ===\n        dataframe['funding_rate'] = 0.0\n        dataframe['ls_ratio'] = 0.5\n        dataframe['whale_signal'] = 0.0\n\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:  # Update every 5 min\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            # Apply latest AiCoin data to current candle\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n            dataframe.iloc[-1, dataframe.columns.get_loc('ls_ratio')] = self._ac_ls_ratio\n            dataframe.iloc[-1, dataframe.columns.get_loc('whale_signal')] = self._ac_whale_signal\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        \"\"\"Fetch latest AiCoin data. Called every 5 min in live mode.\"\"\"\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData, ccxt_to_aicoin\n\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            symbol = ccxt_to_aicoin(pair, exchange)\n\n            # Funding rate (基础版)\n            try:\n                data = ac.funding_rate(symbol, weighted=True, limit='5')\n                items = data.get('data', [])\n                if isinstance(items, list) and items:\n                    latest = items[0]\n                    if isinstance(latest, dict) and 'close' in latest:\n                        self._ac_funding_rate = float(latest['close']) * 100\n            except Exception as e:\n                logger.debug(f\"AiCoin funding_rate unavailable: {e}\")\n\n            # Long/short ratio (基础版)\n            try:\n                ls = ac.ls_ratio()\n                detail = ls.get('data', {}).get('detail', {})\n                if detail:\n                    ratio = float(detail.get('last', 1.0))\n                    self._ac_ls_ratio = max(0.0, min(1.0, ratio / (1.0 + ratio)))\n            except Exception as e:\n                logger.debug(f\"AiCoin ls_ratio unavailable: {e}\")\n\n            # Whale orders (标准版)\n            try:\n                orders = ac.big_orders(symbol)\n                if 'data' in orders and isinstance(orders['data'], list):\n                    buy_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                 if o.get('side', '').lower() in ('buy', 'bid', 'long'))\n                    sell_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                  if o.get('side', '').lower() in ('sell', 'ask', 'short'))\n                    total = buy_vol + sell_vol\n                    if total > 0:\n                        self._ac_whale_signal = (buy_vol - sell_vol) / total\n            except Exception as e:\n                logger.debug(f\"AiCoin big_orders unavailable: {e}\")\n\n        except ImportError:\n            logger.warning(\"aicoin_data module not found. Run ft-deploy.mjs deploy to install.\")\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Long: RSI oversold + MACD bullish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['macd'] > dataframe['macd_signal']) &\n            (dataframe['ema_fast'] > dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] <= 0.55) &        # More shorts = contrarian long\n            (dataframe['whale_signal'] >= -0.3) &     # Whales not heavily selling\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n\n        # Short: RSI overbought + MACD bearish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['macd'] < dataframe['macd_signal']) &\n            (dataframe['ema_fast'] < dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] >= 0.45) &        # More longs = contrarian short\n            (dataframe['whale_signal'] <= 0.3) &      # Whales not heavily buying\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n### AiCoin Data Integration Patterns\n\nUse these patterns to integrate specific AiCoin data into entry/exit conditions:\n\n| AiCoin Data | Signal Logic | Tier |\n|-------------|-------------|------|\n| `funding_rate` | Rate > 0.01% → market over-leveraged long → short signal; Rate < -0.01% → long signal | 基础版 |\n| `ls_ratio` | Ratio < 0.45 (more shorts) → contrarian long; Ratio > 0.55 (more longs) → contrarian short | 基础版 |\n| `big_orders` | `(buy_vol - sell_vol) / total > 0.3` → whale buying → long; `< -0.3` → short | 标准版 |\n| `open_interest` | OI rising + price rising = healthy trend; OI rising + price falling = weak, likely reversal | 专业版 |\n| `liquidation_map` | More short liquidations above → short squeeze likely → long; vice versa | 高级版 |\n\n### Key Rule: Backtest Behavior\n\nAiCoin real-time data is **NOT available for historical periods**. In backtest mode:\n- AiCoin columns use **default values** (funding_rate=0.0, ls_ratio=0.5, whale_signal=0.0)\n- This means backtest results reflect **technical indicators only**\n- Live/dry_run trading uses **real AiCoin data**, which should improve performance vs backtest\n\nAlways explain this to the user when showing backtest results.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Quick-generate strategy | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| Backtest | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}'` |\n| Deploy (dry-run) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Deploy (live) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Hyperopt | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"epochs\":100}'` |\n| Strategy list | `node scripts/ft-deploy.mjs strategy_list` |\n| Bot status | `node scripts/ft-deploy.mjs status` |\n| Bot logs | `node scripts/ft-deploy.mjs logs '{\"lines\":50}'` |\n\n## Setup\n\n**Prerequisites:** Python 3.11+ and git.\n\n`.env` auto-loaded from (first found wins): cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\n**Exchange keys** (for live/dry-run):\n```\nBINANCE_API_KEY=xxx\nBINANCE_API_SECRET=xxx\n```\n\n**AiCoin API key** (for AiCoin data in strategies):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\nGet at https://www.aicoin.com/opendata\n\n## Scripts\n\n### ft-deploy.mjs — Deployment & Strategy\n\n| Action | Params |\n|--------|--------|\n| `check` | None |\n| `deploy` | `{\"strategy\":\"MACDKDJStrategy\",\"dry_run\":true,\"pairs\":[\"BTC/USDT:USDT\"]}` — **strategy 必填，指定策略名** |\n| `backtest` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}` — pairs 可选，默认用 config 中的交易对 |\n| `hyperopt` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `create_strategy` | `{\"name\":\"Name\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}` |\n| `strategy_list` | None |\n| `start` / `stop` / `status` / `logs` | None / `{\"lines\":50}` |\n\n### ft.mjs — Bot Control (requires running process)\n\n`ping`, `start`, `stop`, `balance`, `profit`, `trades_open`, `trades_history`, `force_enter`, `force_exit`, `daily`, `weekly`, `monthly`, `stats`\n\n### ft-dev.mjs — Dev Tools (requires running process)\n\n`backtest_start`, `backtest_status`, `candles_live`, `candles_analyzed`, `strategy_list`, `strategy_get`\n\n## Cross-Skill References\n\n| Need | Use |\n|------|-----|\n| Prices, K-lines, market data | **aicoin-market** |\n| Exchange trading (buy/sell) | **aicoin-trading** |\n| Hyperliquid whale tracking | **aicoin-hyperliquid** |\n\n## Paid Feature Guide\n\nWhen 304/403: **Do NOT retry.** Guide the user:\n\n| Tier | Price | Data for Strategies |\n|------|-------|---------------------|\n| 免费版 | $0 | Pure technical indicators |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\nConfigure: `AICOIN_ACCESS_KEY_ID` + `AICOIN_ACCESS_SECRET` in `.env`\n\nFile v3.4.9:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.4.9\",\n  \"publishedAt\": 1773163465971\n}\n\nFile v3.4.9:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}\n\nFile v3.4.9:package.json\n\n{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.4.9\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n\nArchive v3.4.8: 13 files, 37865 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (51745b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (15079b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)\n\nFile v3.4.8:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about writing trading strategies, backtesting, deploying Freqtrade bots, quantitative trading, or strategy optimization. Trigger words: 'write strategy', 'create strategy', 'backtest', 'deploy Freqtrade', 'deploy bot', 'quantitative', 'hyperopt', '写策略', '创建策略', '回测', '部署', '量化', '策略优化'. This skill provides: (1) create_strategy quick generator with 17 indicators, (2) AiCoin Python SDK (aicoin_data.py) for integrating real market data into custom strategies, (3) deploy/backtest/hyperopt tools. ALWAYS actively use AiCoin data (funding rate, L/S ratio, whale orders, etc.) in strategies when the user's API key supports it. For prices/charts use aicoin-market. For trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n> **⚠️ 运行脚本: 必须先 cd 到本 SKILL.md 所在目录再执行。示例: `cd ~/.openclaw/workspace/skills/aicoin-freqtrade && node scripts/ft-deploy.mjs ...`**\n\n# AiCoin Freqtrade\n\nFreqtrade strategy creation, backtesting, and deployment powered by [AiCoin Open API](https://www.aicoin.com/opendata).\n\n## Critical Rules\n\n1. **ALWAYS use `ft-deploy.mjs backtest`** for backtesting. NEVER write custom backtest scripts. NEVER use simulated/fabricated data.\n2. **ALWAYS use `ft-deploy.mjs deploy`** for deployment. NEVER use Docker. NEVER manually run `freqtrade` commands.\n3. **NEVER manually edit Freqtrade config files.** Use `ft-deploy.mjs` actions.\n4. **NEVER manually run `freqtrade trade`, `source .venv/bin/activate`, or `pip install freqtrade`.**\n5. **ACTIVELY use AiCoin data** in strategies. Check what data the user's API key supports and integrate it. Don't only use basic indicators when richer data is available.\n\n## Two Ways to Create Strategies\n\n### Option A: Quick Generator (for simple strategies)\n\n`create_strategy` generates a ready-to-backtest strategy file with selected indicators and optional AiCoin data:\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\nAvailable `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`\n\n### Option B: Write Custom Strategy Code (for complex/custom strategies)\n\nWhen users need custom logic beyond what `create_strategy` offers, write a Python strategy file directly. **Use the AiCoin Python SDK** (`aicoin_data.py`, auto-installed at `~/.freqtrade/user_data/strategies/`) to integrate real market data.\n\nStrategy file location: `~/.freqtrade/user_data/strategies/YourStrategyName.py`\n\n#### AiCoin Python SDK Reference\n\n```python\nfrom aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis\n```\n\n#### Complete Strategy Template (copy and customize)\n\n```python\n# MyCustomStrategy - Description\n# Uses AiCoin data in live/dry_run mode\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyCustomStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    # Hyperopt parameters\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    # AiCoin data cache\n    _ac_funding_rate = 0.0\n    _ac_ls_ratio = 0.5\n    _ac_whale_signal = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # === Technical Indicators (always available) ===\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # MACD\n        ema12 = dataframe['close'].ewm(span=12, adjust=False).mean()\n        ema26 = dataframe['close'].ewm(span=26, adjust=False).mean()\n        dataframe['macd'] = ema12 - ema26\n        dataframe['macd_signal'] = dataframe['macd'].ewm(span=9, adjust=False).mean()\n\n        # EMA\n        dataframe['ema_fast'] = dataframe['close'].ewm(span=8, adjust=False).mean()\n        dataframe['ema_slow'] = dataframe['close'].ewm(span=21, adjust=False).mean()\n\n        # === AiCoin Data (live/dry_run only) ===\n        dataframe['funding_rate'] = 0.0\n        dataframe['ls_ratio'] = 0.5\n        dataframe['whale_signal'] = 0.0\n\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:  # Update every 5 min\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            # Apply latest AiCoin data to current candle\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n            dataframe.iloc[-1, dataframe.columns.get_loc('ls_ratio')] = self._ac_ls_ratio\n            dataframe.iloc[-1, dataframe.columns.get_loc('whale_signal')] = self._ac_whale_signal\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        \"\"\"Fetch latest AiCoin data. Called every 5 min in live mode.\"\"\"\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData, ccxt_to_aicoin\n\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            symbol = ccxt_to_aicoin(pair, exchange)\n\n            # Funding rate (基础版)\n            try:\n                data = ac.funding_rate(symbol, weighted=True, limit='5')\n                items = data.get('data', [])\n                if isinstance(items, list) and items:\n                    latest = items[0]\n                    if isinstance(latest, dict) and 'close' in latest:\n                        self._ac_funding_rate = float(latest['close']) * 100\n            except Exception as e:\n                logger.debug(f\"AiCoin funding_rate unavailable: {e}\")\n\n            # Long/short ratio (基础版)\n            try:\n                ls = ac.ls_ratio()\n                detail = ls.get('data', {}).get('detail', {})\n                if detail:\n                    ratio = float(detail.get('last', 1.0))\n                    self._ac_ls_ratio = max(0.0, min(1.0, ratio / (1.0 + ratio)))\n            except Exception as e:\n                logger.debug(f\"AiCoin ls_ratio unavailable: {e}\")\n\n            # Whale orders (标准版)\n            try:\n                orders = ac.big_orders(symbol)\n                if 'data' in orders and isinstance(orders['data'], list):\n                    buy_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                 if o.get('side', '').lower() in ('buy', 'bid', 'long'))\n                    sell_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                  if o.get('side', '').lower() in ('sell', 'ask', 'short'))\n                    total = buy_vol + sell_vol\n                    if total > 0:\n                        self._ac_whale_signal = (buy_vol - sell_vol) / total\n            except Exception as e:\n                logger.debug(f\"AiCoin big_orders unavailable: {e}\")\n\n        except ImportError:\n            logger.warning(\"aicoin_data module not found. Run ft-deploy.mjs deploy to install.\")\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Long: RSI oversold + MACD bullish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['macd'] > dataframe['macd_signal']) &\n            (dataframe['ema_fast'] > dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] <= 0.55) &        # More shorts = contrarian long\n            (dataframe['whale_signal'] >= -0.3) &     # Whales not heavily selling\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n\n        # Short: RSI overbought + MACD bearish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['macd'] < dataframe['macd_signal']) &\n            (dataframe['ema_fast'] < dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] >= 0.45) &        # More longs = contrarian short\n            (dataframe['whale_signal'] <= 0.3) &      # Whales not heavily buying\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n### AiCoin Data Integration Patterns\n\nUse these patterns to integrate specific AiCoin data into entry/exit conditions:\n\n| AiCoin Data | Signal Logic | Tier |\n|-------------|-------------|------|\n| `funding_rate` | Rate > 0.01% → market over-leveraged long → short signal; Rate < -0.01% → long signal | 基础版 |\n| `ls_ratio` | Ratio < 0.45 (more shorts) → contrarian long; Ratio > 0.55 (more longs) → contrarian short | 基础版 |\n| `big_orders` | `(buy_vol - sell_vol) / total > 0.3` → whale buying → long; `< -0.3` → short | 标准版 |\n| `open_interest` | OI rising + price rising = healthy trend; OI rising + price falling = weak, likely reversal | 专业版 |\n| `liquidation_map` | More short liquidations above → short squeeze likely → long; vice versa | 高级版 |\n\n### Key Rule: Backtest Behavior\n\nAiCoin real-time data is **NOT available for historical periods**. In backtest mode:\n- AiCoin columns use **default values** (funding_rate=0.0, ls_ratio=0.5, whale_signal=0.0)\n- This means backtest results reflect **technical indicators only**\n- Live/dry_run trading uses **real AiCoin data**, which should improve performance vs backtest\n\nAlways explain this to the user when showing backtest results.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Quick-generate strategy | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| Backtest | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}'` |\n| Deploy (dry-run) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Deploy (live) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Hyperopt | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"epochs\":100}'` |\n| Strategy list | `node scripts/ft-deploy.mjs strategy_list` |\n| Bot status | `node scripts/ft-deploy.mjs status` |\n| Bot logs | `node scripts/ft-deploy.mjs logs '{\"lines\":50}'` |\n\n## Setup\n\n**Prerequisites:** Python 3.11+ and git.\n\n`.env` auto-loaded from (first found wins): cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\n**Exchange keys** (for live/dry-run):\n```\nBINANCE_API_KEY=xxx\nBINANCE_API_SECRET=xxx\n```\n\n**AiCoin API key** (for AiCoin data in strategies):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\nGet at https://www.aicoin.com/opendata\n\n## Scripts\n\n### ft-deploy.mjs — Deployment & Strategy\n\n| Action | Params |\n|--------|--------|\n| `check` | None |\n| `deploy` | `{\"strategy\":\"MACDKDJStrategy\",\"dry_run\":true,\"pairs\":[\"BTC/USDT:USDT\"]}` — **strategy 必填，指定策略名** |\n| `backtest` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"pairs\":[\"ETH/USDT:USDT\"]}` — pairs 可选，默认用 config 中的交易对 |\n| `hyperopt` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `create_strategy` | `{\"name\":\"Name\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}` |\n| `strategy_list` | None |\n| `start` / `stop` / `status` / `logs` | None / `{\"lines\":50}` |\n\n### ft.mjs — Bot Control (requires running process)\n\n`ping`, `start`, `stop`, `balance`, `profit`, `trades_open`, `trades_history`, `force_enter`, `force_exit`, `daily`, `weekly`, `monthly`, `stats`\n\n### ft-dev.mjs — Dev Tools (requires running process)\n\n`backtest_start`, `backtest_status`, `candles_live`, `candles_analyzed`, `strategy_list`, `strategy_get`\n\n## Cross-Skill References\n\n| Need | Use |\n|------|-----|\n| Prices, K-lines, market data | **aicoin-market** |\n| Exchange trading (buy/sell) | **aicoin-trading** |\n| Hyperliquid whale tracking | **aicoin-hyperliquid** |\n\n## Paid Feature Guide\n\nWhen 304/403: **Do NOT retry.** Guide the user:\n\n| Tier | Price | Data for Strategies |\n|------|-------|---------------------|\n| 免费版 | $0 | Pure technical indicators |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\nConfigure: `AICOIN_ACCESS_KEY_ID` + `AICOIN_ACCESS_SECRET` in `.env`\n\nFile v3.4.8:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.4.8\",\n  \"publishedAt\": 1773161892560\n}\n\nFile v3.4.8:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}\n\nFile v3.4.8:package.json\n\n{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.4.6\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n\nArchive v3.4.7: 13 files, 37716 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (51539b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (14910b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)\n\nFile v3.4.7:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about writing trading strategies, backtesting, deploying Freqtrade bots, quantitative trading, or strategy optimization. Trigger words: 'write strategy', 'create strategy', 'backtest', 'deploy Freqtrade', 'deploy bot', 'quantitative', 'hyperopt', '写策略', '创建策略', '回测', '部署', '量化', '策略优化'. This skill provides: (1) create_strategy quick generator with 17 indicators, (2) AiCoin Python SDK (aicoin_data.py) for integrating real market data into custom strategies, (3) deploy/backtest/hyperopt tools. ALWAYS actively use AiCoin data (funding rate, L/S ratio, whale orders, etc.) in strategies when the user's API key supports it. For prices/charts use aicoin-market. For trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n> **⚠️ 运行脚本: 所有 `node scripts/...` 命令必须以本 SKILL.md 所在目录为 workdir。**\n\n# AiCoin Freqtrade\n\nFreqtrade strategy creation, backtesting, and deployment powered by [AiCoin Open API](https://www.aicoin.com/opendata).\n\n## Critical Rules\n\n1. **ALWAYS use `ft-deploy.mjs backtest`** for backtesting. NEVER write custom backtest scripts. NEVER use simulated/fabricated data.\n2. **ALWAYS use `ft-deploy.mjs deploy`** for deployment. NEVER use Docker. NEVER manually run `freqtrade` commands.\n3. **NEVER manually edit Freqtrade config files.** Use `ft-deploy.mjs` actions.\n4. **NEVER manually run `freqtrade trade`, `source .venv/bin/activate`, or `pip install freqtrade`.**\n5. **ACTIVELY use AiCoin data** in strategies. Check what data the user's API key supports and integrate it. Don't only use basic indicators when richer data is available.\n\n## Two Ways to Create Strategies\n\n### Option A: Quick Generator (for simple strategies)\n\n`create_strategy` generates a ready-to-backtest strategy file with selected indicators and optional AiCoin data:\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\nAvailable `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`\n\n### Option B: Write Custom Strategy Code (for complex/custom strategies)\n\nWhen users need custom logic beyond what `create_strategy` offers, write a Python strategy file directly. **Use the AiCoin Python SDK** (`aicoin_data.py`, auto-installed at `~/.freqtrade/user_data/strategies/`) to integrate real market data.\n\nStrategy file location: `~/.freqtrade/user_data/strategies/YourStrategyName.py`\n\n#### AiCoin Python SDK Reference\n\n```python\nfrom aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis\n```\n\n#### Complete Strategy Template (copy and customize)\n\n```python\n# MyCustomStrategy - Description\n# Uses AiCoin data in live/dry_run mode\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyCustomStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    # Hyperopt parameters\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    # AiCoin data cache\n    _ac_funding_rate = 0.0\n    _ac_ls_ratio = 0.5\n    _ac_whale_signal = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # === Technical Indicators (always available) ===\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # MACD\n        ema12 = dataframe['close'].ewm(span=12, adjust=False).mean()\n        ema26 = dataframe['close'].ewm(span=26, adjust=False).mean()\n        dataframe['macd'] = ema12 - ema26\n        dataframe['macd_signal'] = dataframe['macd'].ewm(span=9, adjust=False).mean()\n\n        # EMA\n        dataframe['ema_fast'] = dataframe['close'].ewm(span=8, adjust=False).mean()\n        dataframe['ema_slow'] = dataframe['close'].ewm(span=21, adjust=False).mean()\n\n        # === AiCoin Data (live/dry_run only) ===\n        dataframe['funding_rate'] = 0.0\n        dataframe['ls_ratio'] = 0.5\n        dataframe['whale_signal'] = 0.0\n\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:  # Update every 5 min\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            # Apply latest AiCoin data to current candle\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n            dataframe.iloc[-1, dataframe.columns.get_loc('ls_ratio')] = self._ac_ls_ratio\n            dataframe.iloc[-1, dataframe.columns.get_loc('whale_signal')] = self._ac_whale_signal\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        \"\"\"Fetch latest AiCoin data. Called every 5 min in live mode.\"\"\"\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData, ccxt_to_aicoin\n\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            symbol = ccxt_to_aicoin(pair, exchange)\n\n            # Funding rate (基础版)\n            try:\n                data = ac.funding_rate(symbol, weighted=True, limit='5')\n                items = data.get('data', [])\n                if isinstance(items, list) and items:\n                    latest = items[0]\n                    if isinstance(latest, dict) and 'close' in latest:\n                        self._ac_funding_rate = float(latest['close']) * 100\n            except Exception as e:\n                logger.debug(f\"AiCoin funding_rate unavailable: {e}\")\n\n            # Long/short ratio (基础版)\n            try:\n                ls = ac.ls_ratio()\n                detail = ls.get('data', {}).get('detail', {})\n                if detail:\n                    ratio = float(detail.get('last', 1.0))\n                    self._ac_ls_ratio = max(0.0, min(1.0, ratio / (1.0 + ratio)))\n            except Exception as e:\n                logger.debug(f\"AiCoin ls_ratio unavailable: {e}\")\n\n            # Whale orders (标准版)\n            try:\n                orders = ac.big_orders(symbol)\n                if 'data' in orders and isinstance(orders['data'], list):\n                    buy_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                 if o.get('side', '').lower() in ('buy', 'bid', 'long'))\n                    sell_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                  if o.get('side', '').lower() in ('sell', 'ask', 'short'))\n                    total = buy_vol + sell_vol\n                    if total > 0:\n                        self._ac_whale_signal = (buy_vol - sell_vol) / total\n            except Exception as e:\n                logger.debug(f\"AiCoin big_orders unavailable: {e}\")\n\n        except ImportError:\n            logger.warning(\"aicoin_data module not found. Run ft-deploy.mjs deploy to install.\")\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Long: RSI oversold + MACD bullish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['macd'] > dataframe['macd_signal']) &\n            (dataframe['ema_fast'] > dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] <= 0.55) &        # More shorts = contrarian long\n            (dataframe['whale_signal'] >= -0.3) &     # Whales not heavily selling\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n\n        # Short: RSI overbought + MACD bearish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['macd'] < dataframe['macd_signal']) &\n            (dataframe['ema_fast'] < dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] >= 0.45) &        # More longs = contrarian short\n            (dataframe['whale_signal'] <= 0.3) &      # Whales not heavily buying\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n### AiCoin Data Integration Patterns\n\nUse these patterns to integrate specific AiCoin data into entry/exit conditions:\n\n| AiCoin Data | Signal Logic | Tier |\n|-------------|-------------|------|\n| `funding_rate` | Rate > 0.01% → market over-leveraged long → short signal; Rate < -0.01% → long signal | 基础版 |\n| `ls_ratio` | Ratio < 0.45 (more shorts) → contrarian long; Ratio > 0.55 (more longs) → contrarian short | 基础版 |\n| `big_orders` | `(buy_vol - sell_vol) / total > 0.3` → whale buying → long; `< -0.3` → short | 标准版 |\n| `open_interest` | OI rising + price rising = healthy trend; OI rising + price falling = weak, likely reversal | 专业版 |\n| `liquidation_map` | More short liquidations above → short squeeze likely → long; vice versa | 高级版 |\n\n### Key Rule: Backtest Behavior\n\nAiCoin real-time data is **NOT available for historical periods**. In backtest mode:\n- AiCoin columns use **default values** (funding_rate=0.0, ls_ratio=0.5, whale_signal=0.0)\n- This means backtest results reflect **technical indicators only**\n- Live/dry_run trading uses **real AiCoin data**, which should improve performance vs backtest\n\nAlways explain this to the user when showing backtest results.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Quick-generate strategy | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| Backtest | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\"}'` |\n| Deploy (dry-run) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Deploy (live) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Hyperopt | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"epochs\":100}'` |\n| Strategy list | `node scripts/ft-deploy.mjs strategy_list` |\n| Bot status | `node scripts/ft-deploy.mjs status` |\n| Bot logs | `node scripts/ft-deploy.mjs logs '{\"lines\":50}'` |\n\n## Setup\n\n**Prerequisites:** Python 3.11+ and git.\n\n`.env` auto-loaded from (first found wins): cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\n**Exchange keys** (for live/dry-run):\n```\nBINANCE_API_KEY=xxx\nBINANCE_API_SECRET=xxx\n```\n\n**AiCoin API key** (for AiCoin data in strategies):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\nGet at https://www.aicoin.com/opendata\n\n## Scripts\n\n### ft-deploy.mjs — Deployment & Strategy\n\n| Action | Params |\n|--------|--------|\n| `check` | None |\n| `deploy` | `{\"strategy\":\"MACDKDJStrategy\",\"dry_run\":true,\"pairs\":[\"BTC/USDT:USDT\"]}` — **strategy 必填，指定策略名** |\n| `backtest` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\"}` |\n| `hyperopt` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `create_strategy` | `{\"name\":\"Name\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}` |\n| `strategy_list` | None |\n| `start` / `stop` / `status` / `logs` | None / `{\"lines\":50}` |\n\n### ft.mjs — Bot Control (requires running process)\n\n`ping`, `start`, `stop`, `balance`, `profit`, `trades_open`, `trades_history`, `force_enter`, `force_exit`, `daily`, `weekly`, `monthly`, `stats`\n\n### ft-dev.mjs — Dev Tools (requires running process)\n\n`backtest_start`, `backtest_status`, `candles_live`, `candles_analyzed`, `strategy_list`, `strategy_get`\n\n## Cross-Skill References\n\n| Need | Use |\n|------|-----|\n| Prices, K-lines, market data | **aicoin-market** |\n| Exchange trading (buy/sell) | **aicoin-trading** |\n| Hyperliquid whale tracking | **aicoin-hyperliquid** |\n\n## Paid Feature Guide\n\nWhen 304/403: **Do NOT retry.** Guide the user:\n\n| Tier | Price | Data for Strategies |\n|------|-------|---------------------|\n| 免费版 | $0 | Pure technical indicators |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\nConfigure: `AICOIN_ACCESS_KEY_ID` + `AICOIN_ACCESS_SECRET` in `.env`\n\nFile v3.4.7:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.4.7\",\n  \"publishedAt\": 1773161442225\n}\n\nFile v3.4.7:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}\n\nFile v3.4.7:package.json\n\n{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.4.6\",\n  \"private\": true,\n  \"type\": \"module\"\n}\n\nArchive v3.4.6: 13 files, 37543 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (51081b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (14910b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)\n\nFile v3.4.6:SKILL.md\n\n---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about writing trading strategies, backtesting, deploying Freqtrade bots, quantitative trading, or strategy optimization. Trigger words: 'write strategy', 'create strategy', 'backtest', 'deploy Freqtrade', 'deploy bot', 'quantitative', 'hyperopt', '写策略', '创建策略', '回测', '部署', '量化', '策略优化'. This skill provides: (1) create_strategy quick generator with 17 indicators, (2) AiCoin Python SDK (aicoin_data.py) for integrating real market data into custom strategies, (3) deploy/backtest/hyperopt tools. ALWAYS actively use AiCoin data (funding rate, L/S ratio, whale orders, etc.) in strategies when the user's API key supports it. For prices/charts use aicoin-market. For trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n> **⚠️ 运行脚本: 所有 `node scripts/...` 命令必须以本 SKILL.md 所在目录为 workdir。**\n\n# AiCoin Freqtrade\n\nFreqtrade strategy creation, backtesting, and deployment powered by [AiCoin Open API](https://www.aicoin.com/opendata).\n\n## Critical Rules\n\n1. **ALWAYS use `ft-deploy.mjs backtest`** for backtesting. NEVER write custom backtest scripts. NEVER use simulated/fabricated data.\n2. **ALWAYS use `ft-deploy.mjs deploy`** for deployment. NEVER use Docker. NEVER manually run `freqtrade` commands.\n3. **NEVER manually edit Freqtrade config files.** Use `ft-deploy.mjs` actions.\n4. **NEVER manually run `freqtrade trade`, `source .venv/bin/activate`, or `pip install freqtrade`.**\n5. **ACTIVELY use AiCoin data** in strategies. Check what data the user's API key supports and integrate it. Don't only use basic indicators when richer data is available.\n\n## Two Ways to Create Strategies\n\n### Option A: Quick Generator (for simple strategies)\n\n`create_strategy` generates a ready-to-backtest strategy file with selected indicators and optional AiCoin data:\n\n```bash\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'\n```\n\nAvailable `indicators`: `rsi`, `bb`, `ema`, `sma`, `macd`, `stochastic`/`kdj`, `atr`, `adx`, `cci`, `williams_r`, `vwap`, `ichimoku`, `volume_sma`, `obv`\n\n### Option B: Write Custom Strategy Code (for complex/custom strategies)\n\nWhen users need custom logic beyond what `create_strategy` offers, write a Python strategy file directly. **Use the AiCoin Python SDK** (`aicoin_data.py`, auto-installed at `~/.freqtrade/user_data/strategies/`) to integrate real market data.\n\nStrategy file location: `~/.freqtrade/user_data/strategies/YourStrategyName.py`\n\n#### AiCoin Python SDK Reference\n\n```python\nfrom aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis\n```\n\n#### Complete Strategy Template (copy and customize)\n\n```python\n# MyCustomStrategy - Description\n# Uses AiCoin data in live/dry_run mode\nfrom freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyCustomStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    # Hyperopt parameters\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    # AiCoin data cache\n    _ac_funding_rate = 0.0\n    _ac_ls_ratio = 0.5\n    _ac_whale_signal = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # === Technical Indicators (always available) ===\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # MACD\n        ema12 = dataframe['close'].ewm(span=12, adjust=False).mean()\n        ema26 = dataframe['close'].ewm(span=26, adjust=False).mean()\n        dataframe['macd'] = ema12 - ema26\n        dataframe['macd_signal'] = dataframe['macd'].ewm(span=9, adjust=False).mean()\n\n        # EMA\n        dataframe['ema_fast'] = dataframe['close'].ewm(span=8, adjust=False).mean()\n        dataframe['ema_slow'] = dataframe['close'].ewm(span=21, adjust=False).mean()\n\n        # === AiCoin Data (live/dry_run only) ===\n        dataframe['funding_rate'] = 0.0\n        dataframe['ls_ratio'] = 0.5\n        dataframe['whale_signal'] = 0.0\n\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:  # Update every 5 min\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            # Apply latest AiCoin data to current candle\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n            dataframe.iloc[-1, dataframe.columns.get_loc('ls_ratio')] = self._ac_ls_ratio\n            dataframe.iloc[-1, dataframe.columns.get_loc('whale_signal')] = self._ac_whale_signal\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        \"\"\"Fetch latest AiCoin data. Called every 5 min in live mode.\"\"\"\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData, ccxt_to_aicoin\n\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            symbol = ccxt_to_aicoin(pair, exchange)\n\n            # Funding rate (基础版)\n            try:\n                data = ac.funding_rate(symbol, weighted=True, limit='5')\n                items = data.get('data', [])\n                if isinstance(items, list) and items:\n                    latest = items[0]\n                    if isinstance(latest, dict) and 'close' in latest:\n                        self._ac_funding_rate = float(latest['close']) * 100\n            except Exception as e:\n                logger.debug(f\"AiCoin funding_rate unavailable: {e}\")\n\n            # Long/short ratio (基础版)\n            try:\n                ls = ac.ls_ratio()\n                detail = ls.get('data', {}).get('detail', {})\n                if detail:\n                    ratio = float(detail.get('last', 1.0))\n                    self._ac_ls_ratio = max(0.0, min(1.0, ratio / (1.0 + ratio)))\n            except Exception as e:\n                logger.debug(f\"AiCoin ls_ratio unavailable: {e}\")\n\n            # Whale orders (标准版)\n            try:\n                orders = ac.big_orders(symbol)\n                if 'data' in orders and isinstance(orders['data'], list):\n                    buy_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                 if o.get('side', '').lower() in ('buy', 'bid', 'long'))\n                    sell_vol = sum(float(o.get('amount', 0)) for o in orders['data']\n                                  if o.get('side', '').lower() in ('sell', 'ask', 'short'))\n                    total = buy_vol + sell_vol\n                    if total > 0:\n                        self._ac_whale_signal = (buy_vol - sell_vol) / total\n            except Exception as e:\n                logger.debug(f\"AiCoin big_orders unavailable: {e}\")\n\n        except ImportError:\n            logger.warning(\"aicoin_data module not found. Run ft-deploy.mjs deploy to install.\")\n        except Exception as e:\n            logger.warning(f\"AiCoin data error: {e}\")\n\n    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Long: RSI oversold + MACD bullish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] < self.rsi_buy.value) &\n            (dataframe['macd'] > dataframe['macd_signal']) &\n            (dataframe['ema_fast'] > dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] <= 0.55) &        # More shorts = contrarian long\n            (dataframe['whale_signal'] >= -0.3) &     # Whales not heavily selling\n            (dataframe['volume'] > 0),\n            'enter_long'] = 1\n\n        # Short: RSI overbought + MACD bearish + AiCoin confirmations\n        dataframe.loc[\n            (dataframe['rsi'] > self.rsi_sell.value) &\n            (dataframe['macd'] < dataframe['macd_signal']) &\n            (dataframe['ema_fast'] < dataframe['ema_slow']) &\n            (dataframe['ls_ratio'] >= 0.45) &        # More longs = contrarian short\n            (dataframe['whale_signal'] <= 0.3) &      # Whales not heavily buying\n            (dataframe['volume'] > 0),\n            'enter_short'] = 1\n\n        return dataframe\n\n    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[(dataframe['rsi'] > 70), 'exit_long'] = 1\n        dataframe.loc[(dataframe['rsi'] < 30), 'exit_short'] = 1\n        return dataframe\n```\n\n### AiCoin Data Integration Patterns\n\nUse these patterns to integrate specific AiCoin data into entry/exit conditions:\n\n| AiCoin Data | Signal Logic | Tier |\n|-------------|-------------|------|\n| `funding_rate` | Rate > 0.01% → market over-leveraged long → short signal; Rate < -0.01% → long signal | 基础版 |\n| `ls_ratio` | Ratio < 0.45 (more shorts) → contrarian long; Ratio > 0.55 (more longs) → contrarian short | 基础版 |\n| `big_orders` | `(buy_vol - sell_vol) / total > 0.3` → whale buying → long; `< -0.3` → short | 标准版 |\n| `open_interest` | OI rising + price rising = healthy trend; OI rising + price falling = weak, likely reversal | 专业版 |\n| `liquidation_map` | More short liquidations above → short squeeze likely → long; vice versa | 高级版 |\n\n### Key Rule: Backtest Behavior\n\nAiCoin real-time data is **NOT available for historical periods**. In backtest mode:\n- AiCoin columns use **default values** (funding_rate=0.0, ls_ratio=0.5, whale_signal=0.0)\n- This means backtest results reflect **technical indicators only**\n- Live/dry_run trading uses **real AiCoin data**, which should improve performance vs backtest\n\nAlways explain this to the user when showing backtest results.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Quick-generate strategy | `node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MyStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}'` |\n| Backtest | `node scripts/ft-deploy.mjs backtest '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\"}'` |\n| Deploy (dry-run) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Deploy (live) | `node scripts/ft-deploy.mjs deploy '{\"strategy\":\"MyStrat\",\"dry_run\":false,\"pairs\":[\"BTC/USDT:USDT\"]}'` |\n| Hyperopt | `node scripts/ft-deploy.mjs hyperopt '{\"strategy\":\"MyStrat\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\",\"epochs\":100}'` |\n| Strategy list | `node scripts/ft-deploy.mjs strategy_list` |\n| Bot status | `node scripts/ft-deploy.mjs status` |\n| Bot logs | `node scripts/ft-deploy.mjs logs '{\"lines\":50}'` |\n\n## Setup\n\n**Prerequisites:** Python 3.11+ and git.\n\n`.env` auto-loaded from (first found wins): cwd → `~/.openclaw/workspace/.env` → `~/.openclaw/.env`\n\n**Exchange keys** (for live/dry-run):\n```\nBINANCE_API_KEY=xxx\nBINANCE_API_SECRET=xxx\n```\n\n**AiCoin API key** (for AiCoin data in strategies):\n```\nAICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret\n```\nGet at https://www.aicoin.com/opendata\n\n## Scripts\n\n### ft-deploy.mjs — Deployment & Strategy\n\n| Action | Params |\n|--------|--------|\n| `check` | None |\n| `deploy` | `{\"strategy\":\"MACDKDJStrategy\",\"dry_run\":true,\"pairs\":[\"BTC/USDT:USDT\"]}` — **strategy 必填，指定策略名** |\n| `backtest` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"timerange\":\"20250101-20260301\"}` |\n| `hyperopt` | `{\"strategy\":\"Name\",\"timeframe\":\"1h\",\"epochs\":100}` |\n| `create_strategy` | `{\"name\":\"Name\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\"]}` |\n| `strategy_list` | None |\n| `start` / `stop` / `status` / `logs` | None / `{\"lines\":50}` |\n\n### ft.mjs — Bot Control (requires running process)\n\n`ping`, `start`, `stop`, `balance`, `profit`, `trades_open`, `trades_history`, `force_enter`, `force_exit`, `daily`, `weekly`, `monthly`, `stats`\n\n### ft-dev.mjs — Dev Tools (requires running process)\n\n`backtest_start`, `backtest_status`, `candles_live`, `candles_analyzed`, `strategy_list`, `strategy_get`\n\n## Cross-Skill References\n\n| Need | Use |\n|------|-----|\n| Prices, K-lines, market data | **aicoin-market** |\n| Exchange trading (buy/sell) | **aicoin-trading** |\n| Hyperliquid whale tracking | **aicoin-hyperliquid** |\n\n## Paid Feature Guide\n\nWhen 304/403: **Do NOT retry.** Guide the user:\n\n| Tier | Price | Data for Strategies |\n|------|-------|---------------------|\n| 免费版 | $0 | Pure technical indicators |\n| 基础版 | $29/mo | + `funding_rate`, `ls_ratio` |\n| 标准版 | $79/mo | + `big_orders`, `agg_trades` |\n| 高级版 | $299/mo | + `liquidation_map` |\n| 专业版 | $699/mo | + `open_interest`, `ai_analysis` |\n\nConfigure: `AICOIN_ACCESS_KEY_ID` + `AICOIN_ACCESS_SECRET` in `.env`\n\nFile v3.4.6:_meta.json\n\n{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.4.6\",\n  \"publishedAt\": 1773159047270\n}\n\nFile v3.4.6:lib/defaults.json\n\n{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via\n\nArchive v3.4.5: 13 files, 37543 bytes\n\nFiles: lib/aicoin_data.py (12721b), lib/aicoin-api.mjs (6448b), lib/defaults.json (227b), lib/freqtrade-api.mjs (2874b), package.json (93b), scripts/ft-deploy.mjs (51081b), scripts/ft-dev.mjs (941b), scripts/ft.mjs (1269b), SKILL.md (14910b), strategies/FundingRateStrategy.py (7774b), strategies/LiquidationHunterStrategy.py (10066b), strategies/WhaleFollowStrategy.py (8469b), _meta.json (135b)","readmeExcerpt":"Skill: Aicoin Freqtrade Owner: procaross Summary: Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance /... Tags: aicoin:1.0.0, bot:1.0.0, crypto:1.0.0, freqtrade:1.0.0, latest:3.5.4 Version history: v3.5.4 | 2026-05-21T07:35:48.973Z | user 同步最新仓库变更:set-key 支持直接喂后台 JSON + install-test 实测修正 (catalog 分组冲突 / 403 信封归一) ","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"RSILong\",\"timeframe\":\"1h\",\"indicators\":[\"rsi\"],\"direction\":\"long\"}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'"},{"language":"python","snippet":"from aicoin_data import AiCoinData\n\nac = AiCoinData(cache_ttl=300)   # 自动从 .env 读 key，内置 5 分钟缓存\n\n# 高层信号 —— 直接返回能用的数字，丢进策略即可\nac.whale_signal(\"BTC/USDT:USDT\", \"binance\")        # 大单买卖压力 -1..+1\nac.ls_ratio_norm()                                 # 多空比 0..1（>0.5 偏多）\nac.funding_rate_pct(\"BTC/USDT:USDT\", \"binance\")    # 最新资金费率（百分比）\nac.liq_bias(\"BTC/USDT:USDT\", \"binance\")            # 清算图方向偏向 -1..+1\n\n# 原始数据\nac.coin_ticker(\"bitcoin,ethereum\")                 # 实时行情\nac.klines(\"BTC/USDT\", \"binance\", interval=\"1h\", limit=100)\n\n# 任意 v3 接口 —— path 是 /api/v3/ 后那段，清单见 https://open.aicoin.com/api/v3/_catalog\nac.get(\"markets/hot-coins\", {\"tab_key\": \"defi\"})\nac.get(\"hyperliquid/whales/open-positions\", {\"coin\": \"BTC\"})"},{"language":"python","snippet":"from freqtrade.strategy import IStrategy, IntParameter, DecimalParameter\nfrom pandas import DataFrame\nimport logging, time\n\nlogger = logging.getLogger(__name__)\n\n\nclass MyStrategy(IStrategy):\n    INTERFACE_VERSION = 3\n    timeframe = '15m'\n    can_short = True\n\n    minimal_roi = {\"0\": 0.05, \"60\": 0.03, \"120\": 0.01}\n    stoploss = -0.05\n    trailing_stop = True\n    trailing_stop_positive = 0.02\n    trailing_stop_positive_offset = 0.03\n\n    rsi_buy = IntParameter(20, 40, default=30, space='buy')\n    rsi_sell = IntParameter(60, 80, default=70, space='sell')\n\n    _ac_funding_rate = 0.0\n    _ac_last_update = 0.0\n\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # RSI\n        delta = dataframe['close'].diff()\n        gain = delta.clip(lower=0).rolling(window=14).mean()\n        loss = (-delta.clip(upper=0)).rolling(window=14).mean()\n        rs = gain / loss\n        dataframe['rsi'] = 100 - (100 / (1 + rs))\n\n        # AiCoin 数据 (live/dry_run only, backtest 用默认值 0.0)\n        dataframe['funding_rate'] = 0.0\n        if self.dp and self.dp.runmode.value in ('live', 'dry_run'):\n            now = time.time()\n            if now - self._ac_last_update > 300:\n                self._update_aicoin_data(metadata)\n                self._ac_last_update = now\n            dataframe.iloc[-1, dataframe.columns.get_loc('funding_rate')] = self._ac_funding_rate\n\n        return dataframe\n\n    def _update_aicoin_data(self, metadata: dict):\n        try:\n            import sys, os\n            _sd = os.path.dirname(os.path.abspath(__file__))\n            if _sd not in sys.path:\n                sys.path.insert(0, _sd)\n            from aicoin_data import AiCoinData\n            ac = AiCoinData(cache_ttl=300)\n            pair = metadata.get('pair', 'BTC/USDT:USDT')\n            exchange = self.config.get('exchange', {}).get('name', 'binance')\n            self._ac_funding_rate = ac.funding_rate_pct(pair, exchange)\n        except Exception as e:\n            logger."},{"language":"text","snippet":"AICOIN_ACCESS_KEY_ID=your-key-id\nAICOIN_ACCESS_SECRET=your-secret"},{"language":"bash","snippet":"node scripts/ft-deploy.mjs create_strategy '{\"name\":\"MACDStrategy\",\"timeframe\":\"15m\",\"indicators\":[\"macd\",\"rsi\",\"atr\"]}'\nnode scripts/ft-deploy.mjs create_strategy '{\"name\":\"WhaleStrat\",\"timeframe\":\"15m\",\"indicators\":[\"rsi\",\"macd\"],\"aicoin_data\":[\"funding_rate\",\"ls_ratio\"]}'"},{"language":"python","snippet":"from aicoin_data import AiCoinData, ccxt_to_aicoin\n\nac = AiCoinData(cache_ttl=300)  # Auto-loads API keys from .env\n\n# Convert CCXT pair to AiCoin symbol\nsymbol = ccxt_to_aicoin(\"BTC/USDT:USDT\", \"binance\")  # → \"btcswapusdt:binance\"\n\n# ── Free tier (no key needed) ──\nac.coin_ticker(\"bitcoin\")             # Real-time price\nac.kline(symbol, period=\"3600\")       # K-line data (period in seconds)\nac.hot_coins(\"market\")                # Trending coins\n\n# ── 基础版 ($29/mo) ──\nac.funding_rate(symbol)               # Funding rate history\nac.funding_rate(symbol, weighted=True) # Volume-weighted cross-exchange rate\nac.ls_ratio()                         # Aggregated long/short ratio\n\n# ── 标准版 ($79/mo) ──\nac.big_orders(symbol)                 # Whale/large orders\nac.agg_trades(symbol)                 # Aggregated large trades\n\n# ── 高级版 ($299/mo) ──\nac.liquidation_map(symbol, cycle=\"24h\")    # Liquidation heatmap\nac.liquidation_history(symbol)              # Liquidation history\n\n# ── 专业版 ($699/mo) ──\nac.open_interest(\"BTC\", interval=\"15m\")    # Aggregated open interest\nac.ai_analysis([\"BTC\"])                     # AI-powered analysis"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: aicoin-freqtrade\ndescription: \"Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance / open positions / 盈亏. Trigger words: 'write strategy', 'create strategy', 'backtest', 'switch strategy', 'switch to live', 'open positions', 'P&L', '写策略', '创建策略', '回测', '部署策略', '切策略', '切实盘', '当前持仓', '今天赚多少', '盈亏'. In CoinClaw containers (OpenClaw / Hermes / Claude Code) freqtrade is a supervisord-managed daemon on :8080 — this skill auto-detects engine + paths via lib/coinclaw-env.mjs and never spawns competing freqtrade processes. Outside CoinClaw it falls back to host mode (clone freqtrade + nohup). For prices/charts use aicoin-market. For exchange trading use aicoin-trading. For Hyperliquid use aicoin-hyperliquid.\"\nmetadata: { \"openclaw\": { \"primaryEnv\": \"AICOIN_ACCESS_KEY_ID\", \"requires\": { \"bins\": [\"node\"] }, \"homepage\": \"https://www.aicoin.com/opendata\", \"source\": \"https://github.com/aicoincom/coinos-skills\", \"license\": \"MIT\" } }\n---\n\n# AiCoin Freqtrade\n\nFreqtrade 策略 / 回测 / 部署 / 实时控制 — 跨 CoinClaw 三引擎自动适配。\n\n## 关键原则(读完再动手)\n\n### 一、CoinClaw 容器里 freqtrade 是常驻 daemon\n\nOpenClaw / Hermes / Claude Code 三个引擎容器都通过 supervisord 把 freqtrade 起为常驻进程, 监听 `127.0.0.1:8080`, 默认跑 `NoOpStrategy`(空跑). **不要自己起 freqtrade 进程** — 会跟 daemon 抢端口, dashboard 立刻 offline.\n\n正确流程是: 写策略文件 → 调 `ft-deploy.mjs deploy {\"strategy\":\"...\"}` → 脚本改 config + 重启 daemon. dashboard 会自动刷出新策略.\n\n`scripts/ft.mjs` + `scripts/ft-deploy.mjs` 内置三引擎自动识别(`lib/coinclaw-env.mjs`), 路径 / auth / supervisord socket 都自动解析, **agent 不用关心是哪个引擎**.\n\n### 二、永远先调 freqtrade REST API, 不要\"自己计算\"\n\n| 用户问 | 必须先调 |\n|---|---|\n| 现在赚多少 / 总盈亏 / 今天涨了多少 | `ft.mjs profit` (`/api/v1/profit`) |\n| 持仓 / 现在开了哪些 | `ft.mjs trades_open` (`/api/v1/status`) |\n| 余额 / 资金多少 | `ft.mjs balance` (`/api/v1/balance`) |\n| 跑的什么策略 / 当前模式 | `ft.mjs daemon_info` 或 `config` |\n| 历史交易 / 已平仓 | `ft.mjs trades_history` |\n| 单交易对绩效 | `ft.mjs profit_per_pair` |\n\n**dashboard 数字对齐规则(关键)**: 用户问\"赚了多少\"必须报告**两个数字**:\n- **已平仓累计盈亏** = `profit_closed_coin` (USDT) — **dashboard 顶栏的累计盈亏 = 这个**\n- **含浮动总盈亏** = `profit_all_coin` (USDT) — 已平仓 + 当前持仓的浮动盈亏\n\n只调 `/status` 拿持仓浮动盈亏会漏掉已平仓部分, 导致跟 dashboard 数字不一致 — 用户立刻发现, 信任度归零.\n\n### 三、切策略 / 切实盘 / 切交易对必须走脚本\n\nconfig.json 是 daemon 启动时读一次, 手动改完不会自动生效. 必须用:\n\n| 操作 | 命令 | 是否需要 daemon 重启 |\n|---|---|---|\n| 切策略 | `ft.mjs set_strategy {\"strategy\":\"X\"}` | 必须重启 (~30s) |\n| 切交易对 | `ft.mjs set_pairs {\"pairs\":[...]}` | 不重启, `reload_config` 即可 |\n| 切实盘/模拟 | `ft.mjs set_dry_run {\"dry_run\":false}` | 必须重启 |\n| reload 配置 | `ft.mjs reload` | 不重启 |\n\n或者一次完成所有变更: `ft-deploy.mjs deploy {\"strategy\":\"X\",\"pairs\":[\"BTC/USDT:USDT\"],\"dry_run\":false}`.\n\n**任何直接修改 config.json 的操作(包括手动编辑 pair_whitelist / minimal_roi / stoploss 等), 改完后必须立即调 `ft.mjs reload`** — 否则 daemon 仍用内存里的旧配置运行, 白名单/止损等改动不会生效. 忘了 reload 是最常见的\"改了但没用\"的原因.\n\n**chat 主动发起的高 stake 操作必须强 confirm**(违反即错):\n\n适用: 用户在 chat 里说\"平掉\"、\"切实盘\"、\"卖了\"、\"开仓\"等 — 通过 agent 调用 `force_exit` / `force_enter` / `set_dry_run` 的操作.\n\n流程:\n1. *"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn744cgmrtxwys18mxjhzaapn582553w\",\n  \"slug\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.4\",\n  \"publishedAt\": 1779348948973\n}"},{"path":"skill-card.md","content":"## Description:\n\nHelps agents create, backtest, tune, deploy, and operate Freqtrade strategies with AiCoin market data integrations across CoinClaw-style agent containers and host-mode environments.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[procaross](https://clawhub.ai/user/procaross)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nExternal developers and trading-bot operators use this skill to generate and manage Freqtrade strategies, run backtests and hyperopt, switch strategies or trading pairs, and query live bot status, balances, positions, and profit/loss. It is intended for users who understand the risks of automated cryptocurrency trading and can review generated strategy files before deployment.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The skill can control a Freqtrade bot and may interact with configured exchange credentials, which can lead to real trading losses if used in live mode.\n\nMitigation: Start in dry-run mode, verify exchange credentials and balances separately, and require explicit confirmation before live-mode or manual open/close actions.\n\nRisk: Generated or modified strategy files can affect automated trading behavior.\n\nMitigation: Review strategy code and configuration changes before deployment, then backtest or dry-run before allowing live trading.\n\nRisk: Crafted action parameters or host-mode setup paths can run unintended commands or code.\n\nMitigation: Avoid untrusted action inputs, prefer the managed CoinClaw daemon path, and install host prerequisites independently instead of relying on host-mode auto-install.\n\nRisk: Pointing AICOIN_BASE_URL at a non-AiCoin host can redirect API traffic and credentials.\n\nMitigation: Keep AICOIN_BASE_URL unset or set only to an AiCoin-controlled endpoint.\n\n## Reference(s):\n\n- [AiCoin Open Data](https://www.aicoin.com/opendata)\n- [AiCoin Open API v3 Catalog](https://open.aicoin.com/api/v3/_catalog)\n- [ClawHub skill page](https://clawhub.ai/procaross/skills/aicoin-freqtrade)\n- [Publisher profile](https://clawhub.ai/user/procaross)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown guidance with inline shell commands, JSON parameters, and generated Python strategy code]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May create or modify Freqtrade strategy and configuration files when used by an agent with filesystem and command execution access.]\n\n## Skill Version(s):\n\n3.5.4 (source: ClawHub release evidence; artifact package.json reports 3.5.2)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment."},{"path":"lib/defaults.json","content":"{\n  \"comment\": \"Public free-tier AiCoin API key. IP rate-limited. Users can replace with their own key via env vars.\",\n  \"accessKeyId\": \"ronJ8uI0Yj2soAfGVs5H1YALUIINbE22\",\n  \"accessSecret\": \"CWHZcH2us1CLSE7grroR1TpS0Z1JxTwU\"\n}"},{"path":"package.json","content":"{\n  \"name\": \"aicoin-freqtrade\",\n  \"version\": \"3.5.2\",\n  \"private\": true,\n  \"type\": \"module\"\n}"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance /... Skill: Aicoin Freqtrade Owner: procaross Summary: Use when user asks about Freqtrade — strategy creation, backtest, hyperopt, switching strategies / pairs / dry-run mode, querying live bot status / balance /... Tags: aicoin:1.0.0, bot:1.0.0, crypto:1.0.0, freqtrade:1.0.0, latest:3.5.4 Version history: v3.5.4 | 2026-05-21T07:35:48.973Z | user 同步最新仓库变更:set-key 支持直接喂后台 JSON + install-test 实测修正 (catalog 分组冲突 / 403 信封归一)","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":1344,"uniquenessScore":48,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-11T12:14:35.491Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-11T12:14:35.491Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-11T15:26:02.620Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}