Openclaw Quant Skill
by @zhenstaff
Professional quantitative trading system for cryptocurrency - backtesting, paper trading, live trading, and strategy optimization
clawhub install openclaw-quant-skillπ About This Skill
name: openclaw-quant description: Professional quantitative trading system for cryptocurrency - backtesting, paper trading, live trading, and strategy optimization tags: [quant, trading, backtest, crypto, strategy, optimization, bitcoin, trading-bot, algorithmic-trading] version: 0.1.0
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
clawhub install openclaw-quant
Step 2: Clone & Setup the Project
# Clone repository
git clone https://github.com/ZhenRobotics/openclaw-quant.git ~/openclaw-quant
cd ~/openclaw-quantInstall dependencies
pip install -r requirements.txtSet API keys (optional for backtesting)
export BINANCE_API_KEY="your-key"
export BINANCE_API_SECRET="your-secret"
Step 3: Verify Installation
cd ~/openclaw-quant
python -m openclaw_quant --help
Core Features
When to Use This Skill
AUTO-TRIGGER when user's message contains:
backtest, trading strategy, quant, cryptocurrency trading, optimize strategyTRIGGER EXAMPLES:
DO NOT USE when:
Quick Start Examples
Example 1: Simple Moving Average Strategy
from openclaw_quant import Strategy, Backtestclass MAStrategy(Strategy):
# Parameters (can be optimized)
fast_period = 10
slow_period = 30
def init(self):
# Vectorized indicator calculation
self.fast_ma = self.I(SMA, self.data.Close, self.fast_period)
self.slow_ma = self.I(SMA, self.data.Close, self.slow_period)
def next(self):
# Event-driven logic
if self.fast_ma[-1] > self.slow_ma[-1]:
if not self.position:
self.buy()
else:
if self.position:
self.sell()
Backtest
bt = Backtest(MAStrategy, data, cash=10000, commission=0.001)
result = bt.run()
print(result)
result.plot()
Example 2: RSI Mean Reversion
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()
Example 3: Parameter Optimization
# Optimize parameters automatically
result = bt.optimize(
fast_period=range(5, 20, 2),
slow_period=range(20, 60, 5),
maximize='sharpe_ratio' # or 'total_return', 'profit_factor'
)print(f"Best parameters: {result.best_params}")
print(f"Sharpe Ratio: {result.sharpe_ratio:.2f}")
Example 4: Paper Trading
from openclaw_quant import LiveTradingPaper trading with real-time data
live = LiveTrading(
strategy=MAStrategy,
exchange='binance',
symbol='BTC/USDT',
paper=True # Simulation mode
)live.run()
Example 5: Live Trading
# Real trading (use with caution!)
live = LiveTrading(
strategy=MAStrategy,
exchange='binance',
symbol='BTC/USDT',
paper=False, # Real mode
api_key=os.getenv('BINANCE_API_KEY'),
api_secret=os.getenv('BINANCE_API_SECRET')
)live.run()
Agent Usage Guide
Command-Line Interface
# Backtest a strategy
openclaw-quant backtest --strategy ma_cross --symbol BTCUSDT --days 365Optimize parameters
openclaw-quant optimize --strategy rsi --symbol ETHUSDT --metric sharpe_ratioPaper trading
openclaw-quant paper --strategy ma_cross --symbol BTCUSDTLive trading
openclaw-quant live --strategy ma_cross --symbol BTCUSDT --confirmView results
openclaw-quant results --backtest-id abc123
Natural Language (via OpenClaw Agent)
Agent can understand requests like:
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 2. RSI Mean Reversion: Buy oversold, sell overbought 3. MACD Momentum: MACD line and signal crossover 4. Bollinger Bounce: Trade Bollinger band touches 5. Breakout: Support/resistance breakouts 6. Grid Trading: Buy low, sell high in range 7. DCA (Dollar Cost Average): Regular accumulation 8. Mean Reversion: Statistical arbitrage
Technical Indicators
50+ indicators available via self.I() method:
Trend Indicators:
Momentum Indicators:
Volatility Indicators:
Volume Indicators:
Risk Management
Built-in risk management features:
class MyStrategy(Strategy):
def init(self):
# Set risk parameters
self.risk_per_trade = 0.02 # 2% of capital
self.stop_loss = 0.05 # 5% stop loss
self.take_profit = 0.10 # 10% take profit self.ma = self.I(SMA, self.data.Close, 20)
def next(self):
if self.ma[-1] > self.data.Close[-1]:
if not self.position:
# Calculate position size based on risk
size = self.calculate_position_size(
risk=self.risk_per_trade,
stop_loss=self.stop_loss
)
self.buy(size=size)
self.set_stop_loss(self.stop_loss)
self.set_take_profit(self.take_profit)
Data Sources
Supports multiple data sources:
1. Exchange APIs: Binance, OKX, Bybit, etc. (via ccxt) 2. CSV Files: Load historical data from files 3. Database: PostgreSQL, SQLite for caching 4. Real-time WebSocket: Live market data
# Example: Load data from Binance
from openclaw_quant import DataFetcherfetcher = DataFetcher('binance')
data = fetcher.fetch_candles(
symbol='BTC/USDT',
timeframe='1h',
since='2023-01-01',
limit=1000
)
Configuration
Example configuration file (config.yaml):
backtest:
initial_capital: 10000
commission: 0.001 # 0.1%
slippage: 0.0005 # 0.05%strategy:
name: ma_cross
parameters:
fast_period: 10
slow_period: 30
exchange:
name: binance
testnet: false
risk:
max_position_size: 0.1 # 10% of capital
max_drawdown: 0.2 # Stop if 20% drawdown
daily_loss_limit: 0.05 # Stop if 5% daily loss
notification:
telegram:
enabled: true
bot_token: "your-token"
chat_id: "your-chat-id"
Project Structure
openclaw-quant/
βββ src/
β βββ openclaw_quant/
β β βββ __init__.py
β β βββ strategy.py # Strategy base class
β β βββ backtest.py # Backtest engine
β β βββ live.py # Live trading engine
β β βββ broker.py # Order execution
β β βββ data.py # Data fetching
β β βββ indicators.py # Technical indicators
β β βββ optimizer.py # Parameter optimization
β β βββ metrics.py # Performance metrics
β β βββ risk.py # Risk management
β βββ strategies/
β βββ ma_cross.py
β βββ rsi.py
β βββ ...
βββ examples/
β βββ backtest_example.py
β βββ optimization_example.py
β βββ paper_trading_example.py
βββ tests/
βββ docs/
βββ requirements.txt
βββ README.md
Requirements
Python >= 3.9
pandas >= 2.0.0
numpy >= 1.24.0
ccxt >= 4.0.0
optuna >= 3.0.0
matplotlib >= 3.7.0
pydantic >= 2.0.0
Troubleshooting
Issue 1: API Connection Error
Error: ccxt.NetworkError or connection timeout
Solution:
# Check internet connection
Verify API keys are correct
Use testnet for testing:
exchange = ccxt.binance({'enableRateLimit': True, 'options': {'defaultType': 'future', 'testnet': True}})
Issue 2: Insufficient Data
Error: Not enough candles for strategy
Solution:
# Increase warmup period
bt = Backtest(strategy, data, warmup=100) # Skip first 100 candlesOr fetch more historical data
data = fetcher.fetch_candles(symbol='BTC/USDT', limit=5000)
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
Paper Trading
Live Trading
Performance Tips
1. Vectorization: Use self.I() for indicators (computed once)
2. Data Caching: Cache historical data to avoid repeated API calls
3. Optimization: Use Bayesian optimization, not grid search
4. Parallel Backtesting: Test multiple symbols simultaneously
5. WebSocket: Use WebSocket for real-time data (faster than REST)
Documentation
~/openclaw-quant/QUICKSTART.md~/openclaw-quant/docs/API.md~/openclaw-quant/docs/STRATEGIES.md~/openclaw-quant/README.mdRoadmap
Version 0.1.0 (Current)
Version 0.2.0
Version 0.3.0
Version 1.0.0
Cost
License
MIT License - Free for personal and commercial use
Support
Agent Behavior Guidelines
When using this skill, agents should:
DO:
DON'T:
Status: Under Development (Alpha)
Author: @ZhenStaff
Last Updated: 2026-03-05
βοΈ Configuration
Example configuration file (config.yaml):
backtest:
initial_capital: 10000
commission: 0.001 # 0.1%
slippage: 0.0005 # 0.05%strategy:
name: ma_cross
parameters:
fast_period: 10
slow_period: 30
exchange:
name: binance
testnet: false
risk:
max_position_size: 0.1 # 10% of capital
max_drawdown: 0.2 # Stop if 20% drawdown
daily_loss_limit: 0.05 # Stop if 5% daily loss
notification:
telegram:
enabled: true
bot_token: "your-token"
chat_id: "your-chat-id"
π Tips & Best Practices
Issue 1: API Connection Error
Error: ccxt.NetworkError or connection timeout
Solution:
# Check internet connection
Verify API keys are correct
Use testnet for testing:
exchange = ccxt.binance({'enableRateLimit': True, 'options': {'defaultType': 'future', 'testnet': True}})
Issue 2: Insufficient Data
Error: Not enough candles for strategy
Solution:
# Increase warmup period
bt = Backtest(strategy, data, warmup=100) # Skip first 100 candlesOr fetch more historical data
data = fetcher.fetch_candles(symbol='BTC/USDT', limit=5000)
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
)