Session Extremes vs Random [KomiTrade]

KomiTrade · study · 304 行 · 点赞 7 · 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/
// © KomiTrade — Pavel
//
// Session Extremes vs Random [KomiTrade]
// Version 0.1.2 (2026-11-15) · compiled in TV 2026-11-13 (MNQ1! 5m and 1h, no errors).
//
// Originality check (2026-10-29): session boxes and counts of the day's high / low by session already exist on
// TradingView; this script adds a control group (random walk of the same length) and a two-standard-error test.
//
// What it does: draws the three sessions of the day in New York time (default CME futures: Asia 18:00-03:00,
// Europe 03:00-09:30, US 09:30-17:00) as light boxes with a midline, and shows in a table in which session the
// high and the low of the day were made over the last N days, next to what a random walk of the same length would
// give (arcsine law: extremes are more frequent near the start and the end of the day). Arrows mark a difference
// larger than two standard errors (up / down, otherwise approx.). Live marks show which session holds today's high
// and low so far. No signals, no forecasts.
//
// Design: presets via input.enum, labels in English / Czech / German / Spanish, theme from chart.bg_color, layer
// switches, calculations on confirmed bars only (no request.security, varip, timenow or calc_on_every_tick),
// compact mode for phones, one label per session so labels never overlap.
//
// Limitations: intraday charts only (on D / W / M the table shows a note); session borders follow the bar open time,
// exact on timeframes of 30 minutes or less; the day = the symbol's trading session; bars outside the three sessions
// are not counted; shares come from the history loaded on the chart (note when fewer than 20 days); the random walk
// assumes constant volatility per bar, real volatility is uneven (US open), so "up" for the US session often reflects
// volatility only. A description of the past, not a trading signal.
//
// Changelog:
//   0.1.0 (2026-10-29) first version.
//   0.1.1 (2026-11-13) session colours renamed (name clash with counters).
//   0.1.2 (2026-11-15) comments in English for publication.
//@version=6
indicator("Session Extremes vs Random [KomiTrade]", shorttitle = "Sessions vs Random", overlay = true, max_boxes_count = 200, max_lines_count = 200, max_labels_count = 200)
 
// ───────────────────────── Inputs ─────────────────────────
enum Preset
    futures = "CME futures (New York time)"
    stocks  = "US stocks (pre / RTH / post)"
    custom  = "Custom"
 
enum Lang
    en = "English"
    cs = "Czech (CZ)"
    de = "German (DE)"
    es = "Spanish (ES)"
 
enum Theme
    automatic = "Auto (chart background)"
    dark      = "Dark"
    light     = "Light"
 
const string G_GEN = "General"
const string G_SES = "Sessions (Custom)"
const string G_LAY = "Layers"
const string TZ = "America/New_York"
 
Preset iPreset  = input.enum(Preset.futures, "Preset", group = G_GEN, tooltip = "One version for all markets. Custom unlocks the session times below (New York time).")
Lang   iLang    = input.enum(Lang.en, "Language", group = G_GEN, tooltip = "Language of labels and table. Input names stay in English.")
Theme  iTheme   = input.enum(Theme.automatic, "Theme", group = G_GEN)
bool   iCompact = input.bool(false, "Compact mode (phone)", group = G_GEN, tooltip = "Smaller text, table with one column.")
int    iAvgN    = input.int(60, "Statistics: last N days", minval = 10, maxval = 250, group = G_GEN, tooltip = "Share of the last N completed days in which the day's high / low was made in each session.")
int    iDays    = input.int(5, "Days to keep on chart", minval = 1, maxval = 60, group = G_GEN)
 
string iS1C = input.session("1800-0300", "Session 1", group = G_SES, active = iPreset == Preset.custom)
string iS2C = input.session("0300-0930", "Session 2", group = G_SES, active = iPreset == Preset.custom)
string iS3C = input.session("0930-1700", "Session 3", group = G_SES, active = iPreset == Preset.custom)
 
bool   iShow1   = input.bool(true, "Show session 1", group = G_LAY)
bool   iShow2   = input.bool(true, "Show session 2", group = G_LAY)
bool   iShow3   = input.bool(true, "Show session 3", group = G_LAY)
bool   iShowMid = input.bool(true, "Show session midline", group = G_LAY)
bool   iShowLbl = input.bool(true, "Show end-of-session labels", group = G_LAY)
bool   iShowTbl = input.bool(true, "Show table", group = G_LAY)
string iTblPos  = input.string(position.top_right, "Table position", options = [position.top_right, position.bottom_right, position.top_left, position.bottom_left], group = G_LAY)
 
