非持仓条件导致Pine Script指标BUY/SELL标签不显示问题咨询
问题逻辑非常清晰:指标中的「BUY」和「SELL」标签无法始终正常显示,问题根源是enterLong与enterShort的入场条件,尤其是其中的not inTrade限制,部分场景下平仓信号会同时触发入场判定。

核心需求是在指标中模拟如下策略逻辑:
FLAT = strategy.position_size == 0 LONG = strategy.position_size > 0 SHORT = strategy.position_size < 0 entry = strategy.position_avg_price
代码片段
//@version=4 study("非持仓状态问题", overlay = true, precision = 6) // —————————— 常量定义 { // ————— 输入选项 var string TD1 = "双向交易" var string TD2 = "仅做多" var string TD3 = "仅做空" // } // —————————— 参数设置 { // ————— 入场参数 var string GP1 = "入场设置" string i_tradeDirection = input(TD1, "交易方向", options = [TD1, TD2, TD3], group = GP1) // ————— 用户选择的交易方向对应变量 var bool doLongs = (i_tradeDirection == TD2 or i_tradeDirection == TD1) var bool doShorts = (i_tradeDirection == TD3 or i_tradeDirection == TD1) // } // —————————— 指标计算 { ema = ema(close, 200) // } // —————————— 策略逻辑计算 { // ————— 持仓状态 var float entryPrice = na var bool inLong = false var bool inShort = false bool inTrade = inLong or inShort // ————— 信号条件 a = close > ema enterLongCondition = not a[1] and a enterShortCondition = a[1] and not a exitLongCondition = enterShortCondition exitShortCondition = enterLongCondition // ————— 过滤条件 filterLong = true filterShort = true // ————— 入场触发 enterLong = doLongs and not inTrade and enterLongCondition enterShort = doShorts and not inTrade and enterShortCondition // ————— 止损计算 atr = atr(14) stopLong = min(lowest(5), min(close, open) - atr * 1.5) stopShort = max(highest(5), max(close, open) + atr * 1.5) // ————— 出场触发 exitLong = inLong and (exitLongCondition or close < stopLong[1]) exitShort = inShort and (exitShortCondition or close > stopShort[1]) // ————— 状态更新 if enterLong inLong := true entryPrice := close else if enterShort inShort := true entryPrice := close else if exitLong inLong := false entryPrice := na else if exitShort inShort := false entryPrice := na // } // —————————— 绘制内容 { color colorBar = close > ema ? color.green : color.red plot(ema, "EMA", color = colorBar, linewidth = 2, style = plot.style_circles) // ————— 信号标签 plotshape(enterLong, style = shape.labelup, location = location.belowbar, color = color.new(color.green, 20), text = "BUY", textcolor = color.white, size = size.normal) plotshape(enterShort, style = shape.labeldown, location = location.abovebar, color = color.new(color.red, 20), text = "SELL", textcolor = color.white, size = size.normal) // }
内容的提问来源于stack exchange,提问作者nop
相关产品推荐
相关产品推荐

