NQ Lite v4.1 | MSS BOS + MTF RB

alithecaca · study · 487 行 · 点赞 41 · TradingView 原页

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

Pine Script

//@version=6
indicator("NQ Lite v4.1 | MSS BOS + MTF RB", overlay=true, max_boxes_count=250, max_lines_count=300, max_labels_count=250)
 
// SETTINGS
fvgGroup = "Fair Value Gaps"
showFVG = input.bool(false, "Show original FVG (optional)", group=fvgGroup)
confirmedRetestsOnly = input.bool(true, "Only show IFVG after confirmed retest", group=fvgGroup)
showIFVG = input.bool(true, "Show inverted FVG", group=fvgGroup)
minGap = input.float(0.10, "Minimum gap in ATR", minval=0.0, step=0.05, group=fvgGroup)
maxGapBars = input.int(65, "Zone lifetime (bars)", minval=5, group=fvgGroup)
maxGaps = input.int(25, "Maximum gaps", minval=5, maxval=80, group=fvgGroup)
 
rbGroup = "Rejection Blocks"
showRB = input.bool(true, "Show rejection blocks", group=rbGroup)
rbStrength = input.string("Normal", "Rejection strength", options=["Loose", "Normal", "Strong", "Very Strong", "Custom"], group=rbGroup)
customWickBody = input.float(1.75, "Custom minimum wick/body", minval=0.5, step=0.25, group=rbGroup)
customWickRange = input.float(0.40, "Custom minimum wick/range", minval=0.1, maxval=0.9, step=0.05, group=rbGroup)
wickBody = rbStrength == "Loose" ? 1.0 : rbStrength == "Strong" ? 2.25 : rbStrength == "Very Strong" ? 3.0 : rbStrength == "Custom" ? customWickBody : 1.75
wickRange = rbStrength == "Loose" ? 0.30 : rbStrength == "Strong" ? 0.50 : rbStrength == "Very Strong" ? 0.60 : rbStrength == "Custom" ? customWickRange : 0.40
showHTFRB = input.bool(true, "Show higher-timeframe blocks", group=rbGroup)
htf1 = input.timeframe("15", "Higher timeframe 1", group=rbGroup)
htf2Enabled = input.bool(true, "Enable higher timeframe 2", group=rbGroup)
htf2 = input.timeframe("60", "Higher timeframe 2", group=rbGroup)
confirmRB = input.bool(true, "Confirm with next candle", group=rbGroup)
rbPivot = input.int(5, "Rejection at recent extreme (bars)", minval=2, maxval=30, group=rbGroup)
maxRB = input.int(12, "Maximum blocks", minval=1, maxval=60, group=rbGroup)
rbLife = input.int(60, "Block lifetime (bars)", minval=5, group=rbGroup)
 
liqGroup = "Estimated Liquidity"
showSSL = input.bool(true, "Show SSL", group=liqGroup)
showBSL = input.bool(true, "Show BSL", group=liqGroup)
pivotBars = input.int(4, "Pivot strength", minval=2, maxval=20, group=liqGroup)
equalTolerance = input.float(0.15, "Equal-level tolerance (ATR)", minval=0.01, step=0.01, group=liqGroup)
liqLife = input.int(120, "Level lifetime (bars)", minval=10, group=liqGroup)
maxLevels = input.int(18, "Maximum levels", minval=5, maxval=80, group=liqGroup)
 
structureGroup = "Market Structure | MSS / BOS"
showStructure = input.bool(true, "Show MSS and BOS", group=structureGroup)
structurePivot = input.int(5, "Swing confirmation (bars)", minval=2, maxval=25, group=structureGroup)
structureLimit = input.int(18, "Maximum structure annotations", minval=2, maxval=60, group=structureGroup)
structureBreak = input.string("Close", "Break confirmation", options=["Close", "Wick"], group=structureGroup)
showLiqLabels = input.bool(true, "Label SSL / BSL lines", group=structureGroup)
 
