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

如何在日线图上绘制指定时段的实时相对成交量?

时段累计相对成交量指标实现思路

我原本用以下Pine Script绘制相对成交量:

//@version=5
indicator('rVol')

length = input.int(30, 'Avg Length')
avg = ta.sma(volume, length)
rVol = volume / avg
plot(rVol, style=plot.style_columns)

现在想要在日线时间框架上实时查看该指标,需要完成以下目标:

  1. 设置常规交易时段的时间范围(示例:0930-1600)
  2. 计算从选定时段起始到当前时刻的累计成交量(cVol)
  3. 计算过去x天内该精确时段累计成交量的移动平均线,最终得到相对成交量:rVol = cVol / ta.sma(cVol, length)

核心实现步骤

  • 1. 时段判断与当日累计成交量计算
    使用ta.session函数判断当前K线是否处于设定的交易时段内,在日线图上逐根K线累加时段内的成交量:

    time_range = input.session('0930-1600', '交易时段')
    in_session = ta.session(time_range)
    
    // 当日时段内累计成交量
    var float daily_cVol = 0.0
    if ta.newbar
        daily_cVol := 0.0  // 新交易日重置累计值
    if in_session
        daily_cVol += volume  // 时段内累加成交量
    
  • 2. 存储历史时段累计成交量
    要计算过去x天的时段累计成交量均线,需把每日的最终时段累计值保存到数组中:

    var float[] cVol_history = array.new_float()
    
    // 每日时段结束时保存当日累计成交量
    if ta.sessionclose(time_range)
        array.unshift(cVol_history, daily_cVol)
        // 限制数组长度,避免内存占用过大
        if array.size(cVol_history) > length
            array.pop(cVol_history)
    
  • 3. 计算相对成交量
    从数组提取历史数据计算移动平均线,得到实时相对成交量:

    // 计算历史时段累计成交量的SMA
    cVol_sma = ta.sma(array.get(cVol_history, 0), length)
    // 实时相对成交量(当日累计/历史均线)
    rVol = daily_cVol / cVol_sma
    
  • 4. 绘图与优化
    可设置仅在交易时段内绘制指标,过滤非时段内的无效数据:

    plot(in_session ? rVol : na, style=plot.style_columns, title="时段相对成交量")
    

关键注意点

  • 日线图上的实时数据依赖逐根K线更新,需确保daily_cVol在每个交易日开始时正确重置
  • 用var关键字声明数组、累计值等变量,避免脚本重新计算时重复初始化
  • 时段结束判断用ta.sessionclose,确保每日累计值被正确存入历史数组
  • 若涉及跨时区,可在ta.session中指定时区参数(如timezone=timezone.new("America/New_York"))

内容的提问来源于stack exchange,提问作者Richard D.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 20:27:32