本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("ATH Drawdown Distribution", "ATH DD Distribution", overlay = true, behind_chart = false, max_boxes_count = 500, max_labels_count = 500)
// ─────────────────────────────────────────────────────────────────────────────
// Inputs
// ─────────────────────────────────────────────────────────────────────────────
string groupCalc = "Calculation"
string calculationTF = input.timeframe("", "Calculation timeframe", group = groupCalc, tooltip = "Empty means the current chart timeframe. Higher and lower timeframes are supported.")
float binStep = input.float(5.0, "Drawdown bin width (%)", minval = 0.5, maxval = 50.0, step = 0.5, group = groupCalc)
string priceMode = input.string("High / Low", "ATH and trough prices", options = ["High / Low", "Close"], group = groupCalc, tooltip = "High / Low: use candle highs for ATHs and lows for troughs. Close: use closing prices for both.")
bool useStartDate = input.bool(false, "Start from custom date", group = groupCalc, tooltip = "Disabled: use all available loaded history. Enabled: establish a fresh ATH from the first eligible candle.")
int startDate = input.time(timestamp("01 Jan 2020 00:00 +0000"), "Custom start date", active = useStartDate, group = groupCalc)
string groupVisual = "Visual debugging"
bool showZones = input.bool(true, "Highlight completed drawdowns", group = groupVisual)
bool showBoxPercent = input.bool(true, "Show drawdown % inside rectangles", group = groupVisual, tooltip = "Show the maximum drawdown of each completed ATH-to-ATH cycle in the bottom-right corner of its shaded rectangle.")
string boxPercentSize = input.string(size.small, "Rectangle percentage text size", options = [size.tiny, size.small, size.normal, size.large], group = groupVisual, active = showZones and showBoxPercent)
bool showDepthLabels = input.bool(false, "Label completed drawdown depths", group = groupVisual)
bool showATH = input.bool(true, "Show running ATH", group = groupVisual)
int maxVisible = input.int(150, "Maximum highlighted drawdowns", minval = 1, maxval = 500, group = groupVisual, tooltip = "Old drawings are deleted from the chart, but all completed drawdowns stay in the statistical counts.")
int binCount = int(math.ceil(100.0 / binStep))
int chartSeconds = timeframe.in_seconds()
int chosenSeconds = timeframe.in_seconds(calculationTF)
if na(chartSeconds) or na(chosenSeconds)
runtime.error("This indicator needs time-based chart and calculation timeframes.")
// One state machine processes candles in chronological order regardless of TF.
type DrawdownState
float ath
float trough
int athTime
int troughTime
int completed
array<int> counts
var DrawdownState stats = DrawdownState.new(na, na, na, na, 0, array.new_int(binCount, 0))
var array<box> shadedZones = array.new<box>()
var array<label> depthLabels = array.new<label>()
var int lastProcessedTime = na
// A cycle closes ONLY if a later candle makes a strictly new ATH.
// Its magnitude is the deepest trough observed after that cycle's ATH.
// For High / Low mode, the high and low inside an ATH-making candle have
// unknown ordering. Its low is therefore not counted in either cycle.
processCandle(DrawdownState state, int candleTime, float candleHigh, float candleLow, float candleClose, array<box> zones, array<label> labels) =>
float newPeak = priceMode == "Close" ? candleClose : candleHigh
float newTrough = priceMode == "Close" ? candleClose : candleLow
if (not useStartDate or candleTime >= startDate) and not na(newPeak) and not na(newTrough) and newPeak > 0
if na(state.ath)
// The first eligible candle establishes the initial reference ATH.
state.ath := newPeak
state.trough := newPeak
state.athTime := candleTime
state.troughTime := candleTime
else if newPeak > state.ath
// Recovered: classify the MAXIMUM drawdown exactly once.
if state.trough < state.ath
float drawdownPct = 100.0 * (state.ath - state.trough) / state.ath
int binIndex = math.min(binCount - 1, int(math.floor(drawdownPct / binStep)))
state.counts.set(binIndex, state.counts.get(binIndex) + 1)
state.completed += 1
if showZones
// The box owns its own percentage text, placed at the bottom-right of the highlighted range.
// We draw completed-cycle maximum depth, never the intermediate low or recovery.
string boxDepthText = showBoxPercent ? "-" + str.tostring(drawdownPct, "#.##") + "%" : ""
box zone = box.new(left = state.athTime, top = state.ath, right = candleTime, bottom = state.trough, xloc = xloc.bar_time, border_color = color.new(color.orange, 87), bgcolor = color.new(color.orange, 92), text = boxDepthText, text_color = color.orange, text_size = boxPercentSize, text_halign = text.align_right, text_valign = text.align_bottom, text_wrap = text.wrap_none, text_formatting = text.format_bold)
zones.push(zone)
if zones.size() > maxVisible
box.delete(zones.shift())
if showDepthLabels
label depthLabel = label.new(x = state.troughTime, y = state.trough, text = "-" + str.tostring(drawdownPct, "#.##") + "%", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_up, color = color.new(color.orange, 35), textcolor = color.white, size = size.tiny)
labels.push(depthLabel)
if labels.size() > maxVisible
label.delete(labels.shift())
// Begin the next ATH-to-ATH cycle at this new ATH.
state.ath := newPeak
state.trough := newPeak
state.athTime := candleTime
state.troughTime := candleTime
else if newTrough < state.trough
state.trough := newTrough
state.troughTime := candleTime
0
// ─────────────────────────────────────────────────────────────────────────────
// Process completed candles in the selected timeframe.
// HTF: previous fully closed bar via lookahead_on + [1], no future leakage.
// Same TF: use chart candles when confirmed.
// LTF: consume every available intrabar, not just the last intrabar.
// The live peak below is separate from completed-candle statistics so that
// "Current drawdown" can update during an unfinished candle.
// ─────────────────────────────────────────────────────────────────────────────
float livePeak = na
if chosenSeconds > chartSeconds
[htTime, htHigh, htLow, htClose] = request.security(syminfo.tickerid, calculationTF, [time[1], high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
// Include the evolving high (or close) of the active higher-timeframe bar.
[htLiveHigh, htLiveClose] = request.security(syminfo.tickerid, calculationTF, [high, close], lookahead = barmerge.lookahead_off)
livePeak := priceMode == "Close" ? htLiveClose : htLiveHigh
if barstate.isconfirmed and not na(htTime) and (na(lastProcessedTime) or htTime > lastProcessedTime)
processCandle(stats, htTime, htHigh, htLow, htClose, shadedZones, depthLabels)
lastProcessedTime := htTime
else if chosenSeconds < chartSeconds
[ltTimes, ltHighs, ltLows, ltCloses] = request.security_lower_tf(syminfo.tickerid, calculationTF, [time, high, low, close])
// Capture the highest intrabar price (or close) within the live chart bar.
if ltTimes.size() > 0
livePeak := priceMode == "Close" ? ltCloses.max() : ltHighs.max()
if barstate.isconfirmed and ltTimes.size() > 0
for i = 0 to ltTimes.size() - 1
int t = ltTimes.get(i)
if na(lastProcessedTime) or t > lastProcessedTime
processCandle(stats, t, ltHighs.get(i), ltLows.get(i), ltCloses.get(i), shadedZones, depthLabels)
lastProcessedTime := t
else
livePeak := priceMode == "Close" ? close : high
if barstate.isconfirmed
processCandle(stats, time, high, low, close, shadedZones, depthLabels)
lastProcessedTime := time
plot(showATH ? stats.ath : na, title = "ATH reference", color = color.new(color.teal, 55), linewidth = 1, style = plot.style_stepline)
// ─────────────────────────────────────────────────────────────────────────────
// Table: 0..-step, -step..-2*step, etc., up to the deepest occupied bin.
// Empty bins IN BETWEEN occupied bins are kept, to avoid hiding deeper data.
// ─────────────────────────────────────────────────────────────────────────────
var table histogram = na
if barstate.islast
int deepestOccupied = 0
for i = 0 to binCount - 1
if stats.counts.get(i) > 0
deepestOccupied := i
int displayedBins = deepestOccupied + 1 // Always display the first range.
int rows = displayedBins + 4 // Header + bins + three summary rows.
if not na(histogram)
table.delete(histogram)
histogram := table.new(position.bottom_right, 3, rows, frame_color = color.new(color.gray, 60), frame_width = 1, border_color = color.new(color.gray, 85), border_width = 1)
color headerBg = color.rgb(36, 42, 51)
color rowBg = color.rgb(28, 33, 41)
color altRowBg = color.rgb(39, 45, 55)
color fg = color.white
table.cell(histogram, 0, 0, "Max drawdown", text_color = fg, bgcolor = headerBg, text_size = size.small)
table.cell(histogram, 1, 0, "Count", text_color = fg, bgcolor = headerBg, text_size = size.small)
table.cell(histogram, 2, 0, "Share", text_color = fg, bgcolor = headerBg, text_size = size.small)
for i = 0 to displayedBins - 1
float fromPct = i * binStep
float toPct = math.min((i + 1) * binStep, 100.0)
string leftText = i == 0 ? "0" : "-" + str.tostring(fromPct, "#.##")
string rangeText = leftText + "% to -" + str.tostring(toPct, "#.##") + "%"
int count = stats.counts.get(i)
string shareText = stats.completed > 0 ? str.tostring(100.0 * count / stats.completed, "#.0") + "%" : "0%"
color bg = i % 2 == 0 ? rowBg : altRowBg
table.cell(histogram, 0, i + 1, rangeText, text_color = fg, bgcolor = bg, text_size = size.small)
table.cell(histogram, 1, i + 1, str.tostring(count), text_color = fg, bgcolor = bg, text_size = size.small)
table.cell(histogram, 2, i + 1, shareText, text_color = fg, bgcolor = bg, text_size = size.small)
int footer = displayedBins + 1
table.cell(histogram, 0, footer, "Completed cycles", text_color = fg, bgcolor = headerBg, text_size = size.small)
table.cell(histogram, 1, footer, str.tostring(stats.completed), text_color = fg, bgcolor = headerBg, text_size = size.small)
table.cell(histogram, 2, footer, stats.completed > 0 ? "100%" : "0%", text_color = fg, bgcolor = headerBg, text_size = size.small)
float openDepth = not na(stats.ath) and stats.ath > 0 ? 100.0 * (stats.ath - stats.trough) / stats.ath : na
int openRow = displayedBins + 2
table.cell(histogram, 0, openRow, "Open max drawdown", text_color = fg, bgcolor = rowBg, text_size = size.small, tooltip = "Deepest drawdown in the unfinished ATH cycle using confirmed calculation-timeframe candles. Not included in bin counts.")
table.cell(histogram, 1, openRow, na(openDepth) ? "N/A" : "-" + str.tostring(openDepth, "#.##") + "%", text_color = fg, bgcolor = rowBg, text_size = size.small)
table.cell(histogram, 2, openRow, "", text_color = fg, bgcolor = rowBg, text_size = size.small)
// Unlike the open-cycle maximum, this is the distance from the ATH to
// the latest traded price (chart close), not to the deepest prior low.
// An active bar can establish a new ATH before it is fully confirmed.
float currentATH = not na(stats.ath) ? (na(livePeak) ? stats.ath : math.max(stats.ath, livePeak)) : na
float currentDepth = not na(currentATH) and currentATH > 0 ? math.max(0.0, 100.0 * (currentATH - close) / currentATH) : na
string currentText = na(currentDepth) ? "N/A" : currentDepth < 0.005 ? "0.00%" : "-" + str.tostring(currentDepth, "#.##") + "%"
int currentRow = displayedBins + 3
table.cell(histogram, 0, currentRow, "Current drawdown", text_color = fg, bgcolor = altRowBg, text_size = size.small, tooltip = "Percentage decline from the latest ATH to the current price. Updates with the live bar; not included in bin counts until the cycle completes.")
table.cell(histogram, 1, currentRow, currentText, text_color = fg, bgcolor = altRowBg, text_size = size.small)
table.cell(histogram, 2, currentRow, "", text_color = fg, bgcolor = altRowBg, text_size = size.small)