visualGroup = "Appearance"
bullColor = input.color(color.rgb(68, 190, 130), "Bullish green", group=visualGroup)
bearColor = input.color(color.rgb(225, 100, 110), "Bearish red", group=visualGroup)
lineFade = input.int(25, "Outline transparency", minval=0, maxval=90, group=visualGroup)
fillFade = input.int(92, "Zone fill transparency (higher = lighter)", minval=70, maxval=100, group=visualGroup)
showTags = input.bool(true, "Small zone labels", group=visualGroup)
showMarkers = input.bool(false, "Signal markers", group=visualGroup)
atrLength = input.int(14, "ATR period", minval=2, group=visualGroup)
 
dashboardGroup = "Trade Plan Dashboard"
showDashboard = input.bool(true, "Show top-right trade plan", group=dashboardGroup)
trendLength = input.int(50, "EMA trend filter", minval=5, group=dashboardGroup)
signalLookback = input.int(12, "Signal validity (bars)", minval=1, maxval=100, group=dashboardGroup)
stopATR = input.float(1.0, "Estimated stop distance (ATR)", minval=0.25, step=0.25, group=dashboardGroup)
tp1R = input.float(1.0, "TP1 risk multiple", minval=0.25, step=0.25, group=dashboardGroup)
tp2R = input.float(1.5, "TP2 risk multiple", minval=0.5, step=0.25, group=dashboardGroup)
tp3R = input.float(2.5, "TP3 risk multiple", minval=0.75, step=0.25, group=dashboardGroup)
 
atr = ta.atr(atrLength)
ready = barstate.isconfirmed
clearFill = color.new(color.black, 100)
bullOutline = color.new(bullColor, lineFade)
bearOutline = color.new(bearColor, lineFade)
muted = color.new(color.gray, 75)
bullFill = color.new(bullColor, fillFade)
bearFill = color.new(bearColor, fillFade)
 
// FVG / IFVG
// direction: 1 = bullish FVG; -1 = bearish FVG
// state: 0 = original; 1 = inverted awaiting retest; 2 = retest confirmed
var array<box> gapBoxes = array.new<box>()
var array<float> gapHighs = array.new<float>()
var array<float> gapLows = array.new<float>()
var array<int> gapDirs = array.new<int>()
var array<int> gapStates = array.new<int>()
var array<int> gapStarts = array.new<int>()
var array<int> inversionBars = array.new<int>()
 
bool newBullIFVG = false
bool newBearIFVG = false
bool bullRetest = false
bool bearRetest = false
 
if ready and array.size(gapBoxes) > 0
    for i = array.size(gapBoxes) - 1 to 0
        bx = array.get(gapBoxes, i)
        top = array.get(gapHighs, i)
        bottom = array.get(gapLows, i)
        dir = array.get(gapDirs, i)
        state = array.get(gapStates, i)
        born = array.get(gapStarts, i)
        invertedAt = array.get(inversionBars, i)
        expired = bar_index - born > maxGapBars
        // A gap is inverted by a close beyond its opposite edge.
        bullFlip = state == 0 and dir == -1 and close > top
        bearFlip = state == 0 and dir == 1 and close < bottom
        // An inverted zone is invalidated by a close back through it.
        invalid = state > 0 and (dir == -1 ? close < bottom : close > top)
        // Keep wick-mitigated gaps: inversion requires a later CLOSE through the far edge.
        if expired or invalid
            box.delete(bx)
            array.remove(gapBoxes, i)
            array.remove(gapHighs, i)
            array.remove(gapLows, i)
            array.remove(gapDirs, i)
            array.remove(gapStates, i)
            array.remove(gapStarts, i)
            array.remove(inversionBars, i)
        else
            box.set_right(bx, bar_index + 1)
            if bullFlip or bearFlip
                array.set(gapStates, i, 1)
                array.set(inversionBars, i, bar_index)
                newBullIFVG := newBullIFVG or bullFlip
                newBearIFVG := newBearIFVG or bearFlip
                zoneColor = bullFlip ? bullOutline : bearOutline
                visible = showIFVG and not confirmedRetestsOnly
                box.set_border_color(bx, visible ? zoneColor : color.new(zoneColor, 100))
                box.set_bgcolor(bx, visible ? (bullFlip ? bullFill : bearFill) : clearFill)
                box.set_text_color(bx, zoneColor)
                box.set_text(bx, visible and showTags ? (bullFlip ? "Bull IFVG" : "Bear IFVG") : "")
            else if state > 0 and bar_index > invertedAt
                // A valid retest touches the zone and closes back outside it.
                bullOK = dir == -1 and low <= top and high >= bottom and close > top and close > open
                bearOK = dir == 1 and high >= bottom and low <= top and close < bottom and close < open
                if state == 1 and (bullOK or bearOK)
                    array.set(gapStates, i, 2)
                    bullRetest := bullRetest or bullOK
                    bearRetest := bearRetest or bearOK
                    c = bullOK ? bullOutline : bearOutline
                    box.set_border_color(bx, showIFVG ? c : color.new(c, 100))
                    box.set_bgcolor(bx, showIFVG ? (bullOK ? bullFill : bearFill) : clearFill)
                    box.set_text_color(bx, c)
                    box.set_text(bx, showIFVG and showTags ? (bullOK ? "Bull IFVG" : "Bear IFVG") : "")
 
