Breakout Signals by Marat

Maratbwinnin · study · 598 行 · 点赞 10 · TradingView 原页

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

Pine Script

//@version=6
// Breakout Signals — Pine v6 port of the Hyperprop script v14.1
// Tuned on the NQ 1-minute chart. On tested history the rules did NOT hold up on the 2-minute chart.
//
// BOXES
//   Blue box, thick border  = tight range, ready (12+ candle bodies inside 1.5 x ATR50).
//   Blue box, thin border   = loose cluster (tall for ATR50, but only ~2.5 of its own candles tall). Levels only.
//   Green / red box         = the range gave a BUY / SELL call.
//   Grey outline            = the range broke against the fast trend. No call.
// CALLS
//   STRONG = close outside the range, fast and slow trend agree, inside trading hours.
//   weak   = fast trend only, or outside trading hours. Dark bubble. On tested history these lost money overall.
//   AMD    = the other side of the range was swept by a wick before the break. Tag only, not a grade.
// FOLLOWING
//   One call at a time. The stop starts at the middle of the range (6 to 20 pts away), then trails behind
//   the last N finished candles. The call ends on the stop, a session break, or a call the other way.
//
// Draws and alerts only. Places no orders.
indicator("Breakout Signals v20.3", shorttitle = "BRK v20.3", overlay = true, max_boxes_count = 500, max_lines_count = 100, max_labels_count = 500, max_bars_back = 500)
 
// ─── Inputs ────────────────────────────────────────────────────────────────
gR = "Range"
minBars    = input.int(13, "Candles needed", minval = 5, maxval = 100, group = gR)
maxATR     = input.float(1.5, "How tight (x ATR50, lower = tighter)", minval = 0.25, maxval = 10, step = 0.25, group = gR)
looseOn    = input.bool(true, "Also box loose clusters", group = gR)
looseK     = input.float(2.5, "Loose cluster: how tall, in its own candles", minval = 1, maxval = 6, step = 0.25, group = gR)
looseCalls = input.bool(false, "Loose clusters give weak calls", group = gR)
sweepK     = input.float(0.15, "Sweep: how far a wick must poke out (x range height)", minval = 0.05, maxval = 2, step = 0.05, group = gR)
 
gT = "Trend and hours"
fastLen  = input.int(20, "Fast trend line", minval = 2, inline = "f", group = gT)
fastType = input.string("EMA", "", options = ["EMA", "SMA", "WMA", "RMA", "HMA", "VWMA"], inline = "f", group = gT)
slowLen  = input.int(100, "Slow trend line", minval = 5, inline = "s", group = gT)
slowType = input.string("EMA", "", options = ["EMA", "SMA", "WMA", "RMA", "HMA", "VWMA"], inline = "s", group = gT)
showMAs  = input.bool(true, "Draw the two trend lines", group = gT)
htfOn    = input.bool(true, "Draw the higher-timeframe line", group = gT)
htfTf    = input.timeframe("15", "Higher timeframe", inline = "h", group = gT)
htfLen   = input.int(20, "", minval = 2, inline = "h", group = gT)
htfType  = input.string("EMA", "", options = ["EMA", "SMA", "WMA", "RMA", "HMA", "VWMA"], inline = "h", group = gT)
htfNeed  = input.bool(false, "Strong call needs price on the right side of the higher-timeframe line", group = gT)
useSlow  = input.bool(true, "Strong call needs slow trend", group = gT)
useHours = input.bool(true, "Strong call needs trading hours", group = gT)
actK     = input.float(0.8, "Strong call needs an active market (ATR vs its normal, 0 = off)", minval = 0, maxval = 3, step = 0.1, group = gT)
extMax   = input.float(0.75, "Strong call: not if the close is this far past the edge (x ATR, 0 = off)", minval = 0, maxval = 5, step = 0.25, group = gT)
hoursStr = input.session("0630-1400", "Day session", group = gT)
hoursTz  = input.string("America/Los_Angeles", "Time zone of those hours", group = gT)
showWeak = input.bool(true, "Take weak calls", group = gT)
 
gS = "Stop"
stopAt  = input.string("Middle of the range", "First stop sits at", options = ["Middle of the range", "Far side of the range"], group = gS)
stopMin = input.float(6, "First stop: closest (pts)", minval = 0.25, step = 0.25, group = gS)
stopMax = input.float(20, "First stop: farthest (pts)", minval = 0.25, step = 0.25, group = gS)
trailN  = input.int(3, "Trail the stop behind the last N candles", minval = 1, maxval = 50, group = gS)
 
