Time Beyond [Zen]

ChartZenFX · study · 297 行 · 点赞 8 · TradingView 原页

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

Pine Script

//@version=6
indicator("Time Beyond [Zen]", overlay = true, max_labels_count = 200, max_lines_count = 200)
 
// Time Beyond [Zen]
// Event = a liquidity sweep on a closed candle (same sweep rule as Sweep Entry Zone [Zen]); the script does not wait for a BOS.
// For every sweep it counts what share of the lower-timeframe closes inside the sweep candle were beyond the pool:
// FLASH = a small share of those closes was beyond the pool, HELD = a large share.
// A class is given only when lower-timeframe candles cover the sweep candle from its open to its close without a gap
// or an overlap; otherwise the sweep is not classified.
// The table shows what happened after past sweeps of each class on this chart. Descriptive statistics, not a forecast.
 
// ---------- Inputs ----------
gP = "Sweep (rule of Sweep Entry Zone)"
poolLen = input.int(20, "Pool length (candles)", minval = 5, group = gP, display = display.none, tooltip = "Pool = highest high / lowest low of the previous N closed candles. Sweep = wick beyond the pool and close back inside, on a closed candle.")
 
gC = "Time beyond the pool"
subTf    = input.timeframe("15", "Lower timeframe", group = gC, display = display.none, tooltip = "The sweep candle is split into candles of this timeframe. The script counts what share of them closed beyond the pool.")
flashMax = input.float(6.25, "FLASH: share of closes beyond, up to (%)", minval = 0, maxval = 100, step = 0.25, group = gC, display = display.none, tooltip = "Share of the lower-timeframe closes inside the sweep candle that were beyond the pool. 6.25% = 1 close of 16.")
heldMin  = input.float(25.0, "HELD: share of closes beyond, from (%)", minval = 0.01, maxval = 100, step = 1, group = gC, display = display.none, tooltip = "25% = 4 closes of 16.")
 
gO = "Outcome"
atrLen  = input.int(14, "ATR length", minval = 1, group = gO, display = display.none, tooltip = "ATR of the candles before the sweep candle.")
moveAtr = input.float(1.0, "Reversal size (ATR)", minval = 0.1, step = 0.1, group = gO, display = display.none, tooltip = "After a sweep the script watches which comes first: a move of this size back from the pool, counted from the close of the sweep candle, or a new break of the sweep extreme.")
resBars = input.int(12, "Outcome window (candles)", minval = 1, maxval = 100, group = gO, display = display.none)
minN    = input.int(30, "Minimum sample", minval = 1, group = gO, display = display.none, tooltip = "Percentages are shown only when a class has at least this many finished sweeps.")
 
gV = "Display"
showLabels = input.bool(true, "Show sweep labels", group = gV, display = display.none, tooltip = "The label shows the class and the count of lower-timeframe closes beyond the pool. Hover over it to see what happened after that sweep.")
showTable  = input.bool(true, "Show table", group = gV, display = display.none)
tablePos   = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gV, display = display.none)
 
int chartSec = timeframe.in_seconds()
int lowerSec = timeframe.in_seconds(subTf)
if lowerSec >= chartSec or chartSec % lowerSec != 0
    runtime.error("Lower timeframe must be smaller than the chart timeframe and divide it evenly")
if heldMin <= flashMax
    runtime.error("HELD threshold must be greater than FLASH threshold")
string tfTxt = lowerSec < 60 ? str.tostring(lowerSec) + "s" : lowerSec < 3600 ? str.tostring(lowerSec / 60) + "m" : lowerSec < 86400 ? str.tostring(lowerSec / 3600) + "h" : subTf
 
// ---------- ChartZenFX palette (auto light / dark) ----------
bool isLight = (color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color)) / 3 > 128
color cHI    = isLight ? #AD4A12 : #D9703A
color cLO    = isLight ? #1B46B4 : #6F88EE
color cMUTED = isLight ? #647482 : #8391A4
 
const int NEAR_BARS = 12   // labels of the same side closer than this are put on separate text rows
const int LBL_SPAN  = 6    // a fresh label is kept clear of the candles printing next to it for this many candles
 
// ---------- Pool and sweep (closed candles), as in Sweep Entry Zone ----------
float atrPrev = ta.atr(atrLen)[1]
float hh = ta.highest(high, poolLen)[1]
float ll = ta.lowest(low, poolLen)[1]
int hhBar = bar_index - 1 + ta.highestbars(high, poolLen)[1]
int llBar = bar_index - 1 + ta.lowestbars(low, poolLen)[1]
bool ok  = bar_index >= poolLen
bool swH = ok and high > hh and close <= hh
bool swL = ok and low < ll and close >= ll
bool swHonly = swH and not swL          // a candle that sweeps both pools is skipped
bool swLonly = swL and not swH
 
