Jilly's Noise Band

jillyhatt · study · 583 行 · 点赞 134 · TradingView 原页

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

Pine Script

//@version=6
// ─────────────────────────────────────────────────────────────────────────────
//  Jilly's Noise Band
//
//  Intraday breakout indicator built on a time-of-day-adaptive "noise band"
//  around the session open. Price closing outside the band at a checkpoint
//  signals a move larger than the usual noise for that time of day.
//
//  Defaults: N = 14, k = 1.0, 30-min checkpoints, open-anchored reference,
//  band + VWAP trailing stop, RTH 09:30–16:00 ET, flat at the 15:59 bar open.
//  Built for index futures (e.g. MNQ / NQ) on a 1-minute chart.
//
//  Band
//    move(t)  = |close at t / 09:30 open − 1|, t = minutes since 09:30 at the bar close
//    σ(t)     = mean of move(t) over the prior N RTH sessions (today excluded)
//    Upper    = ref × (1 + k·σ(t))     Lower = ref × (1 − k·σ(t))
//    ref      = 09:30 open (or max/min of open and prior RTH close when
//               Reference = Gap-adjusted)
//    VWAP     = session VWAP of hlc3 anchored at 09:30
//
//  Signals – evaluated only at checkpoints (bar closes at 09:30 + cadence·j)
//    Exit    long if close < stop, short if close > stop
//            stop: long max(Upper, VWAP), short min(Lower, VWAP)  (Band + VWAP)
//    Entry   when flat: LONG if close > Upper and close ≥ long stop,
//            SHORT if close < Lower and close ≤ short stop. A stop-out straight
//            into the opposite signal is a reversal.
//    Fills   at the OPEN OF THE NEXT BAR. Markers are drawn on that fill bar.
//    Flat    at the open of the bar containing 15:59 (exact on a 1-minute chart).
//
//  Stop = Fixed (entry price) – replaces the trailing stop
//    stop    long: entry − m × dev, short: entry + m × dev, set once at the fill
//            and rounded to the tick
//            dev = band half-width at the signal (Upper − ref for longs,
//            ref − Lower for shorts), m = "Fixed stop × band deviation"
//    Exit    resting stop checked on every bar: fills at the stop, or at the bar
//            open if it opens through the stop (marker "SL"); a reversal at a
//            checkpoint; or the 15:59 flat. No trailing exit.
//    Entry   same rule as Band + VWAP (close beyond the band and beyond VWAP).
//    Boxes   red = entry → stop; green = entry → current price while in profit
//            (there is no take-profit). Projected "Box projection" bars ahead
//            while open, trimmed at the exit bar, and stamped with the trade's
//            net $ at the outer edge of the box the exit landed in.
//
//  Daily P&L: each session's summed net $ of closed trades, centred at 12:45 on
//  the 09:30-open center line — under it when VWAP finished above the open
//  (VWAP up), above it when VWAP finished below; green if positive, red if
//  negative, same text size as the per-trade box stamps.
//
//  Performance table: trades, win %, PF, net P&L, max DD, buy-and-hold P&L /
//  max DD from the first trade, first trade time. Net of the "Round-trip cost
//  per contract" input for "Contracts". Hypothetical results from the
//  indicator's modeled fills over the loaded chart history.
//
//  Chart: a 1-minute chart gives exact checkpoint and 15:59 timing. Any chart
//  whose minutes divide the cadence works; the 15:59 flat then moves to the
//  open of the bar that contains 15:59. σ needs N completed sessions of chart
//  history before the first signal.
//
//  Notes: half-days are included in σ, and an open position is flattened at
//  the last bar of a session that ends early. The Gap-adjusted reference uses
//  the prior session's close as charted, so on a continuous contract it is
//  affected by roll gaps unless back-adjustment is enabled.
//
//  For research and educational use only. Not financial advice. Simulated
//  results do not guarantee future performance.
// ─────────────────────────────────────────────────────────────────────────────
indicator("Jilly's Noise Band", shorttitle = "Noise Band", overlay = true, max_labels_count = 500, max_boxes_count = 500)
 
