BTM - SMC Confluence Engine

BeyondTheMarkets · study · 647 行 · 点赞 15 · TradingView 原页

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

Pine Script

//@version=6
indicator("BTM - SMC Confluence Engine",
     shorttitle="BTM - SMC Confluence",
     overlay=true,
     max_boxes_count=500,
     max_labels_count=100,
     max_lines_count=100,
     max_bars_back=500)
 
//━━━━━━━━━━━━━━━━━━━
// ABOUT
//━━━━━━━━━━━━━━━━━━━
// Non-repainting:
//   - Zones are detected, broken, flipped and touch-counted only on closed bars
//     (barstate.isconfirmed), so nothing appears and then vanishes intrabar.
//   - Pivot-based zones (structure for OBs, S/R) are confirmed `length` bars
//     after the pivot candle. They are drawn from that candle, but only exist
//     from the confirmation bar onward - the same in history as live.
//   - Merging and strength use the ATR and bar count of the last closed bar,
//     so the drawing only changes when a bar closes.
//
// Zone types (each type has its own colour, labels say Bullish / Bearish):
//   OB           last opposite candle before the leg that broke a swing high/low
//   Internal OB  same, from the smaller internal structure
//   Breaker      an OB / internal OB that price closed through - it flips polarity
//   FVG          3-candle imbalance (gap between candle 1 and candle 3 wicks)
//   IFVG         an FVG that price closed through - it flips polarity
//   Support /    swing pivot widened by ATR, optional role reversal when broken
//   Resistance
//
// Merging: only overlapping zones of the SAME type merge (e.g. Bullish FVG with
// Bullish FVG). FVG / IFVG, OB / Internal OB, Support / Resistance never merge.
//
// Display: only the nearest zones above (bearish) and below (bullish) the last
// close are drawn, weak zones are hidden, and labels sit in the right margin,
// stacked so they never overlap. Hover a label for the zone's exact prices.
//
// Volume / momentum candles: a big-bodied candle that closes near its extreme,
// has the biggest body of the last N candles and closes beyond their high/low
// (and by default also trades well above-average volume) is coloured white once it closes.
//
// Auto fib: drawn over the latest swing leg (zigzag of confirmed swing highs / lows).
// Retracements are measured back from the leg's end (0%) towards its start (100%),
// targets project beyond the end. It only moves once a new swing is confirmed.
//
// Strength (1-100):
//   single = type base (OB 40, Internal OB 30, Breaker 30, FVG/IFVG 25, S/R 30, flipped S/R 35)
//          + 35 x quality (displacement / gap size / pivot reaction, blended with relative volume)
//          + touches (S/R +8 each | OBs, Breaker, FVG, IFVG -8 each as the first retest is the best, max 3)
//          - up to 15 for age
//   merged = the strongest zone counts in full, then every extra overlapping zone
//            closes (Confluence Weight x its strength) of the remaining gap to 100:
//            100 x (1 - (1 - sMax/100) x (1 - w x s2/100) x (1 - w x s3/100) ...)
 
//━━━━━━━━━━━━━━━━━━━
// INPUTS
//━━━━━━━━━━━━━━━━━━━
G_OB    = "Order Blocks / Breakers"
G_FVG   = "Fair Value Gaps"
G_SR    = "Support / Resistance"
G_MOMO  = "Volume / Momentum Candles"
G_FIB   = "Auto Fibonacci"
G_MERGE = "Merging & Strength"
G_DISP  = "Display"
G_COL   = "Colours"
 
showOB    = input.bool(true, "Show Order Blocks", group=G_OB)
obLen     = input.int(20, "Order Block Structure Length", minval=2, group=G_OB, tooltip="Pivot length of the swing structure that order blocks come from.")
showIOB   = input.bool(true, "Show Internal Order Blocks", group=G_OB)
iobLen    = input.int(5, "Internal OB Structure Length", minval=1, group=G_OB, tooltip="Pivot length of the smaller internal structure that internal order blocks come from.")
showBB    = input.bool(true, "Show Breaker Blocks", group=G_OB)
obUseBody = input.bool(false, "OBs Use Candle Body (not wicks)", group=G_OB)
obMaxATR  = input.float(1.0, "Max OB Height (x ATR)", minval=0.0, step=0.1, group=G_OB, tooltip="Taller order blocks are trimmed to the part nearest price (the proximal side). 0 = no limit.")
 
