Quantitative Trading Skill
Professional quantitative trading system designed for cryptocurrency markets, featuring backtesting, paper trading, live trading, and advanced strategy optimization.
Installation
Step 1: Install the Skill
CODEBLOCK0
Step 2: Clone & Setup the Project
CODEBLOCK1
Step 3: Verify Installation
CODEBLOCK2
Core Features
- - Backtesting Engine: Test strategies on historical data with realistic simulation
- Paper Trading: Real-time simulation with live market data
- Live Trading: Automated trading on real exchanges (Binance, OKX, etc.)
- Strategy Optimization: Parameter optimization using Bayesian methods
- Technical Indicators: 50+ built-in indicators (MA, RSI, MACD, Bollinger, etc.)
- Risk Management: Position sizing, stop-loss, take-profit
- Performance Analytics: Sharpe ratio, max drawdown, win rate, profit factor
- Multi-Exchange Support: Via ccxt library (100+ exchanges)
When to Use This Skill
AUTO-TRIGGER when user's message contains:
- - Keywords:
backtest, trading strategy, quant, cryptocurrency trading, INLINECODE4 - Requests like: "test this trading strategy", "backtest MA cross", "paper trade bitcoin"
- Strategy descriptions: "buy when RSI < 30, sell when RSI > 70"
- Performance questions: "what's the sharpe ratio", "calculate max drawdown"
TRIGGER EXAMPLES:
- - "Backtest a moving average crossover strategy on Bitcoin"
- "Optimize RSI parameters for the last 6 months"
- "Start paper trading with my momentum strategy"
- "What's the win rate of this strategy?"
DO NOT USE when:
- - Only portfolio tracking (use portfolio-tracker skill)
- Only price alerts (use price-alert skill)
- General crypto news or information
Quick Start Examples
Example 1: Simple Moving Average Strategy
CODEBLOCK3
Example 2: RSI Mean Reversion
CODEBLOCK4
Example 3: Parameter Optimization
CODEBLOCK5
Example 4: Paper Trading
CODEBLOCK6
Example 5: Live Trading
CODEBLOCK7
Agent Usage Guide
Command-Line Interface
CODEBLOCK8
Natural Language (via OpenClaw Agent)
Agent can understand requests like:
- - "Backtest a moving average crossover on Bitcoin for the last year"
- "Optimize RSI parameters to maximize Sharpe ratio"
- "Start paper trading with 10k USDT using my momentum strategy"
- "Show me the performance metrics of the last backtest"
- "What's the max drawdown of my live trading account?"
Performance Metrics
The system calculates comprehensive performance metrics:
| Metric | Description |
|---|
| Total Return | Overall profit/loss percentage |
| Annualized Return |
Return extrapolated to one year |
|
Sharpe Ratio | Risk-adjusted return (higher is better) |
|
Sortino Ratio | Downside risk-adjusted return |
|
Max Drawdown | Largest peak-to-trough decline |
|
Win Rate | Percentage of profitable trades |
|
Profit Factor | Gross profit / Gross loss |
|
Calmar Ratio | Return / Max drawdown |
|
Average Win/Loss | Mean profit/loss per trade |
|
Expectancy | Expected value per trade |
Built-in Strategies
The system includes several ready-to-use strategies:
- 1. MA Cross: Moving average crossover
- RSI Mean Reversion: Buy oversold, sell overbought
- MACD Momentum: MACD line and signal crossover
- Bollinger Bounce: Trade Bollinger band touches
- Breakout: Support/resistance breakouts
- Grid Trading: Buy low, sell high in range
- DCA (Dollar Cost Average): Regular accumulation
- Mean Reversion: Statistical arbitrage
Technical Indicators
50+ indicators available via self.I() method:
Trend Indicators:
- - SMA, EMA, WMA, DEMA, TEMA
- MACD, ADX, Aroon, Supertrend
Momentum Indicators:
- - RSI, Stochastic, CCI, Williams %R
- ROC (Rate of Change), Momentum
Volatility Indicators:
- - Bollinger Bands, ATR, Keltner Channels
- Standard Deviation, Historical Volatility
Volume Indicators:
- - OBV, Volume SMA, MFI, VWAP
- Accumulation/Distribution, CMF
Risk Management
Built-in risk management features:
CODEBLOCK9
Data Sources
Supports multiple data sources:
- 1. Exchange APIs: Binance, OKX, Bybit, etc. (via ccxt)
- CSV Files: Load historical data from files
- Database: PostgreSQL, SQLite for caching
- Real-time WebSocket: Live market data
CODEBLOCK10
Configuration
Example configuration file (config.yaml):
CODEBLOCK11
Project Structure
CODEBLOCK12
Requirements
CODEBLOCK13
Troubleshooting
Issue 1: API Connection Error
Error: ccxt.NetworkError or connection timeout
Solution:
CODEBLOCK14
Issue 2: Insufficient Data
Error: Not enough candles for strategy
Solution:
CODEBLOCK15
Issue 3: Optimization Takes Too Long
Solution:
# Reduce search space
result = bt.optimize(
fast_period=range(5, 20, 5), # Larger step
slow_period=range(20, 60, 10),
max_tries=50 # Limit iterations
)
Safety Guidelines
Backtesting
- - Always test on historical data first
- Use realistic commission and slippage
- Beware of overfitting
- Walk-forward validation recommended
Paper Trading
- - Test for at least 1-2 weeks
- Monitor slippage and fills
- Check strategy behavior in different market conditions
Live Trading
- - Start with small capital
- Set strict risk limits
- Monitor continuously for first week
- Have emergency stop mechanism
- Never risk more than you can afford to lose
Performance Tips
- 1. Vectorization: Use
self.I() for indicators (computed once) - Data Caching: Cache historical data to avoid repeated API calls
- Optimization: Use Bayesian optimization, not grid search
- Parallel Backtesting: Test multiple symbols simultaneously
- WebSocket: Use WebSocket for real-time data (faster than REST)
Documentation
- - GitHub: https://github.com/ZhenRobotics/openclaw-quant
- Quick Start: INLINECODE9
- API Reference: INLINECODE10
- Strategy Guide: INLINECODE11
- Full README: INLINECODE12
Roadmap
Version 0.1.0 (Current)
- - Basic backtesting engine
- Simple strategies (MA, RSI)
- Binance support
Version 0.2.0
- - Paper trading
- Parameter optimization
- More indicators
Version 0.3.0
- - Live trading
- Multi-exchange support
- Advanced risk management
Version 1.0.0
- - Production-ready
- Web dashboard
- Strategy marketplace
Cost
- - Development: Free and open source (MIT License)
- Data: Free (using exchange APIs)
- Trading Fees: Varies by exchange (typically 0.1%)
- API Costs: Free tier available on most exchanges
License
MIT License - Free for personal and commercial use
Support
- - Issues: https://github.com/ZhenRobotics/openclaw-quant/issues
- Discussions: https://github.com/ZhenRobotics/openclaw-quant/discussions
- ClawHub: https://clawhub.ai/ZhenStaff/openclaw-quant
Agent Behavior Guidelines
When using this skill, agents should:
DO:
- - Check if project is installed before use
- Warn about risks in live trading mode
- Validate strategy parameters
- Show clear performance metrics
- Explain optimization results
DON'T:
- - Execute live trades without explicit confirmation
- Recommend specific trading strategies
- Guarantee profits or returns
- Ignore risk warnings
- Make financial advice
Status: Under Development (Alpha)
Author: @ZhenStaff
Last Updated: 2026-03-05
量化交易技能
专为加密货币市场设计的专业量化交易系统,具备回测、模拟交易、实盘交易和高级策略优化功能。
安装
步骤1:安装技能
bash
clawhub install quant-analyst
步骤2:克隆并设置项目
bash
克隆仓库
git clone https://github.com/ZhenRobotics/openclaw-quant.git ~/openclaw-quant
cd ~/openclaw-quant
安装依赖
pip install -r requirements.txt
设置API密钥(回测时可选)
export BINANCE
APIKEY=your-key
export BINANCE
APISECRET=your-secret
步骤3:验证安装
bash
cd ~/openclaw-quant
python -m openclaw_quant --help
核心功能
- - 回测引擎:在历史数据上以真实模拟方式测试策略
- 模拟交易:使用实时市场数据进行实时模拟
- 实盘交易:在真实交易所(币安、OKX等)上自动交易
- 策略优化:使用贝叶斯方法进行参数优化
- 技术指标:50+内置指标(MA、RSI、MACD、布林带等)
- 风险管理:仓位管理、止损、止盈
- 绩效分析:夏普比率、最大回撤、胜率、盈亏比
- 多交易所支持:通过ccxt库(100+交易所)
何时使用此技能
当用户消息包含以下内容时自动触发:
- - 关键词:回测、交易策略、量化、加密货币交易、优化策略
- 请求如:测试这个交易策略、回测MA交叉、模拟交易比特币
- 策略描述:当RSI < 30时买入,当RSI > 70时卖出
- 绩效问题:夏普比率是多少、计算最大回撤
触发示例:
- - 在比特币上回测移动平均线交叉策略
- 优化过去6个月的RSI参数
- 用我的动量策略开始模拟交易
- 这个策略的胜率是多少?
不要使用当:
- - 仅需投资组合跟踪(使用portfolio-tracker技能)
- 仅需价格提醒(使用price-alert技能)
- 一般加密货币新闻或信息
快速入门示例
示例1:简单移动平均线策略
python
from openclaw_quant import Strategy, Backtest
class MAStrategy(Strategy):
# 参数(可优化)
fast_period = 10
slow_period = 30
def init(self):
# 向量化指标计算
self.fastma = self.I(SMA, self.data.Close, self.fastperiod)
self.slowma = self.I(SMA, self.data.Close, self.slowperiod)
def next(self):
# 事件驱动逻辑
if self.fastma[-1] > self.slowma[-1]:
if not self.position:
self.buy()
else:
if self.position:
self.sell()
回测
bt = Backtest(MAStrategy, data, cash=10000, commission=0.001)
result = bt.run()
print(result)
result.plot()
示例2:RSI均值回归
python
class RSIStrategy(Strategy):
rsi_period = 14
oversold = 30
overbought = 70
def init(self):
self.rsi = self.I(RSI, self.data.Close, self.rsi_period)
def next(self):
if self.rsi[-1] < self.oversold:
if not self.position:
self.buy()
elif self.rsi[-1] > self.overbought:
if self.position:
self.sell()
bt = Backtest(RSIStrategy, data, cash=10000)
result = bt.run()
示例3:参数优化
python
自动优化参数
result = bt.optimize(
fast_period=range(5, 20, 2),
slow_period=range(20, 60, 5),
maximize=sharpe
ratio # 或 totalreturn, profit_factor
)
print(f最佳参数:{result.best_params})
print(f夏普比率:{result.sharpe_ratio:.2f})
示例4:模拟交易
python
from openclaw_quant import LiveTrading
使用实时数据进行模拟交易
live = LiveTrading(
strategy=MAStrategy,
exchange=binance,
symbol=BTC/USDT,
paper=True # 模拟模式
)
live.run()
示例5:实盘交易
python
真实交易(谨慎使用!)
live = LiveTrading(
strategy=MAStrategy,
exchange=binance,
symbol=BTC/USDT,
paper=False, # 真实模式
api
key=os.getenv(BINANCEAPI_KEY),
api
secret=os.getenv(BINANCEAPI_SECRET)
)
live.run()
代理使用指南
命令行界面
bash
回测策略
openclaw-quant backtest --strategy ma_cross --symbol BTCUSDT --days 365
优化参数
openclaw-quant optimize --strategy rsi --symbol ETHUSDT --metric sharpe_ratio
模拟交易
openclaw-quant paper --strategy ma_cross --symbol BTCUSDT
实盘交易
openclaw-quant live --strategy ma_cross --symbol BTCUSDT --confirm
查看结果
openclaw-quant results --backtest-id abc123
自然语言(通过OpenClaw代理)
代理可以理解如下请求:
- - 回测比特币过去一年的移动平均线交叉策略
- 优化RSI参数以最大化夏普比率
- 用1万USDT开始模拟交易,使用我的动量策略
- 显示上次回测的绩效指标
- 我的实盘交易账户的最大回撤是多少?
绩效指标
系统计算全面的绩效指标:
外推至一年的收益率 |
|
夏普比率 | 风险调整后收益(越高越好) |
|
索提诺比率 | 下行风险调整后收益 |
|
最大回撤 | 从峰值到谷底的最大跌幅 |
|
胜率 | 盈利交易百分比 |
|
盈亏比 | 总盈利 / 总亏损 |
|
卡玛比率 | 收益率 / 最大回撤 |
|
平均盈亏 | 每笔交易的平均盈亏 |
|
期望值 | 每笔交易的期望值 |
内置策略
系统包含多个即用型策略:
- 1. MA交叉:移动平均线交叉
- RSI均值回归:超卖买入,超买卖出
- MACD动量:MACD线和信号线交叉
- 布林带反弹:交易布林带触及
- 突破:支撑/阻力突破
- 网格交易:区间内低买高卖
- DCA(定投):定期积累
- 均值回归:统计套利
技术指标
通过self.I()方法提供50+指标:
趋势指标:
- - SMA、EMA、WMA、DEMA、TEMA
- MACD、ADX、Aroon、Supertrend
动量指标:
- - RSI、随机指标、CCI、威廉%R
- ROC(变化率)、动量
波动率指标:
- - 布林带、ATR、凯尔特纳通道
- 标准差、历史波动率
成交量指标:
- - OBV、成交量SMA、MFI、VWAP
- 累积/派发、CMF
风险管理
内置风险管理功能:
python
class MyStrategy(Strategy):
def init(self):
# 设置风险参数
self.riskpertrade = 0.02 # 资金的2%
self.stop_loss = 0.05 # 5%止损
self.take_profit = 0.10 # 10%止盈
self.ma = self.I(SMA, self.data.Close, 20)
def next(self):
if self.ma[-1] > self.data.Close[-1]:
if not self.position:
# 基于风险计算仓位大小
size = self.calculatepositionsize(
risk=self.riskpertrade,
stoploss=self.stoploss
)
self.buy(size=size)
self.setstoploss(self.stop_loss)
self.settakeprofit(self.take_profit)
数据源
支持多种数据