本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman
//@version=6
indicator("CQ_Breakout Probability (Expo)", overlay=true, max_bars_back=5000, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
// ~~ Tooltips {
t1 = "Distance between consecutive levels, as a percentage of the previous bar's close.\n\n" +
"Level 1 always sits exactly on the previous bar's high (above) and low (below). Each additional level adds one more step.\n\n" +
"Example — 1% with a previous close of 100: upper levels at prev high +0, +1, +2, +3, +4, +5, +6 (mirrored below the prev low).\n\n" +
"The step is fixed for the whole bar (it no longer drifts with the live price). Smaller step = tighter levels with higher hit odds; larger step = wider targets with lower odds. Changing it recalculates all historical statistics."
t2 = "How many levels to draw above the previous high and below the previous low (1–7).\n\n" +
"Level 1 is the previous bar's high/low itself; each extra level adds one Percentage Step. " +
"Statistics for all 7 levels are always calculated — this only controls how many are drawn."
t3 = "When ON, a level pair (upper + lower at the same distance) is hidden if either side has a 0.00% historical likelihood of being hit for the current candle condition.\n\n" +
"Turn OFF to draw every level regardless of its odds."
t4 = "Shows the statistics panel (off by default): previous candle color, current bias and Level 1 odds, whether the bias has been reached on this bar, Level 1 odds after green and after red candles, sample sizes, the step value, and the bias backtest. Hover any row for its explanation.\n\n" +
"On every closed bar, the script checks the bias it had at that bar's open — previous high (bullish) or previous low (bearish), whichever had the higher Level 1 odds for the previous candle's color, using only bars that closed before it.\n\n" +
"WIN = bars where the predicted side was actually reached.\nLOSS = bars where it wasn't.\nProfitability = WIN ÷ (WIN + LOSS).\n\n" +
"Bars following a doji (open = close) are not scored. It's a hit rate of the bias, not a trading P&L."
tCol = "Colors for the levels above the previous high (Upper) and below the previous low (Lower). Also used for the label text and the background fill.\n\n" +
"Label percentages are the share of closed bars where price reached that level, counted separately for green and red previous candles (after a doji, the red statistics are shown)."
tLn = "Thickness (1–5) and pattern of the level lines."
tLen = "How many bars back from the current bar each level line starts.\n\n1 = a short stub over the last bar (original look). Larger values make the levels easier to see against past price."
tExt = "How many bars each level line extends to the right of the current bar (0–10). 0 = the line ends on the current bar. Right-side labels move out with the line end."
tHl = "Highlights the two levels closest to the current price — the nearest one above and the nearest one below — by drawing them thicker, at full color. Updates live as price moves."
tFade = "Levels beyond the highlighted ones fade out step by step, the farther from price the fainter — lines, labels and the background fill.\n\nStep: how much fainter each further level gets (% transparency per level).\nMax: the most a level can fade, so the outer levels stay visible."
tFill = "Shades the zones between adjacent levels — upper color above, lower color below.\n\nTransparency: 0 = solid, 100 = invisible. Default 80."
tLbl = "Shows the probability label at the right end of each level line."
tLblSp = "Spacing between the bar and the labels.\n\n" +
"Bar Spacing — whole bars away from the bar (Right side: counted from the end of the level line; Left side: counted from the start of the level line). 0 = labels touch it; -1 = pulled one bar back so the caption overlaps the line end.\n" +
"Fine Spacing — extra blank characters between the text and the bar, for small nudges smaller than one bar.\n\n" +
"Both can be combined."
tNoDec = "When ON (default), percentages are rounded to whole numbers (e.g. 63%) everywhere: level labels, hover details, the statistics panel and alert messages. Turn OFF to show two decimals (e.g. 62.84%)."
tLblTip = "When ON, hovering over a level label shows the full breakout breakdown for that level:\n\n" +
"• Breakout probability and its \"1 in N\" equivalent\n• Sample size — how many past bars reached the level out of how many comparable bars\n" +
"• Level price and how it's built (steps from the previous high/low)\n• Distance from the current price\n• Whether the level has already been reached on the current bar\n" +
"• The odds of the opposite level at the same distance\n• The overall Level 1 bias"
tCap = "Caption Mode — how the level percentages are drawn:\n\n" +
"Labels — floating text next to the line (original look).\n" +
"Boxes — a thin captioned box that rides on the level line itself, centered on the price, with a light fill and a border in the level color. The box fades with its level and the nearest levels stay highlighted.\n\n" +
"Box Width: length of each box in bars.\nBox Height: thickness of each box as a % of the current price (keep it small so the box stays thin).\n\n" +
"Side, Bar Spacing, Size, Hover Details and Remove Decimals work in both modes."
tLblSz = "Side: show the labels to the Right of the current bar (default) or to the Left of the level lines.\nSize: label text size."
tTbl = "Where the statistics panel sits on the chart, and its text size (Auto scales with the panel)."
tTblCol = "Text colors for the WIN, LOSS and Profitability rows."
tProfAuto = "When ON, the Profitability row uses the chart's own text color (adapts to light/dark themes) instead of the color picked above."
tFrame = "Color and thickness of the statistics panel's outer frame. Width 0 removes it."
tAlert = "Choose what goes into the alert message, then create an alert on this indicator with the condition \"Any alert() function call\".\n\n" +
"Ticker ID — symbol name.\nHigh/Low Price — the previous bar's high and low.\nBullish/Bearish Bias — the side with the higher Level 1 odds.\nBullish/Bearish Percentage — the Level 1 odds of reaching the previous high and the previous low."
tFreq = "Once Per Bar: fires on the first update of each new bar (the bias is already known at the bar's open).\n" +
"Once Per Bar Close: fires only when the bar closes."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Inputs {
string G1 = "📐 Levels"
string G2 = "🎨 Lines & Fill"
string G3 = "🏷️ Labels"
string G4 = "📊 Statistics Panel"
string G5 = "🔔 Alerts — Any alert() function call"
string G6 = "✨ Highlight & Fade"
string G7 = "🧭 Probability Pixel Dials — Layout"
string G8 = "🎨 Probability Pixel Dials — Style"
string G9 = "🌙 Probability Pixel Dials — Auto Dim"
indMode = input.string("Classic + Pixel Gauge",title="Indicator Mode",options=["Classic","Pixel Gauge","Classic + Pixel Gauge"],group=G1,
tooltip="Classic — the level lines on the chart with their probability labels / boxes, highlight & fade and background fill.\n\n" +
"Pixel Gauge — the Probability Pixel Dial(s) only, pinned to the screen (see the 🧭 Probability Pixel Dials groups); no lines are drawn on the chart. " +
"The dials read 0–100% from the same closed-bar statistics; hover the tag rows for the level-by-level breakdown.\n\n" +
"Classic + Pixel Gauge (default) — both at once.\n\n" +
"The Statistics Panel and alerts work in every mode.")
showClassic = indMode != "Pixel Gauge"
showGauge = indMode != "Classic"
perc = input.float(1.0,title="Percentage Step",step=.1,minval=0,group=G1,tooltip=t1)
nbr = input.int(7, title="Number of Lines",maxval=7,minval=1,group=G1,tooltip=t2)
hideZero = input.bool(true,title="Disable 0.00%",group=G1,tooltip=t3)
upCol = input.color(color.new(color.green,0),title="Upper",inline="col",group=G2)
dnCol = input.color(color.new(color.red,0),title="Lower",inline="col",group=G2,tooltip=tCol)
lnWidth = input.int(2,title="Width",minval=1,maxval=5,inline="ln",group=G2)
lnStyleS = input.string("Solid",title="Style",options=["Solid","Dashed","Dotted"],inline="ln",group=G2,tooltip=tLn)
lnBack = input.int(1,title="Line Length (bars back)",minval=1,maxval=500,group=G2,tooltip=tLen)
lnFwd = input.int(0,title="Extend Right (bars)",minval=0,maxval=10,group=G2,tooltip=tExt)
showFill = input.bool(true,title="BG Color",inline="fill",group=G2)
fillTr = input.int(80,title="Transparency",minval=0,maxval=100,inline="fill",group=G2,tooltip=tFill)
hlOn = input.bool(true,title="Highlight Nearest Levels",inline="hl",group=G6)
hlWidth = input.int(4,title="Width",minval=1,maxval=10,inline="hl",group=G6,tooltip=tHl)
fadeOn = input.bool(true,title="Fade Outer Levels",inline="fd",group=G6)
fadeStep = input.int(20,title="Step",minval=1,maxval=50,inline="fd",group=G6)
fadeMax = input.int(80,title="Max",minval=0,maxval=95,inline="fd",group=G6,tooltip=tFade)
lblShow = input.bool(true,title="Show Labels",group=G3,tooltip=tLbl)
lblSpacing = input.int(1,title="Bar Spacing",minval=-1,maxval=50,inline="lsp",group=G3)
lblFine = input.int(0,title="Fine Spacing",minval=0,maxval=20,inline="lsp",group=G3,tooltip=tLblSp)
lblTips = input.bool(true,title="Hover Details",group=G3,tooltip=tLblTip)
noDec = input.bool(true,title="Remove Decimals from Percentages",group=G3,tooltip=tNoDec)
lblSide = input.string("Right",title="Side",options=["Right","Left"],inline="lsz",group=G3)
lblSizeS = input.string("Normal",title="Size",options=["Tiny","Small","Normal","Large","Huge"],inline="lsz",group=G3,tooltip=tLblSz)
capMode = input.string("Labels",title="Caption Mode",options=["Labels","Boxes"],group=G3,tooltip=tCap)
boxW = input.int(6,title="Box Width",minval=2,maxval=50,inline="bx",group=G3)
boxHpct = input.float(0.08,title="Height %",minval=0.01,maxval=2,step=0.01,inline="bx",group=G3)
showPanel = input.bool(false, title="Show Statistic Panel",group=G4,tooltip=t4)
tblPosS = input.string("Top Right",title="Position",options=["Top Left","Top Center","Top Right","Middle Left","Middle Center","Middle Right","Bottom Left","Bottom Center","Bottom Right"],inline="tbl",group=G4)
tblSizeS = input.string("Auto",title="Text",options=["Auto","Tiny","Small","Normal","Large","Huge"],inline="tbl",group=G4,tooltip=tTbl)
winCol = input.color(color.green,title="Win",inline="tc",group=G4)
lossCol = input.color(color.red,title="Loss",inline="tc",group=G4)
profCol = input.color(color.white,title="Profitability",inline="tc",group=G4,tooltip=tTblCol)
profAuto = input.bool(true,title="Profitability uses chart text color",group=G4,tooltip=tProfAuto)
frameCol = input.color(color.new(color.gray,50),title="Frame",inline="fr",group=G4)
frameW = input.int(3,title="Width",minval=0,maxval=10,inline="fr",group=G4,tooltip=tFrame)
// ── Probability Pixel Dials · Layout ──
pd_merge = input.bool(true, "Merge Into Single Dial", group=G7,
tooltip="ON (default): one combined dial. The right half of the arc is the BREAKOUT side and lights up from the top out to the odds of reaching the previous high; the left half is the BREAKDOWN side, lit out to the odds of reaching the previous low. The needle points at the net edge (breakout − breakdown odds): straight up = balanced, right = breakout edge, left = breakdown edge. Scale reads 100 · 50 · 0 · 50 · 100. Wedges, dividers and deeper-level ticks are mirrored on both halves.\n\nOFF: separate BREAKOUT and BREAKDOWN dials (see Dials).")
pd_which = input.string("Both", "Dials", options=["Both","Breakout (High)","Breakdown (Low)"], group=G7,
tooltip="Separate-dial mode only (Merge Into Single Dial OFF): draw both dials side by side (BREAKOUT on the left, BREAKDOWN on the right), or only one of them.")
pd_pos = input.string(position.middle_right, "Position",
options=[position.top_left, position.top_center, position.top_right,
position.middle_left, position.middle_center, position.middle_right,
position.bottom_left, position.bottom_center, position.bottom_right], group=G7,
tooltip="Screen position of the dials. Pick a different spot than the Statistics Panel — two tables in the same position draw on top of each other.")
pd_pxW = input.float(0.15, "Pixel Width (% of chart)", minval=0.05, maxval=5.0, step=0.05, group=G7,
tooltip="Width of each dial pixel as a percentage of the chart pane width. Adjust together with Pixel Height until the dials look round on your screen (wide monitors need a smaller width than height). Each dial grid is 41 × 27 pixels.")
pd_pxH = input.float(0.3, "Pixel Height (% of chart)", minval=0.05, maxval=10.0, step=0.05, group=G7,
tooltip="Height of each dial pixel as a percentage of the chart pane height.")
pd_scale = input.float(1.0, "Dial Size (×)", minval=0.25, maxval=5.0, step=0.05, group=G7,
tooltip="Overall size multiplier. Scales Pixel Width and Pixel Height together, so the dials grow or shrink without changing shape.")
pd_gap = input.int(0, "Separation Between Dials (pixels)", minval=0, maxval=40, group=G7,
tooltip="Blank space between the BREAKOUT and BREAKDOWN dials, in dial pixels. 0 = touching.")
pd_padL = input.float(0, "Left Padding (pixels)", minval=0, maxval=400, step=1, group=G7,
tooltip="Blank space to the left of the dials, in dial pixels. Raise it to slide the dials to the right without changing their shape. 0 = no padding.")
pd_numSize = input.string(size.tiny, "Scale Number Size", options=[size.tiny, size.small, size.normal, size.large, size.huge], group=G7,
tooltip="Font size of the scale numbers (0 / 25 / 50 / 75 / 100) and the PREV HIGH / PREV LOW captions. Each number sits in a 4 × 2 pixel block and is hidden while the needle passes over it.")
pd_needleW = input.int(2, "Needle Thickness", minval=1, maxval=10, group=G7,
tooltip="Thickness of the needles. The center hub grows with it so the pivot stays covered.")
pd_titleSize = input.string(size.small, "Title Tag Size", options=[size.tiny, size.small, size.normal, size.large, size.huge], group=G7,
tooltip="Font size of the B R E A K O U T / B R E A K D O W N title tags above the dials.")
pd_infoSize = input.string(size.tiny, "Level Tag Size", options=[size.tiny, size.small, size.normal, size.large, size.huge], group=G7,
tooltip="Font size of the tag below each dial with the previous high / low price and its distance from the current price.")
pd_valSize = input.string(size.normal, "Reading Tag Size", options=[size.tiny, size.small, size.normal, size.large, size.huge], group=G7,
tooltip="Font size of the reading tag: the Level 1 breakout / breakdown probability.")
pd_zoneSize = input.string(size.tiny, "Zone Tag Size", options=[size.tiny, size.small, size.normal, size.large, size.huge], group=G7,
tooltip="Font size of the zone tag at the bottom of each dial: LOW ODDS (< 30%), BELOW EVEN (30–50%), LEANING (50–70%), STRONG ODDS (70%+), or ✅ BROKEN once price has reached the level on the current bar.")
// ── Probability Pixel Dials · Style ──
pd_theme = input.string("Aircraft Instrument", "Dial Color Theme",
options=["Custom","Beige VU Meter","Aircraft Instrument","Volkswagen Tacho","Racing White Face","Amber Night","Marine Brass","Night Vision Green","Cockpit Night","Illuminated Instrument"], group=G8,
tooltip="Palette for the dial face, scale numbers, needle and hub, and the tag text — same presets as the TACHIMETER Pixel Dial.\nCustom: uses the Dial Face, Scale Number and Needle colors below.\nWhatever is selected here, the Night Palette (Auto Dim group) replaces it during the Dim Period unless the Night Palette is Off.\nThe arc always uses the Upper (breakout) / Lower (breakdown) level colors — the night palette's gain / loss colors while a Night Palette is active.")
pd_faceGrad = input.bool(true, "Dial Face Gradient", inline="pdfg", group=G8)
pd_faceGradPct = input.int(60, "Bottom Opacity %", minval=0, maxval=100, inline="pdfg", group=G8,
tooltip="Fades the dial face from top to bottom. The bottom row is drawn at this percentage of the face color's own opacity (100 = no fade, 0 = fully transparent at the bottom).")
pd_faceColor = input.color(color.new(color.black, 35), "Dial Face Color", group=G8, tooltip="Fill color of the dial face. Custom theme only.")
pd_scaleColor = input.color(color.gray, "Scale Number Color", group=G8, tooltip="Color of the scale numbers and captions. Custom theme only.")
pd_needleColor = input.color(color.white, "Needle Color", group=G8, tooltip="Color of the needles and hubs. Custom theme only.")
pd_unlitTransp = input.int(75, "Unlit Arc Transparency", minval=0, maxval=100, group=G8,
tooltip="The arc is fully lit up to the needle (dark → bright level color); the rest of the scale stays visible at this transparency (100 = hidden).")
pd_dividers = input.bool(true, "Zone Dividers", group=G8,
tooltip="Cuts a thin notch in the arc at 30 / 50 / 70% so the Low, Below Even, Leaning and Strong zones read as separate segments.")
pd_wedgeShow = input.bool(true, "Odds Zone Wedges", group=G8,
tooltip="Shades two pie wedges from the hub out to the arc in each dial's level color: Leaning (50–70%) and Strong (70–100%). The needle and hub are always drawn on top.")
pd_leanOp = input.int(20, "Leaning 50–70 Opacity %", minval=0, maxval=100, inline="pdw", group=G8)
pd_strongOp = input.int(40, "Strong 70–100 %", minval=0, maxval=100, inline="pdw", group=G8,
tooltip="Opacity of each wedge blended over the dial face: 0 = face only, 100 = solid color.")
pd_tickShow = input.bool(true, "Deeper Level Ticks", inline="pdtk", group=G8)
pd_tickCol = input.color(#00B0FF, "", inline="pdtk", group=G8,
tooltip="Marks the odds of each deeper visible level (L2, L3 …) with a tick on the arc, so you can see how fast the probability drops beyond the previous high / low. Warm ivory (Cockpit Night) or light bright amber (Illuminated Instrument) while a Night Palette is active.")
// ── Probability Pixel Dials · Auto Dim ──
pd_dimOn = input.bool(true, "Auto Dim Pixel Dials", group=G9,
tooltip="Dims the dials (face, arc, wedges, needle, numbers, captions and tags) during the Dim Period below, same as the TACHIMETER's Auto Dim. Dimming cuts the opacity of every color by Dim Amount %.\nWhile a Night Palette is selected, that palette and its Panel Rheostat replace this opacity dimming during the Dim Period.\nUses the real clock, so it works on any timeframe; the change happens on the first tick after the period starts or ends.")
pd_dimPct = input.int(50, "Dim Amount %", minval=0, maxval=100, step=5, group=G9,
tooltip="How much to dim during the Dim Period. 50 = colors drawn at 50% of their normal opacity. 0 = no dimming, 100 = dials fully hidden.")
pd_dimSess = input.session("1900-0700", "Dim Period", group=G9,
tooltip="Start and end time of the dim period, in the Dim Timezone below. May cross midnight (default 7:00 PM to 7:00 AM). Start equal to end = never dims. Also the period the Night Palette is active.")
pd_dimTz = input.string("America/Chicago", "Dim Timezone", group=G9,
tooltip="Timezone the Dim Period is read in. Examples: America/Chicago, America/New_York, UTC, GMT-5. Blank = the symbol's exchange timezone.")
pd_ncMode = input.string("Cockpit Night", "Night Palette", options=["Off","Cockpit Night","Illuminated Instrument"], group=G9,
tooltip="Palette the dials switch to during the Dim Period.\nOff: no night palette (Auto Dim opacity dimming applies instead).\nCockpit Night: edge-lit panel with warm incandescent backlighting — near-black face, glowing amber numerals, the needle as the brightest element, dimmed annunciator green / red arcs, tag rows at 25% opacity with text in the same color at 100%.\nIlluminated Instrument: LED-backlit cluster — near-black face, bright amber numerals, glowing orange-red pointer, cool-lit green / red arcs; tag rows keep their level color faded to 15% opacity, with that color brightened as text.")
pd_ncRheo = input.int(85, "Panel Rheostat %", minval=20, maxval=100, step=5, group=G9,
tooltip="Panel brightness while a Night Palette is active, like the instrument-lighting knob in a cockpit. 100 = full brightness, 85 = default, 20 = darkest.")
pd_ncHalo = input.bool(true, "Needle Halo (Night)", group=G9,
tooltip="While a Night Palette is active, draws a faint glow around each needle and hub, like the bloom of a lit pointer.")
var bool [] alert_bool = array.from(
input.bool(true,title="Ticker ID",group=G5,tooltip=tAlert),
input.bool(true,title="High/Low Price",group=G5),
input.bool(true,title="Bullish/Bearish Bias",group=G5),
input.bool(true,title="Bullish/Bearish Percentage",group=G5))
alertFreqS = input.string("Once Per Bar",title="Frequency",options=["Once Per Bar","Once Per Bar Close"],group=G5,tooltip=tFreq)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input Mapping {
f_size(string s) => s=="Tiny" ? size.tiny : s=="Small" ? size.small : s=="Normal" ? size.normal : s=="Large" ? size.large : s=="Huge" ? size.huge : size.auto
f_pos(string s) =>
switch s
"Top Left" => position.top_left
"Top Center" => position.top_center
"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
"Bottom Right" => position.bottom_right
=> position.top_right
lnStyle = lnStyleS=="Dashed" ? line.style_dashed : lnStyleS=="Dotted" ? line.style_dotted : line.style_solid
lblSize = f_size(lblSizeS)
lblPad = str.repeat(" ", lblFine)
lblLeft = lblSide=="Left"
lblStyle = lblLeft ? label.style_label_right : label.style_label_left
useBoxes = capMode=="Boxes"
tblSize = f_size(tblSizeS)
//Percentage text: whole numbers or two decimals
PctStr(float v) => noDec ? str.tostring(math.round(v)) + "%" : str.tostring(v, format.percent)
alertFreq = alertFreqS=="Once Per Bar Close" ? alert.freq_once_per_bar_close : alert.freq_once_per_bar
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables {
b = bar_index
o = open
h = high
l = low
c = close
prevH = h[1]
prevL = l[1]
step = c[1]*(perc/100) // fixed for the whole bar: based on the previous close, not the live price
green = c[1]>o[1]
red = c[1]<o[1]
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Save Values In Matrix {
// total rows 0-6: level hit counts | cols 0 green→high, 1 green→low, 2 red→high, 3 red→low
// total row 7: col 0 green bars scored, col 1 red bars scored | row 8: col 0 WIN, col 1 LOSS
// lines/labels cols 0-6: upper levels | cols 7-13: lower levels
var total = matrix.new<int>(9,4,0)
var lines = matrix.new<line>(1,14,line(na))
var labels = matrix.new<label>(1,14,label(na))
var boxes = matrix.new<box>(1,14,box(na))
var fills = array.new<linefill>()
var tbl = table.new(f_pos(tblPosS),2,14,
frame_color=frameCol,frame_width=frameW,
border_color=chart.bg_color,border_width=-2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Functions {
//Probability from closed-bar counts (always uses the current denominator)
Pct(int r, int col, int denom) =>
denom > 0 ? math.round(matrix.get(total,r,col) / float(denom) * 100, 2) : 0.0
//Lines
CreateLine(float p, int i, color col, int w) =>
line.delete(matrix.get(lines,0,i))
matrix.set(lines,0,i,line.new(b-lnBack,p,b+lnFwd,p,color=col,width=w,style=lnStyle))
//Fade a color by f% of its remaining opacity
Fade(color col, float f) =>
t = color.t(col)
color.new(col, t + (100 - t) * f / 100)
//Hover details for a level label
LevelTip(bool up, int i, float p, float prob, int hits, int n, float oppProb, string biasTxt) =>
refName = up ? "previous high" : "previous low"
ref = up ? prevH : prevL
cond = red or not green ? "RED" : "GREEN"
fromC = (p - c) / c * 100
reached = up ? h >= p : l <= p
build = i == 0 ? "Sits exactly on the " + refName + "." :
str.tostring(i) + " × " + str.tostring(perc) + "% step " + (up ? "above" : "below") + " the " + refName +
" (" + (up ? "+" : "−") + str.tostring(math.abs(p - ref), format.mintick) + ")."
oneIn = prob > 0 ? " (≈ 1 in " + str.tostring(100 / prob, "#.#") + ")" : ""
(up ? "▲ UPPER" : "▼ LOWER") + " LEVEL " + str.tostring(i+1) + " of " + str.tostring(nbr) + "\n" +
"━━━━━━━━━━━━━━━━━━━━\n" +
"Breakout probability: " + PctStr(prob) + oneIn + "\n" +
"Sample: reached on " + str.tostring(hits) + " of " + str.tostring(n) + " closed bars that followed a " + cond + " candle.\n" +
(green or red ? "" : "Previous candle was a doji — red-candle statistics are used.\n") + "\n" +
"Level price: " + str.tostring(p, format.mintick) + "\n" + build + "\n" +
"Distance from current price: " + (fromC >= 0 ? "+" : "") + str.tostring(fromC, "#.##") + "%\n" +
"Current bar: " + (reached ? "✅ level already reached" : "⏳ not reached yet") + "\n\n" +
"Opposite " + (up ? "lower" : "upper") + " level at the same distance: " + PctStr(oppProb) + "\n" +
"Level 1 bias: " + biasTxt + "\n\n" +
"How to read it: in past bars that followed a " + cond + " candle, price traded through this level before the bar closed " +
PctStr(prob) + " of the time. It's a historical frequency, not a guarantee."
//Labels
//Remove a level's caption (label and/or box)
ClearCaption(int i) =>
label.delete(matrix.get(labels,0,i))
matrix.set(labels,0,i,label(na))
box.delete(matrix.get(boxes,0,i))
matrix.set(boxes,0,i,box(na))
CreateLabel(float p, int i, color col, float v, string tip) =>
ClearCaption(i)
txt = PctStr(v)
if useBoxes
//Thin captioned box riding on the level line
bL = lblLeft ? b-lnBack-lblSpacing-boxW : b+lnFwd+lblSpacing
bR = bL + boxW
half = c * boxHpct / 200
matrix.set(boxes,0,i,box.new(bL,p+half,bR,p-half,border_color=col,border_width=1,
bgcolor=Fade(col,85),text=txt,text_color=col,text_size=lblSize,
text_halign=text.align_center,text_valign=text.align_center))
//Invisible hover target carrying the details (boxes have no tooltip of their own)
if str.length(tip) > 0
matrix.set(labels,0,i,label.new(int(math.round((bL+bR)/2)),p,text=str.repeat(" ",str.length(txt)+2),
style=label.style_label_center,color=color.new(color.black,100),textcolor=color.new(color.black,100),
size=lblSize,tooltip=tip))
else
x = lblLeft ? b-lnBack-lblSpacing : b+lnFwd+lblSpacing
matrix.set(labels,0,i,label.new(x,p,text=lblLeft ? txt+lblPad : lblPad+txt,
style=lblStyle,color=color.new(color.black,100),textcolor=col,size=lblSize,tooltip=tip))
//Remove a level's line and caption
ClearLevel(int i) =>
line.delete(matrix.get(lines,0,i))
matrix.set(lines,0,i,line(na))
ClearCaption(i)
//Fill between two levels
AddFill(int i1, int i2, color col) =>
l1 = matrix.get(lines,0,i1)
l2 = matrix.get(lines,0,i2)
if not na(l1) and not na(l2)
array.push(fills,linefill.new(l1,l2,col))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Current Bar Odds (closed bars only — no lookahead) {
denom = green ? matrix.get(total,7,0) : matrix.get(total,7,1)
hiCol = green ? 0 : 2
loCol = green ? 1 : 3
hiOdds = Pct(0,hiCol,denom)
loOdds = Pct(0,loCol,denom)
bullish = hiOdds >= loOdds
hasStats = denom > 0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Lines & Labels & Fill {
if barstate.islast
biasTxt = (bullish ? "BULLISH" : "BEARISH") + " — prev high " + PctStr(hiOdds) + " vs prev low " + PctStr(loOdds)
//Collect visible levels (slots 0-6 upper, 7-13 lower)
lvP = array.new_float(14, na)
lvV = array.new_float(14, 0.0)
lvT = array.new_string(14, "")
for i = 0 to 6
upP = Pct(i,hiCol,denom)
dnP = Pct(i,loCol,denom)
if showClassic and i < nbr and (not hideZero or math.min(upP,dnP) > 0)
hi = prevH + step*i
lo = prevL - step*i
lvP.set(i,hi)
lvP.set(7+i,lo)
lvV.set(i,upP)
lvV.set(7+i,dnP)
if lblShow and lblTips
lvT.set(i,LevelTip(true, i,hi,upP,matrix.get(total,i,hiCol),denom,dnP,biasTxt))
lvT.set(7+i,LevelTip(false,i,lo,dnP,matrix.get(total,i,loCol),denom,upP,biasTxt))
//Rank each level by how many visible levels sit between it and the current price (0 = nearest → highlighted)
lvF = array.new_float(14, 0.0)
for k = 0 to 13
p = lvP.get(k)
if na(p)
ClearLevel(k)
else
rank = 0
for m = 0 to 13
q = lvP.get(m)
if m != k and not na(q)
if p >= c and q >= c and q < p
rank += 1
if p < c and q < c and q > p
rank += 1
isHL = hlOn and rank == 0
fade = fadeOn ? math.min(rank * fadeStep, fadeMax) : 0
lvF.set(k,fade)
base = k < 7 ? upCol : dnCol
col = Fade(base,fade)
CreateLine(p,k,col,isHL ? hlWidth : lnWidth)
if lblShow
CreateLabel(p,k,col,lvV.get(k),lvT.get(k))
else
ClearCaption(k)
for f in fills
linefill.delete(f)
array.clear(fills)
if showFill and showClassic
for i = 0 to 5
AddFill(i,i+1,Fade(color.new(upCol,fillTr),math.max(lvF.get(i),lvF.get(i+1))))
AddFill(7+i,8+i,Fade(color.new(dnCol,fillTr),math.max(lvF.get(7+i),lvF.get(8+i))))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alerts {
if barstate.isrealtime and hasStats and array.includes(alert_bool, true)
string [] str_vals = array.from(str.tostring(syminfo.ticker),
"High Price: "+str.tostring(math.round_to_mintick(prevH))+" | Low Price: "+str.tostring(math.round_to_mintick(prevL)),
"BIAS: "+(bullish ? "BULLISH" : "BEARISH"),
"Percentage: High: "+PctStr(hiOdds)+" | Low: "+PctStr(loOdds))
output = array.new_string()
for x = 0 to array.size(alert_bool)-1
if array.get(alert_bool,x)
array.push(output,array.get(str_vals,x))
alert(array.join(output,'\n'),alertFreq)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Record Outcome Of The Closed Bar {
if barstate.isconfirmed and (green or red)
//Backtest: score the bias that was known at this bar's open
if hasStats
win = bullish ? h >= prevH : l <= prevL
r = win ? 0 : 1
matrix.set(total,8,r,matrix.get(total,8,r)+1)
//Level hit counts
for i = 0 to 6
x = step*i
if h >= prevH + x
matrix.set(total,i,hiCol,matrix.get(total,i,hiCol)+1)
if l <= prevL - x
matrix.set(total,i,loCol,matrix.get(total,i,loCol)+1)
tc = green ? 0 : 1
matrix.set(total,7,tc,matrix.get(total,7,tc)+1)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Table {
//Write one label/value row
Row(int r, string lbl, string val, color valCol, string tip) =>
table.cell(tbl,0,r,lbl,text_halign=text.align_left,bgcolor=chart.bg_color,
text_color=color.gray,text_size=tblSize,tooltip=tip)
table.cell(tbl,1,r,val,text_halign=text.align_right,bgcolor=chart.bg_color,
text_color=valCol,text_size=tblSize,tooltip=tip)
if barstate.islast and showPanel
var bool merged = false
if not merged
table.merge_cells(tbl,0,0,1,0)
merged := true
fg = chart.fg_color
gN = matrix.get(total,7,0)
rN = matrix.get(total,7,1)
W = matrix.get(total,8,0)
L = matrix.get(total,8,1)
WR = W+L > 0 ? math.round(W / float(W+L) * 100, 2) : 0.0
reachd = bullish ? h >= prevH : l <= prevL
candle = green ? "GREEN" : red ? "RED" : "DOJI"
table.cell(tbl,0,0,"BREAKOUT PROBABILITY",text_halign=text.align_center,bgcolor=chart.bg_color,
text_color=fg,text_size=tblSize,tooltip="Statistics for the current bar's levels and the bias backtest. All figures come from closed bars only.")
Row(1,"Prev Candle",candle,green ? upCol : red ? dnCol : fg,
"Color of the previous candle. The level odds are counted separately for bars that follow a green and a red candle (after a doji, red statistics are used).")
Row(2,"Current Bias",hasStats ? (bullish ? "BULLISH ▲" : "BEARISH ▼") : "—",bullish ? upCol : dnCol,
"The side with the higher Level 1 odds for this candle color: previous high (bullish) or previous low (bearish).")
Row(3,"Odds → Prev High",PctStr(hiOdds),upCol,
"Share of past bars, after the same candle color, that traded at or above the previous high.")
Row(4,"Odds → Prev Low",PctStr(loOdds),dnCol,
"Share of past bars, after the same candle color, that traded at or below the previous low.")
Row(5,"Bias This Bar",hasStats ? (reachd ? "✅ Reached" : "⏳ Pending") : "—",reachd ? winCol : fg,
"Whether the current bar has already reached the side the bias points to. It's scored as a WIN or LOSS when the bar closes.")
Row(6,"After GREEN (H / L)",PctStr(Pct(0,0,gN))+" / "+PctStr(Pct(0,1,gN)),fg,
"Level 1 odds after a green candle: reaching the previous high / the previous low.")
Row(7,"After RED (H / L)",PctStr(Pct(0,2,rN))+" / "+PctStr(Pct(0,3,rN)),fg,
"Level 1 odds after a red candle: reaching the previous high / the previous low.")
Row(8,"Sample (G / R)",str.tostring(gN)+" / "+str.tostring(rN),fg,
"Number of closed bars behind the statistics: bars after a green candle / bars after a red candle. Larger samples make the odds more reliable.")
Row(9,"Step",str.tostring(perc)+"% ("+str.tostring(step,format.mintick)+")",fg,
"Percentage Step between levels and its price value on the current bar (based on the previous close).")
Row(10,"WIN",str.tostring(W),winCol,
"Closed bars where price reached the side the bias predicted (previous high or previous low).")
Row(11,"LOSS",str.tostring(L),lossCol,
"Closed bars where price failed to reach the side the bias predicted.")
Row(12,"Profitability",PctStr(WR),profAuto ? fg : profCol,
"Bias win rate: WIN ÷ (WIN + LOSS). A hit rate, not a trading P&L.")
Row(13,"Bars Scored",str.tostring(W+L),fg,
"Total closed bars included in the backtest (bars after a doji are not scored).")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
////////////////////////////////////////////////////////////////////////////
//// PROBABILITY PIXEL DIALS ///
//// Round 240° dials built from table cells (same 41 × 27 grid, face ///
//// gradient, needle, hub, scale-number blocks, color themes and night ///
//// lighting as the CQ Fibonacci / TACHIMETER Pixel Dials). ///
//// BREAKOUT : odds of reaching the previous high (0 → 100%) ///
//// BREAKDOWN : odds of reaching the previous low (0 → 100%) ///
//// Ticks on the arc mark the odds of the deeper levels. ///
//// Identifiers use pd_ / PD_. ///
////////////////////////////////////////////////////////////////////////////
PD_COLS = 41
PD_ROWS = 27
PD_CX = 20.0
PD_CY = 18.5
PD_R = 17.2
PD_BG = color.rgb(0, 0, 0, 100)
// ── Cockpit Night palette (edge-lit incandescent panel) ──
PD_NC_FACE = #050607
PD_NC_NUM = #F0C27A
PD_NC_NEEDLE = #FF6A3D
PD_NC_GAIN = #3FBF7F
PD_NC_LOSS = #E0503A
PD_NC_IVORY = #E6D3B0
// ── Illuminated Instrument palette (LED-backlit cluster) ──
PD_II_FACE = #030508
PD_II_NUM = #FFB000
PD_II_HL = #FFD24D
PD_II_NEEDLE = #FF6A3D
PD_II_GAIN = #3DE0A0
PD_II_LOSS = #FF5A4A
PD_II_ROW_T = 85
// ── Auto Dim / Night window ──
f_pdHhmm(string s) =>
int(str.tonumber(str.substring(s, 0, 2))) * 60 + int(str.tonumber(str.substring(s, 2, 4)))
string pd_dimTzR = pd_dimTz == "" ? syminfo.timezone : pd_dimTz
int pd_dimStart = f_pdHhmm(str.substring(pd_dimSess, 0, 4))
int pd_dimEnd = f_pdHhmm(str.substring(pd_dimSess, 5, 9))
int pd_nowMin = hour(timenow, pd_dimTzR) * 60 + minute(timenow, pd_dimTzR)
bool pd_inWin = pd_dimStart <= pd_dimEnd ? pd_nowMin >= pd_dimStart and pd_nowMin < pd_dimEnd : pd_nowMin >= pd_dimStart or pd_nowMin < pd_dimEnd
bool pd_night = pd_ncMode != "Off" and pd_inWin
bool pd_nightII = pd_night and pd_ncMode == "Illuminated Instrument"
bool pd_dimNow = pd_dimOn and pd_dimPct > 0 and pd_inWin and not pd_night
bool pd_haloOn = pd_night and pd_ncHalo
float pd_ncK = pd_ncRheo / 100.0
// Night: brightness scaled by the Panel Rheostat. Dim period: opacity cut by Dim Amount %.
f_pdDim(color c) =>
pd_night ? color.rgb(color.r(c) * pd_ncK, color.g(c) * pd_ncK, color.b(c) * pd_ncK, color.t(c)) :
pd_dimNow ? color.new(c, 100 - (100 - color.t(c)) * (1 - pd_dimPct / 100.0)) : c
// Backlit text version of a box color (same hue, full brightness, lifted toward white).
f_pdBright(color c) =>
float m = math.max(color.r(c), color.g(c), color.b(c))
float k = m > 0 ? 255.0 / m : 1.0
color full = color.rgb(math.min(255, color.r(c) * k), math.min(255, color.g(c) * k), math.min(255, color.b(c) * k), 0)
color.from_gradient(25, 0, 100, full, color.white)
color pdTickCol = pd_nightII ? PD_II_HL : pd_night ? PD_NC_IVORY : pd_tickCol
// Dial color theme → [face, scale numbers, needle, tag text].
f_pdTheme(string th) =>
color face = pd_faceColor
color scale = pd_scaleColor
color needle = pd_needleColor
color txt = color.white
if th == "Beige VU Meter"
face := #E9DDB5
scale := #2A2016
needle := #141414
txt := #F3E9D2
else if th == "Aircraft Instrument"
face := #15181B
scale := #F4F4F4
needle := #FFFFFF
txt := #FFFFFF
else if th == "Volkswagen Tacho"
face := #07080C
scale := #5B9BFF
needle := #FF3B1F
txt := #A8C8FF
else if th == "Racing White Face"
face := #F4F2EC
scale := #121212
needle := #E3221B
txt := #FFFFFF
else if th == "Amber Night"
face := #160D02
scale := #FFB000
needle := #FFC24D
txt := #FFC95A
else if th == "Marine Brass"
face := #0F2236
scale := #D9B44A
needle := #F4E6BC
txt := #E8CF83
else if th == "Night Vision Green"
face := #081408
scale := #79FF66
needle := #C2FFB8
txt := #9CFF8F
else if th == "Cockpit Night"
face := PD_NC_FACE
scale := PD_NC_NUM
needle := PD_NC_NEEDLE
txt := PD_NC_NUM
else if th == "Illuminated Instrument"
face := PD_II_FACE
scale := PD_II_NUM
needle := PD_II_NEEDLE
txt := PD_II_NUM
[face, scale, needle, txt]
string pdActiveTheme = pd_night ? pd_ncMode : pd_theme
[pdFace, pdScale, pdNeedle, pdText] = f_pdTheme(pdActiveTheme)
bool pdIiOn = pdActiveTheme == "Illuminated Instrument"
// Linear 240° sweep: 0% at -120°, 100% at +120° (clockwise from straight up).
f_pdAng(float v) =>
-120 + math.max(0, math.min(v, 100)) / 100 * 240
f_pdVal(float deg) =>
(deg + 120) / 240 * 100
f_pdAtan2(float y, float x) =>
x > 0 ? math.atan(y / x) :
x < 0 and y >= 0 ? math.atan(y / x) + math.pi :
x < 0 ? math.atan(y / x) - math.pi :
y > 0 ? math.pi / 2 : y < 0 ? -math.pi / 2 : 0.0
// Pixel (dx, dy from hub) lies on the needle ray at angle tRad.
f_pdNeedle(float dx, float dy, float tRad, float perpMax, float len) =>
float proj = dx * math.sin(tRad) + dy * math.cos(tRad)
float perp = math.abs(dx * math.cos(tRad) - dy * math.sin(tRad))
proj > 0 and proj < len and perp < perpMax
// Dial face color for grid row j (top = theme face, fading toward the bottom).
f_pdFaceAt(int j) =>
float topOp = 100 - color.t(pdFace)
float frac = pd_faceGrad ? j / (PD_ROWS - 1.0) : 0.0
float op = topOp * (1 - frac * (1 - pd_faceGradPct / 100.0))
color.new(pdFace, 100 - op)
// Odds zone wedge shade for scale value cv, blended over the face in the dial's color.
f_pdWedge(color face, float cv, color tCol) =>
not pd_wedgeShow ? face :
cv >= 70 ? color.from_gradient(pd_strongOp, 0, 100, face, tCol) :
cv >= 50 ? color.from_gradient(pd_leanOp, 0, 100, face, tCol) : face
// Draws one dial into tb at column ox. v = needle reading (%), tickV = deeper level odds.
f_pdDial(table tb, int ox, float v, color tCol, array<float> tickV, string cap, float pw, float ph) =>
float vv = math.max(0, math.min(v, 100))
float tRad = math.toradians(f_pdAng(vv))
float sweep = math.toradians(120.0)
float nPerp = 0.3 + 0.2 * pd_needleW
float nLen = PD_R - 2.4
float hubR = 1.0 + 0.15 * pd_needleW
float faceR = PD_R * 1.08
color cDark = color.from_gradient(0.4, 0.0, 1.0, color.black, tCol)
array<float> divA = array.new<float>()
for dv in array.from(30.0, 50.0, 70.0)
divA.push(math.toradians(f_pdAng(dv)))
array<float> tkA = array.new<float>()
for tv in tickV
tkA.push(math.toradians(f_pdAng(tv)))
for j = 0 to PD_ROWS - 1
color rowFace = f_pdFaceAt(j)
for i = 0 to PD_COLS - 1
float dx = i - PD_CX
float dy = PD_CY - j
float d = math.sqrt(dx * dx + dy * dy)
float a = f_pdAtan2(dx, dy)
color col = d <= faceR ? rowFace : PD_BG
// Odds zone wedges: from the hub out to the inner edge of the arc.
if pd_wedgeShow and d < PD_R - 1.2 and math.abs(a) <= sweep
col := f_pdWedge(rowFace, f_pdVal(math.todegrees(a)), tCol)
// Arc ring: level color dark → bright, lit up to the needle.
if math.abs(d - PD_R) < 1.2 and math.abs(a) <= sweep
float cv = f_pdVal(math.todegrees(a))
color zc = color.from_gradient(cv, 0, 100, cDark, tCol)
col := cv <= vv ? zc : color.new(zc, pd_unlitTransp)
if pd_dividers
for da in divA
if math.abs(a - da) < 0.045
col := rowFace
if pd_tickShow
for ta in tkA
if math.abs(a - ta) < 0.045
col := pdTickCol
// Needle and hub; night halo tints the face pixels next to them.
if f_pdNeedle(dx, dy, tRad, nPerp, nLen) or d < hubR
col := pdNeedle
else if pd_haloOn and d <= faceR and (f_pdNeedle(dx, dy, tRad, nPerp + 0.9, nLen + 0.7) or d < hubR + 0.8)
col := color.from_gradient(18, 0, 100, col, pdNeedle)
table.cell(tb, ox + i, j + 1, "", width=pw, height=ph, bgcolor=f_pdDim(col))
// Scale numbers in 4 × 2 blocks at 0.80 of the radius; hidden while the needle crosses them.
for mv in array.from(0.0, 25.0, 50.0, 75.0, 100.0)
float ta = math.toradians(f_pdAng(mv))
int i0 = int(math.round(PD_CX + PD_R * 0.80 * math.sin(ta) - 1.5))
int j0 = int(math.round(PD_CY - PD_R * 0.80 * math.cos(ta) - 0.5))
bool hit = false
for jj = j0 to j0 + 1
for ii = i0 to i0 + 3
float bdx = ii - PD_CX
float bdy = PD_CY - jj
if f_pdNeedle(bdx, bdy, tRad, nPerp, nLen) or math.sqrt(bdx * bdx + bdy * bdy) < hubR
hit := true
if not hit
table.cell(tb, ox + i0, j0 + 1, str.tostring(mv, "0"), width=pw, height=ph,
text_color=f_pdDim(pdScale), text_size=pd_numSize,
bgcolor=f_pdDim(f_pdWedge(f_pdFaceAt(j0), mv, tCol)))
table.merge_cells(tb, ox + i0, j0 + 1, ox + i0 + 3, j0 + 2)
// Caption in the open bottom of the dial.
table.cell(tb, ox + 15, 24, cap, width=pw, height=ph,
text_color=f_pdDim(pdScale), text_size=pd_numSize, bgcolor=f_pdDim(f_pdFaceAt(23)))
table.merge_cells(tb, ox + 15, 24, ox + 25, 27)
// Title / level / reading / zone tags under one dial (merged across its width).
f_pdTags(table tb, int ox, float pw, string ttl, string info, string val, string zone, color hdrBg, color valBg, color tagTx, string tip) =>
int ex = ox + PD_COLS - 1
color txt = f_pdDim(tagTx)
color hb = f_pdDim(hdrBg)
color vb = f_pdDim(valBg)
table.cell(tb, ox, 0, ttl, width=pw, text_color=txt, text_size=pd_titleSize, bgcolor=hb, tooltip=tip)
table.merge_cells(tb, ox, 0, ex, 0)
table.cell(tb, ox, PD_ROWS + 1, info, width=pw, text_color=txt, text_size=pd_infoSize, bgcolor=vb, tooltip=tip)
table.merge_cells(tb, ox, PD_ROWS + 1, ex, PD_ROWS + 1)
table.cell(tb, ox, PD_ROWS + 2, val, width=pw, text_color=txt, text_size=pd_valSize, bgcolor=vb, tooltip=tip)
table.merge_cells(tb, ox, PD_ROWS + 2, ex, PD_ROWS + 2)
table.cell(tb, ox, PD_ROWS + 3, zone, width=pw, text_color=txt, text_size=pd_zoneSize, bgcolor=hb, tooltip=tip)
table.merge_cells(tb, ox, PD_ROWS + 3, ex, PD_ROWS + 3)
// Odds zone name (or BROKEN once the level was reached on the current bar).
f_pdZone(float p, bool hit) =>
hit ? "✅ B R O K E N" : p >= 70 ? "S T R O N G O D D S" : p >= 50 ? "L E A N I N G" :
p >= 30 ? "B E L O W E V E N" : "L O W O D D S"
// Odds of the deeper visible levels (L2 …) for the tick marks.
f_pdTicks(int col) =>
array<float> t = array.new<float>()
if nbr > 1
for i = 1 to nbr - 1
float pp = Pct(i, col, denom)
if pp > 0
t.push(pp)
t
// Level-by-level hover breakdown.
f_pdTip(bool up) =>
int col = up ? hiCol : loCol
string cond = green ? "GREEN" : "RED"
string s = (up ? "▲ BREAKOUT ODDS — reaching levels above the previous high" : "▼ BREAKDOWN ODDS — reaching levels below the previous low") +
"\nBased on " + str.tostring(denom) + " closed bars that followed a " + cond + " candle." +
(green or red ? "" : "\nPrevious candle was a doji — red-candle statistics are used.") +
"\n━━━━━━━━━━━━━━━━━━━━"
for i = 0 to nbr - 1
float p = up ? prevH + step * i : prevL - step * i
bool hit = up ? h >= p : l <= p
s := s + "\nL" + str.tostring(i + 1) + " " + str.tostring(p, "#,##0") + " → " + PctStr(Pct(i, col, denom)) + (hit ? " ✅ reached" : "")
s := s + "\n\nNeedle: Level 1 odds (the " + (up ? "previous high" : "previous low") + ")." +
(nbr > 1 ? "\nTicks on the arc: odds of L2–L" + str.tostring(nbr) + "." : "") +
"\nZones: < 30% low · 30–50% below even · 50–70% leaning · 70%+ strong." +
"\nLevel 1 bias: " + (bullish ? "BULLISH" : "BEARISH") +
"\n\nHistorical frequency, not a guarantee."
s
// ── Merged dial: breakdown on the left half, breakout on the right half ──
// Angle: -100 (far left) → 0 (top) → +100 (far right).
f_pdAngM(float v) =>
math.max(-100, math.min(v, 100)) / 100 * 120
f_pdValM(float deg) =>
deg / 120 * 100
// Right arc lit from the top out to the breakout odds, left arc out to the breakdown
// odds; the needle points at the net edge (breakout − breakdown).
f_pdDialM(table tb, int ox, float upV, float dnV, color upC, color dnC, array<float> tkUp, array<float> tkDn, float pw, float ph) =>
float net = upV - dnV
float tRad = math.toradians(f_pdAngM(net))
float sweep = math.toradians(120.0)
float nPerp = 0.3 + 0.2 * pd_needleW
float nLen = PD_R - 2.4
float hubR = 1.0 + 0.15 * pd_needleW
float faceR = PD_R * 1.08
color cDarkU = color.from_gradient(0.4, 0.0, 1.0, color.black, upC)
color cDarkD = color.from_gradient(0.4, 0.0, 1.0, color.black, dnC)
array<float> divA = array.new<float>()
for dv in array.from(-70.0, -50.0, -30.0, 0.0, 30.0, 50.0, 70.0)
divA.push(math.toradians(f_pdAngM(dv)))
array<float> tkA = array.new<float>()
for tv in tkUp
tkA.push(math.toradians(f_pdAngM(tv)))
for tv in tkDn
tkA.push(math.toradians(f_pdAngM(-tv)))
for j = 0 to PD_ROWS - 1
color rowFace = f_pdFaceAt(j)
for i = 0 to PD_COLS - 1
float dx = i - PD_CX
float dy = PD_CY - j
float d = math.sqrt(dx * dx + dy * dy)
float a = f_pdAtan2(dx, dy)
color col = d <= faceR ? rowFace : PD_BG
float cv = f_pdValM(math.todegrees(a))
bool isU = cv >= 0
// Odds zone wedges on both halves, each in its side's color.
if pd_wedgeShow and d < PD_R - 1.2 and math.abs(a) <= sweep
col := f_pdWedge(rowFace, math.abs(cv), isU ? upC : dnC)
// Arc ring: each half lit from the top out to its own odds.
if math.abs(d - PD_R) < 1.2 and math.abs(a) <= sweep
color zc = color.from_gradient(math.abs(cv), 0, 100, isU ? cDarkU : cDarkD, isU ? upC : dnC)
bool lit = isU ? cv <= upV : -cv <= dnV
col := lit ? zc : color.new(zc, pd_unlitTransp)
if pd_dividers
for da in divA
if math.abs(a - da) < 0.045
col := rowFace
if pd_tickShow
for ta in tkA
if math.abs(a - ta) < 0.045
col := pdTickCol
// Needle and hub; night halo tints the face pixels next to them.
if f_pdNeedle(dx, dy, tRad, nPerp, nLen) or d < hubR
col := pdNeedle
else if pd_haloOn and d <= faceR and (f_pdNeedle(dx, dy, tRad, nPerp + 0.9, nLen + 0.7) or d < hubR + 0.8)
col := color.from_gradient(18, 0, 100, col, pdNeedle)
table.cell(tb, ox + i, j + 1, "", width=pw, height=ph, bgcolor=f_pdDim(col))
// Scale numbers 100 · 50 · 0 · 50 · 100 (left = breakdown, right = breakout).
for mv in array.from(-100.0, -50.0, 0.0, 50.0, 100.0)
float ta = math.toradians(f_pdAngM(mv))
int i0 = int(math.round(PD_CX + PD_R * 0.80 * math.sin(ta) - 1.5))
int j0 = int(math.round(PD_CY - PD_R * 0.80 * math.cos(ta) - 0.5))
bool hit = false
for jj = j0 to j0 + 1
for ii = i0 to i0 + 3
float bdx = ii - PD_CX
float bdy = PD_CY - jj
if f_pdNeedle(bdx, bdy, tRad, nPerp, nLen) or math.sqrt(bdx * bdx + bdy * bdy) < hubR
hit := true
if not hit
table.cell(tb, ox + i0, j0 + 1, str.tostring(math.abs(mv), "0"), width=pw, height=ph,
text_color=f_pdDim(pdScale), text_size=pd_numSize,
bgcolor=f_pdDim(f_pdWedge(f_pdFaceAt(j0), math.abs(mv), mv >= 0 ? upC : dnC)))
table.merge_cells(tb, ox + i0, j0 + 1, ox + i0 + 3, j0 + 2)
table.cell(tb, ox + 15, 24, "▼ NET ▲", width=pw, height=ph,
text_color=f_pdDim(pdScale), text_size=pd_numSize, bgcolor=f_pdDim(f_pdFaceAt(23)))
table.merge_cells(tb, ox + 15, 24, ox + 25, 27)
var table pdT = na
if barstate.islast
table.delete(pdT)
pdT := na
if showGauge and hasStats
float pw = pd_pxW * pd_scale
float ph = pd_pxH * pd_scale
bool showUp = pd_which != "Breakdown (Low)"
bool showDn = pd_which != "Breakout (High)"
int padC = pd_padL > 0 ? 1 : 0
int oxU = padC
int oxD = showUp ? oxU + PD_COLS + pd_gap : padC
pdT := table.new(pd_pos, pd_merge ? padC + PD_COLS : oxD + PD_COLS, PD_ROWS + 4, bgcolor=PD_BG, border_width=1, border_color=PD_BG)
// Left padding: one blank spacer column.
if padC == 1
for j = 0 to PD_ROWS + 3
table.cell(pdT, 0, j, "", width=pd_padL * pw, height=j >= 1 and j <= PD_ROWS ? ph : 0, bgcolor=PD_BG)
// Blank gap columns between the dials.
if not pd_merge and showUp and showDn and pd_gap > 0
for g = 0 to pd_gap - 1
for j = 1 to PD_ROWS
table.cell(pdT, oxU + PD_COLS + g, j, "", width=pw, height=ph, bgcolor=PD_BG)
for side = 0 to 1
bool up = side == 0
if not pd_merge and ((up and showUp) or (not up and showDn))
int ox = up ? oxU : oxD
color base = up ? upCol : dnCol
color tCol = pd_nightII ? (up ? PD_II_GAIN : PD_II_LOSS) : pd_night ? (up ? PD_NC_GAIN : PD_NC_LOSS) : base
color hdrBg = pdIiOn ? color.new(base, PD_II_ROW_T) : pd_night ? color.new(PD_NC_NUM, 75) : color.new(tCol, 65)
color valBg = pdIiOn ? color.new(base, PD_II_ROW_T) : pd_night ? color.new(tCol, 75) : color.new(tCol, 50)
color tagTx = pdIiOn ? f_pdBright(base) : pdText
float odds = up ? hiOdds : loOdds
float lvl = up ? prevH : prevL
bool hit = up ? h >= prevH : l <= prevL
float dd = lvl - c
string info = (up ? "PREV HIGH " : "PREV LOW ") + str.tostring(lvl, "#,##0") +
" (" + (dd >= 0 ? "+" : "") + str.tostring(dd, "#,##0") + " · " + (dd >= 0 ? "+" : "") + str.tostring(dd / c * 100, "0.00") + "%)"
f_pdDial(pdT, ox, odds, tCol, f_pdTicks(up ? hiCol : loCol), up ? "PREV HIGH" : "PREV LOW", pw, ph)
f_pdTags(pdT, ox, pw, up ? "B R E A K O U T ▲" : "B R E A K D O W N ▼", info,
PctStr(odds) + (up ? " ▲" : " ▼"), f_pdZone(odds, hit), hdrBg, valBg, tagTx, f_pdTip(up))
if pd_merge
//Single combined dial; tags take the color of the side with the edge
float net = hiOdds - loOdds
bool upDom = net >= 0
color base = upDom ? upCol : dnCol
color tUp = pd_nightII ? PD_II_GAIN : pd_night ? PD_NC_GAIN : upCol
color tDn = pd_nightII ? PD_II_LOSS : pd_night ? PD_NC_LOSS : dnCol
color tCol = upDom ? tUp : tDn
color hdrBg = pdIiOn ? color.new(base, PD_II_ROW_T) : pd_night ? color.new(PD_NC_NUM, 75) : color.new(tCol, 65)
color valBg = pdIiOn ? color.new(base, PD_II_ROW_T) : pd_night ? color.new(tCol, 75) : color.new(tCol, 50)
color tagTx = pdIiOn ? f_pdBright(base) : pdText
bool hitU = h >= prevH
bool hitD = l <= prevL
float dU = (prevH - c) / c * 100
float dD = (prevL - c) / c * 100
string info = "▼ " + str.tostring(prevL, "#,##0") + " " + str.tostring(dD, "0.00") + "% · ▲ " +
str.tostring(prevH, "#,##0") + " +" + str.tostring(dU, "0.00") + "%"
string zone = hitU and hitD ? "✅ B O T H B R O K E N" : hitU ? "✅ H I G H B R O K E N" : hitD ? "✅ L O W B R O K E N" :
math.abs(net) < 10 ? "B A L A N C E D" :
upDom ? "B R E A K O U T E D G E +" + str.tostring(math.round(net)) : "B R E A K D O W N E D G E −" + str.tostring(math.round(-net))
string tip = "NET EDGE: " + (net >= 0 ? "+" : "−") + str.tostring(math.abs(net), "0.##") + " pts toward " + (upDom ? "BREAKOUT ▲" : "BREAKDOWN ▼") +
" (needle). Within ±10 = balanced.\n\n" + f_pdTip(true) + "\n\n" + f_pdTip(false)
f_pdDialM(pdT, padC, hiOdds, loOdds, tUp, tDn, f_pdTicks(hiCol), f_pdTicks(loCol), pw, ph)
f_pdTags(pdT, padC, pw, "B R E A K O U T P R O B A B I L I T Y", info,
"▼ " + PctStr(loOdds) + " · " + PctStr(hiOdds) + " ▲", zone, hdrBg, valBg, tagTx, tip)
////////////////////////////////////////////////////////////////////////////
//// END PROBABILITY PIXEL DIALS ///
////////////////////////////////////////////////////////////////////////////