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