showFVG   = input.bool(true, "Show FVGs", group=G_FVG)
showIFVG  = input.bool(true, "Show IFVGs", group=G_FVG)
fvgMinATR = input.float(0.2, "Min FVG Size (x ATR)", minval=0.0, step=0.05, group=G_FVG)
 
showSR     = input.bool(true, "Show Support / Resistance", group=G_SR)
srLen      = input.int(15, "S/R Pivot Length", minval=2, group=G_SR)
srWidthATR = input.float(0.3, "S/R Zone Width (x ATR)", minval=0.05, step=0.05, group=G_SR)
srFlip     = input.bool(true, "Role Reversal (broken S/R flips)", group=G_SR)
 
showMomo    = input.bool(true, "Colour Volume / Momentum Candles", group=G_MOMO)
momoMode    = input.string("Volume + Momentum", "Candle Must Have", options=["Volume + Momentum", "Volume or Momentum", "Momentum only", "Volume only"], group=G_MOMO, tooltip="Momentum = big body that closes near its high/low. Volume = well above the 20-bar average.\nIf the feed has no volume, 'Volume + Momentum' falls back to momentum only.")
momoBodyATR = input.float(1.5, "Min Body Size (x ATR)", minval=0.1, step=0.1, group=G_MOMO)
momoBodyPct = input.int(70, "Min Body % of Candle Range", minval=10, maxval=100, group=G_MOMO, tooltip="How much of the high-low range the body must fill - higher means smaller wicks and a stronger close.")
momoVolMult = input.float(2.0, "Min Volume (x 20-bar Avg)", minval=1.0, step=0.1, group=G_MOMO)
momoLookN   = input.int(10, "Must Beat Last N Candles", minval=0, maxval=100, group=G_MOMO, tooltip="Strong candles only: the body must be the biggest of the last N candles and it must close above their highest high (bullish) or below their lowest low (bearish). 0 = off.")
colMomo     = input.color(color.white, "Candle Colour", group=G_MOMO)
 
