Statistical Zones+ (M1D)

mayb1dayy · study · 1043 行 · 点赞 45 · TradingView 原页

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

Pine Script

//@version=6
// © mayb1dayy
indicator("Statistical Zones+ (M1D)", "Stat Z+", overlay = true, max_lines_count = 100, max_labels_count = 200, max_boxes_count = 200)
 
// == CONSTANTS ===============================================================
 
//@variable Exchange-independent New York clock used by every time function
const string TZ = "America/New_York"
//@variable Minute-of-day the cash session opens
const int CASH_OPEN = 570
//@variable Minute-of-day the cash session closes; the last cash bar's close is the RTH ORG origin
const int CASH_CLOSE = 975
//@variable Minute-of-day every morning statistic is measured to
const int AM_END = 690
//@variable Distance from price, in average daily ranges, a AM high or low must sit at 10:30 to be graded
const float HOLD_GAP = 0.15
//@variable Two names closer than this many average daily ranges clash; only the higher odds is drawn
const float CLASH = 0.04
//@variable Days averaged into the daily range, matching the statistics
const int ADR_DAYS = 10
//@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 every line and label: black on a light chart, white on a dark one
color INK = DARK ? #FFFFFF : #000000
 
//@variable Length of one chart bar in minutes
int barMinutes = math.max(math.round(timeframe.in_seconds() / 60), 1)
//@variable Milliseconds in one chart bar
int msPerBar = timeframe.in_seconds() * 1000
 
// == INPUTS ==================================================================
 
const string G_LV = "Level odds (9:30 to 11:30)"
bool showLv  = input.bool(true, "Show level odds", group = G_LV)
bool lvOn    = input.bool(true, "Overnight high / low", group = G_LV)
bool lvPd    = input.bool(true, "Previous day high / low", group = G_LV)
bool lvPw    = input.bool(true, "Previous week high / low", group = G_LV)
bool lvMid   = input.bool(true, "Midnight open", group = G_LV)
bool lv830   = input.bool(true, "8:30 open", group = G_LV)
bool lvWk    = input.bool(true, "Week open", group = G_LV)
bool lvOrg   = input.bool(true, "RTH ORG close and CE", group = G_LV)
int  minOdds = input.int(55, "Draw a level from (%)", minval = 55, maxval = 95, step = 5, group = G_LV, tooltip = "Only levels with at least these odds of trading by 11:30 are drawn. Nothing below 55 is ever drawn.")
bool clearHit = input.bool(true, "Remove a level once traded", group = G_LV, tooltip = "Off: a traded level stays, marked with a tick, until 11:30.")
 
const string G_OR = "Opening range"
bool showOr   = input.bool(true, "Opening range reads in the table", group = G_OR)
bool showFar  = input.bool(true, "Draw the far side after a failed break", group = G_OR)
bool showHold = input.bool(true, "AM high / low holds (from 10:30)", group = G_OR)
 
const string G_ZN = "Zones"
bool   showDayZ  = input.bool(true, "Day zones (18:00 open to 17:00)", group = G_ZN)
bool   showLdnZ  = input.bool(true, "London zones (2:00 open to 5:00)", group = G_ZN)
bool   showAmZ   = input.bool(true, "AM zones (9:30 open to 11:30)", group = G_ZN)
bool   showTicks = input.bool(true, "Tick each edge once price reaches it", group = G_ZN, tooltip = "Each edge carries a cross until price trades to it inside its window, then a tick. Scroll back to see which edges each day reached.")
int    zoneDays  = input.int(3, "Days kept on chart", minval = 1, maxval = 10, group = G_ZN)
string capSideIn = input.string("Right", "Zone names", options = ["Right", "Left"], group = G_ZN, tooltip = "Right names each edge inside the zone's right end; while that end is far off screen, a live zone's names sit just past the live candle. Left names them before the zone starts.")
int    dayNameStep = input.int(10, "Day names: extra bars right", minval = 0, maxval = 100, group = G_ZN, tooltip = "The live Day names sit this many bars further right than the level odds names, so the two never print on top of each other. 0 puts them in one column.")
 
const string G_DAY = "Table"
bool showUsed  = input.bool(true, "Range used against the zone edges", group = G_DAY)
bool showProf  = input.bool(true, "Midnight-open profile", group = G_DAY)
bool showGap   = input.bool(true, "RTH ORG gap grade", group = G_DAY)
bool showExp   = input.bool(true, "Typical morning range", group = G_DAY)
bool showWeek  = input.bool(true, "Monday week read", group = G_DAY)
bool showAft   = input.bool(true, "After 13:00: day high / low already in", group = G_DAY)
 
