本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Parallax", overlay = true, scale = scale.none, behind_chart = true, format = format.volume, max_boxes_count = 50, max_lines_count = 500, max_labels_count = 500, max_bars_back = 500)
// Blocks
strength = input.int(3, "Swing strength", minval = 1, maxval = 50, group = "Blocks", tooltip = "Bars on each side of the pivot. A strength of 3 confirms after 3 later bars close; the box is drawn back to the pivot.", display = display.none)
wickBodyRatio = input.float(1, "Minimum wick / body", minval = 0, step = 0.1, group = "Blocks", display = display.none)
minWickPercent = input.float(50, "Minimum wick % of range", minval = 0, maxval = 100, group = "Blocks", display = display.none)
maxBlocks = input.int(20, "Maximum active blocks", minval = 1, maxval = 50, group = "Blocks", tooltip = "The oldest block is removed when this limit is reached.", display = display.none)
bullishEnabled = input.bool(true, "Show bullish blocks", group = "Blocks", display = display.none)
bearishEnabled = input.bool(true, "Show bearish blocks", group = "Blocks", display = display.none)
skipOverlap = input.bool(true, "Skip same-direction overlap", group = "Blocks", display = display.none)
extendRight = input.bool(true, "Extend blocks to current bar", group = "Block appearance", display = display.none)
showMidline = input.bool(true, "Show 50% midline", group = "Block appearance", display = display.none)
showBlockLabels = input.bool(false, "Show block names", group = "Block appearance", display = display.none)
borderWidth = input.int(1, "Border width", minval = 1, maxval = 4, group = "Block appearance", display = display.none)
fillTransparency = input.int(90, "Fill transparency", minval = 0, maxval = 100, group = "Block appearance", display = display.none)
bullishColor = input.color(color.rgb(0, 173, 162), "Bullish block color", group = "Block appearance", display = display.none)
bearishColor = input.color(color.rgb(244, 64, 85), "Bearish block color", group = "Block appearance", display = display.none)
showFibs = input.bool(true, "Show Fibonacci lines", group = "Block Fibonacci", display = display.none)
showFibLabels = input.bool(true, "Show Fibonacci labels", group = "Block Fibonacci", display = display.none)
fibInput = input.string("0.5, 0.62, 0.705, 0.79", "Fib levels", group = "Block Fibonacci", tooltip = "Up to 8 ratios from 0 to 1, measured across the block's wick range.", display = display.none)
highlightInput = input.string("0.705, 0.79", "Highlight levels", group = "Block Fibonacci", display = display.none)
labelPrices = input.bool(false, "Include prices in fib labels", group = "Block Fibonacci", display = display.none)
labelSizeInput = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = "Block Fibonacci", display = display.none)
fibColor = input.color(color.rgb(86, 174, 185), "Fib color", group = "Block Fibonacci", display = display.none)
highlightColor = input.color(color.rgb(0, 209, 225), "Highlight color", group = "Block Fibonacci", display = display.none)
string labelSize = labelSizeInput == "Tiny" ? size.tiny : labelSizeInput == "Normal" ? size.normal : size.small
// EMAs
showEMAs = input.bool(true, "Show EMA lines", group = "Optional EMA lines", tooltip = "Chart-timeframe EMAs. Does not affect block detection.", display = display.none)
ema1Length = input.int(15, "EMA 1 length", minval = 1, group = "Optional EMA lines", display = display.none)
ema2Length = input.int(30, "EMA 2 length", minval = 1, group = "Optional EMA lines", display = display.none)
ema3Length = input.int(65, "EMA 3 length", minval = 1, group = "Optional EMA lines", display = display.none)
ema4Length = input.int(200, "EMA 4 length", minval = 1, group = "Optional EMA lines", display = display.none)
ema1Color = input.color(color.orange, "EMA 1 color", group = "Optional EMA lines", display = display.none)
ema2Color = input.color(color.blue, "EMA 2 color", group = "Optional EMA lines", display = display.none)
ema3Color = input.color(color.teal, "EMA 3 color", group = "Optional EMA lines", display = display.none)
ema4Color = input.color(color.gray, "EMA 4 color", group = "Optional EMA lines", display = display.none)
// Manual gamma levels
showGamma = input.bool(false, "Show supplied gamma levels", group = "Optional gamma lines", tooltip = "Draws pasted levels until you replace them. A GAMMA1 import here runs the model instead. Data does not refresh automatically.", display = display.none)
gammaTicker = input.string("", "Snapshot ticker, e.g. QQQ", group = "Optional gamma lines", display = display.none)
gammaInput = input.text_area("", "Gamma prices and optional labels", group = "Optional gamma lines", tooltip = "Up to 15 prices, separated by commas or newlines. Optional label: 730|GEX 1. Labels are supplied, not ranked here. Also accepts a complete GAMMA1 import; no raw CSV or Pine code.", display = display.none)
gammaNote = input.string("", "Optional source / expiry note", group = "Optional gamma lines", tooltip = "Saved in Settings only; does not expire or hide levels.", display = display.none)
gammaColor = input.color(color.purple, "Gamma line color", group = "Optional gamma lines", display = display.none)
showGammaLabels = input.bool(true, "Show gamma price labels", group = "Optional gamma lines", display = display.none)
gammaLabelSide = input.string("Above", "Gamma labels", options = ["Above", "Below"], group = "Optional gamma lines", display = display.none)
gammaGapTicks = input.int(5, "Gamma label gap: ticks", minval = 0, maxval = 200, group = "Optional gamma lines", display = display.none)
gammaLabelOffset = input.int(3, "Gamma label spacing: bars right", minval = 0, maxval = 50, group = "Optional gamma lines", display = display.none)
// Dashboard and volume
showDashboard = input.bool(true, "Show dashboard", group = "Dashboard", display = display.none)
dashboardPosition = input.string("Top right", "Position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Bottom left"], group = "Dashboard", display = display.none)
dashboardSize = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = "Dashboard", display = display.none)
volumeLength = input.int(20, "Volume average length", minval = 2, maxval = 200, group = "Volume", display = display.none)
showVolumeBars = input.bool(true, "Show volume bars", group = "Volume", display = display.none)
showVolumeAverage = input.bool(false, "Show previous-bar average", group = "Volume", display = display.none)
showVolumeSummary = input.bool(false, "Show compact volume summary", group = "Volume", tooltip = "Adds volume and closed-bar RVOL when the dashboard is enabled.", display = display.none)
volumeHeight = input.int(20, "Volume height % (approx.)", minval = 5, maxval = 35, group = "Volume", tooltip = "Volume's share of its autoscale range. Chart margins affect the visible height.", display = display.none)
volumeTransparency = input.int(60, "Volume transparency", minval = 0, maxval = 95, group = "Volume", display = display.none)
highVolumeRatio = input.float(1.5, "Highlight volume above average by", minval = 1, step = 0.1, group = "Volume", tooltip = "Multiple of the preceding candles' average volume. No time-of-day adjustment.", display = display.none)
volumeUpColor = input.color(color.rgb(0, 150, 136), "Up candle volume", group = "Volume", display = display.none)
volumeDownColor = input.color(color.rgb(239, 83, 80), "Down candle volume", group = "Volume", display = display.none)
string dashboardTextSize = dashboardSize == "Tiny" ? size.tiny : dashboardSize == "Normal" ? size.normal : size.small
string dashboardLocation = dashboardPosition == "Middle right" ? position.middle_right : dashboardPosition == "Bottom right" ? position.bottom_right : dashboardPosition == "Top left" ? position.top_left : dashboardPosition == "Bottom left" ? position.bottom_left : position.top_right
// Gamma model
gmEnabled = input.bool(false, "Enable in-chart gamma model", group = "Gamma model", display = display.none)
gmData = input.text_area("", "Compact options data", group = "Gamma model", tooltip = "Complete GAMMA1 file with header: one expiry, up to 400 strikes. No raw CSV or price lists.", display = display.none)
gmMode = input.string("Snapshot preview", "Model reference", options = ["Snapshot preview", "Chart price / current time"], group = "Gamma model", tooltip = "Snapshot: imported price/time. Chart: latest close/current time on script updates. Both keep imported IV and OI fixed. No live options feed or historical backtest.", display = display.none)
gmRate = input.float(4.0, "Interest rate % (assumption)", minval = -10, maxval = 30, step = 0.1, group = "Gamma model", display = display.none) / 100.0
gmYield = input.float(0.6, "Continuous dividend yield % (assumption)", minval = 0, maxval = 30, step = 0.1, group = "Gamma model", display = display.none) / 100.0
gmMove = input.float(2.0, "Scenario price range +/- %", minval = 0.1, maxval = 20, step = 0.1, group = "Gamma model", display = display.none) / 100.0
gmHours = input.float(8.0, "Scenario horizon: hours", minval = 0.1, maxval = 48, step = 0.5, group = "Gamma model", tooltip = "Tests 0, half and full horizon, capped at 80% of remaining time to expiry.", display = display.none)
gmIVMove = input.float(20.0, "Scenario IV change +/- %", minval = 1, maxval = 80, step = 1, group = "Gamma model", tooltip = "Relative change applied to each imported IV. At 20%, an IV of 0.25 is tested at 0.20, 0.25 and 0.30.", display = display.none) / 100.0
gmLineCount = input.int(10, "Model levels shown", minval = 1, maxval = 15, group = "Gamma model", display = display.none)
gmShowPanel = input.bool(true, "Include gamma in dashboard", group = "Gamma model", display = display.none)
// Accept GAMMA1 in either input, but reject conflicting imports.
gm_route(string compactText, string levelsText, bool enabled, bool showLevels) =>
string proper = str.trim(str.replace_all(compactText, "\r", ""))
string legacy = str.trim(str.replace_all(levelsText, "\r", ""))
bool packed = str.startswith(legacy, "GAMMA1,")
bool active = enabled or (showLevels and packed)
string payload = proper
if str.length(payload) == 0 and packed
payload := legacy
bool conflict = active and packed and str.length(proper) > 0 and proper != legacy
[active, payload, conflict]
[gmActive, gmPayload, gmConflict] = gm_route(gmData, gammaInput, gmEnabled, showGamma)
if barstate.isfirst and gmConflict
runtime.error("Two different gamma imports were found. Keep the intended GAMMA1 file in Gamma model > Compact options data and clear Optional gamma lines > Gamma prices and optional labels.")
// Block helpers
f_contains(array<float> values, float value) =>
bool found = false
for item in values
if math.abs(item - value) < 0.000001
found := true
found
f_parse(string raw, string fieldName) =>
array<float> values = array.new<float>()
if str.length(str.trim(raw)) > 0
for token in str.split(raw, ",")
float value = str.tonumber(str.trim(token))
if na(value) or value < 0 or value > 1
runtime.error(fieldName + ": use comma-separated numbers between 0 and 1.")
if not f_contains(values, value)
array.push(values, value)
if array.size(values) > 8
runtime.error(fieldName + ": maximum 8 unique levels.")
values
f_qualifies(float o, float h, float l, float c, bool bull) =>
float body = math.abs(c - o)
float candleRange = h - l
float wick = bull ? math.min(o, c) - l : h - math.max(o, c)
float tolerance = syminfo.mintick * 0.000001
candleRange > 0 and wick > 0 and wick + tolerance >= body * wickBodyRatio and wick + tolerance >= candleRange * minWickPercent / 100.0
f_fibPrice(float bottom, float top, bool bull, float ratio) =>
bull ? top - (top - bottom) * ratio : bottom + (top - bottom) * ratio
f_invalid(bool bull, float bottom, float top, float closingPrice) =>
bull ? closingPrice < bottom : closingPrice > top
f_intersects(bool existingBull, float existingBottom, float existingTop, bool bull, float bottom, float top) =>
existingBull == bull and bottom <= existingTop and top >= existingBottom
var array<float> fibRatios = f_parse(fibInput, "Fib levels")
var array<float> highlightRatios = f_parse(highlightInput, "Highlight levels")
type Block
bool bull
float bottom
float top
int confirmedTime
box region
line midpoint
label tag
array<line> fibLines
array<label> fibLabels
f_destroy(Block block) =>
box.delete(block.region)
line.delete(block.midpoint)
label.delete(block.tag)
for fibLine in block.fibLines
line.delete(fibLine)
for fibLabel in block.fibLabels
label.delete(fibLabel)
f_overlaps(array<Block> blocks, bool bull, float bottom, float top) =>
bool overlaps = false
for block in blocks
if f_intersects(block.bull, block.bottom, block.top, bull, bottom, top)
overlaps := true
overlaps
f_create(bool bull, float bottom, float top, int pivotTime, int confirmationTime, int confirmationClose) =>
color edge = bull ? bullishColor : bearishColor
box region = box.new(left = pivotTime, top = top, right = confirmationTime, bottom = bottom, xloc = xloc.bar_time, border_color = edge, border_width = borderWidth, bgcolor = color.new(edge, fillTransparency), force_overlay = true)
line midpoint = na
label tag = na
array<line> fibLines = array.new<line>()
array<label> fibLabels = array.new<label>()
if showMidline and not (showFibs and f_contains(fibRatios, 0.5))
float mid = (top + bottom) / 2
midpoint := line.new(pivotTime, mid, confirmationTime, mid, xloc = xloc.bar_time, color = color.new(edge, 25), style = line.style_dashed, force_overlay = true)
string timing = "Pivot: " + str.format_time(pivotTime, "yyyy-MM-dd HH:mm", syminfo.timezone) + "\nFirst known: " + str.format_time(confirmationClose, "yyyy-MM-dd HH:mm", syminfo.timezone) + " " + syminfo.timezone + "\nBox drawn back to pivot for context. Block appears only at confirmation."
if showBlockLabels
tag := label.new(confirmationTime, bull ? bottom : top, bull ? "Bullish block" : "Bearish block", xloc = xloc.bar_time, style = bull ? label.style_label_upper_left : label.style_label_lower_left, color = color.new(edge, 15), textcolor = color.white, size = labelSize, tooltip = timing, force_overlay = true)
if showFibs
for ratio in fibRatios
float price = f_fibPrice(bottom, top, bull, ratio)
bool highlighted = f_contains(highlightRatios, ratio)
color ink = highlighted ? highlightColor : fibColor
string stroke = highlighted ? line.style_solid : showMidline and math.abs(ratio - 0.5) < 0.000001 ? line.style_dashed : line.style_dotted
array.push(fibLines, line.new(pivotTime, price, confirmationTime, price, xloc = xloc.bar_time, color = ink, style = stroke, width = highlighted ? 2 : 1, force_overlay = true))
if showFibLabels
string caption = str.tostring(ratio, "#.###") + (labelPrices ? " " + str.tostring(price, format.mintick) : "")
array.push(fibLabels, label.new(confirmationTime, price, caption, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = ink, size = labelSize, tooltip = str.tostring(price, format.mintick) + "\n" + timing, force_overlay = true))
Block.new(bull, bottom, top, confirmationTime, region, midpoint, tag, fibLines, fibLabels)
f_extend(Block block, int rightTime) =>
box.set_right(block.region, rightTime)
if not na(block.midpoint)
line.set_x2(block.midpoint, rightTime)
if not na(block.tag)
label.set_x(block.tag, rightTime)
for fibLine in block.fibLines
line.set_x2(fibLine, rightTime)
for fibLabel in block.fibLabels
label.set_x(fibLabel, rightTime)
var array<Block> blocks = array.new<Block>()
var array<float> strikes = array.new<float>()
var array<string> strikeNames = array.new<string>()
var array<line> gammaLines = array.new<line>()
var array<label> gammaLabels = array.new<label>()
var label gammaNotice = na
if barstate.isfirst
if not chart.is_standard or not (timeframe.isintraday or timeframe.isdaily)
runtime.error("Use standard candles on an intraday or daily time-based chart.")
if showGamma and not gmActive
for token in str.split(str.replace_all(gammaInput, "\n", ","), ",")
string cleaned = str.trim(token)
if str.length(cleaned) > 0
array<string> fields = str.split(cleaned, "|")
if array.size(fields) > 2
runtime.error("Gamma: use price|label, with one | per entry.")
float price = str.tonumber(str.trim(array.get(fields, 0)))
string suppliedName = array.size(fields) == 2 ? str.trim(array.get(fields, 1)) : ""
if na(price) or price <= 0
runtime.error("Gamma prices and optional labels: use entries such as 720|GEX 1. For options data, paste the complete file starting GAMMA1,QQQ,... into Gamma model > Compact options data and enable the gamma model. Raw CSV and Pine code are not accepted here.")
int existing = array.indexof(strikes, price)
if existing == -1
array.push(strikes, price)
array.push(strikeNames, suppliedName)
else if str.length(suppliedName) > 0
string previousName = array.get(strikeNames, existing)
if str.length(previousName) == 0
array.set(strikeNames, existing, suppliedName)
else if previousName != suppliedName
runtime.error("Gamma: duplicate price with different labels. Combine its labels in one entry, for example 730|GEX 1 / P1.")
if array.size(strikes) > 15
runtime.error("Use at most 15 unique gamma prices.")
// A block becomes known when its pivot confirms, not at the box's left edge.
float pivotHigh = ta.pivothigh(high, strength, strength)
float pivotLow = ta.pivotlow(low, strength, strength)
if barstate.isconfirmed
int index = array.size(blocks) - 1
while index >= 0
Block block = array.get(blocks, index)
if f_invalid(block.bull, block.bottom, block.top, close)
f_destroy(block)
array.remove(blocks, index)
index -= 1
float o = open[strength]
float h = high[strength]
float l = low[strength]
float c = close[strength]
int pivotTime = time[strength]
if bullishEnabled and not na(pivotLow) and f_qualifies(o, h, l, c, true)
float bottom = l
float top = math.min(o, c)
if close >= bottom and (not skipOverlap or not f_overlaps(blocks, true, bottom, top))
if array.size(blocks) >= maxBlocks
f_destroy(array.shift(blocks))
Block newBlock = f_create(true, bottom, top, pivotTime, time, time_close)
array.push(blocks, newBlock)
if bearishEnabled and not na(pivotHigh) and f_qualifies(o, h, l, c, false)
float bottom = math.max(o, c)
float top = h
if close <= top and (not skipOverlap or not f_overlaps(blocks, false, bottom, top))
if array.size(blocks) >= maxBlocks
f_destroy(array.shift(blocks))
Block newBlock = f_create(false, bottom, top, pivotTime, time, time_close)
array.push(blocks, newBlock)
if barstate.islast
for block in blocks
f_extend(block, extendRight ? time : block.confirmedTime)
// Static levels extend across older bars too; they are not historical observations.
if barstate.islast
for ln in gammaLines
line.delete(ln)
for lb in gammaLabels
label.delete(lb)
array.clear(gammaLines)
array.clear(gammaLabels)
label.delete(gammaNotice)
gammaNotice := na
if showGamma and not gmActive
string problem = ""
if array.size(strikes) == 0
problem := "Paste selected gamma prices in Settings"
else if str.upper(str.trim(gammaTicker)) != syminfo.ticker
problem := "Snapshot ticker must match this chart"
int labelBar = bar_index + gammaLabelOffset
if str.length(problem) > 0
gammaNotice := label.new(labelBar, close, "Gamma: " + problem, xloc = xloc.bar_index, style = label.style_label_left, color = color.new(chart.bg_color, 0), textcolor = color.orange, size = size.small, tooltip = "Enable gamma, match the ticker and paste selected prices. Blocks remain available.", force_overlay = true)
else
for [i, strike] in strikes
array.push(gammaLines, line.new(bar_index, strike, bar_index + 1, strike, xloc = xloc.bar_index, extend = extend.both, color = gammaColor, style = line.style_dashed, width = 2, force_overlay = true))
if showGammaLabels
float labelY = strike + (gammaLabelSide == "Above" ? 1 : -1) * gammaGapTicks * syminfo.mintick
string gammaStyle = gammaLabelSide == "Above" ? label.style_label_lower_left : label.style_label_upper_left
string suppliedName = array.get(strikeNames, i)
string caption = (str.length(suppliedName) > 0 ? suppliedName : "Gamma ref") + " | " + str.tostring(strike, format.mintick)
array.push(gammaLabels, label.new(labelBar, labelY, caption, xloc = xloc.bar_index, yloc = yloc.price, style = gammaStyle, color = color.new(chart.bg_color, 0), textcolor = gammaColor, size = size.small, force_overlay = true))
float ema1 = ta.ema(close, ema1Length)
float ema2 = ta.ema(close, ema2Length)
float ema3 = ta.ema(close, ema3Length)
float ema4 = ta.ema(close, ema4Length)
plot(showEMAs ? ema1 : na, "EMA 1", color = ema1Color, linewidth = 2, format = format.price, force_overlay = true, display = display.all - display.status_line)
plot(showEMAs ? ema2 : na, "EMA 2", color = ema2Color, linewidth = 2, format = format.price, force_overlay = true, display = display.all - display.status_line)
plot(showEMAs ? ema3 : na, "EMA 3", color = ema3Color, linewidth = 2, format = format.price, force_overlay = true, display = display.all - display.status_line)
plot(showEMAs ? ema4 : na, "EMA 4", color = ema4Color, linewidth = 2, format = format.price, force_overlay = true, display = display.all - display.status_line)
// Each timeframe uses its own EMAs. Readings can change before its bar closes.
f_trendPayload() =>
float e1 = ta.ema(close, ema1Length)
float e2 = ta.ema(close, ema2Length)
float e3 = ta.ema(close, ema3Length)
float e4 = ta.ema(close, ema4Length)
int requiredBars = math.max(math.max(ema1Length, ema2Length), math.max(ema3Length, ema4Length))
bool ready = bar_index + 1 >= requiredBars and not na(e1) and not na(e2) and not na(e3) and not na(e4)
bool bull = close > e1 and e1 > e2 and e2 > e3 and e3 > e4
bool bear = close < e1 and e1 < e2 and e2 < e3 and e3 < e4
int bias = ready ? (bull ? 1 : bear ? -1 : 0) : na
int side = ready ? (close > e4 ? 1 : close < e4 ? -1 : 0) : na
[bias, side, time_close]
[bias1m, side1m, end1m] = request.security(syminfo.tickerid, "1", f_trendPayload(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[bias5m, side5m, end5m] = request.security(syminfo.tickerid, "5", f_trendPayload(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[bias15m, side15m, end15m] = request.security(syminfo.tickerid, "15", f_trendPayload(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[bias30m, side30m, end30m] = request.security(syminfo.tickerid, "30", f_trendPayload(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[bias1h, side1h, end1h] = request.security(syminfo.tickerid, "60", f_trendPayload(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[bias4h, side4h, end4h] = request.security(syminfo.tickerid, "240", f_trendPayload(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[bias1d, side1d, end1d] = request.security(syminfo.tickerid, "1D", f_trendPayload(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[bias1w, side1w, end1w] = request.security(syminfo.tickerid, "1W", f_trendPayload(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
// RVOL excludes the measured candle from its baseline.
float priorVolumeAverage = ta.sma(volume[1], volumeLength)
float priorVolumeCoverage = ta.sma(na(volume[1]) ? 0.0 : 1.0, volumeLength)
float closedVolume = barstate.isconfirmed ? volume : volume[1]
float closedVolumeAverage = barstate.isconfirmed ? priorVolumeAverage : priorVolumeAverage[1]
float closedVolumeCoverage = barstate.isconfirmed ? priorVolumeCoverage : priorVolumeCoverage[1]
int volumeBarEnd = barstate.isconfirmed ? time_close : time_close[1]
bool volumeReady = not na(closedVolume) and closedVolume >= 0 and not na(closedVolumeAverage) and closedVolumeAverage > 0 and not na(closedVolumeCoverage) and closedVolumeCoverage == 1.0
float relativeVolume = volumeReady ? closedVolume / closedVolumeAverage : na
f_biasInk(int bias) =>
na(bias) ? color.gray : bias == 1 ? color.rgb(0, 150, 110) : bias == -1 ? color.rgb(215, 60, 75) : color.orange
f_biasName(int bias) =>
na(bias) ? "Warming / N/A" : bias == 1 ? "Bullish" : bias == -1 ? "Bearish" : "Mixed"
f_sideName(int side) =>
na(side) ? "N/A" : side == 1 ? "Above" : side == -1 ? "Below" : "At"
// One table: gamma (0-3), gap (4), EMAs and trends (5-6).
color panelBg = color.rgb(15, 19, 27)
color panelAlt = color.rgb(21, 27, 37)
color panelHeader = color.rgb(31, 41, 55)
color panelText = color.rgb(226, 232, 240)
color panelMuted = color.rgb(148, 163, 184)
var table dashboard = table.new(dashboardLocation, 7, 16, bgcolor = color.new(panelBg, 100), frame_width = 0, border_width = 0, force_overlay = true)
f_dashCell(int column, int row, string cellText, color ink, string tip, bool heading) =>
color shade = heading ? panelHeader : row % 2 == 0 ? panelBg : panelAlt
string alignment = column < 4 ? text.align_center : column == 6 ? text.align_right : text.align_left
table.cell(dashboard, column, row, cellText, bgcolor = shade, text_color = ink, text_size = dashboardTextSize, text_halign = alignment, tooltip = column < 4 ? "" : tip)
f_dashPair(int row, string title, string value, color ink, string tip) =>
f_dashCell(5, row, title, panelText, tip, false)
f_dashCell(6, row, value, ink, tip, false)
f_dashEMA(int row, int length, float value, color ink) =>
f_dashPair(row, "EMA " + str.tostring(length), na(value) ? "N/A" : str.tostring(value, format.mintick), ink, "EMA on the current chart timeframe. Changes while the current candle forms.")
f_dashTrend(int row, string tfName, int bias, int barEnd) =>
string tip = "Bullish: price > EMA 1 > EMA 2 > EMA 3 > EMA 4. Bearish: reverse order. Otherwise Mixed. Requires at least the longest EMA length in bars. Latest readings may change before close or after reload. Lower timeframes use the latest available intrabar."
if not na(barEnd)
tip += "\nBar ends: " + str.format_time(barEnd, "yyyy-MM-dd HH:mm", syminfo.timezone) + " " + syminfo.timezone
color ink = na(bias) ? panelMuted : bias == 1 ? color.rgb(45, 212, 167) : bias == -1 ? color.rgb(251, 113, 133) : color.rgb(251, 191, 36)
f_dashPair(row, tfName, f_biasName(bias), ink, tip)
f_dashGammaHeader() =>
f_dashCell(0, 0, "Strike", panelText, "", true)
f_dashCell(1, 0, "Gross %", panelText, "", true)
f_dashCell(2, 0, "Top 3 / 45", panelText, "", true)
f_dashCell(3, 0, "Sensitivity", panelText, "", true)
f_dashGammaMessage(string message) =>
f_dashGammaHeader()
f_dashCell(0, 1, message, color.orange, "", false)
for col = 1 to 3
f_dashCell(col, 1, "—", panelMuted, "", false)
if barstate.islast
table.clear(dashboard, 0, 0, 6, 15)
if showDashboard
if gmActive and gmShowPanel
table.cell(dashboard, 4, 0, "", width = 1, bgcolor = color.new(panelBg, 100))
f_dashCell(5, 0, "CHART EMAs", panelText, "Current chart EMA prices.", true)
f_dashCell(6, 0, "PRICE", panelMuted, "Current chart EMA prices.", true)
f_dashEMA(1, ema1Length, ema1, ema1Color)
f_dashEMA(2, ema2Length, ema2, ema2Color)
f_dashEMA(3, ema3Length, ema3, ema3Color)
f_dashEMA(4, ema4Length, ema4, color.rgb(203, 213, 225))
f_dashCell(5, 5, "TIMEFRAME", panelText, "Trend uses the selected four EMA lengths.", true)
f_dashCell(6, 5, "TREND", panelMuted, "Hover over any trend for its rules and bar time.", true)
f_dashTrend(6, "1m", bias1m, end1m)
f_dashTrend(7, "5m", bias5m, end5m)
f_dashTrend(8, "15m", bias15m, end15m)
f_dashTrend(9, "30m", bias30m, end30m)
f_dashTrend(10, "1h", bias1h, end1h)
f_dashTrend(11, "4h", bias4h, end4h)
f_dashTrend(12, "Daily", bias1d, end1d)
f_dashTrend(13, "Weekly", bias1w, end1w)
if showVolumeSummary
string liveTip = "Current candle volume; updates while the candle forms. Colors follow candle direction, not buy/sell transactions."
string closedTip = "Latest completed candle volume divided by the average of its preceding " + str.tostring(volumeLength) + " candles. Not adjusted for time of day or session changes."
if not na(volumeBarEnd)
closedTip += "\nMeasured candle ends: " + str.format_time(volumeBarEnd, "yyyy-MM-dd HH:mm", syminfo.timezone) + " " + syminfo.timezone
f_dashPair(14, "VOLUME", na(volume) ? "N/A" : str.tostring(volume, format.volume), panelText, liveTip)
f_dashPair(15, "RVOL (closed)", na(relativeVolume) ? "N/A" : str.tostring(relativeVolume, "0.00") + "x", na(relativeVolume) ? panelMuted : relativeVolume >= highVolumeRatio ? color.rgb(251, 191, 36) : panelText, closedTip)
// Volume has its own scale; force_overlay keeps price drawings on the chart scale.
bool volumeHigh = not na(volume) and not na(priorVolumeAverage) and priorVolumeAverage > 0 and priorVolumeCoverage == 1.0 and volume >= priorVolumeAverage * highVolumeRatio
color volumeBase = close > open ? volumeUpColor : close < open ? volumeDownColor : color.rgb(148, 163, 184)
color volumeInk = color.new(volumeBase, volumeHigh ? math.max(volumeTransparency - 15, 0) : volumeTransparency)
float volumeBars = showVolumeBars ? volume : na
float volumeMean = showVolumeAverage and priorVolumeCoverage == 1.0 ? priorVolumeAverage : na
plot(volumeBars, "Volume", color = volumeInk, style = plot.style_columns, histbase = 0, display = display.pane + display.data_window)
plot(volumeMean, "Previous volume average", color = color.rgb(251, 191, 36), linewidth = 1, display = display.pane + display.data_window)
// Invisible plots reserve volume headroom. display.none would disable autoscaling.
bool hasVolumeVisual = not na(volumeBars) or not na(volumeMean)
float volumeExtent = hasVolumeVisual ? math.max(nz(volumeBars), nz(volumeMean)) : na
plot(hasVolumeVisual ? 0.0 : na, "Volume floor", color = na, editable = false, display = display.pane)
plot(volumeExtent * 100.0 / volumeHeight, "Volume headroom", color = na, editable = false, display = display.pane)
// BSM gamma with continuous dividend yield; an approximation for American options.
gm_gamma(float s, float k, float t, float iv, float r, float q) =>
float d1 = (math.log(s / k) + (r - q + iv * iv / 2.0) * t) / (iv * math.sqrt(t))
math.exp(-q * t - d1 * d1 / 2.0) / (math.sqrt(6.283185307179586) * s * iv * math.sqrt(t))
gm_weight(float s, float k, float t, float co, float ci, float po, float pi, float ivFactor, float r, float q, float mult) =>
float callPart = 0.0
float putPart = 0.0
if co > 0
callPart := co * gm_gamma(s, k, t, ci * ivFactor, r, q)
if po > 0
putPart := po * gm_gamma(s, k, t, pi * ivFactor, r, q)
(callPart + putPart) * mult
gm_number(array<string> fields, int index) =>
float value = str.tonumber(str.trim(array.get(fields, index)))
if na(value) or math.abs(value) > 1e15
runtime.error("Gamma model: invalid numeric input.")
value
// Sorted strikes make ties favor the lower strike.
gm_best(array<float> values, int skip1, int skip2) =>
int best = -1
float biggest = 0.0
for i = 0 to array.size(values) - 1
float v = array.get(values, i)
if i != skip1 and i != skip2 and v > biggest
best := i
biggest := v
best
var array<float> gmK = array.new<float>()
var array<float> gmCO = array.new<float>()
var array<float> gmCI = array.new<float>()
var array<float> gmPO = array.new<float>()
var array<float> gmPI = array.new<float>()
var int gmStamp = na
var int gmExpiry = na
var float gmSpot = na
var float gmMult = na
var float gmTotalOI = na
var float gmImportedOI = 0.0
var string gmTicker = ""
var array<line> gmLines = array.new<line>()
var array<label> gmLabels = array.new<label>()
if barstate.isfirst and gmActive and str.length(gmPayload) > 0
array<string> gmRows = str.split(gmPayload, "\n")
array<string> gmHeader = str.split(array.get(gmRows, 0), ",")
if array.size(gmHeader) != 9
runtime.error("Gamma model: paste the full GAMMA1 file with its nine-field header.")
if str.trim(array.get(gmHeader, 0)) != "GAMMA1"
runtime.error("Gamma model: expected GAMMA1 compact data, not price labels or raw CSV.")
gmTicker := str.upper(str.trim(array.get(gmHeader, 1)))
float stampValue = gm_number(gmHeader, 2)
float expiryValue = gm_number(gmHeader, 3)
gmStamp := int(stampValue)
gmExpiry := int(expiryValue)
gmSpot := gm_number(gmHeader, 4)
gmMult := gm_number(gmHeader, 5)
gmTotalOI := gm_number(gmHeader, 6)
float expectedOI = gm_number(gmHeader, 7)
float expectedRows = gm_number(gmHeader, 8)
if gmStamp != stampValue or gmExpiry != expiryValue or gmStamp < 946684800000 or gmExpiry <= gmStamp or gmExpiry - gmStamp > 315360000000 or gmSpot <= 0 or gmMult <= 0 or gmMult > 10000 or expectedOI <= 0 or gmTotalOI < expectedOI or expectedRows < 1 or expectedRows > 400 or expectedRows != math.floor(expectedRows)
runtime.error("Gamma model: invalid header values or expiry before snapshot.")
if array.size(gmRows) < 2 or array.size(gmRows) > 402
runtime.error("Gamma model: expected 1-400 compact strike rows.")
float lastK = 0.0
for rowIndex = 1 to array.size(gmRows) - 1
string rowText = str.trim(array.get(gmRows, rowIndex))
if str.length(rowText) > 0
array<string> fields = str.split(rowText, ",")
if array.size(fields) != 5
runtime.error("Gamma model: each row must be strike,callOI,callIV,putOI,putIV.")
float k = gm_number(fields, 0)
float co = gm_number(fields, 1)
float ci = gm_number(fields, 2)
float po = gm_number(fields, 3)
float pi = gm_number(fields, 4)
if k <= lastK or k > 1e7 or co < 0 or po < 0 or co > 1e9 or po > 1e9 or co != math.floor(co) or po != math.floor(po) or co + po <= 0 or ci < 0 or pi < 0 or ci > 10 or pi > 10 or (co > 0 and ci <= 0) or (po > 0 and pi <= 0)
runtime.error("Gamma model: invalid OI/IV or unsorted/duplicate strikes.")
array.push(gmK, k)
array.push(gmCO, co)
array.push(gmCI, ci)
array.push(gmPO, po)
array.push(gmPI, pi)
gmImportedOI += co + po
lastK := k
if array.size(gmK) != expectedRows or gmImportedOI != expectedOI
runtime.error("Gamma model: incomplete or changed data. Row count/OI do not match header.")
gm_calculate(float s, float remainingHours, float horizon, array<float> ks, array<float> cos, array<float> cis, array<float> pos, array<float> pis, float mult) =>
int n = array.size(ks)
array<float> base = array.new<float>(n, 0.0)
array<float> slopes = array.new<float>(n, 0.0)
matrix<float> weights = matrix.new<float>(n, 45, 0.0)
array<float> totals = array.new<float>(45, 0.0)
float baseTotal = 0.0
float h = math.max(s * 0.0001, 0.01)
float years = remainingHours / 8760.0
// Five prices x three times x three IV multipliers.
for i = 0 to n - 1
float k = array.get(ks, i)
float co = array.get(cos, i)
float ci = array.get(cis, i)
float po = array.get(pos, i)
float pi = array.get(pis, i)
float b = gm_weight(s, k, years, co, ci, po, pi, 1.0, gmRate, gmYield, mult)
array.set(base, i, b)
baseTotal += b
float plus = gm_weight(s + h, k, years, co, ci, po, pi, 1.0, gmRate, gmYield, mult)
float minus = gm_weight(s - h, k, years, co, ci, po, pi, 1.0, gmRate, gmYield, mult)
array.set(slopes, i, (plus - minus) / (2.0 * h))
for scenario = 0 to 44
int moveIndex = int(math.floor(scenario / 9.0))
int hourIndex = int(math.floor((scenario % 9) / 3.0))
int ivIndex = scenario % 3
float scenarioS = s * (1.0 + (moveIndex - 2) * gmMove / 2.0)
float scenarioT = (remainingHours - hourIndex * horizon / 2.0) / 8760.0
float factor = 1.0 + (ivIndex - 1) * gmIVMove
float w = gm_weight(scenarioS, k, scenarioT, co, ci, po, pi, factor, gmRate, gmYield, mult)
matrix.set(weights, i, scenario, w)
array.set(totals, scenario, array.get(totals, scenario) + w)
array<float> means = array.new<float>(n, 0.0)
array<float> m2 = array.new<float>(n, 0.0)
array<int> topCounts = array.new<int>(n, 0)
int validCount = 0
for scenario = 0 to 44
float total = array.get(totals, scenario)
if total > 0
validCount += 1
array<float> column = array.new<float>(n, 0.0)
for i = 0 to n - 1
float w = matrix.get(weights, i, scenario)
array.set(column, i, w)
float fraction = w / total
// Welford variance of scenario shares.
float delta = fraction - array.get(means, i)
float mean = array.get(means, i) + delta / validCount
array.set(means, i, mean)
array.set(m2, i, array.get(m2, i) + delta * (fraction - mean))
int first = gm_best(column, -1, -1)
int secondIdx = gm_best(column, first, -1)
int third = gm_best(column, first, secondIdx)
for idx in array.from(first, secondIdx, third)
if idx >= 0
array.set(topCounts, idx, array.get(topCounts, idx) + 1)
array<float> deviations = array.new<float>(n, na)
if validCount > 0
for i = 0 to n - 1
array.set(deviations, i, math.sqrt(math.max(0.0, array.get(m2, i) / validCount)))
[base, baseTotal, slopes, means, deviations, topCounts, validCount]
// Draw the latest model state.
if barstate.islast
for ln in gmLines
line.delete(ln)
for lb in gmLabels
label.delete(lb)
array.clear(gmLines)
array.clear(gmLabels)
if gmActive
bool preview = gmMode == "Snapshot preview"
int clockTime = preview ? gmStamp : timenow
float modelSpot = preview ? gmSpot : close
bool showModelRows = showDashboard and gmShowPanel
string problem = ""
if array.size(gmK) == 0
problem := "Paste compact options data"
else if gmTicker != syminfo.ticker
problem := "Imported ticker must match chart"
else if not preview and timenow < gmStamp
problem := "Snapshot header is in the future"
else if not preview and clockTime >= gmExpiry
problem := "Expiry reached: import a new chain"
else if not preview and time_close < gmStamp
problem := "Chart predates snapshot: use preview"
else if na(modelSpot) or modelSpot <= 0
problem := "No positive reference price"
if str.length(problem) > 0
if showModelRows
f_dashGammaMessage(array.size(gmK) == 0 ? "Add data" : "Unavailable")
else
float remainingHours = (gmExpiry - clockTime) / 3600000.0
float horizon = math.min(gmHours, remainingHours * 0.8)
[base, total, slopes, means, deviations, topCounts, validCount] = gm_calculate(modelSpot, remainingHours, horizon, gmK, gmCO, gmCI, gmPO, gmPI, gmMult)
bool valid = total > 0 and validCount == 45
if not valid
if showModelRows
f_dashGammaMessage("Unavailable")
else
if showModelRows
f_dashGammaHeader()
array<float> ranking = array.copy(base)
for rank = 0 to math.min(gmLineCount, array.size(base)) - 1
int i = gm_best(ranking, -1, -1)
if i >= 0
array.set(ranking, i, -1.0)
float k = array.get(gmK, i)
float share = array.get(base, i) / total * 100.0
float sensitivity = array.get(slopes, i) / array.get(base, i) * 100.0
string topText = str.tostring(array.get(topCounts, i)) + "/45"
int right = bar_index + gammaLabelOffset
array.push(gmLines, line.new(math.max(0, bar_index - 50), k, right, k, xloc = xloc.bar_index, extend = extend.right, color = gammaColor, width = 2, style = line.style_dashed, force_overlay = true))
if showGammaLabels
float y = k + (gammaLabelSide == "Above" ? 1.0 : -1.0) * gammaGapTicks * syminfo.mintick
string labelStyle = gammaLabelSide == "Above" ? label.style_label_lower_left : label.style_label_upper_left
string caption = "GEX " + str.tostring(rank + 1) + " | " + str.tostring(k, format.mintick)
array.push(gmLabels, label.new(right, y, caption, xloc = xloc.bar_index, yloc = yloc.price, style = labelStyle, color = color.new(chart.bg_color, 0), textcolor = gammaColor, size = size.small, force_overlay = true))
if showModelRows and rank < 5
f_dashCell(0, 1 + rank, str.tostring(k, format.mintick), color.white, "", false)
f_dashCell(1, 1 + rank, str.tostring(share, "#.0") + "%", color.aqua, "", false)
f_dashCell(2, 1 + rank, topText, panelMuted, "", false)
f_dashCell(3, 1 + rank, str.tostring(sensitivity, "#.0") + "%/$", panelMuted, "", false)