Sphinx Horizon: Weekly & Daily Context

TheHermeticTrader · study · 552 行 · 点赞 5 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0
// © Hermetic Trader. All rights reserved.
// Sphinx Horizon v1.1.9
// v1.1.9: level lines start at the candle that made the high / low; gap boxes
//         start at the gap's middle candle.
// v1.1.8: SMT always measured on the full contracts (ES / NQ / YM), also for the
//         chart's own index - micro and full charts show the same SMTs.
// v1.1.7: level labels that sit on top of each other merge (PWH · PDH).
// v1.1.6: the index that fails must also miss its level by the margin - equal
//         highs / lows no longer count as SMTs.
// v1.1.5: hover a past SMT tag to see how far each index took or missed its level.
// v1.1.4: sister data uses the chart's own settings (back-adjustment, session),
//         so contract rolls no longer create false SMTs.
// v1.1.3: SMT only at external liquidity - the index that takes the level must
//         make the highest high / lowest low of the last N weeks / days.
// v1.1.2: option to connect the two highs / lows of each SMT with a line.
// v1.1.1: SMT tightened - ES / NQ pair by default, the index that takes the
//         level must clear it by a margin and the one that fails must not reach
//         it at all; past daily SMTs off by default; no daily tag stacked on a
//         weekly one.
// v1.1: v1.1: HTF SMT - divergence between ES / NQ / YM at the prior week / day
//       high or low, live in the panel, on the level labels, past SMTs marked,
//       alerts.
// v1.0.1: compile fix (CE10235) - gap fill uses separate if blocks.
// Weekly and daily location HUD for intraday charts. Shows where price sits in
// the higher-timeframe picture: prior week / day highs and lows, the nearest
// unfilled weekly gaps above and below, and the odds - learned from this
// chart's own history - that this week / day takes the prior week's / day's
// high or low given where that candle closed in its range. Weekly and daily
// order flow (close beyond the prior candle's high / low) is shown as context.
// Companion to Sphinx Regime (the day) and Sphinx Strike (the entry).
//
// Measured on ES 2021 - 2026: where a week closes in its range is what
// predicts which side it takes next; the order-flow label alone added little.
// So location leads, order flow is context.
 
//@version=6
indicator('Sphinx Horizon: Weekly & Daily Context', shorttitle = 'Horizon', overlay = true, max_boxes_count = 20, max_lines_count = 200, max_labels_count = 300)
 
