本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Crypto Relative Underwater", shorttitle = "Crypto Relative Underwater", overlay = false)
//=============================================================================
// Crypto Relative Underwater v1.0 RC
//
// PURPOSE
// Measures how deeply and how long a crypto asset has remained below its
// highest relative value versus a selected benchmark after the chosen start date.
//
// PRICE BENCHMARKS
// NVDA, GOLD, BRENT, NDX, ETH
// Relative Ratio = asset price / benchmark price.
//
// MARKET-CAP BENCHMARKS
// TOTAL2, TOTALES
// Relative Ratio = asset market cap / benchmark market cap.
//
// EPISODE LOGIC
// The episode engine is close-based. An underwater episode starts when the
// relative close moves below its active relative high and ends only when that
// same relative high is fully recovered or exceeded.
//
// RAW RATIO CANDLES
// Raw Ratio candles are visual OHLC envelopes only. They do not change episode
// starts, recovery calculations, ranks, or dashboard values.
//
// The script does not generate buy/sell signals.
//=============================================================================
//------------------------------------------------------------------------------
// USER CONTROLS
//------------------------------------------------------------------------------
benchmarkChoice = input.string(
"NVDA",
"Benchmark",
options = ["NVDA", "GOLD", "BRENT", "TOTALES", "NDX", "TOTAL2", "ETH"],
group = "Relative Analysis")
analysisStart = input.time(
timestamp("01 Jan 2010 00:00 +0000"),
"Analysis start",
group = "Relative Analysis",
tooltip = "Historical calculations begin from this date. Weekly charts are recommended for long-term comparative research.")
displayMode = input.string(
"Underwater",
"View",
options = ["Underwater", "Raw Ratio"],
group = "Display",
tooltip = "Underwater shows relative drawdown from the active relative high. Raw Ratio shows the untransformed asset/benchmark ratio.")
rawRatioStyle = input.string(
"Line",
"Raw Ratio style",
options = ["Line", "Candles"],
group = "Display",
tooltip = "Applies only when View is set to Raw Ratio.")
//------------------------------------------------------------------------------
// FIXED METHODOLOGY
//------------------------------------------------------------------------------
MIN_EPISODE_BARS = 2
MIN_EPISODE_DEPTH = 1.0
MIN_RANK_EPISODES = 3
MS_PER_DAY = 86400000.0
benchmarkSymbol = switch benchmarkChoice
"NVDA" => "NASDAQ:NVDA"
"GOLD" => "TVC:GOLD"
"BRENT" => "TVC:UKOIL"
"TOTALES" => "CRYPTOCAP:TOTALES"
"NDX" => "NASDAQ:NDX"
"TOTAL2" => "CRYPTOCAP:TOTAL2"
"ETH" => "COINBASE:ETHUSD"
=> "NASDAQ:NVDA"
//------------------------------------------------------------------------------
// BENCHMARK OHLC
//------------------------------------------------------------------------------
[benchmarkOpen, benchmarkHigh, benchmarkLow, benchmarkClose] = request.security(
benchmarkSymbol,
timeframe.period,
[open, high, low, close],
gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_off)
// TOTAL2 and TOTALES are market-cap series, so the numerator must also be a
// market-cap series. syminfo.basecurrency maps crypto pairs such as DOGEUSD
// to CRYPTOCAP:DOGE automatically.
isMarketCapBenchmark = benchmarkChoice == "TOTAL2" or benchmarkChoice == "TOTALES"
assetMarketCapSymbol = "CRYPTOCAP:" + syminfo.basecurrency
[assetMcOpen, assetMcHigh, assetMcLow, assetMcClose] = request.security(
assetMarketCapSymbol,
timeframe.period,
[open, high, low, close],
gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_off,
ignore_invalid_symbol = true)
numeratorOpen = isMarketCapBenchmark ? assetMcOpen : open
numeratorHigh = isMarketCapBenchmark ? assetMcHigh : high
numeratorLow = isMarketCapBenchmark ? assetMcLow : low
numeratorClose = isMarketCapBenchmark ? assetMcClose : close
//------------------------------------------------------------------------------
// RELATIVE OHLC
//
// For A/B:
// open = A open / B open
// close = A close / B close
// high = A high / B low
// low = A low / B high
//
// High/low are bar-level envelopes. When two instruments trade in different
// sessions, these values should not be interpreted as synchronized intrabar
// executable prices.
//------------------------------------------------------------------------------
relativeOpen = not na(numeratorOpen) and not na(benchmarkOpen) and benchmarkOpen != 0 ? numeratorOpen / benchmarkOpen : na
relativeHigh = not na(numeratorHigh) and not na(benchmarkLow) and benchmarkLow != 0 ? numeratorHigh / benchmarkLow : na
relativeLow = not na(numeratorLow) and not na(benchmarkHigh) and benchmarkHigh != 0 ? numeratorLow / benchmarkHigh : na
relativeClose = not na(numeratorClose) and not na(benchmarkClose) and benchmarkClose != 0 ? numeratorClose / benchmarkClose : na
active = time >= analysisStart and not na(relativeClose)
relativeRatio = active ? relativeClose : na
//------------------------------------------------------------------------------
// EPISODE STATE
//------------------------------------------------------------------------------
var float relativePeak = na
var int relativePeakTime = na
var bool underwater = false
var float episodeMaxDepth = na
var int episodeTroughBarIndex = na
var int episodeBars = 0
var array<float> historicalDepths = array.new_float()
var array<float> historicalDurations = array.new_float()
float currentDrawdown = na
float currentDurationDays = na
//------------------------------------------------------------------------------
// EPISODE ENGINE
//------------------------------------------------------------------------------
if active
if na(relativePeak)
relativePeak := relativeRatio
relativePeakTime := time
currentDrawdown := 0.0
currentDurationDays := 0.0
else
if relativeRatio >= relativePeak
if underwater
float completedDurationDays = (time - relativePeakTime) / MS_PER_DAY
float completedDepth = math.abs(episodeMaxDepth)
if episodeBars >= MIN_EPISODE_BARS and completedDepth >= MIN_EPISODE_DEPTH
array.push(historicalDepths, completedDepth)
array.push(historicalDurations, completedDurationDays)
relativePeak := relativeRatio
relativePeakTime := time
underwater := false
episodeMaxDepth := na
episodeTroughBarIndex := na
episodeBars := 0
currentDrawdown := 0.0
currentDurationDays := 0.0
else
currentDrawdown := 100.0 * (relativeRatio / relativePeak - 1.0)
if not underwater
underwater := true
episodeMaxDepth := currentDrawdown
episodeTroughBarIndex := bar_index
episodeBars := 1
else
if currentDrawdown < episodeMaxDepth
episodeMaxDepth := currentDrawdown
episodeTroughBarIndex := bar_index
episodeBars += 1
currentDurationDays := (time - relativePeakTime) / MS_PER_DAY
//------------------------------------------------------------------------------
// CURRENT EPISODE METRICS
//------------------------------------------------------------------------------
float currentEpisodeDepth = underwater ? math.abs(episodeMaxDepth) : na
float recoveryProgress = na
if underwater and not na(episodeMaxDepth) and episodeMaxDepth < 0
recoveryProgress := 100.0 * (currentDrawdown - episodeMaxDepth) / math.abs(episodeMaxDepth)
recoveryProgress := math.max(0.0, math.min(100.0, recoveryProgress))
int sampleSize = array.size(historicalDepths)
//------------------------------------------------------------------------------
// HISTORICAL RANKING
//------------------------------------------------------------------------------
f_extreme_rank(array<float> values, float currentValue) =>
int n = array.size(values)
int rank = 1
if n > 0 and not na(currentValue)
for i = 0 to n - 1
if array.get(values, i) > currentValue
rank += 1
rank
f_percentile_rank(array<float> values, float currentValue) =>
int n = array.size(values)
float result = na
if n >= MIN_RANK_EPISODES and not na(currentValue)
int count = 0
for i = 0 to n - 1
if array.get(values, i) <= currentValue
count += 1
result := 100.0 * count / n
result
f_joint_dominance(
array<float> depths,
array<float> durations,
float depth,
float duration) =>
int n = array.size(depths)
float result = na
if n >= MIN_RANK_EPISODES and not na(depth) and not na(duration)
int count = 0
for i = 0 to n - 1
if array.get(depths, i) <= depth and array.get(durations, i) <= duration
count += 1
result := 100.0 * count / n
result
int depthRank = na
int durationRank = na
if underwater
depthRank := f_extreme_rank(historicalDepths, currentEpisodeDepth)
durationRank := f_extreme_rank(historicalDurations, currentDurationDays)
float depthPercentile = underwater
? f_percentile_rank(historicalDepths, currentEpisodeDepth)
: na
float durationPercentile = underwater
? f_percentile_rank(historicalDurations, currentDurationDays)
: na
float jointDominance = underwater
? f_joint_dominance(
historicalDepths,
historicalDurations,
currentEpisodeDepth,
currentDurationDays)
: na
//------------------------------------------------------------------------------
// VISUALS
//------------------------------------------------------------------------------
float depthMagnitude = not na(currentDrawdown) ? math.abs(currentDrawdown) : na
color depthLineColor = color.from_gradient(
depthMagnitude,
0.0,
100.0,
color.rgb(245, 166, 35),
color.rgb(255, 111, 0))
color rawCandleColor =
relativeClose >= relativeOpen
? color.rgb(89, 184, 148)
: color.rgb(255, 111, 0)
plot(
displayMode == "Underwater" ? 0.0 : na,
"Relative high",
color = color.new(color.gray, 68),
linewidth = 1,
style = plot.style_line,
editable = false,
display = display.pane,
precision = 1)
plot(
displayMode == "Underwater" ? currentDrawdown : na,
"Relative underwater",
color = depthLineColor,
linewidth = 2,
style = plot.style_linebr,
editable = false,
display = display.pane,
precision = 1)
plot(
displayMode == "Underwater" ? currentDrawdown : na,
"Underwater fill",
color = color.new(depthLineColor, 95),
linewidth = 1,
style = plot.style_areabr,
editable = false,
display = display.pane,
precision = 1)
plot(
displayMode == "Raw Ratio" and rawRatioStyle == "Line" ? relativeRatio : na,
"Raw relative ratio",
color = color.orange,
linewidth = 2,
style = plot.style_linebr,
editable = false,
display = display.pane,
format = format.price,
precision = 8)
plotcandle(
displayMode == "Raw Ratio" and rawRatioStyle == "Candles" ? relativeOpen : na,
displayMode == "Raw Ratio" and rawRatioStyle == "Candles" ? relativeHigh : na,
displayMode == "Raw Ratio" and rawRatioStyle == "Candles" ? relativeLow : na,
displayMode == "Raw Ratio" and rawRatioStyle == "Candles" ? relativeClose : na,
title = "Raw relative ratio candles",
color = rawCandleColor,
wickcolor = color.new(rawCandleColor, 10),
bordercolor = rawCandleColor,
editable = false,
display = display.pane)
// Research values remain available in Data Window.
plot(relativeRatio, "Relative ratio", display = display.data_window, editable = false, format = format.price, precision = 8)
plot(benchmarkClose, "Benchmark close", display = display.data_window, editable = false)
plot(isMarketCapBenchmark ? assetMcClose : na, "Asset market cap", display = display.data_window, editable = false)
plot(currentEpisodeDepth, "Maximum depth (%)", display = display.data_window, editable = false)
plot(currentDurationDays, "Underwater duration (days)", display = display.data_window, editable = false)
plot(recoveryProgress, "Recovery from trough (%)", display = display.data_window, editable = false)
plot(depthPercentile, "Depth percentile", display = display.data_window, editable = false)
plot(durationPercentile, "Duration percentile", display = display.data_window, editable = false)
plot(jointDominance, "Joint dominance (%)", display = display.data_window, editable = false)
//------------------------------------------------------------------------------
// FORMATTING
//------------------------------------------------------------------------------
f_signed_pct(float value) =>
na(value) ? "n/a" : str.tostring(value, "#.0") + "%"
f_positive_pct(float value) =>
na(value) ? "n/a" : str.tostring(value, "#.0") + "%"
f_raw_ratio(float value) =>
na(value) ? "n/a" : str.tostring(value, "#.########")
f_duration_compact(float value) =>
if na(value)
"n/a"
else if value >= 365.25
str.tostring(value / 365.25, "#.00") + "Y"
else if value >= 30.44
str.tostring(value / 30.44, "#.0") + "M"
else
str.tostring(value, "#") + "D"
f_rank_display(int rank, int n, string extremeText) =>
if n < MIN_RANK_EPISODES or na(rank)
"n/a"
else
rank == 1 ? extremeText : "#" + str.tostring(rank) + " / " + str.tostring(n + 1)
//------------------------------------------------------------------------------
// DASHBOARD
//------------------------------------------------------------------------------
var table dashboard = table.new(
position.top_right,
4,
5,
bgcolor = color.new(chart.bg_color, 3),
frame_color = color.new(chart.fg_color, 84),
frame_width = 1,
border_color = color.new(chart.fg_color, 92),
border_width = 1)
if barstate.isfirst
table.merge_cells(dashboard, 0, 0, 3, 0)
table.merge_cells(dashboard, 0, 2, 3, 2)
if barstate.islast
color muted = color.new(chart.fg_color, 48)
color normal = chart.fg_color
color accent = color.orange
color cellBg = color.new(chart.bg_color, 3)
color headerBg = color.new(color.orange, 87)
table.cell(
dashboard, 0, 0,
"CRYPTO RELATIVE UNDERWATER",
text_color = normal,
bgcolor = headerBg,
text_size = size.tiny,
text_halign = text.align_center)
// Pair, timeframe, sample.
table.cell(
dashboard, 0, 1,
syminfo.ticker + " / " + benchmarkChoice + " · " + timeframe.period,
text_color = normal,
bgcolor = cellBg,
text_size = size.tiny,
text_halign = text.align_left)
table.cell(dashboard, 1, 1, "",
text_color = muted, bgcolor = cellBg, text_size = size.tiny)
table.cell(
dashboard, 2, 1,
str.tostring(sampleSize) + " EPISODES",
text_color = sampleSize >= MIN_RANK_EPISODES ? muted : accent,
bgcolor = cellBg,
text_size = size.tiny,
text_halign = text.align_right)
table.cell(dashboard, 3, 1, "",
text_color = muted, bgcolor = cellBg, text_size = size.tiny)
// Hero clock.
table.cell(
dashboard, 0, 2,
underwater
? "UNDERWATER " + f_duration_compact(currentDurationDays)
: active ? "AT RELATIVE HIGH" : "DATA UNAVAILABLE",
text_color = underwater ? accent : normal,
bgcolor = cellBg,
text_size = size.small,
text_halign = text.align_center)
// Context-aware metrics.
table.cell(
dashboard, 0, 3,
displayMode == "Raw Ratio" ? "RATIO" : "DEPTH",
text_color = muted,
bgcolor = cellBg,
text_size = size.tiny)
table.cell(
dashboard, 1, 3,
displayMode == "Raw Ratio"
? f_raw_ratio(relativeRatio)
: f_signed_pct(currentDrawdown),
text_color = normal,
bgcolor = cellBg,
text_size = size.tiny,
text_halign = text.align_right)
table.cell(
dashboard, 2, 3,
displayMode == "Raw Ratio" ? "DEPTH" : "RECOVERY",
text_color = muted,
bgcolor = cellBg,
text_size = size.tiny)
table.cell(
dashboard, 3, 3,
displayMode == "Raw Ratio"
? f_signed_pct(currentDrawdown)
: underwater ? f_positive_pct(recoveryProgress) : "100.0%",
text_color = normal,
bgcolor = cellBg,
text_size = size.tiny,
text_halign = text.align_right)
// Historical ranks.
table.cell(dashboard, 0, 4, "DEPTH RANK",
text_color = muted, bgcolor = cellBg, text_size = size.tiny)
table.cell(
dashboard, 1, 4,
underwater ? f_rank_display(depthRank, sampleSize, "DEEPEST") : "n/a",
text_color = depthRank == 1 and sampleSize >= MIN_RANK_EPISODES ? accent : normal,
bgcolor = cellBg,
text_size = size.tiny,
text_halign = text.align_right)
table.cell(dashboard, 2, 4, "TIME RANK",
text_color = muted, bgcolor = cellBg, text_size = size.tiny)
table.cell(
dashboard, 3, 4,
underwater ? f_rank_display(durationRank, sampleSize, "LONGEST") : "n/a",
text_color = durationRank == 1 and sampleSize >= MIN_RANK_EPISODES ? accent : normal,
bgcolor = cellBg,
text_size = size.tiny,
text_halign = text.align_right)
//------------------------------------------------------------------------------
// CURRENT EPISODE MARKERS
// Descriptive markers only. They are not trading signals.
//------------------------------------------------------------------------------
var label troughMarker = na
var label currentMarker = na
if barstate.islast
if not na(troughMarker)
label.delete(troughMarker)
if not na(currentMarker)
label.delete(currentMarker)
if displayMode == "Underwater" and underwater
if not na(episodeTroughBarIndex) and not na(episodeMaxDepth)
troughMarker := label.new(
episodeTroughBarIndex,
episodeMaxDepth,
"",
xloc = xloc.bar_index,
yloc = yloc.price,
style = label.style_circle,
color = color.new(color.orange, 12),
textcolor = color.new(color.orange, 100),
size = size.tiny)
currentMarker := label.new(
bar_index,
currentDrawdown,
"",
xloc = xloc.bar_index,
yloc = yloc.price,
style = label.style_circle,
color = color.new(chart.fg_color, 18),
textcolor = color.new(chart.fg_color, 100),
size = size.tiny)