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

如何实现支持自定义时间框架的K线时间范围验证(优于timestamp)

TradingView 通用时间范围验证方案

问题

需要验证当前K线是否处于指定时间范围(D、W、M、3M、12M、12h、2D等),原静态判断代码无法适配自定义时间框架,用security()时因序列值问题始终返回true,求通用实现方法。

原静态代码:

bool dMonth = year(timenow) == year(time) and month(timenow) == month(time)

通用实现方案

核心是通过时间周期的秒数计算动态判断当前K线是否处于目标时间框架的最新周期,无需硬编码时间单位,同时避开security()的序列问题。

通用验证函数

//@version=5
indicator("通用时间范围验证", overlay=true)

// 获取时间框架对应的秒数,可自行扩展自定义框架
int getTfSeconds(string tf) =>
    switch tf
        "D" => 86400
        "W" => 604800
        "M" => 2592000
        "3M" => 7776000
        "12M" => 31104000
        "12h" => 43200
        "2D" => 172800
        => 0 // 未知框架返回0

// 验证当前K线是否在目标时间框架的最新周期内
bool isInTargetTf(string targetTf) =>
    tfSec = getTfSeconds(targetTf)
    if tfSec == 0
        false
    // 计算当前周期起始时间戳:当前时间减去周期内偏移量,得到周期起点
    currentPeriodStart = timenow - (timenow % tfSec)
    // 判断当前K线时间是否落在该周期内
    time >= currentPeriodStart

使用示例

// 调用函数验证不同时间框架
isInDay = isInTargetTf("D")
isIn3Month = isInTargetTf("3M")
isIn12h = isInTargetTf("12h")

// 在图表上可视化验证结果
plotshape(isInDay, title="当日周期", location=location.belowbar, color=color.green, style=shape.labelup, text="当日")
plotshape(isIn3Month, title="3月周期", location=location.belowbar, color=color.red, style=shape.labelup, text="3月")
plotshape(isIn12h, title="12h周期", location=location.belowbar, color=color.blue, style=shape.labelup, text="12h")

关键说明

  • 动态周期计算:通过timenow % tfSec获取当前时间在目标周期内的偏移量,减去偏移量得到周期起始点,无需硬编码年/月/日判断逻辑
  • 避开序列问题:直接基于当前时间戳计算,不需要跨周期调用security(),避免序列值导致的判断失效
  • 可扩展性:添加自定义时间框架只需在getTfSeconds的switch分支新增对应项,比如新增"4h"框架就返回14400(4*3600秒)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 21:30:05