Back to skills
SkillHub ClubShip Full StackFull Stack

crypto-levels

Analyze cryptocurrency support and resistance levels. Use when users ask about crypto price analysis, support/resistance levels, technical analysis for BTC, ETH, or other cryptocurrencies. Provides current price, key levels, and trading insights for crypto pairs like BTC-USDT, ETH-USDT.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
3,126
Hot score
99
Updated
March 20, 2026
Overall rating
C4.6
Composite score
4.6
Best-practice grade
B75.6

Install command

npx @skill-hub/cli install openclaw-skills-crypto-levels

Repository

openclaw/skills

Skill path: skills/362224222/crypto-levels

Analyze cryptocurrency support and resistance levels. Use when users ask about crypto price analysis, support/resistance levels, technical analysis for BTC, ETH, or other cryptocurrencies. Provides current price, key levels, and trading insights for crypto pairs like BTC-USDT, ETH-USDT.

Open repository

Best for

Primary workflow: Ship Full Stack.

Technical facets: Full Stack.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: openclaw.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install crypto-levels into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/openclaw/skills before adding crypto-levels to shared team environments
  • Use crypto-levels for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: crypto-levels
description: Analyze cryptocurrency support and resistance levels. Use when users ask about crypto price analysis, support/resistance levels, technical analysis for BTC, ETH, or other cryptocurrencies. Provides current price, key levels, and trading insights for crypto pairs like BTC-USDT, ETH-USDT.
---

# Crypto Levels Analyzer

## Quick Start

### Basic Usage

Ask about any cryptocurrency pair:

```
BTC-USDT 支撑位压力位
ETH-USDT 技术分析
SOL-USDT 当前价格和关键水平
```

### What You'll Get

- **Current Price**: Real-time price data
- **Support Levels**: Key price levels where buying interest may emerge
- **Resistance Levels**: Key price levels where selling pressure may increase
- **Technical Analysis**: Brief market sentiment and trading insights

## Supported Pairs

### Major Cryptocurrencies
- **BTC-USDT** - Bitcoin
- **ETH-USDT** - Ethereum
- **SOL-USDT** - Solana
- **BNB-USDT** - Binance Coin
- **XRP-USDT** - Ripple
- **ADA-USDT** - Cardano
- **DOGE-USDT** - Dogecoin
- **DOT-USDT** - Polkadot

### Altcoins
- **AVAX-USDT** - Avalanche
- **MATIC-USDT** - Polygon
- **LINK-USDT** - Chainlink
- **UNI-USDT** - Uniswap
- **ATOM-USDT** - Cosmos
- **LTC-USDT** - Litecoin
- **BCH-USDT** - Bitcoin Cash
- **XLM-USDT** - Stellar

*Note: Full list in [SUPPORTED_PAIRS.md](references/SUPPORTED_PAIRS.md)*

## How It Works

### Data Sources

The skill uses multiple data sources to calculate support and resistance levels:

1. **Price Data**: Current market price
2. **Historical Data**: Recent price action (24h, 7d, 30d)
3. **Volume Data**: Trading volume analysis
4. **Technical Indicators**: Moving averages, RSI, etc.

### Level Calculation

#### Support Levels (Buying Interest)
- **Primary Support**: Recent low + volume profile
- **Secondary Support**: Moving average crossovers
- **Tertiary Support**: Fibonacci retracement levels

#### Resistance Levels (Selling Pressure)
- **Primary Resistance**: Recent high + volume profile
- **Secondary Resistance**: Moving average resistance
- **Tertiary Resistance**: Fibonacci extension levels

### Analysis Methodology

```
1. Fetch current price and 24h data
2. Calculate recent highs/lows
3. Apply technical indicators
4. Generate support/resistance levels
5. Provide trading insights
```

## Usage Examples

### Example 1: Basic Query
**User**: "BTC-USDT 支撑位压力位"

**Response**:
```
📊 BTC-USDT 技术分析

💰 当前价格: $67,500
📈 24h变化: +2.5%

🔴 压力位 (Resistance):
• R1: $68,200 (近期高点)
• R2: $69,500 (心理关口)
• R3: $71,000 (历史阻力)

🟢 支撑位 (Support):
• S1: $66,800 (日内低点)
• S2: $65,500 (MA50)
• S3: $64,000 (强支撑)

💡 交易建议: 短期看涨,关注$68,200突破
```

### Example 2: Detailed Analysis
**User**: "ETH-USDT 详细技术分析"

**Response**:
```
📊 ETH-USDT 详细技术分析

💰 当前价格: $3,450
📈 24h变化: +3.2%
📉 7d变化: -1.5%

🔴 压力位 (Resistance):
• R1: $3,500 (心理关口)
• R2: $3,600 (近期高点)
• R3: $3,750 (斐波那契扩展)

🟢 支撑位 (Support):
• S1: $3,400 (日内支撑)
• S2: $3,300 (MA100)
• S3: $3,200 (强支撑区)

📊 技术指标:
• RSI: 62 (中性偏强)
• MACD: 金叉向上
• MA50: $3,350 (支撑)

💡 市场情绪: 看涨
💡 交易建议: 回调买入,突破追涨
```

### Example 3: Multiple Pairs
**User**: "BTC, ETH, SOL 的支撑位"

**Response**:
```
📊 多币种支撑位分析

BTC-USDT ($67,500)
• 支撑: $66,800, $65,500, $64,000
• 压力: $68,200, $69,500, $71,000

ETH-USDT ($3,450)
• 支撑: $3,400, $3,300, $3,200
• 压力: $3,500, $3,600, $3,750

SOL-USDT ($175)
• 支撑: $170, $165, $160
• 压力: $180, $185, $195
```

## Advanced Features

### Time Frame Analysis

#### Short-term (Intraday)
- Focus on 1h, 4h charts
- Key levels: Previous day high/low
- Best for: Day trading, scalping

#### Medium-term (Swing)
- Focus on 4h, daily charts
- Key levels: Weekly highs/lows
- Best for: Swing trading (3-7 days)

#### Long-term (Position)
- Focus on daily, weekly charts
- Key levels: Monthly highs/lows
- Best for: Position trading (weeks/months)

### Volume Analysis

The skill analyzes volume to confirm levels:

- **High Volume at Support**: Strong buying interest
- **High Volume at Resistance**: Strong selling pressure
- **Low Volume**: Weak levels, more likely to break

### Market Sentiment

Based on technical indicators:
- **Bullish**: RSI > 50, MACD positive
- **Bearish**: RSI < 50, MACD negative
- **Neutral**: RSI 40-60, mixed signals

## Risk Management

### Important Disclaimer

**This is not financial advice.** The skill provides technical analysis for educational purposes only.

### Trading Risks

- **Market Volatility**: Crypto markets are highly volatile
- **Liquidity Risk**: Low liquidity can cause slippage
- **Regulatory Risk**: Regulations can impact prices
- **Technical Risk**: System failures, exchange issues

### Recommended Practices

1. **Never invest more than you can afford to lose**
2. **Use stop-loss orders**
3. **Diversify your portfolio**
4. **Do your own research (DYOR)**
5. **Consider professional advice**

## Configuration

### API Settings

The skill can be configured to use different data sources:

```json
{
  "crypto-levels": {
    "dataSource": "coingecko",  // or "binance", "coinmarketcap"
    "updateInterval": 60,       // seconds
    "cacheDuration": 300,       // seconds
    "defaultTimeframe": "4h"
  }
}
```

### Supported Data Sources

- **CoinGecko**: Free, comprehensive
- **Binance**: Real-time exchange data
- **CoinMarketCap**: Professional tier available

See [CONFIGURATION.md](references/CONFIGURATION.md) for details.

## Troubleshooting

### Common Issues

#### "Pair not found"
- Check the pair format: `SYMBOL-USDT`
- See [SUPPORTED_PAIRS.md](references/SUPPORTED_PAIRS.md) for full list
- Try common alternatives (e.g., BTC instead of BTC-USDT)

#### "No data available"
- Check internet connection
- Verify API is accessible
- Try different data source

#### "Price seems wrong"
- Data may be delayed (check timestamp)
- Different exchanges have different prices
- Consider using multiple sources

### Error Messages

**"Invalid pair format"**
- Use format: `SYMBOL-USDT` (e.g., BTC-USDT)

**"API rate limit exceeded"**
- Wait a moment and try again
- Consider using a different data source

**"Network timeout"**
- Check your internet connection
- Try again in a few seconds

## Best Practices

### For Traders

1. **Combine with other indicators**
   - Use RSI, MACD, Bollinger Bands
   - Consider volume profile
   - Watch for chart patterns

2. **Risk management**
   - Set stop-loss below support
   - Take profit near resistance
   - Risk no more than 1-2% per trade

3. **Time frame alignment**
   - Check multiple time frames
   - Look for confluence
   - Avoid counter-trend trades

### For Investors

1. **Long-term perspective**
   - Focus on weekly/monthly levels
   - Consider dollar-cost averaging
   - Don't time the market

2. **Portfolio management**
   - Diversify across coins
   - Rebalance periodically
   - Keep emergency fund

## References

### Technical Analysis
- [SUPPORTED_PAIRS.md](references/SUPPORTED_PAIRS.md) - Full list of supported pairs
- [CONFIGURATION.md](references/CONFIGURATION.md) - Configuration options
- [TECHNICAL_GUIDE.md](references/TECHNICAL_GUIDE.md) - Detailed methodology

