本页源码来自 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/
// Copyright (c) 2026 WizTrader
//@version=6
indicator("WizTrader Range Grid", shorttitle="WT Range Grid", overlay=false,
max_bars_back=1000, max_labels_count=500, max_lines_count=200, explicit_plot_zorder=true, behind_chart=true)
// WIZTRADER RANGE GRID · v1.0
// Adaptive center and volatility-scaled spacing shared by chart and oscillator.
// Confirmed Long/Flat grid-step cycle; no broker orders or strategy simulation.
string G_EVENTS = "1 · Start Here"
string G_CHART = "2 · Price Chart"
string G_PANE = "3 · Oscillator & Dashboard"
string G_LAYOUT = "4 · Appearance"
string G_CORE = "5 · Calculation · Changes Signals"
string G_EXTRA = "6 · Extra Grid Details"
string summaryMode = input.string("Simple", "Display Detail", options=["Simple", "Detailed"], display=display.none, group=G_EVENTS,
tooltip="Simple shows position, last signal, next condition, distance from center and the price of one grid step. Detailed adds the location meter, calculation diagnostics and extra Focus price-label detail. Optional crossing/comparison displays in Extra Grid Details can be selected independently in either mode. This is display only: it does not reset calculation settings or change signals or alerts.")
bool advancedView = summaryMode == "Detailed"
bool showBuySell = input.bool(true, "Entry / Exit Markers", display=display.none, group=G_EVENTS,
tooltip="▲ enters a virtual Long; × closes it. Events wait for candle close. SELL does not open Short. Hover a marker for its conditions and threshold. The indicator tracks its own state and sends no broker orders. Hiding markers leaves calculations and alerts active. Up to 80 events retained; oldest entry/exit pairs are removed together. The latest entry can still be open.")
string markerSizeChoice = input.string("Normal", "Signal Size", options=["Small", "Normal", "Large"], display=display.none, group=G_EVENTS,
tooltip="Changes only the entry triangles and exit crosses, independently of dashboard text. Small 20/24, Normal 26/30, Large 32/36. One-tick wick anchors keep symbols close to their event candle. Text extends away from the wick as size increases. Entries sit below the low; exits above the high. Event candles and trigger prices are not affected.")
bool showGrid = input.bool(true, "Grid Lines", display=display.none, group=G_CHART,
tooltip="Blue lines are above the adaptive center, purple lines below. One gap between adjacent lines is one grid step. These are location references; crossing a line alone is not necessarily an entry. Hiding lines also hides the outer glow and grid surfaces. Center Line controls its own halo. Signal calculations are not affected.")
bool colorBars = input.bool(false, "Color Bars by Grid Position", display=display.none, group=G_CHART,
tooltip="Optional native bar coloring: gray inside Neutral Zone, blue above it and purple below it. Default Neutral Zone is +/-0.15 grid steps around center. Uses the same current reading and colors as the oscillator; it does not report candle direction, an entry signal or an open position. Open-candle color can change before close. Off or insufficient data leaves native chart colors untouched. Independent of grid/oscillator visibility. No signal or alert changes.")
bool showSignalGuide = input.bool(true, "Next Entry / Exit Line", display=display.none, group=G_CHART,
tooltip="The blue dashed line marks the next entry threshold; the neutral line marks the next exit threshold. On a signal candle, the old line finishes at the threshold actually tested; the new reference has its own right-edge tag. The latest 80 signal-line endings are retained independently of marker visibility. While no position is open, entry also needs a rising close and recovery in the Previous Grid. While Long, a confirmed close below the line exits. The dashboard explains what is still needed. The line price moves with the grid; it is not a fixed-price stop or guaranteed fill.")
bool showCenter = input.bool(true, "Center Line", display=display.none, group=G_CHART,
tooltip="The adaptive price reference. Its color shows rising, falling or nearly flat slope. Oscillator zero means price equals this center. Its color does not open or close a position.")
bool showChartGlow = input.bool(true, "Depth & Glow", display=display.none, group=G_CHART,
tooltip="Light blue/purple surfaces and three-layer luminous outer edges. Blue surface means above center; purple means below. Surface colors do not report an open position. Glow Strength controls surface transparency and edge-glow width/visibility. The extra inner glow is a drawing layer on the same boundary, not another price level. Outer glow and grid surfaces require Grid Lines; the center halo requires Center Line. Signal glyphs are single, fully visible symbols and do not change with glow.")
string priceTagMode = input.string("Focus", "Price Labels", options=["Focus", "All", "Off"], display=display.none, group=G_CHART,
tooltip="Focus in Simple mode shows the center and outer levels, plus a separate Entry >/Exit < tag for the dashed threshold. Detailed Focus also includes +/-1. All labels every displayed grid line; Off hides all price tags. Labels sit at exact current prices. The threshold tag is farther right for spacing. It is a pending reference, not a signal or forecast.")
bool showOscillator = input.bool(true, "Oscillator", display=display.none, group=G_PANE,
tooltip="Shows distance from center in grid steps. +1 = one line spacing above center; -1 = one below; 0 = at center. The curve is gray inside Neutral Zone without changing the numerical distance. Values are not percentages or probabilities and can exceed the outer grid. The native pane remains when contents are hidden.")
bool showOscillatorGlow = input.bool(true, "Depth & Glow", display=display.none, group=G_PANE,
tooltip="Faint blue/purple distance shading. It uses the same grid as the price chart, without extra smoothing or delay. Glow Strength adjusts the gradients, curve halo and outer extension surfaces together. Balanced uses an 11% curve halo and 5% extension surfaces; Subtle 7%/3%, Strong 15%/7%.")
bool showPaneValue = input.bool(true, "Distance Label", display=display.none, group=G_PANE,
tooltip="The live curve label says how many grid steps price is above or below the center. One step equals one current gap between grid lines. Open-candle readings can change before close.")
bool showSummary = input.bool(true, "Dashboard", display=display.none, group=G_PANE,
tooltip="Shows the indicator's confirmed position, last signal and the next condition, followed by live distance and the price of one grid step. Both modes include a marker key. Detailed adds the location meter, center/spacing diagnostics and Grid-event details. It describes the latest available candle, not a historical crosshair selection, and does not read your broker account.")
string summaryCorner = input.string("Bottom Right", "Dashboard Position", options=["Top Left", "Top Right", "Bottom Left", "Bottom Right"], display=display.none, group=G_PANE)
string glowStrength = input.string("Balanced", "Glow Strength", options=["Subtle", "Balanced", "Strong"], display=display.none, group=G_LAYOUT,
tooltip="Light shading in all three modes. Balanced uses only 12% chart opacity and 14% oscillator opacity at the strongest gradient edge; Strong uses 20%/22%, Subtle 6%/7%. The gradients fade to clear at center. Outer edges use wide halo + brighter inner glow + thin full-color contour. Balanced uses widths 12/6/2; Strong 16/8/2; Subtle 12/6/2 with lower opacity. In the oscillator, strength also controls curve-halo opacity (7%/11%/15%) and extension-surface opacity (3%/5%/7%) for Subtle/Balanced/Strong. Surface opacity stays light. Signal glyphs stay single at their selected size. No signal changes.")
int chartSurfaceAlpha = glowStrength == "Strong" ? 80 : glowStrength == "Balanced" ? 88 : 94
int paneSurfaceAlpha = glowStrength == "Strong" ? 78 : glowStrength == "Balanced" ? 86 : 93
int edgeHaloAlpha = glowStrength == "Strong" ? 75 : glowStrength == "Balanced" ? 82 : 90
int edgeHaloWidth = glowStrength == "Strong" ? 16 : 12
int edgeGlowAlpha = glowStrength == "Strong" ? 48 : glowStrength == "Balanced" ? 58 : 76
int edgeGlowWidth = glowStrength == "Strong" ? 8 : 6
int centerHaloAlpha = glowStrength == "Strong" ? 88 : glowStrength == "Balanced" ? 93 : 96
int paneHaloAlpha = glowStrength == "Strong" ? 85 : glowStrength == "Balanced" ? 89 : 93
int paneShellAlpha = glowStrength == "Strong" ? 93 : glowStrength == "Balanced" ? 95 : 97
string textChoice = input.string("Normal", "Dashboard / Label Text Size", options=["Small", "Normal", "Large"], display=display.none, group=G_LAYOUT,
tooltip="Changes dashboard and current-value labels. Historical entry/exit markers use the separate Signal Size setting.")
color aboveColor = input.color(color.rgb(85, 134, 219), "Above Center / Entry", display=display.none, group=G_LAYOUT,
tooltip="Blue identifies the upper grid half and the entry triangle. A blue area alone is not a BUY. Read the dashboard marker key and position.")
color belowColor = input.color(color.rgb(172, 68, 203), "Below Center", display=display.none, group=G_LAYOUT)
color neutralColor = input.color(color.rgb(100, 100, 120), "Neutral", display=display.none, group=G_LAYOUT)
float neutralZone = input.float(0.15, "Neutral Zone (Grid Steps)", minval=0.0, maxval=0.50, step=0.05, display=display.none, group=G_LAYOUT,
tooltip="Color only, never a signal filter. Bars (when enabled), the oscillator curve and distance-value color are gray within +/- this distance from center. Default 0.15 means fifteen hundredths of one line spacing, not 15% of price. Boundaries included. Beyond it: blue above, purple below. Larger values show more gray; 0 restores exact-center-only gray. Does not classify the whole market as sideways. Numerical readings, entry/exit rules and alerts are not affected.")
int centerLength = input.int(75, "Center Response", minval=5, maxval=200, display=display.none, group=G_CORE,
tooltip="Changes signals. Adaptive response horizon in chart candles; default 75. Longer generally reacts more slowly. This is not a forecast holding period. Recursive initialization can retain effects from the available history start.")
int rangeLength = input.int(14, "Range Response", minval=3, maxval=100, display=display.none, group=G_CORE,
tooltip="Changes signals. Fast and slow smoothed True Range define the changing line spacing. Default 14. This is not conventional ATR. Both chart and oscillator use the resulting spacing.")
int gridSmoothness = input.int(6, "Spacing Smoothness", minval=1, maxval=12, display=display.none, group=G_CORE,
tooltip="Changes signals. Two EMA stages smooth the logarithm of the raw spacing. Default 6; 1 bypasses this extra smoothing. Higher values make spacing changes slower. Spacing remains at least two ticks.")
float stepMultiplier = input.float(1.0, "Grid Spacing Multiplier", minval=0.25, maxval=5.0, step=0.25, display=display.none, group=G_CORE,
tooltip="Changes signals. Scales the spacing between adjacent lines. +1 oscillator step always means one current line spacing above center, regardless of the multiplier. Steps are not percentages.")
int levels = input.int(3, "Grid Levels / Signal Depth", minval=1, maxval=5, display=display.none, group=G_CORE,
tooltip="Changes signals as well as display. Sets the number of lines per side and limits the signal-cycle base steps. With 3 levels and buffer 0.10, the highest base-derived exit threshold is +1.90 steps even if readings rise higher. This is not merely a line-visibility setting.")
float signalBuffer = input.float(0.10, "Signal Buffer (Grid Steps)", minval=0.0, maxval=0.50, step=0.05, display=display.none, group=G_CORE,
tooltip="Changes signals. Default 0.10 adds one tenth of a line spacing beyond the base step: above for entry, below for exit. It is not 10% of price. The dashed line shows this buffered threshold. Entry also needs rising close and recovery in the Previous Grid. Larger buffers generally need more recovery and permit more pullback; no performance advantage is implied.")
string eventBoundary = input.string("Middle", "Grid Crossing Level (Alerts)", options=["Inner", "Middle", "Outer"], display=display.none, group=G_EXTRA,
tooltip="Only the four Grid context alerts/markers use this selection; BUY/SELL do not. With three levels: Inner +/-1, Middle +/-2, Outer +/-3. Middle is the level count divided by two, rounded up. With two levels, Middle equals Inner (+/-1); with one level, all three choices equal +/-1. Crossing events wait for close. These alerts stay active in Simple mode even if markers are hidden.")
bool showChartEvents = input.bool(false, "Crossing Markers on Chart", display=display.none, group=G_EXTRA,
tooltip="Available in Simple and Detailed. ○ = close crosses outward beyond the selected upper/lower level; ◇ = return through that level. They describe grid crossings, not position entries/exits. Hiding them leaves the four Grid alerts active.")
bool showPaneEvents = input.bool(false, "Crossing Markers in Oscillator", display=display.none, group=G_EXTRA,
tooltip="Available in Simple and Detailed when Oscillator is on. Shows the same confirmed ○/◇ crossing events in the oscillator. These are separate from ▲ entry / × exit. Alerts do not depend on these markers.")
bool showMotionLens = input.bool(false, "Previous-Grid Comparison", display=display.none, group=G_EXTRA,
tooltip="Available in Simple and Detailed when Oscillator is on. A last-bar ⊕ shows the current close in the previous candle's unchanged grid. A dotted connector compares it with the actual reading. It is not a signal or forecast. Off by default.")
if barstate.isfirst and not chart.is_standard
runtime.error("WizTrader Range Grid requires standard Candles or Bars. Synthetic chart prices are not supported.")
// ---------------------------------------------------------------------
// Independent calculation. Persistent values use ordinary var, so realtime
// recalculation starts from the prior confirmed center on every update.
// ---------------------------------------------------------------------
bool priceReady = not na(open) and not na(high) and not na(low) and not na(close)
float pathChange = math.abs(close - close[1])
float pathLength = ta.sma(pathChange, centerLength) * centerLength
float netChange = math.abs(close - close[centerLength])
float efficiency = not na(pathLength) and pathLength > 0.0 ? math.min(1.0, netChange / pathLength) : 0.0
float baseAlpha = 2.0 / (centerLength + 1.0)
float centerAlpha = baseAlpha * (0.5 + 0.5 * efficiency)
float centerDamping = 4.0 * baseAlpha / math.pow(1.0 + baseAlpha, 2.0)
var float center = na
var float centerVelocity = 0.0
float previousCenter = nz(center[1], close)
float previousVelocity = nz(centerVelocity[1], 0.0)
centerVelocity := priceReady ? previousVelocity + centerDamping * (centerAlpha * (close - previousCenter) - previousVelocity) : 0.0
center := priceReady ? previousCenter + centerVelocity : center[1]
float trueRange = ta.tr(true)
float fastRange = ta.ema(trueRange, rangeLength)
float slowRange = ta.ema(trueRange, rangeLength * 3)
float rangeUnit = math.sqrt(math.max(fastRange, 0.0) * math.max(slowRange, 0.0))
float rawInterval = math.max(rangeUnit * stepMultiplier, syminfo.mintick * 2.0)
float logInterval = math.log(rawInterval)
float widthStage1 = ta.ema(logInterval, gridSmoothness)
float widthStage2 = ta.ema(widthStage1, gridSmoothness)
float interval = math.max(math.exp(widthStage2), syminfo.mintick * 2.0)
// Minimum initialization only: recursive filters retain dataset-start effects.
int warmupBars = math.max(centerLength + 1, rangeLength * 3 + 2 * (gridSmoothness - 1))
bool ready = priceReady and bar_index >= warmupBars - 1 and not na(center) and not na(interval) and interval > 0.0 and not na(pathLength)
float gridUnits = ready ? (close - center) / interval : na
float widthReference = ta.ema(interval, rangeLength * 3)
float widthRatio = ready and not na(widthReference) and widthReference > 0.0 ? interval / widthReference : na
string widthState = na(widthRatio) ? "Waiting" : widthRatio > 1.10 ? "Expanding" : widthRatio < 0.90 ? "Contracting" : "Stable"
float centerSlope = center - center[1]
color centerInk = not ready or na(centerSlope) or math.abs(centerSlope) <= interval * 0.015 ? neutralColor : centerSlope > 0.0 ? aboveColor : belowColor
color distanceInk = na(gridUnits) or math.abs(gridUnits) <= neutralZone ? neutralColor : gridUnits > 0.0 ? aboveColor : belowColor
int eventLevel = eventBoundary == "Inner" ? 1 : eventBoundary == "Outer" ? levels : int(math.ceil(levels / 2.0))
// MOTION LENS · exact change attribution, not a second oscillator.
// With z=(price-center)/width, this identity holds between usable bars:
// delta(z) = delta(price)/width - delta(center)/width
// + z[1] * (width[1]/width - 1).
// Price/Center use CURRENT width. Width is the remaining exact scale term.
// These are signed grid-unit changes, never percentages or probabilities.
bool motionReady = ready and ready[1]
float priceContribution = motionReady ? (close - close[1]) / interval : na
float centerContribution = motionReady ? -(center - center[1]) / interval : na
float widthContribution = motionReady ? gridUnits[1] * (interval[1] / interval - 1.0) : na
float distanceChange = motionReady ? gridUnits - gridUnits[1] : na
// Separate counterfactual: move only price in the PREVIOUS confirmed grid.
// This test answers whether the same directional crossing also occurs there.
float fixedGridUnits = motionReady ? (close - center[1]) / interval[1] : na
// All events use the SAME normalized series displayed by the oscillator.
// Both price movement and movement of the grid can cause a crossing.
// Equality alone is not a crossing. Gaps may jump across the selected level.
bool eventReady = ready and ready[1] and barstate.isconfirmed
bool upperExpansion = eventReady and gridUnits > eventLevel and gridUnits[1] <= eventLevel
bool lowerExpansion = eventReady and gridUnits < -eventLevel and gridUnits[1] >= -eventLevel
bool upperReturn = eventReady and gridUnits < eventLevel and gridUnits[1] >= eventLevel
bool lowerReturn = eventReady and gridUnits > -eventLevel and gridUnits[1] <= -eventLevel
bool hasEvent = upperExpansion or lowerExpansion or upperReturn or lowerReturn
bool eventUp = upperExpansion or lowerReturn
bool eventExpansion = upperExpansion or lowerExpansion
// A wide gap can cross both selected boundaries in one bar. Both named
// conditions qualify; one combined marker reports both roles in its tooltip.
string eventRole = ""
string eventGlyph = eventExpansion ? "○" : "◇"
color eventInk = eventExpansion ? (eventUp ? aboveColor : belowColor) : chart.fg_color
string distanceText = ready ? (gridUnits > 0.0 ? "+" : "") + str.tostring(gridUnits, "0.00") + " grid steps" : "Waiting"
// Every actual event is classified against the unchanged Previous Grid.
// "Previous Grid also crossed" does not mean the current grid did not move.
// "Moving grid required" means the actual event would fail in that test;
// it does not imply the event is false or that price did not move.
bool upperExpansionPrior = upperExpansion and fixedGridUnits > eventLevel
bool lowerExpansionPrior = lowerExpansion and fixedGridUnits < -eventLevel
bool upperReturnPrior = upperReturn and fixedGridUnits < eventLevel
bool lowerReturnPrior = lowerReturn and fixedGridUnits > -eventLevel
int eventCount = (upperExpansion ? 1 : 0) + (lowerExpansion ? 1 : 0) + (upperReturn ? 1 : 0) + (lowerReturn ? 1 : 0)
int priorCrossCount = (upperExpansionPrior ? 1 : 0) + (lowerExpansionPrior ? 1 : 0) + (upperReturnPrior ? 1 : 0) + (lowerReturnPrior ? 1 : 0)
string eventContext = ""
string eventMechanics = ""
// GRID-STEP LONG / FLAT CYCLE · no separate indicator signals.
// All visible base steps participate. Buffer offsets the exact entry/exit line.
// BUY must also clear the same buffered step in the PREVIOUS confirmed grid,
// on a rising close. Movement of the current grid alone cannot qualify it.
// SELL uses the current buffered guide without a price-direction veto or an
// extra waiting candle. Its base INDEX never falls while Long; its PRICE can.
var bool signalLong = false
var int signalAnchor = na
var int signalPeak = na
// Startup protection: an initial reading above the upper base must first
// return to/below its entry base. After a regular exit this test is already met.
var bool signalArmed = false
bool signalCommit = ready and barstate.isconfirmed
bool buySignal = false
bool sellSignal = false
int cycleEventLevel = na
float cycleEventUnits = na
if signalCommit
int _downLevel = int(math.max(-levels, math.min(levels - 1, math.ceil(gridUnits))))
int _upLevel = int(math.max(-levels + 1, math.min(levels, math.floor(gridUnits))))
if signalLong
signalPeak := na(signalPeak) ? _upLevel : math.max(signalPeak, _upLevel)
int _exitLevel = signalPeak - 1
float _exitUnits = _exitLevel - signalBuffer
if gridUnits < _exitUnits
sellSignal := true
cycleEventLevel := _exitLevel
cycleEventUnits := _exitUnits
signalLong := false
signalPeak := na
signalAnchor := _downLevel
signalArmed := gridUnits <= signalAnchor + 1
else
signalAnchor := na(signalAnchor) ? _downLevel : math.min(signalAnchor, _downLevel)
int _entryLevel = signalAnchor + 1
float _entryUnits = _entryLevel + signalBuffer
if gridUnits <= _entryLevel
signalArmed := true
bool _priceRecovery = motionReady and not na(close[1]) and close > close[1] and fixedGridUnits > _entryUnits
if signalArmed and gridUnits > _entryUnits and _priceRecovery
buySignal := true
cycleEventLevel := _entryLevel
cycleEventUnits := _entryUnits
signalLong := true
signalPeak := _upLevel
signalArmed := false
int actionLevel = signalLong ? signalPeak - 1 : na(signalAnchor) ? na : signalAnchor + 1
float actionUnits = na(actionLevel) ? na : actionLevel + (signalLong ? -signalBuffer : signalBuffer)
float actionPrice = ready and not na(actionUnits) ? center + interval * actionUnits : na
bool entryPriceConfirmed = motionReady and not na(actionUnits) and close > close[1] and fixedGridUnits > actionUnits
bool entryWaitingPrice = ready and not signalLong and signalArmed and not na(actionUnits) and gridUnits > actionUnits and not entryPriceConfirmed
// Break pending references at changes of level/role. Confirmed event endings
// below complete the old threshold separately, without joining opposite roles.
bool actionContinuous = not na(actionLevel[1]) and actionLevel == actionLevel[1] and signalLong == signalLong[1]
var string lastSetup = "None"
var int lastSetupBar = na
if buySignal or sellSignal
lastSetup := buySignal ? "BUY" : "SELL"
lastSetupBar := bar_index
var string lastEvent = "None"
var int lastEventBar = na
var string lastEventContext = "No event yet"
var string lastEventMechanics = "Waiting for a confirmed crossing."
if hasEvent
// Allocate event descriptions only when a confirmed Grid event exists.
eventRole := (upperReturn ? "Return below +" + str.tostring(eventLevel) : lowerReturn ? "Return above -" + str.tostring(eventLevel) : "")
eventRole := eventRole + ((upperReturn or lowerReturn) and eventExpansion ? " / " : "") + (upperExpansion ? "Expansion above +" + str.tostring(eventLevel) : lowerExpansion ? "Expansion below -" + str.tostring(eventLevel) : "")
eventContext := priorCrossCount == eventCount ? "Previous Grid also crossed" : priorCrossCount == 0 ? "Moving grid required" : "Mixed · Previous Grid / moving grid"
eventMechanics := "\nPrevious Grid comparison: " + eventContext + ".\nActual " + str.tostring(gridUnits, "0.00") + " steps; Previous Grid " + str.tostring(fixedGridUnits, "0.00") + " steps."
eventMechanics := eventMechanics + "\nChange split (current grid steps): Price " + str.tostring(priceContribution, "0.000") + "; Center " + str.tostring(centerContribution, "0.000") + "; Spacing " + str.tostring(widthContribution, "0.000") + "."
lastEvent := eventRole
lastEventBar := bar_index
lastEventContext := eventContext
lastEventMechanics := eventMechanics
// ---------------------------------------------------------------------
// Price grid. Upper/lower hues describe price location, not trade direction.
// Nearby lines remain intact. The fade affects opacity only, never geometry.
// ---------------------------------------------------------------------
bool gridReferenceVisible = showChartEvents or showOscillator and showPaneEvents
// Native chart bars use the same current neutral-zone color as the oscillator. No
// duplicate candle series and no one-bar offset. na preserves native colors.
barcolor(colorBars and ready ? distanceInk : na, title="Grid Position Bar Color", editable=false)
f_levelInk(int _level) =>
bool _selected = not na(actionLevel) and _level == actionLevel
bool _outer = math.abs(_level) == levels
float _base = _selected ? 22.0 : 58.0
int _alpha = na(gridUnits) ? 90 : _outer ? (showChartGlow ? 0 : 12) : int(math.min(_selected ? 58.0 : 88.0, _base + math.abs(gridUnits - _level) * 6.0))
color.new(_level > 0 ? aboveColor : belowColor, _alpha)
// Keep the named alert-source plot early, independent of chart glow layers.
pDistanceHalo = plot(showOscillator and showOscillatorGlow ? gridUnits : na, "Distance halo", color=color.new(distanceInk, paneHaloAlpha), linewidth=6, style=plot.style_linebr, editable=false, display=display.pane)
// Keep this named alert source populated even when its drawing is hidden.
// display.none suppresses visuals; replacing the series with na would blank
// the four Grid alert placeholders while their conditions remain active.
pDistance = plot(gridUnits, "Grid steps", color=color.new(distanceInk, 0), linewidth=2, style=plot.style_linebr, precision=2, editable=false, display=showOscillator ? display.pane + display.data_window : display.none)
// Concentric strokes share exactly one price path per side. Wide halo first,
// brighter inner glow second; the existing grid plot supplies the sharp core.
// All glow colors/widths depend only on inputs, without per-bar glow modulation.
pOuterUpper = plot(showGrid and showChartGlow and ready ? center + interval * levels : na, "Upper edge halo", color=color.new(aboveColor, edgeHaloAlpha), linewidth=edgeHaloWidth, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pOuterLower = plot(showGrid and showChartGlow and ready ? center - interval * levels : na, "Lower edge halo", color=color.new(belowColor, edgeHaloAlpha), linewidth=edgeHaloWidth, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pEdgeGlowUpper = plot(showGrid and showChartGlow and ready ? center + interval * levels : na, "Upper edge inner glow", color=color.new(aboveColor, edgeGlowAlpha), linewidth=edgeGlowWidth, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pEdgeGlowLower = plot(showGrid and showChartGlow and ready ? center - interval * levels : na, "Lower edge inner glow", color=color.new(belowColor, edgeGlowAlpha), linewidth=edgeGlowWidth, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pCenterHalo = plot(showCenter and showChartGlow and ready ? center : na, "Center halo", color=color.new(centerInk, centerHaloAlpha), linewidth=10, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pCenter = plot(showCenter and ready ? center : na, "Grid center", color=color.new(centerInk, 0), linewidth=3, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pUpper1 = plot(showGrid and ready ? center + interval : na, "+1 price", color=f_levelInk(1), linewidth=levels == 1 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 1 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pLower1 = plot(showGrid and ready ? center - interval : na, "-1 price", color=f_levelInk(-1), linewidth=levels == 1 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 1 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pUpper2 = plot(showGrid and ready and levels >= 2 ? center + interval * 2 : na, "+2 price", color=f_levelInk(2), linewidth=levels == 2 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 2 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pLower2 = plot(showGrid and ready and levels >= 2 ? center - interval * 2 : na, "-2 price", color=f_levelInk(-2), linewidth=levels == 2 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 2 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pUpper3 = plot(showGrid and ready and levels >= 3 ? center + interval * 3 : na, "+3 price", color=f_levelInk(3), linewidth=levels == 3 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 3 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pLower3 = plot(showGrid and ready and levels >= 3 ? center - interval * 3 : na, "-3 price", color=f_levelInk(-3), linewidth=levels == 3 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 3 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pUpper4 = plot(showGrid and ready and levels >= 4 ? center + interval * 4 : na, "+4 price", color=f_levelInk(4), linewidth=levels == 4 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 4 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pLower4 = plot(showGrid and ready and levels >= 4 ? center - interval * 4 : na, "-4 price", color=f_levelInk(-4), linewidth=levels == 4 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 4 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pUpper5 = plot(showGrid and ready and levels >= 5 ? center + interval * 5 : na, "+5 price", color=f_levelInk(5), linewidth=levels == 5 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 5 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
pLower5 = plot(showGrid and ready and levels >= 5 ? center - interval * 5 : na, "-5 price", color=f_levelInk(-5), linewidth=levels == 5 ? (showChartGlow ? 2 : 3) : 1, linestyle=gridReferenceVisible and eventLevel == 5 ? plot.linestyle_dotted : plot.linestyle_solid, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
// Full-grid surfaces fade to transparency at the moving center. Their stronger
// outer color and wide halos establish the frame; intermediate rails stay quiet.
fill(pOuterUpper, pOuterLower, top_value=center + interval * levels, bottom_value=center,
top_color=color.new(aboveColor, showChartGlow ? chartSurfaceAlpha : 100), bottom_color=color.new(aboveColor, 100),
title="Upper grid gradient", fillgaps=false, editable=false)
fill(pOuterUpper, pOuterLower, top_value=center, bottom_value=center - interval * levels,
top_color=color.new(belowColor, 100), bottom_color=color.new(belowColor, showChartGlow ? chartSurfaceAlpha : 100),
title="Lower grid gradient", fillgaps=false, editable=false)
pActionGuide = plot(showSignalGuide and actionContinuous ? actionPrice : na, "Next Entry / Exit Price", color=color.new(signalLong ? chart.fg_color : aboveColor, 0), linewidth=3, linestyle=plot.linestyle_dashed, style=plot.style_linebr, editable=false, display=display.pane, force_overlay=true)
// ---------------------------------------------------------------------
// Oscillator: native grid units, unbounded, no independent smoothing.
// ---------------------------------------------------------------------
pZero = plot(showOscillator and ready ? 0.0 : na, "Oscillator fill baseline", color=na, display=display.none, editable=false)
// Each half fades to full transparency AT zero. Both halves use the same
// contour and zero mask; the opposite half is transparent outside its bounds.
fill(pDistance, pZero, top_value=float(levels), bottom_value=0.0,
top_color=color.new(aboveColor, showOscillatorGlow ? paneSurfaceAlpha : 100), bottom_color=color.new(aboveColor, 100),
title="Positive distance glow", fillgaps=false, editable=false)
fill(pDistance, pZero, top_value=0.0, bottom_value=-float(levels),
top_color=color.new(belowColor, 100), bottom_color=color.new(belowColor, showOscillatorGlow ? paneSurfaceAlpha : 100),
title="Negative distance glow", fillgaps=false, editable=false)
hline(0, "Center · 0", color=color.new(chart.fg_color, 55), display=showOscillator ? display.all : display.none)
hline(1, "+1 grid step", color=color.new(aboveColor, levels == 1 ? 68 : 85), linewidth=1, linestyle=hline.style_dotted, display=showOscillator ? display.all : display.none)
hline(-1, "-1 grid step", color=color.new(belowColor, levels == 1 ? 68 : 85), linewidth=1, linestyle=hline.style_dotted, display=showOscillator ? display.all : display.none)
hline(2, "+2 grid steps", color=color.new(aboveColor, levels == 2 ? 68 : 89), linewidth=1, linestyle=hline.style_dotted, display=showOscillator and levels >= 2 ? display.all : display.none)
hline(-2, "-2 grid steps", color=color.new(belowColor, levels == 2 ? 68 : 89), linewidth=1, linestyle=hline.style_dotted, display=showOscillator and levels >= 2 ? display.all : display.none)
hline(3, "+3 grid steps", color=color.new(aboveColor, levels == 3 ? 68 : 89), linewidth=1, linestyle=hline.style_dotted, display=showOscillator and levels >= 3 ? display.all : display.none)
hline(-3, "-3 grid steps", color=color.new(belowColor, levels == 3 ? 68 : 89), linewidth=1, linestyle=hline.style_dotted, display=showOscillator and levels >= 3 ? display.all : display.none)
hline(4, "+4 grid steps", color=color.new(aboveColor, levels == 4 ? 68 : 89), linewidth=1, linestyle=hline.style_dotted, display=showOscillator and levels >= 4 ? display.all : display.none)
hline(-4, "-4 grid steps", color=color.new(belowColor, levels == 4 ? 68 : 89), linewidth=1, linestyle=hline.style_dotted, display=showOscillator and levels >= 4 ? display.all : display.none)
hline(5, "+5 grid steps", color=color.new(aboveColor, levels == 5 ? 68 : 89), linewidth=1, linestyle=hline.style_dotted, display=showOscillator and levels >= 5 ? display.all : display.none)
hline(-5, "-5 grid steps", color=color.new(belowColor, levels == 5 ? 68 : 89), linewidth=1, linestyle=hline.style_dotted, display=showOscillator and levels >= 5 ? display.all : display.none)
// Input-qualified hlines add no plot counts. The faint shells identify the
// interval from the inner grid reference to the outer visible boundary.
hInnerUpper = hline(1, "Upper inner mask", color=na, display=showOscillator ? display.all : display.none, editable=false)
hInnerLower = hline(-1, "Lower inner mask", color=na, display=showOscillator ? display.all : display.none, editable=false)
hOuterUpper = hline(levels, "Upper outer mask", color=na, display=showOscillator ? display.all : display.none, editable=false)
hOuterLower = hline(-levels, "Lower outer mask", color=na, display=showOscillator ? display.all : display.none, editable=false)
fill(hInnerUpper, hOuterUpper, color=color.new(aboveColor, showOscillator and showOscillatorGlow ? paneShellAlpha : 100), title="Upper extension surface", editable=false)
fill(hInnerLower, hOuterLower, color=color.new(belowColor, showOscillator and showOscillatorGlow ? paneShellAlpha : 100), title="Lower extension surface", editable=false)
pPaneActionGuide = plot(showOscillator and showSignalGuide and ready and actionContinuous ? actionUnits : na, "Next Entry / Exit Step", color=color.new(signalLong ? chart.fg_color : aboveColor, 18), linewidth=2, linestyle=plot.linestyle_dashed, style=plot.style_linebr, editable=false, display=display.pane)
// Finish the CHECKED threshold on the event candle. actionPrice now refers
// to the next role, so using it here would connect two different thresholds.
// Independent segments also handle adjacent BUY / SELL / BUY candles.
// These are display-only endpoints, not additional signals or historical fills.
var array<line> chartThresholdEnds = array.new<line>()
var array<line> paneThresholdEnds = array.new<line>()
f_keepThresholdEnd(array<line> _store, line _id) =>
array.push(_store, _id)
if array.size(_store) > 80
line.delete(array.shift(_store))
if showSignalGuide and (buySignal or sellSignal) and not na(actionPrice[1])
// The old phase's base is unchanged on its trigger candle: lowering an
// entry anchor or raising an exit peak cannot itself trigger that event.
bool _sameThreshold = cycleEventLevel == actionLevel[1] and signalLong[1] == sellSignal
if _sameThreshold
color _endInk = buySignal ? aboveColor : chart.fg_color
float _testedPrice = center + interval * cycleEventUnits
line _chartEnd = line.new(bar_index - 1, actionPrice[1], bar_index, _testedPrice,
xloc=xloc.bar_index, color=_endInk, style=line.style_dashed, width=3, force_overlay=true)
f_keepThresholdEnd(chartThresholdEnds, _chartEnd)
if showOscillator
line _paneEnd = line.new(bar_index - 1, actionUnits[1], bar_index, cycleEventUnits,
xloc=xloc.bar_index, color=color.new(_endInk, 18), style=line.style_dashed, width=2)
f_keepThresholdEnd(paneThresholdEnds, _paneEnd)
// ---------------------------------------------------------------------
// Fonts, fixed label stores and current boundary tags.
// Object ceiling: 160 grid-event labels + 80 position markers + 11 base tags
// + action tag + pane value + Motion Lens ghost = 254; insertion peak <= 256.
// Eleven base leaders + action leader + comparison connector = 13 lines.
// Two stores retain at most 80 confirmed threshold endings each: peak 174 lines.
// ---------------------------------------------------------------------
int tableSize = textChoice == "Large" ? 14 : textChoice == "Normal" ? 12 : 11
int tagSize = tableSize
int signalEntrySize = markerSizeChoice == "Large" ? 32 : markerSizeChoice == "Normal" ? 26 : 20
int signalExitSize = markerSizeChoice == "Large" ? 36 : markerSizeChoice == "Normal" ? 30 : 24
// Display geometry only. Directional transparent styles already put text
// outside the anchor. Place that anchor just one tick beyond the event wick;
// adding a volatility-sized price pad would separate symbols too far.
// Range/size spacing below is reserved for optional context-marker lanes.
// No later bars, viewport assumptions or changes to event/threshold prices.
float markerRange = math.max(interval, nz(fastRange, interval))
float markerCandleRange = math.max(high - low, 0.0)
float markerSizeScale = markerSizeChoice == "Large" ? 1.15 : markerSizeChoice == "Normal" ? 1.0 : 0.90
float signalMarkerGap = syminfo.mintick
float contextMarkerGap = math.max(math.max(markerRange * 0.28, markerCandleRange * 0.12), syminfo.mintick * 6.0)
int heroSize = textChoice == "Large" ? 22 : textChoice == "Normal" ? 18 : 16
string tableCorner = summaryCorner == "Top Left" ? position.top_left : summaryCorner == "Top Right" ? position.top_right : summaryCorner == "Bottom Left" ? position.bottom_left : position.bottom_right
var array<label> priceTags = array.new<label>()
var array<line> tagLeaders = array.new<line>()
var label actionPriceTag = na
var line actionTagLeader = na
var label paneValueTag = na
var label motionGhost = na
var line motionLink = na
var array<label> setupMarkers = array.new<label>()
var array<label> chartEvents = array.new<label>()
var array<label> paneEvents = array.new<label>()
f_keepEvent(array<label> _store, label _id) =>
array.push(_store, _id)
if array.size(_store) > 80
label.delete(array.shift(_store))
// One symbol per position event. Keep at most 80 events and remove whole
// oldest entry/exit pairs, never leaving the exit of a deleted entry.
f_keepCycleEvent(array<label> _store, label _id) =>
array.push(_store, _id)
if array.size(_store) > 80
label.delete(array.shift(_store))
label.delete(array.shift(_store))
if showBuySell and (buySignal or sellSignal)
float _markerY = buySignal ? low - signalMarkerGap : high + signalMarkerGap
string _markerStyle = buySignal ? label.style_label_up : label.style_label_down
color _ink = buySignal ? aboveColor : chart.fg_color
int _markerSize = buySignal ? signalEntrySize : signalExitSize
string _glyph = buySignal ? "▲" : "×"
string _tip = (buySignal ? "BUY · virtual Long entry" : "SELL · virtual Long exit") + "\n" + (buySignal ? "Confirmed recovery above the buffered next grid step, also in the Previous Grid, with a rising close." : "Confirmed close below the buffered exit line, one step below the highest reached level. No extra waiting candle.") + "\nThreshold: " + str.tostring(cycleEventUnits, "0.00") + " grid steps (base step " + str.tostring(cycleEventLevel) + ") = " + str.tostring(center + interval * cycleEventUnits, format.mintick) + ".\nGrid movement can contribute. Candle close: " + str.tostring(close, format.mintick) + ".\nSymbol is anchored outside the event candle wick; height is visual clearance only. SELL closes Long, never opens Short. No broker order or simulated fill."
label _id = label.new(bar_index, _markerY, _glyph,
xloc=xloc.bar_index, yloc=yloc.price, style=_markerStyle, color=color.new(_ink, 100),
textcolor=_ink, size=_markerSize, text_formatting=text.format_bold,
tooltip=_tip, force_overlay=true)
f_keepCycleEvent(setupMarkers, _id)
if hasEvent
string _tip = eventRole + "\nConfirmed boundary event · " + distanceText + ".\nSelected boundary: +/-" + str.tostring(eventLevel) + ".\nPrice movement or movement of the center/spacing can cause a crossing.\nHollow circle = outward grid expansion; diamond = grid return. Entry triangles and exit crosses use separate rules. Not an order or a guaranteed reversal."
_tip := _tip + eventMechanics
if showChartEvents
// Reserve an outer lane only for a VISIBLE position marker on this side.
// An opposite-side event or hidden position marker needs no extra lane.
bool _sharesSignalSide = showBuySell and (eventUp ? buySignal : sellSignal)
float _laneGap = markerRange * 0.95 * markerSizeScale
float _pad = _sharesSignalSide ? signalMarkerGap + _laneGap : contextMarkerGap
label _id = label.new(bar_index, eventUp ? low - _pad : high + _pad, eventGlyph,
xloc=xloc.bar_index, yloc=yloc.price,
style=eventUp ? label.style_label_up : label.style_label_down,
textcolor=eventInk, color=color.new(eventInk, 100),
size=eventExpansion ? 14 : 16, tooltip=_tip, force_overlay=true)
f_keepEvent(chartEvents, _id)
if showOscillator and showPaneEvents
label _id = label.new(bar_index, gridUnits + (eventUp ? -0.25 : 0.25), eventGlyph,
style=label.style_none, textcolor=eventInk, color=color.new(eventInk, 100),
size=eventExpansion ? 12 : 14, tooltip=_tip, force_overlay=false)
f_keepEvent(paneEvents, _id)
// Eleven fixed object slots cover -5 ... +5. Hidden slots use na prices.
// Updating an existing tag avoids allocating a new tag/leader every live tick.
if barstate.isfirst
for _slot = 0 to 10
label _tag = label.new(bar_index, float(na), "", style=label.style_label_left,
color=color.new(chart.bg_color, 100), textcolor=chart.fg_color,
size=tagSize, force_overlay=true)
line _leader = line.new(bar_index, float(na), bar_index, float(na), force_overlay=true)
array.push(priceTags, _tag)
array.push(tagLeaders, _leader)
actionPriceTag := label.new(bar_index, float(na), "", style=label.style_label_left,
color=color.new(chart.bg_color, 100), textcolor=chart.fg_color,
size=tagSize, text_formatting=text.format_bold, force_overlay=true)
actionTagLeader := line.new(bar_index, float(na), bar_index, float(na), force_overlay=true)
if barstate.islast
for _slot = 0 to 10
int _level = _slot - 5
bool _essential = _level == 0 or math.abs(_level) == levels or advancedView and math.abs(_level) == 1
bool _enabled = math.abs(_level) <= levels and (_level == 0 ? showCenter : showGrid)
bool _visible = ready and _enabled and (priceTagMode == "All" or priceTagMode == "Focus" and _essential)
bool _selected = not na(actionLevel) and _level == actionLevel
float _price = _visible ? center + interval * _level : na
color _ink = _level > 0 ? aboveColor : _level < 0 ? belowColor : chart.fg_color
string _levelName = _level == 0 ? "0" : (_level > 0 ? "+" : "") + str.tostring(_level)
string _name = _level == 0 ? "CENTER" : _levelName + (math.abs(_level) == 1 ? " step" : " steps")
string _role = _level == 0 ? "Adaptive center" : math.abs(_level) == levels ? "Outer cycle anchor / limit" : "Grid step reference"
_role := _role + (_selected ? " · base of current entry/exit line; the separate Entry/Exit tag shows its buffered threshold" : "")
string _tip = _role + "\n" + _name + " = " + str.tostring(_price, format.mintick) + "\nExact current boundary on the last candle.\nOne grid step: " + str.tostring(interval, format.mintick) + ".\nHorizontal tag spacing is not a future projection."
label _tag = array.get(priceTags, _slot)
label.set_xy(_tag, bar_index + 4, _price)
label.set_text(_tag, _visible ? _name + " " + str.tostring(_price, format.mintick) : "")
label.set_textcolor(_tag, _ink)
label.set_color(_tag, color.new(_level == 0 ? chart.bg_color : _ink, _level == 0 ? 8 : _selected ? 87 : 94))
label.set_text_formatting(_tag, _selected or _level == 0 ? text.format_bold : text.format_none)
label.set_size(_tag, tagSize)
label.set_tooltip(_tag, _tip)
line _leader = array.get(tagLeaders, _slot)
line.set_xy1(_leader, bar_index, _price)
line.set_xy2(_leader, bar_index + 3, _price)
line.set_color(_leader, color.new(_ink, _selected ? 24 : 58))
line.set_style(_leader, line.style_solid)
bool _actionVisible = ready and showSignalGuide and priceTagMode != "Off" and not na(actionUnits)
color _actionInk = signalLong ? chart.fg_color : aboveColor
string _actionName = (signalLong ? "Exit <" : "Entry >") + (advancedView ? " " + (actionUnits > 0.0 ? "+" : "") + str.tostring(actionUnits, "0.00") + " steps" : "")
label.set_xy(actionPriceTag, bar_index + 9, _actionVisible ? actionPrice : na)
label.set_text(actionPriceTag, _actionVisible ? _actionName + " " + str.tostring(actionPrice, format.mintick) : "")
label.set_color(actionPriceTag, color.new(_actionInk, 87))
label.set_textcolor(actionPriceTag, _actionInk)
label.set_size(actionPriceTag, tagSize)
label.set_tooltip(actionPriceTag, (signalLong ? "SELL" : "BUY") + " buffered threshold\n" + _actionName + " = " + str.tostring(actionPrice, format.mintick) + ".\nBase step " + str.tostring(actionLevel) + "; buffer " + str.tostring(signalBuffer, "0.00") + " grid step.\nConfirmed close required." + (signalLong ? " No extra waiting candle." : " BUY also requires a rising close and recovery in the Previous Grid.") + "\nPending reference, not an already triggered signal or a guaranteed execution price.")
line.set_xy1(actionTagLeader, bar_index + 1, _actionVisible ? actionPrice : na)
line.set_xy2(actionTagLeader, bar_index + 8, _actionVisible ? actionPrice : na)
line.set_color(actionTagLeader, color.new(_actionInk, 24))
line.set_style(actionTagLeader, line.style_dashed)
if showOscillator and showPaneValue and ready
if na(paneValueTag)
paneValueTag := label.new(bar_index + 3, gridUnits, distanceText, style=label.style_label_left,
color=color.new(distanceInk, 85), textcolor=chart.fg_color, size=tagSize,
tooltip="Distance from center: +1 grid step = one line spacing above it; -1 = one below. Gray means within Neutral Zone, not an unavailable value. Not percent or probability. No extra oscillator smoothing.", force_overlay=false)
label.set_xy(paneValueTag, bar_index + 3, gridUnits)
label.set_text(paneValueTag, distanceText)
label.set_color(paneValueTag, color.new(distanceInk, 85))
label.set_size(paneValueTag, tagSize)
else if not na(paneValueTag)
label.delete(paneValueTag)
paneValueTag := na
// Motion Lens uses one reusable ghost and connector. Both values refer to
// THIS candle. The horizontal offset is solely for legibility.
if barstate.islast and showOscillator and showMotionLens and motionReady
if na(motionGhost)
motionGhost := label.new(bar_index + 1, fixedGridUnits, "⊕", style=label.style_none,
color=color.new(chart.bg_color, 100), textcolor=color.new(chart.fg_color, 18), size=14)
motionLink := line.new(bar_index + 1, gridUnits, bar_index + 1, fixedGridUnits,
color=color.new(chart.fg_color, 48), style=line.style_dotted, width=1)
label.set_xy(motionGhost, bar_index + 1, fixedGridUnits)
label.set_tooltip(motionGhost, "PREVIOUS GRID · " + str.tostring(fixedGridUnits, "0.00") + " steps\nCurrent close measured in the previous confirmed center and grid step.\nActual reading: " + str.tostring(gridUnits, "0.00") + " steps.\nThe dotted gap shows the combined effect of center and spacing changes. If the grids agree, the comparison point overlaps the actual reading.\nThis point is a comparison on the current candle, not a signal or a forecast.")
line.set_xy1(motionLink, bar_index + 1, gridUnits)
line.set_xy2(motionLink, bar_index + 1, fixedGridUnits)
else if barstate.islast and not na(motionGhost)
label.set_y(motionGhost, float(na))
line.set_xy1(motionLink, bar_index + 1, float(na))
line.set_xy2(motionLink, bar_index + 1, float(na))
// ---------------------------------------------------------------------
// Summary: exact live number, bounded location meter, separate diagnostics.
// Meter positions are geometric locations, never a score or probability.
// ---------------------------------------------------------------------
f_meterIndex(float _units, int _levels) =>
int(math.round((math.max(-float(_levels), math.min(float(_levels), _units)) / _levels + 1.0) * 5.0))
f_units(float _value) =>
(_value > 0.0 ? "+" : "") + str.tostring(_value, "0.00")
f_cardCell(table _table, int _col, int _row, string _text, color _ink, color _bg, string _align, bool _bold, int _size, string _tip) =>
table.cell(_table, _col, _row, _text, text_color=_ink, bgcolor=_bg,
text_size=_size, text_halign=_align,
text_formatting=_bold ? text.format_bold : text.format_none, tooltip=_tip)
var table summary = na
if barstate.islast and showSummary
if na(summary)
summary := table.new(tableCorner, 11, advancedView ? 12 : 7, bgcolor=color.new(chart.bg_color, 3),
frame_color=color.new(chart.fg_color, 85), frame_width=1, border_width=0, force_overlay=false)
table.merge_cells(summary, 0, 0, 6, 0)
table.merge_cells(summary, 7, 0, 10, 0)
table.merge_cells(summary, 0, 1, 3, 1)
table.merge_cells(summary, 4, 1, 10, 1)
table.merge_cells(summary, 0, 2, 3, 2)
table.merge_cells(summary, 4, 2, 10, 2)
table.merge_cells(summary, 0, 3, 10, 3)
table.merge_cells(summary, 0, 4, 4, 4)
table.merge_cells(summary, 5, 4, 10, 4)
table.merge_cells(summary, 0, 5, 5, 5)
table.merge_cells(summary, 6, 5, 10, 5)
table.merge_cells(summary, 0, 6, 5, 6)
table.merge_cells(summary, 6, 6, 10, 6)
if advancedView
// Row 7 is the optional eleven-cell location meter.
table.merge_cells(summary, 0, 8, 3, 8)
table.merge_cells(summary, 4, 8, 6, 8)
table.merge_cells(summary, 7, 8, 10, 8)
table.merge_cells(summary, 0, 9, 5, 9)
table.merge_cells(summary, 6, 9, 10, 9)
table.merge_cells(summary, 0, 10, 3, 10)
table.merge_cells(summary, 4, 10, 6, 10)
table.merge_cells(summary, 7, 10, 10, 10)
table.merge_cells(summary, 0, 11, 6, 11)
table.merge_cells(summary, 7, 11, 10, 11)
color _bg = color.new(chart.bg_color, 3)
color _quiet = color.new(chart.fg_color, 35)
color _headerBg = color.new(neutralColor, 94)
string _liveTip = "Distance and threshold prices update on the open candle. Position and entry/exit events change only at confirmed close. Latest available candle; this card does not follow the crosshair. No broker-account data is read."
f_cardCell(summary, 0, 0, "WIZTRADER / GRID", chart.fg_color, _headerBg, text.align_left, true, tableSize,
"Adaptive center; one shared grid on the current timeframe. Center Response " + str.tostring(centerLength) + "; Spacing Smoothness " + str.tostring(gridSmoothness) + ". Display Detail never resets calculation settings.")
f_cardCell(summary, 7, 0, barstate.isconfirmed ? "Bar closed" : "Bar open", _quiet, _headerBg, text.align_right, true, tableSize, _liveTip)
string _positionText = signalLong ? "Long open" : "No position"
f_cardCell(summary, 0, 1, "Position", _quiet, _bg, text.align_left, false, tableSize, "The indicator's virtual position. This is not your broker-account position.")
f_cardCell(summary, 4, 1, _positionText, signalLong ? aboveColor : chart.fg_color, _bg, text.align_right, true, tableSize, _liveTip)
string _lastRole = lastSetup == "BUY" ? "▲ Entry" : lastSetup == "SELL" ? "× Exit" : "No signal yet"
string _lastAge = na(lastSetupBar) ? "" : lastSetupBar == bar_index ? " · this candle" : " · " + str.tostring(bar_index - lastSetupBar) + " candles ago"
f_cardCell(summary, 0, 2, "Last signal", _quiet, _bg, text.align_left, false, tableSize, "Latest confirmed entry or exit, independently of optional Grid crossings.")
f_cardCell(summary, 4, 2, _lastRole + _lastAge, lastSetup == "BUY" ? aboveColor : chart.fg_color, _bg, text.align_right, false, tableSize, "The triangle records entry; the cross records exit. These roles never mean Short entry.")
string _nextAction = not ready ? "Waiting for enough candles" : na(actionLevel) ? "Entry: waiting for first candle close" : signalLong ? (gridUnits < actionUnits and not barstate.isconfirmed ? "Exit: waiting for candle close" : "Exit: close below " + str.tostring(actionPrice, format.mintick)) : not signalArmed ? (gridUnits <= actionLevel and not barstate.isconfirmed ? "Entry: waiting for close to arm" : "Entry: return to " + str.tostring(center + interval * actionLevel, format.mintick) + " first") : entryWaitingPrice ? (not motionReady ? "Entry: waiting for Previous Grid data" : close <= close[1] ? "Entry: waiting for a rising close" : "Entry: also close above " + str.tostring(center[1] + interval[1] * actionUnits, format.mintick)) : gridUnits > actionUnits and entryPriceConfirmed and not barstate.isconfirmed ? "Entry: waiting for candle close" : "Entry: close above " + str.tostring(actionPrice, format.mintick) + " + rising"
f_cardCell(summary, 0, 3, _nextAction, chart.fg_color, _headerBg, text.align_left, true, tableSize,
"NEXT CONDITION, NOT AN ORDER\nThe dashed threshold updates live. Entry requires a confirmed close above it, a rising close and recovery above the same buffered level in the Previous Grid. Exit requires a confirmed close below the current exit line, without an extra waiting candle. Equality does not trigger. Displayed prices are rounded to the minimum tick; comparisons use unrounded references. The moving line is not a fixed-price stop or guaranteed fill.")
string _distanceSide = not ready ? "Distance from center" : gridUnits > 0.0 ? "Above center" : gridUnits < 0.0 ? "Below center" : "At center"
f_cardCell(summary, 0, 4, _distanceSide, _quiet, _bg, text.align_left, false, tableSize, "One grid step is one gap between adjacent grid lines. + means above center; - means below.")
f_cardCell(summary, 5, 4, ready ? str.tostring(math.abs(gridUnits), "0.00") + " steps" : "—", distanceInk, _bg, text.align_right, true, heroSize,
"Current distance from center, measured in grid steps. Example: +2 means two current line spacings above center. Gray inside Neutral Zone changes only the color, never the reading. Not percent, probability or measured order flow. Readings remain unbounded.")
f_cardCell(summary, 0, 5, "1 grid step", _quiet, _bg, text.align_left, false, tableSize, "Price difference between two adjacent grid lines. This spacing changes with the grid.")
f_cardCell(summary, 6, 5, ready ? str.tostring(interval, format.mintick) + (syminfo.currency == "" ? "" : " " + syminfo.currency) : "—", chart.fg_color, _bg, text.align_right, false, tableSize, "Both chart and oscillator use this exact spacing.")
f_cardCell(summary, 0, 6, "▲ Entry", aboveColor, _headerBg, text.align_left, true, tableSize, "▲ opens the indicator's virtual Long. The chart marker contains only the glyph; this row explains it.")
f_cardCell(summary, 6, 6, "× Exit", chart.fg_color, _headerBg, text.align_right, true, tableSize, "× closes Long. It never opens Short. Both event types wait for close.")
if advancedView
int _active = ready ? f_meterIndex(gridUnits, levels) : -1
for _cell = 0 to 10
float _location = (_cell - 5.0) * levels / 5.0
color _hue = _cell > 5 ? aboveColor : _cell < 5 ? belowColor : neutralColor
bool _lit = _cell == _active
bool _path = ready and (_active > 5 ? _cell >= 5 and _cell <= _active : _cell <= 5 and _cell >= _active)
string _glyph = _lit ? (math.abs(gridUnits) > levels ? (gridUnits > 0.0 ? "▸" : "◂") : "◆") : "·"
table.cell(summary, _cell, 7, _glyph, text_color=_lit ? chart.fg_color : color.new(_hue, 45),
bgcolor=color.new(_hue, _lit ? 55 : _path ? 85 : 97), text_size=tableSize,
text_halign=text.align_center,
tooltip="Location near " + f_units(_location) + " grid steps. This meter is bounded by the displayed outer lines; the exact numerical distance is not clipped. It is not a strength score.")
f_cardCell(summary, 0, 8, "-" + str.tostring(levels) + (levels == 1 ? " step" : " steps"), belowColor, _bg, text.align_left, false, tableSize, "Lower displayed grid edge, not a lower bound on the distance.")
f_cardCell(summary, 4, 8, "Center · 0", _quiet, _bg, text.align_center, false, tableSize, "Zero means price equals center.")
f_cardCell(summary, 7, 8, "+" + str.tostring(levels) + (levels == 1 ? " step" : " steps"), aboveColor, _bg, text.align_right, false, tableSize, "Upper displayed grid edge, not an upper bound on the distance.")
string _slope = not ready ? "Center · Waiting" : math.abs(centerSlope) <= interval * 0.015 ? "Center · Flat" : centerSlope > 0.0 ? "Center · Rising" : "Center · Falling"
f_cardCell(summary, 0, 9, _slope, centerInk, _headerBg, text.align_left, false, tableSize, "Center slope is separate from price location. Diagnostic only.")
f_cardCell(summary, 6, 9, "Spacing · " + widthState, _quiet, _headerBg, text.align_right, false, tableSize, "Spacing versus its slower exponential reference. Diagnostic only.")
string _splitTip = "Distance change = Price + Center + Spacing contributions, using the current spacing. Signed accounting terms, not independent confirmations or unique causation. Change: " + (motionReady ? f_units(distanceChange) : "—") + " steps."
f_cardCell(summary, 0, 10, "Price\n" + (motionReady ? f_units(priceContribution) : "—"), _quiet, _bg, text.align_left, false, tableSize, _splitTip)
f_cardCell(summary, 4, 10, "Center\n" + (motionReady ? f_units(centerContribution) : "—"), _quiet, _bg, text.align_center, false, tableSize, _splitTip)
f_cardCell(summary, 7, 10, "Spacing\n" + (motionReady ? f_units(widthContribution) : "—"), _quiet, _bg, text.align_right, false, tableSize, _splitTip)
f_cardCell(summary, 0, 11, na(lastEventBar) ? "No grid crossing yet" : lastEvent, _quiet, _headerBg, text.align_left, false, tableSize, "Optional Grid crossing at +/-" + str.tostring(eventLevel) + " steps. " + lastEventContext + "." + lastEventMechanics)
f_cardCell(summary, 7, 11, na(lastEventBar) ? "—" : str.tostring(bar_index - lastEventBar) + " candles ago", _quiet, _headerBg, text.align_right, false, tableSize, "Crossing-event age, separate from the last position signal.")
// ---------------------------------------------------------------------
// Six named, confirmed-close conditions. Marker visibility is independent.
// Create each desired condition directly, with Once Per Bar Close.
// Recreate alerts after changing script code or relevant inputs.
// ---------------------------------------------------------------------
alertcondition(upperExpansion, "Grid - Upper Expansion", "WizTrader Range Grid | Confirmed expansion above selected upper boundary | {{ticker}} | TF {{interval}} | Close {{close}} | Grid steps {{plot(\"Grid steps\")}}")
alertcondition(lowerExpansion, "Grid - Lower Expansion", "WizTrader Range Grid | Confirmed expansion below selected lower boundary | {{ticker}} | TF {{interval}} | Close {{close}} | Grid steps {{plot(\"Grid steps\")}}")
alertcondition(upperReturn, "Grid - Return from Upper", "WizTrader Range Grid | Confirmed return below selected upper boundary | {{ticker}} | TF {{interval}} | Close {{close}} | Grid steps {{plot(\"Grid steps\")}}")
alertcondition(lowerReturn, "Grid - Return from Lower", "WizTrader Range Grid | Confirmed return above selected lower boundary | {{ticker}} | TF {{interval}} | Close {{close}} | Grid steps {{plot(\"Grid steps\")}}")
alertcondition(buySignal, "Signal - BUY", "WizTrader Range Grid | BUY - Virtual Long entry confirmed | Buffered grid recovery in current and Previous Grid with rising close while Flat | {{ticker}} | TF {{interval}} | Close {{close}} | Grid steps {{plot(\"Grid steps\")}}")
alertcondition(sellSignal, "Signal - SELL", "WizTrader Range Grid | SELL - Virtual Long exit confirmed | Close below the buffered exit line while Long | {{ticker}} | TF {{interval}} | Close {{close}} | Grid steps {{plot(\"Grid steps\")}}")