bullFVG = ready and bar_index >= 2 and not na(atr) and low > high[2] and low - high[2] >= atr * minGap
bearFVG = ready and bar_index >= 2 and not na(atr) and high < low[2] and low[2] - high >= atr * minGap
if bullFVG or bearFVG
    dir = bullFVG ? 1 : -1
    top = bullFVG ? low : low[2]
    bottom = bullFVG ? high[2] : high
    bx = box.new(bar_index - 2, top, bar_index + 1, bottom, border_color=showFVG ? muted : color.new(color.gray, 100), bgcolor=clearFill, text=showFVG and showTags ? "FVG" : "", text_color=muted, text_size=size.tiny)
    array.push(gapBoxes, bx)
    array.push(gapHighs, top)
    array.push(gapLows, bottom)
    array.push(gapDirs, dir)
    array.push(gapStates, 0)
    array.push(gapStarts, bar_index)
    array.push(inversionBars, -1)
    if array.size(gapBoxes) > maxGaps
        box.delete(array.shift(gapBoxes))
        array.shift(gapHighs)
        array.shift(gapLows)
        array.shift(gapDirs)
        array.shift(gapStates)
        array.shift(gapStarts)
        array.shift(inversionBars)
 
// REJECTION BLOCKS: wick of a rejection candle, optionally confirmed by the next close.
barRange = math.max(high - low, syminfo.mintick)
body = math.max(math.abs(close - open), syminfo.mintick)
lowWick = math.min(open, close) - low
highWick = high - math.max(open, close)
recentLow = ta.lowest(low, rbPivot)
recentHigh = ta.highest(high, rbPivot)
bullCandidate = lowWick / body >= wickBody and lowWick / barRange >= wickRange and close > (high + low) / 2 and low <= recentLow
bearCandidate = highWick / body >= wickBody and highWick / barRange >= wickRange and close < (high + low) / 2 and high >= recentHigh
bullRB = ready and (confirmRB ? bullCandidate[1] and close > high[1] : bullCandidate)
bearRB = ready and (confirmRB ? bearCandidate[1] and close < low[1] : bearCandidate)
 
// Higher timeframe calculations are evaluated in their own timeframe.
// [1] with lookahead_on returns the PREVIOUS fully closed HTF candle,
// preventing developing HTF candles from appearing as confirmed signals.
f_htfRB() =>
    rng = math.max(high - low, syminfo.mintick)
    bod = math.max(math.abs(close - open), syminfo.mintick)
    lw = math.min(open, close) - low
    uw = high - math.max(open, close)
    htfRecentLow = ta.lowest(low, rbPivot)
    htfRecentHigh = ta.highest(high, rbPivot)
    bc = lw / bod >= wickBody and lw / rng >= wickRange and close > (high + low) / 2 and low <= htfRecentLow
    sc = uw / bod >= wickBody and uw / rng >= wickRange and close < (high + low) / 2 and high >= htfRecentHigh
    b = confirmRB ? bc[1] and close > high[1] : bc
    s = confirmRB ? sc[1] and close < low[1] : sc
    off = confirmRB ? 1 : 0
    bTop = math.min(open[off], close[off])
    bBot = low[off]
    sTop = high[off]
    sBot = math.max(open[off], close[off])
    [b[1], s[1], bTop[1], bBot[1], sTop[1], sBot[1]]
 
