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

如何在Pine Script指标中每日首次触发涨幅条件时绘制背景?

解决方案:实现每日首次触发背景色变更

要实现仅每日首次达到设定价格变化水平时触发背景色变更,核心是跟踪当日是否已触发信号,并在每日指定时间点重置状态。以下是修改后的完整代码及关键说明:

关键修改点

  • 新增var bool has_triggered_today = false:用持久化变量记录当日是否已触发过背景色信号,var关键字确保变量不会在每根K线重新初始化。
  • 每日指定时间点重置标记:在用户设定的时间点将has_triggered_today重置为false,确保次日可以重新触发。
  • 触发条件优化:只有当价格变化上穿阈值且当日未触发过信号时,才显示背景色,同时标记当日已触发避免重复生效。

修改后的完整代码

//@version=5
indicator(title = 'Price Change (%) From a Specific Time of the Day', shorttitle = 'PC (%)', overlay = false)

input_hour = input.int(title = 'Hour', minval = 0, maxval = 23, defval = 23, tooltip = 'Selected time is in the timezone of the exchange.')
input_minute = input.int(title = 'Minute', minval = 0, maxval = 59, defval = 0)
input_percentage = input.int(title = 'Price Change (%) Signal Level', minval = 0, maxval = 1000, defval = 5)

var initial_time = 0.0
// 新增:跟踪当日是否已触发信号的持久化变量
var bool has_triggered_today = false

// 每日指定时间点重置初始价格和触发标记
if hour == input_hour and minute == input_minute
    initial_time := close
    has_triggered_today := false  // 重置当日触发状态

price_change_percentage = math.round((close - initial_time) / initial_time * 100 * 100) / 100
price_change_percentage_crossover = ta.crossover(price_change_percentage, input_percentage)

// 仅在首次触发时更新标记并显示背景色
trigger_condition = price_change_percentage_crossover and not has_triggered_today
if trigger_condition
    has_triggered_today := true

price_change_line_color = price_change_percentage > 0 ? color.new(#089981, 0) : price_change_percentage < 0 ? color.new(#f23645, 0) : na
plot(price_change_percentage, title = 'Price Change (%) Color', color = price_change_line_color, linewidth = 1)
hline(price = 0, title = 'Zero Line', color = color.new(color.white, 70))
bgcolor(hour == input_hour and minute == input_minute ? color.new(color.white, 80) : na, title = "Selected Time Background")
// 使用新的触发条件控制背景色
bgcolor(trigger_condition ? color.new(color.green, 50) : na, title = "Price Change Cross Background")

代码说明

  • 到达用户设定的每日时间点时,同步重置初始价格和触发状态标记,保证每日的信号判断独立。
  • trigger_condition组合了上穿信号和未触发标记,确保只有每日第一次满足价格变化阈值时才触发背景色。
  • 触发后has_triggered_today变为true,当日内后续的上穿动作不会再重复触发背景色变更。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:55:39