本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// =============================================================================
// Gamma Levels - horizontal levels from a pasted CSV (multi-instrument)
// + S/R & Supply/Demand ZONES (boxes)
//
// - Two level sets: SPX/ES and NDX/NQ. The script detects the chart symbol
// and shows the matching set:
// SPX, ES, MES, US500 -> SPX set NDX, NQ, MNQ, US100 -> NDX set
// Paste each CSV once, then switch symbols freely.
// - On a futures chart (ES, NQ) the basis (futures - index) is added
// automatically (measured live against the index, or a manual fallback).
// - Expected format (the header line is ignored automatically):
// Price Level,Note,Foreground Color,Background Color
// 7807,Call Resistance,yellow,black
// Accepted record separators: new line, ';' or '|'
//
// - NEW: a separate "ZONES" text area for Support/Resistance and
// Supply/Demand zones. Each zone is a price RANGE drawn as lines
// (width 6): BLACK for Support/Resistance, BLUE for Supply/Demand:
// Price zone,Note,Foreground Color,Background Color
// 30370-30380,Resistance-1H,white,black
// The range is detected from "low-high" in the first CSV field.
// =============================================================================
indicator("Gamma Levels", "GEX Levels", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
// -----------------------------------------------------------------------------
// 0. Instrument
// -----------------------------------------------------------------------------
string gInst = "0. Instrument"
instMode = input.string("Auto (detect from chart)", "Level set", group = gInst,
options = ["Auto (detect from chart)", "SPX (index)", "ES (futures)", "NDX (index)", "NQ (futures)"],
tooltip = "Auto: SPX, ES, MES, US500 -> SPX levels; NDX, NQ, MNQ, US100 -> NDX levels. The basis is applied on futures charts only (ES, MES, NQ, MNQ); CFDs are treated as the cash index. Force a choice if the symbol is not recognized or if your CFD tracks the futures.")
unitsIn = input.string("Index (SPX / NDX)", "Pasted levels are in", group = gInst,
options = ["Index (SPX / NDX)", "Futures (ES / NQ)"],
tooltip = "Index: you paste the SPX and NDX CSVs (recommended), the script adds the basis on ES/NQ. Futures: you paste already-converted ES and NQ CSVs, the script removes the basis on SPX/NDX.")
basisMode = input.string("Auto (live measurement)", "Basis (futures - index)", group = gInst,
options = ["Auto (live measurement)", "Manual"],
tooltip = "Auto: ES - SPX (or NQ - NDX) measured on the last bar where both trade (cash session); outside the session the last measurement is kept. If unavailable, the manual basis is used.")
showBadge = input.bool(true, "Show status badge", group = gInst,
tooltip = "Small box: active level set, basis in use, number of levels displayed.")
badgePos = input.string("Top right", "Badge position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = gInst)
// -----------------------------------------------------------------------------
// 1. SPX / ES levels
// -----------------------------------------------------------------------------
string gSpx = "1. SPX / ES levels"
spxText = input.text_area(
defval = "Price Level,Note,Foreground Color,Background Color\n7807,Call Resistance,yellow,black\n7687,1D Max,yellow,black\n7672,Neg Gamma 2,yellow,black\n7667,Call Resistance 0DTE,yellow,black\n7634,1D Min,yellow,black\n7622,GEX 2,yellow,black\n7607,Put Support,yellow,black\n7602,Neg Gamma 0DTE,yellow,black\n7499,HVL 0DTE,yellow,black\n7470,HVL,yellow,black",
title = "SPX levels (paste your CSV here)",
tooltip = "One line per level: Price,Note,TextColor,BackgroundColor\nThe header line and lines starting with # are ignored.",
group = gSpx)
spxBasisMan = input.float(0.0, "Manual basis ES - SPX", step = 0.25, group = gSpx,
tooltip = "Used when the basis mode is Manual, or when the live measurement is unavailable.")
spxIdxSym = input.symbol("SP:SPX", "S&P 500 index symbol", group = gSpx,
tooltip = "Used to measure the live basis when the chart is ES.")
spxFutSym = input.symbol("CME_MINI:ES1!", "ES futures symbol", group = gSpx,
tooltip = "Used to measure the live basis when the chart is SPX.")
// -----------------------------------------------------------------------------
// 2. NDX / NQ levels
// -----------------------------------------------------------------------------
string gNdx = "2. NDX / NQ levels"
ndxText = input.text_area(
defval = "Price Level,Note,Foreground Color,Background Color",
title = "NDX levels (paste your CSV here)",
tooltip = "One line per level: Price,Note,TextColor,BackgroundColor\nThe header line and lines starting with # are ignored.",
group = gNdx)
ndxBasisMan = input.float(0.0, "Manual basis NQ - NDX", step = 0.25, group = gNdx,
tooltip = "Used when the basis mode is Manual, or when the live measurement is unavailable.")
ndxIdxSym = input.symbol("NASDAQ:NDX", "Nasdaq 100 index symbol", group = gNdx,
tooltip = "Used to measure the live basis when the chart is NQ.")
ndxFutSym = input.symbol("CME_MINI:NQ1!", "NQ futures symbol", group = gNdx,
tooltip = "Used to measure the live basis when the chart is NDX.")
// -----------------------------------------------------------------------------
// 2b. Support / Resistance & Supply / Demand ZONES (boxes)
// -----------------------------------------------------------------------------
string gZone = "2b. S/R & Supply/Demand zones"
zonesText = input.text_area(
defval = "Price zone,Note,Foreground Color,Background Color\n30370-30380,Resistance-1H,white,black\n30470-30487,Resistance-5min,white,black\n30370-30380,support-30min,white,black\n30340-30350,Supply-1H,white,black\n30370-30380,demande-1H,white,black",
title = "Zones (paste your CSV here)",
tooltip = "One line per zone: PriceRange,Note,TextColor,BackgroundColor\nThe range is written low-high (e.g. 30370-30380).\nThe header line and lines starting with # are ignored.",
group = gZone)
srColor = input.color(color.black, "Support / Resistance line color", group = gZone)
sdColor = input.color(color.blue, "Supply / Demand line color", group = gZone)
zoneWidth = input.int(6, "Zone line width", minval = 1, maxval = 10, group = gZone)
zoneDraw = input.string("Bounds (2 lines)", "Zone drawing", options = ["Bounds (2 lines)", "Middle (1 line)"], group = gZone,
tooltip = "Bounds: one line on the low and one on the high of the zone. Middle: a single line at the middle of the zone.")
zoneShowLabel = input.bool(true, "Show zone labels", group = gZone)
zoneLabelTransp = input.int(0, "Label background transparency (%)", minval = 0, maxval = 100, group = gZone)
// Supply/Demand if the note contains supply / demand / demande / offre, otherwise Support/Resistance
isSupplyDemand(string note) =>
string n = str.lower(note)
str.contains(n, "supply") or str.contains(n, "demand") or str.contains(n, "offre")
// -----------------------------------------------------------------------------
// 3. Merge / filter
// -----------------------------------------------------------------------------
string gFlt = "3. Merge / filter"
mergeSame = input.bool(true, "Merge identical levels", group = gFlt,
tooltip = "Groups the notes of levels sharing the same price on a single line.")
mergeTol = input.float(0.0, "Merge tolerance (points)", minval = 0, step = 0.25, group = gFlt)
maxDistPct = input.float(0.0, "Hide if distance > (%)", minval = 0, step = 0.1, group = gFlt,
tooltip = "0 = show everything. Otherwise hides levels too far from the current price.")
// -----------------------------------------------------------------------------
// 4. Lines
// -----------------------------------------------------------------------------
string gLine = "4. Lines"
lineWidth = input.int(1, "Width", minval = 1, maxval = 10, group = gLine)
lineStyleIn = input.string("Solid", "Style", options = ["Solid", "Dashed", "Dotted"], group = gLine)
lineTransp = input.int(0, "Transparency (%)", minval = 0, maxval = 100, group = gLine)
extendMode = input.string("Both sides", "Extend", options = ["Both sides", "Right only"], group = gLine)
// -----------------------------------------------------------------------------
// 5. Labels
// -----------------------------------------------------------------------------
string gLbl = "5. Labels"
showLabels = input.bool(true, "Show labels", group = gLbl)
showPrice = input.bool(true, "Show price", group = gLbl)
labelSide = input.string("Right", "Side", options = ["Right", "Left"], group = gLbl)
labelOffset = input.int(8, "Offset (bars)", minval = 0, maxval = 400, group = gLbl)
labelSizeIn = input.string("Normal", "Size", options = ["Tiny", "Small", "Normal", "Large"], group = gLbl)
labelTransp = input.int(15, "Background transparency (%)", minval = 0, maxval = 100, group = gLbl)
// -----------------------------------------------------------------------------
// 6. Colors
// -----------------------------------------------------------------------------
string gCol = "6. Colors"
overrideCol = input.bool(false, "Override with my colors", group = gCol,
tooltip = "Ignores the CSV color columns and applies the colors below.")
myLineCol = input.color(color.yellow, "Line color", group = gCol)
myTextCol = input.color(color.yellow, "Text color", group = gCol)
myBackCol = input.color(color.black, "Background color", group = gCol)
defTextCol = input.color(color.yellow, "Default text (if CSV incomplete)", group = gCol)
defBackCol = input.color(color.black, "Default background (if CSV incomplete)", group = gCol)
// =============================================================================
// Helpers
// =============================================================================
// Manual trim (spaces, tabs, carriage returns)
trimStr(string s) =>
string r = s
while str.length(r) > 0 and (str.startswith(r, " ") or str.startswith(r, "\t") or str.startswith(r, "\r"))
r := str.substring(r, 1)
while str.length(r) > 0 and (str.endswith(r, " ") or str.endswith(r, "\t") or str.endswith(r, "\r"))
r := str.substring(r, 0, str.length(r) - 1)
r
// Value of a hexadecimal digit, -1 if invalid
hexDigit(string ch) =>
int p = str.pos("0123456789abcdef", str.lower(ch))
na(p) ? -1 : p
// Converts "yellow", "#FFD700"... into a Pine color
parseColor(string raw, color fallback, int transp) =>
string k = str.lower(trimStr(raw))
color out = color(na)
if str.startswith(k, "#") and str.length(k) >= 7
int r = hexDigit(str.substring(k, 1, 2)) * 16 + hexDigit(str.substring(k, 2, 3))
int g = hexDigit(str.substring(k, 3, 4)) * 16 + hexDigit(str.substring(k, 4, 5))
int b = hexDigit(str.substring(k, 5, 6)) * 16 + hexDigit(str.substring(k, 6, 7))
if r >= 0 and g >= 0 and b >= 0
out := color.rgb(r, g, b, transp)
else
color named = switch k
"yellow" => color.yellow
"black" => color.black
"white" => color.white
"red" => color.red
"green" => color.green
"lime" => color.lime
"blue" => color.blue
"aqua" => color.aqua
"cyan" => color.aqua
"teal" => color.teal
"navy" => color.navy
"orange" => color.orange
"purple" => color.purple
"fuchsia" => color.fuchsia
"magenta" => color.fuchsia
"pink" => color.fuchsia
"maroon" => color.maroon
"olive" => color.olive
"gray" => color.gray
"grey" => color.gray
"silver" => color.silver
=> color(na)
if not na(named)
out := color.new(named, transp)
na(out) ? color.new(fallback, transp) : out
// "+41.25" / "-3.5"
fmtSigned(float v) =>
(v >= 0 ? "+" : "") + str.tostring(v, "#.##")
// =============================================================================
// Instrument detection
// =============================================================================
string tk = str.upper(syminfo.ticker)
string root = str.upper(syminfo.root)
bool isFutTp = syminfo.type == "futures"
bool autoSpx = (isFutTp and (root == "ES" or root == "MES")) or str.contains(tk, "SPX") or str.contains(tk, "US500") or str.contains(tk, "SP500")
bool autoNdx = (isFutTp and (root == "NQ" or root == "MNQ")) or str.contains(tk, "NDX") or str.contains(tk, "NAS100") or str.contains(tk, "US100") or str.contains(tk, "USTEC")
// Level set: "SPX", "NDX" or "" (unknown symbol)
// (ternaries rather than switch: the symbol passed to request.security must stay "simple")
bool isAuto = instMode == "Auto (detect from chart)"
bool forceSpx = instMode == "SPX (index)" or instMode == "ES (futures)"
bool forceNdx = instMode == "NDX (index)" or instMode == "NQ (futures)"
string fam = forceSpx ? "SPX" : forceNdx ? "NDX" : autoSpx ? "SPX" : autoNdx ? "NDX" : ""
// Is the chart a futures contract (-> basis to apply)? In Auto mode only real
// futures get the basis: CFDs such as SPREADEX:SPX or US500 usually track the
// cash index, so they are treated as the index. If your CFD tracks the futures,
// force "ES (futures)" / "NQ (futures)" in the settings.
bool chartFut = instMode == "ES (futures)" or instMode == "NQ (futures)" or (isAuto and syminfo.type == "futures")
bool unitsFut = unitsIn == "Futures (ES / NQ)"
int offSign = (chartFut ? 1 : 0) - (unitsFut ? 1 : 0) // +1 index->futures, -1 futures->index, 0 nothing to do
string idxName = fam == "NDX" ? "NDX" : "SPX"
string futName = fam == "NDX" ? "NQ" : "ES"
string levelsText = fam == "SPX" ? spxText : fam == "NDX" ? ndxText : ""
float basisMan = fam == "NDX" ? ndxBasisMan : spxBasisMan
// =============================================================================
// Live basis: query the "other" symbol (the index when the chart is the
// futures, the futures when the chart is the index) on the 1-minute timeframe,
// and keep the measurement only when its last bar is contemporaneous with the
// chart bar (i.e. during the cash session). Outside the session, the last
// measurement is kept.
// =============================================================================
string reqSym = fam == "NDX" ? (chartFut ? ndxIdxSym : ndxFutSym) : (chartFut ? spxIdxSym : spxFutSym)
[othC, othT] = request.security(reqSym, "1", [close, time], ignore_invalid_symbol = true)
var float basisAuto = na
int freshTol = timeframe.isseconds ? 60000 : 0
bool fresh = not na(othC) and not na(othT) and othT >= time - freshTol
if fresh and fam != ""
basisAuto := chartFut ? close - othC : othC - close
bool autoOK = basisMode == "Auto (live measurement)" and not na(basisAuto)
float basisUsed = autoOK ? basisAuto : basisMan
string basisSrc = autoOK ? "live" : basisMode == "Manual" ? "manual" : "manual, live n/a"
float priceOffset = offSign * basisUsed
// =============================================================================
// CSV parsing (once, on the first bar) - raw prices, without basis
// =============================================================================
var array<float> pxArr = array.new<float>()
var array<string> noteArr = array.new<string>()
var array<string> fgArr = array.new<string>()
var array<string> bgArr = array.new<string>()
// Zone arrays (raw prices, without basis): lo, hi, note, fg, bg
var array<float> zLoArr = array.new<float>()
var array<float> zHiArr = array.new<float>()
var array<string> zNoteArr = array.new<string>()
var array<string> zFgArr = array.new<string>()
var array<string> zBgArr = array.new<string>()
// Parse a "low-high" range string like "30370-30380" into lo and hi floats.
// Returns [lo, hi]; lo/hi are na when the field is invalid.
parseRange(string raw) =>
string s = trimStr(raw)
float lo = na
float hi = na
int d = str.pos(s, "-")
if d > 0
lo := str.tonumber(trimStr(str.substring(s, 0, d)))
hi := str.tonumber(trimStr(str.substring(s, d + 1)))
[lo, hi]
if barstate.isfirst
string flat = str.replace_all(str.replace_all(levelsText, ";", "\n"), "|", "\n")
array<string> rows = str.split(flat, "\n")
if array.size(rows) > 0
for i = 0 to array.size(rows) - 1
string row = trimStr(array.get(rows, i))
if str.length(row) == 0 or str.startswith(row, "#") or str.startswith(row, "//")
continue
array<string> f = str.split(row, ",")
float p = str.tonumber(trimStr(array.get(f, 0)))
// If the 1st field is not a number -> header line, skip it
if na(p)
continue
string note = array.size(f) > 1 ? trimStr(array.get(f, 1)) : ""
string fg = array.size(f) > 2 ? array.get(f, 2) : ""
string bg = array.size(f) > 3 ? array.get(f, 3) : ""
int hit = -1
if mergeSame and array.size(pxArr) > 0
for j = 0 to array.size(pxArr) - 1
if math.abs(array.get(pxArr, j) - p) <= mergeTol
hit := j
break
if hit >= 0
string prev = array.get(noteArr, hit)
if str.length(note) > 0 and not str.contains(prev, note)
array.set(noteArr, hit, str.length(prev) == 0 ? note : prev + " / " + note)
else
array.push(pxArr, p)
array.push(noteArr, note)
array.push(fgArr, fg)
array.push(bgArr, bg)
// Parse the zones CSV
string zFlat = str.replace_all(str.replace_all(zonesText, ";", "\n"), "|", "\n")
array<string> zRows = str.split(zFlat, "\n")
if array.size(zRows) > 0
for i = 0 to array.size(zRows) - 1
string row = trimStr(array.get(zRows, i))
if str.length(row) == 0 or str.startswith(row, "#") or str.startswith(row, "//")
continue
array<string> f = str.split(row, ",")
[zlo, zhi] = parseRange(array.get(f, 0))
// Skip if the range is invalid or not a number
if na(zlo) or na(zhi)
continue
float zzl = math.min(zlo, zhi)
float zzh = math.max(zlo, zhi)
string note = array.size(f) > 1 ? trimStr(array.get(f, 1)) : ""
string fg = array.size(f) > 2 ? array.get(f, 2) : ""
string bg = array.size(f) > 3 ? array.get(f, 3) : ""
array.push(zLoArr, zzl)
array.push(zHiArr, zzh)
array.push(zNoteArr, note)
array.push(zFgArr, fg)
array.push(zBgArr, bg)
// =============================================================================
// Rendering
// =============================================================================
var array<line> lineIds = array.new<line>()
var array<label> labelIds = array.new<label>()
var array<box> boxIds = array.new<box>()
lStyle = lineStyleIn == "Dashed" ? line.style_dashed : lineStyleIn == "Dotted" ? line.style_dotted : line.style_solid
lExt = extendMode == "Right only" ? extend.right : extend.both
lSize = switch labelSizeIn
"Tiny" => size.tiny
"Small" => size.small
"Large" => size.large
=> size.normal
tblPos = badgePos == "Top left" ? position.top_left : badgePos == "Bottom right" ? position.bottom_right : badgePos == "Bottom left" ? position.bottom_left : position.top_right
var table badge = table.new(tblPos, 1, 1)
if barstate.islast
// Clear the previous rendering
if array.size(lineIds) > 0
for i = 0 to array.size(lineIds) - 1
line.delete(array.get(lineIds, i))
array.clear(lineIds)
if array.size(labelIds) > 0
for i = 0 to array.size(labelIds) - 1
label.delete(array.get(labelIds, i))
array.clear(labelIds)
if array.size(boxIds) > 0
for i = 0 to array.size(boxIds) - 1
box.delete(array.get(boxIds, i))
array.clear(boxIds)
int nShown = 0
if array.size(pxArr) > 0
for i = 0 to array.size(pxArr) - 1
// Basis applied here (not at parsing time) so it follows the live measurement
float p = math.round_to_mintick(array.get(pxArr, i) + priceOffset)
// Distance filter
bool tooFar = maxDistPct > 0 and close > 0 and math.abs(p - close) / close * 100.0 > maxDistPct
if tooFar
continue
nShown += 1
color cLine = overrideCol ? color.new(myLineCol, lineTransp) : parseColor(array.get(fgArr, i), defTextCol, lineTransp)
color cText = overrideCol ? myTextCol : parseColor(array.get(fgArr, i), defTextCol, 0)
color cBack = overrideCol ? color.new(myBackCol, labelTransp) : parseColor(array.get(bgArr, i), defBackCol, labelTransp)
array.push(lineIds, line.new(
x1 = bar_index - 1,
y1 = p,
x2 = bar_index,
y2 = p,
xloc = xloc.bar_index,
extend = lExt,
color = cLine,
style = lStyle,
width = lineWidth))
if showLabels
string note = array.get(noteArr, i)
string txt = showPrice ? (str.length(note) > 0 ? note + " " + str.tostring(p, format.mintick) : str.tostring(p, format.mintick)) : (str.length(note) > 0 ? note : str.tostring(p, format.mintick))
int lx = labelSide == "Right" ? bar_index + labelOffset : math.max(0, bar_index - labelOffset)
lblStyle = labelSide == "Right" ? label.style_label_left : label.style_label_right
array.push(labelIds, label.new(
x = lx,
y = p,
text = txt,
xloc = xloc.bar_index,
style = lblStyle,
color = cBack,
textcolor = cText,
size = lSize))
// ---- Zones rendering (lines: black = Support/Resistance, blue = Supply/Demand) ----
int nZones = 0
if array.size(zLoArr) > 0
for i = 0 to array.size(zLoArr) - 1
float zlo = math.round_to_mintick(array.get(zLoArr, i) + priceOffset)
float zhi = math.round_to_mintick(array.get(zHiArr, i) + priceOffset)
string znote0 = array.get(zNoteArr, i)
color zCol = isSupplyDemand(znote0) ? sdColor : srColor
if zoneDraw == "Middle (1 line)"
float zm = math.round_to_mintick((zlo + zhi) / 2.0)
array.push(lineIds, line.new(bar_index - 1, zm, bar_index, zm, xloc = xloc.bar_index, extend = lExt, color = zCol, style = line.style_solid, width = zoneWidth))
else
array.push(lineIds, line.new(bar_index - 1, zhi, bar_index, zhi, xloc = xloc.bar_index, extend = lExt, color = zCol, style = line.style_solid, width = zoneWidth))
if zhi != zlo
array.push(lineIds, line.new(bar_index - 1, zlo, bar_index, zlo, xloc = xloc.bar_index, extend = lExt, color = zCol, style = line.style_solid, width = zoneWidth))
if zoneShowLabel
string znote = znote0
string ztxt = str.length(znote) > 0 ? znote : "Zone"
color zText = parseColor(array.get(zFgArr, i), color.white, 0)
color zBack = color.new(zCol, zoneLabelTransp)
string zMid = str.tostring((zlo + zhi) / 2.0, format.mintick)
int zlx = labelSide == "Right" ? bar_index + labelOffset : math.max(0, bar_index - labelOffset)
lblStyle = labelSide == "Right" ? label.style_label_left : label.style_label_right
array.push(labelIds, label.new(
x = zlx,
y = (zlo + zhi) / 2.0,
text = ztxt + " " + zMid,
xloc = xloc.bar_index,
style = lblStyle,
color = zBack,
textcolor = zText,
size = lSize))
nZones += 1
// Status badge
if showBadge
string bTxt = ""
if fam == ""
bTxt := "GEX Levels: symbol " + syminfo.ticker + " not recognized -> pick the level set in the settings (0. Instrument)"
else
string bBasis = ""
if offSign != 0
bBasis := " | basis " + futName + "-" + idxName + " " + fmtSigned(basisUsed) + " (" + basisSrc + ")"
else if autoOK
bBasis := " | basis " + futName + "-" + idxName + " " + fmtSigned(basisAuto) + " (live)"
bTxt := (unitsFut ? futName : idxName) + " levels" + (offSign != 0 ? " -> " + (chartFut ? futName : idxName) : "") + bBasis + " | " + str.tostring(nShown) + " levels" + " | " + str.tostring(nZones) + " zones"
table.cell(badge, 0, 0, bTxt, text_color = fam == "" ? color.red : color.yellow, text_size = size.small, bgcolor = color.new(color.black, 20))