// ---------- Lower-timeframe candles inside the current candle: close, open time, close time ----------
[subC, subT, subTC] = request.security_lower_tf(syminfo.tickerid, subTf, [close, time, time_close])
 
// ---------- Sweep events and statistics ----------
type Ev
    int    cls      // 1 FLASH, 2 MID, 3 HELD
    int    dir      // 1 = low sweep (reversal up), -1 = high sweep (reversal down)
    int    born
    float  tgt
    float  ext
    label  lb
    string base     // label text
    string info     // second line of the tooltip
 
var array<Ev>  evs   = array.new<Ev>()
// index 0 = ALL, 1 = FLASH, 2 = MID, 3 = HELD
var array<int> nFin  = array.new<int>(4, 0)   // finished classified sweeps (the denominator)
var array<int> nRev  = array.new<int>(4, 0)   // reversal move came first
var array<int> nExt  = array.new<int>(4, 0)   // sweep extreme was broken first
var array<int> nNone = array.new<int>(4, 0)   // neither within the window
var array<int> nBoth = array.new<int>(4, 0)   // both on one candle, order unknown
var int nNoData  = 0                          // sweeps with no lower-timeframe candles: not classified, not in any percentage
var int nPartial = 0                          // sweeps where lower-timeframe candles cover only part of the candle: same
// last label of each side (0 = low sweep, 1 = high sweep): its candle and its text row
var array<int>   stBar = array.new<int>(2, na)
var array<int>   stRow = array.new<int>(2, 0)
var array<label> stLb  = array.new<label>(2, na)
// fresh labels that are still being kept clear of the candles printing next to them
var array<label> adjLb   = array.new<label>()
var array<int>   adjBorn = array.new<int>()
var array<int>   adjDir  = array.new<int>()
 
bool swFlash = false
bool swMid   = false
bool swHeld  = false
string msg = ""
 
f_inc(array<int> a, int cls) =>
    a.set(0, a.get(0) + 1)
    a.set(cls, a.get(cls) + 1)
 
f_name(int cls) =>
    cls == 1 ? "FLASH" : cls == 2 ? "MID" : "HELD"
 
f_side(int dir) =>
    dir == 1 ? "Low sweep" : "High sweep"
 
f_share(array<int> a, int cls) =>
    int n = nFin.get(cls)
    n >= minN ? str.tostring(a.get(cls)) + " (" + str.tostring(100.0 * a.get(cls) / n, "#") + "%)" : str.tostring(a.get(cls))
 
f_tip(int dir, string info, string res) =>
    f_side(dir) + "\n" + info + "\nOutcome: " + res
 
// coverage of a candle [t0, t1] by lower-timeframe candles, checked joint by joint: the first one must open at t0,
// each next one must open exactly when the previous one closed, and the last one must close at t1.
// 0 = no lower-timeframe candles, 1 = a gap, an overlap or a wrong start / end, 2 = the whole candle is covered.
f_cover(array<float> c, array<int> t, array<int> tc, int t0, int t1) =>
    int n = t.size()
    int st = 0
    if n > 0
        st := 1
        bool chain = not na(t0) and not na(t1) and c.size() == n and tc.size() == n
        int edge = t0
        if chain
            for i = 0 to n - 1
                int a = t.get(i)
                int b = tc.get(i)
                if na(c.get(i)) or na(a) or na(b) or a != edge or b <= a
                    chain := false
                    break
                edge := b
        if chain and edge == t1
            st := 2
    st
 
// number of lower-timeframe closes beyond the pool (called only when the candle is fully covered)
f_beyond(int dir, float pool) =>
    int cnt = 0
    for i = 0 to subC.size() - 1
        float p = subC.get(i)
        if dir == -1 ? p > pool : p < pool
            cnt += 1
    cnt
 
