Inducement & Trap Detector

ApexFlow_ · study · 387 行 · 点赞 820 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════════════
// Inducement & Trap Detector [ApexFlow]
// by ApexFlow
//
// Description
//   Finds closes beyond major swing highs/lows that fail within a few bars
//   (bull traps and bear traps), grades each trap from 0-100 on four equally
//   weighted components, marks the inducement level that forms after a genuine
//   break of structure, and tabulates which sessions produced the most traps.
//
// Original work
//   This script is original work by ApexFlow. The logic, scoring model and
//   code were written from scratch and are not copied from any other script.
//
// Disclaimer
//   Educational chart-analysis tool. Statistics describe loaded bars only.
// ═══════════════════════════════════════════════════════════════════════════════
indicator("Inducement & Trap Detector [ApexFlow]", shorttitle = "IDM Trap [ApexFlow]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
// ─────────────────────────────── Inputs ─────────────────────────────────────
string G1 = "Swing levels"
string G2 = "Trap detection"
string G3 = "Inducement"
string G4 = "Session statistics"
string G5 = "Colours"
 
int majorLen = input.int(10, "Major swing length", minval = 2, maxval = 50, group = G1, tooltip = "Bars on each side required to confirm a major swing high or low. A swing is only used once confirmed, majorLen bars after it formed.")
int keepN = input.int(5, "Swing levels kept per side", minval = 1, maxval = 20, group = G1, tooltip = "How many of the most recent unbroken major swing highs and lows are monitored for breakouts.")
bool showSwings = input.bool(true, "Draw active swing levels", group = G1, tooltip = "Thin dotted lines for swing levels that have not yet been broken.")
 
int trapWin = input.int(5, "Trap window (bars)", minval = 1, maxval = 30, group = G2, tooltip = "A breakout is a trap if a bar closes back through the broken level within this many bars after the breakout bar. Otherwise it counts as a genuine breakout.")
string minGrade = input.string("B", "Minimum grade to display", options = ["C", "B", "A", "A+"], group = G2, tooltip = "Traps graded below this are hidden and do not trigger alerts. They are still counted in the statistics table.")
bool showBos = input.bool(true, "Show BOS labels", group = G2, tooltip = "Tiny label on breakouts that did not fail within the trap window.")
 
bool showIdm = input.bool(true, "Show inducement", group = G3, tooltip = "After a genuine break of structure, the first minor swing pivot formed afterwards is marked as the inducement level.")
int minorLen = input.int(3, "Minor swing length", minval = 1, maxval = 20, group = G3, tooltip = "Bars on each side required to confirm the minor pivot used for inducement.")
 
bool showStats = input.bool(true, "Show session table", group = G4, tooltip = "Breakouts and traps per session. Each breakout belongs to the session of its breakout bar and is counted once it resolves (trap or genuine).")
string statsPosIn = input.string("Top right", "Table position", options = ["Top left", "Top right", "Bottom left", "Bottom right"], group = G4)
string tzIn = input.string("America/New_York", "Session timezone", group = G4, tooltip = "Timezone used to interpret the session ranges below (IANA name).")
string asiaSess = input.session("2000-0000", "Asia", group = G4)
string lonSess = input.session("0200-0500", "London", group = G4)
string nySess = input.session("0930-1600", "New York", group = G4)
bool showGuide = input.bool(true, "Show 'How to read' guide", group = G4, tooltip = "A small legend explaining every mark this indicator draws.")
string guidePosIn = input.string("Bottom left", "Guide position", options = ["Top left", "Top right", "Bottom left", "Bottom right"], group = G4)
 
color cBear = input.color(#F23645, "Bearish", group = G5)
color cBull = input.color(#089981, "Bullish", group = G5)
color cAccent = input.color(#FF9800, "Grade / inducement accent", group = G5)
color cNeutral = input.color(#787B86, "Neutral grey", group = G5)
 
// ─────────────────────────────── Helpers ────────────────────────────────────
f_ratio(float a, float b) => b > 0.0 ? a / b : 0.0
f_grade(float s) => s >= 80.0 ? "A+" : s >= 65.0 ? "A" : s >= 50.0 ? "B" : "C"
f_rank(string g) => g == "A+" ? 3 : g == "A" ? 2 : g == "B" ? 1 : 0
f_pos(string p) => p == "Top left" ? position.top_left : p == "Top right" ? position.top_right : p == "Bottom left" ? position.bottom_left : position.bottom_right
f_sname(int s) => s == 0 ? "Asia" : s == 1 ? "London" : s == 2 ? "New York" : "Other"
f_rate(int b, int t) => b > 0 ? str.tostring(100.0 * t / b, "0.0") + "%" : "-"
 
f_row(table t, int r, string nm, int b, int tr, bool bold) =>
    color tc = bold ? color.white : #D1D4DC
    table.cell(t, 0, r, nm, text_color = tc, text_size = size.small, text_halign = text.align_left)
    table.cell(t, 1, r, str.tostring(b), text_color = tc, text_size = size.small)
    table.cell(t, 2, r, str.tostring(tr), text_color = tc, text_size = size.small)
    table.cell(t, 3, r, f_rate(b, tr), text_color = cAccent, text_size = size.small)
 
f_gRow(table t, int r, string sym, color sc, string txt) =>
    table.cell(t, 0, r, sym, text_color = sc, text_size = size.small, text_halign = text.align_left)
    table.cell(t, 1, r, txt, text_color = #D1D4DC, text_size = size.small, text_halign = text.align_left)
 
// ───────────────── Indicator series (global scope, every bar) ───────────────
float majHi = ta.pivothigh(majorLen, majorLen)
float majLo = ta.pivotlow(majorLen, majorLen)
float minHi = ta.pivothigh(minorLen, minorLen)
float minLo = ta.pivotlow(minorLen, minorLen)
float atr14 = ta.atr(14)
float volSma = ta.sma(volume, 20)
 
float atrV = nz(atr14)
bool hasVol = not na(volume) and volume > 0 and not na(volSma) and volSma > 0
float volRatio = hasVol ? volume / volSma : -1.0
 
bool inAsia = not na(time(timeframe.period, asiaSess, tzIn))
bool inLon = not na(time(timeframe.period, lonSess, tzIn))
bool inNY = not na(time(timeframe.period, nySess, tzIn))
int sessId = inAsia ? 0 : inLon ? 1 : inNY ? 2 : 3
 
int minRank = f_rank(minGrade)
 
// ─────────────────────────────── State ──────────────────────────────────────
// Active (unbroken) major swings. Parallel arrays: price, bar index, line.
var array<float> hiPrice = array.new<float>()
var array<int> hiBar = array.new<int>()
var array<line> hiLine = array.new<line>()
var array<float> loPrice = array.new<float>()
var array<int> loBar = array.new<int>()
var array<line> loLine = array.new<line>()
 
// Pending breakouts being tracked through the trap window. pDir: 1 = up, -1 = down.
var array<float> pLevel = array.new<float>()
var array<int> pBar = array.new<int>()
var array<float> pExt = array.new<float>()
var array<float> pVolR = array.new<float>()
var array<int> pSess = array.new<int>()
var array<int> pDir = array.new<int>()
 
// Drawing registries, so old objects can be deleted before limits are reached.
var array<box> trapBoxes = array.new<box>()
var array<label> trapLabels = array.new<label>()
var array<line> idmLines = array.new<line>()
var array<label> idmLabels = array.new<label>()
 
// Session statistics (index 0-3 = Asia, London, New York, Other).
var array<int> sBrk = array.new<int>(4, 0)
var array<int> sTrp = array.new<int>(4, 0)
 
// Inducement state, bullish side (after BOS up, waits for a minor pivot low).
var bool bullWait = false
var int bullBosBar = na
var bool bullIdmOn = false
var float bullIdmLvl = na
var int bullIdmBar = na
var line bullIdmLine = na
var label bullIdmLbl = na
// Inducement state, bearish side (after BOS down, waits for a minor pivot high).
var bool bearWait = false
var int bearBosBar = na
var bool bearIdmOn = false
var float bearIdmLvl = na
var int bearIdmBar = na
var line bearIdmLine = na
var label bearIdmLbl = na
 
var table tbl = na
var table guide = na
var string lastTxt = ""
var int lastBar = na
 
// Per-bar event flags for alerts.
bool bullTrapEv = false
bool bearTrapEv = false
bool aPlusEv = false
bool idmEv = false
string alertMsg = ""
 
// ─────────────────────── Main logic (confirmed bars only) ───────────────────
if barstate.isconfirmed
    // 1) Resolve pending breakouts: trap, genuine breakout, or keep waiting.
    int pn = array.size(pLevel)
    if pn > 0
        for i = pn - 1 to 0
            int dir = array.get(pDir, i)
            float lvl = array.get(pLevel, i)
            int bb = array.get(pBar, i)
            int sx = array.get(pSess, i)
            float vr = array.get(pVolR, i)
            float ext = array.get(pExt, i)
            ext := dir == 1 ? math.max(ext, high) : math.min(ext, low)
            int k = bar_index - bb
            bool failed = dir == 1 ? close < lvl : close > lvl
            bool done = false
            if failed
                // Trap grade: four components of 25 points each.
                float exc = dir == 1 ? ext - lvl : lvl - ext
                float s1 = 25.0 * math.min(1.0, f_ratio(exc, atrV))
                float s2 = vr >= 0.0 ? 25.0 * math.min(1.0, vr / 2.0) : 0.0
                float s3 = 25.0 * (trapWin - k + 1) / trapWin
                float s4 = 25.0 * math.min(1.0, f_ratio(math.abs(close - open), atrV))
                float score = vr >= 0.0 ? s1 + s2 + s3 + s4 : (s1 + s3 + s4) * 100.0 / 75.0
                string grade = f_grade(score)
                array.set(sBrk, sx, array.get(sBrk, sx) + 1)
                array.set(sTrp, sx, array.get(sTrp, sx) + 1)
                if f_rank(grade) >= minRank
                    color tc = dir == 1 ? cBear : cBull
                    float boxTop = dir == 1 ? ext : lvl
                    float boxBot = dir == 1 ? lvl : ext
                    box bx = box.new(bb, boxTop, bar_index, boxBot, border_color = color.new(tc, 40), bgcolor = color.new(tc, 85), border_width = 1)
                    array.push(trapBoxes, bx)
                    if array.size(trapBoxes) > 250
                        box.delete(array.shift(trapBoxes))
                    string volTxt = vr >= 0.0 ? "Breakout volume: " + str.tostring(s2, "0.0") + "/25" : "Breakout volume: n/a (no volume data, score rescaled)"
                    string story = dir == 1 ? "Price broke ABOVE the swing high at " + str.tostring(lvl, format.mintick) + ", then closed back below it " + str.tostring(k) + " bar(s) later.\nBuyers who chased the breakout are now trapped.\nBias: bearish while price stays below " + str.tostring(lvl, format.mintick) + "." : "Price broke BELOW the swing low at " + str.tostring(lvl, format.mintick) + ", then closed back above it " + str.tostring(k) + " bar(s) later.\nSellers who chased the breakdown are now trapped.\nBias: bullish while price stays above " + str.tostring(lvl, format.mintick) + "."
                    string tip = story + "\n\nTrap grade " + grade + " (" + str.tostring(score, "0") + "/100)\n• Size of the fake move: " + str.tostring(s1, "0.0") + "/25\n• " + volTxt + "\n• Speed of failure: " + str.tostring(s3, "0.0") + "/25\n• Strength of reversal candle: " + str.tostring(s4, "0.0") + "/25"
                    string txt = (dir == 1 ? "▼ Trapped buyers · " : "▲ Trapped sellers · ") + grade
                    lastTxt := (dir == 1 ? "▼ Trapped buyers " : "▲ Trapped sellers ") + grade + " at " + str.tostring(lvl, format.mintick)
                    lastBar := bar_index
                    float ly = dir == 1 ? high : low
                    label lb = label.new(bar_index, ly, txt, style = dir == 1 ? label.style_label_down : label.style_label_up, color = tc, textcolor = color.white, size = size.small, tooltip = tip)
                    array.push(trapLabels, lb)
                    if array.size(trapLabels) > 350
                        label.delete(array.shift(trapLabels))
                    if dir == 1
                        bullTrapEv := true
                    else
                        bearTrapEv := true
                    if grade == "A+"
                        aPlusEv := true
                    alertMsg += (dir == 1 ? "Bull trap " : "Bear trap ") + grade + " | level " + str.tostring(lvl, format.mintick) + " | " + syminfo.ticker + "\n"
                done := true
            else if k >= trapWin
                // Genuine breakout (break of structure).
                array.set(sBrk, sx, array.get(sBrk, sx) + 1)
                if showBos
                    float bosY = dir == 1 ? low[k] : high[k]
                    string bosTip = "Break of structure: price closed " + (dir == 1 ? "above the swing high" : "below the swing low") + " at " + str.tostring(lvl, format.mintick) + " and held for " + str.tostring(trapWin) + " bars. The breakout was real, not a trap."
                    label bl = label.new(bb, bosY, "BOS ✓", style = dir == 1 ? label.style_label_up : label.style_label_down, color = color.new(cNeutral, 100), textcolor = dir == 1 ? cBull : cBear, size = size.small, tooltip = bosTip)
                    array.push(trapLabels, bl)
                    if array.size(trapLabels) > 350
                        label.delete(array.shift(trapLabels))
                if showIdm
                    if dir == 1
                        bullWait := true
                        bullBosBar := bar_index
                        if bullIdmOn
                            line.delete(bullIdmLine)
                            label.delete(bullIdmLbl)
                            bullIdmOn := false
                    else
                        bearWait := true
                        bearBosBar := bar_index
                        if bearIdmOn
                            line.delete(bearIdmLine)
                            label.delete(bearIdmLbl)
                            bearIdmOn := false
                done := true
            if done
                array.remove(pLevel, i)
                array.remove(pBar, i)
                array.remove(pExt, i)
                array.remove(pVolR, i)
                array.remove(pSess, i)
                array.remove(pDir, i)
            else
                array.set(pExt, i, ext)
 
    // 2) New breakouts: a close beyond an active major swing level.
    int nh = array.size(hiPrice)
    if nh > 0
        for i = nh - 1 to 0
            float lv = array.get(hiPrice, i)
            if close > lv
                array.push(pLevel, lv)
                array.push(pBar, bar_index)
                array.push(pExt, high)
                array.push(pVolR, volRatio)
                array.push(pSess, sessId)
                array.push(pDir, 1)
                line.delete(array.get(hiLine, i))
                array.remove(hiPrice, i)
                array.remove(hiBar, i)
                array.remove(hiLine, i)
    int nl = array.size(loPrice)
    if nl > 0
        for i = nl - 1 to 0
            float lv = array.get(loPrice, i)
            if close < lv
                array.push(pLevel, lv)
                array.push(pBar, bar_index)
                array.push(pExt, low)
                array.push(pVolR, volRatio)
                array.push(pSess, sessId)
                array.push(pDir, -1)
                line.delete(array.get(loLine, i))
                array.remove(loPrice, i)
                array.remove(loBar, i)
                array.remove(loLine, i)
 
    // 3) Register newly confirmed major swings (drawn at the pivot bar via offset).
    if not na(majHi)
        array.push(hiPrice, majHi)
        array.push(hiBar, bar_index - majorLen)
        line hl = na
        if showSwings
            hl := line.new(bar_index - majorLen, majHi, bar_index, majHi, extend = extend.right, color = color.new(cBear, 30), style = line.style_dotted, width = 1)
        array.push(hiLine, hl)
        if array.size(hiPrice) > keepN
            line.delete(array.shift(hiLine))
            array.shift(hiPrice)
            array.shift(hiBar)
    if not na(majLo)
        array.push(loPrice, majLo)
        array.push(loBar, bar_index - majorLen)
        line ll = na
        if showSwings
            ll := line.new(bar_index - majorLen, majLo, bar_index, majLo, extend = extend.right, color = color.new(cBull, 30), style = line.style_dotted, width = 1)
        array.push(loLine, ll)
        if array.size(loPrice) > keepN
            line.delete(array.shift(loLine))
            array.shift(loPrice)
            array.shift(loBar)
 
    // 4) Inducement. First check whether an active level has been taken,
    //    then look for the first minor pivot after a BOS.
    if showIdm
        if bullIdmOn and low < bullIdmLvl
            line.set_x2(bullIdmLine, bar_index)
            line.set_extend(bullIdmLine, extend.none)
            label tl = label.new(bar_index, low, "IDM taken ✓", style = label.style_label_up, color = color.new(cAccent, 100), textcolor = cAccent, size = size.small, tooltip = "Price swept the inducement level. The liquidity resting below the first pullback has been taken.")
            array.push(idmLabels, tl)
            bullIdmOn := false
            idmEv := true
            alertMsg += "Bullish inducement taken | level " + str.tostring(bullIdmLvl, format.mintick) + " | " + syminfo.ticker + "\n"
        if bearIdmOn and high > bearIdmLvl
            line.set_x2(bearIdmLine, bar_index)
            line.set_extend(bearIdmLine, extend.none)
            label tl = label.new(bar_index, high, "IDM taken ✓", style = label.style_label_down, color = color.new(cAccent, 100), textcolor = cAccent, size = size.small, tooltip = "Price swept the inducement level. The liquidity resting above the first pullback has been taken.")
            array.push(idmLabels, tl)
            bearIdmOn := false
            idmEv := true
            alertMsg += "Bearish inducement taken | level " + str.tostring(bearIdmLvl, format.mintick) + " | " + syminfo.ticker + "\n"
 
        if bullWait and not na(minLo) and bar_index - minorLen > bullBosBar
            bullWait := false
            bullIdmOn := true
            bullIdmLvl := minLo
            bullIdmBar := bar_index - minorLen
            bullIdmLine := line.new(bullIdmBar, minLo, bar_index, minLo, extend = extend.right, color = cAccent, style = line.style_dotted, width = 1)
            bullIdmLbl := label.new(bullIdmBar, minLo, "IDM", style = label.style_label_up, color = color.new(cAccent, 100), textcolor = cAccent, size = size.small, tooltip = "Inducement: the first pullback low after a bullish break of structure. Stops of early buyers sit below it, so price often sweeps it before continuing up.")
            array.push(idmLines, bullIdmLine)
            array.push(idmLabels, bullIdmLbl)
        if bearWait and not na(minHi) and bar_index - minorLen > bearBosBar
            bearWait := false
            bearIdmOn := true
            bearIdmLvl := minHi
            bearIdmBar := bar_index - minorLen
            bearIdmLine := line.new(bearIdmBar, minHi, bar_index, minHi, extend = extend.right, color = cAccent, style = line.style_dotted, width = 1)
            bearIdmLbl := label.new(bearIdmBar, minHi, "IDM", style = label.style_label_down, color = color.new(cAccent, 100), textcolor = cAccent, size = size.small, tooltip = "Inducement: the first pullback high after a bearish break of structure. Stops of early sellers sit above it, so price often sweeps it before continuing down.")
            array.push(idmLines, bearIdmLine)
            array.push(idmLabels, bearIdmLbl)
        if array.size(idmLines) > 100
            line.delete(array.shift(idmLines))
        if array.size(idmLabels) > 120
            label.delete(array.shift(idmLabels))
 
// ─────────────────────────────── Alerts ─────────────────────────────────────
alertcondition(bullTrapEv, "Bull trap", "Bull trap: breakout above a swing high failed")
alertcondition(bearTrapEv, "Bear trap", "Bear trap: breakout below a swing low failed")
alertcondition(aPlusEv, "A+ trap", "A+ graded trap detected")
alertcondition(idmEv, "Inducement taken", "Inducement level taken")
 
if alertMsg != ""
    alert(alertMsg, alert.freq_once_per_bar_close)
 
// ─────────────────────────── Session statistics table ───────────────────────
if barstate.islast and showStats
    if not na(tbl)
        table.delete(tbl)
    bool htf = timeframe.isdwm
    int nRows = htf ? 5 : 9
    tbl := table.new(f_pos(statsPosIn), 4, nRows, bgcolor = color.new(#0E1117, 6), frame_color = #2A2E39, frame_width = 1, border_color = color.new(#2A2E39, 40), border_width = 1)
    table.cell(tbl, 0, 0, "HOW OFTEN BREAKOUTS FAIL  ·  " + syminfo.ticker, text_color = color.white, text_size = size.normal, text_halign = text.align_left)
    table.merge_cells(tbl, 0, 0, 3, 0)
    table.cell(tbl, 0, 1, "Session", text_color = #787B86, text_size = size.tiny, text_halign = text.align_left)
    table.cell(tbl, 1, 1, "Breakouts", text_color = #787B86, text_size = size.tiny)
    table.cell(tbl, 2, 1, "Failed", text_color = #787B86, text_size = size.tiny)
    table.cell(tbl, 3, 1, "Fail rate", text_color = #787B86, text_size = size.tiny)
    int totB = 0
    int totT = 0
    for s = 0 to 3
        int bv = array.get(sBrk, s)
        int tv = array.get(sTrp, s)
        totB += bv
        totT += tv
        if not htf
            f_row(tbl, s + 2, f_sname(s), bv, tv, false)
    int totRow = htf ? 2 : 6
    f_row(tbl, totRow, "All sessions", totB, totT, true)
    string latest = lastTxt == "" ? "Latest trap: none shown yet" : "Latest: " + lastTxt + "  ·  " + str.tostring(bar_index - lastBar) + " bars ago"
    table.cell(tbl, 0, totRow + 1, latest, text_color = lastTxt == "" ? #787B86 : str.startswith(lastTxt, "▼") ? cBear : cBull, text_size = size.small, text_halign = text.align_left)
    table.merge_cells(tbl, 0, totRow + 1, 3, totRow + 1)
    table.cell(tbl, 0, nRows - 1, "Stats on loaded bars only. Not a prediction.", text_color = #787B86, text_size = size.tiny, text_halign = text.align_left)
    table.merge_cells(tbl, 0, nRows - 1, 3, nRows - 1)
 
// ─────────────────────────── How-to-read guide ──────────────────────────────
if barstate.islast and showGuide
    if not na(guide)
        table.delete(guide)
    guide := table.new(f_pos(guidePosIn), 2, 7, bgcolor = color.new(#0E1117, 6), frame_color = #2A2E39, frame_width = 1, border_color = color.new(#2A2E39, 40), border_width = 1)
    table.cell(guide, 0, 0, "HOW TO READ", text_color = color.white, text_size = size.normal, text_halign = text.align_left)
    table.merge_cells(guide, 0, 0, 1, 0)
    f_gRow(guide, 1, "▼ Trapped buyers", cBear, "Breakout above a swing high failed → bearish")
    f_gRow(guide, 2, "▲ Trapped sellers", cBull, "Breakdown below a swing low failed → bullish")
    f_gRow(guide, 3, "Shaded box", cNeutral, "The fake move where traders got caught")
    f_gRow(guide, 4, "BOS ✓", cNeutral, "Breakout held → trend continues")
    f_gRow(guide, 5, "IDM", cAccent, "First pullback after BOS, often swept next")
    f_gRow(guide, 6, "A+  A  B  C", cAccent, "Trap quality. Hover any label for details")

← 返回列表