Session Zones: Trend vs Range

Black-Chart · study · 640 行 · 点赞 95 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Black-Chart
//@version=6
indicator("Session Zones v2.5", shorttitle="Session Zones v2.5", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)
 
// ───────────────────────────── Constants ─────────────────────────────
const string VER     = "v2.5"
const int    NS      = 3        // number of sessions
const int    NSTAT   = 14       // statistics stored per session
const int    MIN_N   = 30       // sessions needed before a verdict is shown
const float  Z_CI    = 2.394    // two-sided 98.33% interval (3 sessions tested together, Bonferroni)
const int    FLIPS   = 100      // random-sign paths per session
const int    WH_M    = 30269    // Wichmann–Hill generator: x = x * 171 mod 30269
const int    WH_A    = 171
const int    WH_HALF = 15135
const int    ST_WAIT = 0
const int    ST_KEEP = 1
const int    ST_GIVE = 2
const int    ST_RAND = 3
const int    DAY_MS  = 86400000
const int    MAXB    = 50       // max 30-minute bars in one session (24 h + the extra hour when clocks go back)
 
cObsidian = #08090d
cCharcoal = color.new(#121418, 8)
cGraphite = color.new(#1a1c22, 8)
cGhost    = #3a3d45
cChrome   = #c8c8cc
cSilver   = #8a8a8e
cSteel    = #484a50
cAccBuy   = #4FC3F7
cAccSell  = #CE93D8
 
// ───────────────────────────── Inputs ─────────────────────────────
grpS = "Sessions"
i_tz     = input.string("Europe/Rome", "Session clock", options=["Europe/Rome", "Europe/London", "America/New_York", "UTC", "Asia/Tokyo", "Australia/Sydney"], group=grpS, tooltip="Time zone used to read the session hours below. The defaults are written in Rome time (CET/CEST).")
i_nA     = input.string("ASIA", "Session 1", inline="s1", group=grpS)
i_sA     = input.session("0000-0800", "", inline="s1", group=grpS)
i_nL     = input.string("LONDON", "Session 2", inline="s2", group=grpS)
i_sL     = input.session("0900-1530", "", inline="s2", group=grpS)
i_nN     = input.string("NEW YORK", "Session 3", inline="s3", group=grpS)
i_sN     = input.session("1530-2100", "", inline="s3", group=grpS, tooltip="Name and hours are free. A bar belongs to a session when it opens inside the hours. Sessions may overlap and may cross midnight (e.g. 2300-0800): each one is measured on its own bars. Start and end must be on :00 or :30 because the statistics are built from 30-minute moves. Changing the hours recalculates the whole history with the new hours.")
i_N      = input.int(100, "Lookback (sessions)", minval=30, maxval=300, group=grpS, tooltip="Each percentage is measured on the last N completed sessions of that row (the name is only a label) and updates by itself at every session close.")
 
grpZ = "Chart"
i_show   = input.bool(true, "Show session boxes", group=grpZ)
i_lbl    = input.bool(true, "Labels above the boxes", group=grpZ)
i_lblSz  = input.string("Small", "Label size", options=["Tiny", "Small", "Normal"], group=grpZ)
i_proj   = input.bool(true, "Project today's sessions", group=grpZ, tooltip="Draws the sessions that have not finished yet to the right of the last bar, between today's high and low.")
i_days   = input.int(5, "Days of boxes", minval=1, maxval=30, group=grpZ)
i_thr    = input.int(53, "Colour threshold (%)", minval=51, maxval=70, group=grpZ, tooltip="Green when at least this share of the last N sessions trended, red when at least this share ranged, grey in between (balanced).")
i_cKeep  = input.color(color.new(#4CAF50, 85), "Trend", group=grpZ)
i_cGive  = input.color(color.new(#E53935, 85), "Range", group=grpZ)
i_cRand  = input.color(color.new(#9E9E9E, 85), "Balanced", group=grpZ)
 
grpP = "Dashboard"
i_dash   = input.string("Compact", "Dashboard", options=["Compact", "Detailed", "Off"], group=grpP, tooltip="Compact: one line per session plus the higher-timeframe bias. Detailed: the full statistics. A warning is always shown when the indicator cannot draw.")
i_pos    = input.string("top_right", "Position", options=["top_right", "top_left", "bottom_right", "bottom_left"], group=grpP)
i_size   = input.string("Medium", "Size", options=["Small", "Medium", "Large"], group=grpP)
 
grpB = "Bias"
i_bias   = input.bool(true, "Show H1 / H4 / D bias", group=grpB)
i_bLen   = input.int(50, "Bias EMA length", minval=5, maxval=400, group=grpB, tooltip="Read on the last closed bar of each timeframe. BULL: close above the EMA and the EMA rising. BEAR: close below the EMA and the EMA falling. Anything else: FLAT.")
 
// ───────────────────────────── Session helpers ─────────────────────────────
f_min(string s, int off) =>
    int(str.tonumber(str.substring(s, off, off + 2))) * 60 + int(str.tonumber(str.substring(s, off + 2, off + 4)))
 
f_end(string s) =>
    int e = f_min(s, 5)
    e == 0 ? 1440 : e
 
int sA0 = f_min(i_sA, 0)
int sA1 = f_end(i_sA)
int sL0 = f_min(i_sL, 0)
int sL1 = f_end(i_sL)
int sN0 = f_min(i_sN, 0)
int sN1 = f_end(i_sN)
bool sesOk = sA1 % 1440 != sA0 and sL1 % 1440 != sL0 and sN1 % 1440 != sN0 and sA0 % 30 == 0 and sA1 % 30 == 0 and sL0 % 30 == 0 and sL1 % 30 == 0 and sN0 % 30 == 0 and sN1 % 30 == 0
 
f_s0(int s) =>
    s == 0 ? sA0 : s == 1 ? sL0 : sN0
 
f_s1(int s) =>
    s == 0 ? sA1 : s == 1 ? sL1 : sN1
 
// true when the session crosses midnight of the session clock (end earlier than start)
f_x(int s) =>
    f_s1(s) < f_s0(s)
 
f_in(int s, int m) =>
    f_x(s) ? (m >= f_s0(s) or m < f_s1(s)) : (m >= f_s0(s) and m < f_s1(s))
 
// end in minutes from the start day's midnight (beyond 1440 when it crosses midnight)
f_s1x(int s) =>
    f_x(s) ? f_s1(s) + 1440 : f_s1(s)
 
f_need(int s) =>
    int(math.ceil(0.8 * (f_s1x(s) - f_s0(s)) / 30.0))
 
f_name(int s) =>
    string n = str.upper(str.trim(s == 0 ? i_nA : s == 1 ? i_nL : i_nN))
    n := str.length(n) > 16 ? str.substring(n, 0, 16) : n
    n == "" ? "SESSION " + str.tostring(s + 1) : n
 
f_hhmm(string s, int off) =>
    str.substring(s, off, off + 2) + ":" + str.substring(s, off + 2, off + 4)
 
f_hours(int s) =>
    string x = s == 0 ? i_sA : s == 1 ? i_sL : i_sN
    f_hhmm(x, 0) + "–" + f_hhmm(x, 5)
 
f_dayKey(int t) =>
    year(t, i_tz) * 10000 + month(t, i_tz) * 100 + dayofmonth(t, i_tz)
 
// a session is keyed by the day it starts: after midnight a crossing session still belongs to the previous day
f_key(int s, int m, int dk, int t) =>
    f_x(s) and m < f_s1(s) ? f_dayKey(timestamp(i_tz, year(t, i_tz), month(t, i_tz), dayofmonth(t, i_tz), 12, 0, 0) - DAY_MS) : dk
 
f_pos(string p) =>
    switch p
        "top_left"     => position.top_left
        "bottom_right" => position.bottom_right
        "bottom_left"  => position.bottom_left
        => position.top_right
 
f_pts(float ticks) =>
    float p = ticks * syminfo.mintick
    close >= 1000 and syminfo.mintick < 0.1 ? str.tostring(math.round(p), "0") : str.tostring(p, format.mintick)
 
f_p100(float x) =>
    na(x) ? "—" : str.tostring(math.round(x * 100)) + "%"
 
f_dec(float x) =>
    na(x) ? "—" : (x >= 0 ? "+" : "") + str.tostring(x, "0.00")
 
f_median(array<float> a) =>
    int n = array.size(a)
    float r = na
    if n > 0
        array.sort(a, order.ascending)
        r := n % 2 == 1 ? array.get(a, int((n - 1) / 2)) : (array.get(a, int(n / 2) - 1) + array.get(a, int(n / 2))) / 2.0
    r
 
// ───────────────────────────── Engine (runs on 30-minute bars) ─────────────────────────────
// Keep ratio of one path: |net move| / farthest excursion in the direction of the net move.
// With flip = true every half-hour move gets a random sign (same sizes, random direction).
f_keepFlip(array<int> st, array<int> hi, array<int> lo, int kSeed) =>
    int   kX  = kSeed
    float cum = 0.0
    float H   = -1e18
    float L   = 1e18
    for i = 0 to array.size(st) - 1
        kX := (kX * WH_A) % WH_M
        if kX >= WH_HALF
            H := math.max(H, cum - array.get(lo, i))
            L := math.min(L, cum - array.get(hi, i))
            cum -= array.get(st, i)
        else
            H := math.max(H, cum + array.get(hi, i))
            L := math.min(L, cum + array.get(lo, i))
            cum += array.get(st, i)
    float mfe = cum > 0 ? H : cum < 0 ? -L : 0.0
    [mfe > 0 ? math.abs(cum) / mfe : 0.0, kX]
 
f_engine() =>
    float tk   = syminfo.mintick
    int   mins = hour(time, i_tz) * 60 + minute(time, i_tz)
    int   dKey = f_dayKey(time)
    // Sessions that started more than ~1.5 x (lookback + days of boxes + 10) + 7 calendar days before the last bar
    // are skipped, so the cost stays the same however much history is loaded. On symbols that trade at least five
    // days a week this changes nothing that is shown; with many missing sessions the window can hold fewer than N.
    int   cutK = f_dayKey(last_bar_time - int(math.ceil((i_N + i_days + 10) * 1.5) + 7) * DAY_MS)
    int   oT   = math.round(open / tk)
    int   hT   = math.round(high / tk)
    int   lT   = math.round(low / tk)
    int   cT   = math.round(close / tk)
    // one independent accumulator per session: sessions may overlap and may cross midnight
    var array<int> uSt   = array.new<int>(NS * MAXB, 0)
    var array<int> uHi   = array.new<int>(NS * MAXB, 0)
    var array<int> uLo   = array.new<int>(NS * MAXB, 0)
    var array<int> uN    = array.new<int>(NS, 0)
    var array<int> uKey  = array.new<int>(NS, na)
    var array<int> uLast = array.new<int>(NS, na)
    var array<float> rKeep = array.new<float>(NS * i_N, na)
    var array<float> rCh   = array.new<float>(NS * i_N, na)
    var array<float> rN2   = array.new<float>(NS * i_N, na)
    var array<float> rSs   = array.new<float>(NS * i_N, na)
    var array<float> rNet  = array.new<float>(NS * i_N, na)
    var array<float> rR    = array.new<float>(NS * i_N, na)
    var array<float> rDir  = array.new<float>(NS * i_N, na)
    var array<float> rD    = array.new<float>(NS * i_N, na)
    var array<float> rD2   = array.new<float>(NS * i_N, na)
    var array<int>   ptr   = array.new<int>(NS, 0)
    var array<int>   fil   = array.new<int>(NS, 0)
    var array<float> stat  = array.new<float>(NS * NSTAT, na)
    bool commit = false
    for s = 0 to NS - 1
        bool inS = f_in(s, mins)
        int  key = inS ? f_key(s, mins, dKey, time) : na
        if inS and key < cutK
            inS := false
            key := na
        int ck = array.get(uKey, s)
        if not na(ck) and (not inS or key != ck)
            int n  = array.get(uN, s)
            int b0 = s * MAXB
            if n >= f_need(s)
                array<int> aSt = array.slice(uSt, b0, b0 + n)
                array<int> aHi = array.slice(uHi, b0, b0 + n)
                array<int> aLo = array.slice(uLo, b0, b0 + n)
                // real path
                float cum = 0.0
                float H   = -1e18
                float L   = 1e18
                float ss  = 0.0
                for i = 0 to n - 1
                    H := math.max(H, cum + array.get(aHi, i))
                    L := math.min(L, cum + array.get(aLo, i))
                    cum += array.get(aSt, i)
                    ss += math.pow(array.get(aSt, i), 2)
                float mfeR  = cum > 0 ? H : cum < 0 ? -L : 0.0
                float kReal = mfeR > 0 ? math.abs(cum) / mfeR : 0.0
                // random-sign paths, seeded by start date and session (reproducible)
                int dy = int(ck / 10000)
                int dm = int(ck / 100) % 100
                int dd = ck % 100
                int seedX = (((dy - 2000) * 372 + dm * 31 + dd) * 3 + s) % (WH_M - 1) + 1
                float sumCh = 0.0
                array<float> ks = array.new<float>(FLIPS, 0.0)
                for j = 0 to FLIPS - 1
                    [kf, xn] = f_keepFlip(aSt, aHi, aLo, seedX)
                    sumCh += kf
                    array.set(ks, j, kf)
                    seedX := xn
                array.sort(ks, order.ascending)
                float kMed = (array.get(ks, FLIPS / 2 - 1) + array.get(ks, FLIPS / 2)) / 2.0
                int k = s * i_N + array.get(ptr, s)
                array.set(rKeep, k, kReal)
                array.set(rCh,   k, sumCh / FLIPS)
                array.set(rN2,   k, cum * cum)
                array.set(rSs,   k, ss)
                array.set(rNet,  k, math.abs(cum))
                array.set(rR,    k, H - L)
                float dOut = array.get(rDir, k)
                float dIn  = kReal > kMed ? 1.0 : 0.0
                array.set(rDir,  k, dIn)
                array.set(ptr, s, (array.get(ptr, s) + 1) % i_N)
                array.set(fil, s, math.min(array.get(fil, s) + 1, i_N))
                // window statistics
                float dk = kReal - sumCh / FLIPS
                array.set(rD,  k, dk)
                array.set(rD2, k, dk * dk)
                int m  = array.get(fil, s)
                int q0 = s * i_N
                int q1 = q0 + m
                float sK   = array.sum(array.slice(rKeep, q0, q1))
                float sC   = array.sum(array.slice(rCh, q0, q1))
                float sD   = array.sum(array.slice(rD, q0, q1))
                float sD2  = array.sum(array.slice(rD2, q0, q1))
                float sN2  = array.sum(array.slice(rN2, q0, q1))
                float sSs  = array.sum(array.slice(rSs, q0, q1))
                float sDir = array.sum(array.slice(rDir, q0, q1))
                array<float> nets = array.copy(array.slice(rNet, q0, q1))
                array<float> rngs = array.copy(array.slice(rR, q0, q1))
                float mD = sD / m
                float sd = m > 1 ? math.sqrt(math.max(0.0, (sD2 - m * mD * mD) / (m - 1))) : na
                float lo = m > 1 ? mD - Z_CI * sd / math.sqrt(m) : na
                float hi = m > 1 ? mD + Z_CI * sd / math.sqrt(m) : na
                int state = m < MIN_N ? ST_WAIT : lo > 0 ? ST_KEEP : hi < 0 ? ST_GIVE : ST_RAND
                int b = s * NSTAT
                array.set(stat, b + 0, m)                              // sessions in the window
                array.set(stat, b + 1, sK / m)                         // mean keep ratio
                array.set(stat, b + 2, sC / m)                         // mean keep ratio of the random paths
                array.set(stat, b + 3, mD)                             // mean difference
                array.set(stat, b + 4, lo)                             // interval low
                array.set(stat, b + 5, hi)                             // interval high
                array.set(stat, b + 6, sSs > 0 ? sN2 / sSs : na)       // variance ratio
                array.set(stat, b + 7, f_median(nets))                 // median net move (ticks)
                array.set(stat, b + 8, f_median(rngs))                 // median range (ticks)
                array.set(stat, b + 9, state)
                array.set(stat, b + 10, sDir)                          // trending sessions in the window
                array.set(stat, b + 11, math.round(100.0 * sDir / m))  // trending share %
                array.set(stat, b + 12, dIn)                           // session entering the window
                array.set(stat, b + 13, dOut)                          // session leaving the window
                commit := true
            array.set(uKey, s, na)
            array.set(uN, s, 0)
        if inS
            if na(array.get(uKey, s))
                array.set(uKey, s, key)
                array.set(uLast, s, na)
                array.set(uN, s, 0)
            int n  = array.get(uN, s)
            if n < MAXB
                int lastC = array.get(uLast, s)
                int gap   = na(lastC) ? 0 : oT - lastC
                int q     = s * MAXB + n
                array.set(uSt, q, gap + cT - oT)
                array.set(uHi, q, gap + hT - oT)
                array.set(uLo, q, gap - (oT - lT))
                array.set(uN, s, n + 1)
                array.set(uLast, s, cT)
    array<float> oSt = na
    if commit
        oSt := array.copy(stat)
    [minute(time, i_tz) % 30 != 0, oSt]
 
// ───────────────────────────── Chart context ─────────────────────────────
bool   tfOk  = timeframe.isminutes and timeframe.multiplier <= 30 and 30 % timeframe.multiplier == 0
bool   typOk = not (chart.is_renko or chart.is_kagi or chart.is_pnf or chart.is_linebreak or chart.is_range)
string engTf = tfOk ? "30" : "1D"
float  tk    = syminfo.mintick
int    mins  = hour(time, i_tz) * 60 + minute(time, i_tz)
int    dKey  = f_dayKey(time)
 
[eMis, eSt] = request.security(ticker.standard(syminfo.tickerid), engTf, f_engine(), lookahead=barmerge.lookahead_on)
 
var array<float> st = array.new<float>(NS * NSTAT, na)
if not na(eSt)
    st := eSt
 
f_st(int s, int k) =>
    array.get(st, s * NSTAT + k)
 
f_state(int s) =>
    float v = f_st(s, 9)
    na(v) ? ST_WAIT : int(v)
 
// trending share, -1 while collecting data
f_pct(int s) =>
    float v = f_st(s, 11)
    f_state(s) == ST_WAIT or na(v) ? -1 : int(v)
 
// ranging share, -1 while collecting data
f_lat(int s) =>
    float d = f_st(s, 10)
    float m = f_st(s, 0)
    f_pct(s) < 0 ? -1 : int(math.round(100.0 * (m - d) / m))
 
// 1 trend, -1 range, 0 balanced (colour threshold not reached), na while collecting
f_side(int s) =>
    int p = f_pct(s)
    p < 0 ? na : p >= i_thr ? 1 : f_lat(s) >= i_thr ? -1 : 0
 
f_col(int s) =>
    int sd = f_side(s)
    na(sd) or sd == 0 ? i_cRand : sd > 0 ? i_cKeep : i_cGive
 
// the larger side, always named: "Trend 57%", "Range 54%" or "Even 50%" on a tie
f_share(int s) =>
    int p = f_pct(s)
    int q = f_lat(s)
    p > q ? "Trend " + str.tostring(p) + "%" : q > p ? "Range " + str.tostring(q) + "%" : "Even " + str.tostring(p) + "%"
 
f_txt(int s) =>
    int n = na(f_st(s, 0)) ? 0 : int(f_st(s, 0))
    f_pct(s) < 0 ? f_name(s) + "\ncollecting data " + str.tostring(n) + "/" + str.tostring(MIN_N) : f_name(s) + "  " + str.upper(f_share(s))
 
bool ready = tfOk and typOk and sesOk and not eMis
 
// session labels: dark chip with the session colour at full strength, readable on any background
cLblBg = color.new(#121418, 5)
szLbl  = i_lblSz == "Tiny" ? size.tiny : i_lblSz == "Normal" ? size.normal : size.small
 
// ───────────────────────────── Session boxes ─────────────────────────────
var array<box>   boxes  = array.new<box>()
var array<line>  lnTop  = array.new<line>()
var array<line>  lnBot  = array.new<line>()
var array<label> lbls   = array.new<label>()
var array<int>   boxDay = array.new<int>()
var array<int>   boxSes = array.new<int>()
var array<box>   cBox  = array.new<box>(NS)
var array<line>  cTop  = array.new<line>(NS)
var array<line>  cBot  = array.new<line>(NS)
var array<label> cLbl  = array.new<label>(NS)
var array<int>   cKey  = array.new<int>(NS, na)
int  barMs  = timeframe.in_seconds() * 1000
int  tEnd   = nz(time_close, time + barMs)
// boxes older than the requested days are deleted anyway: skip them instead of drawing and deleting
bool recent = time >= last_bar_time - (i_days * 2 + 5) * DAY_MS
for s = 0 to NS - 1
    bool inS = i_show and ready and recent and f_in(s, mins)
    int  key = inS ? f_key(s, mins, dKey, time) : na
    if inS and key == array.get(cKey, s)
        box   bx = array.get(cBox, s)
        box.set_top(bx, math.max(box.get_top(bx), high))
        box.set_bottom(bx, math.min(box.get_bottom(bx), low))
        box.set_right(bx, tEnd)
        line.set_xy1(array.get(cTop, s), box.get_left(bx), box.get_top(bx))
        line.set_xy2(array.get(cTop, s), tEnd, box.get_top(bx))
        line.set_xy1(array.get(cBot, s), box.get_left(bx), box.get_bottom(bx))
        line.set_xy2(array.get(cBot, s), tEnd, box.get_bottom(bx))
        label lb = array.get(cLbl, s)
        if not na(lb)
            label.set_y(lb, box.get_top(bx))
    else if inS
        color bc = f_col(s)
        box   bx = box.new(time, high, tEnd, low, xloc=xloc.bar_time, border_width=0, bgcolor=bc)
        line  lt = line.new(time, high, tEnd, high, xloc=xloc.bar_time, color=color.new(bc, 50), width=2)
        line  lw = line.new(time, low, tEnd, low, xloc=xloc.bar_time, color=color.new(bc, 50), width=2)
        label lb = i_lbl ? label.new(time, high, f_txt(s), xloc=xloc.bar_time, style=label.style_label_lower_left, color=cLblBg, textcolor=color.new(bc, 0), size=szLbl) : na
        array.set(cBox, s, bx)
        array.set(cTop, s, lt)
        array.set(cBot, s, lw)
        array.set(cLbl, s, lb)
        array.push(boxes, bx)
        array.push(lnTop, lt)
        array.push(lnBot, lw)
        array.push(lbls, lb)
        array.push(boxDay, key)
        array.push(boxSes, s)
        // keep the boxes of the last i_days distinct session days; never delete a box still in progress
        array<int> ds = array.copy(boxDay)
        array.sort(ds, order.descending)
        int nd  = 0
        int cut = na
        for i = 0 to array.size(ds) - 1
            if i == 0 or array.get(ds, i) != array.get(ds, i - 1)
                nd += 1
                if nd == i_days
                    cut := array.get(ds, i)
        if not na(cut)
            for i = array.size(boxDay) - 1 to 0
                int os = array.get(boxSes, i)
                int lk = os == s ? key : array.get(cKey, os)
                if array.get(boxDay, i) < cut and (na(lk) or array.get(boxDay, i) != lk)
                    box.delete(array.remove(boxes, i))
                    line.delete(array.remove(lnTop, i))
                    line.delete(array.remove(lnBot, i))
                    label.delete(array.remove(lbls, i))
                    array.remove(boxDay, i)
                    array.remove(boxSes, i)
    array.set(cKey, s, key)
 
// ───────────────────────────── Projection of today's sessions ─────────────────────────────
var float dHi = na
var float dLo = na
bool dayChg = not na(dKey[1]) and dKey != dKey[1]
if na(dHi) or dayChg
    dHi := high
    dLo := low
else
    dHi := math.max(dHi, high)
    dLo := math.min(dLo, low)
 
f_tAt(int dayOff, int m) =>
    int dd = dayOff + int(m / 1440)
    int mm = m % 1440
    int tn = timestamp(i_tz, year(time, i_tz), month(time, i_tz), dayofmonth(time, i_tz), 12, 0, 0) + dd * DAY_MS
    timestamp(i_tz, year(tn, i_tz), month(tn, i_tz), dayofmonth(tn, i_tz), int(mm / 60), mm % 60, 0)
 
var array<box>   projs  = array.new<box>()
var array<line>  projLn = array.new<line>()
var array<label> projLb = array.new<label>()
if barstate.islast
    for b in projs
        box.delete(b)
    array.clear(projs)
    for l in projLn
        line.delete(l)
    array.clear(projLn)
    for l in projLb
        label.delete(l)
    array.clear(projLb)
    if i_show and i_proj and ready
        float top = dHi
        float bot = dLo
        if top - bot < tk * 10
            top += tk * 5
            bot -= tk * 5
        int wd = dayofweek(time, i_tz)
        bool tomOk = wd != dayofweek.friday and wd != dayofweek.saturday
        for dOff = -1 to 1
            for s = 0 to NS - 1
                int m0 = f_s0(s)
                int m1 = f_s1x(s)
                int t0 = f_tAt(dOff, m0)
                int t1 = f_tAt(dOff, m1)
                if (dOff < 0 or (dOff == 0 and (tomOk or not f_x(s))) or (tomOk and time >= f_tAt(0, m1))) and t1 > time_close and t0 < time_close + DAY_MS
                    color zc = f_col(s)
                    int left = math.max(t0, time_close)
                    array.push(projs, box.new(left, top, t1, bot, xloc=xloc.bar_time, border_width=0, bgcolor=color.new(zc, math.min(100, color.t(zc) + 8))))
                    array.push(projLn, line.new(left, top, t1, top, xloc=xloc.bar_time, color=color.new(zc, 50), style=line.style_dashed, width=2))
                    array.push(projLn, line.new(left, bot, t1, bot, xloc=xloc.bar_time, color=color.new(zc, 50), style=line.style_dashed, width=2))
                    if i_lbl and t0 > time
                        array.push(projLb, label.new(left, top, f_txt(s), xloc=xloc.bar_time, style=label.style_label_lower_left, color=cLblBg, textcolor=color.new(zc, 0), size=szLbl))
                    if array.size(projs) == 1
                        int mid = int((left + t1) / 2)
                        array.push(projLb, label.new(mid, top, "Daily H", xloc=xloc.bar_time, style=label.style_label_down, color=color.new(zc, 100), textcolor=color.new(zc, 0), size=size.tiny))
                        array.push(projLb, label.new(mid, bot, "Daily L", xloc=xloc.bar_time, style=label.style_label_up, color=color.new(zc, 100), textcolor=color.new(zc, 0), size=size.tiny))
 
// ───────────────────────────── Higher-timeframe bias ─────────────────────────────
f_biasReq(string tf) =>
    request.security(ticker.standard(syminfo.tickerid), tf, [close[1], ta.ema(close, i_bLen)[1], ta.ema(close, i_bLen)[2]], lookahead=barmerge.lookahead_on)
 
[h1C, h1E, h1P] = f_biasReq("60")
[h4C, h4E, h4P] = f_biasReq("240")
[d1C, d1E, d1P] = f_biasReq("1D")
 
f_bias(float c, float e, float p) =>
    na(c) or na(e) or na(p) ? 2 : c > e and e > p ? 1 : c < e and e < p ? -1 : 0
 
f_biasTxt(int b) =>
    b == 2 ? "—" : b > 0 ? "▲ BULL" : b < 0 ? "▼ BEAR" : "FLAT"
 
f_biasCol(int b) =>
    b == 2 ? cSteel : b > 0 ? cAccBuy : b < 0 ? cAccSell : cSilver
 
// ───────────────────────────── Dashboard ─────────────────────────────
szData = i_size == "Large" ? size.normal : i_size == "Medium" ? size.small : size.tiny
szSect = i_size == "Large" ? size.small : size.tiny
szHead = i_size == "Large" ? size.normal : i_size == "Medium" ? size.small : size.tiny
 
f_row_bg(int i) =>
    i % 2 == 0 ? cCharcoal : cGraphite
 
string tipShare = "Share of the last " + str.tostring(i_N) + " completed sessions that TRENDED (kept more of their farthest move than the median of 100 random-sign versions of the same half-hour moves) or RANGED (did not). The larger side is shown. Green: trend ≥ " + str.tostring(i_thr) + "%. Red: range ≥ " + str.tostring(i_thr) + "%. Otherwise BALANCED. It describes the past window, it does not forecast the next session."
string tipLive  = "▪ = session in progress"
 
var table panel = table.new(f_pos(i_pos), 10, 7, bgcolor=cObsidian, border_width=1, border_color=cGhost, frame_width=1, frame_color=cGhost)
if barstate.islast
    table.clear(panel, 0, 0, 9, 6)
    table.set_frame_width(panel, i_dash != "Off" or not ready ? 1 : 0)
if barstate.islast and (i_dash != "Off" or not ready)
    bool det = i_dash == "Detailed"
    int  lc  = det ? 9 : 4
    table.cell(panel, 0, 0, "SESSION ZONES " + VER, text_color=cChrome, bgcolor=cObsidian, text_size=szHead, text_halign=text.align_left, tooltip="Statistics are computed on 30-minute data for any chart timeframe from 1 to 30 minutes.")
    table.merge_cells(panel, 0, 0, lc, 0)
    string warn = not tfOk ? "INVALID TIMEFRAME · use 1, 2, 3, 5, 6, 10, 15 or 30 minutes" : not typOk ? "INVALID CHART TYPE · use candles, bars, line or Heikin Ashi" : not sesOk ? "INVALID HOURS · start and end on :00 or :30, start different from end" : eMis ? "MISALIGNED DATA · the symbol's 30-minute bars do not start at :00 and :30" : ""
    if warn != ""
        table.cell(panel, 0, 1, warn, text_color=cChrome, bgcolor=cCharcoal, text_size=szData, text_halign=text.align_left)
        table.merge_cells(panel, 0, 1, lc, 1)
    else if not det
        table.cell(panel, 0, 1, "SESSIONS · LAST " + str.tostring(i_N), text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_left)
        table.merge_cells(panel, 0, 1, 1, 1)
        table.cell(panel, 2, 1, i_tz == "Europe/Rome" ? "HOURS (ROME)" : "HOURS", text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_right, tooltip="Session clock: " + i_tz)
        table.cell(panel, 3, 1, "CHARACTER", text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_right, tooltip=tipShare)
        table.cell(panel, 4, 1, "SHARE", text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_right, tooltip=tipShare)
        for s = 0 to NS - 1
            color bg  = f_row_bg(s)
            bool  liv = ready and f_in(s, mins)
            int   sd  = f_side(s)
            string chr = na(sd) ? "COLLECTING" : sd > 0 ? "TREND" : sd < 0 ? "RANGE" : "BALANCED"
            color  cc  = na(sd) ? cSteel : sd == 0 ? cSilver : color.new(sd > 0 ? i_cKeep : i_cGive, 0)
            string shr = na(sd) ? str.tostring(na(f_st(s, 0)) ? 0 : int(f_st(s, 0))) + "/" + str.tostring(MIN_N) : str.upper(f_share(s))
            string tps = na(sd) ? "Collecting data" : "Trend " + str.tostring(f_pct(s)) + "% · Range " + str.tostring(f_lat(s)) + "%"
            table.cell(panel, 0, s + 2, liv ? "▪" : "▫", text_color=liv ? cChrome : cSteel, bgcolor=bg, text_size=szData, text_halign=text.align_center, tooltip=tipLive)
            table.cell(panel, 1, s + 2, f_name(s), text_color=cSilver, bgcolor=bg, text_size=szData, text_halign=text.align_left)
            table.cell(panel, 2, s + 2, f_hours(s), text_color=cSilver, bgcolor=bg, text_size=szData, text_halign=text.align_right)
            table.cell(panel, 3, s + 2, chr, text_color=cc, bgcolor=bg, text_size=szData, text_halign=text.align_right, tooltip=tipShare)
            table.cell(panel, 4, s + 2, shr, text_color=cc, bgcolor=bg, text_size=szData, text_halign=text.align_right, tooltip=tps)
    else
        array<string> hd = array.from("TREND %", "TEST", "KEEPS", "RANDOM", "DIFF [INTERVAL]", "VAR. RATIO", "NET / RANGE", "N")
        array<string> ht = array.from(tipShare, "Average keep ratio against the random baseline, 98.3% interval (Bonferroni for three sessions). KEEPS MORE: above random. GIVES BACK: below random. LIKE RANDOM: the interval contains zero.", "Average share of the farthest move still held at the close.", "Same half-hour moves replayed with random signs (100 paths per session).", "Keeps minus random, with the interval.", "Variance ratio: 1 = random, above 1 = trending, below 1 = mean-reverting.", "Median absolute net move / median range, in price.", "Completed sessions in the window.")
        table.cell(panel, 0, 1, "STATISTICS · LAST " + str.tostring(i_N), text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_left)
        table.merge_cells(panel, 0, 1, 1, 1)
        for c = 0 to 7
            table.cell(panel, c + 2, 1, array.get(hd, c), text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_right, tooltip=array.get(ht, c))
        for s = 0 to NS - 1
            color bg  = f_row_bg(s)
            bool  liv = ready and f_in(s, mins)
            int   sv  = f_state(s)
            string stTxt = sv == ST_KEEP ? "KEEPS MORE" : sv == ST_GIVE ? "GIVES BACK" : sv == ST_RAND ? "LIKE RANDOM" : "COLLECTING"
            color  sc    = sv == ST_KEEP ? color.new(i_cKeep, 0) : sv == ST_GIVE ? color.new(i_cGive, 0) : sv == ST_WAIT ? cSteel : cSilver
            int    sd    = f_side(s)
            int    pq    = f_pct(s)
            color  pc    = na(sd) ? cSteel : sd == 0 ? cSilver : color.new(sd > 0 ? i_cKeep : i_cGive, 0)
            table.cell(panel, 0, s + 2, liv ? "▪" : "▫", text_color=liv ? cChrome : cSteel, bgcolor=bg, text_size=szData, text_halign=text.align_center, tooltip=tipLive)
            table.cell(panel, 1, s + 2, f_name(s), text_color=cSilver, bgcolor=bg, text_size=szData, text_halign=text.align_left)
            table.cell(panel, 2, s + 2, pq < 0 ? "—" : str.tostring(pq) + " %", text_color=pc, bgcolor=bg, text_size=szData, text_halign=text.align_right)
            table.cell(panel, 3, s + 2, stTxt, text_color=sc, bgcolor=bg, text_size=szData, text_halign=text.align_right)
            table.cell(panel, 4, s + 2, f_p100(f_st(s, 1)), text_color=cChrome, bgcolor=bg, text_size=szData, text_halign=text.align_right)
            table.cell(panel, 5, s + 2, f_p100(f_st(s, 2)), text_color=cChrome, bgcolor=bg, text_size=szData, text_halign=text.align_right)
            table.cell(panel, 6, s + 2, f_dec(f_st(s, 3)) + " [" + f_dec(f_st(s, 4)) + " / " + f_dec(f_st(s, 5)) + "]", text_color=cChrome, bgcolor=bg, text_size=szData, text_halign=text.align_right)
            table.cell(panel, 7, s + 2, na(f_st(s, 6)) ? "—" : str.tostring(f_st(s, 6), "0.00"), text_color=cChrome, bgcolor=bg, text_size=szData, text_halign=text.align_right)
            table.cell(panel, 8, s + 2, na(f_st(s, 7)) ? "—" : f_pts(f_st(s, 7)) + " / " + f_pts(f_st(s, 8)), text_color=cChrome, bgcolor=bg, text_size=szData, text_halign=text.align_right)
            table.cell(panel, 9, s + 2, na(f_st(s, 0)) ? "0" : str.tostring(int(f_st(s, 0))), text_color=cChrome, bgcolor=bg, text_size=szData, text_halign=text.align_right)
    if warn == "" and i_bias
        int bH1 = f_bias(h1C, h1E, h1P)
        int bH4 = f_bias(h4C, h4E, h4P)
        int bD1 = f_bias(d1C, d1E, d1P)
        bool agree = bH1 == bH4 and bH4 == bD1 and (bH1 == 1 or bH1 == -1)
        string tipB = "Last closed bar of each timeframe vs EMA " + str.tostring(i_bLen) + ". ▲ BULL: close above a rising EMA. ▼ BEAR: close below a falling EMA. FLAT: anything else. — = not enough bars on that timeframe for the EMA."
        table.cell(panel, 0, 5, "BIAS", text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_left, tooltip=tipB)
        table.merge_cells(panel, 0, 5, 1, 5)
        int cH4 = det ? 4 : 3
        int cD1 = det ? 7 : 4
        table.cell(panel, 2, 5, "1h", text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_right)
        table.cell(panel, cH4, 5, "4h", text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_right)
        table.cell(panel, cD1, 5, "D", text_color=cSilver, bgcolor=cObsidian, text_size=szSect, text_halign=text.align_right)
        table.cell(panel, 0, 6, agree ? "▪" : "▫", text_color=agree ? cChrome : cSteel, bgcolor=f_row_bg(0), text_size=szData, text_halign=text.align_center, tooltip="▪ = the same bias on all three timeframes")
        table.cell(panel, 1, 6, "EMA " + str.tostring(i_bLen), text_color=cSilver, bgcolor=f_row_bg(0), text_size=szData, text_halign=text.align_left, tooltip=tipB)
        table.cell(panel, 2, 6, f_biasTxt(bH1), text_color=f_biasCol(bH1), bgcolor=f_row_bg(0), text_size=szData, text_halign=text.align_right, tooltip=tipB)
        table.cell(panel, cH4, 6, f_biasTxt(bH4), text_color=f_biasCol(bH4), bgcolor=f_row_bg(0), text_size=szData, text_halign=text.align_right, tooltip=tipB)
        table.cell(panel, cD1, 6, f_biasTxt(bD1), text_color=f_biasCol(bD1), bgcolor=f_row_bg(0), text_size=szData, text_halign=text.align_right, tooltip=tipB)
        if det
            table.merge_cells(panel, 2, 5, 3, 5)
            table.merge_cells(panel, 4, 5, 6, 5)
            table.merge_cells(panel, 7, 5, 9, 5)
            table.merge_cells(panel, 2, 6, 3, 6)
            table.merge_cells(panel, 4, 6, 6, 6)
            table.merge_cells(panel, 7, 6, 9, 6)
 
// ───────────────────────────── Data window ─────────────────────────────
plot(f_st(0, 0), "S1 n", display=display.data_window)
plot(f_st(0, 1), "S1 keep", display=display.data_window)
plot(f_st(0, 2), "S1 random keep", display=display.data_window)
plot(f_st(0, 4), "S1 diff low", display=display.data_window)
plot(f_st(0, 5), "S1 diff high", display=display.data_window)
plot(f_st(0, 6), "S1 variance ratio", display=display.data_window)
plot(f_st(0, 7), "S1 median net (ticks)", display=display.data_window)
plot(f_st(0, 9), "S1 test (0 collecting, 1 keeps, 2 gives back, 3 random)", display=display.data_window)
plot(f_st(1, 0), "S2 n", display=display.data_window)
plot(f_st(1, 1), "S2 keep", display=display.data_window)
plot(f_st(1, 2), "S2 random keep", display=display.data_window)
plot(f_st(1, 4), "S2 diff low", display=display.data_window)
plot(f_st(1, 5), "S2 diff high", display=display.data_window)
plot(f_st(1, 6), "S2 variance ratio", display=display.data_window)
plot(f_st(1, 7), "S2 median net (ticks)", display=display.data_window)
plot(f_st(1, 9), "S2 test (0 collecting, 1 keeps, 2 gives back, 3 random)", display=display.data_window)
plot(f_st(2, 0), "S3 n", display=display.data_window)
plot(f_st(2, 1), "S3 keep", display=display.data_window)
plot(f_st(2, 2), "S3 random keep", display=display.data_window)
plot(f_st(2, 4), "S3 diff low", display=display.data_window)
plot(f_st(2, 5), "S3 diff high", display=display.data_window)
plot(f_st(2, 6), "S3 variance ratio", display=display.data_window)
plot(f_st(2, 7), "S3 median net (ticks)", display=display.data_window)
plot(f_st(2, 9), "S3 test (0 collecting, 1 keeps, 2 gives back, 3 random)", display=display.data_window)
plot(f_st(0, 10), "S1 trending sessions", display=display.data_window)
plot(f_st(0, 11), "S1 trend share %", display=display.data_window)
plot(f_st(1, 10), "S2 trending sessions", display=display.data_window)
plot(f_st(1, 11), "S2 trend share %", display=display.data_window)
plot(f_st(2, 10), "S3 trending sessions", display=display.data_window)
plot(f_st(2, 11), "S3 trend share %", display=display.data_window)
plot(f_st(0, 12), "S1 in (1 trend, 0 range)", display=display.data_window)
plot(f_st(0, 13), "S1 out (1 trend, 0 range)", display=display.data_window)
plot(f_st(1, 12), "S2 in (1 trend, 0 range)", display=display.data_window)
plot(f_st(1, 13), "S2 out (1 trend, 0 range)", display=display.data_window)
plot(f_st(2, 12), "S3 in (1 trend, 0 range)", display=display.data_window)
plot(f_st(2, 13), "S3 out (1 trend, 0 range)", display=display.data_window)

← 返回列表