showFib = input.bool(true, "Show Auto Fib", group=G_FIB)
fibLen  = input.int(10, "Fib Swing Length", minval=2, group=G_FIB, tooltip="Pivot length of the swings the fib is drawn between. A new swing is confirmed this many bars after it forms, then the fib moves to it.")
fib236  = input.bool(false, "23.6", inline="fr", group=G_FIB)
fib382  = input.bool(true, "38.2", inline="fr", group=G_FIB)
fib500  = input.bool(true, "50", inline="fr", group=G_FIB)
fib618  = input.bool(true, "61.8", inline="fr", group=G_FIB)
fib786  = input.bool(true, "78.6", inline="fr", group=G_FIB)
fib1272 = input.bool(true, "127.2 target", inline="fe", group=G_FIB)
fib1618 = input.bool(true, "161.8 target", inline="fe", group=G_FIB)
fib2618 = input.bool(false, "261.8 target", inline="fe", group=G_FIB)
fibZone = input.string("OTE 62-79%", "Shaded Zone", options=["OTE 62-79%", "Golden Pocket 61.8-65%", "None"], group=G_FIB)
colFib  = input.color(#FFD600, "Fib Colour", group=G_FIB)
 
mergeSame    = input.bool(true, "Merge Overlapping Zones of the Same Type", group=G_MERGE, tooltip="Only identical types merge, e.g. Bullish FVG with Bullish FVG.\nFVG and IFVG, OB and Internal OB, Support and Resistance never merge with each other.")
mergeTolATR  = input.float(0.0, "Merge Proximity (x ATR)", minval=0.0, step=0.05, group=G_MERGE, tooltip="0 = zones must actually overlap. Above 0, same-type zones this close are merged too.")
confWeight   = input.float(0.5, "Confluence Weight", minval=0.1, maxval=1.0, step=0.1, group=G_MERGE, tooltip="Merged strength: the strongest zone counts in full, each extra overlapping zone adds this share of its own strength towards 100. 1.0 = full weight.")
ageDecayBars = input.int(500, "Strength Age Decay (bars)", minval=10, group=G_MERGE)
maxPerType   = input.int(5, "Max Tracked Zones per Type", minval=1, maxval=40, group=G_MERGE)
 
maxAbove     = input.int(3, "Zones Shown Above Price", minval=0, maxval=20, group=G_DISP, tooltip="Nearest bearish zones above the last close.")
maxBelow     = input.int(3, "Zones Shown Below Price", minval=0, maxval=20, group=G_DISP, tooltip="Nearest bullish zones below the last close.")
minStrength  = input.int(25, "Hide Zones Below Strength %", minval=0, maxval=100, group=G_DISP)
labelGapATR  = input.float(0.35, "Label Spacing (x ATR)", minval=0.0, step=0.05, group=G_DISP, tooltip="Minimum vertical gap between labels so they never sit on top of each other.")
extendBars   = input.int(20, "Extend Zones Right (bars)", minval=0, maxval=200, group=G_DISP)
showStrength = input.bool(true, "Show Strength % in Labels", group=G_DISP)
fadeByStr    = input.bool(true, "Shade Zones by Strength", group=G_DISP)
labelSizeOpt = input.string("Small", "Label Size", options=["Tiny", "Small", "Normal"], group=G_DISP)
showHistory  = input.bool(false, "Show Broken Zones", group=G_DISP)
maxHistory   = input.int(30, "Max Broken Zones Shown", minval=1, maxval=200, group=G_DISP)
 
colOBBull   = input.color(#2962FF, "Order Block  Bull", inline="ob", group=G_COL)
colOBBear   = input.color(#2962FF, "Bear", inline="ob", group=G_COL)
colIOBBull  = input.color(#90CAF9, "Internal OB  Bull", inline="iob", group=G_COL)
colIOBBear  = input.color(#90CAF9, "Bear", inline="iob", group=G_COL)
colBBBull   = input.color(#FF9800, "Breaker  Bull", inline="bb", group=G_COL)
colBBBear   = input.color(#FF9800, "Bear", inline="bb", group=G_COL)
colFVGBull  = input.color(#AB47BC, "FVG  Bull", inline="fvg", group=G_COL)
colFVGBear  = input.color(#AB47BC, "Bear", inline="fvg", group=G_COL)
colIFVGBull = input.color(#00BCD4, "IFVG  Bull", inline="ifvg", group=G_COL)
colIFVGBear = input.color(#00BCD4, "Bear", inline="ifvg", group=G_COL)
colSup      = input.color(#4CAF50, "Support", inline="sr", group=G_COL)
colRes      = input.color(#F44336, "Resistance", inline="sr", group=G_COL)
 
//━━━━━━━━━━━━━━━━━━━
// ZONE MODEL
//━━━━━━━━━━━━━━━━━━━
// kind: even = bullish, odd = bearish
//   0 Bullish OB        1 Bearish OB
//   2 Bullish Breaker   3 Bearish Breaker
//   4 Bullish FVG       5 Bearish FVG
//   6 Bullish IFVG      7 Bearish IFVG
//   8 Support           9 Resistance
//  10 Bullish Int. OB  11 Bearish Int. OB
N_KINDS = 12
 
type Zone
    float top
    float bottom
    int   left
    int   created
    int   kind
    float quality
    int   touches = 0
    bool  flipped = false
    int   ended   = na
 
// last unbroken swing point of one structure level
type Swing
    float price
    int   pivotBar
    bool  broken = true
 
var array<Zone>  zones       = array.new<Zone>()
var array<Zone>  brokenZones = array.new<Zone>()
var array<box>   drawnBoxes  = array.new<box>()
var array<label> drawnLabels = array.new<label>()
var array<line>  drawnLines  = array.new<line>()
 
var Swing swingHi    = Swing.new()
var Swing swingLo    = Swing.new()
var Swing internalHi = Swing.new()
var Swing internalLo = Swing.new()
 
// latest fib leg: last swing high / low, fibLast = 1 when the high came last (up leg), -1 for a low
var float fibHi    = na
var int   fibHiBar = na
var float fibLo    = na
var int   fibLoBar = na
var int   fibLast  = 0
 
// one zone, or several merged zones of the same type, ready to draw
type Cluster
    float top
    float bottom
    int   left
    int   kind
    int   n
    float strength
    bool  flipped
 
// values from the last closed bar, used when drawing
var float confAtr   = na
var float confClose = na
var int   confBar   = na
 
//━━━━━━━━━━━━━━━━━━━
// SERIES (every bar, so their history stays consistent)
//━━━━━━━━━━━━━━━━━━━
atrVal    = ta.atr(14)
volSma    = ta.sma(volume, 20)
swPH      = ta.pivothigh(high, obLen, obLen)
swPL      = ta.pivotlow(low, obLen, obLen)
inPH      = ta.pivothigh(high, iobLen, iobLen)
inPL      = ta.pivotlow(low, iobLen, iobLen)
srPH      = ta.pivothigh(high, srLen, srLen)
srPL      = ta.pivotlow(low, srLen, srLen)
lowSince  = ta.lowest(low, srLen)
highSince = ta.highest(high, srLen)
fibPH     = ta.pivothigh(high, fibLen, fibLen)
fibPL     = ta.pivotlow(low, fibLen, fibLen)
 
lblSize = labelSizeOpt == "Tiny" ? size.tiny : labelSizeOpt == "Normal" ? size.normal : size.small
 
//━━━━━━━━━━━━━━━━━━━
// HELPERS
//━━━━━━━━━━━━━━━━━━━
kindBull(int k) =>
    k % 2 == 0
 
isSRKind(int k) =>
    k == 8 or k == 9
 
kindShort(int k) =>
    k <= 1 ? "OB" : k <= 3 ? "Breaker" : k <= 5 ? "FVG" : k <= 7 ? "IFVG" : k == 8 ? "Support" : k == 9 ? "Resistance" : "Internal OB"
 
zoneName(int k, bool flipped) =>
    string nm = isSRKind(k) ? kindShort(k) : (kindBull(k) ? "Bullish " : "Bearish ") + kindShort(k)
    isSRKind(k) and flipped ? nm + " (Flip)" : nm
 
kindVisible(int k) =>
    k <= 1 ? showOB : k <= 3 ? showBB : k <= 5 ? showFVG : k <= 7 ? showIFVG : k <= 9 ? showSR : showIOB
 
kindColor(int k) =>
    switch k
        0  => colOBBull
        1  => colOBBear
        2  => colBBBull
        3  => colBBBear
        4  => colFVGBull
        5  => colFVGBear
        6  => colIFVGBull
        7  => colIFVGBear
        8  => colSup
        9  => colRes
        10 => colIOBBull
        => colIOBBear
 
// kind a zone turns into when price closes through it, -1 = remove it
flipKind(int k) =>
    switch k
        0  => 3
        1  => 2
        4  => 7
        5  => 6
        8  => srFlip ? 9 : -1
        9  => srFlip ? 8 : -1
        10 => 3
        11 => 2
        => -1
 
kindBase(int k) =>
    k <= 1 ? 40.0 : k <= 3 ? 30.0 : k <= 7 ? 25.0 : 30.0
 
// relative volume mapped to 0..1 (0.5x avg -> 0, 2.5x avg -> 1), na when the feed has no volume
relVolNorm(float v, float s) =>
    na(v) or na(s) or s <= 0 ? na : math.max(0.0, math.min((v / s - 0.5) / 2.0, 1.0))
 
qualityOf(float disp, float vol) =>
    float d = math.max(0.0, math.min(disp, 1.0))
    na(vol) ? d : d * 0.6 + vol * 0.4
 
zoneStrength(Zone z) =>
    bool  isSR = isSRKind(z.kind)
    float s    = kindBase(z.kind) + (isSR and z.flipped ? 5.0 : 0.0) + 35.0 * z.quality
    float tch  = math.min(z.touches, 3) * 8.0
    float age  = math.min(float(confBar - z.created) / ageDecayBars, 1.0)
    math.max(1.0, math.min(100.0, s + (isSR ? tch : -tch) - 15.0 * age))
 
fillTransp(float s) =>
    fadeByStr ? 92.0 - s * 0.15 : 88.0
 
// black text on light colours, white on dark
textOn(color c) =>
    0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c) > 150 ? color.black : color.white
 
clusterText(Cluster c) =>
    string nm = c.n == 1 ? zoneName(c.kind, c.flipped) : zoneName(c.kind, false) + " (" + str.tostring(c.n) + " merged)"
    showStrength ? nm + " | " + str.tostring(math.round(c.strength)) + "%" : nm
 
//━━━━━━━━━━━━━━━━━━━
// ZONE ENGINE (closed bars only)
//━━━━━━━━━━━━━━━━━━━
if barstate.isconfirmed and not na(atrVal)
    confAtr   := atrVal
    confClose := close
    confBar   := bar_index
    bool changed = false
 
    // 1) existing zones: a close through flips or removes the zone, otherwise count fresh touches
    if zones.size() > 0
        for i = zones.size() - 1 to 0
            Zone z      = zones.get(i)
            bool broken = kindBull(z.kind) ? close < z.bottom : close > z.top
            if broken
                if showHistory
                    Zone h = z.copy()
                    h.ended := bar_index
                    brokenZones.push(h)
                    if brokenZones.size() > maxHistory
                        brokenZones.shift()
                int nk = z.flipped ? -1 : flipKind(z.kind)
                if nk < 0
                    zones.remove(i)
                else
                    z.kind    := nk
                    z.left    := bar_index
                    z.created := bar_index
                    z.touches := 0
                    z.flipped := true
                    changed   := true
            else
                bool inNow  = high > z.bottom and low < z.top
                bool inPrev = high[1] > z.bottom and low[1] < z.top
                if inNow and not inPrev
                    z.touches := z.touches + 1
 
    // 2) structure breaks -> order blocks. lvl 0 = swing structure (OB), lvl 1 = internal structure (Internal OB)
    int bullOBLeft = -1
    int bearOBLeft = -1
    for lvl = 0 to 1
        int   len  = lvl == 0 ? obLen : iobLen
        float ph   = lvl == 0 ? swPH : inPH
        float pl   = lvl == 0 ? swPL : inPL
        Swing sh   = lvl == 0 ? swingHi : internalHi
        Swing sl   = lvl == 0 ? swingLo : internalLo
        int   kOff = lvl == 0 ? 0 : 10
        if not na(ph)
            sh.price    := ph
            sh.pivotBar := bar_index - len
            sh.broken   := false
        if not na(pl)
            sl.price    := pl
            sl.pivotBar := bar_index - len
            sl.broken   := false
 
        if not sh.broken and close > sh.price
            sh.broken := true
            int span = math.min(bar_index - sh.pivotBar, 250)
            if span >= 1
                // origin of the breaking leg = lowest low since the swing high
                int org = 1
                for j = 1 to span
                    if low[j] < low[org]
                        org := j
                // OB = last bearish candle at or just before the origin, else the origin candle
                int ob = org
                for j = org to math.min(org + 3, span)
                    if close[j] < open[j]
                        ob := j
                        break
                // skip the internal OB when the swing OB already took the same candle this bar
                if bar_index - ob != bullOBLeft
                    bullOBLeft := bar_index - ob
                    float obTop = obUseBody ? math.max(open[ob], close[ob]) : high[ob]
                    float obBot = obUseBody ? math.min(open[ob], close[ob]) : low[ob]
                    if obMaxATR > 0 and obTop - obBot > obMaxATR * atrVal
                        obBot := obTop - obMaxATR * atrVal
                    float leg   = math.min((close - obBot) / atrVal, 6.0) / 6.0
                    float brk   = math.min(math.abs(close - open) / atrVal, 1.5) / 1.5
                    zones.push(Zone.new(obTop, obBot, bar_index - ob, bar_index, kOff, qualityOf(0.5 * leg + 0.5 * brk, relVolNorm(volume[ob], volSma[ob]))))
                    changed := true
 
        if not sl.broken and close < sl.price
            sl.broken := true
            int span = math.min(bar_index - sl.pivotBar, 250)
            if span >= 1
                // origin of the breaking leg = highest high since the swing low
                int org = 1
                for j = 1 to span
                    if high[j] > high[org]
                        org := j
                // OB = last bullish candle at or just before the origin, else the origin candle
                int ob = org
                for j = org to math.min(org + 3, span)
                    if close[j] > open[j]
                        ob := j
                        break
                if bar_index - ob != bearOBLeft
                    bearOBLeft := bar_index - ob
                    float obTop = obUseBody ? math.max(open[ob], close[ob]) : high[ob]
                    float obBot = obUseBody ? math.min(open[ob], close[ob]) : low[ob]
                    if obMaxATR > 0 and obTop - obBot > obMaxATR * atrVal
                        obTop := obBot + obMaxATR * atrVal
                    float leg   = math.min((obTop - close) / atrVal, 6.0) / 6.0
                    float brk   = math.min(math.abs(close - open) / atrVal, 1.5) / 1.5
                    zones.push(Zone.new(obTop, obBot, bar_index - ob, bar_index, kOff + 1, qualityOf(0.5 * leg + 0.5 * brk, relVolNorm(volume[ob], volSma[ob]))))
                    changed := true
 
    // 3) fair value gaps: candle 1 = [2], candle 2 = [1], candle 3 = current
    float minGap = atrVal * fvgMinATR
    if low > high[2] and close[1] > open[1] and low - high[2] >= minGap
        float gap = low - high[2]
        zones.push(Zone.new(low, high[2], bar_index - 2, bar_index, 4, qualityOf(math.min(gap / atrVal, 1.5) / 1.5, relVolNorm(volume[1], volSma[1]))))
        changed := true
    if high < low[2] and close[1] < open[1] and low[2] - high >= minGap
        float gap = low[2] - high
        zones.push(Zone.new(low[2], high, bar_index - 2, bar_index, 5, qualityOf(math.min(gap / atrVal, 1.5) / 1.5, relVolNorm(volume[1], volSma[1]))))
        changed := true
 
    // 4) support / resistance from swing pivots, quality = how far price reacted away
    float srW = atrVal * srWidthATR
    if not na(srPH)
        float react = math.min((srPH - lowSince) / atrVal, 4.0) / 4.0
        zones.push(Zone.new(srPH, srPH - srW, bar_index - srLen, bar_index, 9, qualityOf(react, relVolNorm(volume[srLen], volSma[srLen]))))
        changed := true
    if not na(srPL)
        float react = math.min((highSince - srPL) / atrVal, 4.0) / 4.0
        zones.push(Zone.new(srPL + srW, srPL, bar_index - srLen, bar_index, 8, qualityOf(react, relVolNorm(volume[srLen], volSma[srLen]))))
        changed := true
 
    // 5) keep only the newest `maxPerType` zones of each type
    if changed
        array<int> cnt = array.new<int>(N_KINDS, 0)
        for z in zones
            cnt.set(z.kind, cnt.get(z.kind) + 1)
        for k = 0 to N_KINDS - 1
            while cnt.get(k) > maxPerType
                int oldest = -1
                for [i, z] in zones
                    if z.kind == k and (oldest < 0 or z.created < zones.get(oldest).created)
                        oldest := i
                zones.remove(oldest)
                cnt.set(k, cnt.get(k) - 1)
 
//━━━━━━━━━━━━━━━━━━━
// AUTO FIB LEG (closed bars only)
//━━━━━━━━━━━━━━━━━━━
// zigzag: highs and lows alternate, a repeat on the same side keeps the more extreme swing
if barstate.isconfirmed
    bool newHi = not na(fibPH) and (fibLast != 1 or fibPH > fibHi)
    bool newLo = not na(fibPL) and (fibLast != -1 or fibPL < fibLo)
    // a candle that is both a swing high and low: only take the side that continues the zigzag
    if newHi and newLo
        newHi := fibLast == -1
        newLo := fibLast == 1
    if newHi
        fibHi    := fibPH
        fibHiBar := bar_index - fibLen
        fibLast  := 1
    if newLo
        fibLo    := fibPL
        fibLoBar := bar_index - fibLen
        fibLast  := -1
 
//━━━━━━━━━━━━━━━━━━━
// VOLUME / MOMENTUM CANDLES (coloured on bar close, so they never repaint)
//━━━━━━━━━━━━━━━━━━━
candleBody  = math.abs(close - open)
candleRange = high - low
lookN       = math.max(momoLookN, 1)
maxBodyN    = ta.highest(candleBody, lookN)
priorHighN  = ta.highest(high, lookN)[1]
priorLowN   = ta.lowest(low, lookN)[1]
// biggest body of the last N candles and a close beyond their high / low
standsOut   = momoLookN == 0 or (candleBody >= maxBodyN and (close > open ? close > priorHighN : close < priorLowN))
hasVolume   = not na(volume) and not na(volSma) and volSma > 0
isMomentum  = not na(atrVal) and candleRange > 0 and candleBody >= momoBodyATR * atrVal and candleBody / candleRange >= momoBodyPct / 100.0 and standsOut
isVolume    = hasVolume and volume >= momoVolMult * volSma
isMomoBar   = switch momoMode
    "Volume + Momentum"  => hasVolume ? isMomentum and isVolume : isMomentum
    "Volume or Momentum" => isMomentum or isVolume
    "Momentum only"      => isMomentum
    => isVolume
 
barcolor(showMomo and barstate.isconfirmed and isMomoBar ? colMomo : na, title="Volume / Momentum Candle")
 
//━━━━━━━━━━━━━━━━━━━
// MERGE + DRAW (last bar only, from the closed-bar state above)
//━━━━━━━━━━━━━━━━━━━
// one zone, or several overlapping zones of the same type as one merged zone
collectCluster(array<int> members, float bot, float top, array<Cluster> out) =>
    int   leftX = bar_index
    int   top1  = 0
    array<float> strs = array.new<float>()
    for zi in members
        Zone  z = zones.get(zi)
        float s = zoneStrength(z)
        strs.push(s)
        if s > strs.get(top1)
            top1 := strs.size() - 1
        leftX := math.min(leftX, z.left)
    float miss = 1.0
    for [i, s] in strs
        miss *= 1.0 - (i == top1 ? 1.0 : confWeight) * s / 100.0
    float strength = (1.0 - miss) * 100.0
    if strength >= minStrength
        Zone z0 = zones.get(members.get(0))
        out.push(Cluster.new(top, bot, leftX, z0.kind, members.size(), strength, z0.flipped))
 
// sweep the zones of one type sorted by bottom: each zone that starts inside (or within
// `tol` of) the running cluster joins it, so merged zones of a type never overlap each other
collectKind(array<int> sorted, array<int> idxs, int kind, float tol, array<Cluster> out) =>
    array<int> members = array.new<int>()
    float cBot = na
    float cTop = na
    for oi in sorted
        int  zi = idxs.get(oi)
        Zone z  = zones.get(zi)
        if z.kind == kind
            if mergeSame and members.size() > 0 and z.bottom <= cTop + tol
                members.push(zi)
                cTop := math.max(cTop, z.top)
            else
                if members.size() > 0
                    collectCluster(members, cBot, cTop, out)
                members.clear()
                members.push(zi)
                cBot := z.bottom
                cTop := z.top
    if members.size() > 0
        collectCluster(members, cBot, cTop, out)
 
// one fib level: line from x1 to x2, price label to the left of x1
fibLevel(int x1, int x2, float price, string txt, string style) =>
    drawnLines.push(line.new(x1, price, x2, price, color=color.new(colFib, 25), style=style))
    drawnLabels.push(label.new(x1, price, txt + "  " + str.tostring(price, format.mintick),
         style     = label.style_label_right,
         color     = color.new(colFib, 100),
         textcolor = colFib,
         size      = size.small))
 
if barstate.islast
    for b in drawnBoxes
        b.delete()
    drawnBoxes.clear()
    for l in drawnLabels
        l.delete()
    drawnLabels.clear()
    for ln in drawnLines
        ln.delete()
    drawnLines.clear()
 
    // auto fib: 0% = end of the latest leg, 100% = its start
    if showFib and fibLast != 0 and not na(fibHi) and not na(fibLo) and fibHi > fibLo
        bool  up     = fibLast == 1
        float fEnd   = up ? fibHi : fibLo
        float fStart = up ? fibLo : fibHi
        int   xEnd   = up ? fibHiBar : fibLoBar
        int   xStart = up ? fibLoBar : fibHiBar
        int   xRight = bar_index + extendBars
        float rng    = fEnd - fStart
        if fibZone != "None"
            bool  ote = fibZone == "OTE 62-79%"
            float zA  = fEnd - (ote ? 0.62 : 0.618) * rng
            float zB  = fEnd - (ote ? 0.79 : 0.65) * rng
            drawnBoxes.push(box.new(xEnd, math.max(zA, zB), xRight, math.min(zA, zB),
                 border_color = color.new(colFib, 70),
                 bgcolor      = color.new(colFib, 90),
                 text         = ote ? "OTE" : "Golden Pocket",
                 text_color   = color.new(colFib, 30),
                 text_size    = size.small,
                 text_halign  = text.align_left,
                 text_valign  = text.align_center))
        fibLevel(xStart, xRight, fEnd, "0%", line.style_solid)
        fibLevel(xStart, xRight, fStart, "100%", line.style_solid)
        array<float> rets = array.from(0.236, 0.382, 0.5, 0.618, 0.786)
        array<bool>  rOn  = array.from(fib236, fib382, fib500, fib618, fib786)
        for [i, r] in rets
            if rOn.get(i)
                fibLevel(xStart, xRight, fEnd - r * rng, str.tostring(r * 100, "#.#") + "%", r == 0.5 or r == 0.618 ? line.style_solid : line.style_dashed)
        array<float> exts = array.from(1.272, 1.618, 2.618)
        array<bool>  eOn  = array.from(fib1272, fib1618, fib2618)
        for [i, t] in exts
            if eOn.get(i)
                fibLevel(xEnd, xRight, fStart + t * rng, str.tostring(t * 100, "#.#") + "% target", line.style_dotted)
 
    if showHistory
        for h in brokenZones
            if kindVisible(h.kind)
                color c = kindColor(h.kind)
                drawnBoxes.push(box.new(h.left, h.top, h.ended, h.bottom,
                     border_color = color.new(c, 70),
                     border_style = line.style_dotted,
                     bgcolor      = color.new(c, 95)))
 
    // 1) merge overlapping zones of the same type
    array<float> bots = array.new<float>()
    array<int>   idxs = array.new<int>()
    for [i, z] in zones
        if kindVisible(z.kind)
            bots.push(z.bottom)
            idxs.push(i)
    array<Cluster> cands = array.new<Cluster>()
    if idxs.size() > 0
        array<int> sorted = bots.sort_indices(order.ascending)
        float      tol    = mergeTolATR * confAtr
        for k = 0 to N_KINDS - 1
            if kindVisible(k)
                collectKind(sorted, idxs, k, tol, cands)
 
    // 2) keep the nearest bearish zones above and bullish zones below the last close
    array<float> dUp = array.new<float>()
    array<int>   iUp = array.new<int>()
    array<float> dDn = array.new<float>()
    array<int>   iDn = array.new<int>()
    for [i, c] in cands
        if kindBull(c.kind)
            dDn.push(math.max(0.0, confClose - c.top))
            iDn.push(i)
        else
            dUp.push(math.max(0.0, c.bottom - confClose))
            iUp.push(i)
    array<Cluster> shown = array.new<Cluster>()
    if maxAbove > 0 and dUp.size() > 0
        array<int> near = dUp.sort_indices(order.ascending)
        for j = 0 to math.min(maxAbove, near.size()) - 1
            shown.push(cands.get(iUp.get(near.get(j))))
    if maxBelow > 0 and dDn.size() > 0
        array<int> near = dDn.sort_indices(order.ascending)
        for j = 0 to math.min(maxBelow, near.size()) - 1
            shown.push(cands.get(iDn.get(near.get(j))))
 
    // 3) boxes, then labels in the right margin stacked bottom-up so none overlap
    if shown.size() > 0
        array<float> mids = array.new<float>()
        for c in shown
            color base = kindColor(c.kind)
            drawnBoxes.push(box.new(c.left, c.top, bar_index + extendBars, c.bottom,
                 border_color = color.new(base, 40),
                 border_width = c.n > 1 ? 2 : 1,
                 bgcolor      = color.new(base, fillTransp(c.strength))))
            mids.push((c.top + c.bottom) / 2)
        float gap  = labelGapATR * confAtr
        float prev = na
        array<int> byPrice = mids.sort_indices(order.ascending)
        for j in byPrice
            Cluster c    = shown.get(j)
            color   base = kindColor(c.kind)
            float   y    = na(prev) ? mids.get(j) : math.max(mids.get(j), prev + gap)
            prev := y
            drawnLabels.push(label.new(bar_index + extendBars, y, clusterText(c),
                 style     = label.style_label_left,
                 color     = color.new(base, 15),
                 textcolor = textOn(base),
                 size      = lblSize,
                 tooltip   = "Top " + str.tostring(c.top, format.mintick) + "\nBottom " + str.tostring(c.bottom, format.mintick)))

← 返回列表