Market Structure + ORB + Thestrat + Vwap + EMAs + BB + DASHBOARD

xilouty · study · 843 行 · 点赞 18 · TradingView 原页

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

Pine Script

//@version=6
indicator("Market Structure + ORB", shorttitle="MS+ORB", overlay=true, max_labels_count=500, max_lines_count=500, max_boxes_count=100, max_bars_back=500)
 
//====================================================
// 01 — MAIN TREND
//====================================================
groupMain = "01 — Main Trend"
mainLen = input.int(30, "Length", minval=1, group=groupMain)
mainSrc = input.source(close, "Source", group=groupMain)
mainBullColor = input.color(color.lime, "Bull Color", group=groupMain)
mainBearColor = input.color(color.red, "Bear Color", group=groupMain)
mainWidth = input.int(2, "Width", minval=1, maxval=5, group=groupMain)
 
mainEMA = ta.ema(mainSrc, mainLen)
mainBull = close > mainEMA
mainTrend = mainBull ? "BULL" : close < mainEMA ? "BEAR" : "NEUTRAL"
 
plot(mainEMA, "Main Trend", color=mainBull ? mainBullColor : mainBearColor, linewidth=mainWidth)
 
//====================================================
// 02 — BOLLINGER BANDS
//====================================================
groupBB = "02 — Bollinger Bands"
showBB = input.bool(true, "Show Bollinger Bands", group=groupBB)
bbLen = input.int(20, "Length", minval=1, group=groupBB)
bbDev = input.float(2.0, "Deviation", minval=0.1, step=0.1, group=groupBB)
bbSrc = input.source(close, "Source", group=groupBB)
bbBasisColor = input.color(color.yellow, "Basis Color", group=groupBB)
bbBandColor = input.color(color.blue, "Band Color", group=groupBB)
bbFillColor = input.color(color.blue, "Fill Color", group=groupBB)
bbWidth = input.int(1, "Width", minval=1, maxval=5, group=groupBB)
bbTransparency = input.int(90, "Fill Transparency", minval=0, maxval=100, group=groupBB)
 
bbBasis = ta.sma(bbSrc, bbLen)
bbRange = ta.stdev(bbSrc, bbLen) * bbDev
bbUpper = bbBasis + bbRange
bbLower = bbBasis - bbRange
 
bb1 = plot(showBB ? bbBasis : na, "BB Basis", color=bbBasisColor, linewidth=bbWidth)
bb2 = plot(showBB ? bbUpper : na, "BB Upper", color=bbBandColor, linewidth=bbWidth)
bb3 = plot(showBB ? bbLower : na, "BB Lower", color=bbBandColor, linewidth=bbWidth)
fill(bb2, bb3, color=showBB ? color.new(bbFillColor, bbTransparency) : na)
 
//====================================================
// 03 — VWAP
//====================================================
groupVWAP = "03 — VWAP"
showVWAP = input.bool(true, "Show VWAP", group=groupVWAP)
vwapSrc = input.source(hlc3, "Source", group=groupVWAP)
vwapColor = input.color(color.orange, "Color", group=groupVWAP)
vwapWidth = input.int(2, "Width", minval=1, maxval=5, group=groupVWAP)
vwapMaxTF = input.string("Always", "Maximum Timeframe", options=["15m", "30m", "1H", "4H", "Always"], group=groupVWAP)
 
vwapOK = vwapMaxTF == "Always" or
     vwapMaxTF == "15m" and timeframe.in_seconds() <= timeframe.in_seconds("15") or
     vwapMaxTF == "30m" and timeframe.in_seconds() <= timeframe.in_seconds("30") or
     vwapMaxTF == "1H" and timeframe.in_seconds() <= timeframe.in_seconds("60") or
     vwapMaxTF == "4H" and timeframe.in_seconds() <= timeframe.in_seconds("240")
 
vwapValue = ta.vwap(vwapSrc)
plot(showVWAP and vwapOK ? vwapValue : na, "VWAP", color=vwapColor, linewidth=vwapWidth)
 
//====================================================
// 04 — PREMARKET
//====================================================
groupPM = "04 — Premarket"
showPM = input.bool(true, "Show PMH / PML", group=groupPM)
preMarketSession = input.session("0400-0930", "Pre-Market Session", group=groupPM)
pmhColor = input.color(color.orange, "PMH Color", group=groupPM)
pmlColor = input.color(color.aqua, "PML Color", group=groupPM)
pmhWidth = input.int(1, "PMH Width", minval=1, maxval=5, group=groupPM)
pmlWidth = input.int(1, "PML Width", minval=1, maxval=5, group=groupPM)
pmhStyleInput = input.string("Dotted", "PMH Style", options=["Solid", "Dashed", "Dotted"], group=groupPM)
pmlStyleInput = input.string("Dotted", "PML Style", options=["Solid", "Dashed", "Dotted"], group=groupPM)
showPMLabels = input.bool(true, "Show Labels", group=groupPM)
pmLabelOffset = input.int(3, "Label Distance", minval=1, maxval=50, group=groupPM)
pmLineLength = input.int(300, "Line Length", minval=1, maxval=500, group=groupPM)
 
getLineStyle(s) =>
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
 
pmhStyle = getLineStyle(pmhStyleInput)
pmlStyle = getLineStyle(pmlStyleInput)
 
ny = "America/New_York"
extTicker = ticker.new(syminfo.prefix, syminfo.ticker, session.extended)
 
fPMHigh() =>
    var float v = na
    nd = ta.change(time("D", "", ny)) != 0
    inside = not na(time(timeframe.period, preMarketSession, ny))
    if nd
        v := na
    if inside
        v := na(v) ? high : math.max(v, high)
    v
 
fPMLow() =>
    var float v = na
    nd = ta.change(time("D", "", ny)) != 0
    inside = not na(time(timeframe.period, preMarketSession, ny))
    if nd
        v := na
    if inside
        v := na(v) ? low : math.min(v, low)
    v
 