// ── Inputs ───────────────────────────────────────────────────────────────────
grpB     = "Band"
N        = input.int(14, "Lookback N (sessions)", minval = 2, maxval = 60, group = grpB)
k        = input.float(1.0, "Band multiplier k", minval = 0.1, step = 0.05, group = grpB)
refMode  = input.string("Open", "Reference", options = ["Open", "Gap-adjusted"], group = grpB)
 
grpT     = "Trading"
cadence  = input.int(30, "Checkpoint cadence (min)", options = [5, 15, 30, 60], group = grpT)
exitMode = input.string("Band + VWAP", "Stop", options = ["Band + VWAP", "Band", "VWAP", "Fixed (entry price)"], group = grpT,
                        tooltip = "Band + VWAP / Band / VWAP: trailing stop checked at checkpoints (Band + VWAP is the default). Fixed (entry price): resting stop at entry ∓ multiple × band deviation, set once at the fill.")
fixedMult = input.float(0.5, "Fixed stop × band deviation", minval = 0.1, step = 0.1, group = grpT,
                        tooltip = "Only used when Stop = Fixed (entry price). Deviation = band half-width at the signal.")
 
grpS     = "Session"
sess     = input.session("0930-1600", "RTH session", group = grpS)
tz       = input.string("America/New_York", "Timezone", group = grpS)
 
grpD     = "Display"
showSig  = input.bool(true, "Entry / exit markers", group = grpD)
showStop = input.bool(true, "Active stop", group = grpD)
showTradeBoxes = input.bool(true, "Show SL/TP boxes", group = grpD,
     tooltip = "Fixed stop only. Red box = entry to stop; green box = entry to current price while the trade is in profit (this strategy has no take-profit). Projected ahead while the trade is open, trimmed at exit, and stamped with the trade's $ P&L.")
boxLead  = input.int(5, "Box projection (bars ahead)", minval = 0, group = grpD)
showDaily = input.bool(true, "Daily P&L on the center line", group = grpD,
     tooltip = "At the end of each session: the day's summed net $ of closed trades, placed on the 09:30-open center line — under it when VWAP finished above the open, above it when VWAP finished below. Green if positive, red if negative.")
showStats = input.bool(true, "Show performance table", group = grpD,
     tooltip = "Closed-trade stats over this chart's history: fills at the modeled prices (next-bar open, stop price, 15:59 open), net of the round-trip cost below. Hypothetical and indicative only.")
statsPos = input.string("Bottom Right", "Table position", options = ["Top Left", "Top Right", "Top Center", "Middle Left", "Middle Right", "Bottom Left", "Bottom Right", "Bottom Center"], group = grpD)
qty      = input.int(1, "Contracts (table / box $)", minval = 1, group = grpD)
rtCost   = input.float(1.80, "Round-trip cost per contract ($)", minval = 0, step = 0.1, group = grpD,
     tooltip = "Default $1.80 = $0.40/side commission + 1 tick ($0.50) slippage per side on MNQ. Set this to your own costs.")
