如何在TradingView均线带内置指标中添加自定义时间周期选择与切换功能?
自定义TradingView均线带(Moving Average Ribbon)指标实现
完整Pine Script代码
//@version=5 indicator("自定义均线带", overlay=true, shorttitle="MA Ribbon Custom") // --- 全局/单独周期切换开关 --- useGlobalTimeframe = input.bool(true, title="使用全局图表周期", tooltip="勾选后所有均线使用当前图表周期,取消则每条均线可单独设置周期") // --- 均线配置:周期、颜色、显示控制(后续可直接添加第5条) --- // 10D 均线 ma10D_period = input.int(10, title="10D 周期", group="日线均线") ma10D_color = input.color(color.new(color.blue, 0), title="10D 颜色", group="日线均线") // 21D 均线 ma21D_period = input.int(21, title="21D 周期", group="日线均线") ma21D_color = input.color(color.new(color.red, 0), title="21D 颜色", group="日线均线") // 10W 均线 ma10W_period = input.int(10, title="10W 周期", group="周线均线") ma10W_color = input.color(color.new(color.green, 0), title="10W 颜色", group="周线均线") // 20W 均线 ma20W_period = input.int(20, title="20W 周期", group="周线均线") ma20W_color = input.color(color.new(color.orange, 0), title="20W 颜色", group="周线均线") // 40W 均线 ma40W_period = input.int(40, title="40W 周期", group="周线均线") ma40W_color = input.color(color.new(color.purple, 0), title="40W 颜色", group="周线均线") // --- 周期自适应显示逻辑 --- currentTF = timeframe.period // 定义各均线的显示状态 show10D = currentTF == "D" show21D = currentTF == "D" show10W = true // 所有周期都显示周线均线 show20W = true show40W = true // --- 计算并绘制均线 --- // 辅助函数:根据模式获取均线周期 getMaPeriod(globalPeriod, customPeriod) => useGlobalTimeframe ? globalPeriod : customPeriod // 10D 均线 if show10D ma10D = ta.sma(close, getMaPeriod(10, ma10D_period)) plot(ma10D, color=ma10D_color, title="10D MA", linewidth=2) // 21D 均线 if show21D ma21D = ta.sma(close, getMaPeriod(21, ma21D_period)) plot(ma21D, color=ma21D_color, title="21D MA", linewidth=2) // 10W 均线 if show10W ma10W = ta.sma(close, getMaPeriod(10, ma10W_period)) plot(ma10W, color=ma10W_color, title="10W MA", linewidth=2) // 20W 均线 if show20W ma20W = ta.sma(close, getMaPeriod(20, ma20W_period)) plot(ma20W, color=ma20W_color, title="20W MA", linewidth=2) // 40W 均线 if show40W ma40W = ta.sma(close, getMaPeriod(40, ma40W_period)) plot(ma40W, color=ma40W_color, title="40W MA", linewidth=2) // --- 扩展提示:添加第5条均线 --- // 复制以下格式修改参数即可 // maX_period = input.int(X, title="X[周期] 周期", group="自定义均线") // maX_color = input.color(color.new(color.XXX, 0), title="X[周期] 颜色", group="自定义均线") // showX = [设置显示条件] // if showX // maX = ta.sma(close, getMaPeriod(X, maX_period)) // plot(maX, color=maX_color, title="X[周期] MA", linewidth=2)
功能说明
- 全局/单独周期切换:通过顶部的
使用全局图表周期复选框控制,勾选时所有均线使用预设的对应周期参数;取消勾选后,每条均线的周期都可通过对应分组下的输入框单独修改。 - 周期自适应显示:
- 图表切换到**周线(W)**周期时,仅显示10W、20W、40W三条周线均线
- 图表切换到**日线(D)**周期时,自动添加显示10D、21D两条日线均线,同时保留周线均线的显示
- 可扩展性:代码末尾预留了第5条均线的添加模板,直接复制模板修改周期、颜色和显示条件即可快速新增均线。
内容的提问来源于stack exchange,提问作者Ishan Choubey
相关产品推荐
相关产品推荐

