Coil & Break

stelko135 · study · 408 行 · 点赞 10 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════
//  SETUP FINDER — inside bar, bull flag, tight range
//  Long only. Finds setups; does not manage trades.
//
//  How to read the chart:
//    light blue bar = a setup is armed here, waiting
//    amber line     = the price it has to clear
//    A / B / C icon = the setup triggered, graded by how many
//                     independent factors agreed
//
//  Grading counts votes from sources that measure DIFFERENT
//  things — trend, momentum, volume, pressure. Two moving-average
//  crosses agreeing is one measurement read twice, not two votes.
//  That is why there is no EMA-cross signal in here.
//
//  No stops, no targets. Where risk sits and when to take profit
//  depend on an environment the chart cannot see.
// ═══════════════════════════════════════════════════════════
indicator("Setup Finder", overlay = true)
 
// ═══════════════════════════════════════════════════════════
//  CONTEXT — trend and momentum. No signals of their own.
// ═══════════════════════════════════════════════════════════
gX        = "Context"
trendLen  = input.int(200, "Trend MA length", minval = 1, group = gX)
trendType = input.string("EMA", "Trend MA type", options = ["SMA", "EMA"], group = gX)
reqTrend  = input.bool(true, "Only look for setups above the trend MA", group = gX,
     tooltip = "Long only means a setup against the trend is never actionable.")
confirmed = input.bool(true, "Trigger on closed bars only", group = gX,
     tooltip = "On: honest history, but on a daily chart the icon appears after " +
               "the close. Off: the icon appears the moment price clears the " +
               "level, and can disappear if price falls back before the close. " +
               "Off is the right setting while you are executing at the open.")
macdFast  = input.int(12, "MACD fast", minval = 1, group = gX)
macdSlow  = input.int(26, "MACD slow", minval = 1, group = gX)
 
f_ma(src, len, t) => t == "SMA" ? ta.sma(src, len) : ta.ema(src, len)
 
trendMA  = f_ma(close, trendLen, trendType)
macdLine = ta.ema(close, macdFast) - ta.ema(close, macdSlow)
// na(trendMA) means the chart has fewer bars than the MA needs. That
// is missing information, not a failed test — do not block on it.
trendOk  = not reqTrend or na(trendMA) or close > trendMA
 
// ═══════════════════════════════════════════════════════════
//  VOLUME — one place, used by the flag definition and the vote
// ═══════════════════════════════════════════════════════════
gVol    = "Volume"
volLen  = input.int(20, "Volume average (bars)", minval = 1, group = gVol)
volMult = input.float(1.2, "Above-average multiplier", minval = 0.1, step = 0.1, group = gVol)
volLive = input.string("Ignore it", "Volume while the bar is still open",
     options = ["Ignore it", "Use the volume so far"], group = gVol,
     tooltip = "A daily bar's volume is incomplete until the day closes. Half an " +
               "hour after the open you hold a fraction of a session compared " +
               "against whole sessions — the check fails for a reason that has " +
               "nothing to do with the breakout.\n\n" +
               "Ignore: the volume vote drops out of the grade entirely while the " +
               "bar is live, and rejoins at the close. The grade may change then.")
 
volAvg   = ta.sma(volume, volLen)
volReady = barstate.isconfirmed or volLive == "Use the volume so far"
volUsable = not na(volume) and volReady
 
// ═══════════════════════════════════════════════════════════
//  SETUP A — INSIDE BAR
//  A bar that sits inside the previous one: compression before
//  expansion. The tradable event is the breakout after it.
// ═══════════════════════════════════════════════════════════
gI       = "Setup — Inside bar"
useIB    = input.bool(true, "Enable", group = gI)
ibMode   = input.string("Range in range (classic)", "Pattern definition",
     options = ["Range in range (classic)", "Body in body (harami)", "Range in body (strict)"],
     group = gI,
     tooltip = "Range in range: the whole bar, wicks included, inside the previous " +
               "bar's range. The textbook inside bar.\n" +
               "Body in body: bodies only, wicks ignored. A harami — more frequent, " +
               "weaker.\n" +
               "Range in body: the whole bar inside the previous body. Rarest.")
