PROTECTED SOURCE SCRIPT
Chip Distribution Pro

// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org/MPL/2.0/
// Enhanced Position Cost Distribution - Auto-adaptive with improved visualization
// Works with ETFs, commodities, forex, crypto, stocks - any instrument
// version=5
indicator('Chip Distribution Pro', overlay = true, max_lines_count = 500, max_bars_back = 500)
//#region Inputs
string GRP_GENERAL = "General Settings"
int LOOKBACK = input.int(1000, 'Lookback Bars', maxval = 20000, minval = 500, step = 250, group = GRP_GENERAL)
int CHART_X_OFFSET = input.int(100, 'Chart Offset', step = 10, group = GRP_GENERAL)
int LABEL_X_OFFSET = CHART_X_OFFSET + 4
int CHART_MAX_WIDTH = input.int(80, 'Max Width', maxval = 500, minval = 10, step = 10, group = GRP_GENERAL)
int NUM_BUCKETS = input.int(400, 'Price Buckets', maxval = 500, minval = 50, step = 50, group = GRP_GENERAL)
string GRP_AUTO = "Auto-Tuning"
bool AUTO_TUNE = input.bool(true, 'Enable Auto-Tuning', group = GRP_AUTO,
tooltip = 'Automatically adjusts turnover rate based on volatility and volume characteristics')
float MANUAL_DECAY = input.float(0.1, 'Manual Turnover Rate', minval = 0.01, maxval = 0.5, step = 0.01, group = GRP_AUTO,
tooltip = 'Only used when Auto-Tuning is disabled')
int VOLATILITY_PERIOD = input.int(20, 'Volatility Period', minval = 5, maxval = 100, group = GRP_AUTO)
string GRP_VISUAL = "Visualization"
string COLOR_SCHEME = input.string("Rainbow", "Color Scheme", options = ["Rainbow", "Gradient", "Classic", "Heatmap"], group = GRP_VISUAL)
color PROFIT_COLOR_LIGHT = input.color(#26a69a, 'Profit Light', group = GRP_VISUAL)
color PROFIT_COLOR_DARK = input.color(#004d40, 'Profit Dark', group = GRP_VISUAL)
color LOSS_COLOR_LIGHT = input.color(#ef5350, 'Loss Light', group = GRP_VISUAL)
color LOSS_COLOR_DARK = input.color(#b71c1c, 'Loss Dark', group = GRP_VISUAL)
color CURRENT_PRICE_COLOR = input.color(color.yellow, 'Current Price', group = GRP_VISUAL)
color AVG_PRICE_COLOR = input.color(#2196F3, 'Average Cost', group = GRP_VISUAL)
color PEAK_COLOR = input.color(#FF9800, 'Peak Concentration', group = GRP_VISUAL)
color STATS_COLOR = input.color(#434651, 'Stats Background', group = GRP_VISUAL)
string GRP_LEVELS = "Key Levels"
bool SHOW_SUPPORT_RESISTANCE = input.bool(true, 'Show Support/Resistance Zones', group = GRP_LEVELS)
bool SHOW_PEAK = input.bool(true, 'Show Peak Concentration', group = GRP_LEVELS)
float SR_THRESHOLD = input.float(0.7, 'S/R Detection Threshold', minval = 0.3, maxval = 0.95, step = 0.05, group = GRP_LEVELS,
tooltip = 'Minimum concentration (relative to peak) to mark as support/resistance')
string GRP_SIGNALS = "Signals Panel"
bool SHOW_SIGNALS = input.bool(true, 'Show Signal Panel', group = GRP_SIGNALS)
bool SHOW_KEY_LEVELS = input.bool(true, 'Show Key Price Levels', group = GRP_SIGNALS)
bool SHOW_TREND_ARROW = input.bool(true, 'Show Trend Arrow', group = GRP_SIGNALS)
bool SHOW_PRESSURE_BAR = input.bool(true, 'Show Pressure Bar', group = GRP_SIGNALS)
// Colors for key levels
color SUPPORT_COLOR = input.color(#00E676, 'Support Level', group = GRP_LEVELS)
color RESISTANCE_COLOR = input.color(#FF5252, 'Resistance Level', group = GRP_LEVELS)
color BREAKOUT_COLOR = input.color(#FFD600, 'Breakout Level', group = GRP_LEVELS)
//#endregion
//#region Candle Type
type Candle
int idx
float hi
float lo
float vol
float relativeVol
float atrPct
//#endregion
//#region PCD Type
type PCD
array<Candle> candles
float minPrice
float maxPrice
float priceStep
array<line> lines
label currentPriceLabel
label avgPriceLabel
label peakLabel
label statsLabel
label signalLabel
array<box> srZones
float calculatedTurnover
// New visualization elements
line supportLine
line resistanceLine
line avgCostLine
label trendArrow
box pressureBar
box pressureFill
label pressureLabel
// Create a new price label
newPriceLabel(color bg, color txtColor) =>
label.new(0, 0, '', style = label.style_label_left, color = bg, textcolor = txtColor, size = size.small)
// Create a new PCD instance
newPCD() =>
array<line> lns = array.new<line>(NUM_BUCKETS)
for i = 0 to NUM_BUCKETS - 1
array.set(lns, i, line.new(0, 0, 0, 0))
PCD.new(
candles = array.new<Candle>(0),
lines = lns,
currentPriceLabel = newPriceLabel(color.new(#00BCD4, 0), color.white),
avgPriceLabel = newPriceLabel(AVG_PRICE_COLOR, color.white),
peakLabel = newPriceLabel(PEAK_COLOR, color.white),
statsLabel = label.new(0, 0, '', style = label.style_label_up, size = size.small,
textalign = text.align_left, color = color.new(STATS_COLOR, 20), textcolor = color.white),
signalLabel = label.new(0, 0, '', style = label.style_label_left, size = size.small,
textalign = text.align_left, color = color.new(#1a1a2e, 20), textcolor = color.white),
srZones = array.new<box>(0),
calculatedTurnover = 0.1,
minPrice = na,
maxPrice = na,
priceStep = na,
supportLine = line.new(0, 0, 0, 0, color = SUPPORT_COLOR, width = 2, style = line.style_dashed),
resistanceLine = line.new(0, 0, 0, 0, color = RESISTANCE_COLOR, width = 2, style = line.style_dashed),
avgCostLine = line.new(0, 0, 0, 0, color = AVG_PRICE_COLOR, width = 2, style = line.style_dotted),
trendArrow = label.new(0, 0, '', style = label.style_label_center, size = size.large, textcolor = color.white),
pressureBar = box.new(0, 0, 0, 0, bgcolor = color.new(#424242, 50), border_color = color.gray),
pressureFill = box.new(0, 0, 0, 0, bgcolor = color.green, border_color = na),
pressureLabel = label.new(0, 0, '', style = label.style_label_right, size = size.tiny, color = color.new(#000000, 100), textcolor = color.white))
// Auto-calculate turnover rate based on instrument characteristics
calcAdaptiveTurnover(float atrPct, float volRatio) =>
float safeAtrPct = na(atrPct) or atrPct <= 0 ? 0.02 : atrPct
float safeVolRatio = na(volRatio) or volRatio <= 0 ? 1.0 : volRatio
float volBasedTurnover = math.max(0.03, math.min(0.3, safeAtrPct * 3))
float volAdjustment = math.max(0.5, math.min(2.0, safeVolRatio))
float turnover = volBasedTurnover * volAdjustment
math.max(0.02, math.min(0.4, turnover))
// Store candle method
method storeCandle(PCD this, int barIdx, float hiPrice, float loPrice, float volVal, float avgVol, float atrPct) =>
if not na(hiPrice) and not na(loPrice) and not na(volVal) and volVal > 0
float safeAvgVol = na(avgVol) or avgVol <= 0 ? volVal : avgVol
float relVol = volVal / safeAvgVol
float safeAtrPct = na(atrPct) ? 0.02 : atrPct
bool modified = false
int candleSize = array.size(this.candles)
if candleSize > 0
Candle c = array.get(this.candles, candleSize - 1)
if c.idx == barIdx
c.hi := hiPrice
c.lo := loPrice
c.vol := volVal
c.relativeVol := relVol
c.atrPct := safeAtrPct
modified := true
if not modified
Candle c = Candle.new(barIdx, hiPrice, loPrice, volVal, relVol, safeAtrPct)
array.push(this.candles, c)
this.minPrice := na(this.minPrice) ? loPrice : math.min(this.minPrice, loPrice)
this.maxPrice := na(this.maxPrice) ? hiPrice : math.max(this.maxPrice, hiPrice)
float priceRange = this.maxPrice - this.minPrice
this.priceStep := priceRange > 0 ? priceRange / NUM_BUCKETS : 0.0001
// Get bucket index for price
method getBucketIndex(PCD this, float price) =>
if na(this.priceStep) or this.priceStep <= 0 or na(this.minPrice)
0
else
int idx = int(math.floor((price - this.minPrice) / this.priceStep))
math.max(0, math.min(idx, NUM_BUCKETS - 1))
// Get price for bucket index
method getBucketedPrice(PCD this, int bucketIdx) =>
int safeIndex = math.max(0, math.min(bucketIdx, NUM_BUCKETS - 1))
float safeStep = na(this.priceStep) or this.priceStep <= 0 ? 0.0001 : this.priceStep
float safeMin = na(this.minPrice) ? 0.0 : this.minPrice
(safeIndex + 0.5) * safeStep + safeMin
// Get rainbow color based on position (0.0 = bottom/red, 1.0 = top/violet)
getRainbowColor(float position, float intensityRatio) =>
float pos = math.max(0.0, math.min(1.0, position))
int transparency = int(math.round((1.0 - intensityRatio) * 50))
// Rainbow spectrum: red -> orange -> yellow -> green -> cyan -> blue -> violet
if pos < 0.166
color.new(color.from_gradient(pos, 0.0, 0.166, #FF0000, #FF7F00), transparency)
else if pos < 0.333
color.new(color.from_gradient(pos, 0.166, 0.333, #FF7F00, #FFFF00), transparency)
else if pos < 0.5
color.new(color.from_gradient(pos, 0.333, 0.5, #FFFF00, #00FF00), transparency)
else if pos < 0.666
color.new(color.from_gradient(pos, 0.5, 0.666, #00FF00, #00FFFF), transparency)
else if pos < 0.833
color.new(color.from_gradient(pos, 0.666, 0.833, #00FFFF, #0000FF), transparency)
else
color.new(color.from_gradient(pos, 0.833, 1.0, #0000FF, #8B00FF), transparency)
// Get color based on scheme and intensity
getColor(bool isProfitable, float intensity, float maxIntensity, int bucketIdx) =>
float safeMax = maxIntensity > 0 ? maxIntensity : 1.0
float ratio = math.max(0.0, math.min(1.0, intensity / safeMax))
float positionRatio = bucketIdx / math.max(1.0, NUM_BUCKETS - 1.0)
if COLOR_SCHEME == "Rainbow"
getRainbowColor(positionRatio, ratio)
else if COLOR_SCHEME == "Gradient"
if isProfitable
color.from_gradient(ratio, 0.0, 1.0, PROFIT_COLOR_DARK, PROFIT_COLOR_LIGHT)
else
color.from_gradient(ratio, 0.0, 1.0, LOSS_COLOR_DARK, LOSS_COLOR_LIGHT)
else if COLOR_SCHEME == "Heatmap"
color.from_gradient(ratio, 0.0, 1.0, #1a237e, #f44336)
else
if isProfitable
color.new(#5d606b, int(math.round((1.0 - ratio) * 70)))
else
color.new(#e91e63, int(math.round((1.0 - ratio) * 70)))
// Update method
method update(PCD this) =>
int candleCount = array.size(this.candles)
if candleCount > 0 and not na(this.priceStep) and this.priceStep > 0
// Create distribution array
array<float> dist = array.new_float(NUM_BUCKETS, 0.0)
// Process each candle
for candleIdx = 0 to candleCount - 1
Candle candle = array.get(this.candles, candleIdx)
bool isFirstCandle = candleIdx == 0
float turnover = AUTO_TUNE ? calcAdaptiveTurnover(candle.atrPct, candle.relativeVol) : MANUAL_DECAY * candle.relativeVol
turnover := math.min(turnover, 0.95)
this.calculatedTurnover := turnover
int startIdx = this.getBucketIndex(candle.lo)
int endIdx = this.getBucketIndex(candle.hi)
int buckets = math.max(1, endIdx - startIdx + 1)
if isFirstCandle
float initialWeight = 1.0 / buckets
for i = startIdx to endIdx
array.set(dist, i, initialWeight)
else
float decayedAmount = 0.0
for i = 0 to NUM_BUCKETS - 1
float oldVal = array.get(dist, i)
float newVal = oldVal * (1.0 - turnover)
array.set(dist, i, newVal)
decayedAmount += oldVal - newVal
float addPerBucket = decayedAmount / buckets
for i = startIdx to endIdx
array.set(dist, i, array.get(dist, i) + addPerBucket)
// Normalize distribution
float totalWeight = 0.0
for i = 0 to NUM_BUCKETS - 1
totalWeight += array.get(dist, i)
if totalWeight > 0
for i = 0 to NUM_BUCKETS - 1
array.set(dist, i, array.get(dist, i) / totalWeight)
// Find peak
float maxWeight = array.max(dist)
if na(maxWeight) or maxWeight <= 0
maxWeight := 0.001
int peakIndex = array.indexof(dist, maxWeight)
if peakIndex < 0
peakIndex := 0
float peakPrice = this.getBucketedPrice(peakIndex)
// Find support/resistance zones
array<int> srIndices = array.new<int>(0)
if SHOW_SUPPORT_RESISTANCE
bool inZone = false
int zoneStart = 0
for i = 0 to NUM_BUCKETS - 1
bool isHighConcentration = array.get(dist, i) >= maxWeight * SR_THRESHOLD
if isHighConcentration and not inZone
inZone := true
zoneStart := i
else if not isHighConcentration and inZone
inZone := false
array.push(srIndices, int(math.floor((zoneStart + i) / 2)))
if inZone
array.push(srIndices, int(math.floor((zoneStart + NUM_BUCKETS - 1) / 2)))
// Clear old SR zones
int srZoneSize = array.size(this.srZones)
if srZoneSize > 0
for i = 0 to srZoneSize - 1
box b = array.get(this.srZones, i)
box.set_lefttop(b, 0, 0)
box.set_rightbottom(b, 0, 0)
// Draw the distribution
float lowestDisplayedPrice = na
float highestDisplayedPrice = na
for i = 0 to NUM_BUCKETS - 1
float weight = array.get(dist, i)
float price = (i + 0.5) * this.priceStep + this.minPrice
int width = int(math.round(weight / maxWeight * CHART_MAX_WIDTH))
line ln = array.get(this.lines, i)
if width > 0
if na(lowestDisplayedPrice)
lowestDisplayedPrice := price
highestDisplayedPrice := price
int x1 = bar_index + CHART_X_OFFSET
int x2 = x1 - width
bool isProfitable = price < close
color c = getColor(isProfitable, weight, maxWeight, i)
line.set_xy1(ln, x1, price)
line.set_xy2(ln, x2, price)
line.set_color(ln, c)
else
line.set_xy1(ln, 0, 0)
line.set_xy2(ln, 0, 0)
// Draw S/R zones
if SHOW_SUPPORT_RESISTANCE
int srCount = array.size(srIndices)
int leftBar = math.max(0, bar_index - LOOKBACK)
if srCount > 0
for i = 0 to srCount - 1
int idx = array.get(srIndices, i)
float zonePrice = this.getBucketedPrice(idx)
float zoneHalfHeight = this.priceStep * 3
box b = na
if i < array.size(this.srZones)
b := array.get(this.srZones, i)
box.set_lefttop(b, leftBar, zonePrice + zoneHalfHeight)
box.set_rightbottom(b, bar_index, zonePrice - zoneHalfHeight)
else
b := box.new(leftBar, zonePrice + zoneHalfHeight, bar_index, zonePrice - zoneHalfHeight, bgcolor = color.new(PEAK_COLOR, 85), border_color = color.new(PEAK_COLOR, 60))
array.push(this.srZones, b)
// Calculate cumulative distribution
array<float> cumdist = array.copy(dist)
for i = 1 to NUM_BUCKETS - 1
array.set(cumdist, i, array.get(cumdist, i - 1) + array.get(cumdist, i))
// Highlight current price
int closeIndex = this.getBucketIndex(close)
if closeIndex >= 0 and closeIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, closeIndex), CURRENT_PRICE_COLOR)
// Calculate stats
float totalShares = array.get(cumdist, NUM_BUCKETS - 1)
int profitIndex = math.min(closeIndex + 1, NUM_BUCKETS - 1)
float profitRatio = totalShares > 0 ? array.get(cumdist, profitIndex) / totalShares : 0.0
// Calculate average price
float avg = 0.0
for i = 0 to NUM_BUCKETS - 1
float weight = array.get(dist, i)
float price = this.getBucketedPrice(i)
avg += price * weight
int avgIndex = this.getBucketIndex(avg)
if avgIndex >= 0 and avgIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, avgIndex), AVG_PRICE_COLOR)
// Peak concentration - highlight line
if SHOW_PEAK and peakIndex >= 0 and peakIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, peakIndex), PEAK_COLOR)
// Smart label positioning - avoid overlaps
float priceRange = na(highestDisplayedPrice) or na(lowestDisplayedPrice) ? close * 0.01 : (highestDisplayedPrice - lowestDisplayedPrice)
float minLabelSpacing = priceRange * 0.025
// Sort prices and assign staggered X offsets
float currentY = close
float avgY = avg
float peakY = peakPrice
// Adjust avg label if too close to current
if math.abs(avgY - currentY) < minLabelSpacing
avgY := currentY > avgY ? avgY - minLabelSpacing : avgY + minLabelSpacing
// Adjust peak label if too close to current or avg
if SHOW_PEAK
if math.abs(peakY - currentY) < minLabelSpacing
peakY := currentY > peakY ? peakY - minLabelSpacing : peakY + minLabelSpacing
if math.abs(peakY - avgY) < minLabelSpacing
peakY := avgY > peakY ? peakY - minLabelSpacing : peakY + minLabelSpacing
// Position price labels - compact format, right side of distribution
label.set_text(this.currentPriceLabel, str.format('{0,number,#.##}', close))
label.set_xy(this.currentPriceLabel, bar_index + LABEL_X_OFFSET + 2, close)
label.set_style(this.currentPriceLabel, label.style_label_left)
label.set_size(this.currentPriceLabel, size.tiny)
label.set_text(this.avgPriceLabel, str.format('{0,number,#.##} AVG', avg))
label.set_xy(this.avgPriceLabel, bar_index + LABEL_X_OFFSET + 2, avgY)
label.set_style(this.avgPriceLabel, label.style_label_left)
label.set_size(this.avgPriceLabel, size.tiny)
if SHOW_PEAK
label.set_text(this.peakLabel, str.format('{0,number,#.##} PEAK', peakPrice))
label.set_xy(this.peakLabel, bar_index + LABEL_X_OFFSET + 2, peakY)
label.set_style(this.peakLabel, label.style_label_left)
label.set_size(this.peakLabel, size.tiny)
// Calculate ranges safely
float safeTotalShares = totalShares > 0 ? totalShares : 1.0
int idx05 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.05)
int idx95 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.95)
int idx15 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.15)
int idx85 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.85)
float ninetyPctLow = this.getBucketedPrice(idx05)
float ninetyPctHigh = this.getBucketedPrice(idx95)
float seventyPctLow = this.getBucketedPrice(idx15)
float seventyPctHigh = this.getBucketedPrice(idx85)
float rangeDenom = ninetyPctHigh - ninetyPctLow
float rangeOverlap = rangeDenom != 0 ? (seventyPctHigh - seventyPctLow) / rangeDenom : 0.0
// Calculate chip concentration
float concentration = rangeOverlap * 100
string concentrationDesc = concentration < 50 ? "High" : concentration < 70 ? "Medium" : "Dispersed"
// Pressure analysis
float safeAvg = avg > 0 ? avg : close
float priceVsAvg = ((close - safeAvg) / safeAvg) * 100
string pressure = priceVsAvg > 5 ? "Strong Bullish" : priceVsAvg > 1 ? "Bullish" :
priceVsAvg < -5 ? "Strong Bearish" : priceVsAvg < -1 ? "Bearish" : "Neutral"
// Price vs Peak
float safePeak = peakPrice > 0 ? peakPrice : close
float priceVsPeak = ((close - safePeak) / safePeak) * 100
string peakRelation = close > peakPrice ? "Above Peak" : close < peakPrice ? "Below Peak" : "At Peak"
// Stats panel - positioned at bottom, compact
float displayedRange = na(highestDisplayedPrice) or na(lowestDisplayedPrice) ? close * 0.02 : highestDisplayedPrice - lowestDisplayedPrice
label.set_text(this.statsLabel, str.format(
'90%: {0,number,#.##} - {1,number,#.##} | 70%: {2,number,#.##} - {3,number,#.##}',
ninetyPctLow, ninetyPctHigh, seventyPctLow, seventyPctHigh))
if not na(lowestDisplayedPrice) and displayedRange > 0
label.set_y(this.statsLabel, lowestDisplayedPrice - displayedRange * 0.05)
label.set_style(this.statsLabel, label.style_label_up)
label.set_x(this.statsLabel, bar_index + CHART_X_OFFSET - 30)
label.set_size(this.statsLabel, size.tiny)
// Signal panel - hidden (info moved to trend arrow and pressure bar)
label.set_text(this.signalLabel, "")
label.set_xy(this.signalLabel, bar_index, close)
// === NEW PROFESSIONAL VISUALIZATIONS ===
// 1. Key Level Lines - Support, Resistance, and Average Cost extending across chart
if SHOW_KEY_LEVELS
int chartLeft = math.max(0, bar_index - LOOKBACK)
int chartRight = bar_index + CHART_X_OFFSET - 5
// Average cost line (horizontal dotted blue line)
line.set_xy1(this.avgCostLine, chartLeft, avg)
line.set_xy2(this.avgCostLine, chartRight, avg)
line.set_color(this.avgCostLine, AVG_PRICE_COLOR)
// Find strongest support (highest concentration below current price)
float strongestSupport = na
float strongestSupportWeight = 0.0
float strongestResistance = na
float strongestResistanceWeight = 0.0
for i = 0 to NUM_BUCKETS - 1
float bucketPrice = this.getBucketedPrice(i)
float bucketWeight = array.get(dist, i)
if bucketPrice < close and bucketWeight > strongestSupportWeight
strongestSupport := bucketPrice
strongestSupportWeight := bucketWeight
if bucketPrice > close and bucketWeight > strongestResistanceWeight
strongestResistance := bucketPrice
strongestResistanceWeight := bucketWeight
// Support line (green dashed)
if not na(strongestSupport)
line.set_xy1(this.supportLine, chartLeft, strongestSupport)
line.set_xy2(this.supportLine, chartRight, strongestSupport)
line.set_color(this.supportLine, SUPPORT_COLOR)
else
line.set_xy1(this.supportLine, bar_index, close)
line.set_xy2(this.supportLine, bar_index, close)
line.set_color(this.supportLine, color.new(SUPPORT_COLOR, 100))
// Resistance line (red dashed)
if not na(strongestResistance)
line.set_xy1(this.resistanceLine, chartLeft, strongestResistance)
line.set_xy2(this.resistanceLine, chartRight, strongestResistance)
line.set_color(this.resistanceLine, RESISTANCE_COLOR)
else
line.set_xy1(this.resistanceLine, bar_index, close)
line.set_xy2(this.resistanceLine, bar_index, close)
line.set_color(this.resistanceLine, color.new(RESISTANCE_COLOR, 100))
// 2. Trend Direction Arrow
if SHOW_TREND_ARROW
string trendSymbol = priceVsAvg > 5 ? "▲▲" : priceVsAvg > 1 ? "▲" :
priceVsAvg < -5 ? "▼▼" : priceVsAvg < -1 ? "▼" : "◆"
color trendColor = priceVsAvg > 5 ? color.new(#00E676, 0) : priceVsAvg > 1 ? color.new(#4CAF50, 0) :
priceVsAvg < -5 ? color.new(#FF1744, 0) : priceVsAvg < -1 ? color.new(#EF5350, 0) : color.new(#9E9E9E, 0)
string trendText = trendSymbol + "\n" + pressure
label.set_text(this.trendArrow, trendText)
float arrowY = na(highestDisplayedPrice) ? close : highestDisplayedPrice + displayedRange * 0.12
label.set_xy(this.trendArrow, bar_index + CHART_X_OFFSET - 40, arrowY)
label.set_color(this.trendArrow, color.new(trendColor, 70))
label.set_textcolor(this.trendArrow, trendColor)
label.set_size(this.trendArrow, size.large)
// 3. Pressure Bar (Profit/Loss ratio visualization)
if SHOW_PRESSURE_BAR
float barWidth = 8.0
float barHeight = displayedRange * 0.25
float barX = bar_index + CHART_X_OFFSET + 5
float barTop = na(highestDisplayedPrice) ? close + barHeight/2 : highestDisplayedPrice - displayedRange * 0.02
float barBottom = barTop - barHeight
// Background bar
box.set_lefttop(this.pressureBar, int(barX), barTop)
box.set_rightbottom(this.pressureBar, int(barX + barWidth), barBottom)
box.set_bgcolor(this.pressureBar, color.new(#424242, 60))
// Fill based on profit ratio (green from bottom)
float fillHeight = barHeight * profitRatio
float fillTop = barBottom + fillHeight
color fillColor = profitRatio > 0.7 ? color.new(#00E676, 30) :
profitRatio > 0.5 ? color.new(#4CAF50, 30) :
profitRatio > 0.3 ? color.new(#FFC107, 30) : color.new(#FF5252, 30)
box.set_lefttop(this.pressureFill, int(barX), fillTop)
box.set_rightbottom(this.pressureFill, int(barX + barWidth), barBottom)
box.set_bgcolor(this.pressureFill, fillColor)
// Pressure label
string pressureText = str.format('{0,number,#}%', profitRatio * 100)
label.set_text(this.pressureLabel, pressureText)
label.set_xy(this.pressureLabel, int(barX - 1), barTop + displayedRange * 0.01)
label.set_textcolor(this.pressureLabel, fillColor)
//#endregion
//#region Main
[dailyBarIdx, dailyHigh, dailyLow, dailyVolume, dailyClose, dailyATR, avgVolume] = request.security(syminfo.tickerid, 'D', [bar_index, high, low, volume, close, ta.atr(VOLATILITY_PERIOD), ta.sma(volume, 60)], lookahead = barmerge.lookahead_off)
float atrPercent = dailyClose > 0 ? dailyATR / dailyClose : 0.02
if timeframe.in_seconds(timeframe.period) <= timeframe.in_seconds('D')
var PCD pcd = newPCD()
if last_bar_index - bar_index < LOOKBACK
pcd.storeCandle(dailyBarIdx, dailyHigh, dailyLow, dailyVolume, avgVolume, atrPercent)
if barstate.islast
pcd.update()
//#endregion
// Enhanced Position Cost Distribution - Auto-adaptive with improved visualization
// Works with ETFs, commodities, forex, crypto, stocks - any instrument
// version=5
indicator('Chip Distribution Pro', overlay = true, max_lines_count = 500, max_bars_back = 500)
//#region Inputs
string GRP_GENERAL = "General Settings"
int LOOKBACK = input.int(1000, 'Lookback Bars', maxval = 20000, minval = 500, step = 250, group = GRP_GENERAL)
int CHART_X_OFFSET = input.int(100, 'Chart Offset', step = 10, group = GRP_GENERAL)
int LABEL_X_OFFSET = CHART_X_OFFSET + 4
int CHART_MAX_WIDTH = input.int(80, 'Max Width', maxval = 500, minval = 10, step = 10, group = GRP_GENERAL)
int NUM_BUCKETS = input.int(400, 'Price Buckets', maxval = 500, minval = 50, step = 50, group = GRP_GENERAL)
string GRP_AUTO = "Auto-Tuning"
bool AUTO_TUNE = input.bool(true, 'Enable Auto-Tuning', group = GRP_AUTO,
tooltip = 'Automatically adjusts turnover rate based on volatility and volume characteristics')
float MANUAL_DECAY = input.float(0.1, 'Manual Turnover Rate', minval = 0.01, maxval = 0.5, step = 0.01, group = GRP_AUTO,
tooltip = 'Only used when Auto-Tuning is disabled')
int VOLATILITY_PERIOD = input.int(20, 'Volatility Period', minval = 5, maxval = 100, group = GRP_AUTO)
string GRP_VISUAL = "Visualization"
string COLOR_SCHEME = input.string("Rainbow", "Color Scheme", options = ["Rainbow", "Gradient", "Classic", "Heatmap"], group = GRP_VISUAL)
color PROFIT_COLOR_LIGHT = input.color(#26a69a, 'Profit Light', group = GRP_VISUAL)
color PROFIT_COLOR_DARK = input.color(#004d40, 'Profit Dark', group = GRP_VISUAL)
color LOSS_COLOR_LIGHT = input.color(#ef5350, 'Loss Light', group = GRP_VISUAL)
color LOSS_COLOR_DARK = input.color(#b71c1c, 'Loss Dark', group = GRP_VISUAL)
color CURRENT_PRICE_COLOR = input.color(color.yellow, 'Current Price', group = GRP_VISUAL)
color AVG_PRICE_COLOR = input.color(#2196F3, 'Average Cost', group = GRP_VISUAL)
color PEAK_COLOR = input.color(#FF9800, 'Peak Concentration', group = GRP_VISUAL)
color STATS_COLOR = input.color(#434651, 'Stats Background', group = GRP_VISUAL)
string GRP_LEVELS = "Key Levels"
bool SHOW_SUPPORT_RESISTANCE = input.bool(true, 'Show Support/Resistance Zones', group = GRP_LEVELS)
bool SHOW_PEAK = input.bool(true, 'Show Peak Concentration', group = GRP_LEVELS)
float SR_THRESHOLD = input.float(0.7, 'S/R Detection Threshold', minval = 0.3, maxval = 0.95, step = 0.05, group = GRP_LEVELS,
tooltip = 'Minimum concentration (relative to peak) to mark as support/resistance')
string GRP_SIGNALS = "Signals Panel"
bool SHOW_SIGNALS = input.bool(true, 'Show Signal Panel', group = GRP_SIGNALS)
bool SHOW_KEY_LEVELS = input.bool(true, 'Show Key Price Levels', group = GRP_SIGNALS)
bool SHOW_TREND_ARROW = input.bool(true, 'Show Trend Arrow', group = GRP_SIGNALS)
bool SHOW_PRESSURE_BAR = input.bool(true, 'Show Pressure Bar', group = GRP_SIGNALS)
// Colors for key levels
color SUPPORT_COLOR = input.color(#00E676, 'Support Level', group = GRP_LEVELS)
color RESISTANCE_COLOR = input.color(#FF5252, 'Resistance Level', group = GRP_LEVELS)
color BREAKOUT_COLOR = input.color(#FFD600, 'Breakout Level', group = GRP_LEVELS)
//#endregion
//#region Candle Type
type Candle
int idx
float hi
float lo
float vol
float relativeVol
float atrPct
//#endregion
//#region PCD Type
type PCD
array<Candle> candles
float minPrice
float maxPrice
float priceStep
array<line> lines
label currentPriceLabel
label avgPriceLabel
label peakLabel
label statsLabel
label signalLabel
array<box> srZones
float calculatedTurnover
// New visualization elements
line supportLine
line resistanceLine
line avgCostLine
label trendArrow
box pressureBar
box pressureFill
label pressureLabel
// Create a new price label
newPriceLabel(color bg, color txtColor) =>
label.new(0, 0, '', style = label.style_label_left, color = bg, textcolor = txtColor, size = size.small)
// Create a new PCD instance
newPCD() =>
array<line> lns = array.new<line>(NUM_BUCKETS)
for i = 0 to NUM_BUCKETS - 1
array.set(lns, i, line.new(0, 0, 0, 0))
PCD.new(
candles = array.new<Candle>(0),
lines = lns,
currentPriceLabel = newPriceLabel(color.new(#00BCD4, 0), color.white),
avgPriceLabel = newPriceLabel(AVG_PRICE_COLOR, color.white),
peakLabel = newPriceLabel(PEAK_COLOR, color.white),
statsLabel = label.new(0, 0, '', style = label.style_label_up, size = size.small,
textalign = text.align_left, color = color.new(STATS_COLOR, 20), textcolor = color.white),
signalLabel = label.new(0, 0, '', style = label.style_label_left, size = size.small,
textalign = text.align_left, color = color.new(#1a1a2e, 20), textcolor = color.white),
srZones = array.new<box>(0),
calculatedTurnover = 0.1,
minPrice = na,
maxPrice = na,
priceStep = na,
supportLine = line.new(0, 0, 0, 0, color = SUPPORT_COLOR, width = 2, style = line.style_dashed),
resistanceLine = line.new(0, 0, 0, 0, color = RESISTANCE_COLOR, width = 2, style = line.style_dashed),
avgCostLine = line.new(0, 0, 0, 0, color = AVG_PRICE_COLOR, width = 2, style = line.style_dotted),
trendArrow = label.new(0, 0, '', style = label.style_label_center, size = size.large, textcolor = color.white),
pressureBar = box.new(0, 0, 0, 0, bgcolor = color.new(#424242, 50), border_color = color.gray),
pressureFill = box.new(0, 0, 0, 0, bgcolor = color.green, border_color = na),
pressureLabel = label.new(0, 0, '', style = label.style_label_right, size = size.tiny, color = color.new(#000000, 100), textcolor = color.white))
// Auto-calculate turnover rate based on instrument characteristics
calcAdaptiveTurnover(float atrPct, float volRatio) =>
float safeAtrPct = na(atrPct) or atrPct <= 0 ? 0.02 : atrPct
float safeVolRatio = na(volRatio) or volRatio <= 0 ? 1.0 : volRatio
float volBasedTurnover = math.max(0.03, math.min(0.3, safeAtrPct * 3))
float volAdjustment = math.max(0.5, math.min(2.0, safeVolRatio))
float turnover = volBasedTurnover * volAdjustment
math.max(0.02, math.min(0.4, turnover))
// Store candle method
method storeCandle(PCD this, int barIdx, float hiPrice, float loPrice, float volVal, float avgVol, float atrPct) =>
if not na(hiPrice) and not na(loPrice) and not na(volVal) and volVal > 0
float safeAvgVol = na(avgVol) or avgVol <= 0 ? volVal : avgVol
float relVol = volVal / safeAvgVol
float safeAtrPct = na(atrPct) ? 0.02 : atrPct
bool modified = false
int candleSize = array.size(this.candles)
if candleSize > 0
Candle c = array.get(this.candles, candleSize - 1)
if c.idx == barIdx
c.hi := hiPrice
c.lo := loPrice
c.vol := volVal
c.relativeVol := relVol
c.atrPct := safeAtrPct
modified := true
if not modified
Candle c = Candle.new(barIdx, hiPrice, loPrice, volVal, relVol, safeAtrPct)
array.push(this.candles, c)
this.minPrice := na(this.minPrice) ? loPrice : math.min(this.minPrice, loPrice)
this.maxPrice := na(this.maxPrice) ? hiPrice : math.max(this.maxPrice, hiPrice)
float priceRange = this.maxPrice - this.minPrice
this.priceStep := priceRange > 0 ? priceRange / NUM_BUCKETS : 0.0001
// Get bucket index for price
method getBucketIndex(PCD this, float price) =>
if na(this.priceStep) or this.priceStep <= 0 or na(this.minPrice)
0
else
int idx = int(math.floor((price - this.minPrice) / this.priceStep))
math.max(0, math.min(idx, NUM_BUCKETS - 1))
// Get price for bucket index
method getBucketedPrice(PCD this, int bucketIdx) =>
int safeIndex = math.max(0, math.min(bucketIdx, NUM_BUCKETS - 1))
float safeStep = na(this.priceStep) or this.priceStep <= 0 ? 0.0001 : this.priceStep
float safeMin = na(this.minPrice) ? 0.0 : this.minPrice
(safeIndex + 0.5) * safeStep + safeMin
// Get rainbow color based on position (0.0 = bottom/red, 1.0 = top/violet)
getRainbowColor(float position, float intensityRatio) =>
float pos = math.max(0.0, math.min(1.0, position))
int transparency = int(math.round((1.0 - intensityRatio) * 50))
// Rainbow spectrum: red -> orange -> yellow -> green -> cyan -> blue -> violet
if pos < 0.166
color.new(color.from_gradient(pos, 0.0, 0.166, #FF0000, #FF7F00), transparency)
else if pos < 0.333
color.new(color.from_gradient(pos, 0.166, 0.333, #FF7F00, #FFFF00), transparency)
else if pos < 0.5
color.new(color.from_gradient(pos, 0.333, 0.5, #FFFF00, #00FF00), transparency)
else if pos < 0.666
color.new(color.from_gradient(pos, 0.5, 0.666, #00FF00, #00FFFF), transparency)
else if pos < 0.833
color.new(color.from_gradient(pos, 0.666, 0.833, #00FFFF, #0000FF), transparency)
else
color.new(color.from_gradient(pos, 0.833, 1.0, #0000FF, #8B00FF), transparency)
// Get color based on scheme and intensity
getColor(bool isProfitable, float intensity, float maxIntensity, int bucketIdx) =>
float safeMax = maxIntensity > 0 ? maxIntensity : 1.0
float ratio = math.max(0.0, math.min(1.0, intensity / safeMax))
float positionRatio = bucketIdx / math.max(1.0, NUM_BUCKETS - 1.0)
if COLOR_SCHEME == "Rainbow"
getRainbowColor(positionRatio, ratio)
else if COLOR_SCHEME == "Gradient"
if isProfitable
color.from_gradient(ratio, 0.0, 1.0, PROFIT_COLOR_DARK, PROFIT_COLOR_LIGHT)
else
color.from_gradient(ratio, 0.0, 1.0, LOSS_COLOR_DARK, LOSS_COLOR_LIGHT)
else if COLOR_SCHEME == "Heatmap"
color.from_gradient(ratio, 0.0, 1.0, #1a237e, #f44336)
else
if isProfitable
color.new(#5d606b, int(math.round((1.0 - ratio) * 70)))
else
color.new(#e91e63, int(math.round((1.0 - ratio) * 70)))
// Update method
method update(PCD this) =>
int candleCount = array.size(this.candles)
if candleCount > 0 and not na(this.priceStep) and this.priceStep > 0
// Create distribution array
array<float> dist = array.new_float(NUM_BUCKETS, 0.0)
// Process each candle
for candleIdx = 0 to candleCount - 1
Candle candle = array.get(this.candles, candleIdx)
bool isFirstCandle = candleIdx == 0
float turnover = AUTO_TUNE ? calcAdaptiveTurnover(candle.atrPct, candle.relativeVol) : MANUAL_DECAY * candle.relativeVol
turnover := math.min(turnover, 0.95)
this.calculatedTurnover := turnover
int startIdx = this.getBucketIndex(candle.lo)
int endIdx = this.getBucketIndex(candle.hi)
int buckets = math.max(1, endIdx - startIdx + 1)
if isFirstCandle
float initialWeight = 1.0 / buckets
for i = startIdx to endIdx
array.set(dist, i, initialWeight)
else
float decayedAmount = 0.0
for i = 0 to NUM_BUCKETS - 1
float oldVal = array.get(dist, i)
float newVal = oldVal * (1.0 - turnover)
array.set(dist, i, newVal)
decayedAmount += oldVal - newVal
float addPerBucket = decayedAmount / buckets
for i = startIdx to endIdx
array.set(dist, i, array.get(dist, i) + addPerBucket)
// Normalize distribution
float totalWeight = 0.0
for i = 0 to NUM_BUCKETS - 1
totalWeight += array.get(dist, i)
if totalWeight > 0
for i = 0 to NUM_BUCKETS - 1
array.set(dist, i, array.get(dist, i) / totalWeight)
// Find peak
float maxWeight = array.max(dist)
if na(maxWeight) or maxWeight <= 0
maxWeight := 0.001
int peakIndex = array.indexof(dist, maxWeight)
if peakIndex < 0
peakIndex := 0
float peakPrice = this.getBucketedPrice(peakIndex)
// Find support/resistance zones
array<int> srIndices = array.new<int>(0)
if SHOW_SUPPORT_RESISTANCE
bool inZone = false
int zoneStart = 0
for i = 0 to NUM_BUCKETS - 1
bool isHighConcentration = array.get(dist, i) >= maxWeight * SR_THRESHOLD
if isHighConcentration and not inZone
inZone := true
zoneStart := i
else if not isHighConcentration and inZone
inZone := false
array.push(srIndices, int(math.floor((zoneStart + i) / 2)))
if inZone
array.push(srIndices, int(math.floor((zoneStart + NUM_BUCKETS - 1) / 2)))
// Clear old SR zones
int srZoneSize = array.size(this.srZones)
if srZoneSize > 0
for i = 0 to srZoneSize - 1
box b = array.get(this.srZones, i)
box.set_lefttop(b, 0, 0)
box.set_rightbottom(b, 0, 0)
// Draw the distribution
float lowestDisplayedPrice = na
float highestDisplayedPrice = na
for i = 0 to NUM_BUCKETS - 1
float weight = array.get(dist, i)
float price = (i + 0.5) * this.priceStep + this.minPrice
int width = int(math.round(weight / maxWeight * CHART_MAX_WIDTH))
line ln = array.get(this.lines, i)
if width > 0
if na(lowestDisplayedPrice)
lowestDisplayedPrice := price
highestDisplayedPrice := price
int x1 = bar_index + CHART_X_OFFSET
int x2 = x1 - width
bool isProfitable = price < close
color c = getColor(isProfitable, weight, maxWeight, i)
line.set_xy1(ln, x1, price)
line.set_xy2(ln, x2, price)
line.set_color(ln, c)
else
line.set_xy1(ln, 0, 0)
line.set_xy2(ln, 0, 0)
// Draw S/R zones
if SHOW_SUPPORT_RESISTANCE
int srCount = array.size(srIndices)
int leftBar = math.max(0, bar_index - LOOKBACK)
if srCount > 0
for i = 0 to srCount - 1
int idx = array.get(srIndices, i)
float zonePrice = this.getBucketedPrice(idx)
float zoneHalfHeight = this.priceStep * 3
box b = na
if i < array.size(this.srZones)
b := array.get(this.srZones, i)
box.set_lefttop(b, leftBar, zonePrice + zoneHalfHeight)
box.set_rightbottom(b, bar_index, zonePrice - zoneHalfHeight)
else
b := box.new(leftBar, zonePrice + zoneHalfHeight, bar_index, zonePrice - zoneHalfHeight, bgcolor = color.new(PEAK_COLOR, 85), border_color = color.new(PEAK_COLOR, 60))
array.push(this.srZones, b)
// Calculate cumulative distribution
array<float> cumdist = array.copy(dist)
for i = 1 to NUM_BUCKETS - 1
array.set(cumdist, i, array.get(cumdist, i - 1) + array.get(cumdist, i))
// Highlight current price
int closeIndex = this.getBucketIndex(close)
if closeIndex >= 0 and closeIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, closeIndex), CURRENT_PRICE_COLOR)
// Calculate stats
float totalShares = array.get(cumdist, NUM_BUCKETS - 1)
int profitIndex = math.min(closeIndex + 1, NUM_BUCKETS - 1)
float profitRatio = totalShares > 0 ? array.get(cumdist, profitIndex) / totalShares : 0.0
// Calculate average price
float avg = 0.0
for i = 0 to NUM_BUCKETS - 1
float weight = array.get(dist, i)
float price = this.getBucketedPrice(i)
avg += price * weight
int avgIndex = this.getBucketIndex(avg)
if avgIndex >= 0 and avgIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, avgIndex), AVG_PRICE_COLOR)
// Peak concentration - highlight line
if SHOW_PEAK and peakIndex >= 0 and peakIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, peakIndex), PEAK_COLOR)
// Smart label positioning - avoid overlaps
float priceRange = na(highestDisplayedPrice) or na(lowestDisplayedPrice) ? close * 0.01 : (highestDisplayedPrice - lowestDisplayedPrice)
float minLabelSpacing = priceRange * 0.025
// Sort prices and assign staggered X offsets
float currentY = close
float avgY = avg
float peakY = peakPrice
// Adjust avg label if too close to current
if math.abs(avgY - currentY) < minLabelSpacing
avgY := currentY > avgY ? avgY - minLabelSpacing : avgY + minLabelSpacing
// Adjust peak label if too close to current or avg
if SHOW_PEAK
if math.abs(peakY - currentY) < minLabelSpacing
peakY := currentY > peakY ? peakY - minLabelSpacing : peakY + minLabelSpacing
if math.abs(peakY - avgY) < minLabelSpacing
peakY := avgY > peakY ? peakY - minLabelSpacing : peakY + minLabelSpacing
// Position price labels - compact format, right side of distribution
label.set_text(this.currentPriceLabel, str.format('{0,number,#.##}', close))
label.set_xy(this.currentPriceLabel, bar_index + LABEL_X_OFFSET + 2, close)
label.set_style(this.currentPriceLabel, label.style_label_left)
label.set_size(this.currentPriceLabel, size.tiny)
label.set_text(this.avgPriceLabel, str.format('{0,number,#.##} AVG', avg))
label.set_xy(this.avgPriceLabel, bar_index + LABEL_X_OFFSET + 2, avgY)
label.set_style(this.avgPriceLabel, label.style_label_left)
label.set_size(this.avgPriceLabel, size.tiny)
if SHOW_PEAK
label.set_text(this.peakLabel, str.format('{0,number,#.##} PEAK', peakPrice))
label.set_xy(this.peakLabel, bar_index + LABEL_X_OFFSET + 2, peakY)
label.set_style(this.peakLabel, label.style_label_left)
label.set_size(this.peakLabel, size.tiny)
// Calculate ranges safely
float safeTotalShares = totalShares > 0 ? totalShares : 1.0
int idx05 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.05)
int idx95 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.95)
int idx15 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.15)
int idx85 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.85)
float ninetyPctLow = this.getBucketedPrice(idx05)
float ninetyPctHigh = this.getBucketedPrice(idx95)
float seventyPctLow = this.getBucketedPrice(idx15)
float seventyPctHigh = this.getBucketedPrice(idx85)
float rangeDenom = ninetyPctHigh - ninetyPctLow
float rangeOverlap = rangeDenom != 0 ? (seventyPctHigh - seventyPctLow) / rangeDenom : 0.0
// Calculate chip concentration
float concentration = rangeOverlap * 100
string concentrationDesc = concentration < 50 ? "High" : concentration < 70 ? "Medium" : "Dispersed"
// Pressure analysis
float safeAvg = avg > 0 ? avg : close
float priceVsAvg = ((close - safeAvg) / safeAvg) * 100
string pressure = priceVsAvg > 5 ? "Strong Bullish" : priceVsAvg > 1 ? "Bullish" :
priceVsAvg < -5 ? "Strong Bearish" : priceVsAvg < -1 ? "Bearish" : "Neutral"
// Price vs Peak
float safePeak = peakPrice > 0 ? peakPrice : close
float priceVsPeak = ((close - safePeak) / safePeak) * 100
string peakRelation = close > peakPrice ? "Above Peak" : close < peakPrice ? "Below Peak" : "At Peak"
// Stats panel - positioned at bottom, compact
float displayedRange = na(highestDisplayedPrice) or na(lowestDisplayedPrice) ? close * 0.02 : highestDisplayedPrice - lowestDisplayedPrice
label.set_text(this.statsLabel, str.format(
'90%: {0,number,#.##} - {1,number,#.##} | 70%: {2,number,#.##} - {3,number,#.##}',
ninetyPctLow, ninetyPctHigh, seventyPctLow, seventyPctHigh))
if not na(lowestDisplayedPrice) and displayedRange > 0
label.set_y(this.statsLabel, lowestDisplayedPrice - displayedRange * 0.05)
label.set_style(this.statsLabel, label.style_label_up)
label.set_x(this.statsLabel, bar_index + CHART_X_OFFSET - 30)
label.set_size(this.statsLabel, size.tiny)
// Signal panel - hidden (info moved to trend arrow and pressure bar)
label.set_text(this.signalLabel, "")
label.set_xy(this.signalLabel, bar_index, close)
// === NEW PROFESSIONAL VISUALIZATIONS ===
// 1. Key Level Lines - Support, Resistance, and Average Cost extending across chart
if SHOW_KEY_LEVELS
int chartLeft = math.max(0, bar_index - LOOKBACK)
int chartRight = bar_index + CHART_X_OFFSET - 5
// Average cost line (horizontal dotted blue line)
line.set_xy1(this.avgCostLine, chartLeft, avg)
line.set_xy2(this.avgCostLine, chartRight, avg)
line.set_color(this.avgCostLine, AVG_PRICE_COLOR)
// Find strongest support (highest concentration below current price)
float strongestSupport = na
float strongestSupportWeight = 0.0
float strongestResistance = na
float strongestResistanceWeight = 0.0
for i = 0 to NUM_BUCKETS - 1
float bucketPrice = this.getBucketedPrice(i)
float bucketWeight = array.get(dist, i)
if bucketPrice < close and bucketWeight > strongestSupportWeight
strongestSupport := bucketPrice
strongestSupportWeight := bucketWeight
if bucketPrice > close and bucketWeight > strongestResistanceWeight
strongestResistance := bucketPrice
strongestResistanceWeight := bucketWeight
// Support line (green dashed)
if not na(strongestSupport)
line.set_xy1(this.supportLine, chartLeft, strongestSupport)
line.set_xy2(this.supportLine, chartRight, strongestSupport)
line.set_color(this.supportLine, SUPPORT_COLOR)
else
line.set_xy1(this.supportLine, bar_index, close)
line.set_xy2(this.supportLine, bar_index, close)
line.set_color(this.supportLine, color.new(SUPPORT_COLOR, 100))
// Resistance line (red dashed)
if not na(strongestResistance)
line.set_xy1(this.resistanceLine, chartLeft, strongestResistance)
line.set_xy2(this.resistanceLine, chartRight, strongestResistance)
line.set_color(this.resistanceLine, RESISTANCE_COLOR)
else
line.set_xy1(this.resistanceLine, bar_index, close)
line.set_xy2(this.resistanceLine, bar_index, close)
line.set_color(this.resistanceLine, color.new(RESISTANCE_COLOR, 100))
// 2. Trend Direction Arrow
if SHOW_TREND_ARROW
string trendSymbol = priceVsAvg > 5 ? "▲▲" : priceVsAvg > 1 ? "▲" :
priceVsAvg < -5 ? "▼▼" : priceVsAvg < -1 ? "▼" : "◆"
color trendColor = priceVsAvg > 5 ? color.new(#00E676, 0) : priceVsAvg > 1 ? color.new(#4CAF50, 0) :
priceVsAvg < -5 ? color.new(#FF1744, 0) : priceVsAvg < -1 ? color.new(#EF5350, 0) : color.new(#9E9E9E, 0)
string trendText = trendSymbol + "\n" + pressure
label.set_text(this.trendArrow, trendText)
float arrowY = na(highestDisplayedPrice) ? close : highestDisplayedPrice + displayedRange * 0.12
label.set_xy(this.trendArrow, bar_index + CHART_X_OFFSET - 40, arrowY)
label.set_color(this.trendArrow, color.new(trendColor, 70))
label.set_textcolor(this.trendArrow, trendColor)
label.set_size(this.trendArrow, size.large)
// 3. Pressure Bar (Profit/Loss ratio visualization)
if SHOW_PRESSURE_BAR
float barWidth = 8.0
float barHeight = displayedRange * 0.25
float barX = bar_index + CHART_X_OFFSET + 5
float barTop = na(highestDisplayedPrice) ? close + barHeight/2 : highestDisplayedPrice - displayedRange * 0.02
float barBottom = barTop - barHeight
// Background bar
box.set_lefttop(this.pressureBar, int(barX), barTop)
box.set_rightbottom(this.pressureBar, int(barX + barWidth), barBottom)
box.set_bgcolor(this.pressureBar, color.new(#424242, 60))
// Fill based on profit ratio (green from bottom)
float fillHeight = barHeight * profitRatio
float fillTop = barBottom + fillHeight
color fillColor = profitRatio > 0.7 ? color.new(#00E676, 30) :
profitRatio > 0.5 ? color.new(#4CAF50, 30) :
profitRatio > 0.3 ? color.new(#FFC107, 30) : color.new(#FF5252, 30)
box.set_lefttop(this.pressureFill, int(barX), fillTop)
box.set_rightbottom(this.pressureFill, int(barX + barWidth), barBottom)
box.set_bgcolor(this.pressureFill, fillColor)
// Pressure label
string pressureText = str.format('{0,number,#}%', profitRatio * 100)
label.set_text(this.pressureLabel, pressureText)
label.set_xy(this.pressureLabel, int(barX - 1), barTop + displayedRange * 0.01)
label.set_textcolor(this.pressureLabel, fillColor)
//#endregion
//#region Main
[dailyBarIdx, dailyHigh, dailyLow, dailyVolume, dailyClose, dailyATR, avgVolume] = request.security(syminfo.tickerid, 'D', [bar_index, high, low, volume, close, ta.atr(VOLATILITY_PERIOD), ta.sma(volume, 60)], lookahead = barmerge.lookahead_off)
float atrPercent = dailyClose > 0 ? dailyATR / dailyClose : 0.02
if timeframe.in_seconds(timeframe.period) <= timeframe.in_seconds('D')
var PCD pcd = newPCD()
if last_bar_index - bar_index < LOOKBACK
pcd.storeCandle(dailyBarIdx, dailyHigh, dailyLow, dailyVolume, avgVolume, atrPercent)
if barstate.islast
pcd.update()
//#endregion
Korumalı komut dosyası
Bu komut dosyası kapalı kaynak olarak yayınlanmaktadır. Ancak, ücretsiz ve herhangi bir sınırlama olmaksızın kullanabilirsiniz – daha fazla bilgiyi buradan edinebilirsiniz.
Feragatname
Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.
Korumalı komut dosyası
Bu komut dosyası kapalı kaynak olarak yayınlanmaktadır. Ancak, ücretsiz ve herhangi bir sınırlama olmaksızın kullanabilirsiniz – daha fazla bilgiyi buradan edinebilirsiniz.
Feragatname
Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.