### External Resources
- [Investopedia - Support and Resistance](https://www.investopedia.com/terms/s/support.asp)
- [BabyPips - Technical Analysis](https://www.babypips.com/learn/forex)
- [TradingView - Chart Patterns](https://www.tradingview.com/chart-patterns/)

## Legal Disclaimer

**Important**: This skill is for educational purposes only. It does not constitute financial advice, investment recommendation, or trading strategy. Cryptocurrency trading involves substantial risk of loss. Past performance is not indicative of future results. Always consult with a qualified financial advisor before making investment decisions.

By using this skill, you acknowledge that you understand these risks and agree to hold the skill provider harmless for any losses incurred.


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### references/SUPPORTED_PAIRS.md

```markdown
# Supported Cryptocurrency Pairs

## Major Cryptocurrencies (Top 20 by Market Cap)

| Symbol | Name | Ticker | Example Query |
|--------|------|--------|---------------|
| BTC | Bitcoin | BTC-USDT | "BTC-USDT 支撑位" |
| ETH | Ethereum | ETH-USDT | "ETH-USDT 技术分析" |
| BNB | Binance Coin | BNB-USDT | "BNB-USDT 当前价格" |
| SOL | Solana | SOL-USDT | "SOL-USDT 关键水平" |
| XRP | Ripple | XRP-USDT | "XRP-USDT 压力位" |
| ADA | Cardano | ADA-USDT | "ADA-USDT 支撑位" |
| DOGE | Dogecoin | DOGE-USDT | "DOGE-USDT 分析" |
| DOT | Polkadot | DOT-USDT | "DOT-USDT 技术面" |
| AVAX | Avalanche | AVAX-USDT | "AVAX-USDT 交易建议" |
| MATIC | Polygon | MATIC-USDT | "MATIC-USDT 行情" |
| LINK | Chainlink | LINK-USDT | "LINK-USDT 指标" |
| UNI | Uniswap | UNI-USDT | "UNI-USDT 趋势" |
| ATOM | Cosmos | ATOM-USDT | "ATOM-USDT 分析" |
| LTC | Litecoin | LTC-USDT | "LTC-USDT 支撑" |
| BCH | Bitcoin Cash | BCH-USDT | "BCH-USDT 压力" |
| XLM | Stellar | XLM-USDT | "XLM-USDT 技术" |
| SHIB | Shiba Inu | SHIB-USDT | "SHIB-USDT 分析" |
| TRX | Tron | TRX-USDT | "TRX-USDT 水平" |
| ETC | Ethereum Classic | ETC-USDT | "ETC-USDT 交易" |
| FIL | Filecoin | FIL-USDT | "FIL-USDT 策略" |

## Popular Altcoins

### DeFi Tokens
| Symbol | Name | Ticker |
|--------|------|--------|
| AAVE | Aave | AAVE-USDT |
| COMP | Compound | COMP-USDT |
| MKR | Maker | MKR-USDT |
| SNX | Synthetix | SNX-USDT |
| SUSHI | SushiSwap | SUSHI-USDT |
| YFI | Yearn Finance | YFI-USDT |
| CRV | Curve DAO | CRV-USDT |
| BAL | Balancer | BAL-USDT |

### Layer 2 Solutions
| Symbol | Name | Ticker |
|--------|------|--------|
| OP | Optimism | OP-USDT |
| ARB | Arbitrum | ARB-USDT |
| METIS | Metis | METIS-USDT |
| SKL | SKALE | SKL-USDT |

### AI & Big Data
| Symbol | Name | Ticker |
|--------|------|--------|
| FET | Fetch.ai | FET-USDT |
| RNDR | Render | RNDR-USDT |
| GRT | The Graph | GRT-USDT |
| OCEAN | Ocean Protocol | OCEAN-USDT |
| AKT | Akash Network | AKT-USDT |

### Gaming & Metaverse
| Symbol | Name | Ticker |
|--------|------|--------|
| SAND | The Sandbox | SAND-USDT |
| MANA | Decentraland | MANA-USDT |
| AXS | Axie Infinity | AXS-USDT |
| GALA | Gala | GALA-USDT |
| ENJ | Enjin | ENJ-USDT |

### Infrastructure
| Symbol | Name | Ticker |
|--------|------|--------|
| NEAR | NEAR Protocol | NEAR-USDT |
| APT | Aptos | APT-USDT |
| SUI | Sui | SUI-USDT |
| TON | Toncoin | TON-USDT |
| INJ | Injective | INJ-USDT |

### Privacy Coins
| Symbol | Name | Ticker |
|--------|------|--------|
| XMR | Monero | XMR-USDT |
| ZEC | Zcash | ZEC-USDT |
| DASH | Dash | DASH-USDT |

### Meme Coins
| Symbol | Name | Ticker |
|--------|------|--------|
| PEPE | Pepe | PEPE-USDT |
| BONK | Bonk | BONK-USDT |
| WIF | dogwifhat | WIF-USDT |
| FLOKI | Floki | FLOKI-USDT |

## Stablecoins (for reference)

| Symbol | Name | Ticker |
|--------|------|--------|
| USDT | Tether | USDT-USD |
| USDC | USD Coin | USDC-USD |
| DAI | Dai | DAI-USD |
| BUSD | Binance USD | BUSD-USD |

## How to Query

### Standard Format
```
SYMBOL-USDT
```

### Examples
```
BTC-USDT 支撑位压力位
ETH-USDT 技术分析
SOL-USDT 当前价格和关键水平
```

### Multiple Pairs
```
BTC, ETH, SOL 的支撑位
```

### Alternative Queries
```
比特币 支撑位
以太坊 技术分析
```

## Adding New Pairs

If you want to add a new cryptocurrency pair:

1. **Check if it's listed on major exchanges** (Binance, Coinbase, Kraken)
2. **Verify USDT trading pair exists**
3. **Ensure sufficient liquidity** (daily volume > $1M)

### Request Format
```
[SYMBOL]-USDT
```

### Example
```
NEWCOIN-USDT
```

## Data Source Coverage

### CoinGecko
- **Coverage**: 10,000+ cryptocurrencies
- **Update**: Real-time
- **Rate Limit**: 50 calls/minute (free tier)

### Binance API
- **Coverage**: All Binance listed pairs
- **Update**: Real-time
- **Rate Limit**: 1200 requests/minute

### CoinMarketCap
- **Coverage**: 5,000+ cryptocurrencies
- **Update**: Real-time
- **Rate Limit**: 333 calls/day (free tier)

## Pair Format Variations

### Standard (Recommended)
```
BTC-USDT
ETH-USDT
```

### Alternative (Accepted)
```
BTCUSDT
ETHUSDT
```

### With Slash (Accepted)
```
BTC/USDT
ETH/USDT
```

## Regional Variations

### Chinese Users
```
BTC-USDT → 比特币-USDT
ETH-USDT → 以太坊-USDT
```

### Common Abbreviations
```
BTC → Bitcoin
ETH → Ethereum
SOL → Solana
BNB → Binance Coin
```

## Troubleshooting

### "Pair not found"
1. Check spelling (case-insensitive)
2. Verify USDT pair exists
3. Try alternative symbol name

### "No data available"
1. Check internet connection
2. Verify API is accessible
3. Try different data source

### "Insufficient liquidity"
1. Choose more liquid pairs
2. Check trading volume
3. Consider major cryptocurrencies

## Performance Tips

### Best Pairs for Analysis
- **High Liquidity**: BTC, ETH, BNB, SOL
- **Good Volume**: Most top 50 coins
- **Reliable Data**: Major exchanges listed

### Pairs to Avoid
- **Low Volume**: New or obscure coins
- **High Spread**: Low liquidity pairs
- **Unstable**: Frequent delistings

## Updates

This list is regularly updated. New pairs are added based on:
- Market capitalization
- Trading volume
- User requests
- Exchange listings

**Last Updated**: 2026-02-05

```

### references/CONFIGURATION.md

```markdown
# Crypto Levels Configuration Guide

## Overview

Configure the Crypto Levels skill to use different data sources, update intervals, and analysis parameters.

## Configuration File

### Location
```
/home/openclaw/.openclaw/openclaw.json
```

### Basic Configuration

```json
{
  "crypto-levels": {
    "enabled": true,
    "dataSource": "coingecko",
    "updateInterval": 60,
    "cacheDuration": 300,
    "defaultTimeframe": "4h",
    "apiKey": {
      "coingecko": "",
      "coinmarketcap": "",
      "binance": ""
    }
  }
}
```

## Data Source Configuration

### 1. CoinGecko (Recommended - Free)

**Pros:**
- Free tier available
- 10,000+ cryptocurrencies
- Real-time data
- No API key required for basic use

**Cons:**
- Rate limit: 50 calls/minute
- Limited historical data

**Configuration:**
```json
{
  "crypto-levels": {
    "dataSource": "coingecko",
    "apiKey": {
      "coingecko": ""  // Optional for higher limits
    }
  }
}
```

**API Key (Optional):**
- Sign up at: https://www.coingecko.com/en/api
- Free tier: 50 calls/minute
- Pro tier: 500 calls/minute ($79/month)

### 2. Binance API

**Pros:**
- Real-time exchange data
- High liquidity pairs
- No API key needed for public data
- Very reliable

**Cons:**
- Limited to Binance listed pairs
- No historical data for some pairs

**Configuration:**
```json
{
  "crypto-levels": {
    "dataSource": "binance",
    "apiKey": {
      "binance": ""  // Optional for higher limits
    }
  }
}
```

**API Key (Optional):**
- Create at: https://www.binance.com/en/my/settings/api-management
- Basic: 1200 requests/minute
- IP restrictions recommended

### 3. CoinMarketCap

**Pros:**
- Professional data
- 5,000+ cryptocurrencies
- Good documentation

**Cons:**
- Requires API key
- Free tier limited to 333 calls/day
- More expensive for higher tiers

**Configuration:**
```json
{
  "crypto-levels": {
    "dataSource": "coinmarketcap",
    "apiKey": {
      "coinmarketcap": "YOUR_API_KEY"
    }
  }
}
```

**API Key Required:**
- Sign up at: https://coinmarketcap.com/api/
- Free: 333 calls/day
- Hobbyist: $29/month (10,000 calls/day)
- Professional: $99/month (100,000 calls/day)

## Advanced Configuration

### Update Intervals

#### Real-time (Default)
```json
{
  "updateInterval": 60  // Update every 60 seconds
}
```

#### Fast Updates
```json
{
  "updateInterval": 30  // Update every 30 seconds
}
```

#### Conservative
```json
{
  "updateInterval": 300  // Update every 5 minutes
}
```

### Cache Settings

#### Short Cache (Fast Response)
```json
{
  "cacheDuration": 60  // Cache for 1 minute
}
```

#### Medium Cache (Balanced)
```json
{
  "cacheDuration": 300  // Cache for 5 minutes
}
```

#### Long Cache (Reduced API Calls)
```json
{
  "cacheDuration": 1800  // Cache for 30 minutes
}
```

### Time Frame Settings

#### Default Time Frame
```json
{
  "defaultTimeframe": "4h"  // 4-hour charts
}
```

**Available Time Frames:**
- `1m` - 1 minute (for high-frequency trading)
- `5m` - 5 minutes
- `15m` - 15 minutes
- `1h` - 1 hour
- `4h` - 4 hours (recommended)
- `1d` - 1 day
- `1w` - 1 week

### Analysis Parameters

#### Support/Resistance Calculation
```json
{
  "analysis": {
    "lookbackPeriod": 30,      // Days to analyze
    "volumeThreshold": 0.1,    // Volume multiplier
    "priceDeviation": 0.02,    // 2% deviation
    "minLevels": 3,            // Minimum levels per side
    "maxLevels": 5             // Maximum levels per side
  }
}
```

#### Technical Indicators
```json
{
  "indicators": {
    "rsi": {
      "enabled": true,
      "period": 14
    },
    "macd": {
      "enabled": true,
      "fastPeriod": 12,
      "slowPeriod": 26,
      "signalPeriod": 9
    },
    "movingAverages": {
      "enabled": true,
      "periods": [50, 100, 200]
    },
    "bollingerBands": {
      "enabled": true,
      "period": 20,
      "stdDev": 2
    }
  }
}
```

## Multi-Source Configuration

### Fallback Strategy
```json
{
  "crypto-levels": {
    "dataSource": "coingecko",
    "fallbackSources": ["binance", "coinmarketcap"],
    "maxRetries": 3,
    "timeout": 10
  }
}
```

### Weighted Sources
```json
{
  "crypto-levels": {
    "sources": [
      {
        "name": "coingecko",
        "weight": 0.5,
        "priority": 1
      },
      {
        "name": "binance",
        "weight": 0.3,
        "priority": 2
      },
      {
        "name": "coinmarketcap",
        "weight": 0.2,
        "priority": 3
      }
    ]
  }
}
```

## Environment Variables

### Alternative to JSON Config

```bash
# Data Source
export CRYPTO_LEVELS_DATA_SOURCE="coingecko"

# API Keys
export COINGECKO_API_KEY="your_key"
export COINMARKETCAP_API_KEY="your_key"
export BINANCE_API_KEY="your_key"

# Intervals
export CRYPTO_LEVELS_UPDATE_INTERVAL="60"
export CRYPTO_LEVELS_CACHE_DURATION="300"

# Timeframe
export CRYPTO_LEVELS_DEFAULT_TIMEFRAME="4h"
```

## Performance Optimization

### For High Traffic
```json
{
  "crypto-levels": {
    "dataSource": "binance",
    "updateInterval": 120,
    "cacheDuration": 600,
    "maxConcurrentRequests": 5,
    "requestTimeout": 15
  }
}
```

### For Low Traffic
```json
{
  "crypto-levels": {
    "dataSource": "coingecko",
    "updateInterval": 300,
    "cacheDuration": 1800,
    "maxConcurrentRequests": 2,
    "requestTimeout": 10
  }
}
```

## Security Settings

### API Key Management
```json
{
  "crypto-levels": {
    "security": {
      "encryptKeys": true,
      "keyStorage": "env",  // or "file", "vault"
      "rotateKeys": true,
      "keyRotationDays": 30
    }
  }
}
```

### Rate Limiting
```json
{
  "crypto-levels": {
    "rateLimit": {
      "enabled": true,
      "requestsPerMinute": 50,
      "burstSize": 10,
      "cooldownPeriod": 60
    }
  }
}
```

## Logging Configuration

### Debug Mode
```json
{
  "crypto-levels": {
    "logging": {
      "level": "debug",
      "file": "/var/log/openclaw/crypto-levels.log",
      "maxSize": "10m",
      "maxFiles": 5
    }
  }
}
```

### Production Mode
```json
{
  "crypto-levels": {
    "logging": {
      "level": "info",
      "file": "/var/log/openclaw/crypto-levels.log",
      "maxSize": "5m",
      "maxFiles": 3
    }
  }
}
```

## Error Handling

### Retry Logic
```json
{
  "crypto-levels": {
    "errorHandling": {
      "maxRetries": 3,
      "retryDelay": 1000,
      "backoffMultiplier": 2,
      "circuitBreaker": {
        "enabled": true,
        "failureThreshold": 5,
        "resetTimeout": 60000
      }
    }
  }
}
```

### Fallback Behavior
```json
{
  "crypto-levels": {
    "fallback": {
      "enabled": true,
      "useCachedData": true,
      "cacheOnFailure": true,
      "staleDataThreshold": 300
    }
  }
}
```

## Testing Configuration

### Test Mode
```json
{
  "crypto-levels": {
    "test": {
      "enabled": false,
      "mockData": true,
      "simulateDelay": 500,
      "useTestData": false
    }
  }
}
```

### Development Mode
```json
{
  "crypto-levels": {
    "development": {
      "strictValidation": true,
      "verboseLogging": true,
      "mockExternalAPIs": false
    }
  }
}
```

## Complete Example

### Production Configuration
```json
{
  "crypto-levels": {
    "enabled": true,
    "dataSource": "coingecko",
    "fallbackSources": ["binance"],
    "updateInterval": 60,
    "cacheDuration": 300,
    "defaultTimeframe": "4h",
    "apiKey": {
      "coingecko": "CG-xxxxxxxxxxxx",
      "binance": ""
    },
    "analysis": {
      "lookbackPeriod": 30,
      "volumeThreshold": 0.1,
      "priceDeviation": 0.02,
      "minLevels": 3,
      "maxLevels": 5
    },
    "indicators": {
      "rsi": { "enabled": true, "period": 14 },
      "macd": { "enabled": true },
      "movingAverages": { "enabled": true, "periods": [50, 100, 200] }
    },
    "rateLimit": {
      "enabled": true,
      "requestsPerMinute": 50
    },
    "logging": {
      "level": "info",
      "file": "/var/log/openclaw/crypto-levels.log"
    }
  }
}
```

## Validation

### Test Configuration
```bash
# Validate config syntax
python3 -m json.tool /home/openclaw/.openclaw/openclaw.json

# Test data source connection
python3 crypto-levels/scripts/test_connection.py

# Run diagnostics
python3 crypto-levels/scripts/diagnostics.py
```

## Troubleshooting

### Common Issues

#### "API key required"
- Add API key to configuration
- Check environment variables
- Verify key has correct permissions

#### "Rate limit exceeded"
- Increase update interval
- Use caching
- Consider paid API tier

#### "No data available"
- Check pair format
- Verify data source coverage
- Try different data source

### Debug Mode
```json
{
  "crypto-levels": {
    "logging": {
      "level": "debug"
    }
  }
}
```

## Best Practices

### 1. API Key Security
- Never commit API keys to version control
- Use environment variables in production
- Rotate keys regularly
- Use IP restrictions when available

### 2. Rate Limit Management
- Monitor API usage
- Implement caching
- Use multiple sources
- Respect rate limits

### 3. Error Handling
- Implement retry logic
- Use circuit breakers
- Log errors appropriately
- Provide graceful degradation

### 4. Performance
- Cache aggressively
- Use appropriate update intervals
- Monitor response times
- Optimize queries

## Monitoring

### Metrics to Track
- API response times
- Cache hit rates
- Error rates
- Data freshness
- User query volume

### Alerting
```json
{
  "crypto-levels": {
    "monitoring": {
      "alerts": {
        "enabled": true,
        "email": "[email protected]",
        "slack": "https://hooks.slack.com/...",
        "thresholds": {
          "errorRate": 0.05,
          "responseTime": 5000,
          "cacheHitRate": 0.7
        }
      }
    }
  }
}
```

## Updates

This configuration guide is regularly updated. Check for new features and best practices.

**Last Updated**: 2026-02-05

```

### references/TECHNICAL_GUIDE.md

```markdown
# Technical Analysis Guide

## Overview

This guide explains the methodology behind support and resistance level calculation in the Crypto Levels skill.

## Core Concepts

### Support and Resistance

#### Support Level
- **Definition**: Price level where buying interest is strong enough to overcome selling pressure
- **Characteristics**:
  - Price tends to bounce up from this level
  - High volume at this price
  - Multiple touches increase significance
- **Psychology**: "This is a good price to buy"

#### Resistance Level
- **Definition**: Price level where selling pressure overcomes buying interest
- **Characteristics**:
  - Price tends to reverse down from this level
  - High volume at this price
  - Multiple touches increase significance
- **Psychology**: "This is a good price to sell"

## Calculation Methods

### 1. Price Action Analysis

#### Recent Highs and Lows
```python
# Primary Support/Resistance
Primary_Support = min(low_prices[-5:])  # Last 5 periods low
Primary_Resistance = max(high_prices[-5:])  # Last 5 periods high
```

#### Multiple Time Frame Analysis
- **Short-term**: Last 5-10 periods
- **Medium-term**: Last 20-50 periods
- **Long-term**: Last 100-200 periods

### 2. Volume Profile

#### Volume at Price Levels
```python
# Calculate volume-weighted price levels
def calculate_volume_levels(prices, volumes, bins=20):
    # Group prices into bins
    # Calculate total volume per bin
    # Return levels with highest volume
    pass
```

#### Volume Confirmation
- **High Volume at Support**: Strong buying interest
- **High Volume at Resistance**: Strong selling pressure
- **Low Volume**: Weak levels, prone to break

### 3. Moving Averages

#### Common Periods
```python
MA_periods = {
    'short': [5, 10, 20],      # Short-term
    'medium': [50, 100],       # Medium-term
    'long': [200]              # Long-term
}
```

#### MA as Dynamic Support/Resistance
- **Price above MA**: MA acts as support
- **Price below MA**: MA acts as resistance
- **MA crossovers**: Signal potential level changes

### 4. Fibonacci Retracement

#### Key Levels
```python
fib_levels = {
    'support': [0.236, 0.382, 0.5, 0.618],
    'resistance': [1.0, 1.236, 1.382, 1.618]
}
```

#### Calculation
```python
def fibonacci_levels(high, low, trend='up'):
    if trend == 'up':
        # Retracement from low to high
        diff = high - low
        return {
            's1': high - diff * 0.236,
            's2': high - diff * 0.382,
            's3': high - diff * 0.5,
            's4': high - diff * 0.618,
            'r1': high + diff * 0.236,
            'r2': high + diff * 0.382
        }
    else:
        # Retracement from high to low
        diff = high - low
        return {
            'r1': low + diff * 0.236,
            'r2': low + diff * 0.382,
            'r3': low + diff * 0.5,
            'r4': low + diff * 0.618,
            's1': low - diff * 0.236,
            's2': low - diff * 0.382
        }
```

### 5. Pivot Points

#### Classic Pivot Points
```python
def classic_pivots(high, low, close):
    pivot = (high + low + close) / 3
    
    r1 = 2 * pivot - low
    s1 = 2 * pivot - high
    
    r2 = pivot + (high - low)
    s2 = pivot - (high - low)
    
    r3 = high + 2 * (pivot - low)
    s3 = low - 2 * (high - pivot)
    
    return {
        'pivot': pivot,
        'resistance': [r1, r2, r3],
        'support': [s1, s2, s3]
    }
```

#### Camarilla Pivots
```python
def camarilla_pivots(high, low, close):
    diff = high - low
    
    return {
        'support': [
            close - diff * 1.1/12,
            close - diff * 1.1/6,
            close - diff * 1.1/4
        ],
        'resistance': [
            close + diff * 1.1/12,
            close + diff * 1.1/6,
            close + diff * 1.1/4
        ]
    }
```

### 6. Trend Line Analysis

#### Drawing Trend Lines
```python
def trend_line_support(prices, lookback=20):
    # Find local minima
    local_minima = find_local_minima(prices, lookback)
    
    # Fit linear regression
    if len(local_minima) >= 2:
        slope, intercept = linear_regression(local_minima)
        return slope, intercept
    return None, None
```

#### Channel Analysis
- **Ascending Channel**: Higher highs and higher lows
- **Descending Channel**: Lower highs and lower lows
- **Horizontal Channel**: Equal highs and lows

## Technical Indicators

### RSI (Relative Strength Index)

#### Calculation
```python
def calculate_rsi(prices, period=14):
    deltas = np.diff(prices)
    gains = np.where(deltas > 0, deltas, 0)
    losses = np.where(deltas < 0, -deltas, 0)
    
    avg_gain = np.mean(gains[-period:])
    avg_loss = np.mean(losses[-period:])
    
    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))
    
    return rsi
```

#### Interpretation
- **RSI > 70**: Overbought (potential resistance)
- **RSI < 30**: Oversold (potential support)
- **RSI 50**: Neutral

### MACD (Moving Average Convergence Divergence)

#### Calculation
```python
def calculate_macd(prices, fast=12, slow=26, signal=9):
    ema_fast = ema(prices, fast)
    ema_slow = ema(prices, slow)
    
    macd_line = ema_fast - ema_slow
    signal_line = ema(macd_line, signal)
    histogram = macd_line - signal_line
    
    return {
        'macd': macd_line,
        'signal': signal_line,
        'histogram': histogram
    }
```

#### Interpretation
- **MACD > Signal**: Bullish (support likely)
- **MACD < Signal**: Bearish (resistance likely)
- **Histogram increasing**: Momentum strengthening

### Bollinger Bands

#### Calculation
```python
def bollinger_bands(prices, period=20, std_dev=2):
    sma = moving_average(prices, period)
    std = np.std(prices[-period:])
    
    upper = sma + (std * std_dev)
    lower = sma - (std * std_dev)
    
    return {
        'upper': upper,
        'middle': sma,
        'lower': lower,
        'width': (upper - lower) / sma
    }
```

#### Interpretation
- **Price at lower band**: Potential support
- **Price at upper band**: Potential resistance
- **Band contraction**: Low volatility (breakout imminent)
- **Band expansion**: High volatility

## Volume Analysis

### Volume Profile

#### Point of Control (POC)
- Price level with highest volume
- Acts as strong support/resistance

#### Value Area
- 70% of volume around POC
- Range where price spends most time

### Volume Indicators

#### On-Balance Volume (OBV)
```python
def calculate_obv(prices, volumes):
    obv = [volumes[0]]
    for i in range(1, len(prices)):
        if prices[i] > prices[i-1]:
            obv.append(obv[-1] + volumes[i])
        elif prices[i] < prices[i-1]:
            obv.append(obv[-1] - volumes[i])
        else:
            obv.append(obv[-1])
    return obv
```

#### Volume Weighted Average Price (VWAP)
```python
def calculate_vwap(prices, volumes):
    total_pv = sum(p * v for p, v in zip(prices, volumes))
    total_v = sum(volumes)
    return total_pv / total_v
```

## Market Structure

### Breakouts and Breakdowns

#### Breakout Confirmation
```python
def is_breakout(price, resistance, volume, threshold=0.02):
    # Price above resistance
    price_above = price > resistance * (1 + threshold)
    
    # Volume confirmation
    volume_confirm = volume > average_volume * 1.5
    
    # Time confirmation (sustained)
    time_confirm = price > resistance for n_periods
    
    return price_above and volume_confirm and time_confirm
```

#### Breakdown Confirmation
```python
def is_breakdown(price, support, volume, threshold=0.02):
    # Price below support
    price_below = price < support * (1 - threshold)
    
    # Volume confirmation
    volume_confirm = volume > average_volume * 1.5
    
    return price_below and volume_confirm
```

### Support/Resistance Role Reversal

#### Principle
- **Broken support becomes resistance**
- **Broken resistance becomes support**

#### Detection
```python
def role_reversal(old_support, current_price, threshold=0.05):
    if current_price < old_support * (1 - threshold):
        # Support broken, now acts as resistance
        return 'resistance'
    elif current_price > old_support * (1 + threshold):
        # Retested and held, still support
        return 'support'
    return 'uncertain'
```

## Time Frame Analysis

### Multi-Time Frame Approach

#### Top-Down Analysis
1. **Monthly/Weekly**: Long-term trend
2. **Daily**: Medium-term structure
3. **4H/1H**: Short-term entry

#### Time Frame Confluence
- **Strong levels**: Multiple time frames align
- **Weak levels**: Only one time frame

### Optimal Time Frames

#### For Day Trading
- **Primary**: 1H, 4H
- **Secondary**: 15M, 1D
- **Confirmation**: 15M + 1H + 4H

#### For Swing Trading
- **Primary**: 4H, 1D
- **Secondary**: 1H, 1W
- **Confirmation**: 4H + 1D + 1W

#### For Position Trading
- **Primary**: 1D, 1W
- **Secondary**: 1M, 4H
- **Confirmation**: 1D + 1W + 1M

## Risk Management

### Position Sizing

#### Kelly Criterion
```python
def kelly_criterion(win_rate, win_loss_ratio):
    # win_rate: probability of winning
    # win_loss_ratio: average win / average loss
    return win_rate - (1 - win_rate) / win_loss_ratio
```

#### Fixed Fractional
```python
def fixed_fractional(account_size, risk_per_trade=0.02):
    return account_size * risk_per_trade
```

### Stop Loss Placement

#### Below Support
```python
def stop_loss_below_support(support, price, atr=None):
    if atr:
        # Use ATR for dynamic stop
        return support - (atr * 1.5)
    else:
        # Fixed percentage
        return support * 0.98
```

#### Trailing Stop
```python
def trailing_stop(current_price, highest_price, trail_percent=0.05):
    return highest_price * (1 - trail_percent)
```

### Take Profit Levels

#### Resistance Based
```python
def take_profit_at_resistance(resistance_levels, risk_reward_ratio=2):
    # Target 2:1 risk/reward
    return [level for level in resistance_levels 
            if level >= entry_price + (risk * risk_reward_ratio)]
```

#### Partial Profits
```python
def partial_profit-taking(levels, position_size):
    # Take profit at multiple levels
    return {
        'level1': position_size * 0.3,  # 30% at first resistance
        'level2': position_size * 0.3,  # 30% at second resistance
        'level3': position_size * 0.4   # 40% at third resistance
    }
```

## Market Psychology

### Support/Resistance Psychology

#### Support Psychology
- "This is a good price to buy"
- "The price won't go lower"
- "Fear of missing out (FOMO) kicks in"

#### Resistance Psychology
- "This is a good price to sell"
- "The price won't go higher"
- "Greed turns to fear"

### Emotional Levels

#### Round Numbers
- **BTC**: $50,000, $60,000, $70,000
- **ETH**: $3,000, $4,000, $5,000
- **Psychology**: Humans prefer round numbers

#### Psychological Levels
- **All-time highs**: Strong resistance
- **Previous lows**: Strong support
- **Fibonacci levels**: Self-fulfilling prophecy

## Advanced Techniques

### Order Flow Analysis

#### Order Book Levels
- **Bid walls**: Large buy orders (support)
- **Ask walls**: Large sell orders (resistance)
- **Iceberg orders**: Hidden large orders

#### Liquidation Levels
- **Long liquidations**: Below support (cascade down)
- **Short liquidations**: Above resistance (cascade up)

### Market Profile

#### TPO (Time-Price Opportunity)
- **Point of Control (POC)**: Highest TPO count
- **Value Area**: 70% of TPOs
- **High/Low**: Range extremes

#### Volume Profile
- **High Volume Nodes (HVN)**: Strong levels
- **Low Volume Nodes (LVN)**: Weak levels (breakthrough easily)

### Elliott Wave Theory

#### Impulsive Waves (5 waves)
- **Wave 1**: New trend
- **Wave 2**: Retracement (support)
- **Wave 3**: Strongest move
- **Wave 4**: Retracement (support)
- **Wave 5**: Final push

#### Corrective Waves (3 waves)
- **Wave A**: Down
- **Wave B**: Retracement (resistance)
- **Wave C**: Final down

## Algorithm Implementation

### Level Ranking System

```python
def rank_levels(levels, weights):
    """
    Rank support/resistance levels by strength
    """
    scores = {}
    
    for level in levels:
        score = 0
        
        # Volume score (0-30)
        score += min(level['volume'] / avg_volume * 10, 30)
        
        # Touch score (0-30)
        score += min(level['touches'] * 5, 30)
        
        # Time frame score (0-20)
        score += level['timeframes'] * 5
        
        # Volume profile score (0-20)
        score += level['volume_profile'] * 20
        
        scores[level['price']] = score
    
    return sorted(scores.items(), key=lambda x: x[1], reverse=True)
```

### Confidence Scoring

```python
def calculate_confidence(level, context):
    """
    Calculate confidence in a level
    """
    confidence = 0
    
    # Multiple time frame confirmation
    if context['timeframe_confluence']:
        confidence += 30
    
    # Volume confirmation
    if context['volume_spike']:
        confidence += 25
    
    # Historical significance
    if context['historical_touches'] >= 3:
        confidence += 20
    
    # Technical indicator alignment
    if context['indicator_alignment']:
        confidence += 15
    
    # Market structure
    if context['market_structure']:
        confidence += 10
    
    return min(confidence, 100)
```

## Limitations and Caveats

### Market Conditions

#### Trending Markets
- **Support/Resistance**: More reliable
- **Breakouts**: More common
- **False breaks**: Less frequent

#### Ranging Markets
- **Support/Resistance**: Very reliable
- **Bounces**: More predictable
- **Range boundaries**: Strong

#### Volatile Markets
- **Support/Resistance**: Less reliable
- **False breaks**: More common
- **Wider stops needed**

### Black Swan Events

#### Unexpected Events
- **Regulatory news**: Can break any level
- **Exchange hacks**: Immediate price impact
- **Market manipulation**: Can invalidate analysis

#### Risk Mitigation
- **Position sizing**: Never risk too much
- **Stop losses**: Always use stops
- **Diversification**: Don't put all eggs in one basket

## Continuous Improvement

### Backtesting

#### Historical Data
```python
def backtest_strategy(levels, historical_data):
    """
    Test strategy on historical data
    """
    results = []
    
    for period in historical_data:
        # Simulate trades
        # Calculate win rate
        # Calculate risk/reward
        pass
    
    return results
```

### Optimization

#### Parameter Tuning
- **Lookback periods**: Test different lengths
- **Volume thresholds**: Optimize for different pairs
- **Time frames**: Find optimal combinations

#### Walk-Forward Testing
- **In-sample**: Optimize parameters
- **Out-of-sample**: Validate performance
- **Rolling window**: Continuous validation

## Resources

### Books
- "Technical Analysis of the Financial Markets" - John Murphy
- "Market Wizards" - Jack Schwager
- "Trading in the Zone" - Mark Douglas

### Online Resources
- Investopedia Technical Analysis
- BabyPips School of Pipsology
- TradingView Chart Patterns

### Tools
- TradingView: Charting and analysis
- CoinGecko: Crypto data
- Binance: Exchange and API

## Disclaimer

**This is educational content only.** Trading involves substantial risk. Past performance does not guarantee future results. Always do your own research and consider professional advice.

---

**Last Updated**: 2026-02-05

```



---

## Skill Companion Files

> Additional files collected from the skill directory layout.

### README.md

```markdown
# Crypto Levels Analyzer

一个用于分析加密货币支撑位和压力位的 OpenClaw 技能。输入如 `BTC-USDT` 即可获取当前价格、关键支撑位、压力位和技术分析。

## 🚀 快速开始

### 基本用法

直接询问任何加密货币对:

```
BTC-USDT 支撑位压力位
ETH-USDT 技术分析
SOL-USDT 当前价格和关键水平
```

### 示例输出

```
📊 BTC-USDT 技术分析

💰 当前价格: $67,500
📈 24h变化: +2.5%

🔴 压力位 (Resistance):
• R1: $68,200 (近期高点)
• R2: $69,500 (心理关口)
• R3: $71,000 (历史阻力)

🟢 支撑位 (Support):
• S1: $66,800 (日内低点)
• S2: $65,500 (MA50)
• S3: $64,000 (强支撑)

📊 技术指标:
• RSI: 62 (中性偏强)
• MA50: $66,500 (支撑)
• MA100: $65,200 (支撑)

💡 交易建议: 短期看涨,关注$68,200突破
```

## 📦 安装

### 从 ClawHub 安装

```bash
clawhub install crypto-levels
```

### 手动安装

```bash
cd ~/.openclaw/skills
git clone <repo-url> crypto-levels
```

## 🎯 功能特性

### 核心功能

- ✅ **实时价格**: 获取当前市场价格
- ✅ **支撑位分析**: 识别关键买入区域
- ✅ **压力位分析**: 识别关键卖出区域
- ✅ **技术指标**: RSI, 移动平均线
- ✅ **多币种支持**: 100+ 加密货币
- ✅ **中文支持**: 完整的中文界面

### 技术分析

- **价格行为**: 近期高低点分析
- **移动平均线**: MA50, MA100, MA200
- **RSI指标**: 超买超卖判断
- **斐波那契**: 回撤和扩展水平
- **成交量分析**: 量价关系

## 📊 支持的币种

### 主要加密货币

| 代码 | 名称 | 示例查询 |
|------|------|----------|
| BTC | Bitcoin | `BTC-USDT 支撑位` |
| ETH | Ethereum | `ETH-USDT 技术分析` |
| SOL | Solana | `SOL-USDT 关键水平` |
| BNB | Binance Coin | `BNB-USDT 当前价格` |
| XRP | Ripple | `XRP-USDT 压力位` |
| ADA | Cardano | `ADA-USDT 支撑位` |
| DOGE | Dogecoin | `DOGE-USDT 分析` |
| DOT | Polkadot | `DOT-USDT 技术面` |

### 完整列表

查看 [SUPPORTED_PAIRS.md](references/SUPPORTED_PAIRS.md) 获取完整支持的币种列表。

## 🔧 使用示例

### 基础查询

```
BTC-USDT 支撑位压力位
```

### 详细分析

```
ETH-USDT 详细技术分析
```

### 多币种查询

```
BTC, ETH, SOL 的支撑位
```

### 中文查询

```
比特币 支撑位
以太坊 技术分析
```

## 📚 技术指标说明

### RSI (相对强弱指数)

- **> 70**: 超买区域(可能回调)
- **< 30**: 超卖区域(可能反弹)
- **30-70**: 中性区域

### 移动平均线

- **MA50**: 短期趋势
- **MA100**: 中期趋势
- **MA200**: 长期趋势

### 支撑位 (Support)

- 价格下跌时可能遇到的买入区域
- 多次测试未破的低点
- 成交量放大的价格区间

### 压力位 (Resistance)

- 价格上涨时可能遇到的卖出区域
- 多次测试未过的高点
- 成交量放大的价格区间

## ⚙️ 配置

### 数据源配置

技能支持多个数据源:

1. **CoinGecko** (默认) - 免费,覆盖广泛
2. **Binance** - 实时交易所数据
3. **CoinMarketCap** - 专业数据

配置文件:`/home/openclaw/.openclaw/openclaw.json`

```json
{
  "crypto-levels": {
    "enabled": true,
    "dataSource": "coingecko",
    "updateInterval": 60,
    "cacheDuration": 300,
    "defaultTimeframe": "4h"
  }
}
```

详见 [CONFIGURATION.md](references/CONFIGURATION.md)

## 🛠️ 脚本说明

### analyze_levels.py

主分析脚本,提供核心功能:

```bash
python3 scripts/analyze_levels.py BTC-USDT
```

### test_analyzer.py

测试脚本,验证多个币种:

```bash
python3 scripts/test_analyzer.py
```

### package_skill.py

打包技能用于发布:

```bash
python3 scripts/package_skill.py .
```

## 📈 使用场景

### 交易决策

- **入场时机**: 等待支撑位附近买入
- **出场时机**: 接近压力位卖出
- **止损设置**: 放在支撑位下方

### 风险管理

- **仓位控制**: 根据支撑位距离设置
- **止盈策略**: 多个压力位分批止盈
- **止损策略**: 关键支撑位下方

### 市场分析

- **趋势判断**: 通过支撑压力位
- **突破确认**: 成交量配合
- **反转信号**: 支撑压力位转换

## ⚠️ 风险提示

### 重要声明

**本技能不构成投资建议。** 所有分析仅供参考,加密货币交易存在极高风险。

### 交易风险

- **市场波动**: 加密货币价格波动剧烈
- **流动性风险**: 低流动性可能导致滑点
- **监管风险**: 政策变化可能影响价格
- **技术风险**: 系统故障、交易所问题

### 推荐做法

1. **不要投入超过承受能力的资金**
2. **使用止损订单控制风险**
3. **分散投资,不要全仓一个币种**
4. **做好自己的研究 (DYOR)**
5. **考虑专业财务建议**

## 🔒 安全建议

### API 使用

- **保护 API 密钥**: 不要泄露
- **使用环境变量**: 避免硬编码
- **定期轮换密钥**: 增强安全性
- **限制 IP 访问**: 减少风险

### 资金安全

- **使用硬件钱包**: 存储大额资金
- **启用双因素认证**: 保护交易所账户
- **警惕钓鱼**: 不要点击可疑链接
- **验证地址**: 转账前仔细检查

## 🐛 常见问题

### "Pair not found"

**原因**: 币种代码错误或不支持

**解决**:
- 检查代码是否正确(如 BTC-USDT)
- 查看 [SUPPORTED_PAIRS.md](references/SUPPORTED_PAIRS.md)
- 使用常见代码(BTC, ETH, SOL 等)

### "No data available"

**原因**: 网络问题或 API 限制

**解决**:
- 检查网络连接
- 等待几秒后重试
- 尝试不同数据源

### "Price seems wrong"

**原因**: 数据延迟或不同交易所价格差异

**解决**:
- 数据可能有延迟(检查时间戳)
- 不同交易所价格不同
- 考虑使用多个数据源

## 📊 性能优化

### 缓存策略

- **短缓存**: 60秒(快速更新)
- **中缓存**: 300秒(平衡)
- **长缓存**: 1800秒(减少 API 调用)

### 更新频率

- **高频交易**: 30秒
- **普通使用**: 60秒
- **长期投资**: 300秒

## 🎓 学习资源

### 技术分析

- [Investopedia - Support and Resistance](https://www.investopedia.com/terms/s/support.asp)
- [BabyPips - Technical Analysis](https://www.babypips.com/learn/forex)
- [TradingView - Chart Patterns](https://www.tradingview.com/chart-patterns/)

### 加密货币

- [CoinGecko](https://www.coingecko.com/)
- [Binance Academy](https://academy.binance.com/)
- [CoinMarketCap](https://coinmarketcap.com/)

## 📞 支持

### 问题反馈

- 检查 [TROUBLESHOOTING.md](references/TROUBLESHOOTING.md)
- 查看 [CONFIGURATION.md](references/CONFIGURATION.md)
- 参考 [TECHNICAL_GUIDE.md](references/TECHNICAL_GUIDE.md)

### 社区资源

- OpenClaw 社区论坛
- 加密货币交易群组
- 技术分析讨论区

## 📄 许可证

MIT License - 详见 LICENSE 文件

## 🙏 贡献

欢迎贡献!请:

1. 阅读本 README
2. 遵循代码风格
3. 添加测试用例
4. 更新文档

## 🎯 下一步计划

### 短期(1-2 个月)

- [ ] 添加更多技术指标(MACD, Bollinger Bands)
- [ ] 支持更多币种
- [ ] 优化数据源切换

### 中期(3-6 个月)

- [ ] 添加图表生成功能
- [ ] 支持自定义时间框架
- [ ] 集成更多数据源

### 长期(6-12 个月)

- [ ] 机器学习预测
- [ ] 实时交易信号
- [ ] 高级风险分析

---

**最后更新**: 2026-02-05  
**版本**: 1.0.0  
**状态**: 🟢 开发中

```

### _meta.json

```json
{
  "owner": "362224222",
  "slug": "crypto-levels",
  "displayName": "Crypto Levels Analyzer",
  "latest": {
    "version": "1.0.3",
    "publishedAt": 1770224478956,
    "commit": "https://github.com/clawdbot/skills/commit/605f2269eadf9aac231d39622502cadcb423254e"
  },
  "history": []
}

```

### scripts/analyze_levels.py

```python
#!/usr/bin/env python3
"""
Crypto Levels Analyzer
Analyzes support and resistance levels for cryptocurrency pairs
"""

import requests
import json
import sys
import time
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
import math


class CryptoLevelsAnalyzer:
    def __init__(self, data_source="coingecko"):
        self.data_source = data_source
        self.base_urls = {
            "coingecko": "https://api.coingecko.com/api/v3",
            "binance": "https://api.binance.com/api/v3",
            "coinmarketcap": "https://pro-api.coinmarketcap.com/v1"
        }
        self.base_url = self.base_urls.get(data_source, self.base_urls["coingecko"])
        
    def normalize_pair(self, pair: str) -> str:
        """Normalize pair format"""
        # Remove spaces and convert to uppercase
        pair = pair.replace(" ", "").upper()
        
        # Handle different formats
        if "-" in pair:
            base, quote = pair.split("-")
        elif "/" in pair:
            base, quote = pair.split("/")
        elif pair.endswith("USDT"):
            base = pair[:-4]
            quote = "USDT"
        else:
            # Assume format like BTCUSDT
            base = pair[:-4] if pair.endswith("USDT") else pair
            quote = "USDT"
        
        return base, quote
    
    def get_coin_id(self, symbol: str) -> Optional[str]:
        """Get CoinGecko coin ID from symbol"""
        # Mapping of common symbols to CoinGecko IDs
        symbol_map = {
            "BTC": "bitcoin",
            "ETH": "ethereum",
            "BNB": "binancecoin",
            "SOL": "solana",
            "XRP": "ripple",
            "ADA": "cardano",
            "DOGE": "dogecoin",
            "DOT": "polkadot",
            "AVAX": "avalanche-2",
            "MATIC": "polygon",
            "LINK": "chainlink",
            "UNI": "uniswap",
            "ATOM": "cosmos",
            "LTC": "litecoin",
            "BCH": "bitcoin-cash",
            "XLM": "stellar",
            "SHIB": "shiba-inu",
            "TRX": "tron",
            "ETC": "ethereum-classic",
            "FIL": "filecoin",
            "AAVE": "aave",
            "COMP": "compound-governance-token",
            "MKR": "maker",
            "SNX": "havven",
            "SUSHI": "sushi",
            "YFI": "yearn-finance",
            "CRV": "curve-dao-token",
            "BAL": "balancer",
            "OP": "optimism",
            "ARB": "arbitrum",
            "FET": "fetch-ai",
            "RNDR": "render-token",
            "GRT": "the-graph",
            "NEAR": "near",
            "APT": "aptos",
            "SUI": "sui",
            "TON": "toncoin",
            "INJ": "injective-protocol",
            "XMR": "monero",
            "ZEC": "zcash",
            "DASH": "dash",
            "PEPE": "pepe",
            "BONK": "bonk",
            "WIF": "dogwifhat",
            "FLOKI": "floki",
            "SAND": "the-sandbox",
            "MANA": "decentraland",
            "AXS": "axie-infinity",
            "GALA": "gala",
            "ENJ": "enjin"
        }
        
        return symbol_map.get(symbol.upper())
    
    def fetch_price_data(self, symbol: str, days: int = 30) -> Optional[Dict]:
        """Fetch historical price data"""
        coin_id = self.get_coin_id(symbol)
        
        if not coin_id:
            print(f"❌ Unknown symbol: {symbol}")
            return None
        
        try:
            if self.data_source == "coingecko":
                url = f"{self.base_url}/coins/{coin_id}/market_chart"
                params = {
                    "vs_currency": "usd",
                    "days": days,
                    "interval": "hourly"
                }
                
                response = requests.get(url, params=params, timeout=10)
                
                if response.status_code == 200:
                    data = response.json()
                    return {
                        "prices": data.get("prices", []),
                        "market_caps": data.get("market_caps", []),
                        "total_volumes": data.get("total_volumes", [])
                    }
                else:
                    print(f"❌ API error: {response.status_code}")
                    return None
                    
        except Exception as e:
            print(f"❌ Fetch error: {e}")
            return None
        
        return None
    
    def fetch_current_price(self, symbol: str) -> Optional[float]:
        """Fetch current price"""
        coin_id = self.get_coin_id(symbol)
        
        if not coin_id:
            return None
        
        try:
            if self.data_source == "coingecko":
                url = f"{self.base_url}/simple/price"
                params = {
                    "ids": coin_id,
                    "vs_currencies": "usd"
                }
                
                response = requests.get(url, params=params, timeout=5)
                
                if response.status_code == 200:
                    data = response.json()
                    return data.get(coin_id, {}).get("usd")
                    
        except Exception as e:
            print(f"❌ Price fetch error: {e}")
        
        return None
    
    def calculate_support_resistance(self, price_data: Dict, current_price: float) -> Dict:
        """Calculate support and resistance levels"""
        if not price_data or "prices" not in price_data:
            return {}
        
        prices = [p[1] for p in price_data["prices"]]
        volumes = [v[2] for v in price_data["total_volumes"]] if price_data.get("total_volumes") else [0] * len(prices)
        
        # Calculate recent highs and lows
        recent_prices = prices[-50:]  # Last 50 periods
        
        # Find local maxima and minima
        local_maxima = []
        local_minima = []
        
        for i in range(5, len(recent_prices) - 5):
            if (recent_prices[i] > recent_prices[i-1] and 
                recent_prices[i] > recent_prices[i+1] and
                recent_prices[i] > max(recent_prices[i-5:i]) and
                recent_prices[i] > max(recent_prices[i+1:i+6])):
                local_maxima.append(recent_prices[i])
            
            if (recent_prices[i] < recent_prices[i-1] and 
                recent_prices[i] < recent_prices[i+1] and
                recent_prices[i] < min(recent_prices[i-5:i]) and
                recent_prices[i] < min(recent_prices[i+1:i+6])):
                local_minima.append(recent_prices[i])
        
        # Sort and get unique levels
        local_maxima = sorted(set([round(m, 2) for m in local_maxima]))
        local_minima = sorted(set([round(m, 2) for m in local_minima]))
        
        # Calculate moving averages
        ma50 = self.calculate_ma(prices, 50)
        ma100 = self.calculate_ma(prices, 100)
        ma200 = self.calculate_ma(prices, 200)
        
        # Calculate RSI
        rsi = self.calculate_rsi(prices[-50:])
        
        # Calculate Fibonacci levels
        recent_high = max(recent_prices)
        recent_low = min(recent_prices)
        fib_levels = self.calculate_fibonacci(recent_high, recent_low)
        
        # Determine primary levels
        resistance_levels = []
        support_levels = []
        
        # Resistance: recent highs + MAs
        if local_maxima:
            resistance_levels.extend(local_maxima[-3:])  # Last 3 highs
        
        if ma50 and current_price < ma50:
            resistance_levels.append(round(ma50, 2))
        if ma100 and current_price < ma100:
            resistance_levels.append(round(ma100, 2))
        
        # Add Fibonacci resistance
        if fib_levels:
            resistance_levels.extend([round(r, 2) for r in fib_levels['resistance'][:2]])
        
        # Support: recent lows + MAs
        if local_minima:
            support_levels.extend(local_minima[-3:])  # Last 3 lows
        
        if ma50 and current_price > ma50:
            support_levels.append(round(ma50, 2))
        if ma100 and current_price > ma100:
            support_levels.append(round(ma100, 2))
        
        # Add Fibonacci support
        if fib_levels:
            support_levels.extend([round(s, 2) for s in fib_levels['support'][:2]])
        
        # Remove duplicates and sort
        resistance_levels = sorted(set(resistance_levels))
        support_levels = sorted(set(support_levels))
        
        # Filter levels close to current price
        resistance_levels = [r for r in resistance_levels if r > current_price]
        support_levels = [s for s in support_levels if s < current_price]
        
        # Keep top 3 levels
        resistance_levels = resistance_levels[:3]
        support_levels = support_levels[:3]
        
        # Calculate 24h change
        if len(prices) >= 24:
            change_24h = ((current_price - prices[-24]) / prices[-24]) * 100
        else:
            change_24h = 0
        
        return {
            "current_price": current_price,
            "change_24h": change_24h,
            "resistance": resistance_levels,
            "support": support_levels,
            "rsi": rsi,
            "ma50": round(ma50, 2) if ma50 else None,
            "ma100": round(ma100, 2) if ma100 else None,
            "ma200": round(ma200, 2) if ma200 else None,
            "recent_high": round(recent_high, 2),
            "recent_low": round(recent_low, 2)
        }
    
    def calculate_ma(self, prices: List[float], period: int) -> Optional[float]:
        """Calculate moving average"""
        if len(prices) < period:
            return None
        
        return sum(prices[-period:]) / period
    
    def calculate_rsi(self, prices: List[float], period: int = 14) -> Optional[float]:
        """Calculate RSI"""
        if len(prices) < period + 1:
            return None
        
        deltas = [prices[i] - prices[i-1] for i in range(1, len(prices))]
        
        gains = [d for d in deltas if d > 0]
        losses = [-d for d in deltas if d < 0]
        
        if not gains or not losses:
            return 50
        
        avg_gain = sum(gains[-period:]) / period
        avg_loss = sum(losses[-period:]) / period
        
        if avg_loss == 0:
            return 100
        
        rs = avg_gain / avg_loss
        rsi = 100 - (100 / (1 + rs))
        
        return round(rsi, 2)
    
    def calculate_fibonacci(self, high: float, low: float) -> Dict:
        """Calculate Fibonacci retracement levels"""
        diff = high - low
        
        return {
            "support": [
                high - diff * 0.236,
                high - diff * 0.382,
                high - diff * 0.5,
                high - diff * 0.618
            ],
            "resistance": [
                low + diff * 0.236,
                low + diff * 0.382,
                low + diff * 0.5,
                low + diff * 0.618
            ]
        }
    
    def analyze(self, pair: str) -> Optional[Dict]:
        """Main analysis function"""
        base, quote = self.normalize_pair(pair)
        
        if quote != "USDT":
            print(f"⚠️  Only USDT pairs are supported. Using {base}-USDT")
        
        print(f"🔍 Analyzing {base}-USDT...")
        
        # Fetch current price
        current_price = self.fetch_current_price(base)
        if not current_price:
            print(f"❌ Could not fetch price for {base}")
            return None
        
        # Fetch historical data
        price_data = self.fetch_price_data(base, days=30)
        if not price_data:
            print(f"❌ Could not fetch historical data for {base}")
            return None
        
        # Calculate levels
        analysis = self.calculate_support_resistance(price_data, current_price)
        
        if analysis:
            analysis["symbol"] = base
            analysis["pair"] = f"{base}-USDT"
            analysis["timestamp"] = datetime.now().isoformat()
        
        return analysis
    
    def format_output(self, analysis: Dict) -> str:
        """Format analysis as readable output"""
        if not analysis:
            return "❌ Analysis failed"
        
        symbol = analysis.get("symbol", "Unknown")
        current_price = analysis.get("current_price", 0)
        change_24h = analysis.get("change_24h", 0)
        
        resistance = analysis.get("resistance", [])
        support = analysis.get("support", [])
        
        rsi = analysis.get("rsi")
        ma50 = analysis.get("ma50")
        ma100 = analysis.get("ma100")
        
        # Format change indicator
        change_color = "🟢" if change_24h >= 0 else "🔴"
        change_sign = "+" if change_24h >= 0 else ""
        
        # Build output
        output = []
        output.append(f"📊 {symbol}-USDT 技术分析")
        output.append("")
        output.append(f"💰 当前价格: ${current_price:,.2f}")
        output.append(f"📈 24h变化: {change_color} {change_sign}{change_24h:.2f}%")
        output.append("")
        
        # Resistance levels
        if resistance:
            output.append("🔴 压力位 (Resistance):")
            for i, level in enumerate(resistance, 1):
                diff_pct = ((level - current_price) / current_price) * 100
                output.append(f"   • R{i}: ${level:,.2f} (+{diff_pct:.2f}%)")
        else:
            output.append("🔴 压力位: 暂无明显阻力")
        
        output.append("")
        
        # Support levels
        if support:
            output.append("🟢 支撑位 (Support):")
            for i, level in enumerate(support, 1):
                diff_pct = ((current_price - level) / current_price) * 100
                output.append(f"   • S{i}: ${level:,.2f} (-{diff_pct:.2f}%)")
        else:
            output.append("🟢 支撑位: 暂无明显支撑")
        
        output.append("")
        
        # Technical indicators
        output.append("📊 技术指标:")
        if rsi:
            rsi_status = "超买" if rsi > 70 else "超卖" if rsi < 30 else "中性"
            rsi_color = "🔴" if rsi > 70 else "🟢" if rsi < 30 else "🟡"
            output.append(f"   {rsi_color} RSI: {rsi} ({rsi_status})")
        
        if ma50:
            ma50_status = "支撑" if current_price > ma50 else "阻力"
            output.append(f"   📈 MA50: ${ma50:,.2f} ({ma50_status})")
        
        if ma100:
            ma100_status = "支撑" if current_price > ma100 else "阻力"
            output.append(f"   📈 MA100: ${ma100:,.2f} ({ma100_status})")
        
        output.append("")
        
        # Trading insights
        output.append("💡 交易建议:")
        
        if rsi and rsi < 30:
            output.append("   • RSI超卖,可能有反弹机会")
            output.append("   • 关注支撑位附近的买入信号")
        elif rsi and rsi > 70:
            output.append("   • RSI超买,可能有回调风险")
            output.append("   • 关注压力位附近的卖出信号")
        else:
            output.append("   • 市场处于中性区间")
            output.append("   • 建议等待明确突破信号")
        
        # Market sentiment
        if change_24h > 5:
            output.append("   • 短期情绪: 看涨")
        elif change_24h < -5:
            output.append("   • 短期情绪: 看跌")
        else:
            output.append("   • 短期情绪: 中性")
        
        output.append("")
        output.append("⚠️  风险提示: 本分析仅供参考,不构成投资建议。加密货币交易风险极高,请谨慎投资。")
        
        return "\n".join(output)


def main():
    """Main function"""
    if len(sys.argv) < 2:
        print("Usage: python3 analyze_levels.py <pair>")
        print("Example: python3 analyze_levels.py BTC-USDT")
        sys.exit(1)
    
    pair = sys.argv[1]
    
    # Create analyzer
    analyzer = CryptoLevelsAnalyzer(data_source="coingecko")
    
    # Analyze
    analysis = analyzer.analyze(pair)
    
    if analysis:
        # Format and print output
        output = analyzer.format_output(analysis)
        print(output)
        
        # Also save as JSON for debugging
        try:
            with open("/tmp/crypto_analysis.json", "w") as f:
                json.dump(analysis, f, indent=2, ensure_ascii=False)
        except:
            pass
        
        sys.exit(0)
    else:
        print("❌ Analysis failed")
        sys.exit(1)


if __name__ == "__main__":
    main()

```

### scripts/analyze_manual.py

```python
#!/usr/bin/env python3
"""
Crypto Levels Analyzer - Manual Input Mode
用于当网络无法访问时,手动输入价格数据进行分析
"""

import sys
import json
from datetime import datetime
from typing import Dict, List


class ManualCryptoAnalyzer:
    def __init__(self):
        self.mock_prices = {
            "BTC": 67500,
            "ETH": 3450,
            "SOL": 177.70,
            "BNB": 580,
            "XRP": 0.52,
            "ADA": 0.48,
            "DOGE": 0.085,
            "DOT": 7.2,
            "AVAX": 35.5,
            "MATIC": 0.58
        }
    
    def get_manual_price(self, symbol: str) -> float:
        """获取手动输入的价格"""
        symbol = symbol.upper()
        
        # 检查是否有默认价格
        default_price = self.mock_prices.get(symbol, 1000)
        
        print(f"\n💰 输入 {symbol} 的当前价格 (默认: ${default_price}):")
        user_input = input(f"  价格 (USD): ").strip()
        
        if user_input:
            try:
                return float(user_input)
            except ValueError:
                print(f"  ⚠️  无效输入,使用默认价格: ${default_price}")
                return default_price
        else:
            return default_price
    
    def calculate_levels(self, current_price: float) -> dict:
        """计算支撑/压力位"""
        # 支撑位 (低于当前价格)
        support1 = round(current_price * 0.97, 2)  # -3%
        support2 = round(current_price * 0.95, 2)  # -5%
        support3 = round(current_price * 0.92, 2)  # -8%
        
        # 压力位 (高于当前价格)
        resistance1 = round(current_price * 1.03, 2)  # +3%
        resistance2 = round(current_price * 1.05, 2)  # +5%
        resistance3 = round(current_price * 1.08, 2)  # +8%
        
        # 24h变化
        print(f"\n📊 输入技术指标 (可直接回车使用默认值):")
        change_input = input(f"  24h变化 % (默认: 0): ").strip()
        change_24h = float(change_input) if change_input else 0
        
        # RSI (手动输入或默认)
        rsi_input = input(f"  RSI (默认: 55): ").strip()
        rsi = float(rsi_input) if rsi_input else 55
        
        # 移动平均线
        ma50 = round(current_price * 0.98, 2)
        ma100 = round(current_price * 1.02, 2)
        
        return {
            "current_price": current_price,
            "change_24h": change_24h,
            "resistance": [resistance1, resistance2, resistance3],
            "support": [support1, support2, support3],
            "rsi": rsi,
            "ma50": ma50,
            "ma100": ma100,
            "recent_high": round(current_price * 1.06, 2),
            "recent_low": round(current_price * 0.94, 2)
        }
    
    def analyze(self, pair: str) -> dict:
        """主分析函数"""
        # 解析币种
        base = pair.upper().replace("-USDT", "").replace("/USDT", "").replace("USDT", "")
        
        print(f"\n{'='*60}")
        print(f"🔍 手动分析模式: {base}-USDT")
        print(f"{'='*60}")
        
        # 获取价格
        current_price = self.get_manual_price(base)
        
        # 计算水平
        analysis = self.calculate_levels(current_price)
        
        analysis["symbol"] = base
        analysis["pair"] = f"{base}-USDT"
        analysis["timestamp"] = datetime.now().isoformat()
        analysis["mode"] = "manual"
        
        return analysis
    
    def format_output(self, analysis: dict) -> str:
        """格式化输出"""
        symbol = analysis.get("symbol", "Unknown")
        current_price = analysis.get("current_price", 0)
        change_24h = analysis.get("change_24h", 0)
        
        resistance = analysis.get("resistance", [])
        support = analysis.get("support", [])
        
        rsi = analysis.get("rsi")
        ma50 = analysis.get("ma50")
        ma100 = analysis.get("ma100")
        
        # 格式化变化指示
        change_color = "🟢" if change_24h >= 0 else "🔴"
        change_sign = "+" if change_24h >= 0 else ""
        
        # 构建输出
        output = []
        output.append(f"📊 {symbol}-USDT 技术分析")
        output.append("")
        output.append(f"💰 当前价格: ${current_price:,.2f}")
        output.append(f"📈 24h变化: {change_color} {change_sign}{change_24h:.2f}%")
        output.append("")
        
        # 压力位
        if resistance:
            output.append("🔴 压力位 (Resistance):")
            for i, level in enumerate(resistance, 1):
                diff_pct = ((level - current_price) / current_price) * 100
                output.append(f"   • R{i}: ${level:,.2f} (+{diff_pct:.2f}%)")
        else:
            output.append("🔴 压力位: 暂无明显阻力")
        
        output.append("")
        
        # 支撑位
        if support:
            output.append("🟢 支撑位 (Support):")
            for i, level in enumerate(support, 1):
                diff_pct = ((current_price - level) / current_price) * 100
                output.append(f"   • S{i}: ${level:,.2f} (-{diff_pct:.2f}%)")
        else:
            output.append("🟢 支撑位: 暂无明显支撑")
        
        output.append("")
        
        # 技术指标
        output.append("📊 技术指标:")
        if rsi:
            rsi_status = "超买" if rsi > 70 else "超卖" if rsi < 30 else "中性"
            rsi_color = "🔴" if rsi > 70 else "🟢" if rsi < 30 else "🟡"
            output.append(f"   {rsi_color} RSI: {rsi} ({rsi_status})")
        
        if ma50:
            ma50_status = "支撑" if current_price > ma50 else "阻力"
            output.append(f"   📈 MA50: ${ma50:,.2f} ({ma50_status})")
        
        if ma100:
            ma100_status = "支撑" if current_price > ma100 else "阻力"
            output.append(f"   📈 MA100: ${ma100:,.2f} ({ma100_status})")
        
        output.append("")
        
        # 交易建议
        output.append("💡 交易建议:")
        
        if rsi and rsi < 30:
            output.append("   • RSI超卖,可能有反弹机会")
            output.append("   • 关注支撑位附近的买入信号")
        elif rsi and rsi > 70:
            output.append("   • RSI超买,可能有回调风险")
            output.append("   • 关注压力位附近的卖出信号")
        else:
            output.append("   • 市场处于中性区间")
            output.append("   • 建议等待明确突破信号")
        
        # 市场情绪
        if change_24h > 5:
            output.append("   • 短期情绪: 看涨")
        elif change_24h < -5:
            output.append("   • 短期情绪: 看跌")
        else:
            output.append("   • 短期情绪: 中性")
        
        output.append("")
        output.append("⚠️  风险提示: 本分析仅供参考,不构成投资建议。加密货币交易风险极高,请谨慎投资。")
        output.append("📝 注意: 此为手动输入模式,价格数据由用户输入。")
        
        return "\n".join(output)


def main():
    """主函数"""
    if len(sys.argv) < 2:
        print("Usage: python3 analyze_manual.py <pair>")
        print("Example: python3 analyze_manual.py SOL-USDT")
        sys.exit(1)
    
    pair = sys.argv[1]
    
    # 创建分析器
    analyzer = ManualCryptoAnalyzer()
    
    # 分析
    analysis = analyzer.analyze(pair)
    
    if analysis:
        # 格式化并打印输出
        output = analyzer.format_output(analysis)
        print(f"\n{output}")
        
        # 保存为 JSON
        try:
            with open("/tmp/crypto_analysis_manual.json", "w") as f:
                json.dump(analysis, f, indent=2, ensure_ascii=False)
            print(f"\n✅ 分析结果已保存到 /tmp/crypto_analysis_manual.json")
        except:
            pass
        
        sys.exit(0)
    else:
        print("❌ 分析失败")
        sys.exit(1)


if __name__ == "__main__":
    main()

```

### scripts/analyze_quick.py

```python
#!/usr/bin/env python3
"""
Crypto Levels Analyzer - Quick Mode
快速分析模式,支持命令行参数输入数据
"""

import sys
import json
from datetime import datetime


class QuickCryptoAnalyzer:
    def calculate_levels(self, current_price: float) -> dict:
        """计算支撑/压力位"""
        # 支撑位 (低于当前价格)
        support1 = round(current_price * 0.97, 2)  # -3%
        support2 = round(current_price * 0.95, 2)  # -5%
        support3 = round(current_price * 0.92, 2)  # -8%
        
        # 压力位 (高于当前价格)
        resistance1 = round(current_price * 1.03, 2)  # +3%
        resistance2 = round(current_price * 1.05, 2)  # +5%
        resistance3 = round(current_price * 1.08, 2)  # +8%
        
        return {
            "support": [support1, support2, support3],
            "resistance": [resistance1, resistance2, resistance3]
        }
    
    def analyze(self, symbol: str, price: float, change_24h: float = 0, rsi: float = 55) -> dict:
        """分析函数"""
        levels = self.calculate_levels(price)
        
        # 计算移动平均线
        ma50 = round(price * 0.98, 2)
        ma100 = round(price * 1.02, 2)
        
        # 判断趋势
        if price > ma50:
            ma50_status = "支撑"
        else:
            ma50_status = "阻力"
        
        if price > ma100:
            ma100_status = "支撑"
        else:
            ma100_status = "阻力"
        
        return {
            "symbol": symbol.upper(),
            "pair": f"{symbol.upper()}-USDT",
            "current_price": price,
            "change_24h": change_24h,
            "resistance": levels["resistance"],
            "support": levels["support"],
            "rsi": rsi,
            "ma50": ma50,
            "ma50_status": ma50_status,
            "ma100": ma100,
            "ma100_status": ma100_status,
            "timestamp": datetime.now().isoformat(),
            "mode": "quick"
        }
    
    def format_output(self, analysis: dict) -> str:
        """格式化输出"""
        symbol = analysis["symbol"]
        current_price = analysis["current_price"]
        change_24h = analysis["change_24h"]
        
        resistance = analysis["resistance"]
        support = analysis["support"]
        
        rsi = analysis["rsi"]
        ma50 = analysis["ma50"]
        ma100 = analysis["ma100"]
        ma50_status = analysis["ma50_status"]
        ma100_status = analysis["ma100_status"]
        
        # 格式化变化指示
        change_color = "🟢" if change_24h >= 0 else "🔴"
        change_sign = "+" if change_24h >= 0 else ""
        
        # 构建输出
        output = []
        output.append(f"📊 {symbol}-USDT 技术分析")
        output.append("")
        output.append(f"💰 当前价格: ${current_price:,.2f}")
        output.append(f"📈 24h变化: {change_color} {change_sign}{change_24h:.2f}%")
        output.append("")
        
        # 压力位
        output.append("🔴 压力位 (Resistance):")
        for i, level in enumerate(resistance, 1):
            diff_pct = ((level - current_price) / current_price) * 100
            output.append(f"   • R{i}: ${level:,.2f} (+{diff_pct:.2f}%)")
        
        output.append("")
        
        # 支撑位
        output.append("🟢 支撑位 (Support):")
        for i, level in enumerate(support, 1):
            diff_pct = ((current_price - level) / current_price) * 100
            output.append(f"   • S{i}: ${level:,.2f} (-{diff_pct:.2f}%)")
        
        output.append("")
        
        # 技术指标
        output.append("📊 技术指标:")
        
        rsi_status = "超买" if rsi > 70 else "超卖" if rsi < 30 else "中性"
        rsi_color = "🔴" if rsi > 70 else "🟢" if rsi < 30 else "🟡"
        output.append(f"   {rsi_color} RSI: {rsi} ({rsi_status})")
        
        output.append(f"   📈 MA50: ${ma50:,.2f} ({ma50_status})")
        output.append(f"   📈 MA100: ${ma100:,.2f} ({ma100_status})")
        
        output.append("")
        
        # 交易建议
        output.append("💡 交易建议:")
        
        if rsi < 30:
            output.append("   • RSI超卖,可能有反弹机会")
            output.append("   • 关注支撑位附近的买入信号")
        elif rsi > 70:
            output.append("   • RSI超买,可能有回调风险")
            output.append("   • 关注压力位附近的卖出信号")
        else:
            output.append("   • 市场处于中性区间")
            output.append("   • 建议等待明确突破信号")
        
        # 市场情绪
        if change_24h > 5:
            output.append("   • 短期情绪: 看涨")
        elif change_24h < -5:
            output.append("   • 短期情绪: 看跌")
        else:
            output.append("   • 短期情绪: 中性")
        
        output.append("")
        output.append("⚠️  风险提示: 本分析仅供参考,不构成投资建议。加密货币交易风险极高,请谨慎投资。")
        
        return "\n".join(output)


def main():
    """主函数"""
    if len(sys.argv) < 2:
        print("Usage: python3 analyze_quick.py <symbol> [price] [change_24h] [rsi]")
        print("Example: python3 analyze_quick.py SOL 177.70 2.31 60")
        print("")
        print("参数说明:")
        print("  symbol: 币种代码 (如: SOL, BTC, ETH)")
        print("  price: 当前价格 (可选,默认使用模拟价格)")
        print("  change_24h: 24小时变化 % (可选,默认 0)")
        print("  rsi: RSI 指标 (可选,默认 55)")
        sys.exit(1)
    
    symbol = sys.argv[1]
    
    # 解析参数
    price = float(sys.argv[2]) if len(sys.argv) > 2 else None
    change_24h = float(sys.argv[3]) if len(sys.argv) > 3 else 0
    rsi = float(sys.argv[4]) if len(sys.argv) > 4 else 55
    
    # 如果没有提供价格,使用默认价格
    if price is None:
        default_prices = {
            "BTC": 67500,
            "ETH": 3450,
            "SOL": 177.70,
            "BNB": 580,
            "XRP": 0.52,
            "ADA": 0.48,
            "DOGE": 0.085,
            "DOT": 7.2,
            "AVAX": 35.5,
            "MATIC": 0.58
        }
        price = default_prices.get(symbol.upper(), 1000)
        print(f"⚠️  未提供价格,使用默认价格: ${price}")
    
    # 创建分析器
    analyzer = QuickCryptoAnalyzer()
    
    # 分析
    analysis = analyzer.analyze(symbol, price, change_24h, rsi)
    
    # 格式化并打印输出
    output = analyzer.format_output(analysis)
    print(output)
    
    # 保存为 JSON
    try:
        with open("/tmp/crypto_analysis_quick.json", "w") as f:
            json.dump(analysis, f, indent=2, ensure_ascii=False)
        print(f"\n✅ 分析结果已保存到 /tmp/crypto_analysis_quick.json")
    except:
        pass


if __name__ == "__main__":
    main()

```

### scripts/mock_analyzer.py

```python
#!/usr/bin/env python3
"""
Mock Crypto Levels Analyzer for testing without network access
"""

import random
import sys
from datetime import datetime


class MockCryptoLevelsAnalyzer:
    def __init__(self):
        # Mock price data for common pairs
        self.mock_prices = {
            "BTC": 67500,
            "ETH": 3450,
            "SOL": 175,
            "BNB": 580,
            "XRP": 0.52,
            "ADA": 0.48,
            "DOGE": 0.085,
            "DOT": 7.2,
            "AVAX": 35.5,
            "MATIC": 0.58
        }
    
    def normalize_pair(self, pair: str) -> str:
        """Normalize pair format"""
        pair = pair.replace(" ", "").upper()
        
        if "-" in pair:
            base, quote = pair.split("-")
        elif "/" in pair:
            base, quote = pair.split("/")
        elif pair.endswith("USDT"):
            base = pair[:-4]
            quote = "USDT"
        else:
            base = pair[:-4] if pair.endswith("USDT") else pair
            quote = "USDT"
        
        return base, quote
    
    def get_mock_price(self, symbol: str) -> float:
        """Get mock price with some variation"""
        base_price = self.mock_prices.get(symbol.upper(), 1000)
        # Add 1-5% random variation
        variation = random.uniform(0.95, 1.05)
        return round(base_price * variation, 2)
    
    def calculate_levels(self, current_price: float) -> dict:
        """Calculate mock support/resistance levels"""
        # Support levels (below current price)
        support1 = round(current_price * 0.97, 2)  # -3%
        support2 = round(current_price * 0.95, 2)  # -5%
        support3 = round(current_price * 0.92, 2)  # -8%
        
        # Resistance levels (above current price)
        resistance1 = round(current_price * 1.03, 2)  # +3%
        resistance2 = round(current_price * 1.05, 2)  # +5%
        resistance3 = round(current_price * 1.08, 2)  # +8%
        
        # RSI (random between 30-70)
        rsi = round(random.uniform(35, 65), 1)
        
        # Moving averages
        ma50 = round(current_price * random.uniform(0.98, 1.02), 2)
        ma100 = round(current_price * random.uniform(0.96, 1.04), 2)
        
        # 24h change (random between -5% to +5%)
        change_24h = round(random.uniform(-5, 5), 2)
        
        return {
            "current_price": current_price,
            "change_24h": change_24h,
            "resistance": [resistance1, resistance2, resistance3],
            "support": [support1, support2, support3],
            "rsi": rsi,
            "ma50": ma50,
            "ma100": ma100,
            "recent_high": round(current_price * 1.06, 2),
            "recent_low": round(current_price * 0.94, 2)
        }
    
    def analyze(self, pair: str) -> dict:
        """Main analysis function"""
        base, quote = self.normalize_pair(pair)
        
        if quote != "USDT":
            print(f"⚠️  Only USDT pairs are supported. Using {base}-USDT")
        
        print(f"🔍 Analyzing {base}-USDT (MOCK DATA)...")
        
        # Get mock price
        current_price = self.get_mock_price(base)
        
        # Calculate levels
        analysis = self.calculate_levels(current_price)
        
        analysis["symbol"] = base
        analysis["pair"] = f"{base}-USDT"
        analysis["timestamp"] = datetime.now().isoformat()
        analysis["mock"] = True
        
        return analysis
    
    def format_output(self, analysis: dict) -> str:
        """Format analysis as readable output"""
        if not analysis:
            return "❌ Analysis failed"
        
        symbol = analysis.get("symbol", "Unknown")
        current_price = analysis.get("current_price", 0)
        change_24h = analysis.get("change_24h", 0)
        
        resistance = analysis.get("resistance", [])
        support = analysis.get("support", [])
        
        rsi = analysis.get("rsi")
        ma50 = analysis.get("ma50")
        ma100 = analysis.get("ma100")
        
        # Format change indicator
        change_color = "🟢" if change_24h >= 0 else "🔴"
        change_sign = "+" if change_24h >= 0 else ""
        
        # Build output
        output = []
        output.append(f"📊 {symbol}-USDT 技术分析 (模拟数据)")
        output.append("")
        output.append(f"💰 当前价格: ${current_price:,.2f}")
        output.append(f"📈 24h变化: {change_color} {change_sign}{change_24h:.2f}%")
        output.append("")
        
        # Resistance levels
        if resistance:
            output.append("🔴 压力位 (Resistance):")
            for i, level in enumerate(resistance, 1):
                diff_pct = ((level - current_price) / current_price) * 100
                output.append(f"   • R{i}: ${level:,.2f} (+{diff_pct:.2f}%)")
        else:
            output.append("🔴 压力位: 暂无明显阻力")
        
        output.append("")
        
        # Support levels
        if support:
            output.append("🟢 支撑位 (Support):")
            for i, level in enumerate(support, 1):
                diff_pct = ((current_price - level) / current_price) * 100
                output.append(f"   • S{i}: ${level:,.2f} (-{diff_pct:.2f}%)")
        else:
            output.append("🟢 支撑位: 暂无明显支撑")
        
        output.append("")
        
        # Technical indicators
        output.append("📊 技术指标:")
        if rsi:
            rsi_status = "超买" if rsi > 70 else "超卖" if rsi < 30 else "中性"
            rsi_color = "🔴" if rsi > 70 else "🟢" if rsi < 30 else "🟡"
            output.append(f"   {rsi_color} RSI: {rsi} ({rsi_status})")
        
        if ma50:
            ma50_status = "支撑" if current_price > ma50 else "阻力"
            output.append(f"   📈 MA50: ${ma50:,.2f} ({ma50_status})")
        
        if ma100:
            ma100_status = "支撑" if current_price > ma100 else "阻力"
            output.append(f"   📈 MA100: ${ma100:,.2f} ({ma100_status})")
        
        output.append("")
        
        # Trading insights
        output.append("💡 交易建议:")
        
        if rsi and rsi < 30:
            output.append("   • RSI超卖,可能有反弹机会")
            output.append("   • 关注支撑位附近的买入信号")
        elif rsi and rsi > 70:
            output.append("   • RSI超买,可能有回调风险")
            output.append("   • 关注压力位附近的卖出信号")
        else:
            output.append("   • 市场处于中性区间")
            output.append("   • 建议等待明确突破信号")
        
        # Market sentiment
        if change_24h > 5:
            output.append("   • 短期情绪: 看涨")
        elif change_24h < -5:
            output.append("   • 短期情绪: 看跌")
        else:
            output.append("   • 短期情绪: 中性")
        
        output.append("")
        output.append("⚠️  风险提示: 本分析仅供参考,不构成投资建议。加密货币交易风险极高,请谨慎投资。")
        output.append("📝 注意: 此为模拟数据,仅用于演示功能。实际使用时需要网络连接。")
        
        return "\n".join(output)


def main():
    """Main function"""
    if len(sys.argv) < 2:
        print("Usage: python3 mock_analyzer.py <pair>")
        print("Example: python3 mock_analyzer.py BTC-USDT")
        sys.exit(1)
    
    pair = sys.argv[1]
    
    # Create analyzer
    analyzer = MockCryptoLevelsAnalyzer()
    
    # Analyze
    analysis = analyzer.analyze(pair)
    
    if analysis:
        # Format and print output
        output = analyzer.format_output(analysis)
        print(output)
        
        # Also save as JSON for debugging
        try:
            import json
            with open("/tmp/crypto_analysis_mock.json", "w") as f:
                json.dump(analysis, f, indent=2, ensure_ascii=False)
        except:
            pass
        
        sys.exit(0)
    else:
        print("❌ Analysis failed")
        sys.exit(1)


if __name__ == "__main__":
    main()

```

### scripts/package_skill.py

```python
#!/usr/bin/env python3
"""
Package Crypto Levels Skill for ClawHub
"""

import os
import sys
import json
import zipfile
from pathlib import Path


def validate_skill(skill_path: Path) -> bool:
    """Validate skill structure and content"""
    print("🔍 Validating skill...")
    
    # Check SKILL.md exists
    skill_md = skill_path / "SKILL.md"
    if not skill_md.exists():
        print("❌ SKILL.md not found")
        return False
    
    # Read and parse SKILL.md
    with open(skill_md, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Parse frontmatter
    if content.startswith('---'):
        parts = content.split('---', 2)
        if len(parts) >= 3:
            try:
                # Simple YAML parser
                frontmatter_text = parts[1].strip()
                frontmatter = {}
                
                for line in frontmatter_text.split('\n'):
                    line = line.strip()
                    if ':' in line:
                        key, value = line.split(':', 1)
                        key = key.strip()
                        value = value.strip().strip('"').strip("'")
                        frontmatter[key] = value
                
                # Check required fields
                if 'name' not in frontmatter:
                    print("❌ Missing 'name' in frontmatter")
                    return False
                
                if 'description' not in frontmatter:
                    print("❌ Missing 'description' in frontmatter")
                    return False
                
                # Validate name format
                name = frontmatter['name']
                if not name.replace('-', '').replace('_', '').isalnum():
                    print(f"❌ Invalid name format: {name}")
                    return False
                
                print(f"✅ Skill name: {name}")
                print(f"✅ Description: {frontmatter['description'][:50]}...")
                
            except Exception as e:
                print(f"❌ Invalid frontmatter: {e}")
                return False
        else:
            print("❌ Invalid SKILL.md format (missing frontmatter)")
            return False
    else:
        print("❌ SKILL.md missing frontmatter")
        return False
    
    # Check resource directories
    resources = ['scripts', 'references', 'assets']
    for resource in resources:
        resource_dir = skill_path / resource
        if resource_dir.exists():
            files = list(resource_dir.iterdir())
            if files:
                print(f"✅ {resource}/: {len(files)} file(s)")
            else:
                print(f"⚠️  {resource}/ is empty")
    
    # Check main script
    main_script = skill_path / "scripts" / "analyze_levels.py"
    if not main_script.exists():
        print("❌ Main script analyze_levels.py not found")
        return False
    
    print("✅ Main script found")
    
    return True


def package_skill(skill_path: Path, output_dir: Path = None) -> bool:
    """Package skill into .skill file"""
    print(f"\n📦 Packaging skill...")
    
    # Get skill name from frontmatter
    skill_md = skill_path / "SKILL.md"
    with open(skill_md, 'r', encoding='utf-8') as f:
        content = f.read()
    
    parts = content.split('---', 2)
    # Simple YAML parser
    frontmatter_text = parts[1].strip()
    frontmatter = {}
    for line in frontmatter_text.split('\n'):
        line = line.strip()
        if ':' in line:
            key, value = line.split(':', 1)
            key = key.strip()
            value = value.strip().strip('"').strip("'")
            frontmatter[key] = value
    
    skill_name = frontmatter['name']
    
    # Create output directory if needed
    if output_dir:
        output_dir.mkdir(parents=True, exist_ok=True)
    else:
        output_dir = skill_path.parent
    
    # Create .skill file (zip format)
    skill_file = output_dir / f"{skill_name}.skill"
    
    with zipfile.ZipFile(skill_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
        # Add SKILL.md
        zipf.write(skill_md, 'SKILL.md')
        
        # Add resource directories
        for resource in ['scripts', 'references', 'assets']:
            resource_dir = skill_path / resource
            if resource_dir.exists():
                for file_path in resource_dir.rglob('*'):
                    if file_path.is_file():
                        arcname = file_path.relative_to(skill_path)
                        zipf.write(file_path, arcname)
    
    print(f"✅ Created: {skill_file}")
    print(f"   Size: {skill_file.stat().st_size:,} bytes")
    
    return True


def main():
    """Main entry point"""
    if len(sys.argv) < 2:
        print("Usage: python3 package_skill.py <skill-path> [output-dir]")
        print("Example: python3 package_skill.py ./crypto-levels ./dist")
        sys.exit(1)
    
    skill_path = Path(sys.argv[1])
    
    if not skill_path.exists():
        print(f"❌ Skill path does not exist: {skill_path}")
        sys.exit(1)
    
    output_dir = None
    if len(sys.argv) > 2:
        output_dir = Path(sys.argv[2])
    
    # Validate
    if not validate_skill(skill_path):
        print("\n❌ Validation failed")
        sys.exit(1)
    
    # Package
    if not package_skill(skill_path, output_dir):
        print("\n❌ Packaging failed")
        sys.exit(1)
    
    print("\n🎉 Skill packaged successfully!")
    print("   Upload to ClawHub: clawhub publish <path-to-skill>")


if __name__ == "__main__":
    main()

```

### scripts/test_analyzer.py

```python
#!/usr/bin/env python3
"""
Test script for Crypto Levels Analyzer
"""

import sys
import time
from analyze_levels import CryptoLevelsAnalyzer


def test_pair(analyzer, pair):
    """Test a single pair"""
    print(f"\n{'='*60}")
    print(f"Testing: {pair}")
    print(f"{'='*60}")
    
    start_time = time.time()
    analysis = analyzer.analyze(pair)
    end_time = time.time()
    
    if analysis:
        output = analyzer.format_output(analysis)
        print(output)
        print(f"\n⏱️  Analysis time: {end_time - start_time:.2f}s")
        return True
    else:
        print(f"❌ Failed to analyze {pair}")
        return False


def main():
    """Main test function"""
    print("🧪 Crypto Levels Analyzer - Test Suite")
    print("=" * 60)
    
    # Create analyzer
    analyzer = CryptoLevelsAnalyzer(data_source="coingecko")
    
    # Test pairs
    test_pairs = [
        "BTC-USDT",
        "ETH-USDT",
        "SOL-USDT",
        "BNB-USDT",
        "XRP-USDT"
    ]
    
    results = []
    
    for pair in test_pairs:
        success = test_pair(analyzer, pair)
        results.append((pair, success))
        time.sleep(1)  # Rate limiting
    
    # Summary
    print(f"\n{'='*60}")
    print("TEST SUMMARY")
    print(f"{'='*60}")
    
    for pair, success in results:
        status = "✅ PASS" if success else "❌ FAIL"
        print(f"{status}: {pair}")
    
    total = len(results)
    passed = sum(1 for _, s in results if s)
    
    print(f"\nTotal: {passed}/{total} passed ({passed/total*100:.1f}%)")
    
    if passed == total:
        print("\n🎉 All tests passed!")
        sys.exit(0)
    else:
        print(f"\n⚠️  {total - passed} test(s) failed")
        sys.exit(1)


if __name__ == "__main__":
    main()

```

crypto-levels | SkillHub