Pine Script如何按指定日期获取K线高低值实现斐波那契分析
Pine Script 指定日期K线定位及高低价获取方法
核心原理
Pine Script 内置time变量存储每根K线开盘时间的毫秒级Unix时间戳,只需将用户输入的目标日期转换为同格式时间戳,匹配对应K线即可读取其高低价数值。
可直接运行的实现代码
//@version=5 indicator("指定日期K线高低价获取", overlay=true) // 1. 提供用户日期输入入口 start_date = input.time(title="起始日期", defval=timestamp("2024-01-01")) end_date = input.time(title="结束日期", defval=timestamp("2024-02-01")) // 2. 定义变量存储目标K线的高低价 var float start_high = na var float start_low = na var float end_high = na var float end_low = na // 3. 匹配K线并赋值 if time == start_date start_high := high start_low := low if time == end_date end_high := high end_low := low // 可选:在对应K线上标记高低价验证效果 plotshape(start_high, title="起始日最高价", location=location.belowbar, color=color.green, style=shape.labelup, text="起高") plotshape(start_low, title="起始日最低价", location=location.abovebar, color=color.red, style=shape.labeldown, text="起低") plotshape(end_high, title="结束日最高价", location=location.belowbar, color=color.green, style=shape.labelup, text="终高") plotshape(end_low, title="结束日最低价", location=location.abovebar, color=color.red, style=shape.labeldown, text="终低")
封装为斐波那契分析函数的扩展思路
拿到两个日期的高低价后,可直接基于数值计算斐波那契各档位水平:
- 若用于上涨回调分析,取起始日低点、结束日高点作为斐波那契的0%和100%档位
- 若用于下跌反弹分析,取起始日高点、结束日低点作为斐波那契的0%和100%档位
- 直接调用
line.new()、label.new()函数绘制各档位线及标注即可
注意事项
- 日期输入的时区需要和图表设置的时区保持一致,否则会出现匹配不到K线的问题
- 如果是日内分钟/秒级图表,输入日期时可精确到时分秒,比如
timestamp("2024-01-01 09:30:00") - 如果目标日期属于非交易日,匹配结果会返回空值,可额外加判断逻辑顺延到最近的交易日
内容的提问来源于stack exchange,提问作者Pswiss87
相关产品推荐
相关产品推荐

