TS-Market Phases

OdegosX · study · 818 行 · 点赞 15 · TradingView 原页

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

Pine Script

//@version=6
// TS-Market Phases v18 (auto light/dark theme)
// Beginner-friendly market phases: Up / Down / Range ribbon (pale = pausing), higher-timeframe dot rows,
// range lines on the chart (box and swing/dealing ranges) and a plain-English narrator.
// Signals don't repaint; range lines are drawn back to where the range began.
 
indicator("TS-Market Phases", shorttitle = "TS-Phases", overlay = false, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500)
 
// ═══ Inputs: basic ═══════════════════════════════════════
grpV = "Display"
showNarr  = input.bool(true, "Show narrator box", group = grpV, display = display.none)
narrPos   = input.string("Top right", "Narrator position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = grpV, display = display.none)
narrSize  = input.string("Small", "Narrator text size", options = ["Tiny", "Small", "Normal"], group = grpV, display = display.none)
showLines = input.bool(true, "Show ranges on chart", group = grpV, display = display.none)
rngStyle  = input.string("Shaded box", "Range style", options = ["Lines", "Shaded box"], group = grpV, display = display.none)
showForm  = input.bool(true, "Show \"Range forming?\" early warning", group = grpV, display = display.none, tooltip = "Light-gray patch in the ribbon and dotted lines on the chart when a trend stalls and price starts rotating between two levels.")
ribH      = input.float(0.5, "Ribbon thickness", minval = 0.2, maxval = 1.0, step = 0.1, group = grpV, display = display.none)
labelBars = input.int(10, "Show tab name when tab is at least (bars)", minval = 1, group = grpV, display = display.none)
 
grpH = "Higher timeframes (dot rows)"
useH1   = input.bool(true, "", inline = "h1", group = grpH, display = display.none)
tfH1    = input.timeframe("60", "HTF 1", inline = "h1", group = grpH, display = display.none)
useH2   = input.bool(true, "", inline = "h2", group = grpH, display = display.none)
tfH2    = input.timeframe("240", "HTF 2", inline = "h2", group = grpH, display = display.none)
useH3   = input.bool(true, "", inline = "h3", group = grpH, display = display.none)
tfH3    = input.timeframe("D", "HTF 3", inline = "h3", group = grpH, display = display.none)
dotSize = input.int(3, "Dot size", minval = 1, maxval = 6, group = grpH, display = display.none)
 
grpT = "Theme"
themeMode = input.string("Auto", "Theme", options = ["Auto", "Light", "Dark"], group = grpT, display = display.none, tooltip = "Auto follows the chart background. Pick Light or Dark to force one set of colors.")
cUpL    = input.color(#1D9E75, "Light chart:  Up", inline = "tl", group = grpT, display = display.none)
cDownL  = input.color(#E24B4A, "Down", inline = "tl", group = grpT, display = display.none)
cRangeL = input.color(#888780, "Range", inline = "tl", group = grpT, display = display.none)
cUpD    = input.color(#3DD6A3, "Dark chart:   Up", inline = "td", group = grpT, display = display.none)
cDownD  = input.color(#FF6B6A, "Down", inline = "td", group = grpT, display = display.none)
cRangeD = input.color(#B4B2A9, "Range", inline = "td", group = grpT, display = display.none)
pauseL  = input.int(60, "Pause shade transparency:  light", minval = 0, maxval = 90, inline = "tp", group = grpT, display = display.none)
pauseD  = input.int(45, "dark", minval = 0, maxval = 90, inline = "tp", group = grpT, display = display.none)
fillL   = input.int(88, "Range box fill transparency:  light", minval = 0, maxval = 100, inline = "tf", group = grpT, display = display.none)
fillD   = input.int(80, "dark", minval = 0, maxval = 100, inline = "tf", group = grpT, display = display.none)
 
// chart background brightness (0–255): below 128 counts as a dark chart
float bgLum  = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
bool  isDark = themeMode == "Dark" or (themeMode == "Auto" and bgLum < 128)
color cUp       = isDark ? cUpD : cUpL
color cDown     = isDark ? cDownD : cDownL
color cRange    = isDark ? cRangeD : cRangeL
int   pauseFade = isDark ? pauseD : pauseL
int   boxFill   = isDark ? fillD : fillL
color headTxt   = isDark ? #131722 : color.white     // narrator header text on the phase color
 
grpC = "Lines"
rngLnStyle = input.string("Dotted", "Range lines / box border", options = ["Solid", "Dashed", "Dotted"], inline = "cR", group = grpC, display = display.none)
rngLnW     = input.int(2, "", minval = 1, maxval = 5, inline = "cR", group = grpC, display = display.none, tooltip = "Line style and thickness of the range lines (or the shaded box border) on the price chart.")
frmLnStyle = input.string("Dotted", "Range forming lines", options = ["Solid", "Dashed", "Dotted"], inline = "cF", group = grpC, display = display.none)
frmLnW     = input.int(1, "", minval = 1, maxval = 5, inline = "cF", group = grpC, display = display.none, tooltip = "Line style and thickness of the \"Range forming?\" early-warning lines. They use the Range color.")
 
f_lnStyle(string s) =>
    s == "Solid" ? line.style_solid : s == "Dotted" ? line.style_dotted : line.style_dashed
 
// ═══ Inputs: advanced (defaults are tuned; change with care) ═
grpS = "Advanced · Structure"
swL       = input.int(10, "Swing left bars", minval = 1, group = grpS, display = display.none, tooltip = "Bigger = only major swings count as structure.")
swR       = input.int(3, "Swing right bars (confirmation lag)", minval = 1, group = grpS, display = display.none)
 
grpE = "Advanced · Trend strength"
erLen      = input.int(20, "Efficiency length", minval = 2, group = grpE, display = display.none)
erSmooth   = input.int(5, "Efficiency smoothing", minval = 1, group = grpE, display = display.none)
erEnter    = input.float(0.35, "Trend starts above", minval = 0.05, maxval = 0.95, step = 0.05, group = grpE, display = display.none)
erExit     = input.float(0.20, "Trend ends below", minval = 0.0, maxval = 0.9, step = 0.05, group = grpE, display = display.none)
slopeLen   = input.int(21, "Trend EMA length", minval = 2, group = grpE, display = display.none)
slopeBars  = input.int(5, "EMA slope lookback (bars)", minval = 1, group = grpE, display = display.none)
slopeEnter = input.float(0.15, "Slope starts trend (ATR per bar)", minval = 0.01, step = 0.01, group = grpE, display = display.none)
slopeExit  = input.float(0.07, "Slope ends trend (ATR per bar)", minval = 0.0, step = 0.01, group = grpE, display = display.none)
slopeErMin = input.float(0.15, "Slope only counts if efficiency ≥", minval = 0.0, maxval = 0.9, step = 0.05, group = grpE, display = display.none)
dispMult   = input.float(1.75, "Displacement candle ≥ average ATR ×", minval = 1.0, step = 0.25, group = grpE, display = display.none)
atrLen     = input.int(14, "ATR length", minval = 1, group = grpE, display = display.none)
atrBase    = input.int(50, "ATR baseline length", minval = 5, group = grpE, display = display.none)
useHA      = input.bool(true, "Use Heikin Ashi to confirm shading", group = grpE, display = display.none, tooltip = "Backend only: chart candles are unchanged and levels always use real prices.")
 
grpP = "Advanced · Phase switching"
minBars   = input.int(5, "Bars a shade must hold before changing", minval = 1, group = grpP, display = display.none)
breakBars = input.int(3, "Closes outside a range to confirm a breakout", minval = 1, maxval = 10, group = grpP, display = display.none)
brkMult   = input.float(1.0, "…or one breakout candle with body ≥ average ATR ×", minval = 0.25, step = 0.25, group = grpP, display = display.none)
edgeTol   = input.float(0.1, "Edge tolerance for closes (× range height)", minval = 0.0, maxval = 0.5, step = 0.05, group = grpP, display = display.none, tooltip = "Closes this close beyond an edge still count as inside (a sweep), not a break.")
 
grpR = "Advanced · Range detection"
rngLook   = input.int(20, "Look-back window (bars)", minval = 8, maxval = 150, group = grpR, display = display.none)
minTouch  = input.int(2, "Touches needed on each edge", minval = 1, maxval = 5, group = grpR, display = display.none)
touchPct  = input.float(0.2, "Touch zone (part of box height)", minval = 0.05, maxval = 0.5, step = 0.05, group = grpR, display = display.none)
hMin      = input.float(1.0, "Box min height (× average ATR)", minval = 0.25, step = 0.25, group = grpR, display = display.none)
hMax      = input.float(4.0, "Box max height (× average ATR)", minval = 1.0, step = 0.5, group = grpR, display = display.none)
flatMax   = input.float(0.35, "Max drift across the window (× box height)", minval = 0.05, maxval = 1.0, step = 0.05, group = grpR, display = display.none)
chopMin   = input.float(50.0, "Min choppiness (0–100)", minval = 0.0, maxval = 100.0, step = 5.0, group = grpR, display = display.none)
useSwing  = input.bool(true, "Detect swing (dealing) ranges", group = grpR, display = display.none)
drMaxAge  = input.int(100, "Swing range: swings no older than (bars)", minval = 10, group = grpR, display = display.none)
hMaxSw    = input.float(10.0, "Swing range: max height (× average ATR)", minval = 1.0, step = 0.5, group = grpR, display = display.none)
drMinBars = input.int(6, "Swing range: closes inside to widen a range", minval = 2, group = grpR, display = display.none)
drMinCross = input.int(2, "Swing range: midline crosses to widen a range", minval = 1, group = grpR, display = display.none)
swAlone   = input.bool(true, "Swing ranges can start on their own", group = grpR, display = display.none)
swAloneBars = input.int(20, "Standalone swing range: closes inside", minval = 6, group = grpR, display = display.none)
swAloneCross = input.int(3, "Standalone swing range: midline crosses", minval = 2, group = grpR, display = display.none)
mergeNb   = input.bool(true, "Merge neighbouring ranges", group = grpR, display = display.none)
mergeGap  = input.int(20, "Merge if the gap is at most (bars)", minval = 1, group = grpR, display = display.none)
 
// ═══ Ids and text ════════════════════════════════════════
R_RANGE  = 0
R_UP     = 1
R_DOWN   = -1
S_STRONG = 0
S_PAUSE  = 1
S_NORMAL = 3
S_FORM   = 4
 
f_base(int r) =>
    r == R_UP ? cUp : r == R_DOWN ? cDown : cRange
 
f_col(int r, int s) =>
    s == S_FORM ? color.new(cRange, 45) : s == S_PAUSE ? color.new(f_base(r), pauseFade) : f_base(r)
 
f_tab(int r) =>
    r == R_UP ? "Up" : r == R_DOWN ? "Down" : "Range"
 
f_head(int r, int s) =>
    if s == S_FORM
        "Range forming?"
    else if r == R_UP
        s == S_PAUSE ? "Uptrend · pausing" : "Trending up"
    else if r == R_DOWN
        s == S_PAUSE ? "Downtrend · pausing" : "Trending down"
    else
        "Range"
 
f_story(int r, int s) =>
    if s == S_FORM
        "The trend has stalled and price is starting to rotate between two levels (dotted lines).\nIf both edges get tested again, it becomes a Range. Don't chase the trend inside the box."
    else if r == R_UP
        s == S_PAUSE ? "Structure is still up, but the move is resting.\nPullback or possible top. The uptrend holds until a swing low breaks with strength." : "Price broke structure up with strength.\nBuyers in control. Look for pullbacks, not tops."
    else if r == R_DOWN
        s == S_PAUSE ? "Structure is still down, but the move is resting.\nBounce or possible bottom. The downtrend holds until a swing high breaks with strength." : "Price broke structure down with strength.\nSellers in control. Don't try to catch the bottom."
    else
        "No clear direction. Buyers and sellers are balanced.\nWait for a strong close outside the box."
 
f_state(int r, int s) =>
    f_tab(r) + (s == S_PAUSE ? " (pausing)" : "")
 
f_tfName(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec >= 2592000 ? "M" : sec >= 604800 and sec % 604800 == 0 ? str.tostring(int(sec / 604800)) + "W" : sec >= 86400 and sec % 86400 == 0 ? (sec == 86400 ? "D" : str.tostring(int(sec / 86400)) + "D") : sec >= 3600 and sec % 3600 == 0 ? str.tostring(int(sec / 3600)) + "H" : str.tostring(int(sec / 60)) + "m"
 
// ═══ Higher-timeframe engine ═════════════════════════════
// Same phase and range rules as the main ribbon (box + standalone swing ranges, HA shading), without drawings,
// merging or upgrades. Used for the higher-timeframe dot rows.
f_engine() =>
    // structure
    var float ph1 = na
    var float pl1 = na
    float pH = ta.pivothigh(high, swL, swR)
    float pL = ta.pivotlow(low, swL, swR)
    if not na(pH)
        ph1 := pH
    if not na(pL)
        pl1 := pL
    var int   bias     = 0
    var float brokenHi = na
    var float brokenLo = na
    bool bosUp = false
    bool bosDn = false
    if not na(ph1) and close > ph1
        bias := 1
        if na(brokenHi) or ph1 != brokenHi
            brokenHi := ph1
            bosUp    := true
    if not na(pl1) and close < pl1
        bias := -1
        if na(brokenLo) or pl1 != brokenLo
            brokenLo := pl1
            bosDn    := true
    // trend strength
    float pathLen = math.sum(math.abs(close - close[1]), erLen)
    float erRaw   = pathLen > 0 ? (close - close[erLen]) / pathLen : 0.0
    float erS     = ta.ema(nz(erRaw), erSmooth)
    float atrNow  = ta.atr(atrLen)
    float atrAvg  = ta.sma(atrNow, atrBase)
    float atrRef  = na(atrAvg) ? atrNow : atrAvg
    float emaT    = ta.ema(close, slopeLen)
    float slope   = nz(atrRef) > 0 ? (emaT - emaT[slopeBars]) / (slopeBars * atrRef) : 0.0
    slope := ((slope > 0 and close > emaT) or (slope < 0 and close < emaT)) and math.abs(erS) >= slopeErMin ? nz(slope) : 0.0
    bool strongNow = math.abs(erS) >= erEnter or math.abs(slope) >= slopeEnter
    bool weakNow   = math.abs(erS) < erExit and math.abs(slope) < slopeExit
    var bool trending = false
    if not trending and strongNow
        trending := true
    else if trending and weakNow
        trending := false
    float rng  = high - low
    bool  disp = not na(atrRef) and rng > atrRef * dispMult and math.abs(close - open) > rng * 0.6
    if disp
        trending := true
    int tDir = (erS + slope) > 0 ? 1 : -1
    int dir  = disp ? (close > open ? 1 : -1) : trending ? tDir : 0
    // box range detector
    float bTop   = ta.highest(math.max(open, close), rngLook)
    float bBot   = ta.lowest(math.min(open, close), rngLook)
    float bH     = bTop - bBot
    float lrNow  = ta.linreg(close, rngLook, 0)
    float lrPrev = ta.linreg(close, rngLook, 1)
    float drift  = math.abs(lrNow - lrPrev) * (rngLook - 1)
    float wRange = ta.highest(high, rngLook) - ta.lowest(low, rngLook)
    float trSum  = math.sum(ta.tr(true), rngLook)
    float chopV  = wRange > 0 ? 100 * math.log10(trSum / wRange) / math.log10(rngLook) : 0.0
    int   nTop     = 0
    int   nBot     = 0
    int   lastEdge = 0
    float tol      = bH * touchPct
    if bH > 0
        for i = rngLook - 1 to 0
            bool atTop = high[i] >= bTop - tol
            bool atBot = low[i] <= bBot + tol
            if atTop and lastEdge != 1
                nTop     += 1
                lastEdge := 1
            else if atBot and lastEdge != -1
                nBot     += 1
                lastEdge := -1
    var int lastRangeEnd = -1
    bool windowFresh = bar_index - rngLook + 1 > lastRangeEnd or (mergeNb and bar_index - lastRangeEnd >= breakBars * 2)
    bool qualified   = bH > 0 and not na(atrRef) and bH >= atrRef * hMin and bH <= atrRef * hMax and drift <= bH * flatMax and nz(chopV) >= chopMin and nTop >= minTouch and nBot >= minTouch and windowFresh
    // standalone swing range
    float lowAfter  = ta.lowest(low, swR)
    float highAfter = ta.highest(high, swR)
    var float cHi     = na
    var float cLo     = na
    var int   cStart  = na
    var int   cAnchor = 0
    var bool  cLive   = false
    var int   drIn    = 0
    var int   drCross = 0
    var int   drSide  = 0
    if cLive
        if cAnchor == 1
            cLo := math.min(cLo, low)
        else
            cHi := math.max(cHi, high)
        float cH   = cHi - cLo
        float cTol = cH * edgeTol
        bool  brk  = cAnchor == 1 ? close > cHi + cTol : close < cLo - cTol
        if brk or (not na(atrRef) and cH > atrRef * hMaxSw) or bar_index - cStart > drMaxAge
            cLive := false
    if not cLive and (not na(pH) or not na(pL))
        cAnchor := not na(pH) ? 1 : -1
        cHi     := not na(pH) ? pH : highAfter
        cLo     := not na(pH) ? lowAfter : pL
        cStart  := bar_index - swR
        cLive   := true
        drIn    := 0
        drCross := 0
        drSide  := 0
    if cLive
        drIn += 1
        int sd = close > (cHi + cLo) / 2 ? 1 : -1
        if drSide != 0 and sd != drSide
            drCross += 1
        drSide := sd
    bool swAloneQ = useSwing and swAlone and cLive and drIn >= swAloneBars and drCross >= swAloneCross and not trending and cStart > lastRangeEnd and not na(atrRef) and (cHi - cLo) >= atrRef * hMin
    bool useSw    = swAloneQ and (not qualified or (cHi - cLo) >= bH)
    // regime
    var int   regime    = 0
    var float regHi     = na
    var float regLo     = na
    var int   outUp     = 0
    var int   outDn     = 0
    var int   trendHold = 0
    float edgeHi = regime == 0 ? regHi : na
    float edgeLo = regime == 0 ? regLo : na
    int  target = regime
    bool newBox = false
    if regime == 0
        float eTol = not na(edgeHi) ? (edgeHi - edgeLo) * edgeTol : 0.0
        outUp     := not na(edgeHi) and close > edgeHi + eTol ? outUp + 1 : 0
        outDn     := not na(edgeLo) and close < edgeLo - eTol ? outDn + 1 : 0
        trendHold := dir != 0 and dir == bias ? trendHold + 1 : 0
        if (outUp >= breakBars and dir == 1) or (outUp >= 1 and close > open and (disp or close - open >= atrRef * brkMult))
            target := 1
        else if (outDn >= breakBars and dir == -1) or (outDn >= 1 and close < open and (disp or open - close >= atrRef * brkMult))
            target := -1
        else if na(edgeHi) and trendHold >= minBars and bias != 0
            target := bias
        else if outUp >= breakBars * 2 or (not na(edgeHi) and close > edgeHi + (edgeHi - edgeLo) * 0.5)
            target := 1
        else if outDn >= breakBars * 2 or (not na(edgeLo) and close < edgeLo - (edgeHi - edgeLo) * 0.5)
            target := -1
        else if na(edgeHi) and (qualified or swAloneQ)
            newBox := true
    else
        if bias == -regime and dir == bias
            target := bias
        else if qualified or swAloneQ
            target := 0
    bool newR = target != regime
    var int rStart = 0
    if newR
        rStart := bar_index
    if newR and regime == 0 and bar_index > 0
        lastRangeEnd := bar_index - 1
    if newR
        regime    := target
        regHi     := regime == 0 ? (useSw ? cHi : bTop) : na
        regLo     := regime == 0 ? (useSw ? cLo : bBot) : na
        outUp     := 0
        outDn     := 0
        trendHold := 0
    if newBox
        regHi := useSw ? cHi : bTop
        regLo := useSw ? cLo : bBot
    // shade, with Heikin Ashi confirmation
    float haC = (open + high + low + close) / 4
    float haO = na
    haO := na(haO[1]) ? (open + close) / 2 : (haO[1] + haC[1]) / 2
    float haH   = math.max(high, haO, haC)
    float haL   = math.min(low, haO, haC)
    float haRng = haH - haL
    float haBT  = math.max(haO, haC)
    float haBB  = math.min(haO, haC)
    bool  haCU  = haC > haO and haRng > 0 and (haBB - haL) <= haRng * 0.05
    bool  haCD  = haC < haO and haRng > 0 and (haH - haBT) <= haRng * 0.05
    bool  haInd = haRng > 0 and math.abs(haC - haO) <= haRng * 0.3 and (haH - haBT) >= haRng * 0.2 and (haBB - haL) >= haRng * 0.2
    bool  haIndN = math.sum(haInd ? 1 : 0, 3) >= 2
    bool  haWith = regime == 1 ? (haCU and haCU[1]) : (haCD and haCD[1])
    bool  haAg   = regime == 1 ? (haC < haO and haC[1] < haO[1]) : (haC > haO and haC[1] > haO[1])
    int trendSub = dir == regime ? 0 : 1
    if useHA and regime != 0
        trendSub := haWith ? 0 : ((haAg or haIndN) and bar_index - rStart >= 3) ? 1 : trendSub
    int rawSub = regime == 0 ? 3 : trendSub
    var int sub      = 3
    var int subCand  = 3
    var int subCount = 0
    if newR
        sub      := rawSub
        subCand  := rawSub
        subCount := 1
    else
        if rawSub == subCand
            subCount += 1
        else
            subCand  := rawSub
            subCount := 1
        if subCand != sub and (subCount >= minBars or (disp and subCand == 0))
            sub := subCand
    if (regime == 1 and bosUp) or (regime == -1 and bosDn)
        sub      := 0
        subCand  := 0
        subCount := minBars
    [regime, sub]
 
// confirmed (closed) higher-timeframe bar only: no repainting
f_htf() =>
    [r, sb] = f_engine()
    [r[1], sb[1]]
 
// ═══ 1. Structure: major swings + break-of-structure bias ═
var float ph1 = na
var float pl1 = na
pH = ta.pivothigh(high, swL, swR)
pL = ta.pivotlow(low, swL, swR)
if not na(pH)
    ph1 := pH
if not na(pL)
    pl1 := pL
 
var int   bias     = 0
var float brokenHi = na
var float brokenLo = na
bool bosUp = false
bool bosDn = false
if not na(ph1) and close > ph1
    bias := 1
    if na(brokenHi) or ph1 != brokenHi
        brokenHi := ph1
        bosUp    := true
if not na(pl1) and close < pl1
    bias := -1
    if na(brokenLo) or pl1 != brokenLo
        brokenLo := pl1
        bosDn    := true
 
// ═══ 2. Trend strength ═══════════════════════════════════
float pathLen = math.sum(math.abs(close - close[1]), erLen)
float erRaw   = pathLen > 0 ? (close - close[erLen]) / pathLen : 0.0
float erS     = ta.ema(nz(erRaw), erSmooth)
float atrNow  = ta.atr(atrLen)
float atrAvg  = ta.sma(atrNow, atrBase)
float atrRef  = na(atrAvg) ? atrNow : atrAvg
float emaT    = ta.ema(close, slopeLen)
float slope   = nz(atrRef) > 0 ? (emaT - emaT[slopeBars]) / (slopeBars * atrRef) : 0.0
slope := ((slope > 0 and close > emaT) or (slope < 0 and close < emaT)) and math.abs(erS) >= slopeErMin ? nz(slope) : 0.0
bool strongNow = math.abs(erS) >= erEnter or math.abs(slope) >= slopeEnter
bool weakNow   = math.abs(erS) < erExit and math.abs(slope) < slopeExit
var bool trending = false
if not trending and strongNow
    trending := true
else if trending and weakNow
    trending := false
float rng  = high - low
bool  disp = not na(atrRef) and rng > atrRef * dispMult and math.abs(close - open) > rng * 0.6
if disp
    trending := true
int tDir = (erS + slope) > 0 ? 1 : -1
int dir  = disp ? (close > open ? 1 : -1) : trending ? tDir : 0
 
// ═══ Heikin Ashi (internal, only used to confirm shading) ═
float haC = (open + high + low + close) / 4
float haO = na
haO := na(haO[1]) ? (open + close) / 2 : (haO[1] + haC[1]) / 2
float haH   = math.max(high, haO, haC)
float haL   = math.min(low, haO, haC)
float haRng = haH - haL
float haBodyTop = math.max(haO, haC)
float haBodyBot = math.min(haO, haC)
bool  haCleanUp = haC > haO and haRng > 0 and (haBodyBot - haL) <= haRng * 0.05
bool  haCleanDn = haC < haO and haRng > 0 and (haH - haBodyTop) <= haRng * 0.05
bool  haIndec   = haRng > 0 and math.abs(haC - haO) <= haRng * 0.3 and (haH - haBodyTop) >= haRng * 0.2 and (haBodyBot - haL) >= haRng * 0.2
bool  haUp2     = haCleanUp and haCleanUp[1]
bool  haDn2     = haCleanDn and haCleanDn[1]
bool  haOppUp2  = haC < haO and haC[1] < haO[1]
bool  haOppDn2  = haC > haO and haC[1] > haO[1]
bool  haIndecN  = math.sum(haIndec ? 1 : 0, 3) >= 2
 
// ═══ 3. Box range detector ═══════════════════════════════
float bTop   = ta.highest(math.max(open, close), rngLook)      // body box
float bBot   = ta.lowest(math.min(open, close), rngLook)
float bH     = bTop - bBot
float lrNow  = ta.linreg(close, rngLook, 0)
float lrPrev = ta.linreg(close, rngLook, 1)
float drift  = math.abs(lrNow - lrPrev) * (rngLook - 1)
float wRange = ta.highest(high, rngLook) - ta.lowest(low, rngLook)
float trSum  = math.sum(ta.tr(true), rngLook)
float chopV  = wRange > 0 ? 100 * math.log10(trSum / wRange) / math.log10(rngLook) : 0.0
 
// alternating edge touches (rotations) inside the window, oldest → newest
int   nTop       = 0
int   nBot       = 0
int   firstTouch = na
int   lastEdge   = 0
float tol        = bH * touchPct
if bH > 0
    for i = rngLook - 1 to 0
        bool atTop = high[i] >= bTop - tol
        bool atBot = low[i] <= bBot + tol
        if atTop and lastEdge != 1
            nTop     += 1
            lastEdge := 1
            if na(firstTouch)
                firstTouch := bar_index - i
        else if atBot and lastEdge != -1
            nBot     += 1
            lastEdge := -1
            if na(firstTouch)
                firstTouch := bar_index - i
 
var int lastRangeEnd = -1
bool windowFresh = bar_index - rngLook + 1 > lastRangeEnd or (mergeNb and bar_index - lastRangeEnd >= breakBars * 2)
bool boxShape    = bH > 0 and not na(atrRef) and bH >= atrRef * hMin and bH <= atrRef * hMax and drift <= bH * flatMax and nz(chopV) >= chopMin and windowFresh
bool qualified   = boxShape and nTop >= minTouch and nBot >= minTouch
bool formQ       = showForm and boxShape and not qualified and nTop >= 1 and nBot >= 1 and (not useHA or haIndecN)
 
// ═══ 4. Swing (dealing) range ════════════════════════════
// Anchored on one confirmed major swing; the opposite edge forms from price until the range is used, then freezes.
float lowAfter  = ta.lowest(low, swR)
float highAfter = ta.highest(high, swR)
var float cHi     = na
var float cLo     = na
var int   cStart  = na
var int   cAnchor = 0
var bool  cLive   = false
var bool  cFrozen = false
var int   drIn    = 0
var int   drCross = 0
var int   drSide  = 0
if cLive
    if not cFrozen
        if cAnchor == 1
            cLo := math.min(cLo, low)
        else
            cHi := math.max(cHi, high)
    float cH   = cHi - cLo
    float cTol = cH * edgeTol
    bool  brk  = cFrozen ? (close > cHi + cTol or close < cLo - cTol) : cAnchor == 1 ? close > cHi + cTol : close < cLo - cTol
    if brk or (not na(atrRef) and cH > atrRef * hMaxSw) or (not cFrozen and bar_index - cStart > drMaxAge)
        cLive := false
if not cLive and (not na(pH) or not na(pL))
    cAnchor := not na(pH) ? 1 : -1
    cHi     := not na(pH) ? pH : highAfter
    cLo     := not na(pH) ? lowAfter : pL
    cStart  := bar_index - swR
    cLive   := true
    cFrozen := false
    drIn    := 0
    drCross := 0
    drSide  := 0
if cLive
    drIn += 1
    int sd = close > (cHi + cLo) / 2 ? 1 : -1
    if drSide != 0 and sd != drSide
        drCross += 1
    drSide := sd
bool swQual   = useSwing and cLive and drIn >= drMinBars and drCross >= drMinCross and not trending and cStart > lastRangeEnd and not na(atrRef) and (cHi - cLo) >= atrRef * hMin
bool swAloneQ = swAlone and swQual and drIn >= swAloneBars and drCross >= swAloneCross
bool useSw    = swAloneQ and (not qualified or (cHi - cLo) >= bH)
 
// ═══ 5. Regime: Up / Down / Range ════════════════════════
var int   regime    = R_RANGE
var int   regStart  = 0
var float regHi     = na
var float regLo     = na
var int   outUp     = 0
var int   outDn     = 0
var int   trendHold = 0
 
float edgeHi = regime == R_RANGE ? regHi : na
float edgeLo = regime == R_RANGE ? regLo : na
 
int  target  = regime
bool newBox  = false
bool upgrade = false
// a qualified swing range around the current (smaller) range takes over: leaving the small box is not a breakout
if regime == R_RANGE and swQual and not na(edgeHi) and cHi >= edgeHi and cLo <= edgeLo and (cHi - cLo) > (edgeHi - edgeLo)
    upgrade := true
    edgeHi  := cHi
    edgeLo  := cLo
if regime == R_RANGE
    float eTol = not na(edgeHi) ? (edgeHi - edgeLo) * edgeTol : 0.0
    outUp     := not na(edgeHi) and close > edgeHi + eTol ? outUp + 1 : 0
    outDn     := not na(edgeLo) and close < edgeLo - eTol ? outDn + 1 : 0
    trendHold := dir != 0 and dir == bias ? trendHold + 1 : 0
    if upgrade
        outUp := 0
        outDn := 0
    else if (outUp >= breakBars and dir == 1) or (outUp >= 1 and close > open and (disp or close - open >= atrRef * brkMult))
        target := R_UP
    else if (outDn >= breakBars and dir == -1) or (outDn >= 1 and close < open and (disp or open - close >= atrRef * brkMult))
        target := R_DOWN
    else if na(edgeHi) and trendHold >= minBars and bias != 0
        target := bias      // only the edgeless Range at the start of the chart; a mapped range must be left to end
    else if outUp >= breakBars * 2 or (not na(edgeHi) and close > edgeHi + (edgeHi - edgeLo) * 0.5)
        target := R_UP      // leaked out of the top
    else if outDn >= breakBars * 2 or (not na(edgeLo) and close < edgeLo - (edgeHi - edgeLo) * 0.5)
        target := R_DOWN    // leaked out of the bottom
    else if na(edgeHi) and (qualified or swAloneQ)
        newBox := true
else
    if bias == -regime and dir == bias
        target := bias      // structure broke against the trend, with strength
    else if qualified or swAloneQ
        target := R_RANGE   // only a qualified range ends a trend; otherwise it is a pause
 
bool newReg = bar_index == 0 or target != regime
 
var int   boxStart  = 0
var float pRngHi    = na
var float pRngLo    = na
var int   pRngStart = na
if newReg and regime == R_RANGE and bar_index > 0
    lastRangeEnd := bar_index - 1
    pRngHi       := regHi
    pRngLo       := regLo
    pRngStart    := boxStart
if newReg
    regime    := target
    regStart  := bar_index
    regHi     := regime == R_RANGE ? (useSw ? cHi : bTop) : na
    regLo     := regime == R_RANGE ? (useSw ? cLo : bBot) : na
    outUp     := 0
    outDn     := 0
    trendHold := 0
if newBox
    regHi := useSw ? cHi : bTop
    regLo := useSw ? cLo : bBot
if upgrade
    regHi := cHi
    regLo := cLo
var bool regIsSw = false
if (newReg and regime == R_RANGE) or newBox
    boxStart := useSw ? cStart : nz(firstTouch, bar_index)
    regIsSw  := useSw
    if useSw
        cFrozen := true
// merge with the previous range if it ended recently and overlaps in price
bool mergedPrev = false
if mergeNb and newReg and regime == R_RANGE and not na(pRngHi) and not na(regHi) and bar_index - lastRangeEnd <= mergeGap and regLo < pRngHi and regHi > pRngLo
    float uHi = math.max(regHi, pRngHi)
    float uLo = math.min(regLo, pRngLo)
    if not na(atrRef) and uHi - uLo <= atrRef * hMaxSw
        regHi      := uHi
        regLo      := uLo
        boxStart   := pRngStart
        mergedPrev := true
if upgrade
    boxStart := cStart
    regIsSw  := true
    cFrozen  := true
int regLen = bar_index - regStart + 1
 
// ═══ 6. Shade inside the regime ══════════════════════════
int trendSub = dir == regime ? S_STRONG : S_PAUSE
if useHA and regime != R_RANGE
    bool haWith    = regime == R_UP ? haUp2 : haDn2
    bool haAgainst = regime == R_UP ? haOppUp2 : haOppDn2
    // HA can confirm strength any time; it can only force a pause after a 3-bar grace period (HA lags a new trend)
    trendSub := haWith ? S_STRONG : ((haAgainst or haIndecN) and regLen > 3) ? S_PAUSE : trendSub
int rawSub = regime == R_RANGE ? S_NORMAL : (formQ ? S_FORM : trendSub)
 
var int sub      = S_NORMAL
var int subCand  = S_NORMAL
var int subCount = 0
if newReg
    sub      := rawSub
    subCand  := rawSub
    subCount := 1
else
    if rawSub == subCand
        subCount += 1
    else
        subCand  := rawSub
        subCount := 1
    bool fastSwitch = (disp and subCand == S_STRONG) or subCand == S_FORM
    if subCand != sub and (subCount >= minBars or fastSwitch)
        sub := subCand
// a new break of structure in the trend's direction is strength by definition
if (regime == R_UP and bosUp) or (regime == R_DOWN and bosDn)
    sub      := S_STRONG
    subCand  := S_STRONG
    subCount := minBars
bool  newSub = not newReg and sub != sub[1]
color col    = f_col(regime, sub)
 
// ═══ 7. Ribbon pane ══════════════════════════════════════
int  chartSec = timeframe.in_seconds(timeframe.period)
bool okH1 = useH1 and timeframe.in_seconds(tfH1) > chartSec
bool okH2 = useH2 and timeframe.in_seconds(tfH2) > chartSec
bool okH3 = useH3 and timeframe.in_seconds(tfH3) > chartSec
 
// layout, bottom to top: HTF 3 dots, HTF 2 dots, HTF 1 dots, ribbon, tab names
float rowY0   = 0.2
float rowStep = 0.55
int   nRows   = (okH1 ? 1 : 0) + (okH2 ? 1 : 0) + (okH3 ? 1 : 0)
float tBot    = nRows == 0 ? 0.0 : rowY0 + rowStep * (nRows - 1) + 0.45
float tTop    = tBot + ribH
float yName   = tTop + 0.18
 
var box   sb = na
var label rl = na
if newReg
    sb := box.new(bar_index, tTop, bar_index, tBot, border_color = col, border_width = 1, bgcolor = col)
    rl := label.new(bar_index, yName, "", style = label.style_none, textcolor = chart.fg_color, size = size.tiny)
else if newSub
    sb := box.new(bar_index - 1, tTop, bar_index, tBot, border_color = col, border_width = 1, bgcolor = col)
else
    box.set_right(sb, bar_index)
 
label.set_x(rl, regStart + int(math.floor((bar_index - regStart) / 2)))
if regLen >= labelBars or (regime == R_RANGE and regLen >= 3)
    label.set_text(rl, f_tab(regime))
 
// higher-timeframe dot rows
[h1r, h1s] = request.security(syminfo.tickerid, tfH1, f_htf(), lookahead = barmerge.lookahead_on)
[h2r, h2s] = request.security(syminfo.tickerid, tfH2, f_htf(), lookahead = barmerge.lookahead_on)
[h3r, h3s] = request.security(syminfo.tickerid, tfH3, f_htf(), lookahead = barmerge.lookahead_on)
 
int htfN   = (okH1 and not na(h1r) ? 1 : 0) + (okH2 and not na(h2r) ? 1 : 0) + (okH3 and not na(h3r) ? 1 : 0)
int htfUp  = (okH1 and nz(h1r) == 1 ? 1 : 0) + (okH2 and nz(h2r) == 1 ? 1 : 0) + (okH3 and nz(h3r) == 1 ? 1 : 0)
int htfDn  = (okH1 and nz(h1r) == -1 ? 1 : 0) + (okH2 and nz(h2r) == -1 ? 1 : 0) + (okH3 and nz(h3r) == -1 ? 1 : 0)
int htfDir = htfUp > htfDn ? 1 : htfDn > htfUp ? -1 : 0
 
float yH3 = okH3 ? rowY0 : na
float yH2 = okH2 ? rowY0 + rowStep * (okH3 ? 1 : 0) : na
float yH1 = okH1 ? rowY0 + rowStep * ((okH3 ? 1 : 0) + (okH2 ? 1 : 0)) : na
 
plot(na(h1r) ? na : yH1, "HTF 1 phase", color = na(h1r) ? na : f_col(h1r, h1s), style = plot.style_circles, linewidth = dotSize, editable = false, display = display.pane)
plot(na(h2r) ? na : yH2, "HTF 2 phase", color = na(h2r) ? na : f_col(h2r, h2s), style = plot.style_circles, linewidth = dotSize, editable = false, display = display.pane)
plot(na(h3r) ? na : yH3, "HTF 3 phase", color = na(h3r) ? na : f_col(h3r, h3s), style = plot.style_circles, linewidth = dotSize, editable = false, display = display.pane)
 
// row names at the right edge
var label nmMain = label.new(0, 0.5, "", style = label.style_label_left, color = color.new(color.black, 100), textcolor = chart.fg_color, size = size.tiny)
var label nmH1   = label.new(0, 0.5, "", style = label.style_label_left, color = color.new(color.black, 100), textcolor = chart.fg_color, size = size.tiny)
var label nmH2   = label.new(0, 0.5, "", style = label.style_label_left, color = color.new(color.black, 100), textcolor = chart.fg_color, size = size.tiny)
var label nmH3   = label.new(0, 0.5, "", style = label.style_label_left, color = color.new(color.black, 100), textcolor = chart.fg_color, size = size.tiny)
if barstate.islast
    label.set_xy(nmMain, bar_index + 1, (tTop + tBot) / 2)
    label.set_text(nmMain, f_tfName(timeframe.period))
    label.set_xy(nmH1, bar_index + 1, nz(yH1, 0.5))
    label.set_text(nmH1, okH1 ? f_tfName(tfH1) : "")
    label.set_xy(nmH2, bar_index + 1, nz(yH2, 0.5))
    label.set_text(nmH2, okH2 ? f_tfName(tfH2) : "")
    label.set_xy(nmH3, bar_index + 1, nz(yH3, 0.5))
    label.set_text(nmH3, okH3 ? f_tfName(tfH3) : "")
 
// keep the pane tight: scale hugs the content
plot(yName + 0.12, "scale top", color = color.new(color.black, 100), editable = false, display = display.pane)
plot(nRows == 0 ? -0.08 : 0.0, "scale bottom", color = color.new(color.black, 100), editable = false, display = display.pane)
 
// ═══ 8. Ranges on the price chart ════════════════════════
var box  rBox  = na
var line rHi   = na
var line rLo   = na
var box  pBoxL = na
var line pHiL  = na
var line pLoL  = na
if newReg
    if not na(rHi) or not na(rBox)
        pHiL  := rHi
        pLoL  := rLo
        pBoxL := rBox
    rBox := na
    rHi  := na
    rLo  := na
if mergedPrev
    line.delete(pHiL)
    line.delete(pLoL)
    box.delete(pBoxL)
if upgrade
    box.delete(rBox)
    line.delete(rHi)
    line.delete(rLo)
    rBox := na
    rHi  := na
    rLo  := na
if showLines and regime == R_RANGE and not na(regHi) and (newReg or newBox or upgrade)
    if rngStyle == "Shaded box"
        rBox := box.new(boxStart, regHi, bar_index, regLo, border_color = color.new(cRange, 20), border_style = f_lnStyle(rngLnStyle), border_width = rngLnW, bgcolor = color.new(cRange, boxFill), force_overlay = true)
    else
        rHi := line.new(boxStart, regHi, bar_index, regHi, color = color.new(cRange, 10), style = f_lnStyle(rngLnStyle), width = rngLnW, force_overlay = true)
        rLo := line.new(boxStart, regLo, bar_index, regLo, color = color.new(cRange, 10), style = f_lnStyle(rngLnStyle), width = rngLnW, force_overlay = true)
else if regime == R_RANGE
    if not na(rBox)
        box.set_right(rBox, bar_index)
    if not na(rHi)
        line.set_x2(rHi, bar_index)
        line.set_x2(rLo, bar_index)
 
// "Range forming?" dotted lines (live; removed if it fails or becomes a Range)
var line fHi = na
var line fLo = na
if regime != R_RANGE and sub == S_FORM and showLines
    int fx = nz(firstTouch, bar_index - rngLook + 1)
    if na(fHi)
        fHi := line.new(fx, bTop, bar_index, bTop, color = color.new(cRange, 35), style = f_lnStyle(frmLnStyle), width = frmLnW, force_overlay = true)
        fLo := line.new(fx, bBot, bar_index, bBot, color = color.new(cRange, 35), style = f_lnStyle(frmLnStyle), width = frmLnW, force_overlay = true)
    else
        line.set_xy1(fHi, fx, bTop)
        line.set_xy2(fHi, bar_index, bTop)
        line.set_xy1(fLo, fx, bBot)
        line.set_xy2(fLo, bar_index, bBot)
else if not na(fHi)
    line.delete(fHi)
    line.delete(fLo)
    fHi := na
    fLo := na
 
// range stats for the tab-name tooltip
var int rotT  = 0
var int rotB  = 0
var int lastE = 0
if regime == R_RANGE and (newReg or newBox or upgrade)
    rotT  := regIsSw ? 0 : nTop
    rotB  := regIsSw ? 0 : nBot
    lastE := regIsSw ? 0 : lastEdge
else if regime == R_RANGE and not na(regHi)
    float tol2 = (regHi - regLo) * touchPct
    if high >= regHi - tol2 and lastE != 1
        rotT  += 1
        lastE := 1
    else if low <= regLo + tol2 and lastE != -1
        rotB  += 1
        lastE := -1
if regime == R_RANGE and regLen >= 3
    float boxAtr = not na(regHi) and nz(atrRef) > 0 ? (regHi - regLo) / atrRef : na
    string tip = na(regHi) ? "Range (no box mapped yet)" : (regIsSw ? "Swing range (dealing range)\n" : "Box range\n") + str.tostring(rotT + rotB) + " edge touches (" + str.tostring(rotT) + " top · " + str.tostring(rotB) + " bottom)\n" + str.tostring(bar_index - boxStart + 1) + " bars · " + str.tostring(boxAtr, "#.#") + " ATR tall"
    label.set_tooltip(rl, tip)
 
// ═══ 9. Narrator ═════════════════════════════════════════
tPos = switch narrPos
    "Top left"     => position.top_left
    "Bottom right" => position.bottom_right
    "Bottom left"  => position.bottom_left
    => position.top_right
tSize = switch narrSize
    "Tiny"   => size.tiny
    "Normal" => size.normal
    => size.small
 
var table narr = table.new(tPos, 1, 3, border_width = 0, force_overlay = true)
if showNarr and barstate.islast
    bool   aligned = regime != R_RANGE and sub != S_FORM and htfN > 0 and (regime == R_UP ? htfUp : htfDn) == htfN
    bool   counter = regime != R_RANGE and sub != S_FORM and htfDir == -regime
    string cue  = aligned ? "  ·  all timeframes agree" : counter ? "  ·  against the bigger trend" : ""
    string head = f_head(regime, sub) + cue
    string body = f_story(regime, sub)
    if counter
        body += regime == R_UP ? "\nCounter-trend: the bigger picture is still Down. Treat this as a bounce until it proves otherwise." : "\nCounter-trend: the bigger picture is still Up. Treat this as a pullback until it proves otherwise."
    table.cell(narr, 0, 0, head, text_color = headTxt, bgcolor = f_base(regime), text_size = tSize, text_halign = text.align_left)
    table.cell(narr, 0, 1, body, text_color = chart.fg_color, bgcolor = color.new(chart.bg_color, 10), text_size = tSize, text_halign = text.align_left)
    string htf = ""
    if okH1 and not na(h1r)
        htf += f_tfName(tfH1) + ": " + f_state(h1r, h1s)
    if okH2 and not na(h2r)
        htf += (htf == "" ? "" : "   ·   ") + f_tfName(tfH2) + ": " + f_state(h2r, h2s)
    if okH3 and not na(h3r)
        htf += (htf == "" ? "" : "   ·   ") + f_tfName(tfH3) + ": " + f_state(h3r, h3s)
    if htf != ""
        table.cell(narr, 0, 2, "Bigger picture → " + htf, text_color = chart.fg_color, bgcolor = color.new(chart.bg_color, 10), text_size = tSize, text_halign = text.align_left)
 
// ═══ Alerts ══════════════════════════════════════════════
alertcondition(newReg and bar_index > 0, "Phase change", "TS-Phases: market phase changed")
alertcondition(newReg and regime == R_UP, "Now Up", "TS-Phases: structure broke up with strength — Uptrend")
alertcondition(newReg and regime == R_DOWN, "Now Down", "TS-Phases: structure broke down with strength — Downtrend")
alertcondition(newReg and regime == R_RANGE, "Now Range", "TS-Phases: Range — wait for a strong breakout")
alertcondition(newSub and sub == S_FORM, "Range forming?", "TS-Phases: trend stalled, a range may be forming")

← 返回列表