// label at the sweep extreme; neighbouring labels of the same side go to the next text row so that they do not overlap
f_label(int dir, string txt, color c, string tip, bool tiny) =>
    int si = dir == 1 ? 0 : 1
    int row = 0
    float y = dir == 1 ? low : high
    if not na(stBar.get(si)) and bar_index - stBar.get(si) <= NEAR_BARS
        row := (stRow.get(si) + 1) % 3
        float py = label.get_y(stLb.get(si))
        if not na(py)
            y := dir == 1 ? math.min(y, py) : math.max(y, py)
    stBar.set(si, bar_index)
    stRow.set(si, row)
    string pad = row == 0 ? "" : row == 1 ? "\n" : "\n\n"
    label lb = label.new(bar_index, y, dir == 1 ? pad + txt : txt + pad, style = dir == 1 ? label.style_label_up : label.style_label_down, color = color.new(c, 100), textcolor = c, size = tiny ? size.tiny : size.small, tooltip = tip)
    stLb.set(si, lb)
    adjLb.push(lb)
    adjBorn.push(bar_index)
    adjDir.push(dir)
    lb
 
// returns the class of the new event: 1..3, 0 = not classified (no or incomplete lower-timeframe data), -1 = no ATR yet
f_sweep(int dir, float pool, int poolBar, int cover) =>
    int cls = -1
    if not na(atrPrev) and atrPrev > 0
        int n = subC.size()
        if cover < 2
            cls := 0
            if showLabels
                string why = cover == 0 ? "No " + tfTxt + " candles for this candle." : tfTxt + " candles do not cover this candle from open to close without a gap (" + str.tostring(n) + " found)."
                f_label(dir, cover == 0 ? "NO DATA" : "PARTIAL", cMUTED, f_side(dir) + "\n" + why + "\nNot classified, not in the table.", true)
        else
            int cnt = f_beyond(dir, pool)
            float share = 100.0 * cnt / n
            cls := share <= flashMax ? 1 : share < heldMin ? 2 : 3
            color c = dir == 1 ? cLO : cHI
            string base = f_name(cls) + " " + str.tostring(cnt) + "/" + str.tostring(n) + " x " + tfTxt
            string info = f_name(cls) + ": " + str.tostring(cnt) + " of " + str.tostring(n) + " " + tfTxt + " closes beyond the pool (" + str.tostring(share, "#.##") + "%)"
            label lb = na
            if showLabels
                line.new(poolBar, pool, bar_index, pool, color = color.new(c, 30), width = 1, style = line.style_solid)
                lb := f_label(dir, base, c, f_tip(dir, info, "not finished yet (window " + str.tostring(resBars) + " candles)"), false)
            evs.push(Ev.new(cls, dir, bar_index, close + dir * moveAtr * atrPrev, dir == 1 ? low : high, lb, base, info))
    cls
 
if barstate.isconfirmed
    // ----- fresh labels: step away if a new candle prints through them (position only, nothing is recalculated) -----
    int a = adjLb.size() - 1
    while a >= 0
        if bar_index - adjBorn.get(a) > LBL_SPAN
            adjLb.remove(a)
            adjBorn.remove(a)
            adjDir.remove(a)
        else if bar_index > adjBorn.get(a)
            label q = adjLb.get(a)
            if adjDir.get(a) == 1 and low < label.get_y(q)
                label.set_y(q, low)
            if adjDir.get(a) == -1 and high > label.get_y(q)
                label.set_y(q, high)
        a -= 1
 
    // ----- open sweep events: which came first (checked from the candle after the sweep) -----
    int k = evs.size() - 1
    while k >= 0
        Ev e = evs.get(k)
        int age = bar_index - e.born
        if age > 0
            bool hitT = e.dir == 1 ? high >= e.tgt : low <= e.tgt
            bool hitE = e.dir == 1 ? low < e.ext : high > e.ext
            string res = ""
            if hitT and hitE
                f_inc(nBoth, e.cls)
                res := "both on one candle (candle " + str.tostring(age) + "), order unknown"
            else if hitT
                f_inc(nRev, e.cls)
                res := str.tostring(moveAtr) + " ATR reversal first, candle " + str.tostring(age)
            else if hitE
                f_inc(nExt, e.cls)
                res := "sweep extreme broken first, candle " + str.tostring(age)
            else if age >= resBars
                f_inc(nNone, e.cls)
                res := "neither in " + str.tostring(resBars) + " candles"
            if res != ""
                f_inc(nFin, e.cls)
                if not na(e.lb)
                    label.set_tooltip(e.lb, f_tip(e.dir, e.info, res))
                evs.remove(k)
        k -= 1
 
    // ----- new sweep on this closed candle -----
    if swHonly or swLonly
        int dir = swHonly ? -1 : 1
        float pool = swHonly ? hh : ll
        int cover = f_cover(subC, subT, subTC, time, time_close)
        int cls = f_sweep(dir, pool, swHonly ? hhBar : llBar, cover)
        if cls == 0
            if cover == 0
                nNoData += 1
            else
                nPartial += 1
            msg += f_side(dir) + ": not classified (" + (cover == 0 ? "no " : "partial ") + tfTxt + " data for this candle)\n"
        else if cls > 0
            swFlash := cls == 1
            swMid   := cls == 2
            swHeld  := cls == 3
            Ev ne = evs.last()
            msg += f_side(dir) + ": " + ne.base + " closes beyond the pool | pool " + str.tostring(pool, format.mintick) + " | past " + f_name(cls) + ": reversal first " + f_share(nRev, cls) + " of " + str.tostring(nFin.get(cls)) + "\n"
 
