You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:编写循环统计均线交叉后连续红绿蜡烛块数量

均线交叉后蜡烛块统计实现方案

以下是基于Pine Script的实现代码,满足你统计均线交叉后红绿蜡烛块数量并标注的需求:

//@version=5
indicator("CrossMA后蜡烛块统计", overlay=true)

// 定义均线交叉条件(示例用50和200均线金叉,可自行修改)
maFast = ta.sma(close, 50)
maSlow = ta.sma(close, 200)
crossma = ta.crossover(maFast, maSlow)

// 定义蜡烛颜色:红蜡烛=close<open,绿蜡烛=close>open
redCnd = close < open
greenCnd = close > open

// 初始化变量:记录当前蜡烛块颜色、计数,以及存储块信息的数组
var int[] blockCounts = array.new_int()
var bool[] blockColors = array.new_bool() // true=绿,false=红
var int blockStart = na
var currentColor = na
var currentCount = 0

// 当出现均线交叉时,重置统计状态
if crossma
    array.clear(blockCounts)
    array.clear(blockColors)
    blockStart = bar_index
    currentColor = na
    currentCount = 0

// 仅在均线交叉后开始统计
if not na(blockStart)
    // 判断当前蜡烛颜色
    currGreen = greenCnd
    // 首次统计或当前蜡烛颜色与上一个块不同时,记录上一个块并重置计数
    if na(currentColor) or currGreen != currentColor
        if not na(currentColor)
            array.push(blockCounts, currentCount)
            array.push(blockColors, currentColor)
        currentColor = currGreen
        currentCount = 1
    else
        currentCount += 1
    // 最后一根K线时,把当前块加入数组
    if barstate.islast
        array.push(blockCounts, currentCount)
        array.push(blockColors, currentColor)

// 标注每个蜡烛块的数量
for i = 0 to array.size(blockCounts) - 1
    count = array.get(blockCounts, i)
    isGreen = array.get(blockColors, i)
    // 计算块的结束位置:从交叉后的第1根K线开始累加
    endBar = blockStart + array.sum(blockCounts, 0, i)
    // 标注在块的最后一根蜡烛上方
    label.new(endBar, high + ta.atr(10)*0.2, str.tostring(count), 
              color=isGreen ? color.green : color.red, 
              textcolor=color.white, style=label.style_label_down)

关键逻辑说明

  • 均线交叉触发:示例用50和200均线金叉,可直接替换成你自定义的crossma条件
  • 蜡烛块判定:连续同色蜡烛为一个块,颜色切换时完成上一个块的统计
  • 数组存储块信息:用两个数组分别记录每个块的数量和颜色,方便后续遍历标注
  • 循环标注:遍历数组计算每个块的结束位置,将数量标注在对应蜡烛块的上方

内容的提问来源于stack exchange,提问作者Shiva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 14:48:23