如何在两次均线交叉间的中点生成买入信号?
两次均线交叉间的买入信号
我有两段Pine Script脚本:
- 一段是基于EMA(8)、EMA(20)和SMA(20)的交叉买卖策略脚本
- 另一段是K线计数脚本
我需要把这两段脚本整合,实现以下功能:
- 从第一次均线交叉发生的K线开始计数
- 在两次相邻交叉的K线中点位置,显示多头买入信号
整合后的Pine Script(v5)代码
//@version=5 indicator(title="均线交叉中点买入信号", overlay=true, max_labels_count=500) // 1. 定义均线参数 src = input(close, title="价格源") ema_len1 = input.int(8, title="EMA1周期") ema_len2 = input.int(20, title="EMA2周期") sma_len3 = input.int(20, title="SMA周期") // 计算均线 ema1 = ta.ema(src, ema_len1) ema2 = ta.ema(src, ema_len2) sma3 = ta.sma(src, sma_len3) // 2. 识别有效交叉信号(金叉/死叉) // 定义交叉:EMA8上穿EMA20或SMA20视为多头交叉;EMA8下穿EMA20或SMA20视为空头交叉 long_cross = ta.crossover(ema1, ema2) or ta.crossover(ema1, sma3) short_cross = ta.crossunder(ema1, ema2) or ta.crossunder(ema1, sma3) // 3. 记录交叉位置与计数 var int cross_bar_index = na var int bars_since_cross = 0 var int total_between_cross = 0 // 当新交叉发生时,记录当前K线位置,计算上一次交叉到本次的总K线数 if long_cross or short_cross if not na(cross_bar_index) total_between_cross := bar_index - cross_bar_index cross_bar_index := bar_index bars_since_cross := 0 else bars_since_cross := na(cross_bar_index) ? 0 : bars_since_cross + 1 // 4. 计算中点并显示买入信号 mid_point = total_between_cross / 2 // 当K线计数达到中点时,显示买入标记(奇数K线数时取前后两个位置) buy_signal = bars_since_cross == math.floor(mid_point) or bars_since_cross == math.ceil(mid_point) // 绘制均线 plot(ema1, title="EMA8", color=color.new(color.red, 0), linewidth=1) plot(ema2, title="EMA20", color=color.new(color.green, 0), linewidth=1) plot(sma3, title="SMA20", color=color.new(color.black, 0), linewidth=1) // 绘制交叉标记与买入信号 plotshape(long_cross, title="多头交叉", location=location.belowbar, color=color.green, style=shape.labelup, text="多叉") plotshape(short_cross, title="空头交叉", location=location.abovebar, color=color.red, style=shape.labeldown, text="空叉") plotshape(buy_signal, title="中点买入信号", location=location.belowbar, color=color.blue, style=shape.triangleup, size=size.small) // 可选:显示从上次交叉开始的K线计数标签 label.new(bar_index, high, str.tostring(bars_since_cross), textcolor=color.blue, style=label.style_none)
代码说明
- 统一使用Pine Script v5版本,兼容最新TradingView环境
- 修正了原脚本中宽泛的交叉条件,仅识别EMA8上穿/下穿EMA20或SMA20的有效交叉
- 自动记录每次交叉的K线位置,计算两次交叉之间的总K线数
- 在交叉区间的中点位置(若总K线数为奇数,取前后两个K线)显示蓝色向上三角形的买入信号
- 保留了K线计数标签,可直观看到从上次交叉开始的K线数量
内容的提问来源于stack exchange,提问作者ls rok
相关产品推荐
相关产品推荐

