3CandleWar

CryptoZoso · study · 384 行 · 点赞 436 · TradingView 原页

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

Pine Script

//@version=6
indicator("3CandleWar", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
// ============================================================
// INPUT
// ============================================================
grpLines    = "Linee C1"
showLines   = input.bool(true, "Mostra linee max/min di C1", group=grpLines)
maxHistory  = input.int(50, "Setup confermati (C1-C2-C3 riusciti) da mantenere a video", minval=5, maxval=200, group=grpLines)
lineColor   = input.color(color.new(color.gray, 60), "Colore linee (C1 in attesa di C2)", group=grpLines)
setupColor  = input.color(color.new(color.fuchsia, 0), "Colore linee (C2 valido, in attesa di C3)", group=grpLines)
 
grpSig      = "Segnali Pattern"
showBuy     = input.bool(true,  "Mostra segnali BUY", group=grpSig)
showSell    = input.bool(true,  "Mostra segnali SELL (speculare)", group=grpSig)
buyColor    = input.color(color.yellow, "Colore stella Buy", group=grpSig)
sellColor   = input.color(color.red,    "Colore stella Sell", group=grpSig)
closeToleranceATR = input.float(0.01, "Tolleranza chiusura C3 rispetto a C1 (in ATR, 0 = chiusura netta)", minval=0, step=0.01, group=grpSig)
 
grpMA       = "Filtro Media Mobile"
useMaFilter = input.bool(true, "Attiva filtro trend con media mobile", group=grpMA)
maTF        = input.timeframe("5", "Timeframe media", group=grpMA)
maLen       = input.int(20, "Periodo SMA", minval=1, group=grpMA)
maSrc       = input.source(close, "Sorgente", group=grpMA)
showMaPlot  = input.bool(true, "Mostra la media sul grafico", group=grpMA)
maDynamicColor = input.bool(true, "Colore media dinamico in base al trend", group=grpMA)
maColorUp   = input.color(color.lime, "Colore media (prezzo sopra)", group=grpMA)
maColorDown = input.color(color.red,  "Colore media (prezzo sotto)", group=grpMA)
maColorFlat = input.color(color.aqua, "Colore media (fisso, se dinamico disattivo)", group=grpMA)
 
grpOB           = "Order Block"
obEnable        = input.bool(true, "Attiva rilevamento Order Block", group=grpOB)
showObBoxes     = input.bool(true, "Mostra box Order Block a grafico", group=grpOB)
obRealtimeDraw  = input.bool(true, "Disegna OB anche sulla candela in formazione (repainting)", group=grpOB)
useDisplacement = input.bool(true, "Richiedi displacement (rottura forte)", group=grpOB)
atrLen          = input.int(14, "Periodo ATR (displacement)", minval=1, group=grpOB)
dispMult        = input.float(1.2, "Moltiplicatore ATR per displacement", minval=0.1, step=0.1, group=grpOB)
obBoxCount      = input.int(5, "Numero massimo OB per lato a video", minval=1, maxval=20, group=grpOB)
obMitigateOnClose = input.bool(true, "Mitigazione su chiusura (altrimenti su wick)", group=grpOB)
obProximityATR  = input.float(0.5, "Margine 'a ridosso' (in ATR)", minval=0, step=0.1, group=grpOB)
obBypassMaOnTouch = input.bool(true, "Bypassa filtro MA se C1 o C2 toccano un OB concorde", group=grpOB)
obBorderTransp  = input.int(70, "Trasparenza bordo OB (0 = pieno, 100 = invisibile)", minval=0, maxval=100, group=grpOB)
bullObColor     = input.color(color.new(color.teal, 80), "Colore box Bullish OB", group=grpOB)
bearObColor     = input.color(color.new(color.orange, 80), "Colore box Bearish OB", group=grpOB)
warnColor       = input.color(color.new(color.fuchsia, 0), "Colore label warning (OB lato opposto)", group=grpOB)
 
grpDbg      = "Debug"
dbgOB       = input.bool(false, "Debug: mostra stato tocco OB su C1/C2 e tolleranza C3", group=grpDbg)
 
// ============================================================
// STATO
// ============================================================
var int   state       = 0
var float c1High      = na
var float c1Low       = na
var line  c1HiLine    = na
var line  c1LoLine    = na
var bool  isBuySetup  = false
var bool  isSellSetup = false
 
// Flag: C1 o C2 hanno toccato un OB concorde
var bool c1c2TouchedBullOB = false
var bool c1c2TouchedBearOB = false
 
// Anti-duplicato OB per barra
var int lastBullOBBar = -1
var int lastBearOBBar = -1
 
var line[] histHi = array.new_line()
var line[] histLo = array.new_line()
 
// reset ogni barra
buySignal   = false
sellSignal  = false
buyNearOB   = false
sellNearOB  = false
buyWarnOB   = false
sellWarnOB  = false
 
// ============================================================
// MEDIA MOBILE SU TIMEFRAME CUSTOM (filtro trend) + colore dinamico
// ============================================================
maValue = request.security(syminfo.tickerid, maTF, ta.sma(maSrc, maLen), lookahead=barmerge.lookahead_off)
 
maPlotColor = maDynamicColor ? (close > maValue ? maColorUp : close < maValue ? maColorDown : maColorFlat) : maColorFlat
 
plot(showMaPlot ? maValue : na, title="SMA Filtro", color=maPlotColor, linewidth=2)
 
aboveMa = not useMaFilter or close > maValue
belowMa = not useMaFilter or close < maValue
 
// ============================================================
// ORDER BLOCK: strutture dati
// ============================================================
var box[]   bullBoxes  = array.new_box()
var float[] bullTop    = array.new_float()
var float[] bullBottom = array.new_float()
 
var box[]   bearBoxes  = array.new_box()
var float[] bearTop    = array.new_float()
var float[] bearBottom = array.new_float()
 
atrVal = ta.atr(atrLen)
 
// ============================================================
// ORDER BLOCK: mitigazione (solo a barra confermata)
// ============================================================
if barstate.isconfirmed and obEnable
    if array.size(bullBoxes) > 0
        for i = array.size(bullBoxes) - 1 to 0
            bx  = array.get(bullBoxes, i)
            bot = array.get(bullBottom, i)
            box.set_right(bx, bar_index)
            mitigated = obMitigateOnClose ? close < bot : low < bot
            if mitigated
                box.delete(bx)
                array.remove(bullBoxes, i)
                array.remove(bullTop, i)
                array.remove(bullBottom, i)
 
    if array.size(bearBoxes) > 0
        for i = array.size(bearBoxes) - 1 to 0
            bx  = array.get(bearBoxes, i)
            top = array.get(bearTop, i)
            box.set_right(bx, bar_index)
            mitigated = obMitigateOnClose ? close > top : high > top
            if mitigated
                box.delete(bx)
                array.remove(bearBoxes, i)
                array.remove(bearTop, i)
                array.remove(bearBottom, i)
 
// ============================================================
// ORDER BLOCK: creazione (in tempo reale o solo a barra confermata)
// ============================================================
if obEnable and (obRealtimeDraw or barstate.isconfirmed)
    // --- Bullish OB ---
    bullishOB = close[1] < open[1] and close > high[1] and (not useDisplacement or (close - open) > atrVal * dispMult)
    if bullishOB and bar_index != lastBullOBBar
        obTop = high[1]
        obBot = low[1]
        newBoxBull = box.new(left=bar_index[1], top=obTop, right=bar_index, bottom=obBot, border_color=color.new(bullObColor, obBorderTransp), bgcolor=showObBoxes ? bullObColor : na)
        array.push(bullBoxes, newBoxBull)
        array.push(bullTop, obTop)
        array.push(bullBottom, obBot)
        lastBullOBBar := bar_index
        if array.size(bullBoxes) > obBoxCount
            box.delete(array.shift(bullBoxes))
            array.shift(bullTop)
            array.shift(bullBottom)
 
    // --- Bearish OB ---
    bearishOB = close[1] > open[1] and close < low[1] and (not useDisplacement or (open - close) > atrVal * dispMult)
    if bearishOB and bar_index != lastBearOBBar
        obTop = high[1]
        obBot = low[1]
        newBoxBear = box.new(left=bar_index[1], top=obTop, right=bar_index, bottom=obBot, border_color=color.new(bearObColor, obBorderTransp), bgcolor=showObBoxes ? bearObColor : na)
        array.push(bearBoxes, newBoxBear)
        array.push(bearTop, obTop)
        array.push(bearBottom, obBot)
        lastBearOBBar := bar_index
        if array.size(bearBoxes) > obBoxCount
            box.delete(array.shift(bearBoxes))
            array.shift(bearTop)
            array.shift(bearBottom)
 
// ============================================================
// FUNZIONI DI VERIFICA OB
// ============================================================
// Verifica se un prezzo (px) è dentro o vicino a un box OB
f_nearAnyBox(tops, bottoms, px, margin) =>
    bool found = false
    if array.size(tops) > 0
        for i = 0 to array.size(tops) - 1
            t = array.get(tops, i)
            b = array.get(bottoms, i)
            if px <= t + margin and px >= b - margin
                found := true
    found
 
// Verifica se il range [lo, hi] di una candela si sovrappone a un box OB
f_overlapsAnyBox(tops, bottoms, lo, hi, margin) =>
    bool found = false
    if array.size(tops) > 0
        for i = 0 to array.size(tops) - 1
            t = array.get(tops, i)
            b = array.get(bottoms, i)
            if hi >= b - margin and lo <= t + margin
                found := true
    found
 
// ============================================================
// CHECK IN TEMPO REALE (ogni tick, non solo a barra chiusa)
// ============================================================
if state == 2
    margin = atrVal * obProximityATR
    tolC3  = atrVal * closeToleranceATR
 
    buyBase  = isBuySetup  and low  >= c1Low  and high >= c1High and close > c1High - tolC3
    sellBase = isSellSetup and high <= c1High and low  <= c1Low  and close < c1Low  + tolC3
 
    buyNearOBcheck  = obEnable and buyBase  and f_nearAnyBox(bullTop, bullBottom, close, margin)
    sellNearOBcheck = obEnable and sellBase and f_nearAnyBox(bearTop, bearBottom, close, margin)
 
    buyWarnOBcheck  = obEnable and buyBase  and f_nearAnyBox(bearTop, bearBottom, close, margin)
    sellWarnOBcheck = obEnable and sellBase and f_nearAnyBox(bullTop, bullBottom, close, margin)
 
    buyBypassMa  = obEnable and obBypassMaOnTouch and c1c2TouchedBullOB
    sellBypassMa = obEnable and obBypassMaOnTouch and c1c2TouchedBearOB
 
    buyConfirm  = buyBase  and (aboveMa or buyNearOBcheck  or buyBypassMa)
    sellConfirm = sellBase and (belowMa or sellNearOBcheck or sellBypassMa)
 
    if buyConfirm and showBuy
        buySignal := true
        buyNearOB := buyNearOBcheck
        buyWarnOB := buyWarnOBcheck
    if sellConfirm and showSell
        sellSignal := true
        sellNearOB := sellNearOBcheck
        sellWarnOB := sellWarnOBcheck
 
// ============================================================
// LOGICA STATEFUL (solo a barra confermata)
// ============================================================
if barstate.isconfirmed
    if state == 0
        c1High   := high
        c1Low    := low
        c1c2TouchedBullOB := false
        c1c2TouchedBearOB := false
        if obEnable
            marginC1 = atrVal * obProximityATR
            if f_overlapsAnyBox(bullTop, bullBottom, low, high, marginC1)
                c1c2TouchedBullOB := true
            if f_overlapsAnyBox(bearTop, bearBottom, low, high, marginC1)
                c1c2TouchedBearOB := true
        if showLines
            c1HiLine := line.new(bar_index, high, bar_index + 2, high, xloc=xloc.bar_index, color=lineColor, width=1)
            c1LoLine := line.new(bar_index, low,  bar_index + 2, low,  xloc=xloc.bar_index, color=lineColor, width=1)
        state := 1
 
    else if state == 1
        brokeDown = low  < c1Low
        brokeUp   = high > c1High
        reclaimed = close >= c1Low and close <= c1High
        buySetup  = brokeDown and not brokeUp and reclaimed
        sellSetup = brokeUp and not brokeDown and reclaimed
 
        if obEnable and (buySetup or sellSetup)
            marginC2 = atrVal * obProximityATR
            if f_overlapsAnyBox(bullTop, bullBottom, low, high, marginC2)
                c1c2TouchedBullOB := true
            if f_overlapsAnyBox(bearTop, bearBottom, low, high, marginC2)
                c1c2TouchedBearOB := true
 
        if buySetup or sellSetup
            isBuySetup  := buySetup
            isSellSetup := sellSetup
            if showLines and not na(c1HiLine)
                line.set_color(c1HiLine, setupColor)
                line.set_color(c1LoLine, setupColor)
            state := 2
        else
            if not na(c1HiLine)
                line.delete(c1HiLine)
                line.delete(c1LoLine)
            c1High := high
            c1Low  := low
            c1c2TouchedBullOB := false
            c1c2TouchedBearOB := false
            if obEnable
                marginC1 = atrVal * obProximityATR
                if f_overlapsAnyBox(bullTop, bullBottom, low, high, marginC1)
                    c1c2TouchedBullOB := true
                if f_overlapsAnyBox(bearTop, bearBottom, low, high, marginC1)
                    c1c2TouchedBearOB := true
            if showLines
                c1HiLine := line.new(bar_index, high, bar_index + 2, high, xloc=xloc.bar_index, color=lineColor, width=1)
                c1LoLine := line.new(bar_index, low,  bar_index + 2, low,  xloc=xloc.bar_index, color=lineColor, width=1)
            else
                c1HiLine := na
                c1LoLine := na
            state := 1
 
    else if state == 2
        margin = atrVal * obProximityATR
        tolC3F = atrVal * closeToleranceATR
 
        buyBaseFinal  = isBuySetup  and low  >= c1Low  and high >= c1High and close > c1High - tolC3F
        sellBaseFinal = isSellSetup and high <= c1High and low  <= c1Low  and close < c1Low  + tolC3F
 
        buyNearOBFinal  = obEnable and buyBaseFinal  and f_nearAnyBox(bullTop, bullBottom, close, margin)
        sellNearOBFinal = obEnable and sellBaseFinal and f_nearAnyBox(bearTop, bearBottom, close, margin)
 
        buyBypassMaFinal  = obEnable and obBypassMaOnTouch and c1c2TouchedBullOB
        sellBypassMaFinal = obEnable and obBypassMaOnTouch and c1c2TouchedBearOB
 
        buyConfirmFinal  = buyBaseFinal  and (aboveMa or buyNearOBFinal  or buyBypassMaFinal)
        sellConfirmFinal = sellBaseFinal and (belowMa or sellNearOBFinal or sellBypassMaFinal)
 
        if dbgOB
            label.new(bar_index, high,
                 text="C1C2 BullOB=" + str.tostring(c1c2TouchedBullOB) + "\nC1C2 BearOB=" + str.tostring(c1c2TouchedBearOB) +
                      "\nC1 low=" + str.tostring(c1Low, "#.#####") + " C1 high=" + str.tostring(c1High, "#.#####") +
                      "\nC3 low=" + str.tostring(low, "#.#####") + " close=" + str.tostring(close, "#.#####") +
                      "\ntol=" + str.tostring(tolC3F, "#.#####") +
                      "\nsellBase=" + str.tostring(sellBaseFinal) + " buyBase=" + str.tostring(buyBaseFinal) +
                      "\nsellConfirm=" + str.tostring(sellConfirmFinal) + " buyConfirm=" + str.tostring(buyConfirmFinal),
                 style=label.style_label_down, color=color.new(color.blue, 60), textcolor=color.white, size=size.tiny)
 
        if buyConfirmFinal or sellConfirmFinal
            if not na(c1HiLine)
                array.push(histHi, c1HiLine)
                array.push(histLo, c1LoLine)
                while array.size(histHi) > maxHistory
                    line.delete(array.shift(histHi))
                    line.delete(array.shift(histLo))
            isBuySetup  := false
            isSellSetup := false
            c1c2TouchedBullOB := false
            c1c2TouchedBearOB := false
            state       := 0
        else
            if not na(c1HiLine)
                line.delete(c1HiLine)
                line.delete(c1LoLine)
            isBuySetup  := false
            isSellSetup := false
            c1High := high
            c1Low  := low
            c1c2TouchedBullOB := false
            c1c2TouchedBearOB := false
            if obEnable
                marginC1 = atrVal * obProximityATR
                if f_overlapsAnyBox(bullTop, bullBottom, low, high, marginC1)
                    c1c2TouchedBullOB := true
                if f_overlapsAnyBox(bearTop, bearBottom, low, high, marginC1)
                    c1c2TouchedBearOB := true
            if showLines
                c1HiLine := line.new(bar_index, high, bar_index + 2, high, xloc=xloc.bar_index, color=lineColor, width=1)
                c1LoLine := line.new(bar_index, low,  bar_index + 2, low,  xloc=xloc.bar_index, color=lineColor, width=1)
            else
                c1HiLine := na
                c1LoLine := na
            state := 1
 
// ============================================================
// PLOT SEGNALI
// ============================================================
plotchar(buySignal,  title="Buy Star",  char="★", location=location.belowbar, color=buyColor,  size=size.small)
plotchar(sellSignal, title="Sell Star", char="★", location=location.abovebar, color=sellColor, size=size.small)
 
if buyNearOB
    label.new(bar_index, low,  text="OB", style=label.style_label_up,   color=color.new(bullObColor, 0), textcolor=color.white, size=size.tiny)
if sellNearOB
    label.new(bar_index, high, text="OB", style=label.style_label_down, color=color.new(bearObColor, 0), textcolor=color.white, size=size.tiny)
 
if buyWarnOB
    label.new(bar_index, high, text="⚠OB", style=label.style_label_down, color=warnColor, textcolor=color.white, size=size.tiny)
if sellWarnOB
    label.new(bar_index, low,  text="⚠OB", style=label.style_label_up,   color=warnColor, textcolor=color.white, size=size.tiny)
 
if buySignal
    alert("BUY confermato su " + syminfo.ticker, alert.freq_once_per_bar)
if sellSignal
    alert("SELL confermato su " + syminfo.ticker, alert.freq_once_per_bar)
if buyNearOB
    alert("BUY confermato + confluenza Order Block su " + syminfo.ticker, alert.freq_once_per_bar)
if sellNearOB
    alert("SELL confermato + confluenza Order Block su " + syminfo.ticker, alert.freq_once_per_bar)
if buyWarnOB
    alert("ATTENZIONE: BUY vicino a Order Block ribassista (possibile inversione) su " + syminfo.ticker, alert.freq_once_per_bar)
if sellWarnOB
    alert("ATTENZIONE: SELL vicino a Order Block rialzista (possibile inversione) su " + syminfo.ticker, alert.freq_once_per_bar)
 
alertcondition(isBuySetup  and state == 2, title="Buy Setup In Attesa",  message="Sweep minimo + reclaim: attesa conferma su C3")
alertcondition(isSellSetup and state == 2, title="Sell Setup In Attesa", message="Sweep massimo + reclaim: attesa conferma su C3")
alertcondition(buySignal,  title="Buy Confermato",  message="C3 conferma: pattern BUY completato")
alertcondition(sellSignal, title="Sell Confermato", message="C3 conferma: pattern SELL completato")
alertcondition(buyNearOB,  title="Buy + Order Block", message="BUY confermato in confluenza con Order Block")
alertcondition(sellNearOB, title="Sell + Order Block", message="SELL confermato in confluenza con Order Block")
alertcondition(buyWarnOB,  title="Buy - Warning OB opposto", message="BUY vicino a Order Block ribassista: rischio inversione")
alertcondition(sellWarnOB, title="Sell - Warning OB opposto", message="SELL vicino a Order Block rialzista: rischio inversione")

← 返回列表