ibStrict = input.bool(false, "Strict (reject equal edges)", group = gI)
ibRef    = input.string("Inside bar high", "Breakout level",
     options = ["Inside bar high", "Mother bar high"], group = gI,
     tooltip = "Mother bar high is the stronger confirmation — the whole " +
               "compression is cleared — but it fires later.")
ibClose  = input.bool(true, "Breakout needs a close above the level", group = gI,
     tooltip = "Off = an intrabar touch is enough.")
ibWin    = input.int(1, "Breakout window (bars after the inside bar)", minval = 1, group = gI,
     tooltip = "1 = the very next bar only, as in the classic setup.")
 
bodyHi  = math.max(open,    close)
bodyLo  = math.min(open,    close)
pBodyHi = math.max(open[1], close[1])
pBodyLo = math.min(open[1], close[1])
 
insideBar = switch ibMode
    "Body in body (harami)" =>
        ibStrict ? (bodyHi < pBodyHi and bodyLo > pBodyLo) : (bodyHi <= pBodyHi and bodyLo >= pBodyLo)
    "Range in body (strict)" =>
        ibStrict ? (high < pBodyHi and low > pBodyLo) : (high <= pBodyHi and low >= pBodyLo)
    =>
        ibStrict ? (high < high[1] and low > low[1]) : (high <= high[1] and low >= low[1])
 
var float ibHigh = na
var float ibMomH = na
var float ibLow  = na
var int   ibBar  = na
var bool  ibDone = false
 
if insideBar
    ibHigh := high
    ibMomH := high[1]
    ibLow  := low
    ibBar  := bar_index
    ibDone := false
 
// A close back under the inside bar kills the setup
if not na(ibLow) and close < ibLow
    ibDone := true
 
ibLevel   = ibRef == "Inside bar high" ? ibHigh : ibMomH
ibAge     = na(ibBar) ? na : bar_index - ibBar
ibAlive   = useIB and not ibDone and not na(ibAge) and ibAge <= ibWin
ibPending = ibAlive
ibBrk     = na(ibLevel) ? false : (ibClose ? close > ibLevel : high > ibLevel)
ibTrigRaw = ibAlive and not insideBar and ibAge >= 1 and ibBrk
 
// ═══════════════════════════════════════════════════════════
//  SETUP B — BULL FLAG
//  Pole : an impulsive rise inside the lookback window. It keeps
//         extending while price makes new highs, and freezes when
//         price stops.
//  Flag : the pause after it — shallow enough and short enough to
//         still be a pause rather than a reversal.
//  Break: a close above the flag's ceiling.
// ═══════════════════════════════════════════════════════════
gB       = "Setup — Bull flag"
useBF    = input.bool(true, "Enable", group = gB)
poleLen  = input.int(10, "Flagpole lookback (bars)", minval = 2, group = gB)
poleUnit = input.string("ATR", "Pole size measured in", options = ["ATR", "Percent"], group = gB)
poleMinA = input.float(3.0, "Min pole size (× ATR)", minval = 0.5, step = 0.5, group = gB)
poleMinP = input.float(5.0, "Min pole size (%)",     minval = 0.5, step = 0.5, group = gB)
flagMin  = input.int(3,  "Min flag length (bars)", minval = 1, group = gB)
flagMax  = input.int(15, "Max flag length (bars)", minval = 2, group = gB)
maxRetr  = input.float(50, "Max retracement of the pole (%)", minval = 10, maxval = 90,
     step = 5, group = gB,
     tooltip = "Deeper than this and the move is being undone, not paused.")
bfRefSel = input.string("Flag high (aggressive)", "Breakout level",
     options = ["Flag high (aggressive)", "Pole high (conservative)"], group = gB)
