简介
开源DeFi交易机器人,集成Bankr CLI与Base链,具备自学习能力的自动化交易引擎
原始描述
DeFi Trading Engine - Autonomous DeFi trading bot with self-improving review system for OpenClaw agents. Use when setting up DeFi trading, crypto trading bot...
通过你的 Agent 添加
安装目录:defi-trading-engine/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。
点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。
或者手动安装
包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可;
目录名不用换,也不要把包直接解压到 skills 根目录。
技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。
中文使用说明 来自收录源
核心用法
DeFi Trading Engine 是一套完整的自动化加密货币交易解决方案,专为Base等EVM链设计。核心工作流遵循"扫描→评估→执行→记录→复盘→优化参数→循环"的自改进闭环。
主要功能模块:
- Token Scanner (
scan-tokens.py):利用CoinGecko、DexScreener等免费API扫描交易机会,支持量价异常检测和流动性筛选 - Risk Manager (
risk-manager.py):每笔交易前的风控守门员,检查仓位上限、日交易次数、冷却期和最大回撤熔断 - Trade Executor (
trade-executor.py):通过Bankr CLI执行买卖操作,支持市价单、限价单、止损止盈设置 - Daily Review (
daily-review.py):自动生成交易复盘报告,计算胜率、夏普比率、最大回撤,并基于Pattern识别提出参数调优建议
配置中心 (trading-config.json) 统一管理风险参数(默认单笔$40、止盈4%/止损8%、最大回撤15%)、策略类型(动量摆动/均值回归/定投/非对称押注)及Bankr集成设置。
显著优点
- 自学习能力:每日复盘自动识别高胜率信号组合(如"动量交易4/5盈利"),并推荐参数调整,实现策略进化
- 多层风控:仓位限制、冷却期、日交易上限、15%最大回撤熔断,层层保护本金
- 零成本数据源:整合CoinGecko趋势、DexScreener等免费API,无需付费行情服务
- Paper Trading支持:模拟模式验证策略后再上实盘
- 模块化设计:扫描、风控、执行、复盘四模块独立,便于替换组件(如换用其他DEX工具替代Bankr)
潜在缺点与局限
- 依赖Bankr CLI生态:核心执行层绑定Bankr,若Bankr服务中断或接口变更需适配
- 免费API限制:CoinGecko免费版有速率限制,高频扫描可能受限;DexScreener数据延迟
- 回测功能缺失:文档提及Backtest但未提供实现,需用户自行开发
- 无杠杆支持:仅支持现货交易,策略收益天花板有限
- 链上执行风险:智能合约风险、Gas费波动、网络拥堵时的滑点失控(默认1.5%可能不足)
适合人群
- DeFi进阶用户:已熟悉钱包操作、理解滑点/无常损失等概念
- 系统化交易者:希望将主观判断转化为可量化、可迭代的规则
- Base生态参与者:已在Base链有活跃地址和Bankr配置
- 小额资金实验:默认$40仓位适合策略验证,非大额资管场景
常规风险
- 资金安全:需妥善保管私钥,建议专用钱包、小额资金隔离
- 策略失效:市场结构变化(如熊市流动性枯竭)可能导致历史有效策略亏损
- 过度拟合:自学习系统若参数调整过频,可能在噪声中寻找虚假模式
- 执行故障:Cron定时任务依赖本地机器在线,断网/关机导致错过信号或风控失效
- 合规不确定性:自动化交易在部分司法辖区可能触发证券法规制
- 依赖Bankr CLI生态:核心执行层绑定Bankr,若Bankr服务中断或接口变更需适配
- 免费API限制:CoinGecko免费版有速率限制,高频扫描可能受限;DexScreener数据延迟
- 回测功能缺失:文档提及Backtest但未提供实现,需用户自行开发
- 无杠杆支持:仅支持现货交易,策略收益天花板有限
- 链上执行风险:智能合约风险、Gas费波动、网络拥堵时的滑点失控(默认1.5%可能不足)
适合人群
- DeFi进阶用户:已熟悉钱包操作、理解滑点/无常损失等概念
- 系统化交易者:希望将主观判断转化为可量化、可迭代的规则
- Base生态参与者:已在Base链有活跃地址和Bankr配置
- 小额资金实验:默认$40仓位适合策略验证,非大额资管场景
常规风险
- 资金安全:需妥善保管私钥,建议专用钱包、小额资金隔离
- 策略失效:市场结构变化(如熊市流动性枯竭)可能导致历史有效策略亏损
- 过度拟合:自学习系统若参数调整过频,可能在噪声中寻找虚假模式
- 执行故障:Cron定时任务依赖本地机器在线,断网/关机导致错过信号或风控失效
- 合规不确定性:自动化交易在部分司法辖区可能触发证券法规制
- 资金安全:需妥善保管私钥,建议专用钱包、小额资金隔离
- 策略失效:市场结构变化(如熊市流动性枯竭)可能导致历史有效策略亏损
- 过度拟合:自学习系统若参数调整过频,可能在噪声中寻找虚假模式
- 执行故障:Cron定时任务依赖本地机器在线,断网/关机导致错过信号或风控失效
- 合规不确定性:自动化交易在部分司法辖区可能触发证券法规制
技能正文
name: defi-trading-engine
description: DeFi Trading Engine - Autonomous DeFi trading bot with self-improving review system for OpenClaw agents. Use when setting up DeFi trading, crypto trading bot, automated trading, Base chain trading, Bankr integration, trading engine, self-improving bot, or trading strategy execution.
DeFi Trading Engine
Autonomous DeFi trading bot with self-improving review system. Scans for opportunities, executes trades, logs performance, and learns from mistakes.
When to Use
Apply this skill when:
- Setting up automated crypto trading on Base or other EVM chains
- Building a self-improving trading system
- Implementing systematic DeFi trading strategies
- Executing DCA, momentum, or mean reversion strategies
- Reviewing and optimizing trading performance
- Managing trading risk (position sizing, drawdown limits)
- Integrating with Bankr CLI or other DEX tools
Architecture
Self-Improvement Loop:
scan → evaluate → execute → log → review → patch params → repeat
Components:
- Token Scanner (
scan-tokens.py) — Finds trading opportunities - Risk Manager (
risk-manager.py) — Enforces position limits and risk rules - Trade Executor (
trade-executor.py) — Executes trades via Bankr CLI - Daily Review (
daily-review.py) — Analyzes performance and suggests improvements - Config File (
trading-config.json) — Central configuration for all parameters
Quick Start
1. Setup
Create workspace:
mkdir -p ~/trading-bot/{trades,reviews}
cd ~/trading-bot
Copy skill scripts:
cp ~/.openclaw/skills/defi-trading-engine/scripts/* .
2. Configure
Create trading-config.json:
{
"risk": {
"max_position_size_usd": 40,
"take_profit_pct": 4,
"stop_loss_pct": 8,
"max_active_positions": 5,
"max_daily_trades": 8,
"cooldown_minutes": 30,
"max_drawdown_pct": 15
},
"strategy": {
"type": "momentum_swing",
"entry_signal": "volume_spike_and_price_up",
"exit_signal": "take_profit_or_stop_loss",
"timeframe": "15min"
},
"bankr": {
"chain": "base",
"wallet": "trading-wallet",
"slippage_pct": 1.5
},
"data_sources": {
"use_coingecko_trending": true,
"use_dexscreener": true,
"min_liquidity_usd": 50000,
"min_volume_24h_usd": 100000
}
}
3. Setup Bankr (if needed)
See references/bankr-setup.md for Bankr CLI setup.
4. Run the Trading Loop
Manual execution:
# 1. Scan for opportunities
python3 scan-tokens.py --output candidates.json
# 2. Review candidates
cat candidates.json
# 3. Execute a trade (after risk check)
python3 trade-executor.py --symbol SOL --action buy --amount 40
# 4. Run daily review
python3 daily-review.py
Automated loop (cron):
# Run scanner every 30 minutes
*/30 * * * * cd ~/trading-bot && python3 scan-tokens.py --output candidates.json
# Run daily review at 23:00
0 23 * * * cd ~/trading-bot && python3 daily-review.py
Core Scripts
scan-tokens.py
Scans for trading opportunities using free APIs.
Data Sources:
- CoinGecko trending coins
- Volume spikes (24h volume vs 7d average)
- Price momentum (1h, 4h, 24h trends)
- Liquidity and market cap filters
Output (candidates.json):
[
{
"symbol": "SOL",
"name": "Solana",
"price": 145.5,
"volume_24h": 2800000000,
"volume_spike_ratio": 1.8,
"price_change_1h_pct": 2.5,
"price_change_24h_pct": 5.2,
"liquidity_usd": 850000000,
"score": 8.5,
"signals": ["trending", "volume_spike", "momentum_up"]
}
]
Usage:
python3 scan-tokens.py --output candidates.json --min-score 7.0
risk-manager.py
Enforces risk limits before every trade. Acts as the gatekeeper.
Checks:
- Position size within limit
- Max active positions not exceeded
- Daily trade limit not exceeded
- Cooldown period respected
- Max drawdown not breached
Usage:
python3 risk-manager.py --action check --symbol SOL --amount 40
Exit Codes:
0— Trade approved1— Trade denied (prints reason)
Example Output:
✅ Risk check passed
- Position size: $40 (limit: $40)
- Active positions: 3 (limit: 5)
- Daily trades: 5 (limit: 8)
- Cooldown: OK (35 minutes since last trade)
- Drawdown: 8.5% (limit: 15%)
trade-executor.py
Executes trades via Bankr CLI (or generic DEX interface).
Supported Actions:
buy— Market buysell— Market selllimit_buy— Limit order buylimit_sell— Limit order sellset_stop_loss— Stop-loss orderset_take_profit— Take-profit order
Usage:
# Market buy
python3 trade-executor.py --symbol SOL --action buy --amount 40
# Sell with stop-loss
python3 trade-executor.py --symbol SOL --action sell --stop-loss-pct 8
Trade Log (trades/YYYY-MM-DD.json):
[
{
"timestamp": "2026-03-13T15:45:00Z",
"symbol": "SOL",
"action": "buy",
"amount_usd": 40,
"price": 145.5,
"quantity": 0.275,
"tx_hash": "0xabc123...",
"status": "success",
"take_profit_price": 151.32,
"stop_loss_price": 133.86
}
]
daily-review.py
Analyzes trade history, calculates P&L, identifies weaknesses, and suggests parameter adjustments.
Metrics Calculated:
- Total P&L (realized + unrealized)
- Win rate (% of profitable trades)
- Average win vs average loss
- Sharpe ratio (if enough data)
- Max drawdown
- Best/worst trades
Output (reviews/review-YYYY-MM-DD.md):
# Trading Review — 2026-03-13
## Performance Summary
- **Total P&L:** +$42.50 (+5.3%)
- **Trades:** 8 (6 wins, 2 losses)
- **Win Rate:** 75%
- **Avg Win:** $9.20
- **Avg Loss:** -$5.80
- **Max Drawdown:** 8.5%
## Top Performers
1. SOL: +$18.50 (+12.7%)
2. LINK: +$12.20 (+8.1%)
## Worst Performers
1. UNI: -$8.50 (-5.7%)
## Pattern Analysis
- ✅ Momentum trades (4/5 profitable)
- ⚠️ Low liquidity tokens (1/3 profitable)
- ❌ Entries during high volatility (0/2 profitable)
## Recommended Adjustments
1. Increase `min_liquidity_usd` from $50k to $100k (low liquidity trades underperformed)
2. Add volatility filter (skip trades when VIX > 30)
3. Tighten stop-loss to 6% (avg loss exceeds target)
## Next Actions
- [ ] Update `trading-config.json` with new parameters
- [ ] Backtest on last 30 days with new rules
- [ ] Monitor performance for 1 week before further changes
Usage:
python3 daily-review.py --start-date 2026-03-01 --end-date 2026-03-13
Configuration Reference
Risk Parameters
| Parameter | Default | Purpose |
|---|---|---|
max_position_size_usd |
40 | Max $ per trade |
take_profit_pct |
4 | Exit when +4% gain |
stop_loss_pct |
8 | Exit when -8% loss |
max_active_positions |
5 | Max concurrent positions |
max_daily_trades |
8 | Max trades per day |
cooldown_minutes |
30 | Wait time between trades |
max_drawdown_pct |
15 | Stop trading if down 15% |
Strategy Parameters
Parameter
Options
Purpose
type
momentum_swing, mean_reversion, dca, asymmetric
Strategy type
entry_signal
volume_spike_and_price_up, oversold, breakout
Entry condition
exit_signal
take_profit_or_stop_loss, reversal, time_based
Exit condition
timeframe
5min, 15min, 1h, 4h
Trading timeframe
Bankr Integration
Parameter
Default
Purpose
chain
base
EVM chain (base, ethereum, polygon)
wallet
trading-wallet
Bankr wallet name
slippage_pct
1.5
Max acceptable slippage
Strategy Templates
| Parameter | Options | Purpose |
|---|---|---|
type |
momentum_swing, mean_reversion, dca, asymmetric |
Strategy type |
entry_signal |
volume_spike_and_price_up, oversold, breakout |
Entry condition |
exit_signal |
take_profit_or_stop_loss, reversal, time_based |
Exit condition |
timeframe |
5min, 15min, 1h, 4h |
Trading timeframe |
| Parameter | Default | Purpose |
|---|---|---|
chain |
base |
EVM chain (base, ethereum, polygon) |
wallet |
trading-wallet |
Bankr wallet name |
slippage_pct |
1.5 | Max acceptable slippage |
Strategy Templates
See references/strategies.md for detailed strategy implementations:
- DCA (Dollar-Cost Averaging) — Buy fixed amount on schedule
- Momentum Swing — Ride short-term momentum with tight stops
- Mean Reversion — Buy dips, sell rallies
- Asymmetric Bets — Small positions on high-upside opportunities
Risk Management Rules
The risk manager enforces these rules:
Position Sizing
Position size ≤ max_position_size_usd
Active Position Limit
count(open_positions) < max_active_positions
Daily Trade Limit
count(trades_today) < max_daily_trades
Cooldown Period
time_since_last_trade ≥ cooldown_minutes
Max Drawdown Circuit Breaker
if current_drawdown ≥ max_drawdown_pct:
halt_all_trading()
send_alert()
Position size ≤ max_position_size_usd
count(open_positions) < max_active_positions
Daily Trade Limit
count(trades_today) < max_daily_trades
Cooldown Period
time_since_last_trade ≥ cooldown_minutes
Max Drawdown Circuit Breaker
if current_drawdown ≥ max_drawdown_pct:
halt_all_trading()
send_alert()
count(trades_today) < max_daily_trades
time_since_last_trade ≥ cooldown_minutes
Max Drawdown Circuit Breaker
if current_drawdown ≥ max_drawdown_pct:
halt_all_trading()
send_alert()
if current_drawdown ≥ max_drawdown_pct:
halt_all_trading()
send_alert()
When max drawdown is hit, all trading stops until manually reset.
Self-Improvement Process
The bot learns from performance:
1. Daily Review
Run daily-review.py to analyze trades.
2. Pattern Recognition Identify which setups worked:
- Entry conditions with >70% win rate
- Tokens with consistent performance
- Timeframes with best risk/reward
3. Parameter Adjustment
Update trading-config.json based on findings:
- Tighten filters if win rate < 60%
- Adjust position size if drawdown too high
- Change timeframe if signals lag
4. Backtest Changes Test new parameters on historical data (manual or automated).
5. Monitor Run new parameters for 7 days, then review again.
Cycle: Weekly reviews → Parameter tweaks → Monitor → Repeat
Safety Features
✅ DO:
- Start with small position sizes ($40 default)
- Use stop-losses on every trade
- Respect cooldown periods (avoid overtrading)
- Run daily reviews to catch bad patterns early
- Keep max drawdown limit low (15% default)
- Paper trade first (simulate without real funds)
❌ DON'T:
- Disable risk manager checks
- Increase position size without testing
- Remove stop-losses ("this time is different")
- Trade during network congestion (high gas fees)
- Ignore max drawdown signals
- Use leverage (this engine is spot-only by design)
Monitoring & Alerts
Track bot health:
Check active positions:
jq '.[] | select(.status == "open")' trades/*.json
Check today's P&L:
python3 daily-review.py --start-date $(date +%Y-%m-%d) --end-date $(date +%Y-%m-%d)
Alert on max drawdown:
# Add to cron (every hour)
python3 risk-manager.py --action check_drawdown && echo "Trading halted: max drawdown exceeded"
Troubleshooting
Problem: Risk manager denies all trades
Solution: Check trading-config.json limits. May have hit daily trade limit or max drawdown.
Problem: Trades execute but P&L is negative
Solution: Run daily-review.py to identify losing patterns. Tighten entry filters or adjust stop-loss.
Problem: Bankr CLI errors
Solution: Check wallet balance, network connection, and gas fees. See references/bankr-setup.md.
Problem: Scanner returns no candidates
Solution: Lower min_score threshold or relax liquidity filters.
Advanced Features
Paper Trading Mode
Test strategies without real funds:
{
"mode": "paper",
"paper_balance_usd": 1000
}
All trades simulate execution, no real transactions.
Multi-Strategy Support
Run multiple strategies in parallel:
{
"strategies": [
{
"name": "momentum",
"allocation_pct": 60,
"config": { ... }
},
{
"name": "mean_reversion",
"allocation_pct": 40,
"config": { ... }
}
]
}
Backtesting
Test parameters on historical data (requires historical price data):
python3 backtest.py --start 2026-01-01 --end 2026-03-01 --config trading-config.json
(Backtest script not included — implement based on your data source)
Resources
- Bankr Setup:
references/bankr-setup.md
- Strategy Templates:
references/strategies.md
- CoinGecko API: https://www.coingecko.com/en/api/documentation
- Base Chain Docs: https://docs.base.org
references/bankr-setup.mdreferences/strategies.mdVersion: 1.0 Last Updated: 2026-03-13 Security Note: Store API keys and wallet private keys securely. Never commit to Git.
正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。