// ---------- Table ----------
f_pos(string s) =>
    s == "Top right" ? position.top_right : s == "Bottom right" ? position.bottom_right : s == "Top left" ? position.top_left : position.bottom_left
 
f_row(table t, int row, string name, int cls, color txt, color bg) =>
    table.cell(t, 0, row, name, text_color = txt, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(t, 1, row, str.tostring(nFin.get(cls)), text_color = txt, bgcolor = bg, text_size = size.small)
    table.cell(t, 2, row, f_share(nRev, cls), text_color = txt, bgcolor = bg, text_size = size.small)
    table.cell(t, 3, row, f_share(nExt, cls), text_color = txt, bgcolor = bg, text_size = size.small)
    table.cell(t, 4, row, f_share(nNone, cls), text_color = txt, bgcolor = bg, text_size = size.small)
    table.cell(t, 5, row, f_share(nBoth, cls), text_color = txt, bgcolor = bg, text_size = size.small)
 
var table panel = table.new(f_pos(tablePos), 6, 8, border_width = 0)
if barstate.islast and showTable
    color txt = chart.fg_color
    color hdr = color.new(cMUTED, 65)
    color bg  = color.new(chart.bg_color, 15)     // own background, so the numbers stay readable over candles
    int r0 = 0
    if str.startswith(tablePos, "Top")
        // empty row: keeps the table below the chart status line on narrow charts
        table.cell(panel, 0, 0, "", height = 7)
        table.merge_cells(panel, 0, 0, 5, 0)
        r0 := 1
    table.cell(panel, 0, r0, tfTxt + " closes beyond", text_color = txt, bgcolor = hdr, text_size = size.small, text_halign = text.align_left, tooltip = "Share of the " + tfTxt + " candles inside the sweep candle that closed beyond the pool.")
    table.cell(panel, 1, r0, "N", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Finished classified sweeps of the row on this chart. Every percentage in the row is a share of this N.")
    table.cell(panel, 2, r0, "Reversal first", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Price moved " + str.tostring(moveAtr) + " ATR back from the pool, counted from the close of the sweep candle, before the sweep extreme was broken, within " + str.tostring(resBars) + " candles.")
    table.cell(panel, 3, r0, "Extreme first", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "The sweep extreme was broken first, within " + str.tostring(resBars) + " candles.")
    table.cell(panel, 4, r0, "Neither", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Neither happened within " + str.tostring(resBars) + " candles.")
    table.cell(panel, 5, r0, "Both", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Both happened on the same candle, so the order is unknown.")
    f_row(panel, r0 + 1, "ALL", 0, txt, bg)
    f_row(panel, r0 + 2, "FLASH  <= " + str.tostring(flashMax) + "%", 1, txt, bg)
    f_row(panel, r0 + 3, "MID", 2, txt, bg)
    f_row(panel, r0 + 4, "HELD  >= " + str.tostring(heldMin) + "%", 3, txt, bg)
    table.cell(panel, 0, r0 + 5, "% of N | window " + str.tostring(resBars) + " | not finished: " + str.tostring(evs.size()), text_color = cMUTED, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.merge_cells(panel, 0, r0 + 5, 5, r0 + 5)
    table.cell(panel, 0, r0 + 6, "no class: no " + tfTxt + " data " + str.tostring(nNoData) + " | partial " + str.tostring(nPartial), text_color = cMUTED, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.merge_cells(panel, 0, r0 + 6, 5, r0 + 6)
 
// ---------- Alerts ----------
if barstate.isconfirmed and msg != ""
    alert(msg + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
alertcondition(swFlash or swMid or swHeld, "Sweep (any class)", "Sweep on {{ticker}} {{interval}}")
alertcondition(swFlash, "Sweep: FLASH", "FLASH sweep on {{ticker}} {{interval}}")
alertcondition(swMid, "Sweep: MID", "MID sweep on {{ticker}} {{interval}}")
alertcondition(swHeld, "Sweep: HELD", "HELD sweep on {{ticker}} {{interval}}")

← 返回列表