[h1Bull, h1Bear, h1BT, h1BB, h1ST, h1SB] = request.security(syminfo.tickerid, htf1, f_htfRB(), lookahead=barmerge.lookahead_on)
[h2Bull, h2Bear, h2BT, h2BB, h2ST, h2SB] = request.security(syminfo.tickerid, htf2, f_htfRB(), lookahead=barmerge.lookahead_on)
validH1 = timeframe.in_seconds(htf1) > timeframe.in_seconds(timeframe.period)
validH2 = timeframe.in_seconds(htf2) > timeframe.in_seconds(timeframe.period)
newH1 = ta.change(time(htf1)) != 0
newH2 = ta.change(time(htf2)) != 0
 
var array<box> rbBoxes = array.new<box>()
var array<int> rbDirs = array.new<int>()
var array<int> rbStarts = array.new<int>()
if ready and array.size(rbBoxes) > 0
    for i = array.size(rbBoxes) - 1 to 0
        bx = array.get(rbBoxes, i)
        dir = array.get(rbDirs, i)
        born = array.get(rbStarts, i)
        invalid = dir == 1 ? close < box.get_bottom(bx) : close > box.get_top(bx)
        if invalid or bar_index - born > rbLife
            box.delete(bx)
            array.remove(rbBoxes, i)
            array.remove(rbDirs, i)
            array.remove(rbStarts, i)
        else
            box.set_right(bx, bar_index + 1)
 
if showRB and (bullRB or bearRB)
    dir = bullRB ? 1 : -1
    offset = confirmRB ? 1 : 0
    top = bullRB ? math.min(open[offset], close[offset]) : high[offset]
    bottom = bullRB ? low[offset] : math.max(open[offset], close[offset])
    bx = box.new(bar_index - offset, top, bar_index + 1, bottom, border_color=bullRB ? bullOutline : bearOutline, bgcolor=bullRB ? bullFill : bearFill, text=showTags ? (bullRB ? "Bull RB" : "Bear RB") : "", text_color=bullRB ? bullOutline : bearOutline, text_size=size.tiny)
    array.push(rbBoxes, bx)
    array.push(rbDirs, dir)
    array.push(rbStarts, bar_index)
    if array.size(rbBoxes) > maxRB
        box.delete(array.shift(rbBoxes))
        array.shift(rbDirs)
        array.shift(rbStarts)
 
// Add confirmed HTF zones at the first chart bar of the following HTF candle.
// These are plotted on the current chart and updated/invalidated alongside local RBs.
if showRB and showHTFRB and barstate.isnew
    for n = 1 to 2
        enabled = n == 1 ? validH1 : validH2 and htf2Enabled
        fresh = n == 1 ? newH1 : newH2
        b = n == 1 ? h1Bull : h2Bull
        s = n == 1 ? h1Bear : h2Bear
        bt = n == 1 ? h1BT : h2BT
        bb = n == 1 ? h1BB : h2BB
        st = n == 1 ? h1ST : h2ST
        sb = n == 1 ? h1SB : h2SB
        tfLabel = n == 1 ? htf1 : htf2
        if enabled and fresh and (b or s)
            isBull = b
            top = isBull ? bt : st
            bottom = isBull ? bb : sb
            if not na(top) and not na(bottom) and top > bottom
                cOutline = isBull ? bullOutline : bearOutline
                cFill = isBull ? bullFill : bearFill
                bx = box.new(bar_index, top, bar_index + 1, bottom, border_color=cOutline, bgcolor=cFill, text=showTags ? tfLabel + " RB" : "", text_color=cOutline, text_size=size.tiny)
                array.push(rbBoxes, bx)
                array.push(rbDirs, isBull ? 1 : -1)
                array.push(rbStarts, bar_index)
                if array.size(rbBoxes) > maxRB
                    box.delete(array.shift(rbBoxes))
                    array.shift(rbDirs)
                    array.shift(rbStarts)
 
// ESTIMATED LIQUIDITY: confirmed pivot lows/highs (not real order-book data).
pLow = ta.pivotlow(low, pivotBars, pivotBars)
pHigh = ta.pivothigh(high, pivotBars, pivotBars)
var float lastPivotLow = na
var float lastPivotHigh = na
var array<line> liqLines = array.new<line>()
var array<label> liqTags = array.new<label>()
var array<float> liqPrices = array.new<float>()
var array<int> liqDirs = array.new<int>()
var array<int> liqStarts = array.new<int>()
 
