AiCoin
Crypto data & trading toolkit powered by AiCoin Open API.
Setup Checklist
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 <skill-dir>/aicoin && npm install for ccxt
- Freqtrade bot → run
ft-deploy.mjs deploy (auto-configures everything, needs Python 3 + exchange keys in .env)
- 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"}'
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:
cd <skill-dir>/aicoin && npm 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"} |
Trading (API key required)
🚨 SAFETY RULES — MANDATORY for ALL trading operations:
- NEVER execute a buy/sell/trade without explicit user confirmation. Always show the order details and ask "确认下单?" BEFORE calling
create_order.
- 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.
⚠️ 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
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:
- 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
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"} |
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.
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
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 →
ft-deploy.mjs backtest (does NOT require Freqtrade to be running)
- 写策略 / write strategy → Write a
.py file to ~/.freqtrade/user_data/strategies/, then ft-deploy.mjs backtest
- 量化策略 / 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.
1---
2name: aicoin
3description: >
4 Use this skill when the user asks to buy, sell, or trade crypto on exchanges like
5 Binance, OKX, Bybit, Bitget, Gate, HTX, KuCoin, MEXC, or Coinbase — spot or futures,
6 place orders, check balance, set leverage, view positions, or cancel orders.
7 Also use when the user asks for crypto market data: real-time prices, K-lines, funding
8 rates, open interest, liquidation data, whale tracking, AI analysis, order flow, news,
9 Twitter/X crypto tweets, Hyperliquid on-chain data, or Freqtrade bot control.
10 Also use when the user asks to set up automated trading, deploy Freqtrade, backtest
11 strategies, or control a trading bot.
12 Scripts auto-load .env — just run them directly. If a script fails due to missing
13 credentials, guide the user through the Setup Checklist in SKILL.md.
14metadata:
15 openclaw:
16 primaryEnv: "AICOIN_ACCESS_KEY_ID"
17 requires:
18 bins:
19 - "node"
20 homepage: "https://www.aicoin.com/opendata"
21 source: https://skillmd.com/skills/modbender/aicoin
22 upstream: "https://github.com/aicoincom/aicoin-skills"
23 license: "MIT"
24---
25
26# AiCoin
27
28Crypto data & trading toolkit powered by [AiCoin Open API](https://www.aicoin.com/opendata).
29
30## Setup Checklist
31
32**Scripts auto-load `.env` files** from these locations (earlier paths take priority):
331. Current working directory (`.env`)
342. `~/.openclaw/workspace/.env`
353. `~/.openclaw/.env`
36
37**Before asking the user for ANY credentials, first check if `.env` already exists:**
38
39```bash
40grep -c "AICOIN_ACCESS_KEY_ID" ~/.openclaw/workspace/.env 2>/dev/null || echo "0"
41```
42
43- If output is `1` or more → **`.env` has AiCoin key configured. Skip setup, just run scripts directly.**
44- If output is `0` → **No AiCoin key, but the built-in free key works automatically. Just run scripts.**
45
46**Only ask setup questions when the user explicitly requests features that need configuration:**
47- Exchange trading (Binance, OKX, etc.) → needs exchange API keys + `cd <skill-dir>/aicoin && npm install` for ccxt
48- Freqtrade bot → run `ft-deploy.mjs deploy` (auto-configures everything, needs Python 3 + exchange keys in .env)
49- Proxy access → needs `PROXY_URL`
50
51**Do NOT block the user from running commands. The skill works out of the box with the built-in free key.**
52
53### How to Configure Environment Variables
54
55The `.env` file location is `~/.openclaw/workspace/.env`. When adding new variables:
56
571. **Check if `.env` already exists:**
58 ```bash
59 test -f ~/.openclaw/workspace/.env && echo "EXISTS" || echo "NOT_FOUND"
60 ```
61
622. **If EXISTS → append** (do NOT overwrite):
63 ```bash
64 echo 'PROXY_URL=socks5://127.0.0.1:7890' >> ~/.openclaw/workspace/.env
65 ```
66
673. **If NOT_FOUND → create**:
68 ```bash
69 echo 'PROXY_URL=socks5://127.0.0.1:7890' > ~/.openclaw/workspace/.env
70 ```
71
724. **If a key already exists and needs updating**, replace the specific line:
73 ```bash
74 sed -i '' 's|^PROXY_URL=.*|PROXY_URL=socks5://127.0.0.1:7890|' ~/.openclaw/workspace/.env
75 ```
76
77**NEVER overwrite the entire `.env` file** — it may contain other credentials the user has already configured.
78
79### SECURITY: How to Run Scripts
80
81**Scripts auto-load `.env` — NEVER pass credentials inline.** Just run:
82
83```bash
84node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'
85```
86
87**NEVER do this** — it exposes secrets in conversation logs:
88```bash
89# WRONG! DO NOT DO THIS!
90AICOIN_ACCESS_KEY_ID=xxx node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'
91```
92
93If a script fails due to missing env vars, guide the user to update their `.env` file instead of injecting variables into the command.
94
95### Environment Variables
96
97Create a `.env` file in the OpenClaw workspace directory (recommended):
98
99```bash
100# AiCoin API (optional — built-in free key works with IP rate limits)
101# Mapping: AiCoin website "API Key" → AICOIN_ACCESS_KEY_ID
102# AiCoin website "API Secret" → AICOIN_ACCESS_SECRET
103AICOIN_ACCESS_KEY_ID=your-api-key
104AICOIN_ACCESS_SECRET=your-api-secret
105
106# Exchange trading — only if needed (requires: npm install -g ccxt)
107BINANCE_API_KEY=xxx
108BINANCE_API_SECRET=xxx
109# Supported: BINANCE, OKX, BYBIT, BITGET, GATE, HTX, KUCOIN, MEXC, COINBASE
110# For OKX also set OKX_PASSWORD=xxx
111
112# Proxy for exchange access — only if needed
113# Supports http, https, socks5, socks4
114PROXY_URL=socks5://127.0.0.1:7890
115# Or standard env vars: HTTPS_PROXY=http://127.0.0.1:7890
116
117# Freqtrade — auto-configured by ft-deploy.mjs, no manual setup needed
118# FREQTRADE_URL=http://localhost:8080
119# FREQTRADE_USERNAME=freqtrader
120# FREQTRADE_PASSWORD=auto-generated
121```
122
123**IMPORTANT — AiCoin API Key Configuration:**
124
1251. 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.
126
1272. **After writing keys to `.env`, ALWAYS verify by running a test call:**
128 ```bash
129 node scripts/coin.mjs coin_ticker '{"coin_list":"bitcoin"}'
130 ```
131
1323. **If the test returns error code `1001` (signature verification failed), the keys are swapped.** Fix by swapping them:
133 ```bash
134 # Read current values, swap them
135 OLD_KEY=$(grep '^AICOIN_ACCESS_KEY_ID=' ~/.openclaw/workspace/.env | cut -d= -f2)
136 OLD_SECRET=$(grep '^AICOIN_ACCESS_SECRET=' ~/.openclaw/workspace/.env | cut -d= -f2)
137 sed -i '' "s|^AICOIN_ACCESS_KEY_ID=.*|AICOIN_ACCESS_KEY_ID=${OLD_SECRET}|" ~/.openclaw/workspace/.env
138 sed -i '' "s|^AICOIN_ACCESS_SECRET=.*|AICOIN_ACCESS_SECRET=${OLD_KEY}|" ~/.openclaw/workspace/.env
139 ```
140 Then re-run the test to confirm it works.
141
142Or configure in `~/.openclaw/openclaw.json`:
143
144```json
145{
146 "skills": {
147 "entries": {
148 "aicoin": {
149 "enabled": true,
150 "apiKey": "your-aicoin-access-key-id",
151 "env": {
152 "AICOIN_ACCESS_SECRET": "your-secret"
153 }
154 }
155 }
156 }
157}
158```
159
160### Prerequisites
161
162- **Node.js** — required for all scripts
163- **ccxt** — required only for exchange trading: `cd <skill-dir>/aicoin && npm install`
164
165## Scripts
166
167All scripts follow: `node scripts/<name>.mjs <action> [json-params]`
168
169---
170
171### scripts/coin.mjs — Coin Data
172
173| Action | Description | Params |
174|--------|-------------|--------|
175| `coin_list` | List all coins | None |
176| `coin_ticker` | Real-time prices | `{"coin_list":"bitcoin,ethereum"}` |
177| `coin_config` | Coin profile | `{"coin_list":"bitcoin"}` |
178| `ai_analysis` | AI analysis & prediction | `{"coin_keys":"[\"bitcoin\"]","language":"CN"}` |
179| `funding_rate` | Funding rate | `{"symbol":"btcswapusdt:binance","interval":"8h"}` Weighted: `{"symbol":"btcswapusdt","interval":"8h","weighted":"true"}` |
180| `liquidation_map` | Liquidation heatmap | `{"dbkey":"btcswapusdt:binance","cycle":"24h"}` |
181| `liquidation_history` | Liquidation history | `{"symbol":"btcswapusdt:binance","interval":"1m"}` |
182| `estimated_liquidation` | Estimated liquidation | `{"dbkey":"btcswapusdt:binance","cycle":"24h"}` |
183| `open_interest` | Open interest | `{"symbol":"BTC","interval":"15m"}` Coin-margined: add `"margin_type":"coin"` |
184| `historical_depth` | Historical depth | `{"key":"btcswapusdt:okcoinfutures"}` |
185| `super_depth` | Large order depth (>$10k) | `{"key":"btcswapusdt:okcoinfutures"}` |
186| `trade_data` | Trade data | `{"dbkey":"btcswapusdt:okcoinfutures"}` |
187
188---
189
190### scripts/market.mjs — Market Data
191
192#### Market Info
193| Action | Description | Params |
194|--------|-------------|--------|
195| `exchanges` | Exchange list | None |
196| `ticker` | Exchange tickers | `{"market_list":"okex,binance"}` |
197| `hot_coins` | Trending coins | `{"key":"defi"}` key: gamefi/anonymous/market/web/newcoin/stable/defi |
198| `futures_interest` | Futures OI ranking | `{"lan":"cn"}` |
199
200#### K-Line
201| Action | Description | Params |
202|--------|-------------|--------|
203| `kline` | Standard K-line | `{"symbol":"btcusdt:okex","period":"3600","size":"100"}` period in seconds: 900=15m, 3600=1h, 14400=4h, 86400=1d |
204| `indicator_kline` | Indicator K-line | `{"symbol":"btcswapusdt:binance","indicator_key":"fundflow","period":"3600"}` |
205| `indicator_pairs` | Indicator available pairs | `{"indicator_key":"fundflow"}` |
206
207#### Index
208| Action | Description | Params |
209|--------|-------------|--------|
210| `index_list` | Index list | None |
211| `index_price` | Index price | `{"key":"i:diniw:ice"}` |
212| `index_info` | Index details | `{"key":"i:diniw:ice"}` |
213
214#### Crypto Stocks
215| Action | Description | Params |
216|--------|-------------|--------|
217| `stock_quotes` | Stock quotes | `{"tickers":"i:mstr:nasdaq,i:coin:nasdaq"}` |
218| `stock_top_gainer` | Top gainers | `{"us_stock":"true"}` |
219| `stock_company` | Company details | `{"symbol":"i:mstr:nasdaq"}` |
220
221#### Treasury (Corporate Holdings)
222| Action | Description | Params |
223|--------|-------------|--------|
224| `treasury_entities` | Holding entities | `{"coin":"BTC"}` |
225| `treasury_history` | Transaction history | `{"coin":"BTC"}` |
226| `treasury_accumulated` | Accumulated holdings | `{"coin":"BTC"}` |
227| `treasury_latest_entities` | Latest entities | `{"coin":"BTC"}` |
228| `treasury_latest_history` | Latest history | `{"coin":"BTC"}` |
229| `treasury_summary` | Holdings overview | `{"coin":"BTC"}` |
230
231#### Order Book Depth
232| Action | Description | Params |
233|--------|-------------|--------|
234| `depth_latest` | Real-time snapshot | `{"dbKey":"btcswapusdt:binance"}` |
235| `depth_full` | Full order book | `{"dbKey":"btcswapusdt:binance"}` |
236| `depth_grouped` | Grouped depth | `{"dbKey":"btcswapusdt:binance","groupSize":"100"}` |
237
238---
239
240### scripts/news.mjs — News & Content
241
242| Action | Description | Params |
243|--------|-------------|--------|
244| `news_list` | News list | `{"page":"1","pageSize":"20"}` |
245| `news_detail` | News detail | `{"id":"xxx"}` |
246| `news_rss` | RSS news | `{"page":"1"}` |
247| `newsflash` | AiCoin flash news | `{"language":"cn"}` |
248| `flash_list` | Industry flash news | `{"language":"cn"}` |
249| `exchange_listing` | Exchange listing announcements | `{"memberIds":"477,1509"}` (477=Binance, 1509=Bitget) |
250
251---
252
253### scripts/twitter.mjs — Twitter/X Crypto Tweets
254
255| Action | Description | Params |
256|--------|-------------|--------|
257| `latest` | Latest crypto tweets (cursor-paginated) | `{"language":"cn","page_size":"20","last_time":"1234567890"}` |
258| `search` | Search tweets by keyword | `{"keyword":"bitcoin","language":"cn","page_size":"20"}` |
259| `members` | Search Twitter KOL/users | `{"word":"elon","page":"1","size":"20"}` |
260| `interaction_stats` | Tweet engagement stats | `{"flash_ids":"123,456,789"}` (max 50 IDs) |
261
262---
263
264### scripts/newsflash.mjs — Newsflash (OpenData)
265
266| Action | Description | Params |
267|--------|-------------|--------|
268| `search` | Search newsflash by keyword | `{"word":"bitcoin","page":"1","size":"20"}` |
269| `list` | Newsflash list with filters | `{"pagesize":"20","lan":"cn","date_mode":"range","start_date":"2025-03-01","end_date":"2025-03-04"}` |
270| `detail` | Newsflash full content | `{"flash_id":"123456"}` |
271
272---
273
274### scripts/features.mjs — Features & Signals
275
276#### Market Overview
277| Action | Description | Params |
278|--------|-------------|--------|
279| `nav` | Market navigation | `{"lan":"cn"}` |
280| `ls_ratio` | Long/short ratio | None |
281| `liquidation` | Liquidation data | `{"type":"1","coinKey":"bitcoin"}` type: 1=by coin, 2=by exchange |
282| `grayscale_trust` | Grayscale trust | None |
283| `gray_scale` | Grayscale holdings | `{"coins":"btc,eth"}` |
284| `stock_market` | Crypto stocks | None |
285
286#### Whale Order Tracking
287| Action | Description | Params |
288|--------|-------------|--------|
289| `big_orders` | Large/whale orders | `{"symbol":"btcswapusdt:binance"}` |
290| `agg_trades` | Aggregated large trades | `{"symbol":"btcswapusdt:binance"}` |
291
292#### Trading Pairs
293| Action | Description | Params |
294|--------|-------------|--------|
295| `pair_ticker` | Pair ticker | `{"key_list":"btcusdt:okex,btcusdt:huobipro"}` |
296| `pair_by_market` | Pairs by exchange | `{"market":"binance"}` |
297| `pair_list` | Pair list | `{"market":"binance","currency":"USDT"}` |
298
299#### Signals
300| Action | Description | Params |
301|--------|-------------|--------|
302| `strategy_signal` | Strategy signal | `{"signal_key":"depth_win_one"}` |
303| `signal_alert` | Signal alerts | None |
304| `signal_config` | Alert config | `{"lan":"cn"}` |
305| `signal_alert_list` | Alert list | None |
306| `change_signal` | Anomaly signal | `{"type":"1"}` |
307| `delete_signal` | Delete alert | `{"id":"xxx"}` |
308
309---
310
311### scripts/hl-market.mjs — Hyperliquid Market
312
313#### Tickers
314| Action | Description | Params |
315|--------|-------------|--------|
316| `tickers` | All tickers | None |
317| `ticker` | Single coin ticker | `{"coin":"BTC"}` |
318
319#### Whales
320| Action | Description | Params |
321|--------|-------------|--------|
322| `whale_positions` | Whale positions | `{"coin":"BTC","min_usd":"1000000"}` |
323| `whale_events` | Whale events | `{"coin":"BTC"}` |
324| `whale_directions` | Long/short direction | `{"coin":"BTC"}` |
325| `whale_history_ratio` | Historical long ratio | `{"coin":"BTC"}` |
326
327#### Liquidations
328| Action | Description | Params |
329|--------|-------------|--------|
330| `liq_history` | Liquidation history | `{"coin":"BTC"}` |
331| `liq_stats` | Liquidation stats | None |
332| `liq_stats_by_coin` | Stats by coin | `{"coin":"BTC"}` |
333| `liq_top_positions` | Large liquidations | `{"coin":"BTC","interval":"1d"}` |
334
335#### Open Interest
336| Action | Description | Params |
337|--------|-------------|--------|
338| `oi_summary` | OI overview | None |
339| `oi_top_coins` | OI ranking | `{"limit":"10"}` |
340| `oi_history` | OI history | `{"coin":"BTC","interval":"4h"}` |
341
342#### Taker
343| Action | Description | Params |
344|--------|-------------|--------|
345| `taker_delta` | Taker delta | `{"coin":"BTC"}` |
346| `taker_klines` | Taker K-lines | `{"coin":"BTC","interval":"4h"}` |
347
348---
349
350### scripts/hl-trader.mjs — Hyperliquid Trader
351
352#### Trader Analytics
353| Action | Description | Params |
354|--------|-------------|--------|
355| `trader_stats` | Trader statistics | `{"address":"0x...","period":"30"}` |
356| `best_trades` | Best trades | `{"address":"0x...","period":"30"}` |
357| `performance` | Performance by coin | `{"address":"0x...","period":"30"}` |
358| `completed_trades` | Completed trades | `{"address":"0x...","coin":"BTC"}` |
359| `accounts` | Batch accounts | `{"addresses":"[\"0x...\"]"}` |
360| `statistics` | Batch statistics | `{"addresses":"[\"0x...\"]"}` |
361
362#### Fills
363| Action | Description | Params |
364|--------|-------------|--------|
365| `fills` | Address fills | `{"address":"0x..."}` |
366| `fills_by_oid` | By order ID | `{"oid":"xxx"}` |
367| `fills_by_twapid` | By TWAP ID | `{"twapid":"xxx"}` |
368| `top_trades` | Large trades | `{"coin":"BTC","interval":"1d"}` |
369
370#### Orders
371| Action | Description | Params |
372|--------|-------------|--------|
373| `orders_latest` | Latest orders | `{"address":"0x..."}` |
374| `order_by_oid` | By order ID | `{"oid":"xxx"}` |
375| `filled_orders` | Filled orders | `{"address":"0x..."}` |
376| `filled_by_oid` | Filled by ID | `{"oid":"xxx"}` |
377| `top_open` | Large open orders | `{"coin":"BTC","min_val":"100000"}` |
378| `active_stats` | Active stats | `{"coin":"BTC"}` |
379| `twap_states` | TWAP states | `{"address":"0x..."}` |
380
381#### Positions
382| Action | Description | Params |
383|--------|-------------|--------|
384| `current_pos_history` | Current position history | `{"address":"0x...","coin":"BTC"}` |
385| `completed_pos_history` | Closed position history | `{"address":"0x...","coin":"BTC"}` |
386| `current_pnl` | Current PnL | `{"address":"0x...","coin":"BTC","interval":"1h"}` |
387| `completed_pnl` | Closed PnL | `{"address":"0x...","coin":"BTC","interval":"1h"}` |
388| `current_executions` | Current executions | `{"address":"0x...","coin":"BTC","interval":"1h"}` |
389| `completed_executions` | Closed executions | `{"address":"0x...","coin":"BTC","interval":"1h"}` |
390
391#### Portfolio
392| Action | Description | Params |
393|--------|-------------|--------|
394| `portfolio` | Account curve | `{"address":"0x...","window":"week"}` window: day/week/month/allTime |
395| `pnls` | PnL curve | `{"address":"0x...","period":"30"}` |
396| `max_drawdown` | Max drawdown | `{"address":"0x...","days":"30"}` |
397| `net_flow` | Net flow | `{"address":"0x...","days":"30"}` |
398
399#### Advanced
400| Action | Description | Params |
401|--------|-------------|--------|
402| `info` | Info API | `{"type":"metaAndAssetCtxs"}` |
403| `smart_find` | Smart money discovery | `{}` |
404| `discover` | Trader discovery | `{}` |
405
406---
407
408### scripts/exchange.mjs — Exchange Trading (CCXT)
409
410**⚠️ MANDATORY: All exchange operations MUST go through `exchange.mjs`.**
411- **NEVER** write custom CCXT/Python code to interact with exchanges. Always use `node scripts/exchange.mjs <action> '<params>'`.
412- **NEVER** import ccxt directly in custom scripts. The exchange.mjs wrapper handles broker attribution, proxy config, and API key management.
413- `exchange.mjs` automatically sets AiCoin broker tags for order attribution. Custom CCXT code will NOT have these tags, causing orders to be mis-attributed.
414- For automated trading workflows, use `auto-trade.mjs` which wraps `exchange.mjs` with risk management.
415
416Requires `npm install ccxt` and exchange API keys.
417
418#### Public (no API key required)
419| Action | Description | Params |
420|--------|-------------|--------|
421| `exchanges` | Supported exchanges | None |
422| `markets` | Market list | `{"exchange":"binance","market_type":"swap","base":"BTC"}` |
423| `ticker` | Real-time ticker | `{"exchange":"binance","symbol":"BTC/USDT"}` |
424| `orderbook` | Order book | `{"exchange":"binance","symbol":"BTC/USDT"}` |
425| `trades` | Recent trades | `{"exchange":"binance","symbol":"BTC/USDT"}` |
426| `ohlcv` | OHLCV candles | `{"exchange":"binance","symbol":"BTC/USDT","timeframe":"1h"}` |
427
428#### Account (API key required)
429| Action | Description | Params |
430|--------|-------------|--------|
431| `balance` | Account balance | `{"exchange":"binance"}` |
432| `positions` | Open positions | `{"exchange":"binance","market_type":"swap"}` |
433| `open_orders` | Open orders | `{"exchange":"binance","symbol":"BTC/USDT"}` |
434
435#### Trading (API key required)
436
437**🚨 SAFETY RULES — MANDATORY for ALL trading operations:**
4381. **NEVER execute a buy/sell/trade without explicit user confirmation.** Always show the order details and ask "确认下单?" BEFORE calling `create_order`.
4392. **NEVER sell or close the user's existing positions** unless the user specifically asks to sell/close.
4403. **NEVER write custom CCXT, Python, or curl code** to interact with exchanges. ALL exchange operations MUST go through `exchange.mjs`.
441
442**⚠️ CRITICAL — `amount` units differ between spot and futures:**
443- **Spot**: `amount` is in **base currency** (e.g., `amount: 0.01` = 0.01 BTC)
444- **Futures/Swap**: `amount` is in **contracts** (e.g., `amount: 1` = 1 contract). Get `contractSize` from `markets` to convert.
445
446**User intent → `amount` conversion (you MUST get this right):**
447| User says | Spot `amount` | Swap `amount` (OKX BTC, contractSize=0.01) |
448|-----------|--------------|---------------------------------------------|
449| "0.01 BTC" / "0.01个BTC" | `0.01` | `0.01 / 0.01 = 1` (1 contract) |
450| "1张合约" / "1 contract" | N/A | `1` (直接用) |
451| "0.01张" | N/A | `0.01` (0.01 contract = 0.0001 BTC) |
452| "100U" / "100 USDT" | `100 / price` | `(100 / price) / contractSize` |
453
454**NEVER pass the user's number directly as `amount` without checking the unit context!**
455
456**Before placing any order, you MUST:**
4571. Run `markets` to get the trading pair's `limits.amount.min` (minimum order size) and `contractSize` — do NOT guess or assume minimums
4582. Run `balance` to check available funds
4593. Convert user's quantity to the correct unit using the table above
4604. For futures/swap: calculate actual buying power = balance × leverage
4615. Verify: buying power ≥ order value
4626. **Confirm with user**: "You want to buy X contracts (= Y BTC ≈ Z USDT), correct?" before placing the order
463
464Example pre-trade check for BTC/USDT perpetual on OKX:
465```bash
466# Step 1: Check minimum order size AND contract size
467node scripts/exchange.mjs markets '{"exchange":"okx","market_type":"swap","base":"BTC"}'
468# → look for limits.amount.min (e.g. 1 contract) and contractSize (e.g. 0.01 BTC)
469# → This means: 1 contract = 0.01 BTC, min order = 1 contract = 0.01 BTC
470
471# Step 2: Check balance
472node scripts/exchange.mjs balance '{"exchange":"okx"}'
473# → e.g. 7 USDT free
474
475# Step 3: Calculate — 7 USDT × 10x = 70 USDT ÷ $68000 ≈ 0.001 BTC ÷ 0.01 = 0.1 contracts → below min 1 contract → cannot trade
476# With more capital: 100 USDT × 10x = 1000 ÷ $68000 ≈ 0.0147 BTC ÷ 0.01 = 1.47 → round to 1 contract → OK
477```
478
479| Action | Description | Params |
480|--------|-------------|--------|
481| `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) |
482| `cancel_order` | Cancel order | `{"exchange":"okx","symbol":"BTC/USDT","order_id":"xxx"}` |
483| `set_leverage` | Set leverage | `{"exchange":"okx","symbol":"BTC/USDT:USDT","leverage":10,"market_type":"swap"}` |
484| `set_margin_mode` | Margin mode | `{"exchange":"okx","symbol":"BTC/USDT:USDT","margin_mode":"cross","market_type":"swap"}` |
485| `transfer` | Transfer funds | `{"exchange":"binance","code":"USDT","amount":100,"from_account":"spot","to_account":"future"}` |
486
487**Notes on `transfer`:**
488- **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.
489- **Binance**: Requires explicit transfer between spot/futures accounts.
490
491---
492
493### scripts/ft.mjs — Freqtrade Bot Control
494
495| Action | Description | Params |
496|--------|-------------|--------|
497| `ping` | Health check | None |
498| `start` | Start trading | None |
499| `stop` | Stop trading | None |
500| `reload` | Reload config | None |
501| `config` | View config | None |
502| `version` | Version info | None |
503| `sysinfo` | System info | None |
504| `health` | Health status | None |
505| `logs` | View logs | `{"limit":50}` |
506| `balance` | Account balance | None |
507| `trades_open` | Open trades | None |
508| `trades_count` | Trade count | None |
509| `trade_by_id` | Trade by ID | `{"trade_id":1}` |
510| `trades_history` | Trade history | `{"limit":50}` |
511| `force_enter` | Manual entry | `{"pair":"BTC/USDT","side":"long"}` |
512| `force_exit` | Manual exit | `{"tradeid":"1"}` |
513| `cancel_order` | Cancel order | `{"trade_id":1}` |
514| `delete_trade` | Delete record | `{"trade_id":1}` |
515| `profit` | Profit summary | None |
516| `profit_per_pair` | Profit per pair | None |
517| `daily` | Daily report | `{"count":7}` |
518| `weekly` | Weekly report | `{"count":4}` |
519| `monthly` | Monthly report | `{"count":3}` |
520| `stats` | Statistics | None |
521
522---
523
524### scripts/ft-dev.mjs — Freqtrade Dev Tools
525
526| Action | Description | Params |
527|--------|-------------|--------|
528| `backtest_start` | Start backtest | `{"strategy":"MyStrategy","timerange":"20240101-20240601","timeframe":"5m"}` |
529| `backtest_status` | Backtest status | None |
530| `backtest_abort` | Abort backtest | None |
531| `backtest_history` | Backtest history | None |
532| `backtest_result` | History result | `{"id":"xxx"}` |
533| `candles_live` | Live candles | `{"pair":"BTC/USDT","timeframe":"1h"}` |
534| `candles_analyzed` | Candles with indicators | `{"pair":"BTC/USDT","timeframe":"1h","strategy":"MyStrategy"}` |
535| `candles_available` | Available pairs | None |
536| `whitelist` | Whitelist | None |
537| `blacklist` | Blacklist | None |
538| `blacklist_add` | Add to blacklist | `{"add":["DOGE/USDT"]}` |
539| `locks` | Trade locks | None |
540| `strategy_list` | Strategy list | None |
541| `strategy_get` | Strategy detail | `{"name":"MyStrategy"}` |
542
543---
544
545### scripts/auto-trade.mjs — Automated Trading
546
547Config + execution helper. **The AI agent makes all strategy decisions** — this script only handles config, risk management, and order execution.
548
549Config is stored at `~/.openclaw/workspace/aicoin-trade-config.json`.
550
551| Action | Description | Params |
552|--------|-------------|--------|
553| `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}` |
554| `status` | Show config + balance + positions + open orders | `{}` |
555| `open` | Open a position (agent decides direction) | `{"direction":"long"}` or `{"direction":"short"}` |
556| `close` | Close current position + cancel orders | `{}` |
557
558The `open` action automatically:
5591. Checks balance and market minimums
5602. Calculates position size from config (capital_pct × balance × leverage)
5613. Sets leverage
5624. Places market order
5635. Places stop-loss and take-profit limit orders
564
565---
566
567### scripts/ft-deploy.mjs — Freqtrade Deployment
568
569**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`.
570
571| Action | Description | Params |
572|--------|-------------|--------|
573| `check` | Check prerequisites (Python 3.11+, git, exchange keys) | None |
574| `deploy` | Deploy Freqtrade (clone, setup.sh, config, start) | `{"dry_run":true,"pairs":["BTC/USDT:USDT","ETH/USDT:USDT"]}` |
575| `backtest` | Run backtest (no running process needed) | `{"strategy":"SampleStrategy","timeframe":"1h","timerange":"20250101-20260301"}` |
576| `update` | Update Freqtrade to latest version | None |
577| `status` | Process status | None |
578| `start` | Start stopped process | None |
579| `stop` | Stop process | None |
580| `logs` | View process logs | `{"lines":50}` |
581| `remove` | Remove process (preserves config) | None |
582
583**Deploy defaults to dry-run mode** (simulated trading, no real money). Pass `{"dry_run":false}` for live trading.
584
585**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.
586
587**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.
588
589---
590
591## Automated Trading Guide
592
593When the user asks to set up automated trading, follow this workflow. **Do NOT write custom scripts.**
594
595### How It Works
596
597The AI agent is the strategist. On each cycle:
5981. **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)
5992. **Analyze** the data — trend, momentum, risk signals. Use your own judgment.
6003. **Decide**: open long, open short, close position, or hold
6014. **Execute** via `auto-trade.mjs open '{"direction":"long"}'` — handles position sizing, leverage, stop-loss/take-profit automatically
602
603### Quick Setup
604
605```bash
606# 1. Configure risk params
607node scripts/auto-trade.mjs setup '{"exchange":"okx","symbol":"BTC/USDT:USDT","leverage":10,"capital_pct":0.5}'
608
609# 2. Check status
610node scripts/auto-trade.mjs status
611```
612
613### OpenClaw Cron (Recommended)
614
615**Use OpenClaw's built-in cron, NOT system crontab.** This gives the user visibility in the web UI.
616
617```bash
618openclaw cron add \
619 --name "BTC auto trade" \
620 --every 10m \
621 --session isolated \
622 --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."
623```
624
625### When User Asks "帮我自动交易"
626
6271. Ask: which exchange? which coin? how much capital? what leverage?
6282. Run `auto-trade.mjs setup` with their params
6293. Run `auto-trade.mjs status` to verify exchange connection
6304. Set up OpenClaw cron with their preferred interval
6315. Done — tell them they can check status anytime via `auto-trade.mjs status`
632
633---
634
635## Freqtrade Guide
636
637When the user asks about backtesting, professional strategies, quantitative trading, or deploying a trading bot, guide them to Freqtrade.
638
639**Freqtrade vs auto-trade.mjs:**
640- auto-trade.mjs = simple AI-driven, good for testing, small capital
641- Freqtrade = professional, backtestable, risk-managed, production-grade
642
643### Deployment (One Command)
644
645```bash
646# Check prerequisites first
647node scripts/ft-deploy.mjs check
648
649# Deploy (dry-run mode by default — safe)
650node scripts/ft-deploy.mjs deploy '{"pairs":["BTC/USDT:USDT","ETH/USDT:USDT"]}'
651```
652
653This automatically:
6541. Ensures Python 3.11+ is available (auto-installs via brew if needed on macOS)
6552. Clones Freqtrade repo to `~/.freqtrade/source/`
6563. Runs official `setup.sh -i` (installs TA-Lib, creates venv, installs all dependencies)
6574. Creates config from exchange keys in `.env`
6585. Includes a sample RSI+EMA strategy (pure pandas, no TA-Lib import needed)
6596. Starts Freqtrade as a background process with API server
6607. Writes `FREQTRADE_URL`, `FREQTRADE_USERNAME`, `FREQTRADE_PASSWORD` to `.env`
6618. Ready to use via `ft.mjs` and `ft-dev.mjs`
662
663**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.
664
665### User Journey
666
667```
668"帮我部署Freqtrade"
669 → node scripts/ft-deploy.mjs deploy
670 → "已部署,dry-run模式,用模拟资金运行"
671
672"帮我回测BTC策略"
673 → node scripts/ft-deploy.mjs backtest '{"strategy":"SampleStrategy","timeframe":"1h","timerange":"20250101-20260301"}'
674 → "回测结果: 胜率62%, 最大回撤-8%, 总收益+45%"
675
676"不错,上实盘"
677 → node scripts/ft-deploy.mjs deploy '{"dry_run":false}'
678 → "⚠️ 已切换到实盘模式,使用真实资金"
679
680"今天赚了多少?"
681 → node scripts/ft.mjs profit
682 → node scripts/ft.mjs daily '{"count":7}'
683
684"暂停交易"
685 → node scripts/ft.mjs stop
686```
687
688### When User Mentions These Keywords → Use Freqtrade
689
690- 回测 / backtest → `ft-deploy.mjs backtest` (does NOT require Freqtrade to be running)
691- 写策略 / write strategy → Write a `.py` file to `~/.freqtrade/user_data/strategies/`, then `ft-deploy.mjs backtest`
692- 量化策略 / strategy → `ft-dev.mjs strategy_list` (requires running process)
693- 部署机器人 / deploy bot → `ft-deploy.mjs deploy`
694- 实盘 / live trading → `ft-deploy.mjs deploy '{"dry_run":false}'`
695- 盈亏 / profit → `ft.mjs profit`
696- 停止机器人 / stop bot → `ft.mjs stop` or `ft-deploy.mjs stop`
697
698**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.**