// ============================================================
// === INPUTS ===
// ============================================================
g_lv = '1 · Levels'
i_wk = input.bool(true, 'Prior week high / low', group = g_lv, display = display.none)
i_dy = input.bool(true, 'Prior day high / low', group = g_lv, display = display.none)
c_wk = input.color(#b39ddb, 'Week', group = g_lv, inline = 'lc', display = display.none)
c_dy = input.color(#80cbc4, 'Day', group = g_lv, inline = 'lc', display = display.none)
 
g_gp = '2 · Gaps'
i_wg = input.bool(true, 'Nearest unfilled weekly gaps', group = g_gp, tooltip = 'Weekly fair value gaps not yet filled: the nearest above and below price. Partly filled gaps shrink to the part still open.', display = display.none)
i_dg = input.bool(false, 'Nearest unfilled daily gaps', group = g_gp, display = display.none)
c_gUp = input.color(#ef5350, 'Bearish gap', group = g_gp, inline = 'gc', display = display.none)
c_gDn = input.color(#26a69a, 'Bullish gap', group = g_gp, inline = 'gc', display = display.none)
 
g_pn = '3 · Panel'
i_tbl = input.bool(true, 'Show panel', group = g_pn, tooltip = 'Week / Day: order flow and where the last candle closed in its range. Takes: the odds - from this chart\'s history - that the current week / day takes the prior high or low, given that close. A check once it has. Needs enough history: use a 1H chart for the weekly odds.', display = display.none)
i_pos = input.string('Bottom Left', 'Position', options = ['Top Right', 'Top Left', 'Bottom Right', 'Bottom Left'], group = g_pn, display = display.none)
i_minN = input.int(20, 'Candles needed per bucket', minval = 5, maxval = 200, group = g_pn, tooltip = 'Odds are shown once each close-location bucket has this many past candles; until then the panel says learning.', display = display.none)
 
g_lb = '4 · Labels'
i_lbl = input.bool(true, 'Label levels', group = g_lb, display = display.none)
i_ext = input.int(15, 'Extend right (bars)', minval = 0, maxval = 200, group = g_lb, display = display.none)
 
g_sm = '5 · SMT'
i_smt = input.bool(true, 'HTF SMT', group = g_sm, tooltip = 'Divergence at the prior week / day high or low: one index takes it and its sister does not. At a high it is a bearish sign, at a low a bullish one. It clears if the lagging index takes its own level later in the same week / day.', display = display.none)
i_pair = input.string('ES / NQ', 'Compare', options = ['ES / NQ', 'ES / NQ / YM'], group = g_sm, tooltip = 'ES / NQ: the classic pair (a YM chart is compared with ES). ES / NQ / YM: all three - an SMT when any one diverges, which fires far more often.', display = display.none)
i_mrg = input.float(0.1, 'Clear take (x daily ATR)', minval = 0, maxval = 1, step = 0.05, group = g_sm, tooltip = 'The index that takes the level must trade beyond it by at least this much, and the one that fails must stay short of it by at least this much. Equal highs / lows in between are not counted.', display = display.none)
i_extW = input.int(4, 'Weekly: external = extreme of last (weeks)', minval = 0, maxval = 26, group = g_sm, tooltip = 'A weekly SMT only counts when the index that took the level made the highest high (or lowest low) of this many weeks - a run on real liquidity, not the prior week inside a range. 0 = off.', display = display.none)
i_extD = input.int(5, 'Daily: external = extreme of last (days)', minval = 0, maxval = 60, group = g_sm, tooltip = 'Same for daily SMTs: the index that took the prior day high / low must make the extreme of this many days. 0 = off.', display = display.none)
i_conn = input.bool(true, 'Connect the highs / lows', group = g_sm, tooltip = 'A line on this chart from the prior high (or low) to the new one - a higher high the sister does not confirm, or this chart\'s own failed lower high.', display = display.none)
i_hist = input.bool(true, 'Mark past SMTs', group = g_sm, tooltip = 'Marks weeks and days that closed with an SMT at the prior high or low, at the extreme where it formed.', display = display.none)
i_histD = input.bool(false, 'Include daily', group = g_sm, inline = 'hd', display = display.none)
i_histN = input.int(30, 'Kept', minval = 5, maxval = 150, group = g_sm, inline = 'hd', display = display.none)
s_es = input.symbol('CME_MINI:ES1!', 'ES symbol', group = g_sm, display = display.none)
s_nq = input.symbol('CME_MINI:NQ1!', 'NQ symbol', group = g_sm, display = display.none)
s_ym = input.symbol('CBOT_MINI:YM1!', 'YM symbol', group = g_sm, display = display.none)
 
// ============================================================
// === HIGHER-TIMEFRAME DATA (closed candles, no repaint) ===
// ============================================================
_htf() =>
    [high[1], low[1], close[1], high[2], low[2], close[2], high[3], low[3], time[1], time[2]]
[wH1, wL1, wC1, wH2, wL2, wC2, wH3, wL3, wT1, wT2] = request.security(syminfo.tickerid, 'W', _htf(), lookahead = barmerge.lookahead_on)
[dH1, dL1, dC1, dH2, dL2, dC2, dH3, dL3, dT1, dT2] = request.security(syminfo.tickerid, 'D', _htf(), lookahead = barmerge.lookahead_on)
dAtr = request.security(syminfo.tickerid, 'D', ta.atr(14)[1], lookahead = barmerge.lookahead_on)
barMs = timeframe.in_seconds() * 1000
 
// sisters: the chart's index is always compared against the other two
string fam = str.contains(syminfo.root, 'NQ') ? 'NQ' : str.contains(syminfo.root, 'YM') ? 'YM' : 'ES'
string symC = ticker.inherit(syminfo.tickerid, fam == 'NQ' ? s_nq : fam == 'YM' ? s_ym : s_es)
string symA = ticker.inherit(syminfo.tickerid, fam == 'ES' ? s_nq : s_es)
string symB = ticker.inherit(syminfo.tickerid, fam == 'YM' ? s_nq : s_ym)
string nmA = fam == 'ES' ? 'NQ' : 'ES'
string nmB = fam == 'YM' ? 'NQ' : 'YM'
bool i_useB = i_pair == 'ES / NQ / YM'
_pr() =>
    [high[1], low[1], high[2], low[2]]
_atr() =>
    ta.atr(14)[1]
aAtr = request.security(symA, 'D', _atr(), lookahead = barmerge.lookahead_on)
xAtr = request.security(symC, 'D', _atr(), lookahead = barmerge.lookahead_on)
[xWH1, xWL1, xWH2, xWL2] = request.security(symC, 'W', _pr(), lookahead = barmerge.lookahead_on)
[xDH1, xDL1, xDH2, xDL2] = request.security(symC, 'D', _pr(), lookahead = barmerge.lookahead_on)
[xH, xL] = request.security(symC, timeframe.period, [high, low])
// external range: extreme of the last n closed candles, and of the last n - 1 (for the live candle)
_xr(int n) =>
    int k = math.max(1, n)
    int m = math.max(1, n - 1)
    [ta.highest(high, k)[1], ta.lowest(low, k)[1], ta.highest(high, m)[1], ta.lowest(low, m)[1]]
[cXWh, cXWl, cXWhL, cXWlL] = request.security(symC, 'W', _xr(i_extW), lookahead = barmerge.lookahead_on)
[cXDh, cXDl, cXDhL, cXDlL] = request.security(symC, 'D', _xr(i_extD), lookahead = barmerge.lookahead_on)
[aXWh, aXWl, aXWhL, aXWlL] = request.security(symA, 'W', _xr(i_extW), lookahead = barmerge.lookahead_on)
[aXDh, aXDl, aXDhL, aXDlL] = request.security(symA, 'D', _xr(i_extD), lookahead = barmerge.lookahead_on)
[bXWh, bXWl, bXWhL, bXWlL] = request.security(symB, 'W', _xr(i_extW), lookahead = barmerge.lookahead_on)
[bXDh, bXDl, bXDhL, bXDlL] = request.security(symB, 'D', _xr(i_extD), lookahead = barmerge.lookahead_on)
bAtr = request.security(symB, 'D', _atr(), lookahead = barmerge.lookahead_on)
[aWH1, aWL1, aWH2, aWL2] = request.security(symA, 'W', _pr(), lookahead = barmerge.lookahead_on)
[aDH1, aDL1, aDH2, aDL2] = request.security(symA, 'D', _pr(), lookahead = barmerge.lookahead_on)
[bWH1, bWL1, bWH2, bWL2] = request.security(symB, 'W', _pr(), lookahead = barmerge.lookahead_on)
[bDH1, bDL1, bDH2, bDL2] = request.security(symB, 'D', _pr(), lookahead = barmerge.lookahead_on)
[aH, aL] = request.security(symA, timeframe.period, [high, low])
[bH, bL] = request.security(symB, timeframe.period, [high, low])
 
// close location bucket 0..4 (bottom fifth .. top fifth)
_bkt(float h, float l, float c) =>
    float r = h - l
    r > 0 ? math.min(4, int((c - l) / r * 5)) : 2
 
// learned odds: per bucket, how often the next candle took the high / the low
var int[] wN = array.new_int(5, 0)
var int[] wTH = array.new_int(5, 0)
var int[] wTL = array.new_int(5, 0)
var int[] dN = array.new_int(5, 0)
var int[] dTH = array.new_int(5, 0)
var int[] dTL = array.new_int(5, 0)
// order flow (close beyond the prior candle's high / low), carried until it flips
var int wOF = 0
var int dOF = 0
// running high / low of the current week / day
var float wHi = na
var float wLo = na
var float dHi = na
var float dLo = na
var int wHiT = na
var int wLoT = na
var int dHiT = na
var int dLoT = na
// sisters' running high / low of the current week / day
var float xWHi = na
var float xWLo = na
var float xDHi = na
var float xDLo = na
var float aWHi = na
var float aWLo = na
var float aDHi = na
var float aDLo = na
var float bWHi = na
var float bWLo = na
var float bDHi = na
var float bDLo = na
var label[] smtL = array.new_label()
var line[] smtLn = array.new_line()
// time of the prior week's / day's high and low on this chart
var int pwHiT = na
var int pwLoT = na
var int pdHiT = na
var int pdLoT = na
 
_mx(float a, float b) =>
    na(a) ? b : na(b) ? a : math.max(a, b)
_mn(float a, float b) =>
    na(a) ? b : na(b) ? a : math.min(a, b)
 
// one index at a level: 1 clear take, -1 clear miss, 0 in between (equal highs / lows)
_st(float ext, float lvl, float atr, bool hi) =>
    float m = nz(atr) * i_mrg
    na(ext) or na(lvl) ? 0 : hi ? (ext > lvl + m ? 1 : ext < lvl - m ? -1 : 0) : (ext < lvl - m ? 1 : ext > lvl + m ? -1 : 0)
// SMT on one side: one index clearly took the level and another never reached it
_div(int c, int a, int b) =>
    bool tk = c == 1 or a == 1 or (i_useB and b == 1)
    bool fl = c == -1 or a == -1 or (i_useB and b == -1)
    tk and fl
// external: at least one index that clearly took the level made the n-candle extreme
_xok(int n, int c, int a, int b, bool xc, bool xa, bool xb) =>
    n == 0 or (c == 1 and xc) or (a == 1 and xa) or (i_useB and b == 1 and xb)
_hiX(float v, float ref) =>
    not na(v) and not na(ref) and v >= ref
_loX(float v, float ref) =>
    not na(v) and not na(ref) and v <= ref
_failed(int c, int a, int b) =>
    string[] f = array.new_string()
    if c == -1
        f.push(fam)
    if a == -1
        f.push(nmA)
    if i_useB and b == -1
        f.push(nmB)
    f.join(' ')
 
_dsc(string nm, float ext, float lvl, bool hi) =>
    float d = hi ? ext - lvl : lvl - ext
    na(d) ? nm + ' -' : nm + (d > 0 ? ' took by ' : ' missed by ') + str.tostring(math.abs(d), format.mintick)
_tip(float c1, float c2, float a1, float a2, float b1, float b2, bool hi) =>
    _dsc(fam, c1, c2, hi) + '\n' + _dsc(nmA, a1, a2, hi) + (i_useB ? '\n' + _dsc(nmB, b1, b2, hi) : '')
 
_mark(int t0, float y0, int t, float y, bool hi, string tag, bool big, string tip) =>
    if i_smt and i_hist and not na(t)
        color c = hi ? #ef5350 : #26a69a
        // a weekly tag replaces a daily one on the same extreme; a daily never stacks on a weekly
        bool skip = false
        if smtL.size() > 0
            for i = smtL.size() - 1 to 0
                label lb = smtL.get(i)
                if label.get_x(lb) == t and label.get_y(lb) == y
                    if big
                        lb.delete()
                        smtL.remove(i)
                        smtLn.get(i).delete()
                        smtLn.remove(i)
                    else
                        skip := true
        if not skip
            smtL.push(label.new(t, y, tag, xloc = xloc.bar_time, style = hi ? label.style_label_down : label.style_label_up, color = color.new(c, 75), textcolor = color.white, size = big ? size.small : size.tiny, tooltip = tip))
            line ln = na
            if i_conn and not na(t0) and not na(y0) and t0 < t
                ln := line.new(t0, y0, t, y, xloc = xloc.bar_time, color = color.new(c, big ? 20 : 45), width = 1)
            smtLn.push(ln)
            while smtL.size() > i_histN
                smtL.shift().delete()
                smtLn.shift().delete()
 
// a new week: score the week that just closed against the one before it
if not na(wT1) and wT1 != nz(wT1[1])
    if not na(wH2)
        int k = _bkt(wH2, wL2, wC2)
        wN.set(k, wN.get(k) + 1)
        wTH.set(k, wTH.get(k) + (wH1 > wH2 ? 1 : 0))
        wTL.set(k, wTL.get(k) + (wL1 < wL2 ? 1 : 0))
        wOF := wC1 > wH2 ? 1 : wC1 < wL2 ? -1 : wOF
        // the week that just closed: did it end with an SMT at the prior high / low?
        if not na(aWH2) and not na(xWH2) and (not i_useB or not na(bWH2))
            int hc = _st(xWH1, xWH2, xAtr, true)
            int ha = _st(aWH1, aWH2, aAtr, true)
            int hb = _st(bWH1, bWH2, bAtr, true)
            int lc = _st(xWL1, xWL2, xAtr, false)
            int la = _st(aWL1, aWL2, aAtr, false)
            int lb_ = _st(bWL1, bWL2, bAtr, false)
            if _div(hc, ha, hb) and _xok(i_extW, hc, ha, hb, _hiX(xWH1, cXWh), _hiX(aWH1, aXWh), _hiX(bWH1, bXWh))
                _mark(pwHiT, wH2, wHiT, wH1, true, 'W SMT', true, 'Prior week high\n' + _tip(xWH1, xWH2, aWH1, aWH2, bWH1, bWH2, true))
            if _div(lc, la, lb_) and _xok(i_extW, lc, la, lb_, _loX(xWL1, cXWl), _loX(aWL1, aXWl), _loX(bWL1, bXWl))
                _mark(pwLoT, wL2, wLoT, wL1, false, 'W SMT', true, 'Prior week low\n' + _tip(xWL1, xWL2, aWL1, aWL2, bWL1, bWL2, false))
    wHi := high
    wLo := low
    pwHiT := wHiT
    pwLoT := wLoT
    wHiT := time
    wLoT := time
    xWHi := xH
    xWLo := xL
    aWHi := aH
    aWLo := aL
    bWHi := bH
    bWLo := bL
if not na(dT1) and dT1 != nz(dT1[1])
    if not na(dH2)
        int k = _bkt(dH2, dL2, dC2)
        dN.set(k, dN.get(k) + 1)
        dTH.set(k, dTH.get(k) + (dH1 > dH2 ? 1 : 0))
        dTL.set(k, dTL.get(k) + (dL1 < dL2 ? 1 : 0))
        dOF := dC1 > dH2 ? 1 : dC1 < dL2 ? -1 : dOF
        if i_histD and not na(aDH2) and not na(xDH2) and (not i_useB or not na(bDH2))
            int hc = _st(xDH1, xDH2, xAtr, true)
            int ha = _st(aDH1, aDH2, aAtr, true)
            int hb = _st(bDH1, bDH2, bAtr, true)
            int lc = _st(xDL1, xDL2, xAtr, false)
            int la = _st(aDL1, aDL2, aAtr, false)
            int lb_ = _st(bDL1, bDL2, bAtr, false)
            if _div(hc, ha, hb) and _xok(i_extD, hc, ha, hb, _hiX(xDH1, cXDh), _hiX(aDH1, aXDh), _hiX(bDH1, bXDh))
                _mark(pdHiT, dH2, dHiT, dH1, true, 'D SMT', false, 'Prior day high\n' + _tip(xDH1, xDH2, aDH1, aDH2, bDH1, bDH2, true))
            if _div(lc, la, lb_) and _xok(i_extD, lc, la, lb_, _loX(xDL1, cXDl), _loX(aDL1, aXDl), _loX(bDL1, bXDl))
                _mark(pdLoT, dL2, dLoT, dL1, false, 'D SMT', false, 'Prior day low\n' + _tip(xDL1, xDL2, aDL1, aDL2, bDL1, bDL2, false))
    dHi := high
    dLo := low
    pdHiT := dHiT
    pdLoT := dLoT
    dHiT := time
    dLoT := time
    xDHi := xH
    xDLo := xL
    aDHi := aH
    aDLo := aL
    bDHi := bH
    bDLo := bL
if na(wHi) or high > wHi
    wHi := high
    wHiT := time
if na(wLo) or low < wLo
    wLo := low
    wLoT := time
if na(dHi) or high > dHi
    dHi := high
    dHiT := time
if na(dLo) or low < dLo
    dLo := low
    dLoT := time
xWHi := _mx(xWHi, xH)
xWLo := _mn(xWLo, xL)
xDHi := _mx(xDHi, xH)
xDLo := _mn(xDLo, xL)
aWHi := _mx(aWHi, aH)
aWLo := _mn(aWLo, aL)
aDHi := _mx(aDHi, aH)
aDLo := _mn(aDLo, aL)
bWHi := _mx(bWHi, bH)
bWLo := _mn(bWLo, bL)
bDHi := _mx(bDHi, bH)
bDLo := _mn(bDLo, bL)
 
// live SMT for the current week / day
bool okW = i_smt and not na(xWH1) and not na(aWH1) and (not i_useB or not na(bWH1))
bool okD = i_smt and not na(xDH1) and not na(aDH1) and (not i_useB or not na(bDH1))
int cWH = _st(xWHi, xWH1, xAtr, true)
int cWL = _st(xWLo, xWL1, xAtr, false)
int cDH = _st(xDHi, xDH1, xAtr, true)
int cDL = _st(xDLo, xDL1, xAtr, false)
int sAWH = _st(aWHi, aWH1, aAtr, true)
int sAWL = _st(aWLo, aWL1, aAtr, false)
int sADH = _st(aDHi, aDH1, aAtr, true)
int sADL = _st(aDLo, aDL1, aAtr, false)
int sBWH = _st(bWHi, bWH1, bAtr, true)
int sBWL = _st(bWLo, bWL1, bAtr, false)
int sBDH = _st(bDHi, bDH1, bAtr, true)
int sBDL = _st(bDLo, bDL1, bAtr, false)
bool smtWH = okW and _div(cWH, sAWH, sBWH) and _xok(i_extW, cWH, sAWH, sBWH, _hiX(xWHi, cXWhL), _hiX(aWHi, aXWhL), _hiX(bWHi, bXWhL))
bool smtWL = okW and _div(cWL, sAWL, sBWL) and _xok(i_extW, cWL, sAWL, sBWL, _loX(xWLo, cXWlL), _loX(aWLo, aXWlL), _loX(bWLo, bXWlL))
bool smtDH = okD and _div(cDH, sADH, sBDH) and _xok(i_extD, cDH, sADH, sBDH, _hiX(xDHi, cXDhL), _hiX(aDHi, aXDhL), _hiX(bDHi, bXDhL))
bool smtDL = okD and _div(cDL, sADL, sBDL) and _xok(i_extD, cDL, sADL, sBDL, _loX(xDLo, cXDlL), _loX(aDLo, aXDlL), _loX(bDLo, bXDlL))
 
// ============================================================
// === GAPS (weekly / daily FVGs, open part only) ===
// ============================================================
var float[] wgT = array.new_float()
var float[] wgB = array.new_float()
var bool[] wgU = array.new_bool()   // true = bullish gap (below price as support)
var int[] wgX = array.new_int()
var float[] dgT = array.new_float()
var float[] dgB = array.new_float()
var bool[] dgU = array.new_bool()
var int[] dgX = array.new_int()
 
_addGap(float[] gt, float[] gb, bool[] gu, int[] gx, float h1, float l1, float h3, float l3, int t) =>
    if not na(h3)
        if l1 > h3
            gt.push(l1)
            gb.push(h3)
            gu.push(true)
            gx.push(t)
        else if h1 < l3
            gt.push(l3)
            gb.push(h1)
            gu.push(false)
            gx.push(t)
        while gt.size() > 40
            gt.shift()
            gb.shift()
            gu.shift()
            gx.shift()
 
// shrink a gap to its open part as price trades into it; drop it once filled
_fill(float[] gt, float[] gb, bool[] gu, int[] gx) =>
    if gt.size() > 0
        for i = gt.size() - 1 to 0
            bool bu = gu.get(i)
            bool kill = bu ? low <= gb.get(i) : high >= gt.get(i)
            if not kill and bu and low < gt.get(i)
                gt.set(i, low)
            if not kill and not bu and high > gb.get(i)
                gb.set(i, high)
            if kill
                gt.remove(i)
                gb.remove(i)
                gu.remove(i)
                gx.remove(i)
 
if not na(wT1) and wT1 != nz(wT1[1])
    _addGap(wgT, wgB, wgU, wgX, wH1, wL1, wH3, wL3, wT2)
if not na(dT1) and dT1 != nz(dT1[1])
    _addGap(dgT, dgB, dgU, dgX, dH1, dL1, dH3, dL3, dT2)
_fill(wgT, wgB, wgU, wgX)
_fill(dgT, dgB, dgU, dgX)
 
// nearest gap above (index) and below
_near(float[] gt, float[] gb, bool above) =>
    int best = -1
    float bd = na
    if gt.size() > 0
        for i = 0 to gt.size() - 1
            float d = above ? gb.get(i) - close : close - gt.get(i)
            if d >= 0 and (na(bd) or d < bd)
                bd := d
                best := i
    best
 
// ============================================================
// === DRAWING ===
// ============================================================
var line[] lns = array.new_line()
var label[] lbs = array.new_label()
var box[] bxs = array.new_box()
 
_lvl(float y, int x1, string t, color c, bool taken) =>
    int x2 = time + barMs * i_ext
    lns.push(line.new(x1, y, x2, y, xloc = xloc.bar_time, color = color.new(c, taken ? 55 : 15), width = 1, style = taken ? line.style_dashed : line.style_solid))
    if i_lbl and t != ''
        lbs.push(label.new(x2, y, t, xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.new(c, taken ? 45 : 0), size = size.small))
 
_gapBox(float[] gt, float[] gb, bool[] gu, int[] gx, int i, string tag) =>
    if i >= 0
        bool bu = gu.get(i)
        color c = bu ? c_gDn : c_gUp
        int x2 = time + barMs * i_ext
        bxs.push(box.new(gx.get(i), gt.get(i), x2, gb.get(i), xloc = xloc.bar_time, bgcolor = color.new(c, 90), border_color = color.new(c, 40), border_style = line.style_dashed))
        if i_lbl
            lbs.push(label.new(x2, (gt.get(i) + gb.get(i)) / 2, tag + (bu ? ' bullish gap' : ' bearish gap'), xloc = xloc.bar_time, style = label.style_label_left, color = color.new(color.black, 100), textcolor = color.new(c, 10), size = size.small))
 
if barstate.islast
    while lns.size() > 0
        lns.shift().delete()
    while lbs.size() > 0
        lbs.shift().delete()
    while bxs.size() > 0
        bxs.shift().delete()
    // a daily level close to a weekly one shares its label
    float thr = nz(dAtr) * 0.12
    bool shW = i_wk and not na(wH1)
    bool shD = i_dy and not na(dH1)
    string tWH = smtWH ? 'PWH · SMT' : 'PWH'
    string tWL = smtWL ? 'PWL · SMT' : 'PWL'
    string tDH = smtDH ? 'PDH · SMT' : 'PDH'
    string tDL = smtDL ? 'PDL · SMT' : 'PDL'
    if shW and shD
        if math.abs(dH1 - wH1) <= thr
            tWH := tWH + ' · ' + tDH
            tDH := ''
        else if math.abs(dH1 - wL1) <= thr
            tWL := tWL + ' · ' + tDH
            tDH := ''
        if math.abs(dL1 - wL1) <= thr
            tWL := tWL + ' · ' + tDL
            tDL := ''
        else if math.abs(dL1 - wH1) <= thr
            tWH := tWH + ' · ' + tDL
            tDL := ''
    // each line starts at the candle that made the level
    if shW
        _lvl(wH1, nz(pwHiT, wT1), tWH, c_wk, wHi > wH1)
        _lvl(wL1, nz(pwLoT, wT1), tWL, c_wk, wLo < wL1)
    if shD
        _lvl(dH1, nz(pdHiT, dT1), tDH, c_dy, dHi > dH1)
        _lvl(dL1, nz(pdLoT, dT1), tDL, c_dy, dLo < dL1)
    if i_conn
        if smtWH and not na(pwHiT) and pwHiT < wHiT
            lns.push(line.new(pwHiT, wH1, wHiT, wHi, xloc = xloc.bar_time, color = color.new(#ef5350, 20), width = 1, style = line.style_dashed))
        if smtWL and not na(pwLoT) and pwLoT < wLoT
            lns.push(line.new(pwLoT, wL1, wLoT, wLo, xloc = xloc.bar_time, color = color.new(#26a69a, 20), width = 1, style = line.style_dashed))
        if smtDH and not na(pdHiT) and pdHiT < dHiT
            lns.push(line.new(pdHiT, dH1, dHiT, dHi, xloc = xloc.bar_time, color = color.new(#ef5350, 45), width = 1, style = line.style_dashed))
        if smtDL and not na(pdLoT) and pdLoT < dLoT
            lns.push(line.new(pdLoT, dL1, dLoT, dLo, xloc = xloc.bar_time, color = color.new(#26a69a, 45), width = 1, style = line.style_dashed))
    if i_wg
        _gapBox(wgT, wgB, wgU, wgX, _near(wgT, wgB, true), 'W')
        _gapBox(wgT, wgB, wgU, wgX, _near(wgT, wgB, false), 'W')
    if i_dg
        _gapBox(dgT, dgB, dgU, dgX, _near(dgT, dgB, true), 'D')
        _gapBox(dgT, dgB, dgU, dgX, _near(dgT, dgB, false), 'D')
 
// ============================================================
// === PANEL ===
// ============================================================
_pos(string p) =>
    p == 'Top Left' ? position.top_left : p == 'Bottom Right' ? position.bottom_right : p == 'Top Right' ? position.top_right : position.bottom_left
var table tb = table.new(_pos(i_pos), 2, 8, bgcolor = color.new(#131722, 10), border_width = 1, border_color = color.new(#363a45, 0))
 
_ofTxt(int s) =>
    s == 1 ? 'Bullish' : s == -1 ? 'Bearish' : 'Neutral'
_ofCol(int s) =>
    s == 1 ? #26a69a : s == -1 ? #ef5350 : #787b86
_odds(int[] n, int[] th, int[] tl, int k, bool hiSide) =>
    int nn = n.get(k)
    nn < i_minN ? na : 100.0 * (hiSide ? th.get(k) : tl.get(k)) / nn
_takeTxt(float pH, float pL, bool tookH, bool tookL) =>
    string a = 'High ' + (tookH ? '✓' : na(pH) ? 'learning' : str.tostring(pH, '#') + '%')
    string b = 'Low ' + (tookL ? '✓' : na(pL) ? 'learning' : str.tostring(pL, '#') + '%')
    a + '  ·  ' + b
_gapTxt(float[] gt, float[] gb, bool above) =>
    int i = _near(gt, gb, above)
    if i < 0
        '-'
    else
        float edge = above ? gb.get(i) : gt.get(i)
        str.tostring(gb.get(i), format.mintick) + ' - ' + str.tostring(gt.get(i), format.mintick) + (na(dAtr) ? '' : '  (' + str.tostring(math.abs(edge - close) / dAtr, '0.0') + ' d-ATR)')
 
_smtTxt(bool ok, bool hi, bool lo, int cH, int aH_, int bH_, int cL, int aL_, int bL_) =>
    string t = 'none'
    if not ok
        t := 'no sister data'
    else if hi or lo
        string h = hi ? 'High · ' + _failed(cH, aH_, bH_) + ' failed' : ''
        string l = lo ? 'Low · ' + _failed(cL, aL_, bL_) + ' failed' : ''
        t := h + (hi and lo ? '   ' : '') + l
    t
_smtCol(bool hi, bool lo) =>
    hi and lo ? #ffb74d : hi ? #ef5350 : lo ? #26a69a : #787b86
 
if barstate.islast and i_tbl
    color cg = #b2b5be
    int wk = na(wH1) ? 2 : _bkt(wH1, wL1, wC1)
    int dk = na(dH1) ? 2 : _bkt(dH1, dL1, dC1)
    float wloc = na(wH1) or wH1 == wL1 ? na : 100 * (wC1 - wL1) / (wH1 - wL1)
    float dloc = na(dH1) or dH1 == dL1 ? na : 100 * (dC1 - dL1) / (dH1 - dL1)
    table.cell(tb, 0, 0, 'Horizon', text_color = #ffd700, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 0, 'order flow  ·  last close in its range', text_color = color.new(cg, 30), text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 1, 'Week', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 1, _ofTxt(wOF) + '  ·  closed ' + (na(wloc) ? '-' : str.tostring(wloc, '#') + '%'), text_color = _ofCol(wOF), text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 2, '  takes', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 2, _takeTxt(_odds(wN, wTH, wTL, wk, true), _odds(wN, wTH, wTL, wk, false), wHi > nz(wH1, 1e10), wLo < nz(wL1, -1e10)), text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 3, 'Day', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 3, _ofTxt(dOF) + '  ·  closed ' + (na(dloc) ? '-' : str.tostring(dloc, '#') + '%'), text_color = _ofCol(dOF), text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 4, '  takes', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 4, _takeTxt(_odds(dN, dTH, dTL, dk, true), _odds(dN, dTH, dTL, dk, false), dHi > nz(dH1, 1e10), dLo < nz(dL1, -1e10)), text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 0, 5, 'W gaps', text_color = cg, text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, 5, 'above ' + _gapTxt(wgT, wgB, true) + '   below ' + _gapTxt(wgT, wgB, false), text_color = cg, text_size = size.small, text_halign = text.align_left)
    if i_smt
        table.cell(tb, 0, 6, 'W SMT', text_color = cg, text_size = size.small, text_halign = text.align_left)
        table.cell(tb, 1, 6, _smtTxt(okW, smtWH, smtWL, cWH, sAWH, sBWH, cWL, sAWL, sBWL), text_color = _smtCol(smtWH, smtWL), text_size = size.small, text_halign = text.align_left)
        table.cell(tb, 0, 7, 'D SMT', text_color = cg, text_size = size.small, text_halign = text.align_left)
        table.cell(tb, 1, 7, _smtTxt(okD, smtDH, smtDL, cDH, sADH, sBDH, cDL, sADL, sBDL), text_color = _smtCol(smtDH, smtDL), text_size = size.small, text_halign = text.align_left)
 
// a hidden plot on the close keeps the script on the candles' price scale
plot(close, 'Price anchor', color = color.new(color.white, 100), display = display.pane, editable = false)
 
// ============================================================
// === ALERTS ===
// ============================================================
alertcondition(ta.crossover(high, nz(wH1, 1e10)) and wHi[1] <= nz(wH1, 1e10), 'Prior week high taken', 'Horizon: price took the prior week high')
alertcondition(ta.crossunder(low, nz(wL1, -1e10)) and wLo[1] >= nz(wL1, -1e10), 'Prior week low taken', 'Horizon: price took the prior week low')
alertcondition(ta.crossover(high, nz(dH1, 1e10)) and dHi[1] <= nz(dH1, 1e10), 'Prior day high taken', 'Horizon: price took the prior day high')
alertcondition(ta.crossunder(low, nz(dL1, -1e10)) and dLo[1] >= nz(dL1, -1e10), 'Prior day low taken', 'Horizon: price took the prior day low')
alertcondition(smtWH and not smtWH[1], 'Weekly SMT at the high', 'Horizon: weekly SMT at the prior week high')
alertcondition(smtWL and not smtWL[1], 'Weekly SMT at the low', 'Horizon: weekly SMT at the prior week low')
alertcondition(smtDH and not smtDH[1], 'Daily SMT at the high', 'Horizon: daily SMT at the prior day high')
alertcondition(smtDL and not smtDL[1], 'Daily SMT at the low', 'Horizon: daily SMT at the prior day low')

← 返回列表