WiselyWealth : Volume Delta Oscillator with Smart Order Levels

TaninWiselyWealth · study · 299 行 · 点赞 41 · TradingView 原页

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

Pine Script

//@version=6
indicator("Volume Delta Oscillator with Smart Order Levels", overlay = false, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// INPUTS ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// 1. Engine Settings
deltaPeriod = input.int(14, title="Volume Delta Lookback", minval=1, group="Engine Settings", tooltip="Number of bars used to calculate the Exponential Moving Average (EMA) of the net buying and selling volume delta.")
smoothLen   = input.int(5, title="Signal Smoothing Length", minval=1, group="Engine Settings", tooltip="Period length for the Weighted Moving Average (WMA) signal line used to identify momentum crossovers.")
autoScale   = input.bool(true, title="Stabilize Oscillator Range", group="Engine Settings", tooltip="Automatically normalizes the EMA amplitude so the oscillator stays within a consistent visual range regardless of the lookback period.")
 
// 2. Pivot & Divergence Settings
pivLeft             = input.int(7, title="Pivot Left Lookback", minval=1, group="Divergence Settings", tooltip="Number of preceding bars required to confirm a valid pivot high or pivot low on the oscillator.")
pivRight            = input.int(2, title="Pivot Right Lookback", minval=1, group="Divergence Settings", tooltip="Number of subsequent bars required to confirm a pivot point. Higher values reduce noise but add confirmation delay.")
showBullDiv         = input.bool(true, title="Show Bullish Divergence Labels", group="Divergence Settings", tooltip="Displays a 'Bull' marker on the main price chart when a regular bullish divergence is confirmed.")
showBearDiv         = input.bool(true, title="Show Bearish Divergence Labels", group="Divergence Settings", tooltip="Displays a 'Bear' marker on the main price chart when a regular bearish divergence is confirmed.")
divLabelSize        = input.string("small", title="Divergence & Order Label Size", options=["tiny", "small", "normal", "large", "huge"], group="Divergence Settings", tooltip="Adjusts the text and box size for divergence markers, price level tags, and Buy/Sell order labels.")
showDivLines        = input.bool(true, title="Show Divergence Lines on Oscillator", group="Divergence Settings", tooltip="Draws trendlines connecting consecutive oscillator pivot points when a bullish or bearish divergence occurs.")
showDivLevels       = input.bool(true, title="Show Divergence Price Levels", group="Divergence Settings", tooltip="Projects horizontal support and resistance lines on the price chart from divergence pivot points until broken by closing price.")
showDivLevelsLabels = input.bool(true, title="Show Price Values on Levels", group="Divergence Settings", tooltip="Displays the exact price value at the right end of each active divergence support or resistance line.")
maxLevels           = 5
 
// 3. Threshold Settings
obThreshold = input.float(50.0, title="Overbought Threshold", group="Threshold & Signal Settings", tooltip="Upper oscillator boundary defining the overbought zone. Used for zone shading and filtering bearish crossover signals.")
osThreshold = input.float(-50.0, title="Oversold Threshold", group="Threshold & Signal Settings", tooltip="Lower oscillator boundary defining the oversold zone. Used for zone shading and filtering bullish crossover signals.")
 
// 4. Entry Signal Settings
showOrderSignals = input.bool(true, title="Show Buy/Sell Order Signals", group="Threshold & Signal Settings", tooltip="Toggles the visibility of 'OPEN BUY' and 'OPEN SELL' labels with Entry and Stop Loss prices on the main chart.")
entryMode        = input.string("Both", title="Entry Signal Mode", options=["Divergence Only", "OB/OS Crossover Only", "Both"], group="Threshold & Signal Settings", tooltip="Selects the trigger condition for order signals: immediate entry on divergence, momentum crossover inside OB/OS zones, or both.")
 
// 5. Palette & Visual Settings
bullColor   = input.color(color.rgb(13, 176, 182), title="Positive / Buy Color", group="Artistic Palette", tooltip="Primary color applied to positive volume delta columns, oversold zone shading, bullish divergences, and OPEN BUY labels.")
bearColor   = input.color(#d65933, title="Negative / Sell Color", group="Artistic Palette", tooltip="Primary color applied to negative volume delta columns, overbought zone shading, bearish divergences, and OPEN SELL labels.")
signalColor = input.color(#ffb74d, title="Signal Line Color", group="Artistic Palette", tooltip="Color of the smoothed WMA signal line plotted over the volume delta oscillator.")
zeroColor   = input.color(#b2b5be, title="Zero Level Line Color", group="Artistic Palette", tooltip="Color of the central zero baseline separating net buying and selling pressure.")
showSignal  = input.bool(true, title="Show Signal Line", group="Visual Options", tooltip="Shows or hides the smoothed WMA signal line on the oscillator pane.")
// }
 
// CALCULATIONS――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
clamp(float val, float min_val, float max_val) =>
    math.min(max_val, math.max(min_val, val))
 
// คำนวณสัดส่วนเนื้อเทียนและ Volume Delta
float bodyRatio = math.abs(close - open) / math.max(high - low, syminfo.mintick)
float volDelta  = close >= open ? volume * bodyRatio : -volume * bodyRatio
 
// แปลงเป็นสเกล [-50, 50]
float rawDeltaRatio = (volDelta / math.max(volume, 1.0)) * 50.0
float deltaRatio    = clamp(rawDeltaRatio, -50.0, 50.0)
 
// คำนวณ Stabilized EMA และ Signal Line (WMA)
float refAlpha      = 2.0 / (14 + 1)
float curAlpha      = 2.0 / (deltaPeriod + 1)
float emaScale      = autoScale ? (refAlpha / curAlpha) * 10.0 : 10.0
float smoothedDelta = ta.ema(deltaRatio, deltaPeriod) * emaScale
float signalLine    = ta.wma(smoothedDelta, smoothLen)
 
// ระบบตรวจจับ Divergence และเส้นระดับราคา (Active Levels)
float ph = ta.pivothigh(smoothedDelta, pivLeft, pivRight)
float pl = ta.pivotlow(smoothedDelta, pivLeft, pivRight)
 
var float prevPhOsc   = na
var float prevPhPrice = na
var int   prevPhIdx   = na
 
var float prevPlOsc   = na
var float prevPlPrice = na
var int   prevPlIdx   = na
 
bool bearDiv = false
bool bullDiv = false
 
int currentPivotIdx = bar_index - pivRight
 
// Array เก็บเส้นระดับราคาสูงสุด 5 เส้นล่าสุด
var line[]  activeLines  = array.new_line()
var label[] activeLabels = array.new_label()
var float[] activePrices = array.new_float()
var bool[]  activeIsBull = array.new_bool()
 
trimActive(int cap) =>
    while array.size(activeLines) > cap
        line  oldL = array.shift(activeLines)
        label oldB = array.shift(activeLabels)
        array.shift(activePrices)
        array.shift(activeIsBull)
        line.delete(oldL)
        if not na(oldB)
            label.delete(oldB)
 
// ตรวจสอบ Bearish Divergence
if not na(ph)
    float currentPriceHigh = high[pivRight]
    if not na(prevPhOsc) and ph < prevPhOsc and currentPriceHigh > prevPhPrice
        bearDiv := true
        if showDivLines
            line.new(
                 x1=prevPhIdx, y1=prevPhOsc, 
                 x2=currentPivotIdx, y2=ph, 
                 color=bearColor, width=2, style=line.style_solid
             )
        if showDivLevels
            line newL = line.new(
                 x1=currentPivotIdx, y1=currentPriceHigh, 
                 x2=bar_index, y2=currentPriceHigh, 
                 color=bearColor, width=1, style=line.style_solid, 
                 force_overlay=true
             )
            label newLbl = showDivLevelsLabels ? label.new(
                 x=bar_index, y=currentPriceHigh, 
                 text=str.tostring(currentPriceHigh, format.mintick), 
                 style=label.style_label_left, 
                 color=color.new(bearColor, 100), 
                 textcolor=bearColor, 
                 size=divLabelSize, 
                 force_overlay=true
             ) : na
 
            array.push(activeLines, newL)
            array.push(activeLabels, newLbl)
            array.push(activePrices, currentPriceHigh)
            array.push(activeIsBull, false)
            trimActive(maxLevels)
 
    prevPhOsc   := ph
    prevPhPrice := currentPriceHigh
    prevPhIdx   := currentPivotIdx
 
// ตรวจสอบ Bullish Divergence
if not na(pl)
    float currentPriceLow = low[pivRight]
    if not na(prevPlOsc) and pl > prevPlOsc and currentPriceLow < prevPlPrice
        bullDiv := true
        if showDivLines
            line.new(
                 x1=prevPlIdx, y1=prevPlOsc, 
                 x2=currentPivotIdx, y2=pl, 
                 color=bullColor, width=2, style=line.style_solid
             )
        if showDivLevels
            line newL = line.new(
                 x1=currentPivotIdx, y1=currentPriceLow, 
                 x2=bar_index, y2=currentPriceLow, 
                 color=bullColor, width=1, style=line.style_solid, 
                 force_overlay=true
             )
            label newLbl = showDivLevelsLabels ? label.new(
                 x=bar_index, y=currentPriceLow, 
                 text=str.tostring(currentPriceLow, format.mintick), 
                 style=label.style_label_left, 
                 color=color.new(bullColor, 100), 
                 textcolor=bullColor, 
                 size=divLabelSize, 
                 force_overlay=true
             ) : na
 
            array.push(activeLines, newL)
            array.push(activeLabels, newLbl)
            array.push(activePrices, currentPriceLow)
            array.push(activeIsBull, true)
            trimActive(maxLevels)
 
    prevPlOsc   := pl
    prevPlPrice := currentPriceLow
    prevPlIdx   := currentPivotIdx
 
// อัปเดตเส้นระดับราคาในทุกแท่งเทียน
if array.size(activeLines) > 0
    for i = array.size(activeLines) - 1 to 0
        line  l      = array.get(activeLines, i)
        label lbl    = array.get(activeLabels, i)
        float lPrice = array.get(activePrices, i)
        bool  isBull = array.get(activeIsBull, i)
 
        bool crossed = isBull ? (close < lPrice) : (close > lPrice)
 
        if crossed
            // หยุดเส้นไว้ที่แท่งปัจจุบันและเปลี่ยนเป็นเส้นประเมื่อราคาปิดหลุดเส้น
            line.set_x2(l, bar_index)
            line.set_style(l, line.style_dashed)
            if not na(lbl)
                label.set_x(lbl, bar_index)
 
            array.remove(activeLines, i)
            array.remove(activeLabels, i)
            array.remove(activePrices, i)
            array.remove(activeIsBull, i)
        else
            // ยืดเส้นมาจนถึงแท่งปัจจุบัน
            line.set_x2(l, bar_index)
            if not na(lbl)
                label.set_x(lbl, bar_index)
 
trimActive(maxLevels)
// }
 
// ENTRY SIGNALS ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
// เงื่อนไขที่ 1: Divergence Entry
bool buyDivSignal  = bullDiv
bool sellDivSignal = bearDiv
 
// เงื่อนไขที่ 2: Momentum OB/OS Crossover Entry
bool buyCrossSignal  = ta.crossover(smoothedDelta, signalLine) and smoothedDelta < osThreshold and deltaRatio > 0
bool sellCrossSignal = ta.crossunder(smoothedDelta, signalLine) and smoothedDelta > obThreshold and deltaRatio < 0
 
// รวมสัญญาณตามโหมดที่เลือก
bool openBuy = switch entryMode
    "Divergence Only"      => buyDivSignal
    "OB/OS Crossover Only" => buyCrossSignal
    => buyDivSignal or buyCrossSignal
 
bool openSell = switch entryMode
    "Divergence Only"      => sellDivSignal
    "OB/OS Crossover Only" => sellCrossSignal
    => sellDivSignal or sellCrossSignal
 
// คำนวณจุดต่ำสุด/สูงสุดล่าสุดสำหรับการอ้างอิง Stop Loss
float lowestRecent  = ta.lowest(low, pivLeft + pivRight)
float highestRecent = ta.highest(high, pivLeft + pivRight)
 
float buySL  = buyDivSignal ? low[pivRight] : math.min(low[pivRight], lowestRecent)
float sellSL = sellDivSignal ? high[pivRight] : math.max(high[pivRight], highestRecent)
 
// วาดป้ายสัญญาณ OPEN BUY / OPEN SELL บนกราฟราคาหลัก
if showOrderSignals and openBuy
    string buyText = "OPEN BUY\nEntry: " + str.tostring(close, format.mintick) + "\nSL: " + str.tostring(buySL, format.mintick)
    label.new(
         x=bar_index, 
         y=low, 
         text=buyText, 
         style=label.style_label_up, 
         color=bullColor, 
         textcolor=color.white, 
         size=divLabelSize, 
         force_overlay=true
     )
 
if showOrderSignals and openSell
    string sellText = "OPEN SELL\nEntry: " + str.tostring(close, format.mintick) + "\nSL: " + str.tostring(sellSL, format.mintick)
    label.new(
         x=bar_index, 
         y=high, 
         text=sellText, 
         style=label.style_label_down, 
         color=bearColor, 
         textcolor=color.white, 
         size=divLabelSize, 
         force_overlay=true
     )
// }
 
// PLOT & VISUALS ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
hline(0, "Baseline", color=zeroColor, linestyle=hline.style_dashed)
 
// OB/OS Zone Fills (50 ถึง 150 และ -50 ถึง -150)
hOB     = hline(obThreshold, "Overbought Lower", color=color.new(bearColor, 100), linestyle=hline.style_dotted)
hOB_top = hline(150, "Overbought Upper", color=color.new(bearColor, 50), linestyle=hline.style_solid)
fill(hOB, hOB_top, 150, obThreshold, color.new(bearColor, 80), color.new(bearColor, 100), title="Overbought Zone Fill")
 
hOS     = hline(osThreshold, "Oversold Upper", color=color.new(bullColor, 100), linestyle=hline.style_dotted)
hOS_bot = hline(-150, "Oversold Lower", color=color.new(bullColor, 50), linestyle=hline.style_solid)
fill(hOS, hOS_bot, osThreshold, -150, color.new(bullColor, 100), color.new(bullColor, 80), title="Oversold Zone Fill")
 
// พล็อตคอลัมน์ไล่เฉดสี deltaRatio และเส้น Oscillator
colgradient = color.from_gradient(deltaRatio, -50, 50, color.new(bearColor, 50), color.new(bullColor, 50))
 
plot(deltaRatio, "Raw Volume Delta", color=colgradient, style=plot.style_columns)
plot(smoothedDelta, "Smoothed Delta Shadow", color=color.new(chart.bg_color, 50), linewidth=8)
plot(smoothedDelta, "Smoothed Delta", color=chart.fg_color, linewidth=2)
plot(showSignal ? signalLine : na, "Signal Line", color=signalColor, linewidth=1)
 
// ป้ายกำกับจุด Pivot Divergence บนกราฟหลัก
if bullDiv and showBullDiv
    label.new(
         x=bar_index[pivRight], 
         y=low[pivRight], 
         text="▲\nBull", 
         style=label.style_label_up, 
         color=na, 
         textcolor=chart.fg_color, 
         size=divLabelSize, 
         force_overlay=true
     )
 
if bearDiv and showBearDiv
    label.new(
         x=bar_index[pivRight], 
         y=high[pivRight], 
         text="Bear\n▼", 
         style=label.style_label_down, 
         color=na, 
         textcolor=chart.fg_color, 
         size=divLabelSize, 
         force_overlay=true
     )
// }
 
// ALERTS ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――{
alertcondition(openBuy, title="OPEN BUY Signal", message="Volume Delta Oscillator with Smart Order Levels: OPEN BUY Signal at {{close}} on {{ticker}} ({{interval}})")
alertcondition(openSell, title="OPEN SELL Signal", message="Volume Delta Oscillator with Smart Order Levels: OPEN SELL Signal at {{close}} on {{ticker}} ({{interval}})")
// }

← 返回列表