Turtle Soup Stop Hunt, False Break & Liquidity Grab [DNA]

DNA_PROFIT · study · 379 行 · 点赞 14 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
//  Turtle Soup Stop Hunt, False Break & Liquidity Grab [DNA]
// ----------------------------------------------------------------------------
//  Flags a Turtle Soup setup only after price closes back inside the prior
//  range following a swept high/low, then tracks a symmetric 1R reversal
//  leg measured from the arming bar's close. Every armed setup is carried
//  through to one outcome — reached 1R, failed or expired — so the panel
//  reports a real, geometry-fair hit rate instead of a target that sits
//  closer to the entry than the invalidation point.
//
//  NON-REPAINTING: everything is decided on closed bars from confirmed pivots.
//  No higher-timeframe requests, no lookahead.
// ============================================================================
indicator("Turtle Soup Stop Hunt, False Break & Liquidity Grab [DNA]", "Turtle Soup [DNA]", overlay = true, max_lines_count = 300, max_labels_count = 300, max_boxes_count = 200)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS
// ─────────────────────────────────────────────────────────────────────────
gL = "Logic / Swings"
swingLen = input.int(5, "Swing strength (bars)", minval = 2, maxval = 30, group = gL, tooltip = "Bars on each side that confirm a swing high/low. Higher = fewer, larger swings.")
minSize  = input.float(0.3, "Min. sweep depth (× ATR)", minval = 0.0, maxval = 5.0, step = 0.1, group = gL, tooltip = "The wick beyond the level must clear this many ATR(14) to count as a real sweep, filtering out noise ticks.")
maxDepth = input.float(1.5, "Max. sweep depth (× ATR)", minval = 0.1, maxval = 5.0, step = 0.1, group = gL, tooltip = "If price trades this many ATR(14) beyond the swept level before any bar closes back inside, the sweep is closed as a continuation immediately — stops the zone from ballooning while a trend keeps extending the extreme.")
maxBars  = input.int(40, "Max bars to track a setup (bars)", minval = 5, maxval = 200, group = gL, tooltip = "A setup that neither reaches 1R nor gets invalidated within this many bars is closed out as expired.")
targetMult = input.float(1.0, "Target (x R)", minval = 0.1, maxval = 5.0, step = 0.1, group = gL, tooltip = "The 1R profit objective measured from the arming bar's close: target = entryRef ∓ this many multiples of R, where R is the distance from entryRef to the frozen sweep extreme. Setups where R is below 0.2×ATR are skipped entirely — too little room to be a fair test.")
 
gD = "Drawing"
keepLast = input.int(6, "Items kept on the chart", minval = 1, maxval = 30, group = gD, tooltip = "Older finished setups are removed from the chart. The record keeps all of them.")
labelSz  = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = gD)
showZone = input.bool(true, "Show liquidity grab zone", group = gD, tooltip = "Shaded box from the swept level to the wick extreme.")
 
gT = "Panel"
showPanel = input.bool(true, "Show the panel", group = gT)
panelPos  = input.string("Bottom centre", "Position", options = ["Bottom centre", "Bottom left", "Bottom right", "Top centre", "Top right"], group = gT)
panelSz   = input.string("Normal", "Text size", options = ["Small", "Normal", "Large"], group = gT)
 
gA = "Alerts"
alOn = input.bool(true, "Alerts with full messages (alert() calls)", group = gA)
 
gV = "Visuals"
brandCandles = input.bool(true, "Brand candles", group = gV, tooltip = "Gold for rising candles, periwinkle for falling. Off = your own chart candles.")
glowCandles  = input.bool(true, "Glow candles", group = gV, tooltip = "Each body is drawn in three bands that brighten towards the close. Off = flat bodies.")
 
