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:
CODEBLOCK0
Components:
- 1. 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:
CODEBLOCK1
Copy skill scripts:
CODEBLOCK2
2. Configure
Create trading-config.json:
CODEBLOCK3
3. Setup Bankr (if needed)
See references/bankr-setup.md for Bankr CLI setup.
4. Run the Trading Loop
Manual execution:
CODEBLOCK4
Automated loop (cron):
CODEBLOCK5
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):
CODEBLOCK6
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:
CODEBLOCK8
Exit Codes:
- -
0 — Trade approved - INLINECODE9 — 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 buy - INLINECODE11 — Market sell
- INLINECODE12 — Limit order buy
- INLINECODE13 — Limit order sell
- INLINECODE14 — Stop-loss order
- INLINECODE15 — Take-profit order
Usage:
CODEBLOCK10
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):
INLINECODE18
Usage:
python3 daily-review.py --start-date 2026-03-01 --end-date 2026-03-13
Configuration Reference
Risk Parameters
| Parameter | Default | Purpose |
|---|
| INLINECODE19 | 40 | Max $ per trade |
| INLINECODE20 |
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 |
|---|
| INLINECODE26 | INLINECODE27 , mean_reversion, dca, INLINECODE30 | Strategy type |
| INLINECODE31 |
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 |
|---|
| INLINECODE44 | INLINECODE45 | EVM chain (base, ethereum, polygon) |
| INLINECODE46 |
trading-wallet | Bankr wallet name |
|
slippage_pct | 1.5 | Max acceptable slippage |
Strategy Templates
See references/strategies.md for detailed strategy implementations:
- 1. 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
CODEBLOCK14
Active Position Limit
CODEBLOCK15
Daily Trade Limit
CODEBLOCK16
Cooldown Period
CODEBLOCK17
Max Drawdown Circuit Breaker
CODEBLOCK18
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:
CODEBLOCK19
Check today's P&L:
CODEBLOCK20
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:
CODEBLOCK22
All trades simulate execution, no real transactions.
Multi-Strategy Support
Run multiple strategies in parallel:
CODEBLOCK23
Backtesting
Test parameters on historical data (requires historical price data):
CODEBLOCK24
(Backtest script not included — implement based on your data source)
Resources
- - Bankr Setup: INLINECODE56
- Strategy Templates: INLINECODE57
- CoinGecko API: https://www.coingecko.com/en/api/documentation
- Base Chain Docs: https://docs.base.org
Version: 1.0
Last Updated: 2026-03-13
Security Note: Store API keys and wallet private keys securely. Never commit to Git.
DeFi 交易引擎
具备自我改进审查系统的自主DeFi交易机器人。扫描机会、执行交易、记录表现,并从错误中学习。
使用场景
在以下情况应用此技能:
- - 在Base或其他EVM链上设置自动化加密货币交易
- 构建自我改进的交易系统
- 实施系统性DeFi交易策略
- 执行定投、动量或均值回归策略
- 审查和优化交易表现
- 管理交易风险(仓位规模、回撤限制)
- 与Bankr CLI或其他DEX工具集成
架构
自我改进循环:
扫描 → 评估 → 执行 → 记录 → 审查 → 调整参数 → 重复
组件:
- 1. 代币扫描器(scan-tokens.py)— 发现交易机会
- 风险管理器(risk-manager.py)— 执行仓位限制和风险规则
- 交易执行器(trade-executor.py)— 通过Bankr CLI执行交易
- 每日审查(daily-review.py)— 分析表现并提出改进建议
- 配置文件(trading-config.json)— 所有参数的集中配置
快速开始
1. 设置
创建工作空间:
bash
mkdir -p ~/trading-bot/{trades,reviews}
cd ~/trading-bot
复制技能脚本:
bash
cp ~/.openclaw/skills/defi-trading-engine/scripts/* .
2. 配置
创建 trading-config.json:
json
{
risk: {
maxpositionsize_usd: 40,
takeprofitpct: 4,
stoplosspct: 8,
maxactivepositions: 5,
maxdailytrades: 8,
cooldown_minutes: 30,
maxdrawdownpct: 15
},
strategy: {
type: momentum_swing,
entrysignal: volumespikeandprice_up,
exitsignal: takeprofitorstop_loss,
timeframe: 15min
},
bankr: {
chain: base,
wallet: trading-wallet,
slippage_pct: 1.5
},
data_sources: {
usecoingeckotrending: true,
use_dexscreener: true,
minliquidityusd: 50000,
minvolume24h_usd: 100000
}
}
3. 设置Bankr(如需)
参见 references/bankr-setup.md 了解Bankr CLI设置。
4. 运行交易循环
手动执行:
bash
1. 扫描机会
python3 scan-tokens.py --output candidates.json
2. 审查候选代币
cat candidates.json
3. 执行交易(风险检查后)
python3 trade-executor.py --symbol SOL --action buy --amount 40
4. 运行每日审查
python3 daily-review.py
自动循环(cron):
bash
每30分钟运行扫描器
/30 * cd ~/trading-bot && python3 scan-tokens.py --output candidates.json
23:00运行每日审查
0 23
* cd ~/trading-bot && python3 daily-review.py
核心脚本
scan-tokens.py
使用免费API扫描交易机会。
数据源:
- - CoinGecko热门代币
- 成交量激增(24小时成交量 vs 7日均值)
- 价格动量(1小时、4小时、24小时趋势)
- 流动性和市值过滤器
输出(candidates.json):
json
[
{
symbol: SOL,
name: Solana,
price: 145.5,
volume_24h: 2800000000,
volumespikeratio: 1.8,
pricechange1h_pct: 2.5,
pricechange24h_pct: 5.2,
liquidity_usd: 850000000,
score: 8.5,
signals: [trending, volumespike, momentumup]
}
]
用法:
bash
python3 scan-tokens.py --output candidates.json --min-score 7.0
risk-manager.py
在每笔交易前执行风险限制。充当守门员角色。
检查项:
- - 仓位规模在限制内
- 未超过最大活跃仓位数
- 未超过每日交易限制
- 遵守冷却期
- 未突破最大回撤
用法:
bash
python3 risk-manager.py --action check --symbol SOL --amount 40
退出码:
示例输出:
✅ 风险检查通过
- 仓位规模:$40(限制:$40)
- 活跃仓位:3(限制:5)
- 每日交易:5(限制:8)
- 冷却期:正常(距上次交易35分钟)
- 回撤:8.5%(限制:15%)
trade-executor.py
通过Bankr CLI(或通用DEX接口)执行交易。
支持的操作:
- - buy — 市价买入
- sell — 市价卖出
- limitbuy — 限价买入
- limitsell — 限价卖出
- setstoploss — 止损订单
- settakeprofit — 止盈订单
用法:
bash
市价买入
python3 trade-executor.py --symbol SOL --action buy --amount 40
带止损卖出
python3 trade-executor.py --symbol SOL --action sell --stop-loss-pct 8
交易日志(trades/YYYY-MM-DD.json):
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,
takeprofitprice: 151.32,
stoplossprice: 133.86
}
]
daily-review.py
分析交易历史、计算盈亏、识别弱点并提出参数调整建议。
计算的指标:
- - 总盈亏(已实现+未实现)
- 胜率(盈利交易百分比)
- 平均盈利 vs 平均亏损
- 夏普比率(数据充足时)
- 最大回撤
- 最佳/最差交易
输出(reviews/review-YYYY-MM-DD.md):
markdown
交易审查 — 2026-03-13
表现总结
- - 总盈亏: +$42.50(+5.3%)
- 交易次数: 8(6胜,2负)
- 胜率: 75%
- 平均盈利: $9.20
- 平均亏损: -$5.80
- 最大回撤: 8.5%
最佳表现
- 1. SOL:+$18.50(+12.7%)
- LINK:+$12.20(+8.1%)
最差表现
- 1. UNI:-$8.50(-5.7%)
模式分析
- - ✅ 动量交易(4/5盈利)
- ⚠️ 低流动性代币(1/3盈利)
- ❌ 高波动期间入场(0/2盈利)
推荐调整
- 1. 将 minliquidityusd 从$50k提高到$100k(低流动性交易表现不佳)
- 添加波动率过滤器(VIX > 30时跳过交易)
- 收紧止损至6%(平均亏损超过目标)
后续行动
- - [ ] 使用新参数更新 trading-config.json
- [ ] 用新规则回测过去30天
- [ ] 监控表现1周后再做进一步更改
用法:
bash
python3 daily-review.py --start-date 2026-03-01 --end-date 2026-03-13
配置参考
风险参数
| 参数 | 默认值 | 用途 |
|---|
| maxpositionsize_usd | 40 |
每笔交易最大