为Pine Script百分比水平指标添加盘前盘后交易时段支持
支持盘前盘后时段的百分比水平指标修改版
我有一个日内指标,可基于用户选择的当日开盘价、最高价、最低价或收盘价绘制百分比水平。希望为该指标添加盘前盘后延长交易时段功能:例如当盘前当日最高价高于常规时段当日最高价时,使用盘前最高价计算百分比水平。本人非编程人员,附上现有Pine Script代码,寻求修改帮助。
修改后的完整代码
//@version=5 indicator(title="% Levels (含盘前盘后)", overlay=true) // 核心设置 calc = input.title("计算源选择", defval="开盘价", options=["开盘价","最高价", "最低价", "收盘价"]) use_extended = input.bool("启用盘前盘后时段数据", defval=true, group="盘前盘后设置") showlast = input.int("显示历史K线数量", defval=3, options=[1,2,3,4,5,10,15,20,30,50,100,200,300], group="绘图设置") extendLines = input.int("起始偏移量", defval=0, options=[0,1,3,5,10,15,20,30,50,100,200,300], group="绘图设置") // 获取常规时段和盘前盘后时段的日线数据 o_reg = request.security(syminfo.tickerid, "D", open) h_reg = request.security(syminfo.tickerid, "D", high) l_reg = request.security(syminfo.tickerid, "D", low) c_reg = request.security(syminfo.tickerid, "D", close) // 盘前盘后时段数据(仅当启用时获取) h_ext = request.security(syminfo.tickerid, "D", high, session_extended=true) l_ext = request.security(syminfo.tickerid, "D", low, session_extended=true) // 自动选择极值(常规/盘前盘后取最大/最小) h_final = use_extended ? math.max(h_reg, h_ext) : h_reg l_final = use_extended ? math.min(l_reg, l_ext) : l_reg o_final = o_reg // 开盘价默认用常规时段,如需修改可调整 c_final = c_reg // 收盘价默认用常规时段,如需修改可调整 // 选择计算用的基准值 calcm = switch calc "最高价" => h_final "最低价" => l_final "收盘价" => c_final "开盘价" => o_final // 计算百分比水平 pct10 = calcm * 1.10 pctm10 = calcm * 0.90 pct12_5 = calcm * 1.125 pctm12_5 = calcm * 0.875 pct15 = calcm * 1.15 pctm15 = calcm * 0.85 // 绘制水平线条 plot(pct10, title="10%", color=color.white, style=plot.style_line, show_last=showlast, offset=extendLines) plot(pct12_5, title="12.5%", color=color.white, style=plot.style_line, show_last=showlast, offset=extendLines) plot(pct15, title="15%", color=color.white, style=plot.style_line, show_last=showlast, offset=extendLines) plot(pctm10, title="-10%", color=color.red, style=plot.style_line, show_last=showlast, offset=extendLines) plot(pctm12_5, title="-12.5%", color=color.red, style=plot.style_line, show_last=showlast, offset=extendLines) plot(pctm15, title="-15%", color=color.red, style=plot.style_line, show_last=showlast, offset=extendLines)
关键修改说明
- 升级到Pine Script v5版本(更稳定,功能更完善)
- 新增盘前盘后数据开关:可自由选择是否启用盘前盘后时段的数据
- 自动取极值:启用盘前盘后时,最高价取常规时段+盘前盘后的最大值,最低价取两者的最小值,完全匹配需求
- 保留原所有功能:计算源选择、历史K线显示数量、线条偏移设置均与原代码一致
- 开盘价/收盘价默认沿用常规时段数据(如需改用盘前盘后数据,可修改代码中对应注释行)
内容的提问来源于stack exchange,提问作者sfsurftrades
相关产品推荐
相关产品推荐

