CBDR Deviations+ (M1D)

mayb1dayy · study · 1498 行 · 点赞 103 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
indicator("CBDR Deviations+ (M1D)", "CBDR+ (M1D)", overlay = true,
     max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
const color C_BLACK = #000000
 
//@variable True on a dark chart background
bool DARK = color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color) < 384
 
//@variable Ink for text, the panel and neutral lines: black on a light chart, white on a dark one
color C_INK = DARK ? #FFFFFF : C_BLACK
 
//@function Swaps a black colour for white on a dark chart, keeping its transparency.
//@param c (color) The colour as set
//@returns (color) The colour to draw with
inkFor(color c) =>
    DARK and color.r(c) + color.g(c) + color.b(c) == 0 ? color.new(#FFFFFF, color.t(c)) : c
 
string TZ = "America/New_York"
 
// ── Reference windows ───────────────────────────────────────────────────────
string GRP_W = "Reference Windows (New York time)"
 
string DAY_EVE = "Sun-Thu (evening, feeds the next day)"
string DAY_RTH = "Mon-Fri (the trading day itself)"
 
bool   showCbdr  = input.bool(true,  "CBDR",        group = GRP_W, inline = "cbdr")
string cbdrSess  = input.session("1400-2000", "", group = GRP_W, inline = "cbdr",
     tooltip = "Central Bank Dealers Range. 14:00-20:00 New York.")
string cbdrDays  = input.string(DAY_EVE, "CBDR runs on", options = [DAY_EVE, DAY_RTH], group = GRP_W)
 
bool   showAsia  = input.bool(false, "Asian Range", group = GRP_W, inline = "asia")
string asiaSess  = input.session("2000-2400", "", group = GRP_W, inline = "asia",
     tooltip = "Asian Range. Begins as the CBDR window closes at 20:00 New York.")
string asiaDays  = input.string(DAY_EVE, "Asia runs on", options = [DAY_EVE, DAY_RTH], group = GRP_W)
 
bool   showLondon = input.bool(false, "London",    group = GRP_W, inline = "london")
string londonSess = input.session("0200-0500", "", group = GRP_W, inline = "london",
     tooltip = "London. 02:00-05:00 New York.")
string lonDays    = input.string(DAY_RTH, "London runs on", options = [DAY_EVE, DAY_RTH], group = GRP_W)
 
bool   showCustom = input.bool(false, "Custom",    group = GRP_W, inline = "custom")
string customSess = input.session("0000-0030", "", group = GRP_W, inline = "custom",
     tooltip = "A free window for any reference period. Not a named concept from the source " +
               "material — it applies the same arithmetic to whatever window is set.")
string custDays   = input.string(DAY_RTH, "Custom runs on", options = [DAY_EVE, DAY_RTH], group = GRP_W,
     tooltip = "Which calendar days a window fires on. A evening window that leads into the " +
               "following session runs Sunday through Thursday — it carries Sunday and skips " +
               "Friday, because Friday evening has no session to feed. A window inside the " +
               "trading day itself runs Monday through Friday. Choosing the wrong one does not " +
               "throw a error, it silently drops a day.")
 
string customName = input.string("Custom", "Name for the custom window", group = GRP_W,
     tooltip = "The name the zone is tagged with on the chart and in the status panel.")
 
// ── Measurement ─────────────────────────────────────────────────────────────
string GRP_M = "Measurement"
 
string measureMode = input.string("Bodies + wick reference", "Range measured from",
     options = ["Bodies", "Wicks", "Bodies + wick reference"], group = GRP_M,
     tooltip = "The projections are built from the BODIES by default — the highest open-or-close " +
               "to the lowest open-or-close — because a wick carries the dealing spread and every " +
               "feed disagrees on it. The wick range still matters though, so the default mode " +
               "draws it as a faint box behind the body range rather than hiding it.")
 
int maxSets = input.int(2, "Windows kept on chart", minval = 1, maxval = 5, group = GRP_M)
 
float partialTol = input.float(60, "Partial window threshold (%)", minval = 10, maxval = 100,
     step = 5, group = GRP_M,
     tooltip = "A window holding fewer than this share of its expected bars is reported as " +
               "Partial. Catches windows truncated by a closed market, such as Sunday " +
               "afternoon on index futures.")
 
// ── Standard deviations ─────────────────────────────────────────────────────
string GRP_D = "Standard Deviations"
 
bool showDev1  = input.bool(true,  "1.0", group = GRP_D, inline = "dev")
bool showDev2  = input.bool(true,  "2.0", group = GRP_D, inline = "dev")
bool showDev3  = input.bool(true,  "3.0", group = GRP_D, inline = "dev")
bool showDev4  = input.bool(true,  "4.0", group = GRP_D, inline = "dev")
bool showDev25 = input.bool(false, "2.5 (not part of the original set)", group = GRP_D)
bool showEq    = input.bool(true,  "Equilibrium (50% of the range)",     group = GRP_D)
 
// Deviations are the main source of clutter — four multiples, two sides, per range.
// Each range decides for itself whether it projects at all.
bool cbdrDevs = input.bool(false, "CBDR",   group = GRP_D, inline = "which")
bool asiaDevs = input.bool(false, "Asia",   group = GRP_D, inline = "which")
bool lonDevs  = input.bool(false, "London", group = GRP_D, inline = "which")
bool custDevs = input.bool(false, "Custom", group = GRP_D, inline = "which",
     tooltip = "Which ranges project deviations. The range box, its high and its low still " +
               "draw for every window switched on — this only governs the projections.")
 
float devSpanHours = input.float(0, "Stop deviation lines after (hours, 0 = run to price)",
     minval = 0, maxval = 48, step = 1, group = GRP_D,
     tooltip = "Deviation lines run from the window close to the current candle by default. " +
               "Give them a fixed span and they stop early instead of striping the whole chart.")
 
string sideMode = input.string("Both", "Project", options = ["Both", "Above only", "Below only"],
     group = GRP_D,
     tooltip = "These projections need a directional bias to be worth anything. On a sell day " +
               "the upside set locates the high; on a buy day the downside set locates the low.")
 
// ── Size validity ───────────────────────────────────────────────────────────
string GRP_V = "Size Validity"
 
string gateMode = input.string("Percent of ADR", "Threshold measured as",
     options = ["Percent of ADR", "Absolute price"], group = GRP_V,
     tooltip = "The published limits are quoted in foreign exchange pips against a daily range " +
               "of roughly 100 pips. Percent of ADR carries the same ratios to any instrument.")
 
int adrLen = input.int(20, "ADR length (days)", minval = 2, maxval = 100, group = GRP_V)
 
float cbdrIdealPct = input.float(30, "CBDR ideal ceiling (% of ADR)", minval = 1, maxval = 300, step = 5, group = GRP_V)
float cbdrMaxPct   = input.float(40, "CBDR hard cap (% of ADR)",      minval = 1, maxval = 300, step = 5, group = GRP_V)
float asiaIdealPct = input.float(20, "Asia ideal ceiling (% of ADR)", minval = 1, maxval = 300, step = 5, group = GRP_V)
float asiaMaxPct   = input.float(30, "Asia hard cap (% of ADR)",      minval = 1, maxval = 300, step = 5, group = GRP_V)
float lonIdealPct  = input.float(30, "London ideal ceiling (% of ADR)", minval = 1, maxval = 300, step = 5, group = GRP_V)
float lonMaxPct    = input.float(40, "London hard cap (% of ADR)",      minval = 1, maxval = 300, step = 5, group = GRP_V)
float custIdealPct = input.float(30, "Custom ideal ceiling (% of ADR)", minval = 1, maxval = 300, step = 5, group = GRP_V)
float custMaxPct   = input.float(40, "Custom hard cap (% of ADR)",      minval = 1, maxval = 300, step = 5, group = GRP_V)
 
float cbdrIdealAbs = input.float(0.0, "CBDR ideal ceiling (price)", minval = 0, group = GRP_V)
float cbdrMaxAbs   = input.float(0.0, "CBDR hard cap (price)",      minval = 0, group = GRP_V)
float asiaIdealAbs = input.float(0.0, "Asia ideal ceiling (price)", minval = 0, group = GRP_V)
float asiaMaxAbs   = input.float(0.0, "Asia hard cap (price)",      minval = 0, group = GRP_V)
float lonIdealAbs  = input.float(0.0, "London ideal ceiling (price)", minval = 0, group = GRP_V)
float lonMaxAbs    = input.float(0.0, "London hard cap (price)",      minval = 0, group = GRP_V)
float custIdealAbs = input.float(0.0, "Custom ideal ceiling (price)", minval = 0, group = GRP_V)
float custMaxAbs   = input.float(0.0, "Custom hard cap (price)",      minval = 0, group = GRP_V)
 
bool hideOversized = input.bool(true, "Hide projections from a oversized range", group = GRP_V,
     tooltip = "The range itself is still drawn so the reason for the rejection stays visible.")
 
// ── Retirement ──────────────────────────────────────────────────────────────
string GRP_G = "Retirement"
 
float expiryHours = input.float(72, "Expire a window after (hours)", minval = 1, maxval = 240,
     step = 1, group = GRP_G,
     tooltip = "A reference range speaks for the day that follows it, but a evening window on " +
               "the Sunday-to-Thursday rule has a gap built into the week: no Friday range, no " +
               "Saturday range, and Sunday's does not close until 20:00. That leaves 72 hours " +
               "where Thursday's is the newest one there is. Seventy-two carries it across the " +
               "weekend rather than blanking the chart from Friday evening to Sunday night. " +
               "Shorten it to show nothing rather than something stale — the panel always " +
               "states a range's age either way.")
 
float maxDistAdr = input.float(1.5, "Remove levels further than (x ADR)", minval = 0.2, maxval = 10.0,
     step = 0.1, group = GRP_G,
     tooltip = "A drawing left hanging far from the candles forces the auto price scale to keep " +
               "reaching for it, and the pane rescales on every interaction.")
 
// ── Style ───────────────────────────────────────────────────────────────────
string GRP_C = "Style"
 
string labelDetail = input.string("Short", "Label detail", options = ["Short", "Full", "None"],
     group = GRP_C)
 
string tableSize = input.string("Small", "Status panel size", options = ["Tiny", "Small", "Normal"],
     group = GRP_C)
 
// Spreading the labels across several placements beats stacking every range at one edge.
string cbdrLblPos = input.string("Right edge", "CBDR labels",
     options = ["Right edge", "Left of line", "Centre above line", "Hidden"], group = GRP_C)
string asiaLblPos = input.string("Left of line", "Asia labels",
     options = ["Right edge", "Left of line", "Centre above line", "Hidden"], group = GRP_C)
string lonLblPos  = input.string("Left of line", "London labels",
     options = ["Right edge", "Left of line", "Centre above line", "Hidden"], group = GRP_C)
string custLblPos = input.string("Right edge", "Custom labels",
     options = ["Right edge", "Left of line", "Centre above line", "Hidden"], group = GRP_C,
     tooltip = "Right edge sits the caption beside price and is the only placement that gets " +
               "the anti-overlap pass. Left of line puts it where the line leaves its window, " +
               "text running away from the line. Centre above line rides the middle of the " +
               "line's own span. Hidden draws the line with no caption at all.")
 
// ── Line widths ─────────────────────────────────────────────────────────────
int cbdrW = input.int(1, "High / low width — CBDR", minval = 1, maxval = 4, group = GRP_C, inline = "rngw")
int asiaW = input.int(1, "Asia",   minval = 1, maxval = 4, group = GRP_C, inline = "rngw")
int lonW  = input.int(1, "London", minval = 1, maxval = 4, group = GRP_C, inline = "rngw")
int custW = input.int(1, "Custom", minval = 1, maxval = 4, group = GRP_C, inline = "rngw",
     tooltip = "Width of each range's own high and low lines.")
 
int cbdrDevW = input.int(1, "Projection width — CBDR", minval = 1, maxval = 4, group = GRP_C, inline = "devw")
int asiaDevW = input.int(1, "Asia",   minval = 1, maxval = 4, group = GRP_C, inline = "devw")
int lonDevW  = input.int(1, "London", minval = 1, maxval = 4, group = GRP_C, inline = "devw")
int custDevW = input.int(1, "Custom", minval = 1, maxval = 4, group = GRP_C, inline = "devw",
     tooltip = "Width of each range's projection lines, set separately from its own extremes.")
 
int eqW = input.int(1, "Equilibrium width", minval = 1, maxval = 4, group = GRP_C)
int boxBorderW = input.int(1, "Range box border width", minval = 1, maxval = 4, group = GRP_C)
 
float labelGapAdr = input.float(0.04, "Minimum label spacing (x ADR)", minval = 0.0, maxval = 1.0,
     step = 0.01, group = GRP_C,
     tooltip = "Applies to the projection labels at the right edge only, and only when two would " +
               "physically collide. Keep it small — a label nudged far off its own line reads as " +
               "a mistake, and the further it is nudged the worse it looks on zoom.")
 
color cbdrCol = inkFor(input.color(color.new(C_BLACK, 0), "CBDR",       group = GRP_C))
color asiaCol = inkFor(input.color(color.new(C_BLACK, 0), "Asian Range", group = GRP_C))
color lonCol  = input.color(color.new(color.gray, 0),  "London",      group = GRP_C)
color custCol = inkFor(input.color(color.new(C_BLACK, 0), "Custom",     group = GRP_C))
color eqCol   = input.color(color.new(color.gray, 0),  "Equilibrium", group = GRP_C)
 
bool showZone  = input.bool(true, "Show the range box",    group = GRP_C)
 
bool showLevelTags = input.bool(false, "Caption the high, low and equilibrium lines",
     group = GRP_C,
     tooltip = "Off by default because the box already carries the range name. On names each " +
               "line as well.")
bool showPanel = input.bool(true, "Show the status panel", group = GRP_C)
bool suiteOn  = false   // public build: draws every window itself
int  suiteLane = 0
 
// ── Block projection ────────────────────────────────────────────────────────
string GRP_B = "CBDR Block Projection"
 
string PIP_AUTO = "Auto (pips on forex, ADR / 100 elsewhere)"
string PIP_FX   = "Pips"
string PIP_ADR  = "ADR / 100"
 
bool showBlocks = input.bool(true, "Project the CBDR block", group = GRP_B,
     tooltip = "London's Judas run away from the CBDR sets the measure. The block is the CBDR " +
               "plus every standard deviation London used: a high at +2 SD makes a block of three " +
               "CBDR heights. A sell day (London made the high) stacks the block down from the " +
               "CBDR low; a buy day (London made the low) stacks it up from the CBDR high.")
int blockCount = input.int(2, "Blocks drawn", minval = 1, maxval = 4, group = GRP_B)
string blockBasis = input.string("Bodies", "Block measured from", options = ["Bodies", "Wicks", "Both"],
     group = GRP_B,
     tooltip = "Bodies: the highest open-or-close to the lowest open-or-close of the CBDR window. " +
               "Wicks: high to low. Both draws the wick set as dashed lines beside the body set.")
string judasSrc = input.string("Wicks", "London extreme read from", options = ["Wicks", "Bodies"],
     group = GRP_B)
int judasHour = input.int(5, "London extreme counts at (New York hour)", minval = 0, maxval = 9,
     group = GRP_B,
     tooltip = "The furthest point price reaches beyond the CBDR between the window close at " +
               "20:00 and this hour is the Judas extreme. 05:00 is the close of the London open " +
               "kill zone. The blocks draw at this hour, once the move has happened.")
float sdTolPct = input.float(25, "Count a SD missed by up to (% of a SD)", minval = 0, maxval = 50,
     step = 5, group = GRP_B,
     tooltip = "A London extreme that stops just short of a standard deviation still counts as " +
               "reaching it. At 25, a run to 0.8 SD counts as 1 SD; a run to 0.7 SD counts as none.")
bool blockCap = input.bool(true, "Stop the blocks at 14:00 New York", group = GRP_B,
     tooltip = "14:00 New York usually caps the range of the day on FX and gold. " +
               "Off by itself on index and other futures, which run on to their own close.")
// 14:00 caps the day on FX and gold; index futures trade on into their own close.
bool capApplies = syminfo.type != "futures" or
     str.contains("GC MGC SI SIL HG MHG PL", syminfo.root)
bool showLcKz = input.bool(false, "Mark the London close (10:00-12:00) and 14:00", group = GRP_B)
string pipMode = input.string(PIP_AUTO, "Size test in", options = [PIP_AUTO, PIP_FX, PIP_ADR],
     group = GRP_B,
     tooltip = "Pips are the forex unit. On futures, metals and crypto one pip is read as a " +
               "hundredth of the average daily range, so a 100 pip day is the instrument's own " +
               "average day.")
float pipMin   = input.float(5,  "Ideal from (pips)",   minval = 0, step = 1, group = GRP_B, inline = "pip")
float pipIdeal = input.float(30, "to",                  minval = 1, step = 1, group = GRP_B, inline = "pip")
float pipMax   = input.float(40, "No CBDR over (pips)", minval = 1, step = 1, group = GRP_B,
     tooltip = "Ideal from the first figure to the second, pushing it up to the cap, and no CBDR " +
               "past the cap: no block is drawn on that day and the panel says why. A range under " +
               "the first figure is reported as small and still projected.")
 
string BLK_BOX  = "Boxes"
string BLK_LINE = "Lines"
string blockStyle = input.string(BLK_BOX, "Draw the block as", options = [BLK_BOX, BLK_LINE],
     group = GRP_B,
     tooltip = "Boxes: the SDs London used stacked on the CBDR, and the blocks as a staircase of " +
               "boxes stepping away from the CBDR edge, each day kept inside its own window. " +
               "Lines: one level per block running to the 14:00 stop.")
color blockFill = inkFor(input.color(color.new(C_BLACK, 90), "Block colour", group = GRP_B,
     tooltip = "Black turns white on a dark chart."))
 
// ── London profile ──────────────────────────────────────────────────────────
string GRP_P = "London Profile"
 
bool showProfile = input.bool(true, "Report the London profile", group = GRP_P,
     tooltip = "The four London profiles: sell or buy, normal or delayed. Reported in the panel " +
               "as facts only: the Asian range against 20-30 pips, what price did from 00:00 to " +
               "02:00 New York, and whether it traded through the Asian range or CBDR by 01:30. " +
               "The bias comes from the daily chart first; both sides are shown.")
float asiaMinP = input.float(20, "Asian range from (pips)", minval = 0, step = 1, group = GRP_P, inline = "asp")
float asiaMaxP = input.float(30, "to",                      minval = 1, step = 1, group = GRP_P, inline = "asp")
float flatPips = input.float(10, "00:00-02:00 counts as flat under (pips)", minval = 0, step = 1,
     group = GRP_P,
     tooltip = "The net move from the 00:00 open to the 02:00 close. Under this it reads FLAT.")
int breakMins = input.int(90, "Break of the range counted until (minutes after 00:00)",
     minval = 15, maxval = 120, step = 15, group = GRP_P,
     tooltip = "Price above the Asian range or CBDR high (or below the low) by 01:30 New York " +
               "confirms a normal profile.")
 
 
// ════════════════════════════════════════════════════════════════════════════
// HELPERS
// ════════════════════════════════════════════════════════════════════════════
 
//@function Reads the span of a session string in minutes, handling a window that crosses midnight.
//@param sess (string) A session string in HHMM-HHMM form, with or without a day mask
//@returns (int) The window length in minutes, or 0 if the string is malformed
sessionMinutes(string sess) =>
    int span = 0
    if str.length(sess) >= 9
        int startHour = math.round(nz(str.tonumber(str.substring(sess, 0, 2))))
        int startMin  = math.round(nz(str.tonumber(str.substring(sess, 2, 4))))
        int endHour   = math.round(nz(str.tonumber(str.substring(sess, 5, 7))))
        int endMin    = math.round(nz(str.tonumber(str.substring(sess, 7, 9))))
        int fromMin = startHour * 60 + startMin
        int toMin   = endHour * 60 + endMin
        span := toMin <= fromMin ? (toMin + 1440) - fromMin : toMin - fromMin
    span
 
//@function Formats a price using the instrument's own tick formatting.
//@param value (float) The price to format
//@returns (string) The formatted price
fmtPrice(float value) =>
    str.tostring(value, format.mintick)
 
//@function Returns the expectation attached to a standard deviation multiple.
//@param mult (float) The deviation multiple
//@param upside (bool) True for a projection above the range, false for below
//@returns (string) The annotation, or a empty string where none applies
devMeaning(float mult, bool upside) =>
    switch
        mult <= 2.0 => upside ? "Ideal HOD" : "Ideal LOD"
        mult == 3.0 => "Typical Extreme"
        mult == 4.0 => "News / Reversal"
        =>             ""
 
//@variable Chart bar length in minutes, used to size the expected bar count of a window.
float tfMinutes = timeframe.in_seconds(timeframe.period) / 60.0
 
//@variable True when the chart resolution is fine enough to measure these windows.
bool tfSupported = timeframe.isintraday and tfMinutes <= 60
 
//@variable True when the projections are built from the wick range rather than the bodies.
bool useWickBase = measureMode == "Wicks"
 
//@variable True when the wick range is drawn as a reference behind a body-based measurement.
bool showWickRef = measureMode == "Bodies + wick reference"
 
//@variable Average daily range over the previous adrLen completed daily bars.
float adr = request.security(syminfo.tickerid, "D", ta.sma(high - low, adrLen)[1],
     lookahead = barmerge.lookahead_on)
 
//@variable Price distance beyond which a drawing is deleted rather than left hanging.
float distGate = nz(adr, 0.0) * maxDistAdr
 
//@variable Minimum vertical spacing between two labels, in price.
float labelGap = nz(adr, 0.0) * labelGapAdr
 
//@variable Resolved text size for every cell in the status panel.
string tblTxt = tableSize == "Tiny" ? size.tiny : tableSize == "Small" ? size.small : size.normal
 
//@variable The enabled standard deviation multiples, built once on the first bar.
var array<float> devMults = array.new<float>()
if barstate.isfirst
    if showDev1
        devMults.push(1.0)
    if showDev2
        devMults.push(2.0)
    if showDev25
        devMults.push(2.5)
    if showDev3
        devMults.push(3.0)
    if showDev4
        devMults.push(4.0)
 
// ════════════════════════════════════════════════════════════════════════════
// TYPES
// ════════════════════════════════════════════════════════════════════════════
 
//@type One drawn price level. Every coordinate is a timestamp, never a bar index.
type Level
    line   ln     = na
    label  lbl    = na
    float  price  = na
    int    setId  = 0
    int    bornAt = 0
    int    anchorT = 0
    string lblPos = "Right edge"
    int    endCap = 0
    int    lblX   = 0
    bool   isBlock = false
    bool   below   = false
    bool   spent   = false
    bool   pinned  = false
 
//@type Live measurement state and drawing set for one reference range
type RangeState
    string        name       = ""
    float         bodyHi     = na
    float         bodyLo     = na
    int           bodyHiT    = 0
    int           bodyLoT    = 0
    float         wickHi     = na
    float         wickLo     = na
    int           wickHiT    = 0
    int           wickLoT    = 0
    float         hi         = na
    float         lo         = na
    int           hiT        = 0
    int           loT        = 0
    int           startT     = 0
    int           endT       = 0
    int           winEnd     = 0
    int           bars       = 0
    float         rangeSize  = na
    float         idealLimit = na
    float         maxLimit   = na
    string        grade      = ""
    bool          complete   = false
    bool          oversized  = false
    bool          partial    = false
    int           setId      = 0
    int           hidden     = 0
    int           closedAt   = 0
    array<Level>  levels     = na
    array<box>    boxes      = na
    array<int>    boxSet     = na
    array<float>  boxMid     = na
    array<int>    boxBorn    = na
    array<label>  boxTag     = na
    box           liveBox    = na
    box           liveWick   = na
    label         liveTag    = na
    line           liveHiLn  = na
    line           liveLoLn  = na
 
//@function Builds a range with its drawing stores initialised.
//@param name (string) Display name used on labels and in the status panel
//@returns (RangeState) A ready-to-use range
newRange(string name) =>
    RangeState.new(name = name, levels = array.new<Level>(),
         boxes = array.new<box>(), boxSet = array.new<int>(),
         boxMid = array.new<float>(), boxBorn = array.new<int>(),
         boxTag = array.new<label>())
 
// ════════════════════════════════════════════════════════════════════════════
// MEASUREMENT
// ════════════════════════════════════════════════════════════════════════════
 
//@function Opens a fresh measurement window and puts its zone on the chart immediately.
//@param this (RangeState) The range being measured
//@param col (color) Colour for this range
//@param lineW (int) Width of this range's own high and low lines
//@param fullEnd (int) Timestamp the window closes at
//@returns (bool) Always true
method beginWindow(RangeState this, color col, int lineW, int fullEnd) =>
    box.delete(this.liveBox)
    box.delete(this.liveWick)
    label.delete(this.liveTag)
    line.delete(this.liveHiLn)
    line.delete(this.liveLoLn)
 
    this.bodyHi   := na
    this.bodyLo   := na
    this.wickHi   := na
    this.wickLo   := na
    this.bars     := 0
    this.startT   := time
    this.endT     := time_close
    this.winEnd   := math.max(fullEnd, time_close)
    this.complete := false
 
    // The zone is drawn the moment the window opens and grows with price for the whole
    // session, so it is watchable while it forms instead of appearing finished at 20:00.
    if showWickRef
        color wickFill = color.new(col, 95)
        this.liveWick := box.new(this.startT, high, this.winEnd, low, xloc = xloc.bar_time,
             border_color = wickFill, border_width = boxBorderW, border_style = line.style_dotted,
             bgcolor = wickFill)
    if showZone
        color fill = color.new(col, 82)
        this.liveBox := box.new(this.startT, high, this.winEnd, low, xloc = xloc.bar_time,
             border_color = color.new(col, 100), border_width = 0, bgcolor = fill)
        label tag = label.new(this.startT, high, this.name,
             xloc      = xloc.bar_time,
             style     = label.style_label_down,
             color     = color.new(color.white, 100),
             textcolor = col,
             size      = size.small,
             textalign = text.align_center)
        label.set_text_font_family(tag, font.family_monospace)
        this.liveTag := tag
    this.liveHiLn := line.new(this.startT, high, this.winEnd, high, xloc = xloc.bar_time,
         color = col, width = lineW, style = line.style_solid)
    this.liveLoLn := line.new(this.startT, low, this.winEnd, low, xloc = xloc.bar_time,
         color = col, width = lineW, style = line.style_solid)
    true
 
//@function Folds one in-window candle into the body and wick extremes, recording its time.
//@param this (RangeState) The range being measured
//@returns (bool) Always true
method addBar(RangeState this) =>
    float barBodyHi = math.max(open, close)
    float barBodyLo = math.min(open, close)
    if na(this.bodyHi) or barBodyHi > this.bodyHi
        this.bodyHi  := barBodyHi
        this.bodyHiT := time
    if na(this.bodyLo) or barBodyLo < this.bodyLo
        this.bodyLo  := barBodyLo
        this.bodyLoT := time
    if na(this.wickHi) or high > this.wickHi
        this.wickHi  := high
        this.wickHiT := time
    if na(this.wickLo) or low < this.wickLo
        this.wickLo  := low
        this.wickLoT := time
    this.endT := time_close
    this.bars += 1
 
    // Grow the live drawings with the window rather than waiting for it to close.
    float runHi = useWickBase ? this.wickHi : this.bodyHi
    float runLo = useWickBase ? this.wickLo : this.bodyLo
    int   runHiT = useWickBase ? this.wickHiT : this.bodyHiT
    int   runLoT = useWickBase ? this.wickLoT : this.bodyLoT
    if not na(this.liveWick)
        box.set_top(this.liveWick, this.wickHi)
        box.set_bottom(this.liveWick, this.wickLo)
        box.set_right(this.liveWick, math.max(this.winEnd, this.endT))
    if not na(this.liveBox)
        box.set_top(this.liveBox, runHi)
        box.set_bottom(this.liveBox, runLo)
        box.set_right(this.liveBox, math.max(this.winEnd, this.endT))
    if not na(this.liveTag)
        label.set_xy(this.liveTag, int(math.avg(this.startT, math.max(this.winEnd, this.endT))), runHi)
    if not na(this.liveHiLn)
        line.set_xy1(this.liveHiLn, runHiT, runHi)
        line.set_xy2(this.liveHiLn, math.max(this.winEnd, this.endT), runHi)
    if not na(this.liveLoLn)
        line.set_xy1(this.liveLoLn, runLoT, runLo)
        line.set_xy2(this.liveLoLn, math.max(this.winEnd, this.endT), runLo)
    true
 
//@function Closes the window, resolves the measurement basis and grades the range.
//@param this (RangeState) The range being measured
//@param idealPct (float) Ideal ceiling as a percent of the average daily range
//@param maxPct (float) Hard cap as a percent of the average daily range
//@param idealAbs (float) Ideal ceiling in the instrument's own price units
//@param maxAbs (float) Hard cap in the instrument's own price units
//@param expectedBars (float) Bar count a full window would hold at this resolution
//@returns (bool) Always true
method closeWindow(RangeState this, float idealPct, float maxPct,
     float idealAbs, float maxAbs, float expectedBars) =>
    this.hi  := useWickBase ? this.wickHi  : this.bodyHi
    this.lo  := useWickBase ? this.wickLo  : this.bodyLo
    this.hiT := useWickBase ? this.wickHiT : this.bodyHiT
    this.loT := useWickBase ? this.wickLoT : this.bodyLoT
    this.rangeSize := na(this.hi) or na(this.lo) ? na : this.hi - this.lo
 
    this.idealLimit := gateMode == "Percent of ADR" ? adr * idealPct / 100.0 : idealAbs
    this.maxLimit   := gateMode == "Percent of ADR" ? adr * maxPct   / 100.0 : maxAbs
 
    bool capSet = not na(this.maxLimit) and this.maxLimit > 0
    this.oversized := not na(this.rangeSize) and capSet and this.rangeSize > this.maxLimit
    this.partial   := expectedBars > 0 and this.bars < expectedBars * partialTol / 100.0
    this.complete  := not na(this.rangeSize)
 
    this.setId    += 1
    this.hidden   := 0
    this.closedAt := time
 
    bool idealSet = not na(this.idealLimit) and this.idealLimit > 0
    this.grade := switch
        not this.complete => ""
        this.oversized    => "Oversized"
        idealSet and this.rangeSize <= this.idealLimit => "Ideal"
        capSet            => "Acceptable"
        =>                   "Ungated"
    true
 
// ════════════════════════════════════════════════════════════════════════════
// DRAWING — every coordinate is a timestamp under xloc.bar_time
// ════════════════════════════════════════════════════════════════════════════
 
//@function Creates one level, its line and its label, and files it under the current set.
//@param this (RangeState) The range that owns the level
//@param price (float) Price of the level
//@param anchorT (int) Timestamp of the candle the level starts from
//@param levelText (string) Label text, or empty to draw the line unlabelled
//@param col (color) Line and text colour
//@param lineStyle (string) Line style constant
//@param lblPos (string) Where the caption sits relative to the line
//@param endCap (int) Timestamp the line stops at, or 0 to run to the current candle
//@param lineW (int) Line width
//@returns (Level) The level just filed
method addLevel(RangeState this, float price, int anchorT, string levelText,
     color col, string lineStyle, string lblPos, int endCap, int lineW) =>
    Level lv = Level.new(price = price, setId = this.setId, bornAt = time,
         anchorT = anchorT, lblPos = lblPos, endCap = endCap, lblX = anchorT)
    lv.ln := line.new(anchorT, price, time, price, xloc = xloc.bar_time,
         color = col, width = lineW, style = lineStyle)
    if labelDetail != "None" and levelText != "" and lblPos != "Hidden"
        // Left-placed carries its text BEFORE the line starts so the line runs away from
        // it; centre rides above the span; right sits beside price.
        string lblStyle = switch lblPos
            "Left of line"      => label.style_label_right
            "Centre above line" => label.style_label_down
            =>                     label.style_label_left
        lv.lbl := label.new(lblPos == "Right edge" ? time : anchorT, price, levelText,
             xloc      = xloc.bar_time,
             style     = lblStyle,
             color     = color.new(C_INK, 100),
             textcolor = col,
             size      = size.small,
             textalign = text.align_center)
        label.set_text_font_family(lv.lbl, font.family_monospace)
    this.levels.push(lv)
    lv
 
//@function Draws the completed window: its box, extremes, equilibrium and projections.
//@param this (RangeState) The range being drawn
//@param col (color) Colour for this range
//@param devsOn (bool) Whether this range projects deviations at all
//@param lblPos (string) Where this range's captions sit relative to their line
//@param lineW (int) Width of this range's own high and low lines
//@param devW (int) Width of this range's projection lines
//@returns (bool) Always true
method drawAll(RangeState this, color col, bool devsOn, string lblPos,
     int lineW, int devW) =>
    if this.complete
        string state = this.partial ? " Partial" : this.oversized ? " Oversized" : ""
        bool  wantUp = sideMode != "Below only"
        bool  wantDn = sideMode != "Above only"
 
        // The zone already exists — it has been growing since the window opened. Closing
        // hands it to the retained store rather than drawing a second copy over it.
        if not na(this.liveWick)
            this.boxes.push(this.liveWick)
            this.boxSet.push(this.setId)
            this.boxMid.push(math.avg(this.wickHi, this.wickLo))
            this.boxBorn.push(time)
            this.boxTag.push(label(na))
            this.liveWick := na
 
        if not na(this.liveBox)
            this.boxes.push(this.liveBox)
            this.boxSet.push(this.setId)
            this.boxMid.push(math.avg(this.hi, this.lo))
            this.boxBorn.push(time)
            if not na(this.liveTag)
                label.set_text(this.liveTag, this.name + state)
            this.boxTag.push(this.liveTag)
            this.liveBox := na
            this.liveTag := na
 
        // The forming extremes become tracked levels so they can run forward from the
        // candle that made them and retire with the rest of the set.
        line.delete(this.liveHiLn)
        line.delete(this.liveLoLn)
        this.liveHiLn := na
        this.liveLoLn := na
 
        string hiTxt = showLevelTags ? this.name + " H" : ""
        string loTxt = showLevelTags ? this.name + " L" : ""
        string eqTxt = showLevelTags ? this.name + " EQ" : ""
        this.addLevel(this.hi, this.hiT, hiTxt, col, line.style_solid, lblPos, this.endT, lineW)
        this.addLevel(this.lo, this.loT, loTxt, col, line.style_solid, lblPos, this.endT, lineW)
 
        if showEq
            this.addLevel(math.avg(this.hi, this.lo), this.startT, eqTxt, eqCol,
                 line.style_dotted, lblPos, this.endT, eqW)
 
        // Projections are only known once the window has closed, so they start at its end.
        int devCap = devSpanHours > 0 ? this.endT + math.round(devSpanHours * 3600000) : 0
        bool drawDevs = devsOn and not (this.oversized and hideOversized)
        if drawDevs and devMults.size() > 0
            for i = 0 to devMults.size() - 1
                float mult = devMults.get(i)
                string stem = this.name + " " + str.tostring(mult, "#.0")
                if wantUp
                    string note = labelDetail == "Full" ? " " + devMeaning(mult, true) : ""
                    this.addLevel(this.hi + this.rangeSize * mult, this.endT,
                         "+" + stem + note, col, line.style_dashed, lblPos, devCap, devW)
                if wantDn
                    string note = labelDetail == "Full" ? " " + devMeaning(mult, false) : ""
                    this.addLevel(this.lo - this.rangeSize * mult, this.endT,
                         "-" + stem + note, col, line.style_dashed, lblPos, devCap, devW)
    true
 
//@function Deletes one level's drawings.
//@param lv (Level) The level to remove
//@returns (bool) Always true
dropLevel(Level lv) =>
    line.delete(lv.ln)
    label.delete(lv.lbl)
    true
 
//@function Retires stale and far-off drawings, then walks the live levels forward in time.
//@param this (RangeState) The range being maintained
//@returns (bool) Always true
method maintain(RangeState this) =>
    int oldest = this.setId - maxSets + 1
    // With the set on, live lines and their right-edge names end in their own column past price.
    int laneT  = suiteOn ? time + suiteLane * math.round(tfMinutes * 60000) : time
    int maxAge = math.round(expiryHours * 3600000)
 
    // Walk backwards so removals cannot shift a index still to be visited.
    if this.levels.size() > 0
        for i = this.levels.size() - 1 to 0
            Level lv = this.levels.get(i)
            bool tooOld = lv.setId < oldest or (time - lv.bornAt) > maxAge
            bool tooFar = not lv.pinned and distGate > 0 and math.abs(lv.price - close) > distGate
            if tooOld or tooFar
                dropLevel(lv)
                this.levels.remove(i)
                if tooFar and not tooOld
                    this.hidden += 1
            else
                int stopT = lv.endCap > 0 ? math.min(laneT, lv.endCap) : laneT
                line.set_x2(lv.ln, stopT)
                lv.lblX := switch lv.lblPos
                    "Left of line"      => lv.anchorT
                    "Centre above line" => int(math.avg(lv.anchorT, stopT))
                    =>                     stopT
 
    if this.boxes.size() > 0
        for i = this.boxes.size() - 1 to 0
            bool tooOld = this.boxSet.get(i) < oldest or
                 (time - this.boxBorn.get(i)) > maxAge
            bool tooFar = not na(this.boxMid.get(i)) and distGate > 0 and
                 math.abs(this.boxMid.get(i) - close) > distGate
            if tooOld or tooFar
                box.delete(this.boxes.get(i))
                label.delete(this.boxTag.get(i))
                this.boxes.remove(i)
                this.boxSet.remove(i)
                this.boxMid.remove(i)
                this.boxBorn.remove(i)
                this.boxTag.remove(i)
    true
 
//@function Adds this range's still-live labels to the shared layout pools.
//@param this (RangeState) The range being collected
//@param edgeLbl (array<label>) Pool for labels riding the right edge
//@param edgePx (array<float>) Prices matching edgeLbl
//@param edgeX (array<int>) Timestamps matching edgeLbl
//@returns (bool) Always true
method collect(RangeState this, array<label> edgeLbl, array<float> edgePx,
     array<int> edgeX) =>
    if this.levels.size() > 0
        for i = 0 to this.levels.size() - 1
            Level lv = this.levels.get(i)
            if not na(lv.lbl)
                if lv.lblPos == "Right edge"
                    edgeLbl.push(lv.lbl)
                    edgePx.push(lv.price)
                    edgeX.push(lv.lblX)
                else
                    // Everything not at the right edge sits on its own line's span, and
                    // every range spans somewhere different, so they cannot pile up.
                    label.set_xy(lv.lbl, lv.lblX, lv.price)
    true
 
//@function Places the right-edge labels, nudging apart only a pair that would overlap.
//@param lbls (array<label>) The labels to place
//@param prices (array<float>) Their true prices, index-matched to lbls
//@param xs (array<int>) Timestamps to place them at, index-matched to lbls
//@returns (bool) Always true
layoutColumn(array<label> lbls, array<float> prices, array<int> xs) =>
    int n = prices.size()
    if n > 0
        array<int> byPrice = prices.sort_indices(order.ascending)
        float lastY = na
        for k = 0 to n - 1
            int j = byPrice.get(k)
            float y = prices.get(j)
            if not na(lastY) and labelGap > 0 and y - lastY < labelGap
                y := lastY + labelGap
            label.set_xy(lbls.get(j), xs.get(j), y)
            lastY := y
    true
 
// ════════════════════════════════════════════════════════════════════════════
// DRIVER
// ════════════════════════════════════════════════════════════════════════════
 
var RangeState cbdr = newRange("CBDR")
var RangeState asia = newRange("Asia")
var RangeState lon  = newRange("London")
var RangeState cust = newRange(customName)
 
// The day mask is composed inline from the two inputs. A session string routed through a
// helper function would come back series-qualified and time() demands simple, so the mask
// is appended here at the call site and nowhere else.
bool inCbdr = not na(time(timeframe.period,
     str.substring(cbdrSess, 0, 9) + (cbdrDays == DAY_EVE ? ":12345" : ":23456"), TZ))
bool inAsia = not na(time(timeframe.period,
     str.substring(asiaSess, 0, 9) + (asiaDays == DAY_EVE ? ":12345" : ":23456"), TZ))
bool inLon  = not na(time(timeframe.period,
     str.substring(londonSess, 0, 9) + (lonDays == DAY_EVE ? ":12345" : ":23456"), TZ))
bool inCust = not na(time(timeframe.period,
     str.substring(customSess, 0, 9) + (custDays == DAY_EVE ? ":12345" : ":23456"), TZ))
 
float cbdrExpected = tfMinutes > 0 ? sessionMinutes(cbdrSess)   / tfMinutes : 0.0
float asiaExpected = tfMinutes > 0 ? sessionMinutes(asiaSess)   / tfMinutes : 0.0
float lonExpected  = tfMinutes > 0 ? sessionMinutes(londonSess) / tfMinutes : 0.0
float custExpected = tfMinutes > 0 ? sessionMinutes(customSess) / tfMinutes : 0.0
 
//@function Advances one range through the open, measure, close and draw cycle.
//@param this (RangeState) The range to advance
//@param inSession (bool) True while the current bar sits inside the window
//@param wasInSession (bool) True when the previous bar sat inside the window
//@param enabled (bool) Whether this range is switched on
//@param idealPct (float) Ideal ceiling as a percent of the average daily range
//@param maxPct (float) Hard cap as a percent of the average daily range
//@param idealAbs (float) Ideal ceiling in the instrument's own price units
//@param maxAbs (float) Hard cap in the instrument's own price units
//@param expectedBars (float) Bar count a full window would hold
//@param col (color) Colour for this range
//@param devsOn (bool) Whether this range projects deviations
//@param lblPos (string) Where this range's captions sit relative to their line
//@param lineW (int) Width of this range's own high and low lines
//@param devW (int) Width of this range's projection lines
//@returns (bool) True when the window closed on this bar
method step(RangeState this, bool inSession, bool wasInSession, bool enabled,
     float idealPct, float maxPct, float idealAbs, float maxAbs,
     float expectedBars, color col, bool devsOn, string lblPos, int lineW, int devW) =>
    bool justClosed = false
    if enabled and tfSupported
        if inSession and not wasInSession
            this.beginWindow(col, lineW, time + math.round(expectedBars * tfMinutes * 60000))
        if inSession
            this.addBar()
        if not inSession and wasInSession
            this.closeWindow(idealPct, maxPct, idealAbs, maxAbs, expectedBars)
            this.drawAll(col, devsOn, lblPos, lineW, devW)
            justClosed := this.complete
    justClosed
 
bool cbdrClosed = false
bool asiaClosed = false
bool lonClosed  = false
bool custClosed = false
 
if barstate.isconfirmed
    cbdrClosed := cbdr.step(inCbdr, inCbdr[1], showCbdr,
         cbdrIdealPct, cbdrMaxPct, cbdrIdealAbs, cbdrMaxAbs, cbdrExpected, cbdrCol,
         cbdrDevs, cbdrLblPos, cbdrW, cbdrDevW)
    asiaClosed := asia.step(inAsia, inAsia[1], showAsia and not suiteOn,
         asiaIdealPct, asiaMaxPct, asiaIdealAbs, asiaMaxAbs, asiaExpected, asiaCol,
         asiaDevs, asiaLblPos, asiaW, asiaDevW)
    lonClosed  := lon.step(inLon, inLon[1], showLondon and not suiteOn,
         lonIdealPct, lonMaxPct, lonIdealAbs, lonMaxAbs, lonExpected, lonCol,
         lonDevs, lonLblPos, lonW, lonDevW)
    custClosed := cust.step(inCust, inCust[1], showCustom,
         custIdealPct, custMaxPct, custIdealAbs, custMaxAbs, custExpected, custCol,
         custDevs, custLblPos, custW, custDevW)
 
// ════════════════════════════════════════════════════════════════════════════
// CBDR BLOCK PROJECTION
//
// London's run away from the CBDR is counted in whole standard deviations of
// the CBDR's own height. The block is the CBDR plus every one of them, and it is
// stacked the other way: down from the CBDR low when London made the high, up
// from the CBDR high when London made the low. It is drawn once the London
// extreme is set, never while it is still forming.
// ════════════════════════════════════════════════════════════════════════════
 
const color C_BULL = #1d4ed8
const color C_BEAR = #f23645
 
//@variable Price of one pip under the chosen unit.
float pipUnit = switch
    pipMode == PIP_FX  => syminfo.mintick * 10
    pipMode == PIP_ADR => nz(adr) / 100.0
    =>                    syminfo.type == "forex" ? syminfo.mintick * 10 : nz(adr) / 100.0
 
//@variable The London cut-off hour as text, used in the panel.
string judasClock = (judasHour < 10 ? "0" : "") + str.tostring(judasHour) + ":00"
 
//@function The first New York clock time at or after a moment, on that day or the next.
//@param fromT (int) The moment to search from
//@param hh (int) New York hour
//@param mm (int) New York minute
//@returns (int) Timestamp of that clock time
nyAt(int fromT, int hh, int mm) =>
    int t = timestamp(TZ, year(fromT, TZ), month(fromT, TZ), dayofmonth(fromT, TZ), hh, mm)
    if t < fromT
        int nxt = fromT + 86400000
        t := timestamp(TZ, year(nxt, TZ), month(nxt, TZ), dayofmonth(nxt, TZ), hh, mm)
    t
 
//@function Whole standard deviations a run reached past a edge, a near miss included.
//@param excess (float) Distance the run travelled beyond the edge
//@param cbdrH (float) One standard deviation, the CBDR height
//@returns (int) Deviations used, 0 to 4
sdsUsed(float excess, float cbdrH) =>
    int n = 0
    if cbdrH > 0 and not na(excess) and excess > 0
        n := math.min(4, int(math.floor(excess / cbdrH + sdTolPct / 100.0)))
    n
 
//@function Reads which side London ran and how far, against one CBDR measurement.
//@param topEdge (float) CBDR high
//@param botEdge (float) CBDR low
//@param exHi (float) Highest point since the CBDR closed
//@param exHiT (int) Time of that high
//@param exLo (float) Lowest point since the CBDR closed
//@param exLoT (int) Time of that low
//@returns ([int, int, float]) Direction (-1 sell day, 1 buy day, 0 none), deviations used, CBDR height
blockPlan(float topEdge, float botEdge, float exHi, int exHiT, float exLo, int exLoT) =>
    float cbdrH = topEdge - botEdge
    int nUp = sdsUsed(exHi - topEdge, cbdrH)
    int nDn = sdsUsed(botEdge - exLo, cbdrH)
    int dir = 0
    int n = 0
    // Both sides past 1 SD: the side reached first is the Judas run.
    if nUp >= 1 and (nDn < 1 or exHiT <= exLoT)
        dir := -1
        n := nUp
    else if nDn >= 1
        dir := 1
        n := nDn
    [dir, n, cbdrH]
 
//@function Grades a CBDR height in pips.
//@param sizePips (float) CBDR height in pips
//@returns (string) Ideal, Small, Pushing it or No CBDR
validity(float sizePips) =>
    switch
        na(sizePips)        => ""
        sizePips > pipMax   => "No CBDR"
        sizePips > pipIdeal => "Pushing it"
        sizePips < pipMin   => "Small"
        =>                     "Ideal"
 
//@function Formats a CBDR height in pips.
//@param cbdrH (float) CBDR height in price
//@returns (string) The height with its unit
pipText(float cbdrH) =>
    pipUnit > 0 ? str.tostring(cbdrH / pipUnit, "#.#") + "p" : fmtPrice(cbdrH)
 
//@function Files a box under the range's current set so it retires with it.
//@param rs (RangeState) The range that owns the box
//@param bx (box) The box
//@param mid (float) Its middle price, used by the distance gate
//@returns (bool) Always true
fileBox(RangeState rs, box bx, float mid) =>
    rs.boxes.push(bx)
    rs.boxSet.push(rs.setId)
    rs.boxMid.push(mid)
    rs.boxBorn.push(time)
    rs.boxTag.push(label(na))
    true
 
//@function Stacks the block levels the other way from London's run.
//@param rs (RangeState) The CBDR range that owns the levels
//@param dir (int) 1 stacks up from the CBDR high, -1 stacks down from the CBDR low
//@param n (int) Standard deviations London used
//@param cbdrH (float) CBDR height
//@param topEdge (float) CBDR high
//@param botEdge (float) CBDR low
//@param wickSet (bool) True for the wick-measured set
//@param capT (int) Timestamp the lines stop at, or 0 to run to price
//@param exPx (float) London's extreme
//@param exT (int) Time of that extreme
//@returns (bool) Always true
drawBlocks(RangeState rs, int dir, int n, float cbdrH, float topEdge, float botEdge,
     bool wickSet, int capT, float exPx, int exT) =>
    float blockH = cbdrH * (n + 1)
    color col = dir > 0 ? C_BULL : C_BEAR
    string edgeName = dir > 0 ? "high " + fmtPrice(topEdge) : "low " + fmtPrice(botEdge)
    bool asBoxes = blockStyle == BLK_BOX and not wickSet
    if asBoxes
        int winW  = rs.endT - rs.startT
        int barMs = math.round(tfMinutes * 60000)
        int midT  = rs.startT + int(winW / 2)
        // The SDs London used, stacked on the CBDR edge it ran from, inside the CBDR window.
        for k = 1 to n
            float sdA = dir < 0 ? topEdge + cbdrH * (k - 1) : botEdge - cbdrH * (k - 1)
            float sdB = dir < 0 ? topEdge + cbdrH * k       : botEdge - cbdrH * k
            color sdCol = k == 1 ? color.new(#A0A0A0, 45) : color.new(dir < 0 ? C_BEAR : C_BULL, 60)
            box sdBox = box.new(rs.startT, math.max(sdA, sdB), rs.endT, math.min(sdA, sdB),
                 xloc = xloc.bar_time, border_color = sdCol, border_width = 1,
                 border_style = line.style_solid, bgcolor = sdCol,
                 text = str.tostring(k) + " SD · " + pipText(cbdrH), text_size = size.small,
                 text_color = C_INK, text_halign = text.align_center,
                 text_valign = text.align_center, text_font_family = font.family_monospace)
            fileBox(rs, sdBox, na)
        // The blocks, a staircase stepping one candle right per block.
        for k = 1 to blockCount
            float bNear = dir > 0 ? topEdge + blockH * (k - 1) : botEdge - blockH * (k - 1)
            float bFar  = dir > 0 ? topEdge + blockH * k       : botEdge - blockH * k
            int   bLeft = midT + (k - 1) * barMs
            int   bRight = bLeft + int(winW * 0.8)
            string blkTxt = k == 1 ? "Block 1" + "\n= CBDR + " + str.tostring(n) + " SD" + "\n= " +
                 str.tostring(n + 1) + " x " + pipText(cbdrH) + " = " + pipText(blockH) :
                 "Block " + str.tostring(k)
            box blk = box.new(bLeft, math.max(bNear, bFar), bRight,
                 math.min(bNear, bFar), xloc = xloc.bar_time, border_color = color.new(blockFill, 0),
                 border_width = 1, border_style = line.style_solid, bgcolor = blockFill,
                 text = blkTxt, text_size = size.small, text_color = color.new(C_INK, 45),
                 text_halign = text.align_center, text_valign = text.align_center,
                 text_font_family = font.family_monospace)
            fileBox(rs, blk, na)
            // Each block is n + 1 CBDR heights tall: a dotted line marks every one of them.
            for u = 1 to n
                float unitPx = dir > 0 ? bNear + cbdrH * u : bNear - cbdrH * u
                Level unit = rs.addLevel(unitPx, bLeft, "", color.new(C_INK, 40), line.style_dotted,
                     "Hidden", bRight, 1)
                unit.pinned := true
        // The window's own tag gives way to the London label below.
        if rs.boxTag.size() > 0
            for i = 0 to rs.boxTag.size() - 1
                label tg = rs.boxTag.get(i)
                if rs.boxSet.get(i) == rs.setId and not na(tg)
                    label.set_text(tg, "")
        // London's run: a line along the top of the SD stack out to the extreme candle, named
        // centred on the CBDR window just past the stack, clear of price.
        if not na(exPx) and exT > rs.endT
            float stackPx = dir < 0 ? topEdge + cbdrH * n : botEdge - cbdrH * n
            Level jud = rs.addLevel(stackPx, rs.endT, "", col, line.style_solid, "Hidden", exT, 1)
            jud.pinned := true
            if labelDetail != "None" and rs.boxTag.size() > 0
                string runTxt = (dir < 0 ? "London high +" : "London low -") + str.tostring(n) + " SD"
                string sizeTxt = "CBDR " + pipText(cbdrH)
                label judLbl = label.new(midT, stackPx, dir < 0 ? runTxt + "\n" + sizeTxt : sizeTxt + "\n" + runTxt,
                     xloc = xloc.bar_time,
                     style = dir < 0 ? label.style_label_down : label.style_label_up,
                     color = color.new(color.white, 100), textcolor = col, size = size.small,
                     textalign = text.align_center)
                label.set_text_font_family(judLbl, font.family_monospace)
                label.set_tooltip(judLbl, "London's extreme " + fmtPrice(exPx) + ", counted as " +
                     str.tostring(n) + " SD of " + pipText(cbdrH) + ".")
                // Filed with the set's last box so it retires with the drawing.
                label.delete(rs.boxTag.get(rs.boxTag.size() - 1))
                rs.boxTag.set(rs.boxTag.size() - 1, judLbl)
    for k = (asBoxes ? blockCount : 1) to blockCount
        float px = dir > 0 ? topEdge + blockH * k : botEdge - blockH * k
        string txt = "Block " + str.tostring(k) + (wickSet ? " W" : "") + (asBoxes ? " · " + fmtPrice(px) : "")
        if labelDetail == "Full"
            txt += " · " + str.tostring((n + 1) * k) + "x"
        int lineFrom = asBoxes ? rs.startT + int((rs.endT - rs.startT) / 2) +
             (blockCount - 1) * math.round(tfMinutes * 60000) + int((rs.endT - rs.startT) * 0.8) : time
        Level lv = rs.addLevel(px, lineFrom, txt, col,
             wickSet ? line.style_dashed : line.style_solid, cbdrLblPos, capT, cbdrDevW)
        lv.isBlock := true
        lv.below   := dir < 0
        lv.pinned  := asBoxes
        if not na(lv.lbl)
            label.set_tooltip(lv.lbl, "Block " + str.tostring(k) + " of " + str.tostring(blockCount) +
                 (wickSet ? " (wicks)" : " (bodies)") + ": CBDR " + fmtPrice(cbdrH) + " + " +
                 str.tostring(n) + " SD = " + str.tostring(n + 1) + " x " + fmtPrice(cbdrH) + " = " +
                 fmtPrice(blockH) + ", " + str.tostring(k) + " block(s) " +
                 (dir > 0 ? "above the CBDR " : "below the CBDR ") + edgeName + " = " + fmtPrice(px))
    true
 
//@variable True while the CBDR has closed and the London extreme is still forming.
var bool  jPending = false
var int   jSet     = 0
var int   jCutT    = 0
var float jHi      = na
var int   jHiT     = 0
var float jLo      = na
var int   jLoT     = 0
 
//@variable What the panel's block row reads.
var string blockTxt    = ""
var string blockTip    = ""
var string bDay        = ""
var string bLon        = ""
var string bBlk        = ""
 
var array<box>   kzBoxes  = array.new<box>()
var array<line>  capLines = array.new<line>()
var array<label> kzTags   = array.new<label>()
 
//@variable True on the bar a block projection is drawn.
bool blockDrawnNow = false
 
if barstate.isconfirmed and tfSupported and showCbdr and showBlocks
    if cbdrClosed
        jPending    := true
        jSet        := cbdr.setId
        jCutT       := nyAt(time, judasHour, 0)
        jHi         := na
        jLo         := na
        blockTip    := ""
        bBlk        := ""
    if jPending and cbdr.setId != jSet
        jPending := false
 
    if jPending and time >= jCutT
        jPending := false
        bool  useBody = blockBasis != "Wicks"
        float tE = useBody ? cbdr.bodyHi : cbdr.wickHi
        float bE = useBody ? cbdr.bodyLo : cbdr.wickLo
        [dir, n, cbdrH] = blockPlan(tE, bE, jHi, jHiT, jLo, jLoT)
        string grade = validity(pipUnit > 0 ? cbdrH / pipUnit : na)
        string partTxt = cbdr.partial ? " · partial CBDR" : ""
        if grade == "No CBDR" or dir == 0
            string why = grade == "No CBDR" ? "over " + str.tostring(pipMax, "#") + "p" : "0 SD"
            if cbdr.boxTag.size() > 0
                for i = 0 to cbdr.boxTag.size() - 1
                    label tg = cbdr.boxTag.get(i)
                    if cbdr.boxSet.get(i) == cbdr.setId and not na(tg)
                        label.set_text(tg, cbdr.name + " · Not valid · " + why)
        if grade == "No CBDR"
            blockTxt    := "No CBDR · " + pipText(cbdrH) + " is over " + str.tostring(pipMax, "#") +
                 "p · no block" + partTxt
            bDay := "No CBDR"
            bLon := "—"
            bBlk := "none, " + pipText(cbdrH) + " > " + str.tostring(pipMax, "#") + "p"
        else if dir == 0
            blockTxt    := "London stayed inside 1 SD by " + judasClock + " · 0 SD used · no block" + partTxt
            bDay := "No Judas"
            bLon := "inside 1 SD"
            bBlk := "none"
        else
            int capT = blockCap and capApplies ? nyAt(time, 14, 0) : 0
            drawBlocks(cbdr, dir, n, cbdrH, tE, bE, false, capT,
                 dir < 0 ? jHi : jLo, dir < 0 ? jHiT : jLoT)
            if blockBasis == "Both"
                [dirW, nW, cbdrHW] = blockPlan(cbdr.wickHi, cbdr.wickLo, jHi, jHiT, jLo, jLoT)
                if dirW != 0 and validity(pipUnit > 0 ? cbdrHW / pipUnit : na) != "No CBDR"
                    drawBlocks(cbdr, dirW, nW, cbdrHW, cbdr.wickHi, cbdr.wickLo, true, capT,
                         dirW < 0 ? jHi : jLo, dirW < 0 ? jHiT : jLoT)
 
            // One name per price: a deviation line sitting on a block keeps its line and
            // gives up its name to the block.
            if cbdr.levels.size() > 0
                for i = 0 to cbdr.levels.size() - 1
                    Level other = cbdr.levels.get(i)
                    if not other.isBlock and other.setId == cbdr.setId and not na(other.lbl)
                        for j = 0 to cbdr.levels.size() - 1
                            Level blk = cbdr.levels.get(j)
                            if blk.isBlock and blk.setId == cbdr.setId and
                                 math.abs(blk.price - other.price) < syminfo.mintick / 2
                                label.delete(other.lbl)
                                other.lbl := na
                                break
 
            if showLcKz
                float nearPx = dir > 0 ? tE : bE
                float farPx  = dir > 0 ? tE + cbdrH * (n + 1) * blockCount : bE - cbdrH * (n + 1) * blockCount
                float topPx  = math.max(nearPx, farPx)
                float botPx  = math.min(nearPx, farPx)
                int   kzS    = nyAt(time, 10, 0)
                int   kzE    = nyAt(time, 12, 0)
                int   cutAt  = nyAt(time, 14, 0)
                color kzFill = color.new(C_INK, 92)
                kzBoxes.push(box.new(kzS, topPx, kzE, botPx, xloc = xloc.bar_time,
                     border_color = kzFill, border_width = 1, border_style = line.style_solid,
                     bgcolor = kzFill))
                label kzTag = label.new(int(math.avg(kzS, kzE)), topPx, "London close",
                     xloc = xloc.bar_time, style = label.style_label_down,
                     color = color.new(color.white, 100), textcolor = C_INK, size = size.small,
                     textalign = text.align_center)
                label.set_text_font_family(kzTag, font.family_monospace)
                kzTags.push(kzTag)
                if capApplies
                    capLines.push(line.new(cutAt, topPx, cutAt, botPx, xloc = xloc.bar_time,
                         color = C_INK, width = 1, style = line.style_dotted))
                    label capTag = label.new(cutAt, topPx, "14:00", xloc = xloc.bar_time,
                         style = label.style_label_center, color = color.new(color.white, 100),
                         textcolor = C_INK, size = size.small, textalign = text.align_right)
                    label.set_text_font_family(capTag, font.family_monospace)
                    kzTags.push(capTag)
                while kzBoxes.size() > maxSets
                    box.delete(kzBoxes.shift())
                while capLines.size() > maxSets
                    line.delete(capLines.shift())
                while kzTags.size() > maxSets * 2
                    label.delete(kzTags.shift())
 
            blockTxt := (dir < 0 ? "Sell day · London high +" : "Buy day · London low -") +
                 str.tostring(n) + " SD · block " + str.tostring(n + 1) + "x = " +
                 fmtPrice(cbdrH * (n + 1)) + " · CBDR " + pipText(cbdrH) + " " + grade + partTxt
            blockTip := "CBDR " + fmtPrice(cbdrH) + " (" + pipText(cbdrH) + ", " +
                 (useBody ? "bodies" : "wicks") + "). London " + (dir < 0 ? "high" : "low") +
                 " used " + str.tostring(n) + " SD, so the block = CBDR + " + str.tostring(n) +
                 " SD = " + str.tostring(n + 1) + " x " + fmtPrice(cbdrH) + " = " +
                 fmtPrice(cbdrH * (n + 1)) + ", stacked " + (dir < 0 ? "down from the CBDR low " +
                 fmtPrice(bE) : "up from the CBDR high " + fmtPrice(tE)) + "."
            blockDrawnNow := true
            bDay := dir < 0 ? "Sell" : "Buy"
            bLon := (dir < 0 ? "+" : "-") + str.tostring(n) + " SD"
            bBlk := str.tostring(n + 1) + "x = " + pipText(cbdrH * (n + 1))
 
    if jPending
        float bh = judasSrc == "Wicks" ? high : math.max(open, close)
        float bl = judasSrc == "Wicks" ? low  : math.min(open, close)
        if na(jHi) or bh > jHi
            jHi  := bh
            jHiT := time
        if na(jLo) or bl < jLo
            jLo  := bl
            jLoT := time
        float tL = blockBasis != "Wicks" ? cbdr.bodyHi : cbdr.wickHi
        float bL = blockBasis != "Wicks" ? cbdr.bodyLo : cbdr.wickLo
        float sL = tL - bL
        blockTxt := "Forming · high +" + str.tostring(sdsUsed(jHi - tL, sL)) + " SD · low -" +
             str.tostring(sdsUsed(bL - jLo, sL)) + " SD · counts at " + judasClock
        bDay := "at " + judasClock
        bLon := "+" + str.tostring(sdsUsed(jHi - tL, sL)) + " / -" + str.tostring(sdsUsed(bL - jLo, sL)) + " SD"
 
// A block is a target: once price trades to it inside the day's window it is spent.
if barstate.isconfirmed and cbdr.levels.size() > 0
    for i = 0 to cbdr.levels.size() - 1
        Level lv = cbdr.levels.get(i)
        if lv.isBlock and not lv.spent and time > lv.bornAt and (lv.endCap == 0 or time <= lv.endCap)
            if lv.below ? low <= lv.price : high >= lv.price
                lv.spent := true
                line.set_style(lv.ln, line.style_dotted)
 
// ════════════════════════════════════════════════════════════════════════════
// LONDON PROFILE
//
// Normal: a move straight away from the 00:00 open, through the Asian range or
// the CBDR by 01:30, with a Asian range of 20-30 pips (and a CBDR under 40, or
// over it with Asia still tight). Delayed: no clean move by 02:00, so the 02:00
// to 03:00 retracement is watched instead. Facts only; the bias is not decided
// here.
// ════════════════════════════════════════════════════════════════════════════
 
bool inMidRun = not na(time(timeframe.period, "0000-0200:23456", TZ))
bool inRetrace = not na(time(timeframe.period, "0200-0300:23456", TZ))
 
var float pAsiaHi = na
var float pAsiaLo = na
var float pMidOpen = na
var float pMidHi = na
var float pMidLo = na
var float pMidClose = na
var int   pMidT = 0
var bool  pMidDone = false
var int   pBreakDir = 0
var int   pBreakT = 0
var float pRetOpen = na
var float pRetHi = na
var float pRetLo = na
var bool  pRetDone = false
 
if barstate.isconfirmed and tfSupported and showProfile
    bool  useBodyP = blockBasis != "Wicks"
    float pHiBar = useBodyP ? math.max(open, close) : high
    float pLoBar = useBodyP ? math.min(open, close) : low
    if inAsia and not inAsia[1]
        pAsiaHi   := pHiBar
        pAsiaLo   := pLoBar
        pMidOpen  := na
        pMidDone  := false
        pBreakDir := 0
        pRetOpen  := na
        pRetDone  := false
    else if inAsia and not na(pAsiaHi)
        pAsiaHi := math.max(pAsiaHi, pHiBar)
        pAsiaLo := math.min(pAsiaLo, pLoBar)
    if inMidRun and not inMidRun[1]
        pMidOpen  := open
        pMidHi    := high
        pMidLo    := low
        pMidT     := time
        pMidDone  := false
        pBreakDir := 0
    else if inMidRun and not na(pMidOpen)
        pMidHi := math.max(pMidHi, high)
        pMidLo := math.min(pMidLo, low)
    if inMidRun and not na(pMidOpen)
        pMidClose := close
        float topLvl = math.max(nz(pAsiaHi, high), cbdr.complete ? (useBodyP ? cbdr.bodyHi : cbdr.wickHi) : nz(pAsiaHi, high))
        float botLvl = math.min(nz(pAsiaLo, low), cbdr.complete ? (useBodyP ? cbdr.bodyLo : cbdr.wickLo) : nz(pAsiaLo, low))
        if pBreakDir == 0 and time < pMidT + breakMins * 60000
            if high > topLvl
                pBreakDir := 1
                pBreakT   := time
            else if low < botLvl
                pBreakDir := -1
                pBreakT   := time
    if not inMidRun and inMidRun[1] and not na(pMidOpen)
        pMidDone := true
    if inRetrace and not inRetrace[1] and pMidDone
        pRetOpen := open
        pRetHi   := high
        pRetLo   := low
    else if inRetrace and not na(pRetOpen)
        pRetHi := math.max(pRetHi, high)
        pRetLo := math.min(pRetLo, low)
    if not inRetrace and inRetrace[1] and not na(pRetOpen)
        pRetDone := true
 
cbdr.maintain()
asia.maintain()
lon.maintain()
cust.maintain()
 
// One layout pass per column, so no two labels can ever sit on top of each other.
// Only the last bar's placement is ever seen, so it runs there alone.
if labelDetail != "None" and barstate.islast
    array<label> edgeLbl = array.new<label>()
    array<float> edgePx  = array.new<float>()
    array<int>   edgeX   = array.new<int>()
    cbdr.collect(edgeLbl, edgePx, edgeX)
    asia.collect(edgeLbl, edgePx, edgeX)
    lon.collect(edgeLbl, edgePx, edgeX)
    cust.collect(edgeLbl, edgePx, edgeX)
    layoutColumn(edgeLbl, edgePx, edgeX)
 
// ════════════════════════════════════════════════════════════════════════════
// STATUS PANEL
// ════════════════════════════════════════════════════════════════════════════
 
//@function The value a range's panel row reads: size, grade and age.
//@param this (RangeState) The range being reported
//@returns (string) The reading
rowText(RangeState this) =>
    string g = switch
        this.partial              => "Part"
        this.grade == "Acceptable" => "OK"
        this.grade == "Oversized"  => "Over"
        =>                           this.grade
    pipText(this.rangeSize) + " " + g
 
//@function The arithmetic behind a range's row, for its tooltip.
//@param this (RangeState) The range being reported
//@returns (string) The tooltip
rowTip(RangeState this) =>
    "Size " + fmtPrice(this.rangeSize) + ", cap " +
         (na(this.maxLimit) or this.maxLimit <= 0 ? "none" : fmtPrice(this.maxLimit)) +
         ", closed " + str.tostring(this.closedAt > 0 ? int((time - this.closedAt) / 3600000) : 0) +
         "h ago" + (this.hidden > 0 ? ", " + str.tostring(this.hidden) + " level(s) removed for distance" : "") + "."
 
//@function Writes one name and value row.
//@param panel (table) The panel being filled
//@param row (int) Row index
//@param name (string) Left cell
//@param value (string) Right cell
//@param tip (string) Tooltip for both cells
//@returns (bool) Always true
writeLine(table panel, int row, string name, string value, string tip) =>
    table.cell(panel, 0, row, name, text_color = C_INK, text_size = tblTxt,
         text_halign = text.align_left, text_font_family = font.family_monospace, tooltip = tip)
    table.cell(panel, 1, row, value, text_color = C_INK, text_size = tblTxt,
         text_halign = text.align_left, text_font_family = font.family_monospace, tooltip = tip)
    true
 
//@variable The checklist that has to be answered before a block is worth anything.
string CHECK_TIP = "Before using the block: where is price in the IPDA data range, premium or " +
     "discount? Bullish or bearish? Is the CBDR inside the size limit? Target = a opposing " +
     "higher timeframe PD array or liquidity. Not a trade every day."
 
//@variable The chart timeframe as a short tag.
string tfTag = tfMinutes >= 60 and tfMinutes % 60 == 0 ? str.tostring(tfMinutes / 60, "#") + "H" :
     timeframe.isintraday ? str.tostring(tfMinutes, "#") + "m" : timeframe.period
 
var table panel     = na
var int   panelRows = na
 
if showPanel and barstate.islast
    bool cbdrRow = showCbdr   and cbdr.complete
    bool asiaRow = (showAsia or showProfile) and not na(pAsiaHi)
    bool lonRow  = showLondon and not suiteOn and lon.complete
    bool custRow = showCustom and cust.complete
    bool blkRow  = showCbdr and showBlocks and tfSupported
    bool profRow = showProfile and tfSupported and not na(pAsiaHi)
    // Profile facts, built only on the bar that reads them.
    float asiaP  = pipUnit > 0 ? (pAsiaHi - pAsiaLo) / pipUnit : na
    bool  asiaOk = not na(asiaP) and asiaP >= asiaMinP and asiaP <= asiaMaxP
    float cbdrP  = cbdr.complete and pipUnit > 0 ? (blockBasis != "Wicks" ? cbdr.bodyHi - cbdr.bodyLo : cbdr.wickHi - cbdr.wickLo) / pipUnit : na
    string asiaVal = na(asiaP) ? "—" : str.tostring(asiaP, "#.#") + "p " +
         (asiaOk ? "in " : asiaP < asiaMinP ? "under " : "over ") +
         str.tostring(asiaMinP, "#") + "-" + str.tostring(asiaMaxP, "#")
    string filterTxt = not asiaOk ? "Asia " + (na(asiaP) ? "—" : str.tostring(asiaP, "#.#") + "p") +
         " outside " + str.tostring(asiaMinP, "#") + "-" + str.tostring(asiaMaxP, "#") + ": normal filter not met" :
         not na(cbdrP) and cbdrP > pipMax ? "CBDR " + str.tostring(cbdrP, "#.#") + "p over " +
         str.tostring(pipMax, "#") + " with Asia tight: the exception" : "normal filter met"
    float  moveP  = not na(pMidOpen) and pipUnit > 0 ? (pMidClose - pMidOpen) / pipUnit : na
    string moveDir = na(moveP) ? "" : moveP >= flatPips ? "UP" : moveP <= -flatPips ? "DOWN" : "FLAT"
    string brkTxt = pBreakDir > 0 ? " · above range " + str.format_time(pBreakT, "HH:mm", TZ) :
         pBreakDir < 0 ? " · below range " + str.format_time(pBreakT, "HH:mm", TZ) : ""
    string midVal = na(moveP) ? "from 00:00" : moveDir + " " + (moveP >= 0 ? "+" : "") +
         str.tostring(moveP, "#.#") + "p" + brkTxt + (pMidDone ? "" : " (running)")
    string shapeVal = switch
        na(pMidOpen)                          => "Asia forming"
        moveDir == "UP" and asiaOk            => pMidDone ? "Sell normal shape" : "Sell normal forming"
        moveDir == "DOWN" and asiaOk          => pMidDone ? "Buy normal shape" : "Buy normal forming"
        moveDir == "UP"                       => pMidDone ? "Up, filter not met: delayed watch 02-03" : "Up, normal filter not met"
        moveDir == "DOWN"                     => pMidDone ? "Down, filter not met: delayed watch 02-03" : "Down, normal filter not met"
        pMidDone                              => "Delayed: watch 02-03 retrace"
        =>                                       "No direction yet"
    bool retRow = profRow and pMidDone and not (asiaOk and (moveDir == "UP" or moveDir == "DOWN"))
    string retVal = na(pRetOpen) or pipUnit <= 0 ? "from 02:00" : "rally +" + str.tostring((pRetHi - pRetOpen) / pipUnit, "#.#") +
         "p · dip -" + str.tostring((pRetOpen - pRetLo) / pipUnit, "#.#") + "p" + (pRetDone ? "" : " (running)")
    string profTip = "Up from 00:00 is the sell normal shape (high of day 02:00-04:00); down is the buy " +
         "normal shape. With no clean move by 02:00, the delayed profile looks for a rally (sell) or " +
         "dip (buy) from 02:00 into a premium or discount PD array. " + filterTxt + ". Bias comes from " +
         "the daily chart first."
    int  want = 4 + (cbdrRow ? 1 : 0) + (asiaRow ? 1 : 0) + (lonRow ? 1 : 0) + (custRow ? 1 : 0) +
         (blkRow ? 3 : 0) + (profRow ? 2 : 0) + (retRow ? 1 : 0) + (tfSupported ? 0 : 1)
    if na(panel) or panelRows != want
        if not na(panel)
            table.delete(panel)
        panel := table.new(suiteOn ? position.bottom_right : position.top_right, 2, want, frame_color = C_INK, frame_width = 1,
             border_width = 0)
        panelRows := want
    int r = 0
    writeLine(panel, r, "CBDR DEV+", "", "")
    r += 1
    writeLine(panel, r, "INSTRUMENT", syminfo.ticker, "")
    r += 1
    writeLine(panel, r, "TIMEFRAME", tfTag, "")
    r += 1
    if cbdrRow
        writeLine(panel, r, "CBDR", rowText(cbdr), rowTip(cbdr))
        r += 1
    if asiaRow
        writeLine(panel, r, "ASIA", asiaVal, "Asian range " + asiaSess + " New York, " +
             (blockBasis != "Wicks" ? "bodies" : "wicks") + ". " + filterTxt + ".")
        r += 1
    if lonRow
        writeLine(panel, r, "LON WINDOW", rowText(lon), rowTip(lon))
        r += 1
    if custRow
        writeLine(panel, r, str.upper(customName), rowText(cust), rowTip(cust))
        r += 1
    writeLine(panel, r, "ADR", na(adr) ? "—" : pipText(adr),
         "Windows retire after " + str.tostring(expiryHours, "#") + "h; levels further than " +
         str.tostring(maxDistAdr, "#.0") + "x ADR from price are removed.")
    r += 1
    if blkRow
        string bTip = (blockTxt == "" ? "Waiting for a CBDR to close." : blockTxt + ". " + blockTip) +
             " " + CHECK_TIP
        writeLine(panel, r, "DAY", bDay == "" ? "—" : bDay, bTip)
        r += 1
        writeLine(panel, r, "LONDON", bLon == "" ? "—" : bLon, bTip)
        r += 1
        writeLine(panel, r, "BLOCK", bBlk == "" ? "—" : bBlk, bTip)
        r += 1
    if profRow
        writeLine(panel, r, "00-02", midVal, profTip)
        r += 1
        writeLine(panel, r, "PROFILE", shapeVal, profTip)
        r += 1
    if retRow
        writeLine(panel, r, "02-03", retVal, profTip)
        r += 1
    if not tfSupported
        writeLine(panel, r, "CHART", "Use 60 minutes or finer", "")
 
// ════════════════════════════════════════════════════════════════════════════
// ALERTS
// ════════════════════════════════════════════════════════════════════════════
 
//@variable True on the bar the CBDR window closes inside its ideal ceiling.
bool cbdrIdealClose = cbdrClosed and cbdr.grade == "Ideal" and not cbdr.partial
 
//@variable True on the bar the CBDR window closes between its ideal ceiling and its hard cap.
bool cbdrAcceptClose = cbdrClosed and cbdr.grade == "Acceptable" and not cbdr.partial
 
//@variable True on the bar the CBDR window closes wider than its hard cap.
bool cbdrOverClose = cbdrClosed and cbdr.oversized
 
//@variable True on the bar the Asian Range window closes inside its ideal ceiling.
bool asiaIdealClose = asiaClosed and asia.grade == "Ideal" and not asia.partial
 
//@variable Upper second deviation of the most recent CBDR — the ideal high of day boundary.
float cbdrUpper2 = cbdr.complete ? cbdr.hi + cbdr.rangeSize * 2.0 : na
 
//@variable Lower second deviation of the most recent CBDR — the ideal low of day boundary.
float cbdrLower2 = cbdr.complete ? cbdr.lo - cbdr.rangeSize * 2.0 : na
 
//@variable True when price first closes above the CBDR second deviation.
bool reachedUpper2 = not na(cbdrUpper2) and not cbdr.oversized and
     barstate.isconfirmed and close > cbdrUpper2 and close[1] <= cbdrUpper2
 
//@variable True when price first closes below the CBDR second deviation.
bool reachedLower2 = not na(cbdrLower2) and not cbdr.oversized and
     barstate.isconfirmed and close < cbdrLower2 and close[1] >= cbdrLower2
 
//@variable Upper third deviation of the most recent CBDR — the outer bound most days respect.
float cbdrUpper3 = cbdr.complete ? cbdr.hi + cbdr.rangeSize * 3.0 : na
 
//@variable Lower third deviation of the most recent CBDR — the outer bound most days respect.
float cbdrLower3 = cbdr.complete ? cbdr.lo - cbdr.rangeSize * 3.0 : na
 
//@variable True when price first closes above the CBDR third deviation.
bool reachedUpper3 = not na(cbdrUpper3) and not cbdr.oversized and
     barstate.isconfirmed and close > cbdrUpper3 and close[1] <= cbdrUpper3
 
//@variable True when price first closes below the CBDR third deviation.
bool reachedLower3 = not na(cbdrLower3) and not cbdr.oversized and
     barstate.isconfirmed and close < cbdrLower3 and close[1] >= cbdrLower3
 
alertcondition(cbdrIdealClose, "CBDR closed ideal",
     "CBDR closed inside its ideal ceiling on {{ticker}} — projections are live")
alertcondition(cbdrAcceptClose, "CBDR closed acceptable",
     "CBDR closed under its hard cap but over the ideal ceiling on {{ticker}}")
alertcondition(cbdrOverClose, "CBDR closed oversized",
     "CBDR closed wider than its hard cap on {{ticker}} — projections suppressed")
alertcondition(asiaIdealClose, "Asian Range closed ideal",
     "Asian Range closed inside its ideal ceiling on {{ticker}} — projections are live")
alertcondition(reachedUpper2, "CBDR +2.0 SD reached",
     "{{ticker}} closed above the CBDR +2.0 SD projection — past the ideal high of day zone")
alertcondition(reachedLower2, "CBDR -2.0 SD reached",
     "{{ticker}} closed below the CBDR -2.0 SD projection — past the ideal low of day zone")
alertcondition(reachedUpper3, "CBDR +3.0 SD reached",
     "{{ticker}} closed above the CBDR +3.0 SD projection")
alertcondition(reachedLower3, "CBDR -3.0 SD reached",
     "{{ticker}} closed below the CBDR -3.0 SD projection")
alertcondition(blockDrawnNow, "CBDR block projected",
     "London's extreme is set on {{ticker}} — the CBDR block projection is drawn")

← 返回列表