Liquidity & Inducement + Sessions [TradeIQ]

Tradeiqofficial · study · 846 行 · 点赞 551 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Liquidity & Inducement: buy-side / sell-side liquidity, equal highs and lows, session and previous day / week levels,
// inducement (IDM), BOS / CHoCH and graded liquidity-sweep signals with filters. Built for forex and crypto. © TradeIQ
// Non-repainting: sweeps, signals, inducement and structure breaks are only confirmed when the candle closes.
// Education only, not financial advice.
//@version=6
indicator("Liquidity & Inducement + Sessions [TradeIQ]", shorttitle = "Liquidity IDM", overlay = true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500, max_bars_back = 1000)
 
// ═════════════════════════════════════════ INPUTS ═════════════════════════════════════════
G_MK = "1 · Market & Sessions"
mkt       = input.string("Auto", "Market", ["Auto", "Forex", "Crypto"], group = G_MK,
     tooltip = "Auto reads the symbol type. Forex: volume filter off (tick volume only), candles grey outside the sessions, distances in pips. Crypto: volume filter on, candles grey on low volume, distances in %.")
tz        = input.string("America/New_York", "Session time zone", group = G_MK,
     tooltip = "Default hours are the ICT kill zones in New York time. Any IANA name or offset works: Europe/London, UTC, GMT+2… For full sessions use e.g. Asia 1900-0400, London 0300-1200, New York 0800-1700.")