bool sslSwept = false
bool bslSwept = false
if ready and array.size(liqLines) > 0
    for i = array.size(liqLines) - 1 to 0
        ln = array.get(liqLines, i)
        tag = array.get(liqTags, i)
        price = array.get(liqPrices, i)
        dir = array.get(liqDirs, i)
        born = array.get(liqStarts, i)
        swept = dir == -1 ? low < price : high > price
        if swept
            sslSwept := sslSwept or dir == -1
            bslSwept := bslSwept or dir == 1
        if swept or bar_index - born > liqLife
            line.delete(ln)
            label.delete(tag)
            array.remove(liqTags, i)
            array.remove(liqLines, i)
            array.remove(liqPrices, i)
            array.remove(liqDirs, i)
            array.remove(liqStarts, i)
        else
            line.set_x2(ln, bar_index + 1)
            label.set_x(tag, bar_index + 1)
 
if ready
    if not na(pLow)
        equalLow = not na(lastPivotLow) and math.abs(pLow - lastPivotLow) <= atr * equalTolerance
        lastPivotLow := pLow
        if showSSL
            ln = line.new(bar_index - pivotBars, pLow, bar_index + 1, pLow, color=bullOutline, width=equalLow ? 2 : 1, style=line.style_solid)
            array.push(liqLines, ln)
            array.push(liqTags, label.new(bar_index + 1, pLow, showLiqLabels ? "SSL" : "", style=label.style_label_left, textcolor=bullOutline, color=color.new(color.black, 100), size=size.tiny))
            array.push(liqPrices, pLow)
            array.push(liqDirs, -1)
            array.push(liqStarts, bar_index)
    if not na(pHigh)
        equalHigh = not na(lastPivotHigh) and math.abs(pHigh - lastPivotHigh) <= atr * equalTolerance
        lastPivotHigh := pHigh
        if showBSL
            ln = line.new(bar_index - pivotBars, pHigh, bar_index + 1, pHigh, color=bearOutline, width=equalHigh ? 2 : 1, style=line.style_solid)
            array.push(liqLines, ln)
            array.push(liqTags, label.new(bar_index + 1, pHigh, showLiqLabels ? "BSL" : "", style=label.style_label_left, textcolor=bearOutline, color=color.new(color.black, 100), size=size.tiny))
            array.push(liqPrices, pHigh)
            array.push(liqDirs, 1)
            array.push(liqStarts, bar_index)
    while array.size(liqLines) > maxLevels
        line.delete(array.shift(liqLines))
        label.delete(array.shift(liqTags))
        array.shift(liqPrices)
        array.shift(liqDirs)
        array.shift(liqStarts)
 
// MARKET STRUCTURE: swing breaks, labeled MSS or BOS.
// Trend starts unknown: first confirmed break is BOS; a later reversal is MSS.
// Pivot lines begin at their actual pivot bar, but are only created after confirmation.
structureHigh = ta.pivothigh(high, structurePivot, structurePivot)
structureLow = ta.pivotlow(low, structurePivot, structurePivot)
var float activeHigh = na
var float activeLow = na
var int activeHighBar = na
var int activeLowBar = na
var bool highBroken = false
var bool lowBroken = false
var int structureTrend = 0
var array<line> structureLines = array.new<line>()
var array<label> structureLabels = array.new<label>()
bool bullishMSS = false
bool bearishMSS = false
bool bullishBOS = false
bool bearishBOS = false
 
