Turtle Soup Reversal Map [AGPro Series]

AGProLabs · study · 420 行 · 点赞 290 · TradingView 原页

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

Pine Script

// ─────────────────────────────────────────────────
// Turtle Soup Reversal Map [AGPro Series]
//
// Author  : AGProLabs | AGPro Series
// Version : 1.3
// License : Mozilla Public License 2.0 — https://mozilla.org/MPL/2.0/
//
// Turtle Soup reversal pattern detector with adaptive quality scoring.
// Detects 20-bar extreme sweeps that fail and reverse — Linda Raschke's
// classic mean-reversion setup, re-engineered with wick rejection, volume
// confirmation, overshoot magnitude, HTF trend alignment and key-level
// proximity scoring. Pending / Fired / Invalidated state engine, target
// projection, historical win-rate and average reward tracking.
// Keywords: turtle soup, reversal, liquidity sweep, false breakout,
// mean reversion, Raschke, 20-bar extreme, failed breakout.
// ─────────────────────────────────────────────────
 
//@version=6
indicator("Turtle Soup Reversal Map [AGPro Series]",
     shorttitle = "AG Pro TSRM",
     overlay    = true,
     max_labels_count = 300,
     max_lines_count  = 300,
     max_boxes_count  = 200)
 
// ═════════════════════════════════════════════════
// INPUTS
// ═════════════════════════════════════════════════
grpCore = "◆ Core Detection"
lookback      = input.int(20, "Lookback Bars",    minval=10, maxval=50, group=grpCore, tooltip="Number of bars defining the extreme high/low window. Raschke's original spec is 20. Higher values yield fewer but stronger setups.")
confirmMode   = input.string("Next-Bar Close", "Confirmation Mode", options=["Same-Bar Close","Next-Bar Close"], group=grpCore, tooltip="Same-Bar Close: setup fires on the violating bar's close. Faster but higher false-signal rate. Next-Bar Close: Raschke standard — requires the next bar to close back inside the prior range. More reliable.")
invalidateATR = input.float(0.5, "Invalidation Distance (ATR)", minval=0.2, maxval=3.0, step=0.1, group=grpCore, tooltip="Pending setups are invalidated if price moves this many ATR beyond the sweep extreme before confirmation.")
 
grpScore = "◆ Quality Score"
useWick    = input.bool(true, "Wick Rejection (25 pts)",     group=grpScore, tooltip="Scores the ratio of the rejection wick to total bar range at the extreme bar. Strong wicks indicate decisive rejection.")
useVolume  = input.bool(true, "Volume Spike (20 pts)",       group=grpScore, tooltip="Scores how much volume exceeded its moving average on the extreme bar. High volume confirms absorption of breakout attempts.")
useOver    = input.bool(true, "Overshoot Magnitude (15 pts)",group=grpScore, tooltip="Scores how far price pierced beyond the prior extreme, normalized by ATR. Moderate overshoots score best — tiny or extreme pierces score lower.")
useHTF     = input.bool(true, "HTF Trend Alignment (25 pts)",group=grpScore, tooltip="Mean-reversion edge — scores highest when the setup fades against the higher-timeframe trend (counter-trend mean reversion).")
useLevel   = input.bool(true, "Key Level Proximity (15 pts)",group=grpScore, tooltip="Scores proximity to round numbers and multi-bar pivot levels. Sweeps at obvious liquidity pools score higher.")
htfRes     = input.timeframe("240", "HTF for Trend", group=grpScore, tooltip="Higher timeframe used for trend alignment component.")
volLen     = input.int(20, "Volume Average Length", minval=5, maxval=100, group=grpScore)
 
grpTarget = "◆ Target & Stats"
targetATR   = input.float(2.5, "Target Projection (ATR)", minval=0.5, maxval=6.0, step=0.1, group=grpTarget, tooltip="Projected reversal target distance from entry, measured in ATR units. This is a reference projection — not a trade instruction.")
statsWindow = input.int(30, "Stats Sample Size", minval=10, maxval=200, group=grpTarget, tooltip="Number of most recent resolved setups used for win-rate and average reward metrics.")
 
grpVis = "◆ Visual"
showZones  = input.bool(true,  "Rejection Zones",   group=grpVis, tooltip="Tight zones drawn between the sweep extreme and the prior range boundary. Auto-closes when setup resolves.")
showLines  = input.bool(true,  "Extreme Ref Lines", group=grpVis)
showLabels = input.bool(true,  "Setup Labels",      group=grpVis)
showTarget = input.bool(true,  "Target Projection", group=grpVis)
labelSize  = input.string("Normal", "Label Size",   options=["Tiny","Small","Normal","Large"], group=grpVis)
projBars   = input.int(25, "Projection Length (bars)", minval=10, maxval=100, group=grpVis)
 
