Dynamic Anchor Flow & Pressure Profile

TaninWiselyWealth · study · 346 行 · 点赞 36 · TradingView 原页

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

Pine Script

//@version=6
indicator("Dynamic Anchor Flow & Pressure Profile", shorttitle="DAFP Profile", overlay=true, behind_chart=true, max_bars_back=250, calc_bars_count=2500, max_labels_count=500)
 
// ============================================================================
// 1. การตั้งค่าพารามิเตอร์ (Inputs) พร้อม Tooltip ภาษาอังกฤษ
// ============================================================================
// กลุ่ม Anchor
grpAnchor = "Anchor Settings"
anchType  = input.string("EMA", "Anchor Type", options=["EMA", "SMA", "VWMA", "VWAP", "Donchian Mid"], group=grpAnchor, tooltip="Selects the baseline calculation method used as the starting boundary for the 12-level profile corridor. Falls back to EMA if volume data is unavailable.")
anchorLen = input.int(200, "Anchor Length", minval=1, group=grpAnchor, tooltip="Number of bars used to calculate the Anchor line (applies to EMA, SMA, VWMA, and Donchian Mid). Higher values create a smoother, slower-reacting baseline.")
 
// กลุ่ม Pressure Engine
grpPress  = "Pressure Engine"
pressMode = input.string("Price Pressure", "Pressure Mode", options=["Price Pressure", "Volume Delta", "Hybrid"], group=grpPress, tooltip="Determines how buying and selling pressure is weighted: purely by price action geometry (Price Pressure), scaled directly by volume (Volume Delta), or square-root volume weighted (Hybrid).")
tfMode    = input.string("Auto", "Lower Timeframe Mode", options=["Auto", "Manual"], group=grpPress, tooltip="Select 'Auto' to automatically pick an intrabar lower timeframe based on your current chart, or 'Manual' to specify a custom lower timeframe for pressure calculation.")
manTf     = input.timeframe("5", "Manual Lower Timeframe", group=grpPress, tooltip="Custom lower timeframe used for intrabar pressure analysis when Lower Timeframe Mode is set to 'Manual'. Must be lower than the current chart timeframe.")
pxWidth   = input.float(0.01, "Price Spread Width (pxWidth)", minval=0.0001, step=0.001, group=grpPress, tooltip="Controls the spatial smoothing bandwidth of the cubic kernel across price levels. Higher values blend pressure smoothly across wider price ranges.")
wickW     = input.float(0.85, "Wick Weight (wickW)", minval=0.0, maxval=2.0, step=0.05, group=grpPress, tooltip="Multiplier for upper and lower wick rejection forces. Increase to give more weight to tail rejections; decrease to focus primarily on candle body momentum.")
 
