CTZ Whale vs Retail Flow

CryptoTradingZone · study · 212 行 · 点赞 27 · TradingView 原页

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

Pine Script

//@version=6
indicator("CTZ Whale vs Retail Flow", "CTZ W/R Flow", overlay = true, max_labels_count = 500)
 
// ═════════ Inputs ═════════
grpE = "Exchanges (spot, aggregated)"
use1 = input.bool(true, "", inline = "e1", group = grpE)
sym1 = input.symbol("BINANCE:BTCUSDT", "", inline = "e1", group = grpE)
use2 = input.bool(true, "", inline = "e2", group = grpE)
sym2 = input.symbol("COINBASE:BTCUSD", "", inline = "e2", group = grpE)
use3 = input.bool(true, "", inline = "e3", group = grpE)
sym3 = input.symbol("OKX:BTCUSDT", "", inline = "e3", group = grpE)
use4 = input.bool(true, "", inline = "e4", group = grpE)
sym4 = input.symbol("BYBIT:BTCUSDT", "", inline = "e4", group = grpE)
 
grpD = "Whale Detection"
ltfIn     = input.timeframe("", "Lower timeframe (blank = auto)", group = grpD)
largeMult = input.float(3.0, "Whale size (x avg intrabar volume)", minval = 1.0, step = 0.5, group = grpD)
baseLen   = input.int(50, "Volume baseline length (bars)", minval = 5, group = grpD)
sumLen    = input.int(20, "Flow window (bars)", minval = 2, group = grpD)
zLen      = input.int(100, "Normalisation length (bars)", minval = 20, group = grpD)
zFlow     = input.float(0.5, "Whale zone sensitivity (higher = fewer)", minval = 0.1, step = 0.1, group = grpD)
 
grpP = "Confirmation: Coinbase Premium"
usePrem  = input.bool(true, "Use Coinbase premium", group = grpP)
cbSym    = input.symbol("COINBASE:BTCUSD", "Coinbase symbol", group = grpP)
bnSym    = input.symbol("BINANCE:BTCUSDT", "Binance symbol", group = grpP)
premLen  = input.int(3, "Premium smoothing (bars)", minval = 1, group = grpP)
premMin  = input.float(0.0, "Min premium % for buy", step = 0.01, group = grpP)
 
grpO = "Confirmation: Open Interest Flush"
useOI    = input.bool(true, "Use OI flush", group = grpO)
oiSym    = input.symbol("BINANCE:BTCUSDT.P_OI", "OI symbol", group = grpO)
oiLen    = input.int(10, "OI lookback (bars)", minval = 2, group = grpO)
oiDrop   = input.float(3.0, "OI drop % from recent peak", minval = 0.1, step = 0.5, group = grpO)
 
grpS = "Signals"
minScore = input.int(2, "Min score to signal (out of 3)", minval = 1, maxval = 3, group = grpS)
needLow  = input.bool(true, "Require price near recent low", group = grpS)
swingLen = input.int(50, "Price extreme lookback", minval = 5, group = grpS)
nearPct  = input.float(3.0, "Within % of low / high", minval = 0.1, step = 0.5, group = grpS)
cooldown = input.int(10, "Cooldown bars between signals", minval = 0, group = grpS)
buysOnly = input.bool(false, "Buys only (hide all sell signals)", group = grpS)
showBg   = input.bool(true, "Shade confirmed zones", group = grpS)
autoTune = input.bool(true, "Auto-tune on daily and above", group = grpS)
 
