Albrecht Edge - Sessions

jonathanalbrecht_trader · study · 1032 行 · 点赞 29 · TradingView 原页

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

Pine Script

//@version=6
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jonathanalbrecht_trader
 
indicator("Albrecht Edge - Sessions", shorttitle = "AE Session", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ─── Constants ───────────────────────────────────────────────────────────────
// Exchange time zones as IANA names: daylight saving time is applied automatically.
const string TZ_TK = "Asia/Tokyo"
const string TZ_LN = "Europe/London"
const string TZ_NY = "America/New_York"
const int    HOUR  = 3600000
const int    DAY   = 86400000
// Live statistics: up to 18 elapsed slots per session; extension histogram in 0.03 ATR bins up to 3 ATR
const int    JMAX  = 18
const int    NBIN  = 100
const float  BINW  = 0.03
const float  ZONEQ = 0.8
 
// ─── Inputs ──────────────────────────────────────────────────────────────────
const string G1 = "01 · Sessions"
const string G2 = "02 · Levels"
const string G3 = "03 · Live"
const string G4 = "04 · Dashboard"
const string G5 = "05 · Alerts"
const string G6 = "06 · Style"
 
const string T_AS = "Asia: 09:00-15:00 Tokyo time."
const string T_LN = "London: 08:00 London time until the New York open (08:00 New York time), so the box is complete before New York starts."
const string T_NY = "New York: 08:00-17:00 New York time, or the US cash session 09:30-16:00. The cash window needs 30m or lower; on 1h the 09:00 bar is included."
const string T_CU = "Your own session in any time zone. Windows across midnight are supported. Custom sessions are drawn and measured for range only."
const string T_WK = "Off: sessions starting on a Saturday or Sunday are skipped, on the chart and in the statistics. Only matters for markets that trade on weekends, such as crypto."
const string T_HD = "Number of past days with boxes and levels on the chart. Statistics always use the full chart history."
const string T_LV = "High and low of the most recent finished sessions, extended until price trades beyond them. The number sets how many sessions per market stay on the chart."
const string T_PD = "High (green) and low (red) of the previous trading day on this chart. Extended until price trades beyond them. Highs or lows of the days before stay as well while they are untaken and close to the newest one (within 0.3 daily ATR, up to 3 days back), labeled with their age in days, for example PDH 2."
const string T_TK = "When price trades beyond a level, its line runs up to that bar and ends in its name with Sweep or Break, written just above (highs) or below (lows) the line, once the bar has closed. Sweep: the bar closed back inside. Break: the bar closed beyond the level. The text sizes itself to the room on the chart: zoomed out it gets smaller instead of covering other marks."
const string T_OD = "While Asia or New York runs: how often, on this chart, the session high (low) reached so far was still the high (low) at the session end. Shown in the box and the dashboard, next to the base: windows of the same length at other hours of the day. Updates every 30 minutes (every hour on charts above 30m). Not shown for London and the custom session."
const string T_EZ = "Dotted zone around the running session: in 80% of past sessions on this chart, price did not move further beyond the range so far than this distance by the session end."
const string T_AL = "Create one alert with the condition 'Any alert() function call' to receive the events selected here."
const string T_RG = "Session range from high to low, in the unit chosen under Style → Session size. Latest: running or last finished session. Avg: average session of this kind on this chart (median of past sessions, so single news days do not distort it). Other hours: windows of the same length at all other hours of the day. In pips / points both are scaled to the current daily ATR(14), so they fit today's volatility."
const string T_TA = "How often New York traded beyond the Asia high or low of the same day. Chart: this chart's history. Base: the same window lengths and gap, shifted to all other hours of the day."
const string T_BS = "Frame: outline with a light tint. Filled: shaded area without outline. Filled + frame: shaded area with outline."
const string T_BL = "Where the session name and size are written: inside the box (top left), above the box, or nowhere. Above the box the text sizes itself to the width of the session: zoomed out it gets smaller instead of running into the next session. The second line shows the live statistics while Asia or New York runs."
const string T_AT = "How the session size is written in the box and the dashboard. Pips / points: range from high to low (pips on forex, price on other markets) and the average range of this session on this chart. % vs average: how much bigger or smaller than an average session of this kind (for example 30% above average). % of ATR: range as a share of the daily ATR(14), the average daily range. Average = median of past sessions, so single news days do not distort it."
const string T_CC = "Candles in your up and down colors. Outside the sessions they are faded. Inside a session they get stronger the more of its typical range the session has already used: faint right after the start, full color once it has moved as much as a normal session of this kind on this chart. Turn off if another indicator colors the candles."
const string T_UN = "The biggest 10% of sessions get a thick frame, the quietest 10% a dotted frame, measured against past sessions of the same kind on this chart (from 20 sessions on). Shown even when the box style has no frame. A running session gets the thick frame as soon as it passes that mark."
const string T_CD = "Averages need 5 past sessions of a kind on this chart, the unusual-session frames and live statistics 20, the noise check (≈) 30. On low timeframes the chart loads fewer days of history, a higher timeframe gives more sessions."
const string T_NZ = " ≈ and grey: on this chart the value is not distinguishable from the base, the difference is within two standard errors (or fewer than 30 sessions). Differences of a few points on a single chart are usually noise."
 
bool   iAsia  = input.bool(true, "Asia", inline = "as", group = G1, display = display.none)
color  cAsia  = input.color(#FB923C, "", inline = "as", group = G1, tooltip = T_AS, display = display.none)
bool   iLon   = input.bool(true, "London", inline = "ln", group = G1, display = display.none)
color  cLon   = input.color(#22D3EE, "", inline = "ln", group = G1, tooltip = T_LN, display = display.none)
bool   iNY    = input.bool(true, "New York", inline = "ny", group = G1, display = display.none)
color  cNY    = input.color(#4C9DFF, "", inline = "ny", group = G1, display = display.none)
string iNYw   = input.string("08:00-17:00", "", options = ["08:00-17:00", "Cash 09:30-16:00"], inline = "ny", group = G1, tooltip = T_NY, display = display.none)
bool   iCus   = input.bool(false, "Custom", inline = "cu", group = G1, display = display.none)
color  cCus   = input.color(#8B95A7, "", inline = "cu", group = G1, display = display.none)
string iCusS  = input.session("0700-1100", "", inline = "cu2", group = G1, active = iCus, display = display.none)
string iCusTz = input.string("Europe/London", "", options = ["America/Los_Angeles", "America/Phoenix", "America/Chicago", "America/New_York", "America/Sao_Paulo", "UTC", "Europe/London", "Europe/Berlin", "Asia/Dubai", "Asia/Kolkata", "Asia/Singapore", "Asia/Hong_Kong", "Asia/Shanghai", "Asia/Tokyo", "Australia/Sydney"], inline = "cu2", group = G1, tooltip = T_CU, active = iCus, display = display.none)
bool   iWknd  = input.bool(false, "Weekend sessions", group = G1, tooltip = T_WK, display = display.none)
int    iDays  = input.int(10, "History (days)", minval = 1, maxval = 30, group = G1, tooltip = T_HD, display = display.none)
 
bool   iLvl   = input.bool(true, "Session highs / lows", inline = "lv", group = G2, display = display.none)
int    iLvlN  = input.int(1, "", minval = 1, maxval = 3, inline = "lv", group = G2, tooltip = T_LV, active = iLvl, display = display.none)
bool   iPD    = input.bool(true, "Previous day high / low", inline = "pd", group = G2, display = display.none)
color  cPDH   = input.color(#4ADE80, "", inline = "pd", group = G2, display = display.none)
color  cPDL   = input.color(#F87171, "", inline = "pd", group = G2, tooltip = T_PD, display = display.none)
bool   iTake  = input.bool(true, "Mark taken levels", group = G2, tooltip = T_TK, active = iLvl or iPD, display = display.none)
 
bool   iOdds  = input.bool(true, "Live statistics", group = G3, tooltip = T_OD, display = display.none)
bool   iZone  = input.bool(false, "End zone", group = G3, tooltip = T_EZ, display = display.none)
 
bool   iDash  = input.bool(true, "Dashboard", inline = "db", group = G4, display = display.none)
string iDV    = input.string("Bottom", "", options = ["Top", "Middle", "Bottom"], inline = "db", group = G4, active = iDash, display = display.none)
string iDH    = input.string("Right", "", options = ["Right", "Left", "Center"], inline = "db", group = G4, active = iDash, display = display.none)
string iDS    = input.string("Normal", "", options = ["Small", "Normal", "Large"], inline = "db", group = G4, active = iDash, tooltip = "Position (vertical, horizontal) and text size of the dashboard.", display = display.none)
string iDL    = input.string("Full", "Layout", options = ["Full", "Compact"], group = G4, tooltip = "Compact: the running session only, in three short columns, and short box labels (for example NY · 62 pips). Made for phones and small screens; Bottom / Right keeps it clear of the chart legend.", active = iDash, display = display.none)
 
bool   aStart = input.bool(false, "Session start", group = G5, display = display.none)
bool   aTake  = input.bool(false, "Level taken", group = G5, tooltip = T_AL, display = display.none)
 
string iTheme = input.string("Auto", "Color scheme", options = ["Auto", "Dark", "Light"], group = G6, tooltip = "Auto: detects whether the chart background is light or dark and uses matching default colors. Any color you change always stays exactly as you set it.", display = display.none)
string iBS    = input.string("Frame", "Box style", options = ["Frame", "Filled", "Filled + frame"], group = G6, tooltip = T_BS, display = display.none)
int    iFill  = input.int(85, "Fill transparency", minval = 50, maxval = 100, group = G6, tooltip = "Transparency of the shaded area for the filled styles. 100 = no fill.", active = iBS != "Frame", display = display.none)
string iBL    = input.string("Above", "Box label", options = ["Inside", "Above", "Off"], group = G6, tooltip = T_BL, display = display.none)
string iBT    = input.string("Auto", "Text size", options = ["Auto", "Small", "Normal", "Large"], group = G6, tooltip = "Size of the labels inside the boxes and of the level tags at the right edge. Auto: larger on charts of 5 minutes and below, where the boxes are wide, smaller above. Labels above the boxes and the Sweep / Break marks size themselves to the room they have; Small and Large make them smaller or larger.", display = display.none)
string iBR    = input.string("Pips / points", "Session size", options = ["Pips / points", "% vs average", "% of ATR", "Off"], group = G6, tooltip = T_AT, display = display.none)
bool   iUnu   = input.bool(true, "Highlight unusual sessions", group = G6, tooltip = T_UN, display = display.none)
bool   iCC    = input.bool(false, "Candle colors", inline = "cc", group = G6, display = display.none)
color  cUp    = input.color(#26A69A, "", inline = "cc", group = G6, active = iCC, display = display.none)
color  cDn    = input.color(#EF5350, "", inline = "cc", group = G6, tooltip = T_CC, active = iCC, display = display.none)
 
// ─── Derived settings ────────────────────────────────────────────────────────
bool nyCash = iNYw != "08:00-17:00"
int  cSH    = int(str.tonumber(str.substring(iCusS, 0, 2)))
int  cSM    = int(str.tonumber(str.substring(iCusS, 2, 4)))
int  cEH    = int(str.tonumber(str.substring(iCusS, 5, 7)))
int  cEM    = int(str.tonumber(str.substring(iCusS, 7, 9)))
int  cS     = cSH * 60 + cSM
int  cE     = cEH * 60 + cEM
bool cWrap  = cE <= cS
int  cDur   = cWrap ? cE + 1440 - cS : cE - cS
bool bxLine = iBS != "Filled"
int  bxFill = iBS == "Frame" ? 90 : iFill
bool dCmp   = iDL == "Compact"
// Sizes: pips on forex, price on other markets
// Metals quoted against a currency (gold, silver ...) are not counted in pips, even where the feed lists them as forex
bool   METAL = str.contains("XAU XAG XPT XPD", syminfo.basecurrency) and syminfo.basecurrency != ""
float  PIP  = syminfo.type == "forex" and not METAL ? (syminfo.currency == "JPY" ? 0.01 : 0.0001) : na
string UNIT = na(PIP) ? "" : " pips"
// Unit of the session size: 0 = pips / points, 1 = % vs average, 2 = % of ATR (Off keeps pips / points in the dashboard)
int    szMode = iBR == "% vs average" ? 1 : iBR == "% of ATR" ? 2 : 0
 
// ─── Theme: on a light background the default colors switch to stronger, darker tones ─
// Colors the user changed always stay as set.
float bgLum   = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
bool  isLight = iTheme == "Light" or (iTheme == "Auto" and bgLum > 140)
themed(color c, color darkDef, color lightDef) =>
    isLight and c == darkDef ? lightDef : c
// Subtle elements get less transparency on light backgrounds, otherwise they look washed out
soft(color c, int t) =>
    color.new(c, isLight ? math.round(t * 0.6) : t)
color accentCol  = isLight ? #C27C0E : #F2B84B
color neutralCol = isLight ? #6E7788 : #8B95A7
color colAsia    = themed(cAsia, #FB923C, #D9650F)
color colLon     = themed(cLon, #22D3EE, #0E8FA8)
color colNY      = themed(cNY, #4C9DFF, #1F6FD1)
color colCus     = themed(cCus, #8B95A7, #6E7788)
color colPDH     = themed(cPDH, #4ADE80, #15803D)
color colPDL     = themed(cPDL, #F87171, #B91C1C)
color fg         = chart.fg_color
color dim        = color.new(neutralCol, 15)
 
// ─── Timeframe and statistic slots ───────────────────────────────────────────
int  tfMs = timeframe.in_seconds() * 1000
// Chart text sizes: labels and the smaller tags / marks. Auto: larger where the boxes are wide (5m and below)
string szTxt = iBT == "Large" ? size.large : iBT == "Normal" ? size.normal : iBT == "Small" ? size.small : tfMs <= 300000 ? size.normal : size.small
string szSub = szTxt == size.large ? size.normal : szTxt == size.normal ? size.small : size.tiny
// Level tags at the right edge: never below small, they have to stay readable
string szTag = szSub == size.tiny ? size.small : szSub
// Self-sizing texts (labels above the boxes, Sweep / Break marks): Small / Large give them less / more room
float  TXM   = iBT == "Large" ? 1.3 : iBT == "Small" ? 0.8 : 1.0
bool tfOk = timeframe.isintraday and timeframe.in_seconds() <= 3600
// Statistics work on 30-minute slots (1-hour slots on charts above 30m).
int  SLOT = tfMs <= 1800000 ? 1800000 : HOUR
int  STEP = SLOT == 1800000 ? 2 : 1
int  NB   = 48 * STEP + 8
 
// Non-repainting: daily ATR(14) of the previous finished day. The [1] offset combined with lookahead_on only returns confirmed data.
float dAtr = request.security(syminfo.tickerid, "D", ta.atr(14)[1], lookahead = barmerge.lookahead_on)
// Height of the self-sizing texts. They take a fixed share of the price range of about the last two days,
// which is roughly what a chart shows, so they come out at a similar size on every market and screen.
int   RNB  = math.max(10, math.min(2000, int(2 * DAY / math.max(tfMs, 60000))))
float RREF = ta.highest(high, RNB) - ta.lowest(low, RNB)
float TXH  = (na(RREF) or RREF <= 0 ? (na(dAtr) ? 20 * syminfo.mintick : 0.075 * dAtr) : 0.028 * RREF) * TXM
 
// ─── Types ───────────────────────────────────────────────────────────────────
// One trading session (Asia, London, New York, Custom)
type Ses
    string name
    string tag
    bool   active = false
    bool   draw   = false
    int    skip   = 0
    int    ps
    int    pe
    float  hi
    float  lo
    int    hiT
    int    loT
    int    tl
    float  atr
    box    bx
    box    hb
    float  typ
    float  p90
    float  p10
    bool   big = false
    bool   seen = false
    int    t0
    int    nFin = 0
    bool   lOk = false
    float  lHi
    float  lLo
    float  lR
    float  lX
    int    lE  = -1
    float  tx
    int    L   = 0
    array<float> rR
    array<float> rB
 
// Level line on the chart
type Lvl
    float price
    bool  isHigh
    int   k
    line  ln
    int   d = 0
 
// ─── State ───────────────────────────────────────────────────────────────────
// Slot buffer: high/low per slot over the last two days
var array<int>   bId = array.new<int>(NB, -1)
var array<float> bHi = array.new<float>(NB, na)
var array<float> bLo = array.new<float>(NB, na)
var array<bool>  bWk = array.new<bool>(NB, false)
var int          curSid = -1
 
// New York takes the Asia high or low: base*2 + [n, high or low taken]
var array<int> M2 = array.new<int>(4, 0)
// Live statistics: ((session*2 + base)*JMAX + elapsed slots)*3 + [n, high already in, low already in]
var array<int> P1 = array.new<int>(3 * 2 * JMAX * 3, 0)
// End zone: histogram of the extension beyond the range so far, real sessions per elapsed slot, NBIN bins each
var array<int> HG = array.new<int>(3 * JMAX * NBIN, 0)
// Window cache: high/low of each session's window length ending at every full hour (48 hours per session)
var array<int>   wcE = array.new<int>(192, -1)
var array<int>   wcN = array.new<int>(192, 0)
var array<float> wcH = array.new<float>(192, na)
var array<float> wcL = array.new<float>(192, na)
 
var array<Ses>   S  = array.new<Ses>()
var array<Lvl>   LV = array.new<Lvl>()
var array<label> TG = array.new<label>()
 
if barstate.isfirst
    S.push(Ses.new("ASIA", "Asia", rR = array.new<float>(), rB = array.new<float>()))
    S.push(Ses.new("LONDON", "London", rR = array.new<float>(), rB = array.new<float>()))
    S.push(Ses.new("NEW YORK", "NY", rR = array.new<float>(), rB = array.new<float>()))
    S.push(Ses.new("CUSTOM", "Custom", rR = array.new<float>(), rB = array.new<float>()))
 
// ─── Helpers ─────────────────────────────────────────────────────────────────
inc(array<int> a, int i) =>
    a.set(i, a.get(i) + 1)
 
mins(int t, string tz) =>
    hour(t, tz) * 60 + minute(t, tz)
 
// Does the bar [a, b) in local minutes overlap the window [s, e)? The window must not cross midnight.
ovm(int a, int b0, int s, int e) =>
    int b = b0 <= a ? b0 + 1440 : b0
    a < e and b > s
 
atLocal(int t, string tz, int hh, int mm) =>
    timestamp(tz, year(t, tz), month(t, tz), dayofmonth(t, tz), hh, mm, 0)
 
isWk(int t, string tz) =>
    int d = dayofweek(t, tz)
    d != dayofweek.saturday and d != dayofweek.sunday
 
tzOf(int k) =>
    k == 0 ? TZ_TK : k == 1 ? TZ_LN : k == 2 ? TZ_NY : iCusTz
 
colOf(int k) =>
    k == 0 ? colAsia : k == 1 ? colLon : k == 2 ? colNY : colCus
 
showOf(int k) =>
    k == 0 ? iAsia : k == 1 ? iLon : k == 2 ? iNY : iCus
 
pOff(int k, int b, int j) =>
    ((k * 2 + b) * JMAX + j) * 3
 
hOff(int k, int j) =>
    (k * JMAX + j) * NBIN
 
// Planned start and end of the session that contains time t
plan(int k, int t) =>
    int a = na
    int b = na
    if k == 0
        a := atLocal(t, TZ_TK, 9, 0)
        b := atLocal(t, TZ_TK, 15, 0)
    else if k == 1
        a := atLocal(t, TZ_LN, 8, 0)
        b := atLocal(t, TZ_NY, 8, 0)
    else if k == 2
        a := nyCash ? atLocal(t, TZ_NY, 9, 30) : atLocal(t, TZ_NY, 8, 0)
        b := nyCash ? atLocal(t, TZ_NY, 16, 0) : atLocal(t, TZ_NY, 17, 0)
    else
        a := atLocal(t, iCusTz, cSH, cSM)
        if cWrap and mins(t, iCusTz) < cE
            a -= DAY
        b := a + cDur * 60000
    [a, b]
 
startOn(int k, int t) =>
    k == 0 ? atLocal(t, TZ_TK, 9, 0) : k == 1 ? atLocal(t, TZ_LN, 8, 0) : k == 2 ? atLocal(t, TZ_NY, nyCash ? 9 : 8, nyCash ? 30 : 0) : atLocal(t, iCusTz, cSH, cSM)
 
nextStart(int k, int t) =>
    int r = na
    for d = 0 to 4
        int a = startOn(k, t + d * DAY)
        if na(r) and a > t and (iWknd or isWk(a, tzOf(k)))
            r := a
    r
 
// High and low of the slot window [e - L, e). Returns na if a slot has no data.
win(int e, int L) =>
    float h  = na
    float l  = na
    bool  ok = L > 0
    if ok
        for j = 0 to L - 1
            int id = e - L + j
            int p  = id % NB
            if bId.get(p) != id or (not iWknd and bWk.get(p))
                ok := false
                break
            float bh = bHi.get(p)
            float bl = bLo.get(p)
            if na(h) or bh > h
                h := bh
            if na(l) or bl < l
                l := bl
    [ok ? h : na, ok ? l : na]
 
// Window [e - L, e) of session k from the hourly cache; computed directly if it is not cached
cwin(int k, int e, int L) =>
    int   ix = k * 48 + math.floor(e / STEP) % 48
    float h  = na
    float l  = na
    if wcE.get(ix) == e and wcN.get(ix) == L
        h := wcH.get(ix)
        l := wcL.get(ix)
    else
        [h2, l2] = win(e, L)
        h := h2
        l := l2
    [h, l]
 
// Count one New York window: was the Asia high or low taken?
cnt2(int b, bool tH, bool tL) =>
    inc(M2, b * 2)
    if tH or tL
        inc(M2, b * 2 + 1)
 
// Does New York [tS, tE) trade beyond the Asia high/low? Base: identical window lengths and gap,
// shifted to all 23 other full hours (the shifted Asia window ends i hours before the Asia end).
pair(Ses r, int tS, int tE, float th, float tl) =>
    cnt2(0, th > r.lHi, tl < r.lLo)
    int Lt = tE - tS
    for i = 1 to 23
        [h2, l2] = cwin(2, tE - i * STEP, Lt)
        [h3, l3] = cwin(0, r.lE - i * STEP, r.L)
        if not na(h2) and not na(h3)
            cnt2(1, h2 > h3, l2 < l3)
 
// q-quantile (upper bin edge, in ATR) of one or two extension histograms; na below 20 values
pctX(int o1, int o2, float q) =>
    int n = 0
    for i = 0 to NBIN - 1
        n += HG.get(o1 + i) + (o2 >= 0 ? HG.get(o2 + i) : 0)
    float x = na
    if n >= 20
        int need = math.ceil(q * n)
        int c    = 0
        for i = 0 to NBIN - 1
            c += HG.get(o1 + i) + (o2 >= 0 ? HG.get(o2 + i) : 0)
            if c >= need
                x := (i + 1) * BINW
                break
    x
 
// Live statistics and end zone for one finished window [e - L, e) with final high H and low lo:
// after every complete slot j, was the high (low) already in (real sessions and base windows),
// and how far did price move beyond the range so far (real sessions only, for the end zone)? London: end zone only.
prof(int k, int b, int e, int L, float H, float lo, float atr) =>
    if L > 1 and L <= JMAX and not na(H) and atr > 0
        float ph = na
        float pl = na
        for j = 1 to L - 1
            int p = (e - L + j - 1) % NB
            ph := na(ph) ? bHi.get(p) : math.max(ph, bHi.get(p))
            pl := na(pl) ? bLo.get(p) : math.min(pl, bLo.get(p))
            if k != 1
                int o = pOff(k, b, j)
                inc(P1, o)
                if ph >= H
                    inc(P1, o + 1)
                if pl <= lo
                    inc(P1, o + 2)
            if b == 0
                float m  = math.max(H - ph, pl - lo) / atr
                int   bn = math.min(NBIN - 1, math.floor(m / BINW))
                inc(HG, hOff(k, j) + bn)
 
// Median, once at least 5 values exist
med(array<float> a) =>
    a.size() >= 5 ? a.median() : na
 
pct(float x) =>
    na(x) ? "–" : str.tostring(x * 100, "0") + "%"
 
// A price distance as text: pips on forex, otherwise price with sensible decimals
fmtSz(float x) =>
    na(x) ? "–" : not na(PIP) ? str.tostring(x / PIP, "#,##0") : x >= 100 ? str.tostring(x, "#,##0") : x >= 10 ? str.tostring(x, "0.0") : x >= 1 ? str.tostring(x, "0.00") : str.tostring(x, format.mintick)
 
// Normal range of this session in price: median share of the daily ATR, times the given ATR
normOf(Ses s, float atr) =>
    na(s.typ) or na(atr) ? na : s.typ * atr
 
// Size of the session so far compared with its typical size on this chart; na until 5 sessions exist
relOf(Ses s) =>
    na(s.typ) or na(s.atr) or s.typ <= 0 or s.atr <= 0 ? na : (s.hi - s.lo) / s.atr / s.typ
 
// Difference to the average: signed (+30%, −25%) or in words (30% above average)
dSigned(float x) =>
    int p = na(x) ? 0 : math.round((x - 1) * 100)
    na(x) ? "–" : (p > 0 ? "+" : p < 0 ? "−" : "±") + str.tostring(math.abs(p)) + "%"
dWords(float x) =>
    int p = na(x) ? 0 : math.round((x - 1) * 100)
    na(x) ? "" : p == 0 ? "at average" : str.tostring(math.abs(p)) + (p > 0 ? "% above average" : "% below average")
 
// Size as text in the chosen unit. x: share of the daily ATR, atr: ATR to turn it into price, nrm: average share
szFmt(float x, float atr, float nrm) =>
    szMode == 1 ? (na(nrm) or nrm <= 0 or na(x) ? "–" : dSigned(x / nrm)) : szMode == 2 ? pct(x) : (na(x) or na(atr) ? "–" : fmtSz(x * atr))
 
// Box label: name and size in the chosen unit (compact layout: short name, size only)
bxText(Ses s) =>
    string nm = dCmp ? str.upper(s.tag) : s.name
    float  r  = na(s.atr) or s.atr <= 0 ? na : (s.hi - s.lo) / s.atr
    string t  = ""
    if iBR == "Pips / points"
        float nr = normOf(s, s.atr)
        t := " · " + fmtSz(s.hi - s.lo) + UNIT + (dCmp or na(nr) ? "" : " · avg " + fmtSz(nr))
    else if iBR == "% vs average"
        float x = relOf(s)
        t := na(x) ? "" : " · " + (dCmp ? dSigned(x) : dWords(x))
    else if iBR == "% of ATR"
        t := na(r) ? "" : " · " + pct(r) + (dCmp ? "" : " of ATR")
    nm + t
 
// Session label: inside the box (top left), above the box, or off.
// Above: an invisible box over the session holds the text, which sizes itself to that room,
// so on a zoomed-out chart it gets smaller instead of running into the next session.
setTxt(Ses s, string t) =>
    if not na(s.bx) and iBL == "Inside"
        box.set_text(s.bx, t)
    if not na(s.hb)
        float hh  = TXH * 1.2 * (str.contains(t, "\n") ? 2 : 1)
        // A small gap over the box top keeps the line of the session high free for its Sweep / Break text
        float gap = TXH / 2
        // A Sweep / Break text above a high inside this session pushes the label up, so the two never overlap
        float bs  = math.max(s.hi, nz(s.tx, s.hi))
        box.set_text(s.hb, t)
        box.set_top(s.hb, bs + gap + hh)
        box.set_bottom(s.hb, bs + gap)
 
// Unusual session: thick solid frame (biggest 10%) or dotted frame (quietest 10%), also without a frame style
markBox(Ses s, int k, bool big) =>
    if not na(s.bx)
        box.set_border_color(s.bx, colOf(k))
        box.set_border_width(s.bx, big ? 2 : 1)
        box.set_border_style(s.bx, big ? line.style_solid : line.style_dotted)
 
// Short name of a level: session tag with H / L, or PDH / PDL (older days with their age, e.g. PDH 2)
lvTag(Lvl v, int dNow) =>
    int age = dNow - v.d
    v.k == 4 ? (v.isHigh ? "PDH" : "PDL") + (age > 1 ? " " + str.tostring(age) : "") : S.get(v.k).tag + (v.isHigh ? " H" : " L")
 
// Adds a level to a shared name; levels of the same side share their H / L, e.g. "London · NY L".
// A name that is already there is not repeated (two NY highs close together stay "NY H").
joinTag(string a, Lvl v, int dNow) =>
    string sfx = v.isHigh ? " H" : " L"
    string tg  = lvTag(v, dNow)
    string nm  = v.k == 4 ? tg : S.get(v.k).tag
    bool   dup = false
    for w in str.split(a, " · ")
        if w == tg or (v.k != 4 and w == nm)
            dup := true
    dup ? a : v.k != 4 and str.endswith(a, sfx) ? str.substring(a, 0, str.length(a) - 2) + " · " + nm + sfx : a + " · " + tg
 
// Color of a level: session color, previous day high green and low red
lvCol(int k, bool hi) =>
    k == 4 ? (hi ? colPDH : colPDL) : colOf(k)
 
// New level line; per market and side only the most recent ones stay (previous day: one)
addLv(int k, float p, bool hi, int t, int d = 0) =>
    color c = lvCol(k, hi)
    LV.push(Lvl.new(p, hi, k, line.new(t, p, t + tfMs, p, xloc = xloc.bar_time, extend = extend.right, color = soft(c, 20), style = line.style_dashed, width = 1), d))
    int cnt = 0
    for i = LV.size() - 1 to 0
        Lvl v = LV.get(i)
        if v.k == k and v.isHigh == hi
            cnt += 1
            // Previous days: older untaken levels stay while they sit close to the newest one (up to 3 days back)
            bool keep = k == 4 ? (cnt == 1 or (d - v.d <= 2 and not na(dAtr) and math.abs(v.price - p) <= 0.3 * dAtr)) : cnt <= iLvlN
            if not keep
                line.delete(v.ln)
                LV.remove(i)
 
// Close a session: final box, level lines, statistics
fin(int k, Ses s) =>
    s.active := false
    s.nFin   += 1
    // Measured window: the hours the session actually traded. Markets that close before the planned end
    // (index CFDs with a daily break, stocks) still count, over the part they traded.
    int lS = math.floor(float(math.max(s.ps, s.t0)) / SLOT)
    int lE = math.ceil(float(math.min(s.pe, s.tl + tfMs)) / SLOT)
    int L  = lE - lS
    [h, l] = win(lE, L)
    bool ok = not na(h) and not na(s.atr) and s.atr > 0
    s.lOk := ok
    s.lHi := h
    s.lLo := l
    s.lR  := ok ? (h - l) / s.atr : na
    s.lX  := ok and not na(s.typ) and s.typ > 0 ? s.lR / s.typ : na
    s.lE  := lE
    s.L   := L
    if not na(s.bx)
        // A finished box ends at its last bar (not at the planned end, which may fall on a weekend gap)
        // Edges half a bar outside the first and last bar, so they do not cut through those candles
        box.set_right(s.bx, s.tl + tfMs / 2)
        // Label centered over the finished box
        if not na(s.hb)
            box.set_right(s.hb, s.tl + tfMs / 2)
            box.set_text_halign(s.hb, text.align_center)
    setTxt(s, bxText(s))
    if s.draw and iLvl
        addLv(k, s.hi, true, s.hiT)
        addLv(k, s.lo, false, s.loT)
    if ok
        float rx = (h - l) / s.atr
        // Unusual size against the past sessions of this kind (marks from before this session)
        if iUnu and not s.big and not na(s.p90) and rx >= s.p90
            markBox(s, k, true)
        else if iUnu and not s.big and not na(s.p10) and rx <= s.p10
            markBox(s, k, false)
        s.rR.push(rx)
        // Typical range of this session on this chart (median), for the candle colors
        s.typ := med(s.rR)
        if s.rR.size() >= 20
            s.p90 := s.rR.percentile_nearest_rank(90)
            s.p10 := s.rR.percentile_nearest_rank(10)
        if k <= 2
            prof(k, 0, lE, L, h, l, s.atr)
        // Base windows: same length, ending 1 to 23 hours earlier (live statistics use every third hour)
        for i = 1 to 23
            [bh, bl] = cwin(k, lE - i * STEP, L)
            if not na(bh)
                s.rB.push((bh - bl) / s.atr)
                if k <= 2 and i % 3 == 1
                    prof(k, 1, lE - i * STEP, L, bh, bl, s.atr)
        // New York and the Asia high/low of the same day
        if k == 2
            Ses a = S.get(0)
            if a.lOk and a.lE <= lS and (lS - a.lE) * SLOT < DAY
                pair(a, lS, lE, h, l)
 
dur(int ms) =>
    int m  = math.max(0, math.round(ms / 60000.0))
    int h  = math.floor(m / 60)
    int mm = m - h * 60
    h > 0 ? str.tostring(h) + "h " + str.tostring(mm) + "m" : str.tostring(mm) + "m"
 
// True when the chart value differs from the base by more than two standard errors
sig(float p, float b, int n) =>
    float se = math.sqrt(p * (1 - p) / n)
    n >= 30 and not na(p) and not na(b) and math.abs(p - b) > 2 * se
 
// Noise filter: chart value, "≈" and grey when it is not distinguishable from the base
cmpTxt(float p, float b, int n) =>
    bool s = sig(p, b, n)
    [na(p) or n < 20 ? "–" : (s ? "" : "≈ ") + pct(p), s ? fg : dim]
 
// Sign test for the typical range: share of sessions above the base median, against 50%
medSig(array<float> a, float mb) =>
    int n = a.size()
    int c = 0
    if n > 0 and not na(mb)
        for v in a
            if v > mb
                c += 1
    n >= 30 and math.abs(float(c) / n - 0.5) > 1.0 / math.sqrt(n)
 
bar10(float f) =>
    int n = math.max(0, math.min(10, math.round(f * 10)))
    str.repeat("▰", n) + str.repeat("▱", 10 - n)
 
// Table position from the vertical and horizontal choice
posOf(string v, string h) =>
    v == "Top" ? (h == "Left" ? position.top_left : h == "Center" ? position.top_center : position.top_right) : v == "Middle" ? (h == "Left" ? position.middle_left : h == "Center" ? position.middle_center : position.middle_right) : (h == "Left" ? position.bottom_left : h == "Center" ? position.bottom_center : position.bottom_right)
 
// ─── Slot buffer ─────────────────────────────────────────────────────────────
int  sid     = math.floor(float(time) / SLOT)
int  pos     = sid % NB
bool newSlot = sid != curSid
if tfOk
    if newSlot
        bId.set(pos, sid)
        bHi.set(pos, high)
        bLo.set(pos, low)
        int dw = dayofweek(time, "UTC")
        bWk.set(pos, dw == dayofweek.saturday or dw == dayofweek.sunday)
        curSid := sid
    else
        bHi.set(pos, math.max(bHi.get(pos), high))
        bLo.set(pos, math.min(bLo.get(pos), low))
 
// ─── Window cache: every full hour, each session's window length ending now ───
if tfOk and barstate.isconfirmed and newSlot and sid % STEP == 0
    for k = 0 to 3
        Ses s = S.get(k)
        if s.L > 0
            [h, l] = win(sid, s.L)
            int ix = k * 48 + math.floor(sid / STEP) % 48
            wcE.set(ix, sid)
            wcN.set(ix, s.L)
            wcH.set(ix, h)
            wcL.set(ix, l)
 
// ─── Previous day high / low ─────────────────────────────────────────────────
// Tracked on the chart bars within each daily bar of the symbol, so the line starts where the
// high (low) was made. The first day on the chart is incomplete and is skipped.
var float dH  = na
var float dL  = na
var int   dHT = na
var int   dLT = na
var int   dN  = 0
if tfOk
    if timeframe.change("D") and bar_index > 0
        if dN >= 1 and iPD and not na(dH) and time >= last_bar_time - iDays * DAY
            addLv(4, dH, true, dHT, dN)
            addLv(4, dL, false, dLT, dN)
        dN  += 1
        dH  := high
        dL  := low
        dHT := time
        dLT := time
    else
        if na(dH) or high > dH
            dH  := high
            dHT := time
        if na(dL) or low < dL
            dL  := low
            dLT := time
 
// ─── Level lines: taken? (closed bars only) ──────────────────────────────────
// Levels this close together share one name, so their texts never sit on top of each other
// (about 3.5% of the daily range on 15m, wider on higher timeframes, where a pip takes fewer pixels)
// Top of the Sweep / Break texts set above highs on this bar (the label of the running session moves up for them)
float mkTop = na
float NEAR = math.max(syminfo.mintick / 2, na(dAtr) ? 0.0 : 0.035 * dAtr * math.sqrt(timeframe.in_seconds() / 900.0))
if tfOk and barstate.isconfirmed and LV.size() > 0
    // Taken levels of this bar; levels at (nearly) the same price share one mark, e.g. "PDH · NY H Sweep"
    array<float>  gP = array.new<float>()
    array<string> gN = array.new<string>()
    array<color>  gC = array.new<color>()
    array<bool>   gB = array.new<bool>()
    array<int>    gS = array.new<int>()
    array<bool>   gH = array.new<bool>()
    for i = LV.size() - 1 to 0
        Lvl v = LV.get(i)
        if v.isHigh ? high > v.price : low < v.price
            bool brk = v.isHigh ? close > v.price : close < v.price
            line.set_extend(v.ln, extend.none)
            // The line runs up to the candle that took it
            line.set_x2(v.ln, time - tfMs / 2)
            int at = -1
            if gP.size() > 0
                for j = 0 to gP.size() - 1
                    if at < 0 and math.abs(gP.get(j) - v.price) <= NEAR
                        at := j
            int x1 = line.get_x1(v.ln)
            if at < 0
                gP.push(v.price)
                gN.push(lvTag(v, dN))
                gC.push(lvCol(v.k, v.isHigh))
                gB.push(brk)
                gS.push(x1)
                gH.push(v.isHigh)
                at := gP.size() - 1
            else
                gN.set(at, joinTag(gN.get(at), v, dN))
                gS.set(at, math.max(gS.get(at), x1))
                if v.k == 4
                    gC.set(at, lvCol(v.k, v.isHigh))
            if aTake
                alert("AE Sessions: " + lvTag(v, dN) + (brk ? " broken" : " swept") + " (" + syminfo.ticker + ")", alert.freq_once_per_bar_close)
            LV.remove(i)
    // Name and result next to the line: the line runs on to the candle that took the level, the text sits right
    // above it (highs) or below it (lows) and ends at that candle. So line and text never leave a gap at any zoom,
    // and a level on the edge of a session box does not run through the text.
    // The text sizes itself to the room it has: on a zoomed-out chart it gets smaller instead of covering other marks.
    if iTake and gP.size() > 0
        for j = 0 to gP.size() - 1
            string t  = gN.get(j) + (gB.get(j) ? " Break" : " Sweep")
            int    xR = time - tfMs
            int    wF = int(math.round(str.length(t) * 3.0 * TXM))
            // Room from the start of the line; at least 60% of the full width, so a level taken right after it formed keeps a readable name
            int    xL = math.min(xR - int(math.round(wF * 0.6)) * tfMs, math.max(gS.get(j), xR - wF * tfMs))
            color  c  = gC.get(j)
            float  p  = gP.get(j)
            float  pd = TXH * 0.15
            bool   hi = gH.get(j)
            if hi
                float tt = p + pd + TXH
                mkTop := math.max(nz(mkTop, tt), tt)
                // Session labels over this stretch (also of a session that just ended) move up above the text
                for k = 0 to 3
                    Ses ss = S.get(k)
                    if not na(ss.hb) and box.get_left(ss.hb) < xR and box.get_right(ss.hb) > xL
                        ss.tx := math.max(nz(ss.tx, tt), tt)
                        float need = tt + TXH / 2
                        float hb0  = box.get_bottom(ss.hb)
                        if hb0 < need
                            box.set_top(ss.hb, box.get_top(ss.hb) + need - hb0)
                            box.set_bottom(ss.hb, need)
            box.new(xL, hi ? p + pd + TXH : p - pd, xR, hi ? p + pd : p - pd - TXH, xloc = xloc.bar_time, border_color = color.new(c, 100), bgcolor = color.new(c, 100), text = t, text_size = size.auto, text_color = c, text_halign = text.align_right, text_valign = hi ? text.align_bottom : text.align_top)
 
// ─── Sessions ────────────────────────────────────────────────────────────────
if tfOk
    int  t1  = time + tfMs
    int  tk0 = mins(time, TZ_TK)
    int  tk1 = mins(t1, TZ_TK)
    int  ln0 = mins(time, TZ_LN)
    int  ln1 = mins(t1, TZ_LN)
    int  ny0 = mins(time, TZ_NY)
    int  ny1 = mins(t1, TZ_NY)
    bool inA = ovm(tk0, tk1, 540, 900)
    bool nyF = ovm(ny0, ny1, 480, 1020)
    bool inL = ovm(ln0, ln1, 480, 1020) and not nyF
    bool inN = nyCash ? ovm(ny0, ny1, 570, 960) : nyF
    bool inC = false
    if iCus
        int c0 = mins(time, iCusTz)
        int c1 = mins(t1, iCusTz)
        inC := cWrap ? (ovm(c0, c1, cS, 1440) or ovm(c0, c1, 0, cE)) : ovm(c0, c1, cS, cE)
    for k = 0 to 3
        Ses  s     = S.get(k)
        bool inNow = k == 0 ? inA : k == 1 ? inL : k == 2 ? inN : inC
        // The bar left the session or its planned end has passed: close it
        if s.active and (not inNow or time >= s.pe)
            fin(k, s)
        if inNow and not s.active and time >= s.skip
            [a, b] = plan(k, time)
            if not iWknd and not isWk(a, tzOf(k))
                // Weekend session: skipped until its planned end
                s.skip := b
            else
                s.active := true
                s.seen   := true
                s.t0     := time
                s.ps     := a
                s.pe     := b
                s.hi     := high
                s.lo     := low
                s.hiT    := time
                s.loT    := time
                s.tl     := time
                s.atr    := dAtr
                s.draw   := showOf(k) and time >= last_bar_time - iDays * DAY
                s.bx     := na
                s.hb     := na
                s.tx     := na
                s.big    := false
                if s.draw
                    color c = colOf(k)
                    s.bx := box.new(time - tfMs / 2, high, b - tfMs / 2, low, xloc = xloc.bar_time, border_color = bxLine ? c : color.new(c, 100), border_width = 1, bgcolor = color.new(c, bxFill), text_size = szTxt, text_color = c, text_halign = text.align_left, text_valign = text.align_top)
                    if iBL == "Above"
                        // Over the planned session window, so it stays above the box and off the candles.
                        // While the session runs the text starts at its left edge (the window's middle is still in the future).
                        s.hb := box.new(time - tfMs / 2, high, b - tfMs / 2, high, xloc = xloc.bar_time, border_color = color.new(c, 100), bgcolor = color.new(c, 100), text_size = size.auto, text_color = c, text_halign = text.align_left, text_valign = text.align_bottom)
                if aStart and showOf(k)
                    alert("AE Sessions: " + s.tag + " session started (" + syminfo.ticker + ")", alert.freq_once_per_bar)
        else if inNow and s.active
            s.tl := time
            if high > s.hi
                s.hi  := high
                s.hiT := time
            if low < s.lo
                s.lo  := low
                s.loT := time
        if s.active
            if not na(mkTop)
                s.tx := math.max(nz(s.tx, mkTop), mkTop)
            if not na(s.bx)
                box.set_top(s.bx, s.hi)
                box.set_bottom(s.bx, s.lo)
                if iUnu and not s.big and not na(s.p90) and not na(s.atr) and s.atr > 0 and (s.hi - s.lo) / s.atr >= s.p90
                    s.big := true
                    markBox(s, k, true)
            setTxt(s, bxText(s))
            // Close on the last bar of the session, once it is confirmed; also when the market closes for the day
            // before the planned end (stocks), so its levels are on the chart before the next day opens
            if barstate.isconfirmed and (t1 >= s.pe or (k <= 2 and session.islastbar))
                fin(k, s)
 
// ─── Candle colors: strength = share of the typical session range used so far ─
color cc = na
if iCC and tfOk
    int   ka = S.get(2).active and showOf(2) ? 2 : S.get(1).active and showOf(1) ? 1 : S.get(0).active and showOf(0) ? 0 : S.get(3).active and showOf(3) ? 3 : -1
    color c0 = close >= open ? cUp : cDn
    if ka < 0
        cc := color.new(c0, 80)
    else
        Ses   s = S.get(ka)
        float x = relOf(s)
        float u = na(x) ? 0.5 : math.min(1.0, x)
        cc := color.new(c0, math.round(70 * (1 - u)))
barcolor(cc, title = "Candle colors")
 
// ─── Live: odds and end zone (last bar only) ─────────────────────────────────
var box ZB = na
int   kL = -1
int   nL = 0
int   nB = 0
float pH = na
float pL = na
float bH = na
float bL = na
if barstate.islast
    box.delete(ZB)
    ZB := na
    for lb in TG
        label.delete(lb)
    TG.clear()
// The market has closed for the day (or the week): no session counts as running, even before its planned end.
// Closed: the last bar of the trading day has finished, or the chart opened while the market is closed
// (the last bar is a finished bar from a while ago; markets that stop before their listed hours, such as index CFDs on Fridays).
// Live and Bar Replay bars are never treated as stale, nor is a Bar Replay start more than 4 days back.
bool histStale = barstate.islast and barstate.ishistory and timenow - (time + tfMs) > math.max(tfMs, 30 * 60000) and timenow - (time + tfMs) < 4 * DAY
bool mClosed   = barstate.islast and ((session.islastbar and barstate.isconfirmed) or histStale)
if barstate.islast and tfOk
    // Running session with the highest priority (New York, London, Asia)
    for k in array.from(2, 1, 0)
        if kL < 0 and S.get(k).active and showOf(k) and not mClosed
            kL := k
    if kL >= 0
        Ses s  = S.get(kL)
        int lS = math.floor(float(math.max(s.ps, s.t0)) / SLOT)
        int Lc = math.ceil(float(s.pe) / SLOT) - lS
        int j  = sid - lS
        if j >= 1 and j <= math.min(Lc, JMAX) - 1
            // Live statistics: not for London (see prof)
            if kL != 1
                int o = pOff(kL, 0, j)
                int q = pOff(kL, 1, j)
                nL := P1.get(o)
                nB := P1.get(q)
                if nL > 0 and nB > 0
                    pH := float(P1.get(o + 1)) / nL
                    pL := float(P1.get(o + 2)) / nL
                    bH := float(P1.get(q + 1)) / nB
                    bL := float(P1.get(q + 2)) / nB
            if iOdds and not dCmp and not na(s.bx) and nL >= 20 and nB > 0
                string aH = (sig(pH, bH, nL) ? "" : "≈ ") + pct(pH)
                string aL = (sig(pL, bL, nL) ? "" : "≈ ") + pct(pL)
                setTxt(s, bxText(s) + "\nHigh in " + aH + " · Low in " + aL)
            if iZone and not na(s.bx) and not na(s.atr)
                float xz = pctX(hOff(kL, j), -1, ZONEQ)
                if not na(xz)
                    color c = colOf(kL)
                    ZB := box.new(box.get_left(s.bx), s.hi + xz * s.atr, s.pe - tfMs / 2, s.lo - xz * s.atr, xloc = xloc.bar_time, border_color = soft(c, 25), border_style = line.style_dotted, border_width = 1, bgcolor = color.new(c, 100), text = "80% end zone", text_size = szSub, text_color = soft(c, 25), text_halign = text.align_right, text_valign = text.align_bottom)
    // Level tags on the line, right of the last bar (older previous-day levels a little further right, so close ones do not overlap)
    // Levels at (nearly) the same price share one tag, e.g. "NY L · London L"
    array<float> tP = array.new<float>()
    array<label> tL = array.new<label>()
    for v in LV
        int at = -1
        if tP.size() > 0
            for j = 0 to tP.size() - 1
                if at < 0 and math.abs(tP.get(j) - v.price) <= NEAR
                    at := j
        if at >= 0
            label lb = tL.get(at)
            label.set_text(lb, joinTag(label.get_text(lb), v, dN))
            if v.k == 4
                label.set_textcolor(lb, lvCol(v.k, v.isHigh))
        else
            int   sh = v.k == 4 ? math.max(0, dN - v.d - 1) * 8 : 0
            label nl = label.new(time + (3 + sh) * tfMs, v.price, lvTag(v, dN), xloc = xloc.bar_time, style = label.style_label_left, color = chart.bg_color, textcolor = lvCol(v.k, v.isHigh), size = szTag)
            TG.push(nl)
            tP.push(v.price)
            tL.push(nl)
 
// ─── Dashboard ───────────────────────────────────────────────────────────────
string dashP = posOf(iDV, iDH)
// Text sizes of the dashboard: main text and secondary text
string szM   = iDS == "Small" ? size.tiny : iDS == "Large" ? size.normal : size.small
string szS   = iDS == "Small" ? size.tiny : iDS == "Large" ? size.small : size.tiny
var table dash = table.new(dashP, 4, 16, bgcolor = color.new(chart.bg_color, 0), frame_color = color.new(neutralCol, 70), frame_width = 1, border_color = color.new(neutralCol, 90), border_width = 1)
 
if iDash and barstate.isfirst
    if dCmp
        table.merge_cells(dash, 0, 0, 2, 0)
    else
        table.cell(dash, 0, 0, "AE · SESSIONS", text_color = accentCol, text_size = szM, text_halign = text.align_left)
        table.merge_cells(dash, 0, 0, 3, 0)
        if tfOk
            table.merge_cells(dash, 1, 1, 3, 1)
            // Last row: the "collecting data" hint across the full width (rows depend on the settings only)
            int rH = 2 + (iOdds ? 3 : 0) + 1 + (showOf(0) and showOf(2) ? 2 : 0)
            for k = 0 to 3
                if showOf(k)
                    rH += 1
            table.merge_cells(dash, 0, rH, 3, rH)
        else
            table.merge_cells(dash, 0, 1, 3, 1)
 
if iDash and barstate.islast
    if not tfOk
        table.cell(dash, 0, dCmp ? 0 : 1, (dCmp ? "AE · " : "") + "Use a timeframe of 1h or lower.", text_color = dim, text_size = szS, text_halign = text.align_left)
    else
        // Running session (New York, London, Asia, Custom), otherwise the next one to start
        // Countdown from now while the market is closed, otherwise from the current bar (also in Bar Replay)
        int  tN   = histStale ? timenow : math.min(timenow, time + tfMs)
        int  nowK = -1
        int  best = na
        for k in array.from(2, 1, 0, 3)
            if nowK < 0 and S.get(k).active and showOf(k) and not mClosed
                nowK := k
        bool nowA = nowK >= 0
        // Next session: only sessions that trade on this market (a stock chart has no Asia or London session)
        bool anySeen = false
        for k = 0 to 3
            if showOf(k) and S.get(k).seen
                anySeen := true
        if not nowA
            for k = 0 to 3
                if showOf(k) and (S.get(k).seen or not anySeen)
                    int ns = nextStart(k, tN)
                    if not na(ns) and (na(best) or ns < best)
                        best := ns
                        nowK := k
        string run  = nowA ? bar10(float(tN - S.get(nowK).ps) / (S.get(nowK).pe - S.get(nowK).ps)) + " " + dur(S.get(nowK).pe - tN) : ""
        string nxt  = not nowA and nowK >= 0 ? "Next: " + S.get(nowK).name + " in " + dur(best - tN) : "–"
        color  nowC = nowA ? colOf(nowK) : dim
        // New York takes the Asia high or low
        int   n0 = M2.get(0)
        int   n1 = M2.get(2)
        float pc = n0 > 0 ? float(M2.get(1)) / n0 : na
        float pb = n1 > 0 ? float(M2.get(3)) / n1 : na
        [tE, cE2] = cmpTxt(pc, pb, n0)
        // Fewest past sessions among the shown ones: below 20 a hint says the statistics are still filling up
        int nMin = na
        for k = 0 to 3
            // Sessions that cannot be measured on this market (a break inside, e.g. a lunch break) do not hold the hint up
            Ses q = S.get(k)
            if showOf(k) and q.seen and not (q.nFin >= 20 and q.rR.size() == 0)
                nMin := na(nMin) ? q.rR.size() : math.min(nMin, q.rR.size())
        string cTxt = not na(nMin) and nMin < 20 ? "Collecting data · " + str.tostring(nMin) + " of 20 sessions" : ""
        [tH, cH]  = cmpTxt(pH, bH, nL)
        [tL, cL]  = cmpTxt(pL, bL, nL)
        if dCmp
            // Compact layout for phones and small screens: the running session only
            table.clear(dash, 0, 1, 3, 15)
            table.cell(dash, 0, 0, "AE · " + (nowA ? S.get(nowK).tag + " " + run : nxt), text_color = nowC, text_size = szM, text_halign = text.align_left)
            int r = 1
            if iOdds and kL >= 0 and kL != 1
                table.cell(dash, 0, r, "High in", text_color = fg, text_size = szM, text_halign = text.align_left)
                table.cell(dash, 1, r, tH, text_color = cH, text_size = szM, text_halign = text.align_right)
                table.cell(dash, 2, r, "base " + pct(bH), text_color = dim, text_size = szS, text_halign = text.align_left)
                r += 1
                table.cell(dash, 0, r, "Low in", text_color = fg, text_size = szM, text_halign = text.align_left)
                table.cell(dash, 1, r, tL, text_color = cL, text_size = szM, text_halign = text.align_right)
                table.cell(dash, 2, r, "base " + pct(bL), text_color = dim, text_size = szS, text_halign = text.align_left)
                r += 1
            if kL >= 0
                Ses s = S.get(kL)
                table.cell(dash, 0, r, "Size", text_color = fg, text_size = szM, text_halign = text.align_left)
                float rr = na(s.atr) or s.atr <= 0 ? na : (s.hi - s.lo) / s.atr
                table.cell(dash, 1, r, szFmt(rr, s.atr, s.typ) + (szMode == 0 ? UNIT : ""), text_color = fg, text_size = szM, text_halign = text.align_right)
                table.cell(dash, 2, r, szMode == 1 ? "vs average" : "avg " + szFmt(s.typ, s.atr, s.typ), text_color = dim, text_size = szS, text_halign = text.align_left)
                r += 1
            if showOf(0) and showOf(2)
                table.cell(dash, 0, r, "NY takes Asia", text_color = fg, text_size = szM, text_halign = text.align_left)
                table.cell(dash, 1, r, tE, text_color = cE2, text_size = szM, text_halign = text.align_right)
                table.cell(dash, 2, r, "base " + pct(pb), text_color = dim, text_size = szS, text_halign = text.align_left)
                r += 1
            if cTxt != ""
                table.cell(dash, 0, r, "Collecting " + str.tostring(nMin) + "/20", text_color = dim, text_size = szS, text_halign = text.align_left, tooltip = T_CD)
        else
            table.cell(dash, 0, 1, "Now", text_color = fg, text_size = szM, text_halign = text.align_left)
            table.cell(dash, 1, 1, nowA ? S.get(nowK).name + " " + run + " left" : nxt, text_color = nowC, text_size = szM, text_halign = text.align_left)
            int r = 2
            // Live statistics (running session)
            if iOdds
                table.cell(dash, 0, r, "Live" + (kL >= 0 and kL != 1 ? " · " + S.get(kL).tag : ""), text_color = dim, text_size = szS, text_halign = text.align_left, tooltip = T_OD + T_NZ)
                table.cell(dash, 1, r, "chart", text_color = dim, text_size = szS, tooltip = T_OD + T_NZ)
                table.cell(dash, 2, r, "base", text_color = dim, text_size = szS, tooltip = T_OD + T_NZ)
                table.cell(dash, 3, r, "n", text_color = dim, text_size = szS, tooltip = T_OD + T_NZ)
                r += 1
                table.cell(dash, 0, r, "High in", text_color = fg, text_size = szM, text_halign = text.align_left)
                table.cell(dash, 1, r, tH, text_color = cH, text_size = szM, tooltip = T_OD + T_NZ)
                table.cell(dash, 2, r, pct(bH), text_color = dim, text_size = szS)
                table.cell(dash, 3, r, nL > 0 ? str.tostring(nL) : "–", text_color = dim, text_size = szS)
                r += 1
                table.cell(dash, 0, r, "Low in", text_color = fg, text_size = szM, text_halign = text.align_left)
                table.cell(dash, 1, r, tL, text_color = cL, text_size = szM, tooltip = T_OD + T_NZ)
                table.cell(dash, 2, r, pct(bL), text_color = dim, text_size = szS)
                table.cell(dash, 3, r, nL > 0 ? str.tostring(nL) : "–", text_color = dim, text_size = szS)
                r += 1
            // Range block
            table.cell(dash, 0, r, szMode == 1 ? "Size vs average" : szMode == 2 ? "Size (% of ATR)" : "Size" + (na(PIP) ? "" : " (pips)"), text_color = dim, text_size = szS, text_halign = text.align_left, tooltip = T_RG + T_NZ)
            table.cell(dash, 1, r, "latest", text_color = dim, text_size = szS, tooltip = T_RG)
            table.cell(dash, 2, r, szMode == 1 ? "vs other hours" : "avg", text_color = dim, text_size = szS, tooltip = T_RG + T_NZ)
            table.cell(dash, 3, r, szMode == 1 ? "n" : "other hours", text_color = dim, text_size = szS, tooltip = T_RG)
            r += 1
            for k = 0 to 3
                if showOf(k)
                    Ses   s   = S.get(k)
                    float mR  = med(s.rR)
                    float mB  = med(s.rB)
                    bool  sg  = medSig(s.rR, mB)
                    // Latest in shares of the daily ATR; in % vs average the finished session uses the average from before it
                    float lat = s.active ? (na(s.atr) or s.atr <= 0 ? na : (s.hi - s.lo) / s.atr) : s.lOk ? s.lR : na
                    string tl = szMode == 1 and not s.active ? dSigned(s.lX) : szFmt(lat, s.atr, s.typ)
                    // % vs average: the average of this session compared with the other hours; otherwise average and other hours in the unit
                    string t2 = szMode == 1 ? (na(mR) or na(mB) or mB <= 0 ? "–" : dSigned(mR / mB)) : szFmt(mR, dAtr, mR)
                    string t3 = szMode == 1 ? str.tostring(s.rR.size()) : szFmt(mB, dAtr, mR)
                    table.cell(dash, 0, r, s.name, text_color = colOf(k), text_size = szM, text_halign = text.align_left)
                    table.cell(dash, 1, r, tl, text_color = fg, text_size = szM, tooltip = T_RG)
                    table.cell(dash, 2, r, na(mR) ? "–" : (sg ? "" : "≈ ") + t2, text_color = sg ? fg : dim, text_size = szM, tooltip = "Median of " + str.tostring(s.rR.size()) + " sessions on this chart against " + str.tostring(s.rB.size()) + " windows of the same length at other hours." + T_NZ)
                    table.cell(dash, 3, r, t3, text_color = dim, text_size = szS)
                    r += 1
            // New York takes the Asia high or low
            if showOf(0) and showOf(2)
                table.cell(dash, 0, r, "NY takes Asia", text_color = dim, text_size = szS, text_halign = text.align_left, tooltip = T_TA + T_NZ)
                table.cell(dash, 1, r, "chart", text_color = dim, text_size = szS, tooltip = T_TA + T_NZ)
                table.cell(dash, 2, r, "base", text_color = dim, text_size = szS, tooltip = T_TA)
                table.cell(dash, 3, r, "n", text_color = dim, text_size = szS, tooltip = T_TA)
                r += 1
                table.cell(dash, 0, r, "High or low", text_color = fg, text_size = szM, text_halign = text.align_left)
                table.cell(dash, 1, r, tE, text_color = cE2, text_size = szM, tooltip = T_TA + T_NZ)
                table.cell(dash, 2, r, pct(pb), text_color = dim, text_size = szS, tooltip = T_TA)
                table.cell(dash, 3, r, str.tostring(n0), text_color = dim, text_size = szS)
                r += 1
            if cTxt != ""
                table.cell(dash, 0, r, cTxt, text_color = dim, text_size = szS, text_halign = text.align_left, tooltip = T_CD)
            else
                table.clear(dash, 0, r, 3, r)

← 返回列表