本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © 2026 Genexus
//
// GX Volatility Cone 1.0.0
// Statistical price range for the next N bars, sized from the symbol's own volatility, with a calibration table
// that checks how often past cones actually contained price. Shows how far price has typically moved, not where it will go.
// Free and open-source. The directional version (GX Forecast Cone) is a separate script.
// No buy/sell signals. Past behavior does not predict future results. Not investment advice.
//@version=6
indicator("GX Volatility Cone", shorttitle = "GX VCone", overlay = true, max_bars_back = 2500, max_lines_count = 20, max_labels_count = 20, max_polylines_count = 10)
// ═══════════════════════════ INPUTS ═══════════════════════════
const string G_F = "1. Cone range"
int hor = input.int(10, "Horizon (bars ahead)", minval = 2, maxval = 100, group = G_F, tooltip = "Shorter = smaller cone. 10 bars on a 5-minute chart = the next 50 minutes.")
int volLen = input.int(100, "Volatility lookback (bars)", minval = 20, maxval = 500, group = G_F, tooltip = "Standard deviation of 1-bar log returns over this many bars.")
string method = input.string("Empirical", "Band width", options = ["Empirical", "Normal"], group = G_F, tooltip = "Empirical: band width taken from how far price really moved over N bars in the calibration window (handles fat tails). Normal: textbook bell-curve width. Empirical falls back to Normal until enough history exists.")
string lvlIn = input.string("68%", "Inner band", options = ["50%", "68%", "80%", "90%"], group = G_F)
string lvlOut = input.string("90%", "Outer band", options = ["80%", "90%", "95%", "99%"], group = G_F)
int calLen = input.int(500, "Calibration window (checks)", minval = 100, maxval = 2000, group = G_F, tooltip = "How many past N-bar outcomes are used to size (Empirical) and to grade the cone.")
const string G_D = "2. Display"
bool showCone = input.bool(true, "Cone", group = G_D)
bool showMid = input.bool(true, "Center line (current price)", group = G_D)
bool showOut = input.bool(true, "Outer band", group = G_D, tooltip = "Turn off to show only the inner band, for the smallest cone.")
bool showLbl = input.bool(true, "Price labels at the end of the cone", group = G_D)
bool showPrev = input.bool(false, "Previous cone (drawn N bars ago)", group = G_D, tooltip = "Outline of the cone made N bars ago, to see how it held up.")
color colUp = input.color(#089981, "Upper half", group = G_D, inline = "c", tooltip = "Upper half = room above the current price, lower half = room below. Colors show the side, not a predicted direction.")
color colDn = input.color(#f23645, "Lower half", group = G_D, inline = "c")
int trIn = input.int(70, "Inner / outer transparency", minval = 0, maxval = 100, group = G_D, inline = "t")
int trOut = input.int(88, "", minval = 0, maxval = 100, group = G_D, inline = "t")
color colMid = input.color(color.new(#b2b5be, 30), "Center", group = G_D, inline = "c")
bool showTb = input.bool(true, "Table", group = G_D)
string tbPosIn = input.string("Top Right", "Table position", options = ["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group = G_D)
string tbSzIn = input.string("Small", "Table text size", options = ["Tiny", "Small", "Normal"], group = G_D)
const string G_A = "3. Alerts"
float bigSig = input.float(3.0, "Unusual bar: move larger than (σ)", minval = 1.5, maxval = 10.0, step = 0.5, group = G_A, tooltip = "One closed bar moving more than this many 1-bar standard deviations.")
string alFmt = input.string("Text", "Alert message", options = ["Text", "Discord"], group = G_A)
string botName = input.string("GX Volatility Cone", "Name in message", group = G_A)
// ═══════════════════════════ HELPERS ═══════════════════════════
// Levels as "simple" values (ta.percentile_nearest_rank needs a simple percentage)
simple float pIn = lvlIn == "50%" ? 50.0 : lvlIn == "68%" ? 68.27 : lvlIn == "80%" ? 80.0 : 90.0
simple float pOut = lvlOut == "80%" ? 80.0 : lvlOut == "90%" ? 90.0 : lvlOut == "95%" ? 95.0 : 99.0
simple float nzIn = lvlIn == "50%" ? 0.6745 : lvlIn == "68%" ? 1.0 : lvlIn == "80%" ? 1.2816 : 1.6449
simple float nzOut = lvlOut == "80%" ? 1.2816 : lvlOut == "90%" ? 1.6449 : lvlOut == "95%" ? 1.96 : 2.5758
f_px(float x) =>
str.tostring(x, format.mintick)
f_pct(float x) =>
na(x) ? "—" : str.tostring(x, "#.#") + "%"
// ═══════════════════════════ VOLATILITY AND BAND WIDTH ═══════════════════════════
float r1 = math.log(close / close[1])
float sig = ta.stdev(r1, volLen)
float sqN = math.sqrt(hor)
// N-bar move, measured in units of the volatility known N bars ago (no look-ahead)
float rN = math.log(close / close[hor])
float sigP = sig[hor]
float nm = not na(sigP) and sigP > 0 ? math.abs(rN) / (sigP * sqN) : na
var int nmCnt = 0
if not na(nm)
nmCnt += 1
float eIn = ta.percentile_nearest_rank(nm, calLen, pIn)
float eOut = ta.percentile_nearest_rank(nm, calLen, pOut)
bool empOk = method == "Empirical" and nmCnt >= calLen and not na(eIn) and not na(eOut)
float zIn = empOk ? eIn : nzIn
float zOut = empOk ? eOut : nzOut
// ═══════════════════════════ CALIBRATION (cone made N bars ago vs the close now) ═══════════════════════════
bool chk = not na(nm)
int ck = chk ? 1 : 0
int hIn = chk and nm <= zIn[hor] ? 1 : 0
int hOut = chk and nm <= zOut[hor] ? 1 : 0
int bUp = chk and nm > zOut[hor] and rN > 0 ? 1 : 0
int bDn = chk and nm > zOut[hor] and rN < 0 ? 1 : 0
f_win(int x) =>
float c = ta.cum(x)
c - nz(c[calLen])
float wCk = f_win(ck)
float wIn = f_win(hIn)
float wOut = f_win(hOut)
float wUp = f_win(bUp)
float wDn = f_win(bDn)
// ═══════════════════════════ ALERTS ═══════════════════════════
float bm = sig[1] > 0 ? r1 / sig[1] : na
bool outNow = chk and nm > zOut[hor]
bool unusual = barstate.isconfirmed and not na(bm) and math.abs(bm) >= bigSig
bool outside = barstate.isconfirmed and outNow and not outNow[1]
const string FOOT = "Statistical range from past volatility · Not a forecast of direction · Not investment advice"
f_msg(string title, string desc, int col) =>
alFmt == "Discord" ? '{"username":"' + botName + '","embeds":[{"title":"' + title + '","description":"' + desc + '","color":' + str.tostring(col) + ',"footer":{"text":"' + FOOT + '"}}]}' : title + " · " + desc + " · " + FOOT
if unusual
string t = "Unusual bar " + (bm > 0 ? "▲" : "▼") + " · " + syminfo.ticker + " " + timeframe.period
string d = "Close " + f_px(close) + " · bar move " + str.tostring(r1 * 100, "#.##") + "% = " + str.tostring(math.abs(bm), "#.#") + "σ"
alert(f_msg(t, d, bm > 0 ? 563585 : 15873605), alert.freq_once_per_bar_close)
if outside
string t = "Outside " + lvlOut + " " + str.tostring(hor) + "-bar range " + (rN > 0 ? "▲" : "▼") + " · " + syminfo.ticker + " " + timeframe.period
string d = "Close " + f_px(close) + " · " + str.tostring(hor) + "-bar move " + str.tostring((math.exp(rN) - 1) * 100, "#.##") + "% vs range ±" + str.tostring((math.exp(zOut[hor] * sigP * sqN) - 1) * 100, "#.##") + "%"
alert(f_msg(t, d, rN > 0 ? 563585 : 15873605), alert.freq_once_per_bar_close)
alertcondition(unusual, "GX VCone unusual bar", "GX Volatility Cone: unusual bar move on {{ticker}}")
alertcondition(outside, "GX VCone outside range", "GX Volatility Cone: close outside the outer N-bar range on {{ticker}}")
// ═══════════════════════════ DRAWING (last bar, anchored on the last closed bar) ═══════════════════════════
var array<polyline> polys = array.new<polyline>()
var array<label> lbls = array.new<label>()
var line mid = na
// One half of the cone: from the center line out to the band edge (dir = 1 upper, -1 lower)
f_band(int a, float p, float s, float z, float dir, color lc, color fc) =>
array<chart.point> pts = array.new<chart.point>()
for h = 0 to hor
pts.push(chart.point.from_index(a + h, p))
for h = hor to 0
pts.push(chart.point.from_index(a + h, p * math.exp(dir * z * s * math.sqrt(h))))
polyline.new(pts, false, true, xloc.bar_index, lc, fc, line.style_solid, 1)
f_edge(int a, float p, float s, float z, float dir, color lc) =>
array<chart.point> pts = array.new<chart.point>()
for h = 0 to hor
pts.push(chart.point.from_index(a + h, p * math.exp(dir * z * s * math.sqrt(h))))
polyline.new(pts, false, false, xloc.bar_index, lc, color(na), line.style_dotted, 1)
f_tag(int x, float y, string txt, color tc) =>
label.new(x, y, txt, style = label.style_label_left, color = color.new(color.black, 100), textcolor = tc, size = size.small)
if barstate.islast
for pl in polys
pl.delete()
polys.clear()
for l in lbls
l.delete()
lbls.clear()
mid.delete()
int o = barstate.isconfirmed ? 0 : 1
int a = bar_index - o
float p = close[o]
float s = sig[o]
float zi = zIn[o]
float zo = zOut[o]
if showCone and not na(s) and s > 0
if showOut
polys.push(f_band(a, p, s, zo, 1.0, color.new(colUp, 50), color.new(colUp, trOut)))
polys.push(f_band(a, p, s, zo, -1.0, color.new(colDn, 50), color.new(colDn, trOut)))
polys.push(f_band(a, p, s, zi, 1.0, color.new(colUp, 100), color.new(colUp, trIn)))
polys.push(f_band(a, p, s, zi, -1.0, color.new(colDn, 100), color.new(colDn, trIn)))
if showMid
mid := line.new(a, p, a + hor, p, color = colMid, style = line.style_dashed)
if showLbl
float oUp = p * math.exp(zo * s * sqN)
float oDn = p * math.exp(-zo * s * sqN)
float iUp = p * math.exp(zi * s * sqN)
float iDn = p * math.exp(-zi * s * sqN)
if showOut
lbls.push(f_tag(a + hor + 1, oUp, lvlOut + " " + f_px(oUp) + " +" + str.tostring((oUp / p - 1) * 100, "#.##") + "%", colUp))
lbls.push(f_tag(a + hor + 1, iUp, lvlIn + " " + f_px(iUp) + " +" + str.tostring((iUp / p - 1) * 100, "#.##") + "%", colUp))
lbls.push(f_tag(a + hor + 1, iDn, lvlIn + " " + f_px(iDn) + " " + str.tostring((iDn / p - 1) * 100, "#.##") + "%", colDn))
if showOut
lbls.push(f_tag(a + hor + 1, oDn, lvlOut + " " + f_px(oDn) + " " + str.tostring((oDn / p - 1) * 100, "#.##") + "%", colDn))
// Previous cone: made N bars ago, outline only
if showPrev and bar_index - o - hor >= 0
int a0 = a - hor
float p0 = close[o + hor]
float s0 = sig[o + hor]
if not na(s0) and s0 > 0
polys.push(f_edge(a0, p0, s0, zOut[o + hor], 1.0, color.new(colUp, 20)))
polys.push(f_edge(a0, p0, s0, zOut[o + hor], -1.0, color.new(colDn, 20)))
// ═══════════════════════════ TABLE ═══════════════════════════
string tbSz = tbSzIn == "Tiny" ? size.tiny : tbSzIn == "Normal" ? size.normal : size.small
var table tb = showTb ? table.new(tbPosIn == "Top Right" ? position.top_right : tbPosIn == "Bottom Right" ? position.bottom_right : tbPosIn == "Top Left" ? position.top_left : position.bottom_left, 2, 10, bgcolor = #0b0f1a, border_width = 1, border_color = #1e222d, frame_color = #2962ff, frame_width = 1) : na
f_cell(int c, int r, string t, color tc = color.white, string tip = "") =>
table.cell(tb, c, r, t, text_color = tc, text_size = tbSz, tooltip = tip)
f_grade(float act, float target) =>
na(act) ? "—" : str.tostring(act, "#") + "% " + (act < target - 5 ? "too narrow" : act > target + 5 ? "too wide" : "✓")
f_gcol(float act, float target) =>
na(act) ? color.gray : act < target - 5 ? color.orange : act > target + 5 ? color.gray : #089981
if showTb and barstate.isfirst
table.merge_cells(tb, 0, 0, 1, 0)
table.merge_cells(tb, 0, 9, 1, 9)
if showTb and barstate.islast
int o = barstate.isconfirmed ? 0 : 1
float p = close[o]
float s = sig[o]
float zi = zIn[o]
float zo = zOut[o]
float n = wCk[o]
float aIn = n > 0 ? wIn[o] / n * 100 : na
float aOut = n > 0 ? wOut[o] / n * 100 : na
float aUp = n > 0 ? wUp[o] / n * 100 : na
float aDn = n > 0 ? wDn[o] / n * 100 : na
f_cell(0, 0, "GX Volatility Cone · next " + str.tostring(hor) + " bars", color.white)
f_cell(0, 1, "Width", color.gray)
f_cell(1, 1, empOk[o] ? "Empirical" : method == "Empirical" ? "Normal (need " + str.tostring(calLen) + " checks)" : "Normal", color.white, "Empirical = sized from real past N-bar moves.")
f_cell(0, 2, lvlIn + " range", color.gray)
f_cell(1, 2, na(s) ? "—" : f_px(p * math.exp(-zi * s * sqN)) + "–" + f_px(p * math.exp(zi * s * sqN)) + " (±" + str.tostring((math.exp(zi * s * sqN) - 1) * 100, "#.#") + "%)")
f_cell(0, 3, lvlOut + " range", color.gray)
f_cell(1, 3, na(s) ? "—" : f_px(p * math.exp(-zo * s * sqN)) + "–" + f_px(p * math.exp(zo * s * sqN)) + " (±" + str.tostring((math.exp(zo * s * sqN) - 1) * 100, "#.#") + "%)")
f_cell(0, 4, "σ per bar", color.gray)
f_cell(1, 4, na(s) ? "—" : str.tostring(s * 100, "#.##") + "%")
f_cell(0, 5, "Checks", color.gray, "Past cones whose N-bar outcome is known, within the calibration window.")
f_cell(1, 5, str.tostring(n, "#"), n < 100 ? color.orange : color.white)
f_cell(0, 6, "Inside " + lvlIn, color.gray, "Share of past cones where the close N bars later was inside the inner band. Target " + lvlIn + ".")
f_cell(1, 6, f_grade(aIn, pIn), f_gcol(aIn, pIn))
f_cell(0, 7, "Inside " + lvlOut, color.gray, "Target " + lvlOut + ".")
f_cell(1, 7, f_grade(aOut, pOut), f_gcol(aOut, pOut))
f_cell(0, 8, "Broke above / below", color.gray, "Share of past cones where the close ended above / below the outer band.")
f_cell(1, 8, f_pct(aUp) + " / " + f_pct(aDn))
f_cell(0, 9, "Past volatility only · not a direction forecast", color.gray)