Skill: hypier/tradingview-quantitative-skills (version 1.0.4)

--- name: tradingview-quantitative description: > Professional quantitative investment analysis system based on TradingView data. Provides intelligent stock screening, technical pattern recognition, market review, risk management, and event-driven analysis with multi-factor scoring and trading strategies. --- # Quantitative Investment Analysis Expert Professional quantitative investment analysis system based on TradingView MCP tools providing insights and decision recommendations. ## Core Rules ### Metadata First Principle **Before calling `tradingview_get_leaderboard`, you must first call `tradingview_get_metadata` to get parameter values:** 1. `type='markets'` → Get `market_code` (required for stock leaderboard) 2. `type='tabs'` + `asset_type` → Get available `tab` values 3. `type='columnsets'` → Get available `columnset` values Complete metadata dictionary (market codes, tabs, columnsets, exchanges) see `references/api-documentation.md`. ### Tool Selection Quick Reference | Need | Tool | Key Parameters | |------|------|---------| | Search instruments | `search_market` | query, filter(stock/crypto/forex...) | | Real-time quotes | `get_quote` / `get_quote_batch` | symbol, session | | K-line data | `get_price` / `get_price_batch` | symbol, timeframe(1/5/15/30/60/240/D/W/M), range(max 500) | | Technical analysis | `get_ta` | symbol, **include_indicators=true for detailed indicators** | | Leaderboard | `get_leaderboard` | asset_type, tab, market_code, **columnset**(overview/performance/valuation/dividends/profitability/income_statement/balance_sheet/cash_flow/technical) | | News | `get_news` / `get_news_detail` | market_country, lang(zh-Hans/en/ja), symbol | | Economic calendar | `get_calendar` | type(economic/earnings/revenue/ipo), from/to(Unix seconds), market | | Metadata | `get_metadata` | type(markets/tabs/columnsets/languages/exchanges) | ## Workflows For detailed steps, see `workflows/ directory: ### Core Analysis - **`deep-stock-analysis.md`** - Deep individual stock analysis (combine quote + price multi-timeframe + ta detailed indicators + news + calendar) - **`smart-screening.md`** - Smart stock screening (leaderboard multi-columnset + ta + price) - **`fundamental-screening.md`** - Fundamental screening (leaderboard valuation/profitability/dividends columnsets) - **`pattern-recognition.md`** - Technical pattern recognition (price + ta + pattern-library reference) - **`multi-timeframe-analysis.md`** - Multi-timeframe trend confirmation (price D/W/M + ta multi-period) ### Market & Sectors - **`market-review.md`** - Market review (leaderboard gainers/losers + news) - **`sector-rotation.md`** - Sector rotation analysis (leaderboard performance columnset + multi-sector comparison) - **`news-briefing.md`** - Financial news briefing (news + news_detail, supports multi-country multi-language) ### Risk & Events - **`risk-assessment.md`** - Risk assessment (price historical data + quote + volatility calculation) - **`event-analysis.md`** - Event-driven analysis (calendar + news + search) - **`calendar-tracking.md`** - Calendar event tracking (calendar 4 types) ### Quotes & Search - **`symbol-search.md`** - Instrument search (search_market) - **`realtime-monitor.md`** - Real-time quote monitoring (quote / quote_batch) - **`multi-symbol-analysis.md`** - Multi-instrument batch analysis (quote_batch + price_batch + ta) - **`exchange-overview.md`** - Exchange overview (metadata exchanges/markets/tabs) ## Reference Knowledge Base For professional methodologies and data dictionaries, see `references/` directory: - **`api-documentation.md`** - Complete TradingView API documentation (endpoints, parameters, metadata dictionary: market codes/tabs/columnsets/exchanges, search keywords: `Market Codes`, `Asset Types and Tabs`, `Column Sets`, `Supported Languages`) - **`mcp-tools-guide.md`** - MCP tools usage guide (tool combination patterns, metadata-first rules, best practices for various scenarios) - **`technical-analysis.md`** - Technical analysis methodology (comprehensive scoring model, trend/momentum/pattern/support-resistance scoring, search keywords: `comprehensive scoring model`, `RSI`, `MACD`, `support resistance`) - **`pattern-library.md`** - Pattern recognition library (classic patterns, recognition algorithms, success rate statistics, search keywords: `double bottom`, `head and shoulders`, `triangle`, `flag`, `candlestick patterns`) - **`risk-management.md`** - Risk management system (position management, stop-loss strategies, portfolio management, search keywords: `Kelly formula`, `volatility`, `stop loss take profit`, `batch position building`) - **`china-a-stock-examples.md`** - China A-share practical cases (stock screening, pattern analysis, market review output examples) ## Disclaimer The analysis and recommendations provided by this Skill are **for reference only** and do not constitute investment advice. Investing involves risks; decisions should be made cautiously.

path: CHANGELOG.md
content: ## 1.0.3 - 2026-03-04

### Security
- Replace actual service domains with example domains in documentation to prevent confusion and improve security
- Remove detailed configuration instructions for example domains
- Add clarification notes that API endpoints use example domains for documentation purposes

## 1.0.2 - 2026-03-04

### Documentation
- Update reference documentation links, change practical examples from A-shares to US stocks
- Enhance API key security instructions and configuration examples

## 1.0.1 - 2026-03-04

### Documentation
- Add installation badges and quick install section
- Shorten SKILL.md description for skills CLI compatibility

## 1.0.0 - 2026-03-02

### Features
- Complete TradingView quantitative investment analysis system
- Smart stock screening with multi-factor scoring
- Technical pattern recognition with confidence assessment
- Market review and hot sector tracking
- Risk management with position sizing and stop-loss recommendations
- Event-driven analysis for earnings, policies, and news
- Deep individual stock analysis with multi-timeframe technical analysis
- Fundamental screening for high dividend, low valuation stocks
- Support for multiple markets: China A-shares, US, Hong Kong, Japan, Korea, Crypto, Forex, Futures

### Documentation
- Complete API documentation and metadata dictionary
- MCP tools usage guide
- Technical analysis methodology
- Pattern recognition library
- Risk management methods
- 15 workflow guides covering all major use cases
- Bilingual documentation (English and Chinese)


path: CHANGELOG.zh.md
content: ## 1.0.3 - 2026-03-04

### 安全性
- 将文档中的实际服务域名替换为示例域名，以防止混淆并提高安全性
- 删除示例域名的详细配置说明
- 添加说明注释，表明 API 端点使用示例域名仅供文档参考

## 1.0.2 - 2026-03-04

### 文档
- 更新参考文档链接，将实践案例从 A 股改为美股
- 增强 API 密钥安全性说明和配置示例

## 1.0.1 - 2026-03-04

### 文档
- 添加安装徽章和快速安装部分
- 缩短 SKILL.md 描述以兼容 skills CLI

## 1.0.0 - 2026-03-02

### 新功能
- 完整的 TradingView 量化投资分析系统
- 智能选股，多因子综合评分
- 技术形态识别，提供置信度评估
- 市场复盘和热点板块追踪
- 风险管理，包含仓位建议和止损止盈推荐
- 事件驱动分析，追踪财报、政策和新闻
- 个股深度分析，多时间框架技术分析
- 基本面筛选，高股息、低估值股票
- 支持多个市场：中国 A 股、美国、香港、日本、韩国、加密货币、外汇、期货

### 文档
- 完整的 API 文档和元数据字典
- MCP 工具使用指南
- 技术分析方法论
- 形态识别库
- 风险管理方法
- 15 个工作流指南，涵盖所有主要用例
- 双语文档（英文和中文）


path: README.md
content: # TradingView Quantitative Investment Analysis Skill

[English](README.md) | [简体中文](README.zh.md)