// กลุ่ม Gradient
grpGrad    = "Gradient & Visuals"
brightness = input.float(3.0, "Brightness", minval=0.1, maxval=10.0, step=0.1, group=grpGrad, tooltip="Adjusts the opacity and visual intensity of the 12 profile bands. Higher values make weaker pressure imbalances appear more vivid and opaque on the chart.")
buyCol     = input.color(#00EFB4, "Buy Color", group=grpGrad, tooltip="Primary color used for bullish pressure bands, upward Anchor line trends, and BUY signal labels.")
sellCol    = input.color(#FF3D6E, "Sell Color", group=grpGrad, tooltip="Primary color used for bearish pressure bands, downward Anchor line trends, and SELL signal labels.")
anchOn     = input.bool(true, "Show Anchor Line", group=grpGrad, tooltip="Toggles the visibility of the main Anchor baseline and its surrounding glow effect on the chart.")
 
// กลุ่ม Signals
grpSig      = "Signals (Order Entry)"
sigOn       = input.bool(true, "Enable Signals", group=grpSig, tooltip="Enables or disables BUY and SELL order entry labels and their corresponding alert triggers.")
sigDom      = input.float(0.25, "Dominance Threshold (sigDom)", minval=0.01, maxval=1.0, step=0.05, group=grpSig, tooltip="Minimum net pressure dominance ratio (0.0 to 1.0) required across the profile corridor to validate a BUY or SELL entry signal.")
minBands    = input.int(7, "Minimum Active Bands (out of 12)", minval=1, maxval=12, group=grpSig, tooltip="Minimum number of visible profile bands (out of 12) that must be active before a trade signal can be generated.")
sigGap      = input.int(6, "Minimum Signal Gap (Bars)", minval=1, group=grpSig, tooltip="Minimum cooldown period in bars required between consecutive signals of the same direction to prevent signal clustering.")
labLookback = input.int(10, "Label Lookback (Bars)", minval=1, group=grpSig, tooltip="Number of recent bars used to find the highest high or lowest low for positioning BUY and SELL signal labels cleanly away from price action.")
labMaxGap   = input.float(1.0, "Max Label Gap (ATR Multiplier)", minval=0.1, step=0.1, group=grpSig, tooltip="Maximum vertical distance (in multiples of 14-period ATR) allowed between the signal candle's high/low and the placed signal label.")
 
// ============================================================================
// ฟังก์ชันช่วยเหลือ (Helper Functions)
// ============================================================================
clamp(float val, float lo, float hi) =>
    math.max(lo, math.min(hi, val))
 
// คำนวณแรงกดดันและจุดศูนย์ถ่วงราคาของแท่งเทียน 1 แท่ง
calcStepPressure(float o, float h, float l, float c, float prevC, float v, float prevResp, string pMode, float wW) =>
    float r          = math.max(h - l, syminfo.mintick)
    float bodyHi     = math.max(o, c)
    float bodyLo     = math.min(o, c)
    float body       = bodyHi - bodyLo
    float uWick      = math.max(0.0, h - bodyHi)
    float lWick      = math.max(0.0, bodyLo - l)
    
    float directional = clamp((c - o) / r, -1.0, 1.0)
    float travel      = clamp((c - prevC) / r, -1.5, 1.5)
    float closeLoc    = clamp((2.0 * c - h - l) / r, -1.0, 1.0)
    float response    = clamp(0.55 * travel + 0.25 * directional + 0.20 * closeLoc, -1.5, 1.5)
    
    int dirNow        = response > 0.05 ? 1 : response < -0.05 ? -1 : 0
    int dirPrev       = prevResp > 0.05 ? 1 : prevResp < -0.05 ? -1 : 0
    float continuation = (dirNow != 0 and dirPrev != 0) ? (dirNow == dirPrev ? 1.45 : 0.55) : 1.0
    
    float volMult     = pMode == "Price Pressure" ? 1.0 : pMode == "Volume Delta" ? nz(v, 1.0) : math.sqrt(math.max(nz(v, 1.0), 1.0))
    
    float buyRaw      = math.max(0.0, response) * continuation * (0.5 + 0.5 * (body / r)) * volMult
    float sellRaw     = math.max(0.0, -response) * continuation * (0.5 + 0.5 * (body / r)) * volMult
    float lowRejRaw   = (lWick / r) * wW * (c >= o ? 1.15 : 0.85) * volMult
    float highRejRaw  = (uWick / r) * wW * (c <= o ? 1.15 : 0.85) * volMult
    float stallRaw    = (1.0 - body / r) * (1.0 - math.min(1.0, math.abs(response))) * 0.5 * volMult
    
    float bCtr        = bodyLo + 0.65 * body
    float sCtr        = bodyHi - 0.65 * body
    float lCtr        = l + 0.35 * lWick
    float hCtr        = h - 0.35 * uWick
    float stCtr       = (bodyHi + bodyLo) * 0.5
    
    [buyRaw, sellRaw, lowRejRaw, highRejRaw, stallRaw, bCtr, sCtr, lCtr, hCtr, stCtr, response]
 
// ============================================================================
// 2. ตรรกะการคำนวณ (Core Logic)
// ============================================================================
// 2.1 การคำนวณ Anchor
float emaFallback = ta.ema(close, anchorLen)
float smaVal      = ta.sma(close, anchorLen)
float vwmaVal     = ta.vwma(close, anchorLen)
float vwapVal     = ta.vwap(hlc3)
float donchianMid = (ta.highest(high, anchorLen)[1] + ta.lowest(low, anchorLen)[1]) * 0.5
 
float anchor = switch anchType
    "EMA"          => emaFallback
    "SMA"          => smaVal
    "VWMA"         => na(vwmaVal) ? emaFallback : vwmaVal
    "VWAP"         => na(vwapVal) ? emaFallback : vwapVal
    "Donchian Mid" => na(donchianMid) ? emaFallback : donchianMid
    => emaFallback
 
// 2.2 การคำนวณแรงกดดัน (Pressure Calculation)
string autoLtf = timeframe.isintraday ? (timeframe.multiplier <= 5 ? "1" : timeframe.multiplier <= 30 ? "5" : "15") : "60"
string ltf     = tfMode == "Auto" ? autoLtf : manTf
bool   useLtf  = timeframe.in_seconds(ltf) < timeframe.in_seconds(timeframe.period)
 
array<float> ltfO = request.security_lower_tf(syminfo.tickerid, ltf, open)
array<float> ltfH = request.security_lower_tf(syminfo.tickerid, ltf, high)
array<float> ltfL = request.security_lower_tf(syminfo.tickerid, ltf, low)
array<float> ltfC = request.security_lower_tf(syminfo.tickerid, ltf, close)
array<float> ltfV = request.security_lower_tf(syminfo.tickerid, ltf, volume)
 
var float prevRespChart = 0.0
float buyNow   = 0.0
float sellNow  = 0.0
float lowRej   = 0.0
float highRej  = 0.0
float stallNow = 0.0
 
float buyCtr   = close
float sellCtr  = close
float lowCtr   = low
float highCtr  = high
float stallCtr = hl2
 
if useLtf and array.size(ltfC) > 0
    int count = math.min(array.size(ltfC), 90)
    float bW = 0.0, float sW = 0.0, float lW = 0.0, float hW = 0.0, float stW = 0.0
    float pC = nz(close[1], array.get(ltfO, 0))
    float pR = prevRespChart
    for i = 0 to count - 1
        float cO = array.get(ltfO, i)
        float cH = array.get(ltfH, i)
        float cL = array.get(ltfL, i)
        float cC = array.get(ltfC, i)
        float cV = array.size(ltfV) > i ? nz(array.get(ltfV, i), 1.0) : 1.0
        [bR, sR, lR, hR, stR, bC, sC, lC, hC, stC, resp] = calcStepPressure(cO, cH, cL, cC, pC, cV, pR, pressMode, wickW)
        buyNow   += bR
        sellNow  += sR
        lowRej   += lR
        highRej  += hR
        stallNow += stR
        bW       += bR * bC
        sW       += sR * sC
        lW       += lR * lC
        hW       += hR * hC
        stW      += stR * stC
        pC       := cC
        pR       := resp
    prevRespChart := pR
    buyCtr        := buyNow   > 0.0 ? bW / buyNow   : close
    sellCtr       := sellNow  > 0.0 ? sW / sellNow  : close
    lowCtr        := lowRej   > 0.0 ? lW / lowRej   : low
    highCtr       := highRej  > 0.0 ? hW / highRej  : high
    stallCtr      := stallNow > 0.0 ? stW / stallNow : hl2
else
    [bR, sR, lR, hR, stR, bC, sC, lC, hC, stC, resp] = calcStepPressure(open, high, low, close, nz(close[1], open), nz(volume, 1.0), prevRespChart, pressMode, wickW)
    buyNow        := bR
    sellNow       := sR
    lowRej        := lR
    highRej       := hR
    stallNow      := stR
    buyCtr        := bC
    sellCtr       := sC
    lowCtr        := lC
    highCtr       := hC
    stallCtr      := stC
    prevRespChart := resp
 
// ปรับสเกลด้วย flowScale จาก baseline = ta.ema(totalNow, 55)
float totalNow  = buyNow + sellNow + lowRej + highRej + stallNow
float baseline  = ta.ema(totalNow, 55)
float flowScale = baseline > 0.0 ? clamp(totalNow / baseline, 0.2, 3.0) : 1.0
 
buyNow   *= flowScale
sellNow  *= flowScale
lowRej   *= flowScale
highRej  *= flowScale
stallNow *= flowScale
 
// กำหนดบัฟเฟอร์ย้อนหลังสำหรับตัวแปรที่ถูกเรียกใช้ในลูป 60 แท่ง
max_bars_back(buyNow, 100)
max_bars_back(sellNow, 100)
max_bars_back(lowRej, 100)
max_bars_back(highRej, 100)
max_bars_back(stallNow, 100)
max_bars_back(buyCtr, 100)
max_bars_back(sellCtr, 100)
max_bars_back(lowCtr, 100)
max_bars_back(highCtr, 100)
max_bars_back(stallCtr, 100)
 
// 2.3 การสร้าง Rolling Profile 12 แถบ (Corridor Geometry & Band Pressure)
int   BANDS    = 12
float bodyLo   = math.min(open, close)
float bodyHi   = math.max(open, close)
float edge     = anchor < bodyLo ? bodyLo : anchor > bodyHi ? bodyHi : na
float distance = not na(edge) ? (edge - anchor) / BANDS : na
 
float atrVal   = nz(ta.atr(14), syminfo.mintick * 100)
float spread   = math.max(atrVal * (0.25 + pxWidth * 15.0), math.abs(nz(edge - anchor, atrVal)) * 0.35, syminfo.mintick * 4.0)
float ageDecay = math.pow(0.5, 1.0 / 3.0)
 
array<color> bandColors = array.new_color(BANDS, color(na))
int   visBands  = 0
int   buyBands  = 0
int   sellBands = 0
float profBuy   = 0.0
float profSell  = 0.0
 
if not na(edge) and math.abs(distance) > 0.0
    for b = 0 to BANDS - 1
        float bandMid   = anchor + (b + 0.5) * distance
        float buyField  = 0.0
        float sellField = 0.0
        float wAge      = 1.0
        int   maxBack   = math.min(bar_index, 59)
        
        for k = 0 to maxBack
            // สะสมแรงฝั่งซื้อ (buyNow + lowRej + 0.5 * stallNow) ด้วย Cubic Kernel
            float qb = 1.0 - math.min(1.0, math.abs(bandMid - nz(buyCtr[k], bandMid)) / spread)
            if qb > 0.0
                buyField += nz(buyNow[k]) * (qb * qb * (3.0 - 2.0 * qb)) * wAge
                
            float ql = 1.0 - math.min(1.0, math.abs(bandMid - nz(lowCtr[k], bandMid)) / spread)
            if ql > 0.0
                buyField += nz(lowRej[k]) * (ql * ql * (3.0 - 2.0 * ql)) * wAge
                
            // สะสมแรงฝั่งขาย (sellNow + highRej + 0.5 * stallNow) ด้วย Cubic Kernel
            float qs = 1.0 - math.min(1.0, math.abs(bandMid - nz(sellCtr[k], bandMid)) / spread)
            if qs > 0.0
                sellField += nz(sellNow[k]) * (qs * qs * (3.0 - 2.0 * qs)) * wAge
                
            float qh = 1.0 - math.min(1.0, math.abs(bandMid - nz(highCtr[k], bandMid)) / spread)
            if qh > 0.0
                sellField += nz(highRej[k]) * (qh * qh * (3.0 - 2.0 * qh)) * wAge
                
            float qst = 1.0 - math.min(1.0, math.abs(bandMid - nz(stallCtr[k], bandMid)) / spread)
            if qst > 0.0
                float kSt = (qst * qst * (3.0 - 2.0 * qst)) * wAge * 0.5
                buyField  += nz(stallNow[k]) * kSt
                sellField += nz(stallNow[k]) * kSt
                
            wAge *= ageDecay
            
        float total     = buyField + sellField
        float imbalance = total > 0.0 ? clamp((buyField - sellField) / total * 3.0, -1.0, 1.0) : 0.0
        
        profBuy  += buyField
        profSell += sellField
        
        if imbalance > 0.03
            buyBands += 1
        else if imbalance < -0.03
            sellBands += 1
            
        float intensity = clamp(math.abs(imbalance) * (brightness / 3.0), 0.0, 1.0)
        if total > 0.0 and math.abs(imbalance) > 0.01
            visBands += 1
            float alpha = clamp(88.0 - intensity * 73.0, 12.0, 90.0)
            color baseC = imbalance >= 0.0 ? buyCol : sellCol
            array.set(bandColors, b, color.new(baseC, alpha))
 
// ============================================================================
// 3. เงื่อนไขจุดเปิดออเดอร์ (Buy / Sell Order Entry Conditions)
// ============================================================================
bool  hasProfile = visBands >= minBands and (profBuy + profSell) > 0.0
float profBias   = hasProfile ? (profBuy - profSell) / (profBuy + profSell) : 0.0
float actBias    = profBias
 
bool buyAlign  = hasProfile and close > anchor and anchor > nz(anchor[1], anchor) and actBias >= sigDom and buyBands > sellBands
bool sellAlign = hasProfile and close < anchor and anchor < nz(anchor[1], anchor) and actBias <= -sigDom and sellBands > buyBands
 
var int lastBuyBar  = -99999
var int lastSellBar = -99999
 
// ใน Pine Script v6 ตัวแปร bool[1] ไม่สามารถเป็น na ได้ จึงใช้ not buyAlign[1] ได้โดยตรง
bool buySig  = sigOn and buyAlign and not buyAlign[1] and (bar_index - lastBuyBar >= sigGap)
bool sellSig = sigOn and sellAlign and not sellAlign[1] and (bar_index - lastSellBar >= sigGap)
 
if buySig
    lastBuyBar := bar_index
if sellSig
    lastSellBar := bar_index
 
// ============================================================================
// 4. การแสดงผลบนกราฟและการแจ้งเตือน (Plotting & Alerts)
// ============================================================================
// 4.1 คำนวณระดับ p00 ถึง p12 สำหรับวาด plotcandle() 12 ชุด
float p00 = not na(edge) ? anchor + 0.0  * distance : na
float p01 = not na(edge) ? anchor + 1.0  * distance : na
float p02 = not na(edge) ? anchor + 2.0  * distance : na
float p03 = not na(edge) ? anchor + 3.0  * distance : na
float p04 = not na(edge) ? anchor + 4.0  * distance : na
float p05 = not na(edge) ? anchor + 5.0  * distance : na
float p06 = not na(edge) ? anchor + 6.0  * distance : na
float p07 = not na(edge) ? anchor + 7.0  * distance : na
float p08 = not na(edge) ? anchor + 8.0  * distance : na
float p09 = not na(edge) ? anchor + 9.0  * distance : na
float p10 = not na(edge) ? anchor + 10.0 * distance : na
float p11 = not na(edge) ? anchor + 11.0 * distance : na
float p12 = not na(edge) ? edge : na
 
color c00 = array.get(bandColors, 0)
color c01 = array.get(bandColors, 1)
color c02 = array.get(bandColors, 2)
color c03 = array.get(bandColors, 3)
color c04 = array.get(bandColors, 4)
color c05 = array.get(bandColors, 5)
color c06 = array.get(bandColors, 6)
color c07 = array.get(bandColors, 7)
color c08 = array.get(bandColors, 8)
color c09 = array.get(bandColors, 9)
color c10 = array.get(bandColors, 10)
color c11 = array.get(bandColors, 11)
 
// วาดแถบสี 12 ระดับด้วย plotcandle() ไร้ไส้เทียนและเส้นขอบ
plotcandle(math.min(p00, p01), math.max(p00, p01), math.min(p00, p01), math.max(p00, p01), "Band 01", color=c00, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p01, p02), math.max(p01, p02), math.min(p01, p02), math.max(p01, p02), "Band 02", color=c01, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p02, p03), math.max(p02, p03), math.min(p02, p03), math.max(p02, p03), "Band 03", color=c02, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p03, p04), math.max(p03, p04), math.min(p03, p04), math.max(p03, p04), "Band 04", color=c03, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p04, p05), math.max(p04, p05), math.min(p04, p05), math.max(p04, p05), "Band 05", color=c04, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p05, p06), math.max(p05, p06), math.min(p05, p06), math.max(p05, p06), "Band 06", color=c05, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p06, p07), math.max(p06, p07), math.min(p06, p07), math.max(p06, p07), "Band 07", color=c06, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p07, p08), math.max(p07, p08), math.min(p07, p08), math.max(p07, p08), "Band 08", color=c07, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p08, p09), math.max(p08, p09), math.min(p08, p09), math.max(p08, p09), "Band 09", color=c08, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p09, p10), math.max(p09, p10), math.min(p09, p10), math.max(p09, p10), "Band 10", color=c09, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p10, p11), math.max(p10, p11), math.min(p10, p11), math.max(p10, p11), "Band 11", color=c10, wickcolor=color(na), bordercolor=color(na))
plotcandle(math.min(p11, p12), math.max(p11, p12), math.min(p11, p12), math.max(p11, p12), "Band 12", color=c11, wickcolor=color(na), bordercolor=color(na))
 