// ─────────────────────────────────────────────────────────────────────────
//  THEME  (adapts to a light or dark chart)
// ─────────────────────────────────────────────────────────────────────────
chartBg = chart.bg_color
isLight = (color.r(chartBg) + color.g(chartBg) + color.b(chartBg)) / 3.0 > 140
UP    = isLight ? #B07D0A : #F7C948   // gold: bullish, rising candles
DN    = isLight ? #5546C8 : #8E7CFF   // periwinkle: bearish, falling candles
ACC   = isLight ? #0E8F7E : #5EEAD4   // mint: the zone / the level that matters
WARN  = isLight ? #C2410C : #FF8A5B   // failed / broken
TXT   = isLight ? #12151C : #F2F3F7
MUTE  = isLight ? #646B7D : #8E95A8
PANEL = isLight ? #FBFBFD : #0D1017
ROW   = isLight ? #ECEEF4 : #171B26
INK   = #0D1017
NONE  = color.new(#000000, 100)
 
lSize = switch labelSz
    "Tiny"  => size.tiny
    "Small" => size.small
    "Large" => size.large
    => size.normal
tSize = switch panelSz
    "Small" => size.small
    "Large" => size.large
    => size.normal
 
fmtPrice(float v) =>
    str.tostring(v, format.mintick)
 
pct(int a, int b) =>
    b > 0 ? str.tostring(math.round(100.0 * a / b)) + "%" : "—"
 
// ─────────────────────────────────────────────────────────────────────────
//  CORE  (Turtle Soup state machine — confirmed bars only)
// ─────────────────────────────────────────────────────────────────────────
atr = ta.atr(14)
ph  = ta.pivothigh(high, swingLen, swingLen)
pl  = ta.pivotlow(low, swingLen, swingLen)
 
var float rangeHigh    = na
var float rangeLow     = na
var int   rangeHighBar = na
var int   rangeLowBar  = na
 
var string state = "scanning"   // scanning -> swept -> armed -> scanning
var int    dir    = 0           // 1 = high swept (bearish setup), -1 = low swept (bullish setup)
var float  level   = na
var float  extreme = na         // frozen the moment the setup arms
var float  entryRef = na        // close of the bar that closes back inside
var float  riskR    = na        // |entryRef - extreme| at the moment of arming
var float  target  = na
var int    pivotBar  = na
var int    sweepBar = na
var int    armBar   = na
 
var int nSwept      = 0
var int nClosedBack  = 0
var int nReachedR    = 0
var int nFailed       = 0
var int nExpired      = 0
var string stageLbl = "range tracking"
 
var box   curBox   = na
var line  curLevel = na
var line  curTgt   = na
var label curLbl   = na
 
var array<box>   boxHist = array.new<box>()
var array<line>  lineHist = array.new<line>()
var array<label> lblHist  = array.new<label>()
 
archiveBox(array<box> arr, box b, int keep) =>
    array.push(arr, b)
    if array.size(arr) > keep
        box.delete(array.shift(arr))
 
archiveLine(array<line> arr, line ln, int keep) =>
    array.push(arr, ln)
    if array.size(arr) > keep
        line.delete(array.shift(arr))
 
archiveLabel(array<label> arr, label lb, int keep) =>
    array.push(arr, lb)
    if array.size(arr) > keep
        label.delete(array.shift(arr))
 
evSweep        = false
evArm          = false
evSkip         = false
evContinuation = false
evReached      = false
evFail         = false
evExpired      = false
 
if barstate.isconfirmed
    if state == "scanning"
        if not na(ph)
            rangeHigh := ph
            rangeHighBar := bar_index - swingLen
        if not na(pl)
            rangeLow := pl
            rangeLowBar := bar_index - swingLen
        stageLbl := "range tracking"
 
        if not na(rangeHigh) and high > rangeHigh and (high - rangeHigh) >= minSize * atr
            dir := 1
            level := rangeHigh
            pivotBar := rangeHighBar
            extreme := high
            sweepBar := bar_index
            state := "swept"
            nSwept += 1
            stageLbl := "level swept"
            evSweep := true
        else if not na(rangeLow) and low < rangeLow and (rangeLow - low) >= minSize * atr
            dir := -1
            level := rangeLow
            pivotBar := rangeLowBar
            extreme := low
            sweepBar := bar_index
            state := "swept"
            nSwept += 1
            stageLbl := "level swept"
            evSweep := true
 
    else if state == "swept"
        if dir == 1
            extreme := math.max(extreme, high)
            if close < level
                r = extreme - close
                if r < 0.2 * atr
                    state := "scanning"
                    rangeHigh := na
                    stageLbl := "setup skipped (R < 0.2×ATR)"
                    evSkip := true
                else
                    state := "armed"
                    armBar := bar_index
                    entryRef := close
                    riskR := r
                    target := entryRef - targetMult * riskR
                    nClosedBack += 1
                    stageLbl := "close back inside: armed"
                    evArm := true
            else if (extreme - level) >= maxDepth * atr
                state := "scanning"
                rangeHigh := na
                stageLbl := "continuation ✕"
                evContinuation := true
            else if bar_index - sweepBar > maxBars
                state := "scanning"
                rangeHigh := na
                stageLbl := "continuation ✕"
                evContinuation := true
        else
            extreme := math.min(extreme, low)
            if close > level
                r = close - extreme
                if r < 0.2 * atr
                    state := "scanning"
                    rangeLow := na
                    stageLbl := "setup skipped (R < 0.2×ATR)"
                    evSkip := true
                else
                    state := "armed"
                    armBar := bar_index
                    entryRef := close
                    riskR := r
                    target := entryRef + targetMult * riskR
                    nClosedBack += 1
                    stageLbl := "close back inside: armed"
                    evArm := true
            else if (level - extreme) >= maxDepth * atr
                state := "scanning"
                rangeLow := na
                stageLbl := "continuation ✕"
                evContinuation := true
            else if bar_index - sweepBar > maxBars
                state := "scanning"
                rangeLow := na
                stageLbl := "continuation ✕"
                evContinuation := true
 
    else if state == "armed"
        if dir == 1
            if high > extreme
                nFailed += 1
                state := "scanning"
                rangeHigh := na
                stageLbl := "failed ✕"
                evFail := true
            else if low <= target
                nReachedR += 1
                state := "scanning"
                rangeHigh := na
                stageLbl := "reached 1R ✓"
                evReached := true
            else if bar_index - armBar > maxBars
                nExpired += 1
                state := "scanning"
                rangeHigh := na
                stageLbl := "expired (time limit)"
                evExpired := true
        else
            if low < extreme
                nFailed += 1
                state := "scanning"
                rangeLow := na
                stageLbl := "failed ✕"
                evFail := true
            else if high >= target
                nReachedR += 1
                state := "scanning"
                rangeLow := na
                stageLbl := "reached 1R ✓"
                evReached := true
            else if bar_index - armBar > maxBars
                nExpired += 1
                state := "scanning"
                rangeLow := na
                stageLbl := "expired (time limit)"
                evExpired := true
 
// ─────────────────────────────────────────────────────────────────────────
//  DRAWING  (zone box, level/target lines, outcome labels — keepLast history)
// ─────────────────────────────────────────────────────────────────────────
closingEvent = evReached or evFail or evExpired or evContinuation or evSkip
 
if barstate.isconfirmed
    if evSweep
        curBox := showZone ? box.new(left = sweepBar, top = dir == 1 ? extreme : level, bottom = dir == 1 ? level : extreme, right = bar_index, border_color = ACC, border_width = 1, bgcolor = color.new(ACC, 85)) : na
        curLevel := line.new(x1 = pivotBar, y1 = level, x2 = sweepBar, y2 = level, color = ACC, style = line.style_dashed, width = 1)
        curLbl := label.new(bar_index, extreme, "level swept", style = dir == 1 ? label.style_label_down : label.style_label_up, color = ACC, textcolor = INK, size = lSize)
 
    if evArm
        if not na(curLbl)
            label.delete(curLbl)
        curLbl := label.new(bar_index, close, "armed → 1R  " + fmtPrice(target), style = dir == 1 ? label.style_label_down : label.style_label_up, color = ACC, textcolor = INK, size = lSize)
        curTgt := line.new(x1 = armBar, y1 = target, x2 = bar_index, y2 = target, color = ACC, style = line.style_dotted, width = 1)
        if not na(curBox)
            box.set_right(curBox, bar_index)
 
    if not evSweep and not evArm and not closingEvent and (state == "swept" or state == "armed")
        if not na(curBox)
            box.set_right(curBox, bar_index)
            if state == "swept"
                if dir == 1
                    box.set_top(curBox, extreme)
                else
                    box.set_bottom(curBox, extreme)
        if not na(curTgt)
            line.set_x2(curTgt, bar_index)
 
    if closingEvent
        if not na(curLbl)
            label.delete(curLbl)
        outcomeColor = evReached ? (dir == 1 ? DN : UP) : evFail ? WARN : evExpired ? MUTE : evSkip ? MUTE : WARN
        outcomeText  = evReached ? "✓ 1R  " + fmtPrice(target) : evFail ? "✕ failed  " + fmtPrice(extreme) : evExpired ? "… expired  " + fmtPrice(close) : evSkip ? "skip (R < 0.2×ATR)" : "✕ continuation  " + fmtPrice(extreme)
        outcomeY     = evReached ? target : evFail ? extreme : evExpired ? close : extreme
        finalLbl = label.new(bar_index, outcomeY, outcomeText, style = dir == 1 ? label.style_label_down : label.style_label_up, color = outcomeColor, textcolor = INK, size = lSize)
        if not na(curBox)
            box.set_right(curBox, bar_index)
            box.set_border_color(curBox, outcomeColor)
            archiveBox(boxHist, curBox, keepLast)
            curBox := na
        if not na(curLevel)
            archiveLine(lineHist, curLevel, keepLast)
            curLevel := na
        if not na(curTgt)
            line.set_x2(curTgt, bar_index)
            archiveLine(lineHist, curTgt, keepLast)
            curTgt := na
        archiveLabel(lblHist, finalLbl, keepLast)
 
// ─────────────────────────────────────────────────────────────────────────
//  PANEL  (one strip of tiles: caption row + value row)
// ─────────────────────────────────────────────────────────────────────────
tile(table t, int c, string cap, string val, color vc) =>
    table.cell(t, c, 0, cap, text_color = MUTE, text_size = size.small, bgcolor = PANEL)
    table.cell(t, c, 1, val, text_color = vc, text_size = tSize, bgcolor = PANEL)
 
pos = switch panelPos
    "Bottom left"  => position.bottom_left
    "Bottom right" => position.bottom_right
    "Top centre"   => position.top_center
    "Top right"    => position.top_right
    => position.bottom_center
 
var table tb = table.new(pos, 6, 2, bgcolor = NONE, border_width = 6, border_color = NONE, frame_width = 0)
if showPanel and barstate.islast
    nSettled = nReachedR + nFailed
    tile(tb, 0, "STAGE", stageLbl, TXT)
    tile(tb, 1, "LEVELS SWEPT", str.tostring(nSwept), ACC)
    tile(tb, 2, "CLOSED BACK IN", str.tostring(nClosedBack), ACC)
    tile(tb, 3, "REACHED 1R", str.tostring(nReachedR), dir == 1 ? DN : UP)
    tile(tb, 4, "FAILED", str.tostring(nFailed), WARN)
    tile(tb, 5, "REACHED 1R · " + str.tostring(nSettled), pct(nReachedR, nSettled), ACC)
 
// ─────────────────────────────────────────────────────────────────────────
//  ALERTS  (closed bars only)
// ─────────────────────────────────────────────────────────────────────────
if alOn and evSweep
    alert(syminfo.ticker + " Turtle Soup: " + (dir == 1 ? "high" : "low") + " swept at " + fmtPrice(level), alert.freq_once_per_bar_close)
if alOn and evArm
    alert(syminfo.ticker + " Turtle Soup armed, target " + fmtPrice(target), alert.freq_once_per_bar_close)
if alOn and evReached
    alert(syminfo.ticker + " Turtle Soup reached 1R at " + fmtPrice(target), alert.freq_once_per_bar_close)
if alOn and evFail
    alert(syminfo.ticker + " Turtle Soup setup failed, wick beyond extreme", alert.freq_once_per_bar_close)
if alOn and evContinuation
    alert(syminfo.ticker + " Turtle Soup setup failed (continuation, never closed back inside)", alert.freq_once_per_bar_close)
if alOn and evExpired
    alert(syminfo.ticker + " Turtle Soup setup expired (time limit, no result)", alert.freq_once_per_bar_close)
 
alertcondition(evSweep, "Level swept", "{{ticker}} Turtle Soup: level swept")
alertcondition(evArm, "Closed back inside (armed)", "{{ticker}} Turtle Soup armed, watching for 1R")
alertcondition(evReached, "Reached 1R", "{{ticker}} Turtle Soup reached 1R")
alertcondition(evFail, "Failed (wick beyond extreme)", "{{ticker}} Turtle Soup setup failed, wick beyond extreme")
alertcondition(evContinuation, "Continuation (never armed)", "{{ticker}} Turtle Soup setup failed, continuation")
alertcondition(evExpired, "Expired (time limit)", "{{ticker}} Turtle Soup setup expired, time limit")
 
// ─────────────────────────────────────────────────────────────────────────
//  BRAND CANDLES  (keep this block as it is)
// ─────────────────────────────────────────────────────────────────────────
edge  = close >= open ? UP : DN
flat  = brandCandles and not glowCandles
glow  = brandCandles and glowCandles
third = (close - open) / 3.0
b1    = open + third
b2    = open + 2.0 * third
plotcandle(flat ? open : na, high, low, close, "Candles", color = color.new(edge, 25), wickcolor = color.new(edge, 15), bordercolor = edge, display = display.pane)
plotcandle(glow ? open : na, glow ? math.max(open, close) : na, glow ? math.min(open, close) : na, glow ? close : na, "Glow mask", color = chart.bg_color, wickcolor = NONE, bordercolor = chart.bg_color, display = display.pane)
plotcandle(glow ? open : na, glow ? math.max(open, b1) : na, glow ? math.min(open, b1) : na, glow ? b1 : na, "Glow band 1", color = color.new(edge, 72), wickcolor = NONE, bordercolor = NONE, display = display.pane)
plotcandle(glow ? b1 : na, glow ? math.max(b1, b2) : na, glow ? math.min(b1, b2) : na, glow ? b2 : na, "Glow band 2", color = color.new(edge, 44), wickcolor = NONE, bordercolor = NONE, display = display.pane)
plotcandle(glow ? b2 : na, glow ? math.max(b2, close) : na, glow ? math.min(b2, close) : na, glow ? close : na, "Glow band 3", color = color.new(edge, 8), wickcolor = NONE, bordercolor = NONE, display = display.pane)
plotcandle(glow ? open : na, glow ? high : na, glow ? low : na, glow ? close : na, "Glow wick", color = NONE, wickcolor = color.new(edge, 12), bordercolor = color.new(edge, 30), display = display.pane)

← 返回列表