开发交替显示LONG与SHORT信号标签的计数器技术求助
Hey there! I see you're trying to get your signal labels to strictly alternate between LONG and SHORT, with no consecutive duplicates. Let's break down why your current code isn't working, then fix it with a straightforward solution.
The Problem with Your Current Code
Your existing code uses a counter x but doesn't track what type of signal was last displayed. So when highbar triggers multiple times in a row, x just increments without stopping repeated LONG labels—there's no check to enforce that the next signal has to be the opposite type.
The Solution: Track the Last Signal Type
We need a variable to remember whether the last displayed signal was LONG or SHORT. This way, we only show a new signal if it's the opposite of the last one. Here's a working Pine Script implementation (adjust your trigger conditions if needed):
//@version=5 indicator("Alternating LONG/SHORT Labels", overlay=true) // Initialize a variable to track the last signal type (na = no signal yet) var bool lastSignalWasLong = na // Replace these with your actual LONG/SHORT trigger conditions longTrigger = highbar // Your existing LONG condition shortTrigger = lowbar // Your existing SHORT condition // Handle LONG signals: only show if last wasn't LONG (or no signal yet) if longTrigger and (na(lastSignalWasLong) or not lastSignalWasLong) label.new(bar_index, high, "LONG", color=color.new(color.green, 0), textcolor=color.white, style=label.style_label_down) lastSignalWasLong := true // Update last signal type // Handle SHORT signals: only show if last was LONG (or no signal yet) if shortTrigger and (na(lastSignalWasLong) or lastSignalWasLong) label.new(bar_index, low, "SHORT", color=color.new(color.red, 0), textcolor=color.white, style=label.style_label_up) lastSignalWasLong := false // Update last signal type
How This Works
var bool lastSignalWasLong = na: Thevarkeyword ensures this variable is only initialized once when the script starts.nameans no signal has been displayed yet.- For LONG signals: We check if either it's the first signal (
na(lastSignalWasLong)) or the last signal wasn't LONG (not lastSignalWasLong). If true, we create the label and updatelastSignalWasLongtotrue. - For SHORT signals: We check if either it's the first signal or the last signal was LONG. If true, we create the label and update
lastSignalWasLongtofalse.
This logic guarantees signals will strictly alternate between LONG and SHORT—no more consecutive duplicates!
内容的提问来源于stack exchange,提问作者Stock