// 4.2 วาดเส้น Anchor และ Anchor Glow
color anchColor = close >= anchor ? buyCol : sellCol
plot(anchOn ? anchor : na, "Anchor Line", color=anchColor, linewidth=2)
plot(anchOn ? anchor : na, "Anchor Glow", color=color.new(anchColor, 50), linewidth=6)
 
// 4.3 ป้ายสัญญาณ BUY / SELL และคำสั่งแจ้งเตือน Alert
float lowestLookback  = ta.lowest(low, labLookback)
float highestLookback = ta.highest(high, labLookback)
 
float buyPct  = (profBuy + profSell) > 0.0 ? (profBuy / (profBuy + profSell)) * 100.0 : 50.0
float sellPct = (profBuy + profSell) > 0.0 ? (profSell / (profBuy + profSell)) * 100.0 : 50.0
string status = barstate.isconfirmed ? "confirmed" : "live"
 
if buySig
    float buyY    = math.max(lowestLookback, low - labMaxGap * atrVal)
    string bTip   = str.format("BUY Signal\nBuy Pressure: {0,number,#.#}%\nNet Bias: {1,number,+#.#;-#.#}%\nActive Bands: {2}/12 (Buy: {3}, Sell: {4})", buyPct, actBias * 100.0, visBands, buyBands, sellBands)
    label.new(bar_index, buyY, "BUY", style=label.style_label_up, color=buyCol, textcolor=color.black, size=size.small, tooltip=bTip)
    alert(str.format("[{0}] BUY Signal on {1} ({2}) | Buy Pressure: {3,number,#.#}% | Bias: {4,number,+#.#;-#.#}% | Bands: {5}/12", status, syminfo.ticker, timeframe.period, buyPct, actBias * 100.0, visBands), alert.freq_once_per_bar)
 
if sellSig
    float sellY   = math.min(highestLookback, high + labMaxGap * atrVal)
    string sTip   = str.format("SELL Signal\nSell Pressure: {0,number,#.#}%\nNet Bias: {1,number,+#.#;-#.#}%\nActive Bands: {2}/12 (Sell: {3}, Buy: {4})", sellPct, actBias * 100.0, visBands, sellBands, buyBands)
    label.new(bar_index, sellY, "SELL", style=label.style_label_down, color=sellCol, textcolor=color.white, size=size.small, tooltip=sTip)
    alert(str.format("[{0}] SELL Signal on {1} ({2}) | Sell Pressure: {3,number,#.#}% | Bias: {4,number,+#.#;-#.#}% | Bands: {5}/12", status, syminfo.ticker, timeframe.period, sellPct, actBias * 100.0, visBands), alert.freq_once_per_bar)

← 返回列表