tradingview-mcp-assistant
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTradingView MCP Assistant
TradingView MCP Assistant
Skill by ara.so — MCP Skills collection.
Personal AI assistant for TradingView Desktop charts. Connects Claude Code to your locally running TradingView app via Chrome DevTools Protocol for AI-assisted chart analysis, Pine Script development, and workflow automation.
Important: This tool requires a valid TradingView subscription and the Desktop app. It communicates only with your local TradingView instance via CDP (Chrome DevTools Protocol) — no external connections, no data transmission.
由ara.so开发的Skill——MCP Skills合集。
TradingView桌面端图表的个人AI助手。通过Chrome DevTools Protocol将Claude Code与本地运行的TradingView应用连接,实现AI辅助的图表分析、Pine Script开发以及工作流自动化。
重要提示: 本工具需要有效的TradingView订阅和桌面端应用。它仅通过CDP(Chrome DevTools Protocol)与本地TradingView实例通信——无外部连接,无数据传输。
What This Skill Enables
本Skill可实现的功能
- Pine Script development — write, compile, debug, and iterate on indicators/strategies
- Chart navigation — change symbols, timeframes, zoom to dates, manage layouts
- Visual analysis — read indicator values, price levels, and Pine Script drawings
- Drawing tools — add trend lines, horizontal lines, rectangles, text annotations
- Alert management — create, list, and delete price alerts
- Replay mode — step through historical bars for practice trading
- Multi-pane layouts — set up 2x2, 3x1 grids with different symbols
- Chart streaming — monitor live data with JSONL output
- CLI access — every MCP tool available as command for scripting
tv
- Pine Script开发 — 编写、编译、调试指标/策略并迭代优化
- 图表导航 — 切换交易品种、时间周期、缩放至指定日期、管理布局
- 可视化分析 — 读取指标数值、价格水平及Pine Script绘制的图形
- 绘图工具 — 添加趋势线、水平线、矩形框、文本注释
- 警报管理 — 创建、列出和删除价格警报
- 复盘模式 — 逐根K线回溯历史数据,进行模拟交易练习
- 多面板布局 — 设置2x2、3x1等网格布局,每个面板显示不同品种
- 图表数据流 — 通过JSONL输出监控实时数据
- CLI访问 — 所有MCP工具均可通过命令调用,用于脚本编写
tv
Installation
安装步骤
Prerequisites
前置条件
- TradingView Desktop app (paid subscription required)
- Node.js 18+
- Claude Code with MCP support
- macOS, Windows, or Linux
- TradingView桌面端应用(需付费订阅)
- Node.js 18+
- 支持MCP的Claude Code
- macOS、Windows或Linux系统
Setup Steps
设置流程
bash
undefinedbash
undefined1. Clone and install
1. 克隆项目并安装依赖
git clone https://github.com/tradesdontlie/tradingview-mcp.git
cd tradingview-mcp
npm install
git clone https://github.com/tradesdontlie/tradingview-mcp.git
cd tradingview-mcp
npm install
2. Optional: Install CLI globally
2. 可选:全局安装CLI
npm link
undefinednpm link
undefinedLaunch TradingView with Debug Mode
以调试模式启动TradingView
TradingView Desktop must run with Chrome DevTools Protocol enabled on port 9222.
macOS:
bash
./scripts/launch_tv_debug_mac.shWindows:
bash
scripts\launch_tv_debug.batLinux:
bash
./scripts/launch_tv_debug_linux.shOr use the MCP tool:
javascript
// Claude will execute
tv_launch()TradingView桌面端必须启用Chrome DevTools Protocol并监听9222端口。
macOS系统:
bash
./scripts/launch_tv_debug_mac.shWindows系统:
bash
scripts\launch_tv_debug.batLinux系统:
bash
./scripts/launch_tv_debug_linux.sh或使用MCP工具启动:
javascript
// Claude将执行此命令
tv_launch()Configure Claude Code
配置Claude Code
Add to or project :
~/.claude/.mcp.json.mcp.jsonjson
{
"mcpServers": {
"tradingview": {
"command": "node",
"args": ["/absolute/path/to/tradingview-mcp/src/server.js"]
}
}
}将以下内容添加到或项目目录下的:
~/.claude/.mcp.json.mcp.jsonjson
{
"mcpServers": {
"tradingview": {
"command": "node",
"args": ["/absolute/path/to/tradingview-mcp/src/server.js"]
}
}
}Verify Connection
验证连接
Ask Claude: "Use tv_health_check to verify TradingView is connected"
向Claude询问:"使用tv_health_check验证TradingView是否已连接"
Key MCP Tools
核心MCP工具
Chart Reading (Start Here)
图表读取(入门首选)
javascript
// 1. Always start with state to get chart context
const state = await chart_get_state();
// Returns: { symbol: "BTCUSD", timeframe: "5", indicators: [{name, id}], layout: "..." }
// 2. Get current price
const quote = await quote_get();
// Returns: { symbol, close, open, high, low, volume, change, changePercent }
// 3. Read all indicator values (RSI, MACD, BB, etc.)
const values = await data_get_study_values();
// Returns: [{ name: "RSI", plots: [{title: "RSI", value: 54.32}] }]
// 4. Get OHLCV bars (ALWAYS use summary: true first)
const bars = await data_get_ohlcv({ summary: true });
// Returns: { bars: 500, range: "...", high: 45000, low: 42000, avgVolume: 1234 }javascript
// 1. 先获取图表状态以了解上下文
const state = await chart_get_state();
// 返回结果:{ symbol: "BTCUSD", timeframe: "5", indicators: [{name, id}], layout: "..." }
// 2. 获取当前价格
const quote = await quote_get();
// 返回结果:{ symbol, close, open, high, low, volume, change, changePercent }
// 3. 读取所有指标数值(RSI、MACD、布林带等)
const values = await data_get_study_values();
// 返回结果:[{ name: "RSI", plots: [{title: "RSI", value: 54.32}] }]
// 4. 获取OHLCK数据(务必先使用summary: true)
const bars = await data_get_ohlcv({ summary: true });
// 返回结果:{ bars: 500, range: "...", high: 45000, low: 42000, avgVolume: 1234 }Pine Script Data (Custom Indicators)
Pine Script数据(自定义指标)
Read , , , from Pine Scripts:
line.new()label.new()table.new()box.new()javascript
// Read horizontal price levels (support/resistance)
const lines = await data_get_pine_lines({
study_filter: "Session Levels"
});
// Returns: [{ y: 24500, text: "PDH", color: "blue" }]
// Read text labels with prices
const labels = await data_get_pine_labels({
study_filter: "Market Structure"
});
// Returns: [{ price: 24450, text: "HH", time: "2025-01-15T10:30:00Z" }]
// Read data tables (session stats, analytics)
const tables = await data_get_pine_tables({
study_filter: "Volume Profile"
});
// Returns: [{ headers: ["Price", "Volume"], rows: [[24500, 1234], ...] }]
// Read price zones/ranges
const boxes = await data_get_pine_boxes({
study_filter: "Supply Demand"
});
// Returns: [{ high: 24600, low: 24500, text: "Supply Zone" }]Always use to target specific indicators — reduces noise and token usage.
study_filter读取Pine Script中通过、、、绘制的内容:
line.new()label.new()table.new()box.new()javascript
// 读取水平价格位(支撑/阻力)
const lines = await data_get_pine_lines({
study_filter: "Session Levels"
});
// 返回结果:[{ y: 24500, text: "PDH", color: "blue" }]
// 读取带价格的文本标签
const labels = await data_get_pine_labels({
study_filter: "Market Structure"
});
// 返回结果:[{ price: 24450, text: "HH", time: "2025-01-15T10:30:00Z" }]
// 读取数据表格(时段统计、分析数据)
const tables = await data_get_pine_tables({
study_filter: "Volume Profile"
});
// 返回结果:[{ headers: ["Price", "Volume"], rows: [[24500, 1234], ...] }]
// 读取价格区间/区域
const boxes = await data_get_pine_boxes({
study_filter: "Supply Demand"
});
// 返回结果:[{ high: 24600, low: 24500, text: "Supply Zone" }]务必使用 来定位特定指标——减少冗余信息和token消耗。
study_filterChart Control
图表控制
javascript
// Change symbol
await chart_set_symbol({ symbol: "AAPL" });
// Change timeframe (1, 5, 15, 60, D, W, M)
await chart_set_timeframe({ timeframe: "D" });
// Change chart type
await chart_set_type({ type: "HeikinAshi" }); // Candles, Line, Area, Renko
// Scroll to date
await chart_scroll_to_date({ date: "2025-01-15" });
// Zoom to exact range (unix timestamps)
await chart_set_visible_range({
from: 1705276800,
to: 1705363200
});
// Add indicator (use FULL name)
await chart_manage_indicator({
action: "add",
name: "Relative Strength Index" // NOT "RSI"
});
// Remove indicator
await chart_manage_indicator({
action: "remove",
indicator_id: "123abc" // from chart_get_state
});javascript
// 切换交易品种
await chart_set_symbol({ symbol: "AAPL" });
// 切换时间周期(1、5、15、60、D、W、M)
await chart_set_timeframe({ timeframe: "D" });
// 切换图表类型
await chart_set_type({ type: "HeikinAshi" }); // 蜡烛图、折线图、面积图、Renko图
// 滚动到指定日期
await chart_scroll_to_date({ date: "2025-01-15" });
// 缩放至精确区间(Unix时间戳)
await chart_set_visible_range({
from: 1705276800,
to: 1705363200
});
// 添加指标(使用完整名称)
await chart_manage_indicator({
action: "add",
name: "Relative Strength Index" // 不可用"RSI"
});
// 删除指标
await chart_manage_indicator({
action: "remove",
indicator_id: "123abc" // 从chart_get_state获取
});Pine Script Development
Pine Script开发
javascript
// 1. Inject code into Pine Editor
await pine_set_source({
source: `//@version=5
indicator("My RSI", overlay=false)
rsiValue = ta.rsi(close, 14)
plot(rsiValue, "RSI", color=color.blue)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)`
});
// 2. Compile with auto-detection
const result = await pine_smart_compile();
// Returns: { success: true/false, version_detected: 5, errors: [] }
// 3. Check for errors
if (!result.success) {
const errors = await pine_get_errors();
// Returns: [{ line: 4, message: "Undeclared identifier 'foo'" }]
}
// 4. Read console output (log.info)
const logs = await pine_get_console();
// Returns: ["RSI value: 54.32", "Signal: BUY"]
// 5. Save to TradingView cloud
await pine_save({ name: "My Custom RSI" });
// Read current source (WARNING: can be 200KB+ for complex scripts)
const code = await pine_get_source();
// Analyze code structure (get functions, inputs, plots)
const analysis = await pine_analyze_code();
// Returns: { functions: [...], inputs: [...], plots: [...] }javascript
// 1. 将代码注入Pine编辑器
await pine_set_source({
source: `//@version=5
indicator("My RSI", overlay=false)
rsiValue = ta.rsi(close, 14)
plot(rsiValue, "RSI", color=color.blue)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)`
});
// 2. 自动检测版本并编译
const result = await pine_smart_compile();
// 返回结果:{ success: true/false, version_detected: 5, errors: [] }
// 3. 检查错误
if (!result.success) {
const errors = await pine_get_errors();
// 返回结果:[{ line: 4, message: "Undeclared identifier 'foo'" }]
}
// 4. 读取控制台输出(log.info)
const logs = await pine_get_console();
// 返回结果:["RSI value: 54.32", "Signal: BUY"]
// 5. 保存到TradingView云端
await pine_save({ name: "My Custom RSI" });
// 读取当前代码(注意:复杂脚本可能超过200KB)
const code = await pine_get_source();
// 分析代码结构(获取函数、输入参数、绘图)
const analysis = await pine_analyze_code();
// 返回结果:{ functions: [...], inputs: [...], plots: [...] }Multi-Pane Layouts
多面板布局
javascript
// List all panes
const panes = await pane_list();
// Returns: [{ index: 0, symbol: "BTCUSD", active: true }, ...]
// Change layout (s, 2h, 2v, 2x2, 4, 6, 8)
await pane_set_layout({ layout: "2x2" });
// Set symbol on specific pane
await pane_set_symbol({ pane_index: 0, symbol: "ES1!" });
await pane_set_symbol({ pane_index: 1, symbol: "NQ1!" });
await pane_set_symbol({ pane_index: 2, symbol: "AAPL" });
await pane_set_symbol({ pane_index: 3, symbol: "TSLA" });
// Focus a pane
await pane_focus({ pane_index: 1 });javascript
// 列出所有面板
const panes = await pane_list();
// 返回结果:[{ index: 0, symbol: "BTCUSD", active: true }, ...]
// 切换布局(s、2h、2v、2x2、4、6、8)
await pane_set_layout({ layout: "2x2" });
// 设置指定面板的交易品种
await pane_set_symbol({ pane_index: 0, symbol: "ES1!" });
await pane_set_symbol({ pane_index: 1, symbol: "NQ1!" });
await pane_set_symbol({ pane_index: 2, symbol: "AAPL" });
await pane_set_symbol({ pane_index: 3, symbol: "TSLA" });
// 聚焦指定面板
await pane_focus({ pane_index: 1 });Drawing Tools
绘图工具
javascript
// Draw horizontal line
await draw_shape({
shape_type: "horizontal_line",
price: 24500,
text: "Key Level",
color: "#FF0000"
});
// Draw trend line
await draw_shape({
shape_type: "trend_line",
price1: 24000,
time1: "2025-01-10T10:00:00Z",
price2: 24500,
time2: "2025-01-15T15:00:00Z",
color: "#00FF00"
});
// Draw rectangle
await draw_shape({
shape_type: "rectangle",
price1: 24000,
time1: "2025-01-10T10:00:00Z",
price2: 24500,
time2: "2025-01-15T15:00:00Z",
fill_color: "#0000FF33"
});
// List all drawings
const drawings = await draw_list();
// Remove specific drawing
await draw_remove({ drawing_id: "abc123" });
// Clear all drawings
await draw_clear();javascript
// 绘制水平线
await draw_shape({
shape_type: "horizontal_line",
price: 24500,
text: "关键价位",
color: "#FF0000"
});
// 绘制趋势线
await draw_shape({
shape_type: "trend_line",
price1: 24000,
time1: "2025-01-10T10:00:00Z",
price2: 24500,
time2: "2025-01-15T15:00:00Z",
color: "#00FF00"
});
// 绘制矩形框
await draw_shape({
shape_type: "rectangle",
price1: 24000,
time1: "2025-01-10T10:00:00Z",
price2: 24500,
time2: "2025-01-15T15:00:00Z",
fill_color: "#0000FF33"
});
// 列出所有绘图
const drawings = await draw_list();
// 删除指定绘图
await draw_remove({ drawing_id: "abc123" });
// 清空所有绘图
await draw_clear();Alert Management
警报管理
javascript
// List alerts
const alerts = await alert_list();
// Create price alert
await alert_create({
symbol: "BTCUSD",
condition: "crossing",
price: 45000,
message: "BTC crossed 45k"
});
// Delete alert
await alert_delete({ alert_id: "xyz789" });javascript
// 列出所有警报
const alerts = await alert_list();
// 创建价格警报
await alert_create({
symbol: "BTCUSD",
condition: "crossing",
price: 45000,
message: "BTC突破45000"
});
// 删除警报
await alert_delete({ alert_id: "xyz789" });Replay Mode
复盘模式
javascript
// Start replay at date
await replay_start({ date: "2025-03-01" });
// Step forward (bar-by-bar)
await replay_step({ direction: "forward", bars: 1 });
// Step backward
await replay_step({ direction: "backward", bars: 5 });
// Simulate trade entry
await replay_trade({
action: "long",
price: 24500,
quantity: 1,
stop_loss: 24400,
take_profit: 24700
});
// Check replay status
const status = await replay_status();
// Auto-play
await replay_autoplay({ speed: 2 }); // 1-5
// Stop replay
await replay_stop();javascript
// 从指定日期开始复盘
await replay_start({ date: "2025-03-01" });
// 向前步进(逐根K线)
await replay_step({ direction: "forward", bars: 1 });
// 向后步进
await replay_step({ direction: "backward", bars: 5 });
// 模拟交易入场
await replay_trade({
action: "long",
price: 24500,
quantity: 1,
stop_loss: 24400,
take_profit: 24700
});
// 检查复盘状态
const status = await replay_status();
// 自动播放
await replay_autoplay({ speed: 2 }); // 速度范围1-5
// 停止复盘
await replay_stop();Screenshot Capture
截图捕获
javascript
// Capture full chart
await capture_screenshot({ region: "chart" });
// Capture specific region
await capture_screenshot({
region: "custom",
x: 100, y: 100, width: 800, height: 600
});
// Returns: { path: "/tmp/chart_2025-05-16_12-30-45.png" }javascript
// 捕获完整图表
await capture_screenshot({ region: "chart" });
// 捕获指定区域
await capture_screenshot({
region: "custom",
x: 100, y: 100, width: 800, height: 600
});
// 返回结果:{ path: "/tmp/chart_2025-05-16_12-30-45.png" }CLI Usage
CLI使用方法
Every MCP tool is also a CLI command. All output is JSON.
tvbash
undefined所有MCP工具均可通过 CLI命令调用,输出均为JSON格式。
tvbash
undefinedConnection
连接相关
tv status # check connection
tv launch # start TradingView in debug mode
tv status # 检查连接状态
tv launch # 以调试模式启动TradingView
Chart reading
图表读取
tv quote # current price
tv ohlcv --summary # price summary
tv state # full chart state
tv values # all indicator values
tv quote # 获取当前价格
tv ohlcv --summary # 获取价格汇总
tv state # 获取完整图表状态
tv values # 获取所有指标数值
Chart control
图表控制
tv symbol AAPL # change symbol
tv timeframe D # change timeframe
tv type HeikinAshi # change chart type
tv scroll --date 2025-01-15 # jump to date
tv symbol AAPL # 切换交易品种
tv timeframe D # 切换时间周期
tv type HeikinAshi # 切换图表类型
tv scroll --date 2025-01-15 # 跳转到指定日期
Pine Script
Pine Script相关
tv pine get # read source
tv pine compile # compile
tv pine errors # show errors
tv pine save "My Indicator" # save to cloud
tv pine get # 读取代码
tv pine compile # 编译代码
tv pine errors # 显示错误信息
tv pine save "My Indicator" # 保存到云端
Data extraction
数据提取
tv data lines --filter "Levels" # read Pine lines
tv data labels --filter "MSB" # read Pine labels
tv data tables --filter "Profile" # read Pine tables
tv data lines --filter "Levels" # 读取Pine绘制的线条
tv data labels --filter "MSB" # 读取Pine绘制的标签
tv data tables --filter "Profile" # 读取Pine绘制的表格
Drawing
绘图相关
tv draw shape --type horizontal_line --price 24500
tv draw list # list drawings
tv draw clear # clear all
tv draw shape --type horizontal_line --price 24500
tv draw list # 列出所有绘图
tv draw clear # 清空所有绘图
Layouts
布局相关
tv pane layout 2x2 # 4-chart grid
tv pane symbol 0 ES1! # set pane symbol
tv pane list # list all panes
tv pane layout 2x2 # 设置4面板网格布局
tv pane symbol 0 ES1! # 设置指定面板的交易品种
tv pane list # 列出所有面板
Streaming (JSONL output, pipe-friendly)
数据流(JSONL输出,支持管道操作)
tv stream quote # monitor price
tv stream bars # bar updates
tv stream values # indicator updates
tv stream all # all panes
tv stream quote | jq '.close' # pipe to jq
undefinedtv stream quote # 监控价格
tv stream bars # 监控K线更新
tv stream values # 监控指标更新
tv stream all # 监控所有面板
tv stream quote | jq '.close' # 通过jq处理输出
undefinedCommon Patterns
常用模式
Full Chart Analysis Workflow
完整图表分析流程
javascript
// 1. Get chart context
const state = await chart_get_state();
const quote = await quote_get();
// 2. Read all indicators
const values = await data_get_study_values();
// 3. Read custom Pine data
const lines = await data_get_pine_lines({ study_filter: "Levels" });
const labels = await data_get_pine_labels({ study_filter: "Structure" });
const tables = await data_get_pine_tables({ study_filter: "Stats" });
// 4. Get price summary
const ohlcv = await data_get_ohlcv({ summary: true });
// 5. Capture screenshot
const screenshot = await capture_screenshot({ region: "chart" });
// 6. Compile analysis
const analysis = `
Chart: ${state.symbol} ${state.timeframe}
Price: ${quote.close} (${quote.changePercent}%)
RSI: ${values.find(v => v.name.includes('RSI'))?.plots[0]?.value}
Key Levels: ${lines.map(l => `${l.text}: ${l.y}`).join(', ')}
Screenshot: ${screenshot.path}
`;javascript
// 1. 获取图表上下文
const state = await chart_get_state();
const quote = await quote_get();
// 2. 读取所有指标
const values = await data_get_study_values();
// 3. 读取自定义Pine数据
const lines = await data_get_pine_lines({ study_filter: "Levels" });
const labels = await data_get_pine_labels({ study_filter: "Structure" });
const tables = await data_get_pine_tables({ study_filter: "Stats" });
// 4. 获取价格汇总
const ohlcv = await data_get_ohlcv({ summary: true });
// 5. 捕获截图
const screenshot = await capture_screenshot({ region: "chart" });
// 6. 整理分析报告
const analysis = `
图表:${state.symbol} ${state.timeframe}
价格:${quote.close} (${quote.changePercent}%)
RSI:${values.find(v => v.name.includes('RSI'))?.plots[0]?.value}
关键价位:${lines.map(l => `${l.text}: ${l.y}`).join(', ')}
截图路径:${screenshot.path}
`;Pine Script Iteration
Pine Script迭代开发
javascript
// User says: "Write a VWAP indicator with bands"
// 1. Generate initial code
const code = `//@version=5
indicator("VWAP Bands", overlay=true)
vwapValue = ta.vwap
stdDev = ta.stdev(close, 20)
upper = vwapValue + stdDev
lower = vwapValue - stdDev
plot(vwapValue, "VWAP", color=color.blue)
plot(upper, "Upper", color=color.red)
plot(lower, "Lower", color=color.green)`;
// 2. Inject and compile
await pine_set_source({ source: code });
const result = await pine_smart_compile();
// 3. Check errors
if (!result.success) {
const errors = await pine_get_errors();
// Fix errors, iterate
// await pine_set_source({ source: fixedCode });
// await pine_smart_compile();
}
// 4. Test on chart, read console
const logs = await pine_get_console();
// 5. Save when satisfied
await pine_save({ name: "VWAP Bands" });javascript
// 用户需求:"编写带布林带的VWAP指标"
// 1. 生成初始代码
const code = `//@version=5
indicator("VWAP Bands", overlay=true)
vwapValue = ta.vwap
stdDev = ta.stdev(close, 20)
upper = vwapValue + stdDev
lower = vwapValue - stdDev
plot(vwapValue, "VWAP", color=color.blue)
plot(upper, "Upper", color=color.red)
plot(lower, "Lower", color=color.green)`;
// 2. 注入代码并编译
await pine_set_source({ source: code });
const result = await pine_smart_compile();
// 3. 检查错误
if (!result.success) {
const errors = await pine_get_errors();
// 修复错误并迭代
// await pine_set_source({ source: fixedCode });
// await pine_smart_compile();
}
// 4. 在图表上测试,读取控制台输出
const logs = await pine_get_console();
// 5. 满意后保存
await pine_save({ name: "VWAP Bands" });Multi-Symbol Dashboard
多品种仪表盘
javascript
// Set up 4-chart grid with futures
await pane_set_layout({ layout: "2x2" });
await pane_set_symbol({ pane_index: 0, symbol: "ES1!" }); // S&P 500
await pane_set_symbol({ pane_index: 1, symbol: "NQ1!" }); // Nasdaq
await pane_set_symbol({ pane_index: 2, symbol: "YM1!" }); // Dow
await pane_set_symbol({ pane_index: 3, symbol: "RTY1!" }); // Russell
// Stream all panes
// CLI: tv stream all | jq '{es: .panes[0].quote.close, nq: .panes[1].quote.close}'javascript
// 设置4面板网格布局,显示期货品种
await pane_set_layout({ layout: "2x2" });
await pane_set_symbol({ pane_index: 0, symbol: "ES1!" }); // 标普500
await pane_set_symbol({ pane_index: 1, symbol: "NQ1!" }); // 纳斯达克
await pane_set_symbol({ pane_index: 2, symbol: "YM1!" }); // 道琼斯
await pane_set_symbol({ pane_index: 3, symbol: "RTY1!" }); // 罗素2000
// 监控所有面板数据流
// CLI命令:tv stream all | jq '{es: .panes[0].quote.close, nq: .panes[1].quote.close}'Automated Level Detection
自动价位检测
javascript
// Read Pine Script levels from custom indicator
const lines = await data_get_pine_lines({
study_filter: "Supply Demand Zones"
});
// Create alerts at each level
for (const line of lines) {
await alert_create({
symbol: state.symbol,
condition: "crossing",
price: line.y,
message: `Price crossed ${line.text} at ${line.y}`
});
}javascript
// 读取自定义指标中的Pine绘制价位
const lines = await data_get_pine_lines({
study_filter: "Supply Demand Zones"
});
// 为每个价位创建警报
for (const line of lines) {
await alert_create({
symbol: state.symbol,
condition: "crossing",
price: line.y,
message: `价格突破${line.text},价位:${line.y}`
});
}Replay Practice Session
复盘练习会话
javascript
// 1. Start replay at month start
await replay_start({ date: "2025-05-01" });
// 2. Step forward until setup appears
await replay_step({ direction: "forward", bars: 10 });
// 3. Simulate entry
const quote = await quote_get();
await replay_trade({
action: "long",
price: quote.close,
quantity: 1,
stop_loss: quote.close * 0.98,
take_profit: quote.close * 1.02
});
// 4. Continue stepping to see outcome
await replay_step({ direction: "forward", bars: 20 });javascript
// 1. 从月初开始复盘
await replay_start({ date: "2025-05-01" });
// 2. 向前步进直到出现交易信号
await replay_step({ direction: "forward", bars: 10 });
// 3. 模拟入场
const quote = await quote_get();
await replay_trade({
action: "long",
price: quote.close,
quantity: 1,
stop_loss: quote.close * 0.98,
take_profit: quote.close * 1.02
});
// 4. 继续步进查看交易结果
await replay_step({ direction: "forward", bars: 20 });Troubleshooting
故障排除
Connection Issues
连接问题
bash
undefinedbash
undefinedCheck if TradingView is running with debug port
检查TradingView是否以调试端口运行
tv status
tv status
If failed, launch manually
如果连接失败,手动启动
./scripts/launch_tv_debug_mac.sh # or .bat / _linux.sh
./scripts/launch_tv_debug_mac.sh # 或对应系统的.bat / _linux.sh脚本
Verify port 9222 is open
验证9222端口是否开放
lsof -i :9222 # macOS/Linux
netstat -ano | findstr :9222 # Windows
undefinedlsof -i :9222 # macOS/Linux
netstat -ano | findstr :9222 # Windows
undefinedMCP Tools Not Appearing in Claude
MCP工具未在Claude中显示
- Check has absolute path
~/.claude/.mcp.json - Restart Claude Code completely
- Check Claude Code logs: Help → Show Logs
- Verify Node.js version: (must be 18+)
node --version
- 检查中的路径是否为绝对路径
~/.claude/.mcp.json - 完全重启Claude Code
- 查看Claude Code日志:帮助 → 显示日志
- 验证Node.js版本:(必须为18+)
node --version
Pine Script Compilation Fails
Pine Script编译失败
javascript
// Always check errors first
const result = await pine_smart_compile();
if (!result.success) {
const errors = await pine_get_errors();
console.log(errors);
}
// Common issues:
// - Wrong version (use //@version=5)
// - Undeclared identifiers (check variable names)
// - Invalid function calls (check Pine Script docs)javascript
// 务必先检查错误
const result = await pine_smart_compile();
if (!result.success) {
const errors = await pine_get_errors();
console.log(errors);
}
// 常见问题:
// - 版本错误(需使用//@version=5)
// - 未声明的标识符(检查变量名)
// - 无效函数调用(查阅Pine Script文档)Indicator Values Empty
指标数值为空
javascript
// Make sure indicator is visible and loaded
const state = await chart_get_state();
console.log(state.indicators); // check IDs
// Try toggling visibility
await indicator_toggle_visibility({
indicator_id: "abc123",
visible: true
});
// Wait for chart to update, then read values
await new Promise(r => setTimeout(r, 1000));
const values = await data_get_study_values();javascript
// 确保指标已显示并加载完成
const state = await chart_get_state();
console.log(state.indicators); // 检查指标ID
// 尝试切换指标可见性
await indicator_toggle_visibility({
indicator_id: "abc123",
visible: true
});
// 等待图表更新后再读取数值
await new Promise(r => setTimeout(r, 1000));
const values = await data_get_study_values();Pine Data Returns Empty
Pine数据返回为空
javascript
// Check if Pine Script is actually drawing
const state = await chart_get_state();
// Look for your indicator in state.indicators
// Use exact study_filter match (case-sensitive)
const lines = await data_get_pine_lines({
study_filter: "Session Levels" // exact name from state
});
// If still empty, the Pine Script may not be drawing anything
// Check Pine console: tv pine consolejavascript
// 检查Pine Script是否确实在绘图
const state = await chart_get_state();
// 在state.indicators中查找你的指标
// 使用精确的study_filter匹配(区分大小写)
const lines = await data_get_pine_lines({
study_filter: "Session Levels" // 使用state中的精确名称
});
// 如果仍为空,可能Pine Script未绘制内容
// 检查Pine控制台:tv pine consoleStreaming Stops
数据流中断
bash
undefinedbash
// 数据流通过本地CDP连接轮询
// 如果TradingView崩溃或调试端口关闭,重新启动:
./scripts/launch_tv_debug_mac.sh
tv stream quote # 重启数据流Streams poll local CDP connection
Token消耗过高
If TradingView crashes or debug port closes, restart:
—
./scripts/launch_tv_debug_mac.sh
tv stream quote # restart stream
undefinedjavascript
// 务必先使用summary: true获取OHLCV数据
const bars = await data_get_ohlcv({ summary: true }); // 仅500字节
// 避免使用:data_get_ohlcv({ bars: 100 }) // 约8KB
// 使用study_filter定位特定指标
const lines = await data_get_pine_lines({
study_filter: "Levels" // 将结果从50+条减少到5-10条
});
// 除非必要,避免使用pine_get_source(可能超过200KB)
// 使用pine_analyze_code获取代码结构High Token Usage
环境变量
javascript
// ALWAYS use summary: true for OHLCV first
const bars = await data_get_ohlcv({ summary: true }); // 500B
// NOT: data_get_ohlcv({ bars: 100 }) // 8KB
// Use study_filter to target specific indicators
const lines = await data_get_pine_lines({
study_filter: "Levels" // reduces from 50+ lines to 5-10
});
// Avoid pine_get_source unless necessary (can be 200KB+)
// Use pine_analyze_code for structure instead无需额外配置——所有通信均通过本地9222端口的CDP完成。
可选CLI自定义配置:
bash
export TV_CDP_PORT=9222 # 默认端口
export TV_TIMEOUT=30000 # CDP超时时间(毫秒)Environment Variables
安全注意事项
None required — all communication is local via CDP on port 9222.
Optional CLI customization:
bash
export TV_CDP_PORT=9222 # default
export TV_TIMEOUT=30000 # CDP timeout in ms- 无外部连接 — 仅与本地CDP(9222端口)通信
- 无数据存储 — 所有数据仅保存在本地设备
- 无TradingView服务器访问 — 需要有效的订阅权限
- 调试端口仅本地可见 — 不暴露至网络
- 请查阅TradingView服务条款,确保符合程序化访问规范
Security Considerations
参考资料
- No external connections — only localhost CDP (port 9222)
- No data storage — all data stays on your machine
- No TradingView server access — requires valid subscription
- Debug port is local-only — not exposed to network
- Review TradingView Terms of Use for programmatic access compliance
References
—