gD = "Display"
compact    = input.bool(false, "Phone layout (compact: one status line, one stats line, no key)", group = gD)
showLive   = input.bool(true, "Show live calls before the candle closes", group = gD)
statusMode = input.string("On the chart", "Status line", options = ["On the chart", "Top bar", "Off"], group = gD)
showKey    = input.bool(true, "Show the key", group = gD)
showSess   = input.bool(true, "Mark the sessions", group = gD)
showDash   = input.bool(true, "Show the session dashboard", group = gD)
dashPos    = input.string("Top right", "Dashboard: corner", options = ["Top right", "Middle right", "Bottom right", "Top left"], group = gD)
dashPush   = input.float(8, "Dashboard: push down (% of chart height)", minval = 0, maxval = 60, step = 1, group = gD)
logCalls   = input.bool(true, "Write every call to Pine Logs (for the weekly review)", group = gD)
showStats  = input.bool(false, "Show results on loaded history", group = gD)
buyCol     = input.color(#22c55e, "Buy", group = gD)
sellCol    = input.color(#ef4444, "Sell", group = gD)
boxCol     = input.color(#3b82f6, "Range box", group = gD)
 
// ─── Helpers ───────────────────────────────────────────────────────────────
INK = #0b0e13
DARK = #1e293b
DIM = #94a3b8
GREY = #64748b
AMBER = #f59e0b
VIOLET = #c4b5fd
tick = syminfo.mintick
 
f_snap(float x, int d) =>
    d > 0 ? math.floor(x / tick + 1e-9) * tick : math.ceil(x / tick - 1e-9) * tick
f_px(float x) =>
    str.tostring(x, format.mintick)
f_pts(float x) =>
    (x >= 0 ? "+" : "-") + str.tostring(math.abs(x), "0.00")
// +1 up, -1 down, 0 unclear. An EMA "agrees" when price is on its side and it slopes that way.
f_side(float e, int back) =>
    s = e - e[back]
    p = close - e
    s > 0 and p > 0 ? 1 : s < 0 and p < 0 ? -1 : 0
 
top = math.max(open, close)
bot = math.min(open, close)
rng = high - low
atr50 = ta.atr(50)
// One moving-average function for every line the script uses, so what is drawn is exactly what grades the calls.
f_ma(float src, int len, string kind) =>
    switch kind
        "SMA" => ta.sma(src, len)
        "WMA" => ta.wma(src, len)
        "RMA" => ta.rma(src, len)
        "HMA" => ta.hma(src, math.max(2, len))
        "VWMA" => ta.vwma(src, len)
        => ta.ema(src, len)
fast = f_ma(close, fastLen, fastType)
slow = f_ma(close, slowLen, slowType)
// Higher-timeframe line from its last FINISHED candle, so it never repaints.
htfMa = request.security(syminfo.tickerid, htfTf, f_ma(close, htfLen, htfType)[1], lookahead = barmerge.lookahead_on)
htfSide = na(htfMa) ? 0 : close > htfMa ? 1 : close < htfMa ? -1 : 0
fSide = f_side(fast, 3)
sSide = f_side(slow, 10)
sessT = time(timeframe.period, hoursStr, hoursTz)
inHrs = not useHours or not na(sessT)
// A trading session runs from the 15:00 open to the 14:00 close (one hour of downtime between them).
// Inside it: overnight (open to day start) and the day session (the hours set above).
inDay = not na(sessT)
// Which market is open, by Pacific-style clock in the chosen time zone: Asia from the 15:00 open, London from midnight, New York = the day session.
minTz = hour(time, hoursTz) * 60 + minute(time, hoursTz)
sessName = inDay ? "NEW YORK" : minTz >= 14 * 60 ? "ASIA" : "LONDON"
newSess = bar_index == 0 or time - time[1] > timeframe.in_seconds() * 1000 * 5
dayStart = inDay and not inDay[1] and not newSess
dayEnd = not inDay and inDay[1] and not newSess
bgcolor(showSess and inDay ? color.new(AMBER, 95) : na, title = "Day session")
if showSess and (newSess or dayStart or dayEnd)
    mCol = dayStart ? AMBER : DIM
    line.new(bar_index, low, bar_index, high, extend = extend.both, color = color.new(mCol, 45), style = line.style_dashed)
    label.new(bar_index, high + 2.6 * nz(atr50, 10), newSess ? "OPEN" : dayStart ? "DAY SESSION" : "DAY END", style = label.style_label_center, color = #0f172a, textcolor = mCol, size = size.small)
gapMs = timeframe.in_seconds() * 1000 * 5
// Room between a candle and its bubble, so words never sit on the candles.
gapY = 0.9 * nz(atr50, 40 * tick)
hi30 = ta.highest(high, 30)
 
// Grade of a break in direction d on this candle: 2 strong, 1 weak, 0 none (against the fast trend).
f_grade(int d) =>
    fSide != d ? 0 : (not useSlow or sSide == d) and inHrs and (not htfNeed or htfSide == d) ? 2 : 1
f_takes(int g) =>
    g == 2 or (g == 1 and showWeak)
gUp = f_grade(1)
gDn = f_grade(-1)
atrNorm = ta.sma(atr50, 500)[1]
// Fakeout guard 1: the market has to be active before the break.
activeOK = actK <= 0 or na(atrNorm) or atr50 >= actK * atrNorm
 
// The previous `minBars` candles (not counting this one).
wHi  = ta.highest(top, minBars)[1]
wLo  = ta.lowest(bot, minBars)[1]
wH   = wHi - wLo
wAvg = ta.sma(rng, minBars)[1]
// The first candle must trade through the middle half, so the box does not start on the arriving candle.
wMid = top[minBars] >= wLo + 0.25 * wH and bot[minBars] <= wHi - 0.25 * wH
cumR = ta.cum(rng)
s0   = bar_index - minBars
 
// ─── State ─────────────────────────────────────────────────────────────────
var bool  inC = false
var int   tier = 0            // 1 tight, 2 loose
var float hi = na
var float lo = na
var int   st = 0
var float stCum = 0.0         // cumulative candle range just before the range started
var int   lastTight = -1
var int   lastAny = -1
var int   swUp = -1
var int   swDn = -1
var box   rb = na
 
var int   posDir = 0
var int   posBar = 0
var int   posGrade = 0
var float posEntry = na
var float posStop = na
var float posBest = na
var box   mb = na
 
var int   onN = 0
var int   onW = 0
var float onP = 0.0
var int   dyN = 0
var int   dyW = 0
var float dyP = 0.0
var bool  posDay = false
var int   nS = 0
var int   wS = 0
var float pS = 0.0
var int   nW = 0
var int   wW = 0
var float pW = 0.0
var int   nA = 0
var int   wA = 0
var float pA = 0.0
 
int   callDir = 0
int   callGrade = 0
bool  callAmd = false
float callStop = na
float callHi = na
float callLo = na
int   callLen = 0
float callExt = na
bool  newTight = false
bool  done = barstate.isconfirmed
float tcap = maxATR * atr50
 
// New session (first candle after the downtime): the dashboard starts again from zero.
if newSess
    onN := 0
    onW := 0
    onP := 0.0
    dyN := 0
    dyW := 0
    dyP := 0.0
 
// ─── Ranges and breaks (finished candles only) ─────────────────────────────
if done and not na(tcap) and not na(wH)
    // A tight range can start from nothing, or take over a loose one that has tightened up.
    if (not inC or tier == 2) and s0 > lastTight and wH <= tcap and wMid
        clipX = math.max(s0, lastAny + 1)
        if not inC
            swUp := -1
            swDn := -1
            rb := box.new(clipX, wHi, bar_index, wLo, border_color = boxCol, border_width = 2, bgcolor = color.new(boxCol, 80))
        else
            box.set_lefttop(rb, clipX, wHi)
            box.set_rightbottom(rb, bar_index, wLo)
            box.set_border_width(rb, 2)
            box.set_border_color(rb, boxCol)
            box.set_bgcolor(rb, color.new(boxCol, 80))
        inC := true
        tier := 1
        hi := wHi
        lo := wLo
        st := s0
        stCum := nz(cumR[minBars + 1])
        newTight := true
    if not inC and looseOn and s0 > lastAny and wH <= math.max(tcap, looseK * wAvg) and wMid
        inC := true
        tier := 2
        hi := wHi
        lo := wLo
        st := s0
        stCum := nz(cumR[minBars + 1])
        swUp := -1
        swDn := -1
        rb := box.new(s0, wHi, bar_index, wLo, border_color = color.new(boxCol, 40), border_width = 1, bgcolor = color.new(boxCol, 90))
 
    if inC
        if close > hi or close < lo
            d = close > hi ? 1 : -1
            g0raw = d > 0 ? gUp : gDn
            // Fakeout guard 2: a close stretched far past the edge is only a weak call.
            ext = d * (close - (d > 0 ? hi : lo)) / atr50
            g0 = g0raw == 2 and (not activeOK or (extMax > 0 and ext > extMax)) ? 1 : g0raw
            g = tier == 1 ? g0 : looseCalls and g0 > 0 ? 1 : 0
            sweepBar = d > 0 ? swDn : swUp
            inC := false
            lastAny := bar_index
            if tier == 1
                lastTight := bar_index
            box.set_right(rb, bar_index)
            box.set_border_width(rb, 1)
            if f_takes(g)
                col = d > 0 ? buyCol : sellCol
                box.set_border_color(rb, col)
                box.set_bgcolor(rb, color.new(col, 75))
            else if tier == 2
                box.set_border_color(rb, color.new(boxCol, 55))
                box.set_bgcolor(rb, color.new(boxCol, 93))
            else
                box.set_border_color(rb, color.new(GREY, 30))
                box.set_bgcolor(rb, color(na))
            if f_takes(g)
                // Back at the middle of the box = the breakout failed. That is where the first stop sits.
                far = stopAt == "Far side of the range" ? (d > 0 ? lo : hi) - d * tick : (hi + lo) / 2
                r = math.min(stopMax, math.max(stopMin, d * (close - far)))
                callDir := d
                callGrade := g
                // AMD: range (accumulation), other side swept by a wick (manipulation), then this break (distribution).
                callAmd := sweepBar >= 0
                callStop := f_snap(close - d * r, d)
                callHi := hi
                callLo := lo
                callLen := bar_index - st
                callExt := ext
                if callAmd
                    label.new(sweepBar, d > 0 ? low[bar_index - sweepBar] - gapY : high[bar_index - sweepBar] + gapY, "SWEEP", style = label.style_label_center, color = DARK, textcolor = VIOLET, size = size.small)
        else
            // Sweep: a wick pokes out past the box and the candle still closes back inside.
            if high - hi >= sweepK * (hi - lo)
                swUp := bar_index
            if lo - low >= sweepK * (hi - lo)
                swDn := bar_index
            cap = tier == 1 ? tcap : math.max(tcap, looseK * (cumR - stCum) / (bar_index + 1 - st))
            nh = math.max(hi, top)
            nl = math.min(lo, bot)
            if nh - nl <= cap
                hi := nh
                lo := nl
            box.set_top(rb, hi)
            box.set_bottom(rb, lo)
            box.set_right(rb, bar_index)
 
// ─── Follow the open call (finished candles only) ──────────────────────────
float exitPts = na
float exitPx = na
float stopAtExit = na
// The stop is checked on every tick, so a hit shows the moment price touches it. Only the trail waits for the close.
if posDir != 0 and bar_index > posBar
    d = posDir
    isGap = time - time[1] > gapMs
    isHit = d > 0 ? low <= posStop : high >= posStop
    isFlip = callDir != 0 and callDir != d
    if isGap or isHit or isFlip
        px = isGap ? close[1] : isHit ? (d > 0 ? math.min(open, posStop) : math.max(open, posStop)) : close
        exitPts := d * (px - posEntry)
        exitPx := px
        stopAtExit := posStop
        won = exitPts > 0
        // One line per finished call. Written once, when the candle closes.
        if logCalls and done
            log.info("EXIT," + str.format_time(time, "yyyy-MM-dd HH:mm", hoursTz) + "," + (d > 0 ? "BUY" : "SELL") + "," + str.tostring(exitPts, "0.00") + "," + (isGap ? "session" : isHit ? "stop" : "flip") + "," + str.tostring(bar_index - posBar) + "," + f_px(px))
        if posDay
            dyN += 1
            dyW += won ? 1 : 0
            dyP += exitPts
        else
            onN += 1
            onW += won ? 1 : 0
            onP += exitPts
        label.new(isGap ? bar_index - 1 : bar_index, d > 0 ? high[isGap ? 1 : 0] + gapY : low[isGap ? 1 : 0] - gapY, f_pts(exitPts), style = label.style_label_center, color = won ? buyCol : exitPts < 0 ? sellCol : GREY, textcolor = won ? INK : color.white, size = size.small)
        box.set_right(mb, isGap ? bar_index - 1 : bar_index)
        if posGrade == 2
            nS += 1
            wS += won ? 1 : 0
            pS += exitPts
        else
            nW += 1
            wW += won ? 1 : 0
            pW += exitPts
        posDir := 0
    else if done
        posBest := d > 0 ? math.max(posBest, high) : math.min(posBest, low)
        box.set_right(mb, bar_index)
        if d > 0
            box.set_top(mb, posBest)
        else
            box.set_bottom(mb, posBest)
        // Stop steps along behind the last N finished candles, and only ever in the call's favour.
        k = math.min(trailN, bar_index - posBar + 1)
        float ext = d > 0 ? low : high
        for z = 0 to k - 1
            ext := d > 0 ? math.min(ext, low[z]) : math.max(ext, high[z])
        ns = f_snap(ext - d * tick, d)
        if d * (ns - posStop) > 0
            posStop := ns
 
var bool posAmd = false
if not na(exitPts) and posAmd
    nA += 1
    wA += exitPts > 0 ? 1 : 0
    pA += exitPts
 
if done and posDir == 0 and callDir != 0
    posDir := callDir
    posBar := bar_index
    posDay := inDay
    if logCalls
        // CALL,time,side,grade,amd,entry,stop,rangeLow,rangeHigh,candles,atr,atrVsNormal,closePastEdge,fastSide,slowSide,session,timeframe
        log.info("CALL," + str.format_time(time, "yyyy-MM-dd HH:mm", hoursTz) + "," + (callDir > 0 ? "BUY" : "SELL") + "," + (callGrade == 2 ? "strong" : "weak") + "," + (callAmd ? "AMD" : "-") + "," + f_px(close) + "," + f_px(callStop) + "," + f_px(callLo) + "," + f_px(callHi) + "," + str.tostring(callLen) + "," + str.tostring(atr50, "0.0") + "," + str.tostring(atr50 / nz(atrNorm, atr50), "0.00") + "," + str.tostring(callExt, "0.00") + "," + str.tostring(fSide) + "," + str.tostring(sSide) + "," + (inDay ? "day" : "overnight") + "," + timeframe.period)
    posGrade := callGrade
    posAmd := callAmd
    posEntry := close
    posStop := callStop
    posBest := close
    col = callDir > 0 ? buyCol : sellCol
    mb := box.new(bar_index, close, bar_index, close, border_width = 0, bgcolor = color.new(col, 80))
    txt = (callDir > 0 ? "BUY" : "SELL") + (callAmd ? " · AMD" : "")
    // bright bubble = strong, dark bubble with colored text = weak
    label.new(bar_index, callDir > 0 ? low - gapY : high + gapY, txt, style = label.style_label_center, color = callGrade == 2 ? col : DARK, textcolor = callGrade == 2 ? (callDir > 0 ? INK : color.white) : col, size = size.normal)
 
plot(showMAs ? fast : na, "Fast trend line", color = #f59e0b, linewidth = 1)
plot(showMAs ? slow : na, "Slow trend line", color = #38bdf8, linewidth = 2)
plot(htfOn and not compact ? htfMa : na, "Higher-timeframe line", color = #a78bfa, linewidth = 2, style = plot.style_stepline)
 
// Trailing stop as a staircase. Amber once it locks in profit.
locked = posDir != 0 ? posDir * (posStop - posEntry) : na
// The stop line runs through the candle that hit it, and a cross marks the exact fill price.
plot(posDir != 0 ? posStop : stopAtExit, "Trailing stop", color = locked > 0 ? AMBER : sellCol, linewidth = 2, style = plot.style_steplinebr)
plot(exitPx, "Exit fill", color = color.new(#0f172a, 0), style = plot.style_cross, linewidth = 4)
plot(posDir != 0 ? posEntry : na, "Entry", color = color.new(#e2e8f0, 40), style = plot.style_circles, linewidth = 1)
 
// ─── Live edge: levels, LIVE call, forming range, status ───────────────────
var label tagTop = na
var label tagBot = na
var label tagStop = na
var label liveLb = na
var line  lnTop = na
var line  lnBot = na
var box   formBox = na
var label st1 = na
var label st2 = na
var table keyT = table.new(position.bottom_left, 2, 6, bgcolor = color.new(#0f172a, 8), border_color = color.new(color.white, 90), border_width = 1)
var table dashC = table.new(position.bottom_left, 1, 1, bgcolor = color.new(#0f172a, 8), border_color = color.new(color.white, 90), border_width = 1)
DASHBG = color.new(#0f172a, 8)
var table dash = table.new(dashPos == "Top left" ? position.top_left : dashPos == "Middle right" ? position.middle_right : dashPos == "Bottom right" ? position.bottom_right : position.top_right, 4, 7, bgcolor = color(na), border_width = 0)
var table stat = table.new(position.top_center, 3, 1, bgcolor = color.new(#0f172a, 8), border_color = color.new(color.white, 90), border_width = 1)
var table res = table.new(position.bottom_right, 4, 3, bgcolor = color.new(#0f172a, 8), border_color = color.new(color.white, 90), border_width = 1)
 
f_scan(bool useLoose) =>
    float mx = na
    float mn = na
    float fh = na
    float fl = na
    float sum = 0.0
    int L = 0
    for j = 0 to minBars - 1
        if bar_index - j <= lastAny
            break
        mx := na(mx) ? top[j] : math.max(mx, top[j])
        mn := na(mn) ? bot[j] : math.min(mn, bot[j])
        sum += rng[j]
        c = useLoose ? math.max(tcap, looseK * sum / (j + 1)) : tcap
        if mx - mn > c
            break
        L += 1
        fh := mx
        fl := mn
    [L, fh, fl]
 
if barstate.islast
    label.delete(tagTop)
    label.delete(tagBot)
    label.delete(tagStop)
    label.delete(liveLb)
    line.delete(lnTop)
    line.delete(lnBot)
    box.delete(formBox)
    label.delete(st1)
    label.delete(st2)
    string status = "Waiting for a range"
    endX = bar_index + 12
 
    if inC
        loose = tier == 2
        status := loose ? "Loose range " + f_px(lo) + " to " + f_px(hi) + " · no call" : "Range ready · no call until the trend is clear"
        // Top of the range
        gT1 = tier == 1 ? gUp : looseCalls and gUp > 0 ? 1 : 0
        gB1 = tier == 1 ? gDn : looseCalls and gDn > 0 ? 1 : 0
        if posDir != 1
            if f_takes(gT1)
                lnTop := line.new(bar_index, hi, endX, hi, color = buyCol, width = 2, style = line.style_dashed)
                tagTop := label.new(endX, hi, "BUY above " + f_px(hi) + (posDir != 0 ? " · flips" : ""), style = label.style_label_left, color = gT1 == 2 ? buyCol : DARK, textcolor = gT1 == 2 ? INK : buyCol, size = size.small)
                status := (loose ? "Loose range" : "Range ready") + " · BUY on a close above " + f_px(hi) + (gT1 == 1 ? " (weak)" : "")
            else
                lnTop := line.new(bar_index, hi, endX, hi, color = loose ? color.new(boxCol, 10) : GREY, width = 1, style = line.style_dashed)
                tagTop := label.new(endX, hi, loose and not looseCalls ? "Loose range top " + f_px(hi) : "Top " + f_px(hi) + " · no buy", style = label.style_label_left, color = DARK, textcolor = loose ? #93c5fd : DIM, size = size.small)
        if posDir != -1
            if f_takes(gB1)
                lnBot := line.new(bar_index, lo, endX, lo, color = sellCol, width = 2, style = line.style_dashed)
                tagBot := label.new(endX, lo, "SELL below " + f_px(lo) + (posDir != 0 ? " · flips" : ""), style = label.style_label_left, color = gB1 == 2 ? sellCol : DARK, textcolor = gB1 == 2 ? color.white : sellCol, size = size.small)
                status := (loose ? "Loose range" : "Range ready") + " · SELL on a close below " + f_px(lo) + (gB1 == 1 ? " (weak)" : "")
            else
                lnBot := line.new(bar_index, lo, endX, lo, color = loose ? color.new(boxCol, 10) : GREY, width = 1, style = line.style_dashed)
                tagBot := label.new(endX, lo, loose and not looseCalls ? "Loose range bottom " + f_px(lo) : "Bottom " + f_px(lo) + " · no sell", style = label.style_label_left, color = DARK, textcolor = loose ? #93c5fd : DIM, size = size.small)
        if swDn >= 0 and f_takes(gT1)
            status += " · low swept (AMD setup)"
        if swUp >= 0 and f_takes(gB1)
            status += " · high swept (AMD setup)"
        // LIVE: the candle that is still forming is outside the range. Not final until it closes.
        pend = close > hi ? 1 : close < lo ? -1 : 0
        gP = pend > 0 ? gT1 : pend < 0 ? gB1 : 0
        // Live motion: redraws on every tick. `beat` flips twice a second; the clock counts down to the candle close.
        beat = int(timenow / 500) % 2 == 0
        leftS = math.max(0, int((time_close - timenow) / 1000))
        clock = not done and leftS < 3600 ? " · " + str.tostring(int(leftS / 60)) + ":" + str.tostring(leftS % 60, "00") : ""
        press = pend == 0 and not loose ? (f_takes(gT1) and hi - close <= 0.25 * atr50 ? 1 : f_takes(gB1) and close - lo <= 0.25 * atr50 ? -1 : 0) : 0
        hotDir = pend != 0 and f_takes(gP) ? pend : press
        if hotDir != 0 and not done
            hotCol = hotDir > 0 ? buyCol : sellCol
            box.set_border_color(rb, hotCol)
            box.set_border_width(rb, beat ? 3 : 2)
            box.set_bgcolor(rb, color.new(hotCol, beat ? 70 : 80))
        else if not loose
            box.set_border_color(rb, boxCol)
            box.set_border_width(rb, 2)
            box.set_bgcolor(rb, color.new(boxCol, 80))
        if press != 0 and not done and posDir != press
            liveLb := label.new(bar_index, text = (press > 0 ? "BUY" : "SELL") + " getting close", y = press > 0 ? low - gapY : high + gapY, style = label.style_label_center, color = DARK, textcolor = beat ? (press > 0 ? buyCol : sellCol) : DIM, size = size.small)
            status := "Pressing the " + (press > 0 ? "top" : "bottom") + " · " + (press > 0 ? "BUY on a close above " + f_px(hi) : "SELL on a close below " + f_px(lo)) + clock
        if not done and showLive and pend != 0 and f_takes(gP) and posDir != pend
            liveLb := label.new(bar_index, pend > 0 ? low - gapY : high + gapY, (pend > 0 ? "BUY" : "SELL") + " · LIVE" + clock, style = label.style_label_center, color = beat ? AMBER : #fcd34d, textcolor = INK)
            status := "LIVE " + (pend > 0 ? "BUY" : "SELL") + " · needs a close " + (pend > 0 ? "above " + f_px(hi) : "below " + f_px(lo))
    else if not na(tcap)
        [lt, fht, flt] = f_scan(false)
        int L = lt
        float fh = fht
        float fl = flt
        bool looseF = false
        if L < 4 and looseOn
            [l2, fh2, fl2] = f_scan(true)
            if l2 >= math.ceil(minBars * 0.66)
                L := l2
                fh := fh2
                fl := fl2
                looseF := true
        if L >= 4
            formBox := box.new(bar_index - L + 1, fh, bar_index, fl, border_color = color.new(boxCol, looseF ? 40 : 10), border_style = line.style_dotted, border_width = 1, bgcolor = color.new(boxCol, looseF ? 94 : 88))
            status := looseF ? "Loose range forming" : "Range forming"
 
    if posDir != 0
        lk = posDir * (posStop - posEntry)
        tagStop := label.new(endX, posStop, "STOP " + f_px(posStop) + (lk > 0 ? " · locks " + f_pts(lk) : ""), style = label.style_label_left, color = lk > 0 ? AMBER : sellCol, textcolor = lk > 0 ? INK : color.white, size = size.small)
        if not str.startswith(status, "LIVE")
            status := "Riding a " + (posGrade == 2 ? "" : "weak ") + (posDir > 0 ? "BUY" : "SELL") + " from " + f_px(posEntry) + " · now " + f_pts(posDir * (close - posEntry)) + " · stop " + f_px(posStop)
 
    both = fSide != 0 and (not useSlow or sSide == fSide)
    tr = both ? (fSide > 0 ? "▲ UPTREND" : "▼ DOWNTREND") : fSide != 0 ? (fSide > 0 ? "▲ weak uptrend" : "▼ weak downtrend") : "NO CLEAR TREND"
    trCol = both ? (fSide > 0 ? buyCol : sellCol) : DIM
    if statusMode == "Top bar"
        table.cell(stat, 0, 0, tr, text_color = trCol, text_size = size.small)
        table.cell(stat, 1, 0, status, text_color = #e2e8f0, text_size = size.small)
        table.cell(stat, 2, 0, sessName + (inHrs ? "" : " · weak calls only"), text_color = AMBER, text_size = size.small)
    else if statusMode == "On the chart"
        // Two bubbles stacked in clear space above the latest candles, same as the Hyperprop version.
        topY = math.max(hi30, inC ? hi : high)
        aY = nz(atr50, 40 * tick)
        if compact
            st2 := label.new(bar_index - 4, topY + 2.0 * aY, (fSide > 0 ? "▲ " : fSide < 0 ? "▼ " : "") + status, style = label.style_label_center, color = #0f172a, textcolor = #e2e8f0, size = size.small)
        else
            st1 := label.new(bar_index - 6, topY + 3.4 * aY, tr + " · " + sessName + (inHrs ? "" : " · weak calls only"), style = label.style_label_center, color = #0f172a, textcolor = trCol, size = size.normal)
            st2 := label.new(bar_index - 6, topY + 2.0 * aY, status, style = label.style_label_center, color = #0f172a, textcolor = #e2e8f0, size = size.normal)
    if showDash and compact
        // Phone: the whole dashboard in one line, bottom-left, clear of the chart header.
        cN = onN + dyN
        cP = onP + dyP
        table.cell(dashC, 0, 0, sessName + "  " + str.tostring(cN) + " calls  " + (cN > 0 ? str.tostring(math.round(100.0 * (onW + dyW) / cN)) + "%  " + f_pts(cP) : "") + "   " + htfTf + "m " + (htfSide > 0 ? "▲" : htfSide < 0 ? "▼" : "-"), text_color = cP > 0 ? buyCol : cP < 0 ? sellCol : #e2e8f0, text_size = size.small)
    if showDash and not compact
        // Invisible spacer row: pushes the dashboard down, clear of the chart's own header and buttons.
        table.cell(dash, 0, 0, "", height = dashPush, bgcolor = color(na))
        // Tiny dashboard: this session only (since the last open), split overnight / day.
        table.cell(dash, 0, 1, sessName, text_color = inDay ? AMBER : DIM, text_size = size.small, text_halign = text.align_left, bgcolor = DASHBG)
        table.cell(dash, 1, 1, "calls", text_color = GREY, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 2, 1, "won", text_color = GREY, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 3, 1, "pts", text_color = GREY, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 0, 2, "Overnight", text_color = DIM, text_size = size.small, text_halign = text.align_left, bgcolor = DASHBG)
        table.cell(dash, 1, 2, str.tostring(onN), text_color = #e2e8f0, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 2, 2, onN > 0 ? str.tostring(math.round(100.0 * onW / onN)) + "%" : "-", text_color = #e2e8f0, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 3, 2, onN > 0 ? f_pts(onP) : "-", text_color = onP > 0 ? buyCol : onP < 0 ? sellCol : DIM, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 0, 3, "Day", text_color = DIM, text_size = size.small, text_halign = text.align_left, bgcolor = DASHBG)
        table.cell(dash, 1, 3, str.tostring(dyN), text_color = #e2e8f0, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 2, 3, dyN > 0 ? str.tostring(math.round(100.0 * dyW / dyN)) + "%" : "-", text_color = #e2e8f0, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 3, 3, dyN > 0 ? f_pts(dyP) : "-", text_color = dyP > 0 ? buyCol : dyP < 0 ? sellCol : DIM, text_size = size.small, bgcolor = DASHBG)
        allN = onN + dyN
        allP = onP + dyP
        table.cell(dash, 0, 4, "Session", text_color = DIM, text_size = size.small, text_halign = text.align_left, bgcolor = DASHBG)
        table.cell(dash, 1, 4, str.tostring(allN), text_color = #e2e8f0, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 2, 4, allN > 0 ? str.tostring(math.round(100.0 * (onW + dyW) / allN)) + "%" : "-", text_color = #e2e8f0, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 3, 4, allN > 0 ? f_pts(allP) : "-", text_color = allP > 0 ? buyCol : allP < 0 ? sellCol : DIM, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 0, 6, str.tostring(htfTf) + "m trend", text_color = DIM, text_size = size.small, text_halign = text.align_left, bgcolor = DASHBG)
        table.cell(dash, 1, 6, htfSide > 0 ? "▲ up" : htfSide < 0 ? "▼ down" : "-", text_color = htfSide > 0 ? buyCol : htfSide < 0 ? sellCol : DIM, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 0, 5, posDir != 0 ? "Open now" : "", text_color = DIM, text_size = size.small, text_halign = text.align_left, bgcolor = DASHBG)
        table.cell(dash, 1, 5, posDir > 0 ? "BUY" : posDir < 0 ? "SELL" : "", text_color = posDir > 0 ? buyCol : sellCol, text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 2, 5, "", text_size = size.small, bgcolor = DASHBG)
        table.cell(dash, 3, 5, posDir != 0 ? f_pts(posDir * (close - posEntry)) : "", text_color = #e2e8f0, text_size = size.small, bgcolor = DASHBG)
    if showKey and not compact
        table.cell(keyT, 0, 0, "Blue box", text_color = boxCol, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 1, 0, "range forming / ready", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 0, 1, "Faint blue box", text_color = color.new(boxCol, 25), text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 1, 1, "loose cluster: levels only", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 0, 2, "BUY / SELL", text_color = #e2e8f0, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 1, 2, "bright = strong call, dark = weak call", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 0, 3, "Shaded zone + steps", text_color = #e2e8f0, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 1, 3, "the move being followed and its stop", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 0, 4, "SWEEP / AMD", text_color = VIOLET, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 1, 4, "wick faked one side, break went the other", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 0, 5, "+ / - number", text_color = #e2e8f0, text_size = size.small, text_halign = text.align_left)
        table.cell(keyT, 1, 5, "points when the call ended", text_color = #cbd5e1, text_size = size.small, text_halign = text.align_left)
    if showStats and not compact
        table.cell(res, 0, 0, "Strong", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 1, 0, str.tostring(nS) + " calls", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 2, 0, str.tostring(nS > 0 ? math.round(100.0 * wS / nS) : 0) + "% won", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 3, 0, f_pts(pS) + " pts", text_color = pS >= 0 ? buyCol : sellCol, text_size = size.small)
        table.cell(res, 0, 1, "Weak", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 1, 1, str.tostring(nW) + " calls", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 2, 1, str.tostring(nW > 0 ? math.round(100.0 * wW / nW) : 0) + "% won", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 3, 1, f_pts(pW) + " pts", text_color = pW >= 0 ? buyCol : sellCol, text_size = size.small)
        table.cell(res, 0, 2, "AMD (any)", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 1, 2, str.tostring(nA) + " calls", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 2, 2, str.tostring(nA > 0 ? math.round(100.0 * wA / nA) : 0) + "% won", text_color = #cbd5e1, text_size = size.small)
        table.cell(res, 3, 2, f_pts(pA) + " pts", text_color = pA >= 0 ? buyCol : sellCol, text_size = size.small)
 
// ─── Alerts (the Hyperprop version cannot do this) ─────────────────────────
alertcondition(callDir == 1 and callGrade == 2, "Strong BUY", "Strong BUY: closed above the range")
alertcondition(callDir == -1 and callGrade == 2, "Strong SELL", "Strong SELL: closed below the range")
alertcondition(callDir != 0 and callGrade == 1, "Weak call", "Weak call: closed outside the range")
alertcondition(callDir != 0 and callAmd, "AMD call", "Call after a sweep of the other side")
alertcondition(newTight, "Range ready", "A tight range is ready")
// Early warning: fires while the candle is still forming. Set this alert to "Once Per Bar", not "Once Per Bar Close".
alertcondition(inC and tier == 1 and ((close > hi and f_takes(gUp)) or (close < lo and f_takes(gDn))), "LIVE (early, not confirmed)", "Price is outside the range right now. Not final until the candle closes.")
alertcondition(not na(exitPts), "Call ended", "The open call ended")

← 返回列表