maxSessTf = input.timeframe("60", "Show sessions up to timeframe", group = G_MK)
sOn1 = input.bool(true, "Asia      ", inline = "s1", group = G_MK)
sT1  = input.session("2000-0000", "", inline = "s1", group = G_MK)
sC1  = input.color(#9c6bff, "", inline = "s1", group = G_MK)
sOn2 = input.bool(true, "London   ", inline = "s2", group = G_MK)
sT2  = input.session("0200-0500", "", inline = "s2", group = G_MK)
sC2  = input.color(#2f8cff, "", inline = "s2", group = G_MK)
sOn3 = input.bool(true, "New York ", inline = "s3", group = G_MK)
sT3  = input.session("0700-1000", "", inline = "s3", group = G_MK)
sC3  = input.color(#ffa726, "", inline = "s3", group = G_MK)
sOn4 = input.bool(false, "NY PM     ", inline = "s4", group = G_MK)
sT4  = input.session("1330-1600", "", inline = "s4", group = G_MK)
sC4  = input.color(#26c6da, "", inline = "s4", group = G_MK)
sessDraw  = input.string("Box", "Draw sessions as", ["Box", "Background", "Off"], group = G_MK)
sessLiq   = input.bool(true, "Session high / low = liquidity", group = G_MK)
pdLiq     = input.bool(true, "Previous day high / low (PDH / PDL)", group = G_MK)
pwLiq     = input.bool(true, "Previous week high / low (PWH / PWL)", group = G_MK)
 
G_LQ = "2 · Liquidity Levels"
showLiq   = input.bool(true, "Show liquidity levels", group = G_LQ)
liqLen    = input.int(5, "Swing length", minval = 2, maxval = 50, group = G_LQ, tooltip = "Stops rest beyond every swing high (buy-side, BSL) and swing low (sell-side, SSL).")
eqTol     = input.float(0.1, "Equal highs / lows tolerance (ATR ×)", minval = 0, step = 0.05, group = G_LQ, tooltip = "Two swings this close become one stronger level: EQH / EQL.")
maxPools  = input.int(25, "Max live levels per side", minval = 3, maxval = 100, group = G_LQ)
maxAge    = input.int(500, "Forget untouched levels after (bars)", minval = 50, maxval = 5000, group = G_LQ)
keepSwept = input.bool(true, "Keep swept / broken levels on chart", group = G_LQ)
bslC      = input.color(#ff5e7a, "Buy-side (above)", inline = "lc", group = G_LQ)
sslC      = input.color(#3ddc97, "Sell-side (below)", inline = "lc", group = G_LQ)
 
G_ID = "3 · Structure & Inducement"
showMS    = input.bool(true, "Show BOS / CHoCH", group = G_ID)
swLen     = input.int(10, "Structure swing length", minval = 2, group = G_ID)
showIDM   = input.bool(true, "Show inducement (IDM)", group = G_ID,
     tooltip = "After a bullish break, the latest internal pullback low is the inducement: early buyers' stops. When price takes it, the pullback is real and buys from deeper liquidity get better. Mirror for bearish.")
idmLen    = input.int(3, "Internal swing length", minval = 1, maxval = 20, group = G_ID)
idmC      = input.color(#ffca28, "IDM color", group = G_ID)
 
G_SG = "4 · Trend Sweep Signals & Filters"
showSig   = input.bool(true, "Show trend sweep signals (B / S)", group = G_SG, tooltip = "With the trend: buy when sell-side liquidity is swept in an uptrend, sell when buy-side is swept in a downtrend.")
sigMode   = input.string("Normal + Strong", "Signals to show", ["Strong only", "Normal + Strong", "All (incl. weak)"], group = G_SG,
     tooltip = "Weak = fails one of the filters below. Normal = passes every filter you switched on. Strong = Normal + the higher-timeframe trend agrees + the swept level is a key level (equal H/L, session, day / week) or the inducement was taken first.")
useSwing  = input.bool(true, "Swing", inline = "lt", group = G_SG)
useEq     = input.bool(true, "Equal H/L", inline = "lt", group = G_SG)
useSess   = input.bool(true, "Session", inline = "lt", group = G_SG)
usePD     = input.bool(true, "Day / Week", inline = "lt", group = G_SG)
minDepth  = input.float(0.0, "Min sweep depth (ATR ×)", minval = 0, step = 0.05, group = G_SG, tooltip = "How far the wick must poke past the level.")
confMode  = input.string("Close back inside", "Confirmation", ["Close back inside", "Next candle confirms", "Internal CHoCH"], group = G_SG,
     tooltip = "Close back inside: the sweep candle wicks through and closes back. Next candle confirms: a later candle closes beyond the sweep candle. Internal CHoCH: a later candle closes beyond the last internal swing.")
confWin   = input.int(5, "Confirmation window (bars)", minval = 1, maxval = 50, group = G_SG)
sessFlt   = input.string("Any time", "Session filter", ["Any time", "Inside any session", "London + New York"], group = G_SG)
trendFlt  = input.string("Structure", "Trend filter", ["Structure", "EMA 200", "Off"], group = G_SG, tooltip = "Buy sweeps of sell-side liquidity only in an uptrend, sell sweeps of buy-side only in a downtrend.")
idmFlt    = input.bool(false, "Require inducement taken first", inline = "id", group = G_SG)
idmWin    = input.int(30, "within bars", minval = 1, inline = "id", group = G_SG)
volFlt    = input.string("Auto", "Volume filter", ["Auto", "On", "Off"], group = G_SG, tooltip = "Auto = on for crypto, off for forex.")
volMult   = input.float(1.2, "Volume ≥ average ×", minval = 0, step = 0.1, group = G_SG)
htfTf     = input.timeframe("D", "Higher timeframe (Strong)", group = G_SG)
htfLen    = input.int(50, "Higher timeframe EMA", minval = 1, group = G_SG)
cooldown  = input.int(5, "Min bars between signals", minval = 0, group = G_SG)
 
G_RV = "4b · Reversal Signals"
showRev   = input.bool(true, "Show reversal signals", group = G_RV,
     tooltip = "A key level is swept (session high / low, previous day / week, equal highs / lows), then price shifts the other way. Classic London or New York Judas swing: the session runs the Asia high, traps breakout buyers and reverses.")
rvSwing   = input.bool(false, "Swing", inline = "rl", group = G_RV)
rvEq      = input.bool(true, "Equal H/L", inline = "rl", group = G_RV)
rvSess    = input.bool(true, "Session", inline = "rl", group = G_RV)
rvPD      = input.bool(true, "Day / Week", inline = "rl", group = G_RV)
rvConf    = input.string("Internal CHoCH", "Reversal confirmation", ["Internal CHoCH", "Next candle confirms", "Close back inside"], group = G_RV,
     tooltip = "Internal CHoCH: after the sweep a candle closes beyond the last internal swing on the other side. Next candle confirms: a later candle closes beyond the sweep candle. Close back inside: the sweep candle itself is the signal (earliest, most signals).")
rvWin     = input.int(10, "Confirmation window (bars)", minval = 1, maxval = 50, group = G_RV)
rvTrend   = input.string("Against structure", "Direction", ["Against structure", "Any"], group = G_RV,
     tooltip = "Against structure: only reversals that turn the current trend (buy in a bearish structure, sell in a bullish one). With-trend sweeps are left to the B / S signals.")
rvDisp    = input.float(1.0, "Strong: confirm candle body ≥ ATR ×", minval = 0, step = 0.1, group = G_RV,
     tooltip = "Strong reversal = key level (equal H/L, session or day / week) + a displacement candle this big, or volume ≥ the volume setting.")
rvZoneF   = input.bool(true, "Buy only in discount, sell only in premium", group = G_RV, tooltip = "Uses the premium / discount dealing range (section 6). Reversals on the wrong side are graded weak.")
rvShowLv  = input.bool(true, "Name the swept level on the label", group = G_RV)
 
G_TP = "5 · Stop & Targets"
showTP    = input.bool(true, "Show stop and targets", group = G_TP)
slBuf     = input.float(0.25, "Stop beyond sweep wick (ATR ×)", minval = 0, step = 0.05, group = G_TP)
tpStep    = input.float(1.0, "Target spacing (R)", minval = 0.1, step = 0.1, group = G_TP, tooltip = "Targets at 1×, 2× and 3× this distance in R (R = entry-to-stop distance).")
 
G_UI = "6 · Candles & Dashboard"
colorBars = input.bool(true, "Color candles by premium / discount", group = G_UI,
     tooltip = "Top of the dealing range (premium) = red candles: look for sells. Bottom (discount) = green candles: look for buys. Around the 50% equilibrium = grey.")
pdSrc     = input.string("Structure swings", "Dealing range from", ["Structure swings", "Lookback"], group = G_UI,
     tooltip = "Structure swings: from the latest structure swing low to swing high (stretched when price goes past them). Lookback: highest high to lowest low of the last N bars.")
pdLen     = input.int(100, "Lookback (bars)", minval = 10, maxval = 1000, group = G_UI)
eqBand    = input.float(10, "Equilibrium band ± %", minval = 0, maxval = 40, step = 1, group = G_UI, tooltip = "Candles inside 50% ± this are grey. 0 = no grey middle.")
pdShade   = input.string("Gradient", "Candle shading", ["Gradient", "Solid"], group = G_UI, tooltip = "Gradient: the deeper into premium / discount, the stronger the red / green.")
showPD    = input.bool(true, "Show premium / discount zones", group = G_UI)
greyMode  = input.string("Off", "Also grey candles on", ["Auto", "Low volume or range", "Outside sessions or range", "Range only", "Off"], group = G_UI,
     tooltip = "Auto = outside sessions or range for forex, low volume or range for crypto.")
lowVolX   = input.float(0.8, "Low volume: 5-bar avg < 50-bar avg ×", minval = 0.1, step = 0.05, group = G_UI)
rangeX    = input.float(0.3, "Range: EMA 13 / 34 gap < ATR ×", minval = 0, step = 0.05, group = G_UI, tooltip = "When the 13 and 34 EMA (not drawn) are this close, the market is flat and the candles turn grey.")
showTbl   = input.bool(true, "Show dashboard", group = G_UI)
tblPos    = input.string("Bottom Right", "Dashboard position", ["Top Right", "Bottom Right", "Bottom Left", "Top Left"], group = G_UI)
bullC     = input.color(#00e676, "Bull", inline = "cc", group = G_UI)
bearC     = input.color(#ff2e55, "Bear", inline = "cc", group = G_UI)
greyC     = input.color(#6b6f7a, "Grey", inline = "cc", group = G_UI)
textC     = input.color(#d1d4dc, "Text", inline = "cc", group = G_UI)
 
// ═════════════════════════════════════════ CORE SERIES ═════════════════════════════════════════
bool conf = barstate.isconfirmed
float atr = ta.atr(14)
float ema200 = ta.ema(close, 200)
float volAvg = ta.sma(volume, 20)
float vol5 = ta.sma(volume, 5)
float vol50 = ta.sma(volume, 50)
bool hasVol = ta.cum(nz(volume)) > 0
bool isFx = mkt == "Forex" or (mkt == "Auto" and syminfo.type == "forex")
bool useVol = volFlt == "On" or (volFlt == "Auto" and not isFx)
int htfDir = request.security(syminfo.tickerid, htfTf, close[1] > ta.ema(close, htfLen)[1] ? 1 : -1, lookahead = barmerge.lookahead_on)
 
// ═════════════════════════════════════════ RANGE DETECTOR (not drawn) ═════════════════════════════════════════
float eFast = ta.ema(close, 13)
float eSlow = ta.ema(close, 34)
bool isRange = math.abs(eFast - eSlow) < atr * rangeX
bool isLowVol = hasVol and vol5 < vol50 * lowVolX
 
// ═════════════════════════════════════════ LIQUIDITY POOLS ═════════════════════════════════════════
// src: 0 = swing, 1 = equal highs / lows, 2 = session, 3 = previous day / week
type Liq
    float  lv
    int    x1
    int    dir
    string kind
    int    src
    line   ln
    label  lb
 
var array<Liq> pools = array.new<Liq>()
 
liqColor(int dir) => dir > 0 ? bslC : sslC
 
addLiq(float lv, int x1, int dir, string kind, int src) =>
    bool merged = false
    if src == 0 and array.size(pools) > 0
        for p in pools
            if not merged and p.dir == dir and p.src <= 1 and math.abs(p.lv - lv) <= eqTol * atr
                float nlv = dir > 0 ? math.max(p.lv, lv) : math.min(p.lv, lv)
                if showLiq
                    line.new(p.x1, p.lv, x1, lv, color = color.new(liqColor(dir), 45), style = line.style_dotted)
                    line.set_y1(p.ln, nlv)
                    line.set_y2(p.ln, nlv)
                    line.set_width(p.ln, 2)
                    line.set_color(p.ln, color.new(liqColor(dir), 5))
                    label.set_y(p.lb, nlv)
                    label.set_text(p.lb, dir > 0 ? "EQH" : "EQL")
                p.lv := nlv
                p.src := 1
                p.kind := dir > 0 ? "EQH" : "EQL"
                merged := true
    if not merged and not na(lv)
        color c = liqColor(dir)
        line ln = showLiq ? line.new(x1, lv, bar_index, lv, color = color.new(c, src == 0 ? 35 : 10), width = src == 0 ? 1 : 2) : na
        label lb = showLiq ? label.new(bar_index, lv, kind, style = dir > 0 ? label.style_label_down : label.style_label_up,
             color = color.new(color.black, 100), textcolor = color.new(c, src == 0 ? 25 : 0), size = size.tiny) : na
        array.push(pools, Liq.new(lv, x1, dir, kind, src, ln, lb))
        int n = 0
        int oldest = -1
        for [i, p] in pools
            if p.dir == dir
                n += 1
                if oldest < 0
                    oldest := i
        if n > maxPools and oldest >= 0
            Liq o = array.remove(pools, oldest)
            line.delete(o.ln)
            label.delete(o.lb)
    merged
 
// a level that is done: swept (wick through, close back) or broken (close through)
finish(Liq p, bool swept) =>
    if keepSwept and not na(p.ln)
        line.set_x2(p.ln, bar_index)
        line.set_style(p.ln, swept ? line.style_dotted : line.style_solid)
        line.set_color(p.ln, color.new(liqColor(p.dir), swept ? 45 : 80))
        line.set_width(p.ln, 1)
        if swept
            label.set_x(p.lb, bar_index)
            label.set_text(p.lb, "✕ " + p.kind)
            label.set_textcolor(p.lb, color.new(liqColor(p.dir), 25))
        else
            label.delete(p.lb)
    else
        line.delete(p.ln)
        label.delete(p.lb)
    swept
 
// ═════════════════════════════════════════ SESSIONS ═════════════════════════════════════════
type Sess
    string name
    color  c
    bool   active = false
    float  hi = na
    float  lo = na
    int    hiB = na
    int    loB = na
    box    bx = na
 
method upd(Sess s, bool inNow) =>
    if inNow
        if not s.active
            s.active := true
            s.hi := high
            s.lo := low
            s.hiB := bar_index
            s.loB := bar_index
            s.bx := sessDraw == "Box" ? box.new(bar_index, high, bar_index, low, border_color = color.new(s.c, 45), bgcolor = color.new(s.c, 90),
                 border_style = line.style_dashed, text = s.name, text_color = color.new(s.c, 15), text_size = size.small,
                 text_halign = text.align_left, text_valign = text.align_top) : na
        else
            if high > s.hi
                s.hi := high
                s.hiB := bar_index
            if low < s.lo
                s.lo := low
                s.loB := bar_index
            if not na(s.bx)
                box.set_top(s.bx, s.hi)
                box.set_bottom(s.bx, s.lo)
                box.set_right(s.bx, bar_index)
    else if s.active
        s.active := false
        if sessLiq
            addLiq(s.hi, s.hiB, 1, s.name + " H", 2)
            addLiq(s.lo, s.loB, -1, s.name + " L", 2)
    s.active
 
bool sessTfOk = timeframe.isintraday and timeframe.in_seconds() <= timeframe.in_seconds(maxSessTf)
inS(string hrs) => not na(time(timeframe.period, hrs, tz))
bool raw1 = inS(sT1)
bool raw2 = inS(sT2)
bool raw3 = inS(sT3)
bool raw4 = inS(sT4)
bool in1 = sOn1 and sessTfOk and raw1
bool in2 = sOn2 and sessTfOk and raw2
bool in3 = sOn3 and sessTfOk and raw3
bool in4 = sOn4 and sessTfOk and raw4
bool anyIn = in1 or in2 or in3 or in4
bool anySessOn = sessTfOk and (sOn1 or sOn2 or sOn3 or sOn4)
 
var Sess S1 = Sess.new("Asia", sC1)
var Sess S2 = Sess.new("London", sC2)
var Sess S3 = Sess.new("New York", sC3)
var Sess S4 = Sess.new("NY PM", sC4)
S1.upd(in1)
S2.upd(in2)
S3.upd(in3)
S4.upd(in4)
bgcolor(sessDraw == "Background" ? (in1 ? color.new(sC1, 92) : in2 ? color.new(sC2, 92) : in3 ? color.new(sC3, 92) : in4 ? color.new(sC4, 92) : na) : na, title = "Session background")
 
// ═════════════════════════════════════════ PREVIOUS DAY / WEEK ═════════════════════════════════════════
var float dHi = na
var float dLo = na
var int dHiB = na
var int dLoB = na
var float wHi = na
var float wLo = na
var int wHiB = na
var int wLoB = na
bool newDay = timeframe.change("D")
bool newWeek = timeframe.change("W")
if newDay
    if pdLiq and timeframe.isintraday and not na(dHi)
        addLiq(dHi, dHiB, 1, "PDH", 3)
        addLiq(dLo, dLoB, -1, "PDL", 3)
    dHi := high
    dLo := low
    dHiB := bar_index
    dLoB := bar_index
else
    if na(dHi) or high > dHi
        dHi := high
        dHiB := bar_index
    if na(dLo) or low < dLo
        dLo := low
        dLoB := bar_index
if newWeek
    if pwLiq and (timeframe.isintraday or timeframe.isdaily) and not na(wHi)
        addLiq(wHi, wHiB, 1, "PWH", 3)
        addLiq(wLo, wLoB, -1, "PWL", 3)
    wHi := high
    wLo := low
    wHiB := bar_index
    wLoB := bar_index
else
    if na(wHi) or high > wHi
        wHi := high
        wHiB := bar_index
    if na(wLo) or low < wLo
        wLo := low
        wLoB := bar_index
 
// ═════════════════════════════════════════ SWING LIQUIDITY ═════════════════════════════════════════
float lph = ta.pivothigh(high, liqLen, liqLen)
float lpl = ta.pivotlow(low, liqLen, liqLen)
if not na(lph)
    addLiq(lph, bar_index - liqLen, 1, "BSL", 0)
if not na(lpl)
    addLiq(lpl, bar_index - liqLen, -1, "SSL", 0)
 
// ═════════════════════════════════════════ SWEEPS ═════════════════════════════════════════
int swDir = 0          // +1 = sell-side swept (bullish), -1 = buy-side swept (bearish)
int swSrc = -1
string swKind = ""
bool evBsl = false
bool evSsl = false
bool sweptUp = false
bool sweptDn = false
int bestUp = -1
int bestDn = -1
string kindUp = ""
string kindDn = ""
bool rSweptUp = false
bool rSweptDn = false
int rbUp = -1
int rbDn = -1
string rkUp = ""
string rkDn = ""
if conf and array.size(pools) > 0
    for i = array.size(pools) - 1 to 0
        Liq p = array.get(pools, i)
        bool srcOk = p.src == 0 ? useSwing : p.src == 1 ? useEq : p.src == 2 ? useSess : usePD
        bool rvOk = p.src == 0 ? rvSwing : p.src == 1 ? rvEq : p.src == 2 ? rvSess : rvPD
        if p.dir > 0 and high > p.lv
            bool swept = close < p.lv
            if swept
                evBsl := true
                if srcOk and high - p.lv >= minDepth * atr and p.src > bestDn
                    sweptDn := true
                    bestDn := p.src
                    kindDn := p.kind
                if rvOk and high - p.lv >= minDepth * atr and p.src > rbDn
                    rSweptDn := true
                    rbDn := p.src
                    rkDn := p.kind
            finish(p, swept)
            array.remove(pools, i)
        else if p.dir < 0 and low < p.lv
            bool swept = close > p.lv
            if swept
                evSsl := true
                if srcOk and p.lv - low >= minDepth * atr and p.src > bestUp
                    sweptUp := true
                    bestUp := p.src
                    kindUp := p.kind
                if rvOk and p.lv - low >= minDepth * atr and p.src > rbUp
                    rSweptUp := true
                    rbUp := p.src
                    rkUp := p.kind
            finish(p, swept)
            array.remove(pools, i)
        else if bar_index - p.x1 > maxAge
            line.delete(p.ln)
            label.delete(p.lb)
            array.remove(pools, i)
// an outside candle that sweeps both sides gives no direction
if sweptUp and not sweptDn
    swDir := 1
    swSrc := bestUp
    swKind := kindUp
else if sweptDn and not sweptUp
    swDir := -1
    swSrc := bestDn
    swKind := kindDn
// live levels reach just past the last candle
if barstate.islast and showLiq and array.size(pools) > 0
    for p in pools
        line.set_x2(p.ln, bar_index + 3)
        label.set_x(p.lb, bar_index + 3)
 
// ═════════════════════════════════════════ MARKET STRUCTURE (BOS / CHoCH) ═════════════════════════════════════════
float ph = ta.pivothigh(high, swLen, swLen)
float pl = ta.pivotlow(low, swLen, swLen)
var float shLv = na
var int shBar = na
var bool shUsed = true
var float slwLv = na
var int slwBar = na
var bool slwUsed = true
var int msDir = 0
bool evChoch = false
bool evBos = false
bool brokeUp = false
bool brokeDn = false
if not na(ph)
    shLv := ph
    shBar := bar_index - swLen
    shUsed := false
if not na(pl)
    slwLv := pl
    slwBar := bar_index - swLen
    slwUsed := false
 
drawBreak(int x1, float y, int d, bool isChoch) =>
    if showMS
        color c = d > 0 ? bullC : bearC
        line.new(x1, y, bar_index, y, color = color.new(c, 20), style = line.style_dashed, width = 1)
        label.new(int(math.round((x1 + bar_index) / 2)), y, isChoch ? "CHoCH" : "BOS", style = d > 0 ? label.style_label_down : label.style_label_up,
             color = color.new(color.black, 100), textcolor = color.new(c, 10), size = size.tiny)
    isChoch
 
if conf and not shUsed and close > shLv
    bool isC = msDir == -1
    drawBreak(shBar, shLv, 1, isC)
    evChoch := isC
    evBos := not isC
    brokeUp := true
    msDir := 1
    shUsed := true
if conf and not slwUsed and close < slwLv
    bool isC = msDir == 1
    drawBreak(slwBar, slwLv, -1, isC)
    evChoch := isC
    evBos := not isC
    brokeDn := true
    msDir := -1
    slwUsed := true
 
// ═════════════════════════════════════════ PREMIUM / DISCOUNT ═════════════════════════════════════════
// dealing range: latest structure swing high / low, stretched while price trades beyond them (or a plain lookback range)
var float dsHi = na
var float dsLo = na
var int dsHiB = na
var int dsLoB = na
if not na(ph)
    dsHi := ph
    dsHiB := bar_index - swLen
else if not na(dsHi) and high > dsHi
    dsHi := high
    dsHiB := bar_index
if not na(pl)
    dsLo := pl
    dsLoB := bar_index - swLen
else if not na(dsLo) and low < dsLo
    dsLo := low
    dsLoB := bar_index
float lbHi = ta.highest(high, pdLen)
float lbLo = ta.lowest(low, pdLen)
bool useLb = pdSrc == "Lookback" or na(dsHi) or na(dsLo)
float pdHi = useLb ? lbHi : dsHi
float pdLo = useLb ? lbLo : dsLo
float pdPos = pdHi > pdLo ? math.max(0, math.min(1, (close - pdLo) / (pdHi - pdLo))) : 0.5
float eqB = eqBand / 100
int pdZone = pdPos > 0.5 + eqB ? -1 : pdPos < 0.5 - eqB ? 1 : 0      // -1 premium (sell), +1 discount (buy), 0 equilibrium
 
// ═════════════════════════════════════════ INDUCEMENT (IDM) ═════════════════════════════════════════
float iph = ta.pivothigh(high, idmLen, idmLen)
float ipl = ta.pivotlow(low, idmLen, idmLen)
var float iHiLv = na
var float iLoLv = na
if not na(iph)
    iHiLv := iph
if not na(ipl)
    iLoLv := ipl
 
var int idmDir = 0     // +1 = watching the pullback low after a bullish break, -1 = the pullback high after a bearish break
var int armBar = na
var float idmLv = na
var int idmB = na
var line idmLn = na
var label idmLb = na
var int idmBullBar = na
var int idmBearBar = na
bool evIdmBull = false
bool evIdmBear = false
 
if brokeUp or brokeDn
    line.delete(idmLn)
    label.delete(idmLb)
    idmLn := na
    idmLb := na
    idmDir := brokeUp and not brokeDn ? 1 : brokeDn and not brokeUp ? -1 : 0
    armBar := bar_index
    idmLv := na
// the latest internal pullback after the break is the inducement
float newIdm = idmDir == 1 ? ipl : idmDir == -1 ? iph : na
if not na(newIdm) and bar_index - idmLen > armBar
    idmLv := newIdm
    idmB := bar_index - idmLen
    if showIDM
        line.delete(idmLn)
        label.delete(idmLb)
        idmLn := line.new(idmB, idmLv, bar_index, idmLv, color = color.new(idmC, 55), style = line.style_dotted, width = 1)
        idmLb := label.new(bar_index, idmLv, "IDM", style = idmDir > 0 ? label.style_label_up : label.style_label_down,
             color = color.new(color.black, 100), textcolor = color.new(idmC, 45), size = size.tiny)
if conf and idmDir != 0 and not na(idmLv) and (idmDir > 0 ? low < idmLv : high > idmLv)
    if idmDir > 0
        evIdmBull := true
        idmBullBar := bar_index
    else
        evIdmBear := true
        idmBearBar := bar_index
    if showIDM
        line.set_x2(idmLn, bar_index)
        line.set_style(idmLn, line.style_dashed)
        line.set_color(idmLn, color.new(idmC, 10))
        label.set_x(idmLb, int(math.round((idmB + bar_index) / 2)))
        label.set_textcolor(idmLb, idmC)
        label.set_text(idmLb, "IDM ✓")
    idmLn := na
    idmLb := na
    idmDir := 0
    idmLv := na
else if not na(idmLn)
    line.set_x2(idmLn, bar_index)
    label.set_x(idmLb, bar_index + 3)
 
// ═════════════════════════════════════════ SWEEP SIGNALS ═════════════════════════════════════════
var int pDir = 0
var int pBar = na
var float pExt = na
var float pTrig = na
var int pSrc = -1
var string pKind = ""
var bool pSess = true
var bool pVol = true
int fireDir = 0
int fireSrc = -1
string fireKind = ""
float fireExt = na
bool fireSess = true
bool fireVol = true
 
if conf
    if swDir != 0
        bool sOk = sessFlt == "Any time" or not anySessOn or (sessFlt == "Inside any session" ? anyIn : (in2 or in3 or in4))
        bool vOk = not useVol or not hasVol or volume >= nz(volAvg[1]) * volMult
        float ext = swDir > 0 ? low : high
        if confMode == "Close back inside"
            fireDir := swDir
            fireSrc := swSrc
            fireKind := swKind
            fireExt := ext
            fireSess := sOk
            fireVol := vOk
            pDir := 0
        else
            pDir := swDir
            pBar := bar_index
            pExt := ext
            pSrc := swSrc
            pKind := swKind
            pSess := sOk
            pVol := vOk
            pTrig := confMode == "Next candle confirms" ? (swDir > 0 ? high : low) :
                 swDir > 0 ? (not na(iHiLv) and iHiLv > close ? iHiLv : high) : (not na(iLoLv) and iLoLv < close ? iLoLv : low)
    else if pDir != 0
        if bar_index - pBar > confWin or (pDir > 0 ? low < pExt : high > pExt)
            pDir := 0
        else if pDir > 0 ? close > pTrig : close < pTrig
            fireDir := pDir
            fireSrc := pSrc
            fireKind := pKind
            fireExt := pExt
            fireSess := pSess
            fireVol := pVol
            pDir := 0
 
int grade = 0
bool idmRecent = false
if fireDir != 0
    int d = fireDir
    bool trendOk = trendFlt == "Structure" ? msDir == d : trendFlt == "EMA 200" ? (d > 0 ? close > ema200 : close < ema200) : true
    idmRecent := d > 0 ? (not na(idmBullBar) and bar_index - idmBullBar <= idmWin) : (not na(idmBearBar) and bar_index - idmBearBar <= idmWin)
    bool idmOk = not idmFlt or idmRecent
    bool allOk = trendOk and fireSess and fireVol and idmOk
    grade := not allOk ? 0 : htfDir == d and (fireSrc >= 1 or idmRecent) ? 2 : 1
int minGrade = sigMode == "Strong only" ? 2 : sigMode == "Normal + Strong" ? 1 : 0
var int lastSigBar = na
bool cool = na(lastSigBar) or bar_index - lastSigBar >= cooldown
bool sigBuy = fireDir > 0 and grade >= minGrade and cool
bool sigSell = fireDir < 0 and grade >= minGrade and cool
bool strongBuy = sigBuy and grade == 2
bool strongSell = sigSell and grade == 2
if sigBuy or sigSell
    lastSigBar := bar_index
 
string sigTip = (fireDir > 0 ? "Sell-side liquidity swept: " : "Buy-side liquidity swept: ") + fireKind +
     (idmRecent ? " · inducement taken" : "") + (grade == 2 ? " · higher timeframe agrees" : grade == 0 ? " · fails a filter" : "")
if showSig and sigBuy
    label.new(bar_index, low, grade == 2 ? "Strong" : grade == 1 ? "B" : "b", yloc = yloc.belowbar, style = label.style_label_up,
         color = grade == 0 ? color.new(bullC, 55) : bullC, textcolor = color.white, size = grade == 0 ? size.tiny : size.small, tooltip = sigTip)
if showSig and sigSell
    label.new(bar_index, high, grade == 2 ? "Strong" : grade == 1 ? "S" : "s", yloc = yloc.abovebar, style = label.style_label_down,
         color = grade == 0 ? color.new(bearC, 55) : bearC, textcolor = color.white, size = grade == 0 ? size.tiny : size.small, tooltip = sigTip)
 
// ═════════════════════════════════════════ REVERSAL SIGNALS ═════════════════════════════════════════
// a key level is swept (session, day / week, equal highs / lows), then price shifts the other way
int rvDir0 = rSweptUp and not rSweptDn ? 1 : rSweptDn and not rSweptUp ? -1 : 0
var int rDir = 0
var int rBar = na
var float rExt = na
var float rTrig = na
var int rSrc = -1
var string rKind = ""
var bool rSess = true
var bool rVol = true
var bool rTrOk = true
var bool rZnOk = true
int revFire = 0
int revSrc = -1
int revBar = na
string revKind = ""
float revExt = na
bool revSessF = true
bool revVolF = true
bool revTrF = true
bool revZnF = true
 
if conf
    if rvDir0 != 0
        bool sOk = sessFlt == "Any time" or not anySessOn or (sessFlt == "Inside any session" ? anyIn : (in2 or in3 or in4))
        bool vOk = not useVol or not hasVol or volume >= nz(volAvg[1]) * volMult
        bool tOk = rvTrend == "Any" or msDir == -rvDir0
        bool zOk = not rvZoneF or (rvDir0 > 0 ? pdZone > 0 : pdZone < 0)
        float ext = rvDir0 > 0 ? low : high
        if rvConf == "Close back inside"
            revFire := rvDir0
            revSrc := rbUp > rbDn ? rbUp : rbDn
            revKind := rvDir0 > 0 ? rkUp : rkDn
            revExt := ext
            revBar := bar_index
            revSessF := sOk
            revVolF := vOk
            revTrF := tOk
            revZnF := zOk
            rDir := 0
        else
            rDir := rvDir0
            rBar := bar_index
            rExt := ext
            rSrc := rvDir0 > 0 ? rbUp : rbDn
            rKind := rvDir0 > 0 ? rkUp : rkDn
            rSess := sOk
            rVol := vOk
            rTrOk := tOk
            rZnOk := zOk
            rTrig := rvConf == "Next candle confirms" ? (rvDir0 > 0 ? high : low) :
                 rvDir0 > 0 ? (not na(iHiLv) and iHiLv > close ? iHiLv : high) : (not na(iLoLv) and iLoLv < close ? iLoLv : low)
    else if rDir != 0
        if bar_index - rBar > rvWin or (rDir > 0 ? low < rExt : high > rExt)
            rDir := 0
        else if rDir > 0 ? close > rTrig : close < rTrig
            revFire := rDir
            revSrc := rSrc
            revKind := rKind
            revExt := rExt
            revBar := rBar
            revSessF := rSess
            revVolF := rVol
            revTrF := rTrOk
            revZnF := rZnOk
            rDir := 0
 
int rGrade = 0
if revFire != 0
    bool okAll = revSessF and revVolF and revTrF and revZnF
    bool disp = math.abs(close - open) >= rvDisp * atr or (hasVol and volume >= nz(volAvg[1]) * volMult)
    rGrade := not okAll ? 0 : revSrc >= 1 and disp ? 2 : 1
bool coolR = (na(lastSigBar) or bar_index - lastSigBar >= cooldown) and not sigBuy and not sigSell
bool revBuy = revFire > 0 and rGrade >= minGrade and coolR
bool revSell = revFire < 0 and rGrade >= minGrade and coolR
bool strongRevBuy = revBuy and rGrade == 2
bool strongRevSell = revSell and rGrade == 2
if revBuy or revSell
    lastSigBar := bar_index
 
string rvTip = (revFire > 0 ? "Bullish reversal: " : "Bearish reversal: ") + revKind + " swept, then " +
     (rvConf == "Internal CHoCH" ? "internal CHoCH" : rvConf == "Next candle confirms" ? "next candle confirmed" : "closed back inside") +
     (rGrade == 2 ? " · displacement on a key level" : rGrade == 0 ? " · fails a filter" : "")
string rvTxt = (rGrade == 2 ? "Strong Reversal" : rGrade == 1 ? "Reversal" : "rev") + (rvShowLv and revKind != "" ? "\n" + revKind + " swept" : "")
if showRev and (revBuy or revSell)
    bool up = revBuy
    color c = rGrade == 0 ? color.new(up ? bullC : bearC, 55) : up ? bullC : bearC
    label.new(bar_index, up ? low : high, rvTxt, yloc = up ? yloc.belowbar : yloc.abovebar, style = up ? label.style_label_up : label.style_label_down,
         color = c, textcolor = color.white, size = rGrade == 0 ? size.tiny : size.small, tooltip = rvTip)
    // mark the wick that took the liquidity
    label.new(revBar, revExt, "", style = label.style_diamond, color = color.new(idmC, 10), size = size.tiny)
 
// ═════════════════════════════════════════ STOP & TARGETS ═════════════════════════════════════════
var array<line> tpLines = array.new<line>()
var array<float> tpLv = array.new<float>()
var array<bool> tpHit = array.new<bool>()
var line slLine = na
var line enLine = na
var float slLv = na
var int tDir = 0
var bool tLive = false
bool evTarget = false
bool evStop = false
 
if showTP and tLive and conf
    bool allHit = true
    for k = 0 to array.size(tpLines) - 1
        if not array.get(tpHit, k)
            float lv = array.get(tpLv, k)
            line.set_x2(array.get(tpLines, k), bar_index)
            if tDir > 0 ? high >= lv : low <= lv
                array.set(tpHit, k, true)
                evTarget := true
                label.new(bar_index, lv, "Target " + str.tostring(k + 1) + " Hit", style = label.style_label_right, color = color.new(#3a3f4b, 0), textcolor = textC, size = size.small)
            else
                allHit := false
    if not allHit
        line.set_x2(slLine, bar_index)
        line.set_x2(enLine, bar_index)
        if tDir > 0 ? low <= slLv : high >= slLv
            evStop := true
            allHit := true
            label.new(bar_index, slLv, "Stop", style = label.style_label_right, color = color.new(bearC, 30), textcolor = color.white, size = size.tiny)
    if allHit
        tLive := false
 
bool tradeBuy = (showSig and sigBuy) or (showRev and revBuy)
bool tradeSell = (showSig and sigSell) or (showRev and revSell)
if showTP and (tradeBuy or tradeSell)
    tDir := tradeBuy ? 1 : -1
    slLv := (revBuy or revSell ? revExt : fireExt) - tDir * slBuf * atr
    float risk = math.max(math.abs(close - slLv), atr * 0.25)
    slLv := close - tDir * risk
    array.clear(tpLines)
    array.clear(tpLv)
    array.clear(tpHit)
    for k = 1 to 3
        float lv = close + tDir * k * tpStep * risk
        array.push(tpLv, lv)
        array.push(tpHit, false)
        array.push(tpLines, line.new(bar_index, lv, bar_index + 1, lv, color = color.new(bullC, 10), style = line.style_dashed, width = 1))
    slLine := line.new(bar_index, slLv, bar_index + 1, slLv, color = color.new(bearC, 10), style = line.style_dashed, width = 1)
    enLine := line.new(bar_index, close, bar_index + 1, close, color = color.new(textC, 60), style = line.style_dotted, width = 1)
    tLive := true
 
// ═════════════════════════════════════════ CANDLES: PREMIUM / DISCOUNT ═════════════════════════════════════════
string gm = greyMode == "Auto" ? (isFx ? "Outside sessions or range" : "Low volume or range") : greyMode
bool outSess = anySessOn and not anyIn
bool isGrey = gm == "Low volume or range" ? (isLowVol or isRange) : gm == "Outside sessions or range" ? (outSess or isRange) : gm == "Range only" ? isRange : false
color pdC = pdZone == 0 ? greyC : pdShade == "Solid" ? (pdZone > 0 ? bullC : bearC) :
     pdZone < 0 ? color.from_gradient(pdPos, 0.5 + eqB, 1, color.new(bearC, 45), bearC) : color.from_gradient(pdPos, 0, 0.5 - eqB, bullC, color.new(bullC, 45))
color trendC = isGrey ? greyC : pdC
plotcandle(colorBars ? open : na, colorBars ? high : na, colorBars ? low : na, colorBars ? close : na, "Premium / discount candles", color = trendC, wickcolor = trendC, bordercolor = trendC, display = display.pane)
 
// zones for the current dealing range, redrawn on the last bar
var box pzBox = na
var box dzBox = na
var line eqLine = na
var label pzLb = na
var label dzLb = na
if barstate.islast and showPD and pdHi > pdLo
    box.delete(pzBox)
    box.delete(dzBox)
    line.delete(eqLine)
    label.delete(pzLb)
    label.delete(dzLb)
    int x0 = useLb ? bar_index - pdLen + 1 : math.min(dsHiB, dsLoB)
    float mid = (pdHi + pdLo) / 2
    float span = pdHi - pdLo
    pzBox := box.new(x0, pdHi, bar_index + 3, mid + span * eqB, border_color = color.new(bearC, 85), bgcolor = color.new(bearC, 93))
    dzBox := box.new(x0, mid - span * eqB, bar_index + 3, pdLo, border_color = color.new(bullC, 85), bgcolor = color.new(bullC, 93))
    eqLine := line.new(x0, mid, bar_index + 3, mid, color = color.new(greyC, 30), style = line.style_dotted)
    pzLb := label.new(x0, pdHi, "Premium", style = label.style_label_lower_left, color = color.new(color.black, 100), textcolor = color.new(bearC, 30), size = size.tiny)
    dzLb := label.new(x0, pdLo, "Discount", style = label.style_label_upper_left, color = color.new(color.black, 100), textcolor = color.new(bullC, 30), size = size.tiny)
 
// ═════════════════════════════════════════ DASHBOARD ═════════════════════════════════════════
var table tb = table.new(tblPos == "Top Right" ? position.top_right : tblPos == "Bottom Right" ? position.bottom_right : tblPos == "Bottom Left" ? position.bottom_left : position.top_left,
     2, 10, bgcolor = color.new(#1e222d, 5), border_color = color.new(#363a45, 0), border_width = 1)
var string lastSig = "—"
var color lastSigC = textC
if sigBuy
    lastSig := (strongBuy ? "Strong Buy" : "Buy") + " · " + fireKind
    lastSigC := bullC
if sigSell
    lastSig := (strongSell ? "Strong Sell" : "Sell") + " · " + fireKind
    lastSigC := bearC
if revBuy
    lastSig := (strongRevBuy ? "Strong Reversal ▲" : "Reversal ▲") + " · " + revKind
    lastSigC := bullC
if revSell
    lastSig := (strongRevSell ? "Strong Reversal ▼" : "Reversal ▼") + " · " + revKind
    lastSigC := bearC
cell(int row, string k, string v, color c) =>
    table.cell(tb, 0, row, k, text_color = color.new(textC, 25), text_size = size.small, text_halign = text.align_left)
    table.cell(tb, 1, row, v, text_color = c, text_size = size.small, text_halign = text.align_right)
dirTxt(int d) => d > 0 ? "▲ Bullish" : d < 0 ? "▼ Bearish" : "—"
dirCol(int d) => d > 0 ? bullC : d < 0 ? bearC : textC
distTxt(float lv) =>
    float d = math.abs(lv - close)
    isFx ? str.tostring(d / (syminfo.mintick * 10), "0.0") + " pips" : str.tostring(100 * d / close, "0.00") + "%"
if showTbl and barstate.isfirst
    table.cell(tb, 0, 0, "Liquidity & Inducement", text_color = textC, text_size = size.small)
    table.merge_cells(tb, 0, 0, 1, 0)
if showTbl and barstate.islast
    float nb = na
    float ns = na
    string nbK = ""
    string nsK = ""
    for p in pools
        if p.dir > 0 and p.lv > close and (na(nb) or p.lv < nb)
            nb := p.lv
            nbK := p.kind
        if p.dir < 0 and p.lv < close and (na(ns) or p.lv > ns)
            ns := p.lv
            nsK := p.kind
    string sessTxt = not anySessOn ? "— (timeframe)" : anyIn ? (in1 ? "Asia " : "") + (in2 ? "London " : "") + (in3 ? "New York " : "") + (in4 ? "NY PM" : "") : "Off-session"
    cell(1, "Session", sessTxt, anyIn ? (in1 ? sC1 : in2 ? sC2 : in3 ? sC3 : sC4) : greyC)
    cell(2, "Structure", dirTxt(msDir), dirCol(msDir))
    cell(3, "Reversal watch", rDir != 0 ? (rDir > 0 ? "▲ " : "▼ ") + rKind + " swept · waiting" : "—", rDir > 0 ? bullC : rDir < 0 ? bearC : textC)
    cell(4, "Trend " + htfTf, dirTxt(htfDir), dirCol(htfDir))
    string idmTxt = not na(idmLv) ? (idmDir > 0 ? "Bull IDM at " : "Bear IDM at ") + str.tostring(idmLv, format.mintick) :
         not na(idmBullBar) and (na(idmBearBar) or idmBullBar > idmBearBar) ? "Bull IDM taken " + str.tostring(bar_index - idmBullBar) + " bars ago" :
         not na(idmBearBar) ? "Bear IDM taken " + str.tostring(bar_index - idmBearBar) + " bars ago" : "—"
    cell(5, "Inducement", idmTxt, idmC)
    cell(6, "Next BSL", na(nb) ? "—" : nbK + " · " + str.tostring(nb, format.mintick) + " (" + distTxt(nb) + ")", bslC)
    cell(7, "Next SSL", na(ns) ? "—" : nsK + " · " + str.tostring(ns, format.mintick) + " (" + distTxt(ns) + ")", sslC)
    cell(8, "Price zone", (pdZone < 0 ? "Premium " : pdZone > 0 ? "Discount " : "Equilibrium ") + str.tostring(pdPos * 100, "0") + "%" + (isGrey ? (isRange ? " · range" : outSess and gm == "Outside sessions or range" ? " · off-session" : " · low volume") : ""), isGrey or pdZone == 0 ? greyC : pdZone < 0 ? bearC : bullC)
    cell(9, "Last signal", lastSig, lastSigC)
 
// ═════════════════════════════════════════ ALERTS ═════════════════════════════════════════
alertcondition(sigBuy, "Sweep Buy (any shown grade)", "Liquidity IDM: Buy, sell-side liquidity swept on {{ticker}} {{interval}} at {{close}}")
alertcondition(sigSell, "Sweep Sell (any shown grade)", "Liquidity IDM: Sell, buy-side liquidity swept on {{ticker}} {{interval}} at {{close}}")
alertcondition(strongBuy, "Strong Buy", "Liquidity IDM: Strong Buy on {{ticker}} {{interval}} at {{close}}")
alertcondition(strongSell, "Strong Sell", "Liquidity IDM: Strong Sell on {{ticker}} {{interval}} at {{close}}")
alertcondition(revBuy, "Reversal Buy (any shown grade)", "Liquidity IDM: bullish reversal after a liquidity sweep on {{ticker}} {{interval}} at {{close}}")
alertcondition(revSell, "Reversal Sell (any shown grade)", "Liquidity IDM: bearish reversal after a liquidity sweep on {{ticker}} {{interval}} at {{close}}")
alertcondition(strongRevBuy or strongRevSell, "Strong Reversal", "Liquidity IDM: Strong reversal on {{ticker}} {{interval}} at {{close}}")
alertcondition(evBsl, "Buy-side liquidity swept", "Liquidity IDM: BSL swept on {{ticker}} {{interval}}")
alertcondition(evSsl, "Sell-side liquidity swept", "Liquidity IDM: SSL swept on {{ticker}} {{interval}}")
alertcondition(evIdmBull or evIdmBear, "Inducement taken", "Liquidity IDM: inducement taken on {{ticker}} {{interval}}")
alertcondition(evChoch, "CHoCH", "Liquidity IDM: CHoCH on {{ticker}} {{interval}}")
alertcondition(evBos, "BOS", "Liquidity IDM: BOS on {{ticker}} {{interval}}")
alertcondition(evTarget, "Target Hit", "Liquidity IDM: target hit on {{ticker}} {{interval}}")
alertcondition(evStop, "Stop Hit", "Liquidity IDM: stop hit on {{ticker}} {{interval}}")

← 返回列表