如何用PineScript绘制含实际数据与未来假设数据的K线图?
实现实际数据与假设数据结合的K线图
问题描述
我需要绘制一款K线图,要求t时刻及之前的K线使用实际数据绘制,未来日期的K线则用假设数据延续绘制。最初尝试的代码能定义假设数据,但无法将假设数据偏移至指定日期后展示:
plotcandle(100 , 100, 100, 100, title = 'Title', color = open < close ? color.green : color.red, wickcolor = color.black)
解决方案
后续找到一种可行方法,既能应用假设数据,又不会覆盖偏移日期后的原有K线,完整Pine Script代码如下:
//@version=5 indicator("带假设数据的K线图", overlay=true) // 定义切换实际/假设数据的截止日期 cutoff_date = timestamp("2024-09-12 00:00") // 替换为你需要的截止日期 // 获取当前K线时间 current_time = time // 实际数据:截止日期前使用内置OHLC,之后设为na(不显示) actualOpen = current_time <= cutoff_date ? open : na actualHigh = current_time <= cutoff_date ? high : na actualLow = current_time <= cutoff_date ? low : na actualClose = current_time <= cutoff_date ? close : na // 假设数据:仅在截止日期后显示,可自定义OHLC数值 last_actual_close = ta.valuewhen(current_time <= cutoff_date, close, 0) // 获取最后一根实际K线的收盘价 hypOpen = current_time > cutoff_date ? 150 : na hypHigh = current_time > cutoff_date ? 150 : na hypLow = current_time > cutoff_date ? 150 : na hypClose = current_time > cutoff_date ? 150 : na // 绘制实际数据K线 plotcandle(open = actualOpen, high = actualHigh, low = actualLow, close = actualClose, title = "实际数据", color = actualOpen < actualClose ? color.green : color.red, wickcolor = color.black) // 绘制假设数据K线 plotcandle(open = hypOpen, high = hypHigh, low = hypLow, close = hypClose, title = "假设数据", color = hypOpen < hypClose ? color.blue : color.orange, wickcolor = color.gray)
关键逻辑说明
- 时间区间划分:通过
cutoff_date设定切换节点,用current_time判断当前K线属于实际数据区间还是假设数据区间 - 数据隔离:实际数据在截止日期后赋值为
na,假设数据在截止日期前赋值为na,确保两类数据不会重叠覆盖 - 灵活自定义假设数据:示例中假设数据的OHLC统一设为150,你也可以基于
last_actual_close生成更连贯的延续数据,比如hypOpen = current_time > cutoff_date ? last_actual_close : na
内容的提问来源于stack exchange,提问作者Furqan Hashim
相关产品推荐
相关产品推荐

