You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pine Script需求:指定日期显示ON/OFF及Filter+VWAP绘制问题

解决TradingView Pine Script报错及功能实现问题

报错原因分析

原代码的核心问题有以下几点:

  1. plot()函数位置错误:Pine Script要求plot()必须在全局作用域声明,不能放在if条件块内执行
  2. 时间语法错误:time(9,20)不符合Pine Script v5的时间格式规范,正确写法应为time(timeframe.period, "HHmm")
  3. 逻辑判断错误:bar_index < bar_index[-1]永远不成立,当前K线的bar_index必然大于前一根K线
  4. VWAP获取方式错误:直接请求日周期VWAP无法获取当日9:20的特定时点值,需要用更低时间框架抓取

重构后代码(满足所有需求)

//@version=5
indicator('Intraburst', overlay=true)

// 计算Intraburst核心指标
truemove = math.abs(open[1] - close)
twoDayTrueHigh = math.max(high[1], high, close[2])
twoDayTrueLow = math.min(low[1], low, close[2])
twoDayTrueRange = twoDayTrueHigh - twoDayTrueLow
intraburstLevel = truemove / twoDayTrueRange * 100
filter = twoDayTrueRange * 0.3

// --- 需求1:仅指定日期显示ON/OFF标记 ---
// 判断是否为收盘K线(EOD)
is_eod = ta.islastbar

// 获取当前周几(1=周一,3=周三,4=周四)
current_dow = dayofweek

// 检查周三/周四是否为节假日:通过判断次日是否有K线
is_wed_holiday = not request.security(syminfo.tickerid, timeframe.period, bar_index[1] == bar_index - 1) when current_dow == dayofweek.wednesday
is_thu_holiday = not request.security(syminfo.tickerid, timeframe.period, bar_index[1] == bar_index - 1) when current_dow == dayofweek.thursday

// 确定显示标记的日期:周三收盘,若周三/周四节假日则周二收盘
show_mark = is_eod and (
    (current_dow == dayofweek.wednesday and not is_wed_holiday) or
    (current_dow == dayofweek.tuesday and (is_wed_holiday or is_thu_holiday))
)

// 绘制ON/OFF标记(仅在指定日期显示)
plotshape(show_mark and intraburstLevel > 30, text='OFF', style=shape.circle, location=location.abovebar, color=color.red, size=size.normal)
plotshape(show_mark and intraburstLevel <= 30, text='ON', style=shape.circle, location=location.abovebar, color=color.green, size=size.normal)

// --- 需求2:ON状态次日绘制Filter+VWAP线 ---
// 记录前一个指定日期的Intraburst状态(ON/OFF)
var bool intraburst_on = false
if show_mark
    intraburst_on := intraburstLevel <= 30

// 获取当日9:20的VWAP值(用1分钟时间框架抓取)
vwap_920 = request.security(syminfo.tickerid, "1", vwap, gaps=barmerge.gaps_on) when time(timeframe.period, "0920")
var float daily_vwap_920 = na
if time(timeframe.period, "0920")
    daily_vwap_920 := vwap_920

// 绘制Filter+VWAP线(仅当日intraburst处于ON状态时显示)
plot(intraburst_on ? daily_vwap_920 + filter : na, color=color.green, linetype=linetype.solid, title="Filter + VWAP")

// 绘制Filter标签
label.new(bar_index, close + 0.8 * filter, str.tostring(filter, '##.00'), color=color.black, textcolor=color.white)

关键功能说明

  1. 日期判断逻辑:
    • 通过dayofweek识别周几,ta.islastbar判断收盘K线
    • 利用request.security检查次日是否存在K线,判断是否为节假日,从而调整标记显示日期
  2. VWAP获取逻辑:
    • 用1分钟时间框架请求当日9:20时点的VWAP值,存储为全局变量供当日全周期使用
  3. 线条绘制逻辑:
    • 全局声明plot()函数,通过intraburst_on变量控制线条显示,避免原代码的作用域错误

内容的提问来源于stack exchange,提问作者Avi Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:55:28