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

Pine Script:如何按指定时间框架计算成交量剖面及类型转换?

Pine Script:时间框架字符串转整数与日线成交量剖面实现

1. 时间框架字符串转整数的解决方案

timeframe.period返回字符串类型(如"D"代表日线、"H1"代表1小时线),但ta.highest()/ta.lowest()要求整数参数(回溯K线数量)。你可以通过条件映射实现转换,针对常用时间框架做对应:

// 自定义函数:将时间框架字符串转为对应K线数量
tfToBarCount() =>
    var int barCount = na
    if timeframe.period == "D"
        barCount := 1  // 日线图下,1根K线即为1日
    elif timeframe.period == "H1"
        barCount := 60 / timeframe.multiplier  // 分钟图下,1小时对应60根1分钟K线
    elif timeframe.period == "W"
        barCount := 5  // 默认一周5个交易日,可按需调整
    // 可扩展添加其他时间框架的映射
    barCount

如果你的图表本身是日线图,直接用1作为ta.highest()/ta.lowest()的参数即可;若在低时间框架(如分钟图)计算日线范围,用ta.barssince(time("D")) + 1能动态获取当日已生成的K线数,确保高低点覆盖当日所有K线。

2. 当日计算、次日停止的逻辑实现

要实现"日线周期内计算,次日停止"的需求,核心是判断当前K线是否属于当日周期:

// 判断当前是否处于当日(日线周期内)
isCurrentDay = ta.change(time("D")) == 0

// 仅在当日计算日线高低点范围
var float dailyRange = na
if isCurrentDay
    dailyHigh = ta.highest(high, ta.barssince(time("D")) + 1)
    dailyLow = ta.lowest(low, ta.barssince(time("D")) + 1)
    dailyRange := dailyHigh - dailyLow
else
    dailyRange := na  // 次日停止计算,清空数据

3. 简化版日线成交量剖面实现

结合上述逻辑,可实现当日范围内的成交量分布统计:

// 初始化存储价格区间与对应成交量的数组
var float[] priceLevels = array.new_float()
var int[] volumeCounts = array.new_int()

if isCurrentDay
    // 新交易日开始时清空上一日数据
    if ta.change(time("D"))
        array.clear(priceLevels)
        array.clear(volumeCounts)
    
    // 统计当前K线的价格与成交量
    currentPrice = close
    currentVolume = volume
    
    // 更新对应价格区间的成交量
    idx = array.indexof(priceLevels, currentPrice)
    if idx != -1
        array.set(volumeCounts, idx, array.get(volumeCounts, idx) + currentVolume)
    else
        array.push(priceLevels, currentPrice)
        array.push(volumeCounts, currentVolume)
else
    // 次日停止统计,清空数据
    array.clear(priceLevels)
    array.clear(volumeCounts)

关键说明:

  • 若在日线图上编写脚本,无需复杂转换,直接用ta.highest(high, 1)和ta.lowest(low, 1)即可获取当日高低点。
  • 低时间框架下,ta.barssince(time("D")) + 1会自动适配当日已生成的K线数量,避免固定数值带来的误差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:01:27