pmh = request.security(extTicker, timeframe.period, fPMHigh(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
pml = request.security(extTicker, timeframe.period, fPMLow(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
 
var line pmhLine = na
var line pmlLine = na
var label pmhLabel = na
var label pmlLabel = na
 
if barstate.islast
    if not na(pmhLine)
        line.delete(pmhLine)
    if not na(pmlLine)
        line.delete(pmlLine)
    if not na(pmhLabel)
        label.delete(pmhLabel)
    if not na(pmlLabel)
        label.delete(pmlLabel)
 
    if showPM and not na(pmh)
        pmhLine := line.new(bar_index - pmLineLength, pmh, bar_index, pmh, xloc=xloc.bar_index, color=pmhColor, width=pmhWidth, style=pmhStyle)
        if showPMLabels
            pmhLabel := label.new(bar_index + pmLabelOffset, pmh, "PMH", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=pmhColor, size=size.small)
 
    if showPM and not na(pml)
        pmlLine := line.new(bar_index - pmLineLength, pml, bar_index, pml, xloc=xloc.bar_index, color=pmlColor, width=pmlWidth, style=pmlStyle)
        if showPMLabels
            pmlLabel := label.new(bar_index + pmLabelOffset, pml, "PML", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=pmlColor, size=size.small)
 
//====================================================
// 05 — PREVIOUS DAY / WEEK LEVELS
//====================================================
groupLevels = "05 — Previous Levels"
 
showPDH = input.bool(true, "Show PDH", group=groupLevels)
showPDL = input.bool(true, "Show PDL", group=groupLevels)
showPWH = input.bool(true, "Show PWH", group=groupLevels)
showPWL = input.bool(true, "Show PWL", group=groupLevels)
 
levelLabelOffset = input.int(3, "Label Distance", minval=1, maxval=50, group=groupLevels)
levelLineLength = input.int(5, "Line Length", minval=1, maxval=50, group=groupLevels)
levelWidth = input.int(1, "Line Width", minval=1, maxval=5, group=groupLevels)
 
pdhColor = input.color(color.black, "PDH Color", group=groupLevels)
pdlColor = input.color(color.black, "PDL Color", group=groupLevels)
pwhColor = input.color(color.gray, "PWH Color", group=groupLevels)
pwlColor = input.color(color.gray, "PWL Color", group=groupLevels)
 
pdh = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_off)
pdl = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_off)
pwh = request.security(syminfo.tickerid, "W", high[1], lookahead=barmerge.lookahead_off)
pwl = request.security(syminfo.tickerid, "W", low[1], lookahead=barmerge.lookahead_off)
 
var line pdhLine = na
var line pdlLine = na
var line pwhLine = na
var line pwlLine = na
var label pdhLabel = na
var label pdlLabel = na
var label pwhLabel = na
var label pwlLabel = na
 
if barstate.islast
    if not na(pdhLine)
        line.delete(pdhLine)
    if not na(pdlLine)
        line.delete(pdlLine)
    if not na(pwhLine)
        line.delete(pwhLine)
    if not na(pwlLine)
        line.delete(pwlLine)
    if not na(pdhLabel)
        label.delete(pdhLabel)
    if not na(pdlLabel)
        label.delete(pdlLabel)
    if not na(pwhLabel)
        label.delete(pwhLabel)
    if not na(pwlLabel)
        label.delete(pwlLabel)
 
    if showPDH and not na(pdh)
        pdhLine := line.new(bar_index + levelLabelOffset - levelLineLength, pdh, bar_index + levelLabelOffset, pdh, xloc=xloc.bar_index, color=pdhColor, width=levelWidth)
        pdhLabel := label.new(bar_index + levelLabelOffset, pdh, "PDH", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=pdhColor, size=size.small)
 
    if showPDL and not na(pdl)
        pdlLine := line.new(bar_index + levelLabelOffset - levelLineLength, pdl, bar_index + levelLabelOffset, pdl, xloc=xloc.bar_index, color=pdlColor, width=levelWidth)
        pdlLabel := label.new(bar_index + levelLabelOffset, pdl, "PDL", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=pdlColor, size=size.small)
 
    if showPWH and not na(pwh)
        pwhLine := line.new(bar_index + levelLabelOffset - levelLineLength, pwh, bar_index + levelLabelOffset, pwh, xloc=xloc.bar_index, color=pwhColor, width=levelWidth)
        pwhLabel := label.new(bar_index + levelLabelOffset, pwh, "PWH", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=pwhColor, size=size.small)
 
    if showPWL and not na(pwl)
        pwlLine := line.new(bar_index + levelLabelOffset - levelLineLength, pwl, bar_index + levelLabelOffset, pwl, xloc=xloc.bar_index, color=pwlColor, width=levelWidth)
        pwlLabel := label.new(bar_index + levelLabelOffset, pwl, "PWL", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=pwlColor, size=size.small)
 
//====================================================
// 06 — ORB
//====================================================
groupORB = "06 — Opening Range"
 
showORB = input.bool(true, "Show ORB", group=groupORB)
orbMaxTF = input.int(15, "Max Timeframe (minutes)", minval=1, maxval=240, group=groupORB, tooltip="O ORB só é calculado e desenhado em timeframes iguais ou inferiores a este valor (em minutos).")
orbSession = input.session("0930-0945", "ORB Session", group=groupORB)
orbTimezone = input.string("America/New_York", "Timezone", options=["America/New_York", "Etc/UTC"], group=groupORB)
 
showORBMid = input.bool(true, "Show Midpoint", group=groupORB)
showBreakouts = input.bool(true, "Breakout Signals", group=groupORB)
breakoutsTodayOnly = input.bool(true, "Breakout Signals: Today Only", group=groupORB, tooltip="Mostra os sinais de breakout apenas no dia atual (sem histórico).")
showTargets = input.bool(true, "Show Targets", group=groupORB)
 
orbLineAdvance = input.int(2, "Line Advance (Candles)", minval=0, maxval=50, group=groupORB)
orbLineLength = input.int(20, "Line Length", minval=1, maxval=200, group=groupORB)
 
targetPercent = input.float(50.0, "Target Step %", minval=1, step=1, group=groupORB)
targetCount = input.int(3, "Target Count", minval=1, maxval=6, group=groupORB)
 
orbBullColor = input.color(color.lime, "Bull Color", group=groupORB)
orbBearColor = input.color(color.red, "Bear Color", group=groupORB)
orbMidColor = input.color(color.yellow, "Mid Color", group=groupORB)
orbTargetColor = input.color(color.gray, "Target Color", group=groupORB)
orbWidth = input.int(2, "Width", minval=1, maxval=5, group=groupORB)
 
orbTFOK = timeframe.isintraday and timeframe.in_seconds() <= orbMaxTF * 60
inORB = orbTFOK and not na(time(timeframe.period, orbSession, orbTimezone))
newORBDay = ta.change(time("D", "", orbTimezone)) != 0
 
// Dia atual (para limitar sinais ao dia da última barra)
lastDayStart = timestamp(orbTimezone, year(last_bar_time, orbTimezone), month(last_bar_time, orbTimezone), dayofmonth(last_bar_time, orbTimezone), 0, 0, 0)
barDayStart = timestamp(orbTimezone, year(time, orbTimezone), month(time, orbTimezone), dayofmonth(time, orbTimezone), 0, 0, 0)
isOrbToday = barDayStart == lastDayStart
 
var float orbHigh = na
var float orbLow = na
var int orbStartBar = na
var bool orbLocked = false
var line orbHighLine = na
var line orbLowLine = na
var line orbMidLine = na
var line[] orbTargets = array.new_line()
 
if newORBDay
    orbHigh := na
    orbLow := na
    orbStartBar := na
    orbLocked := false
 
    if not na(orbHighLine)
        line.delete(orbHighLine)
    if not na(orbLowLine)
        line.delete(orbLowLine)
    if not na(orbMidLine)
        line.delete(orbMidLine)
 
    while array.size(orbTargets) > 0
        line.delete(array.shift(orbTargets))
 
if inORB
    if na(orbStartBar)
        orbStartBar := bar_index
    orbHigh := na(orbHigh) ? high : math.max(orbHigh, high)
    orbLow := na(orbLow) ? low : math.min(orbLow, low)
else if not na(orbHigh) and not na(orbLow)
    orbLocked := true
 
orbMid = not na(orbHigh) and not na(orbLow) ? (orbHigh + orbLow) / 2.0 : na
orbRange = not na(orbHigh) and not na(orbLow) ? orbHigh - orbLow : na
 
// Linhas do ORB: apenas dia atual, apenas em timeframes <= Max Timeframe
if barstate.islast and showORB and orbTFOK and not na(orbHigh) and not na(orbLow) and not na(orbStartBar)
    if not na(orbHighLine)
        line.delete(orbHighLine)
    if not na(orbLowLine)
        line.delete(orbLowLine)
    if not na(orbMidLine)
        line.delete(orbMidLine)
 
    while array.size(orbTargets) > 0
        line.delete(array.shift(orbTargets))
 
    orbEnd = bar_index + orbLineAdvance + orbLineLength
 
    orbHighLine := line.new(orbStartBar, orbHigh, orbEnd, orbHigh, xloc=xloc.bar_index, color=orbBullColor, width=orbWidth)
    orbLowLine := line.new(orbStartBar, orbLow, orbEnd, orbLow, xloc=xloc.bar_index, color=orbBearColor, width=orbWidth)
 
    if showORBMid
        orbMidLine := line.new(orbStartBar, orbMid, orbEnd, orbMid, xloc=xloc.bar_index, color=orbMidColor, width=1, style=line.style_dashed)
 
    if showTargets and orbLocked and not na(orbRange)
        step = orbRange * targetPercent / 100.0
 
        for i = 1 to targetCount
            up = orbHigh + step * i
            dn = orbLow - step * i
 
            array.push(orbTargets, line.new(orbStartBar, up, orbEnd, up, xloc=xloc.bar_index, color=orbTargetColor, width=1, style=line.style_dotted))
            array.push(orbTargets, line.new(orbStartBar, dn, orbEnd, dn, xloc=xloc.bar_index, color=orbTargetColor, width=1, style=line.style_dotted))
 
// ta.crossover/crossunder calculados fora de condições (v6 avalia and/or de forma "lazy")
bullCross = ta.crossover(close, orbHigh)
bearCross = ta.crossunder(close, orbLow)
 
orbBullBreak = showBreakouts and orbTFOK and orbLocked and bullCross and (not breakoutsTodayOnly or isOrbToday)
orbBearBreak = showBreakouts and orbTFOK and orbLocked and bearCross and (not breakoutsTodayOnly or isOrbToday)
 
plotshape(orbBullBreak, title="ORB Bull", style=shape.triangleup, location=location.belowbar, color=orbBullColor, size=size.small)
plotshape(orbBearBreak, title="ORB Bear", style=shape.triangledown, location=location.abovebar, color=orbBearColor, size=size.small)
 
//====================================================
// 07 — MOVING AVERAGES
//====================================================
groupMA = "07 — Moving Averages"
 
maType1 = input.string("EMA", "MA 1 Type", options=["EMA","SMA","WMA","HMA","RMA","VWMA"], group=groupMA)
maLen1 = input.int(9, "MA 1 Length", minval=1, group=groupMA)
maSrc1 = input.source(close, "MA 1 Source", group=groupMA)
maColor1 = input.color(color.aqua, "MA 1 Color", group=groupMA)
maWidth1 = input.int(1, "MA 1 Width", minval=1, maxval=5, group=groupMA)
 
maType2 = input.string("EMA", "MA 2 Type", options=["EMA","SMA","WMA","HMA","RMA","VWMA"], group=groupMA)
maLen2 = input.int(20, "MA 2 Length", minval=1, group=groupMA)
maSrc2 = input.source(close, "MA 2 Source", group=groupMA)
maColor2 = input.color(color.blue, "MA 2 Color", group=groupMA)
maWidth2 = input.int(1, "MA 2 Width", minval=1, maxval=5, group=groupMA)
 
maType3 = input.string("EMA", "MA 3 Type", options=["EMA","SMA","WMA","HMA","RMA","VWMA"], group=groupMA)
maLen3 = input.int(30, "MA 3 Length", minval=1, group=groupMA)
maSrc3 = input.source(close, "MA 3 Source", group=groupMA)
maColor3 = input.color(color.orange, "MA 3 Color", group=groupMA)
maWidth3 = input.int(1, "MA 3 Width", minval=1, maxval=5, group=groupMA)
 
maType4 = input.string("EMA", "MA 4 Type", options=["EMA","SMA","WMA","HMA","RMA","VWMA"], group=groupMA)
maLen4 = input.int(50, "MA 4 Length", minval=1, group=groupMA)
maSrc4 = input.source(close, "MA 4 Source", group=groupMA)
maColor4 = input.color(color.fuchsia, "MA 4 Color", group=groupMA)
maWidth4 = input.int(1, "MA 4 Width", minval=1, maxval=5, group=groupMA)
 
maCalc(src, len, typ) =>
    typ == "EMA" ? ta.ema(src, len) :
     typ == "SMA" ? ta.sma(src, len) :
     typ == "WMA" ? ta.wma(src, len) :
     typ == "HMA" ? ta.hma(src, len) :
     typ == "RMA" ? ta.rma(src, len) :
     ta.vwma(src, len)
 
ma1 = maCalc(maSrc1, maLen1, maType1)
ma2 = maCalc(maSrc2, maLen2, maType2)
ma3 = maCalc(maSrc3, maLen3, maType3)
ma4 = maCalc(maSrc4, maLen4, maType4)
 
plot(ma1, "MA 1", color=maColor1, linewidth=maWidth1)
plot(ma2, "MA 2", color=maColor2, linewidth=maWidth2)
plot(ma3, "MA 3", color=maColor3, linewidth=maWidth3)
plot(ma4, "MA 4", color=maColor4, linewidth=maWidth4)
 
//====================================================
// 08 — CLOUDS
//====================================================
groupCloud = "08 — Clouds"
 
showCloud1 = input.bool(true, "Show Cloud 1", group=groupCloud)
showCloud2 = input.bool(true, "Show Cloud 2", group=groupCloud)
 
cloud1BullColor = input.color(color.green, "Cloud 1 Bull", group=groupCloud)
cloud1BearColor = input.color(color.red, "Cloud 1 Bear", group=groupCloud)
cloud1Transparency = input.int(85, "Cloud 1 Transparency", minval=0, maxval=100, group=groupCloud)
 
cloud2BullColor = input.color(color.teal, "Cloud 2 Bull", group=groupCloud)
cloud2BearColor = input.color(color.purple, "Cloud 2 Bear", group=groupCloud)
cloud2Transparency = input.int(90, "Cloud 2 Transparency", minval=0, maxval=100, group=groupCloud)
 
cloud1Bull = ma1 >= ma2
cloud2Bull = ma3 >= ma4
 
cloud1A = plot(showCloud1 ? ma1 : na, "Cloud 1 A", color=color.new(color.white, 100))
cloud1B = plot(showCloud1 ? ma2 : na, "Cloud 1 B", color=color.new(color.white, 100))
cloud2A = plot(showCloud2 ? ma3 : na, "Cloud 2 A", color=color.new(color.white, 100))
cloud2B = plot(showCloud2 ? ma4 : na, "Cloud 2 B", color=color.new(color.white, 100))
 
fill(cloud1A, cloud1B, color=showCloud1 ? color.new(cloud1Bull ? cloud1BullColor : cloud1BearColor, cloud1Transparency) : na)
fill(cloud2A, cloud2B, color=showCloud2 ? color.new(cloud2Bull ? cloud2BullColor : cloud2BearColor, cloud2Transparency) : na)
 
//====================================================
// 09 — MARKET STRUCTURE (SWING PIVOTS, estilo dgt, sem zigzag)
//====================================================
groupStructure = "09 — Structure"
 
showStructure = input.bool(true, "Show Swing Pivots", group=groupStructure)
swingDepth = input.int(11, "Depth", minval=1, group=groupStructure, tooltip="Número de barras para confirmar um swing. Valores maiores = estrutura mais suave.")
swingDevMult = input.float(3.0, "Deviation (ATR)", minval=0.0, step=0.1, group=groupStructure, tooltip="Movimento mínimo (baseado em ATR) para confirmar um novo swing. Valores maiores filtram ruído.")
showTempSwings = input.bool(true, "Show Provisional Swings", group=groupStructure, tooltip="Mostra o último swing ainda não confirmado (pode repintar).")
 
swingHighColor = input.color(#d4a5a5, "Swing High Color", group=groupStructure)
swingLowColor = input.color(#8faadc, "Swing Low Color", group=groupStructure)
swingTempColor = input.color(#0000f0, "Provisional Color", group=groupStructure)
 
swingSizeInput = input.string("Small", "Label Size", options=["Tiny","Small","Normal","Large"], group=groupStructure)
swingDistance = input.float(0.0, "Extra Distance (ATR)", minval=0.0, maxval=20.0, step=0.1, group=groupStructure, tooltip="Afasta as marcas dos máximos/mínimos, em múltiplos de ATR.")
 
// Usados apenas pelo dashboard multi-timeframe (HH/HL/LH/LL)
structureDepth = input.int(11, "Dashboard Depth", minval=2, maxval=50, group=groupStructure, tooltip="Usado apenas na estrutura multi-timeframe do dashboard.")
structureDeviation = input.float(3.0, "Dashboard Deviation %", minval=0.1, maxval=20.0, step=0.1, group=groupStructure, tooltip="Usado apenas na estrutura multi-timeframe do dashboard.")
 
swingSize = swingSizeInput == "Tiny" ? size.tiny :
     swingSizeInput == "Normal" ? size.normal :
     swingSizeInput == "Large" ? size.large :
     size.small
 
atrMain = ta.atr(14)
swingDevThresh = ta.atr(10) / close * 100 * swingDevMult
 
swingPivot(src, depth, isHigh) =>
    length = int(depth / 2)
    c = nz(src[length])
    ok = true
    for i = 0 to depth
        if isHigh and src[i] > c
            ok := false
        if not isHigh and src[i] < c
            ok := false
    if ok
        [bar_index[length], c]
    else
        [int(na), float(na)]
 
[swIH, swPH] = swingPivot(high, swingDepth, true)
[swIL, swPL] = swingPivot(low, swingDepth, false)
 
var int swILast = na
var float swPLast = na
var bool swIsHighLast = false
var bool swHasLeg = false
var int swStartI = na
var float swStartP = na
var label swTmpH = na
var label swTmpL = na
 
swOff = nz(atrMain, 0.0) * swingDistance
 
if not na(swIH)
    devH = na(swPLast) ? 100.0 : 100.0 * (swPH - swPLast) / swPH
    foundH = false
 
    if swHasLeg and swIsHighLast
        // mesma direção: só atualiza se o novo máximo for mais alto
        if swPH > swPLast
            foundH := true
    else if math.abs(devH) > swingDevThresh
        // inversão: confirma o swing de início da perna anterior
        foundH := true
        if showStructure and not na(swStartP) and bar_index - swStartI <= 500
            label.new(swStartI, swStartP + swOff, "▼", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_down, color=color.new(color.white, 100), textcolor=swingHighColor, size=swingSize, textalign=text.align_center, tooltip="Swing High\nPrice: " + str.tostring(swStartP, format.mintick))
        swStartI := swILast
        swStartP := swPLast
 
    if foundH
        swILast := swIH
        swPLast := swPH
        swIsHighLast := true
        swHasLeg := true
 
        if not na(swTmpH)
            label.delete(swTmpH)
        if showStructure and showTempSwings
            swTmpH := label.new(swIH, swPH + swOff, "●\n▼", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_down, color=color.new(color.white, 100), textcolor=swingTempColor, size=swingSize, textalign=text.align_center, tooltip="Temporary Swing High\nPrice: " + str.tostring(swPH, format.mintick) + "\n\n⚠ Provisional level\nSubject to repaint until structure confirms")
 
else if not na(swIL)
    devL = na(swPLast) ? 100.0 : 100.0 * (swPL - swPLast) / swPL
    foundL = false
 
    if swHasLeg and not swIsHighLast
        // mesma direção: só atualiza se o novo mínimo for mais baixo
        if swPL < swPLast
            foundL := true
    else if math.abs(devL) > swingDevThresh
        // inversão: confirma o swing de início da perna anterior
        foundL := true
        if showStructure and not na(swStartP) and bar_index - swStartI <= 500
            label.new(swStartI, swStartP - swOff, "▲", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_up, color=color.new(color.white, 100), textcolor=swingLowColor, size=swingSize, textalign=text.align_center, tooltip="Swing Low\nPrice: " + str.tostring(swStartP, format.mintick))
        swStartI := swILast
        swStartP := swPLast
 
    if foundL
        swILast := swIL
        swPLast := swPL
        swIsHighLast := false
        swHasLeg := true
 
        if not na(swTmpL)
            label.delete(swTmpL)
        if showStructure and showTempSwings
            swTmpL := label.new(swIL, swPL - swOff, "▲\n●", xloc=xloc.bar_index, yloc=yloc.price, style=label.style_label_up, color=color.new(color.white, 100), textcolor=swingTempColor, size=swingSize, textalign=text.align_center, tooltip="Temporary Swing Low\nPrice: " + str.tostring(swPL, format.mintick) + "\n\n⚠ Provisional level\nSubject to repaint until structure confirms")
 
//====================================================
// 10 — THE STRAT
//====================================================
groupStrat = "10 — The Strat"
 
showStrat = input.bool(true, "Show Candle Numbers", group=groupStrat)
stratCandles = input.int(5, "Last Candles", minval=1, maxval=50, group=groupStrat, tooltip="Número de velas (a contar da mais recente) onde aparecem os números do Strat.")
stratPosInput = input.string("Below Candle", "Numbers Position", options=["Above Candle", "Below Candle"], group=groupStrat)
stratDistance = input.float(0.4, "Numbers Distance (ATR)", minval=0.0, maxval=10.0, step=0.1, group=groupStrat)
stratSizeInput = input.string("Small", "Text Size", options=["Tiny","Small","Normal","Large"], group=groupStrat)
 
strat1Color = input.color(color.yellow, "Inside (1) Color", group=groupStrat)
strat2UColor = input.color(color.lime, "2U Color", group=groupStrat)
strat2DColor = input.color(color.red, "2D Color", group=groupStrat)
strat3Color = input.color(color.fuchsia, "Outside (3) Color", group=groupStrat)
 
showStratSetups = input.bool(true, "Show Setup Labels", group=groupStrat, tooltip="Mostra o nome do setup (2-1-2, 3-1-2, 2-2, 3-2-2) no lado oposto aos números.")
stratSetupBull = input.color(color.lime, "Setup Bull Color", group=groupStrat)
stratSetupBear = input.color(color.red, "Setup Bear Color", group=groupStrat)
stratClosedOnly = input.bool(true, "Dashboard / 0DTE Use Closed Candles Only", group=groupStrat)
 
stratSize = stratSizeInput == "Tiny" ? size.tiny :
     stratSizeInput == "Normal" ? size.normal :
     stratSizeInput == "Large" ? size.large :
     size.small
 
// Códigos: 1 = inside, 2 = 2U, -2 = 2D, 3 = outside, 0 = sem dados
stratCode = na(high[1]) ? 0 :
     high > high[1] and low < low[1] ? 3 :
     high > high[1] ? 2 :
     low < low[1] ? -2 : 1
 
f_cname(c) =>
    c == 3 ? "3" : c == 2 ? "2U" : c == -2 ? "2D" : c == 1 ? "1" : "-"
 
f_ccolor(c) =>
    c == 3 ? strat3Color : c == 2 ? strat2UColor : c == -2 ? strat2DColor : strat1Color
 
// Setups (c0 = vela mais recente). Positivo = bull, negativo = bear.
// 1: 2-1-2 Rev | 2: 2-1-2 Cont | 3: 3-1-2 | 4: 2-2 Rev | 5: 3-2-2
f_setup(c0, c1, c2) =>
    c2 == -2 and c1 == 1 and c0 == 2 ? 1 :
     c2 == 2 and c1 == 1 and c0 == -2 ? -1 :
     c2 == 2 and c1 == 1 and c0 == 2 ? 2 :
     c2 == -2 and c1 == 1 and c0 == -2 ? -2 :
     c2 == 3 and c1 == 1 and c0 == 2 ? 3 :
     c2 == 3 and c1 == 1 and c0 == -2 ? -3 :
     c2 == 3 and c1 == -2 and c0 == 2 ? 5 :
     c2 == 3 and c1 == 2 and c0 == -2 ? -5 :
     c1 == -2 and c0 == 2 ? 4 :
     c1 == 2 and c0 == -2 ? -4 : 0
 
f_setupName(s) =>
    a = math.abs(s)
    a == 1 ? "2-1-2 Rev" : a == 2 ? "2-1-2 Cont" : a == 3 ? "3-1-2" : a == 4 ? "2-2 Rev" : a == 5 ? "3-2-2" : ""
 
setupSeries = f_setup(stratCode, stratCode[1], stratCode[2])
 
var label[] stratLabels = array.new_label()
 
if barstate.islast
    while array.size(stratLabels) > 0
        label.delete(array.pop(stratLabels))
 
    if showStrat or showStratSetups
        atrNow = nz(atrMain, 0.0)
        n = math.min(stratCandles, bar_index + 1)
        numbersAbove = stratPosInput == "Above Candle"
 
        for i = 0 to n - 1
            c = stratCode[i]
            s = setupSeries[i]
            hi = high[i]
            lo = low[i]
            off = atrNow * stratDistance
            yAbove = hi + off
            yBelow = lo - off
 
            if showStrat and c != 0
                array.push(stratLabels, label.new(bar_index - i, numbersAbove ? yAbove : yBelow, f_cname(c), xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=f_ccolor(c), size=stratSize))
 
            if showStratSetups and s != 0
                setupTxt = f_setupName(s) + (s > 0 ? " ▲" : " ▼")
                array.push(stratLabels, label.new(bar_index - i, numbersAbove ? yBelow : yAbove, setupTxt, xloc=xloc.bar_index, yloc=yloc.price, style=label.style_none, textcolor=s > 0 ? stratSetupBull : stratSetupBear, size=stratSize))
 
//====================================================
// 11 — MTF STRUCTURE / TREND
//====================================================
getMTFState() =>
    e = ta.ema(close, mainLen)
    trd = close > e ? "BULL" : close < e ? "BEAR" : "NEUTRAL"
 
    ph = ta.pivothigh(high, structureDepth, structureDepth)
    pl = ta.pivotlow(low, structureDepth, structureDepth)
 
    var float h = na
    var float l = na
    var int d = 0
    var string stH = ""
    var string stL = ""
 
    if not na(ph)
        okH = d <= 0 or na(l) or ph >= l * (1 + structureDeviation / 100)
        if okH
            oldH = h
            h := ph
            d := 1
            stH := na(oldH) ? "H" : ph > oldH ? "HH" : "LH"
 
    if not na(pl)
        okL = d >= 0 or na(h) or pl <= h * (1 - structureDeviation / 100)
        if okL
            oldL = l
            l := pl
            d := -1
            stL := na(oldL) ? "L" : pl > oldL ? "HL" : "LL"
 
    st = d == 1 ? stH : d == -1 ? stL : ""
    [trd, st]
 
[trend15, struct15] = request.security(syminfo.tickerid, "15", getMTFState())
[trend1H, struct1H] = request.security(syminfo.tickerid, "60", getMTFState())
[trend4H, struct4H] = request.security(syminfo.tickerid, "240", getMTFState())
[trend1D, struct1D] = request.security(syminfo.tickerid, "D", getMTFState())
[trendW, structW] = request.security(syminfo.tickerid, "W", getMTFState())
 
//====================================================
// 12 — 0DTE SETUP (score simplificado: nível + RSI + confirmação)
//====================================================
groupOdte = "12 — 0DTE Setup"
 
showOdte = input.bool(true, "Show 0DTE Row in Dashboard", group=groupOdte)
odteRsiLen = input.int(14, "RSI Length", minval=2, maxval=50, group=groupOdte)
odteOversold = input.float(30.0, "RSI Oversold (Call)", minval=1.0, maxval=50.0, step=1.0, group=groupOdte)
odteOverbought = input.float(70.0, "RSI Overbought (Put)", minval=50.0, maxval=99.0, step=1.0, group=groupOdte)
odteTolATR = input.float(0.25, "Level Tolerance (ATR)", minval=0.0, maxval=3.0, step=0.05, group=groupOdte)
odteVolMult = input.float(1.5, "Volume Spike (x avg 20)", minval=1.0, maxval=10.0, step=0.1, group=groupOdte)
odteMinScore = input.int(7, "Minimum Score (max 12)", minval=1, maxval=12, group=groupOdte)
odteLookback = input.int(3, "Strat / ORB Lookback (bars)", minval=1, maxval=20, group=groupOdte)
odteSession = input.session("0935-1545", "Active Window (NY time)", group=groupOdte)
showOdteMarkers = input.bool(false, "Show Markers On Chart", group=groupOdte)
 
odteRSI = ta.rsi(close, odteRsiLen)
volAvg = ta.sma(volume, 20)
volSpike = volume > volAvg * odteVolMult
 
candleBody = math.abs(close - open)
lowWick = math.min(open, close) - low
upWick = high - math.max(open, close)
bodyRef = math.max(candleBody, syminfo.mintick)
rejBull = lowWick >= 1.5 * bodyRef and lowWick >= 0.3 * atrMain
rejBear = upWick >= 1.5 * bodyRef and upWick >= 0.3 * atrMain
 
orbHiLvl = orbLocked ? orbHigh : na
orbLoLvl = orbLocked ? orbLow : na
 
nearLevel(lvl, t, isBull) =>
    not na(lvl) and (isBull ? (low <= lvl + t and close >= lvl) : (high >= lvl - t and close <= lvl))
 
lvlCount(isBull, t) =>
    (nearLevel(pdh, t, isBull) ? 1 : 0) +
     (nearLevel(pdl, t, isBull) ? 1 : 0) +
     (nearLevel(pwh, t, isBull) ? 1 : 0) +
     (nearLevel(pwl, t, isBull) ? 1 : 0) +
     (nearLevel(pmh, t, isBull) ? 1 : 0) +
     (nearLevel(pml, t, isBull) ? 1 : 0) +
     (nearLevel(orbHiLvl, t, isBull) ? 1 : 0) +
     (nearLevel(orbLoLvl, t, isBull) ? 1 : 0) +
     (nearLevel(vwapValue, t, isBull) ? 1 : 0)
 
odteTol = nz(atrMain, 0.0) * odteTolATR
lvlBull = lvlCount(true, odteTol)
lvlBear = lvlCount(false, odteTol)
 
lvlPtsBull = lvlBull >= 2 ? 4 : lvlBull == 1 ? 3 : 0
lvlPtsBear = lvlBear >= 2 ? 4 : lvlBear == 1 ? 3 : 0
 
rsiPtsBull = odteRSI <= odteOversold ? 2 : odteRSI <= odteOversold + 5 ? 1 : 0
rsiPtsBear = odteRSI >= odteOverbought ? 2 : odteRSI >= odteOverbought - 5 ? 1 : 0
 
bsStratBull = ta.barssince(setupSeries > 0)
bsStratBear = ta.barssince(setupSeries < 0)
bsOrbBull = ta.barssince(orbBullBreak)
bsOrbBear = ta.barssince(orbBearBreak)
 
stratPtsBull = bsStratBull <= odteLookback - 1 ? 2 : 0
stratPtsBear = bsStratBear <= odteLookback - 1 ? 2 : 0
orbPtsBull = bsOrbBull <= odteLookback - 1 and close > vwapValue ? 1 : 0
orbPtsBear = bsOrbBear <= odteLookback - 1 and close < vwapValue ? 1 : 0
 
// Pontuação (máx 12): nível 0-4 | RSI 0-2 | Strat 0-2 | volume 0-1 | pavio 0-1 | tendência 15m 0-1 | ORB 0-1
bullPts = lvlPtsBull + rsiPtsBull + stratPtsBull + (volSpike ? 1 : 0) + (rejBull ? 1 : 0) + (trend15 == "BULL" ? 1 : 0) + orbPtsBull
bearPts = lvlPtsBear + rsiPtsBear + stratPtsBear + (volSpike ? 1 : 0) + (rejBear ? 1 : 0) + (trend15 == "BEAR" ? 1 : 0) + orbPtsBear
 
inOdteWindow = timeframe.isintraday and not na(time(timeframe.period, odteSession, ny))
 
odteCall = inOdteWindow and bullPts >= odteMinScore and bullPts > bearPts
odtePut = inOdteWindow and bearPts >= odteMinScore and bearPts > bullPts
odteCallSig = odteCall and not odteCall[1]
odtePutSig = odtePut and not odtePut[1]
 
plotshape(showOdteMarkers and odteCallSig, title="0DTE Call", style=shape.diamond, location=location.belowbar, color=color.lime, size=size.tiny, text="C")
plotshape(showOdteMarkers and odtePutSig, title="0DTE Put", style=shape.diamond, location=location.abovebar, color=color.red, size=size.tiny, text="P")
 
//====================================================
// 13 — DASHBOARD
//====================================================
groupDash = "13 — Dashboard"
 
showDashboard = input.bool(true, "Show Dashboard", group=groupDash)
 
dashPosition = input.string(
     "Top Right",
     "Position",
     options=["Top Left","Top Center","Top Right","Middle Left","Middle Center","Middle Right","Bottom Left","Bottom Center","Bottom Right"],
     group=groupDash)
 
dashSizeInput = input.string("Small", "Text Size", options=["Tiny","Small","Normal","Large"], group=groupDash)
 
dashBG = input.color(color.new(color.black, 15), "Background", group=groupDash)
dashHeaderBG = input.color(color.new(color.gray, 70), "Header Background", group=groupDash)
dashBull = input.color(color.lime, "Bull Color", group=groupDash)
dashBear = input.color(color.red, "Bear Color", group=groupDash)
dashNeutral = input.color(color.gray, "Neutral Color", group=groupDash)
dashText = input.color(color.white, "Text Color", group=groupDash)
dashBorder = input.color(color.gray, "Border Color", group=groupDash)
 
dashSize = dashSizeInput == "Tiny" ? size.tiny :
     dashSizeInput == "Normal" ? size.normal :
     dashSizeInput == "Large" ? size.large :
     size.small
 
dashPos = dashPosition == "Top Left" ? position.top_left :
     dashPosition == "Top Center" ? position.top_center :
     dashPosition == "Top Right" ? position.top_right :
     dashPosition == "Middle Left" ? position.middle_left :
     dashPosition == "Middle Center" ? position.middle_center :
     dashPosition == "Middle Right" ? position.middle_right :
     dashPosition == "Bottom Left" ? position.bottom_left :
     dashPosition == "Bottom Center" ? position.bottom_center :
     position.bottom_right
 
trendColor(v) =>
    v == "BULL" ? dashBull : v == "BEAR" ? dashBear : dashNeutral
 
structureColor(v) =>
    v == "HH" or v == "HL" ? dashBull :
     v == "LH" or v == "LL" ? dashBear :
     dashNeutral
 
// Bias = tendência + estrutura alinhadas
biasOf(t, s) =>
    t == "BULL" and (s == "HH" or s == "HL") ? "BULL" :
     t == "BEAR" and (s == "LH" or s == "LL") ? "BEAR" : "MIXED"
 
var table dash = table.new(position.top_right, 4, 10, border_width=1, border_color=dashBorder)
 
mtfRow(r, name, t, s) =>
    b = biasOf(t, s)
    table.cell(dash, 0, r, name, text_color=dashText, text_size=dashSize, bgcolor=dashBG)
    table.cell(dash, 1, r, t, text_color=color.white, text_size=dashSize, bgcolor=trendColor(t))
    table.cell(dash, 2, r, s, text_color=color.white, text_size=dashSize, bgcolor=structureColor(s))
    table.cell(dash, 3, r, b, text_color=color.white, text_size=dashSize, bgcolor=trendColor(b))
 
// Valores usados no dashboard (vela fechada ou atual)
sh = stratClosedOnly ? 1 : 0
dSetup = setupSeries[sh]
dC0 = stratCode[sh]
dC1 = stratCode[sh + 1]
dC2 = stratCode[sh + 2]
dBull = bullPts[sh]
dBear = bearPts[sh]
dCall = odteCall[sh]
dPut = odtePut[sh]
dHigh = high[sh]
dLow = low[sh]
dRSI = odteRSI[sh]
 
if barstate.islast
    table.set_position(dash, dashPos)
 
    if showDashboard
        table.cell(dash, 0, 0, syminfo.ticker, text_color=dashText, text_size=dashSize, bgcolor=dashHeaderBG)
        table.cell(dash, 1, 0, "TREND", text_color=dashText, text_size=dashSize, bgcolor=dashHeaderBG)
        table.cell(dash, 2, 0, "STRUCTURE", text_color=dashText, text_size=dashSize, bgcolor=dashHeaderBG)
        table.cell(dash, 3, 0, "BIAS", text_color=dashText, text_size=dashSize, bgcolor=dashHeaderBG)
 
        table.cell(dash, 0, 1, "MAIN", text_color=dashText, text_size=dashSize, bgcolor=dashBG)
        table.cell(dash, 1, 1, mainTrend, text_color=color.white, text_size=dashSize, bgcolor=trendColor(mainTrend))
        table.cell(dash, 2, 1, "", text_color=dashText, text_size=dashSize, bgcolor=dashBG)
        table.cell(dash, 3, 1, "", text_color=dashText, text_size=dashSize, bgcolor=dashBG)
 
        mtfRow(2, "15M", trend15, struct15)
        mtfRow(3, "1H", trend1H, struct1H)
        mtfRow(4, "4H", trend4H, struct4H)
        mtfRow(5, "1D", trend1D, struct1D)
        mtfRow(6, "W", trendW, structW)
 
        // --- STRAT ---
        setupTxt = dSetup != 0 ? f_setupName(dSetup) : dC0 == 1 ? "INSIDE" : "NONE"
        setupCol = dSetup > 0 ? dashBull : dSetup < 0 ? dashBear : dashNeutral
        setupDir = dSetup > 0 ? "BULL" : dSetup < 0 ? "BEAR" : "-"
 
        table.cell(dash, 0, 7, "STRAT", text_color=dashText, text_size=dashSize, bgcolor=dashBG)
        table.cell(dash, 1, 7, f_cname(dC2) + "-" + f_cname(dC1) + "-" + f_cname(dC0), text_color=dashText, text_size=dashSize, bgcolor=dashBG)
        table.cell(dash, 2, 7, setupTxt, text_color=color.white, text_size=dashSize, bgcolor=setupCol)
        table.cell(dash, 3, 7, setupDir, text_color=color.white, text_size=dashSize, bgcolor=setupCol)
 
        // --- 0DTE ---
        odteStatus = not showOdte ? "" : not inOdteWindow ? "OFF" : dCall ? "CALL" : dPut ? "PUT" : "WAIT"
        odteCol = odteStatus == "CALL" ? dashBull : odteStatus == "PUT" ? dashBear : dashNeutral
 
        if showOdte
            table.cell(dash, 0, 8, "0DTE", text_color=dashText, text_size=dashSize, bgcolor=dashBG)
            table.cell(dash, 1, 8, odteStatus, text_color=color.white, text_size=dashSize, bgcolor=odteCol)
            table.cell(dash, 2, 8, "C " + str.tostring(dBull) + " / P " + str.tostring(dBear), text_color=dashText, text_size=dashSize, bgcolor=dashBG)
            table.cell(dash, 3, 8, "RSI " + str.tostring(dRSI, "#.0"), text_color=dashText, text_size=dashSize, bgcolor=dashBG)
 
        // --- PLAN (entrada / stop, ou gatilhos da inside bar) ---
        isCall = odteStatus == "CALL"
        isPut = odteStatus == "PUT"
        isInside = dC0 == 1
 
        planA = isCall ? "▲ > " + str.tostring(dHigh, format.mintick) : isPut ? "▼ < " + str.tostring(dLow, format.mintick) : isInside ? "▲ > " + str.tostring(dHigh, format.mintick) : "-"
        planB = isCall ? "SL < " + str.tostring(dLow, format.mintick) : isPut ? "SL > " + str.tostring(dHigh, format.mintick) : isInside ? "▼ < " + str.tostring(dLow, format.mintick) : "-"
        planC = isCall ? "CALL" : isPut ? "PUT" : isInside ? "INSIDE" : "-"
        planCol = isCall ? dashBull : isPut ? dashBear : isInside ? dashNeutral : dashBG
 
        table.cell(dash, 0, 9, "PLAN", text_color=dashText, text_size=dashSize, bgcolor=dashBG)
        table.cell(dash, 1, 9, planA, text_color=dashText, text_size=dashSize, bgcolor=dashBG)
        table.cell(dash, 2, 9, planB, text_color=dashText, text_size=dashSize, bgcolor=dashBG)
        table.cell(dash, 3, 9, planC, text_color=color.white, text_size=dashSize, bgcolor=planCol)
    else
        table.clear(dash, 0, 0, 3, 9)
 
//====================================================
// 14 — ALERTS
//====================================================
alertcondition(orbBullBreak, "ORB Bull Breakout", "{{ticker}}: ORB bull breakout")
alertcondition(orbBearBreak, "ORB Bear Breakout", "{{ticker}}: ORB bear breakout")
alertcondition(setupSeries > 0, "Strat Bull Setup", "{{ticker}}: Strat bullish setup")
alertcondition(setupSeries < 0, "Strat Bear Setup", "{{ticker}}: Strat bearish setup")
alertcondition(odteCallSig, "0DTE Call Setup", "{{ticker}}: 0DTE CALL setup")
alertcondition(odtePutSig, "0DTE Put Setup", "{{ticker}}: 0DTE PUT setup")

← 返回列表