In thinkorswim, this study is not working properly. It is showing too many peaks and…
- User
In thinkorswim, this study is not working properly. It is showing too many peaks and troughs. It should only show is there is no higher/lower peak/trough within 'length' candles on either side:
#Inputs input length = 9;
Define peak and trough conditions
def isPeak = high >= Highest(high, length) and high >= Highest(high, length)[-1]; def isTrough = low <= Lowest(low, length) and low <= Lowest(low, length)[-1];
Plot peak and trough markers
plot Peak = if isPeak then high else Double.NaN; Peak.SetDefaultColor(Color.GREEN); Peak.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);
plot Trough = if isTrough then low else Double.NaN; Trough.SetDefaultColor(Color.RED); Trough.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
Assistant
The issue with your code is that it's not properly checking for peaks and troughs on both sides of the current candle. Your current logic only looks backward and one bar forward, but you need to check
lengthbars in both directions.Here's the corrected code:
#Inputs input length = 9; # Define peak condition - current high must be >= all highs within 'length' bars on either side def isPeak = fold i = 1 to length + 1 with p = true do p and high >= GetValue(high, i) and high >= GetValue(high, -i); # Define trough condition - current low must be <= all lows within 'length' bars on either side def isTrough = fold j = 1 to length + 1 with t = true do t and low <= GetValue(low, j) and low <= GetValue(low, -j); # Plot peak and trough markers plot Peak = if isPeak then high else Double.NaN; Peak.SetDefaultColor(Color.GREEN); Peak.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP); plot Trough = if isTrough then low else Double.NaN; Trough.SetDefaultColor(Color.RED); Trough.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);The key changes:
- Using
foldloops: This allows us to check each bar within the specified range on both sides GetValue(high, i): Gets the high valueibars ago (positive i = past)GetValue(high, -i): Gets the high valueibars ahead (negative i = future)- Checking both directions: The condition ensures the current bar is the highest/lowest compared to all bars within
lengthdistance on both sides
This will significantly reduce the number of peaks and troughs shown, as it now properly identifies only the true local extremes within the specified window.
- Using
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.