const string G_ST = "Style"
string lineStyleIn = input.string("Dotted", "Level lines", options = ["Solid", "Dashed", "Dotted"], group = G_ST)
int    labelSizeIn = input.int(10, "Text size", minval = 6, maxval = 14, group = G_ST, tooltip = "Points, for every name, zone and table cell. The Phone layout's table uses 8.")
int    rightOffset = input.int(10, "Right offset (bars)", minval = 3, maxval = 200, group = G_ST, tooltip = "Lines and names end this many bars past the live candle.")
bool   showTable   = input.bool(true, "Table", group = G_ST)
string tablePosIn  = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G_ST)
string layoutIn = input.string("Desktop", "Layout", options = ["Desktop", "Phone"], group = G_ST, tooltip = "Phone: the table in tiny text with its main rows only, for a narrow portrait screen. Nothing else on the chart changes.")
bool   phone    = layoutIn == "Phone"
string tableInkIn  = input.string("Auto", "Table text", options = ["Auto", "Black", "White"], group = G_ST, tooltip = "Auto follows the chart background. Pick White when the table is moved to the bottom panel under a dark theme.")
string statsSet    = input.string("Auto", "Statistics set", options = ["Auto", "Nasdaq", "S&P", "Gold"], group = G_ST, tooltip = "Auto reads the chart's root symbol: NQ and MNQ, ES and MES, GC and MGC. Pick one by hand to use a set on another feed of the same market.")
color  BULL        = input.color(#7246CE, "Bullish", group = G_ST, inline = "c")
color  BEAR        = input.color(#4A4A4A, "Bearish", group = G_ST, inline = "c", tooltip = "The Day zone below the 18:00 open takes Bullish (discount), the one above it takes Bearish (premium).")
bool   show10Y     = input.bool(true, "10Y yield", group = G_DAY, tooltip = "The US 10-year yield (TVC:US10Y) and its change since its previous daily close, in basis points.")
 
// == STATISTICS (generated) ==
// Five years of 1-minute bars, about 1279 trading days per market. Rows: Nasdaq, S&P, gold.
// -1 = did not pass the filter (both halves outside 45-55%, 30+ cases each) and is never shown.
//@function Level reached by 11:30, %, by level (ONH, ONL, PDH, PDL, PWH, PWL, Midnight, 8:30, Wk open, ORG close, ORG CE) x distance bin (<=.05 .05-.10 .10-.20 .20-.35 .35-.50 >.50 x ADR)
//@param s (int) Statistics set: 0 Nasdaq, 1 S&P, 2 gold
//@returns (array) One row per statistics set
f_lvOdds(int s) =>
    switch s
        0 => array.from(93, 78, 62, 43, 28, 12, 90, 79, 64, 40, 32, 16, -1, -1, -1, 40, 17, 3, -1, -1, -1, -1, 18, 6, -1, -1, -1, -1, 22, 1, -1, -1, -1, -1, -1, 2, 93, 74, 63, -1, 31, 13, 93, 78, 69, -1, -1, -1, 89, 75, 68, -1, 25, 4, 92, 83, 61, -1, 29, 10, 95, 81, 68, -1, -1, -1)
        1 => array.from(91, 78, 61, 40, 24, 10, -1, 75, -1, 39, 25, 10, -1, -1, -1, 32, 19, 4, -1, -1, 65, 30, 21, 6, -1, -1, -1, -1, 12, 1, -1, -1, -1, -1, -1, 2, 93, 83, -1, 42, 23, 12, 93, 86, 66, 56, -1, -1, 92, 84, 60, -1, 22, 4, 95, 81, 67, -1, 26, 12, 95, 86, 65, -1, -1, -1)
        => array.from(91, 83, -1, 31, 14, 5, -1, 77, 58, 34, 10, 6, -1, -1, 57, 34, 10, 4, -1, -1, -1, 35, 17, 3, -1, -1, -1, 28, 18, 1, -1, -1, -1, -1, -1, 1, 89, 71, 56, 30, 16, 6, 94, 80, -1, -1, -1, -1, 91, 78, -1, 29, 16, 3, 96, 76, -1, 31, 17, 6, 92, 74, -1, 32, 22, 17)
//@function Event rates, %: or15_fail_far, or15_held_far, or30_fail_far, or30_held_far, or15_ext_retest, amhold_a, amhold_b, amhold_c, prof_above, prof_below, mon_up, mon_dn, in13_hi, in13_lo, ce_small, ce_normal, ce_large, fill_small, fill_normal, fill_large
//@param s (int) Statistics set: 0 Nasdaq, 1 S&P, 2 gold
//@returns (array) One row per statistics set
f_evOdds(int s) =>
    switch s
        0 => array.from(74, 27, 59, 7, 25, 88, 84, 71, 13, 11, 41, 29, 64, 71, 95, 77, -1, 87, -1, 18)
        1 => array.from(78, 33, 64, 9, 29, 86, 84, 71, 10, 8, 38, 33, 63, 68, 95, 77, 44, 88, -1, 18)
        => array.from(81, 33, 65, 10, 42, 88, 88, 78, 7, 6, -1, 34, 82, 84, 92, 65, 31, 86, 41, 9)
//@function Cases behind each event rate, same order
//@param s (int) Statistics set: 0 Nasdaq, 1 S&P, 2 gold
//@returns (array) One row per statistics set
f_evN(int s) =>
    switch s
        0 => array.from(239, 1037, 246, 985, 456, 842, 284, 335, 668, 608, 152, 102, 1279, 1279, 292, 537, 405, 292, 537, 405)
        1 => array.from(252, 1022, 307, 937, 534, 729, 268, 335, 696, 578, 159, 96, 1279, 1279, 287, 546, 395, 287, 546, 395)
        => array.from(252, 1015, 293, 907, 573, 707, 279, 311, 691, 579, 131, 124, 1280, 1280, 226, 482, 493, 226, 482, 493)
//@function Overnight range cuts x2, 9:30-10:00 median x3, 9:30-11:30 median x3, day high p90, day low p90 (all x ADR, from the 18:00 open)
//@param s (int) Statistics set: 0 Nasdaq, 1 S&P, 2 gold
//@returns (array) One row per statistics set
f_shape(int s) =>
    switch s
        0 => array.from(0.427, 0.621, 0.272, 0.342, 0.401, 0.437, 0.559, 0.626, 1.037, 1.183)
        1 => array.from(0.432, 0.636, 0.211, 0.287, 0.359, 0.377, 0.510, 0.596, 1.031, 1.194)
        => array.from(0.595, 0.842, 0.213, 0.246, 0.295, 0.362, 0.432, 0.499, 1.114, 1.087)
//@function Zone edges x ADR at P50, P75, P90: day high from the 18:00 open x3, day low x3, then 9:30-11:30 high from the 9:30 open by overnight tercile (quiet, normal, big) x9, 9:30-11:30 low x9, then 2:00-5:00 high from the 2:00 open x3, 2:00-5:00 low x3
//@param s (int) Statistics set: 0 Nasdaq, 1 S&P, 2 gold
//@returns (array) One row per statistics set
f_zone(int s) =>
    switch s
        0 => array.from(0.399, 0.720, 1.037, 0.397, 0.721, 1.183, 0.176, 0.323, 0.480, 0.249, 0.441, 0.588, 0.269, 0.441, 0.625, 0.192, 0.348, 0.574, 0.216, 0.402, 0.617, 0.303, 0.506, 0.806, 0.105, 0.178, 0.269, 0.101, 0.192, 0.304)
        1 => array.from(0.405, 0.716, 1.031, 0.387, 0.763, 1.194, 0.159, 0.281, 0.419, 0.227, 0.394, 0.513, 0.255, 0.445, 0.618, 0.149, 0.282, 0.483, 0.223, 0.392, 0.574, 0.268, 0.479, 0.714, 0.104, 0.185, 0.282, 0.104, 0.193, 0.315)
        => array.from(0.417, 0.738, 1.114, 0.376, 0.686, 1.087, 0.155, 0.290, 0.457, 0.175, 0.325, 0.513, 0.217, 0.385, 0.576, 0.155, 0.287, 0.426, 0.209, 0.336, 0.525, 0.224, 0.399, 0.631, 0.131, 0.238, 0.359, 0.121, 0.233, 0.349)
// == END GENERATED ==
 
// == TYPES ===================================================================
 
//@type One level drawn on the right-hand runway with its odds
type Lvl
    string name
    float  price
    int    odds
    bool   isHold = false
    bool   done   = false
    string tip
    line   ln
    label  lb
 
//@type One side of a London or AM zone, its names written inside its two band boxes
type ZTxt
    box   inner
    box   outer
    label far
    int   sgn
    float y50
    float y75
    float y90
    bool  h50 = false
    bool  h75 = false
    bool  h90 = false
 
// == HELPERS =================================================================
 
//@function Resolves the line-style input
//@param s (string) One of "Solid", "Dashed", "Dotted"
//@returns (string) Matching line.style_* constant
resolveStyle(string s) => switch s
    "Solid"  => line.style_solid
    "Dashed" => line.style_dashed
    =>          line.style_dotted
 
//@function Resolves the table-position input
//@param s (string) Position name
//@returns (string) Matching position.* constant
resolvePos(string s) => switch s
    "Bottom right" => position.bottom_right
    "Top left"     => position.top_left
    "Bottom left"  => position.bottom_left
    =>                position.top_right
 
//@function Zero-pads a clock component to two digits
//@param v (int) Hour or minute
//@returns (string) Two-character string
pad2(int v) => (v < 10 ? "0" : "") + str.tostring(v)
 
//@function Tests whether a New York wall-clock time falls inside the current bar's span
//@param h (int) Hour, 0-23
//@param m (int) Minute, 0-59
//@returns (bool) True on the one bar containing that time
isTimeInBar(int h, int m) =>
    int target  = h * 60 + m
    int barOpen = hour(time, TZ) * 60 + minute(time, TZ)
    barOpen <= target and barOpen + barMinutes > target
 
//@function Distance bin used by the level table, matching the statistics
//@param d (float) Distance from the 9:30 open in average daily ranges
//@returns (int) 0 to 5
distBin(float d) =>
    d <= 0.05 ? 0 : d <= 0.10 ? 1 : d <= 0.20 ? 2 : d <= 0.35 ? 3 : d <= 0.50 ? 4 : 5
 
//@function Formats a price to the instrument's tick
//@param p (float) Price
//@returns (string) Price text
fmtPx(float p) => str.tostring(p, format.mintick)
 
//@function Formats a size in points, rounded to whole points above 50
//@param x (float) Points
//@returns (string) Points text
fmtPts(float x) => x >= 50 ? str.tostring(math.round(x)) : str.tostring(x, "#.##")
 
// == INSTRUMENT ==============================================================
 
//@variable Statistics set read off the chart's root symbol: 0 Nasdaq, 1 S&P, 2 gold, -1 none
int autoS = syminfo.root == "MNQ" or syminfo.root == "NQ" ? 0 : syminfo.root == "MES" or syminfo.root == "ES" ? 1 : syminfo.root == "MGC" or syminfo.root == "GC" ? 2 : -1
//@variable Statistics set in use
int S = statsSet == "Nasdaq" ? 0 : statsSet == "S&P" ? 1 : statsSet == "Gold" ? 2 : autoS
//@variable True when this chart has a statistics set
bool supported = S >= 0
//@variable True on a chart the day zones can run on: intraday, 4 hours or lower
bool dayTf = timeframe.isintraday and timeframe.in_seconds() <= 14400
//@variable True when a bar opens at 2:00 and ends at 5:00: London zones
bool ldnTf = timeframe.isminutes and barMinutes <= 60 and 60 % barMinutes == 0
//@variable True when a bar opens at 9:30 and ends at 11:30: AM zones, level odds, the 30-minute range
bool amTf = timeframe.isminutes and barMinutes <= 30 and 30 % barMinutes == 0
//@variable True when bars end on 9:45 and 16:15: the 15-minute range, AM holds and the gap grade
bool orTf = timeframe.isminutes and barMinutes <= 15 and 15 % barMinutes == 0
 
var array<int>   LVO = f_lvOdds(math.max(S, 0))
var array<int>   EVO = f_evOdds(math.max(S, 0))
var array<int>   EVN = f_evN(math.max(S, 0))
var array<float> SHP = f_shape(math.max(S, 0))
var array<float> ZN  = f_zone(math.max(S, 0))
 
//@variable Average of the last ten completed daily ranges, the unit every distance is measured in
float adrD = request.security(syminfo.tickerid, "D", ta.sma(high - low, ADR_DAYS)[1], lookahead = barmerge.lookahead_on)
 
int    LBL_SZ  = labelSizeIn
string LN_STY  = resolveStyle(lineStyleIn)
bool   CAP_LEFT = capSideIn == "Left"
 
//@variable Day zone above the open: premium
color Z_UP = BEAR
//@variable Day zone below the open: discount
color Z_DN = BULL
//@variable Neutral grey for the London and AM zones
const color Z_GREY = #787B86
 
// == CLOCK ===================================================================
 
//@variable Minute-of-day the bar opened, New York time
int nyMin = hour(time, TZ) * 60 + minute(time, TZ)
//@variable Minute-of-day the bar closes, New York time
int barEnd = nyMin + barMinutes
//@variable True on the first bar of a new 18:00-17:00 trading day. Evaluated every bar so its history stays whole.
bool newDay = ta.change(time_tradingday) != 0
//@variable Day of the week the trading day is named for
int tdDow = dayofweek(time_tradingday, "UTC")
//@variable True while the bar belongs to the cash session
bool inCash = nyMin >= CASH_OPEN and nyMin < CASH_CLOSE
 
// == STATE ===================================================================
 
var float dH = na
var float dL = na
var float open18 = na
var float pdH = na
var float pdL = na
var float wH = na
var float wL = na
var float pwH = na
var float pwL = na
var float wkOpen = na
var int   lastDow = 0
var float onH = na
var float onL = na
var float midOpen = na
var float o830 = na
var float o930 = na
var float cashClose = na
var int   cashCloseT = 0
var float orgC = na
var float adr = na
 
var int   monDir = 0
var float monH = na
var float monL = na
 
var float or15H = na
var float or15L = na
var float or30H = na
var float or30L = na
var int   brk15 = 0
var int   brk30 = 0
var bool  fail15 = false
var bool  fail30 = false
var bool  far15 = false
var bool  far30 = false
var bool  ext15 = false
var string orTxt = ""
var string orTip = ""
 
var float amH = na
var float amL = na
var int   amHt = 0
var int   amLt = 0
// The whole 9:30-11:30 run and the 2:00-5:00 run, for the range-used rows.
var float amRunH = na
var float amRunL = na
var float o200 = na
var float ldnH = na
var float ldnL = na
 
// Bar time of the candle that printed each level, so every line starts on it.
var int dHt = 0
var int dLt = 0
var int pdHt = 0
var int pdLt = 0
var int wHt = 0
var int wLt = 0
var int pwHt = 0
var int pwLt = 0
var int onHt = 0
var int onLt = 0
var int midT = 0
var int o830T = 0
var int wkOpenT = 0
var int o930T = 0
var int orgCT = 0
var int or15Ht = 0
var int or15Lt = 0
var int amHT = 0
var int amLT = 0
 
var string gapTxt = ""
var string gapTip = ""
var string profTxt = ""
var string profTip = ""
var string expTxt = ""
var int    amTq = 1
 
var array<Lvl> lvls = array.new<Lvl>(0)
 
// Zone drawings, oldest first, and the 18:00 start of each trading day still kept.
var array<box>   zBoxes = array.new<box>(0)
var array<int>   zDays = array.new<int>(0)
var array<color> zCols = array.new<color>(0)
// Every zone label, oldest first, and the live day's and live morning's labels.
var array<label> zLbls = array.new<label>(0)
var array<label> dayCaps = array.new<label>(0)
// The live morning's and London's sides, whose names sit inside their boxes.
var array<ZTxt>  amZ = array.new<ZTxt>(0)
var array<ZTxt>  ldnZ = array.new<ZTxt>(0)
var int dayCapEnd = 0
 
bool evFail  = false
bool evReach = false
 
// == ZONES ===================================================================
 
//@function Label style that sets a name just off its line, never across it
//@param up       (bool) True sits the name above the line, false below it
//@param leftward (bool) True runs the text left of its anchor, false right of it
//@returns (string) A label.style_* constant
offLine(bool up, bool leftward) =>
    up ? (leftward ? label.style_label_lower_right : label.style_label_lower_left) : (leftward ? label.style_label_upper_right : label.style_label_upper_left)
 
//@function One zone edge's name, just off its own line at the zone's end
//@param caps (array<label>) Live store the label also joins
//@param x0   (int)    Bar time the zone starts
//@param x1   (int)    Bar time the zone ends
//@param y    (float)  Edge price
//@param up   (bool)   True sits the name above the line
//@param px   (bool)   True prints the price after the name; false keeps it to the tooltip
//@param txt  (string) Name
//@param tip  (string) Tooltip
//@returns (bool) Always true
edgeLabel(array<label> caps, int x0, int x1, float y, bool up, bool px, string txt, string tip) =>
    string shown = txt + (showTicks ? " ×" : "")
    label lb = label.new(CAP_LEFT ? x0 : x1, y, px ? shown + " " + fmtPx(y) : shown, xloc = xloc.bar_time, style = offLine(up, true), color = color.new(#FFFFFF, 100), textcolor = INK, size = LBL_SZ, textalign = text.align_right, tooltip = txt + " " + fmtPx(y) + ". " + tip)
    label.set_text_font_family(lb, font.family_monospace)
    zLbls.push(lb)
    caps.push(lb)
    true
 
//@function The tick or cross after a name
//@param hit (bool) True once price traded to the edge
//@returns (string) " ✓", " ×", or nothing with ticks off
tickMark(bool hit) => showTicks ? (hit ? " ✓" : " ×") : ""
 
//@function Writes a London or AM side's names inside its two band boxes
//@param z   (ZTxt)   The side
//@param tag (string) Prefix for the names
//@returns (bool) Always true
zText(ZTxt z, string tag) =>
    box.set_text(z.inner, tag + "1/2" + tickMark(z.h50))
    box.set_text(z.outer, tag + "1/4" + tickMark(z.h75))
    label.set_text(z.far, tag + "1/10" + tickMark(z.h90))
    true
 
//@function Draws one side of a zone from its open: P50-P75 inner band, P75-P90 outer band, each edge named.
//          Day zones name each edge with a label off its line at the zone's end. The narrow London and
//          AM zones name each edge in the middle of the zone, on the side of its line away from the open:
//          1/2 and 1/4 inside the band each one opens, 1/10 just past the zone.
//@param caps (array<label>) Live store for the Day edge names
//@param zs   (array<ZTxt>)  Live store for a London or AM side
//@param base (float)  The open the distances are measured from
//@param sgn  (int)    +1 above the open, -1 below
//@param d50  (float)  Median distance, x ADR
//@param d75  (float)  75th percentile distance, x ADR
//@param d90  (float)  90th percentile distance, x ADR
//@param x0   (int)    Bar time the zone starts
//@param x1   (int)    Bar time the zone ends
//@param tag  (string) Prefix for the edge names
//@param col  (color)  Zone colour
//@param tip  (string) Tooltip
//@returns (bool) Always true
zoneSide(array<label> caps, array<ZTxt> zs, float base, int sgn, float d50, float d75, float d90, int x0, int x1, string tag, color col, string tip) =>
    float y50 = base + sgn * d50 * adr
    float y75 = base + sgn * d75 * adr
    float y90 = base + sgn * d90 * adr
    // Fill only, the border the same as the fill. The day's colours are kept light; the morning's grey is a
    // shade darker so the smaller zone reads first.
    bool  grey = col == Z_GREY
    color fIn  = color.new(col, grey ? 80 : 86)
    color fOut = color.new(col, grey ? 88 : 92)
    // Each name sits against the line it names, inside the band that line opens.
    string vAl = sgn > 0 ? text.align_bottom : text.align_top
    box bIn = box.new(x0, math.max(y50, y75), x1, math.min(y50, y75), xloc = xloc.bar_time, border_color = fIn, border_width = 1, bgcolor = fIn, text_size = LBL_SZ, text_color = INK, text_halign = text.align_center, text_valign = vAl, text_font_family = font.family_monospace)
    zBoxes.push(bIn)
    zCols.push(col)
    box bOut = box.new(x0, math.max(y75, y90), x1, math.min(y75, y90), xloc = xloc.bar_time, border_color = fOut, border_width = 1, bgcolor = fOut, text_size = LBL_SZ, text_color = INK, text_halign = text.align_center, text_valign = vAl, text_font_family = font.family_monospace)
    zBoxes.push(bOut)
    zCols.push(col)
    if grey
        label far = label.new(x0 + (x1 - x0) / 2, y90, "", xloc = xloc.bar_time, style = sgn > 0 ? label.style_label_down : label.style_label_up, color = color.new(#FFFFFF, 100), textcolor = INK, size = LBL_SZ, textalign = text.align_center)
        label.set_text_font_family(far, font.family_monospace)
        zLbls.push(far)
        ZTxt z = ZTxt.new(inner = bIn, outer = bOut, far = far, sgn = sgn, y50 = y50, y75 = y75, y90 = y90)
        zText(z, tag)
        zs.push(z)
    else
        // Above the open every name sits just over its line, below the open just under it,
        // so each one reads inside the band it opens and none is struck through.
        edgeLabel(caps, x0, x1, y50, sgn > 0, true, tag + "1/2", tip)
        edgeLabel(caps, x0, x1, y75, sgn > 0, true, tag + "1/4", tip)
        edgeLabel(caps, x0, x1, y90, sgn > 0, true, tag + "1/10", tip)
    true
 
//@function Parks a finished zone's names just inside its right edge, clear of the next zone, and empties the store
//@param caps (array<label>) Live label store
//@param xEnd (int) Bar time the zone ends
//@returns (bool) Always true
parkCaps(array<label> caps, int xEnd) =>
    if not CAP_LEFT and caps.size() > 0
        // The store holds the side above the open first, then the side below it.
        int half = caps.size() / 2
        for i = 0 to caps.size() - 1
            label lb = caps.get(i)
            label.set_x(lb, xEnd)
            label.set_style(lb, offLine(i < half, true))
            label.set_textalign(lb, text.align_right)
    caps.clear()
    true
 
//@function Lightens the previous day's zone fills, keeps its names in full ink, and deletes days past the setting
//@param dayStart (int) Bar time of the new trading day's first bar
//@returns (bool) Always true
rollZones(int dayStart) =>
    if zBoxes.size() > 0
        for i = 0 to zBoxes.size() - 1
            box b = zBoxes.get(i)
            color c = zCols.get(i)
            color f = color.new(c, i % 2 == 0 ? 90 : 95)
            box.set_bgcolor(b, f)
            box.set_border_color(b, f)
    parkCaps(dayCaps, dayCapEnd)
    amZ.clear()
    ldnZ.clear()
    zDays.push(dayStart)
    while zDays.size() > zoneDays
        zDays.shift()
    int cutoff = zDays.first()
    while zBoxes.size() > 0 and box.get_left(zBoxes.first()) < cutoff
        box.delete(zBoxes.shift())
        zCols.shift()
    while zLbls.size() > 0 and label.get_x(zLbls.first()) < cutoff
        label.delete(zLbls.shift())
    true
 
//@function Swaps the cross on each live edge name for a tick once this bar trades to the edge
//@param caps (array<label>) Live label store
//@param base (float) The open the zone is measured from
//@returns (bool) Always true
markHits(array<label> caps, float base) =>
    if showTicks and caps.size() > 0
        for lb in caps
            float y = label.get_y(lb)
            if (y > base ? high >= y : low <= y)
                string t = label.get_text(lb)
                if str.contains(t, "×")
                    label.set_text(lb, str.replace(t, "×", "✓"))
    true
 
//@function Swaps the cross for a tick on each live London or AM edge this bar trades to
//@param zs  (array<ZTxt>) Live sides
//@param tag (string) Prefix for the names
//@returns (bool) Always true
markZones(array<ZTxt> zs, string tag) =>
    if showTicks and zs.size() > 0
        for z in zs
            bool was = z.h50 and z.h75 and z.h90
            z.h50 := z.h50 or (z.sgn > 0 ? high >= z.y50 : low <= z.y50)
            z.h75 := z.h75 or (z.sgn > 0 ? high >= z.y75 : low <= z.y75)
            z.h90 := z.h90 or (z.sgn > 0 ? high >= z.y90 : low <= z.y90)
            if not was
                zText(z, tag)
    true
 
//@function How far a run from the open has gone against the zone edges
//@param run (float) Points run so far
//@param d50 (float) 1 in 2 edge, x ADR
//@param d75 (float) 1 in 4 edge, x ADR
//@param d90 (float) 1 in 10 edge, x ADR
//@returns (string) "inside 1/2", or the furthest edge passed
usedTxt(float run, float d50, float d75, float d90) =>
    run >= d90 * adr ? "past 1/10" : run >= d75 * adr ? "past 1/4" : run >= d50 * adr ? "past 1/2" : "inside 1/2"
 
//@function One range-used row's worked figures, for its tooltip
//@param side (string) "high" or "low"
//@param run  (float)  Points run so far
//@param d50  (float)  1 in 2 edge, x ADR
//@returns (string) Points, ADR share and the first edge
usedTip(string side, float run, float d50) =>
    side + " ran " + fmtPts(run) + " pts / " + fmtPts(adr) + " ADR = " + str.tostring(run / adr, "#.###") + " (the 1 in 2 edge is " + str.tostring(d50, "#.###") + " = " + fmtPts(d50 * adr) + " pts)"
 
// == LEVEL BOOK ==============================================================
 
//@function Draws one level from the candle that printed it to the runway. Where a live level of the
//          same kind already sits within a few points, only the one with the higher odds is drawn.
//@param name   (string) Level name
//@param price  (float)  Level price
//@param odds   (int)    Odds in percent
//@param isHold (bool)   True for a high or low that is expected to stand, false for a level expected to trade
//@param x1     (int)    Bar time of the candle that printed the price
//@param tip    (string) Tooltip text
//@returns (bool) Always true
addLevel(string name, float price, int odds, bool isHold, int x1, string tip) =>
    bool keepNew = true
    if lvls.size() > 0
        for i = lvls.size() - 1 to 0
            Lvl e = lvls.get(i)
            if keepNew and not e.done and e.isHold == isHold and math.abs(e.price - price) <= CLASH * adr
                if e.odds >= odds
                    keepNew := false
                else
                    line.delete(e.ln)
                    label.delete(e.lb)
                    lvls.remove(i)
    if keepNew
        int x2 = time + rightOffset * msPerBar
        line ln = line.new(x1, price, x2, price, xloc = xloc.bar_time, color = INK, width = 1, style = LN_STY)
        label lb = label.new(x2, price, name + "  " + str.tostring(odds) + "%", xloc = xloc.bar_time, style = label.style_label_left, color = color.new(#FFFFFF, 100), textcolor = INK, size = LBL_SZ, textalign = text.align_left, tooltip = tip)
        label.set_text_font_family(lb, font.family_monospace)
        lvls.push(Lvl.new(name = name, price = price, odds = odds, isHold = isHold, tip = tip, ln = ln, lb = lb))
    true
 
//@function Deletes every level on the book
//@returns (bool) Always true
clearLevels() =>
    while lvls.size() > 0
        Lvl e = lvls.pop()
        line.delete(e.ln)
        label.delete(e.lb)
    true
 
//@function Grades one candidate level at the cash open and draws it when its odds pass the setting
//@param k     (int)    Level index in the generated table
//@param name  (string) Level name
//@param price (float)  Level price
//@param x1    (int)    Bar time of the candle that printed the price
//@returns (bool) Always true
gradeLevel(int k, string name, float price, int x1) =>
    if not na(price) and price != o930
        float d = math.abs(price - o930) / adr
        int b = distBin(d)
        int odds = LVO.get(k * 6 + b)
        if odds >= minOdds
            string band = b == 0 ? "within 0.05" : b == 1 ? "0.05-0.10" : b == 2 ? "0.10-0.20" : b == 3 ? "0.20-0.35" : b == 4 ? "0.35-0.50" : "beyond 0.50"
            addLevel(name, price, odds, false, x1, name + " " + fmtPx(price) + ": traded by 11:30 on " + str.tostring(odds) + "% of days with it " + band + " x ADR from the 9:30 open (" + fmtPts(math.abs(price - o930)) + " pts / " + fmtPts(adr) + " ADR = " + str.tostring(d, "#.###") + "). Five years of 1-minute data.")
    true
 
// == DETECTION (confirmed bars only) =========================================
 
if barstate.isconfirmed and supported and dayTf
 
    // ---- THE TRADING DAY, ITS RANGE AND THE WEEK -------------------------------
    float priorCash = cashClose
    int   priorCashT = cashCloseT
    if inCash
        cashClose  := close
        cashCloseT := time
 
    if newDay
        if not na(dH)
            pdH := dH
            pdL := dL
            pdHt := dHt
            pdLt := dLt
            if lastDow == dayofweek.monday
                monDir := close[1] > open18 ? 1 : -1
                monH := dH
                monL := dL
        bool newWeek = tdDow <= lastDow
        if newWeek
            pwH := wH
            pwL := wL
            pwHt := wHt
            pwLt := wLt
            wH := high
            wL := low
            wHt := time
            wLt := time
            wkOpen := open
            wkOpenT := time
            monDir := 0
        else
            if na(wH) or high > wH
                wH := high
                wHt := time
            if na(wL) or low < wL
                wL := low
                wLt := time
        lastDow := tdDow
        adr := adrD
        open18 := open
        dH := high
        dL := low
        dHt := time
        dLt := time
        onH := high
        onL := low
        onHt := time
        onLt := time
        midOpen := na
        o830 := na
        o930 := na
        o200 := na
        orTxt := ""
        gapTxt := ""
        profTxt := ""
        expTxt := ""
        clearLevels()
        rollZones(time)
        // The day's zones, fixed at the 18:00 open for the whole trading day.
        if showDayZ and not na(adr)
            int dayEndT = timestamp(TZ, year(time_tradingday, "UTC"), month(time_tradingday, "UTC"), dayofmonth(time_tradingday, "UTC"), 17, 0)
            string tipZ = " from the 18:00 open " + fmtPx(open18) + ", in shares of the " + fmtPts(adr) + " pt average daily range. Each name says how often a day ran past its line: 1/2 = 1 in 2, 1/4 = 1 in 4, 1/10 = 1 in 10. Five years of 1-minute data."
            dayCapEnd := dayEndT
            zoneSide(dayCaps, na, open18, 1, ZN.get(0), ZN.get(1), ZN.get(2), time, dayEndT, "Day ", Z_UP, "How far the trading day's high ran above" + tipZ)
            zoneSide(dayCaps, na, open18, -1, ZN.get(3), ZN.get(4), ZN.get(5), time, dayEndT, "Day ", Z_DN, "How far the trading day's low ran below" + tipZ)
    else
        if high > dH
            dH := high
            dHt := time
        if low < dL
            dL := low
            dLt := time
        if na(wH) or high > wH
            wH := high
            wHt := time
        if na(wL) or low < wL
            wL := low
            wLt := time
        if nyMin >= 1080 or nyMin < CASH_OPEN
            if na(onH) or high > onH
                onH := high
                onHt := time
            if na(onL) or low < onL
                onL := low
                onLt := time
 
    if amTf and isTimeInBar(0, 0)
        midOpen := open
        midT := time
    if amTf and isTimeInBar(8, 30)
        o830 := open
        o830T := time
 
    // ---- LONDON, 2:00 TO 5:00 --------------------------------------------------
    if ldnTf and isTimeInBar(2, 0) and not na(adr)
        o200 := open
        ldnH := high
        ldnL := low
        if showLdnZ
            int ldnEndT = timestamp(TZ, year(time, TZ), month(time, TZ), dayofmonth(time, TZ), 5, 0)
            string tipL = " from the 2:00 open " + fmtPx(o200) + " by 5:00, in shares of the " + fmtPts(adr) + " pt average daily range. Each name says how often London ran past its line: 1/2 = 1 in 2, 1/4 = 1 in 4, 1/10 = 1 in 10. Five years of 1-minute data."
            zoneSide(na, ldnZ, o200, 1, ZN.get(24), ZN.get(25), ZN.get(26), time, ldnEndT, "LDN ", Z_GREY, "How far London's high ran above" + tipL)
            zoneSide(na, ldnZ, o200, -1, ZN.get(27), ZN.get(28), ZN.get(29), time, ldnEndT, "LDN ", Z_GREY, "How far London's low ran below" + tipL)
    else if ldnTf and not na(o200) and nyMin > 120 and nyMin < 300
        ldnH := math.max(ldnH, high)
        ldnL := math.min(ldnL, low)
 
    // ---- THE CASH OPEN ---------------------------------------------------------
    if amTf and isTimeInBar(9, 30) and not na(adr)
        o930 := open
        o930T := time
        orgC := not na(priorCash) and time - priorCashT <= 4 * 86400000 ? priorCash : na
        orgCT := priorCashT
        or15Ht := time
        or15Lt := time
        amHT := time
        amLT := time
        or15H := high
        or15L := low
        or30H := high
        or30L := low
        brk15 := 0
        brk30 := 0
        fail15 := false
        fail30 := false
        far15 := false
        far30 := false
        ext15 := false
        amH := high
        amL := low
        amHt := nyMin
        amLt := nyMin
        amRunH := high
        amRunL := low
        if showLv
            if lvOn and onH > o930
                gradeLevel(0, "ONH", onH, onHt)
            if lvOn and onL < o930
                gradeLevel(1, "ONL", onL, onLt)
            if lvPd and pdH > o930
                gradeLevel(2, "PDH", pdH, pdHt)
            if lvPd and pdL < o930
                gradeLevel(3, "PDL", pdL, pdLt)
            if lvPw and pwH > o930
                gradeLevel(4, "PWH", pwH, pwHt)
            if lvPw and pwL < o930
                gradeLevel(5, "PWL", pwL, pwLt)
            if lvMid
                gradeLevel(6, "Midnight", midOpen, midT)
            if lv830
                gradeLevel(7, "8:30", o830, o830T)
            if lvWk
                gradeLevel(8, "Wk open", wkOpen, wkOpenT)
        // Gap grade against the average daily range.
        if orTf and not na(orgC) and orgC != o930
            float g = math.abs(o930 - orgC) / adr
            int grade = g <= 0.10 ? 0 : g >= 0.35 ? 2 : 1
            string gName = grade == 0 ? "small" : grade == 2 ? "large" : "normal"
            int ce = EVO.get(14 + grade)
            int fillOdds = EVO.get(17 + grade)
            gapTxt := gName + " " + fmtPts(math.abs(o930 - orgC)) + " pts" + (ce >= 0 ? " · CE " + str.tostring(ce) + "%" : "") + (fillOdds >= 0 ? " · fill " + str.tostring(fillOdds) + "%" : "")
            gapTip := "Gap " + fmtPts(math.abs(o930 - orgC)) + " pts / " + fmtPts(adr) + " ADR = " + str.tostring(g, "#.###") + ": " + gName + " (small up to 0.10, large from 0.35). Odds the CE and the full gap trade by 11:30, from " + str.tostring(EVN.get(14 + grade)) + " " + gName + " gaps. A rate missing here read 45-55% and is left out."
            // The gap's own levels carry the grade's odds, so the chart and the table
            // never give one price two different numbers.
            if showLv and lvOrg
                if ce >= minOdds
                    addLevel("ORG CE", (orgC + o930) / 2.0, ce, false, o930T, "CE of the " + gName + " RTH ORG gap: traded by 11:30 on " + str.tostring(ce) + "% of " + str.tostring(EVN.get(14 + grade)) + " " + gName + " gaps.")
                if fillOdds >= minOdds
                    addLevel("ORG close", orgC, fillOdds, false, orgCT, "Full fill of the " + gName + " RTH ORG gap: traded by 11:30 on " + str.tostring(fillOdds) + "% of " + str.tostring(EVN.get(17 + grade)) + " " + gName + " gaps.")
        // Midnight-open profile.
        if not na(midOpen) and o930 != midOpen
            bool above = o930 > midOpen
            int p = EVO.get(above ? 8 : 9)
            if p >= 0
                profTxt := (above ? "above 12am · AM sets the day low " : "below 12am · AM sets the day high ") + str.tostring(p) + "%"
                profTip := "9:30 opened " + (above ? "above" : "below") + " the midnight open. On " + str.tostring(p) + "% of " + str.tostring(EVN.get(above ? 8 : 9)) + " such days the 9:30-11:30 window set the trading day's " + (above ? "low" : "high") + "."
        // Typical morning range by the size of the overnight range.
        float onN = (onH - onL) / adr
        int tq = onN < SHP.get(0) ? 0 : onN > SHP.get(1) ? 2 : 1
        amTq := tq
        expTxt := "10:00 ~" + fmtPts(SHP.get(2 + tq) * adr) + " · 11:30 ~" + fmtPts(SHP.get(5 + tq) * adr) + " pts (" + (tq == 0 ? "quiet" : tq == 2 ? "big" : "normal") + " overnight)"
        // The morning's zones, picked by the size of the overnight range.
        if showAmZ
            int amEndT = timestamp(TZ, year(time, TZ), month(time, TZ), dayofmonth(time, TZ), 11, 30)
            string onName = tq == 0 ? "quiet" : tq == 2 ? "big" : "normal"
            string tipA = " from the 9:30 open " + fmtPx(o930) + " by 11:30, on days with a " + onName + " overnight range, in shares of the " + fmtPts(adr) + " pt average daily range. Each name says how often a morning ran past its line: 1/2 = 1 in 2, 1/4 = 1 in 4, 1/10 = 1 in 10."
            zoneSide(na, amZ, o930, 1, ZN.get(6 + tq * 3), ZN.get(7 + tq * 3), ZN.get(8 + tq * 3), time, amEndT, "AM ", Z_GREY, "How far the morning's high ran above" + tipA)
            zoneSide(na, amZ, o930, -1, ZN.get(15 + tq * 3), ZN.get(16 + tq * 3), ZN.get(17 + tq * 3), time, amEndT, "AM ", Z_GREY, "How far the morning's low ran below" + tipA)
 
    // ---- THE MORNING -----------------------------------------------------------
    if amTf and not na(o930) and nyMin > CASH_OPEN and nyMin < AM_END
        amRunH := math.max(amRunH, high)
        amRunL := math.min(amRunL, low)
        if orTf and nyMin < 585
            if high > or15H
                or15H := high
                or15Ht := time
            if low < or15L
                or15L := low
                or15Lt := time
        if nyMin < 600
            or30H := math.max(or30H, high)
            or30L := math.min(or30L, low)
        if nyMin < 630
            if high > amH
                amH := high
                amHt := nyMin
                amHT := time
            if low < amL
                amL := low
                amLt := nyMin
                amLT := time
 
    if orTf and not na(o930) and nyMin >= 585 and nyMin < AM_END
        float mid15 = (or15H + or15L) / 2.0
        float w15 = or15H - or15L
        // First break of the 9:30-9:45 range. A bar through both sides voids the read.
        if brk15 == 0
            bool up = high > or15H
            bool dn = low < or15L
            brk15 := up and dn ? 9 : up ? 1 : dn ? -1 : 0
        if math.abs(brk15) == 1
            if brk15 == 1 ? low < or15L : high > or15H
                far15 := true
            if not fail15 and barEnd <= 600 and (brk15 == 1 ? close < mid15 : close > mid15)
                fail15 := true
                evFail := true
                int p = EVO.get(0)
                float farLv = brk15 == 1 ? or15L : or15H
                if p >= 0
                    orTxt := "15m break failed · far side " + fmtPx(farLv) + " " + str.tostring(p) + "%"
                    orTip := "The first break of the 9:30-9:45 range closed back past its middle before 10:00. The far side then traded by 11:30 on " + str.tostring(p) + "% of " + str.tostring(EVN.get(0)) + " such days."
                    if showFar and not far15
                        addLevel("OR far side", farLv, p, false, brk15 == 1 ? or15Lt : or15Ht, orTip)
            if not fail15 and barEnd == 600 and not far15 and EVO.get(1) >= 0
                orTxt := "15m break held to 10:00 · far side " + str.tostring(EVO.get(1)) + "%"
                orTip := "The 9:30-9:45 break never closed back past the middle by 10:00. The far side traded by 11:30 on only " + str.tostring(EVO.get(1)) + "% of " + str.tostring(EVN.get(1)) + " such days."
            if not ext15 and (brk15 == 1 ? high >= or15H + w15 : low <= or15L - w15)
                ext15 := true
                if EVO.get(4) >= 0
                    orTxt := "15m range ran 1x · back to its edge " + str.tostring(EVO.get(4)) + "%"
                    orTip := "Price ran one full 9:30-9:45 width past the break. It came back to the broken edge by 11:30 on only " + str.tostring(EVO.get(4)) + "% of " + str.tostring(EVN.get(4)) + " such days."
    if amTf and not na(o930) and nyMin >= 600 and nyMin < AM_END
        float mid30 = (or30H + or30L) / 2.0
        if brk30 == 0
            bool up = high > or30H
            bool dn = low < or30L
            brk30 := up and dn ? 9 : up ? 1 : dn ? -1 : 0
        if math.abs(brk30) == 1
            if brk30 == 1 ? low < or30L : high > or30H
                far30 := true
            if not fail30 and barEnd <= 630 and (brk30 == 1 ? close < mid30 : close > mid30)
                fail30 := true
                if EVO.get(2) >= 0
                    orTxt := "30m break failed · far side " + fmtPx(brk30 == 1 ? or30L : or30H) + " " + str.tostring(EVO.get(2)) + "%"
                    orTip := "The first break of the 9:30-10:00 range closed back past its middle before 10:30. The far side then traded by 11:30 on " + str.tostring(EVO.get(2)) + "% of " + str.tostring(EVN.get(2)) + " such days."
            if not fail30 and barEnd == 630 and not far30 and EVO.get(3) >= 0
                orTxt := "30m break held to 10:30 · far side " + str.tostring(EVO.get(3)) + "%"
                orTip := "The 9:30-10:00 break never closed back past the middle by 10:30. The far side traded by 11:30 on only " + str.tostring(EVO.get(3)) + "% of " + str.tostring(EVN.get(3)) + " such days."
 
    // ---- 10:30: AM HIGH AND LOW THAT SHOULD STAND ------------------------------
    if orTf and showHold and not na(o930) and barEnd == 630
        for sd = 0 to 1
            float lv = sd == 0 ? amH : amL
            int setAt = sd == 0 ? amHt : amLt
            // A failed break already names this price as one that should trade; the
            // more specific read wins and no second, opposite name is drawn on it.
            bool claimed = false
            if lvls.size() > 0
                for j = 0 to lvls.size() - 1
                    Lvl e = lvls.get(j)
                    if not e.isHold and not e.done and math.abs(e.price - lv) <= CLASH * adr
                        claimed := true
            if not claimed and math.abs(lv - close) / adr > HOLD_GAP
                int k = setAt < 585 ? 0 : setAt < 600 ? 1 : 2
                int p = EVO.get(5 + k)
                if p >= 0
                    string setWhen = k == 0 ? "9:30-9:45" : k == 1 ? "9:45-10:00" : "10:00-10:30"
                    addLevel(sd == 0 ? "AM high holds" : "AM low holds", lv, p, true, sd == 0 ? amHT : amLT, "Set " + setWhen + " and more than 0.15 x ADR from price at 10:30. It stood until 11:30 on " + str.tostring(p) + "% of " + str.tostring(EVN.get(5 + k)) + " such days.")
 
    // ---- LEVELS TRADED, AND 11:30 ----------------------------------------------
    if lvls.size() > 0
        if nyMin >= AM_END or nyMin < CASH_OPEN
            clearLevels()
        else
            for i = lvls.size() - 1 to 0
                Lvl e = lvls.get(i)
                if not e.done
                    bool hit = e.isHold ? (e.price >= o930 ? high > e.price : low < e.price) : high >= e.price and low <= e.price
                    if hit
                        evReach := evReach or not e.isHold
                        if clearHit
                            line.delete(e.ln)
                            label.delete(e.lb)
                            lvls.remove(i)
                        else
                            e.done := true
                            label.set_text(e.lb, e.name + "  " + (e.isHold ? "×" : "✓"))
                            line.set_x2(e.ln, time + rightOffset * msPerBar)
                            label.set_x(e.lb, time + rightOffset * msPerBar)
 
    // ---- ZONE EDGES REACHED, INSIDE EACH ZONE'S OWN WINDOW ---------------------
    if nyMin < 1020 or nyMin >= 1080
        markHits(dayCaps, open18)
    if nyMin >= 120 and nyMin < 300
        markZones(ldnZ, "LDN ")
    if nyMin >= CASH_OPEN and nyMin < AM_END
        markZones(amZ, "AM ")
 
    if nyMin >= 300
        ldnZ.clear()
    if nyMin >= AM_END
        amZ.clear()
        orTxt := ""
        gapTxt := ""
        profTxt := ""
        expTxt := ""
 
// == RIGHT-HAND RUNWAY =======================================================
// Every live level runs from the candle that printed it to a few bars past the
// live candle, its name at the end. A live zone's names start a few bars past the
// live candle and run RIGHT, into the empty space, so no name ever prints over a
// candle. They start at the zone's right edge instead once that edge is nearer.
// A finished zone's names park inside its right edge, running left (parkCaps).
 
//@function Sets a live zone's names on the runway, text running right of the anchor
//@param caps (array<label>) Live label store
//@param x    (int) Bar time the names start at
//@param base (float) The open the zone is measured from
//@returns (bool) Always true
runCaps(array<label> caps, int x, float base) =>
    for lb in caps
        label.set_x(lb, x)
        label.set_style(lb, offLine(label.get_y(lb) > base, false))
        label.set_textalign(lb, text.align_left)
    true
 
if barstate.islast and not CAP_LEFT
    // The level odds names hold the first lane; the Day names get their own lane further right.
    int xRunDay = time + (rightOffset + dayNameStep) * msPerBar
    runCaps(dayCaps, math.min(xRunDay, dayCapEnd), open18)
 
if barstate.islast and lvls.size() > 0
    for i = 0 to lvls.size() - 1
        Lvl e = lvls.get(i)
        if not e.done
            line.set_x2(e.ln, time + rightOffset * msPerBar)
            label.set_x(e.lb, time + rightOffset * msPerBar)
 
// == TABLE ===================================================================
 
// The US 10-year yield, read from its own feed: now, and its previous daily close.
float y10  = request.security("TVC:US10Y", timeframe.period, close, ignore_invalid_symbol = true)
float y10D = request.security("TVC:US10Y", "D", close[1], lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
 
var table dash = na
var int dashRows = na
 
//@variable Ink for the table: the setting, or white on a dark chart background
color TBL_INK = tableInkIn == "White" ? #FFFFFF : tableInkIn == "Black" ? #000000 : INK
 
//@function Writes one name / value row in the house panel look
//@param r   (int)    Row
//@param n   (string) Name
//@param v   (string) Value
//@param tip (string) Tooltip
//@returns (bool) Always true
cellRow(int r, string n, string v, string tip) =>
    table.cell(dash, 0, r, n, text_color = TBL_INK, text_size = phone ? 8 : LBL_SZ, text_halign = text.align_left, text_font_family = font.family_monospace, tooltip = tip)
    table.cell(dash, 1, r, v, text_color = TBL_INK, text_size = phone ? 8 : LBL_SZ, text_halign = text.align_left, text_font_family = font.family_monospace, tooltip = tip)
    true
 
if barstate.islast and showTable
    array<string> names = array.new<string>(0)
    array<string> vals  = array.new<string>(0)
    array<string> tips  = array.new<string>(0)
    string tfTag = barMinutes < 60 ? str.tostring(barMinutes) + "m" : timeframe.period
    if not supported
        names.push("No data")
        vals.push("statistics cover NQ, ES, GC and their micros")
        tips.push("")
    else if not dayTf
        names.push("Timeframe")
        vals.push("use a chart of 4 hours or lower")
        tips.push("Every zone and read here is built inside the trading day.")
    else if na(adr)
        names.push("Warming up")
        vals.push("needs " + str.tostring(ADR_DAYS) + " daily candles")
        tips.push("The average daily range is the last ten daily candles.")
    else
        if not orTf
            names.push("Off on " + tfTag)
            vals.push(amTf ? "15m range and gap grade need 1, 3, 5 or 15m" : ldnTf ? "AM zones and level odds need 30m or lower" : "London and AM zones need 1H or lower")
            tips.push("Day zones run on any chart up to 4 hours. London zones need a bar opening at 2:00 (1H or lower, dividing 60). AM zones, level odds and the 30-minute range need a bar opening at 9:30 (1, 2, 3, 5, 6, 10, 15 or 30m). The 15-minute range, AM holds and the gap grade need bars ending on 9:45 and 16:15 (1, 3, 5 or 15m).")
        // How far each live window has already run against its own zone edges.
        string usedNote = ". 'past 1/4' means only 1 in 4 of the measured windows ran this far or further."
        if showUsed and not na(open18) and (nyMin < 1020 or nyMin >= 1080)
            names.push("Day run")
            vals.push("high " + usedTxt(dH - open18, ZN.get(0), ZN.get(1), ZN.get(2)) + " · low " + usedTxt(open18 - dL, ZN.get(3), ZN.get(4), ZN.get(5)))
            tips.push("From the 18:00 open " + fmtPx(open18) + ": " + usedTip("high", dH - open18, ZN.get(0)) + "; " + usedTip("low", open18 - dL, ZN.get(3)) + usedNote)
        if show10Y and not na(y10)
            float bp = na(y10D) ? na : (y10 - y10D) * 100
            names.push("10Y")
            vals.push(str.tostring(y10, "#.###") + "%" + (na(bp) ? "" : " · " + (bp >= 0 ? "▲ " : "▼ ") + str.tostring(math.abs(bp), "#.#") + " bp on the day"))
            tips.push("US 10-year yield (TVC:US10Y) " + str.tostring(y10, "#.###") + "%" + (na(y10D) ? "." : ", previous daily close " + str.tostring(y10D, "#.###") + "%: " + (bp >= 0 ? "up " : "down ") + str.tostring(math.abs(bp), "#.#") + " basis points."))
        if showUsed and ldnTf and not na(o200) and nyMin >= 120 and nyMin < 300
            names.push("London run")
            vals.push("high " + usedTxt(ldnH - o200, ZN.get(24), ZN.get(25), ZN.get(26)) + " · low " + usedTxt(o200 - ldnL, ZN.get(27), ZN.get(28), ZN.get(29)))
            tips.push("From the 2:00 open " + fmtPx(o200) + ": " + usedTip("high", ldnH - o200, ZN.get(24)) + "; " + usedTip("low", o200 - ldnL, ZN.get(27)) + usedNote)
        if showUsed and amTf and not na(o930) and nyMin >= CASH_OPEN and nyMin < AM_END
            names.push("AM run")
            vals.push("high " + usedTxt(amRunH - o930, ZN.get(6 + amTq * 3), ZN.get(7 + amTq * 3), ZN.get(8 + amTq * 3)) + " · low " + usedTxt(o930 - amRunL, ZN.get(15 + amTq * 3), ZN.get(16 + amTq * 3), ZN.get(17 + amTq * 3)))
            tips.push("From the 9:30 open " + fmtPx(o930) + ": " + usedTip("high", amRunH - o930, ZN.get(6 + amTq * 3)) + "; " + usedTip("low", o930 - amRunL, ZN.get(15 + amTq * 3)) + usedNote)
        if showGap and gapTxt != ""
            names.push("Gap")
            vals.push(gapTxt)
            tips.push(gapTip)
        if showProf and profTxt != ""
            names.push("Profile")
            vals.push(profTxt)
            tips.push(profTip)
        if showExp and expTxt != ""
            names.push("Expect")
            vals.push(expTxt)
            tips.push("Typical (median) 9:30-10:00 and 9:30-11:30 ranges on days with this size of overnight range, scaled by the " + fmtPts(adr) + " pt average daily range. Typical, not a cap.")
        if showOr and orTxt != ""
            names.push("Opening range")
            vals.push(orTxt)
            tips.push(orTip)
        if showWeek and monDir != 0 and tdDow != dayofweek.monday
            bool unbroken = monDir == 1 ? wL >= monL : wH <= monH
            int p = EVO.get(monDir == 1 ? 10 : 11)
            if unbroken and p >= 0
                names.push("Week")
                vals.push(monDir == 1 ? "Mon up · Mon low " + fmtPx(monL) + " is the week low " + str.tostring(p) + "%" : "Mon down · Mon high " + fmtPx(monH) + " is the week high " + str.tostring(p) + "%")
                tips.push("Monday closed " + (monDir == 1 ? "up" : "down") + ". Monday's " + (monDir == 1 ? "low" : "high") + " ended up the week's " + (monDir == 1 ? "low" : "high") + " on " + str.tostring(p) + "% of " + str.tostring(EVN.get(monDir == 1 ? 10 : 11)) + " such weeks. By chance alone any one day is about 1 in 5.")
        if showAft and nyMin >= 780 and nyMin < 1020 and EVO.get(12) >= 0 and EVO.get(13) >= 0
            names.push("After 13:00")
            vals.push("day high in " + str.tostring(EVO.get(12)) + "% · day low in " + str.tostring(EVO.get(13)) + "%")
            tips.push("How often the trading day's high and low were already printed by 13:00, from " + str.tostring(EVN.get(12)) + " days.")
    // Phone: the name and the first three readings only.
    int shown = phone ? math.min(names.size(), 3) : names.size()
    int head  = 1
    int want  = head + shown
    if na(dash) or dashRows != want
        if not na(dash)
            table.delete(dash)
        dash := table.new(resolvePos(tablePosIn), 2, want, frame_color = TBL_INK, frame_width = 1, border_width = 0)
        dashRows := want
    cellRow(0, "Statistical Zones+", tfTag, syminfo.ticker + " on the " + tfTag + " chart.")
    if shown > 0
        for i = 0 to shown - 1
            cellRow(head + i, names.get(i), vals.get(i), tips.get(i))
 
// == ALERTS (script scope) ===================================================
 
alertcondition(evFail,  "Opening range break failed", "M1D: the 9:30-9:45 break failed on {{ticker}} - far side in play")
alertcondition(evReach, "Graded level traded",        "M1D: a graded level traded on {{ticker}} @ {{close}}")

← 返回列表