Grandoc's Top Down Analysis Projection

Grandoc · study · 561 行 · 点赞 12 · TradingView 原页

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

Pine Script

//@version=6
indicator("Grandoc's Top Down Analysis Projection", "Grandoc TDA", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, scale = scale.right)
 
// ═════════════════════════ Helpers ═════════════════════════
f_style(string s) => s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
f_size(string s) => s == "Tiny" ? size.tiny : s == "Small" ? size.small : s == "Normal" ? size.normal : s == "Large" ? size.large : size.huge
f_tfName(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec < 60 ? str.tostring(sec) + "s" : sec < 3600 ? str.tostring(sec / 60) + "m" : sec < 86400 ? str.tostring(sec / 3600) + "H" : sec < 604800 ? str.tostring(sec / 86400) + "D" : sec < 2419200 ? str.tostring(sec / 604800) + "W" : str.tostring(sec / 2419200) + "M"
f_px(float v) => str.tostring(v, format.mintick)
 
// ═════════════════════════ Inputs ═════════════════════════
G0 = "History"
iBars = input.int(500, "Bars to analyze", 50, 3000, group = G0, tooltip = "Chart candles scanned for structure, OB and FVG, counted back from the last loaded candle (the replay candle in Bar Replay). Higher = more history, slower load.")
 
G1 = "External Structure"
iLen      = input.int(5, "Swing length", 2, 20, group = G1, tooltip = "Candles on each side a high/low must beat to count as a swing. External levels only move on breaks, so small swings inside the range are ignored.")
iSwings   = input.bool(true, "Show HH / HL / LH / LL", group = G1, tooltip = "Mark external swing points.")
iMarker   = input.string("Dots", "Marker style", ["Dots", "Letters"], group = G1, tooltip = "Dots = small '•' (smaller than TradingView's tiny shape). Letters = HH/HL/LH/LL text.")
iMkSize   = input.string("Tiny", "Marker size", ["Tiny", "Small", "Normal"], group = G1, tooltip = "Size of the dot or letters.")
iMkTransp = input.int(0, "Marker transparency", 0, 100, group = G1, tooltip = "0 = solid, 100 = invisible.")
iMkOffset = input.float(0.2, "Marker offset (× avg candle range)", 0, 5, 0.1, group = G1, tooltip = "Pushes markers away from the wick tip.")
iHollow   = input.bool(true, "Hollow dot when raided", group = G1, tooltip = "When a later wick trades beyond a swing, its dot turns from '•' to hollow '○' (same colour and size). In Letters mode the letter fades instead.")
cHH = input.color(color.teal,   "HH", inline = "sw1", group = G1, tooltip = "Colours for HH and HL.")
cHL = input.color(color.green,  "HL", inline = "sw1", group = G1)
cLH = input.color(color.orange, "LH", inline = "sw2", group = G1, tooltip = "Colours for LH and LL.")
cLL = input.color(color.red,    "LL", inline = "sw2", group = G1)
eShow  = input.bool(true, "Show eBOS / eCHoCH", group = G1, tooltip = "eBOS = close through the external low/high in the trend direction. eCHoCH = close through the protected high/low against the trend.")
eBull  = input.color(color.teal, "Bull", inline = "ec", group = G1, tooltip = "Line colours for bullish and bearish external breaks.")
eBear  = input.color(color.red,  "Bear", inline = "ec", group = G1)
eStyle = input.string("Dashed", "Line style", ["Solid", "Dashed", "Dotted"], group = G1, tooltip = "External break line style.")
eWidth = input.int(1, "Line width", 1, 5, group = G1, tooltip = "External break line thickness.")
eTH    = input.string("Middle", "Text horizontal", ["Left", "Middle", "Right"], group = G1, tooltip = "Where the text sits along the line.")
eTV    = input.string("Above", "Text vertical", ["Above", "On", "Below"], group = G1, tooltip = "Text above, on, or below the line.")
eTSize = input.string("Tiny", "Text size", ["Tiny", "Small", "Normal", "Large", "Huge"], group = G1, tooltip = "Size of eBOS/eCHoCH text.")
eTCol  = input.color(color.gray, "Text colour", group = G1, tooltip = "Colour of eBOS/eCHoCH text.")
 
G2 = "Internal Structure"
nShow  = input.bool(false, "Show iBOS / iCHoCH", group = G2, tooltip = "Minor breaks inside the external range (pullbacks / entry shifts).")
nLen   = input.int(2, "Internal swing length", 1, 10, group = G2, tooltip = "Swing length for internal structure. Small = every minor swing.")
nBull  = input.color(color.new(color.teal, 55), "Bull", inline = "ic", group = G2, tooltip = "Line colours for internal breaks (faint by default).")
nBear  = input.color(color.new(color.red, 55),  "Bear", inline = "ic", group = G2)
nStyle = input.string("Dotted", "Line style", ["Solid", "Dashed", "Dotted"], group = G2, tooltip = "Internal break line style.")
nWidth = input.int(1, "Line width", 1, 5, group = G2, tooltip = "Internal break line thickness.")
nTH    = input.string("Middle", "Text horizontal", ["Left", "Middle", "Right"], group = G2, tooltip = "Where the text sits along the line.")
nTV    = input.string("Above", "Text vertical", ["Above", "On", "Below"], group = G2, tooltip = "Text above, on, or below the line.")
nTSize = input.string("Tiny", "Text size", ["Tiny", "Small", "Normal", "Large", "Huge"], group = G2, tooltip = "Size of iBOS/iCHoCH text.")
nTCol  = input.color(color.new(color.gray, 40), "Text colour", group = G2, tooltip = "Colour of iBOS/iCHoCH text.")
 
G3 = "Zigzag"
iZZ      = input.bool(false, "Show zigzag", group = G3, tooltip = "Joins every minor wick high and low, strictly alternating (two highs in a row keep the higher, two lows keep the lower).")
iZZLen   = input.int(2, "Zigzag swing length", 1, 10, group = G3, tooltip = "Swing length used only by the zigzag. 1-2 follows every turn.")
iZZCol   = input.color(color.gray, "Colour", group = G3, tooltip = "Zigzag colour.")
iZZWidth = input.int(1, "Width", 1, 5, group = G3, tooltip = "Zigzag thickness.")
iZZStyle = input.string("Solid", "Style", ["Solid", "Dashed", "Dotted"], group = G3, tooltip = "Zigzag line style.")
 
G4 = "Key Levels"
iKey      = input.bool(false, "Show key levels", group = G4, tooltip = "Price levels of external swing highs/lows that have been broken (eBOS/eCHoCH levels). Off by default to keep the chart clean.")
iKeyMode  = input.string("Short stub", "Mode", ["Short stub", "Until touched"], group = G4, tooltip = "Short stub = a short line starting at the swing point, 'Stub length' bars long. Until touched = line from the swing to the candle where price returns to the level; extends right if price has not returned yet.")
iKeyStub  = input.int(10, "Stub length (bars)", 1, 100, group = G4, tooltip = "Length of each line in Short stub mode, counted in chart bars from the swing point. Not used in Until touched mode.")
iKeyMax   = input.int(3, "Max per side", 1, 50, group = G4, tooltip = "Only the most recent N broken highs and N broken lows are drawn. Older levels are dropped.")
iKeyCol   = input.color(color.orange, "Colour", group = G4, tooltip = "Key level colour.")
iKeyWidth = input.int(1, "Width", 1, 5, group = G4, tooltip = "Key level thickness.")
iKeyStyle = input.string("Solid", "Style", ["Solid", "Dashed", "Dotted"], group = G4, tooltip = "Key level line style.")
 
G5 = "Order Blocks"
iOB     = input.bool(true, "Show OB", group = G5, tooltip = "Order block created when structure breaks.")
iOBTrig = input.string("External only", "OB trigger", ["External only", "External + internal"], group = G5, tooltip = "Which breaks create an OB. External + internal gives more OBs (pullback OBs).")
iOBCand = input.string("Extreme of leg", "OB candle", ["Extreme of leg", "Last opposite candle before displacement"], group = G5, tooltip = "Extreme of leg = opposite candle with the lowest low (bull) / highest high (bear) of the leg. Last opposite candle = the last opposite-colour candle before the impulsive move starts.")
iOBAll  = input.bool(false, "Keep all", group = G5, tooltip = "Keep every OB found in the history window (newest kept if the 500-object limit is reached).")
iOBMax  = input.int(3, "Max per side", 1, 50, group = G5, tooltip = "Newest bullish and bearish OBs kept when Keep all is off.")
iOBExt  = input.bool(false, "Extend right", group = G5, tooltip = "Off = fixed box on the origin candle. On = box runs to the right.")
cOBBull = input.color(color.new(color.teal, 80), "Bull", inline = "ob", group = G5, tooltip = "OB fill colours.")
cOBBear = input.color(color.new(color.red, 80),  "Bear", inline = "ob", group = G5)
iOBBord = input.string("Solid", "Border style", ["Solid", "Dashed", "Dotted"], group = G5, tooltip = "OB border style.")
iBoxLen = input.int(5, "Fixed box length (candles)", 1, 50, group = G5, tooltip = "Length of non-extended OB boxes.")
 
G6 = "Fair Value Gaps"
iFVG     = input.bool(true, "Show FVG", group = G6, tooltip = "Plain 3-candle gap between candle 1 and candle 3 wicks. No inversion logic.")
iFVGAll  = input.bool(false, "Keep all", group = G6, tooltip = "Keep every FVG found in the history window (newest kept if the 500-object limit is reached).")
iFVGMax  = input.int(3, "Max per side", 1, 50, group = G6, tooltip = "Newest bullish and bearish FVGs kept when Keep all is off.")
iFVGExt  = input.bool(false, "Extend right", group = G6, tooltip = "Off = fixed box on the 3 origin candles. On = box runs to the right.")
cFVGBull = input.color(color.new(#2962FF, 75), "Bull", inline = "fv", group = G6, tooltip = "FVG fill colours.")
cFVGBear = input.color(color.new(#9C27B0, 75), "Bear", inline = "fv", group = G6)
iFVGBord = input.string("Solid", "Border style", ["Solid", "Dashed", "Dotted"], group = G6, tooltip = "FVG border style.")
 
G7 = "Projection 1"
p1En  = input.bool(true, "Enable", group = G7, tooltip = "Turn this projection on/off.")
p1Tf  = input.timeframe("15", "Timeframe", group = G7, tooltip = "Must be LOWER than the chart timeframe; otherwise this projection switches itself off (no error).")
p1N   = input.int(30, "Candle count", 3, 200, group = G7, tooltip = "Latest candles projected, counted back from the current candle. Trimmed silently if TradingView's 500 box/line limit is reached.")
p1Up  = input.color(color.teal, "Up", inline = "pc1", group = G7, tooltip = "Projected candle colours.")
p1Dn  = input.color(color.red, "Down", inline = "pc1", group = G7)
p1Sw  = input.bool(true, "Swings on projection", group = G7, tooltip = "Swing markers on the projected candles.")
p1Bos = input.bool(true, "eBOS/eCHoCH on projection", group = G7, tooltip = "Break lines on the projected candles.")
p1OB  = input.bool(true, "OB on projection", group = G7, tooltip = "Order blocks on the projected candles.")
p1FVG = input.bool(true, "FVG on projection", group = G7, tooltip = "FVGs on the projected candles.")
p1Ov  = input.bool(false, "Draw this TF structure on chart", group = G7, tooltip = "Also draw this timeframe's external swings and breaks on the main chart.")
p1OvBull = input.color(color.aqua, "Chart bull", inline = "oc1", group = G7, tooltip = "Colours for this TF's structure on the main chart.")
p1OvBear = input.color(color.fuchsia, "Chart bear", inline = "oc1", group = G7)
 
G8 = "Projection 2"
p2En  = input.bool(true, "Enable", group = G8, tooltip = "Turn this projection on/off.")
p2Tf  = input.timeframe("5", "Timeframe", group = G8, tooltip = "Must be LOWER than the chart timeframe; otherwise this projection switches itself off (no error).")
p2N   = input.int(30, "Candle count", 3, 200, group = G8, tooltip = "Latest candles projected, counted back from the current candle. Trimmed silently if TradingView's 500 box/line limit is reached.")
p2Up  = input.color(color.teal, "Up", inline = "pc2", group = G8, tooltip = "Projected candle colours.")
p2Dn  = input.color(color.red, "Down", inline = "pc2", group = G8)
p2Sw  = input.bool(true, "Swings on projection", group = G8, tooltip = "Swing markers on the projected candles.")
p2Bos = input.bool(true, "eBOS/eCHoCH on projection", group = G8, tooltip = "Break lines on the projected candles.")
p2OB  = input.bool(true, "OB on projection", group = G8, tooltip = "Order blocks on the projected candles.")
p2FVG = input.bool(true, "FVG on projection", group = G8, tooltip = "FVGs on the projected candles.")
p2Ov  = input.bool(false, "Draw this TF structure on chart", group = G8, tooltip = "Also draw this timeframe's external swings and breaks on the main chart.")
p2OvBull = input.color(color.aqua, "Chart bull", inline = "oc2", group = G8, tooltip = "Colours for this TF's structure on the main chart.")
p2OvBear = input.color(color.fuchsia, "Chart bear", inline = "oc2", group = G8)
 
G9 = "Projection Layout"
iDist   = input.int(10, "Distance from last candle (bars)", 1, 200, group = G9, tooltip = "Empty chart bars between the last candle and Projection 1.")
iGap    = input.int(6, "Gap between projections (bars)", 1, 100, group = G9, tooltip = "Empty chart bars between Projection 1 and Projection 2.")
iCW     = input.int(2, "Candle width (bars)", 1, 5, group = G9, tooltip = "Body width of each projected candle.")
iCS     = input.int(1, "Candle spacing (bars)", 0, 5, group = G9, tooltip = "Space between projected candles.")
iPLen   = input.int(3, "Swing length on projections", 1, 10, group = G9, tooltip = "External swing length used inside the projections.")
iOvBars = input.int(300, "LTF history for chart structure", 50, 1000, group = G9, tooltip = "Lower-TF candles used when drawing that TF's structure on the main chart.")
 
// ═════════════════════════ Types & object store ═════════════════════════
type LnCfg
    bool   show
    color  bull
    color  bear
    string style
    int    width
    string th
    string tv
    string tsize
    color  tcol
 
type Cfg
    int    len
    int    ilen
    bool   sw
    LnCfg  ext
    LnCfg  intl
    bool   zz
    bool   ob
    bool   fvg
    bool   key
    color  hh
    color  hl
    color  lh
    color  ll
    color  obBull
    color  obBear
    bool   useExtend   // true = chart (extend.right allowed), false = projection
    int    zoneBudget  // max boxes for zones
    string tag
 
var array<box>   gBoxes  = array.new<box>()
var array<line>  gLines  = array.new<line>()
var array<label> gLabels = array.new<label>()
 
f_clear() =>
    for b in gBoxes
        b.delete()
    for l in gLines
        l.delete()
    for lb in gLabels
        lb.delete()
    gBoxes.clear(), gLines.clear(), gLabels.clear()
 
// keep the newest objects within a cap
f_trim(int capB, int capL, int capLb) =>
    while gBoxes.size() > capB
        gBoxes.shift().delete()
    while gLines.size() > capL
        gLines.shift().delete()
    while gLabels.size() > capLb
        gLabels.shift().delete()
 
// ═════════════════════════ Drawing primitives ═════════════════════════
f_marker(int x, float y, bool isHigh, string txt, color col, bool raided, string xl, string tip) =>
    bool dots = iMarker == "Dots"
    int tr = raided and iHollow and not dots ? math.min(100, iMkTransp + 60) : iMkTransp
    string t = dots ? (raided and iHollow ? "○" : "•") : txt
    gLabels.push(label.new(x, y, t, xloc = xl, style = label.style_none, textcolor = color.new(col, tr), size = f_size(iMkSize), tooltip = tip + (raided ? " (raided)" : "")))
 
f_brk(int x1, int x2, float y, string txt, color col, string xl, LnCfg s, string tip) =>
    gLines.push(line.new(x1, y, x2, y, xloc = xl, color = col, width = s.width, style = f_style(s.style)))
    int tx = s.th == "Left" ? x1 : s.th == "Right" ? x2 : int((x1 + x2) / 2)
    string st = s.tv == "Above" ? label.style_label_down : s.tv == "Below" ? label.style_label_up : label.style_label_center
    string al = s.th == "Left" ? text.align_left : s.th == "Right" ? text.align_right : text.align_center
    gLabels.push(label.new(tx, y, txt, xloc = xl, style = st, color = color.new(color.white, 100), textcolor = s.tcol, size = f_size(s.tsize), textalign = al, tooltip = tip))
 
// ═════════════════════════ Analysis helpers ═════════════════════════
f_piv(array<float> h, array<float> l, int len) =>
    int n = h.size()
    ph = array.new<bool>(n, false)
    pl = array.new<bool>(n, false)
    if n > 2 * len
        for p = len to n - 1 - len
            bool isH = true
            bool isL = true
            for k = p - len to p + len
                if k != p
                    if h.get(k) > h.get(p)
                        isH := false
                    if l.get(k) < l.get(p)
                        isL := false
            ph.set(p, isH), pl.set(p, isL)
    [ph, pl]
 
f_opp(array<float> o, array<float> c, int k, bool bull) => bull ? c.get(k) < o.get(k) : c.get(k) > o.get(k)
 
// OB candle inside the leg [from, to]; bull = bullish OB
f_obIdx(array<float> o, array<float> h, array<float> l, array<float> c, int iFrom, int iTo, bool bull) =>
    int e = iFrom
    for k = iFrom to iTo
        if bull ? l.get(k) < l.get(e) : h.get(k) > h.get(e)
            e := k
    int j = -1
    if iOBCand == "Extreme of leg"
        if iTo - 1 >= iFrom
            for k = iFrom to iTo - 1
                if f_opp(o, c, k, bull) and (j < 0 or (bull ? l.get(k) < l.get(j) : h.get(k) > h.get(j)))
                    j := k
    else
        if f_opp(o, c, e, bull)
            j := e
            while j + 1 < iTo and f_opp(o, c, j + 1, bull)
                j += 1
        else if e > iFrom
            for k = e - 1 to iFrom
                if f_opp(o, c, k, bull)
                    j := k
                    break
    j < 0 ? e : j
 
f_pushZone(array<float> arr, int idx, float top, float bot) =>
    bool dup = false
    int n = arr.size() / 3
    if n > 0
        for z = math.max(0, n - 5) to n - 1
            if int(arr.get(z * 3)) == idx
                dup := true
    if not dup
        arr.push(idx), arr.push(top), arr.push(bot)
 
// ═════════════════════════ Core analysis ═════════════════════════
// o/h/l/c = candles, x = drawing coordinate per candle (bar index or time)
f_analyze(array<float> o, array<float> h, array<float> l, array<float> c, array<int> x, string xl, Cfg cf) =>
    int n = c.size()
    if n > 2 * cf.len + 2
        int last = n - 1
        float rng = 0.0
        for i = 0 to last
            rng += h.get(i) - l.get(i)
        float off = rng / n * iMkOffset
        // suffix extremes (for raided swings)
        sufHi = array.new<float>(n + 1, -1e300)
        sufLo = array.new<float>(n + 1, 1e300)
        for i = last to 0
            sufHi.set(i, math.max(h.get(i), sufHi.get(i + 1)))
            sufLo.set(i, math.min(l.get(i), sufLo.get(i + 1)))
        [eph, epl] = f_piv(h, l, cf.len)
        [iph, ipl] = f_piv(h, l, cf.ilen)
        bool obInt = iOBTrig == "External + internal"
        // collected output
        mI = array.new<int>(), mY = array.new<float>(), mH = array.new<bool>(), mT = array.new<string>()
        kI = array.new<int>(), kY = array.new<float>(), kB = array.new<int>(), kH = array.new<bool>()
        obB = array.new<float>(), obS = array.new<float>(), fvB = array.new<float>(), fvS = array.new<float>()
        // external state
        int trend = 0
        float hiLvl = na, int hiIdx = -1, bool hiLive = false
        float loLvl = na, int loIdx = -1, bool loLive = false
        int runIdx = -1, int lastBrk = -1
        float prevEH = na, float prevEL = na
        int lastMH = -1, int lastML = -1
        // internal state
        float iHi = na, int iHiIdx = -1, bool iHiOpen = false
        float iLo = na, int iLoIdx = -1, bool iLoOpen = false
        int iTrend = 0
        for i = 0 to last
            // 1) lock external levels when a swing confirms
            int p = i - cf.len
            if p >= cf.len
                if eph.get(p) and not hiLive
                    int src = trend == 0 ? p : trend == 1 and p >= lastBrk and runIdx >= 0 ? runIdx : -1
                    if src >= 0
                        hiLvl := h.get(src), hiIdx := src, hiLive := true
                        if src != lastMH
                            mI.push(src), mY.push(hiLvl), mH.push(true), mT.push(na(prevEH) ? "H" : hiLvl > prevEH ? "HH" : "LH")
                            prevEH := hiLvl, lastMH := src
                if epl.get(p) and not loLive
                    int src = trend == 0 ? p : trend == -1 and p >= lastBrk and runIdx >= 0 ? runIdx : -1
                    if src >= 0
                        loLvl := l.get(src), loIdx := src, loLive := true
                        if src != lastML
                            mI.push(src), mY.push(loLvl), mH.push(false), mT.push(na(prevEL) ? "L" : loLvl < prevEL ? "LL" : "HL")
                            prevEL := loLvl, lastML := src
            // 2) running extreme of the current leg
            if trend == 1 and not hiLive and runIdx >= 0 and h.get(i) > h.get(runIdx)
                runIdx := i
            if trend == -1 and not loLive and runIdx >= 0 and l.get(i) < l.get(runIdx)
                runIdx := i
            // 3) external bullish break
            if hiLive and c.get(i) > hiLvl
                string t = trend == -1 ? "eCHoCH" : "eBOS"
                if cf.ext.show
                    f_brk(x.get(hiIdx), x.get(i), hiLvl, t, cf.ext.bull, xl, cf.ext, cf.tag + "Bullish " + t + " @ " + f_px(hiLvl))
                kI.push(hiIdx), kY.push(hiLvl), kB.push(i), kH.push(true)
                int j = hiIdx
                for k = hiIdx to i
                    if l.get(k) < l.get(j)
                        j := k
                loLvl := l.get(j), loIdx := j, loLive := true
                if j != lastML
                    mI.push(j), mY.push(loLvl), mH.push(false), mT.push(na(prevEL) ? "L" : loLvl < prevEL ? "LL" : "HL")
                    prevEL := loLvl, lastML := j
                if cf.ob
                    int b = f_obIdx(o, h, l, c, hiIdx, i, true)
                    f_pushZone(obB, b, h.get(b), l.get(b))
                trend := 1, hiLive := false, runIdx := i, lastBrk := i
            // 4) external bearish break
            if loLive and c.get(i) < loLvl
                string t = trend == 1 ? "eCHoCH" : "eBOS"
                if cf.ext.show
                    f_brk(x.get(loIdx), x.get(i), loLvl, t, cf.ext.bear, xl, cf.ext, cf.tag + "Bearish " + t + " @ " + f_px(loLvl))
                kI.push(loIdx), kY.push(loLvl), kB.push(i), kH.push(false)
                int j = loIdx
                for k = loIdx to i
                    if h.get(k) > h.get(j)
                        j := k
                hiLvl := h.get(j), hiIdx := j, hiLive := true
                if j != lastMH
                    mI.push(j), mY.push(hiLvl), mH.push(true), mT.push(na(prevEH) ? "H" : hiLvl > prevEH ? "HH" : "LH")
                    prevEH := hiLvl, lastMH := j
                if cf.ob
                    int b = f_obIdx(o, h, l, c, loIdx, i, false)
                    f_pushZone(obS, b, h.get(b), l.get(b))
                trend := -1, loLive := false, runIdx := i, lastBrk := i
            // 5) internal structure
            int q = i - cf.ilen
            if q >= cf.ilen
                if iph.get(q)
                    iHi := h.get(q), iHiIdx := q, iHiOpen := true
                if ipl.get(q)
                    iLo := l.get(q), iLoIdx := q, iLoOpen := true
            if iHiOpen and c.get(i) > iHi
                iHiOpen := false
                string t = iTrend == -1 ? "iCHoCH" : "iBOS"
                iTrend := 1
                if cf.intl.show
                    f_brk(x.get(iHiIdx), x.get(i), iHi, t, cf.intl.bull, xl, cf.intl, cf.tag + "Bullish " + t + " @ " + f_px(iHi))
                if cf.ob and obInt
                    int b = f_obIdx(o, h, l, c, iHiIdx, i, true)
                    f_pushZone(obB, b, h.get(b), l.get(b))
            if iLoOpen and c.get(i) < iLo
                iLoOpen := false
                string t = iTrend == 1 ? "iCHoCH" : "iBOS"
                iTrend := -1
                if cf.intl.show
                    f_brk(x.get(iLoIdx), x.get(i), iLo, t, cf.intl.bear, xl, cf.intl, cf.tag + "Bearish " + t + " @ " + f_px(iLo))
                if cf.ob and obInt
                    int b = f_obIdx(o, h, l, c, iLoIdx, i, false)
                    f_pushZone(obS, b, h.get(b), l.get(b))
            // 6) plain FVG
            if cf.fvg and i >= 2
                if l.get(i) > h.get(i - 2)
                    fvB.push(i - 2), fvB.push(l.get(i)), fvB.push(h.get(i - 2))
                if h.get(i) < l.get(i - 2)
                    fvS.push(i - 2), fvS.push(l.get(i - 2)), fvS.push(h.get(i))
        // ── zones (newest kept, within budget)
        int sides = (cf.ob ? 2 : 0) + (cf.fvg ? 2 : 0)
        int perSide = sides > 0 ? cf.zoneBudget / (2 * sides) : 0   // each zone = box (+ info label)
        for side = 0 to 3
            bool isOB = side < 2
            if perSide > 0 and ((isOB and cf.ob) or (not isOB and cf.fvg))
                arr = side == 0 ? obB : side == 1 ? obS : side == 2 ? fvB : fvS
                int cnt = arr.size() / 3
                int mx = math.min(perSide * 2, isOB ? (iOBAll ? 100000 : iOBMax) : (iFVGAll ? 100000 : iFVGMax))
                bool ext = isOB ? iOBExt : iFVGExt
                color col = side == 0 ? cf.obBull : side == 1 ? cf.obBear : side == 2 ? cFVGBull : cFVGBear
                string nm = (side == 0 or side == 2 ? "Bullish " : "Bearish ") + (isOB ? "OB" : "FVG")
                if cnt > 0
                    for z = math.max(0, cnt - mx) to cnt - 1
                        int li = int(arr.get(z * 3))
                        float top = arr.get(z * 3 + 1), float bot = arr.get(z * 3 + 2)
                        int ri = ext ? last : math.min(last, li + (isOB ? iBoxLen : 2))
                        gBoxes.push(box.new(x.get(li), top, x.get(ri), bot, xloc = xl, bgcolor = col, border_color = color.new(col, 40), border_width = 1,
                             border_style = f_style(isOB ? iOBBord : iFVGBord), extend = ext and cf.useExtend ? extend.right : extend.none))
                        gLabels.push(label.new(x.get(li), top, "ⓘ", xloc = xl, style = label.style_none, textcolor = color.new(col, 0), size = size.tiny,
                             tooltip = cf.tag + nm + "\nTop " + f_px(top) + "\nBottom " + f_px(bot)))
        // ── key levels
        // levels are stored in break order; walk newest -> oldest, keep iKeyMax per side
        if cf.key and kI.size() > 0
            bool stub = iKeyMode == "Short stub"
            int nHi = 0, int nLo = 0
            for z = kI.size() - 1 to 0
                bool isHi = kH.get(z)
                if (isHi ? nHi : nLo) < iKeyMax
                    if isHi
                        nHi += 1
                    else
                        nLo += 1
                    float y = kY.get(z)
                    int si = kI.get(z)
                    if stub
                        // bar_index x can run past the last bar; time-based x is clamped to known candles
                        int x2 = xl == xloc.bar_index ? x.get(si) + iKeyStub : x.get(math.min(last, si + iKeyStub))
                        gLines.push(line.new(x.get(si), y, x2, y, xloc = xl, color = iKeyCol, width = iKeyWidth, style = f_style(iKeyStyle)))
                    else
                        int m = -1
                        if kB.get(z) < last
                            for k = kB.get(z) + 1 to last
                                if isHi ? l.get(k) <= y : h.get(k) >= y
                                    m := k
                                    break
                        gLines.push(line.new(x.get(si), y, x.get(m < 0 ? last : m), y, xloc = xl, color = iKeyCol, width = iKeyWidth, style = f_style(iKeyStyle),
                             extend = m < 0 and cf.useExtend ? extend.right : extend.none))
                if nHi >= iKeyMax and nLo >= iKeyMax
                    break
        // ── zigzag (strict alternation)
        if cf.zz
            [zph, zpl] = f_piv(h, l, iZZLen)
            zI = array.new<int>(), zY = array.new<float>(), zT = array.new<int>()
            for p = 0 to last
                for s = 0 to 1
                    bool hit = s == 0 ? zph.get(p) : zpl.get(p)
                    if hit
                        int tp = s == 0 ? 1 : -1
                        float y = s == 0 ? h.get(p) : l.get(p)
                        int zn = zT.size()
                        if zn > 0 and zT.get(zn - 1) == tp
                            if tp == 1 ? y > zY.get(zn - 1) : y < zY.get(zn - 1)
                                zI.set(zn - 1, p), zY.set(zn - 1, y)
                        else
                            zI.push(p), zY.push(y), zT.push(tp)
            if zI.size() > 1
                for z = 1 to zI.size() - 1
                    gLines.push(line.new(x.get(zI.get(z - 1)), zY.get(z - 1), x.get(zI.get(z)), zY.get(z), xloc = xl, color = iZZCol, width = iZZWidth, style = f_style(iZZStyle)))
        // ── external swing markers
        if cf.sw and mI.size() > 0
            for z = 0 to mI.size() - 1
                int ix = mI.get(z)
                float y = mY.get(z)
                bool isH = mH.get(z)
                string t = mT.get(z)
                bool raided = ix < last and (isH ? sufHi.get(ix + 1) > y : sufLo.get(ix + 1) < y)
                color col = t == "HH" or t == "H" ? cf.hh : t == "LH" ? cf.lh : t == "HL" ? cf.hl : cf.ll
                float yy = isH ? y + off * (iMarker == "Dots" ? 1 : 2) : y - off * (iMarker == "Dots" ? 1 : 2)
                f_marker(x.get(ix), yy, isH, t, col, raided, xl, cf.tag + t + " @ " + f_px(y))
 
// ═════════════════════════ Chart data buffer ═════════════════════════
var cO = array.new<float>()
var cH = array.new<float>()
var cL = array.new<float>()
var cC = array.new<float>()
var cX = array.new<int>()
cO.push(open), cH.push(high), cL.push(low), cC.push(close), cX.push(bar_index)
if cC.size() > iBars
    cO.shift(), cH.shift(), cL.shift(), cC.shift(), cX.shift()
 
// ═════════════════════════ Lower-TF data (request.security_lower_tf only) ═════════════════════════
chartSec = timeframe.in_seconds()
p1Ok = p1En and timeframe.in_seconds(p1Tf) < chartSec
p2Ok = p2En and timeframe.in_seconds(p2Tf) < chartSec
p1Eff = p1Ok ? p1Tf : timeframe.period
p2Eff = p2Ok ? p2Tf : timeframe.period
 
[a1o, a1h, a1l, a1c, a1t] = request.security_lower_tf(syminfo.tickerid, p1Eff, [open, high, low, close, time])
[a2o, a2h, a2l, a2c, a2t] = request.security_lower_tf(syminfo.tickerid, p2Eff, [open, high, low, close, time])
 
var b1o = array.new<float>()
var b1h = array.new<float>()
var b1l = array.new<float>()
var b1c = array.new<float>()
var b1t = array.new<int>()
var b2o = array.new<float>()
var b2h = array.new<float>()
var b2l = array.new<float>()
var b2c = array.new<float>()
var b2t = array.new<int>()
 
f_store(array<float> bo, array<float> bh, array<float> bl, array<float> bc, array<int> bt, array<float> ao, array<float> ah, array<float> al, array<float> ac, array<int> at, int cap) =>
    if ao.size() > 0
        for i = 0 to ao.size() - 1
            bo.push(ao.get(i)), bh.push(ah.get(i)), bl.push(al.get(i)), bc.push(ac.get(i)), bt.push(at.get(i))
    while bc.size() > cap
        bo.shift(), bh.shift(), bl.shift(), bc.shift(), bt.shift()
 
// last_bar_index is the last loaded bar (the replay bar in Bar Replay); no timenow is used anywhere.
ltfCap = math.max(iOvBars, math.max(p1N, p2N))
if barstate.isconfirmed and bar_index > last_bar_index - 600
    if p1Ok
        f_store(b1o, b1h, b1l, b1c, b1t, a1o, a1h, a1l, a1c, a1t, ltfCap)
    if p2Ok
        f_store(b2o, b2h, b2l, b2c, b2t, a2o, a2h, a2l, a2c, a2t, ltfCap)
 
// ═════════════════════════ Projection ═════════════════════════
extCfg = LnCfg.new(eShow, eBull, eBear, eStyle, eWidth, eTH, eTV, eTSize, eTCol)
intCfg = LnCfg.new(nShow, nBull, nBear, nStyle, nWidth, nTH, nTV, nTSize, nTCol)
barMs  = chartSec * 1000
 
// Draws one projection (time-based x so it can reach beyond 500 future bars). Returns the next free time.
f_project(array<float> bo, array<float> bh, array<float> bl, array<float> bc, array<int> bt, array<float> ao, array<float> ah, array<float> al, array<float> ac, array<int> at,
     int startX, int cnt, int maxN, string tf, color up, color dn, bool sw, bool bos, bool ob, bool fvg, bool ov, color ovBull, color ovBear) =>
    o = bo.copy(), h = bh.copy(), l = bl.copy(), c = bc.copy(), t = bt.copy()
    if not barstate.isconfirmed and ao.size() > 0
        for i = 0 to ao.size() - 1
            o.push(ao.get(i)), h.push(ah.get(i)), l.push(al.get(i)), c.push(ac.get(i)), t.push(at.get(i))
    string tag = f_tfName(tf) + " "
    int nextX = startX
    LnCfg noInt = intCfg.copy()
    noInt.show := false
    if c.size() > 0
        if ov
            LnCfg oc = extCfg.copy()
            oc.show := true, oc.bull := ovBull, oc.bear := ovBear
            f_analyze(o, h, l, c, t, xloc.bar_time, Cfg.new(iLen, nLen, true, oc, noInt, false, false, false, false, ovBull, ovBull, ovBear, ovBear, na, na, true, 0, tag))
        int n = math.min(cnt, c.size(), maxN)
        if n >= 3
            int s = c.size() - n
            po = o.slice(s, s + n), ph = h.slice(s, s + n), pl = l.slice(s, s + n), pc = c.slice(s, s + n)
            px = array.new<int>()
            int step = (iCW + iCS) * barMs
            for i = 0 to n - 1
                int x0 = startX + i * step
                int xm = x0 + int(iCW * barMs / 2)
                px.push(xm)
                float vo = po.get(i), vc = pc.get(i)
                color col = vc >= vo ? up : dn
                float bTop = math.max(vo, vc), float bBot = math.min(vo, vc)
                if bTop - bBot < syminfo.mintick
                    bTop += syminfo.mintick
                gBoxes.push(box.new(x0, bTop, x0 + iCW * barMs, bBot, xloc = xloc.bar_time, bgcolor = col, border_color = col, border_width = 1))
                gLines.push(line.new(xm, ph.get(i), xm, pl.get(i), xloc = xloc.bar_time, color = col, width = 1))
            nextX := startX + n * step
            float top = ph.max(), float bot = pl.min()
            gLabels.push(label.new(int((startX + nextX) / 2), top + (top - bot) * 0.15, f_tfName(tf), xloc = xloc.bar_time, style = label.style_label_down,
                 color = color.new(color.gray, 100), textcolor = color.silver, size = size.normal, tooltip = "Projection: last " + str.tostring(n) + " candles of " + f_tfName(tf)))
            LnCfg pc_ = extCfg.copy()
            pc_.show := bos
            f_analyze(po, ph, pl, pc, px, xloc.bar_time, Cfg.new(iPLen, nLen, sw, pc_, noInt, false, ob, fvg, false, cHH, cHL, cLH, cLL, cOBBull, cOBBear, false, 16, "Projection " + tag))
    nextX
 
// ═════════════════════════ Render (last loaded bar only) ═════════════════════════
if barstate.islast
    f_clear()
    // reserve room for projections, zones/structure are drawn first
    int need = (p1Ok ? p1N + 40 + (p1Ov ? 60 : 0) : 0) + (p2Ok ? p2N + 40 + (p2Ov ? 60 : 0) : 0)
    int cap = math.max(100, 500 - need)
    f_analyze(cO, cH, cL, cC, cX, xloc.bar_index, Cfg.new(iLen, nLen, iSwings, extCfg, intCfg, iZZ, iOB, iFVG, iKey, cHH, cHL, cLH, cLL, cOBBull, cOBBear, true, cap, f_tfName(timeframe.period) + " "))
    f_trim(cap, cap, cap)
    int x = time + iDist * barMs
    if p1Ok
        int rem = math.min(500 - gBoxes.size(), 500 - gLines.size()) - 40
        int m1 = p2Ok ? rem / 2 : rem
        x := f_project(b1o, b1h, b1l, b1c, b1t, a1o, a1h, a1l, a1c, a1t, x, p1N, m1, p1Tf, p1Up, p1Dn, p1Sw, p1Bos, p1OB, p1FVG, p1Ov, p1OvBull, p1OvBear) + iGap * barMs
    if p2Ok
        int rem = math.min(500 - gBoxes.size(), 500 - gLines.size()) - 20
        f_project(b2o, b2h, b2l, b2c, b2t, a2o, a2h, a2l, a2c, a2t, x, p2N, rem, p2Tf, p2Up, p2Dn, p2Sw, p2Bos, p2OB, p2FVG, p2Ov, p2OvBull, p2OvBear)
 
// Keeps the indicator on the same price scale as the candles (hidden)
plot(close, "Scale anchor", color = na, display = display.none, editable = false)

← 返回列表