if ready
    if not na(structureHigh)
        activeHigh := structureHigh
        activeHighBar := bar_index - structurePivot
        highBroken := false
    if not na(structureLow)
        activeLow := structureLow
        activeLowBar := bar_index - structurePivot
        lowBroken := false
 
    breakUp = not na(activeHigh) and not highBroken and (structureBreak == "Close" ? close > activeHigh : high > activeHigh)
    breakDown = not na(activeLow) and not lowBroken and (structureBreak == "Close" ? close < activeLow : low < activeLow)
 
    // Avoid contradictory signals on a large outside bar.
    if breakUp and breakDown
        breakUp := close >= open
        breakDown := not breakUp
 
    if breakUp
        bullishMSS := structureTrend == -1
        bullishBOS := not bullishMSS
        structureTrend := 1
        highBroken := true
        if showStructure
            tagText = bullishMSS ? "MSS ↑" : "BOS ↑"
            ln = line.new(activeHighBar, activeHigh, bar_index, activeHigh, color=bullOutline, style=line.style_solid, width=bullishMSS ? 2 : 1)
            lb = label.new(bar_index, activeHigh, tagText, style=label.style_label_down, color=color.new(color.black, 100), textcolor=bullOutline, size=size.tiny)
            array.push(structureLines, ln)
            array.push(structureLabels, lb)
 
    if breakDown
        bearishMSS := structureTrend == 1
        bearishBOS := not bearishMSS
        structureTrend := -1
        lowBroken := true
        if showStructure
            tagText = bearishMSS ? "MSS ↓" : "BOS ↓"
            ln = line.new(activeLowBar, activeLow, bar_index, activeLow, color=bearOutline, style=line.style_solid, width=bearishMSS ? 2 : 1)
            lb = label.new(bar_index, activeLow, tagText, style=label.style_label_up, color=color.new(color.black, 100), textcolor=bearOutline, size=size.tiny)
            array.push(structureLines, ln)
            array.push(structureLabels, lb)
 
    while array.size(structureLines) > structureLimit
        line.delete(array.shift(structureLines))
        label.delete(array.shift(structureLabels))
 
alertcondition(bullishMSS, "Bullish MSS", "Bullish market structure shift confirmed")
alertcondition(bearishMSS, "Bearish MSS", "Bearish market structure shift confirmed")
alertcondition(bullishBOS, "Bullish BOS", "Bullish break of structure confirmed")
alertcondition(bearishBOS, "Bearish BOS", "Bearish break of structure confirmed")
 
plotshape(showMarkers and showIFVG and (confirmedRetestsOnly ? bullRetest : newBullIFVG), "Bullish IFVG", shape.triangleup, location.belowbar, bullColor, size=size.tiny, text="I+")
plotshape(showMarkers and showIFVG and (confirmedRetestsOnly ? bearRetest : newBearIFVG), "Bearish IFVG", shape.triangledown, location.abovebar, bearColor, size=size.tiny, text="I-")
plotshape(showMarkers and showRB and bullRB, "Bullish RB", shape.circle, location.belowbar, bullColor, size=size.tiny)
plotshape(showMarkers and showRB and bearRB, "Bearish RB", shape.circle, location.abovebar, bearColor, size=size.tiny)
 
alertcondition(newBullIFVG, "Bullish IFVG", "Bearish FVG inverted bullish")
alertcondition(newBearIFVG, "Bearish IFVG", "Bullish FVG inverted bearish")
alertcondition(bullRetest, "Bullish IFVG retest", "Bullish IFVG retest and rejection")
alertcondition(bearRetest, "Bearish IFVG retest", "Bearish IFVG retest and rejection")
alertcondition(bullRB, "Bullish rejection block", "Bullish rejection block detected")
alertcondition(bearRB, "Bearish rejection block", "Bearish rejection block detected")
alertcondition(sslSwept, "SSL sweep", "Estimated sell-side liquidity swept")
alertcondition(bslSwept, "BSL sweep", "Estimated buy-side liquidity swept")
 
// ────────────────────────────────────────────────
// TOP-RIGHT TRADE PLAN
// Only proposes a direction when a recently confirmed
// IFVG retest or rejection block agrees with EMA trend.
// Prices are hypothetical ATR/R estimates, not forecasts.
// ────────────────────────────────────────────────
trendEMA = ta.ema(close, trendLength)
longEvent = (showIFVG and bullRetest) or (showRB and bullRB)
shortEvent = (showIFVG and bearRetest) or (showRB and bearRB)
 
var int lastLongBar = na
var int lastShortBar = na
var float lastLongPrice = na
var float lastShortPrice = na
var float lastLongATR = na
var float lastShortATR = na
if barstate.isconfirmed
    if longEvent
        lastLongBar := bar_index
        lastLongPrice := close
        lastLongATR := atr
    if shortEvent
        lastShortBar := bar_index
        lastShortPrice := close
        lastShortATR := atr
 