[![Install with skills](https://img.shields.io/badge/install-skills-blue)](https://skills.sh/hypier/tradingview-quantitative-skills/tradingview-quantitative)
[![GitHub](https://img.shields.io/github/stars/hypier/tradingview-quantitative-skills?style=social)](https://github.com/hypier/tradingview-quantitative-skills)

Professional quantitative investment analysis system based on TradingView data providing intelligent stock screening, technical pattern recognition, market review, risk management, and event-driven analysis.

## Installation

Install this skill with one command:

```bash
npx skills add hypier/tradingview-quantitative-skills
```

## Features

- ✅ **Smart Stock Screening** - Multi-factor comprehensive scoring, dual filtering of technical + fundamental aspects
- 📊 **Technical Pattern Recognition** - Automatically identify classic patterns, provide confidence assessment and trading strategies
- 📈 **Market Review** - Track hot sectors, capital flows, discover investment opportunities
- 🛡️ **Risk Management** - Position suggestions, stop-loss/take-profit, volatility analysis
- 📰 **Event-Driven Analysis** - Track earnings, policies, news, analyze market impact
- 🔍 **Deep Individual Stock Analysis** - Multi-timeframe technical analysis + fundamentals + news comprehensive evaluation
- 💰 **Fundamental Screening** - High dividend, low valuation, profitability screening
- 🔄 **Sector Rotation** - Identify strong sectors and rotation trends

## Quick Start

### 1. Configure MCP Server

Add TradingView MCP server to Cursor or Claude Desktop configuration file:

**Configuration file paths**:
- **macOS/Linux**: `~/Library/Application Support/Cursor/mcp_config.json`
- **Windows**: `%APPDATA%\Cursor\mcp_config.json`

> **📖 Security Notice**: Please read [SECURITY.md](SECURITY.md) for important information about API key management and data privacy.

#### Method 1: Use RapidAPI (Recommended, Ready to Use)

Visit https://rapidapi.com/hypier/api/tradingview-data1 to apply for a free API Key, then configure:

> **⚠️ SECURITY WARNING**: Never commit your real API key to version control. Keep your API key secure and private. The example below uses a placeholder that you must replace with your actual key.

```json
{
  "mcpServers": {
    "RapidAPI Hub - TradingView Data": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "https://mcp.rapidapi.com",
        "--header",
        "x-api-host: tradingview-data1.p.rapidapi.com",
        "--header",
        "x-[REDACTED_SECRET]"
      ]
    }
  }
}
```

**Configuration Steps**:
1. Visit https://rapidapi.com/hypier/api/tradingview-data1
2. Register/login to RapidAPI account
3. Subscribe to free plan (Free tier)
4. Copy your API Key
5. Replace `<YOUR_RAPIDAPI_KEY_HERE>` in the configuration above with your actual API key
6. Restart Cursor/Claude Desktop

#### Method 2: Use Self-Built JWT Token Service

If you already have a RapidAPI Key, you can use a self-built JWT Token service:

**Step 1**: Generate JWT Token

> **⚠️ SECURITY WARNING**: Replace `<YOUR_RAPIDAPI_KEY_HERE>` with your actual API key. Never share or commit your API key.

```bash
curl --request POST \
  --url https://tradingview-data1.p.rapidapi.com/api/mcp/generate \
  --header 'Content-Type: application/json' \
  --header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
  --header 'x-rapidapi-key: <YOUR_RAPIDAPI_KEY_HERE>' \
  --data '{}'
```

**Step 2**: Configure the returned JWT Token to MCP

> **⚠️ SECURITY WARNING**: Replace `<YOUR_JWT_TOKEN_HERE>` with the actual JWT token from Step 1. Never commit tokens to version control.

```json
{
  "mcpServers": {
    "tradingview": {
      "type": "streamable-http",
      "url": "https://mcp.example-mcp-server.com/mcp",
      "headers": {
        "Authorization": "Bearer <YOUR_JWT_TOKEN_HERE>",
        "Accept": "application/json, text/event-stream"
      }
    }
  }
}
```


#### Recommended Configuration

For most users, **Method 1 (RapidAPI) is recommended** because:
- ✅ No need to manually manage token expiration
- ✅ Simple configuration, one-time setup permanent validity
- ✅ Free quota sufficient for personal use
- ✅ Automatic authentication and retry handling

### 2. Verify Installation

After restart, enter in conversation:

```
Please call tradingview_get_metadata to get the list of supported markets
```

If it returns the market list (america, china, japan, etc.), the configuration is successful.

### 3. Start Using

Just ask questions in natural language, for example:

- "Help me select strong stocks from China A-shares"
- "Analyze the technical patterns of BTC/USDT"
- "How is the China A-share market today?"
- "I have 100k capital, want to buy a certain stock, how much should I buy?"
- "Generate today's China financial news briefing"

## Usage Examples

### Smart Stock Screening

```
Help me select stocks from China A-share technology sector that meet the following conditions:
- Technical: RSI 30-70, MACD golden cross
- Fundamental: PE < 30, ROE > 15%
- Market cap: above 5 billion
```

### Individual Stock Analysis

```
Deep analysis of Puyuan Information (688118), including:
- Multi-timeframe technical analysis
- Fundamental data
- Recent news
- Buy recommendations and risk warnings
```

### Market Review

```
How is the China A-share market today? Analyze hot sectors and investment opportunities
```

### Risk Management

```
I have 100k capital, want to buy Puyuan Information, how much should I buy?
Give me position suggestions, stop-loss/take-profit levels and risk-reward ratio
```

## Supported Markets

- 🇨🇳 **China A-shares** - SSE, SZSE, BSE
- 🇺🇸 **United States** - NYSE, NASDAQ
- 🇭🇰 **Hong Kong** - HKEX
- 🇯🇵 **Japan** - TSE
- 🇰🇷 **South Korea** - KRX
- 🪙 **Cryptocurrency** - Binance, Coinbase, OKX, etc.
- 💱 **Forex** - Major currency pairs
- 📦 **Futures** - Commodity, index futures

For complete market list, see `references/api-documentation.md`.

## Frequently Asked Questions

### Q: What to do if prompted "MCP server not found"?

**A**: Check the following points:
1. Confirm `mcp_config.json` path is correct
2. Confirm `tradingview-mcp-server` is correctly built (run `npm run build`)
3. Confirm paths in configuration file use absolute paths
4. Restart Windsurf/Claude Desktop

### Q: What to do if authentication fails?

**A**: 
1. Confirm TradingView account password is correct
2. Confirm account has logged into TradingView website (first time requires web login)
3. If using two-factor authentication, may need app-specific password

### Q: How to get China A-share data?

**A**: 
```
# First get market codes
tradingview_get_metadata(type='markets')

# Use market_code='china' to get A-share data
tradingview_get_leaderboard(
  asset_type='stocks', 
  tab='gainers',
  market_code='china'
)
```

### Q: Which technical indicators are supported?

**A**: When calling `tradingview_get_ta`, set `include_indicators=true` to get:
- Trend indicators: SMA, EMA, MACD, ADX
- Momentum indicators: RSI, Stoch, CCI, Williams %R
- Volume indicators: Volume, MFI
- Support resistance: Pivot Points, Fibonacci
- Others: ATR, Beta, Bollinger Bands

### Q: How to get historical K-line data?

**A**:
```
tradingview_get_price(
  symbol='SSE:600519',    # Exchange:Code
  timeframe='D',          # 1/5/15/30/60/240/D/W/M
  range=120               # Max 500 K-lines
)
```

### Q: Which languages are supported for news data?

**A**: Supports 19 languages, commonly used are:
- `zh-Hans` - Simplified Chinese
- `en` - English
- `ja` - Japanese
- `ko` - Korean

Complete list: `tradingview_get_metadata(type='languages')`

## Directory Structure

```
tradingview-quantitative-skills/
├── README.md                    # This file - User guide
├── SKILL.md                     # AI skill description (for AI)
├── SECURITY.md                  # Security policy and best practices
├── .gitignore                   # Git ignore patterns for sensitive files
├── references/                  # Reference materials
│   ├── api-documentation.md     # Complete API documentation and metadata dictionary
│   ├── mcp-tools-guide.md       # MCP tools usage guide
│   ├── technical-analysis.md    # Technical analysis methodology
│   ├── pattern-library.md       # Pattern recognition library
│   ├── risk-management.md       # Risk management methods
│   └── china-a-stock-examples.md # China A-share practical cases
└── workflows/                   # Workflows (15 total)
    ├── smart-screening.md       # Smart stock screening
    ├── pattern-recognition.md   # Pattern recognition
    ├── market-review.md         # Market review
    ├── risk-assessment.md       # Risk assessment
    ├── event-analysis.md        # Event analysis
    ├── deep-stock-analysis.md   # Deep individual stock analysis
    ├── fundamental-screening.md # Fundamental screening
    ├── sector-rotation.md       # Sector rotation
    └── ...                      # Other workflows
```

## Advanced Usage

### Custom Screening Criteria

Refer to `workflows/smart-screening.md` and `workflows/fundamental-screening.md`, you can combine:
- Technical indicator screening (RSI, MACD, ADX, etc.)
- Fundamental screening (PE, PB, ROE, dividend yield, etc.)
- Market cap, volume screening
- Industry sector screening

### Multi-Market Comparative Analysis

```
Compare today's financial news from China, US, and Japan, analyze market differences
```

### Portfolio Strategy Backtesting

Combining historical K-line data and technical indicators, simple strategy validation can be performed.

## Technical Support

- **API Documentation**: `references/api-documentation.md`
- **Tools Guide**: `references/mcp-tools-guide.md`
- **Practical Cases**: `references/us-stock-examples.md`

## Disclaimer

This tool is for learning and research purposes only and does not constitute any investment advice. Investing involves risks; enter the market cautiously. Any investment decisions made using this tool are at your own risk.

## License

MIT License


path: README.zh.md
content: # TradingView 量化投资分析技能

[English](README.md) | [简体中文](README.zh.md)

[![Install with skills](https://img.shields.io/badge/install-skills-blue)](https://skills.sh/hypier/tradingview-quantitative-skills/tradingview-quantitative)
[![GitHub](https://img.shields.io/github/stars/hypier/tradingview-quantitative-skills?style=social)](https://github.com/hypier/tradingview-quantitative-skills)

基于 TradingView 数据的专业量化投资分析系统，提供智能选股、技术形态识别、市场复盘、风险管理、事件驱动分析等功能。

## 安装

一键安装此技能：

```bash
npx skills add hypier/tradingview-quantitative-skills
```

## 功能特性

- ✅ **智能选股** - 多因子综合评分，技术面+基本面双重筛选
- 📊 **技术形态识别** - 自动识别经典形态，提供置信度评估和交易策略
- 📈 **市场复盘** - 追踪热点板块、资金流向，发现投资机会
- 🛡️ **风险管理** - 仓位建议、止损止盈、波动率分析
- 📰 **事件驱动分析** - 追踪财报、政策、新闻，分析市场影响
- 🔍 **个股深度分析** - 多时间框架技术分析 + 基本面 + 新闻综合评估
- 💰 **基本面筛选** - 高股息、低估值、盈利能力筛选
- 🔄 **板块轮动** - 识别强势板块和轮动趋势

## 快速开始

### 1. 配置 MCP Server

将 TradingView MCP server 添加到 Cursor 或 Claude Desktop 配置文件：

**配置文件路径**：
- **macOS/Linux**: `~/Library/Application Support/Cursor/mcp_config.json`
- **Windows**: `%APPDATA%\\Cursor\\mcp_config.json`

> **📖 安全提示**：请阅读 [SECURITY.md](SECURITY.md) 了解 API 密钥管理和数据隐私的重要信息。

#### 方法一：使用 RapidAPI（推荐，开箱即用）

访问 https://rapidapi.com/hypier/api/tradingview-data1 申请免费 API Key，然后配置：

> **⚠️ 安全警告**：切勿将真实的 API 密钥提交到版本控制系统。请妥善保管您的 API 密钥。下面的示例使用占位符，您必须将其替换为实际的密钥。

```json
{
  "mcpServers": {
    "RapidAPI Hub - TradingView Data": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "https://mcp.rapidapi.com",
        "--header",
        "x-api-host: tradingview-data1.p.rapidapi.com",
        "--header",
        "x-[REDACTED_SECRET]"
      ]
    }
  }
}
```

**配置步骤**：
1. 访问 https://rapidapi.com/hypier/api/tradingview-data1
2. 注册/登录 RapidAPI 账号
3. 订阅免费计划（Free tier）
4. 复制你的 API Key
5. 将上面配置中的 `<YOUR_RAPIDAPI_KEY_HERE>` 替换为你的实际 API 密钥
6. 重启 Cursor/Claude Desktop

#### 方法二：使用自建 JWT Token 服务

如果你已有 RapidAPI Key，可以使用自建 JWT Token 服务：

**步骤 1**：生成 JWT Token

> **⚠️ 安全警告**：将 `<YOUR_RAPIDAPI_KEY_HERE>` 替换为你的实际 API 密钥。切勿分享或提交你的 API 密钥。

```bash
curl --request POST \
  --url https://tradingview-data1.p.rapidapi.com/api/mcp/generate \
  --header 'Content-Type: application/json' \
  --header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
  --header 'x-rapidapi-key: <YOUR_RAPIDAPI_KEY_HERE>' \
  --data '{}'
```

**步骤 2**：将返回的 JWT Token 配置到 MCP

> **⚠️ 安全警告**：将 `<YOUR_JWT_TOKEN_HERE>` 替换为步骤 1 返回的实际 JWT token。切勿将 token 提交到版本控制系统。

```json
{
  "mcpServers": {
    "tradingview": {
      "type": "streamable-http",
      "url": "https://mcp.example-mcp-server.com/mcp",
      "headers": {
        "Authorization": "Bearer <YOUR_JWT_TOKEN_HERE>",
        "Accept": "application/json, text/event-stream"
      }
    }
  }
}
```


#### 推荐配置

对于大多数用户，**推荐使用方法一（RapidAPI）**，因为：
- ✅ 无需手动管理 token 过期
- ✅ 配置简单，一次配置永久有效
- ✅ 免费额度足够个人使用
- ✅ 自动处理认证和重试

### 2. 验证安装

重启后，在对话中输入：

```
请调用 tradingview_get_metadata 获取支持的市场列表
```

如果返回市场列表（america, china, japan 等），说明配置成功。

### 3. 开始使用

直接用自然语言提问即可，例如：

- "帮我从 A 股科技板块中筛选强势股"
- "分析 BTC/USDT 的技术形态"
- "今天 A 股市场怎么样？"
- "我有 10 万资金，想买某只股票，应该买多少？"
- "生成今日中国财经新闻简报"

## 使用示例

### 智能选股

```
帮我从 A 股科技板块中筛选符合以下条件的股票：
- 技术面：RSI 30-70，MACD 金叉
- 基本面：PE < 30，ROE > 15%
- 市值：50 亿以上
```

### 个股分析

```
深度分析普元信息（688118），包括：
- 多时间框架技术分析
- 基本面数据
- 近期新闻
- 买入建议和风险提示
```

### 市场复盘

```
今天 A 股市场怎么样？分析热点板块和投资机会
```

### 风险管理

```
我有 10 万资金，想买普元信息，应该买多少？
给我仓位建议、止损止盈位和风险收益比
```

## 支持的市场

- 🇨🇳 **中国 A 股** - 上交所、深交所、北交所
- 🇺🇸 **美国** - 纽交所、纳斯达克
- 🇭🇰 **香港** - 港交所
- 🇯🇵 **日本** - 东京证券交易所
- 🇰🇷 **韩国** - 韩国交易所
- 🪙 **加密货币** - Binance、Coinbase、OKX 等
- 💱 **外汇** - 主要货币对
- 📦 **期货** - 商品、指数期货

完整市场列表见 `references/api-documentation.md`。

## 常见问题

### Q: 提示"找不到 MCP server"怎么办？

**A**: 检查以下几点：
1. 确认 `mcp_config.json` 路径正确
2. 确认 `tradingview-mcp-server` 已正确构建（运行 `npm run build`）
3. 确认配置文件中的路径使用绝对路径
4. 重启 Windsurf/Claude Desktop

### Q: 认证失败怎么办？

**A**:
1. 确认 TradingView 账号密码正确
2. 确认账号已登录过 TradingView 网站（首次需要网页登录）
3. 如果使用了两步验证，可能需要应用专用密码

### Q: 如何获取 A 股数据？

**A**:
```
# 先获取市场代码
tradingview_get_metadata(type='markets')

# 使用 market_code='china' 获取 A 股数据
tradingview_get_leaderboard(
  asset_type='stocks',
  tab='gainers',
  market_code='china'
)
```

### Q: 支持哪些技术指标？

**A**: 调用 `tradingview_get_ta` 时设置 `include_indicators=true` 可获取：
- 趋势指标：SMA、EMA、MACD、ADX
- 动量指标：RSI、Stoch、CCI、Williams %R
- 成交量指标：Volume、MFI
- 支撑阻力：Pivot Points、Fibonacci
- 其他：ATR、Beta、Bollinger Bands

### Q: 如何获取历史 K 线数据？

**A**:
```
tradingview_get_price(
  symbol='SSE:600519',    # 交易所:代码
  timeframe='D',          # 1/5/15/30/60/240/D/W/M
  range=120               # 最多 500 根 K 线
)
```

### Q: 新闻数据支持哪些语言？

**A**: 支持 19 种语言，常用的有：
- `zh-Hans` - 简体中文
- `en` - 英语
- `ja` - 日语
- `ko` - 韩语

完整列表：`tradingview_get_metadata(type='languages')`

## 目录结构

```
tradingview-quantitative-skills/
├── README.md                    # 本文件 - 用户指南
├── README.zh.md                 # 中文版用户指南
├── SKILL.md                     # AI 技能描述（给 AI 看的）
├── SECURITY.md                  # 安全策略和最佳实践
├── .gitignore                   # Git 忽略敏感文件的模式
├── references/                  # 参考资料
│   ├── api-documentation.md     # 完整 API 文档和元数据字典
│   ├── mcp-tools-guide.md       # MCP 工具使用指南
│   ├── technical-analysis.md    # 技术分析方法论
│   ├── pattern-library.md       # 形态识别库
│   ├── risk-management.md       # 风险管理方法
│   └── china-a-stock-examples.md # A 股实战案例
└── workflows/                   # 工作流（共 15 个）
    ├── smart-screening.md       # 智能选股
    ├── pattern-recognition.md   # 形态识别
    ├── market-review.md         # 市场复盘
    ├── risk-assessment.md       # 风险评估
    ├── event-analysis.md        # 事件分析
    ├── deep-stock-analysis.md   # 个股深度分析
    ├── fundamental-screening.md # 基本面筛选
    ├── sector-rotation.md       # 板块轮动
    └── ...                      # 其他工作流
```

## 高级用法

### 自定义筛选条件

参考 `workflows/smart-screening.md` 和 `workflows/fundamental-screening.md`，可以组合：
- 技术指标筛选（RSI、MACD、ADX 等）
- 基本面筛选（PE、PB、ROE、股息率等）
- 市值、成交量筛选
- 行业板块筛选

### 多市场对比分析

```
对比今日中美日三国财经新闻，分析市场差异
```

### 组合策略回测

结合历史 K 线数据和技术指标，可以进行简单的策略验证。

## 技术支持

- **API 文档**: `references/api-documentation.md`
- **工具指南**: `references/mcp-tools-guide.md`
- **实战案例**: `references/china-a-stock-examples.md`

## 免责声明

本工具仅供学习研究使用，不构成任何投资建议。投资有风险，入市需谨慎。使用本工具进行的任何投资决策，风险自负。

## 许可证

MIT License


path: SECURITY.md
content: # Security Policy

## API Key Management

This skill requires API keys to access TradingView data through RapidAPI. Please follow these security best practices:

### ⚠️ Critical Security Rules

1. **Never commit API keys to version control**
   - Do not include real API keys in configuration files that are tracked by git
   - Use environment variables or secure configuration management tools
   - Add configuration files with keys to `.gitignore`

2. **Keep your API keys private**
   - Do not share your API keys in public forums, chat rooms, or documentation
   - Do not include API keys in screenshots or screen recordings
   - Treat API keys like passwords

3. **Rotate keys regularly**
   - If you suspect your API key has been compromised, regenerate it immediately
   - Consider rotating keys periodically as a security best practice

4. **Use minimal permissions**
   - Only use API keys with the minimum required permissions
   - Monitor your API usage for unexpected activity

## Data Privacy

### What data is sent to external APIs

When using this skill, the following data may be sent to external services:

- **TradingView API**: Stock symbols, market queries, and analysis requests
- **RapidAPI**: Authentication headers and API requests

### What data is NOT sent

- Your local files and code (unless explicitly referenced in queries)
- Personal information beyond what's required for API authentication
- Conversation history (unless you explicitly include it in queries)

## External Dependencies

This skill relies on the following external services:

- **RapidAPI** (https://rapidapi.com) - API gateway and authentication
- **TradingView Data API** (https://example-mcp-server.com) - Market data provider

These services have their own security policies and terms of service. Please review:
- [RapidAPI Terms of Service](https://rapidapi.com/terms/)
- [RapidAPI Privacy Policy](https://rapidapi.com/privacy/)

## Reporting Security Issues

If you discover a security vulnerability in this skill, please report it by:

1. **Do NOT** open a public GitHub issue
2. Contact the maintainer directly through GitHub private message
3. Provide detailed information about the vulnerability
4. Allow reasonable time for the issue to be addressed before public disclosure

## Security Best Practices for Users

### Configuration File Security

When configuring the MCP server, ensure your configuration file is secure:

```bash
# Set appropriate file permissions (Unix/Linux/macOS)
chmod 600 ~/Library/Application\ Support/Cursor/mcp_config.json
```

### Using Environment Variables (Advanced)

For enhanced security, consider using environment variables instead of hardcoded keys:

```json
{
  "mcpServers": {
    "RapidAPI Hub - TradingView Data": {
      "command": "npx",
      "args": [
        "mcp-remote",
        "https://mcp.rapidapi.com",
        "--header",
        "x-api-host: tradingview-data1.p.rapidapi.com",
        "--header",
        "x-[REDACTED_SECRET]"
      ]
    }
  }
}
```

Then set the environment variable:
```bash
export RAPIDAPI_KEY="your-actual-key-here"
```

### Monitoring API Usage

Regularly check your RapidAPI dashboard to:
- Monitor API call volume
- Detect unusual activity
- Stay within rate limits
- Review billing (if applicable)

## Rate Limiting and Abuse Prevention

- The free tier has rate limits to prevent abuse
- Excessive requests may result in temporary blocks
- Use caching when possible to reduce API calls
- Implement exponential backoff for retries

## Disclaimer

This skill is provided "as is" without warranty of any kind. Users are responsible for:
- Securing their own API keys
- Complying with terms of service of external APIs
- Understanding the risks of using third-party services
- Any investment decisions made using this tool

**Investment Risk Warning**: This tool is for educational and research purposes only. It does not constitute financial advice. All investment decisions are made at your own risk.

## License

This security policy is part of the TradingView Quantitative Skills project and is licensed under the MIT License.


path: references/api-documentation.md
content: # TradingView Data API

Access real-time market data from TradingView with our comprehensive REST API, WebSocket support, and Model Context Protocol (MCP) integration. Get stock quotes, candlestick data, technical analysis, market leaderboards, and financial news for stocks, crypto, forex, futures, bonds, and ETFs. Includes WebSocket support for live data streaming with real-time price updates and quotes, and MCP support for AI assistant integration.

## Available Endpoints

### 📊 Price Data
Historical and real-time OHLCV (Open, High, Low, Close, Volume) candlestick data for charting and analysis.
- **GET /api/price/{symbol}** - Get OHLCV candlestick data with customizable timeframes (1, 5, 15, 30, 60, 240, D, W, M)
- **POST /api/price/batch** - Fetch candlestick data for multiple symbols in one request (max 10)

### 💹 Real-time Quotes
Live market quotes with current prices, bid/ask spreads, volume, and price changes for real-time trading decisions.
- **GET /api/quote/{symbol}** - Get real-time quote data including price, change, volume, bid/ask
- **POST /api/quote/batch** - Get real-time quotes for multiple symbols in one request (max 10)

### 🔍 Market Search
Search and discover trading instruments across stocks, crypto, forex, and other asset types by keyword or symbol.
- **GET /api/search/market/{query}** - Search for stocks, crypto, forex, and other markets by keyword (supports optional filter and offset parameters)

### 📈 Technical Analysis
Professional technical analysis signals and indicators to identify buy/sell opportunities across multiple timeframes.
- **GET /api/ta/{symbol}** - Get professional technical analysis signals (Buy/Sell/Neutral) across multiple timeframes
- **GET /api/ta/{symbol}/indicators** - Get detailed technical indicators data (RSI, MACD, Stoch, CCI, ADX, moving averages, pivot points, etc.)

### 🔄 Batch API
Efficiently retrieve data for multiple symbols in a single request. Batch Get Price Data for up to 10 symbols to retrieve candlestick data, and Batch Get Quotes for up to 10 symbols to access real-time quotes.
- **POST /api/price/batch** - Fetch candlestick data for multiple symbols in one request (max 10)
- **POST /api/quote/batch** - Get real-time quotes for multiple symbols in one request (max 10)

### 📰 Financial News
Access financial news and market updates filtered by symbol, market type, language, and region to stay informed.
- **GET /api/news** - Get financial news list with optional symbol, language, market type, and market country filtering
- **GET /api/news/bond** - Get bond market news
- **GET /api/news/crypto** - Get cryptocurrency market news
- **GET /api/news/economic** - Get economic news
- **GET /api/news/etf** - Get ETF market news
- **GET /api/news/forex** - Get forex market news
- **GET /api/news/futures** - Get futures market news
- **GET /api/news/index** - Get index market news
- **GET /api/news/stock** - Get stock market news
- **GET /api/news/{newsId}** - Get detailed content of a news article by news ID

**News Parameters:**
- `symbol` (optional) - Filter by symbol (e.g., "HKEX:700", "NASDAQ:AAPL")
- `lang` (optional) - Language code (default: "en", e.g., "en", "zh-Hans", "ja")
- `market` (optional, only for /api/news) - Market type filter (stock, crypto, forex, futures, bond, etf, index, economic)
- `market_country` (optional) - Market country code filter (e.g., "US", "CN")

### 🏆 Market Leaderboards
Discover top performers, gainers, losers, and trending instruments across different asset types and markets.
- **GET /api/leaderboard/stocks** - Get stock leaderboard data (requires `market_code` parameter)
- **GET /api/leaderboard/indices** - Get indices leaderboard data
- **GET /api/leaderboard/crypto** - Get cryptocurrency leaderboard data
- **GET /api/leaderboard/futures** - Get futures leaderboard data
- **GET /api/leaderboard/forex** - Get forex leaderboard data
- **GET /api/leaderboard/bonds** - Get government bonds leaderboard data
- **GET /api/leaderboard/corporate-bonds** - Get corporate bonds leaderboard data
- **GET /api/leaderboard/etfs** - Get ETF/funds leaderboard data
- **GET /api/leaderboard/data** - Get leaderboard data by config ID (legacy endpoint)

**Leaderboard Parameters:**
- `tab` (required) - Tab identifier (e.g., "gainers", "all", "major")
- `market_code` (required for stocks) - Market code (e.g., "america", "china")
- `columnset` (optional) - Column set name (default: "overview")
- `start` (optional) - Pagination start index (default: 0)
- `count` (optional) - Number of results, max 150 (default: 20)
- `lang` (optional) - Language code (default: "en")

### 📋 Metadata
Retrieve API configuration data including available markets, tabs, column sets, supported languages, and exchanges.
- **GET /api/metadata/markets** - Get all available market codes
- **GET /api/metadata/tabs** - Get all available tab configurations (optional `type` filter)
- **GET /api/metadata/columnsets** - Get column set metadata by asset type
- **GET /api/metadata/languages** - Get supported language list
- **GET /api/metadata/exchanges** - Get all available exchanges list

**Major Exchanges:**

The API supports 353+ exchanges across different asset types. Here are some of the major exchanges:

**Stock Exchanges:**

| Exchange | Code | Country/Region | Description |
|----------|------|----------------|-------------|
| NASDAQ | NASDAQ | US | NASDAQ Stock Market |
| NYSE | NYSE | US | New York Stock Exchange |
| AMEX | AMEX | US | NYSE Arca |
| HKEX | HKEX | Hong Kong | Hong Kong Exchange |
| SSE | SSE | China | Shanghai Stock Exchange |
| SZSE | SZSE | China | Shenzhen Stock Exchange |
| TSE | TSE | Japan | Tokyo Stock Exchange |
| LSE | LSE | UK | London Stock Exchange |
| Euronext | EURONEXT | EU | Euronext NV |
| XETR | XETR | Germany | Xetra |
| B3 | BMFBOVESPA | Brazil | Brasil Bolsa Balcao S.A. |
| TSX | TSX | Canada | Toronto Stock Exchange |
| ASX | ASX | Australia | Australian Securities Exchange |
| NSE | NSE | India | National Stock Exchange of India |
| BSE | BSE | India | Bombay Stock Exchange |

**Cryptocurrency Exchanges:**

| Exchange | Code | Description |
|----------|------|-------------|
| Binance | BINANCE | Binance |
| Coinbase | COINBASE | Coinbase |
| Kraken | KRAKEN | Kraken |
| Bitfinex | BITFINEX | Bitfinex |
| OKX | OKX | OKX |
| Bybit | BYBIT | Bybit |
| Gate | GATE | Gate |
| MEXC | MEXC | MEXC |
| Deribit | DERIBIT | Deribit |
| KuCoin | KUCOIN | KuCoin |
| HTX | HTX | HTX (formerly Huobi) |
| Bitget | BITGET | Bitget |
| Binance.US | BINANCEUS | Binance.US |

**Note:** The complete list of all 353+ exchanges can be retrieved using the `/api/metadata/exchanges` endpoint.

### 📅 Calendar Events
Access economic calendar, earnings calendar, dividends calendar, and IPO calendar data for tracking important market events.
- **GET /api/calendar/economic** - Get economic calendar events (supports multiple countries via market_code)
- **GET /api/calendar/earnings** - Get earnings calendar with earnings release dates and forecasts
- **GET /api/calendar/revenue** - Get dividends calendar with dividend ex-dates and payment dates
- **GET /api/calendar/ipo** - Get IPO calendar with IPO offer times and details

**Calendar Parameters:**
- `from` (required) - Start time (Unix timestamp in seconds, e.g., 1769356800)
- `to` (required) - End time (Unix timestamp in seconds, e.g., 1769961599)
- `market` (optional) - Market code(s), comma-separated (e.g., "america,china", default: "america")

**Response Format:**
All calendar endpoints return data in standard JSON format:
```json
{
  "success": true,
  "data": {
    "totalCount": 661,
    "data": [
      {
        "symbol": "NASDAQ:FLWS",
        "rank": 1,
        "earnings_release_date": 1761821100,
        "name": "FLWS",
        "description": "1-800-FLOWERS.COM, Inc.",
        ...
      }
    ]
  },
  "msg": "Success"
}
```

**Examples:**
- `/api/calendar/economic?from=1769356800&to=1769961599&market=america,china` - Get economic events for China and US
- `/api/calendar/earnings?from=1769356800&to=1769961599&market=america,china` - Get earnings calendar for multiple markets
- `/api/calendar/revenue?from=1769356800&to=1769961599&market=china` - Get dividends calendar for China
- `/api/calendar/ipo?from=1769356800&to=1769961599&market=america,china` - Get IPO calendar for multiple markets

### 🖼️ Logo Images
Get TradingView logo images. The logo path should be obtained from currency-logoid, base-currency-logoid, or logoid fields returned by other endpoints. These fields can be retrieved from Quote endpoints (`/api/quote/{symbol}` and `/api/quote/batch`) and Leaderboard endpoints (`/api/leaderboard/*`). If the path does not have an extension, .svg will be automatically added. Use the `big` parameter to get large size versions.

- **GET /logo** - Get TradingView logo images using URL query parameters

**Logo Parameters:**
- `url` (required) - Logo path (e.g., "apple.svg" or "crypto/XTVCMIDLE"). If no extension is provided, .svg will be automatically added
- `big` (optional) - Set to true to get large size version

**Examples:**
- `/logo?url=apple.svg` - Get Apple logo
- `/logo?url=apple&big=true` - Get Apple logo (big version)
- `/logo?url=crypto/XTVCMIDLE&big=true` - Get cryptocurrency logo (big version)

**Logo Path Examples by Category:**

| Category | Example Paths |
|----------|---------------|
| **Exchange Providers** | `provider/binance`, `provider/coinbase`, `provider/kraken`, `provider/bitfinex`, `provider/bybit`, `provider/okx`, `provider/huobi`, `provider/okex`, `provider/bitmex`, `provider/deribit`, `provider/ftx`, `provider/gateio`, `provider/kucoin`, `provider/bitstamp`, `provider/gemini` |
| **Exchange Sources** | `source/NASDAQ`, `source/NYSE`, `source/SSE`, `source/HKEX`, `source/LSE`, `source/TSX`, `source/ASX`, `source/FWB`, `source/EURONEXT`, `source/TSE`, `source/BSE`, `source/NSE`, `source/SGX`, `source/KRX` |
| **Cryptocurrencies** | `crypto/XTVCBTC`, `crypto/XTVCETH`, `crypto/XTVCSOL`, `crypto/XTVCDOGE`, `crypto/XTVCADA`, `crypto/XTVCDOT`, `crypto/XTVCLINK`, `crypto/XTVCMATIC`, `crypto/XTVCAVAX`, `crypto/XTVCLUNA` |
| **Stock Companies** | `apple`, `microsoft`, `alphabet`, `tesla`, `amazon`, `meta-platforms`, `nvidia`, `jpmorgan-chase`, `visa`, `johnson-and-johnson`, `berkshire-hathaway`, `unitedhealth-group`, `mastercard`, `home-depot`, `bank-of-america` |
| **Countries/Regions** | `country/EU`, `country/US`, `country/GB`, `country/JP`, `country/CN`, `country/CA`, `country/AU`, `country/DE`, `country/FR`, `country/IN`, `country/KR`, `country/SG`, `country/HK`, `country/CH`, `country/NL` |

### 🤖 Model Context Protocol (MCP)
Access TradingView data through the Model Context Protocol, enabling AI assistants (like Claude, Cursor) to interact with TradingView tools using a standardized protocol.

**Note:** This section describes the API structure for reference. The actual MCP server endpoints shown use example domains for documentation purposes.

### ⚡ WebSocket Real-time Data
WebSocket endpoint for real-time price updates, quotes, and market data streaming.

**Note:** This section describes the WebSocket API structure for reference. The actual WebSocket endpoints shown use example domains for documentation purposes.


## Key Features

- **Real-time Data**: Live price updates and market information
- **Global Coverage**: Access data from major worldwide exchanges
- **Batch Operations**: Efficiently fetch data for multiple symbols
- **Multiple Timeframes**: Support for various chart intervals
- **Professional Analysis**: Built-in technical analysis indicators
- **Market Leaderboards**: Discover trending stocks and market opportunities through comprehensive leaderboards

## Supported Markets

The API supports 8 different asset types:

- **Stocks**: 68+ markets across North America, Europe, Middle East & Africa, South America, and Asia & Oceania
- **Indices**: Global stock indices including major, regional, and sector indices
- **Cryptocurrency**: All major exchanges and trading pairs
- **Futures**: Commodities, energy, metals, currencies, world indices, and interest rates
- **Forex**: All major, minor, and exotic currency pairs
- **Government Bonds**: Government bonds from global markets
- **Corporate Bonds**: Corporate bonds with various terms and coupon types
- **ETFs/Funds**: Comprehensive ETF and fund coverage worldwide

## Asset Types and Tabs

The following tables show all available asset types, their tabs, and column sets:

### Stocks (25 tabs, 9 column sets)

| Tab ID | Title | Market Code Required |
|--------|-------|---------------------|
| all-stocks | All Stocks | Yes |
| gainers | Top Gainers | Yes |
| losers | Top Losers | Yes |
| large-cap | Large Cap | Yes |
| small-cap | Small Cap | Yes |
| largest-employers | Largest Employers | Yes |
| high-dividend | High Dividend | Yes |
| highest-net-income | Highest Net Income | Yes |
| highest-cash | Most Cash | Yes |
| highest-profit-per-employee | Highest Profit Per Employee | Yes |
| highest-revenue-per-employee | Highest Revenue Per Employee | Yes |
| active | Most Active | Yes |
| unusual-volume | Unusual Volume | Yes |
| most-volatile | Most Volatile | Yes |
| high-beta | High Beta | Yes |
| best-performing | Best Performing | Yes |
| highest-revenue | Highest Revenue | Yes |
| most-expensive | Most Expensive | Yes |
| penny-stocks | Penny Stocks | Yes |
| overbought | Overbought | Yes |
| oversold | Oversold | Yes |
| ath | All-Time High | Yes |
| atl | All-Time Low | Yes |
| 52wk-high | 52 Week High | Yes |
| 52wk-low | 52 Week Low | Yes |

**Column Sets:**

| Column Set ID | Title | Column Count |
|---------------|-------|--------------|
| overview | Overview | 12 |
| performance | Performance | 13 |
| valuation | Valuation | 10 |
| dividends | Dividends | 9 |
| profitability | Profitability | 12 |
| income_statement | Income Statement | 10 |
| balance_sheet | Balance Sheet | 10 |
| cash_flow | Cash Flow | 9 |
| technical | Technical | 14 |

### Indices (11 tabs, 3 column sets)

| Tab ID | Title | Market Code Required |
|--------|-------|---------------------|
| all | All | No |
| major | Major | No |
| us | US | No |
| snp | S&P | No |
| currency | Currency | No |
| americas | Americas | No |
| europe | Europe | No |
| asia | Asia | No |
| pacific | Pacific | No |
| middle-east | Middle East | No |
| africa | Africa | No |

**Column Sets:**

| Column Set ID | Title |
|---------------|-------|
| overview | Overview |
| performance | Performance |
| technical | Technical |

### Cryptocurrencies (20 tabs, 3 column sets)

| Tab ID | Title | Market Code Required |
|--------|-------|---------------------|
| all | All | No |
| highest-total-value-locked | Highest Total Value Locked | No |
| defi | Defi | No |
| gainers | Gainers | No |
| losers | Losers | No |
| large-cap | Large Cap | No |
| small-cap | Small Cap | No |
| most-traded | Most Traded | No |
| most-addresses-with-balance | Most Addresses With Balance | No |
| most-addresses-active | Most Addresses Active | No |
| most-transactions | Most Transactions | No |
| highest-transaction-volume | Highest Transaction Volume | No |
| lowest-supply | Lowest Supply | No |
| highest-supply | Highest Supply | No |
| most-expensive | Most Expensive | No |
| most-volatile | Most Volatile | No |
| all-time-high | All-Time High | No |
| all-time-low | All-Time Low | No |
| 52-week-high | 52 Week High | No |
| 52-week-low | 52 Week Low | No |

**Column Sets:**

| Column Set ID | Title |
|---------------|-------|
| overview | Overview |
| performance | Performance |
| technical | Technical |

### Futures (7 tabs, 2 column sets)

| Tab ID | Title | Market Code Required |
|--------|-------|---------------------|
| all | All | No |
| agricultural | Agricultural | No |
| energy | Energy | No |
| currencies | Currencies | No |
| metals | Metals | No |
| world-indices | World Indices | No |
| interest-rates | Interest Rates | No |

**Column Sets:**

| Column Set ID | Title |
|---------------|-------|
| overview | Overview |
| performance | Performance |

### Forex (10 tabs, 3 column sets)

| Tab ID | Title | Market Code Required |
|--------|-------|---------------------|
| all | All | No |
| major | Major | No |
| minor | Minor | No |
| exotic | Exotic | No |
| americas | Americas | No |
| europe | Europe | No |
| asia | Asia | No |
| pacific | Pacific | No |
| middle-east | Middle East | No |
| africa | Africa | No |

**Column Sets:**

| Column Set ID | Title |
|---------------|-------|
| overview | Overview |
| performance | Performance |
| technical | Technical |

### Government Bonds (17 tabs, 2 column sets)

| Tab ID | Title | Market Code Required |
|--------|-------|---------------------|
| all | All | No |
| all-10-year | All 10 Year | No |
| major | Major | No |
| americas | Americas | No |
| europe | Europe | No |
| asia | Asia | No |
| pacific | Pacific | No |
| middle-east | Middle East | No |
| africa | Africa | No |
| usa | USA | No |
| uk | UK | No |
| eu | EU | No |
| germany | Germany | No |
| france | France | No |
| china | China | No |
| india | India | No |
| japan | Japan | No |

**Column Sets:**

| Column Set ID | Title |
|---------------|-------|
| overview | Overview |
| performance | Performance |

### Corporate Bonds (6 tabs, 1 column set)

| Tab ID | Title | Market Code Required |
|--------|-------|---------------------|
| highest-yield | Highest Yield | No |
| long-term | Long Term | No |
| short-term | Short Term | No |
| floating-rate | Floating Rate | No |
| fixed-coupon | Fixed Coupon | No |
| zero-coupon | Zero Coupon | No |

**Column Sets:**

| Column Set ID | Title |
|---------------|-------|
| overview | Overview |

### ETFs/Funds (40 tabs, 3 column sets)

| Tab ID | Title | Market Code Required |
|--------|-------|---------------------|
| largest | Largest | No |
| highest-aum-growth | Highest AUM Growth | No |
| highest-returns | Highest Returns | No |
| biggest-losers | Biggest Losers | No |
| equity | Equity | No |
| bitcoin | Bitcoin | No |
| ethereum | Ethereum | No |
| gold | Gold | No |
| fixed-income | Fixed Income | No |
| real-estate | Real Estate | No |
| total-market | Total Market | No |
| commodities | Commodities | No |
| asset-allocation | Asset Allocation | No |
| inverse-etfs | Inverse ETFs | No |
| leveraged-etfs | Leveraged ETFs | No |
| most-traded | Most Traded | No |
| largest-inflows | Largest Inflows | No |
| largest-outflows | Largest Outflows | No |
| highest-discount | Highest Discount | No |
| highest-premium | Highest Premium | No |
| highest-yield | Highest Yield | No |
| dividend | Dividend | No |
| monthly-distributions | Monthly Distributions | No |
| highest-diversification | Highest Diversification | No |
| actively-managed | Actively Managed | No |
| sector-etfs | Sector ETFs | No |
| highest-beta | Highest Beta | No |
| lowest-beta | Lowest Beta | No |
| negative-beta | Negative Beta | No |
| highest-expense-ratio | Highest Expense Ratio | No |
| all-time-high | All-Time High | No |
| all-time-low | All-Time Low | No |
| 52-week-high | 52 Week High | No |
| 52-week-low | 52 Week Low | No |
| usa | USA | No |
| canada | Canada | No |
| uk | UK | No |
| germany | Germany | No |
| japan | Japan | No |
| australia | Australia | No |

**Column Sets:**

| Column Set ID | Title |
|---------------|-------|
| overview | Overview |
| performance | Performance |
| technical | Technical |

## Market Codes

Market codes are required for stock leaderboard queries. Available market codes:

| Region | Country | Market Code |
|--------|---------|-------------|
| North America | United States | america |
| North America | Canada | canada |
| Europe | Austria | austria |
| Europe | Belgium | belgium |
| Europe | Switzerland | switzerland |
| Europe | Cyprus | cyprus |
| Europe | Czech Republic | czech |
| Europe | Germany | germany |
| Europe | Denmark | denmark |
| Europe | Estonia | estonia |
| Europe | Spain | spain |
| Europe | Finland | finland |
| Europe | France | france |
| Europe | Greece | greece |
| Europe | Hungary | hungary |
| Europe | Ireland | ireland |
| Europe | Iceland | iceland |
| Europe | Italy | italy |
| Europe | Lithuania | lithuania |
| Europe | Latvia | latvia |
| Europe | Luxembourg | luxembourg |
| Europe | Netherlands | netherlands |
| Europe | Norway | norway |
| Europe | Poland | poland |
| Europe | Portugal | portugal |
| Europe | Serbia | serbia |
| Europe | Russia | russia |
| Europe | Romania | romania |
| Europe | Sweden | sweden |
| Europe | Slovakia | slovakia |
| Europe | Turkey | turkey |
| Europe | United Kingdom | uk |
| Middle East & Africa | United Arab Emirates | uae |
| Middle East & Africa | Bahrain | bahrain |
| Middle East & Africa | Egypt | egypt |
| Middle East & Africa | Israel | israel |
| Middle East & Africa | Kenya | kenya |
| Middle East & Africa | Kuwait | kuwait |
| Middle East & Africa | Morocco | morocco |
| Middle East & Africa | Nigeria | nigeria |
| Middle East & Africa | Qatar | qatar |
| Middle East & Africa | Saudi Arabia | saudi-arabia |
| Middle East & Africa | Tunisia | tunisia |
| Middle East & Africa | South Africa | south-africa |
| South America | Argentina | argentina |
| South America | Brazil | brazil |
| South America | Chile | chile |
| South America | Colombia | colombia |
| South America | Mexico | mexico |
| South America | Peru | peru |
| South America | Venezuela | venezuela |
| Asia & Oceania | Australia | australia |
| Asia & Oceania | Bangladesh | bangladesh |
| Asia & Oceania | China | china |
| Asia & Oceania | Hong Kong | hong-kong |
| Asia & Oceania | Indonesia | indonesia |
| Asia & Oceania | India | india |
| Asia & Oceania | Japan | japan |
| Asia & Oceania | South Korea | korea |
| Asia & Oceania | Sri Lanka | sri-lanka |
| Asia & Oceania | Malaysia | malaysia |
| Asia & Oceania | New Zealand | new-zealand |
| Asia & Oceania | Philippines | philippines |
| Asia & Oceania | Pakistan | pakistan |
| Asia & Oceania | Singapore | singapore |
| Asia & Oceania | Thailand | thailand |
| Asia & Oceania | Taiwan | taiwan |
| Asia & Oceania | Vietnam | vietnam |

## Supported Languages

The API supports the following languages (use `lang` parameter):

| Code | Language |
|------|----------|
| en | English |
| zh | 简体中文 |
| de | Deutsch |
| fr | Français |
| es | Español |
| it | Italiano |
| pl | Polski |
| tr | Türkçe |
| ru | Русский |
| pt | Português |
| id | Bahasa Indonesia |
| ms | Bahasa Melayu |
| th | ภาษาไทย |
| vi | Tiếng Việt |
| ja | 日本語 |
| ko | 한국어 |
| zh_TW | 繁體中文 |
| ar | العربية |
| he | עברית |

## Usage Examples

### Get Stock Leaderboard
```bash
# Get top gainers for US stocks
GET /api/leaderboard/stocks?tab=gainers&market_code=america&columnset=overview&count=20
```

### Get Cryptocurrency Leaderboard
```bash
# Get all cryptocurrencies
GET /api/leaderboard/crypto?tab=all&columnset=overview&count=50
```

### Get News
```bash
# Get stock news for a specific symbol
GET /api/news/stock?symbol=HKEX:700&lang=zh-Hans&market_country=US

# Get cryptocurrency news
GET /api/news/crypto?lang=en

# Get general news with market filter
GET /api/news?market=stock&market_country=US&lang=en

# Get news detail by ID
GET /api/news/tag:reuters.com,2025:newsml_L1N3XK042:0?lang=en
```

### Get Metadata
```bash
# Get all tabs for crypto
GET /api/metadata/tabs?type=crypto

# Get all available markets
GET /api/metadata/markets

# Get columnsets by asset type
GET /api/metadata/columnsets

# Get all available exchanges
GET /api/metadata/exchanges
```


Start building with TradingView data today!


path: references/china-a-stock-examples.md
content: # China A-Share Practical Examples

## Example 1: Smart Stock Selection - Technology Sector

**User Request**:
```
"Help me screen for strong stocks from the A-share technology sector"
```

**Skill Execution Process**:

1. Get technology sector candidate pool (150 stocks)
2. Technical screening (RSI, MACD, trend)
3. Comprehensive scoring and ranking
4. Return Top 10

**Output Result**:
```markdown
# Smart Stock Selection Results - A-Share Technology Sector

## Qualified Stocks (Total: 10)

### 1. Primeton (688118) ⭐⭐⭐⭐⭐
**Overall Score**: 92/100

**Technical Analysis**:
- Trend: Strong uptrend 📈
- RSI(14): 65.3 (healthy range)
- MACD: Golden cross day 3, strong momentum
- Volume: 2.1x relative to average volume
- Support: ¥33.50
- Resistance: ¥37.80

**Fundamental Highlights**:
- Market Cap: ¥3.23 billion
- PE: 28.5 (reasonable)
- ROE: 18.2%
- Industry: Cloud Computing/AI

**Buy Recommendation**: ✅ Strongly Recommended
- Suggested Entry: ¥35.00-35.50
- Target Price: ¥40.00
- Stop Loss: ¥33.00
- Position Size: 10-15%
```

---

## Example 2: Pattern Recognition - BTC/USDT

**User Request**:
```
"Analyze BTC/USDT technical patterns"
```

**Output Result**:
```markdown
# BTC/USDT Technical Pattern Analysis

## Identified Patterns

### 🔍 Ascending Triangle (Confidence: 85%)
- Upper Boundary: $68,200
- Lower Boundary: Rising trendline
- Current Position: Near upper boundary

## Trading Strategy

### Strategy A: Breakout Buy
- Entry: Breakout above $68,200
- Target: $72,000
- Stop Loss: $66,500
- Risk-Reward Ratio: 1:2.4
```

---

## Example 3: Market Review

**User Request**:
```
"Generate today's A-share market review report"
```

**Output Result**:
```markdown
# A-Share Market Review - March 1, 2026

## Market Overview
- Shanghai Composite: 3,245.67 (+1.2%)
- Advance/Decline Ratio: 3,245 : 1,432 (2.27:1)
- Trading Volume: ¥987.6 billion (+15%)

## Hot Sectors
1. Cloud Computing (+3.2%) - Price increase cycle
2. Artificial Intelligence (+2.8%) - Policy support
3. New Energy (+1.5%) - Earnings improvement
```


path: references/mcp-tools-guide.md
content: # MCP Tools Usage Guide

> Metadata-first rules, tool combination patterns, best practices for various scenarios

---

## Metadata-First Rules

Before calling tools that require parameter values, first get available values through `tradingview_get_metadata`. For complete metadata dictionary, see `api-documentation.md` (search for `Market Codes`, `Asset Types and Tabs`).

### When to Call Metadata

| Scenario | Call Method | Parameters Obtained |
|----------|------------|-------------------|
| Query stock leaderboard | `get_metadata(type='markets')` | market_code (e.g., america, china) |
| Query any leaderboard | `get_metadata(type='tabs', asset_type='stocks')` | tab (e.g., gainers, losers) |
| Need non-overview data | `get_metadata(type='columnsets')` | columnset (e.g., valuation, dividends) |
| Unsure about exchanges | `get_metadata(type='exchanges')` | 353+ exchange list |

### Common market_code Quick Reference

No need to call metadata every time, here are common values:

- **North America**: america, canada
- **Europe**: uk, germany, france, switzerland, spain, italy
- **Asia**: china, hong-kong, japan, korea, india, taiwan, singapore
- **Others**: australia, brazil

### Common columnset Quick Reference

| columnset | Data Included | Use Cases |
|-----------|--------------|-----------|
| overview | Price, change percentage, market cap, volume | Default overview |
| performance | 1W/1M/3M/6M/1Y/YTD returns | Performance comparison, sector rotation |
| valuation | PE, PB, PS, EV/EBITDA | Valuation screening |
| dividends | Dividend yield, payout ratio, ex-dividend date | High dividend strategy |
| profitability | ROE, ROA, gross margin, net margin | Profitability screening |
| income_statement | Revenue, net profit, EPS | Financial analysis |
| balance_sheet | Total assets, debt ratio, current ratio | Financial health |
| cash_flow | Operating/investing/financing cash flow | Cash flow analysis |
| technical | RSI, Beta, SMA, ATR | Technical overview |

---

## Tool Combination Patterns

### Pattern 1: Deep Individual Stock Analysis

```
1. search_market(query="company name") → Get accurate symbol
2. get_quote(symbol) → Real-time price, change, volume
3. get_price(symbol, timeframe='D', range=120) → Daily K-line data
4. get_ta(symbol, include_indicators=true) → Detailed technical indicators
5. get_news(symbol=symbol, lang='zh-Hans') → Related news
6. get_calendar(type='earnings', from/to) → Recent earnings dates
```

### Pattern 2: Smart Stock Screening (Technical + Fundamental)

```
1. get_metadata(type='markets') → Confirm market_code
2. get_metadata(type='tabs', asset_type='stocks') → Confirm tab
3. get_leaderboard(asset_type='stocks', tab='gainers', market_code, columnset='overview') → Candidate pool
4. get_leaderboard(same, columnset='valuation') → Valuation data
5. get_leaderboard(same, columnset='profitability') → Profitability data
6. For Top candidates: get_ta(symbol, include_indicators=true) → Technical verification
7. For Top candidates: get_price(symbol, timeframe='D', range=60) → K-line verification
```

### Pattern 3: Multi-Timeframe Trend Confirmation

```
1. get_price(symbol, timeframe='M', range=24) → Monthly trend
2. get_price(symbol, timeframe='W', range=52) → Weekly trend
3. get_price(symbol, timeframe='D', range=120) → Daily trend
4. get_price(symbol, timeframe='60', range=100) → 60-minute details
5. get_ta(symbol, include_indicators=true) → Multi-period TA signals
```

Signal consistency: Monthly/weekly/daily trend direction consistent → High confidence

### Pattern 4: Sector Rotation Analysis

```
1. get_metadata(type='tabs', asset_type='stocks') → Get all tabs
2. get_leaderboard(tab='best-performing', columnset='performance') → Sector performance
3. Compare performance columnset data from different tabs
4. get_news(market='stock', market_country='CN') → News confirm hotspots
```

### Pattern 5: Fundamental Screening

```
1. get_leaderboard(tab='high-dividend', columnset='dividends') → High dividend
2. get_leaderboard(tab='all-stocks', columnset='valuation') → Low valuation
3. get_leaderboard(tab='all-stocks', columnset='profitability') → High ROE
4. Cross-filter above results → Value stock candidates
```

### Pattern 6: Market Review

```
1. get_leaderboard(tab='gainers', market_code, count=50) → Gainers
2. get_leaderboard(tab='losers', market_code, count=50) → Losers
3. get_leaderboard(tab='active', market_code) → Active stocks
4. get_leaderboard(tab='unusual-volume', market_code) → Unusual volume
5. get_news(market_country='CN', lang='zh-Hans', limit=10) → News
6. For each news: get_news_detail(news_id) → Full content
```

---

## Key Parameter Description

### get_price Timeframe Selection

| timeframe | Meaning | Typical range | Use Cases |
|-----------|---------|--------------|-----------|
| 1 | 1 minute | 60-240 | Intraday trading |
| 5 | 5 minutes | 48-120 | Short-term analysis |
| 15 | 15 minutes | 48-96 | Short-term analysis |
| 60 | 1 hour | 48-168 | Swing analysis |
| 240 | 4 hours | 30-90 | Swing analysis |
| D | Daily | 60-250 | Medium-term analysis |
| W | Weekly | 52-104 | Medium-long term analysis |
| M | Monthly | 24-60 | Long-term trend |

### get_price Chart Types

- Default: Standard K-line
- `type='HeikinAshi'`: Heikin-Ashi, filters noise, clearer trend direction

### get_ta include_indicators Return Fields

Key fields returned when setting `include_indicators=true`:

- **RSI(14)**: Relative Strength Index (>70 overbought, <30 oversold)
- **MACD**: Trend momentum (DIF, DEA, histogram)
- **Stoch**: Stochastic Oscillator (K, D values)
- **CCI(20)**: Commodity Channel Index
- **ADX(14)**: Trend Strength (>25 trending, >50 strong trend)
- **SMA/EMA**: Simple/Exponential Moving Average
- **Pivot Points**: Pivot points (support/resistance levels)

### get_news Language Codes

| Market | lang | market_country |
|---------|------|----------------|
| China | zh-Hans | CN |
| United States | en | US |
| Japan | ja | JP |
| Hong Kong | zh-Hans or en | HK |
| South Korea | ko | KR |

### get_calendar Timestamps

Calendar queries require Unix timestamps (seconds), time span not exceeding 40 days:

```javascript
// Current time
const now = Math.floor(Date.now() / 1000);
// 7 days later
const weekLater = now + 7 * 24 * 60 * 60;
// 14 days later
const twoWeeksLater = now + 14 * 24 * 60 * 60;
```

---

## Multi-Asset Type Support

MCP supports 8 asset types, each with different tabs and columnsets:

| Asset Type | asset_type | Tabs Count | Columnsets | Requires market_code |
|------------|-----------|------------|------------|-------------------|
| Stocks | stocks | 25 | 9 types (including fundamentals) | Yes |
| Indices | indices | 11 | 3 types | No |
| Cryptocurrency | crypto | 20 | 3 types | No |
| Futures | futures | 7 | 2 types | No |
| Forex | forex | 10 | 3 types | No |
| Government Bonds | bonds | 17 | 2 types | No |
| Corporate Bonds | corporate_bonds | 6 | 1 type | No |
| ETF/Funds | etfs | 40 | 3 types | No |

### Crypto-Specific Tabs

DeFi, TVL ranking, address count, volume, supply, etc. → Use `get_metadata(type='tabs', asset_type='crypto')` to see complete list.

### ETF-Specific Tabs

By strategy: bitcoin, gold, fixed-income, leveraged, inverse, sector, etc. 40 categories.


path: references/pattern-library.md
content: # Technical Pattern Recognition Library

> Classic technical pattern recognition algorithms and trading strategies

---

## 📋 Pattern Classification

### Reversal Patterns
- Double Bottom (W-Bottom)
- Double Top (M-Top)
- Head and Shoulders Bottom
- Head and Shoulders Top
- Rounding Bottom
- Rounding Top

### Continuation Patterns
- Ascending Triangle
- Descending Triangle
- Symmetrical Triangle
- Flag Pattern
- Rectangle Pattern
- Wedge Pattern

### Candlestick Patterns
- Hammer
- Inverted Hammer
- Engulfing Pattern
- Morning Star/Evening Star
- Doji

---

## 🔄 Reversal Patterns

### 1. Double Bottom (W-Bottom)

#### Pattern Characteristics
```
Price movement forms a "W" shape
Two lows are close in price
Middle high point (neckline)
```

#### Recognition Criteria

1. **Price difference between two lows < 3%**
```javascript
const priceDiff = Math.abs(low1.price - low2.price) / low1.price;
if (priceDiff > 0.03) return false;
```

2. **Time interval between two lows > 10 days**
```javascript
const timeDiff = (low2.time - low1.time) / (24 * 60 * 60);
if (timeDiff < 10) return false;
```

3. **Neckline height > 10%**
```javascript
const necklineHeight = (neckline.price - low1.price) / low1.price;
if (necklineHeight < 0.1) return false;
```

4. **Second low volume < First low volume**
```javascript
if (low2.volume >= low1.volume) return false;
```

5. **Breakout volume > 1.5x average**
```javascript
const avgVolume = calculateAvgVolume(history, 20);
if (breakoutVolume < avgVolume * 1.5) return false;
```

#### Confidence Calculation

```javascript
function calculateDoubleBottomConfidence(pattern) {
  let score = 60; // Base score

  // Smaller price difference is better
  const priceDiff = Math.abs(pattern.low1.price - pattern.low2.price) / pattern.low1.price;
  if (priceDiff < 0.02) score += 10;
  else if (priceDiff < 0.03) score += 5;

  // Longer time interval is more reliable
  const timeDiff = (pattern.low2.time - pattern.low1.time) / (24 * 60 * 60);
  if (timeDiff > 20) score += 10;
  else if (timeDiff > 15) score += 5;

  // Higher neckline is better
  const necklineHeight = (pattern.neckline - pattern.low1.price) / pattern.low1.price;
  if (necklineHeight > 0.15) score += 10;
  else if (necklineHeight > 0.12) score += 5;

  // Decreasing volume
  if (pattern.low2.volume < pattern.low1.volume * 0.8) score += 5;

  // Breakout with volume expansion
  const avgVolume = pattern.avgVolume;
  if (pattern.breakoutVolume > avgVolume * 2) score += 5;
  else if (pattern.breakoutVolume > avgVolume * 1.5) score += 3;

  return Math.min(score, 100);
}
```

#### Trading Strategy

**Entry Points**:
- Breakout above neckline + volume expansion
- Pullback to neckline without breaking (second entry opportunity)

**Target Price**:
```
Target = Neckline Price + (Neckline Price - Low Price)
```

**Stop Loss**:
```
Stop Loss = 2-3% below second low
```

**Success Rate**:
- Confidence > 85%: 75% success rate
- Confidence 70-85%: 60% success rate
- Confidence < 70%: 45% success rate

---

### 2. Head and Shoulders Bottom

#### Pattern Characteristics
```
Three lows: left shoulder, head, right shoulder
Head is lower than both shoulders
Both shoulders are close in price
```

#### Recognition Criteria

1. **Head is > 5% lower than shoulders**
2. **Price difference between shoulders < 5%**
3. **Head has highest volume**
4. **Breakout with volume expansion**

#### Confidence Calculation

```javascript
function calculateHeadShouldersConfidence(pattern) {
  let score = 60;

  // Head depth
  const headDepth = (pattern.leftShoulder.price - pattern.head.price) / pattern.leftShoulder.price;
  if (headDepth > 0.1) score += 15;
  else if (headDepth > 0.07) score += 10;

  // Shoulder symmetry
  const shoulderDiff = Math.abs(pattern.leftShoulder.price - pattern.rightShoulder.price) / pattern.leftShoulder.price;
  if (shoulderDiff < 0.03) score += 10;
  else if (shoulderDiff < 0.05) score += 5;

  // Volume characteristics
  if (pattern.head.volume > pattern.leftShoulder.volume &&
      pattern.head.volume > pattern.rightShoulder.volume) {
    score += 10;
  }

  // Breakout volume
  if (pattern.breakoutVolume > pattern.avgVolume * 1.5) score += 5;

  return Math.min(score, 100);
}
```

#### Trading Strategy

**Entry Point**: Breakout above neckline

**Target Price**:
```
Target = Neckline Price + (Neckline Price - Head Price)
```

**Stop Loss**: Below right shoulder

---

### 3. Rounding Bottom

#### Pattern Characteristics
```
Price rises in arc shape
Long formation time (> 30 days)
Volume forms bowl shape
```

#### Recognition Criteria

1. **Formation time > 30 days**
2. **Price forms arc shape**
3. **Left side volume > Right side volume**
4. **Bottom has lowest volume**

#### Trading Strategy

**Entry Point**: Breakout above arc top

**Target Price**: 1.5-2x arc height

**Stop Loss**: Arc bottom

---

## 📐 Continuation Patterns

### 1. Ascending Triangle

#### Pattern Characteristics
```
Upper boundary horizontal (resistance level)
Lower boundary ascending (support line)
Volume gradually decreases
Breakout direction upward probability 70%
```

#### Recognition Criteria

1. **Upper boundary horizontal (fluctuation < 2%)**
```javascript
const topRange = (Math.max(...tops) - Math.min(...tops)) / Math.min(...tops);
if (topRange > 0.02) return false;
```

2. **Lower boundary ascending**
```javascript
const slope = calculateSlope(bottoms);
if (slope <= 0) return false;
```

3. **Formation time 10-30 days**
4. **Volume contraction**

#### Confidence Calculation

```javascript
function calculateAscendingTriangleConfidence(pattern) {
  let score = 60;

  // Upper boundary horizontality
  const topRange = (Math.max(...pattern.tops) - Math.min(...pattern.tops)) / Math.min(...pattern.tops);
  if (topRange < 0.01) score += 15;
  else if (topRange < 0.02) score += 10;

  // Lower boundary slope
  const slope = calculateSlope(pattern.bottoms);
  if (slope > 0.02) score += 10;
  else if (slope > 0.01) score += 5;

  // Volume contraction
  if (pattern.recentVolume < pattern.initialVolume * 0.7) score += 10;

  // Touch count
  const touchCount = pattern.tops.length + pattern.bottoms.length;
  if (touchCount >= 6) score += 5;

  return Math.min(score, 100);
}
```

#### Trading Strategy

**Entry Point**: Breakout above upper boundary + volume expansion

**Target Price**:
```
Target = Upper Boundary + Triangle Height
```

**Stop Loss**: Below lower boundary

**Success Rate**: 70%

---

### 2. Flag Pattern

#### Pattern Characteristics
```
Prior significant uptrend (flagpole)
Consolidation forms parallelogram
Short consolidation time (< 20 days)
Volume contraction
Breakout direction consistent with flagpole
```

#### Recognition Criteria

1. **Prior gain > 10%**
2. **Consolidation time < 20 days**
3. **Consolidation range < 50% of prior gain**
4. **Volume contraction**

#### Trading Strategy

**Entry Point**: Breakout above flag upper boundary

**Target Price**:
```
Target = Breakout Point + Flagpole Height
```

**Stop Loss**: Flag lower boundary

---

### 3. Rectangle Pattern

#### Pattern Characteristics
```
Price oscillates between two horizontal lines
Both upper and lower boundaries are horizontal
Volume gradually decreases
```

#### Recognition Criteria

1. **Upper and lower boundaries horizontal (fluctuation < 2%)**
2. **Touch boundary count ≥ 4 times**
3. **Consolidation time 10-40 days**

#### Trading Strategy

**Entry Point**: Breakout above upper boundary + volume expansion

**Target Price**:
```
Target = Upper Boundary + Rectangle Height
```

**Stop Loss**: Below lower boundary

---

## 🕯️ Candlestick Patterns

### 1. Hammer

#### Pattern Characteristics
```
Small body
Lower shadow length > Body × 2
Very short or no upper shadow
Appears at end of downtrend
```

#### Recognition Criteria

```javascript
function isHammer(candle) {
  const body = Math.abs(candle.close - candle.open);
  const lowerShadow = Math.min(candle.open, candle.close) - candle.low;
  const upperShadow = candle.high - Math.max(candle.open, candle.close);

  // Lower shadow > Body × 2
  if (lowerShadow < body * 2) return false;

  // Very short upper shadow
  if (upperShadow > body * 0.5) return false;

  // Body < 30% of total length
  const totalLength = candle.high - candle.low;
  if (body / totalLength > 0.3) return false;

  return true;
}
```

#### Signal Strength

**Strong Buy**:
- Appears at support level
- Volume expansion
- Next day closes bullish for confirmation

**General Buy**:
- Appears in downtrend
- Normal volume

---

### 2. Engulfing Pattern

#### Bullish Engulfing

**Characteristics**:
```
Previous candle: Bearish
Current candle: Bullish completely engulfs previous
Appears in downtrend
Volume expansion
```

**Recognition Criteria**:
```javascript
function isBullishEngulfing(prev, curr) {
  // Previous is bearish
  if (prev.close >= prev.open) return false;

  // Current is bullish
  if (curr.close <= curr.open) return false;

  // Complete engulfing
  if (curr.open >= prev.close && curr.close <= prev.open) return false;
  if (curr.open > prev.open || curr.close < prev.close) return false;

  // Volume expansion
  if (curr.volume < prev.volume * 1.2) return false;

  return true;
}
```

#### Bearish Engulfing

**Characteristics**:
```
Previous candle: Bullish
Current candle: Bearish completely engulfs previous
Appears in uptrend
Volume expansion
```

---

### 3. Morning Star/Evening Star

#### Morning Star (Bullish)

**Three Candle Combination**:
```
First candle: Large bearish
Second candle: Small body (doji best)
Third candle: Large bullish
```

**Recognition Criteria**:
```javascript
function isMorningStar(k1, k2, k3) {
  // First large bearish
  const body1 = k1.open - k1.close;
  if (body1 < (k1.high - k1.low) * 0.6) return false;

  // Second small body
  const body2 = Math.abs(k2.close - k2.open);
  if (body2 > (k2.high - k2.low) * 0.3) return false;

  // Third large bullish
  const body3 = k3.close - k3.open;
  if (body3 < (k3.high - k3.low) * 0.6) return false;

  // Third close > First body midpoint
  if (k3.close < (k1.open + k1.close) / 2) return false;

  return true;
}
```

---

## 🚫 Pattern Failure Recognition

### False Breakout Characteristics

1. **Volume not expanded after breakout**
```javascript
if (breakoutVolume < avgVolume * 1.3) {
  return { type: 'fake_breakout', reason: 'volume_not_confirmed' };
}
```

2. **Quick reversal after breakout**
```javascript
if (closePrice < breakoutPrice * 0.97) {
  return { type: 'fake_breakout', reason: 'quick_reversal' };
}
```

3. **Breakout magnitude < 3%**
```javascript
const breakoutPercent = (breakoutPrice - resistance) / resistance;
if (breakoutPercent < 0.03) {
  return { type: 'weak_breakout', reason: 'insufficient_momentum' };
}
```

4. **Sideways movement after breakout**
```javascript
const daysAfterBreakout = 5;
const priceChange = (currentPrice - breakoutPrice) / breakoutPrice;
if (priceChange < 0.02 && daysPassed > daysAfterBreakout) {
  return { type: 'failed_breakout', reason: 'no_follow_through' };
}
```

### Response Strategies

**Confirm Breakout**:
- Wait 2-3 days after breakout for confirmation
- Observe volume cooperation
- Set stop loss (3% below breakout point)

**False Breakout Stop Loss**:
- Quick stop loss, don't hesitate
- Re-evaluate pattern
- Wait for new opportunities

---

## 📊 Practical Examples

### Example 1: BTC/USDT Ascending Triangle

```
Time: February 15 - March 1, 2026
Pattern: Ascending Triangle

Recognition Process:
1. Upper boundary: $68,200 (horizontal resistance)
2. Lower boundary: Rising trendline
3. Touch count: Upper boundary 3 times, lower boundary 4 times
4. Volume: Gradually contracting
5. Confidence: 85%

Trading Strategy:
- Entry: Breakout above $68,200 and hold
- Target: $72,000 (pattern height $3,800)
- Stop Loss: $66,500
- Risk-Reward Ratio: 1:2.4

Result:
- March 2: Breakout above $68,200
- March 5: Reached target $72,000
- Success: ✅
```

### Example 2: Primeton Double Bottom Pattern

```
Time: January 10 - February 20, 2026
Pattern: Double Bottom (W-Bottom)

Recognition Process:
1. First low: ¥28.50 (January 10)
2. Second low: ¥28.20 (February 5)
3. Price difference: 1.05% ✅
4. Time interval: 26 days ✅
5. Neckline: ¥33.00
6. Neckline height: 15.9% ✅
7. Volume: Decreasing ✅
8. Confidence: 92%

Trading Strategy:
- Entry: Breakout above ¥33.00
- Target: ¥37.50
- Stop Loss: ¥27.50
- Risk-Reward Ratio: 1:2.7

Result:
- February 20: Breakout above neckline
- March 1: Reached ¥35.50 (target not reached but significant profit)
- Success: ✅
```

---

## 💡 Usage Recommendations

### 1. Pattern Recognition Priority

**High Priority**:
- Double Bottom/Double Top
- Head and Shoulders Bottom/Top
- Ascending Triangle

**Medium Priority**:
- Flag Pattern
- Rectangle Pattern
- Rounding Bottom

**Low Priority**:
- Single candlestick patterns (need confirmation with other signals)

### 2. Confirmation Mechanism

**Must Confirm**:
- Volume cooperation
- Breakout validity
- Time period

**Optional Confirmation**:
- Technical indicator support
- Fundamental cooperation
- Market environment

### 3. Risk Control

**Strict Stop Loss**:
- Exit immediately when pattern breaks
- Don't hold false hopes
- Capital protection first

**Staged Position Building**:
- 50% position on breakout
- 30% add after confirmation
- 20% add on trend continuation

---

## 📚 Advanced Learning

### Recommended Books
1. "Technical Analysis of Stock Trends" - Robert D. Edwards
2. "Technical Analysis of the Futures Markets" - John J. Murphy
3. "Japanese Candlestick Charting Techniques" - Steve Nison

### Practice Recommendations
1. Build pattern recognition journal
2. Backtest historical pattern success rates
3. Summarize failure cases
4. Continuously optimize recognition algorithms


path: references/risk-management.md
content: # Risk Management System

> Professional position management, stop loss/take profit, and portfolio risk control methods

---

## 📊 Three Pillars of Risk Management

1. **Position Management** - Control single trade risk
2. **Stop Loss/Take Profit** - Protect profits, limit losses
3. **Portfolio Management** - Diversify risk, optimize returns

---

## 1️⃣ Position Management

### 1.1 Kelly Criterion

#### Formula
```
Optimal Position = (Win Rate × Profit/Loss Ratio - Loss Rate) / Profit/Loss Ratio

Where:
- Win Rate = Winning Trades / Total Trades
- Loss Rate = 1 - Win Rate
- Profit/Loss Ratio = Average Profit / Average Loss
```

#### Example Calculation
```javascript
function calculateKellyPosition(winRate, profitLossRatio) {
  const loseRate = 1 - winRate;
  const kellyPercent = (winRate * profitLossRatio - loseRate) / profitLossRatio;

  // Use half Kelly for conservative approach
  const conservativeKelly = kellyPercent * 0.5;

  return Math.max(0, Math.min(conservativeKelly, 0.25)); // Max 25%
}

// Example
const winRate = 0.6;        // 60% win rate
const plRatio = 2;          // 2:1 profit/loss ratio
const position = calculateKellyPosition(winRate, plRatio);
// Result: (0.6 × 2 - 0.4) / 2 = 0.4 → Half Kelly = 0.2 (20%)
```

#### Practical Application Recommendations
```
Theoretical Kelly Position × 0.5 = Actual Position (conservative)
Single stock max position: 20%
Single sector max position: 40%
Total position control: Adjust based on market environment
```

---

### 1.2 Fixed Percentage Method

#### Method
```
Position = Total Capital × Fixed Percentage
```

#### Risk Level Classification

| Risk Level | Single Position | Target Audience |
|-----------|----------------|-----------------|
| Conservative | 5-10% | Risk averse |
| Balanced | 10-15% | General investors |
| Aggressive | 15-20% | Risk seekers |
| Extreme | >20% | Professional traders |

---

### 1.3 Volatility Adjustment Method

#### Formula
```
Adjusted Position = Base Position × (Standard Volatility / Actual Volatility)

Standard Volatility = 30%
```

#### Implementation
```javascript
function adjustPositionByVolatility(basePosition, volatility) {
  const standardVol = 0.30;  // 30% standard volatility
  const adjustment = standardVol / volatility;

  return basePosition * Math.min(adjustment, 1.5); // Max 1.5x amplification
}

// Example
const basePosition = 0.15;  // 15% base position
const volatility = 0.45;    // 45% volatility (high volatility)
const adjusted = adjustPositionByVolatility(basePosition, volatility);
// Result: 0.15 × (0.30 / 0.45) = 0.10 (10%)
```

---

### 1.4 Pyramid Position Building

#### Normal Pyramid (Recommended)
```
First batch: 50% position - Buy at support level
Second batch: 30% position - Add after 5% profit
Third batch: 20% position - Add after 10% profit
```

**Advantages**:
- Controlled risk
- Lower cost
- Suitable for trend trading

**Example**:
```javascript
function pyramidBuying(capital, currentPrice, entryPrice, position) {
  const profit = (currentPrice - entryPrice) / entryPrice;

  if (position === 0) {
    // First batch: 50%
    return { amount: capital * 0.5, reason: 'Initial position' };
  } else if (position === 1 && profit >= 0.05) {
    // Second batch: 30%
    return { amount: capital * 0.3, reason: 'Add at 5% profit' };
  } else if (position === 2 && profit >= 0.10) {
    // Third batch: 20%
    return { amount: capital * 0.2, reason: 'Add at 10% profit' };
  }

  return { amount: 0, reason: 'No addition' };
}
```

#### Inverted Pyramid (Not Recommended)
```
First batch: 20% position
Second batch: 30% position
Third batch: 50% position
```

**Disadvantages**:
- Excessive risk
- Higher cost
- Easy to get trapped

---

### 1.5 Staged Position Building

#### Three-Part Method
```
First batch: 33% - Buy at support level
Second batch: 33% - Buy at resistance breakout
Third batch: 34% - Buy after trend confirmation
```

#### Five-Part Method (More Conservative)
```
Each batch: 20%
Buy in 5 batches
Interval: Adjust based on market conditions
```

---

## 2️⃣ Stop Loss Strategies

### 2.1 Fixed Percentage Stop Loss

#### Standards
```
Conservative: -5%
Balanced: -7%
Aggressive: -10%
```

#### Implementation
```javascript
function calculateFixedStopLoss(entryPrice, riskLevel = 'balanced') {
  const stopLossPercent = {
    conservative: 0.05,
    balanced: 0.07,
    aggressive: 0.10
  };

  const percent = stopLossPercent[riskLevel] || 0.07;
  return entryPrice * (1 - percent);
}
```

---

### 2.2 Technical Stop Loss

#### Methods

**1. Support Level Stop Loss**
```
Stop Loss = Support Level × 0.98 (2% below support)
```

**2. Moving Average Stop Loss**
```
Short-term: Break below 5-day MA
Medium-term: Break below 20-day MA
Long-term: Break below 60-day MA
```

**3. Pattern Stop Loss**
```
Double Bottom: Below second low
Triangle: Below lower boundary
Head and Shoulders: Below right shoulder
```

#### Implementation
```javascript
function calculateTechnicalStopLoss(currentPrice, support, ma20, pattern) {
  const stops = [];

  // Support level stop loss
  if (support) {
    stops.push({
      price: support * 0.98,
      type: 'support',
      distance: (currentPrice - support * 0.98) / currentPrice
    });
  }

  // Moving average stop loss
  if (ma20) {
    stops.push({
      price: ma20,
      type: 'ma20',
      distance: (currentPrice - ma20) / currentPrice
    });
  }

  // Pattern stop loss
  if (pattern && pattern.stopLoss) {
    stops.push({
      price: pattern.stopLoss,
      type: 'pattern',
      distance: (currentPrice - pattern.stopLoss) / currentPrice
    });
  }

  // Choose nearest stop loss (minimum risk)
  return stops.sort((a, b) => b.price - a.price)[0];
}
```

---

### 2.3 Time-Based Stop Loss

#### Rules
```
Hold 30 days without profit → Consider exit
Hold 60 days without reaching target → Forced exit
```

#### Reasons
- Low capital efficiency
- High opportunity cost
- Possible misjudgment

---

### 2.4 Trailing Stop Loss

#### Strategy
```javascript
function calculateTrailingStop(entryPrice, currentPrice, highestPrice) {
  const profit = (currentPrice - entryPrice) / entryPrice;

  if (profit < 0.05) {
    // Profit < 5%: Stop at cost
    return entryPrice;
  } else if (profit < 0.10) {
    // Profit 5-10%: Stop at cost + 3%
    return entryPrice * 1.03;
  } else if (profit < 0.20) {
    // Profit 10-20%: Stop at cost + 5%
    return entryPrice * 1.05;
  } else {
    // Profit > 20%: Stop at highest - 10%
    return highestPrice * 0.90;
  }
}
```

---

## 3️⃣ Take Profit Strategies

### 3.1 Staged Take Profit

#### Strategy
```
10% profit: Sell 30%
20% profit: Sell 30%
30% profit: Sell 40%
```

#### Advantages
- Lock in partial profits
- Preserve upside potential
- Reduce psychological pressure

#### Implementation
```javascript
function calculatePartialTakeProfit(entryPrice, currentPrice, remainingPosition) {
  const profit = (currentPrice - entryPrice) / entryPrice;

  if (profit >= 0.30 && remainingPosition > 0.4) {
    return { sell: 0.4, reason: '30% profit, sell 40%' };
  } else if (profit >= 0.20 && remainingPosition > 0.7) {
    return { sell: 0.3, reason: '20% profit, sell 30%' };
  } else if (profit >= 0.10 && remainingPosition === 1.0) {
    return { sell: 0.3, reason: '10% profit, sell 30%' };
  }

  return { sell: 0, reason: 'Hold' };
}
```

---

### 3.2 Trailing Take Profit

#### Strategy
```
After profit > 15%
Exit on 5% drawback
```

#### Implementation
```javascript
function calculateTrailingTakeProfit(entryPrice, currentPrice, highestPrice) {
  const profit = (currentPrice - entryPrice) / entryPrice;

  if (profit < 0.15) {
    return { action: 'hold', reason: 'Profit below 15%' };
  }

  const drawdown = (highestPrice - currentPrice) / highestPrice;

  if (drawdown >= 0.05) {
    return { action: 'sell', reason: '5% drawback, trailing take profit' };
  }

  return { action: 'hold', reason: 'Continue holding' };
}
```

---

### 3.3 Target Price Take Profit

#### Strategy
```
First target: Sell 50%
Second target: Sell 30%
Third target: Sell 20%
```

#### Target Price Calculation
```javascript
function calculateTargetPrices(entryPrice, pattern, resistance) {
  const targets = [];

  // Pattern-based target
  if (pattern && pattern.target) {
    targets.push({
      price: pattern.target,
      type: 'pattern',
      sellPercent: 0.5
    });
  }

  // Resistance-based target
  if (resistance) {
    targets.push({
      price: resistance,
      type: 'resistance',
      sellPercent: 0.3
    });
  }

  // Risk-reward ratio target
  const riskRewardTarget = entryPrice * 1.20; // 20% target
  targets.push({
    price: riskRewardTarget,
    type: 'risk_reward',
    sellPercent: 0.2
  });

  return targets.sort((a, b) => a.price - b.price);
}
```

---

## 4️⃣ Risk Assessment

### 4.1 Individual Stock Risk Assessment

#### Volatility Risk
```javascript
function calculateVolatility(priceHistory) {
  const returns = [];
  for (let i = 1; i < priceHistory.length; i++) {
    const ret = (priceHistory[i].close - priceHistory[i-1].close) / priceHistory[i-1].close;
    returns.push(ret);
  }

  const mean = returns.reduce((a, b) => a + b) / returns.length;
  const variance = returns.reduce((sum, ret) =>
    sum + Math.pow(ret - mean, 2), 0) / returns.length;

  const dailyVol = Math.sqrt(variance);
  const annualVol = dailyVol * Math.sqrt(252);

  return {
    daily: dailyVol,
    annual: annualVol,
    level: annualVol < 0.2 ? 'low' : annualVol < 0.4 ? 'medium' : 'high'
  };
}
```

#### Risk Levels
```
Low risk: Annual volatility < 20%
Medium risk: Annual volatility 20-40%
High risk: Annual volatility > 40%
```

---

#### Liquidity Risk
```
Good: Daily trading volume > ¥100M
Fair: Daily trading volume ¥50M-100M
Poor: Daily trading volume < ¥50M
```

---

#### Beta Coefficient
```
Low risk: Beta < 0.8
Medium risk: Beta 0.8-1.2
High risk: Beta > 1.2
```

---

### 4.2 Portfolio Risk Assessment

#### Diversification Check
```javascript
function checkDiversification(portfolio) {
  const checks = {
    stockCount: portfolio.length >= 5 && portfolio.length <= 10,
    sectorCount: new Set(portfolio.map(p => p.sector)).size >= 3,
    singleStockMax: Math.max(...portfolio.map(p => p.weight)) <= 0.20,
    sectorMax: checkSectorConcentration(portfolio) <= 0.40
  };

  return {
    score: Object.values(checks).filter(Boolean).length / 4,
    checks
  };
}
```

#### Correlation Check
```javascript
function calculateCorrelation(returns1, returns2) {
  const n = returns1.length;
  const mean1 = returns1.reduce((a, b) => a + b) / n;
  const mean2 = returns2.reduce((a, b) => a + b) / n;

  let numerator = 0;
  let denom1 = 0;
  let denom2 = 0;

  for (let i = 0; i < n; i++) {
    const diff1 = returns1[i] - mean1;
    const diff2 = returns2[i] - mean2;
    numerator += diff1 * diff2;
    denom1 += diff1 * diff1;
    denom2 += diff2 * diff2;
  }

  return numerator / Math.sqrt(denom1 * denom2);
}

// Correlation standards
// < 0.3: Low correlation (good)
// 0.3-0.7: Medium correlation (acceptable)
// > 0.7: High correlation (needs adjustment)
```

---

## 5️⃣ Risk-Reward Ratio

### 5.1 Calculation Method

```javascript
function calculateRiskRewardRatio(entryPrice, targetPrice, stopLoss) {
  const potentialProfit = targetPrice - entryPrice;
  const potentialLoss = entryPrice - stopLoss;

  return {
    ratio: potentialProfit / potentialLoss,
    profit: (potentialProfit / entryPrice * 100).toFixed(2) + '%',
    loss: (potentialLoss / entryPrice * 100).toFixed(2) + '%'
  };
}
```

### 5.2 Rating Standards

| Risk-Reward Ratio | Rating | Recommendation |
|------------------|--------|----------------|
| > 1:3 | Excellent | Strongly recommended |
| 1:2 - 1:3 | Good | Recommended |
| 1:1.5 - 1:2 | Fair | Acceptable |
| < 1:1.5 | Poor | Not recommended |

### 5.3 Minimum Requirements

```
Risk-Reward Ratio ≥ 1:2
Win Rate ≥ 50%
```

---

## 6️⃣ Capital Management

### 6.1 Total Position Control

#### Market Environment Adjustment
```
Bull market: 70-90%
Sideways market: 50-70%
Bear market: 20-40%
```

#### Implementation
```javascript
function adjustTotalPosition(marketTrend, basePosition) {
  const adjustments = {
    bull: 1.2,      // Bull market amplify 20%
    neutral: 1.0,   // Sideways unchanged
    bear: 0.6       // Bear market reduce 40%
  };

  const adjusted = basePosition * (adjustments[marketTrend] || 1.0);
  return Math.min(adjusted, 0.90); // Max 90%
}
```

---

### 6.2 Cash Reserve

#### Minimum Cash
```
Minimum cash reserve: 10%
```

#### Purpose
- Adding opportunities
- Emergency funds
- Psychological safety cushion

---

### 6.3 Leverage Usage

#### Recommendations
```
Not recommended to use leverage
If necessary: Leverage ≤ 1.5x
```

#### Risks
- Amplified losses
- Forced liquidation
- Psychological pressure

---

## 📊 Practical Examples

### Example 1: Complete Risk Management Process

```
Stock: Primeton (688118)
Capital: ¥100,000
Current Price: ¥35.50

【Step 1: Risk Assessment】
- Volatility: 45.2% (high risk)
- Beta: 2.19 (high risk)
- Liquidity: Good

【Step 2: Position Calculation】
- Base position: 15% (balanced)
- Volatility adjustment: 15% × (30% / 45%) = 10%
- Recommended position: 8-10%

【Step 3: Staged Position Building】
First batch: 5% (¥5,000) - Price ¥35.00-35.50
Second batch: 5% (¥5,000) - Breakout ¥37.00 or pullback to ¥33.50

【Step 4: Stop Loss Setup】
- Technical stop: ¥33.00 (support level)
- Percentage stop: ¥33.00 (-7%)
- Final stop: ¥33.00

【Step 5: Take Profit Setup】
- First target: ¥40.00 (+12.7%) - Sell 50%
- Second target: ¥45.00 (+26.8%) - Sell 30%
- Trailing take profit: After profit > 15%, exit on 5% drawback

【Step 6: Risk-Reward Ratio】
- Potential profit: +12.7% (first target)
- Potential risk: -7%
- Risk-reward ratio: 1:1.8 ✅

【Execution Result】
- Entry price: ¥35.20
- Quantity: 142 shares (¥5,000)
- Stop loss: ¥33.00
- Target: ¥40.00
```

---

## 💡 Risk Management Principles

### 1. Never Go Full Position

**Reasons**:
- Loss of flexibility
- Unable to respond to opportunities
- Enormous psychological pressure

---

### 2. Strictly Execute Stop Loss

**Principles**:
- Stop loss is discipline, not suggestion
- Don't move stop loss (unless upward)
- Don't buy back immediately after stop loss

---

### 3. Protect Profits

**Methods**:
- Move stop loss up after profit
- Staged take profit
- Don't let profits turn into losses

---

### 4. Control Drawdown

**Targets**:
- Single trade max loss: < 2%
- Monthly max drawdown: < 10%
- Annual max drawdown: < 20%

---

### 5. Record and Review

**Content**:
- Record every trade
- Analyze stop loss reasons
- Summarize successes and failures
- Continuously optimize strategies

---

## 📚 Recommended Reading

1. "The Complete TurtleTrader" - Curtis Faith
2. "Trade Your Way to Financial Freedom" - Van K. Tharp
3. "Trading in the Zone" - Mark Douglas
4. "Trader Vic—Methods of a Wall Street Master" - Victor Sperandeo


path: references/technical-analysis.md
content: # Technical Analysis Methodology

> Professional technical analysis scoring model and indicator interpretation

---

## 📊 Comprehensive Scoring Model

### Total Score Composition (100 points)

```
Total Score = Trend Strength(30 points) + Momentum Indicators(25 points) + Pattern Recognition(20 points) + 
              Support Resistance(15 points) + Market Sentiment(10 points)
```

### Rating Standards

| Score Range | Rating | Recommendation |
|------------|--------|---------------|
| 90-100 | ⭐⭐⭐⭐⭐ | Strongly Recommend |
| 80-89 | ⭐⭐⭐⭐ | Recommend |
| 70-79 | ⭐⭐⭐ | Neutral Watch |
| 60-69 | ⭐⭐ | Cautious |
| < 60 | ⭐ | Not Recommend |

---

## 1️⃣ Trend Strength Analysis (30 points)

### 1.1 Multi-Timeframe Moving Average Arrangement (0-15 points)

#### Perfect Bullish Arrangement (15 points)
```
5-day MA > 10-day MA > 20-day MA > 60-day MA
```

#### Scoring Criteria
- 5-day > 10-day > 20-day > 60-day: **15 points** (Perfect bullish)
- 5-day > 10-day > 20-day: **12 points** (Strong bullish)
- 5-day > 10-day: **8 points** (Short-term bullish)
- Moving averages converging: **5 points** (Direction unclear)
- Bearish arrangement: **0 points** (Downward trend)

### 1.2 Price Relative Position (0-10 points)

#### Scoring Criteria
- Price > all moving averages: **10 points** (Strong)
- Price > 60-day MA: **8 points** (Medium-term strong)
- Price > 20-day MA: **5 points** (Short-term strong)
- Price < all moving averages: **0 points** (Weak)

### 1.3 Trend Duration (0-5 points)

#### Scoring Criteria
- Duration > 30 days: **5 points** (Mature trend)
- Duration 20-30 days: **4 points** (Established trend)
- Duration 10-20 days: **3 points** (Early trend)
- Duration < 10 days: **1 point** (Unstable trend)

---

## 2️⃣ Momentum Indicators Analysis (25 points)

### 2.1 RSI Relative Strength Index (0-10 points)

#### Health Scoring
- RSI in 40-60: **10 points** (Most healthy)
- RSI in 30-40 or 60-70: **8 points** (Healthy)
- RSI in 20-30 or 70-80: **5 points** (Caution)
- RSI < 20 or > 80: **2 points** (Overbought/oversold)

#### Trading Signals
```
Buy Signals:
- RSI breaks above 30 from below
- RSI bottom divergence (price makes new low, RSI doesn't make new low)

Sell Signals:
- RSI breaks below 70 from above
- RSI top divergence (price makes new high, RSI doesn't make new high)
```

### 2.2 MACD Indicator (0-10 points)

#### Status Scoring
- Golden cross + DIF > 0 + histogram expanding: **10 points** (Strong buy)
- Golden cross + DIF < 0: **8 points** (Buy signal)
- Golden cross + histogram contracting: **6 points** (Momentum weakening)
- Death cross + DIF > 0: **3 points** (Caution)
- Death cross + DIF < 0: **0 points** (Sell signal)

#### Trading Signals
```
Strong Buy:
- MACD golden cross above 0 axis
- Histogram rapidly expanding

Buy:
- MACD golden cross below 0 axis
- Bottom divergence

Sell:
- MACD death cross below 0 axis
- Top divergence
```

### 2.3 Volume Coordination (0-5 points)

#### Volume-Price Relationship Scoring
- Rise + volume increase: **5 points** (Healthy rise)
- Rise + volume decrease: **3 points** (Insufficient momentum)
- Fall + volume decrease: **2 points** (Selling pressure easing)
- Fall + volume increase: **0 points** (Panic selling)

#### Relative Volume
```
Volume increase: Daily volume > 5-day average × 1.5
Volume decrease: Daily volume < 5-day average × 0.7
```

---

## 3️⃣ Pattern Recognition (20 points)

### 3.1 Classic Patterns (0-15 points)

#### Reversal Patterns
- **Double bottom/double top**: Confidence > 85% → 15 points
- **Head and shoulders bottom/top**: Confidence > 80% → 12 points
- **Rounding bottom/top**: Confidence > 75% → 10 points

#### Consolidation Patterns
- **Ascending triangle**: Confidence > 80% → 12 points
- **Flag consolidation**: Confidence > 75% → 10 points
- **Rectangle consolidation**: Confidence > 70% → 8 points

### 3.2 Candlestick Patterns (0-5 points)

#### Bullish Patterns
- **Hammer**: Appears at support → 5 points
- **Bullish engulfing**: Volume increases → 5 points
- **Morning star**: Three candlestick combination → 5 points

#### Bearish Patterns
- **Shooting star**: Appears at resistance → 0 points
- **Bearish engulfing**: Volume increases → 0 points
- **Evening star**: Three candlestick combination → 0 points

---

## 4️⃣ Support Resistance Analysis (15 points)

### 4.1 Distance from Support Level (0-8 points)

#### Scoring Criteria
```
Distance from support < 3%: 8 points (High safety margin)
Distance from support 3-5%: 6 points (Relatively safe)
Distance from support 5-8%: 4 points (Average)
Distance from support > 8%: 2 points (Higher risk)
```

### 4.2 Breaking Resistance Level (0-7 points)

#### Scoring Criteria
```
Effective break above resistance + volume increase: 7 points (Strong)
Break above resistance but volume decrease: 4 points (To be confirmed)
Approaching resistance without break: 2 points (Wait)
Far from resistance: 0 points (Limited space)
```

### 4.3 Support Resistance Calculation Methods

#### 1. Historical High-Low Method
```javascript
// Find important high-low points in recent 60 days
function findSupportResistance(priceHistory) {
  const highs = findLocalHighs(priceHistory);
  const lows = findLocalLows(priceHistory);
  
  // Support: Recent important low points
  const support = Math.max(...lows.slice(-3));
  
  // Resistance: Recent important high points
  const resistance = Math.min(...highs.slice(-3));
  
  return { support, resistance };
}
```

#### 2. Moving Average Support Method
```
Short-term support: 20-day MA
Medium-term support: 60-day MA
Long-term support: 120-day MA
```

#### 3. Fibonacci Retracement Method
```
From high point retracement:
- 0.382 retracement level (Shallow retracement)
- 0.5 retracement level (Moderate retracement)
- 0.618 retracement level (Deep retracement)

From low point rebound:
- 1.382 target level
- 1.618 target level
- 2.0 target level
```

---

## 5️⃣ Market Sentiment Analysis (10 points)

### 5.1 Relative Strength (0-5 points)

#### Scoring Criteria
```
Outperform market > 10%: 5 points (Strong)
Outperform market 5-10%: 4 points (Strong)
Outperform market 0-5%: 3 points (Slightly strong)
Underperform market 0-5%: 2 points (Slightly weak)
Underperform market > 5%: 0 points (Weak)
```

### 5.2 Sector Linkage (0-5 points)

#### Scoring Criteria
```
Sector leader + strong sector: 5 points
Sector follower + strong sector: 4 points
Sector leader + average sector: 3 points
Sector follower + average sector: 2 points
Sector laggard: 0 points
```

---

## 📈 Practical Application Examples

### Example 1: Strong Stock Scoring

```
Stock: Puyuan Information (688118)
Current Price: ¥35.50

【Trend Strength】30 points → 28 points
- Moving average arrangement: 5-day>10-day>20-day>60-day(15 points)
- Price position: Above all moving averages (10 points)
- Duration: 25 days (3 points)

【Momentum Indicators】25 points → 23 points
- RSI(14): 65.3 (8 points)
- MACD: Golden cross+DIF>0+increasing (10 points)
- Volume: Volume increase on rise (5 points)

【Pattern Recognition】20 points → 18 points
- Ascending triangle: Confidence 85% (12 points)
- Bullish engulfing: Appeared yesterday (5 points)
- Pattern completeness: 90% (1 point)

【Support Resistance】15 points → 13 points
- Distance from support: 6% (4 points)
- Break above resistance: Effective break + volume increase (7 points)
- Space assessment: Good (2 points)

【Market Sentiment】10 points → 8 points
- Relative strength: Outperform market 8% (4 points)
- Sector linkage: Sector leader + strong sector (4 points)

Total Score: 90 points ⭐⭐⭐⭐⭐
Rating: Strongly Recommend
```

### Example 2: Weak Stock Scoring

```
Stock: XXX (000000)
Current Price: ¥10.50

【Trend Strength】30 points → 8 points
- Moving average arrangement: Bearish arrangement (0 points)
- Price position: Below all moving averages (0 points)
- Duration: Falling for 15 days (0 points)
- Adjustment points: 8 points (Signs of rebound)

【Momentum Indicators】25 points → 10 points
- RSI(14): 25.3 (5 points - Oversold)
- MACD: Death cross+DIF<0 (0 points)
- Volume: Volume decrease on fall (5 points - Selling pressure easing)

【Pattern Recognition】20 points → 5 points
- Descending channel (0 points)
- Bearish patterns (0 points)
- Possible bottom: 5 points (RSI oversold)

【Support Resistance】15 points → 6 points
- Distance from support: 2% (6 points - Close to support)
- Resistance level: Far away (0 points)

【Market Sentiment】10 points → 0 points
- Relative strength: Underperform market 12% (0 points)
- Sector linkage: Sector laggard (0 points)

Total Score: 29 points ⭐
Rating: Not Recommend (But possible oversold rebound)
```

---

## 🎯 Usage Recommendations

### 1. Comprehensive Judgment
- Don't look at single indicators only
- Combine multiple dimensions for comprehensive scoring
- Pay attention to scoring change trends

### 2. Dynamic Adjustment
- Update scores daily
- Track scoring changes
- Adjust strategies promptly

### 3. Risk Control
- Set stop losses even for high-score stocks
- Low-score stocks may have oversold rebounds
- Strictly execute risk management

### 4. Market Environment
- Bull market: Consider above 70 points
- Sideways market: Above 80 points
- Bear market: Above 90 points or oversold rebounds

---

## 📚 Advanced Learning

### Recommended Reading
1. 《Japanese Candlestick Charting Techniques》- Steve Nison
2. 《Reminiscences of a Stock Operator》- Edwin Lefèvre
3. 《The Turtle Trading Rules》- Curtis Faith
4. 《Technical Analysis of the Financial Markets》- Martin J. Pring

### Practical Suggestions
1. Build your own scoring model
2. Backtest historical data validation
3. Keep trading logs
4. Continuously optimize and improve


path: references/us-stock-examples.md
content: # US Stock Practical Examples

## Case 1: Smart Stock Screening - Tech Sector

**User Request**:
```
"Help me screen for strong momentum stocks in the US tech sector"
```

**Skill Execution Process**:

1. Get tech sector candidate pool (200 stocks)
2. Technical analysis filtering (RSI, MACD, trend)
3. Comprehensive scoring and ranking
4. Return Top 10

**Output Result**:
```markdown
# Smart Stock Screening Results - US Tech Sector

## Qualified Stocks (10 total)

### 1. NVIDIA (NVDA) ⭐⭐⭐⭐⭐
**Comprehensive Score**: 94/100

**Technical Analysis**:
- Trend: Strong uptrend 📈
- RSI(14): 67.8 (healthy range)
- MACD: Golden cross day 5, strong momentum
- Volume: 2.3x average volume
- Support: $875.00
- Resistance: $950.00

**Fundamental Highlights**:
- Market Cap: $2.15T
- P/E: 65.3 (growth premium)
- ROE: 123.5%
- Sector: AI/Semiconductors

**Buy Recommendation**: ✅ Strong Buy
- Suggested entry: $890.00-900.00
- Target price: $980.00
- Stop loss: $860.00
- Position size: 10-15%

---

### 2. Microsoft (MSFT) ⭐⭐⭐⭐
**Comprehensive Score**: 89/100

**Technical Analysis**:
- Trend: Steady uptrend 📈
- RSI(14): 62.4 (healthy range)
- MACD: Bullish momentum
- Volume: 1.8x average volume
- Support: $415.00
- Resistance: $445.00

**Fundamental Highlights**:
- Market Cap: $3.08T
- P/E: 35.2 (reasonable)
- ROE: 42.8%
- Sector: Cloud/AI/Software

**Buy Recommendation**: ✅ Buy
- Suggested entry: $425.00-430.00
- Target price: $460.00
- Stop loss: $410.00
- Position size: 10-12%

---

### 3. Advanced Micro Devices (AMD) ⭐⭐⭐⭐
**Comprehensive Score**: 86/100

**Technical Analysis**:
- Trend: Recovery uptrend 📈
- RSI(14): 58.9 (neutral-bullish)
- MACD: Turning positive
- Volume: 1.9x average volume
- Support: $145.00
- Resistance: $165.00

**Fundamental Highlights**:
- Market Cap: $245B
- P/E: 48.5 (growth)
- ROE: 15.3%
- Sector: Semiconductors/AI

**Buy Recommendation**: ✅ Buy
- Suggested entry: $152.00-155.00
- Target price: $175.00
- Stop loss: $142.00
- Position size: 8-10%
```

---

## Case 2: Pattern Recognition - SPY (S&P 500 ETF)

**User Request**:
```
"Analyze the technical pattern for SPY"
```

**Output Result**:
```markdown
# SPY Technical Pattern Analysis

## Identified Patterns

### 🔍 Bull Flag (Confidence: 82%)
- Flagpole: $505 → $525 (strong rally)
- Flag consolidation: $520-$525
- Current position: Mid-flag range
- Duration: 8 trading days

## Trading Strategies

### Strategy A: Breakout Long
- Entry: Break above $525.50
- Target: $540.00
- Stop loss: $518.00
- Risk/Reward: 1:2.0
- Position size: 15-20%

### Strategy B: Support Bounce
- Entry: Bounce at $520.00
- Target: $532.00
- Stop loss: $516.00
- Risk/Reward: 1:3.0
- Position size: 10-15%

## Key Levels
- Strong resistance: $525.50
- Support zone: $520.00-$522.00
- Major support: $515.00
- Volume profile: High volume at $522

## Market Context
- VIX: 14.2 (low volatility)
- Breadth: 65% stocks above 50-day MA
- Sector rotation: Tech leading
```

---

## Case 3: Market Review

**User Request**:
```
"Generate today's US market review report"
```

**Output Result**:
```markdown
# US Market Review - March 2, 2026

## Market Overview
- S&P 500: 5,234.56 (+0.8%)
- Nasdaq: 16,543.21 (+1.2%)
- Dow Jones: 39,876.45 (+0.5%)
- Russell 2000: 2,145.67 (+0.3%)

## Market Internals
- Advance/Decline: 2,845 : 1,234 (2.3:1)
- New Highs/Lows: 234 : 45
- Volume: Above 20-day average (+12%)
- VIX: 14.2 (-5.3%)

## Hot Sectors
1. Technology (+1.5%) - AI momentum continues
2. Communication Services (+1.2%) - Strong earnings
3. Consumer Discretionary (+0.9%) - Retail strength

## Weak Sectors
1. Energy (-0.8%) - Oil price pressure
2. Utilities (-0.5%) - Rate concerns
3. Real Estate (-0.3%) - Yield competition

## Key Movers

### Top Gainers
- NVDA: +3.2% (AI chip demand)
- META: +2.8% (Ad revenue beat)
- TSLA: +2.5% (Delivery numbers)

### Top Losers
- XOM: -2.1% (Oil price drop)
- CVX: -1.8% (Sector weakness)
- NEE: -1.5% (Utility selloff)

## Market Sentiment
- Fear & Greed Index: 68 (Greed)
- Put/Call Ratio: 0.72 (Bullish)
- AAII Bull%: 45.2% (Above average)

## Tomorrow's Watch List
- FOMC Minutes release (2:00 PM ET)
- Jobless claims data (8:30 AM ET)
- Tech earnings: ORCL, CRM

## Trading Strategy
**Bias**: Cautiously bullish
- Focus on tech leaders with momentum
- Watch for FOMC reaction
- Keep stops tight given extended levels
```

---

## Case 4: Options Strategy - AAPL

**User Request**:
```
"Suggest an options strategy for AAPL with moderate bullish outlook"
```

**Output Result**:
```markdown
# AAPL Options Strategy Analysis

## Current Market Data
- Stock Price: $178.50
- IV Rank: 32% (moderate)
- Earnings: 28 days away
- Trend: Consolidating after rally

## Recommended Strategy: Bull Call Spread

### Setup
- Buy: 180 Call @ $4.20
- Sell: 190 Call @ $1.50
- Net Debit: $2.70 per spread
- Expiration: 45 DTE (April 18, 2026)

### Risk/Reward Profile
- Max Profit: $7.30 ($730 per spread)
- Max Loss: $2.70 ($270 per spread)
- Breakeven: $182.70
- Risk/Reward: 1:2.7
- Probability of Profit: ~58%

### Greeks
- Delta: +0.42
- Theta: -0.08 (time decay)
- Vega: +0.15 (IV exposure)

### Management Rules
- Take profit: 50% max gain ($3.65)
- Stop loss: 50% max loss ($1.35)
- Adjust: Roll up if stock breaks $190

### Why This Strategy?
✅ Limited risk, defined reward
✅ Lower cost than buying stock
✅ Benefits from upward movement
✅ Time decay manageable with spread
```

---

## Case 5: Sector Rotation Analysis

**User Request**:
```
"Analyze current sector rotation and suggest positioning"
```

**Output Result**:
```markdown
# Sector Rotation Analysis - March 2026

## Current Market Phase
**Phase**: Mid-Cycle Expansion
- Economic growth: Moderate
- Fed policy: Neutral-to-accommodative
- Inflation: Moderating

## Sector Performance (30-Day)

### Leading Sectors 🚀
1. **Technology** (+8.2%)
   - AI/Cloud momentum
   - Strong earnings
   - Recommendation: Overweight

2. **Communication Services** (+6.5%)
   - Digital ad recovery
   - Streaming growth
   - Recommendation: Overweight

3. **Consumer Discretionary** (+5.1%)
   - Consumer spending resilient
   - E-commerce strong
   - Recommendation: Market weight

### Lagging Sectors 📉
1. **Energy** (-3.2%)
   - Oil price weakness
   - Demand concerns
   - Recommendation: Underweight

2. **Utilities** (-2.1%)
   - Rate sensitivity
   - Defensive rotation out
   - Recommendation: Underweight

3. **Real Estate** (-1.8%)
   - Yield competition
   - Office space concerns
   - Recommendation: Underweight

## Rotation Strategy

### Overweight Positions (60%)
- Technology: 25%
- Communication Services: 20%
- Financials: 15%

### Market Weight (30%)
- Healthcare: 15%
- Consumer Discretionary: 15%

### Underweight (10%)
- Energy: 5%
- Utilities: 3%
- Real Estate: 2%

## Key Catalysts to Watch
- Fed policy signals
- Q1 earnings season
- Economic data (GDP, employment)
- Geopolitical developments

## Tactical Recommendations
1. Add tech on pullbacks to 50-day MA
2. Trim energy on any bounce
3. Hold defensive hedges (5-10% cash)
4. Monitor sector momentum weekly
```


path: workflows/calendar-tracking.md
content: ---
description: Calendar Event Tracking Workflow - Track important market events from financial calendars
---

# Calendar Event Tracking Workflow

Track important market events from financial calendars, including earnings releases, dividend distributions, IPO listings, economic data releases, etc.

## Execution Steps

### Step 1: Determine Calendar Type

Determine the calendar type based on user needs:
- **economic**: Economic calendar (GDP, CPI, employment data, etc.)
- **earnings**: Earnings calendar (company earnings release dates)
- **revenue**: Dividend calendar (dividend distribution dates)
- **ipo**: IPO calendar (new stock listing dates)

### Step 2: Determine Time Range

Calculate the query time range (Unix timestamp):
- Default query: next 7-14 days
- User can specify specific date range
- Note: Time span cannot exceed 40 days

### Step 3: Determine Market Scope

Select market based on calendar type:
- Economic calendar: Supports multiple countries (america, china, japan, etc.)
- Earnings/Dividend/IPO: Default is america, can specify other markets

### Step 4: Call Calendar Tool

Call `tradingview_get_calendar` to retrieve calendar data:

```
Parameter description:
- type: Calendar type (required)
  - economic: Economic events
  - earnings: Earnings releases
  - revenue: Dividend distributions
  - ipo: New stock listings
- from: Start time (required, Unix timestamp)
- to: End time (required, Unix timestamp)
- market: Market code (optional, comma-separated)
```

### Step 5: Filter and Sort Events

Filter based on user focus:
- Sort by importance
- Filter by industry/sector
- Filter by specific securities

### Step 6: Generate Calendar Report

Output formatted calendar report:
- Event list (time, event name, expected value, actual value)
- Highlight important events
- Potential impact analysis
- Recommended securities to watch

## Example Conversations

**User**: "What important earnings are coming next week?"

**Execution**:
1. Calculate next week's time range (from/to timestamps)
2. Call `tradingview_get_calendar` with type="earnings"
3. Return earnings list, highlighting companies with high market attention
4. Suggest securities that may exceed expectations

---

**User**: "Check US economic data releases for the next two weeks"

**Execution**:
1. Calculate time range for next two weeks
2. Call `tradingview_get_calendar` with type="economic", market="america"
3. Return important data release times like CPI, non-farm payrolls, GDP, etc.
4. Analyze potential market impact of the data

---

**User**: "Check which new stocks are listing this month"

**Execution**:
1. Calculate time range for this month
2. Call `tradingview_get_calendar` with type="ipo"
3. Return new stock list including offering price, listing date, etc.
4. Analyze industry distribution of new stocks and IPO recommendations

---

**User**: "Are any of my holdings paying dividends soon?"

**Execution**:
1. Get user's stock holdings list
2. Call `tradingview_get_calendar` with type="revenue"
3. Filter dividend information for user's holdings
4. Return ex-dividend date, payment date, dividend amount, etc.


path: workflows/deep-stock-analysis.md
content: ---
description: Deep Stock Analysis Workflow - Comprehensive analysis of individual stocks using multiple tools
---

# Deep Stock Analysis Workflow

Combine multiple MCP tools to perform comprehensive analysis on individual stocks, outputting integrated reports and trading recommendations.

## Execution Steps

### Step 1: Confirm Symbol

If user input is Chinese name/abbreviation, search to confirm accurate symbol:

```
tradingview_search_market(query="user input", filter="stock", lang="zh")
```

Confirm symbol format is `EXCHANGE:SYMBOL` (e.g., `SSE:688118`, `NASDAQ:AAPL`).

### Step 2: Get Real-time Quote

```
tradingview_get_quote(symbol, session="regular")
```

Extract key data:
- Current price, change %, volume, turnover
- Bid/ask price, bid/ask volume
- 52-week high/low, market cap

### Step 3: Get Multi-Timeframe Charts

Call in parallel to get data for different periods:

```
tradingview_get_price(symbol, timeframe='D', range=120)   # Daily - medium-term trend
tradingview_get_price(symbol, timeframe='W', range=52)    # Weekly - medium to long-term
tradingview_get_price(symbol, timeframe='60', range=100)  # 60-minute - short-term details
```

Optional: `type='HeikinAshi'` to get Heikin Ashi candles for clearer trend visualization.

### Step 4: Get Detailed Technical Analysis

```
tradingview_get_ta(symbol, include_indicators=true)
```

**Key Indicator Interpretation**:
- Multi-timeframe signal summary (1min/5min/15min/1hour/4hour/daily/weekly/monthly)
- RSI(14): >70 overbought, <30 oversold
- MACD: Golden cross/death cross, DIF relationship with zero line
- ADX(14): >25 trending, >50 strong trend
- Moving average alignment: SMA5/10/20/60 relative relationships

See `references/technical-analysis.md` for detailed scoring methodology.

### Step 5: Get Related News

```
tradingview_get_news(symbol=symbol, lang="zh-Hans", limit=5)
```

Get details for important news:
```
tradingview_get_news_detail(news_id, lang="zh-Hans")
```

### Step 6: Query Upcoming Events

```
tradingview_get_calendar(type="earnings", from=now, to=now+30days, market="china")
```

Check for upcoming earnings, dividends, and other events.

### Step 7: Generate Comprehensive Report

Output structure:

```markdown
# [Stock Name] (Symbol) Deep Analysis

## Basic Information
- Current price / Change % / Volume
- Market cap / 52-week range

## Technical Analysis
- Multi-timeframe trend assessment (monthly/weekly/daily/hourly)
- Key indicator status (RSI, MACD, ADX, moving averages)
- Support levels / Resistance levels
- Overall technical score (0-100)

## Pattern Recognition
- Current pattern identification
- Confidence assessment

## News Analysis
- Recent important news summary
- Impact assessment

## Upcoming Events
- Earnings date / Dividend date

## Trading Recommendations
- Action direction (Buy/Hold/Sell)
- Suggested entry price
- Stop loss / Target price
- Position size recommendation
- Risk-reward ratio

## Risk Warnings
```

## Example

**User**: "Help me analyze Primeton"

**Execution**:
1. `search_market(query="普元信息", filter="stock")` → SSE:688118
2. `get_quote(symbol="SSE:688118")` → Real-time quote
3. `get_price` × 3 timeframes → Chart data
4. `get_ta(include_indicators=true)` → Detailed technical indicators
5. `get_news(symbol="SSE:688118", lang="zh-Hans")` → Related news
6. Comprehensive scoring, generate report


path: workflows/event-analysis.md
content: ---
description: Event-Driven Analysis Workflow - Track major events and analyze market impact
---

# Event-Driven Analysis Workflow

Track major events, analyze market impact, identify beneficiary stocks, and provide investment recommendations.

## Execution Steps

### Step 1: Get Financial Calendar

Call calendar based on event type (time span not exceeding 40 days):

```
# Earnings calendar
tradingview_get_calendar(type='earnings', from=now, to=now+14days, market='china')

# Dividend calendar
tradingview_get_calendar(type='revenue', from=now, to=now+14days, market='china')

# Economic data calendar
tradingview_get_calendar(type='economic', from=now, to=now+7days, market='america,china')

# IPO calendar
tradingview_get_calendar(type='ipo', from=now, to=now+14days, market='china')
```

### Step 2: Get Related News

```
# Get specific market news
tradingview_get_news(market='stock', market_country='CN', lang='zh-Hans', limit=20)

# Get specific symbol news
tradingview_get_news(symbol='SSE:600519', lang='zh-Hans', limit=10)

# Get economic news
tradingview_get_news(market='economic', lang='zh-Hans', limit=10)
```

Get details for important news:
```
tradingview_get_news_detail(news_id, lang='zh-Hans')
```

### Step 3: Extract Event Keywords

Extract from calendar events and news:
- **Company name/symbol**: Directly related stocks
- **Industry keywords**: Used to search for same-industry beneficiary stocks
- **Policy keywords**: Used to expand impact scope
- **Event type**: Earnings beat/policy positive/industry event/breaking news

### Step 4: Search Beneficiary Stocks

Search related stocks using extracted keywords:

```
tradingview_search_market(query='keyword', filter='stock', limit=20)
```

For industry events, also find same-sector stocks via leaderboard:
```
tradingview_get_leaderboard(
  asset_type='stocks', tab='gainers',
  market_code='china', columnset='overview', count=50
)
```

### Step 5: Analyze Beneficiary Stock Quotes

For identified beneficiary stocks (5-10), get quotes and technical analysis:

```
tradingview_get_quote_batch(symbols=[...])  # Real-time quotes
tradingview_get_ta(symbol, include_indicators=true)  # Technical confirmation
```

### Step 6: Assess Impact Level

Assess each beneficiary stock:

| Factor | Weight | Assessment Dimension |
|--------|--------|---------------------|
| Event Importance | 30% | Fundamental impact on industry/company |
| Relevance | 25% | Direct correlation between stock and event |
| Timeliness | 20% | Duration of event impact |
| Expectation Gap | 15% | Whether market has fully priced in |
| Certainty | 10% | Certainty of event materialization |

Impact levels:
- **Strong Positive (+3)**: Direct beneficiary, clear earnings improvement
- **Positive (+2)**: Indirect beneficiary, industry prosperity improvement
- **Slight Positive (+1)**: Sentiment positive
- **Neutral (0)**: Limited impact
- **Negative (-1/-2/-3)**: Symmetrical negative impact

### Step 7: Generate Analysis Report

```markdown
# Event-Driven Analysis Report

## Event Overview
- Event: [Event description]
- Time: [Occurrence/expected time]
- Type: [Earnings/Policy/Industry/Breaking]
- Importance: [High/Medium/Low]

## Impact Analysis
- Direct impact: ...
- Indirect impact: ...
- Impact duration: [Short-term/Medium-term/Long-term]

## Beneficiary Stock Analysis

### 1. [Stock Name] (Symbol) - Impact Level: +3
- Relevance: Direct beneficiary, [reason]
- Current price: ¥XX (Change XX%)
- Technical: RSI=XX, TA signal=[Buy/Sell]
- Trading recommendation: ...

### 2. [Stock Name] ...

## Risk Factors
- [Risk 1: Event materialization below expectations]
- [Risk 2: Market has fully priced in]

## Trading Recommendations
- Short-term strategy: ...
- Medium-term strategy: ...
```

## Example

**User**: "Analyze the impact of cloud computing price increases on related companies"

**Execution**:
1. `get_news(market='stock', market_country='CN', lang='zh-Hans')` → Related news
2. `get_news_detail(news_id)` → News details
3. `search_market(query='云计算', filter='stock')` → Related stocks
4. `get_leaderboard(tab='gainers', market_code='china')` → Verify gainers list
5. `get_quote_batch` + `get_ta` → Quotes and technical analysis
6. Assess impact level → Generate analysis report


path: workflows/exchange-overview.md
content: ---
description: Exchange Overview Workflow - View exchange information and market configuration
---

# Exchange Overview Workflow

View the list of exchanges supported by TradingView, market configurations, and available asset types.

## Execution Steps

### Step 1: Determine Query Type

Determine query type based on user needs:
- **exchanges**: View exchange list
- **markets**: View market codes
- **tabs**: View leaderboard category tabs
- **columnsets**: View data column configurations
- **languages**: View supported languages

### Step 2: Call Metadata Tool

Call `tradingview_get_metadata` to get configuration information:

```
Parameter description:
- type: Metadata type (required)
  - markets: Market code list (68+ markets)
  - tabs: Leaderboard tabs (categorized by asset type)
  - columnsets: Data column configurations (categorized by asset type)
  - languages: Supported language list
  - exchanges: Exchange list (353+ exchanges)
- asset_type: Asset type filter (optional, only for tabs)
  - stocks, indices, crypto, futures, forex, bonds, corporate_bonds, etfs
```

### Step 3: Format Output

Format output based on query type:

**Exchange List**:
- Stock exchanges: NASDAQ, NYSE, HKEX, SSE, SZSE, TSE, LSE, etc.
- Cryptocurrency exchanges: Binance, Coinbase, Kraken, OKX, Bybit, etc.

**Market Codes**:
- North America: america, canada
- Europe: uk, germany, france
- Asia: china, japan, korea, india
- Others: australia, brazil, etc.

**Leaderboard Tabs**:
- Stocks: gainers, losers, large-cap, active, etc.
- Crypto: all, gainers, losers, large-cap, etc.
- Other asset type tabs

### Step 4: Provide Usage Guidance

Guide users on how to use the obtained information:
- How to use market codes to query leaderboards
- How to use exchange prefixes to search symbols
- How to select appropriate leaderboard tabs

## Example Conversations

**User**: "Which exchanges does TradingView support?"

**Execution**:
1. Call `tradingview_get_metadata`, type="exchanges"
2. Display stock exchanges and cryptocurrency exchanges by category
3. Indicate total number of exchanges (353+)

---

**User**: "What leaderboards are available for US stocks?"

**Execution**:
1. Call `tradingview_get_metadata`, type="tabs", asset_type="stocks"
2. Display stock leaderboard tabs: gainers, losers, large-cap, etc.
3. Explain how to use these tabs to query leaderboards

---

**User**: "Which countries' stock markets are supported?"

**Execution**:
1. Call `tradingview_get_metadata`, type="markets"
2. Display market code list: america, china, japan, uk, etc.
3. Explain that market codes are used for leaderboard queries

---

**User**: "What data columns can be displayed on leaderboards?"

**Execution**:
1. Call `tradingview_get_metadata`, type="columnsets"
2. Display available data columns by asset type:
   - Stocks: overview, performance, valuation, dividends, etc.
   - Crypto: overview, performance, etc.
3. Explain how to use the columnset parameter in leaderboard queries


path: workflows/fundamental-screening.md
content: ---
description: Fundamental Screening Workflow - Use multiple columnsets to screen value stocks
---

# Fundamental Screening Workflow

Use `tradingview_get_leaderboard` with various columnsets (valuation/profitability/dividends/balance_sheet/income_statement/cash_flow) to screen quality stocks from a fundamental perspective.

## Execution Steps

### Step 1: Determine Screening Strategy

Determine screening strategy based on user needs:

| Strategy | Core Columnset | Key Metrics |
|----------|---------------|-------------|
| Value Investing | valuation | Low PE, Low PB, Low PS |
| High Dividend | dividends | High dividend yield, stable dividends |
| Growth Stocks | profitability + income_statement | High ROE, revenue growth |
| Financial Health | balance_sheet + cash_flow | Low debt ratio, ample cash flow |

### Step 2: Get Metadata

```
tradingview_get_metadata(type='markets')        # Get market_code
tradingview_get_metadata(type='columnsets')      # Confirm available columnsets
```

### Step 3: Get Leaderboard Data (Multiple Columnsets)

Call based on strategy combination, using value investing as example:

```
# Get valuation data
tradingview_get_leaderboard(
  asset_type='stocks', tab='all-stocks',
  market_code='china', columnset='valuation', count=100
)

# Get profitability data
tradingview_get_leaderboard(
  asset_type='stocks', tab='all-stocks',
  market_code='china', columnset='profitability', count=100
)

# Get dividend data
tradingview_get_leaderboard(
  asset_type='stocks', tab='high-dividend',
  market_code='china', columnset='dividends', count=50
)
```

### Step 4: Cross-Filter

Cross-filter results from multiple columnsets:

**Value Investing Filter Example**:
- PE < 20 (reasonable valuation)
- PB < 3 (asset discount)
- ROE > 15% (strong profitability)
- Dividend yield > 2% (dividend protection)

**Growth Stock Filter Example**:
- Revenue YoY growth > 20%
- Net profit growth > 15%
- ROE > 20%
- Gross margin > 40%

### Step 5: Technical Validation

For top candidates (5-10), call individually:

```
tradingview_get_ta(symbol, include_indicators=true)
```

Filter out stocks with obviously weak technicals (e.g., RSI > 80 overbought, MACD death cross).

### Step 6: Generate Screening Report

```markdown
# Fundamental Screening Results - [Strategy Name]

## Screening Criteria
- [List all criteria]

## Qualified Stocks (Total: N)

| Rank | Stock | PE | PB | ROE | Dividend Yield | Technical Score |
|------|-------|----|----|-----|----------------|-----------------|
| 1 | ... | ... | ... | ... | ... | ... |

## Detailed Analysis (Top 5)
### 1. [Stock Name]
- Valuation: ...
- Profitability: ...
- Technical: ...
- Buy recommendation: ...
```

## Common Screening Combinations

### High Dividend Strategy
```
tab='high-dividend' + columnset='dividends' → Dividend yield ranking
Cross with columnset='profitability' → Confirm sustainable earnings
Cross with columnset='balance_sheet' → Confirm financial health
```

### Low Valuation Strategy
```
tab='all-stocks' + columnset='valuation' → PE/PB ranking
Cross with columnset='income_statement' → Confirm revenue and profit
Cross with columnset='cash_flow' → Confirm cash flow
```

### Blue Chip Strategy
```
tab='large-cap' + columnset='profitability' → Large-cap high ROE
Cross with columnset='performance' → Confirm performance trend
Cross with columnset='dividends' → Dividend protection
```


path: workflows/market-review.md
content: ---
description: Market Review Workflow - Daily market analysis and investment opportunity discovery
---

# Market Review Workflow

Daily market review, tracking hot sectors and capital flows, discovering investment opportunities.

## Execution Steps

### Step 1: Get Metadata

```
tradingview_get_metadata(type='markets')  # Confirm market_code
```

### Step 2: Get Gainers/Losers Data

Call in parallel to get multi-dimensional data:

```
# Gainers
tradingview_get_leaderboard(
  asset_type='stocks', tab='gainers',
  market_code='china', columnset='overview', count=50
)

# Losers
tradingview_get_leaderboard(
  asset_type='stocks', tab='losers',
  market_code='china', columnset='overview', count=50
)

# Most active (highest volume)
tradingview_get_leaderboard(
  asset_type='stocks', tab='active',
  market_code='china', columnset='overview', count=30
)

# Unusual volume
tradingview_get_leaderboard(
  asset_type='stocks', tab='unusual-volume',
  market_code='china', columnset='overview', count=30
)
```

### Step 3: Get Market News

```
tradingview_get_news(market='stock', market_country='CN', lang='zh-Hans', limit=10)
```

Get details for important news:
```
tradingview_get_news_detail(news_id, lang='zh-Hans')
```

### Step 4: Get Index Quotes (Optional)

```
tradingview_get_quote_batch(
  symbols=["SSE:000001", "SZSE:399001", "SZSE:399006"]  # Shanghai/Shenzhen/ChiNext
)
```

### Step 5: Identify Hot Sectors

Analyze industry distribution in gainers list:
- Categorize top 50 gainers by industry
- Count number and average gain for each industry
- Identify top 3-5 sectors with highest representation

### Step 6: Analyze Capital Flow

Analyze through volume data:
- Industry distribution of active and unusual volume stocks
- Volume comparison between gainers vs losers
- Stocks with volume surge and price increase (capital inflow signal)

### Step 7: Correlate News with Market Action

Correlate companies/industries in news with gainers/losers:
- News catalysts for limit-up stocks
- Policy/event drivers for sector movements
- Sustainability assessment

### Step 8: Generate Review Report

```markdown
# [Market] Market Review - YYYY-MM-DD

## Market Overview
- Index performance: [Shanghai/Shenzhen/ChiNext changes]
- Advance/decline: XX up / XX down
- Trading volume: XX billion (vs previous +/-XX%)

## Hot Sectors (Ranked by strength)
| Rank | Sector | Gain | Representative Stocks | Catalyst |
|------|--------|------|----------------------|----------|

## Top 10 Gainers
| Rank | Stock | Gain | Volume | Unusual Signal |
|------|-------|------|--------|----------------|

## Capital Flow
- Main inflow sectors: ...
- Main outflow sectors: ...
- Unusual volume stocks: ...

## News Highlights
1. [News title] - [Impact analysis]
2. ...

## Investment Opportunities
- [Opportunity 1]: Reason and recommended stocks
- [Opportunity 2]: ...

## Risk Warnings
- [Risk 1]
- [Risk 2]
```

## Example

**User**: "How was the A-share market today?"

**Execution**:
1. `get_metadata(type='markets')` → china
2. `get_leaderboard` × 4 (gainers/losers/active/unusual-volume)
3. `get_news(market_country='CN', lang='zh-Hans')` + details
4. `get_quote_batch` → Index quotes
5. Sector categorization → Hot sector identification → News correlation
6. Generate review report


path: workflows/multi-symbol-analysis.md
content: ---
description: Multi-Symbol Batch Analysis Workflow - Batch analyze technical and quote data for multiple symbols
---

# Multi-Symbol Batch Analysis Workflow

Batch analyze technical analysis, quote data for multiple symbols, perform horizontal comparison and comprehensive evaluation.

## Execution Steps

### Step 1: Collect Symbol List

Extract list of symbols to analyze from user input:
- Support up to 10 symbols for simultaneous analysis
- Symbol format: EXCHANGE:SYMBOL (e.g., NASDAQ:AAPL)

### Step 2: Batch Get Real-time Quotes

Call `tradingview_get_quote_batch` to get real-time quotes for all symbols:

```
Parameter description:
- symbols: Array of symbols (1-10)
- session: Trading session (default: regular)
- fields: Return fields (default: all)
```

### Step 3: Batch Get Historical Charts

Call `tradingview_get_price_batch` to get historical data for all symbols:

```
Parameter description:
- requests: Request array (each contains symbol, timeframe, range)
- Maximum 10 requests
```

### Step 4: Get Technical Analysis Individually

For each symbol, call `tradingview_get_ta` to get technical analysis signals:
- Aggregate buy/sell/neutral signals
- Calculate comprehensive technical score

### Step 5: Horizontal Comparison Analysis

Compare key metrics across symbols:
- **Price change comparison**: Who gained/lost the most
- **Trading activity**: Who has the highest volume
- **Technical signal comparison**: Who has the strongest technicals
- **Volatility comparison**: Who has the highest volatility

### Step 6: Generate Comparison Report

Output comprehensive comparison report:
- Quote comparison table
- Technical score ranking
- Investment value ranking
- Risk-reward ratio comparison
- Recommended priority symbols

## Example Conversations

**User**: "Compare and analyze AAPL, MSFT, GOOGL stocks"

**Execution**:
1. Call `tradingview_get_quote_batch` to get real-time quotes
2. Call `tradingview_get_price_batch` to get daily chart data
3. Call `tradingview_get_ta` individually to get technical analysis
4. Generate comparison table, highlighting best performers for each metric

---

**User**: "Batch analyze tech leader stocks"

**Execution**:
1. Confirm tech leader list (AAPL, MSFT, GOOGL, AMZN, META, NVDA, TSLA, etc.)
2. Batch get quotes and technical analysis
3. Sort by price change and technical score
4. Recommend symbols with strongest technicals

---

**User**: "Compare BTC and ETH technicals"

**Execution**:
1. Call `tradingview_get_quote_batch`, symbols=["BINANCE:BTCUSDT", "BINANCE:ETHUSDT"]
2. Call `tradingview_get_price_batch` to get historical charts
3. Get technical analysis signals individually
4. Compare trend strength and overbought/oversold conditions


path: workflows/multi-timeframe-analysis.md
content: ---
description: Multi-Timeframe Analysis Workflow - Cross-period trend confirmation and entry timing selection
---

# Multi-Timeframe Analysis Workflow

Use candlestick data and technical indicators across multiple timeframes to confirm trend direction consistency and select optimal entry timing.

## Core Concept

**Higher timeframe defines direction, lower timeframe finds entry**: Monthly/weekly confirms primary trend, daily confirms medium-term trend, hourly selects entry point.

## Execution Steps

### Step 1: Get Multi-Period Chart Data

Call in parallel to get 4 timeframes:

```
tradingview_get_price(symbol, timeframe='M', range=24)    # Monthly - 2 years
tradingview_get_price(symbol, timeframe='W', range=52)    # Weekly - 1 year
tradingview_get_price(symbol, timeframe='D', range=120)   # Daily - 6 months
tradingview_get_price(symbol, timeframe='60', range=120)  # Hourly - 5 days
```

Optional: Use `type='HeikinAshi'` to get Heikin Ashi candles, filtering noise for clearer trend identification.

### Step 2: Get Technical Analysis Signals

```
tradingview_get_ta(symbol, include_indicators=true)
```

The TA tool returns multi-period signals (1-minute to monthly) directly providing buy/sell/neutral signal aggregation for each period.

### Step 3: Trend Assessment for Each Period

Assess trend direction for each timeframe:

**Monthly (Strategic Direction)**:
- Price above SMA20 → Long-term uptrend
- Price below SMA20 → Long-term downtrend
- MACD direction confirmation

**Weekly (Tactical Direction)**:
- Moving average alignment (SMA5 > SMA10 > SMA20 = bullish)
- RSI position (40-70 healthy uptrend range)
- MACD golden cross/death cross status

**Daily (Operating Period)**:
- Short-term vs medium-term moving average relationship
- Volume cooperation (volume surge on rise/volume contraction on pullback)
- Support/resistance levels

**Hourly (Entry Timing)**:
- Pullback near daily support level
- RSI bouncing from oversold zone
- Bullish candlestick pattern appears

### Step 4: Trend Consistency Assessment

| Monthly | Weekly | Daily | Signal Strength | Trading Recommendation |
|---------|--------|-------|----------------|------------------------|
| ↑ | ↑ | ↑ | Strong Bull | Aggressive long, trend following |
| ↑ | ↑ | ↓ | Medium Bull | Wait for daily pullback stabilization before buying |
| ↑ | ↓ | ↓ | Weak Bull | Wait and see, wait for weekly stabilization |
| ↓ | ↓ | ↓ | Strong Bear | Avoid or short |
| ↓ | ↓ | ↑ | Weak Bear | Likely a bounce, not suitable for chasing |
| ↓ | ↑ | ↑ | Medium Bear | Possible early reversal, light position test |

### Step 5: Generate Analysis Report

```markdown
# [Symbol] Multi-Timeframe Analysis

## Trend Status by Period
| Period | Trend | Key Indicators | TA Signal |
|--------|-------|----------------|-----------|
| Monthly | ↑/↓/→ | SMA20, MACD | Buy/Sell/Neutral |
| Weekly | ↑/↓/→ | MA alignment, RSI | Buy/Sell/Neutral |
| Daily | ↑/↓/→ | Volume, MA | Buy/Sell/Neutral |
| Hourly | ↑/↓/→ | Short-term momentum | Buy/Sell/Neutral |

## Trend Consistency: [Strong Bull/Medium Bull/Weak Bull/Neutral/Weak Bear/Strong Bear]

## Key Price Levels
- Monthly support: ¥XX
- Weekly support: ¥XX
- Daily support: ¥XX
- Daily resistance: ¥XX

## Trading Recommendations
- Direction: ...
- Entry conditions: ...
- Stop loss: ...
- Target: ...
```

## Example

**User**: "Multi-timeframe analysis of BTCUSDT"

**Execution**:
1. `get_price` × 4 timeframes (M/W/D/60)
2. `get_ta(include_indicators=true)` → Multi-period signals
3. Assess trend consistency across periods
4. Identify key support/resistance levels
5. Output trend consistency report and entry recommendations


path: workflows/news-briefing.md
content: ---
description: Financial News Briefing Workflow - Get and summarize financial news
---

# Financial News Briefing Workflow

Get financial news for specified countries/regions, analyze impact, and generate structured briefings.

## Execution Steps

### Step 1: Determine Target Market

Common market_country and lang combinations:

| Market | market_country | lang |
|--------|---------------|------|
| China | CN | zh-Hans |
| United States | US | en |
| Japan | JP | ja |
| Hong Kong | HK | zh-Hans or en |
| South Korea | KR | ko |

### Step 2: Get News List

```
tradingview_get_news(
  market_country='CN', lang='zh-Hans', limit=10,
  market='stock'  # Optional filter: stock/crypto/forex/futures/bond/etf/index/economic
)
```

Can also get by symbol:
```
tradingview_get_news(symbol='NASDAQ:AAPL', lang='en', limit=10)
```

### Step 3: Get News Details

Get full content for each news item:

```
tradingview_get_news_detail(news_id='tag:reuters.com,2026:newsml_xxx', lang='zh-Hans')
```

Returns: title, description, full content, related symbols, tags, storyPath.

News link format: `https://www.tradingview.com{storyPath}`

### Step 4: Analysis and Summary

Extract from each news item:
- Event subject (company/industry/policy)
- Impact scope and duration
- Beneficiary/affected symbols
- Investment recommendations

### Step 5: Generate Briefing

```markdown
# [Country/Region] Financial News Briefing - YYYY-MM-DD

## Today's Headlines

### 1. [News Title]
- Event: [Brief description]
- Impact: [Market impact analysis]
- Related symbols: [Stock codes]
- Source: https://www.tradingview.com{storyPath}

## Sector Updates
| Sector | Main News | Affected Symbols | Trend |
|--------|-----------|------------------|-------|

## Investment Opportunities and Risks
- Opportunities: ...
- Risks: ...
```

## Examples

**User**: "Generate today's China financial news briefing"

**Execution**:
1. `get_news(market_country='CN', lang='zh-Hans', limit=10)` → News list
2. For each `get_news_detail(news_id, lang='zh-Hans')` → Full content
3. Analyze impact, categorize by sector
4. Generate structured briefing

**User**: "Compare financial news from China, US, and Japan"

**Execution**:
1. `get_news` separately for CN/US/JP news
2. Get details separately
3. Cross-market comparative analysis
4. Generate comparison briefing


path: workflows/pattern-recognition.md
content: ---
description: Pattern Recognition Workflow - Automatically identify classic technical patterns and provide trading strategies
---

# Pattern Recognition Workflow

Based on candlestick data and technical indicators, identify classic technical patterns, provide confidence assessment and trading strategy recommendations.

Pattern recognition algorithms and success rate statistics can be found in `references/pattern-library.md`.

## Execution Steps

### Step 1: Get Historical Candlestick Data

Get sufficiently long daily data for pattern recognition:

```
tradingview_get_price(symbol, timeframe='D', range=120)
```

For short-term patterns (candlestick combinations), additionally get hourly data:
```
tradingview_get_price(symbol, timeframe='60', range=100)
```

Optional: `type='HeikinAshi'` to get Heikin Ashi candles for clearer trend structure visualization.

### Step 2: Get Technical Indicators

```
tradingview_get_ta(symbol, include_indicators=true)
```

Key indicators for pattern confirmation:
- **RSI**: Overbought/oversold status, divergence signals
- **MACD**: Golden cross/death cross, momentum direction
- **Volume**: Volume cooperation during pattern breakout
- **ADX**: Trend strength

### Step 3: Identify Patterns

Identify patterns based on candlestick data (see `references/pattern-library.md`):

**Reversal Patterns** (appear at trend ends):
- Double Bottom/Top: Two lows/highs close together, neckline breakout confirmation
- Head and Shoulders Bottom/Top: Three lows/highs, middle is lowest/highest
- Rounding Bottom/Top: Gradual reversal

**Continuation Patterns** (appear during trend continuation):
- Ascending/Descending Triangle: One side horizontal, one side diagonal
- Flag/Wedge: Narrow channel
- Rectangle: Horizontal channel

**Candlestick Patterns** (1-3 candle combinations):
- Hammer/Inverted Hammer
- Bullish/Bearish Engulfing
- Morning Star/Evening Star

### Step 4: Calculate Confidence

Confidence factors (0-100%):
- Pattern completeness (whether shape is standard)
- Volume cooperation (volume expansion on breakout adds points)
- Technical indicator confirmation (RSI/MACD direction consistency adds points)
- Time span (longer pattern duration is more reliable)
- Retest position (standing firm after neckline retest adds points)

### Step 5: Generate Trading Strategy

Calculate key price levels based on pattern type:

```
Entry price = Neckline breakout price (or pattern breakout price)
Stop loss = Below pattern lowest point (reversal) / Below channel lower boundary (continuation)
Target price = Entry price + Pattern height (measured move)
Risk-reward ratio = (Target - Entry) / (Entry - Stop loss)
```

Only recommend trades when risk-reward ratio > 1.5.

### Step 6: Output Analysis Report

```markdown
# [Symbol] Technical Pattern Analysis

## Identified Pattern
### [Pattern Name] (Confidence: XX%)
- Pattern description: ...
- Key levels: Neckline ¥XX
- Volume cooperation: [Expansion/Contraction/Normal]

## Technical Indicator Confirmation
- RSI(14): XX ([Overbought/Oversold/Healthy])
- MACD: [Golden cross/Death cross], DIF=[Positive/Negative]
- ADX: XX ([Trending/Non-trending])

## Trading Strategy
- Direction: [Long/Short/Wait]
- Entry price: ¥XX (Condition: [Breakout neckline/Pullback confirmation])
- Stop loss: ¥XX
- Target price: ¥XX
- Risk-reward ratio: 1:X.X

## Risk Warnings
- [List failure scenarios for this pattern]
```

## Example

**User**: "Analyze BTC/USDT technical patterns"

**Execution**:
1. `get_price(symbol='BINANCE:BTCUSDT', timeframe='D', range=120)` → Daily candles
2. `get_ta(symbol='BINANCE:BTCUSDT', include_indicators=true)` → Technical indicators
3. Analyze candlestick data to identify patterns (refer to `references/pattern-library.md`)
4. Calculate confidence and key price levels
5. Generate trading strategy report


path: workflows/realtime-monitor.md
content: ---
description: Real-time Market Monitor Workflow - Get and monitor real-time market quotes
---

# Real-time Market Monitor Workflow

Get and monitor real-time market quotes, including price, bid/ask, volume, and other key data.

## Execution Steps

### Step 1: Determine Monitoring Symbols

Extract list of symbols to monitor from user input:
- Single symbol: Get detailed quote
- Multiple symbols: Batch get quotes (up to 10)

### Step 2: Select Trading Session

Select trading session based on user needs:
- regular: Regular trading hours (default)
- extended: Pre-market and after-hours
- premarket: Pre-market only
- postmarket: After-hours only

### Step 3: Get Real-time Quotes

**Single Symbol**: Call `tradingview_get_quote`

```
Parameter description:
- symbol: Symbol code (required, format EXCHANGE:SYMBOL)
- session: Trading session (optional, default regular)
- fields: Return fields (optional, default all)
```

**Multiple Symbols**: Call `tradingview_get_quote_batch`

```
Parameter description:
- symbols: Symbol array (required, 1-10)
- session: Trading session (optional, default regular)
- fields: Return fields (optional, default all)
```

### Step 4: Parse Quote Data

Extract key information:
- **Price data**: Current price, open, high, low, previous close
- **Change data**: Change %, change amount
- **Trading data**: Volume, turnover
- **Bid/Ask**: Bid price, ask price, bid/ask size
- **Market info**: Exchange, currency, trading status

### Step 5: Generate Quote Report

Output formatted quote report, including:
- Symbol basic information
- Real-time price and change status
- Trading activity analysis
- Bid/ask strength comparison
- Unusual volatility alerts

## Example Conversations

**User**: "Check Apple stock real-time quote"

**Execution**:
1. Call `tradingview_get_quote`, symbol="NASDAQ:AAPL"
2. Return current price, change %, volume, and other data
3. Analyze bid/ask strength, provide brief commentary

---

**User**: "Monitor AAPL, TSLA, NVDA quotes simultaneously"

**Execution**:
1. Call `tradingview_get_quote_batch`, symbols=["NASDAQ:AAPL", "NASDAQ:TSLA", "NASDAQ:NVDA"]
2. Return real-time quote comparison for three stocks
3. Highlight largest change and most active trading

---

**User**: "Check BTCUSDT pre-market quote"

**Execution**:
1. Call `tradingview_get_quote`, symbol="BINANCE:BTCUSDT", session="extended"
2. Return pre-market trading data (if applicable)
3. Compare with regular session price changes


path: workflows/risk-assessment.md
content: ---
description: Risk assessment workflow - Position management and risk control recommendations
---

# Risk Assessment Workflow

Professional position management and risk control recommendation system. For detailed risk management methodology, see `references/risk-management.md`.

## Execution Steps

### Step 1: Get Historical K-line Data

Get sufficiently long daily data for volatility calculation:

```python
tradingview_get_price(symbol, timeframe='D', range=250)  # Approximately 1 year daily data
```

### Step 2: Get Real-time Quotes

```python
tradingview_get_quote(symbol, session='regular')
```

Extract: Current price, 52-week high/low, volume, bid/ask.

### Step 3: Get Technical Indicators

```python
tradingview_get_ta(symbol, include_indicators=true)
```

Key indicators for stop loss calculation:
- **Pivot Points**: Support/resistance levels (S1/S2/S3, R1/R2/R3)
- **SMA/EMA**: Moving average support (SMA20/50/200)
- **ATR**: Average True Range (for dynamic stop loss)
- **Beta**: Relative market volatility (for position adjustment)

### Step 4: Calculate Volatility

Based on daily data calculation:
- **Daily return standard deviation** = std(daily change percentage)
- **Annualized volatility** = Daily std × √252
- **Maximum drawdown** = max(historical peak to trough drawdown)
- **Beta coefficient**: Reference Beta value in TA indicators

### Step 5: Calculate Position Recommendations

Based on user's total capital and risk preference (see `references/risk-management.md`):

**Kelly Formula**:
```python
f = (bp - q) / b
where: b=odds, p=win rate, q=1-p
Recommend using half Kelly (f/2) for more conservative approach
```

**Volatility-adjusted Position Sizing**:
```python
Recommended position % = Target daily volatility / Instrument daily volatility
Example: Target daily volatility 2%, instrument daily volatility 4% → Max position 50%
```

**Staggered Entry Recommendations**:
- First position: 30-40% of total position
- Add position 1: Add 30% after trend confirmation
- Add position 2: Add another 30% after breaking key levels

### Step 6: Calculate Stop Loss and Take Profit

**Stop Loss Calculation** (choose the most reasonable one):
- ATR stop: Current price - 2×ATR
- MA stop: Below recent moving average support (SMA20 or SMA50)
- Pivot stop: Below S1 or S2
- Pattern stop: Below pattern low

**Take Profit Calculation**:
- ATR target: Current price + 3×ATR
- Pivot target: R1, R2, R3
- Measured target: Calculate based on pattern height

**Risk-Reward Ratio**: Must be > 1.5, ideally > 2.0

### Step 7: Generate Risk Management Plan

```markdown
# [Instrument] Risk Assessment Report

## Volatility Analysis
- Annualized volatility: XX%
- Recent 20-day average daily range: XX%
- Beta coefficient: XX
- Maximum drawdown: XX%

## Position Recommendations (Based on total capital ¥XX ten thousand)
- Recommended total position: XX% (¥XX)
- Maximum single trade: ¥XX
- Staggered entry plan:
  - First position ¥XX @ ¥XX (current price)
  - Add position 1 ¥XX @ ¥XX (condition: XX confirmation)
  - Add position 2 ¥XX @ ¥XX (condition: break above XX)

## Stop Loss and Take Profit Plan
- Stop loss price: ¥XX (XX% below current)
  - Method: [ATR/MA/Pivot]
- Take profit target 1: ¥XX (+XX%)
- Take profit target 2: ¥XX (+XX%)
- Risk-reward ratio: 1:X.X

## Maximum Loss Estimation
- Maximum loss per trade: ¥XX (XX% of total capital)
- Recommend single trade risk not exceeding 2% of total capital

## Risk Warnings
- [Volatility risk/Liquidity risk/Event risk etc.]
```

## Example

**User**: "I have 100k capital, want to buy Puyuan Information, how much should I buy?"

**Execution**:
1. `search_market(query='普元信息')` → SSE:688118
2. `get_price(symbol='SSE:688118', timeframe='D', range=250)` → Daily K-lines
3. `get_quote(symbol='SSE:688118')` → Real-time price
4. `get_ta(symbol='SSE:688118', include_indicators=true)` → Technical indicators
5. Calculate volatility → Kelly formula → Position recommendations
6. Calculate stop loss/take profit levels → Risk-reward ratio
7. Generate complete risk management plan, stop loss/take profit strategy, risk-reward ratio plan.


path: workflows/sector-rotation.md
content: ---
description: Sector rotation analysis workflow - Identify strong sectors and rotation trends
---

# Sector Rotation Analysis Workflow

Through `tradingview_get_leaderboard`'s performance columnset and various tabs, identify current strong sectors, analyze rotation trends, and discover investment opportunities.

## Execution Steps

### Step 1: Get Metadata

```
tradingview_get_metadata(type='markets')   # Confirm market_code
tradingview_get_metadata(type='tabs', asset_type='stocks')  # View all category tabs
```

### Step 2: Get Sector Performance Rankings (performance columnset)

```
# Gainers - performance data (1W/1M/3M/6M/1Y returns)
tradingview_get_leaderboard(
  asset_type='stocks', tab='best-performing',
  market_code='china', columnset='performance', count=50
)

# Losers
tradingview_get_leaderboard(
  asset_type='stocks', tab='losers',
  market_code='china', columnset='performance', count=50
)

# Active stocks
tradingview_get_leaderboard(
  asset_type='stocks', tab='active',
  market_code='china', columnset='overview', count=50
)

# Unusual volume
tradingview_get_leaderboard(
  asset_type='stocks', tab='unusual-volume',
  market_code='china', columnset='overview', count=50
)
```

### Step 3: Sector Classification Analysis

Classify gainer stocks by industry/sector, calculate:
- Percentage of each sector in gainers
- Average gains of each sector (1W/1M/3M dimensions)
- Sector leader identification

### Step 4: Sector Strength Ranking

Compare multi-period returns of various sectors through performance data:

| Sector | 1W | 1M | 3M | 6M | Trend Judgment |
|--------|----|----|----|----|---------------|
| ... | ... | ... | ... | ... | Acceleration/Deceleration/Reversal |

Judgment logic:
- **Accelerating up**: Short-term > medium-term > long-term returns
- **Decelerating up**: Long-term > medium-term > short-term returns
- **Reversal up**: Short-term positive, long-term negative
- **Reversal down**: Short-term negative, long-term positive

### Step 5: Confirm with News

```
tradingview_get_news(market='stock', market_country='CN', lang='zh-Hans', limit=10)
```

Analyze news for sector associations, confirm if sector strength has fundamental/policy support.

### Step 6: Sector Leader Technical Verification

For 1-2 leader stocks of each strong sector:

```
tradingview_get_ta(symbol, include_indicators=true)
```

Confirm if sector leader technicals support continued sector trend.

### Step 7: Generate Sector Rotation Report

```markdown
# Sector Rotation Analysis Report

## Current Strong Sectors (Ranked by Strength)
| Rank | Sector | 1W Gain | 1M Gain | Trend Stage | Leader Stock |
|------|--------|---------|---------|------------|-------------|

## Weak Sectors
| Rank | Sector | 1W Loss | Trend Stage | Oversold? |
|------|--------|---------|------------|-----------|

## Rotation Trend Judgment
- Current market style: [Value/Growth/Cyclical/Defensive]
- Capital flow: [From XX sector to XX sector]
- Rotation stage: [Early/Middle/Late]

## Investment Recommendations
- Recommended sectors: ...
- Avoid sectors: ...
- Leader stock recommendations: ...
```

## ETF/Index Sector Analysis

Can also use index and ETF data for sector analysis:

```
# Industry index comparison
tradingview_get_leaderboard(asset_type='indices', tab='all', columnset='performance')

# ETF sector comparison
tradingview_get_leaderboard(asset_type='etfs', tab='sector-etfs', columnset='performance')
tradingview_get_leaderboard(asset_type='etfs', tab='highest-returns', columnset='performance')
```


path: workflows/smart-screening.md
content: ---
description: Smart stock screening workflow - Filter quality targets based on multi-factor model
---

# Smart Stock Screening Workflow

Based on multi-factor model, filter quality targets from the market that meet technical and fundamental conditions, providing comprehensive scoring and buy recommendations.

## Execution Steps

### Step 1: Understand Screening Criteria

Extract from user input:
- **Market scope**: Country/region (determine market_code), asset type
- **Technical conditions**: Trend direction, RSI range, MACD status, volume
- **Fundamental conditions**: PE, PB, ROE, market cap, dividend yield, etc.
- **Sorting preference**: Change percentage, market cap, volume, etc.

### Step 2: Get Metadata (Metadata First)

```
tradingview_get_metadata(type='markets')  # Get market_code
tradingview_get_metadata(type='tabs', asset_type='stocks')  # Get available tabs
```

### Step 3: Get Candidate Pool

Choose appropriate tab and columnset based on screening direction:

```
# Technical screening - Use technical-related tabs
tradingview_get_leaderboard(
  asset_type='stocks', tab='gainers',  # or active/unusual-volume/best-performing
  market_code='china', columnset='overview', count=100
)

# Fundamental data - Switch columnset
tradingview_get_leaderboard(
  asset_type='stocks', tab='all-stocks',
  market_code='china', columnset='valuation', count=100
)

# Profitability
tradingview_get_leaderboard(
  asset_type='stocks', tab='all-stocks',
  market_code='china', columnset='profitability', count=100
)
```

### Step 4: Technical Screening

For Top 20-30 in candidate pool, call individually:

```
tradingview_get_ta(symbol, include_indicators=true)
```

Screening criteria (see `references/technical-analysis.md` scoring model):
- TA multi-timeframe signal is Buy
- RSI in healthy range 30-70
- MACD golden cross or DIF > 0
- ADX > 25 (trend exists)

### Step 5: K-line Data Verification

For Top 10 that pass technical screening, get K-line confirmation:

```
tradingview_get_price(symbol, timeframe='D', range=60)
```

Verify:
- Moving average arrangement (bullish/bearish)
- Volume coordination (volume increase on rise)
- Distance from support level

### Step 6: Comprehensive Scoring and Ranking

Calculate total score (100-point system) according to `references/technical-analysis.md` scoring model:
- Trend strength 30 points
- Momentum indicators 25 points
- Pattern recognition 20 points
- Support resistance 15 points
- Market sentiment 10 points

### Step 7: Generate Detailed Report

```markdown
# Smart Stock Screening Results - [Market/Sector]

## Screening Criteria
- [List technical and fundamental conditions]

## Qualified Stocks (Total N stocks)

### 1. [Stock Name] (Code) ⭐⭐⭐⭐⭐
**Comprehensive Score**: XX/100
- Technical: RSI=XX, MACD=XX, Trend=XX
- Fundamental: PE=XX, ROE=XX%
- Buy Recommendation: ¥XX-XX
- Stop Loss: ¥XX
- Target Price: ¥XX
```

## Example

**User**: "Help me select strong stocks from China A-shares"

**Execution**:
1. `get_metadata(type='markets')` → china
2. `get_leaderboard(tab='gainers', market_code='china', count=100)` → Gainers
3. `get_leaderboard(tab='gainers', market_code='china', columnset='valuation')` → Valuation
4. Top 20 individual `get_ta(include_indicators=true)` → Technical screening
5. Top 10 `get_price(timeframe='D', range=60)` → K-line verification
6. Comprehensive scoring → Output Top 10 report


path: workflows/symbol-search.md
content: ---
description: Symbol search workflow - Quick search and discovery of trading instruments
---

# Symbol Search Workflow

Quickly search and discover trading instruments such as stocks, cryptocurrencies, forex, futures, etc.

## Execution Steps

### Step 1: Parse Search Intent

Extract search keywords and filter conditions from user input:
- Keywords: Stock names, codes, pinyin abbreviations, etc.
- Asset type: Stocks, cryptocurrencies, forex, futures, indices, funds, bonds, options
- Language preference: Chinese or English

### Step 2: Call Search Tool

Call `tradingview_search_market` for instrument search:

```
Parameter description:
- query: Search keywords (required)
- filter: Asset type filter (optional)
  - stock: Stocks
  - crypto: Cryptocurrency
  - forex: Forex
  - futures: Futures
  - index: Indices
  - funds: Funds
  - bond: Bonds
  - options: Options
- lang: Language code (default en)
- limit: Number of results (default 20, max 100)
```

### Step 3: Format Search Results

Organize search results into readable format, including:
- Instrument code (e.g., NASDAQ:AAPL)
- Exchange name
- Full name and description
- Asset type
- Currency code
- Country

### Step 4: Provide Follow-up Action Suggestions

Based on search results, suggest subsequent operations users can perform:
- View real-time quotes: `tradingview_get_quote`
- View technical analysis: `tradingview_get_ta`
- View historical K-lines: `tradingview_get_price`
- View related news: `tradingview_get_news`

## Example Conversations

**User**: "Help me search for Apple company's stock"

**Execution**:
1. Call `tradingview_search_market`, query="AAPL", filter="stock"
2. Return results including NASDAQ:AAPL and other matches
3. Suggest user can view real-time quotes or technical analysis

---

**User**: "Search for Bitcoin-related trading pairs"

**Execution**:
1. Call `tradingview_search_market`, query="BTC", filter="crypto"
2. Return BINANCE:BTCUSDT, COINBASE:BTCUSD and other trading pairs
3. Suggest user select specific trading pair for in-depth analysis


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)