本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tonngnh3
//@version=6
// PSF Fresh — Multi-Band Pivot Confluence
// Floor-trader pivots (PP, S1-S3, R1-R3) computed on Daily, Weekly, Monthly and an N-day band at
// the same time, so levels from different bands that stack close together are flagged as
// confluence. A volatility-regime read (developing range vs the prior completed range, weighted
// across D/W/M) classifies the session as Compression / Normal / Expansion / Extreme.
// Non-repainting: every higher-timeframe value comes from the prior COMPLETED period ([1] with
// lookahead_on); the developing range is accumulated from current and past chart bars only.
indicator("PSF Fresh — Multi-Band Pivot Confluence", "PSF", overlay=true, max_lines_count=500, max_labels_count=500)
// ───────────────────────── Inputs ─────────────────────────
gTF = "Timeframes"
useD = input.bool(true, "Daily", inline="d", group=gTF)
useW = input.bool(true, "Weekly", inline="w", group=gTF)
useM = input.bool(true, "Monthly", inline="m", group=gTF)
useMD = input.bool(true, "Multiday", inline="md", group=gTF)
mdTF = input.timeframe("3D", "N-day resolution", inline="md", group=gTF)
gLv = "Levels"
levelMode = input.string("Manual", "Level Mode", options=["Manual", "Smart"], group=gLv, tooltip="Manual = you control every band and level with the checkboxes below. Smart = ignores those checkboxes and maps the chart timeframe to a preset band set — 1m to 1H: EVERYTHING (Daily + Weekly + Monthly, all levels, no hiding); above 1H incl. Daily chart: Weekly + Monthly (PP, S1/R1); Weekly+: Monthly only. Above 1H it also hides levels far from price. Net effect: full detail zoomed in, fewer/closer/higher-timeframe levels as you zoom out. Switch to Manual for full control.")
showMid = input.bool(true, "Show PP (pivot)", group=gLv)
show12 = input.bool(true, "Show S1/R1, S2/R2", group=gLv)
show3 = input.bool(true, "Show S3/R3", group=gLv)
extRight = input.bool(true, "Extend right", inline="ext", group=gLv)
extLeft = input.bool(true, "Extend left", inline="ext", group=gLv)
neutralPivots = input.bool(false, "Neutral pivot lines (color stays in the tag)", group=gLv, tooltip="On = all pivot lines drawn in one neutral color to kill the multi-TF rainbow; the label tag keeps its per-timeframe color so you still read D/W/M/MD at a glance. Off = classic per-TF colored lines.")
pivotNeutralCol = input.color(color.silver, "Neutral line color", group=gLv)
nearRangeATR = input.float(4.0, "Near-price range (ATR)", minval=0.5, step=0.5, group=gLv, tooltip="Smart mode above 1H only. Hides any pivot more than this many ATRs from the current price. Lower = fewer lines, only the closest levels shown. Ignored in Manual mode and on 1m–1H charts (which show everything).")
gLbl = "Labels"
showLbl = input.bool(true, "Show labels", group=gLbl)
lblAnchor = input.string("Visible right edge", "Anchor", options=["Visible right edge", "Last bar"], group=gLbl)
lblSide = input.string("Right", "Side", options=["Right", "Left"], group=gLbl)
lblOff = input.int(2, "Offset (chart bars)", minval=0, maxval=200, group=gLbl)
lblSizeOpt = input.string("small", "Text size", options=["tiny", "small", "normal"], group=gLbl)
autoStagger = input.bool(true, "Auto-stagger overlapping labels", group=gLbl)
staggerATR = input.float(0.12, "Nearby threshold (ATR)", step=0.01, minval=0.0, maxval=1.0, group=gLbl)
staggerBars = input.int(3, "Stagger step (chart bars)", minval=1, maxval=50, group=gLbl)
staggerMax = input.int(12, "Maximum stagger slots", minval=1, maxval=28, group=gLbl)
gCf = "Confluence (cross-band)"
useConfl = input.bool(true, "Highlight stacked levels", group=gCf)
conflATR = input.float(0.20, "Stack threshold (ATR)", step=0.05, minval=0.01, group=gCf)
gR = "Volatility regime (NR composite)"
useRegime = input.bool(true, "Show regime + background", group=gR)
nrLen = input.int(20, "Range-average length", minval=2, group=gR)
wtD = input.float(0.72, "Daily weight", step=0.01, group=gR)
wtW = input.float(0.22, "Weekly weight", step=0.01, group=gR)
wtM = input.float(0.06, "Monthly weight", step=0.01, group=gR)
nrMode = input.string("Developing", "NR definition", options=["Developing", "Prior range vs average"], group=gR, tooltip="Which normalization ratio the regime uses. Developing = this period's DEVELOPING range divided by the prior period's completed range, i.e. is today expanding relative to yesterday. Updates intraday, which is what an NY-open read needs. Prior range vs average = the PRIOR period's range divided by its 20-period average range, i.e. was yesterday wide relative to typical. Smoother, but stale within the day. The regime cuts move with this setting automatically.")
gNY = "New York open"
markNY = input.bool(true, "Mark NY open (09:30 ET)", group=gNY)
nyCol = input.color(color.new(color.orange, 0), "NY open color", group=gNY)
gN = "Normalization table"
showTab = input.bool(true, "Show table", group=gN)
atrLen = input.int(14, "ATR length", minval=1, group=gN)
atrBasis = input.string("Daily", "Threshold ATR basis", options=["Daily", "Chart"], group=gN, tooltip="Which ATR scales the distance thresholds (confluence stacking, near-price highlight, level-touch tolerance, label stagger, Smart near-range). Daily (default) = the prior completed daily ATR, so a threshold means the same number of points on a 1m chart as on a daily one — correct, because the levels themselves are fixed D/W/M prices that do not change with your chart timeframe. Chart = scale by the chart ATR instead, which shrinks the thresholds ~26x when you drop from 1D to 15m and switches confluence detection off intraday.")
nearATR = input.float(0.25, "Near-price highlight (ATR)", step=0.05, minval=0.0, group=gN)
tabPos = input.string("top_right", "Table position", options=["top_right", "top_left", "bottom_right", "bottom_left"], group=gN)
tabSizeOpt = input.string("tiny", "Table text size", options=["tiny", "small", "normal"], group=gN)
gC = "Colors"
cD = input.color(color.new(color.aqua, 0), "Daily", group=gC)
cW = input.color(color.new(color.lime, 0), "Weekly", group=gC)
cM = input.color(color.new(color.fuchsia, 0), "Monthly", group=gC)
cMD = input.color(color.new(color.yellow, 0), "Multiday", group=gC)
gTr = "Trend filter"
emaTrendOn = input.bool(true, "Filter counter-trend levels", group=gTr)
emaMode = input.string("Persistent", "Counter-trend levels", options=["Dim", "Hide", "Persistent"], group=gTr)
emaFastLen = input.int(9, "EMA fast length (cloud)", minval=1, group=gTr)
emaLen = input.int(20, "EMA slow length (cloud + legacy trend line)", minval=1, group=gTr)
dimAmount = input.int(75, "Dim strength (counter-trend, 0-100)", minval=0, maxval=100, group=gTr)
gEc = "EMA Cloud + VWAP Zones"
showZones = input.bool(false, "Show EMA9/EMA20 cloud + VWAP zones", group=gEc)
showZoneLabels = input.bool(true, "Show BUY/SELL ZONE labels", group=gEc)
showZoneBg = input.bool(false, "Show zone background", group=gEc)
gMd = "MACD gate"
macdGateOn = input.bool(false, "Hide levels against MACD histogram", group=gMd)
macdFast = input.int(12, "Fast", minval=1, group=gMd)
macdSlow = input.int(26, "Slow", minval=1, group=gMd)
macdSig = input.int(9, "Signal", minval=1, group=gMd)
gVe = "Volatility emphasis"
atrEmphOn = input.bool(false, "Emphasize levels in ATR expansion", group=gVe)
atrEmphLen = input.int(14, "ATR length", minval=1, group=gVe)
atrEmphMaLen = input.int(50, "ATR MA length", minval=1, group=gVe)
gVc = "Volume confirmation"
volConfOn = input.bool(true, "Mark high-volume level touches", group=gVc)
volMarkerStyle = input.string("Circles", "Volume marker style", options=["Circles", "Triangles"], group=gVc)
volLen = input.int(20, "Volume MA length", minval=1, group=gVc)
volSpike = input.float(1.1, "Volume spike ×", step=0.05, minval=0.1, group=gVc)
volTouchATR = input.float(0.15, "Touch distance (ATR)", step=0.01, minval=0.0, group=gVc)
volDeltaCol = input.bool(true, "Color by delta (buy/sell)", group=gVc)
volUpCol = input.color(color.new(color.lime, 0), "Positive delta", inline="vcol", group=gVc)
volDnCol = input.color(color.new(color.red, 0), "Negative delta", inline="vcol", group=gVc)
// ───────────────────────── State ─────────────────────────
atr = ta.atr(atrLen)
// Prior COMPLETED daily ATR — [1] + lookahead_on, the same non-repaint pattern f_hlc
// and the NR averages use. scaleAtr is what every price-distance threshold multiplies, so
// those thresholds stop shrinking with the chart timeframe. nz() falls back to the chart ATR
// during daily warmup or on a symbol with no daily series, so nothing ever blanks.
[dh, dl, dc, atrDaily, dAvg] = request.security(syminfo.tickerid, "D", [high[1], low[1], close[1], ta.atr(atrLen)[1], ta.sma(high - low, nrLen)[1]], lookahead = barmerge.lookahead_on)
[wh, wl, wc, wAvg] = request.security(syminfo.tickerid, "W", [high[1], low[1], close[1], ta.sma(high - low, nrLen)[1]], lookahead = barmerge.lookahead_on)
[mh, ml, mc, mAvg] = request.security(syminfo.tickerid, "M", [high[1], low[1], close[1], ta.sma(high - low, nrLen)[1]], lookahead = barmerge.lookahead_on)
[xh, xl, xc] = request.security(syminfo.tickerid, mdTF, [high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
scaleAtr = atrBasis == "Daily" ? nz(atrDaily, atr) : atr
emaTrend = ta.ema(close, emaLen)
emaFast = ta.ema(close, emaFastLen)
vwapTrend = ta.vwap(hlc3)
buyZone = emaFast > emaTrend and close > vwapTrend
stayAway = emaFast < emaTrend and close < vwapTrend
[_mLine, _mSig, macdHist] = ta.macd(close, macdFast, macdSlow, macdSig)
atrExp = ta.atr(atrEmphLen) > ta.sma(ta.atr(atrEmphLen), atrEmphMaLen)
volAvg = ta.sma(volume, volLen)
volHot = not na(volAvg) and volume > volAvg * volSpike
var array<float> levVals = array.new_float() // canonical 28-slot level list, rebuilt each bar
// ───────────────────────── Smart level mode ─────────────────────────
// Manual = every effective bool falls through to its raw input. Smart maps the
// chart TF to a preset band + depth set. nz() fallback: in_seconds() is na on
// tick/Renko/range/HA charts -> without it all Smart bools go false -> blank chart.
smart = levelMode == "Smart"
tfSec = nz(timeframe.in_seconds(timeframe.period), 86400)
// bands
// Scalp bucket (tfSec <= 3600, i.e. 1m..1H) = show EVERYTHING: all bands + all depth,
// no near-price cull (you're zoomed in and want every reference level). Prune only as
// you zoom out above 1H.
eUseD = smart ? (tfSec <= 3600) : useD // Daily: scalp only (dropped above 1H)
eUseW = smart ? (tfSec <= 86400) : useW // Weekly: scalp + higher-intraday + daily
eUseM = smart ? (tfSec < 2592000) : useM // Monthly: every sub-monthly chart; off on monthly+
eUseMD = smart ? false : useMD // Multiday: Smart-off; Manual-only (niche)
// depth (tier split: R1/S1 = eShow12, R2/S2 = eShow2, S3/R3 = eShow3)
eShowMid = smart ? true : showMid
eShow12 = smart ? true : show12
eShow2 = smart ? (tfSec <= 3600) : show12 // S2/R2: scalp only
eShow3 = smart ? (tfSec <= 3600) : show3 // S3/R3: scalp only (everything on the minute)
// Near-price filter (applied at f_push so levVals only holds visible levels ->
// no ghost confluence stars, phantom volume-touch marks, or blank label-stagger gaps).
// Bypassed on the scalp bucket (tfSec <= 3600) so the minute shows everything; only culls
// above 1H. atr-na bypass: first ~14 bars ATR is na -> show all, don't blank.
f_near(float v) => not smart or tfSec <= 3600 or na(v) or na(scaleAtr) or scaleAtr <= 0 or math.abs(v - close) <= nearRangeATR * scaleAtr
// ───────────────────────── Helpers ─────────────────────────
f_piv(float h, float l, float c) =>
pp = (h + l + c) / 3.0
rng = h - l
r1 = 2.0 * pp - l
s1 = 2.0 * pp - h
r2 = pp + rng
s2 = pp - rng
r3 = pp + 2.0 * rng
s3 = pp - 2.0 * rng
[pp, r1, s1, r2, s2, r3, s3]
f_norm(float val) =>
na(val) or na(scaleAtr) or scaleAtr == 0 ? na : (val - close) / scaleAtr
f_size(string opt) =>
opt == "normal" ? size.normal : opt == "small" ? size.small : size.tiny
// Stable display order lets equal-price levels receive distinct stagger slots.
f_levelOrder(string name) =>
switch name
"D PP" => 0
"D R1" => 1
"D S1" => 2
"D R2" => 3
"D S2" => 4
"D R3" => 5
"D S3" => 6
"W PP" => 7
"W R1" => 8
"W S1" => 9
"W R2" => 10
"W S2" => 11
"W R3" => 12
"W S3" => 13
"M PP" => 14
"M R1" => 15
"M S1" => 16
"M R2" => 17
"M S2" => 18
"M R3" => 19
"M S3" => 20
"MD PP" => 21
"MD R1" => 22
"MD S1" => 23
"MD R2" => 24
"MD S2" => 25
"MD R3" => 26
"MD S3" => 27
=> 28
f_staggerSlot(float val, string name) =>
int slot = 0
if autoStagger and staggerATR > 0 and not na(val) and not na(scaleAtr) and scaleAtr > 0
threshold = staggerATR * scaleAtr
order = f_levelOrder(name)
sz = array.size(levVals)
if sz > 0
for i = 0 to sz - 1
other = array.get(levVals, i)
// levVals uses the same canonical order as the draw calls.
if i < order and not na(other) and math.abs(other - val) <= threshold
slot += 1
math.min(slot, staggerMax)
f_labelX(float val, string name) =>
sec = timeframe.in_seconds(timeframe.period)
stepMs = int(nz(sec, 86400) * 1000)
base = lblAnchor == "Visible right edge" ? chart.right_visible_bar_time : time
dir = lblSide == "Right" ? 1 : -1
slot = f_staggerSlot(val, name)
int(base + dir * (lblOff + slot * staggerBars) * stepMs)
// Keep one slot per level so label staggering has a stable order; disabled slots are na.
f_push(bool on, float v) =>
array.push(levVals, on and not na(v) ? v : na)
0
// Count levels (incl. self) within conflATR*ATR of val → confluence when count >= 2.
f_conflCount(float val) =>
int cnt = 0
if useConfl and not na(val) and not na(scaleAtr) and scaleAtr > 0
thr = conflATR * scaleAtr
sz = array.size(levVals)
if sz > 0
for i = 0 to sz - 1
v = array.get(levVals, i)
if not na(v) and math.abs(v - val) <= thr
cnt += 1
cnt
// Persistent level line + label, with confluence star/thicken (per-call-site var objects).
f_draw(bool on, float val, string name, color col) =>
var line ln = na
var label lb = na
if barstate.islast
// Trend qualifier: support = level below price, resistance = above. Counter-trend
// (support in a down-EMA or resistance in an up-EMA) is either dimmed or hidden.
isSupport = val < close
counterTrend = emaTrendOn and (buyZone or stayAway) and ((isSupport and stayAway) or (not isSupport and buyZone))
// MACD gate: hist>0 favors support, <0 favors resistance.
// Counter-momentum levels are hard-hidden (hist sign, not dimmed).
macdCounter = macdGateOn and not na(macdHist) and ((isSupport and macdHist < 0) or (not isSupport and macdHist > 0))
hideThis = (counterTrend and emaMode == "Hide") or macdCounter
if on and not na(val) and not hideThis
conf = f_conflCount(val) >= 2
ext = extRight and extLeft ? extend.both : extRight ? extend.right : extLeft ? extend.left : extend.none
wdt = (conf ? 2 : 1) + (atrEmphOn and atrExp ? 1 : 0)
lineBase = neutralPivots ? pivotNeutralCol : col
lineCol = counterTrend and emaMode == "Dim" ? color.new(lineBase, dimAmount) : lineBase
txt = (conf ? "★ " : "") + name + " " + str.tostring(val, format.mintick)
labelX = f_labelX(val, name)
labelStyle = lblSide == "Right" ? label.style_label_left : label.style_label_right
if na(ln)
ln := line.new(bar_index, val, bar_index + 1, val, color = lineCol, width = wdt, extend = ext)
lb := label.new(labelX, val, "", xloc = xloc.bar_time, style = labelStyle, color = color.new(color.black, 15), textcolor = col, size = f_size(lblSizeOpt))
line.set_xy1(ln, bar_index, val)
line.set_xy2(ln, bar_index + 1, val)
line.set_extend(ln, ext)
line.set_width(ln, wdt)
line.set_color(ln, lineCol)
if showLbl
label.set_xloc(lb, labelX, xloc.bar_time)
label.set_y(lb, val)
label.set_style(lb, labelStyle)
label.set_size(lb, f_size(lblSizeOpt))
label.set_text(lb, txt)
else
label.set_text(lb, "")
else if not na(ln)
line.delete(ln)
label.delete(lb)
ln := na
lb := na
true
// Append one table row; returns the next row index.
f_addrow(table tbl, int r, bool on, string name, float val, color col) =>
int nr = r
if on and not na(val) and r < 24
d = f_norm(val)
near = not na(d) and math.abs(d) <= nearATR
conf = f_conflCount(val) >= 2
bg = near ? color.new(col, 45) : color.new(color.black, 15)
pct = na(close) or close == 0 ? na : (val - close) / close * 100.0
table.cell(tbl, 0, r, (conf ? "★" : "") + name, text_size = f_size(tabSizeOpt), text_color = col, bgcolor = bg)
table.cell(tbl, 1, r, str.tostring(val, format.mintick), text_size = f_size(tabSizeOpt), text_color = color.white, bgcolor = bg)
table.cell(tbl, 2, r, na(d) ? "-" : str.tostring(d, "0.00"), text_size = f_size(tabSizeOpt), text_color = na(d) ? color.gray : (d >= 0 ? color.lime : color.red), bgcolor = bg)
table.cell(tbl, 3, r, na(pct) ? "-" : str.tostring(pct, "0.00"), text_size = f_size(tabSizeOpt), text_color = color.silver, bgcolor = bg)
nr := r + 1
nr
// ───────────────────────── Compute pivots ─────────────────────────
[dpp, dr1, ds1, dr2, ds2, dr3, ds3] = f_piv(dh, dl, dc)
[wpp, wr1, ws1, wr2, ws2, wr3, ws3] = f_piv(wh, wl, wc)
[mpp, mr1, ms1, mr2, ms2, mr3, ms3] = f_piv(mh, ml, mc)
[xpp, xr1, xs1, xr2, xs2, xr3, xs3] = f_piv(xh, xl, xc)
// ───────────────────────── Build confluence set (each bar) ─────────────────────────
array.clear(levVals)
f_push(eUseD and eShowMid and f_near(dpp), dpp)
f_push(eUseD and eShow12 and f_near(dr1), dr1)
f_push(eUseD and eShow12 and f_near(ds1), ds1)
f_push(eUseD and eShow2 and f_near(dr2), dr2)
f_push(eUseD and eShow2 and f_near(ds2), ds2)
f_push(eUseD and eShow3 and f_near(dr3), dr3)
f_push(eUseD and eShow3 and f_near(ds3), ds3)
f_push(eUseW and eShowMid and f_near(wpp), wpp)
f_push(eUseW and eShow12 and f_near(wr1), wr1)
f_push(eUseW and eShow12 and f_near(ws1), ws1)
f_push(eUseW and eShow2 and f_near(wr2), wr2)
f_push(eUseW and eShow2 and f_near(ws2), ws2)
f_push(eUseW and eShow3 and f_near(wr3), wr3)
f_push(eUseW and eShow3 and f_near(ws3), ws3)
f_push(eUseM and eShowMid and f_near(mpp), mpp)
f_push(eUseM and eShow12 and f_near(mr1), mr1)
f_push(eUseM and eShow12 and f_near(ms1), ms1)
f_push(eUseM and eShow2 and f_near(mr2), mr2)
f_push(eUseM and eShow2 and f_near(ms2), ms2)
f_push(eUseM and eShow3 and f_near(mr3), mr3)
f_push(eUseM and eShow3 and f_near(ms3), ms3)
f_push(eUseMD and eShowMid and f_near(xpp), xpp)
f_push(eUseMD and eShow12 and f_near(xr1), xr1)
f_push(eUseMD and eShow12 and f_near(xs1), xs1)
f_push(eUseMD and eShow2 and f_near(xr2), xr2)
f_push(eUseMD and eShow2 and f_near(xs2), xs2)
f_push(eUseMD and eShow3 and f_near(xr3), xr3)
f_push(eUseMD and eShow3 and f_near(xs3), xs3)
// ───────────────────────── Volume-confirmed level touch ─────────────────────────
// After levVals is rebuilt this bar: mark a touch of any active level on a volume spike.
bool volTouch = false
if not na(scaleAtr) and array.size(levVals) > 0
tol = volTouchATR * scaleAtr
for i = 0 to array.size(levVals) - 1
v = array.get(levVals, i)
if not na(v) and low - tol <= v and v <= high + tol
volTouch := true
volSignal = volConfOn and volHot and volTouch
// Delta proxy: no tick data in Pine, so bar close-open is the standard buy/sell proxy.
// Positive delta -> marker below bar; negative -> marker above bar. Shape is user-selectable.
barDelta = close - open
volUp = volSignal and (not volDeltaCol or barDelta >= 0)
volDn = volSignal and volDeltaCol and barDelta < 0
upCol = volDeltaCol ? volUpCol : color.new(color.orange, 0)
plotshape(volUp, "Vol touch +", style=volMarkerStyle == "Circles" ? shape.circle : shape.triangleup, location=location.belowbar, color=upCol, size=size.tiny)
plotshape(volDn, "Vol touch -", style=volMarkerStyle == "Circles" ? shape.circle : shape.triangledown, location=location.abovebar, color=volDnCol, size=size.tiny)
// ───────────────────────── Volatility regime (NR composite) ─────────────────────────
// Prior-range-vs-average definition: PRIOR completed range over the 20-period average range.
nrDnr = na(dAvg) or dAvg == 0 ? na : (dh - dl) / dAvg
nrWnr = na(wAvg) or wAvg == 0 ? na : (wh - wl) / wAvg
nrMnr = na(mAvg) or mAvg == 0 ? na : (mh - ml) / mAvg
// Developing definition: CUR / CPR — this period's
// DEVELOPING range over the prior period's completed range.
// NOT via request.security: with lookahead_off and no offset it returns the last CONFIRMED
// HTF value, which is the same completed range f_hlc already supplies, so every ratio came
// out identically 1.0000. Caught on the live chart — nrD/nrW/nrM all exactly 1.0000 at once.
// Instead accumulate the developing range from CHART bars since the HTF period rolled. Uses
// only current and past bars, so it cannot repaint, and it costs no request.* budget. The var
// state is per-call-site, so the three calls below keep three independent running ranges.
f_devRange(simple string tf) =>
var float dhi = na
var float dlo = na
isNew = ta.change(time(tf)) != 0
dhi := isNew or na(dhi) ? high : math.max(dhi, high)
dlo := isNew or na(dlo) ? low : math.min(dlo, low)
dhi - dlo
dCur = f_devRange("D")
wCur = f_devRange("W")
mCur = f_devRange("M")
nrDdev = na(dCur) or (dh - dl) <= 0 ? na : dCur / (dh - dl)
nrWdev = na(wCur) or (wh - wl) <= 0 ? na : wCur / (wh - wl)
nrMdev = na(mCur) or (mh - ml) <= 0 ? na : mCur / (mh - ml)
developing = nrMode == "Developing"
nrD = developing ? nrDdev : nrDnr
nrW = developing ? nrWdev : nrWnr
nrM = developing ? nrMdev : nrMnr
nr = (na(nrD) ? 0.0 : wtD * nrD) + (na(nrW) ? 0.0 : wtW * nrW) + (na(nrM) ? 0.0 : wtM * nrM)
// The cuts travel WITH the definition: 0.75/1.25/1.75 for Developing; the prior-range cuts are
// quantile-matched so both definitions give the same bucket shares on ES daily data.
cutLo = developing ? 0.75 : 0.741
cutMid = developing ? 1.25 : 1.109
cutHi = developing ? 1.75 : 1.468
regime = nr < cutLo ? "COMPRESSION" : nr < cutMid ? "NORMAL" : nr < cutHi ? "EXPANSION" : "EXTREME"
regCol = nr < cutLo ? color.teal : nr < cutMid ? color.gray : nr < cutHi ? color.orange : color.red
bgcolor(useRegime and regime == "COMPRESSION" ? color.new(color.teal, 90) : useRegime and regime == "EXTREME" ? color.new(color.red, 90) : na)
// EMA Cloud + VWAP Zones
cloudCol = buyZone ? color.new(color.green, 70) : stayAway ? color.new(color.red, 70) : color.new(color.gray, 80)
p9 = plot(showZones ? emaFast : na, "EMA 9 (zone)", color = color.lime, linewidth = 1)
p20 = plot(showZones ? emaTrend : na, "EMA 20 (zone)", color = color.orange, linewidth = 1)
fill(p9, p20, color = showZones ? cloudCol : na, title = "EMA Cloud")
plot(showZones ? vwapTrend : na, "VWAP (zone)", color = color.blue, linewidth = 2)
zoneBgCol = showZoneBg ? (buyZone ? color.new(color.green, 92) : stayAway ? color.new(color.red, 92) : color(na)) : na
bgcolor(zoneBgCol, title = "Zone Background")
if showZoneLabels and buyZone and not buyZone[1]
label.new(bar_index, low, "B", style = label.style_label_up, color = color.green, textcolor = color.white, size = size.tiny)
if showZoneLabels and stayAway and not stayAway[1]
label.new(bar_index, high, "S", style = label.style_label_down, color = color.red, textcolor = color.white, size = size.tiny)
// ───────────────────────── Plot levels ─────────────────────────
f_draw(eUseD and eShowMid and f_near(dpp), dpp, "D PP", cD)
f_draw(eUseD and eShow12 and f_near(dr1), dr1, "D R1", cD)
f_draw(eUseD and eShow12 and f_near(ds1), ds1, "D S1", cD)
f_draw(eUseD and eShow2 and f_near(dr2), dr2, "D R2", cD)
f_draw(eUseD and eShow2 and f_near(ds2), ds2, "D S2", cD)
f_draw(eUseD and eShow3 and f_near(dr3), dr3, "D R3", cD)
f_draw(eUseD and eShow3 and f_near(ds3), ds3, "D S3", cD)
f_draw(eUseW and eShowMid and f_near(wpp), wpp, "W PP", cW)
f_draw(eUseW and eShow12 and f_near(wr1), wr1, "W R1", cW)
f_draw(eUseW and eShow12 and f_near(ws1), ws1, "W S1", cW)
f_draw(eUseW and eShow2 and f_near(wr2), wr2, "W R2", cW)
f_draw(eUseW and eShow2 and f_near(ws2), ws2, "W S2", cW)
f_draw(eUseW and eShow3 and f_near(wr3), wr3, "W R3", cW)
f_draw(eUseW and eShow3 and f_near(ws3), ws3, "W S3", cW)
f_draw(eUseM and eShowMid and f_near(mpp), mpp, "M PP", cM)
f_draw(eUseM and eShow12 and f_near(mr1), mr1, "M R1", cM)
f_draw(eUseM and eShow12 and f_near(ms1), ms1, "M S1", cM)
f_draw(eUseM and eShow2 and f_near(mr2), mr2, "M R2", cM)
f_draw(eUseM and eShow2 and f_near(ms2), ms2, "M S2", cM)
f_draw(eUseM and eShow3 and f_near(mr3), mr3, "M R3", cM)
f_draw(eUseM and eShow3 and f_near(ms3), ms3, "M S3", cM)
f_draw(eUseMD and eShowMid and f_near(xpp), xpp, "MD PP", cMD)
f_draw(eUseMD and eShow12 and f_near(xr1), xr1, "MD R1", cMD)
f_draw(eUseMD and eShow12 and f_near(xs1), xs1, "MD S1", cMD)
f_draw(eUseMD and eShow2 and f_near(xr2), xr2, "MD R2", cMD)
f_draw(eUseMD and eShow2 and f_near(xs2), xs2, "MD S2", cMD)
f_draw(eUseMD and eShow3 and f_near(xr3), xr3, "MD R3", cMD)
f_draw(eUseMD and eShow3 and f_near(xs3), xs3, "MD S3", cMD)
// ───────────────────────── NY open marker ─────────────────────────
inNY = not na(time(timeframe.period, "0930-1600:23456", "America/New_York"))
nyStart = inNY and not inNY[1]
if markNY and nyStart
line.new(bar_index, low, bar_index, high, extend = extend.both, color = color.new(nyCol, 40), style = line.style_dotted, width = 1)
// ───────────────────────── Table ─────────────────────────
var table tb = na
if showTab and barstate.islast
pos = tabPos == "top_left" ? position.top_left : tabPos == "bottom_right" ? position.bottom_right : tabPos == "bottom_left" ? position.bottom_left : position.top_right
if na(tb)
tb := table.new(pos, 4, 26, border_width = 1)
table.clear(tb, 0, 0, 3, 25)
// Regime banner (row 0)
table.cell(tb, 0, 0, "REGIME", text_size = f_size(tabSizeOpt), text_color = color.white, bgcolor = color.new(color.black, 0))
table.cell(tb, 1, 0, useRegime ? regime : "off", text_size = f_size(tabSizeOpt), text_color = regCol, bgcolor = color.new(color.black, 0))
table.cell(tb, 2, 0, "NR", text_size = f_size(tabSizeOpt), text_color = color.white, bgcolor = color.new(color.black, 0))
table.cell(tb, 3, 0, str.tostring(nr, "0.00"), text_size = f_size(tabSizeOpt), text_color = regCol, bgcolor = color.new(color.black, 0))
// Column headers (row 1)
table.cell(tb, 0, 1, "Lvl", text_size = f_size(tabSizeOpt), text_color = color.white, bgcolor = color.new(color.gray, 0))
table.cell(tb, 1, 1, "Price", text_size = f_size(tabSizeOpt), text_color = color.white, bgcolor = color.new(color.gray, 0))
table.cell(tb, 2, 1, "ATR", text_size = f_size(tabSizeOpt), text_color = color.white, bgcolor = color.new(color.gray, 0))
table.cell(tb, 3, 1, "%", text_size = f_size(tabSizeOpt), text_color = color.white, bgcolor = color.new(color.gray, 0))
int row = 2
row := f_addrow(tb, row, eUseM and eShow3, "M R3", mr3, cM)
row := f_addrow(tb, row, eUseM and eShow12, "M R1", mr1, cM)
row := f_addrow(tb, row, eUseM and eShowMid, "M PP", mpp, cM)
row := f_addrow(tb, row, eUseMD and eShowMid, "MD PP", xpp, cMD)
row := f_addrow(tb, row, eUseW and eShowMid, "W PP", wpp, cW)
row := f_addrow(tb, row, eUseD and eShow12, "D R1", dr1, cD)
row := f_addrow(tb, row, eUseD and eShowMid, "D PP", dpp, cD)
row := f_addrow(tb, row, eUseD and eShow12, "D S1", ds1, cD)
row := f_addrow(tb, row, eUseW and eShow12, "W S1", ws1, cW)
row := f_addrow(tb, row, eUseM and (smart ? eShow12 : showMid), "M S1", ms1, cM)
row := f_addrow(tb, row, eUseM and eShow3, "M S3", ms3, cM)
else if not showTab and not na(tb)
table.delete(tb)
tb := na
// ───────────────────────── Machine-readable data layer ─────────────────────────
// Placed last: levVals, atr, nr, regime, buyZone/stayAway and volSignal are all final by here.
// One pass over levVals yields nearest support, nearest resistance, the active count, and
// whether a confluent level was touched. f_conflCount is called only for levels actually
// touched this bar (normally none), so the nested scan stays cheap on historical bars.
float mrSup = na
float mrRes = na
int mrActive = 0
bool mrConfTouch = false
float mrTol = na(scaleAtr) ? 0.0 : volTouchATR * scaleAtr
if array.size(levVals) > 0
for i = 0 to array.size(levVals) - 1
v = array.get(levVals, i)
if not na(v)
mrActive += 1
if v <= close
mrSup := (na(mrSup) or v > mrSup) ? v : mrSup
else
mrRes := (na(mrRes) or v < mrRes) ? v : mrRes
if not na(scaleAtr) and low - mrTol <= v and v <= high + mrTol
if f_conflCount(v) >= 2
mrConfTouch := true
// f_conflCount returns 0 for an na input, so these are safe to call unconditionally.
int mrSupConf = f_conflCount(mrSup)
int mrResConf = f_conflCount(mrRes)
float mrSupDist = na(mrSup) or na(scaleAtr) or scaleAtr <= 0 ? na : (close - mrSup) / scaleAtr
float mrResDist = na(mrRes) or na(scaleAtr) or scaleAtr <= 0 ? na : (mrRes - close) / scaleAtr
// Derived from the regime STRING, not from a second copy of the cuts, so the code can never
// drift from the label the table prints.
int mrRegime = regime == "COMPRESSION" ? 0 : regime == "NORMAL" ? 1 : regime == "EXPANSION" ? 2 : 3
int mrBias = buyZone ? 1 : stayAway ? -1 : 0
// ── Decision series ──
plot(mrSup, "Nearest support", display = display.data_window)
plot(mrRes, "Nearest resistance", display = display.data_window)
plot(mrSupDist, "Support dist (ATR)", display = display.data_window)
plot(mrResDist, "Resistance dist (ATR)", display = display.data_window)
plot(mrSupConf, "Support confluence", display = display.data_window)
plot(mrResConf, "Resistance confluence", display = display.data_window)
plot(mrActive, "Active levels", display = display.data_window)
plot(atr, "ATR (chart)", display = display.data_window)
plot(atrDaily, "ATR (daily)", display = display.data_window)
plot(scaleAtr, "ATR (threshold basis)", display = display.data_window)
plot(mrBias, "Bias (-1/0/1)", display = display.data_window)
plot(mrRegime, "Regime (0-3)", display = display.data_window)
plot(volSignal ? 1 : 0, "Vol touch flag", display = display.data_window)
plot(mrConfTouch ? 1 : 0,"Confluent touch flag", display = display.data_window)
// ── NR composite, and its three components separately (for threshold recalibration) ──
plot(nr, "NR composite", display = display.data_window)
plot(nrD, "NR daily", display = display.data_window)
plot(nrW, "NR weekly", display = display.data_window)
plot(nrM, "NR monthly", display = display.data_window)
plot(developing ? 1 : 0, "NR mode (1=developing)", display = display.data_window)
plot(cutLo, "Regime cut lo", display = display.data_window)
plot(cutMid, "Regime cut mid", display = display.data_window)
plot(cutHi, "Regime cut hi", display = display.data_window)
// Raw pivot prices stay in the level engine and chart lines; the nearest-level and
// decision series above are the Data Window exports.
// ── Alerts ──
alertcondition(volTouch, "PSF level touch", "PSF: price touched an active pivot level")
alertcondition(volSignal, "PSF volume touch", "PSF: high-volume touch of an active pivot level")
alertcondition(mrConfTouch, "PSF confluence touch", "PSF: price touched a confluent (2+ band) level")
alertcondition(mrRegime != mrRegime[1], "PSF regime change", "PSF: volatility regime changed")