Power of Three Map [JOAT]

officialjackofalltrades · study · 942 行 · 点赞 124 · TradingView 原页

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

Pine Script

//@version=6
indicator("Power of Three Map [JOAT]", "PO3 [JOAT]", overlay = true, max_boxes_count = 500, max_lines_count = 500,
     max_labels_count = 500)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 0. SAFETY
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// a drawing anchored far back needs the bar times that far back; a Basic account holds 5,000 bars
max_bars_back(time, 5000)
// Scale anchor: one invisible plot pins a drawing-heavy script to the price scale.
plot(close, "Scale anchor (invisible)", color = color.new(#000000, 100), display = display.pane, editable = false)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 1. INPUTS
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
const string G_SES = "Sessions"
string tzIn    = input.string("America/New_York", "Time zone", group = G_SES,
     options = ["America/New_York", "America/Chicago", "America/Los_Angeles", "Europe/London", "Europe/Berlin", "Asia/Tokyo", "Asia/Hong_Kong", "Australia/Sydney", "UTC", "Exchange"],
     tooltip = "Every window, open and day boundary is read in this time zone, with its own daylight-saving rules. Power of Three is defined in New York time: the day starts at 00:00 New York (the true day open). Exchange = the symbol's own time zone.")
string asiaWin = input.session("2000-0000", "Asia (accumulation)", group = G_SES,
     tooltip = "The Asia range that the day's Judas swing is measured against. The default 20:00-00:00 is the evening BEFORE the day it belongs to, so it ends at the midnight open.")
string lonWin  = input.session("0200-0500", "London (manipulation)", group = G_SES,
     tooltip = "The window in which the Judas swing is looked for: the first trade beyond the Asia high or low inside it. If London never leaves the Asia range, the dashboard reads 'no Judas'.")
string nyWin   = input.session("0830-1600", "New York (distribution)", group = G_SES,
     tooltip = "The window of the day's expansion. The distribution box spans it.")
 
const string G_PH = "Phases on price"
bool showAcc  = input.bool(true, "Accumulation box (Asia range)", group = G_PH,
     tooltip = "The Asia range as a silver box with a filled tag 'ACC · 18.4 pts · 0.6 ATR' above it (below it when the Judas went up). The Asia range that is forming tonight for tomorrow is drawn live too.")
bool showMan  = input.bool(true, "Manipulation box (Judas swing)", group = G_PH,
     tooltip = "From the first London bar beyond the Asia range to the end of London, boxed from the Asia edge to the swing extreme. A filled X sits at the extreme with 'MANIP · swept Asia low by 4.2' next to it. A sweep of the Asia low is drawn in the bull colour, a sweep of the high in the bear colour.")
bool showDist = input.bool(true, "Distribution box (New York expansion)", group = G_PH,
     tooltip = "Over the New York window, from the manipulation extreme to the day's extreme in the bias direction (close vs midnight open). When the Judas went the same way as the day, the box starts at the midnight open instead. Tag: 'DIST · +62.0 from midnight open' = the day extreme minus the midnight open.")
int  oldDays  = input.int(3, "Older days (faded, no tags)", minval = 0, maxval = 5, group = G_PH,
     tooltip = "Days before yesterday keep only their Asia and Judas boxes, faded, with no text. Today and yesterday are fully drawn.")
 
const string G_OP = "Opens"
bool  showMO   = input.bool(true, "Midnight open (true day open, bold)", group = G_OP,
     tooltip = "The open of the first bar of the New York day. A day whose first bar opens more than an hour after midnight (stocks, the Sunday futures open) has no midnight open and no Po3.")
bool  show830  = input.bool(true, "08:30 open", group = G_OP)
bool  show930  = input.bool(true, "09:30 open", group = G_OP,
     tooltip = "On 15m and lower an open prints on the bar that contains that minute. Above 15m it prints only on a bar that starts exactly at that minute.")
bool  showWO   = input.bool(true, "Weekly open", group = G_OP,
     tooltip = "The open of the first bar of the exchange week (18:00 Sunday New York for CME futures), drawn as a dotted line.")
float woWithin = input.float(2.0, "Weekly open drawn within (day ATR)", minval = 0.5, maxval = 20.0, step = 0.5, group = G_OP,
     tooltip = "The weekly open is skipped when it is farther than this many daily ATR from the close, so a far level never squashes the candles.")
 
const string G_PC = "Po3 candle (right of price)"
bool showPc   = input.bool(true, "Today's Po3 candle", group = G_PC,
     tooltip = "Today's daily candle (midnight open to now) drawn large right of the last bar, in the bull colour when the close is at or above the midnight open. O / H / L / C sit in the tag column to its right.")
int  pcOff    = input.int(10, "Starts N bars after the last bar", minval = 8, maxval = 60, group = G_PC)
int  pcW      = input.int(8, "Width (bars)", minval = 4, maxval = 30, group = G_PC,
     tooltip = "Keep the chart's right margin at about Start + Width + 22 bars (40 at the defaults) so the tag column stays on screen.")
bool showYc   = input.bool(true, "Yesterday's candle (smaller, to its left)", group = G_PC)
bool showBand = input.bool(true, "Asia band on the candle's left", group = G_PC,
     tooltip = "A thin silver band beside the candle spanning the Asia high to low: where the day accumulated relative to its full range.")
bool showTick = input.bool(true, "Judas tick on the candle", group = G_PC,
     tooltip = "A short dashed line across the candle at the Judas extreme, in the sweep colour.")
 
const string G_PD = "Premium / Discount (day range)"
bool showPD  = input.bool(true, "Premium / discount gradient", group = G_PD,
     tooltip = "The day's range since midnight split at its mid (EQ): premium above in the bear colour, discount below in the bull colour, strongest toward the high and the low. Tags 'Premium', 'EQ' and 'Discount' sit in the tag column once the range is wide enough to hold them.")
int  pdStops = input.int(6, "Gradient stops", minval = 2, maxval = 12, group = G_PD)
 
const string G_TH = "Theme"
string theme   = input.string("Royal Gold", "Palette", group = G_TH,
     options = ["Royal Gold", "Mystic", "Emerald Ruby", "Ice Magenta", "Aqua Ember", "Ocean Amber", "Sakura Teal", "Aurora", "Mono", "Custom"],
     tooltip = "Royal Gold is this indicator's own palette. Every JOAT jewel palette is offered, plus Mono (clean black / white) and Custom (the pickers below). Lines and plain text deepen automatically on a light chart.")
color cBullIn  = input.color(#FFC233, "Custom bull / bear", group = G_TH, inline = "c1")
color cBearIn  = input.color(#8A5CFF, "", group = G_TH, inline = "c1")
color cBgIn    = input.color(#1C1433, "Custom panel / frame / highlight", group = G_TH, inline = "c2")
color cFrIn    = input.color(#2C2150, "", group = G_TH, inline = "c2")
color cHlIn    = input.color(#FFE08A, "", group = G_TH, inline = "c2")
bool  paintBar = input.bool(true, "Paint candles by day bias", group = G_TH,
     tooltip = "Bull colour while the close is at or above the day's midnight open, bear colour below it. Each bar is painted against its own day's midnight open, so history never changes.")
float gapK     = input.float(0.045, "Tag gap (share of displayed span)", minval = 0.02, maxval = 0.12, step = 0.005, group = G_TH,
     tooltip = "Minimum vertical distance between tags in the right-hand column, as a share of the displayed price span (visible bars plus everything drawn). Tags that would touch are pushed apart in price order, each with a thin leader back to its level.")
 
const string G_DB = "Dashboard"
bool   showDash  = input.bool(true, "Show dashboard", group = G_DB)
string dashPos   = input.string("Top Right", "Position", group = G_DB,
     options = ["Top Right", "Top Left", "Top Center", "Middle Right", "Middle Left", "Middle Center", "Bottom Right", "Bottom Left", "Bottom Center"])
string dashSize  = input.string("Small", "Text size", options = ["Small", "Normal", "Large"], group = G_DB)
int    dashTrans = input.int(15, "Background transparency", minval = 0, maxval = 75, group = G_DB)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 2. CONSTANTS AND PALETTE
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
const int   PAST_MAX = 4990      // furthest back a drawing starts
const int   FUT_MAX  = 490       // furthest ahead a drawing reaches
const int   DAY_KEEP = 30        // day records kept (14 for ATR, 10 for the average range, 5 drawn)
const color TR       = #00000000
const color C_TXT    = #FFFFFF
color C_TXT_M = color.new(#A8B0BD, 10)
color C_NEU   = color.new(#F0F8FF, 30)
string tzUse  = tzIn == "Exchange" ? syminfo.timezone : tzIn
 
light = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color) > 140
 
color P_BULL = switch theme
    "Mystic"       => #00CED1
    "Emerald Ruby" => #00C896
    "Ice Magenta"  => #00B7FF
    "Aqua Ember"   => #00E5C0
    "Ocean Amber"  => #00A8E8
    "Sakura Teal"  => #2EC4B6
    "Aurora"       => #00F5A0
    "Mono"         => light ? #2B2B2B : #E6E6E6
    "Custom"       => cBullIn
    => #FFC233
color P_BEAR = switch theme
    "Mystic"       => #9400D3
    "Emerald Ruby" => #E0115F
    "Ice Magenta"  => #FF2EA6
    "Aqua Ember"   => #FF8C1A
    "Ocean Amber"  => #FFB000
    "Sakura Teal"  => #FF6B9D
    "Aurora"       => #7B2FF7
    "Mono"         => #7A7A7A
    "Custom"       => cBearIn
    => #8A5CFF
color P_BG = switch theme
    "Mystic"       => #191970
    "Emerald Ruby" => #0B2A26
    "Ice Magenta"  => #1A1035
    "Aqua Ember"   => #0F2230
    "Ocean Amber"  => #0A1F33
    "Sakura Teal"  => #1B1530
    "Aurora"       => #120D2B
    "Mono"         => #111111
    "Custom"       => cBgIn
    => #1C1433
color P_FRAME = switch theme
    "Mystic"       => #241A3A
    "Emerald Ruby" => #123D36
    "Ice Magenta"  => #2A1A50
    "Aqua Ember"   => #1B3448
    "Ocean Amber"  => #15324F
    "Sakura Teal"  => #2C2248
    "Aurora"       => #221A45
    "Mono"         => #2E2E2E
    "Custom"       => cFrIn
    => #2C2150
color P_HL = switch theme
    "Mystic"       => #B39DDB
    "Emerald Ruby" => #7FFFD4
    "Ice Magenta"  => #C77DFF
    "Aqua Ember"   => #FFD2A1
    "Ocean Amber"  => #7FD8FF
    "Sakura Teal"  => #FFC2D6
    "Aurora"       => #B8F5DC
    "Mono"         => #D9D9D9
    "Custom"       => cHlIn
    => #FFE08A
 
// deep: a darker shade for thin lines and plain text on a light chart (fills keep the palette)
deep(color c) =>
    color.rgb(color.r(c) * 0.62, color.g(c) * 0.62, color.b(c) * 0.62)
// relative luminance (WCAG) to pick white or dark text on a filled tag
chan(float v) =>
    u = v / 255.0
    u <= 0.03928 ? u / 12.92 : math.pow((u + 0.055) / 1.055, 2.4)
lum(color c) =>
    0.2126 * chan(color.r(c)) + 0.7152 * chan(color.g(c)) + 0.0722 * chan(color.b(c))
onFill(color c) =>
    lum(c) > 0.5 ? #14101F : #FFFFFF
 
color I_BULL = light ? deep(P_BULL) : P_BULL      // chart lines / plain text
color I_BEAR = light ? deep(P_BEAR) : P_BEAR
color I_HL   = light ? deep(P_HL) : P_HL
color I_MUT  = light ? #6A6D78 : #A8B0BD
color C_ACC  = light ? #8C92A0 : #C9CED8          // accumulation (Asia) silver
color C_OTAG = color.from_gradient(0.3, 0.0, 1.0, P_FRAME, P_BEAR)   // 08:30 / 09:30 / weekly tag fill
color D_BULL = theme == "Mono" ? #E6E6E6 : P_BULL // dashboard values sit on the dark panel on every chart
color D_BEAR = P_BEAR
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 3. HELPERS: clamps, text, table
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// nothing anchored more than 4,990 bars back, nothing drawn more than 490 bars ahead
f_xo(int b) =>
    math.max(b, bar_index - PAST_MAX)
f_xr(int b) =>
    math.min(b, bar_index + FUT_MAX)
 
// f_px: price with thousands separators at mintick precision: 24,550.25  /  1.08432
f_px(float p) =>
    string out = "—"
    if not na(p)
        string s = str.tostring(math.abs(p), format.mintick)
        array<string> parts = str.split(s, ".")
        string ip = array.get(parts, 0)
        string fp = ""
        if array.size(parts) > 1
            fp := "." + array.get(parts, 1)
        string g = ""
        int n = str.length(ip)
        if n > 0
            for i = 0 to n - 1
                g += str.substring(ip, i, i + 1)
                int rem = n - 1 - i
                if rem > 0 and rem % 3 == 0
                    g += ","
        out := (p < 0 ? "-" : "") + g + fp
    out
 
// f_val: an unsigned distance in points (pips on forex), no unit: "18.4". Decimals follow the tick size and the
// price: 1-point ticks whole, quarter ticks up to 2 decimals, prices of 100+ one decimal, smaller prices more.
f_val(float v) =>
    string s = "—"
    if not na(v)
        float a = math.abs(v)
        if syminfo.type == "forex"
            s := str.tostring(a / (syminfo.mintick * 10.0), "0.0")
        else if syminfo.mintick >= 1.0
            s := str.tostring(a, "0")
        else if syminfo.mintick >= 0.1
            s := str.tostring(a, "0.0#")
        else if close >= 100
            s := str.tostring(a, "0.0")
        else if close >= 1
            s := str.tostring(a, "0.00")
        else
            s := str.tostring(a, format.mintick)
    s
f_unit() =>
    syminfo.type == "forex" ? " pips" : " pts"
f_pts(float v) =>
    f_val(v) + f_unit()
f_sgn(float v) =>
    (v >= 0 ? "+" : "-") + f_val(v)
// f_atr: "0.6 ATR" (empty when the day ATR is not known yet)
f_atr(float v, float a) =>
    na(v) or na(a) or a <= 0 ? "" : str.tostring(math.abs(v) / a, "0.0") + " ATR"
f_two(int v) =>
    (v < 10 ? "0" : "") + str.tostring(v)
f_hm(int t) =>
    na(t) ? "—" : f_two(hour(t, tzUse)) + ":" + f_two(minute(t, tzUse))
 
f_pos(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Middle Right"  => position.middle_right
        "Middle Left"   => position.middle_left
        "Middle Center" => position.middle_center
        "Bottom Right"  => position.bottom_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        => position.top_right
f_size(string s) =>
    switch s
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
// row background: transparency fades a little down the rows
f_grad(color base, int row, int rows, int minT, int maxT) =>
    float t = rows <= 1 ? float(minT) : float(minT) + float(maxT - minT) * (float(row) / float(rows - 1))
    color.new(base, int(math.min(100.0, t)))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4. SESSION CLOCK (0 request.* calls)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
bool   intra  = timeframe.isintraday
float  tfSec  = timeframe.in_seconds()
bool   po3Ok  = intra and tfSec <= 900
float  tfMin  = tfSec / 60.0
int    tod    = hour(time, tzUse) * 60 + minute(time, tzUse)
int    todP   = hour(nz(time[1], time), tzUse) * 60 + minute(nz(time[1], time), tzUse)
int    dKey   = year(time, tzUse) * 10000 + month(time, tzUse) * 100 + dayofmonth(time, tzUse)
bool   newDay = na(dKey[1]) or dKey != dKey[1]
bool   rawAsia = not na(time(timeframe.period, asiaWin, tzUse))
bool   rawLon  = not na(time(timeframe.period, lonWin, tzUse))
bool   rawNy   = not na(time(timeframe.period, nyWin, tzUse))
bool   inAsia = po3Ok and rawAsia
bool   inLon  = po3Ok and rawLon
bool   inNy   = po3Ok and rawNy
bool   newWeek = ta.change(time("W")) != 0
 
// f_hit: does this bar print the open of minute m? On 15m and lower: the bar that contains m, or the first bar after
// a gap that skipped it. Above 15m: only a bar that starts exactly at m.
f_hit(int m) =>
    bool inside = (m >= tod and m < tod + tfMin) or (m + 1440 >= tod and m + 1440 < tod + tfMin)
    bool gapped = not newDay and todP < m and tod > m
    po3Ok ? (inside or gapped) : tod == m
 
// Asia tracker: the latest run of the Asia window (a run that starts after a gap of 4 hours or more is a new run)
var int   trT0 = na
var int   trB0 = na
var int   trB1 = na
var float trHi = na
var float trLo = na
bool asiaNew = inAsia and (not inAsia[1] or time - nz(time[1], time) > 14400000)
if asiaNew
    trT0 := time
    trB0 := bar_index
    trB1 := bar_index
    trHi := high
    trLo := low
else if inAsia and not na(trT0)
    trB1 := bar_index
    trHi := math.max(trHi, high)
    trLo := math.min(trLo, low)
 
// Weekly open (exchange week)
var float wOpen = na
var int   wBar  = na
if newWeek and not timeframe.isweekly and not timeframe.ismonthly
    wOpen := open
    wBar  := bar_index
 
// Visible range: part of the displayed span that sets the tag gap
var float visHi = na
var float visLo = na
if time >= chart.left_visible_bar_time
    visHi := na(visHi) ? high : math.max(visHi, high)
    visLo := na(visLo) ? low : math.min(visLo, low)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 5. DAY RECORDS: one per New York day, newest last
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
type Po3Day
    int   key
    int   t0                // first bar time / bar index
    int   b0
    int   bEnd              // last bar so far
    int   tEnd
    float mo                // midnight open (na when the day's first bar opens more than an hour after 00:00)
    float o                 // first open
    float hi
    float lo
    float cl
    bool  trunc  = false    // the chart's first, cut-off day
    float dAtr              // day ATR known at this day's start (last <= 14 complete days)
    float avgR              // average day range known at this day's start (last <= 10 complete days)
    int   nA     = 0        // complete days behind dAtr / avgR
    int   nR     = 0
    float pdh               // previous complete day's high / low
    float pdl
    float aHi               // Asia (accumulation)
    float aLo
    int   aB0
    int   aB1
    int   aT0
    float lHi               // London
    float lLo
    int   lB0
    int   lB1
    int   jSide  = 0        // Judas: +1 swept the Asia high, -1 swept the Asia low, 0 none
    int   jBar
    int   jT
    float jExt
    int   jExtBar
    int   jExtT
    int   nB0               // New York
    int   nB1
    float o830
    int   b830
    float o930
    int   b930
    bool  aHiT   = false    // taken after their session closed
    bool  aLoT   = false
    bool  lHiT   = false
    bool  lLoT   = false
    bool  pdhT   = false
    bool  pdlT   = false
 
var array<Po3Day> days = array.new<Po3Day>()
 
// a complete day: not the chart's cut-off first day and at least 6 hours of bars (drops the Sunday futures stub)
f_full(Po3Day d) =>
    not d.trunc and (d.tEnd - d.t0) >= 21600000
 
// newest complete day at or before index `from` (-1 if none)
f_lastFull(int from) =>
    int idx = -1
    if from >= 0
        for i = from to 0
            if f_full(days.get(i))
                idx := i
                break
    idx
 
// day ATR (true range, up to 14 complete days) and average range (up to 10 complete days) from the records
f_stats() =>
    float trSum = 0.0
    int   trN   = 0
    float rSum  = 0.0
    int   rN    = 0
    int   n     = days.size()
    if n > 0
        for i = n - 1 to 0
            Po3Day d = days.get(i)
            if f_full(d)
                float pc = na
                if i > 0
                    for j = i - 1 to 0
                        Po3Day p = days.get(j)
                        if f_full(p)
                            pc := p.cl
                            break
                float tr = na(pc) ? d.hi - d.lo : math.max(d.hi, pc) - math.min(d.lo, pc)
                if trN < 14
                    trSum += tr
                    trN   += 1
                if rN < 10
                    rSum += d.hi - d.lo
                    rN   += 1
            if trN >= 14 and rN >= 10
                break
    [trN > 0 ? trSum / trN : na, rN > 0 ? rSum / rN : na, trN, rN]
 
// new day: open a record (guarded so a realtime re-run of the same bar never adds a second one)
if intra and newDay and (days.size() == 0 or days.last().key != dKey)
    [sAtr, sRng, sA, sN] = f_stats()
    int    li = f_lastFull(days.size() - 1)
    Po3Day nd = Po3Day.new()
    nd.key   := dKey
    nd.t0    := time
    nd.b0    := bar_index
    nd.bEnd  := bar_index
    nd.tEnd  := time
    nd.o     := open
    nd.mo    := tod < 60 ? open : na
    nd.hi    := high
    nd.lo    := low
    nd.cl    := close
    nd.trunc := days.size() == 0
    nd.dAtr  := sAtr
    nd.avgR  := sRng
    nd.nA    := sA
    nd.nR    := sN
    if li >= 0
        nd.pdh := days.get(li).hi
        nd.pdl := days.get(li).lo
    // the Asia run that started in the 12 hours before this midnight (or on this bar) belongs to this day
    if po3Ok and not na(trT0) and trT0 >= time - 43200000 and trT0 <= time
        nd.aHi := trHi
        nd.aLo := trLo
        nd.aB0 := trB0
        nd.aB1 := trB1
        nd.aT0 := trT0
    days.push(nd)
    if days.size() > DAY_KEEP
        days.shift()
 
// every bar: update today's record (max / min / overwrite only, so a realtime re-run is harmless)
if intra and days.size() > 0
    Po3Day d = days.last()
    if high > d.hi
        d.hi := high
    if low < d.lo
        d.lo := low
    d.cl   := close
    d.bEnd := bar_index
    d.tEnd := time
    if na(d.o830) and f_hit(510)
        d.o830 := open
        d.b830 := bar_index
    if na(d.o930) and f_hit(570)
        d.o930 := open
        d.b930 := bar_index
    if po3Ok
        // Asia: a window running past midnight keeps growing; a window that starts after midnight is adopted if it
        // begins in the first 12 hours of the day, before London
        bool asiaMine = inAsia and not na(d.aT0) and trT0 == d.aT0
        if asiaMine
            d.aHi := trHi
            d.aLo := trLo
            d.aB1 := trB1
        else if asiaNew and na(d.aT0) and na(d.lB0) and time - d.t0 < 43200000
            d.aHi := trHi
            d.aLo := trLo
            d.aB0 := trB0
            d.aB1 := trB1
            d.aT0 := trT0
            asiaMine := true
        // London and the Judas swing: the first trade beyond the Asia range; its extreme follows London
        if inLon
            if na(d.lB0)
                d.lB0 := bar_index
                d.lHi := high
                d.lLo := low
            else
                d.lHi := math.max(d.lHi, high)
                d.lLo := math.min(d.lLo, low)
            d.lB1 := bar_index
            if not na(d.aHi) and not asiaMine
                if d.jSide == 0
                    bool upX = high > d.aHi
                    bool dnX = low < d.aLo
                    if upX or dnX
                        // one bar through both sides: an up-close bar took the low first, a down-close bar the high
                        int side = upX and dnX ? (close >= open ? -1 : 1) : upX ? 1 : -1
                        d.jSide   := side
                        d.jBar    := bar_index
                        d.jT      := time
                        d.jExt    := side == 1 ? high : low
                        d.jExtBar := bar_index
                        d.jExtT   := time
                else if d.jSide == 1 and high > d.jExt
                    d.jExt    := high
                    d.jExtBar := bar_index
                    d.jExtT   := time
                else if d.jSide == -1 and low < d.jExt
                    d.jExt    := low
                    d.jExtBar := bar_index
                    d.jExtT   := time
        // New York
        if inNy
            if na(d.nB0)
                d.nB0 := bar_index
            d.nB1 := bar_index
        // session highs / lows taken after their session closed, and the previous day's
        if not na(d.aHi) and not asiaMine and bar_index > d.aB1
            if high > d.aHi
                d.aHiT := true
            if low < d.aLo
                d.aLoT := true
        if not na(d.lB1) and not inLon and bar_index > d.lB1
            if high > d.lHi
                d.lHiT := true
            if low < d.lLo
                d.lLoT := true
        if not na(d.pdh) and high > d.pdh
            d.pdhT := true
        if not na(d.pdl) and low < d.pdl
            d.pdlT := true
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 6. CANDLE PAINT AND ALERTS (plots: anchor 1 + barcolor 1 + alertcondition 2 = 4)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
float curMo = intra and days.size() > 0 ? days.last().mo : na
barcolor(paintBar and not na(curMo) ? (close >= curMo ? P_BULL : P_BEAR) : na, editable = false)
 
bool judasNow = po3Ok and days.size() > 0 and days.last().jBar == bar_index
bool moCross  = not na(curMo) and not newDay and ((close >= curMo and close[1] < curMo) or (close < curMo and close[1] >= curMo))
alertcondition(judasNow, "Judas swing printed", "PO3 [JOAT]: London traded beyond the Asia range on {{ticker}} {{interval}}")
alertcondition(moCross, "Midnight open crossed", "PO3 [JOAT]: price crossed the midnight open on {{ticker}} {{interval}}")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 7. DRAWING KIT: registries rebuilt on the last bar, the tag column and its lane register
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
var array<line>   lns  = array.new<line>()
var array<label>  lbls = array.new<label>()
var array<box>    bxs  = array.new<box>()
// tag column entries: level price, text, fill (na = plain text), text colour, leader colour, tooltip
var array<float>  cP   = array.new<float>()
var array<string> cT   = array.new<string>()
var array<color>  cF   = array.new<color>()
var array<color>  cC   = array.new<color>()
var array<color>  cL   = array.new<color>()
var array<string> cTip = array.new<string>()
var array<int>    cX   = array.new<int>()      // bar where the tag's leader starts
 
clearAll() =>
    for l in lns
        l.delete()
    lns.clear()
    for l in lbls
        l.delete()
    lbls.clear()
    for b in bxs
        b.delete()
    bxs.clear()
    cP.clear()
    cT.clear()
    cF.clear()
    cC.clear()
    cL.clear()
    cTip.clear()
    cX.clear()
 
addTag(float p, int lx, string t, color f, color tc, color lc, string tip) =>
    cX.push(lx)
    cP.push(p)
    cT.push(t)
    cF.push(f)
    cC.push(tc)
    cL.push(lc)
    cTip.push(tip)
 
// f_lanes: least-squares placement of sorted levels with a minimum gap. Levels that would touch merge into a cluster
// that is centred on its members' own prices, so every tag stays as close to its level as the gap allows.
f_lanes(array<float> t, float gap) =>
    int m = t.size()
    array<float> out = array.new<float>(m, 0.0)
    array<int>   cS  = array.new<int>()
    array<int>   cN  = array.new<int>()
    array<float> cB  = array.new<float>()
    if m > 0
        for i = 0 to m - 1
            cS.push(i)
            cN.push(1)
            cB.push(t.get(i))
            while cS.size() > 1
                int   k       = cS.size() - 1
                float topPrev = cB.get(k - 1) + (cN.get(k - 1) - 1) * gap
                if topPrev + gap <= cB.get(k)
                    break
                int   s   = cS.get(k - 1)
                int   nn  = cN.get(k - 1) + cN.get(k)
                float tot = 0.0
                for j = 0 to nn - 1
                    tot += t.get(s + j) - j * gap
                cB.set(k - 1, tot / nn)
                cN.set(k - 1, nn)
                cS.pop()
                cN.pop()
                cB.pop()
        for k = 0 to cS.size() - 1
            for j = 0 to cN.get(k) - 1
                out.set(cS.get(k) + j, cB.get(k) + j * gap)
    out
 
// drawDay: the Po3 boxes of one day. full = today / yesterday (tags, X, distribution); otherwise faded Asia and Judas
// boxes only.
drawDay(Po3Day d, bool full, float gap) =>
    int lim = bar_index - PAST_MAX
    // ACCUMULATION
    if showAcc and not na(d.aHi) and d.aB1 >= lim
        int x0 = f_xo(d.aB0)
        int x1 = math.max(d.aB1, x0 + 1)
        bxs.push(box.new(x0, d.aHi, x1, d.aLo, border_color = color.new(C_ACC, full ? 45 : 80), border_width = 1,
             bgcolor = color.new(C_ACC, full ? 85 : 93)))
        if full
            float  rg    = d.aHi - d.aLo
            string at    = f_atr(rg, d.dAtr)
            bool   below = d.jSide == 1
            lbls.push(label.new(x0, below ? d.aLo : d.aHi, "ACC · " + f_pts(rg) + (at == "" ? "" : " · " + at),
                 color = color.new(C_ACC, 20), textcolor = onFill(C_ACC), size = size.small, text_formatting = text.format_bold,
                 style = below ? label.style_label_upper_left : label.style_label_lower_left,
                 tooltip = "Accumulation: the Asia range from " + f_hm(d.aT0) + "\nHigh " + f_px(d.aHi) + " · Low " + f_px(d.aLo) + "\nRange " + f_pts(rg) + (at == "" ? " (day ATR needs one complete day)" : " = " + at + " (day ATR " + f_pts(d.dAtr) + ")")))
    // MANIPULATION (Judas swing)
    if showMan and d.jSide != 0 and not na(d.aHi) and not na(d.lB1) and d.lB1 >= lim
        bool  up   = d.jSide == 1
        float edge = up ? d.aHi : d.aLo
        color c    = up ? P_BEAR : P_BULL
        int   x0   = f_xo(d.jBar)
        int   x1   = math.max(d.lB1, x0 + 1)
        bxs.push(box.new(x0, math.max(edge, d.jExt), x1, math.min(edge, d.jExt), border_color = color.new(c, full ? 40 : 75),
             border_width = 1, bgcolor = color.new(c, full ? 80 : 92)))
        if full
            int    xe  = f_xo(d.jExtBar)
            string tip = "Manipulation: London's first move beyond the Asia " + (up ? "high " : "low ") + f_px(edge) + " began at " + f_hm(d.jT) + "\nExtreme" + f_px(d.jExt) + " at " + f_hm(d.jExtT) + ", " + f_pts(d.jExt - edge) + (up ? " above" : " below") + " the Asia " + (up ? "high" : "low")
            lbls.push(label.new(xe, d.jExt, "X", color = c, textcolor = onFill(c), size = size.small, text_formatting = text.format_bold,
                 style = up ? label.style_label_down : label.style_label_up, tooltip = tip))
            lbls.push(label.new(xe, up ? d.jExt + gap : d.jExt - gap, "MANIP · swept Asia " + (up ? "high" : "low") + " by " + f_val(d.jExt - edge),
                 color = color.new(c, 15), textcolor = onFill(c), size = size.small, text_formatting = text.format_bold,
                 style = up ? label.style_label_lower_left : label.style_label_upper_left, tooltip = tip))
    // DISTRIBUTION (today and yesterday only)
    if full and showDist and not na(d.nB0) and not na(d.mo) and d.nB1 >= lim
        int   dir  = d.cl >= d.mo ? 1 : -1
        float ext  = dir == 1 ? d.hi : d.lo
        bool  opp  = d.jSide == -dir
        float base = opp ? d.jExt : d.mo
        color c    = dir == 1 ? P_BULL : P_BEAR
        int   x0   = f_xo(d.nB0)
        int   x1   = math.max(d.nB1, x0 + 1)
        bxs.push(box.new(x0, math.max(ext, base), x1, math.min(ext, base), border_color = color.new(c, 45), border_width = 1,
             bgcolor = color.new(c, 85)))
        // a same-side Judas has its own tag near the extreme: keep the two apart
        float ty = ext
        if d.jSide == dir
            ty := dir == 1 ? math.max(ext, d.jExt + 2.2 * gap) : math.min(ext, d.jExt - 2.2 * gap)
        lbls.push(label.new(x0, ty, "DIST · " + f_sgn(ext - d.mo) + " from midnight open",
             color = color.new(c, 15), textcolor = onFill(c), size = size.small, text_formatting = text.format_bold,
             style = dir == 1 ? label.style_label_lower_left : label.style_label_upper_left,
             tooltip = "Distribution: the New York expansion " + (dir == 1 ? "up" : "down") + " from the " + (opp ? "manipulation extreme " + f_px(base) : "midnight open " + f_px(base)) + " to the day " + (dir == 1 ? "high " : "low ") + f_px(ext) + "\nDay extreme vs midnight open " + f_px(d.mo) + ": " + f_sgn(ext - d.mo) + f_unit()))
 
// f_score: Po3 score 0-100 = four parts of 25
f_score(Po3Day d) =>
    int   dir = d.cl >= d.mo ? 1 : -1
    float s1  = d.jSide != 0 ? 25.0 : 0.0
    float s2  = d.jSide == -dir ? 25.0 : 0.0
    float ex  = dir == 1 ? d.hi - d.mo : d.mo - d.lo
    float s3  = na(d.avgR) or d.avgR <= 0 ? 0.0 : math.min(math.max(ex, 0.0) / (0.5 * d.avgR), 1.0) * 25.0
    float s4  = na(d.aHi) ? 0.0 : (dir == 1 ? d.cl > d.aHi : d.cl < d.aLo) ? 25.0 : 0.0
    [s1, s2, s3, s4]
 
// f_taken: "Asia H/L · Lon H · PDH"
f_taken(Po3Day d) =>
    array<string> parts = array.new<string>()
    if d.aHiT or d.aLoT
        parts.push("Asia " + (d.aHiT and d.aLoT ? "H/L" : d.aHiT ? "H" : "L"))
    if d.lHiT or d.lLoT
        parts.push("Lon " + (d.lHiT and d.lLoT ? "H/L" : d.lHiT ? "H" : "L"))
    if d.pdhT or d.pdlT
        parts.push(d.pdhT and d.pdlT ? "PDH/L" : d.pdhT ? "PDH" : "PDL")
    parts.size() == 0 ? "none yet" : parts.join(" · ")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 8. RENDER (last bar): phases, opens, premium / discount, Po3 candle, tag column
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
if barstate.islast
    clearAll()
    int    n     = days.size()
    Po3Day td    = n > 0 ? days.last() : na
    int    ydI   = n > 1 ? f_lastFull(n - 2) : -1
    Po3Day yd    = ydI >= 0 ? days.get(ydI) : na
    bool   hasTd = not na(td)
    bool   tdMo  = hasTd and not na(td.mo)
    bool   candleOn = po3Ok and showPc and tdMo
    bool   ydOn  = candleOn and showYc and not na(yd)
    int    xL    = bar_index + pcOff
    int    xR    = xL + pcW
    int    xC    = xL + int(pcW / 2)
    int    colX  = f_xr(candleOn ? xR + 2 : bar_index + 3)
    int    lineEnd = candleOn ? bar_index + 1 : colX
    int    zoneEnd = candleOn ? xR : bar_index + 2
    int    leadX = candleOn ? xR : colX - 1
 
    // 8a. tag column: opens
    if hasTd and showMO and tdMo
        lns.push(line.new(f_xo(td.b0), td.mo, lineEnd, td.mo, color = I_HL, width = 2))
        addTag(td.mo, leadX, (candleOn ? "O · MIDNIGHT " : "MIDNIGHT ") + f_px(td.mo), P_HL, onFill(P_HL), I_HL,
             "Midnight open (true day open) " + f_px(td.mo) + " at " + f_hm(td.t0) + "\nClose vs it: " + f_sgn(td.cl - td.mo) + f_unit())
    if hasTd and show830 and not na(td.o830)
        lns.push(line.new(f_xo(td.b830), td.o830, lineEnd, td.o830, color = I_MUT, width = 1, style = line.style_dashed))
        addTag(td.o830, leadX, "08:30 OPEN " + f_px(td.o830), C_OTAG, C_TXT, I_MUT, "08:30 New York open " + f_px(td.o830) + "\nClose vs it: " + f_sgn(td.cl - td.o830) + f_unit())
    if hasTd and show930 and not na(td.o930)
        lns.push(line.new(f_xo(td.b930), td.o930, lineEnd, td.o930, color = I_MUT, width = 1, style = line.style_dashed))
        addTag(td.o930, leadX, "09:30 OPEN " + f_px(td.o930), C_OTAG, C_TXT, I_MUT, "09:30 New York open " + f_px(td.o930) + "\nClose vs it: " + f_sgn(td.cl - td.o930) + f_unit())
    if showWO and not na(wOpen) and (not hasTd or na(td.dAtr) or math.abs(close - wOpen) <= woWithin * td.dAtr)
        lns.push(line.new(f_xo(wBar), wOpen, lineEnd, wOpen, color = I_MUT, width = 1, style = line.style_dotted))
        addTag(wOpen, leadX, "WEEKLY OPEN " + f_px(wOpen), C_OTAG, C_TXT, I_MUT, "Weekly open " + f_px(wOpen) + "\nClose vs it: " + f_sgn(close - wOpen) + f_unit())
    // O / H / L / C of the Po3 candle
    if candleOn
        color bc = td.cl >= td.mo ? P_BULL : P_BEAR
        addTag(td.hi, xC, "H " + f_px(td.hi), P_BEAR, onFill(P_BEAR), I_BEAR, "Day high since midnight " + f_px(td.hi) + "\n" + f_sgn(td.hi - td.mo) + f_unit() + " from the midnight open")
        addTag(td.lo, xC, "L " + f_px(td.lo), P_BULL, onFill(P_BULL), I_BULL, "Day low since midnight " + f_px(td.lo) + "\n" + f_sgn(td.lo - td.mo) + f_unit() + " from the midnight open")
        addTag(td.cl, leadX, "C " + f_px(td.cl), bc, onFill(bc), light ? deep(bc) : bc, "Close " + f_px(td.cl) + "\n" + f_sgn(td.cl - td.mo) + f_unit() + " from the midnight open")
 
    // 8b. displayed span: visible bars plus everything drawn at the right edge; it sets the tag gap
    float sHi = visHi
    float sLo = visLo
    for p in cP
        sHi := na(sHi) ? p : math.max(sHi, p)
        sLo := na(sLo) ? p : math.min(sLo, p)
    if po3Ok and hasTd
        sHi := na(sHi) ? td.hi : math.max(sHi, td.hi)
        sLo := na(sLo) ? td.lo : math.min(sLo, td.lo)
    if ydOn
        sHi := math.max(sHi, yd.hi)
        sLo := math.min(sLo, yd.lo)
    float span = na(sHi) or na(sLo) ? 0.0 : sHi - sLo
    float gap  = math.max(gapK * span, syminfo.mintick * 2)
 
    // 8c. premium / discount gradient: base layers at 85 from EQ out, then nested layers from each edge inward (each
    // shorter, no seams) so the tint runs from 85 at EQ to 55 at the day high and low
    if po3Ok and hasTd and showPD and td.hi > td.lo
        float eq   = (td.hi + td.lo) / 2.0
        float half = (td.hi - td.lo) / 2.0
        int   x0   = f_xo(td.b0)
        bxs.push(box.new(x0, td.hi, zoneEnd, eq, border_color = TR, bgcolor = color.new(P_BEAR, 85)))
        bxs.push(box.new(x0, eq, zoneEnd, td.lo, border_color = TR, bgcolor = color.new(P_BULL, 85)))
        int tl = int(math.round(100.0 * math.pow(0.55 / 0.85, 1.0 / (pdStops - 1))))
        for k = 1 to pdStops - 1
            float f = 1.0 - float(k) / float(pdStops)
            bxs.push(box.new(x0, td.hi, zoneEnd, td.hi - half * f, border_color = TR, bgcolor = color.new(P_BEAR, tl)))
            bxs.push(box.new(x0, td.lo + half * f, zoneEnd, td.lo, border_color = TR, bgcolor = color.new(P_BULL, tl)))
        lns.push(line.new(x0, td.hi, zoneEnd, td.hi, color = I_BEAR, width = 1))
        lns.push(line.new(x0, eq, zoneEnd, eq, color = color.new(color.gray, 30), style = line.style_dashed))
        lns.push(line.new(x0, td.lo, zoneEnd, td.lo, color = I_BULL, width = 1))
        if td.hi - td.lo >= 3.0 * gap
            string pz = td.cl >= eq ? "premium" : "discount"
            addTag(td.hi + gap * 0.01, leadX, "Premium", na, I_BEAR, I_BEAR, "Premium: the upper half of today's range, " + f_px(eq) + " to " + f_px(td.hi) + "\nThe close sits in " + pz)
            addTag(eq, leadX, "EQ " + f_px(eq), na, light ? #6A6D78 : #9598A1, color.gray, "Equilibrium: the mid of today's range since midnight\nThe close sits in " + pz)
            addTag(td.lo - gap * 0.01, leadX, "Discount", na, I_BULL, I_BULL, "Discount: the lower half of today's range, " + f_px(td.lo) + " to " + f_px(eq) + "\nThe close sits in " + pz)
 
    // 8d. phase boxes: today and yesterday in full, older days faded
    if po3Ok
        if hasTd
            drawDay(td, true, gap)
        if not na(yd)
            drawDay(yd, true, gap)
            if showMO and not na(yd.mo) and yd.bEnd >= bar_index - PAST_MAX
                lns.push(line.new(f_xo(yd.b0), yd.mo, yd.bEnd, yd.mo, color = color.new(I_HL, 55), width = 1, style = line.style_dashed))
            if oldDays > 0 and ydI > 0
                int cnt = 0
                for i = ydI - 1 to 0
                    Po3Day od = days.get(i)
                    if od.bEnd < bar_index - PAST_MAX or cnt >= oldDays
                        break
                    if f_full(od)
                        drawDay(od, false, gap)
                        cnt += 1
        // tonight's Asia range, forming for tomorrow
        if showAcc and hasTd and not na(trT0) and trT0 > td.t0 and (na(td.aT0) or trT0 != td.aT0) and trB1 >= bar_index - PAST_MAX
            int    x0 = f_xo(trB0)
            int    x1 = math.max(trB1, x0 + 1)
            string at = f_atr(trHi - trLo, td.dAtr)
            bxs.push(box.new(x0, trHi, x1, trLo, border_color = color.new(C_ACC, 45), border_width = 1, bgcolor = color.new(C_ACC, 85)))
            lbls.push(label.new(x0, trHi, "ACC · " + f_pts(trHi - trLo) + (at == "" ? "" : " · " + at),
                 color = color.new(C_ACC, 20), textcolor = onFill(C_ACC), size = size.small, text_formatting = text.format_bold,
                 style = label.style_label_lower_left, tooltip = "Accumulation forming for tomorrow: the Asia range from " + f_hm(trT0) + "\nHigh " + f_px(trHi) + " · Low " + f_px(trLo)))
 
    // 8e. the Po3 candle: yesterday small, the Asia band, today large, the Judas tick
    if candleOn
        color bc = td.cl >= td.mo ? P_BULL : P_BEAR
        float bT = math.max(td.mo, td.cl)
        float bB = math.min(td.mo, td.cl)
        if ydOn
            float yo = na(yd.mo) ? yd.o : yd.mo
            color yc = yd.cl >= yo ? P_BULL : P_BEAR
            int   yW = math.max(2, math.min(int(pcW / 2), pcOff - 6))
            int   yR = xL - 4
            int   yL = yR - yW
            int   yX = yL + int(yW / 2)
            bxs.push(box.new(yL, math.max(yo, yd.cl), yR, math.min(yo, yd.cl), border_color = color.new(yc, 30), border_width = 1, bgcolor = color.new(yc, 55)))
            lns.push(line.new(yX, yd.hi, yX, math.max(yo, yd.cl), color = color.new(yc, 30), width = 1))
            lns.push(line.new(yX, math.min(yo, yd.cl), yX, yd.lo, color = color.new(yc, 30), width = 1))
            lbls.push(label.new(yX, yd.hi, "PREV", color = TR, textcolor = I_MUT, style = label.style_label_down, size = size.small,
                 tooltip = "Previous day: O " + f_px(yo) + " · H " + f_px(yd.hi) + " · L " + f_px(yd.lo) + " · C " + f_px(yd.cl) + "\nRange " + f_pts(yd.hi - yd.lo)))
        if showBand and not na(td.aHi)
            bxs.push(box.new(xL - 2, td.aHi, xL - 1, td.aLo, border_color = color.new(C_ACC, 30), border_width = 1, bgcolor = color.new(C_ACC, 50)))
        bxs.push(box.new(xL, bT, xR, bB, border_color = bc, border_width = 1, bgcolor = color.new(bc, 15)))
        lns.push(line.new(xC, td.hi, xC, bT, color = bc, width = 2))
        lns.push(line.new(xC, bB, xC, td.lo, color = bc, width = 2))
        if showTick and td.jSide != 0
            lns.push(line.new(xL + 1, td.jExt, xR - 1, td.jExt, color = td.jSide == 1 ? P_BEAR : P_BULL, width = 1, style = line.style_dashed))
        lbls.push(label.new(xC, td.hi, "PO3", color = TR, textcolor = I_HL, style = label.style_label_down, size = size.small,
             text_formatting = text.format_bold, tooltip = "Today's daily candle from the midnight open: O " + f_px(td.mo) + " · H " + f_px(td.hi) + " · L " + f_px(td.lo) + " · C " + f_px(td.cl) + (na(td.aHi) ? "" : "\nSilver band: the Asia range " + f_px(td.aLo) + " to " + f_px(td.aHi)) + (td.jSide != 0 ? "\nDashed tick: the Judas extreme " + f_px(td.jExt) : "")))
 
    // 8f. tag column: sorted by price, pushed apart by the lane register, each with a leader back to its level
    int m = cP.size()
    if m > 0
        array<int>   idx    = cP.sort_indices(order.ascending)
        array<float> sorted = array.new<float>()
        for i in idx
            sorted.push(cP.get(i))
        array<float> ys = f_lanes(sorted, gap)
        for j = 0 to m - 1
            int   i = idx.get(j)
            float y = ys.get(j)
            color f = cF.get(i)
            lns.push(line.new(cX.get(i), cP.get(i), colX, y, color = color.new(cL.get(i), 35), width = 1))
            lbls.push(label.new(colX, y, cT.get(i), color = na(f) ? TR : color.new(f, 15), textcolor = cC.get(i),
                 style = label.style_label_left, size = size.small, text_formatting = na(f) ? text.format_none : text.format_bold,
                 tooltip = cTip.get(i)))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 9. DASHBOARD "PO3 CONFLUENCE | STATE"
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
var table dash = na
f_row(table tb, int r, int rows, string k, string v, color vc, string tip, string sz) =>
    color bg = f_grad(P_BG, r, rows, dashTrans, dashTrans + 25)
    table.cell(tb, 0, r, k, text_color = C_TXT_M, bgcolor = bg, text_halign = text.align_left, text_size = sz, tooltip = tip)
    table.cell(tb, 1, r, v, text_color = vc, bgcolor = bg, text_halign = text.align_right, text_size = sz, tooltip = tip)
 
if showDash and barstate.islast
    int ROWS = 9
    if na(dash)
        dash := table.new(f_pos(dashPos), 2, ROWS, bgcolor = color.new(P_BG, 100), frame_color = color.new(P_FRAME, 60),
             frame_width = 1, border_color = color.new(P_FRAME, 65), border_width = 1)
    string sz    = f_size(dashSize)
    color  hdrBg = f_grad(P_BG, 0, ROWS, dashTrans, dashTrans + 5)
    table.cell(dash, 0, 0, "PO3 CONFLUENCE", text_color = C_TXT, bgcolor = hdrBg, text_size = sz,
         text_font_family = font.family_monospace, text_formatting = text.format_bold)
    table.cell(dash, 1, 0, "STATE", text_color = C_TXT, bgcolor = hdrBg, text_halign = text.align_right, text_size = sz,
         text_font_family = font.family_monospace, text_formatting = text.format_bold)
    int    n     = days.size()
    Po3Day td    = n > 0 ? days.last() : na
    bool   hasTd = not na(td)
    bool   tdMo  = hasTd and not na(td.mo)
    int    lastR = 8
    string scTxt = "— / 100"
    string scTip = "Po3 Score needs a 15m or lower chart and a day that opened at midnight."
    // day bias and distance rows (every intraday chart)
    string biasTxt = "no midnight open"
    color  biasCol = C_NEU
    string distTxt = "—"
    if tdMo
        float dv = td.cl - td.mo
        biasTxt := (dv >= 0 ? "Above · " : "Below · ") + f_sgn(dv) + f_unit()
        biasCol := dv >= 0 ? D_BULL : D_BEAR
        string dA = na(td.dAtr) or td.dAtr <= 0 ? "" : (dv >= 0 ? "+" : "-") + str.tostring(math.abs(dv) / td.dAtr, "0.00") + " ATR · "
        distTxt := dA + (dv >= 0 ? "+" : "-") + str.tostring(math.abs(dv) / td.mo * 100.0, "0.00") + "%"
    string biasTip = "Day bias: the close against today's midnight open (00:00 New York, the true day open). Above = bull colour, below = bear colour; candles are painted the same way."
    string distTip = "Distance from the close to the midnight open, in day ATR (average true range of the last " + (hasTd ? str.tostring(td.nA) : "0") + " complete days on this chart, up to 14) and in percent of price."
    if not po3Ok
        f_row(dash, 1, ROWS, "Timeframe", "Po3 needs 15m or lower", D_BEAR, "Asia, the Judas swing and the New York expansion are read from session bars, which needs a 15m or lower chart. On this timeframe only the opens are drawn.", sz)
        f_row(dash, 2, ROWS, "Day bias", intra ? biasTxt : "—", biasCol, biasTip, sz)
        f_row(dash, 3, ROWS, "Distance to MO", intra ? distTxt : "—", biasCol, distTip, sz)
        lastR := 4
    else
        // phase now
        string phase = inAsia ? "Accumulation" : inLon ? "Manipulation" : inNy ? "Distribution" : "Off-session"
        color  phCol = inAsia ? C_ACC : inLon ? P_HL : inNy ? (tdMo and td.cl < td.mo ? D_BEAR : D_BULL) : C_TXT_M
        f_row(dash, 1, ROWS, "Day bias", biasTxt, biasCol, biasTip, sz)
        f_row(dash, 2, ROWS, "Phase now", phase, phCol, "Accumulation = inside the Asia window (" + asiaWin + "), Manipulation = London (" + lonWin + "), Distribution = New York (" + nyWin + "), Off-session = between them. Windows in " + tzUse + ".", sz)
        // Asia range (tonight's forming range while it is building for tomorrow)
        string aTxt = "no Asia bars"
        string aTip = "The Asia range in points and in day ATR."
        bool pend = hasTd and not na(trT0) and trT0 > td.t0 and (na(td.aT0) or trT0 != td.aT0)
        if pend and inAsia
            string at = f_atr(trHi - trLo, td.dAtr)
            aTxt := f_pts(trHi - trLo) + (at == "" ? "" : " · " + at) + " · live"
            aTip := "Tomorrow's Asia range is forming now: high " + f_px(trHi) + " · low " + f_px(trLo) + "."
        else if hasTd and not na(td.aHi)
            string at = f_atr(td.aHi - td.aLo, td.dAtr)
            aTxt := f_pts(td.aHi - td.aLo) + (at == "" ? "" : " · " + at)
            aTip := "Today's Asia range: high " + f_px(td.aHi) + " · low " + f_px(td.aLo) + (td.nA > 0 ? "\nDay ATR from " + str.tostring(td.nA) + " complete days: " + f_pts(td.dAtr) : "\nDay ATR needs one complete day on the chart.")
        f_row(dash, 3, ROWS, "Asia range", aTxt, C_TXT, aTip, sz)
        // Judas
        string jTxt = "—"
        color  jCol = C_TXT_M
        if not hasTd or na(td.aHi)
            jTxt := "no Asia range"
        else if td.jSide != 0
            jTxt := (td.jSide == 1 ? "High · " : "Low · ") + f_pts(td.jExt - (td.jSide == 1 ? td.aHi : td.aLo))
            jCol := td.jSide == 1 ? D_BEAR : D_BULL
        else if inLon
            jTxt := "none yet · London live"
        else if not na(td.lB1)
            jTxt := "no Judas"
        else
            jTxt := "waiting for London"
        f_row(dash, 4, ROWS, "Judas", jTxt, jCol, "The first move beyond the Asia high or low during London: which side it swept and how far past the Asia edge the London extreme reached. 'no Judas' = London never left the Asia range.", sz)
        // day range vs 10-day average
        string rTxt = "—"
        color  rCol = C_TXT
        if hasTd
            float rg = td.hi - td.lo
            if na(td.avgR) or td.avgR <= 0
                rTxt := f_pts(rg) + " · no average yet"
            else
                float pc = 100.0 * rg / td.avgR
                rTxt := str.tostring(pc, "0") + "% · " + f_val(rg) + " / " + f_val(td.avgR)
                rCol := pc >= 100.0 ? P_HL : C_TXT
        f_row(dash, 5, ROWS, "Day range vs avg", rTxt, rCol, "Today's range since midnight against the average range of the last " + (hasTd ? str.tostring(td.nR) : "0") + " complete days on this chart (10 when the chart holds them). Highlighted at 100% and above.", sz)
        f_row(dash, 6, ROWS, "Distance to MO", distTxt, biasCol, distTip, sz)
        f_row(dash, 7, ROWS, "Session H/L taken", hasTd ? f_taken(td) : "—", C_TXT, "Which session extremes price has traded beyond after that session closed: the Asia high / low, the London high / low, and the previous complete day's high / low (PDH / PDL).", sz)
        if tdMo
            [s1, s2, s3, s4] = f_score(td)
            float sc = s1 + s2 + s3 + s4
            scTxt := str.tostring(sc, "0") + " / 100"
            scTip := "Judas " + str.tostring(s1, "0") + " + opposite " + str.tostring(s2, "0") + " + expansion " + str.tostring(s3, "0") + " + beyond Asia " + str.tostring(s4, "0") + " = " + str.tostring(sc, "0") + "\n\nJudas (25): London traded beyond the Asia range.\nOpposite (25): the Judas went against the day bias (swept the low on a day above the midnight open, or the high on a day below it).\nExpansion (0-25): the day extreme in the bias direction measured from the midnight open, full marks at half the average day range.\nBeyond Asia (25): the close sits outside the Asia range on the bias side.\n\nIt describes how closely today's shape matches Power of Three. It is not a forecast and not a signal."
    table.cell(dash, 0, lastR, "Po3 Score", text_color = C_TXT, bgcolor = color.new(P_HL, 60), text_size = sz,
         text_font_family = font.family_monospace, tooltip = scTip)
    table.cell(dash, 1, lastR, scTxt, text_color = onFill(P_HL), bgcolor = color.new(P_HL, 30), text_halign = text.align_right,
         text_size = sz, text_font_family = font.family_monospace, text_formatting = text.format_bold, tooltip = scTip)

← 返回列表