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

PineScript编写:为外汇与加密货币绘制前日高低收盘价

修复跨品种时段线绘制时间偏差问题

问题的核心是脚本的时段触发逻辑没有和品种对应的美东起始时间绑定,导致USDCAD的线绘制时机错误。以下是针对性的修改方案:


关键修改点

  1. 绑定品种专属的时段起始时间
    为BTC(美东19:00)和USDCAD(美东17:00)分别定义时段起始小时,支持自动识别或手动配置。

  2. 统一使用美东时间(EST/EDT)判断时段
    避免用UTC或交易所本地时间计算,确保时段判断和用户预期一致,同时自动处理夏令时切换。

  3. 修正历史时段数据的获取逻辑
    使用request.security的session参数指定自定义24小时时段,确保获取的是前一个完整交易时段的高、低、收盘价,而非自然日数据。

  4. 精准触发线的绘制时机
    准确识别每个新时段的第一根K线,及时更新线的起点,避免延迟绘制。


修改后的完整代码

//@version=5
indicator("Session High/Low/Close Lines", overlay=true)

// 1. 定义品种对应的美东时段起始小时
btc_session_start = 19  // BTC:美东晚7点
usdcad_session_start = 17  // USDCAD:美东晚5点

// 自动识别品种并匹配时段,也可改用input.int手动调整
session_start_hour = syminfo.ticker == "BTCUSD" ? btc_session_start : usdcad_session_start

// 2. 转换当前K线时间为美东时间(自动处理夏令时)
est_time = time(timeframe.period, "EST5EDT")
est_hour = hour(est_time)
est_minute = minute(est_time)
est_day = dayofmonth(est_time)

// 3. 判断是否进入新的交易时段
is_new_session = ta.change(est_hour == session_start_hour and est_minute == 0) or 
                 (ta.change(est_day) and est_hour == session_start_hour)

// 4. 获取前一个完整时段的高、低、收盘价
// 自定义时段格式:"起始小时:00-起始小时:00[时区]",代表连续24小时
custom_session = str.tostring(session_start_hour) + ":00-" + str.tostring(session_start_hour) + ":00[EST5EDT]"
[prev_high, prev_low, prev_close] = request.security(
    syminfo.tickerid, 
    "1440",  // 24小时周期(1440分钟)
    [ta.highest(high), ta.lowest(low), close], 
    session=custom_session, 
    gaps=barmerge.gaps_on, 
    lookahead=barmerge.lookahead_off
)

// 5. 绘制并更新时段线
var float line_high = na
var float line_low = na
var float line_close = na

if is_new_session
    // 删除旧线避免混乱
    line.delete(line_high)
    line.delete(line_low)
    line.delete(line_close)
    // 从新时段第一根K线开始绘制
    line_high = line.new(bar_index, prev_high, bar_index, prev_high, color=color.new(color.green, 0), width=2)
    line_low = line.new(bar_index, prev_low, bar_index, prev_low, color=color.new(color.red, 0), width=2)
    line_close = line.new(bar_index, prev_close, bar_index, prev_close, color=color.new(color.blue, 0), width=1, style=line.style_dashed)
else
    // 实时延伸线到当前K线
    line.set_x2(line_high, bar_index)
    line.set_x2(line_low, bar_index)
    line.set_x2(line_close, bar_index)

代码说明

  • 自动品种识别:通过syminfo.ticker判断当前品种,自动切换时段起始时间,无需手动调整。
  • 时区准确性:使用"EST5EDT"时区字符串,脚本会自动处理夏令时(EDT)和冬令时(EST)的时间偏移。
  • 自定义时段数据:request.security的session参数确保获取的是从指定时间开始的24小时周期数据,而非自然日的00:00-24:00数据。
  • 无延迟绘制:is_new_session的判断逻辑会在时段起始的第一根K线触发绘制,解决USDCAD的7小时延迟问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:46:06