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

基于多条件触发的Pine Code自动化交易策略开发求助

Custom Momentum Strategy Conversion for Pine Script

Got it, let's tackle converting your indicator into a solid strategy that eliminates those duplicate signals and follows all your rules. I'll break down each part clearly since you're new to Pine Script.

Key Fixes & Logic Breakdown

The main issue with multiple triggers is that your original code didn't track whether you were already in a "waiting for exit" state. We'll use persistent state variables (using var) to track when we've recorded the first trigger price, so we don't re-record it while the indicator stays at 100/0. Then we'll handle the exit conditions, compare prices, and add the 0.8% entry price limit.

Full Strategy Code

//@version=5
strategy("Custom Momentum Strategy", overlay=true, 
         default_qty_type=strategy.cash, default_qty_value=10000, 
         initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1)

// 1. Calculate your original momentum percentile indicator
mom = ta.mom(close, 100)
percentile = ta.percentrank(mom, 100) * 100  // Convert 0-1 output to 0-100

// 2. Persistent state variables to track trigger states and prices
var bool tracking_overbought = false
var float overbought_first_price = na
var bool tracking_oversold = false
var float oversold_first_price = na

// 3. Handle Overbought (100) Conditions
// Record first trigger price when indicator hits 100 (only if not already tracking)
if percentile == 100 and not tracking_overbought
    tracking_overbought := true
    overbought_first_price := close
    label.new(bar_index, low, "OB Trigger", color=color.red, textcolor=color.white, style=label.style_label_up)

// Execute strategy when indicator drops below 98 (and we were tracking overbought)
if percentile < 98 and tracking_overbought
    second_price = close
    // Apply 0.8% price limit: long entry can't exceed +0.8% of second price; short can't go below -0.8%
    long_limit = second_price * 1.008
    short_limit = second_price * 0.992

    // Compare prices to decide long/short
    if second_price > overbought_first_price
        strategy.entry("OB Long", strategy.long, limit=long_limit)
        label.new(bar_index, low, "OB Long", color=color.green, textcolor=color.white, style=label.style_label_up)
    else if second_price < overbought_first_price
        strategy.entry("OB Short", strategy.short, limit=short_limit)
        label.new(bar_index, high, "OB Short", color=color.red, textcolor=color.white, style=label.style_label_down)
    
    // Reset tracking state after executing the trade
    tracking_overbought := false
    overbought_first_price := na

// 4. Handle Oversold (0) Conditions
// Record first trigger price when indicator hits 0 (only if not already tracking)
if percentile == 0 and not tracking_oversold
    tracking_oversold := true
    oversold_first_price := close
    label.new(bar_index, high, "OS Trigger", color=color.green, textcolor=color.white, style=label.style_label_down)

// Execute strategy when indicator rises above 2 (and we were tracking oversold)
if percentile > 2 and tracking_oversold
    second_price = close
    long_limit = second_price * 1.008
    short_limit = second_price * 0.992

    if second_price > oversold_first_price
        strategy.entry("OS Long", strategy.long, limit=long_limit)
        label.new(bar_index, low, "OS Long", color=color.green, textcolor=color.white, style=label.style_label_up)
    else if second_price < oversold_first_price
        strategy.entry("OS Short", strategy.short, limit=short_limit)
        label.new(bar_index, high, "OS Short", color=color.red, textcolor=color.white, style=label.style_label_down)
    
    // Reset tracking state after trade
    tracking_oversold := false
    oversold_first_price := na

// Optional: Plot the indicator and levels for visualization
plot(percentile, title="Momentum Percentile", color=color.blue)
hline(100, "Overbought", color=color.red)
hline(0, "Oversold", color=color.green)
hline(98, "OB Exit", color=color.orange, linestyle=hline.style_dashed)
hline(2, "OS Exit", color=color.orange, linestyle=hline.style_dashed)

What Each Part Does

  • Persistent State Variables: The var keyword ensures these variables only initialize once (not every bar), so they remember whether we're already tracking an overbought/oversold trigger. This stops duplicate signal triggers dead in their tracks.
  • Overbought/Oversold Tracking: We only record the first trigger price when we first hit 100/0 (and aren't already tracking). When the indicator exits the extreme range (below 98 or above 2), we calculate the second price and execute the trade based on your comparison rules.
  • 0.8% Price Limit: We use the limit parameter in strategy.entry to enforce that entries can't exceed a 0.8% deviation from the second trigger price. If you meant the limit should be relative to the first trigger price instead, just swap second_price with overbought_first_price/oversold_first_price in the limit calculations.
  • Visualization: Labels and horizontal lines make it easy to see when triggers and trades happen, which helps with testing and debugging.

Testing Tips

  • Backtest this on your target asset to ensure it behaves as expected. You can adjust commission rates, default order sizes, and other strategy parameters in the top section of the code.
  • If you need to tweak any rules (like adjusting the exit thresholds from 98/2), just modify the corresponding values in the if conditions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:48:12