bfClose  = input.bool(true, "Breakout needs a close above the level", group = gB)
bfDry    = input.bool(true, "Volume must dry up during the flag", group = gB,
     tooltip = "The defining tell of a flag: no real sellers, just an absence of " +
               "buying while price rests. Measured on finished bars only, so the " +
               "live bar cannot distort it.")
 
atr14    = ta.atr(14)
poleLow  = ta.lowest(low, poleLen)
poleUp   = high - poleLow
poleReq  = poleUnit == "ATR" ? atr14 * poleMinA : poleLow * poleMinP / 100
poleOk   = poleUp >= poleReq
newHigh  = high >= ta.highest(high, poleLen)
polePace = ta.sma(volume, poleLen)
 
var float pHigh    = na
var float pLow     = na
var int   pBar     = na
var float flagLow  = na
var float flagHigh = na
var float poleVol  = na
var float flagVolS = 0.0
var int   flagVolN = 0
var bool  bfDone   = false
 
// 1. Track the flag's floor; only finished bars feed its volume
if not na(pBar) and bar_index > pBar
    flagLow := na(flagLow) ? low : math.min(flagLow, low)
    if barstate.isconfirmed
        flagVolS := flagVolS + nz(volume)
        flagVolN := flagVolN + 1
 
// 2. Too deep or too long and it is no longer a flag
retrLimit = na(pHigh) ? na : pHigh - (pHigh - pLow) * maxRetr / 100
flagAge   = na(pBar)  ? na : bar_index - pBar
if not na(flagLow) and not na(retrLimit) and flagLow < retrLimit
    bfDone := true
if not na(flagAge) and flagAge > flagMax
    bfDone := true
 
// 3. Did volume actually quieten down?
flagVolAvg = flagVolN > 0 ? flagVolS / flagVolN : na
dryReady   = not na(flagVolAvg) and not na(poleVol)
dryOk      = not bfDry or na(volume) or not dryReady or flagVolAvg < poleVol
 
// 4. Breakout — measured BEFORE the bar is allowed to raise the
//    ceiling it has to clear
bfRef     = bfRefSel == "Flag high (aggressive)" ? nz(flagHigh, pHigh) : pHigh
bfAlive   = useBF and not bfDone and not na(flagAge) and flagAge >= 1 and flagAge <= flagMax
bfPending = bfAlive
bfBrk     = na(bfRef) ? false : (bfClose ? close > bfRef : high > bfRef)
bfTrigRaw = bfAlive and flagAge >= flagMin and bfBrk and dryOk
 
// 5. Only now does this bar count towards the ceiling
if not na(pBar) and bar_index > pBar
    flagHigh := na(flagHigh) ? high : math.max(flagHigh, high)
 
// 6. A new qualifying high starts or extends the pole
if poleOk and newHigh
    pHigh    := high
    pLow     := poleLow
    pBar     := bar_index
    poleVol  := polePace
    flagLow  := na
    flagHigh := na
    flagVolS := 0.0
    flagVolN := 0
    bfDone   := false
 
// ═══════════════════════════════════════════════════════════
//  SETUP C — TIGHT RANGE
//  A quiet box with no flagpole behind it, which is why the flag
//  module cannot see it: that one refuses to wake up without an
//  impulsive rise, expires after 15 bars, and never measures how
//  narrow the range actually is.
//
//  A rolling window decides whether the range is tight; the box
//  then FREEZES its ceiling and floor. Freezing is the point — a
//  rolling highest would lift the ceiling on the very bar that
//  breaks it, so nothing could ever trigger, and the drawn level
//  would crawl upward instead of sitting still.
// ═══════════════════════════════════════════════════════════
gBx      = "Setup — Tight range"
useBox   = input.bool(true, "Enable", group = gBx)
bxWin    = input.int(5, "Tight window (bars)", minval = 2, group = gBx,
     tooltip = "How many bars get measured for tightness. This is also the " +
               "minimum length of the consolidation.")
bxMax    = input.int(10, "Max total length (bars)", minval = 2, group = gBx,
     tooltip = "Once the consolidation is older than this the box expires, and " +
               "it will not re-form until the range widens and tightens again.")
