Volume Z-Score Strategy

OmegaTools · strategy · 280 行 · 点赞 51 · TradingView 原页

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

Pine Script

// © OmegaTools
 
//@version=6
strategy(title             = "Ω Volume Z-Score Strategy",
     shorttitle            = "Ω VolZ",
     overlay               = false,
     precision             = 2,
     default_qty_type      = strategy.fixed,
     default_qty_value     = 1,
     pyramiding            = 0)
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  CONSTANTS                                                                 ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
const string G_SIGNAL   = "◆ Signal Engine"
const string G_FILTER   = "◆ Filters"
const string G_RISK     = "◆ Risk Management"
const string G_STYLE    = "◆ Style"
 
const string DIR_BOTH   = "Both"
const string DIR_LONG   = "Long Only"
const string DIR_SHORT  = "Short Only"
 
const string TF_OFF     = "Off"
const string TF_WITH    = "With Trend"
const string TF_AGAINST = "Counter-Trend"
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  INPUTS                                                                    ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
// ── Signal engine ───────────────────────────────────────────────────────────
int    lenInput       = input.int(21, "Lookback", minval = 2, group = G_SIGNAL,
     tooltip = "Window for the price z-score and the relative-volume baseline.")
float  thrInput       = input.float(3.0, "Z Threshold", minval = 0.1, step = 0.1, group = G_SIGNAL,
     tooltip = "Entry Z beyond ±threshold opens a trade; Exit Z beyond ±threshold closes it.")
bool   invertInput    = input.bool(false, "Invert Volume Weighting", group = G_SIGNAL,
     tooltip = "Off: entries trigger on low-volume extensions, exits on high-volume ones.\nOn: the opposite.")
string dirInput       = input.string(DIR_BOTH, "Direction", options = [DIR_BOTH, DIR_LONG, DIR_SHORT], group = G_SIGNAL)
 
// ── Filters ─────────────────────────────────────────────────────────────────
string sessInput      = input.session("0800-2000", "Trading Session", group = G_FILTER,
     tooltip = "New entries are only allowed inside this window.")
string tzInput        = input.string("UTC+1", "Session Timezone", group = G_FILTER,
     tooltip = "UTC offset (e.g. UTC+1) or IANA name (e.g. Europe/Rome). IANA names follow daylight-saving time.")
string trendModeInput = input.string(TF_WITH, "Trend Filter", options = [TF_OFF, TF_WITH, TF_AGAINST], group = G_FILTER,
     tooltip = "With Trend: longs only above the trend MA, shorts only below.\nCounter-Trend: the opposite.\nOff: no filter.")
int    trendLenInput  = input.int(252, "Trend MA Length", minval = 2, group = G_FILTER)
 
// ── Risk management (all disabled by default) ───────────────────────────────
float  slAtrInput     = input.float(0.0, "Stop Loss (× ATR)", minval = 0.0, step = 0.25, group = G_RISK,
     tooltip = "0 = disabled. Distance from the average entry price, using ATR at entry.")
float  tpAtrInput     = input.float(0.0, "Take Profit (× ATR)", minval = 0.0, step = 0.25, group = G_RISK,
     tooltip = "0 = disabled. Distance from the average entry price, using ATR at entry.")
int    atrLenInput    = input.int(14, "ATR Length", minval = 1, group = G_RISK)
int    maxBarsInput   = input.int(0, "Max Bars in Trade", minval = 0, group = G_RISK,
     tooltip = "0 = disabled. Closes the position after this many bars.")
bool   flatOutInput   = input.bool(false, "Flatten Outside Session", group = G_RISK,
     tooltip = "Closes any open position on the first bar outside the trading session.")
 