grpPanel = "◆ Panel"
showPanel = input.bool(true, "Show Panel", group=grpPanel)
panelLoc  = input.string("Top Right", "Panel Location", options=["Top Right","Top Left","Bottom Right","Bottom Left","Middle Right","Middle Left"], group=grpPanel)
panelSize = input.string("Normal", "Panel Size", options=["Tiny","Small","Normal","Large"], group=grpPanel)
helpSize  = input.string("Normal", "Help Text Size", options=["Tiny","Small","Normal","Large"], group=grpPanel)
 
grpAlert = "◆ Alerts"
alertPending = input.bool(true, "Alert on Pending",     group=grpAlert)
alertFired   = input.bool(true, "Alert on Fired",       group=grpAlert)
alertInvalid = input.bool(false,"Alert on Invalidated", group=grpAlert)
 
// ═════════════════════════════════════════════════
// AGPro Color Palette
// ═════════════════════════════════════════════════
headerBg      = color.rgb(37, 99, 235)
headerText    = color.rgb(245, 247, 250)
panelBg       = color.rgb(15, 23, 42)
panelBorder   = color.rgb(51, 65, 85)
panelLabelCol = color.rgb(148, 163, 184)
panelValueCol = color.rgb(226, 232, 240)
bullColor     = color.rgb(34, 197, 166)
bearColor     = color.rgb(244, 114, 182)
neutralColor  = color.rgb(245, 189, 92)
accentColor   = color.rgb(129, 140, 248)
 