// ───────────────────────── Language ─────────────────────────
tx(string en, string cs, string de, string es) =>
    switch iLang
        Lang.cs => cs
        Lang.de => de
        Lang.es => es
        => en
 
// ───────────────────────── Presets ─────────────────────────
string s1 = switch iPreset
    Preset.futures => "1800-0300"
    Preset.stocks  => "0400-0930"
    => iS1C
string s2 = switch iPreset
    Preset.futures => "0300-0930"
    Preset.stocks  => "0930-1600"
    => iS2C
string s3 = switch iPreset
    Preset.futures => "0930-1700"
    Preset.stocks  => "1600-2000"
    => iS3C
string n1 = iPreset == Preset.stocks ? tx("Pre-market", "Před otevřením", "Vorbörse", "Preapertura") : iPreset == Preset.futures ? tx("Asia", "Asie", "Asien", "Asia") : tx("Session 1", "Seance 1", "Sitzung 1", "Sesión 1")
string n2 = iPreset == Preset.stocks ? tx("Regular hours", "Hlavní seance", "Haupthandel", "Horario regular") : iPreset == Preset.futures ? tx("Europe", "Evropa", "Europa", "Europa") : tx("Session 2", "Seance 2", "Sitzung 2", "Sesión 2")
string n3 = iPreset == Preset.stocks ? tx("After-hours", "Po zavření", "Nachbörse", "Posmercado") : iPreset == Preset.futures ? tx("US", "USA", "USA", "EE. UU.") : tx("Session 3", "Seance 3", "Sitzung 3", "Sesión 3")
 
// ───────────────────────── Theme ─────────────────────────
color bg = chart.bg_color
float bgLum = (0.299 * color.r(bg) + 0.587 * color.g(bg) + 0.114 * color.b(bg)) / 255.0
bool isDark = iTheme == Theme.automatic ? bgLum < 0.5 : iTheme == Theme.dark
color cText  = isDark ? color.rgb(226, 232, 240) : color.rgb(30, 41, 59)
color cMute  = isDark ? color.rgb(148, 163, 184) : color.rgb(100, 116, 139)
color cPanel = isDark ? color.rgb(22, 30, 46) : color.rgb(241, 245, 249)
color cS1 = isDark ? color.rgb(167, 139, 250) : color.rgb(109, 40, 217)
color cS2 = isDark ? color.rgb(56, 189, 248) : color.rgb(3, 105, 161)
color cS3 = isDark ? color.rgb(251, 146, 60) : color.rgb(194, 65, 12)
string tSize = iCompact ? size.tiny : size.small
 
// ───────────────────────── Session (UDT) ─────────────────────────
type Sess
    string     name
    color      col
    bool       show
    bool       active = false
    float      hi = na
    float      lo = na
    int        t0 = na
    box        bx = na
    line       mid = na
    float      last = na
    array<box>   boxes
    array<line>  mids
    array<label> lbls
 
newSess(string nm, color c, bool sh) =>
    Sess.new(nm, c, sh, boxes = array.new<box>(), mids = array.new<line>(), lbls = array.new<label>())
 
method trim(Sess s) =>
    while s.boxes.size() > iDays
        box.delete(s.boxes.shift())
    while s.mids.size() > iDays
        line.delete(s.mids.shift())
    while s.lbls.size() > iDays
        label.delete(s.lbls.shift())
 