// ── Style ───────────────────────────────────────────────────────────────────
color  bullColor      = input.color(#26A69A, "Palette", group = G_STYLE, inline = "pal", tooltip = "Bull · Bear · Neutral")
color  bearColor      = input.color(#EF5350, "",        group = G_STYLE, inline = "pal")
color  neutColor      = input.color(#787B86, "",        group = G_STYLE, inline = "pal")
bool   showTrendMa    = input.bool(true,  "Trend MA on Price Chart",  group = G_STYLE)
bool   showSignals    = input.bool(true,  "Signals on Price Chart",   group = G_STYLE)
bool   colorBars      = input.bool(false, "Color Bars by Position",   group = G_STYLE)
bool   showDash       = input.bool(true,  "Dashboard", group = G_STYLE, inline = "dash")
string dashPosInput   = input.string("Top Right", "", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"],
     group = G_STYLE, inline = "dash")
color  dashBgColor    = input.color(color.new(#131722, 8), "Dashboard Theme", group = G_STYLE, inline = "dcol", tooltip = "Background · Text")
color  dashTxtColor   = input.color(#D1D4DC, "", group = G_STYLE, inline = "dcol")
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  FUNCTIONS                                                                 ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
// @function  Bounds `x` to the [lo, hi] interval.
clamp(float x, float lo, float hi) =>
    math.max(lo, math.min(hi, x))
 
// @function  Rolling z-score; returns 0 on flat windows instead of dividing by zero.
zScore(float src, int len) =>
    float basis = ta.sma(src, len)
    float dev   = ta.stdev(src, len)
    na(dev) ? na : dev > 0 ? (src - basis) / dev : 0.0
 
// @function  Relative volume squashed into a ~[0.4, 2.5] multiplier.
//            Falls back to 1 (neutral) on symbols without volume data.
volumeFactor(int len) =>
    float avgVol = ta.sma(volume, len)
    float rvol   = avgVol > 0 ? nz(volume) / avgVol : 1.0
    math.avg(clamp(rvol, 0.5, 2.0), clamp(rvol, 0.33, 3.0))
 
// @function  Maps the dashboard position label to a `position.*` constant.
dashPosition(string label) =>
    switch label
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
// @function  Writes one key/value row into the dashboard.
method row(table t, int r, string key, string value, color valueColor) =>
    t.cell(0, r, key,   text_color = color.new(dashTxtColor, 40), text_halign = text.align_left,  text_size = size.small)
    t.cell(1, r, value, text_color = valueColor,                  text_halign = text.align_right, text_size = size.small)
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  CALCULATIONS                                                              ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
float z       = zScore(close, lenInput)
float volF    = volumeFactor(lenInput)
 
// Entry Z is dampened by volume, Exit Z amplified (swapped when inverted).
float zEntry  = invertInput ? z * volF : z / volF
float zExit   = invertInput ? z / volF : z * volF
 
// Trend bias: +1 allows longs only, -1 shorts only, 0 both.
float trendMa   = ta.sma(close, trendLenInput)
float trendDir  = math.sign(close - trendMa)
float trendBias = switch trendModeInput
    TF_WITH    =>  trendDir
    TF_AGAINST => -trendDir
    => 0.0
 
bool  inSession = not na(time(timeframe.period, sessInput, tzInput))
float atr       = ta.atr(atrLenInput)
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  SIGNALS                                                                   ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
bool upSignal     = zEntry >  thrInput
bool downSignal   = zEntry < -thrInput
 
bool longEntry    = upSignal   and inSession and trendBias >= 0 and dirInput != DIR_SHORT
bool shortEntry   = downSignal and inSession and trendBias <= 0 and dirInput != DIR_LONG
 
// A blocked signal still invalidates the opposite position.
bool longFlip     = downSignal and not shortEntry
bool shortFlip    = upSignal   and not longEntry
bool longExhaust  = zExit >  thrInput
bool shortExhaust = zExit < -thrInput
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  EXECUTION                                                                 ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
string tag = "Ω VolZ | " + syminfo.ticker + " | "
 
if longEntry
    strategy.entry("Long", strategy.long, comment = "Long", alert_message = tag + "LONG")
else if shortFlip
    strategy.close("Short", comment = "Opposite Signal", alert_message = tag + "CLOSE SHORT")
 
if shortEntry
    strategy.entry("Short", strategy.short, comment = "Short", alert_message = tag + "SHORT")
else if longFlip
    strategy.close("Long", comment = "Opposite Signal", alert_message = tag + "CLOSE LONG")
 
if longExhaust
    strategy.close("Long", comment = "Exhaustion", alert_message = tag + "CLOSE LONG")
if shortExhaust
    strategy.close("Short", comment = "Exhaustion", alert_message = tag + "CLOSE SHORT")
 
// ── Optional risk layer ─────────────────────────────────────────────────────
var float entryAtr = na
if strategy.position_size != 0 and strategy.position_size != strategy.position_size[1]
    entryAtr := atr
 
bool  useBrackets = slAtrInput > 0 or tpAtrInput > 0
float avgPrice    = strategy.position_avg_price
 
if useBrackets and strategy.position_size > 0
    strategy.exit("Long Bracket", from_entry = "Long",
         stop           = slAtrInput > 0 ? avgPrice - slAtrInput * entryAtr : na,
         limit          = tpAtrInput > 0 ? avgPrice + tpAtrInput * entryAtr : na,
         comment_loss   = "Stop Loss",
         comment_profit = "Take Profit",
         alert_message  = tag + "CLOSE LONG")
 
if useBrackets and strategy.position_size < 0
    strategy.exit("Short Bracket", from_entry = "Short",
         stop           = slAtrInput > 0 ? avgPrice + slAtrInput * entryAtr : na,
         limit          = tpAtrInput > 0 ? avgPrice - tpAtrInput * entryAtr : na,
         comment_loss   = "Stop Loss",
         comment_profit = "Take Profit",
         alert_message  = tag + "CLOSE SHORT")
 
if maxBarsInput > 0 and strategy.opentrades > 0
    int barsHeld = bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1)
    if barsHeld >= maxBarsInput
        strategy.close_all(comment = "Time Stop", alert_message = tag + "FLAT")
 
if flatOutInput and not inSession and strategy.position_size != 0
    strategy.close_all(comment = "Session End", alert_message = tag + "FLAT")
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  VISUALS · OSCILLATOR PANE                                                 ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
color zEntryColor = zEntry >= 0
     ? color.from_gradient(zEntry,  0.0,      thrInput, neutColor, bullColor)
     : color.from_gradient(zEntry, -thrInput, 0.0,      bearColor, neutColor)
 
hUpper = hline( thrInput, "Upper Threshold", color.new(bullColor, 40), hline.style_dashed)
hZero  = hline( 0,        "Zero",            color.new(neutColor, 60), hline.style_dotted)
hLower = hline(-thrInput, "Lower Threshold", color.new(bearColor, 40), hline.style_dashed)
fill(hUpper, hLower, color.new(neutColor, 96), "Neutral Band")
 
plot(zExit, "Exit Z", color.new(zExit >= 0 ? bullColor : bearColor, 72), style = plot.style_columns)
pEntry = plot(zEntry, "Entry Z", zEntryColor, 2)
 
pUpper = plot( thrInput, editable = false, display = display.none)
pLower = plot(-thrInput, editable = false, display = display.none)
fill(pEntry, pUpper, zEntry >  thrInput ? color.new(bullColor, 60) : na, "Long Extension")
fill(pEntry, pLower, zEntry < -thrInput ? color.new(bearColor, 60) : na, "Short Extension")
 
color posColor = strategy.position_size > 0 ? bullColor : strategy.position_size < 0 ? bearColor : na
bgcolor(color.new(posColor, 92), title = "Position")
bgcolor(inSession ? na : color.new(neutColor, 90), title = "Outside Session")
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  VISUALS · PRICE CHART                                                     ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
plot(showTrendMa ? trendMa : na, "Trend MA", close >= trendMa ? color.new(bullColor, 20) : color.new(bearColor, 20), 2,
     force_overlay = true)
 
plotshape(showSignals and longEntry  and strategy.position_size <= 0, "Long Signal",  shape.triangleup,
     location.belowbar, bullColor, size = size.tiny, force_overlay = true)
plotshape(showSignals and shortEntry and strategy.position_size >= 0, "Short Signal", shape.triangledown,
     location.abovebar, bearColor, size = size.tiny, force_overlay = true)
plotshape(showSignals and longExhaust  and strategy.position_size > 0, "Long Exhaustion",  shape.xcross,
     location.abovebar, color.new(bullColor, 30), size = size.tiny, force_overlay = true)
plotshape(showSignals and shortExhaust and strategy.position_size < 0, "Short Exhaustion", shape.xcross,
     location.belowbar, color.new(bearColor, 30), size = size.tiny, force_overlay = true)
 
barcolor(colorBars ? nz(posColor, neutColor) : na, title = "Position Bars")
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  DASHBOARD                                                                 ║
// ╚════════════════════════════════════════════════════════════════════════════╝
 
var table dash = table.new(dashPosition(dashPosInput), 2, 12,
     bgcolor      = dashBgColor,
     frame_color  = color.new(dashTxtColor, 80),
     frame_width  = 1,
     border_color = color.new(dashTxtColor, 92),
     border_width = 1)
 
if showDash and barstate.islast
    int   closed   = strategy.closedtrades
    float winRate  = closed > 0 ? 100.0 * strategy.wintrades / closed : na
    float pf       = strategy.grossloss > 0 ? strategy.grossprofit / strategy.grossloss : na
    float netPct   = 100.0 * strategy.netprofit / strategy.initial_capital
    float ddPct    = 100.0 * strategy.max_drawdown / strategy.initial_capital
    string trendTx = trendModeInput == TF_OFF ? "Off" : trendDir > 0 ? "Up ▲" : trendDir < 0 ? "Down ▼" : "—"
    string posTx   = strategy.position_size > 0 ? "Long" : strategy.position_size < 0 ? "Short" : "Flat"
 
    dash.cell(0, 0, "Ω VOLUME Z-SCORE", text_color = dashTxtColor, text_size = size.small, text_halign = text.align_left)
    dash.merge_cells(0, 0, 1, 0)
 
    dash.row(1,  "Entry Z",       str.tostring(zEntry, "+0.00;-0.00"),  zEntryColor)
    dash.row(2,  "Exit Z",        str.tostring(zExit,  "+0.00;-0.00"),  zExit >= 0 ? bullColor : bearColor)
    dash.row(3,  "Volume Factor", str.tostring(volF, "0.00") + "×",     volF >= 1 ? dashTxtColor : neutColor)
    dash.row(4,  "Trend",         trendTx,                              trendDir > 0 ? bullColor : bearColor)
    dash.row(5,  "Session",       inSession ? "Open" : "Closed",        inSession ? bullColor : neutColor)
    dash.row(6,  "Position",      posTx,                                nz(posColor, neutColor))
    dash.row(7,  "Net Profit",    str.tostring(netPct, "+0.00;-0.00") + "%", strategy.netprofit >= 0 ? bullColor : bearColor)
    dash.row(8,  "Max Drawdown",  str.tostring(ddPct, "0.00") + "%",    bearColor)
    dash.row(9,  "Profit Factor", na(pf) ? "—" : str.tostring(pf, "0.00"), na(pf) or pf >= 1 ? bullColor : bearColor)
    dash.row(10, "Win Rate",      na(winRate) ? "—" : str.tostring(winRate, "0.0") + "%", dashTxtColor)
    dash.row(11, "Trades",        str.tostring(closed),                 dashTxtColor)
 
// ╔════════════════════════════════════════════════════════════════════════════╗
// ║  END OF SCRIPT                                                             ║
// ╚════════════════════════════════════════════════════════════════════════════╝

← 返回列表