AiCoin
Crypto data & trading toolkit powered by AiCoin Open API.
Version: 1.6.0 | Last Updated: 2026-03-05
🚨 CRITICAL RULES - READ FIRST
FREQTRADE OPERATIONS:
- ✅ ALWAYS use
node scripts/ft-deploy.mjs deploy for deployment
- ✅ ALWAYS use
node scripts/ft-deploy.mjs backtest for backtesting
- ❌ NEVER use Docker commands
- ❌ NEVER manually run
freqtrade commands
- ❌ NEVER write custom Python scripts for Freqtrade
TRADING SAFETY:
- ❌ NEVER place orders without explicit user confirmation
- ❌ NEVER auto-adjust order parameters
- ✅ ALWAYS show order preview and ask "确认下单?" first
Data Sources: AiCoin aggregates data from 200+ exchanges. Price data is real-time, K-lines updated every second, funding rates every 8h.
Supported Exchanges for Trading: Binance, OKX, Bybit, Bitget, Gate.io, HTX, KuCoin, MEXC, Coinbase (requires API keys in .env).
Quick Start Examples:
# Check BTC price
node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'
# Get 1h K-line
node scripts/market.mjs kline '{"symbol":"btcusdt:okex","period":"3600","size":"10"}'
# Check balance (requires exchange API keys)
node scripts/exchange.mjs balance '{"exchange":"okx"}'
Performance Tips:
- Batch queries:
coin_ticker supports multiple coins → faster than separate calls
- Reduce API calls: Check balance once, reuse result for multiple calculations
- Use appropriate timeframes: Don't fetch 1000 candles when 10 is enough
Quick Reference — Most Common Commands
Run all scripts from the aicoin skill directory. Use exec tool, NOT process.
API keys are pre-configured. Do NOT ask the user for keys. Do NOT run env/printenv.
Do NOT use curl, web_fetch, or browser for crypto data. Always use these scripts.
🚨 TRADING SAFETY: NEVER place orders without user confirmation. ALWAYS show order details and ask "确认下单?" FIRST. NEVER auto-adjust order size or parameters.
⚡ PERFORMANCE: Use batch queries when possible. coin_ticker supports multiple coins in one call (e.g., "coin_list":"bitcoin,ethereum,solana").
| Task |
Command |
| BTC price |
node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}' |
| Multi price |
node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin,ethereum,solana"}' |
| K-line |
node scripts/market.mjs kline '{"symbol":"btcusdt:okex","period":"3600","size":"100"}' |
| Funding rate |
node scripts/coin.mjs funding_rate '{"symbol":"BTC"}' (BTC only, 8h default) |
| Funding rate (other coins) |
node scripts/exchange.mjs funding_rate '{"exchange":"binance","symbol":"ETH/USDT:USDT"}' |
| Open interest |
node scripts/coin.mjs open_interest '{"symbol":"BTC","interval":"15m"}' |
| Long/short ratio |
node scripts/features.mjs ls_ratio |
| Whale orders |
node scripts/features.mjs big_orders '{"symbol":"btcswapusdt:binance"}' |
| News flash |
node scripts/news.mjs newsflash '{"language":"cn"}' |
| HL whale |
node scripts/hl-market.mjs whale_positions '{"coin":"BTC"}' |
| Balance |
node scripts/exchange.mjs balance '{"exchange":"okx"}' |
| Ticker |
node scripts/exchange.mjs ticker '{"exchange":"binance","symbol":"BTC/USDT"}' |
| Orderbook |
node scripts/exchange.mjs orderbook '{"exchange":"binance","symbol":"BTC/USDT"}' |
| Buy/Sell |
node scripts/exchange.mjs create_order '{"exchange":"okx","symbol":"BTC/USDT","type":"market","side":"buy","amount":0.001}' → returns preview only |
| Positions |
node scripts/exchange.mjs positions '{"exchange":"okx","market_type":"swap"}' |
| Market list |
node scripts/exchange.mjs markets '{"exchange":"binance","base":"BTC"}' |
| Deploy Freqtrade |
node scripts/ft-deploy.mjs deploy '{"pairs":["BTC/USDT:USDT"]}' (dry-run by default) |
| Backtest |
node scripts/ft-deploy.mjs backtest '{"strategy":"SampleStrategy","timerange":"20250101-"}' ⚠️ MUST use this script |
Symbol shortcuts: BTC, ETH, SOL, DOGE, XRP auto-resolve to AiCoin format (e.g. btcswapusdt:binance) in coin.mjs. For exchange.mjs, use CCXT format: BTC/USDT, BTC/USDT:USDT (swap).
Chinese Slang Recognition: Understand common crypto slang: 大饼=BTC, 姨太=ETH, 狗狗=DOGE, 瑞波=XRP, 索拉纳=SOL, 做多=long, 做空=short, 爆仓=liquidation, 合约=futures/swap.
Common Errors & Solutions:
Error: Invalid symbol → Check symbol format (AiCoin: btcusdt:okex, CCXT: BTC/USDT)
Error: Insufficient balance → Check balance first with exchange.mjs balance, don't auto-adjust order size
Error: API key invalid → Keys are in .env, never pass inline. Check if user configured exchange keys.
Timeout → Freqtrade operations may take 5+ minutes, increase timeout or use ft-deploy.mjs which handles this
Rate limit exceeded → Wait 1-2 seconds between requests. Use batch queries when possible to reduce API calls.
Script not found → Ensure you're in the aicoin skill directory. Use exec tool with full path to script.
Response Format Best Practices:
- Use tables for structured data (prices, K-lines, balances)
- Include units (USDT, BTC, %) and directions (📈/📉) for clarity
- For analysis: show data first, then interpretation
- Keep responses concise - users can ask for details if needed
- Always fetch fresh data - NEVER use cached or memorized prices
- Timestamps: API returns UTC, convert to user's timezone if needed (default: show UTC+8 for Chinese users)
- Language: Always reply in the same language as the user. If the user writes in Chinese, ALL text (titles, headings, analysis, labels) MUST be in Chinese. Never mix English headings into a Chinese response.
Coin Recommendation Best Practices:
- When the user asks for coin picks WITHOUT specifying a sector, recommend across MULTIPLE sectors (AI, DeFi, L2, Meme, Infrastructure, etc.) for diversification
- Only focus on a single sector when the user explicitly requests it (e.g., "AI赛道", "DeFi概念")
- Use
hot_coins with different keys (defi, gamefi, web, newcoin, market) to discover coins across sectors, don't just pick from one category
- Always include reasoning for each pick: why THIS coin, why NOW (momentum, volume spike, whale activity, news catalyst, etc.)
Setup Checklist
✅ Good News: The skill works out of the box! Scripts auto-load .env files from these locations (earlier paths take priority):
- Current working directory (
.env)
~/.openclaw/workspace/.env
~/.openclaw/.env
Before asking the user for ANY credentials, first check if .env already exists:
grep -c "AICOIN_ACCESS_KEY_ID" ~/.openclaw/workspace/.env 2>/dev/null || echo "0"
- If output is
1 or more → .env has AiCoin key configured. Skip setup, just run scripts directly.
- If output is
0 → No AiCoin key, but the built-in free key works automatically. Just run scripts.
Only ask setup questions when the user explicitly requests features that need configuration:
- Exchange trading (Binance, OKX, etc.) → needs exchange API keys +
cd into the aicoin skill directory and run npm install for ccxt
- Freqtrade bot → MUST use
node scripts/ft-deploy.mjs deploy (auto-configures everything, needs Python 3.11+ + exchange keys in .env). NEVER manually configure Freqtrade, NEVER use Docker, NEVER write custom install scripts.
- Proxy access → needs
PROXY_URL
Do NOT block the user from running commands. The skill works out of the box with the built-in free key.
How to Configure Environment Variables
The .env file location is ~/.openclaw/workspace/.env. When adding new variables:
Check if .env already exists:
test -f ~/.openclaw/workspace/.env && echo "EXISTS" || echo "NOT_FOUND"
If EXISTS → append (do NOT overwrite):
echo 'PROXY_URL=socks5://127.0.0.1:7890' >> ~/.openclaw/workspace/.env
If NOT_FOUND → create:
echo 'PROXY_URL=socks5://127.0.0.1:7890' > ~/.openclaw/workspace/.env
If a key already exists and needs updating, replace the specific line:
sed -i '' 's|^PROXY_URL=.*|PROXY_URL=socks5://127.0.0.1:7890|' ~/.openclaw/workspace/.env
NEVER overwrite the entire .env file — it may contain other credentials the user has already configured.
SECURITY: How to Run Scripts
Scripts auto-load .env — NEVER pass credentials inline. Just run:
node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'
NEVER do this — it exposes secrets in conversation logs:
# WRONG! DO NOT DO THIS!
AICOIN_ACCESS_KEY_ID=xxx node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'
Additional security rules:
- NEVER run
env, printenv, or env | grep — leaks gateway tokens and API secrets into session logs
- NEVER use curl to call exchange REST APIs directly (Binance, OKX, etc.) — use
exchange.mjs which handles auth, broker tags, and proxy
- NEVER use web_fetch, web_search, or browser for crypto data — always use the scripts in this skill
- NEVER fabricate or guess data from memory — always fetch real-time data via scripts
If a script fails due to missing env vars, guide the user to update their .env file instead of injecting variables into the command.
Environment Variables
Create a .env file in the OpenClaw workspace directory (recommended):
# AiCoin API (optional — built-in free key works with IP rate limits)
# Mapping: AiCoin website "API Key" → AICOIN_ACCESS_KEY_ID
# AiCoin website "API Secret" → AICOIN_ACCESS_SECRET
AICOIN_ACCESS_KEY_ID=your-api-key
AICOIN_ACCESS_SECRET=your-api-secret
# Exchange trading — only if needed (requires: npm install -g ccxt)
BINANCE_API_KEY=xxx
BINANCE_API_SECRET=xxx
# Supported: BINANCE, OKX, BYBIT, BITGET, GATE, HTX, KUCOIN, MEXC, COINBASE
# For OKX also set OKX_PASSWORD=xxx
# Proxy for exchange access — only if needed
# Supports http, https, socks5, socks4
PROXY_URL=socks5://127.0.0.1:7890
# Or standard env vars: HTTPS_PROXY=http://127.0.0.1:7890
# Freqtrade — auto-configured by ft-deploy.mjs, no manual setup needed
# FREQTRADE_URL=http://localhost:8080
# FREQTRADE_USERNAME=freqtrader
# FREQTRADE_PASSWORD=auto-generated
IMPORTANT — AiCoin API Key Configuration:
The user may provide two values without labels (just two strings copied from the AiCoin website). Do NOT guess which is which. Ask the user to confirm: "哪个是 API Key,哪个是 API Secret?" Or look for the labels in the user's message.
After writing keys to .env, ALWAYS verify by running a test call:
node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'
If the test returns error code 1001 (signature verification failed), the keys are swapped. Fix by swapping them:
# Read current values, swap them
OLD_KEY=$(grep '^AICOIN_ACCESS_KEY_ID=' ~/.openclaw/workspace/.env | cut -d= -f2)
OLD_SECRET=$(grep '^AICOIN_ACCESS_SECRET=' ~/.openclaw/workspace/.env | cut -d= -f2)
sed -i '' "s|^AICOIN_ACCESS_KEY_ID=.*|AICOIN_ACCESS_KEY_ID=${OLD_SECRET}|" ~/.openclaw/workspace/.env
sed -i '' "s|^AICOIN_ACCESS_SECRET=.*|AICOIN_ACCESS_SECRET=${OLD_KEY}|" ~/.openclaw/workspace/.env
Then re-run the test to confirm it works.
Or configure in ~/.openclaw/openclaw.json:
{
"skills": {
"entries": {
"aicoin": {
"enabled": true,
"apiKey": "your-aicoin-access-key-id",
"env": {
"AICOIN_ACCESS_SECRET": "your-secret"
}
}
}
}
}
Prerequisites
- Node.js — required for all scripts
- ccxt — required only for exchange trading. Run
npm install in the aicoin skill directory to install.
Scripts
All scripts follow: node scripts/<name>.mjs <action> [json-params]
scripts/coin.mjs — Coin Data
| Action |
Description |
Params |
coin_list |
List all coins |
None |
coin_ticker |
Real-time prices |
{"coin_list":"bitcoin,ethereum"} |
coin_config |
Coin profile |
{"coin_list":"bitcoin"} |
ai_analysis |
AI analysis & prediction |
{"coin_keys":"[\"bitcoin\"]","language":"CN"} |
funding_rate |
Funding rate |
{"symbol":"btcswapusdt:binance","interval":"8h"} Weighted: {"symbol":"btcswapusdt","interval":"8h","weighted":"true"} |
liquidation_map |
Liquidation heatmap |
{"dbkey":"btcswapusdt:binance","cycle":"24h"} |
liquidation_history |
Liquidation history |
{"symbol":"btcswapusdt:binance","interval":"1m"} |
estimated_liquidation |
Estimated liquidation |
{"dbkey":"btcswapusdt:binance","cycle":"24h"} |
open_interest |
Open interest |
{"symbol":"BTC","interval":"15m"} Coin-margined: add "margin_type":"coin" |
historical_depth |
Historical depth |
{"key":"btcswapusdt:okcoinfutures"} |
super_depth |
Large order depth (>$10k) |
{"key":"btcswapusdt:okcoinfutures"} |
trade_data |
Trade data |
{"dbkey":"btcswapusdt:okcoinfutures"} |
scripts/market.mjs — Market Data
Market Info
| Action |
Description |
Params |
exchanges |
Exchange list |
None |
ticker |
Exchange tickers |
{"market_list":"okex,binance"} |
hot_coins |
Trending coins |
{"key":"defi"} key: gamefi/anonymous/market/web/newcoin/stable/defi |
futures_interest |
Futures OI ranking |
{"lan":"cn"} |
K-Line
| Action |
Description |
Params |
kline |
Standard K-line |
{"symbol":"btcusdt:okex","period":"3600","size":"100"} period in seconds: 900=15m, 3600=1h, 14400=4h, 86400=1d |
indicator_kline |
Indicator K-line |
{"symbol":"btcswapusdt:binance","indicator_key":"fundflow","period":"3600"} |
indicator_pairs |
Indicator available pairs |
{"indicator_key":"fundflow"} |
Index
| Action |
Description |
Params |
index_list |
Index list |
None |
index_price |
Index price |
{"key":"i:diniw:ice"} |
index_info |
Index details |
{"key":"i:diniw:ice"} |
Crypto Stocks
| Action |
Description |
Params |
stock_quotes |
Stock quotes |
{"tickers":"i:mstr:nasdaq,i:coin:nasdaq"} |
stock_top_gainer |
Top gainers |
{"us_stock":"true"} |
stock_company |
Company details |
{"symbol":"i:mstr:nasdaq"} |
Treasury (Corporate Holdings)
| Action |
Description |
Params |
treasury_entities |
Holding entities |
{"coin":"BTC"} |
treasury_history |
Transaction history |
{"coin":"BTC"} |
treasury_accumulated |
Accumulated holdings |
{"coin":"BTC"} |
treasury_latest_entities |
Latest entities |
{"coin":"BTC"} |
treasury_latest_history |
Latest history |
{"coin":"BTC"} |
treasury_summary |
Holdings overview |
{"coin":"BTC"} |
Order Book Depth
| Action |
Description |
Params |
depth_latest |
Real-time snapshot |
{"dbKey":"btcswapusdt:binance"} |
depth_full |
Full order book |
{"dbKey":"btcswapusdt:binance"} |
depth_grouped |
Grouped depth |
{"dbKey":"btcswapusdt:binance","groupSize":"100"} |
scripts/news.mjs — News & Content
| Action |
Description |
Params |
news_list |
News list |
{"page":"1","pageSize":"20"} |
news_detail |
News detail |
{"id":"xxx"} |
news_rss |
RSS news |
{"page":"1"} |
newsflash |
AiCoin flash news |
{"language":"cn"} |
flash_list |
Industry flash news |
{"language":"cn"} |
exchange_listing |
Exchange listing announcements |
{"memberIds":"477,1509"} (477=Binance, 1509=Bitget) |
scripts/twitter.mjs — Twitter/X Crypto Tweets
| Action |
Description |
Params |
latest |
Latest crypto tweets (cursor-paginated) |
{"language":"cn","page_size":"20","last_time":"1234567890"} |
search |
Search tweets by keyword |
{"keyword":"bitcoin","language":"cn","page_size":"20"} |
members |
Search Twitter KOL/users |
{"word":"elon","page":"1","size":"20"} |
interaction_stats |
Tweet engagement stats |
{"flash_ids":"123,456,789"} (max 50 IDs) |
scripts/newsflash.mjs — Newsflash (OpenData)
| Action |
Description |
Params |
search |
Search newsflash by keyword |
{"word":"bitcoin","page":"1","size":"20"} |
list |
Newsflash list with filters |
{"pagesize":"20","lan":"cn","date_mode":"range","start_date":"2025-03-01","end_date":"2025-03-04"} |
detail |
Newsflash full content |
{"flash_id":"123456"} |
scripts/features.mjs — Features & Signals
Market Overview
| Action |
Description |
Params |
nav |
Market navigation |
{"lan":"cn"} |
ls_ratio |
Long/short ratio |
None |
liquidation |
Liquidation data |
{"type":"1","coinKey":"bitcoin"} type: 1=by coin, 2=by exchange |
grayscale_trust |
Grayscale trust |
None |
gray_scale |
Grayscale holdings |
{"coins":"btc,eth"} |
stock_market |
Crypto stocks |
None |
Whale Order Tracking
| Action |
Description |
Params |
big_orders |
Large/whale orders |
{"symbol":"btcswapusdt:binance"} |
agg_trades |
Aggregated large trades |
{"symbol":"btcswapusdt:binance"} |
Trading Pairs
| Action |
Description |
Params |
pair_ticker |
Pair ticker |
{"key_list":"btcusdt:okex,btcusdt:huobipro"} |
pair_by_market |
Pairs by exchange |
{"market":"binance"} |
pair_list |
Pair list |
{"market":"binance","currency":"USDT"} |
Signals
| Action |
Description |
Params |
strategy_signal |
Strategy signal |
{"signal_key":"depth_win_one"} |
signal_alert |
Signal alerts |
None |
signal_config |
Alert config |
{"lan":"cn"} |
signal_alert_list |
Alert list |
None |
change_signal |
Anomaly signal |
{"type":"1"} |
delete_signal |
Delete alert |
{"id":"xxx"} |
scripts/hl-market.mjs — Hyperliquid Market
Tickers
| Action |
Description |
Params |
tickers |
All tickers |
None |
ticker |
Single coin ticker |
{"coin":"BTC"} |
Whales
| Action |
Description |
Params |
whale_positions |
Whale positions |
{"coin":"BTC","min_usd":"1000000"} |
whale_events |
Whale events |
{"coin":"BTC"} |
whale_directions |
Long/short direction |
{"coin":"BTC"} |
whale_history_ratio |
Historical long ratio |
{"coin":"BTC"} |
Liquidations
| Action |
Description |
Params |
liq_history |
Liquidation history |
{"coin":"BTC"} |
liq_stats |
Liquidation stats |
None |
liq_stats_by_coin |
Stats by coin |
{"coin":"BTC"} |
liq_top_positions |
Large liquidations |
{"coin":"BTC","interval":"1d"} |
Open Interest
| Action |
Description |
Params |
oi_summary |
OI overview |
None |
oi_top_coins |
OI ranking |
{"limit":"10"} |
oi_history |
OI history |
{"coin":"BTC","interval":"4h"} |
Taker
| Action |
Description |
Params |
taker_delta |
Taker delta |
{"coin":"BTC"} |
taker_klines |
Taker K-lines |
{"coin":"BTC","interval":"4h"} |
scripts/hl-trader.mjs — Hyperliquid Trader
Trader Analytics
| Action |
Description |
Params |
trader_stats |
Trader statistics |
{"address":"0x...","period":"30"} |
best_trades |
Best trades |
{"address":"0x...","period":"30"} |
performance |
Performance by coin |
{"address":"0x...","period":"30"} |
completed_trades |
Completed trades |
{"address":"0x...","coin":"BTC"} |
accounts |
Batch accounts |
{"addresses":"[\"0x...\"]"} |
statistics |
Batch statistics |
{"addresses":"[\"0x...\"]"} |
Fills
| Action |
Description |
Params |
fills |
Address fills |
{"address":"0x..."} |
fills_by_oid |
By order ID |
{"oid":"xxx"} |
fills_by_twapid |
By TWAP ID |
{"twapid":"xxx"} |
top_trades |
Large trades |
{"coin":"BTC","interval":"1d"} |
Orders
| Action |
Description |
Params |
orders_latest |
Latest orders |
{"address":"0x..."} |
order_by_oid |
By order ID |
{"oid":"xxx"} |
filled_orders |
Filled orders |
{"address":"0x..."} |
filled_by_oid |
Filled by ID |
{"oid":"xxx"} |
top_open |
Large open orders |
{"coin":"BTC","min_val":"100000"} |
active_stats |
Active stats |
{"coin":"BTC"} |
twap_states |
TWAP states |
{"address":"0x..."} |
Positions
| Action |
Description |
Params |
current_pos_history |
Current position history |
{"address":"0x...","coin":"BTC"} |
completed_pos_history |
Closed position history |
{"address":"0x...","coin":"BTC"} |
current_pnl |
Current PnL |
{"address":"0x...","coin":"BTC","interval":"1h"} |
completed_pnl |
Closed PnL |
{"address":"0x...","coin":"BTC","interval":"1h"} |
current_executions |
Current executions |
{"address":"0x...","coin":"BTC","interval":"1h"} |
completed_executions |
Closed executions |
{"address":"0x...","coin":"BTC","interval":"1h"} |
Portfolio
| Action |
Description |
Params |
portfolio |
Account curve |
{"address":"0x...","window":"week"} window: day/week/month/allTime |
pnls |
PnL curve |
{"address":"0x...","period":"30"} |
max_drawdown |
Max drawdown |
{"address":"0x...","days":"30"} |
net_flow |
Net flow |
{"address":"0x...","days":"30"} |
Advanced
| Action |
Description |
Params |
info |
Info API |
{"type":"metaAndAssetCtxs"} |
smart_find |
Smart money discovery |
{} |
discover |
Trader discovery |
{} |
scripts/exchange.mjs — Exchange Trading (CCXT)
⚠️ MANDATORY: All exchange operations MUST go through exchange.mjs.
- NEVER write custom CCXT/Python code to interact with exchanges. Always use
node scripts/exchange.mjs <action> '<params>'.
- NEVER import ccxt directly in custom scripts. The exchange.mjs wrapper handles broker attribution, proxy config, and API key management.
exchange.mjs automatically sets AiCoin broker tags for order attribution. Custom CCXT code will NOT have these tags, causing orders to be mis-attributed.
- For automated trading workflows, use
auto-trade.mjs which wraps exchange.mjs with risk management.
Requires npm install ccxt and exchange API keys.
Public (no API key required)
| Action |
Description |
Params |
exchanges |
Supported exchanges |
None |
markets |
Market list |
{"exchange":"binance","market_type":"swap","base":"BTC"} |
ticker |
Real-time ticker |
{"exchange":"binance","symbol":"BTC/USDT"} |
orderbook |
Order book |
{"exchange":"binance","symbol":"BTC/USDT"} |
trades |
Recent trades |
{"exchange":"binance","symbol":"BTC/USDT"} |
ohlcv |
OHLCV candles |
{"exchange":"binance","symbol":"BTC/USDT","timeframe":"1h"} |
Account (API key required)
| Action |
Description |
Params |
balance |
Account balance |
{"exchange":"binance"} |
positions |
Open positions |
{"exchange":"binance","market_type":"swap"} |
open_orders |
Open orders |
{"exchange":"binance","symbol":"BTC/USDT"} |
closed_orders |
Order history |
{"exchange":"binance","symbol":"BTC/USDT","limit":50} |
my_trades |
Trade history |
{"exchange":"binance","symbol":"BTC/USDT","limit":50} |
fetch_order |
Order by ID |
{"exchange":"binance","symbol":"BTC/USDT","order_id":"xxx"} |
Trading (API key required)
🚨 SAFETY RULES — MANDATORY for ALL trading operations:
- NEVER execute a buy/sell/trade without explicit user confirmation.
create_order returns a preview by default. Show the preview to the user, wait for them to say "确认" / "yes" / "go ahead", THEN re-run with "confirmed":"true". Do NOT add confirmed=true on the first call.
- NEVER sell or close the user's existing positions unless the user specifically asks to sell/close.
- NEVER write custom CCXT, Python, or curl code to interact with exchanges. ALL exchange operations MUST go through
exchange.mjs.
- NEVER auto-adjust order parameters (size, leverage, etc.) without asking the user first. If balance is insufficient, tell the user and let them decide.
- ALWAYS verify order details before confirmation: Show coin, direction (buy/sell/long/short), quantity, estimated cost, and ask "确认下单?"
⚠️ CRITICAL — amount units differ between spot and futures:
- Spot:
amount is in base currency (e.g., amount: 0.01 = 0.01 BTC)
- Futures/Swap:
amount is in contracts (e.g., amount: 1 = 1 contract). Get contractSize from markets to convert.
User intent → amount conversion (you MUST get this right):
| User says |
Spot amount |
Swap amount (OKX BTC, contractSize=0.01) |
| "0.01 BTC" / "0.01个BTC" |
0.01 |
0.01 / 0.01 = 1 (1 contract) |
| "1张合约" / "1 contract" |
N/A |
1 (直接用) |
| "0.01张" |
N/A |
0.01 (0.01 contract = 0.0001 BTC) |
| "100U" / "100 USDT" |
100 / price |
(100 / price) / contractSize |
NEVER pass the user's number directly as amount without checking the unit context!
Before placing any order, you MUST:
- Run
markets to get the trading pair's limits.amount.min (minimum order size) and contractSize — do NOT guess or assume minimums
- Run
balance to check available funds
- Convert user's quantity to the correct unit using the table above
- For futures/swap: calculate actual buying power = balance × leverage
- Verify: buying power ≥ order value
- Confirm with user: "You want to buy X contracts (= Y BTC ≈ Z USDT), correct?" before placing the order
- Show clear summary: Coin, Direction, Quantity, Est. Cost, Leverage (if applicable)
Example pre-trade check for BTC/USDT perpetual on OKX:
# Step 1: Check minimum order size AND contract size
node scripts/exchange.mjs markets '{"exchange":"okx","market_type":"swap","base":"BTC"}'
# → look for limits.amount.min (e.g. 1 contract) and contractSize (e.g. 0.01 BTC)
# → This means: 1 contract = 0.01 BTC, min order = 1 contract = 0.01 BTC
# Step 2: Check balance
node scripts/exchange.mjs balance '{"exchange":"okx"}'
# → e.g. 7 USDT free
# Step 3: Calculate — 7 USDT × 10x = 70 USDT ÷ $68000 ≈ 0.001 BTC ÷ 0.01 = 0.1 contracts → below min 1 contract → cannot trade
# With more capital: 100 USDT × 10x = 1000 ÷ $68000 ≈ 0.0147 BTC ÷ 0.01 = 1.47 → round to 1 contract → OK
| Action |
Description |
Params |
create_order |
Place order |
Spot: {"exchange":"okx","symbol":"BTC/USDT","type":"market","side":"buy","amount":0.001} (amount in BTC). Swap: {"exchange":"okx","symbol":"BTC/USDT:USDT","type":"market","side":"buy","amount":1,"market_type":"swap"} (amount in contracts) |
cancel_order |
Cancel order |
{"exchange":"okx","symbol":"BTC/USDT","order_id":"xxx"} |
set_leverage |
Set leverage |
{"exchange":"okx","symbol":"BTC/USDT:USDT","leverage":10,"market_type":"swap"} |
set_margin_mode |
Margin mode |
{"exchange":"okx","symbol":"BTC/USDT:USDT","margin_mode":"cross","market_type":"swap"} |
transfer |
Transfer funds |
{"exchange":"binance","code":"USDT","amount":100,"from_account":"spot","to_account":"future"} |
Notes on transfer:
- Account names MUST use these exact values:
spot, future, delivery, margin, funding. Do NOT use futures, usdm, coinm, or other aliases — they may cause errors.
- OKX unified account (重要): OKX uses a unified trading account — spot and derivatives share the SAME balance. Do NOT ask the user to transfer funds between accounts. If transfer returns error 58123, tell the user: "你的 OKX 是统一账户,现货和合约共用同一个余额,不需要划转。" Do NOT suggest manual transfer in the app.
- Binance: Requires explicit transfer between spot/futures accounts.
scripts/ft.mjs — Freqtrade Bot Control
| Action |
Description |
Params |
ping |
Health check |
None |
start |
Start trading |
None |
stop |
Stop trading |
None |
reload |
Reload config |
None |
config |
View config |
None |
version |
Version info |
None |
sysinfo |
System info |
None |
health |
Health status |
None |
logs |
View logs |
{"limit":50} |
balance |
Account balance |
None |
trades_open |
Open trades |
None |
trades_count |
Trade count |
None |
trade_by_id |
Trade by ID |
{"trade_id":1} |
trades_history |
Trade history |
{"limit":50} |
force_enter |
Manual entry |
{"pair":"BTC/USDT","side":"long"} |
force_exit |
Manual exit |
{"tradeid":"1"} |
cancel_order |
Cancel order |
{"trade_id":1} |
delete_trade |
Delete record |
{"trade_id":1} |
profit |
Profit summary |
None |
profit_per_pair |
Profit per pair |
None |
daily |
Daily report |
{"count":7} |
weekly |
Weekly report |
{"count":4} |
monthly |
Monthly report |
{"count":3} |
stats |
Statistics |
None |
scripts/ft-dev.mjs — Freqtrade Dev Tools
| Action |
Description |
Params |
backtest_start |
Start backtest |
{"strategy":"MyStrategy","timerange":"20240101-20240601","timeframe":"5m"} |
backtest_status |
Backtest status |
None |
backtest_abort |
Abort backtest |
None |
backtest_history |
Backtest history |
None |
backtest_result |
History result |
{"id":"xxx"} |
candles_live |
Live candles |
{"pair":"BTC/USDT","timeframe":"1h"} |
candles_analyzed |
Candles with indicators |
{"pair":"BTC/USDT","timeframe":"1h","strategy":"MyStrategy"} |
candles_available |
Available pairs |
None |
whitelist |
Whitelist |
None |
blacklist |
Blacklist |
None |
blacklist_add |
Add to blacklist |
{"add":["DOGE/USDT"]} |
locks |
Trade locks |
None |
strategy_list |
Strategy list |
None |
strategy_get |
Strategy detail |
{"name":"MyStrategy"} |
scripts/auto-trade.mjs — Automated Trading
Config + execution helper. The AI agent makes all strategy decisions — this script only handles config, risk management, and order execution.
Config is stored at ~/.openclaw/workspace/aicoin-trade-config.json.
| Action |
Description |
Params |
setup |
Save trading config |
{"exchange":"okx","symbol":"BTC/USDT:USDT","leverage":20,"capital_pct":0.5,"stop_loss_pct":0.025,"take_profit_pct":0.05} |
status |
Show config + balance + positions + open orders |
{} |
open |
Open a position (agent decides direction) |
{"direction":"long"} or {"direction":"short"} |
close |
Close current position + cancel orders |
{} |
The open action automatically:
- Checks balance and market minimums
- Calculates position size from config (capital_pct × balance × leverage)
- Sets leverage
- Places market order
- Places stop-loss and take-profit limit orders
scripts/ft-deploy.mjs — Freqtrade Deployment
🚨 CRITICAL: For ALL Freqtrade operations (deploy, backtest, update), ALWAYS use ft-deploy.mjs. NEVER manually run freqtrade commands, NEVER write custom Python scripts, NEVER use Docker.
One-click Freqtrade deployment via git clone + official setup.sh (no Docker). Clones the Freqtrade repo, runs setup.sh -i to install all dependencies (including TA-Lib), generates config from .env exchange keys, starts as background process, auto-writes FREQTRADE_* vars to .env.
| Action |
Description |
Params |
check |
Check prerequisites (Python 3.11+, git, exchange keys) |
None |
deploy |
Deploy Freqtrade (clone, setup.sh, config, start) |
{"dry_run":true,"pairs":["BTC/USDT:USDT","ETH/USDT:USDT"]} |
backtest |
Run backtest (no running process needed) |
{"strategy":"SampleStrategy","timeframe":"1h","timerange":"20250101-20260301"} |
hyperopt |
Parameter optimization |
{"strategy":"FundingRateStrategy","timeframe":"1h","timerange":"20250101-20260301","epochs":100} |
strategy_list |
List available strategies |
None |
update |
Update Freqtrade to latest version |
None |
status |
Process status |
None |
start |
Start stopped process |
None |
stop |
Stop process |
None |
logs |
View process logs |
{"lines":50} |
remove |
Remove process (preserves config) |
None |
Deploy defaults to dry-run mode (simulated trading, no real money). Pass {"dry_run":false} for live trading.
AiCoin-powered strategies (auto-installed on deploy, use AiCoin data in live/dry-run mode, fall back to technical indicators in backtest):
FundingRateStrategy — Exploit extreme funding rates for mean reversion (Basic tier)
WhaleFollowStrategy — Follow whale order flow + contrarian L/S ratio (Normal tier)
LiquidationHunterStrategy — Profit from liquidation cascades (Premium tier)
IMPORTANT: NEVER use Docker for Freqtrade. The deploy script uses git clone + setup.sh -i (official Freqtrade installation method). Do NOT fall back to Docker, do NOT write custom install scripts, do NOT try pip install freqtrade directly. Just run node scripts/ft-deploy.mjs deploy — it handles everything.
IMPORTANT: Do NOT manually edit Freqtrade config files, do NOT manually run freqtrade trade commands, do NOT manually source .venv/bin/activate. Always use ft-deploy.mjs actions. If deploy fails, check logs with ft-deploy.mjs logs and report the error — do NOT attempt manual workarounds.
Automated Trading Guide
When the user asks to set up automated trading, follow this workflow. Do NOT write custom scripts.
How It Works
The AI agent is the strategist. On each cycle:
- Fetch data using existing scripts:
coin.mjs (funding, OI, liquidation), market.mjs (klines, volume), features.mjs (whale orders, long/short ratio), hl-market.mjs (Hyperliquid data)
- Analyze the data — trend, momentum, risk signals. Use your own judgment.
- Decide: open long, open short, close position, or hold
- Execute via
auto-trade.mjs open '{"direction":"long"}' — handles position sizing, leverage, stop-loss/take-profit automatically
Quick Setup
# 1. Configure risk params
node scripts/auto-trade.mjs setup '{"exchange":"okx","symbol":"BTC/USDT:USDT","leverage":10,"capital_pct":0.5}'
# 2. Check status
node scripts/auto-trade.mjs status
OpenClaw Cron (Recommended)
Use OpenClaw's built-in cron, NOT system crontab. This gives the user visibility in the web UI.
openclaw cron add \
--name "BTC auto trade" \
--every 10m \
--session isolated \
--message "You are a crypto trader. Use the aicoin skill to: 1) Fetch BTC market data (price, funding rate, OI, whale orders, liquidation). 2) Analyze the data and decide: open long, open short, close, or hold. 3) If trading, run: node scripts/auto-trade.mjs open '{\"direction\":\"long\"}'. 4) Report your analysis briefly."
When User Asks "帮我自动交易"
- Ask: which exchange? which coin? how much capital? what leverage?
- Run
auto-trade.mjs setup with their params
- Run
auto-trade.mjs status to verify exchange connection
- Set up OpenClaw cron with their preferred interval
- Done — tell them they can check status anytime via
auto-trade.mjs status
Freqtrade Guide
🚨 CRITICAL: When user asks to deploy/setup Freqtrade, ALWAYS use ft-deploy.mjs. NEVER manually configure, NEVER use Docker, NEVER write custom scripts.
When the user asks about backtesting, professional strategies, quantitative trading, or deploying a trading bot, guide them to Freqtrade.
Freqtrade vs auto-trade.mjs:
- auto-trade.mjs = simple AI-driven, good for testing, small capital
- Freqtrade = professional, backtestable, risk-managed, production-grade
Deployment (One Command)
# Check prerequisites first
node scripts/ft-deploy.mjs check
# Deploy (dry-run mode by default — safe)
node scripts/ft-deploy.mjs deploy '{"pairs":["BTC/USDT:USDT","ETH/USDT:USDT"]}'
This automatically:
- Ensures Python 3.11+ is available (auto-installs via brew if needed on macOS)
- Clones Freqtrade repo to
~/.freqtrade/source/
- Runs official
setup.sh -i (installs TA-Lib, creates venv, installs all dependencies)
- Creates config from exchange keys in
.env
- Includes a sample RSI+EMA strategy (pure pandas, no TA-Lib import needed)
- Starts Freqtrade as a background process with API server
- Writes
FREQTRADE_URL, FREQTRADE_USERNAME, FREQTRADE_PASSWORD to .env
- Ready to use via
ft.mjs and ft-dev.mjs
Prerequisites: Python 3.11+ and git. Exchange API keys must be in .env. Everything else is auto-installed — do NOT install manually or use Docker.
User Journey
"帮我部署Freqtrade"
→ node scripts/ft-deploy.mjs deploy
→ "已部署,dry-run模式,用模拟资金运行"
"帮我回测BTC策略"
→ node scripts/ft-deploy.mjs backtest '{"strategy":"SampleStrategy","timeframe":"1h","timerange":"20250101-20260301"}'
→ "回测结果: 胜率62%, 最大回撤-8%, 总收益+45%"
"不错,上实盘"
→ node scripts/ft-deploy.mjs deploy '{"dry_run":false}'
→ "⚠️ 已切换到实盘模式,使用真实资金"
"今天赚了多少?"
→ node scripts/ft.mjs profit
→ node scripts/ft.mjs daily '{"count":7}'
"暂停交易"
→ node scripts/ft.mjs stop
When User Mentions These Keywords → Use Freqtrade
- 回测 / backtest → MUST use
ft-deploy.mjs backtest (does NOT require Freqtrade to be running). NEVER write custom Python backtest scripts, NEVER manually run freqtrade commands.
- 写策略 / write strategy → FIRST read an existing template (e.g.
FundingRateStrategy.py), then write .py based on it. See "Writing Custom Strategies with AiCoin Data" below.
- 量化策略 / strategy →
ft-dev.mjs strategy_list (requires running process)
- 部署机器人 / deploy bot →
ft-deploy.mjs deploy
- 实盘 / live trading →
ft-deploy.mjs deploy '{"dry_run":false}'
- 盈亏 / profit →
ft.mjs profit
- 停止机器人 / stop bot →
ft.mjs stop or ft-deploy.mjs stop
IMPORTANT: For backtesting, use ft-deploy.mjs backtest. Do NOT write custom Python backtest scripts. The Freqtrade backtester is production-grade with proper slippage, fees, and position sizing simulation.
Writing Custom Strategies with AiCoin Data
🚨 BEFORE writing ANY strategy, ALWAYS read an existing template first:
cat ~/.freqtrade/user_data/strategies/FundingRateStrategy.py
Copy the pattern exactly. Do NOT invent your own approach.
Required strategy structure:
class MyStrategy(IStrategy):
INTERFACE_VERSION = 3 # MUST be 3
timeframe = '15m'
can_short = True # MUST set for short trading
minimal_roi = {"0": 0.05}
stoploss = -0.05
def populate_indicators(self, dataframe, metadata):
# ... compute indicators ...
# AiCoin data (live/dry_run only):
if self.dp and self.dp.runmode.value in ('live', 'dry_run'):
self._update_data(metadata)
return dataframe
def populate_entry_trend(self, dataframe, metadata): # NO 's' at end!
# ... entry logic ...
return dataframe
def populate_exit_trend(self, dataframe, metadata): # NO 's' at end!
# ... exit logic ...
return dataframe
⚠️ Common mistakes (NEVER do these):
- ❌
populate_entry_trends → ✅ populate_entry_trend (no 's')
- ❌
populate_exit_trades → ✅ populate_exit_trend
- ❌
for x in self.param.range → ✅ self.param.value (single value, not loop)
- ❌ Missing
INTERFACE_VERSION = 3 or `can_shor
…(truncated)
1---2name: aicoin3description: This skill should be used when the user asks about crypto prices, market data, K-line charts, funding rates, open interest, whale orders, long/short ratios, crypto news, exchange balances, trading, or any crypto-related query. Use when user says: 'BTC price', 'check price', 'show K-line', 'funding rate', 'whale orders', 'place order', 'check balance', 'crypto news', '查行情', '看价格', '大饼多少钱', 'K线', '资金费率', '多空比', '鲸鱼单', '查余额', '下单', '空投', '新闻快讯', '合约', '做多做空'. Covers 200+ exchanges with real-time data. MUST run node scripts to fetch real data — NEVER generate fake prices or hallucinate market data.4---56# AiCoin78Crypto data & trading toolkit powered by [AiCoin Open API](https://www.aicoin.com/opendata).910**Version:** 1.6.0 | **Last Updated:** 2026-03-051112---1314## 🚨 CRITICAL RULES - READ FIRST1516**FREQTRADE OPERATIONS:**17- ✅ ALWAYS use `node scripts/ft-deploy.mjs deploy` for deployment18- ✅ ALWAYS use `node scripts/ft-deploy.mjs backtest` for backtesting19- ❌ NEVER use Docker commands20- ❌ NEVER manually run `freqtrade` commands21- ❌ NEVER write custom Python scripts for Freqtrade2223**TRADING SAFETY:**24- ❌ NEVER place orders without explicit user confirmation25- ❌ NEVER auto-adjust order parameters26- ✅ ALWAYS show order preview and ask "确认下单?" first2728---2930**Data Sources:** AiCoin aggregates data from 200+ exchanges. Price data is real-time, K-lines updated every second, funding rates every 8h.3132**Supported Exchanges for Trading:** Binance, OKX, Bybit, Bitget, Gate.io, HTX, KuCoin, MEXC, Coinbase (requires API keys in `.env`).3334**Quick Start Examples:**35```bash36# Check BTC price37node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'3839# Get 1h K-line40node scripts/market.mjs kline '{"symbol":"btcusdt:okex","period":"3600","size":"10"}'4142# Check balance (requires exchange API keys)43node scripts/exchange.mjs balance '{"exchange":"okx"}'44```4546**Performance Tips:**47- Batch queries: `coin_ticker` supports multiple coins → faster than separate calls48- Reduce API calls: Check balance once, reuse result for multiple calculations49- Use appropriate timeframes: Don't fetch 1000 candles when 10 is enough5051## Quick Reference — Most Common Commands5253> **Run all scripts from the aicoin skill directory.** Use `exec` tool, NOT `process`.54> **API keys are pre-configured.** Do NOT ask the user for keys. Do NOT run `env`/`printenv`.55> **Do NOT use curl, web_fetch, or browser** for crypto data. Always use these scripts.56> **🚨 TRADING SAFETY: NEVER place orders without user confirmation. ALWAYS show order details and ask "确认下单?" FIRST. NEVER auto-adjust order size or parameters.**57> **⚡ PERFORMANCE: Use batch queries when possible.** `coin_ticker` supports multiple coins in one call (e.g., `"coin_list":"bitcoin,ethereum,solana"`).5859| Task | Command |60|------|---------|61| **BTC price** | `node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'` |62| **Multi price** | `node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin,ethereum,solana"}'` |63| **K-line** | `node scripts/market.mjs kline '{"symbol":"btcusdt:okex","period":"3600","size":"100"}'` |64| **Funding rate** | `node scripts/coin.mjs funding_rate '{"symbol":"BTC"}'` (BTC only, 8h default) |65| **Funding rate (other coins)** | `node scripts/exchange.mjs funding_rate '{"exchange":"binance","symbol":"ETH/USDT:USDT"}'` |66| **Open interest** | `node scripts/coin.mjs open_interest '{"symbol":"BTC","interval":"15m"}'` |67| **Long/short ratio** | `node scripts/features.mjs ls_ratio` |68| **Whale orders** | `node scripts/features.mjs big_orders '{"symbol":"btcswapusdt:binance"}'` |69| **News flash** | `node scripts/news.mjs newsflash '{"language":"cn"}'` |70| **HL whale** | `node scripts/hl-market.mjs whale_positions '{"coin":"BTC"}'` |71| **Balance** | `node scripts/exchange.mjs balance '{"exchange":"okx"}'` |72| **Ticker** | `node scripts/exchange.mjs ticker '{"exchange":"binance","symbol":"BTC/USDT"}'` |73| **Orderbook** | `node scripts/exchange.mjs orderbook '{"exchange":"binance","symbol":"BTC/USDT"}'` |74| **Buy/Sell** | `node scripts/exchange.mjs create_order '{"exchange":"okx","symbol":"BTC/USDT","type":"market","side":"buy","amount":0.001}'` → returns **preview only** |75| **Positions** | `node scripts/exchange.mjs positions '{"exchange":"okx","market_type":"swap"}'` |76| **Market list** | `node scripts/exchange.mjs markets '{"exchange":"binance","base":"BTC"}'` |77| **Deploy Freqtrade** | `node scripts/ft-deploy.mjs deploy '{"pairs":["BTC/USDT:USDT"]}'` (dry-run by default) |78| **Backtest** | `node scripts/ft-deploy.mjs backtest '{"strategy":"SampleStrategy","timerange":"20250101-"}'` ⚠️ MUST use this script |7980**Symbol shortcuts:** `BTC`, `ETH`, `SOL`, `DOGE`, `XRP` auto-resolve to AiCoin format (e.g. `btcswapusdt:binance`) in coin.mjs. For exchange.mjs, use CCXT format: `BTC/USDT`, `BTC/USDT:USDT` (swap).8182**Chinese Slang Recognition:** Understand common crypto slang: 大饼=BTC, 姨太=ETH, 狗狗=DOGE, 瑞波=XRP, 索拉纳=SOL, 做多=long, 做空=short, 爆仓=liquidation, 合约=futures/swap.8384**Common Errors & Solutions:**85- `Error: Invalid symbol` → Check symbol format (AiCoin: `btcusdt:okex`, CCXT: `BTC/USDT`)86- `Error: Insufficient balance` → Check balance first with `exchange.mjs balance`, don't auto-adjust order size87- `Error: API key invalid` → Keys are in `.env`, never pass inline. Check if user configured exchange keys.88- `Timeout` → Freqtrade operations may take 5+ minutes, increase timeout or use `ft-deploy.mjs` which handles this89- `Rate limit exceeded` → Wait 1-2 seconds between requests. Use batch queries when possible to reduce API calls.90- `Script not found` → Ensure you're in the aicoin skill directory. Use `exec` tool with full path to script.9192**Response Format Best Practices:**93- Use tables for structured data (prices, K-lines, balances)94- Include units (USDT, BTC, %) and directions (📈/📉) for clarity95- For analysis: show data first, then interpretation96- Keep responses concise - users can ask for details if needed97- Always fetch fresh data - NEVER use cached or memorized prices98- Timestamps: API returns UTC, convert to user's timezone if needed (default: show UTC+8 for Chinese users)99- **Language: Always reply in the same language as the user.** If the user writes in Chinese, ALL text (titles, headings, analysis, labels) MUST be in Chinese. Never mix English headings into a Chinese response.100101**Coin Recommendation Best Practices:**102- When the user asks for coin picks WITHOUT specifying a sector, recommend across MULTIPLE sectors (AI, DeFi, L2, Meme, Infrastructure, etc.) for diversification103- Only focus on a single sector when the user explicitly requests it (e.g., "AI赛道", "DeFi概念")104- Use `hot_coins` with different keys (defi, gamefi, web, newcoin, market) to discover coins across sectors, don't just pick from one category105- Always include reasoning for each pick: why THIS coin, why NOW (momentum, volume spike, whale activity, news catalyst, etc.)106107## Setup Checklist108109**✅ Good News: The skill works out of the box!** Scripts auto-load `.env` files from these locations (earlier paths take priority):1101. Current working directory (`.env`)1112. `~/.openclaw/workspace/.env`1123. `~/.openclaw/.env`113114**Before asking the user for ANY credentials, first check if `.env` already exists:**115116```bash117grep -c "AICOIN_ACCESS_KEY_ID" ~/.openclaw/workspace/.env 2>/dev/null || echo "0"118```119120- If output is `1` or more → **`.env` has AiCoin key configured. Skip setup, just run scripts directly.**121- If output is `0` → **No AiCoin key, but the built-in free key works automatically. Just run scripts.**122123**Only ask setup questions when the user explicitly requests features that need configuration:**124- Exchange trading (Binance, OKX, etc.) → needs exchange API keys + `cd` into the aicoin skill directory and run `npm install` for ccxt125- Freqtrade bot → **MUST use `node scripts/ft-deploy.mjs deploy`** (auto-configures everything, needs Python 3.11+ + exchange keys in .env). **NEVER manually configure Freqtrade, NEVER use Docker, NEVER write custom install scripts.**126- Proxy access → needs `PROXY_URL`127128**Do NOT block the user from running commands. The skill works out of the box with the built-in free key.**129130### How to Configure Environment Variables131132The `.env` file location is `~/.openclaw/workspace/.env`. When adding new variables:1331341. **Check if `.env` already exists:**135 ```bash136 test -f ~/.openclaw/workspace/.env && echo "EXISTS" || echo "NOT_FOUND"137 ```1381392. **If EXISTS → append** (do NOT overwrite):140 ```bash141 echo 'PROXY_URL=socks5://127.0.0.1:7890' >> ~/.openclaw/workspace/.env142 ```1431443. **If NOT_FOUND → create**:145 ```bash146 echo 'PROXY_URL=socks5://127.0.0.1:7890' > ~/.openclaw/workspace/.env147 ```1481494. **If a key already exists and needs updating**, replace the specific line:150 ```bash151 sed -i '' 's|^PROXY_URL=.*|PROXY_URL=socks5://127.0.0.1:7890|' ~/.openclaw/workspace/.env152 ```153154**NEVER overwrite the entire `.env` file** — it may contain other credentials the user has already configured.155156### SECURITY: How to Run Scripts157158**Scripts auto-load `.env` — NEVER pass credentials inline.** Just run:159160```bash161node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'162```163164**NEVER do this** — it exposes secrets in conversation logs:165```bash166# WRONG! DO NOT DO THIS!167AICOIN_ACCESS_KEY_ID=xxx node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'168```169170**Additional security rules:**171- **NEVER run `env`, `printenv`, or `env | grep`** — leaks gateway tokens and API secrets into session logs172- **NEVER use curl to call exchange REST APIs directly** (Binance, OKX, etc.) — use `exchange.mjs` which handles auth, broker tags, and proxy173- **NEVER use web_fetch, web_search, or browser** for crypto data — always use the scripts in this skill174- **NEVER fabricate or guess data from memory** — always fetch real-time data via scripts175176If a script fails due to missing env vars, guide the user to update their `.env` file instead of injecting variables into the command.177178### Environment Variables179180Create a `.env` file in the OpenClaw workspace directory (recommended):181182```bash183# AiCoin API (optional — built-in free key works with IP rate limits)184# Mapping: AiCoin website "API Key" → AICOIN_ACCESS_KEY_ID185# AiCoin website "API Secret" → AICOIN_ACCESS_SECRET186AICOIN_ACCESS_KEY_ID=your-api-key187AICOIN_ACCESS_SECRET=your-api-secret188189# Exchange trading — only if needed (requires: npm install -g ccxt)190BINANCE_API_KEY=xxx191BINANCE_API_SECRET=xxx192# Supported: BINANCE, OKX, BYBIT, BITGET, GATE, HTX, KUCOIN, MEXC, COINBASE193# For OKX also set OKX_PASSWORD=xxx194195# Proxy for exchange access — only if needed196# Supports http, https, socks5, socks4197PROXY_URL=socks5://127.0.0.1:7890198# Or standard env vars: HTTPS_PROXY=http://127.0.0.1:7890199200# Freqtrade — auto-configured by ft-deploy.mjs, no manual setup needed201# FREQTRADE_URL=http://localhost:8080202# FREQTRADE_USERNAME=freqtrader203# FREQTRADE_PASSWORD=auto-generated204```205206**IMPORTANT — AiCoin API Key Configuration:**2072081. The user may provide two values without labels (just two strings copied from the AiCoin website). **Do NOT guess which is which.** Ask the user to confirm: "哪个是 API Key,哪个是 API Secret?" Or look for the labels in the user's message.2092102. **After writing keys to `.env`, ALWAYS verify by running a test call:**211 ```bash212 node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'213 ```2142153. **If the test returns error code `1001` (signature verification failed), the keys are swapped.** Fix by swapping them:216 ```bash217 # Read current values, swap them218 OLD_KEY=$(grep '^AICOIN_ACCESS_KEY_ID=' ~/.openclaw/workspace/.env | cut -d= -f2)219 OLD_SECRET=$(grep '^AICOIN_ACCESS_SECRET=' ~/.openclaw/workspace/.env | cut -d= -f2)220 sed -i '' "s|^AICOIN_ACCESS_KEY_ID=.*|AICOIN_ACCESS_KEY_ID=${OLD_SECRET}|" ~/.openclaw/workspace/.env221 sed -i '' "s|^AICOIN_ACCESS_SECRET=.*|AICOIN_ACCESS_SECRET=${OLD_KEY}|" ~/.openclaw/workspace/.env222 ```223 Then re-run the test to confirm it works.224225Or configure in `~/.openclaw/openclaw.json`:226227```json228{229 "skills": {230 "entries": {231 "aicoin": {232 "enabled": true,233 "apiKey": "your-aicoin-access-key-id",234 "env": {235 "AICOIN_ACCESS_SECRET": "your-secret"236 }237 }238 }239 }240}241```242243### Prerequisites244245- **Node.js** — required for all scripts246- **ccxt** — required only for exchange trading. Run `npm install` in the aicoin skill directory to install.247248## Scripts249250All scripts follow: `node scripts/<name>.mjs <action> [json-params]`251252---253254### scripts/coin.mjs — Coin Data255256| Action | Description | Params |257|--------|-------------|--------|258| `coin_list` | List all coins | None |259| `coin_ticker` | Real-time prices | `{"coin_list":"bitcoin,ethereum"}` |260| `coin_config` | Coin profile | `{"coin_list":"bitcoin"}` |261| `ai_analysis` | AI analysis & prediction | `{"coin_keys":"[\"bitcoin\"]","language":"CN"}` |262| `funding_rate` | Funding rate | `{"symbol":"btcswapusdt:binance","interval":"8h"}` Weighted: `{"symbol":"btcswapusdt","interval":"8h","weighted":"true"}` |263| `liquidation_map` | Liquidation heatmap | `{"dbkey":"btcswapusdt:binance","cycle":"24h"}` |264| `liquidation_history` | Liquidation history | `{"symbol":"btcswapusdt:binance","interval":"1m"}` |265| `estimated_liquidation` | Estimated liquidation | `{"dbkey":"btcswapusdt:binance","cycle":"24h"}` |266| `open_interest` | Open interest | `{"symbol":"BTC","interval":"15m"}` Coin-margined: add `"margin_type":"coin"` |267| `historical_depth` | Historical depth | `{"key":"btcswapusdt:okcoinfutures"}` |268| `super_depth` | Large order depth (>$10k) | `{"key":"btcswapusdt:okcoinfutures"}` |269| `trade_data` | Trade data | `{"dbkey":"btcswapusdt:okcoinfutures"}` |270271---272273### scripts/market.mjs — Market Data274275#### Market Info276| Action | Description | Params |277|--------|-------------|--------|278| `exchanges` | Exchange list | None |279| `ticker` | Exchange tickers | `{"market_list":"okex,binance"}` |280| `hot_coins` | Trending coins | `{"key":"defi"}` key: gamefi/anonymous/market/web/newcoin/stable/defi |281| `futures_interest` | Futures OI ranking | `{"lan":"cn"}` |282283#### K-Line284| Action | Description | Params |285|--------|-------------|--------|286| `kline` | Standard K-line | `{"symbol":"btcusdt:okex","period":"3600","size":"100"}` period in seconds: 900=15m, 3600=1h, 14400=4h, 86400=1d |287| `indicator_kline` | Indicator K-line | `{"symbol":"btcswapusdt:binance","indicator_key":"fundflow","period":"3600"}` |288| `indicator_pairs` | Indicator available pairs | `{"indicator_key":"fundflow"}` |289290#### Index291| Action | Description | Params |292|--------|-------------|--------|293| `index_list` | Index list | None |294| `index_price` | Index price | `{"key":"i:diniw:ice"}` |295| `index_info` | Index details | `{"key":"i:diniw:ice"}` |296297#### Crypto Stocks298| Action | Description | Params |299|--------|-------------|--------|300| `stock_quotes` | Stock quotes | `{"tickers":"i:mstr:nasdaq,i:coin:nasdaq"}` |301| `stock_top_gainer` | Top gainers | `{"us_stock":"true"}` |302| `stock_company` | Company details | `{"symbol":"i:mstr:nasdaq"}` |303304#### Treasury (Corporate Holdings)305| Action | Description | Params |306|--------|-------------|--------|307| `treasury_entities` | Holding entities | `{"coin":"BTC"}` |308| `treasury_history` | Transaction history | `{"coin":"BTC"}` |309| `treasury_accumulated` | Accumulated holdings | `{"coin":"BTC"}` |310| `treasury_latest_entities` | Latest entities | `{"coin":"BTC"}` |311| `treasury_latest_history` | Latest history | `{"coin":"BTC"}` |312| `treasury_summary` | Holdings overview | `{"coin":"BTC"}` |313314#### Order Book Depth315| Action | Description | Params |316|--------|-------------|--------|317| `depth_latest` | Real-time snapshot | `{"dbKey":"btcswapusdt:binance"}` |318| `depth_full` | Full order book | `{"dbKey":"btcswapusdt:binance"}` |319| `depth_grouped` | Grouped depth | `{"dbKey":"btcswapusdt:binance","groupSize":"100"}` |320321---322323### scripts/news.mjs — News & Content324325| Action | Description | Params |326|--------|-------------|--------|327| `news_list` | News list | `{"page":"1","pageSize":"20"}` |328| `news_detail` | News detail | `{"id":"xxx"}` |329| `news_rss` | RSS news | `{"page":"1"}` |330| `newsflash` | AiCoin flash news | `{"language":"cn"}` |331| `flash_list` | Industry flash news | `{"language":"cn"}` |332| `exchange_listing` | Exchange listing announcements | `{"memberIds":"477,1509"}` (477=Binance, 1509=Bitget) |333334---335336### scripts/twitter.mjs — Twitter/X Crypto Tweets337338| Action | Description | Params |339|--------|-------------|--------|340| `latest` | Latest crypto tweets (cursor-paginated) | `{"language":"cn","page_size":"20","last_time":"1234567890"}` |341| `search` | Search tweets by keyword | `{"keyword":"bitcoin","language":"cn","page_size":"20"}` |342| `members` | Search Twitter KOL/users | `{"word":"elon","page":"1","size":"20"}` |343| `interaction_stats` | Tweet engagement stats | `{"flash_ids":"123,456,789"}` (max 50 IDs) |344345---346347### scripts/newsflash.mjs — Newsflash (OpenData)348349| Action | Description | Params |350|--------|-------------|--------|351| `search` | Search newsflash by keyword | `{"word":"bitcoin","page":"1","size":"20"}` |352| `list` | Newsflash list with filters | `{"pagesize":"20","lan":"cn","date_mode":"range","start_date":"2025-03-01","end_date":"2025-03-04"}` |353| `detail` | Newsflash full content | `{"flash_id":"123456"}` |354355---356357### scripts/features.mjs — Features & Signals358359#### Market Overview360| Action | Description | Params |361|--------|-------------|--------|362| `nav` | Market navigation | `{"lan":"cn"}` |363| `ls_ratio` | Long/short ratio | None |364| `liquidation` | Liquidation data | `{"type":"1","coinKey":"bitcoin"}` type: 1=by coin, 2=by exchange |365| `grayscale_trust` | Grayscale trust | None |366| `gray_scale` | Grayscale holdings | `{"coins":"btc,eth"}` |367| `stock_market` | Crypto stocks | None |368369#### Whale Order Tracking370| Action | Description | Params |371|--------|-------------|--------|372| `big_orders` | Large/whale orders | `{"symbol":"btcswapusdt:binance"}` |373| `agg_trades` | Aggregated large trades | `{"symbol":"btcswapusdt:binance"}` |374375#### Trading Pairs376| Action | Description | Params |377|--------|-------------|--------|378| `pair_ticker` | Pair ticker | `{"key_list":"btcusdt:okex,btcusdt:huobipro"}` |379| `pair_by_market` | Pairs by exchange | `{"market":"binance"}` |380| `pair_list` | Pair list | `{"market":"binance","currency":"USDT"}` |381382#### Signals383| Action | Description | Params |384|--------|-------------|--------|385| `strategy_signal` | Strategy signal | `{"signal_key":"depth_win_one"}` |386| `signal_alert` | Signal alerts | None |387| `signal_config` | Alert config | `{"lan":"cn"}` |388| `signal_alert_list` | Alert list | None |389| `change_signal` | Anomaly signal | `{"type":"1"}` |390| `delete_signal` | Delete alert | `{"id":"xxx"}` |391392---393394### scripts/hl-market.mjs — Hyperliquid Market395396#### Tickers397| Action | Description | Params |398|--------|-------------|--------|399| `tickers` | All tickers | None |400| `ticker` | Single coin ticker | `{"coin":"BTC"}` |401402#### Whales403| Action | Description | Params |404|--------|-------------|--------|405| `whale_positions` | Whale positions | `{"coin":"BTC","min_usd":"1000000"}` |406| `whale_events` | Whale events | `{"coin":"BTC"}` |407| `whale_directions` | Long/short direction | `{"coin":"BTC"}` |408| `whale_history_ratio` | Historical long ratio | `{"coin":"BTC"}` |409410#### Liquidations411| Action | Description | Params |412|--------|-------------|--------|413| `liq_history` | Liquidation history | `{"coin":"BTC"}` |414| `liq_stats` | Liquidation stats | None |415| `liq_stats_by_coin` | Stats by coin | `{"coin":"BTC"}` |416| `liq_top_positions` | Large liquidations | `{"coin":"BTC","interval":"1d"}` |417418#### Open Interest419| Action | Description | Params |420|--------|-------------|--------|421| `oi_summary` | OI overview | None |422| `oi_top_coins` | OI ranking | `{"limit":"10"}` |423| `oi_history` | OI history | `{"coin":"BTC","interval":"4h"}` |424425#### Taker426| Action | Description | Params |427|--------|-------------|--------|428| `taker_delta` | Taker delta | `{"coin":"BTC"}` |429| `taker_klines` | Taker K-lines | `{"coin":"BTC","interval":"4h"}` |430431---432433### scripts/hl-trader.mjs — Hyperliquid Trader434435#### Trader Analytics436| Action | Description | Params |437|--------|-------------|--------|438| `trader_stats` | Trader statistics | `{"address":"0x...","period":"30"}` |439| `best_trades` | Best trades | `{"address":"0x...","period":"30"}` |440| `performance` | Performance by coin | `{"address":"0x...","period":"30"}` |441| `completed_trades` | Completed trades | `{"address":"0x...","coin":"BTC"}` |442| `accounts` | Batch accounts | `{"addresses":"[\"0x...\"]"}` |443| `statistics` | Batch statistics | `{"addresses":"[\"0x...\"]"}` |444445#### Fills446| Action | Description | Params |447|--------|-------------|--------|448| `fills` | Address fills | `{"address":"0x..."}` |449| `fills_by_oid` | By order ID | `{"oid":"xxx"}` |450| `fills_by_twapid` | By TWAP ID | `{"twapid":"xxx"}` |451| `top_trades` | Large trades | `{"coin":"BTC","interval":"1d"}` |452453#### Orders454| Action | Description | Params |455|--------|-------------|--------|456| `orders_latest` | Latest orders | `{"address":"0x..."}` |457| `order_by_oid` | By order ID | `{"oid":"xxx"}` |458| `filled_orders` | Filled orders | `{"address":"0x..."}` |459| `filled_by_oid` | Filled by ID | `{"oid":"xxx"}` |460| `top_open` | Large open orders | `{"coin":"BTC","min_val":"100000"}` |461| `active_stats` | Active stats | `{"coin":"BTC"}` |462| `twap_states` | TWAP states | `{"address":"0x..."}` |463464#### Positions465| Action | Description | Params |466|--------|-------------|--------|467| `current_pos_history` | Current position history | `{"address":"0x...","coin":"BTC"}` |468| `completed_pos_history` | Closed position history | `{"address":"0x...","coin":"BTC"}` |469| `current_pnl` | Current PnL | `{"address":"0x...","coin":"BTC","interval":"1h"}` |470| `completed_pnl` | Closed PnL | `{"address":"0x...","coin":"BTC","interval":"1h"}` |471| `current_executions` | Current executions | `{"address":"0x...","coin":"BTC","interval":"1h"}` |472| `completed_executions` | Closed executions | `{"address":"0x...","coin":"BTC","interval":"1h"}` |473474#### Portfolio475| Action | Description | Params |476|--------|-------------|--------|477| `portfolio` | Account curve | `{"address":"0x...","window":"week"}` window: day/week/month/allTime |478| `pnls` | PnL curve | `{"address":"0x...","period":"30"}` |479| `max_drawdown` | Max drawdown | `{"address":"0x...","days":"30"}` |480| `net_flow` | Net flow | `{"address":"0x...","days":"30"}` |481482#### Advanced483| Action | Description | Params |484|--------|-------------|--------|485| `info` | Info API | `{"type":"metaAndAssetCtxs"}` |486| `smart_find` | Smart money discovery | `{}` |487| `discover` | Trader discovery | `{}` |488489---490491### scripts/exchange.mjs — Exchange Trading (CCXT)492493**⚠️ MANDATORY: All exchange operations MUST go through `exchange.mjs`.**494- **NEVER** write custom CCXT/Python code to interact with exchanges. Always use `node scripts/exchange.mjs <action> '<params>'`.495- **NEVER** import ccxt directly in custom scripts. The exchange.mjs wrapper handles broker attribution, proxy config, and API key management.496- `exchange.mjs` automatically sets AiCoin broker tags for order attribution. Custom CCXT code will NOT have these tags, causing orders to be mis-attributed.497- For automated trading workflows, use `auto-trade.mjs` which wraps `exchange.mjs` with risk management.498499Requires `npm install ccxt` and exchange API keys.500501#### Public (no API key required)502| Action | Description | Params |503|--------|-------------|--------|504| `exchanges` | Supported exchanges | None |505| `markets` | Market list | `{"exchange":"binance","market_type":"swap","base":"BTC"}` |506| `ticker` | Real-time ticker | `{"exchange":"binance","symbol":"BTC/USDT"}` |507| `orderbook` | Order book | `{"exchange":"binance","symbol":"BTC/USDT"}` |508| `trades` | Recent trades | `{"exchange":"binance","symbol":"BTC/USDT"}` |509| `ohlcv` | OHLCV candles | `{"exchange":"binance","symbol":"BTC/USDT","timeframe":"1h"}` |510511#### Account (API key required)512| Action | Description | Params |513|--------|-------------|--------|514| `balance` | Account balance | `{"exchange":"binance"}` |515| `positions` | Open positions | `{"exchange":"binance","market_type":"swap"}` |516| `open_orders` | Open orders | `{"exchange":"binance","symbol":"BTC/USDT"}` |517| `closed_orders` | Order history | `{"exchange":"binance","symbol":"BTC/USDT","limit":50}` |518| `my_trades` | Trade history | `{"exchange":"binance","symbol":"BTC/USDT","limit":50}` |519| `fetch_order` | Order by ID | `{"exchange":"binance","symbol":"BTC/USDT","order_id":"xxx"}` |520521#### Trading (API key required)522523**🚨 SAFETY RULES — MANDATORY for ALL trading operations:**5241. **NEVER execute a buy/sell/trade without explicit user confirmation.** `create_order` returns a preview by default. Show the preview to the user, wait for them to say "确认" / "yes" / "go ahead", THEN re-run with `"confirmed":"true"`. **Do NOT add confirmed=true on the first call.**5252. **NEVER sell or close the user's existing positions** unless the user specifically asks to sell/close.5263. **NEVER write custom CCXT, Python, or curl code** to interact with exchanges. ALL exchange operations MUST go through `exchange.mjs`.5274. **NEVER auto-adjust order parameters** (size, leverage, etc.) without asking the user first. If balance is insufficient, tell the user and let them decide.5285. **ALWAYS verify order details before confirmation**: Show coin, direction (buy/sell/long/short), quantity, estimated cost, and ask "确认下单?"529530**⚠️ CRITICAL — `amount` units differ between spot and futures:**531- **Spot**: `amount` is in **base currency** (e.g., `amount: 0.01` = 0.01 BTC)532- **Futures/Swap**: `amount` is in **contracts** (e.g., `amount: 1` = 1 contract). Get `contractSize` from `markets` to convert.533534**User intent → `amount` conversion (you MUST get this right):**535| User says | Spot `amount` | Swap `amount` (OKX BTC, contractSize=0.01) |536|-----------|--------------|---------------------------------------------|537| "0.01 BTC" / "0.01个BTC" | `0.01` | `0.01 / 0.01 = 1` (1 contract) |538| "1张合约" / "1 contract" | N/A | `1` (直接用) |539| "0.01张" | N/A | `0.01` (0.01 contract = 0.0001 BTC) |540| "100U" / "100 USDT" | `100 / price` | `(100 / price) / contractSize` |541542**NEVER pass the user's number directly as `amount` without checking the unit context!**543544**Before placing any order, you MUST:**5451. Run `markets` to get the trading pair's `limits.amount.min` (minimum order size) and `contractSize` — do NOT guess or assume minimums5462. Run `balance` to check available funds5473. Convert user's quantity to the correct unit using the table above5484. For futures/swap: calculate actual buying power = balance × leverage5495. Verify: buying power ≥ order value5506. **Confirm with user**: "You want to buy X contracts (= Y BTC ≈ Z USDT), correct?" before placing the order5517. Show clear summary: Coin, Direction, Quantity, Est. Cost, Leverage (if applicable)552553Example pre-trade check for BTC/USDT perpetual on OKX:554```bash555# Step 1: Check minimum order size AND contract size556node scripts/exchange.mjs markets '{"exchange":"okx","market_type":"swap","base":"BTC"}'557# → look for limits.amount.min (e.g. 1 contract) and contractSize (e.g. 0.01 BTC)558# → This means: 1 contract = 0.01 BTC, min order = 1 contract = 0.01 BTC559560# Step 2: Check balance561node scripts/exchange.mjs balance '{"exchange":"okx"}'562# → e.g. 7 USDT free563564# Step 3: Calculate — 7 USDT × 10x = 70 USDT ÷ $68000 ≈ 0.001 BTC ÷ 0.01 = 0.1 contracts → below min 1 contract → cannot trade565# With more capital: 100 USDT × 10x = 1000 ÷ $68000 ≈ 0.0147 BTC ÷ 0.01 = 1.47 → round to 1 contract → OK566```567568| Action | Description | Params |569|--------|-------------|--------|570| `create_order` | Place order | Spot: `{"exchange":"okx","symbol":"BTC/USDT","type":"market","side":"buy","amount":0.001}` (amount in BTC). Swap: `{"exchange":"okx","symbol":"BTC/USDT:USDT","type":"market","side":"buy","amount":1,"market_type":"swap"}` (amount in contracts) |571| `cancel_order` | Cancel order | `{"exchange":"okx","symbol":"BTC/USDT","order_id":"xxx"}` |572| `set_leverage` | Set leverage | `{"exchange":"okx","symbol":"BTC/USDT:USDT","leverage":10,"market_type":"swap"}` |573| `set_margin_mode` | Margin mode | `{"exchange":"okx","symbol":"BTC/USDT:USDT","margin_mode":"cross","market_type":"swap"}` |574| `transfer` | Transfer funds | `{"exchange":"binance","code":"USDT","amount":100,"from_account":"spot","to_account":"future"}` |575576**Notes on `transfer`:**577- **Account names MUST use these exact values**: `spot`, `future`, `delivery`, `margin`, `funding`. Do NOT use `futures`, `usdm`, `coinm`, or other aliases — they may cause errors.578- **OKX unified account (重要)**: OKX uses a **unified trading account** — spot and derivatives share the SAME balance. **Do NOT ask the user to transfer funds between accounts.** If transfer returns error 58123, tell the user: "你的 OKX 是统一账户,现货和合约共用同一个余额,不需要划转。" Do NOT suggest manual transfer in the app.579- **Binance**: Requires explicit transfer between spot/futures accounts.580581---582583### scripts/ft.mjs — Freqtrade Bot Control584585| Action | Description | Params |586|--------|-------------|--------|587| `ping` | Health check | None |588| `start` | Start trading | None |589| `stop` | Stop trading | None |590| `reload` | Reload config | None |591| `config` | View config | None |592| `version` | Version info | None |593| `sysinfo` | System info | None |594| `health` | Health status | None |595| `logs` | View logs | `{"limit":50}` |596| `balance` | Account balance | None |597| `trades_open` | Open trades | None |598| `trades_count` | Trade count | None |599| `trade_by_id` | Trade by ID | `{"trade_id":1}` |600| `trades_history` | Trade history | `{"limit":50}` |601| `force_enter` | Manual entry | `{"pair":"BTC/USDT","side":"long"}` |602| `force_exit` | Manual exit | `{"tradeid":"1"}` |603| `cancel_order` | Cancel order | `{"trade_id":1}` |604| `delete_trade` | Delete record | `{"trade_id":1}` |605| `profit` | Profit summary | None |606| `profit_per_pair` | Profit per pair | None |607| `daily` | Daily report | `{"count":7}` |608| `weekly` | Weekly report | `{"count":4}` |609| `monthly` | Monthly report | `{"count":3}` |610| `stats` | Statistics | None |611612---613614### scripts/ft-dev.mjs — Freqtrade Dev Tools615616| Action | Description | Params |617|--------|-------------|--------|618| `backtest_start` | Start backtest | `{"strategy":"MyStrategy","timerange":"20240101-20240601","timeframe":"5m"}` |619| `backtest_status` | Backtest status | None |620| `backtest_abort` | Abort backtest | None |621| `backtest_history` | Backtest history | None |622| `backtest_result` | History result | `{"id":"xxx"}` |623| `candles_live` | Live candles | `{"pair":"BTC/USDT","timeframe":"1h"}` |624| `candles_analyzed` | Candles with indicators | `{"pair":"BTC/USDT","timeframe":"1h","strategy":"MyStrategy"}` |625| `candles_available` | Available pairs | None |626| `whitelist` | Whitelist | None |627| `blacklist` | Blacklist | None |628| `blacklist_add` | Add to blacklist | `{"add":["DOGE/USDT"]}` |629| `locks` | Trade locks | None |630| `strategy_list` | Strategy list | None |631| `strategy_get` | Strategy detail | `{"name":"MyStrategy"}` |632633---634635### scripts/auto-trade.mjs — Automated Trading636637Config + execution helper. **The AI agent makes all strategy decisions** — this script only handles config, risk management, and order execution.638639Config is stored at `~/.openclaw/workspace/aicoin-trade-config.json`.640641| Action | Description | Params |642|--------|-------------|--------|643| `setup` | Save trading config | `{"exchange":"okx","symbol":"BTC/USDT:USDT","leverage":20,"capital_pct":0.5,"stop_loss_pct":0.025,"take_profit_pct":0.05}` |644| `status` | Show config + balance + positions + open orders | `{}` |645| `open` | Open a position (agent decides direction) | `{"direction":"long"}` or `{"direction":"short"}` |646| `close` | Close current position + cancel orders | `{}` |647648The `open` action automatically:6491. Checks balance and market minimums6502. Calculates position size from config (capital_pct × balance × leverage)6513. Sets leverage6524. Places market order6535. Places stop-loss and take-profit limit orders654655---656657### scripts/ft-deploy.mjs — Freqtrade Deployment658659**🚨 CRITICAL: For ALL Freqtrade operations (deploy, backtest, update), ALWAYS use ft-deploy.mjs. NEVER manually run freqtrade commands, NEVER write custom Python scripts, NEVER use Docker.**660661**One-click Freqtrade deployment via `git clone` + official `setup.sh` (no Docker).** Clones the Freqtrade repo, runs `setup.sh -i` to install all dependencies (including TA-Lib), generates config from `.env` exchange keys, starts as background process, auto-writes `FREQTRADE_*` vars to `.env`.662663| Action | Description | Params |664|--------|-------------|--------|665| `check` | Check prerequisites (Python 3.11+, git, exchange keys) | None |666| `deploy` | Deploy Freqtrade (clone, setup.sh, config, start) | `{"dry_run":true,"pairs":["BTC/USDT:USDT","ETH/USDT:USDT"]}` |667| `backtest` | Run backtest (no running process needed) | `{"strategy":"SampleStrategy","timeframe":"1h","timerange":"20250101-20260301"}` |668| `hyperopt` | Parameter optimization | `{"strategy":"FundingRateStrategy","timeframe":"1h","timerange":"20250101-20260301","epochs":100}` |669| `strategy_list` | List available strategies | None |670| `update` | Update Freqtrade to latest version | None |671| `status` | Process status | None |672| `start` | Start stopped process | None |673| `stop` | Stop process | None |674| `logs` | View process logs | `{"lines":50}` |675| `remove` | Remove process (preserves config) | None |676677**Deploy defaults to dry-run mode** (simulated trading, no real money). Pass `{"dry_run":false}` for live trading.678679**AiCoin-powered strategies** (auto-installed on deploy, use AiCoin data in live/dry-run mode, fall back to technical indicators in backtest):680- `FundingRateStrategy` — Exploit extreme funding rates for mean reversion (Basic tier)681- `WhaleFollowStrategy` — Follow whale order flow + contrarian L/S ratio (Normal tier)682- `LiquidationHunterStrategy` — Profit from liquidation cascades (Premium tier)683684**IMPORTANT: NEVER use Docker for Freqtrade.** The deploy script uses `git clone` + `setup.sh -i` (official Freqtrade installation method). Do NOT fall back to Docker, do NOT write custom install scripts, do NOT try `pip install freqtrade` directly. Just run `node scripts/ft-deploy.mjs deploy` — it handles everything.685686**IMPORTANT: Do NOT manually edit Freqtrade config files, do NOT manually run `freqtrade trade` commands, do NOT manually `source .venv/bin/activate`.** Always use `ft-deploy.mjs` actions. If deploy fails, check logs with `ft-deploy.mjs logs` and report the error — do NOT attempt manual workarounds.687688---689690## Automated Trading Guide691692When the user asks to set up automated trading, follow this workflow. **Do NOT write custom scripts.**693694### How It Works695696The AI agent is the strategist. On each cycle:6971. **Fetch data** using existing scripts: `coin.mjs` (funding, OI, liquidation), `market.mjs` (klines, volume), `features.mjs` (whale orders, long/short ratio), `hl-market.mjs` (Hyperliquid data)6982. **Analyze** the data — trend, momentum, risk signals. Use your own judgment.6993. **Decide**: open long, open short, close position, or hold7004. **Execute** via `auto-trade.mjs open '{"direction":"long"}'` — handles position sizing, leverage, stop-loss/take-profit automatically701702### Quick Setup703704```bash705# 1. Configure risk params706node scripts/auto-trade.mjs setup '{"exchange":"okx","symbol":"BTC/USDT:USDT","leverage":10,"capital_pct":0.5}'707708# 2. Check status709node scripts/auto-trade.mjs status710```711712### OpenClaw Cron (Recommended)713714**Use OpenClaw's built-in cron, NOT system crontab.** This gives the user visibility in the web UI.715716```bash717openclaw cron add \718 --name "BTC auto trade" \719 --every 10m \720 --session isolated \721 --message "You are a crypto trader. Use the aicoin skill to: 1) Fetch BTC market data (price, funding rate, OI, whale orders, liquidation). 2) Analyze the data and decide: open long, open short, close, or hold. 3) If trading, run: node scripts/auto-trade.mjs open '{\"direction\":\"long\"}'. 4) Report your analysis briefly."722```723724### When User Asks "帮我自动交易"7257261. Ask: which exchange? which coin? how much capital? what leverage?7272. Run `auto-trade.mjs setup` with their params7283. Run `auto-trade.mjs status` to verify exchange connection7294. Set up OpenClaw cron with their preferred interval7305. Done — tell them they can check status anytime via `auto-trade.mjs status`731732---733734## Freqtrade Guide735736**🚨 CRITICAL: When user asks to deploy/setup Freqtrade, ALWAYS use `ft-deploy.mjs`. NEVER manually configure, NEVER use Docker, NEVER write custom scripts.**737738When the user asks about backtesting, professional strategies, quantitative trading, or deploying a trading bot, guide them to Freqtrade.739740**Freqtrade vs auto-trade.mjs:**741- auto-trade.mjs = simple AI-driven, good for testing, small capital742- Freqtrade = professional, backtestable, risk-managed, production-grade743744### Deployment (One Command)745746```bash747# Check prerequisites first748node scripts/ft-deploy.mjs check749750# Deploy (dry-run mode by default — safe)751node scripts/ft-deploy.mjs deploy '{"pairs":["BTC/USDT:USDT","ETH/USDT:USDT"]}'752```753754This automatically:7551. Ensures Python 3.11+ is available (auto-installs via brew if needed on macOS)7562. Clones Freqtrade repo to `~/.freqtrade/source/`7573. Runs official `setup.sh -i` (installs TA-Lib, creates venv, installs all dependencies)7584. Creates config from exchange keys in `.env`7595. Includes a sample RSI+EMA strategy (pure pandas, no TA-Lib import needed)7606. Starts Freqtrade as a background process with API server7617. Writes `FREQTRADE_URL`, `FREQTRADE_USERNAME`, `FREQTRADE_PASSWORD` to `.env`7628. Ready to use via `ft.mjs` and `ft-dev.mjs`763764**Prerequisites:** Python 3.11+ and git. Exchange API keys must be in `.env`. Everything else is auto-installed — do NOT install manually or use Docker.765766### User Journey767768```769"帮我部署Freqtrade"770 → node scripts/ft-deploy.mjs deploy771 → "已部署,dry-run模式,用模拟资金运行"772773"帮我回测BTC策略"774 → node scripts/ft-deploy.mjs backtest '{"strategy":"SampleStrategy","timeframe":"1h","timerange":"20250101-20260301"}'775 → "回测结果: 胜率62%, 最大回撤-8%, 总收益+45%"776777"不错,上实盘"778 → node scripts/ft-deploy.mjs deploy '{"dry_run":false}'779 → "⚠️ 已切换到实盘模式,使用真实资金"780781"今天赚了多少?"782 → node scripts/ft.mjs profit783 → node scripts/ft.mjs daily '{"count":7}'784785"暂停交易"786 → node scripts/ft.mjs stop787```788789### When User Mentions These Keywords → Use Freqtrade790791- 回测 / backtest → **MUST use `ft-deploy.mjs backtest`** (does NOT require Freqtrade to be running). NEVER write custom Python backtest scripts, NEVER manually run freqtrade commands.792- 写策略 / write strategy → **FIRST read an existing template** (e.g. `FundingRateStrategy.py`), then write `.py` based on it. See "Writing Custom Strategies with AiCoin Data" below.793- 量化策略 / strategy → `ft-dev.mjs strategy_list` (requires running process)794- 部署机器人 / deploy bot → `ft-deploy.mjs deploy`795- 实盘 / live trading → `ft-deploy.mjs deploy '{"dry_run":false}'`796- 盈亏 / profit → `ft.mjs profit`797- 停止机器人 / stop bot → `ft.mjs stop` or `ft-deploy.mjs stop`798799**IMPORTANT: For backtesting, use `ft-deploy.mjs backtest`. Do NOT write custom Python backtest scripts. The Freqtrade backtester is production-grade with proper slippage, fees, and position sizing simulation.**800801### Writing Custom Strategies with AiCoin Data802803**🚨 BEFORE writing ANY strategy, ALWAYS read an existing template first:**804```bash805cat ~/.freqtrade/user_data/strategies/FundingRateStrategy.py806```807Copy the pattern exactly. Do NOT invent your own approach.808809**Required strategy structure:**810```python811class MyStrategy(IStrategy):812 INTERFACE_VERSION = 3 # MUST be 3813 timeframe = '15m'814 can_short = True # MUST set for short trading815 minimal_roi = {"0": 0.05}816 stoploss = -0.05817818 def populate_indicators(self, dataframe, metadata):819 # ... compute indicators ...820 # AiCoin data (live/dry_run only):821 if self.dp and self.dp.runmode.value in ('live', 'dry_run'):822 self._update_data(metadata)823 return dataframe824825 def populate_entry_trend(self, dataframe, metadata): # NO 's' at end!826 # ... entry logic ...827 return dataframe828829 def populate_exit_trend(self, dataframe, metadata): # NO 's' at end!830 # ... exit logic ...831 return dataframe832```833834**⚠️ Common mistakes (NEVER do these):**835- ❌ `populate_entry_trends` → ✅ `populate_entry_trend` (no 's')836- ❌ `populate_exit_trades` → ✅ `populate_exit_trend`837- ❌ `for x in self.param.range` → ✅ `self.param.value` (single value, not loop)838- ❌ Missing `INTERFACE_VERSION = 3` or `can_shor839840…(truncated)