// call on confirmed bars only
method step(Sess s, bool inS, bool startS) =>
    if s.active and (not inS or startS)
        // end of session: store the range and one label (so labels never overlap)
        float rng = s.hi - s.lo
        s.last := rng
        if s.show and iShowLbl and not na(s.bx)
            string t = s.name + "  " + str.tostring(rng, format.mintick)
            s.lbls.push(label.new(bar_index - 1, s.hi, t, style = label.style_label_lower_left, color = color.new(cPanel, 10), textcolor = cText, size = tSize))
        s.active := false
        s.trim()
    if startS
        s.active := true
        s.hi := high
        s.lo := low
        s.t0 := bar_index
        if s.show
            s.bx := box.new(bar_index, high, bar_index, low, border_color = color.new(s.col, 55), bgcolor = color.new(s.col, 90), border_width = 1)
            s.boxes.push(s.bx)
            if iShowMid
                s.mid := line.new(bar_index, (high + low) / 2, bar_index, (high + low) / 2, color = color.new(s.col, 40), style = line.style_dotted)
                s.mids.push(s.mid)
    else if s.active and inS
        s.hi := math.max(s.hi, high)
        s.lo := math.min(s.lo, low)
        if s.show and not na(s.bx)
            s.bx.set_top(s.hi)
            s.bx.set_bottom(s.lo)
            s.bx.set_right(bar_index)
            if iShowMid and not na(s.mid)
                s.mid.set_xy2(bar_index, (s.hi + s.lo) / 2)
                s.mid.set_y1((s.hi + s.lo) / 2)
 
var Sess S1 = newSess(n1, cS1, iShow1)
var Sess S2 = newSess(n2, cS2, iShow2)
var Sess S3 = newSess(n3, cS3, iShow3)
 
bool intraday = timeframe.isintraday
bool in1 = intraday and not na(time(timeframe.period, s1, TZ))
bool in2 = intraday and not na(time(timeframe.period, s2, TZ))
bool in3 = intraday and not na(time(timeframe.period, s3, TZ))
 
if barstate.isconfirmed and intraday
    S1.step(in1, in1 and not in1[1])
    S2.step(in2, in2 and not in2[1])
    S3.step(in3, in3 and not in3[1])
 
// ───────────────────────── Day: session of the high / low (0 = outside sessions) ─────────────────────────
var float dHi = na
var float dLo = na
var int   hiS = 0
var int   loS = 0
var int   c1 = 0
var int   c2 = 0
var int   c3 = 0
var array<int>   hiHist = array.new<int>()
var array<int>   loHist = array.new<int>()
var array<float> f1Hist = array.new<float>()   // end of session 1 as a share of the day's bars (order 1 -> 2 -> 3)
var array<float> f2Hist = array.new<float>()   // end of session 2
int sNow = in3 ? 3 : in2 ? 2 : in1 ? 1 : 0
if barstate.isconfirmed and intraday
    if timeframe.change("D")
        int nn = c1 + c2 + c3
        if not na(dHi) and nn > 0
            hiHist.push(hiS)
            loHist.push(loS)
            f1Hist.push(float(c1) / nn)
            f2Hist.push(float(c1 + c2) / nn)
            if hiHist.size() > 400
                hiHist.shift()
                loHist.shift()
                f1Hist.shift()
                f2Hist.shift()
        dHi := high
        dLo := low
        hiS := sNow
        loS := sNow
        c1 := 0
        c2 := 0
        c3 := 0
    else if not na(dHi)
        if high > dHi
            dHi := high
            hiS := sNow
        if low < dLo
            dLo := low
            loS := sNow
    c1 += sNow == 1 ? 1 : 0
    c2 += sNow == 2 ? 1 : 0
    c3 += sNow == 3 ? 1 : 0
 
lastMean(array<float> a, int n) =>
    int k = math.min(n, a.size())
    float t = 0.0
    if k > 0
        for i = a.size() - k to a.size() - 1
            t += a.get(i)
    k > 0 ? t / k : na
 
countOf(array<int> a, int sx, int n) =>
    int k = math.min(n, a.size())
    int c = 0
    if k > 0
        for i = a.size() - k to a.size() - 1
            c += a.get(i) == sx ? 1 : 0
    c
 
// Random walk control: with constant volatility the time of the maximum (and minimum) follows the arcsine law
// F(x) = 2 / pi * asin(sqrt(x)) — extremes are more frequent near the start and end of the day. Time = share of the day's bars.
arcF(float x) =>
    2.0 / math.pi * math.asin(math.sqrt(math.max(0.0, math.min(1.0, x))))
int   nStat = math.min(iAvgN, hiHist.size())
float fb1 = lastMean(f1Hist, iAvgN)
float fb2 = lastMean(f2Hist, iAvgN)
float p1 = na(fb1) ? na : arcF(fb1)
float p2 = na(fb1) ? na : arcF(fb2) - arcF(fb1)
float p3 = na(fb1) ? na : 1.0 - arcF(fb2)
 
