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

Pinescript需求:统计收盘价上方/下方的移动平均线数量

在Pine Script中统计收盘价上下的均线数量并生成表格

实现步骤

  1. 计算需要监控的各周期移动平均线
  2. 逐个判断均线与收盘价的位置关系,统计上方、下方的均线数量及对应明细
  3. 创建表格组件,将统计结果展示在图表上

完整代码示例

//@version=5
indicator("均线位置统计表格", overlay=false)

// 定义需要监控的均线周期
maPeriods = [10, 20, 50, 100, 200]
// 计算各周期均线值
maValues = array.new_float()
for period in maPeriods
    array.push(maValues, ta.sma(close, period))

// 初始化统计变量
var countAbove = 0
var countBelow = 0
var aboveMAs = array.new_string()
var belowMAs = array.new_string()

// 仅在最后一根K线更新统计数据
if barstate.islast
    array.clear(aboveMAs)
    array.clear(belowMAs)
    countAbove := 0
    countBelow := 0
    
    // 遍历所有均线,判断位置关系
    for i = 0 to array.size(maPeriods)-1
        maVal = array.get(maValues, i)
        maPeriod = array.get(maPeriods, i)
        maLabel = str.tostring(maPeriod) + " MA: " + str.tostring(maVal, "$#.##")
        
        if maVal > close
            array.push(aboveMAs, maLabel)
            countAbove += 1
        elif maVal < close
            array.push(belowMAs, maLabel)
            countBelow += 1

// 创建并更新统计表格
var table statsTable = table.new(position.top_right, 2, 4, title="均线位置统计", border_color=color.gray)
if barstate.islast
    // 设置表头样式
    table.cell(statsTable, 0, 0, "项目", text_color=color.white, bg_color=color.blue)
    table.cell(statsTable, 1, 0, "详情", text_color=color.white, bg_color=color.blue)
    
    // 填充收盘价信息
    table.cell(statsTable, 0, 1, "当前收盘价", text_color=color.black)
    table.cell(statsTable, 1, 1, str.tostring(close, "$#.##"), text_color=color.black)
    
    // 填充上方均线统计
    table.cell(statsTable, 0, 2, "上方均线数量", text_color=color.red)
    table.cell(statsTable, 1, 2, str.tostring(countAbove) + "条: " + str.join(", ", aboveMAs), text_color=color.red)
    
    // 填充下方均线统计
    table.cell(statsTable, 0, 3, "下方均线数量", text_color=color.green)
    table.cell(statsTable, 1, 3, str.tostring(countBelow) + "条: " + str.join(", ", belowMAs), text_color=color.green)

代码说明

  • 用数组存储均线周期和对应值,后续可直接修改maPeriods数组扩展更多周期
  • 仅在最后一根K线执行统计和表格更新,避免重复计算浪费资源
  • 通过循环遍历所有均线,自动收集符合条件的均线标签,无需手动逐个判断
  • 表格固定在图表右上角,用颜色区分上下均线信息,直观清晰

效果示例

当收盘价为50美元时,表格会显示:

当前收盘价: $50.00
上方均线数量: 2条: 100 MA: $55.00, 200 MA: $70.00
下方均线数量: 3条: 10 MA: $29.00, 20 MA: $40.00, 50 MA: $45.00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 03:23:33