showVwap = input.bool(true, "Session VWAP", group = grpD)
showOpen = input.bool(true, "Reference (open) line", group = grpD)
showCk   = input.bool(false, "Checkpoint dots", group = grpD)
showBg   = input.bool(true, "Shade time in position", group = grpD)
showTbl  = input.bool(false, "Status table (position, bands, stop)", group = grpD)
cBand    = input.color(#2a78d6, "Band", group = grpD)
cVwap    = input.color(#eb6834, "VWAP", group = grpD)
 
// ── Constants ────────────────────────────────────────────────────────────────
RTH_MIN  = 390              // 09:30–16:00
FLAT_KEY = RTH_MIN - 1      // forced flat at the open of the 15:59 bar
isFixed  = exitMode == "Fixed (entry price)"
// the entry rule (and the trailing stop when not fixed); fixed mode keeps the default Band + VWAP entry rule
trailMode = isFixed ? "Band + VWAP" : exitMode
// SL/TP box colours
cRisk    = color.new(color.red, 85)
cRiskB   = color.new(color.red, 50)
cProfit  = color.new(color.green, 85)
cProfitB = color.new(color.green, 50)
 
if barstate.isfirst and (not timeframe.isminutes or cadence % timeframe.multiplier != 0)
    runtime.error("Noise Band: use a minute chart whose interval divides the checkpoint cadence (1-minute recommended).")
 
// ── State ────────────────────────────────────────────────────────────────────
inRTH   = not na(time(timeframe.period, sess, tz))
newSess = inRTH and not inRTH[1]
endedEarly = inRTH[1] and not inRTH          // first bar after an RTH session
 
var matrix<float> mv = matrix.new<float>(N + 1, RTH_MIN + 1, na)   // ring buffer: N prior days + today
var int   dayCount   = 0
var int   row        = 0
var float dayOpen    = na
var float priorClose = na
var float lastRthCl  = na
var int   sessStart  = na
var float cumPV      = 0.0
var float cumV       = 0.0
var int   lastKey    = 0
var float lastMove   = na
 
var int   pos        = 0        // position after the latest checkpoint decision
var float entryPx    = na       // fill price of the open position
var int   heldSide   = 0        // side actually filled (lags pos by one bar)
var float dayPts     = 0.0
var int   pendClose  = 0        // side to close at this bar's open (0 = none)
var int   pendEntry  = 0        // side to open at this bar's open (0 = none)
var bool  pendRev    = false
var float pendDev    = na       // band half-width at the signal, for the fixed stop
var float fixedStop  = na
var int   entryBar   = na
var box   riskBox    = na
var box   profBox    = na
 
// Daily P&L label state (the day's running total lives in `stats`: dayUsd / dayN)
var bool  dailyDone   = false
var float lastVw      = na      // VWAP at the latest RTH bar (for half-days)
 
// Buy & hold benchmark for the table: long from the first trade's entry, marked on bar closes
var float bhPx        = na
var int   firstTradeT = na
var float bhPk        = 0.0
var float bhDD        = 0.0
 
bool longSig  = false
bool shortSig = false
bool exitSig  = false
 
drawExit(float px, string txt, string tip) =>
    if showSig
        label.new(bar_index, px, txt, style = label.style_label_center, color = color.new(chart.fg_color, 85),
                  textcolor = chart.fg_color, size = size.small, tooltip = tip + " @ " + str.tostring(px, format.mintick))
 
closeAt(float px) =>
    heldSide * (px - entryPx)
 
// Signed dollar string for box text: +$1,250 / −$450
usd(float v) =>
    (v < 0 ? "−$" : "+$") + str.tostring(math.abs(v), "#,##0")
 
posFromStr(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Right"     => position.top_right
        "Top Center"    => position.top_center
        "Middle Left"   => position.middle_left
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Right"  => position.bottom_right
        => position.bottom_center
 
fPct(int w, int n) =>
    n > 0 ? str.tostring(100.0 * w / n, "#.#") + "%" : "—"
 
fPF(float gp, float gl) =>
    gl > 0 ? str.tostring(gp / gl, "#.##") : gp > 0 ? "∞" : "—"
 
// Closed-trade performance stats (one object so helper functions can update it)
type Stats
    int   cntL = 0
    int   cntS = 0
    int   winL = 0
    int   winS = 0
    float gpL  = 0.0
    float glL  = 0.0
    float gpS  = 0.0
    float glS  = 0.0
    float eq   = 0.0
    float eqPk = 0.0
    float mdd  = 0.0
    float dayUsd = 0.0      // net $ of trades closed in the current session (reset each session)
    int   dayN   = 0
 
var Stats stats = Stats.new()
 
// Net $ of a closed trade for the table and box text
tradeUsd(float pts) =>
    pts * syminfo.pointvalue * qty - rtCost * qty
 
recordTrade(Stats s, int side, float pnl) =>
    if side == 1
        s.cntL += 1
        if pnl > 0
            s.winL += 1
            s.gpL  += pnl
        else
            s.glL  += -pnl
    else
        s.cntS += 1
        if pnl > 0
            s.winS += 1
            s.gpS  += pnl
        else
            s.glS  += -pnl
    s.eq   += pnl
    s.eqPk := math.max(s.eqPk, s.eq)
    s.mdd  := math.max(s.mdd, s.eqPk - s.eq)
    s.dayUsd += pnl
    s.dayN   += 1
    pnl
 
// Day total centred mid-session on the 09:30-open center line: under it when VWAP finished above the
// open (VWAP up), above it when VWAP finished below. Same text size as the per-trade box stamps.
drawDaily(int tMid, float center, float vwEnd, float total, int n) =>
    if showDaily and n > 0 and not na(center)
        label.new(tMid, center, "Daily: " + usd(total), xloc = xloc.bar_time,
                  style = vwEnd >= center ? label.style_label_up : label.style_label_down,
                  color = color.new(color.white, 100), size = size.small,
                  textcolor = total > 0 ? color.green : total < 0 ? color.red : chart.fg_color,
                  tooltip = "Day net P&L: " + usd(total) + " over " + str.tostring(n) + (n == 1 ? " trade" : " trades"))
 
// Freeze the trade's boxes at its exit: both are trimmed to the exit bar; the profit box shows
// entry → exit price for a winner and is removed for a loser. The trade's net $ is stamped at the
// outer edge of the box the exit landed in (stop / losing exit → red box, winning exit → green box).
closeBoxes(box rb, box pb, float exitPx, int exitBar, int side, float entry, int startBar, float pnl, bool stopHit) =>
    won = side * (exitPx - entry) > 0
    box pbx = pb
    if not na(rb)
        box.set_right(rb, exitBar)
    if won and not na(pb)
        box.set_top(pb, math.max(entry, exitPx))
        box.set_bottom(pb, math.min(entry, exitPx))
        box.set_right(pb, exitBar)
    else if won and showTradeBoxes and not na(rb)
        pbx := box.new(startBar, math.max(entry, exitPx), exitBar, math.min(entry, exitPx), border_color = cProfitB, bgcolor = cProfit)
    else if not na(pb)
        box.delete(pb)
        pbx := na
    inRed = stopHit or not won
    box tgt = inRed ? rb : pbx
    if not na(tgt)
        // outer edge: long stop → bottom, long profit → top, short stop → top, short profit → bottom
        atBottom = inRed == (side == 1)
        box.set_text(tgt, usd(pnl))
        box.set_text_halign(tgt, text.align_center)
        box.set_text_valign(tgt, atBottom ? text.align_bottom : text.align_top)
        box.set_text_color(tgt, pnl > 0 ? color.green : color.red)
        box.set_text_size(tgt, size.small)
    won                     // explicit return so the if-chains' mixed branch types are not the function's value
 
// ── Fills decided at the previous bar's checkpoint happen at this bar's open ──
if pendClose != 0 and heldSide != 0
    dayPts += closeAt(open)
    pnlX = recordTrade(stats, heldSide, tradeUsd(closeAt(open)))
    closeBoxes(riskBox, profBox, open, bar_index, heldSide, entryPx, entryBar, pnlX, false)
    riskBox   := na
    profBox   := na
    fixedStop := na
    drawExit(open, pendRev ? "⇄" : "✕", pendRev ? "Reverse" : "Stop exit")
    heldSide := 0
    entryPx  := na
if pendEntry != 0
    heldSide := pendEntry
    entryPx  := open
    entryBar := bar_index
    if na(bhPx)
        bhPx        := open      // buy-and-hold benchmark anchors at the first trade's entry
        firstTradeT := time
    if isFixed
        fixedStop := math.round_to_mintick(open - pendEntry * fixedMult * pendDev)   // a real stop order sits on a tick
        if showTradeBoxes
            riskBox := box.new(bar_index, math.max(open, fixedStop), bar_index + boxLead, math.min(open, fixedStop),
                               border_color = cRiskB, bgcolor = cRisk)
    if showSig
        label.new(bar_index, open, pendEntry == 1 ? "L" : "S",
                  style = pendEntry == 1 ? label.style_label_up : label.style_label_down,
                  color = pendEntry == 1 ? color.teal : color.red, textcolor = color.white, size = size.small,
                  tooltip = (pendEntry == 1 ? "Long" : "Short") + " fill @ " + str.tostring(open, format.mintick))
pendClose := 0
pendEntry := 0
pendRev   := false
 
// A session that ended before 15:59 (half-day): flatten at the last RTH close.
if endedEarly and heldSide != 0
    dayPts += heldSide * (close[1] - entryPx)
    pnlE = recordTrade(stats, heldSide, tradeUsd(closeAt(close[1])))
    closeBoxes(riskBox, profBox, close[1], bar_index - 1, heldSide, entryPx, entryBar, pnlE, false)
    riskBox   := na
    profBox   := na
    fixedStop := na
    if showSig
        label.new(bar_index - 1, close[1], "✕", style = label.style_label_center, color = color.new(chart.fg_color, 85),
                  textcolor = chart.fg_color, size = size.small, tooltip = "Session ended early: flat @ " + str.tostring(close[1], format.mintick))
    heldSide := 0
    entryPx  := na
    pos      := 0
 
// A session that ended early never reaches its 16:00 bar close: post the day total on its last RTH bar.
if endedEarly and not dailyDone
    drawDaily(int((sessStart + time[1]) / 2), dayOpen, lastVw, stats.dayUsd, stats.dayN)   // midpoint of the short session
    dailyDone := true
 
// ── New session ──────────────────────────────────────────────────────────────
// A session whose first bar is not 09:30 (chart history starting mid-session) is skipped entirely.
var bool validDay = false
if newSess
    validDay   := hour(time, tz) == 9 and minute(time, tz) == 30
    priorClose := lastRthCl
    if validDay
        dayCount += 1
        row      := dayCount % (N + 1)
        for c = 0 to RTH_MIN
            mv.set(row, c, na)
    dayOpen   := open
    sessStart := time
    cumPV     := 0.0
    cumV      := 0.0
    lastKey   := 0
    lastMove  := na
    pos       := 0
    heldSide  := 0
    entryPx   := na
    fixedStop := na
    riskBox   := na
    profBox   := na
    dayPts    := 0.0
    stats.dayUsd := 0.0
    stats.dayN   := 0
    dailyDone    := false
 
// ── Band, VWAP, signals ──────────────────────────────────────────────────────
if inRTH
    lastRthCl := close          // becomes the prior RTH close for the next session (Gap-adjusted reference)
 
float sig = na
float UB  = na
float LB  = na
float vw  = na
float longStop  = na
float shortStop = na
float upRef     = na
float dnRef     = na
bool  isCheck   = false
 
if inRTH and not na(sessStart) and validDay
    key     = int(math.round((time_close - sessStart) / 60000.0))   // minutes since 09:30 at the bar close
    openKey = int(math.round((time - sessStart) / 60000.0))
    cumPV += hlc3 * volume
    cumV  += volume
    vw := cumV > 0 ? cumPV / cumV : close
    lastVw := vw
 
    if key >= 1 and key <= RTH_MIN
        m = math.abs(close / dayOpen - 1)
        // missing minutes carry the previous move forward
        if not na(lastMove) and key > lastKey + 1
            for c = lastKey + 1 to key - 1
                mv.set(row, c, lastMove)
        // σ from the N prior sessions only; today's value is stored after
        if dayCount > N
            s   = 0.0
            cnt = 0
            for r = 0 to N
                if r != row
                    v = mv.get(r, key)
                    if not na(v)
                        s   += v
                        cnt += 1
            sig := cnt == N ? s / N : na
        mv.set(row, key, m)
        lastKey  := key
        lastMove := m
 
    if not na(sig)
        upRef := refMode == "Open" ? dayOpen : math.max(dayOpen, nz(priorClose, dayOpen))
        dnRef := refMode == "Open" ? dayOpen : math.min(dayOpen, nz(priorClose, dayOpen))
        UB := upRef * (1 + k * sig)
        LB := dnRef * (1 - k * sig)
        longStop  := trailMode == "Band + VWAP" ? math.max(UB, vw) : trailMode == "Band" ? UB : vw
        shortStop := trailMode == "Band + VWAP" ? math.min(LB, vw) : trailMode == "Band" ? LB : vw
 
    // Forced flat at the open of the bar that contains 15:59.
    if openKey <= FLAT_KEY and key > FLAT_KEY and heldSide != 0
        dayPts += closeAt(open)
        pnlF = recordTrade(stats, heldSide, tradeUsd(closeAt(open)))
        closeBoxes(riskBox, profBox, open, bar_index, heldSide, entryPx, entryBar, pnlF, false)
        riskBox   := na
        profBox   := na
        fixedStop := na
        drawExit(open, "✕", "15:59 flat")
        heldSide := 0
        entryPx  := na
        pos      := 0
        exitSig  := true
 
    // Fixed stop: resting order, checked on every bar (including the fill bar, after the open).
    if isFixed and heldSide != 0 and not na(fixedStop)
        hit = heldSide == 1 ? low <= fixedStop : high >= fixedStop
        if hit
            px = heldSide == 1 ? math.min(open, fixedStop) : math.max(open, fixedStop)
            dayPts += closeAt(px)
            pnlS = recordTrade(stats, heldSide, tradeUsd(closeAt(px)))
            closeBoxes(riskBox, profBox, px, bar_index, heldSide, entryPx, entryBar, pnlS, true)
            riskBox   := na
            profBox   := na
            fixedStop := na
            drawExit(px, "SL", "Fixed stop")
            heldSide := 0
            entryPx  := na
            pos      := 0
            exitSig  := true
 
    isCheck := key % cadence == 0 and key < FLAT_KEY and not na(sig)
    if isCheck
        goL = close > UB and close >= longStop
        goS = close < LB and close <= shortStop
        // fixed stop: no trailing exit, only a reversal into the opposite signal
        ex  = isFixed ? (pos == 1 and goS) or (pos == -1 and goL) : (pos == 1 and close < longStop) or (pos == -1 and close > shortStop)
        prev = pos
        if ex
            pos := 0
        // no entry whose fill bar would already contain the 15:59 flat (only bites above 1-minute charts)
        canEnter = key + timeframe.multiplier <= FLAT_KEY
        newL = canEnter and pos == 0 and goL and prev != 1
        newS = canEnter and pos == 0 and goS and prev != -1
        if ex
            pendClose := prev
            pendRev   := newL or newS
            exitSig   := true
        if newL
            pos       := 1
            pendEntry := 1
            pendDev   := UB - upRef
            longSig   := true
        else if newS
            pos       := -1
            pendEntry := -1
            pendDev   := dnRef - LB
            shortSig  := true
 
    // Day total, posted on the session's last bar (after the 15:59 flat, so every trade is in it)
    // and centred at 12:45, the middle of 09:30–16:00
    if key >= RTH_MIN and not dailyDone
        drawDaily(sessStart + RTH_MIN * 30000, dayOpen, vw, stats.dayUsd, stats.dayN)   // + 195 min in ms
        dailyDone := true
 
// ── Live risk / profit boxes for an open fixed-stop trade ───────────────────
// Both boxes are projected `boxLead` bars ahead while the trade is open (trimmed at exit).
if isFixed and showTradeBoxes and heldSide != 0 and not na(riskBox)
    box.set_right(riskBox, bar_index + boxLead)
    if heldSide * (close - entryPx) > 0
        if na(profBox)
            profBox := box.new(entryBar, math.max(entryPx, close), bar_index + boxLead, math.min(entryPx, close),
                               border_color = cProfitB, bgcolor = cProfit)
        else
            box.set_top(profBox, math.max(entryPx, close))
            box.set_bottom(profBox, math.min(entryPx, close))
            box.set_right(profBox, bar_index + boxLead)
    else if not na(profBox)
        box.delete(profBox)
        profBox := na
 
// Buy & hold benchmark equity (bar closes since the first trade's entry)
if barstate.isconfirmed and not na(bhPx)
    bhEqNow = (close - bhPx) * syminfo.pointvalue * qty
    bhPk := math.max(bhPk, bhEqNow)
    bhDD := math.max(bhDD, bhPk - bhEqNow)
 
// ── Plots ────────────────────────────────────────────────────────────────────
plot(UB, "Upper band", color = cBand, linewidth = 2, style = plot.style_linebr)
plot(LB, "Lower band", color = cBand, linewidth = 2, style = plot.style_linebr)
plot(showVwap and inRTH ? vw : na, "Session VWAP", color = cVwap, linewidth = 2, style = plot.style_linebr)
refLine = refMode == "Open" ? dayOpen : na
plot(showOpen and inRTH ? refLine : na, "09:30 open", color = color.new(chart.fg_color, 55), style = plot.style_linebr)
activeStop = isFixed ? (heldSide != 0 ? fixedStop : na) : pos == 1 ? longStop : pos == -1 ? shortStop : na
plot(showStop ? activeStop : na, "Active stop", color = isFixed ? color.red : chart.fg_color, linewidth = 1,
     style = isFixed ? plot.style_linebr : plot.style_circles)
plotshape(showCk and isCheck, "Checkpoint", shape.circle, location.bottom, color.new(chart.fg_color, 60), size = size.tiny)
bgcolor(showBg and heldSide == 1 ? color.new(color.teal, 92) : showBg and heldSide == -1 ? color.new(color.red, 92) : na)
 
// ── Alerts (fire on the checkpoint bar close; the fill is the next bar's open) ─
alertcondition(longSig, "Noise Band long", "Noise Band LONG on {{ticker}}: checkpoint close {{close}} above the upper band; fill at next bar open")
alertcondition(shortSig, "Noise Band short", "Noise Band SHORT on {{ticker}}: checkpoint close {{close}} below the lower band; fill at next bar open")
alertcondition(exitSig, "Noise Band exit", "Noise Band EXIT on {{ticker}} at {{close}}")
 
// ── Status table ─────────────────────────────────────────────────────────────
var table tb = table.new(position.top_right, 2, 6, bgcolor = color.new(chart.bg_color, 10),
                         border_color = color.new(chart.fg_color, 80), border_width = 1)
if showTbl and barstate.islast
    posTxt = heldSide == 1 ? "LONG" : heldSide == -1 ? "SHORT" : pos != 0 ? (pos == 1 ? "LONG (fills next bar)" : "SHORT (fills next bar)") : "flat"
    histTxt = dayCount > N ? "ready" : "warming up (" + str.tostring(math.max(dayCount - 1, 0)) + "/" + str.tostring(N) + " sessions)"
    table.cell(tb, 0, 0, "Noise Band", text_color = chart.fg_color, text_size = size.small)
    stopTxt = isFixed ? "fixed " + str.tostring(fixedMult, "#.#") + "×dev" : exitMode
    table.cell(tb, 1, 0, "N" + str.tostring(N) + " k" + str.tostring(k) + " " + str.tostring(cadence) + "m · " + stopTxt, text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 0, 1, "Position", text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 1, 1, posTxt, text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 0, 2, "Upper / Lower", text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 1, 2, na(UB) ? "–" : str.tostring(UB, format.mintick) + " / " + str.tostring(LB, format.mintick), text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 0, 3, isFixed ? "Fixed stop" : "Trailing stop", text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 1, 3, na(activeStop) ? "–" : str.tostring(activeStop, format.mintick), text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 0, 4, "Today (pts, gross)", text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 1, 4, str.tostring(dayPts + (heldSide != 0 ? closeAt(close) : 0.0), "#.##"), text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 0, 5, "History", text_color = chart.fg_color, text_size = size.small)
    table.cell(tb, 1, 5, histTxt, text_color = chart.fg_color, text_size = size.small)
 
// ── Performance table ────────────────────────────────────────────────────────
var table statsTbl = na
if showStats and barstate.islast
    if not na(statsTbl)
        table.delete(statsTbl)
    statsTbl := table.new(posFromStr(statsPos), 4, 9, bgcolor = color.new(color.black, 20), border_width = 1, border_color = color.new(color.gray, 50))
    color hdrBg = color.new(color.blue, 70)
    color lblBg = color.new(color.black, 50)
    int tot  = stats.cntL + stats.cntS
    int wins = stats.winL + stats.winS
    float bhEq = na(bhPx) ? na : (close - bhPx) * syminfo.pointvalue * qty
    table.cell(statsTbl, 0, 0, "Noise Band",  text_color = color.white, bgcolor = hdrBg, text_size = size.small)
    table.cell(statsTbl, 1, 0, "All",         text_color = color.white, bgcolor = hdrBg, text_size = size.small)
    table.cell(statsTbl, 2, 0, "Long",        text_color = color.white, bgcolor = hdrBg, text_size = size.small)
    table.cell(statsTbl, 3, 0, "Short",       text_color = color.white, bgcolor = hdrBg, text_size = size.small)
    table.cell(statsTbl, 0, 1, "Trades",      text_color = color.white, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 1, str.tostring(tot),        text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 2, 1, str.tostring(stats.cntL), text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 3, 1, str.tostring(stats.cntS), text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 0, 2, "Win %",       text_color = color.white, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 2, fPct(wins, tot),              text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 2, 2, fPct(stats.winL, stats.cntL), text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 3, 2, fPct(stats.winS, stats.cntS), text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 0, 3, "PF",          text_color = color.white, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 3, fPF(stats.gpL + stats.gpS, stats.glL + stats.glS), text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 2, 3, fPF(stats.gpL, stats.glL), text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 3, 3, fPF(stats.gpS, stats.glS), text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 0, 4, "P&L",         text_color = color.white, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 4, (stats.eq < 0 ? "-$" : "$") + str.tostring(math.abs(stats.eq), "#.##"),
         text_color = stats.eq >= 0 ? color.new(color.green, 0) : color.new(color.red, 0), text_size = size.small)
    table.cell(statsTbl, 2, 4, "", text_size = size.small)
    table.cell(statsTbl, 3, 4, "", text_size = size.small)
    table.cell(statsTbl, 0, 5, "Max DD",      text_color = color.white, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 5, "$" + str.tostring(stats.mdd, "#.##"), text_color = color.new(color.red, 0), text_size = size.small)
    table.cell(statsTbl, 2, 5, "", text_size = size.small)
    table.cell(statsTbl, 3, 5, "", text_size = size.small)
    table.cell(statsTbl, 0, 6, "B&H P&L",     text_color = color.white, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 6, na(bhEq) ? "—" : (bhEq < 0 ? "-$" : "$") + str.tostring(math.abs(bhEq), "#.##"),
         text_color = na(bhEq) or bhEq >= 0 ? color.new(color.green, 0) : color.new(color.red, 0), text_size = size.small)
    table.cell(statsTbl, 2, 6, "", text_size = size.small)
    table.cell(statsTbl, 3, 6, "", text_size = size.small)
    table.cell(statsTbl, 0, 7, "B&H Max DD",  text_color = color.white, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 7, na(bhPx) ? "—" : "$" + str.tostring(bhDD, "#.##"), text_color = color.new(color.red, 0), text_size = size.small)
    table.cell(statsTbl, 2, 7, "", text_size = size.small)
    table.cell(statsTbl, 3, 7, "", text_size = size.small)
    table.cell(statsTbl, 0, 8, "First trade", text_color = color.white, bgcolor = lblBg, text_size = size.small)
    table.cell(statsTbl, 1, 8, na(firstTradeT) ? "—" : str.format_time(firstTradeT, "dd MMM yy HH:mm", tz),
         text_color = color.white, text_size = size.small)
    table.cell(statsTbl, 2, 8, "", text_size = size.small)
    table.cell(statsTbl, 3, 8, "", text_size = size.small)

← 返回列表