// "↑" / "↓" = difference from the random walk larger than 2 binomial standard errors, otherwise "≈"
cmpTxt(int k, int n, float p) =>
    string r = "—"
    if n > 0 and not na(p)
        float z = p > 0 and p < 1 ? (k - n * p) / math.sqrt(n * p * (1 - p)) : 0.0
        r := str.tostring(math.round(100.0 * k / n)) + " % " + (z >= 2 ? "↑" : z <= -2 ? "↓" : "≈") + " " + str.tostring(math.round(p * 100))
    r
 
// status line / Data Window: midline of the running session (confirmed bars only)
float curMid = S3.active ? (S3.hi + S3.lo) / 2 : S2.active ? (S2.hi + S2.lo) / 2 : S1.active ? (S1.hi + S1.lo) / 2 : na
plot(curMid, "Active session mid", color = color.new(cMute, 100), display = display.data_window)
 
// ───────────────────────── Table ─────────────────────────
var table tbl = table.new(iTblPos, 4, 5, border_width = 1, frame_width = 1, frame_color = color.new(cMute, 60))
rowSess(int r, Sess s, int sx, float p) =>
    float now = s.active ? s.hi - s.lo : s.last
    color hb = color.new(cPanel, 0)
    table.cell(tbl, 0, r, s.name + (s.active ? " ●" : ""), text_color = s.col, bgcolor = hb, text_size = tSize, text_halign = text.align_left)
    table.cell(tbl, 1, r, cmpTxt(countOf(hiHist, sx, iAvgN), nStat, p) + (hiS == sx ? "  ▲" : ""), text_color = cText, bgcolor = hb, text_size = tSize)
    table.cell(tbl, 2, r, cmpTxt(countOf(loHist, sx, iAvgN), nStat, p) + (loS == sx ? "  ▼" : ""), text_color = cText, bgcolor = hb, text_size = tSize)
    if not iCompact
        table.cell(tbl, 3, r, na(now) ? "—" : str.tostring(now, format.mintick), text_color = cMute, bgcolor = hb, text_size = tSize)
 
if iShowTbl and barstate.islast
    color hb = color.new(cPanel, 0)
    if not intraday
        table.cell(tbl, 0, 0, tx("Intraday charts only", "Jen intradenní graf", "Nur Intraday-Charts", "Solo gráficos intradía"), text_color = cMute, bgcolor = hb, text_size = tSize)
    else
        table.cell(tbl, 0, 0, tx("Session", "Seance", "Sitzung", "Sesión"), text_color = cMute, bgcolor = hb, text_size = tSize)
        table.cell(tbl, 1, 0, tx("Day high here", "Max dne zde", "Tageshoch hier", "Máx. del día aquí"), text_color = cMute, bgcolor = hb, text_size = tSize)
        table.cell(tbl, 2, 0, tx("Day low here", "Min dne zde", "Tagestief hier", "Mín. del día aquí"), text_color = cMute, bgcolor = hb, text_size = tSize)
        if not iCompact
            table.cell(tbl, 3, 0, tx("Range", "Rozpětí", "Spanne", "Rango"), text_color = cMute, bgcolor = hb, text_size = tSize)
        int r = 1
        if iShow1
            rowSess(r, S1, 1, p1)
            r += 1
        if iShow2
            rowSess(r, S2, 2, p2)
            r += 1
        if iShow3
            rowSess(r, S3, 3, p3)
            r += 1
        string foot = tx("Last ", "Posledních ", "Letzte ", "Últimos ") + str.tostring(nStat) + tx(" days", " dní", " Tage", " días") + (nStat < 20 ? " · " + tx("few data", "málo dat", "wenig Daten", "pocos datos") : "") + " · " + tx("last number = random walk %", "poslední číslo = náhodná procházka %", "letzte Zahl = Zufallspfad %", "último número = paseo aleatorio %")
        if not iCompact
            foot += " · ↑↓ " + tx("more than 2 standard errors from random", "víc než 2 směrodatné chyby od náhody", "mehr als 2 Standardfehler vom Zufall", "más de 2 errores estándar del azar") + " · ▲▼ " + tx("today", "dnes", "heute", "hoy")
        table.cell(tbl, 0, r, foot, text_color = cMute, bgcolor = hb, text_size = size.tiny)
        table.merge_cells(tbl, 0, r, iCompact ? 2 : 3, r)

← 返回列表