Optimize this code: //@version=5 indicator(title="Automatic Support and Resistance…
- User
Optimize this code: //@version=5 indicator(title="Automatic Support and Resistance Levels (Optimized)", overlay=true)
// Input parameters left_bars = input.int(5, "Left Bars", minval=1) right_bars = input.int(5, "Right Bars", minval=1) lookback = input.int(500, "Lookback Period", minval=100) min_touches = input.int(2, "Minimum Touches", minval=1) price_deviation = input.float(0.5, "Price Deviation (in price units)", minval=0.0) max_levels = input.int(10, "Maximum Levels to Display", minval=1)
// Variables to store pivots var pivot_highs = array.new_float() var pivot_lows = array.new_float() var pivot_times_highs = array.new_int() var pivot_times_lows = array.new_int()
// Calculate pivot high and low values pivotHigh = ta.pivothigh(high, left_bars, right_bars) pivotLow = ta.pivotlow(low, left_bars, right_bars)
// Store pivot highs and their times if not na(pivotHigh) array.push(pivot_highs, pivotHigh) array.push(pivot_times_highs, bar_index[right_bars]) if array.size(pivot_highs) > lookback array.shift(pivot_highs) array.shift(pivot_times_highs)
// Store pivot lows and their times if not na(pivotLow) array.push(pivot_lows, pivotLow) array.push(pivot_times_lows, bar_index[right_bars]) if array.size(pivot_lows) > lookback array.shift(pivot_lows) array.shift(pivot_times_lows)
// Function to find significant levels using bucketization f_find_levels(pivots, price_deviation, min_touches, max_levels) => // Create a map (dictionary) to store levels and their touch counts level_map = array.new_float(0) touch_map = array.new_int(0)
codepivot_count = array.size(pivots) for i = 0 to pivot_count - 1 pivot = array.get(pivots, i) found = false // Check existing levels for j = 0 to array.size(level_map) - 1 level = array.get(level_map, j) if math.abs(pivot - level) <= price_deviation // Increment touch count touch = array.get(touch_map, j) + 1 array.set(touch_map, j, touch) // Update level average new_level = (level * (touch - 1) + pivot) / touch array.set(level_map, j, new_level) found := true break // If not found, add new level if not found array.push(level_map, pivot) array.push(touch_map, 1) // Collect significant levels significant_levels = array.new_float() for i = 0 to array.size(level_map) - 1 if array.get(touch_map, i) >= min_touches array.push(significant_levels, array.get(level_map, i)) // Sort levels array.sort(significant_levels) // Limit the number of levels to display while array.size(significant_levels) > max_levels array.pop(significant_levels) significant_levels - Assistant