// ═════════════════════════════════════════════════
// HELPERS
// ═════════════════════════════════════════════════
f_size(s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.normal
 
f_panelPos(p) =>
    switch p
        "Top Right"     => position.top_right
        "Top Left"      => position.top_left
        "Bottom Right"  => position.bottom_right
        "Bottom Left"   => position.bottom_left
        "Middle Right"  => position.middle_right
        "Middle Left"   => position.middle_left
        => position.top_right
 
// ═════════════════════════════════════════════════
// CORE CALCULATIONS
// ═════════════════════════════════════════════════
atr = ta.atr(14)
volMA = ta.sma(volume, volLen)
 
// 20-bar extremes (exclude current bar)
priorHigh = ta.highest(high, lookback)[1]
priorLow  = ta.lowest(low, lookback)[1]
 
// Sweep detection (intrabar violation)
sweptHigh = high > priorHigh
sweptLow  = low  < priorLow
 
// HTF trend (for alignment score)
htfClose   = request.security(syminfo.tickerid, htfRes, close, lookahead=barmerge.lookahead_off)
htfEMA50   = request.security(syminfo.tickerid, htfRes, ta.ema(close, 50), lookahead=barmerge.lookahead_off)
htfTrendUp = htfClose > htfEMA50
 
// Key level proximity
pivotHigh = ta.pivothigh(high, 5, 5)
pivotLow  = ta.pivotlow(low, 5, 5)
var float lastPH = na
var float lastPL = na
if not na(pivotHigh)
    lastPH := pivotHigh
if not na(pivotLow)
    lastPL := pivotLow
 
f_roundProximity(p) =>
    if p <= 0 or atr <= 0
        10.0
    else
        scale   = math.pow(10, math.floor(math.log10(p)) - 1)
        nearest = math.round(p / scale) * scale
        math.abs(p - nearest) / atr
 
// ═════════════════════════════════════════════════
// QUALITY SCORE
// ═════════════════════════════════════════════════
f_wickScore(isBear) =>
    rng = high - low
    if rng <= 0
        0.0
    else
        wick  = isBear ? (high - math.max(open, close)) : (math.min(open, close) - low)
        ratio = wick / rng
        math.min(25.0, ratio * 35.0)
 
f_volScore() =>
    if volMA <= 0 or na(volMA)
        0.0
    else
        ratio = volume / volMA
        math.min(20.0, math.max(0.0, (ratio - 1.0) * 15.0))
 
f_overScore(isBear) =>
    over    = isBear ? (high - priorHigh) : (priorLow - low)
    overATR = atr > 0 ? over / atr : 0.0
    overATR <= 0 ? 0.0 : overATR < 0.2 ? overATR * 50.0 : overATR <= 1.0 ? 15.0 : math.max(0.0, 15.0 - (overATR - 1.0) * 7.5)
 
f_htfScore(isBear) =>
    isBear ? (htfTrendUp ? 25.0 : 10.0) : (not htfTrendUp ? 25.0 : 10.0)
 
f_levelScore(price) =>
    roundDist = f_roundProximity(price)
    pivotDist = not na(lastPH) and not na(lastPL) ? math.min(math.abs(price - lastPH), math.abs(price - lastPL)) / atr : 10.0
    best = math.min(roundDist, pivotDist)
    best < 0.25 ? 15.0 : best < 0.5 ? 10.0 : best < 1.0 ? 5.0 : 0.0
 
f_score(isBear) =>
    s = 0.0
    s += useWick   ? f_wickScore(isBear) : 0.0
    s += useVolume ? f_volScore()        : 0.0
    s += useOver   ? f_overScore(isBear) : 0.0
    s += useHTF    ? f_htfScore(isBear)  : 0.0
    s += useLevel  ? f_levelScore(isBear ? high : low) : 0.0
    math.min(100.0, s)
 
f_grade(s) =>
    s >= 85 ? "A+" : s >= 70 ? "A" : s >= 55 ? "B" : "C"
 
// ═════════════════════════════════════════════════
// STATE ENGINE
// State: 0=Idle, 1=PendingBear, 2=PendingBull, 3=FiredBear, 4=FiredBull
// ═════════════════════════════════════════════════
var int   currentState = 0
var float setupExtreme = na
var float setupEntry   = na
var float setupTarget  = na
var float setupStop    = na
var float setupScore   = na
var int   setupBar     = na
var box   setupZone    = na
var line  setupRefLn   = na
var line  setupTargetLn= na
var line  setupStopLn  = na
 
// Stats arrays
var array<int>   resultsArr = array.new<int>()
var array<float> rewardsArr = array.new<float>()
 
// Label cooldown — prevent overlapping labels in close proximity
var int lastBullLabelBar = na
var int lastBearLabelBar = na
cooldownBars = 3
 
// Only allow one active setup at a time
newBearSetup = sweptHigh and currentState == 0
newBullSetup = sweptLow  and currentState == 0 and not newBearSetup
 
// ─── New setup: initialize state & draw zone ───
if newBearSetup
    currentState := 1
    setupExtreme := high
    setupEntry   := close
    setupScore   := f_score(true)
    setupBar     := bar_index
    setupTarget  := close - targetATR * atr
    setupStop    := high + invalidateATR * atr
    // Tight rejection zone: from priorHigh to extreme high
    if showZones
        setupZone := box.new(bar_index - 2, high, bar_index + projBars, priorHigh, border_color=color.new(bearColor, 50), bgcolor=color.new(bearColor, 70), border_width=1)
    if showLines
        setupRefLn := line.new(bar_index - lookback, priorHigh, bar_index + projBars, priorHigh, color=color.new(bearColor, 40), style=line.style_dotted, width=1)
 
if newBullSetup
    currentState := 2
    setupExtreme := low
    setupEntry   := close
    setupScore   := f_score(false)
    setupBar     := bar_index
    setupTarget  := close + targetATR * atr
    setupStop    := low - invalidateATR * atr
    if showZones
        setupZone := box.new(bar_index - 2, priorLow, bar_index + projBars, low, border_color=color.new(bullColor, 50), bgcolor=color.new(bullColor, 70), border_width=1)
    if showLines
        setupRefLn := line.new(bar_index - lookback, priorLow, bar_index + projBars, priorLow, color=color.new(bullColor, 40), style=line.style_dotted, width=1)
 
// ─── Confirmation ───
isSameBar = confirmMode == "Same-Bar Close"
 
confirmBear = false
confirmBull = false
 
if currentState == 1
    if isSameBar and bar_index == setupBar
        confirmBear := close < priorHigh
    else if not isSameBar and bar_index == setupBar + 1
        confirmBear := close < priorHigh
 
if currentState == 2
    if isSameBar and bar_index == setupBar
        confirmBull := close > priorLow
    else if not isSameBar and bar_index == setupBar + 1
        confirmBull := close > priorLow
 
if confirmBear
    currentState := 3
    setupEntry   := close
    // Re-set stop to sweep extreme + buffer, target from new entry
    setupStop    := setupExtreme + invalidateATR * atr
    setupTarget  := close - targetATR * atr
    if showTarget
        setupTargetLn := line.new(bar_index, setupTarget, bar_index + projBars, setupTarget, color=color.new(bearColor, 30), style=line.style_dashed, width=2)
        setupStopLn   := line.new(bar_index, setupStop,   bar_index + projBars, setupStop,   color=color.new(neutralColor, 30), style=line.style_dotted, width=1)
 
if confirmBull
    currentState := 4
    setupEntry   := close
    setupStop    := setupExtreme - invalidateATR * atr
    setupTarget  := close + targetATR * atr
    if showTarget
        setupTargetLn := line.new(bar_index, setupTarget, bar_index + projBars, setupTarget, color=color.new(bullColor, 30), style=line.style_dashed, width=2)
        setupStopLn   := line.new(bar_index, setupStop,   bar_index + projBars, setupStop,   color=color.new(neutralColor, 30), style=line.style_dotted, width=1)
 
// ─── Fired setup labels (with cooldown to prevent overlap) ───
if showLabels and confirmBear and (na(lastBearLabelBar) or bar_index - lastBearLabelBar > cooldownBars)
    lblText = "Soup-Bear\n" + f_grade(setupScore) + "  " + str.tostring(math.round(setupScore)) + "/100"
    label.new(bar_index, high + atr * 0.5, lblText, style=label.style_label_down, color=bearColor, textcolor=color.white, size=f_size(labelSize))
    lastBearLabelBar := bar_index
 
if showLabels and confirmBull and (na(lastBullLabelBar) or bar_index - lastBullLabelBar > cooldownBars)
    lblText = "Soup-Bull\n" + f_grade(setupScore) + "  " + str.tostring(math.round(setupScore)) + "/100"
    label.new(bar_index, low - atr * 0.5, lblText, style=label.style_label_up, color=bullColor, textcolor=color.white, size=f_size(labelSize))
    lastBullLabelBar := bar_index
 
// ─── Invalidation (pending state) ───
// 1. Price moves beyond setup stop (extreme violation) → invalidated
// 2. Confirmation window missed → auto-invalidated (timeout)
timeoutBear = currentState == 1 and (isSameBar ? bar_index > setupBar : bar_index > setupBar + 1)
timeoutBull = currentState == 2 and (isSameBar ? bar_index > setupBar : bar_index > setupBar + 1)
invalidBear = currentState == 1 and (high > setupStop or timeoutBear)
invalidBull = currentState == 2 and (low  < setupStop or timeoutBull)
 
// ─── Resolution (fired state) ───
hitTargetBear = currentState == 3 and low  <= setupTarget
hitStopBear   = currentState == 3 and high >= setupStop
hitTargetBull = currentState == 4 and high >= setupTarget
hitStopBull   = currentState == 4 and low  <= setupStop
 
// Helper: close the zone and lines at current bar
f_closeVisuals() =>
    if not na(setupZone)
        box.set_right(setupZone, bar_index)
    if not na(setupTargetLn)
        line.set_x2(setupTargetLn, bar_index)
    if not na(setupStopLn)
        line.set_x2(setupStopLn, bar_index)
 
// Record wins
if hitTargetBear or hitTargetBull
    array.push(resultsArr, 1)
    riskBear   = setupStop  - setupEntry
    riskBull   = setupEntry - setupStop
    rewardBear = setupEntry - setupTarget
    rewardBull = setupTarget - setupEntry
    rMult = hitTargetBear ? (riskBear > 0 ? rewardBear / riskBear : 0.0) : (riskBull > 0 ? rewardBull / riskBull : 0.0)
    array.push(rewardsArr, rMult)
    if array.size(resultsArr) > statsWindow
        array.shift(resultsArr)
        array.shift(rewardsArr)
    f_closeVisuals()
    currentState := 0
    setupBar     := na
    setupZone    := na
    setupTargetLn:= na
    setupStopLn  := na
 
// Record losses
if hitStopBear or hitStopBull
    array.push(resultsArr, 0)
    array.push(rewardsArr, -1.0)
    if array.size(resultsArr) > statsWindow
        array.shift(resultsArr)
        array.shift(rewardsArr)
    f_closeVisuals()
    currentState := 0
    setupBar     := na
    setupZone    := na
    setupTargetLn:= na
    setupStopLn  := na
 
// Invalidated (never fired) — not counted in stats
if invalidBear or invalidBull
    f_closeVisuals()
    currentState := 0
    setupBar     := na
    setupZone    := na
 
// ═════════════════════════════════════════════════
// PANEL
// ═════════════════════════════════════════════════
f_stateText(s) =>
    s == 1 ? "Pending Bear" : s == 2 ? "Pending Bull" : s == 3 ? "Fired Bear" : s == 4 ? "Fired Bull" : "Idle"
 
f_stateCol(s) =>
    s == 1 or s == 3 ? bearColor : s == 2 or s == 4 ? bullColor : panelValueCol
 
var table panel = na
if barstate.islast and showPanel
    if not na(panel)
        table.delete(panel)
    panel := table.new(f_panelPos(panelLoc), 2, 10, border_width=1, border_color=panelBorder, frame_color=panelBorder, frame_width=1)
 
    table.cell(panel, 0, 0, "AG Pro Turtle Soup Reversal Map", bgcolor=headerBg, text_color=headerText, text_size=f_size(panelSize), text_halign=text.align_center)
    table.merge_cells(panel, 0, 0, 1, 0)
 
    table.cell(panel, 0, 1, "Status",                  bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(panelSize), text_halign=text.align_left)
    table.cell(panel, 1, 1, f_stateText(currentState), bgcolor=panelBg, text_color=f_stateCol(currentState), text_size=f_size(panelSize), text_halign=text.align_right)
 
    scoreTxt = currentState == 0 or na(setupScore) ? "—" : f_grade(setupScore) + "  " + str.tostring(math.round(setupScore)) + "/100"
    table.cell(panel, 0, 2, "Setup Quality", bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(panelSize), text_halign=text.align_left)
    table.cell(panel, 1, 2, scoreTxt,        bgcolor=panelBg, text_color=panelValueCol, text_size=f_size(panelSize), text_halign=text.align_right)
 
    table.cell(panel, 0, 3, "Lookback", bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(panelSize), text_halign=text.align_left)
    table.cell(panel, 1, 3, str.tostring(lookback) + " bars", bgcolor=panelBg, text_color=panelValueCol, text_size=f_size(panelSize), text_halign=text.align_right)
 
    table.cell(panel, 0, 4, "Confirmation", bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(panelSize), text_halign=text.align_left)
    table.cell(panel, 1, 4, confirmMode,    bgcolor=panelBg, text_color=panelValueCol, text_size=f_size(panelSize), text_halign=text.align_right)
 
    nRes = array.size(resultsArr)
    wins = 0
    for i = 0 to nRes - 1
        wins += array.get(resultsArr, i)
    wrTxt = nRes > 0 ? str.tostring(math.round(wins / nRes * 100)) + "%  (" + str.tostring(nRes) + ")" : "— (0)"
    table.cell(panel, 0, 5, "Win Rate", bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(panelSize), text_halign=text.align_left)
    table.cell(panel, 1, 5, wrTxt,      bgcolor=panelBg, text_color=panelValueCol, text_size=f_size(panelSize), text_halign=text.align_right)
 
    nRew = array.size(rewardsArr)
    sumR = 0.0
    for i = 0 to nRew - 1
        sumR += array.get(rewardsArr, i)
    avgR = nRew > 0 ? sumR / nRew : 0.0
    table.cell(panel, 0, 6, "Avg Reward", bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(panelSize), text_halign=text.align_left)
    table.cell(panel, 1, 6, str.tostring(avgR, "#.##") + "R", bgcolor=panelBg, text_color=panelValueCol, text_size=f_size(panelSize), text_halign=text.align_right)
 
    barsSince = currentState == 0 or na(setupBar) ? 0 : bar_index - setupBar
    table.cell(panel, 0, 7, "Bars Since Setup", bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(panelSize), text_halign=text.align_left)
    table.cell(panel, 1, 7, currentState == 0 ? "—" : str.tostring(barsSince), bgcolor=panelBg, text_color=panelValueCol, text_size=f_size(panelSize), text_halign=text.align_right)
 
    // Help — two-line split for compactness
    table.cell(panel, 0, 8, "Read: A+ strongest setup · B+ tradeable", bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(helpSize), text_halign=text.align_left)
    table.merge_cells(panel, 0, 8, 1, 8)
    table.cell(panel, 0, 9, "Score = wick + vol + overshoot + HTF + level", bgcolor=panelBg, text_color=panelLabelCol, text_size=f_size(helpSize), text_halign=text.align_left)
    table.merge_cells(panel, 0, 9, 1, 9)
 
// ═════════════════════════════════════════════════
// ALERTS
// ═════════════════════════════════════════════════
if alertPending and (newBearSetup or newBullSetup)
    dir = newBearSetup ? "Bear" : "Bull"
    alert("Turtle Soup Pending " + dir + " · Grade " + f_grade(setupScore) + " · " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
 
if alertFired and (confirmBear or confirmBull)
    dir = confirmBear ? "Bear" : "Bull"
    alert("Turtle Soup Fired " + dir + " · Grade " + f_grade(setupScore) + " · " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
 
if alertInvalid and (invalidBear or invalidBull)
    alert("Turtle Soup Invalidated · " + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)

← 返回列表