ETH/USDC Grid Trading Bot
欢迎使用 ETH/USDC 网格交易策略!
我们在 Base 链上自动执行 ETH/USDC 网格交易——震荡行情中低买高卖,每次价格穿越网格线自动成交。策略基于 EMA 动态居中,自适应波动率调整网格步长,内置仓位限制、冷却期、熔断保护,极低 gas 成本。
投资案例:
小李用 5,000 USDC + 1 ETH(约 $8,000 总资产)启动网格机器人。ETH 在 $2,800~$3,200 区间震荡。
机器人设置 6 档网格,步长约 1.5%,每次交易约 $500。
一周内触发 12 次买卖,累计捕获网格价差约 $180,折合年化约 24%。
同期 ETH 横盘无涨跌,手动持有收益为零。
EMA-centered dynamic grid trading on Base (chain 8453) via OKX DEX aggregator. Available as standalone
binary.
Pre-flight Checks
Run immediately when this skill is triggered — before any response or command. Always follow these steps in order. Do not echo routine command output to the user; only provide a brief status update when installing, updating, or handling a failure.
Step 1: Check onchainos
- Found → run to confirm, then proceed to Step 2.
- Not found → install automatically:
bash
curl -sSL https://raw.githubusercontent.com/okx/onchainos-skills/main/install.sh | sh
- If install succeeds → verify with , then proceed to Step 2.
- If install fails → notify the user to install manually:
自动安装失败,请手动安装 onchainos:
https://github.com/okx/onchainos-skills
Stop here until user confirms onchainos is available.
Step 2: Check skills-store
-
Not found → install:
bash
curl -sSL https://raw.githubusercontent.com/purong-huang-1121/skills-store/main/install.sh | sh
-
Check for updates: Read
~/.cargo/bin/.skills-store/last_check_grid
and compare with current timestamp:
bash
cached_ts=$(cat ~/.cargo/bin/.skills-store/last_check_grid 2>/dev/null || true)
now=$(date +%s)
- If is non-empty and
(now - cached_ts) < 43200
(12 hours), skip the update.
- Otherwise, run the installer to check for updates.
Step 3: Check strategy-grid
- Found → proceed.
- Not found → install:
bash
curl -sSL https://raw.githubusercontent.com/purong-huang-1121/skills-store/main/install_strategy.sh | sh -s -- strategy-grid
- If install succeeds → verify with , then proceed.
- If install fails → notify the user:
自动安装失败,请手动安装 strategy-grid:
curl -sSL https://raw.githubusercontent.com/purong-huang-1121/skills-store/main/install_strategy.sh | sh -s -- strategy-grid
Stop here until user confirms installation.
Authentication
Requires two sets of credentials:
OKX API (for price quotes and swap execution):
bash
OKX_API_KEY=...
OKX_SECRET_KEY=...
OKX_PASSPHRASE=...
EVM Wallet (for on-chain signing):
bash
EVM_PRIVATE_KEY=0x... # Base wallet with ETH + USDC
Optional:
bash
BASE_RPC_URL=... # Custom Base RPC (default: public endpoint)
TELEGRAM_BOT_TOKEN=... # Telegram notifications on trade/error
TELEGRAM_CHAT_ID=... # Telegram chat ID for alerts
Before Starting the Bot
IMPORTANT: Before running
, you MUST:
- Run to show the user their current parameters
- Present the parameters in a readable table and ask if they want to adjust any
- If the user wants to change a parameter, use
strategy-grid set --key <name> --value <value>
- Parameters are saved to in the same directory as the executable and persist across restarts — no need to set them every time
Example flow:
bash
# Show current config
strategy-grid config
# User wants to change tick interval
strategy-grid set --key tick_interval_secs --value 120
# User wants wider position limits
strategy-grid set --key position_max_pct --value 70
strategy-grid set --key position_min_pct --value 30
# Now start
strategy-grid start
Quickstart
bash
# Check market conditions
strategy-grid analyze
# View current state and PnL
strategy-grid status
# Run a single tick (fetch price, detect crossing, trade if needed)
strategy-grid tick
# Start continuous bot (tick every 60 seconds)
strategy-grid start
# Stop running bot
strategy-grid stop
Command Index
| # | Command | Auth | Description |
|---|
| 1 | | Yes | Execute one grid cycle |
| 2 | | Yes | Start foreground bot loop (60s ticks) |
| 3 | | No | Stop running bot via PID file |
| 4 | | No | Show grid state, balances, PnL |
| 5 | | No | Detailed PnL and performance stats |
| 6 | | No | Show trade history |
| 7 | strategy-grid reset --force
| No | Clear all grid state |
| 8 | | Yes | Re-execute last failed trade |
| 9 | | Yes | Market analysis (EMA, volatility, trend) |
| 10 | | No | Record manual deposit/withdrawal |
| 11 | | No | Show current bot configuration |
| 12 | | No | Set a config parameter |
Core Algorithm
1. Fetch ETH price (OKX DEX quote API)
2. Read on-chain balances (ETH + USDC on Base)
3. Check circuit breaker (consecutive errors)
4. Recalibrate grid if needed (price breakout / vol shift / age)
5. Map price → grid level
6. If level changed:
a. Direction: BUY if level dropped, SELL if rose
b. Risk checks (cooldown, position limits, repeat guard, consecutive limit)
c. Calculate trade size (% of portfolio, capped)
d. Execute swap via OKX DEX aggregator
e. Update level ONLY on success
7. Save state and report
Tunable Parameters
Parameters are persisted at
in the same directory as the
executable. View with
, modify with
strategy-grid set --key <key> --value <value>
. Changes take effect on next tick (no rebuild needed). If no config file exists, defaults below are used.
The
Key column shows the exact key name to use with
.
Grid Structure
| Key | Default | Description |
|---|
| | Number of grid levels |
| | EMA lookback periods for grid center calculation |
| | Grid width = multiplier × stddev |
| | Max hours before forced recalibration |
| | Seconds between each tick cycle (restart bot to apply) |
Adaptive Step Sizing
Step scales linearly with real-time volatility:
step = (volatility_multiplier × stddev) / (grid_levels / 2)
step = clamp(step, price × step_min_pct, price × step_max_pct)
step = max(step, step_floor)
| Key | Default | Description |
|---|
| | Step floor (0.8% of price) |
| | Step cap (6% of price) |
| | Absolute minimum step in USD |
Trade Sizing
| Key | Default | Description |
|---|
| | Max 12% of portfolio per trade |
| | Minimum trade size in USD |
| | Slippage tolerance % for DEX swap. Increase to 2-3 if trades revert |
| | ETH reserved for gas, not available for SELL |
Risk Controls
| Key | Default | Description |
|---|
| | 30min cooldown between same-direction trades |
| | Max consecutive same-direction trades |
| | Block BUY when ETH% exceeds this |
| | Block SELL when ETH% drops below this |
| | Circuit breaker threshold |
| | Seconds cooldown after circuit breaker trips |
Common Parameter Adjustments
Slippage (trades reverting on-chain):
bash
strategy-grid set --key slippage_pct --value 2
Wider position limits (allow more one-sided exposure):
bash
strategy-grid set --key position_max_pct --value 75
strategy-grid set --key position_min_pct --value 25
Faster/slower tick interval:
bash
strategy-grid set --key tick_interval_secs --value 120 # 2 minutes
Note: Restart the bot after changing
.
Larger trade sizes:
bash
strategy-grid set --key max_trade_pct --value 0.20 # 20% per trade
strategy-grid set --key min_trade_usd --value 10 # $10 minimum
CLI Command Reference
strategy-grid tick
Execute one grid cycle: fetch price, detect grid crossing, execute trade if needed.
Output actions:
- — Grid was recalibrated (first tick or recalibration trigger)
- — Price stayed within same grid level
- — Swap executed successfully
- — Swap attempted but failed (retriable)
- — Risk check prevented trade (cooldown, position limit, etc.)
- — Trade amount below minimum
strategy-grid start
Start the bot in foreground, executing
every 60 seconds. Creates a PID file at
~/.skills-store/grid_bot.pid
. Use Ctrl+C or
to terminate.
strategy-grid stop
Stop a running bot by sending SIGTERM to the process in the PID file.
strategy-grid status
Show current grid state, balances, PnL overview, and whether the bot is running.
strategy-grid report
Detailed performance report: success rate, buy/sell counts, total volume, grid profit, deposits, and portfolio PnL.
strategy-grid history [--limit N]
Show trade history (default: last 50 trades). Each trade includes direction, price, amount, tx hash, and grid levels.
strategy-grid reset --force
Delete all grid state. Requires
flag for safety.
strategy-grid retry
Re-execute the last failed trade. Validates that price hasn't moved >5% since failure.
strategy-grid analyze
Market analysis showing current price, EMA-20, volatility, trend direction, and grid utilization.
strategy-grid deposit --amount N [--note "..."]
Record a manual deposit (positive) or withdrawal (negative) for accurate PnL tracking.
strategy-grid config
Show all current bot parameters and their values. Indicates whether a custom config file exists.
strategy-grid set --key NAME --value VALUE
Set a single parameter. Saved to
in the executable's directory. Takes effect on next tick (restart bot if already running to apply tick_interval changes).
Available keys:
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
.
Level Update Rule (Critical)
| Outcome | Update level? | Rationale |
|---|
| Trade succeeded | Yes | Grid crossing consumed |
| Trade failed | No | Retry on next tick |
| Trade skipped (cooldown/limit) | No | Don't lose the crossing |
PnL Tracking
total_pnl = current_portfolio_value - initial_value - deposits
grid_profit += estimated spread capture on SELL trades
State Persistence
State is stored at
~/.skills-store/grid_state.json
with atomic writes (write to .tmp, rename). Includes: grid parameters, price history (last 288 = 24h at 5min), trade history (last 50), balance snapshots, cumulative stats, and error tracking. PID file at
~/.skills-store/grid_bot.pid
.
Cross-Skill Workflows
| Need | Skill |
|---|
| USDC yield optimization (Aave/Compound/Morpho) | |
| Aave V3 supply/withdraw/markets | |
| Morpho vault operations | (CLI: ) |
| Hyperliquid perpetual trading | |
| Prediction markets | / |
Edge Cases
| Scenario | Behavior |
|---|
| First tick (no grid) | Calibrates grid from current price + history, sets initial level |
| Price exits grid range | Triggers recalibration (breakout detected) |
| Volatility shifts >30% | Triggers recalibration |
| Grid age > 12 hours | Triggers recalibration |
| 5 consecutive errors | Circuit breaker trips, 1-hour cooldown |
| Trade amount < $5 | Skipped (below minimum) |
| ETH balance < 0.003 | Gas reserve protected, SELL blocked |
| No EVM_PRIVATE_KEY | Error on tick/start/retry commands |
| Bot already running | rejects with existing PID warning |
| No running bot | returns error |
| Reset without --force | Returns error, requires confirmation |
Troubleshooting
| Symptom | Cause | Fix |
|---|
| Trade reverts on-chain () | Slippage too low for the DEX route | strategy-grid set --key slippage_pct --value 2
(or 3 for volatile periods) |
| RPC 429 / rate limit errors | Public Base RPC rate limited | Set env var to a private RPC endpoint |
| Circuit breaker trips (5 errors) | Repeated failures (RPC, slippage, gas) | Check logs, fix root cause, then wait 1h or strategy-grid reset --force
|
| Bot not trading (no_crossing) | Price within same grid level | Normal — bot only trades when price crosses a grid boundary |
| Trade blocked: position limit | ETH% too high/low | Adjust / or manually rebalance |
| Trade blocked: cooldown | Same-direction trade too soon (30min default) | Lower if you want faster trading |
| Trade blocked: repeat guard | Same crossing as last trade | Normal — prevents oscillation. Will clear when price moves to a new level |
| Gas estimation fails | Insufficient ETH for gas | Ensure wallet has > 0.003 ETH (adjust via ) |
Anti-Patterns
| Pattern | Problem |
|---|
| Recalibrate every tick | Grid oscillates, no stable levels |
| Update level on failure/skip | Silently loses grid crossings |
| No position limits | Trending market → 100% one-sided |
| Fixed step in volatile market | Too small → over-trades; too large → never triggers |
| as PnL | Net cash flow ≠ profit |
| No cooldown | Rapid swings cause burst of trades eating slippage |