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

如何将Trend Magic Pine Script指标转换为策略并生成警报

将Trend Magic指标转换为Pine Script策略并设置警报的方法

核心修改步骤

  1. 替换指标声明为策略声明
    把原代码开头的study()替换成strategy(),并添加必要的策略参数(比如初始资金、佣金模式等),保持overlay=true让策略和K线叠加显示。

  2. 保留原指标的信号计算逻辑
    原指标里的CCI计算、buffer上下轨、趋势判断逻辑完全保留,这些是生成交易信号的核心。

  3. 添加开平仓交易逻辑
    利用原指标生成的bullTrendMagic(多头信号)和bearTrendMagic(空头信号),调用Pine Script的策略函数实现自动开平仓:

  • 多头信号触发时,平掉现有空头仓位(如果有),开多单
  • 空头信号触发时,平掉现有多头仓位(如果有),开空单
  1. 启用警报功能
    策略生成的交易信号天然支持TradingView的警报功能,无需额外代码,只要在界面上配置即可。

转换后的完整策略代码

//@version=5
strategy("Trend Magic Strategy", shorttitle="TM Strategy", overlay=true, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1, default_qty_type=strategy.cash, default_qty_value=1000)

CCI = 20  
ATR = 5 
Multiplier=1 
original=true 
upSign = '↑' // 指示上升趋势
downSign = '↓' // 指示下降趋势
colorBuy= #2DFF03 // 多头信号颜色
colorSell = #733629 // 空头信号颜色

thisCCI = ta.cci(close, CCI)
lastCCI = ta.nz(thisCCI[1])
bufferDn= high + Multiplier * ta.sma(ta.tr,ATR)
bufferUp= low - Multiplier * ta.sma(ta.tr,ATR)

if (thisCCI >= 0 and lastCCI < 0) 
    bufferUp := bufferDn[1]
if (thisCCI <= 0 and lastCCI > 0) 
    bufferDn := bufferUp[1]

if (thisCCI >= 0)
     if (bufferUp < bufferUp[1])
        bufferUp := bufferUp[1]
else
    if (thisCCI <= 0)
        if (bufferDn > bufferDn[1])
            bufferDn := bufferDn[1]

x = thisCCI >= 0 ? bufferUp : thisCCI <= 0 ? bufferDn : x[1]
swap = x > x[1] ? 1 : x < x[1] ? -1 : swap[1]
swap2 = swap == 1 ? color.lime : color.red
swap3 = thisCCI >=0 ? color.lime : color.red
swap4 = original ? swap3 : swap2

bullTrendMagic = swap4 == color.lime and swap4[1] == color.red
bearTrendMagic = swap4 == color.red and swap4[1] == color.lime

// 绘制信号图标(和原指标一致)
plotchar(bullTrendMagic, title="TM", char=upSign, location=location.belowbar, color=colorBuy, transp=0, text="TM", textcolor=colorBuy, size=size.auto)
plotchar(bearTrendMagic, title="TM", char=downSign, location=location.abovebar, color=colorSell, transp=0, text="TM", textcolor=colorSell, size=size.auto)

// 交易逻辑:多头信号开多,空头信号开空
if (bullTrendMagic)
    strategy.close("Short", comment="Close Short on Long Signal")
    strategy.entry("Long", strategy.long, comment="Long Entry")

if (bearTrendMagic)
    strategy.close("Long", comment="Close Long on Short Signal")
    strategy.entry("Short", strategy.short, comment="Short Entry")

关键修改说明

  • 代码开头用strategy()替换了study(),并配置了初始资金、佣金等策略参数(可根据自己需求调整)
  • 把原代码里的cci()、nz()、sma()、tr()这些函数加上了ta.前缀(适配Pine Script V5版本规范)
  • 添加了strategy.entry和strategy.close函数实现开平仓逻辑,给每个仓位加了标识("Long"、"Short")方便追踪

设置警报的步骤

  1. 在TradingView图表界面点击右上角的警报按钮
  2. 在警报设置窗口:
    • 选择“条件”为你的策略名称(比如"Trend Magic Strategy")
    • 触发条件选择“当策略发出交易信号”
    • 选择要接收警报的通知方式(邮件、短信、推送等)
    • 保存设置即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:43:16