本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © officialjackofalltrades
//@version=6
indicator("Market Structure Map [JOAT]", "Market Structure Map", overlay = true,
max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 0. SAFETY
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
max_bars_back(time, 5000)
// Scale anchor: a script that only draws boxes / lines / labels can land on its own price scale on a customer's
// chart. One invisible plot pins it to the price scale. display.pane keeps it out of the status line and data window.
plot(close, "Scale anchor (invisible)", color = color.new(#000000, 100), display = display.pane, editable = false)
float atrK = ta.atr(14) // shared ATR for glow padding, lane gaps, break legs and range size
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 7. STRUCTURE INPUTS (declared first so they lead the Settings dialog; the kit blocks follow)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G7 = "Structure"
int swingLen = input.int(12, "Swing pivot length", minval = 5, maxval = 50, group = G7,
tooltip = "Bars on each side a high or low must dominate to count as a SWING pivot. 10-15 is the usual range. A pivot is confirmed only after this many bars have closed to its right, so it never repaints.")
int intLen = input.int(4, "Internal pivot length", minval = 2, maxval = 10, group = G7,
tooltip = "Same rule for the fine INTERNAL structure. 3-5 reads the small legs inside the swing legs.")
bool showInternal = input.bool(false, "Show internal structure", group = G7,
tooltip = "Draw the internal iBOS / iCHoCH lines (thinner, one-line tags) and the internal pivot letters. Off by default: on a 5m or 1m chart they crowd the candles. The internal bias is still computed for the dashboard's Internal row when this is off.")
bool showBOS = input.bool(true, "Show BOS", group = G7,
tooltip = "BOS = break of structure: a confirmed close through the last swing high while structure is bullish (or through the last swing low while bearish). Read as continuation of the structure. Solid line.")
bool showCHoCH = input.bool(true, "Show CHoCH", group = G7,
tooltip = "CHoCH = change of character: the first confirmed close against the structure. Drawn DASHED with its own word in bold so it never reads as a BOS.")
int maxEvSw = input.int(10, "Swing events kept", minval = 2, maxval = 40, group = G7,
tooltip = "Visible swing BOS / CHoCH lines and tags. Oldest retire first; the latest swing CHoCH is always kept so the dashboard's 'Last CHoCH' stays on the chart.")
int maxEvIn = input.int(4, "Internal events kept", minval = 1, maxval = 4, group = G7,
tooltip = "Visible internal iBOS / iCHoCH lines and tags, newest first. Capped at 4 so the internal layer never buries the swing structure.")
bool greyFailed = input.bool(true, "Grey out failed breaks", group = G7,
tooltip = "When price later closes back through a broken level, that BOS / CHoCH turns grey and dotted and its tag says 'failed': the break did not hold.")
bool showBreakSz = input.bool(true, "Leg size on the tag", group = G7,
tooltip = "Adds the size of the leg that produced the break, in ATR, to every BOS / CHoCH tag: 'BOS ▲ 24,550.25 +1.2 ATR'. The sign is the direction. The leg runs from the opposite extreme (the lowest low before an up-break, the highest high before a down-break) to the break close.")
string evDetail = input.string("Two lines", "Swing event tag", options = ["Two lines", "One line"], group = G7,
tooltip = "Two lines: 'BOS ▲ price +ATR' over a small 'leg N pts · N bars'. One line: 'BOS ▲ price +ATR · N bars', for very fast charts. Internal tags are always one short line.")
bool eventGlow = input.bool(true, "Glow on the freshest event", group = G7,
tooltip = "Only the most recent swing-scale event glows; the rest stay flat. Glow is a state, not a decoration.")
int lineW = input.int(2, "Swing line width", minval = 1, maxval = 3, group = G7)
string G8 = "Labels"
bool showSwingTags = input.bool(true, "Swing tags (H / L / HH / HL / LH / LL)", group = G8,
tooltip = "Highs are tagged above the candle in the bear colour, lows below the candle in the bull colour.")
bool showIntTags = input.bool(true, "Internal tags", group = G8, tooltip = "Letters on the internal pivots (HH / HL / LH / LL), shown only while 'Show internal structure' is on. Turn off on very fast charts if it gets busy.")
bool swingPx = input.bool(true, "Price on swing tags", group = G8, tooltip = "'HH 24,550.25' instead of 'HH'.")
string tagSizeStr = input.string("Small", "Tag size", options = ["Small", "Normal", "Large"], group = G8,
tooltip = "Size of the swing tags and swing event tags. Internal tags are one step smaller, never below Small, so every tag stays readable.")
float laneGap = input.float(0.8, "Label gap (ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = G8,
tooltip = "Vertical room one tag line takes, in ATR. Tags that would touch another tag nearby are stacked away from the candles by this much; right-edge tags keep at least this distance. Larger = more spread.")
string G9 = "Dealing range"
bool showRange = input.bool(true, "Show dealing range", group = G9,
tooltip = "The box between the last confirmed swing low and swing high, trailed to any newer extreme printed since. The upper half (premium) is tinted in the bear colour, the lower half (discount) in the bull colour, fading toward the equilibrium.")
int rangeExt = input.int(8, "Range extension (bars)", minval = 1, maxval = 60, group = G9,
tooltip = "How far past the last candle the range box reaches. The right-edge tags start just after it.")
int gradBands = input.int(4, "Gradient bands per half", minval = 1, maxval = 6, group = G9,
tooltip = "Each half of the range is drawn as this many bands that fade from the edge toward the equilibrium. 1 = flat tint.")
float eqBandPct = input.float(5.0, "Equilibrium band (± %)", minval = 0.0, maxval = 20.0, step = 0.5, group = G9,
tooltip = "The close is called 'equilibrium' while it sits within this many percent of the 50 % line.")
bool showQuartiles = input.bool(false, "Quartile lines (25 % / 75 %)", group = G9)
bool showRangeTags = input.bool(true, "Range tags", group = G9,
tooltip = "Short right-edge data tags: STRONG / WEAK HIGH and LOW with price (RANGE HIGH / LOW before structure forms), RANGE with its size in points and ATR, EQ with its price, PREMIUM 50-100 % and DISCOUNT 0-50 %. Hover a tag for its band prices and details.")
bool showCloseTag = input.bool(true, "Close position tag", group = G9,
tooltip = "Right-edge tag at the close: 'close 68 % · premium'. Hover it for the distance from EQ in ATR.")
bool showOTE = input.bool(false, "OTE band (62-79 %)", group = G9,
tooltip = "Optional faint stripe at the 62-79 % retracement of the dealing range, measured from the latest extreme: inside discount when the swing structure is bullish, inside premium when bearish. It is a zone to read, not a signal.")
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 1. THEME
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G1 = "Theme"
string theme = input.string("JOAT Signature", "Theme", group = G1,
options = ["JOAT Signature", "Midnight Blue / Red", "Aurora Night", "Delta Cyan / Pink", "Paper & Ink", "Lime Ember", "Custom"],
tooltip = "Named presets. JOAT Signature is the brand pair. Paper & Ink is the clean black / white preset: direction is carried by position and line style, not colour. Custom uses the colour pickers below.")
int bright = input.int(3, "Brightness", minval = 1, maxval = 5, group = G1,
tooltip = "1 = faint, 3 = as designed, 5 = vivid. Scales every fill and glow transparency; solid lines and plates stay solid.")
string bgMode = input.string("Auto", "Chart background", options = ["Auto", "Dark", "Light"], group = G1,
tooltip = "Auto reads the luminance of the chart background and swaps every role so it stays readable on a white chart.")
color inBull = input.color(#5CF0D7, "Custom bull / bear", group = G1, inline = "c1")
color inBear = input.color(#B32AC3, "", group = G1, inline = "c1")
color inAcc = input.color(#FFFFFF, "Custom accent / neutral", group = G1, inline = "c2")
color inNeu = input.color(#787B86, "", group = G1, inline = "c2")
color inTxt = input.color(#D1D4DC, "Custom text / panel", group = G1, inline = "c3")
color inPanel = input.color(#0E1116, "", group = G1, inline = "c3")
color inGlow = input.color(#5CF0D7, "Custom glow", group = G1, inline = "c4")
// f_lum: relative luminance 0..1 of any colour (Rec. 601 weights). Used for light / dark awareness and plate ink.
f_lum(color c) =>
(0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) / 255.0
bool isLight = bgMode == "Light" ? true : bgMode == "Dark" ? false : f_lum(chart.bg_color) > 0.5
bool isMono = theme == "Paper & Ink"
// Roles, resolved once. Defaults = JOAT Signature. Each preset overrides every role, with the white-chart swap.
color cBull = isLight ? #12B5A0 : #5CF0D7
color cBear = isLight ? #8E1FA0 : #B32AC3
color cAcc = isLight ? #131722 : #FFFFFF
color cNeu = #787B86
color cTxt = isLight ? #131722 : #D1D4DC
color cPanel = isLight ? #FFFFFF : #0E1116
color cGlow = isLight ? #12B5A0 : #5CF0D7
color cCandle = cAcc // colour for the "Mono" candle paint (white bodies on black, ink on white)
if theme == "Midnight Blue / Red"
cBull := #2962FF
cBear := #F23645
cAcc := isLight ? #131722 : #FFFFFF
cNeu := #787B86
cTxt := isLight ? #131722 : #D1D4DC
cPanel := isLight ? #FFFFFF : #0B0F13
cGlow := #2962FF
cCandle := cAcc
else if theme == "Aurora Night"
cBull := isLight ? #00A86B : #00E676
cBear := isLight ? #C2185B : #E040FB
cAcc := isLight ? #B59A00 : #FDD835
cNeu := #5C6BC0
cTxt := isLight ? #1A1F2E : #E6F1FF
cPanel := isLight ? #F4F6FB : #0A0E17
cGlow := isLight ? #0097A7 : #00BCD4 // the outer aurora hue (cyan); bear outer is #7C4DFF
cCandle := cNeu
else if theme == "Delta Cyan / Pink"
cBull := isLight ? #0097A7 : #00E5FF
cBear := isLight ? #D81B60 : #FF2E88
cAcc := isLight ? #B59A00 : #FFD600
cNeu := #6B7280
cTxt := isLight ? #111827 : #F8FAFC
cPanel := isLight ? #FFFFFF : #111827
cGlow := isLight ? #0097A7 : #00E5FF
cCandle := cNeu
else if theme == "Paper & Ink"
color ink = isLight ? #111827 : #F0F3FA
cBull := ink
cBear := ink // same ink; bear objects carry direction by DASHED style (kBearStyle)
cAcc := #2962FF // the one accent: "live / nearest"; #F23645 is reserved for "broken"
cNeu := #B2B5BE
cTxt := ink
cPanel := isLight ? #FFFFFF : #131722
cGlow := #2962FF
cCandle := ink
else if theme == "Lime Ember"
cBull := isLight ? #64DD17 : #B2FF59 // below-price liquidity
cBear := isLight ? #2962FF : #448AFF // above-price liquidity
cAcc := #FF9800 // ember: POC / peak row
cNeu := #787B86
cTxt := isLight ? #131722 : #E0E0E0
cPanel := isLight ? #FFFFFF : #161A25
cGlow := #FF9800
cCandle := cNeu
else if theme == "Custom"
cBull := inBull
cBear := inBear
cAcc := inAcc
cNeu := inNeu
cTxt := inTxt
cPanel := inPanel
cGlow := inGlow
cCandle := inAcc
color cBroken = #F23645 // grey-or-red for dead things; Paper & Ink "broken"
string kBearStyle = isMono ? line.style_dashed : line.style_solid // Paper & Ink: direction by style, not hue
int kPanelT = isLight ? 8 : 15 // panel alpha: 92 % on white, 85 % on dark
// f_t: brightness-aware transparency. Scales the OPACITY (100 - t) by 0.5x .. 1.5x so faint things stay faint
// and solid things stay solid; fills (t >= 40) get +4 on a white chart and are floored at 92 in Paper & Ink.
f_t(int t) =>
float op = 100.0 - t
float k = 1.0 + (bright - 3) * 0.25
float tt = 100.0 - op * k
if t >= 40
if isMono
tt := math.max(tt, 92.0)
if isLight
tt += 4.0
math.min(100, math.max(0, math.round(tt)))
// f_ink: black or white text for a solid plate of colour c, by luminance.
f_ink(color c) =>
f_lum(c) > 0.55 ? #0B0F13 : #FFFFFF
// f_grad: 3-stop gradient c1 (t = 0) -> c2 (t = 0.5) -> c3 (t = 1).
f_grad(color c1, color c2, color c3, float t) =>
float tt = math.min(1.0, math.max(0.0, nz(t, 0.5)))
tt < 0.5 ? color.from_gradient(tt, 0.0, 0.5, c1, c2) : color.from_gradient(tt, 0.5, 1.0, c2, c3)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4a. LAYOUT — clamps (defined early because the glow and text helpers use them)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_xo: a drawing anchored further back than ~5,000 bars kills the script on a LIVE bar (RE10143) and a Basic
// account only has 5,000 bars anyway. f_xr: nothing may be drawn more than 500 bars ahead.
f_xo(int b) =>
math.max(b, bar_index - 4990)
f_xr(int b) =>
math.min(b, bar_index + 490)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 2. GLOW
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_glowBox: N concentric boxes. Halo h (1..layers-1) is padded h * 0.05 ATR outward and fades toward 97;
// the last element of the returned array is the CORE box (fill baseT, 1-px border). Keep the array so the
// retirement helpers can delete all layers together.
f_glowBox(int x1, float top, int x2, float bot, color c, int layers, int baseT) =>
array<box> out = array.new<box>()
int xl = f_xo(math.min(x1, x2))
int xr = f_xr(math.max(x1, x2))
float hi = math.max(top, bot)
float lo = math.min(top, bot)
float pad = nz(atrK, (hi - lo) * 0.2) * 0.05
int n = math.max(1, layers)
if n > 1
for i = 1 to n - 1
int h = n - i // outermost first so the core draws on top
int tH = f_t(math.min(99, baseT + math.round(float(97 - baseT) * h / n)))
array.push(out, box.new(xl, hi + pad * h, xr, lo - pad * h,
border_color = color.new(c, 100), border_width = 1, bgcolor = color.new(c, tH)))
array.push(out, box.new(xl, hi, xr, lo,
border_color = color.new(c, f_t(math.max(0, baseT - 50))), border_width = 1, bgcolor = color.new(c, f_t(baseT))))
out
// f_glowLine: a solid core line of `width` with layers-1 wider, fainter halos beneath it. Last element = core.
f_glowLine(int x1, float y1, int x2, float y2, color c, int layers, int width) =>
array<line> out = array.new<line>()
int xl = f_xo(x1)
int xr = f_xr(x2)
int n = math.max(1, layers)
if n > 1
for i = 1 to n - 1
int h = n - i
int tH = f_t(math.min(99, 70 + math.round(27.0 * h / n)))
array.push(out, line.new(xl, y1, xr, y2, color = color.new(c, tH), width = math.max(1, width + 2 * h)))
array.push(out, line.new(xl, y1, xr, y2, color = color.new(c, f_t(0)), width = math.max(1, width)))
out
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 3. TEXT
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_plate: label on a SOLID plate of colour c, text in f_ink(c). sty = label.style_*, sz = size.*
f_plate(int x, float y, string txt, color c, string sty, string sz) =>
label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = c, style = sty,
textcolor = f_ink(c), size = sz)
// f_tag: plateless text (transparent background, coloured text). Evolves f_tag of [JOAT] Fibonacci Vault.
f_tag(int x, float y, string txt, color c, string sty, string sz) =>
label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(#000000, 100),
style = sty, textcolor = c, size = sz)
// f_px: price with thousands separators at mintick precision: 24,550.25 / 1.08432 / —
f_px(float p) =>
string out = "—"
if not na(p)
string s = str.tostring(math.abs(p), format.mintick)
array<string> parts = str.split(s, ".")
string ip = array.get(parts, 0)
string fp = ""
if array.size(parts) > 1
fp := "." + array.get(parts, 1)
string g = ""
int n = str.length(ip)
if n > 0
for i = 0 to n - 1
g += str.substring(ip, i, i + 1)
int rem = n - 1 - i
if rem > 0 and rem % 3 == 0
g += ","
out := (p < 0 ? "-" : "") + g + fp
out
// f_k: compact numbers: 1.2K 3.4M 2.1B (below 1,000: up to two decimals)
f_k(float v) =>
string out = "—"
if not na(v)
float a = math.abs(v)
string sgn = v < 0 ? "-" : ""
if a >= 1e9
out := sgn + str.tostring(a / 1e9, "#.#") + "B"
else if a >= 1e6
out := sgn + str.tostring(a / 1e6, "#.#") + "M"
else if a >= 1e3
out := sgn + str.tostring(a / 1e3, "#.#") + "K"
else
out := sgn + str.tostring(a, "#.##")
out
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4b. LAYOUT — label lane de-collision + object retirement
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Lane register: every right-edge label asks f_lane for a y. The register is cleared at the start of each
// last-bar redraw (f_laneReset) so the slots are recomputed from scratch every tick. Historical tags (pivots and
// events) use the x-aware map register of section 9 instead, because they sit at different bars.
var array<float> laneReg = array.new<float>()
f_laneReset() =>
array.clear(laneReg)
// f_lane: returns the nearest free y to `y`, trying y, y - gap, y + gap, y - 2gap, y + 2gap ... (gap = ATR mult)
f_lane(float y, float gapAtrMult) =>
float gap = math.max(nz(atrK) * gapAtrMult, syminfo.mintick * 2)
float out = y
for k = 0 to 24
float off = math.ceil(k / 2.0) * gap
float cand = k % 2 == 0 ? y + off : y - off
bool free = true
for r in laneReg
if math.abs(r - cand) < gap * 0.999
free := false
if free
out := cand
break
array.push(laneReg, out)
out
// Retirement: push every new object into one array per kind, then cap it. Oldest leaves first (array.shift).
// This script's boxes are a fixed set (1 outline + 2 x gradient bands + 1 OTE stripe, at most 14) and its lines are
// bounded by the event caps of the Structure group, so the free caps here are the pivot-tag ones.
string G3 = "Limits (free account)"
int maxLabSw = input.int(24, "Swing tags kept", minval = 4, maxval = 200, group = G3,
tooltip = "Oldest H / L / HH / HL / LH / LL swing tags are deleted first. 24 covers roughly the last 10 swing events.")
int maxLabIn = input.int(8, "Internal tags kept", minval = 2, maxval = 200, group = G3,
tooltip = "Oldest internal pivot letters are deleted first. 8 covers roughly the last 4 internal events, matching the internal event cap.")
f_capBoxes(array<box> a, int maxN) =>
while array.size(a) > math.max(0, maxN)
box.delete(array.shift(a))
f_capLines(array<line> a, int maxN) =>
while array.size(a) > math.max(0, maxN)
line.delete(array.shift(a))
f_capLabels(array<label> a, int maxN) =>
while array.size(a) > math.max(0, maxN)
label.delete(array.shift(a))
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 5. DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G2 = "Dashboard"
bool showDash = input.bool(true, "Show dashboard", group = G2)
string dashPos = input.string("Top Right", "Dashboard position", group = G2,
options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"])
string dashSize = input.string("Small", "Dashboard size", options = ["Small", "Normal", "Large"], group = G2,
tooltip = "Small is the smallest size: every cell carries data and must stay readable. The Read line wraps at about 60 characters so the panel stays narrow.")
bool dashCompact = input.bool(false, "Compact dashboard", group = G2, tooltip = "Fewer rows for phones: header, one key row and the Read line.")
bool dashTint = input.bool(true, "Tinted value cells", group = G2, tooltip = "Value cells carry a faint tint of their own colour.")
f_pos(string s) =>
switch s
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
=> position.bottom_right
f_size(string s) =>
switch s
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
=> size.small
// f_dashNew: panel in cPanel at the theme alpha, 1-px neutral frame. Rows = header + data rows + Read line.
f_dashNew(string pos, int cols, int rows) =>
table.new(f_pos(pos), cols, rows, bgcolor = color.new(cPanel, kPanelT), frame_color = color.new(cNeu, 40),
frame_width = 1, border_color = color.new(cNeu, 78), border_width = 1)
int dashRows = dashCompact ? 3 : 10
var table dash = f_dashNew(dashPos, 2, dashRows)
var array<int> dCur = array.from(0) // row cursor (arrays are the only globals a function may mutate)
var array<int> dMerged = array.from(-1) // row already merged for the Read line
// f_dBegin: clear and rewind; call once per last-bar redraw before f_dHead.
f_dBegin() =>
table.clear(dash, 0, 0, 1, dashRows - 1)
array.set(dCur, 0, 0)
// f_dHead: title band (bold, glow tint) with symbol · timeframe on the right.
f_dHead(string title) =>
int r = array.get(dCur, 0)
if r < dashRows
table.cell(dash, 0, r, " " + title + " ", text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
bgcolor = color.new(cGlow, isLight ? 80 : 70), text_formatting = text.format_bold)
table.cell(dash, 1, r, syminfo.ticker + " · " + timeframe.period + " ", text_color = cTxt, text_halign = text.align_right,
text_size = f_size(dashSize), bgcolor = color.new(cGlow, isLight ? 88 : 80))
array.set(dCur, 0, r + 1)
// f_dRow: name | value, value text in valueColor with an optional tint cell (evolves the 51-series f_row / f_pill).
f_dRow(string name, string value, color valueColor, string tip) =>
int r = array.get(dCur, 0)
if r < dashRows
table.cell(dash, 0, r, " " + name, text_color = color.new(cTxt, 25), text_halign = text.align_left,
text_size = f_size(dashSize), tooltip = tip)
table.cell(dash, 1, r, value + " ", text_color = valueColor, text_halign = text.align_right, text_size = f_size(dashSize),
bgcolor = dashTint ? color.new(valueColor, isLight ? 90 : 86) : color.new(cPanel, 100), tooltip = tip)
array.set(dCur, 0, r + 1)
// f_wrap: word wrap. A line breaks ("\n") before the word that would take it past maxLen characters, so the merged
// Read cell sets the panel width at about maxLen characters instead of the full sentence.
f_wrap(string txt, int maxLen) =>
array<string> words = str.split(txt, " ")
string out = ""
int cur = 0
for w in words
int wl = str.length(w)
if cur == 0
out += w
cur := wl
else if cur + 1 + wl > maxLen
out += "\n" + w
cur := wl
else
out += " " + w
cur += 1 + wl
out
// f_dRead: the "Read" sentence, merged across both columns, italic, wrapped at ~60 characters. Always the last row.
f_dRead(string txt) =>
int r = array.get(dCur, 0)
if r < dashRows
if array.get(dMerged, 0) != r
table.merge_cells(dash, 0, r, 1, r)
array.set(dMerged, 0, r)
table.cell(dash, 0, r, f_wrap(txt, 60), text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
text_formatting = text.format_italic)
array.set(dCur, 0, r + 1)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 6. CANDLES
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G4 = "Candles"
string paintMode = input.string("Off", "Candle paint", options = ["Off", "Score", "Mono"], group = G4,
tooltip = "Off = chart candles (default: the gradient halves already carry premium / discount). Score = bear -> neutral -> bull gradient by where the close sits in the dealing range (premium = bear tint, discount = bull tint); it replaces your up / down candle colours. Mono = one colour so the structure carries all the colour.")
// f_candlePaint: na (Off), f_grad(cBear, cNeu, cBull, score) (Score) or cCandle (Mono). Feed it to barcolor().
f_candlePaint(string mode, float score) =>
color out = na
if mode == "Score"
out := f_grad(cBear, cNeu, cBull, score)
else if mode == "Mono"
out := cCandle
out
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 8. STRUCTURE ENGINE — types, state, pivots
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// One Scale per pivot length. Evolves the swing memory / break state / structure trend of [JOAT] Structure Weaver.
type Scale
float hi = na // last confirmed swing high and the bar it printed on (the BOS / CHoCH trigger)
int hiBar = na
float lo = na
int loBar = na
bool hiTaken = false // has the current swing high already been closed through?
bool loTaken = false
float tHi = na // trailing extreme: the last swing high, raised by any higher high since (range top)
int tHiBar = na
float tLo = na // trailing extreme: the last swing low, lowered by any lower low since (range bottom)
int tLoBar = na
float legLo = na // lowest low since the current swing high printed: where an up-break's leg starts
int legLoBar = na
float legHi = na // highest high since the current swing low printed: where a down-break's leg starts
int legHiBar = na
int trend = 0 // 1 bullish, -1 bearish, 0 undecided
int lastDir = 0 // direction of the last structure event
int prevDir = 0 // direction of the event before it (the pair sets the bias)
string lastName = "—" // "BOS" or "CHoCH"
int lastBar = na
float bosLvl = na // last BOS: level, direction, bar, closed back through since?
int bosDir = 0
int bosBar = na
bool bosFail = false
float chLvl = na // last CHoCH: same
int chDir = 0
int chBar = na
bool chFail = false
int bos = 0
int choch = 0
int failed = 0
// One structure event: the line from the broken swing to the break bar, its tag, its text and its state.
type Ev
line ln
label tg
color c
int dir
float lvl
bool isCh = false
bool failed = false
string l1 = ""
string l2 = ""
string tip = ""
var Scale sw = Scale.new() // swing scale
var Scale it = Scale.new() // internal scale
var array<Ev> evSw = array.new<Ev>()
var array<Ev> evIn = array.new<Ev>()
var array<label> tagSw = array.new<label>()
var array<label> tagIn = array.new<label>()
var array<label> noLbl = array.new<label>() // empty clash list for the internal scale
var array<line> halo = array.new<line>() // glow halos of the freshest swing event
// Map register for HISTORICAL tags (pivot tags and event tags): centre bar, half width in bars, price footprint,
// kind (0 swing scale, 1 internal). A new tag that would touch a registered one nearby is stacked away from the
// candles (up for tags above price, down for tags below), so tags never sit on top of each other.
var array<int> mX = array.new<int>()
var array<int> mW = array.new<int>()
var array<float> mLo = array.new<float>()
var array<float> mHi = array.new<float>()
var array<int> mK = array.new<int>()
float phS = ta.pivothigh(high, swingLen, swingLen)
float plS = ta.pivotlow(low, swingLen, swingLen)
float phI = ta.pivothigh(high, intLen, intLen)
float plI = ta.pivotlow(low, intLen, intLen)
// the window between a pivot and its confirmation bar: where each break leg starts (lowest low after a swing high,
// highest high after a swing low). Computed every bar at global scope so the series stay consistent.
float loWinS = ta.lowest(low, swingLen)
int loOffS = ta.lowestbars(low, swingLen)
float hiWinS = ta.highest(high, swingLen)
int hiOffS = ta.highestbars(high, swingLen)
float loWinI = ta.lowest(low, intLen)
int loOffI = ta.lowestbars(low, intLen)
float hiWinI = ta.highest(high, intLen)
int hiOffI = ta.highestbars(high, intLen)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 9. STRUCTURE ENGINE — helpers
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_tagSize: swing tags Small / Normal / Large; internal tags one step smaller but never below size.small.
f_tagSize(string s, bool internal) =>
string out = size.small
if s == "Normal"
out := internal ? size.small : size.normal
else if s == "Large"
out := internal ? size.normal : size.large
out
// f_gapP: one tag line of vertical room in price (the "Label gap" input, floored at two ticks).
f_gapP() =>
math.max(nz(atrK) * laneGap, syminfo.mintick * 2)
// f_hw: estimated half width of a tag in bars (about one character per bar at the default zoom).
f_hw(string l1, string l2, bool small) =>
math.max(2, math.round(math.max(str.length(l1), str.length(l2)) * (small ? 0.5 : 0.4)))
// f_mapY: the y a historical tag should take so it does not touch any registered tag. `up` = the tag sits above
// its anchor (label_down style), so its footprint is [y, y + h]; otherwise [y - h, y]. Registers the result.
f_mapY(int x, float y, int hw, float h, bool up, int kind) =>
float yc = y
int n = array.size(mX)
for iter = 0 to 11
float lo = up ? yc : yc - h
float hi = up ? yc + h : yc
bool hit = false
float nxt = yc
if n > 0
for i = 0 to n - 1
if math.abs(array.get(mX, i) - x) < array.get(mW, i) + hw
float rLo = array.get(mLo, i)
float rHi = array.get(mHi, i)
if lo < rHi and hi > rLo
hit := true
nxt := up ? math.max(nxt, rHi) : math.min(nxt, rLo)
if not hit
break
yc := nxt
array.push(mX, x)
array.push(mW, hw)
array.push(mLo, up ? yc : yc - h)
array.push(mHi, up ? yc + h : yc)
array.push(mK, kind)
while array.size(mX) > 150
array.shift(mX)
array.shift(mW)
array.shift(mLo)
array.shift(mHi)
array.shift(mK)
yc
// f_clearAt: delete every label in `a` that sits on bar x (an internal tag on the pivot a swing tag now names),
// and drop the internal entries at x from the map register so the swing tag can take that spot.
f_clearAt(array<label> a, int x) =>
int n = array.size(a)
if n > 0
for i = n - 1 to 0
label l = array.get(a, i)
if label.get_x(l) == x
label.delete(l)
array.remove(a, i)
int m = array.size(mX)
if m > 0
for j = m - 1 to 0
if array.get(mX, j) == x and array.get(mK, j) == 1
array.remove(mX, j)
array.remove(mW, j)
array.remove(mLo, j)
array.remove(mHi, j)
array.remove(mK, j)
// f_biasWord: the bias from the last two events. Two events in the same direction = trend; opposite = ranging.
f_biasWord(Scale s) =>
string out = "Forming"
if s.lastDir != 0
if s.prevDir == 0 or s.prevDir == s.lastDir
out := s.lastDir == 1 ? "Bullish" : "Bearish"
else
out := "Ranging"
out
f_biasColor(string w) =>
w == "Bullish" ? cBull : w == "Bearish" ? cBear : w == "Ranging" ? cAcc : cNeu
f_arrow(int dir) =>
dir == 1 ? "▲" : dir == -1 ? "▼" : ""
// f_drawEv: one BOS / CHoCH line from the broken swing to this bar + a data tag:
// swing: "BOS ▲ 24,550.25 +1.2 ATR" over "leg 86 pts · 23 bars" (CHoCH: dashed line, bold word)
// internal: "iBOS ▲ +0.6 ATR" (size.small, one line; the line itself is thin and faint, the text stays readable)
// The previous freshest event of the same scale is dimmed first (state by opacity). Oldest events retire; on the
// swing scale the latest CHoCH is never the one retired, so the dashboard's "Last CHoCH" stays on the chart.
f_drawEv(array<Ev> evs, int x1, float lvl, int dir, bool isCh, bool internal, float legPts, int legBars, int cap) =>
color c = dir == 1 ? cBull : cBear
int w = internal ? 1 : lineW
int tA = internal ? f_t(50) : f_t(0) // line
int tX = internal ? f_t(15) : f_t(0) // tag text
if array.size(evs) > 0
Ev p = array.last(evs)
if not p.failed
line.set_color(p.ln, color.new(p.c, internal ? f_t(72) : f_t(42)))
label.set_textcolor(p.tg, color.new(p.c, internal ? f_t(35) : f_t(42)))
int xa = f_xo(x1)
line ln = line.new(xa, lvl, bar_index, lvl, color = color.new(c, tA), width = w,
style = isCh ? line.style_dashed : line.style_solid)
float legAtr = nz(atrK) > 0 ? math.abs(legPts) / atrK : 0.0
float beyond = nz(atrK) > 0 ? math.abs(close - lvl) / atrK : 0.0
string word = isCh ? "CHoCH" : "BOS"
string name = (internal ? "i" : "") + word
string szTxt = (dir == 1 ? "+" : "−") + str.tostring(legAtr, "#.#") + " ATR"
string barsTx = str.tostring(legBars) + " bars"
string l1 = ""
string l2 = ""
if internal
l1 := name + " " + f_arrow(dir) + (showBreakSz ? " " + szTxt : "")
else
l1 := name + " " + f_arrow(dir) + " " + f_px(lvl) + (showBreakSz ? " " + szTxt : "")
if evDetail == "Two lines"
l2 := "leg " + f_px(math.abs(legPts)) + " pts · " + barsTx
else
l1 += " · " + barsTx
string txt = l2 == "" ? l1 : l1 + "\n" + l2
bool up = dir == 1
int xm = math.round(math.avg(xa, bar_index))
float h = f_gapP() * (l2 == "" ? 1.0 : 1.7)
// up-breaks sit ABOVE the line (no close traded there between the swing and the break), down-breaks below
float y = f_mapY(xm, lvl, f_hw(l1, l2, true), h, up, internal ? 1 : 0)
label tg = f_tag(xm, y, txt, color.new(c, tX), up ? label.style_label_down : label.style_label_up,
f_tagSize(tagSizeStr, internal))
if isCh
label.set_text_formatting(tg, text.format_bold)
string tip = (internal ? "Internal " : "Swing ") + (isCh ? "CHoCH (change of character)" : "BOS (break of structure)")
+ (up ? " up" : " down") + "\nClosed through the " + (internal ? "internal " : "swing ") + (up ? "high " : "low ")
+ f_px(lvl) + " set " + str.tostring(bar_index - xa) + " bars earlier\nLeg " + f_px(math.abs(legPts)) + " pts · "
+ str.tostring(legAtr, "#.##") + " ATR · " + barsTx + " from the " + (up ? "lowest low" : "highest high")
+ "\nBreak close " + str.tostring(beyond, "#.##") + " ATR beyond the level"
label.set_tooltip(tg, tip)
array.push(evs, Ev.new(ln = ln, tg = tg, c = c, dir = dir, lvl = lvl, isCh = isCh, failed = false, l1 = l1, l2 = l2, tip = tip))
while array.size(evs) > cap
int k = 0
if not internal
int lastCh = -1
for i = array.size(evs) - 1 to 0
Ev e = array.get(evs, i)
if e.isCh
lastCh := i
break
if lastCh == 0
k := 1
Ev old = array.remove(evs, k)
line.delete(old.ln)
label.delete(old.tg)
// f_failCheck: a break the market closes back through turns grey and dotted and says "failed".
// Returns how many failed this bar.
f_failCheck(array<Ev> a) =>
int n = 0
if greyFailed
for e in a
if not e.failed and ((e.dir == 1 and close < e.lvl) or (e.dir == -1 and close > e.lvl))
e.failed := true
line.set_color(e.ln, color.new(cNeu, f_t(35)))
line.set_style(e.ln, line.style_dotted)
label.set_textcolor(e.tg, color.new(cNeu, f_t(35)))
label.set_text(e.tg, e.l1 + " · failed" + (e.l2 == "" ? "" : "\n" + e.l2))
label.set_tooltip(e.tg, e.tip + "\nFAILED: price closed back through the level")
n += 1
n
// f_step: one confirmed bar for one scale. Registers confirmed pivots (tags), trails the range extremes, then tests
// the close against the last swing high / low (BOS / CHoCH). Returns [bosUp, chochUp, bosDown, chochDown, eventLevel].
// skipLvl: an internal event at the same level as this bar's swing event is not drawn twice.
f_step(Scale s, float ph, float pl, int len, bool internal, bool drawTags, bool drawEv, array<label> tags,
array<label> clash, array<Ev> evs, float skipLvl, int tagCap, int evCap, float loWin, int loOff, float hiWin, int hiOff) =>
bool bosUp = false
bool chUp = false
bool bosDn = false
bool chDn = false
float evLvl = na
int x = f_xo(bar_index - len)
string sz = f_tagSize(tagSizeStr, internal)
int tTag = internal ? f_t(20) : f_t(0)
float hTag = f_gapP()
// ---- confirmed swing high: tagged above the candle in the bear role
if not na(ph)
string cls = na(s.hi) ? "H" : ph > s.hi ? "HH" : "LH"
if drawTags
if not internal
f_clearAt(clash, x)
string txt = not internal and swingPx ? cls + " " + f_px(ph) : cls
float yT = f_mapY(x, ph, f_hw(txt, "", true), hTag, true, internal ? 1 : 0)
label lb = f_tag(x, yT, txt, color.new(cBear, tTag), label.style_label_down, sz)
label.set_tooltip(lb, (internal ? "Internal " : "Swing ") + cls + " " + f_px(ph) + " · confirmed " + str.tostring(len) + " bars later")
array.push(tags, lb)
f_capLabels(tags, tagCap)
s.hi := ph
s.hiBar := x
s.hiTaken := false
s.tHi := ph
s.tHiBar := x
s.legLo := loWin
s.legLoBar := bar_index + loOff
// ---- confirmed swing low: tagged below the candle in the bull role
if not na(pl)
string cls = na(s.lo) ? "L" : pl < s.lo ? "LL" : "HL"
if drawTags
if not internal
f_clearAt(clash, x)
string txt = not internal and swingPx ? cls + " " + f_px(pl) : cls
float yT = f_mapY(x, pl, f_hw(txt, "", true), hTag, false, internal ? 1 : 0)
label lb = f_tag(x, yT, txt, color.new(cBull, tTag), label.style_label_up, sz)
label.set_tooltip(lb, (internal ? "Internal " : "Swing ") + cls + " " + f_px(pl) + " · confirmed " + str.tostring(len) + " bars later")
array.push(tags, lb)
f_capLabels(tags, tagCap)
s.lo := pl
s.loBar := x
s.loTaken := false
s.tLo := pl
s.tLoBar := x
s.legHi := hiWin
s.legHiBar := bar_index + hiOff
// ---- trail the range extremes and the leg origins to any newer high / low
if not na(s.tHi) and high > s.tHi
s.tHi := high
s.tHiBar := bar_index
if not na(s.tLo) and low < s.tLo
s.tLo := low
s.tLoBar := bar_index
if not na(s.legLo) and low < s.legLo
s.legLo := low
s.legLoBar := bar_index
if not na(s.legHi) and high > s.legHi
s.legHi := high
s.legHiBar := bar_index
// ---- close through the last swing high: BOS when bullish / undecided, CHoCH when bearish
if not na(s.hi) and not s.hiTaken and close > s.hi
s.hiTaken := true
bool isCh = s.trend == -1
if isCh
chUp := true
s.choch += 1
s.chLvl := s.hi
s.chDir := 1
s.chBar := bar_index
s.chFail := false
else
bosUp := true
s.bos += 1
s.bosLvl := s.hi
s.bosDir := 1
s.bosBar := bar_index
s.bosFail := false
s.trend := 1
s.prevDir := s.lastDir
s.lastDir := 1
s.lastName := isCh ? "CHoCH" : "BOS"
s.lastBar := bar_index
evLvl := s.hi
float legFrom = na(s.legLo) ? s.hi : s.legLo
int legBar = na(s.legLo) ? s.hiBar : s.legLoBar
bool dup = not na(skipLvl) and math.abs(skipLvl - s.hi) < syminfo.mintick * 0.5
if drawEv and not dup and (isCh ? showCHoCH : showBOS)
f_drawEv(evs, s.hiBar, s.hi, 1, isCh, internal, close - legFrom, bar_index - legBar, evCap)
// ---- close through the last swing low: BOS when bearish / undecided, CHoCH when bullish
if not na(s.lo) and not s.loTaken and close < s.lo
s.loTaken := true
bool isCh = s.trend == 1
if isCh
chDn := true
s.choch += 1
s.chLvl := s.lo
s.chDir := -1
s.chBar := bar_index
s.chFail := false
else
bosDn := true
s.bos += 1
s.bosLvl := s.lo
s.bosDir := -1
s.bosBar := bar_index
s.bosFail := false
s.trend := -1
s.prevDir := s.lastDir
s.lastDir := -1
s.lastName := isCh ? "CHoCH" : "BOS"
s.lastBar := bar_index
evLvl := na(evLvl) ? s.lo : evLvl
float legFrom = na(s.legHi) ? s.lo : s.legHi
int legBar = na(s.legHi) ? s.loBar : s.legHiBar
bool dup = not na(skipLvl) and math.abs(skipLvl - s.lo) < syminfo.mintick * 0.5
if drawEv and not dup and (isCh ? showCHoCH : showBOS)
f_drawEv(evs, s.loBar, s.lo, -1, isCh, internal, close - legFrom, bar_index - legBar, evCap)
[bosUp, chUp, bosDn, chDn, evLvl]
// f_haloFor: glow halos (2 wider, fainter lines) under the freshest swing event. The old halos are wiped first.
f_haloFor(Ev e) =>
f_capLines(halo, 0)
array<line> g = f_glowLine(line.get_x1(e.ln), e.lvl, line.get_x2(e.ln), e.lvl, e.c, 3, lineW)
line.delete(array.pop(g)) // the kit's core duplicate; the event already owns its core line
array.concat(halo, g)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 10. STRUCTURE ENGINE — per bar (confirmed bars only, so nothing repaints)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
bool evBosUp = false
bool evChUp = false
bool evBosDn = false
bool evChDn = false
bool evIntCh = false
if barstate.isconfirmed
[a, b, c, d, lvlS] = f_step(sw, phS, plS, swingLen, false, showSwingTags, true, tagSw, tagIn, evSw, na, maxLabSw, maxEvSw,
loWinS, loOffS, hiWinS, hiOffS)
evBosUp := a
evChUp := b
evBosDn := c
evChDn := d
[e, f, g, h, lvlI] = f_step(it, phI, plI, intLen, true, showInternal and showIntTags, showInternal, tagIn, noLbl, evIn, lvlS, maxLabIn, maxEvIn,
loWinI, loOffI, hiWinI, hiOffI)
evIntCh := f or h
// state by opacity: a break the market closes back through turns grey
sw.failed += f_failCheck(evSw)
it.failed += f_failCheck(evIn)
// the dashboard's last BOS / last CHoCH: has a close come back through since?
if not na(sw.bosLvl) and not sw.bosFail and ((sw.bosDir == 1 and close < sw.bosLvl) or (sw.bosDir == -1 and close > sw.bosLvl))
sw.bosFail := true
if not na(sw.chLvl) and not sw.chFail and ((sw.chDir == 1 and close < sw.chLvl) or (sw.chDir == -1 and close > sw.chLvl))
sw.chFail := true
// glow only on the freshest swing event; gone when it fails
if array.size(evSw) > 0
Ev last = array.last(evSw)
if (a or b or c or d) and eventGlow and not last.failed
f_haloFor(last)
else if last.failed or not eventGlow
f_capLines(halo, 0)
// dealing range (trailed swing extremes, plus the forming bar's extreme so the live close stays inside it) and the
// range position 0..1 for the candle paint (global scope, every bar)
float rHi = na(sw.tHi) ? na : math.max(sw.tHi, high)
float rLo = na(sw.tLo) ? na : math.min(sw.tLo, low)
int rHiBar = na(sw.tHi) ? na : high > sw.tHi ? bar_index : sw.tHiBar
int rLoBar = na(sw.tLo) ? na : low < sw.tLo ? bar_index : sw.tLoBar
bool rangeLive = not na(rHi) and not na(rLo) and rHi > rLo
float pos01 = rangeLive ? (close - rLo) / (rHi - rLo) : na
barcolor(f_candlePaint(paintMode, pos01), title = "Range position paint")
// strong / weak (standard SMC naming): the extreme the latest break leg started from is STRONG (structure defends
// it; a close beyond it is a change of character), the opposite extreme is WEAK (the one the leg ran to).
string hiState = sw.trend == -1 ? "strong" : sw.trend == 1 ? "weak" : ""
string loState = sw.trend == 1 ? "strong" : sw.trend == -1 ? "weak" : ""
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 11. LAST-BAR REDRAW — dealing range (gradient halves, EQ, quartiles, OTE, data tags) and the dashboard
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
var array<box> rB = array.new<box>() // 0 = outline, 1..n = premium bands, n+1..2n = discount bands
var array<line> rL = array.new<line>() // 0 = equilibrium, 1 = 25 %, 2 = 75 %
var array<label> rLbls = array.new<label>()
var box oteBx = na
if barstate.islast
f_laneReset()
f_capLabels(rLbls, 0)
float rng = rangeLive ? rHi - rLo : na
float eq = rangeLive ? (rHi + rLo) / 2.0 : na
float posPct = rangeLive ? (close - rLo) / rng * 100.0 : na
string zone = na(posPct) ? "—" : posPct > 100 ? "above range" : posPct < 0 ? "below range" :
posPct > 50 + eqBandPct ? "premium" : posPct < 50 - eqBandPct ? "discount" : "equilibrium"
color zoneC = zone == "premium" or zone == "above range" ? cBear : zone == "discount" or zone == "below range" ? cBull : cNeu
string rngAtr = rangeLive ? str.tostring(rng / nz(atrK, rng), "#.#") : "—"
bool rangeOk = showRange and rangeLive
if rangeOk
int x1 = f_xo(math.min(rHiBar, rLoBar))
int x2 = f_xr(bar_index + rangeExt)
float h2 = rng / 2.0
int need = 1 + 2 * gradBands
if array.size(rB) != need
f_capBoxes(rB, 0)
for i = 1 to need
array.push(rB, box.new(x1, eq, x2, eq, border_color = color.new(cNeu, 100), bgcolor = color.new(cNeu, 100)))
if array.size(rL) != 3
f_capLines(rL, 0)
for i = 1 to 3
array.push(rL, line.new(x1, eq, x2, eq, color = color.new(cNeu, 100), style = line.style_dotted, width = 1))
// faint outline
box o = array.get(rB, 0)
box.set_lefttop(o, x1, rHi)
box.set_rightbottom(o, x2, rLo)
box.set_border_color(o, color.new(cNeu, f_t(62)))
box.set_border_style(o, kBearStyle)
box.set_bgcolor(o, color.new(cNeu, 100))
// gradient halves: band 0 hugs the equilibrium (faintest), the last band hugs the swing (strongest)
for i = 0 to gradBands - 1
int tB = f_t(97 - math.round(9.0 * (i + 1) / gradBands))
float yA = h2 * i / gradBands
float yB = h2 * (i + 1) / gradBands
box p = array.get(rB, 1 + i)
box.set_lefttop(p, x1, eq + yB)
box.set_rightbottom(p, x2, eq + yA)
box.set_bgcolor(p, color.new(cBear, tB))
box.set_border_color(p, color.new(cBear, 100))
box q = array.get(rB, 1 + gradBands + i)
box.set_lefttop(q, x1, eq - yA)
box.set_rightbottom(q, x2, eq - yB)
box.set_bgcolor(q, color.new(cBull, tB))
box.set_border_color(q, color.new(cBull, 100))
// equilibrium and quartiles
line eqLn = array.get(rL, 0)
line.set_xy1(eqLn, x1, eq)
line.set_xy2(eqLn, x2, eq)
line.set_color(eqLn, color.new(cNeu, f_t(25)))
for qn = 1 to 2
line ql = array.get(rL, qn)
float yq = qn == 1 ? eq - h2 / 2.0 : eq + h2 / 2.0
line.set_xy1(ql, x1, yq)
line.set_xy2(ql, x2, yq)
line.set_color(ql, color.new(cNeu, showQuartiles ? f_t(60) : 100))
// optional OTE stripe: 62-79 % retracement of the range from the latest extreme, from the leg's end onward
bool oteOk = showOTE and sw.trend != 0
float oTop = na
float oBot = na
color oC = sw.trend == 1 ? cBull : cBear
if oteOk
float oA = sw.trend == 1 ? rHi - 0.62 * rng : rLo + 0.62 * rng
float oB = sw.trend == 1 ? rHi - 0.79 * rng : rLo + 0.79 * rng
oTop := math.max(oA, oB)
oBot := math.min(oA, oB)
int xo1 = f_xo(math.max(rHiBar, rLoBar))
if na(oteBx)
oteBx := box.new(xo1, oTop, x2, oBot, border_width = 1)
box.set_lefttop(oteBx, xo1, oTop)
box.set_rightbottom(oteBx, x2, oBot)
box.set_bgcolor(oteBx, color.new(oC, f_t(88)))
box.set_border_color(oteBx, color.new(oC, f_t(60)))
box.set_border_style(oteBx, line.style_dotted)
else if not na(oteBx)
box.delete(oteBx)
oteBx := na
// right-edge data tags. Each one is 28 characters at most so it fits ~35 bars of right margin; the detail lives
// in its tooltip. Every y goes through the lane register, most important first so it keeps its exact price.
// Every tag is size.small: no data-carrying text is drawn smaller.
int xt = x2 + 1
string hiWord = hiState == "" ? "RANGE HIGH" : str.upper(hiState) + " HIGH"
string loWord = loState == "" ? "RANGE LOW" : str.upper(loState) + " LOW"
float dEq = nz(atrK) > 0 ? (close - eq) / atrK : 0.0
string dEqTx = str.tostring(math.abs(dEq), "#.#") + " ATR " + (dEq >= 0 ? "above" : "below") + " EQ"
if showRangeTags
// "STRONG HIGH 27,180.50" (strong / weak is the standard SMC name of the extreme)
label tH = f_tag(xt, f_lane(rHi, laneGap), hiWord + " " + f_px(rHi),
color.new(cBear, hiState == "weak" ? f_t(30) : f_t(0)), label.style_label_left, size.small)
label.set_tooltip(tH, "Top of the dealing range " + f_px(rHi) + ": the last swing high, raised to any higher high since. "
+ (hiState == "strong" ? "STRONG: the bearish leg started here; a close above it would be a change of character." :
hiState == "weak" ? "WEAK: the extreme the bullish leg ran to; structure has not defended it yet." : "No structure yet."))
array.push(rLbls, tH)
label tL = f_tag(xt, f_lane(rLo, laneGap), loWord + " " + f_px(rLo),
color.new(cBull, loState == "weak" ? f_t(30) : f_t(0)), label.style_label_left, size.small)
label.set_tooltip(tL, "Bottom of the dealing range " + f_px(rLo) + ": the last swing low, lowered to any lower low since. "
+ (loState == "strong" ? "STRONG: the bullish leg started here; a close below it would be a change of character." :
loState == "weak" ? "WEAK: the extreme the bearish leg ran to; structure has not defended it yet." : "No structure yet."))
array.push(rLbls, tL)
// "EQ 26,774.00"
label tE = f_tag(xt, f_lane(eq, laneGap), "EQ " + f_px(eq), color.new(cTxt, f_t(10)), label.style_label_left, size.small)
label.set_tooltip(tE, "Equilibrium " + f_px(eq) + ": the 50 % line of the dealing range. The range is " + f_px(rng)
+ " points high, " + rngAtr + " times ATR(14). The close is " + dEqTx + ".")
array.push(rLbls, tE)
if showCloseTag
// "close 81 % · premium"
label tC = f_tag(xt, f_lane(close, laneGap), "close " + str.tostring(posPct, "#") + " % · " + zone,
color.new(zoneC, f_t(0)), label.style_label_left, size.small)
label.set_tooltip(tC, "Where the close sits in the dealing range: 0 % = range low, 100 % = range high. Now "
+ str.tostring(posPct, "#.#") + " % (" + zone + "), " + dEqTx + ".")
array.push(rLbls, tC)
if showRangeTags
// "RANGE 813.25 pts · 12.5 ATR" one slot above the high, where the right edge is normally empty (the range
// holds the live bar's high, so the close sits at or below it). Drops "pts" when a long price would break
// the 28-character budget.
string rTx = "RANGE " + f_px(rng) + " pts · " + rngAtr + " ATR"
if str.length(rTx) > 28
rTx := "RANGE " + f_px(rng) + " · " + rngAtr + " ATR"
label tR = f_tag(xt, f_lane(rHi + f_gapP(), laneGap), rTx, color.new(cTxt, f_t(30)), label.style_label_left, size.small)
label.set_tooltip(tR, "Height of the dealing range: " + f_px(rng) + " points, " + rngAtr + " times ATR(14).")
array.push(rLbls, tR)
label tP = f_tag(xt, f_lane(eq + h2 / 2.0, laneGap), "PREMIUM 50-100 %",
color.new(cBear, f_t(25)), label.style_label_left, size.small)
label.set_tooltip(tP, "Premium: the upper half of the dealing range, " + f_px(eq) + " – " + f_px(rHi) + " (50-100 %).")
array.push(rLbls, tP)
label tD = f_tag(xt, f_lane(eq - h2 / 2.0, laneGap), "DISCOUNT 0-50 %",
color.new(cBull, f_t(25)), label.style_label_left, size.small)
label.set_tooltip(tD, "Discount: the lower half of the dealing range, " + f_px(rLo) + " – " + f_px(eq) + " (0-50 %).")
array.push(rLbls, tD)
if oteOk
// "OTE 26,520.00–26,600.25"
label tO = f_tag(xt, f_lane((oTop + oBot) / 2.0, laneGap), "OTE " + f_px(oBot) + "–" + f_px(oTop),
color.new(oC, f_t(30)), label.style_label_left, size.small)
label.set_tooltip(tO, "OTE: the 62-79 % retracement of the dealing range measured from the latest " + (sw.trend == 1 ? "high" : "low")
+ ", " + f_px(oBot) + " – " + f_px(oTop) + ". A zone, not a signal.")
array.push(rLbls, tO)
else
f_capBoxes(rB, 0)
f_capLines(rL, 0)
if not na(oteBx)
box.delete(oteBx)
oteBx := na
// ---- dashboard: every row is also on the chart (event lines / tags, range tags, close tag). Values stay short
// ("N bars" = N bars ago, spelled out in each row's tooltip) so the panel stays narrow over a 1m chart.
if showDash
string biasW = f_biasWord(sw)
string biasI = f_biasWord(it)
string ago = na(sw.lastBar) ? "" : " · " + str.tostring(bar_index - sw.lastBar) + " bars"
string agoI = na(it.lastBar) ? "" : " · " + str.tostring(bar_index - it.lastBar) + " bars"
string structV = biasW + (sw.lastDir == 0 ? "" : " · " + sw.lastName + " " + f_arrow(sw.lastDir) + ago)
string intV = biasI + (it.lastDir == 0 ? "" : " · i" + it.lastName + " " + f_arrow(it.lastDir) + agoI)
bool agree = biasI == biasW or biasI == "Forming" or biasW == "Forming"
string posV = na(posPct) ? "—" : str.tostring(posPct, "#") + " % · " + zone
string sizeV = rangeLive ? f_px(rng) + " pts · " + rngAtr + " ATR" : "—"
string hiV = na(rHi) ? "—" : f_px(rHi) + (hiState == "" ? "" : " · " + hiState)
string loV = na(rLo) ? "—" : f_px(rLo) + (loState == "" ? "" : " · " + loState)
string bosV = na(sw.bosLvl) ? "—" : f_arrow(sw.bosDir) + " " + f_px(sw.bosLvl) + " · " + str.tostring(bar_index - sw.bosBar)
+ " bars · " + (sw.bosFail ? "failed" : "held")
string chV = na(sw.chLvl) ? "—" : f_arrow(sw.chDir) + " " + f_px(sw.chLvl) + " · " + str.tostring(bar_index - sw.chBar)
+ " bars · " + (sw.chFail ? "failed" : "held")
color bosC = na(sw.bosLvl) or sw.bosFail ? cNeu : sw.bosDir == 1 ? cBull : cBear
color chC = na(sw.chLvl) or sw.chFail ? cNeu : sw.chDir == 1 ? cBull : cBear
string readTxt = "Waiting for two confirmed swings"
if rangeLive
string head = biasW == "Forming" ? "Structure forming" : biasW + " structure"
string intP = agree ? "" : ", internal " + str.lower(biasI)
string keyP = sw.trend == 1 ? "; strong low " + f_px(rLo) : sw.trend == -1 ? "; strong high " + f_px(rHi) : ""
readTxt := head + intP + "; close " + str.tostring(posPct, "#") + " % of a " + rngAtr + " ATR range (" + zone + ")" + keyP
f_dBegin()
f_dHead("STRUCTURE MAP")
f_dRow("Structure", structV, f_biasColor(biasW),
"Swing structure from the last two swing events: two in the same direction = Bullish / Bearish (a trend), opposite = Ranging. Then the last event and how many bars ago it closed ('7 bars' = 7 bars ago).\nHow SMC traders read it: bullish structure = higher highs and higher lows, and it stays bullish until a close breaks the strong low (a CHoCH).\nOn the chart: the swing lines, solid for BOS, dashed for CHoCH.")
if not dashCompact
f_dRow("Internal", intV, agree ? f_biasColor(biasI) : cAcc,
"The same reading on the short internal pivots. Accent colour = it disagrees with the swing structure.\nHow SMC traders read it: internal structure against the swing structure is a pullback inside the larger leg, or the first sign of a change.\nOn the chart: the thin iBOS / iCHoCH lines, when 'Show internal structure' is on (off by default; this row is computed either way).")
f_dRow("Range position", posV, zoneC,
"Where the close sits in the dealing range: 0 % = range low, 100 % = range high. Within ±" + str.tostring(eqBandPct) + " % of 50 % is equilibrium.\nHow SMC traders read it: the upper half is premium (price is expensive relative to the range), the lower half discount (cheap).\nOn the chart: the 'close' tag at the right edge and the gradient halves.")
f_dRow("Range size", sizeV, cTxt,
"Height of the dealing range in points and in ATR(14).\nHow SMC traders read it: a range only a couple of ATR tall puts premium and discount close together; a tall range separates them clearly.\nOn the chart: the RANGE tag just above the range high at the right edge.")
f_dRow("Range high", hiV, cBear,
"Top of the dealing range: the last swing high, raised to any higher high since.\nHow SMC traders read it: STRONG = the high the latest bearish leg started from, the level structure defends; WEAK = the high the latest bullish leg ran to, not yet defended and commonly seen as resting liquidity.\nOn the chart: the STRONG HIGH / WEAK HIGH tag (RANGE HIGH before structure forms).")
f_dRow("Range low", loV, cBull,
"Bottom of the dealing range: the last swing low, lowered to any lower low since.\nHow SMC traders read it: STRONG = the low the latest bullish leg started from, the level structure defends; WEAK = the low the latest bearish leg ran to, not yet defended and commonly seen as resting liquidity.\nOn the chart: the STRONG LOW / WEAK LOW tag (RANGE LOW before structure forms).")
f_dRow("Last BOS", bosV, bosC,
"The latest swing break of structure: direction, level, how many bars ago, and whether a later close came back through it (failed) or not (held).\nHow SMC traders read it: a held BOS confirms the structure is continuing; a failed one weakens it.\nOn the chart: the latest solid swing line, glowing while it is the freshest event.")
f_dRow("Last CHoCH", chV, chC,
"The latest swing change of character: the first close against the prior structure.\nHow SMC traders read it: the earliest structural sign that direction may be changing; it becomes a BOS-confirmed trend only after a second break the same way.\nOn the chart: the dashed swing line with the bold CHoCH tag (always kept on the chart).")
f_dRead(readTxt)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 12. ALERTS — structure events only (no direction calls, no entries). Set them to "Once per bar close".
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
alertcondition(evBosUp, "Swing BOS up", "Market Structure Map: close through the swing high, structure bullish, on {{ticker}} {{interval}}")
alertcondition(evBosDn, "Swing BOS down", "Market Structure Map: close through the swing low, structure bearish, on {{ticker}} {{interval}}")
alertcondition(evChUp, "Swing CHoCH up", "Market Structure Map: change of character up on {{ticker}} {{interval}}")
alertcondition(evChDn, "Swing CHoCH down", "Market Structure Map: change of character down on {{ticker}} {{interval}}")
alertcondition(evIntCh, "Internal CHoCH", "Market Structure Map: internal change of character on {{ticker}} {{interval}}")