longRecent = not na(lastLongBar) and bar_index - lastLongBar <= signalLookback
shortRecent = not na(lastShortBar) and bar_index - lastShortBar <= signalLookback
longAllowed = longRecent and close > trendEMA and close >= lastLongPrice and (not shortRecent or lastLongBar > lastShortBar)
shortAllowed = shortRecent and close < trendEMA and close <= lastShortPrice and (not longRecent or lastShortBar > lastLongBar)
tradeDir = longAllowed ? 1 : shortAllowed ? -1 : 0
 
// Anchor targets to the most recent signal close, not each new bar.
var float planEntry = na
var float planStop = na
var float planTP1 = na
var float planTP2 = na
var float planTP3 = na
var int planDir = 0
if barstate.isconfirmed
    planDir := tradeDir
    if planDir != 0 and not na(atr)
        planEntry := planDir == 1 ? lastLongPrice : lastShortPrice
        signalATR = planDir == 1 ? lastLongATR : lastShortATR
        riskDistance = math.max(signalATR * stopATR, syminfo.mintick)
        planStop := planEntry - planDir * riskDistance
        planTP1 := planEntry + planDir * riskDistance * tp1R
        planTP2 := planEntry + planDir * riskDistance * tp2R
        planTP3 := planEntry + planDir * riskDistance * tp3R
    else
        planEntry := na
        planStop := na
        planTP1 := na
        planTP2 := na
        planTP3 := na
 
var table planTable = table.new(position.top_right, 2, 7, bgcolor=color.new(color.black, 93), frame_color=color.new(color.gray, 92), frame_width=1, border_width=0)
if barstate.islast
    if showDashboard
        planColor = planDir == 1 ? bullColor : planDir == -1 ? bearColor : color.silver
        directionText = planDir == 1 ? "LONG BIAS" : planDir == -1 ? "SHORT BIAS" : "WAIT"
        valueColor = color.new(color.white, 12)
        table.cell(planTable, 0, 0, "TRADE PLAN", text_color=color.new(color.white, 35), text_size=size.tiny)
        table.cell(planTable, 1, 0, directionText, text_color=planColor, text_size=size.small)
        table.cell(planTable, 0, 1, "Reference", text_color=color.new(color.white, 45), text_size=size.tiny)
        table.cell(planTable, 1, 1, na(planEntry) ? "—" : str.tostring(planEntry, format.mintick), text_color=valueColor, text_size=size.tiny)
        table.cell(planTable, 0, 2, "Est. stop", text_color=color.new(color.white, 45), text_size=size.tiny)
        table.cell(planTable, 1, 2, na(planStop) ? "—" : str.tostring(planStop, format.mintick), text_color=valueColor, text_size=size.tiny)
        table.cell(planTable, 0, 3, "TP1 · " + str.tostring(tp1R) + "R", text_color=color.new(color.white, 45), text_size=size.tiny)
        table.cell(planTable, 1, 3, na(planTP1) ? "—" : str.tostring(planTP1, format.mintick), text_color=planColor, text_size=size.tiny)
        table.cell(planTable, 0, 4, "TP2 · " + str.tostring(tp2R) + "R", text_color=color.new(color.white, 45), text_size=size.tiny)
        table.cell(planTable, 1, 4, na(planTP2) ? "—" : str.tostring(planTP2, format.mintick), text_color=planColor, text_size=size.tiny)
        table.cell(planTable, 0, 5, "TP3 · " + str.tostring(tp3R) + "R", text_color=color.new(color.white, 45), text_size=size.tiny)
        table.cell(planTable, 1, 5, na(planTP3) ? "—" : str.tostring(planTP3, format.mintick), text_color=planColor, text_size=size.tiny)
        table.cell(planTable, 0, 6, "ATR-based · estimate", text_color=color.new(color.white, 65), text_size=size.tiny)
        table.cell(planTable, 1, 6, "Scenario only", text_color=color.new(color.white, 65), text_size=size.tiny)
    else
        table.clear(planTable, 0, 0, 1, 6)

← 返回列表