bxUnit   = input.string("ATR", "Tightness measured in", options = ["ATR", "Percent"],
     group = gBx)
bxTightA = input.float(1.5, "Max box height (× ATR)", minval = 0.1, step = 0.1, group = gBx)
bxTightP = input.float(3.0, "Max box height (%)",     minval = 0.1, step = 0.1, group = gBx)
bxClose  = input.bool(true, "Breakout needs a close above the ceiling", group = gBx)
bxNear   = input.bool(false, "Box must sit near the recent high", group = gBx,
     tooltip = "Off by default: the trend filter above the 200 MA already gives " +
               "the bullish context. Turn it on to reject quiet ranges that " +
               "formed after a decline.")
bxNearP  = input.float(3.0, "Near-high tolerance (%)", minval = 0.1, step = 0.5, group = gBx)
 
winHi = ta.highest(high, bxWin)
winLo = ta.lowest(low,   bxWin)
bxReq = bxUnit == "ATR" ? atr14 * bxTightA : winLo * bxTightP / 100
tight = (winHi - winLo) <= bxReq
 
nearRef = ta.highest(high, bxMax * 3)
nearOk  = not bxNear or na(nearRef) or winHi >= nearRef * (1 - bxNearP / 100)
 
var float bxHi   = na
var float bxLo   = na
var int   bxBar  = na
var bool  bxDone = false
 
// 1. Breakout against the STORED box, before this bar can touch it
bxAge     = na(bxBar) ? na : bar_index - bxBar
bxLive    = useBox and not na(bxHi) and not bxDone
bxBrk     = na(bxHi) ? false : (bxClose ? close > bxHi : high > bxHi)
bxTrigRaw = bxLive and bxBrk
 
// 2. A close under the floor kills it
if bxLive and close < bxLo
    bxDone := true
 
// 3. Too long and this is no longer a fresh consolidation
bxTotal = na(bxAge) ? na : bxAge + bxWin
if not na(bxTotal) and bxTotal > bxMax
    bxDone := true
 
// 4. Form a box only on a FRESHLY tight window. Without the freshness
//    test an expired box would re-form on the next bar out of the same
//    still-tight window, and the max length would mean nothing.
freshTight = tight and not tight[1]
if freshTight and nearOk and (na(bxHi) or bxDone)
    bxHi   := winHi
    bxLo   := winLo
    bxBar  := bar_index
    bxDone := false
 
boxPending = useBox and not na(bxHi) and not bxDone
 
// ═══════════════════════════════════════════════════════════
//  GRADING — how many independent factors back this breakout
//
//  Each vote comes from a different kind of evidence. A vote you
//  switch off, or one that cannot be measured yet, drops out of
//  the maximum too — so the grade is always relative to what is
//  actually knowable at this moment.
//
//    A  every available vote agreed          (two aces)
//    B  all but one                          (two queens)
//    C  anything weaker
// ═══════════════════════════════════════════════════════════
gQ       = "Grading"
qTrend   = input.bool(true, "Vote: price above the trend MA", group = gQ)
qMom     = input.bool(true, "Vote: MACD above zero",          group = gQ)
qVol     = input.bool(true, "Vote: above-average volume",     group = gQ)
qPress   = input.bool(true, "Vote: bar closes in its upper part", group = gQ)
qPressP  = input.float(60, "Strong close (% of bar range)", minval = 0, maxval = 100,
     step = 5, group = gQ)
minGrade = input.string("B and better", "Show which grades",
     options = ["A only", "B and better", "Everything"], group = gQ)
 
barRange = high - low
closePos = barRange > 0 ? (close - low) / barRange * 100 : 100.0
qVolAvail = qVol and volUsable
 
qT = qTrend    and close > trendMA
qM = qMom      and macdLine > 0
qV = qVolAvail and volume > volAvg * volMult
qP = qPress    and closePos >= qPressP
 