grpC = "Divergence Candles"
showDivC  = input.bool(true, "Recolour divergence candles", group = grpC)
zBar      = input.float(1.0, "Candle sensitivity (higher = fewer)", minval = 0.1, step = 0.1, group = grpC)
candleCnf = input.bool(true, "Candles need premium or OI confirmation", group = grpC)
bullCol   = input.color(#00FF00, "Red candle, whales buying", group = grpC)
bearCol   = input.color(#FF0000, "Green candle, whales selling", group = grpC)
 
// ═════════ Timeframe handling ═════════
autoLtf() =>
    s = timeframe.in_seconds()
    s <= 3600 ? "1" : s <= 14400 ? "5" : s <= 86400 ? "15" : "60"
 
ltf = ltfIn == "" ? autoLtf() : ltfIn
 
bool  isHTF  = autoTune and timeframe.in_seconds() >= 86400
float zBarE  = isHTF ? zBar * 0.5 : zBar
float zFlowE = isHTF ? zFlow * 0.6 : zFlow
int   zLenE  = isHTF ? math.max(20, int(math.round(zLen * 0.6))) : zLen
int   swingE = isHTF ? math.max(10, int(math.round(swingLen * 0.4))) : swingLen
float nearE  = isHTF ? nearPct * 2 : nearPct
float oiDrpE = isHTF ? oiDrop * 2 : oiDrop
 
// ═════════ Per-exchange whale / retail split ═════════
f_flow(sym, tf, bLen, mult) =>
    [h, l, c, v] = request.security_lower_tf(sym, tf, [high, low, close, volume], ignore_invalid_symbol = true)
    float avgRaw = v.size() > 0 ? v.avg() : na
    var float lastAvg = na
    if not na(avgRaw)
        lastAvg := avgRaw
    float base = ta.sma(lastAvg, bLen)
    float thr  = nz(base) * mult
    float wB = 0.0
    float wS = 0.0
    float rB = 0.0
    float rS = 0.0
    if v.size() > 0 and thr > 0
        for i = 0 to v.size() - 1
            float vol = v.get(i)
            float rng = h.get(i) - l.get(i)
            float bp  = rng > 0 ? (c.get(i) - l.get(i)) / rng : 0.5
            float bv  = vol * bp
            float sv  = vol - bv
            if vol >= thr
                wB += bv
                wS += sv
            else
                rB += bv
                rS += sv
    [wB - wS, rB - rS, wB + wS + rB + rS]
 
[w1, r1, t1] = f_flow(sym1, ltf, baseLen, largeMult)
[w2, r2, t2] = f_flow(sym2, ltf, baseLen, largeMult)
[w3, r3, t3] = f_flow(sym3, ltf, baseLen, largeMult)
[w4, r4, t4] = f_flow(sym4, ltf, baseLen, largeMult)
 
float whaleNet = (use1 ? w1 : 0.0) + (use2 ? w2 : 0.0) + (use3 ? w3 : 0.0) + (use4 ? w4 : 0.0)
float retNet   = (use1 ? r1 : 0.0) + (use2 ? r2 : 0.0) + (use3 ? r3 : 0.0) + (use4 ? r4 : 0.0)
float totVol   = (use1 ? t1 : 0.0) + (use2 ? t2 : 0.0) + (use3 ? t3 : 0.0) + (use4 ? t4 : 0.0)
int   exCount  = (use1 and t1 > 0 ? 1 : 0) + (use2 and t2 > 0 ? 1 : 0) + (use3 and t3 > 0 ? 1 : 0) + (use4 and t4 > 0 ? 1 : 0)
 
// ═════════ Rolling whale flow ═════════
float whaleSum = math.sum(whaleNet, sumLen)
float retSum   = math.sum(retNet, sumLen)
float sumTot   = math.sum(totVol, sumLen)
float whalePct = sumTot > 0 ? whaleSum / sumTot * 100 : 0.0
float retPct   = sumTot > 0 ? retSum / sumTot * 100 : 0.0
 
float sdBar     = ta.stdev(whaleNet, zLenE)
float sdSum     = ta.stdev(whaleSum, zLenE)
float whaleZ    = nz(sdBar) > 0 ? whaleNet / sdBar : 0.0
float whaleSumZ = nz(sdSum) > 0 ? whaleSum / sdSum : 0.0
 
// ═════════ Coinbase premium ═════════
float cbPx    = request.security(cbSym, timeframe.period, close, ignore_invalid_symbol = true)
float bnPx    = request.security(bnSym, timeframe.period, close, ignore_invalid_symbol = true)
float premRaw = nz(bnPx) > 0 and not na(cbPx) ? (cbPx - bnPx) / bnPx * 100 : na
float prem    = ta.sma(premRaw, premLen)
bool  premBuy  = usePrem and not na(prem) and prem >  premMin
bool  premSell = usePrem and not na(prem) and prem < -premMin
 
// ═════════ Open interest ═════════
float oi       = request.security(oiSym, timeframe.period, close, ignore_invalid_symbol = true)
float oiPeak   = ta.highest(oi, oiLen)
float oiTrough = ta.lowest(oi, oiLen)
float oiFromPk = nz(oiPeak) > 0 ? (oi - oiPeak) / oiPeak * 100 : na
float oiFromTr = nz(oiTrough) > 0 ? (oi - oiTrough) / oiTrough * 100 : na
bool  oiFlush  = useOI and not na(oiFromPk) and oiFromPk <= -oiDrpE   // longs flushed
bool  oiBuild  = useOI and not na(oiFromTr) and oiFromTr >=  oiDrpE   // leverage piling in
 
// ═════════ Scores ═════════
bool nearLow  = close <= ta.lowest(low, swingE) * (1 + nearE / 100)
bool nearHigh = close >= ta.highest(high, swingE) * (1 - nearE / 100)
 
bool whaleBuy  = whaleSumZ >  zFlowE and retSum < 0
bool whaleSell = whaleSumZ < -zFlowE and retSum > 0
 
int buyScore  = (whaleBuy ? 1 : 0) + (premBuy ? 1 : 0) + (oiFlush ? 1 : 0)
int sellScore = (whaleSell ? 1 : 0) + (premSell ? 1 : 0) + (oiBuild ? 1 : 0)
 
bool buyZone  = whaleBuy and buyScore >= minScore
bool sellZone = not buysOnly and whaleSell and sellScore >= minScore
 
bool buyCond  = buyZone and (not needLow or nearLow)
bool sellCond = sellZone and (not needLow or nearHigh)
 
// ═════════ Signals with cooldown ═════════
var int lastBuy  = -100000
var int lastSell = -100000
 
bool buySig  = buyCond and not buyCond[1] and bar_index - lastBuy > cooldown
bool sellSig = sellCond and not sellCond[1] and bar_index - lastSell > cooldown
 
if buySig
    lastBuy := bar_index
    label.new(bar_index, low, "WHALE BUY\n" + str.tostring(buyScore) + "/3", yloc = yloc.belowbar,
         style = label.style_label_up, color = color.new(color.green, 0), textcolor = color.white, size = size.small)
 
if sellSig
    lastSell := bar_index
    label.new(bar_index, high, "WHALE SELL\n" + str.tostring(sellScore) + "/3", yloc = yloc.abovebar,
         style = label.style_label_down, color = color.new(color.red, 0), textcolor = color.white, size = size.small)
 
// ═════════ Divergence candles ═════════
bool hiddenBuy  = close < open and whaleZ > zBarE and (not candleCnf or premBuy or oiFlush)
bool hiddenSell = not buysOnly and close > open and whaleZ < -zBarE and (not candleCnf or premSell or oiBuild)
 
color divCol = hiddenBuy ? bullCol : hiddenSell ? bearCol : na
bool  divOn  = showDivC and (hiddenBuy or hiddenSell)
 
plotcandle(divOn ? open : na, divOn ? high : na, divOn ? low : na, divOn ? close : na,
     "Whale divergence candle", color = divCol, wickcolor = divCol, bordercolor = color.white)
 
// ═════════ Zone shading (darker = higher score) ═════════
color buyBg  = buyScore == 3 ? color.new(color.green, 75) : color.new(color.green, 88)
color sellBg = sellScore == 3 ? color.new(color.red, 75) : color.new(color.red, 88)
bgcolor(showBg and buyZone  ? buyBg  : na, title = "Confirmed accumulation")
bgcolor(showBg and sellZone ? sellBg : na, title = "Confirmed distribution")
 
// ═════════ Dashboard ═════════
f_col(bool good, bool bad) => good ? color.lime : bad ? color.red : color.gray
 
var table tb = table.new(position.top_right, 2, 8, bgcolor = color.new(color.black, 30), border_width = 1)
if barstate.islast
    table.cell(tb, 0, 0, "LTF / Exchanges", text_color = color.white)
    table.cell(tb, 1, 0, ltf + " / " + str.tostring(exCount), text_color = color.white)
    table.cell(tb, 0, 1, "Whale flow", text_color = color.white)
    table.cell(tb, 1, 1, str.tostring(whalePct, "0.0") + "%", text_color = f_col(whalePct > 0, whalePct < 0))
    table.cell(tb, 0, 2, "Retail flow", text_color = color.white)
    table.cell(tb, 1, 2, str.tostring(retPct, "0.0") + "%", text_color = f_col(retPct > 0, retPct < 0))
    table.cell(tb, 0, 3, "Whale strength", text_color = color.white)
    table.cell(tb, 1, 3, str.tostring(whaleSumZ, "0.00"), text_color = f_col(whaleBuy, whaleSell))
    table.cell(tb, 0, 4, "CB premium", text_color = color.white)
    table.cell(tb, 1, 4, na(prem) ? "n/a" : str.tostring(prem, "0.000") + "%", text_color = f_col(premBuy, premSell))
    table.cell(tb, 0, 5, "OI vs peak", text_color = color.white)
    table.cell(tb, 1, 5, na(oiFromPk) ? "n/a" : str.tostring(oiFromPk, "0.0") + "%", text_color = f_col(oiFlush, oiBuild))
    table.cell(tb, 0, 6, "Buy / Sell score", text_color = color.white)
    table.cell(tb, 1, 6, str.tostring(buyScore) + "/3  |  " + str.tostring(sellScore) + "/3",
         text_color = buyScore >= minScore ? color.lime : sellScore >= minScore ? color.red : color.gray)
    table.cell(tb, 0, 7, "State", text_color = color.white)
    table.cell(tb, 1, 7, buyZone ? "ACCUMULATION" : sellZone ? "DISTRIBUTION" : "Neutral",
         text_color = buyZone ? color.lime : sellZone ? color.red : color.gray)
 
// ═════════ Alerts ═════════
alertcondition(buySig,  "Whale buy (confirmed)",  "Confirmed whale buying near lows")
alertcondition(sellSig, "Whale sell (confirmed)", "Confirmed whale selling near highs")
alertcondition(hiddenBuy,  "Red candle, whales buying",    "Price dropping but whales are net buying")
alertcondition(hiddenSell, "Green candle, whales selling", "Price pumping but whales are net selling")

← 返回列表