qMax   = (qTrend ? 1 : 0) + (qMom ? 1 : 0) + (qVolAvail ? 1 : 0) + (qPress ? 1 : 0)
qScore = (qT ? 1 : 0) + (qM ? 1 : 0) + (qV ? 1 : 0) + (qP ? 1 : 0)
 
isA = qScore >= qMax
isB = not isA and qScore >= qMax - 1
isC = not isA and not isB
 
showA = true
showB = minGrade != "A only"
showC = minGrade == "Everything"
 
// ═══════════════════════════════════════════════════════════
//  TRIGGERS
// ═══════════════════════════════════════════════════════════
ibTrig = ibTrigRaw and trendOk
bfTrig = bfTrigRaw and trendOk
bxTrig = bxTrigRaw and trendOk
 
ibTrig := confirmed ? ibTrig and barstate.isconfirmed : ibTrig
bfTrig := confirmed ? bfTrig and barstate.isconfirmed : bfTrig
bxTrig := confirmed ? bxTrig and barstate.isconfirmed : bxTrig
 
// One trigger per setup
if ibTrig
    ibDone := true
if bfTrig
    bfDone := true
if bxTrig
    bxDone := true
 
triggered = ibTrig or bfTrig or bxTrig
anyArmed  = ibPending or bfPending or boxPending
armed     = anyArmed and trendOk and not triggered
 
// The level an armed setup has to clear. Gated by `armed` so the line
// and the tint always appear together — one without the other is just
// confusing. Priority runs longest structure first: an inside bar's
// level usually sits inside a box anyway.
rawLvl  = bfPending ? bfRef : boxPending ? bxHi : ibPending ? ibLevel : na
pendLvl = armed ? rawLvl : na
 
// ═══════════════════════════════════════════════════════════
//  PLOTTING
//  Colors and icons live in the Style tab. text and size have to
//  be compile-time constants, so they are edited here.
// ═══════════════════════════════════════════════════════════
gV       = "Appearance"
showTint = input.bool(true, "Tint bars where a setup is armed", group = gV)
showPend = input.bool(true, "Draw the pending breakout level",  group = gV)
 
txtCol = chart.fg_color
 
barcolor(showTint and armed ? #81d4fa : na, title = "Armed setup")
 
plotshape(triggered and isA and showA, title = "Grade A",
     style = shape.labelup, location = location.belowbar,
     color = #00c853, textcolor = txtCol, text = "A", size = size.small,
     display = display.pane)
 
plotshape(triggered and isB and showB, title = "Grade B",
     style = shape.triangleup, location = location.belowbar,
     color = #ffab00, textcolor = txtCol, text = "B", size = size.small,
     display = display.pane)
 
plotshape(triggered and isC and showC, title = "Grade C",
     style = shape.circle, location = location.belowbar,
     color = #90a4ae, textcolor = txtCol, text = "C", size = size.tiny,
     display = display.pane)
 
plot(showPend and not na(pendLvl) ? pendLvl : na, "Pending breakout",
     color = #ffab00, style = plot.style_linebr, linewidth = 1)
 
plot(qScore, "Votes earned",   display = display.data_window)
plot(qMax,   "Votes possible", display = display.data_window)
 
// ═══════════════════════════════════════════════════════════
//  ALERTS
// ═══════════════════════════════════════════════════════════
alertcondition(triggered, "Setup triggered", "Setup triggered")
alertcondition(armed and not armed[1], "Setup armed", "A setup is now armed")
 
if triggered
    grade = isA ? "A" : isB ? "B" : "C"
    pRaw  = (ibTrig ? "IB " : "") + (bfTrig ? "FLAG " : "") + (bxTrig ? "BOX" : "")
    pattern = str.trim(pRaw)
    alert(grade + " setup — " + pattern + " " + syminfo.ticker + " @ " +
          str.tostring(close, format.mintick) + "  (" + str.tostring(qScore) +
          "/" + str.tostring(qMax) + " votes)",
          alert.freq_once_per_bar_close)

← 返回列表