Normality Threshold (MTF) + Anchored VWAP

OlympusCipher · study · 352 行 · 点赞 40 · 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/
// © OlympusCipher
 
//@version=6
indicator("Normality Threshold (MTF) + Anchored VWAP", shorttitle = "NT", overlay = true, max_lines_count = 500)
 
// ─────────────────────────────────────────────────────────────
// Normality Threshold (MTF) + Anchored VWAP + Regime Signals
//
// Credits:
// - Noise-area concept: Zarattini, Aziz & Barbon (2024), "Beat the Market: An Effective
//   Intraday Momentum Strategy for S&P500 ETF (SPY)", Concretum Research / Swiss Finance
//   Institute Research Paper 24-97. https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4824172
//
// This is an independent implementation, not an official Concretum Research product.
// Additions: multi-timeframe anchoring, anchored VWAP with deviation bands,
// price-discovery (breakout) and mean-reversion (re-entry) signals with
// anti-chop filtering and alerts.
//
// For educational purposes only. Not financial advice.
// ─────────────────────────────────────────────────────────────
 
// ── Inputs ──────────────────────────────────────────────
tf_choice  = input.string("Auto", "Anchor Timeframe", options = ["Auto", "1-Hour", "4-Hour", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], tooltip = "Auto picks an anchor above the chart timeframe. A manual anchor must be higher than the chart timeframe, otherwise Auto is used.")
lookback   = input.int(10, "Lookback (completed periods)", minval = 1)
width_mult = input.float(1.0, "Width Multiplier", minval = 0.0, step = 0.1)
proj_bars  = input.int(30, "Projection Bars", minval = 0, maxval = 250)
 
zone_col   = input.color(color.new(color.white, 80), "Normal Zone Color")
edge_col   = input.color(color.new(color.white, 20), "Threshold Line Color")
 
show_vwap  = input.bool(true, "Show Anchored VWAP", group = "Anchored VWAP")
vwap_col   = input.color(color.blue, "VWAP Color", group = "Anchored VWAP")
show_dev   = input.bool(true, "Show Deviation Bands", group = "Anchored VWAP")
dev_mult   = input.float(1.0, "Deviation Multiplier", minval = 0.1, step = 0.1, group = "Anchored VWAP")
dev_col    = input.color(color.new(color.blue, 50), "Deviation Line Color", group = "Anchored VWAP")
dev_fill   = input.color(color.new(color.blue, 90), "Deviation Fill Color", group = "Anchored VWAP")
 
// Signals
show_pd      = input.bool(true, "Show Price Discovery Signals", group = "Signals", tooltip = "First close outside the normality band.")
show_mr      = input.bool(true, "Show Mean Reversion Signals", group = "Signals", tooltip = "Close back inside the band after trading outside it.")
confirm_bar  = input.bool(true, "Signal On Bar Close Only", group = "Signals", tooltip = "Avoids intrabar repainting in realtime.")
atr_len      = input.int(14, "ATR Length", minval = 1, group = "Signals")
mr_vwap_filt = input.bool(false, "MR Requires VWAP Room", group = "Signals", tooltip = "Short MR only if the re-entry close is still above VWAP; long MR only if still below. Ensures there is distance left to the VWAP target.")
tint_bars    = input.bool(false, "Tint Bars Outside Band", group = "Signals")
 
// Anti-chop
brk_buf      = input.float(0.10, "Breakout Buffer (x ATR)", minval = 0.0, step = 0.05, group = "Anti-Chop", tooltip = "Close must be this many ATRs BEYOND the band to count as price discovery.")
re_buf       = input.float(0.10, "Re-entry Buffer (x ATR)", minval = 0.0, step = 0.05, group = "Anti-Chop", tooltip = "Close must come back this many ATRs INSIDE the band edge to count as re-entry. Together with the breakout buffer this creates a dead zone at the edge so price wiggling on the line does nothing.")
min_out      = input.int(2, "Min Bars Outside Before MR", minval = 1, group = "Anti-Chop", tooltip = "Price must have closed outside for at least this many bars before a re-entry counts as mean reversion.")
hold_bars    = input.int(1, "Re-entry Hold Bars", minval = 1, group = "Anti-Chop", tooltip = "Consecutive closes back inside required before MR fires. Higher = fewer, later, cleaner signals.")
cooldown     = input.int(5, "Cooldown (bars)", minval = 0, group = "Anti-Chop", tooltip = "After a signal fires, the same signal type on the same side is blocked for this many bars.")
max_per_side = input.int(2, "Max Signals Per Side Per Period", minval = 0, group = "Anti-Chop", tooltip = "Caps how many times each signal type can fire per side within one anchor period. 0 = unlimited.")
 
// Marker style
show_txt     = input.bool(true, "Show Marker Captions", group = "Marker Style", tooltip = "Small PD / MR text next to each marker.")
mk_transp    = input.int(10, "Marker Transparency", minval = 0, maxval = 90, group = "Marker Style")
sig_flash    = input.bool(false, "Flash Background On Signal", group = "Marker Style", tooltip = "Faint vertical highlight on the signal bar.")
flash_transp = input.int(90, "Flash Transparency", minval = 70, maxval = 98, group = "Marker Style")
 
pd_up_col = input.color(#22d3ee, "Price Discovery Up",   group = "Signal Colors")
pd_dn_col = input.color(#fb923c, "Price Discovery Down", group = "Signal Colors")
mr_lg_col = input.color(#4ade80, "Mean Reversion Long",  group = "Signal Colors")
mr_sh_col = input.color(#e879f9, "Mean Reversion Short", group = "Signal Colors")
 
// ── Constants ───────────────────────────────────────────
const int MAX_SLOTS = 100000   // Pine arrays hold at most 100,000 elements
 
// ── Types & helpers ─────────────────────────────────────
type PeriodMoves
    array<float> v   // |close / period open - 1| for each bar slot of one period
 
// Sum and count of historical moves at a given slot across stored periods
slot_stats(array<PeriodMoves> arr, int s) =>
    float total = 0.0
    int cnt = 0
    for p in arr
        if s < p.v.size()
            total += p.v.get(s)
            cnt += 1
    [total, cnt]
 
// ── Period detection ────────────────────────────────────
// Anchor chosen by the user
string tf_manual = switch tf_choice
    "1-Hour"    => "60"
    "4-Hour"    => "240"
    "Daily"     => "D"
    "Weekly"    => "W"
    "Monthly"   => "M"
    "Quarterly" => "3M"
    "Yearly"    => "12M"
    => ""
 
// Anchor picked automatically from the chart timeframe (always one step above it)
int chart_secs = timeframe.in_seconds()
string tf_auto = chart_secs < 86400   ? "D"  :
                 chart_secs < 604800  ? "W"  :
                 chart_secs < 2592000 ? "M"  :
                 chart_secs < 7776000 ? "3M" : "12M"
 
bool manual_ok = tf_manual != "" and timeframe.in_seconds(tf_manual) > chart_secs
string tf_code = manual_ok ? tf_manual : tf_auto
 
// If even the Auto anchor is not above the chart timeframe (e.g. a 12-month chart), the indicator idles
bool active = timeframe.in_seconds(tf_code) > chart_secs
bool fell_back = tf_choice != "Auto" and not manual_ok
 
bool new_period = timeframe.change(tf_code)
 
// ── Per-period state ────────────────────────────────────
var array<PeriodMoves> hist = array.new<PeriodMoves>()
var PeriodMoves cur = PeriodMoves.new(array.new<float>())
 
var bool  synced = false   // true once the first full period has started (skips the partial first period)
var float p_open = na
var float ref_hi = na
var float ref_lo = na
var int   slot   = 0
 
if new_period
    p_open := open
    ref_hi := math.max(open, nz(close[1], open))
    ref_lo := math.min(open, nz(close[1], open))
    slot   := 0
    if bar_index > 0
        synced := true
else
    slot += 1
 
// Mutate collections only on confirmed bars so realtime ticks don't duplicate data
if barstate.isconfirmed and synced and active
    if new_period and cur.v.size() > 0
        hist.push(cur)
        while hist.size() > lookback
            hist.shift()
        cur := PeriodMoves.new(array.new<float>())
    if cur.v.size() < MAX_SLOTS
        cur.v.push(math.abs(close / p_open - 1.0))
 
// ── Thresholds ──────────────────────────────────────────
float upper = na
float lower = na
 
if active and synced and hist.size() >= lookback and slot > 0
    [tot, cnt] = slot_stats(hist, slot)
    if cnt > 0
        float avg_move = tot / cnt
        upper := ref_hi * (1 + width_mult * avg_move)
        lower := ref_lo * (1 - width_mult * avg_move)
 
pu = plot(upper, "Upper Threshold", color = edge_col, style = plot.style_linebr)
pl = plot(lower, "Lower Threshold", color = edge_col, style = plot.style_linebr)
fill(pu, pl, color = zone_col, title = "Normal Zone")
 
// ── Forward projection (drawn on the last bar) ──────────
var array<line> proj_lines = array.new<line>()
 
if barstate.islast
    for ln in proj_lines
        ln.delete()
    proj_lines.clear()
 
    if active and proj_bars > 0 and synced and hist.size() >= lookback
        float last_u = na(upper) ? p_open : upper
        float last_l = na(lower) ? p_open : lower
        for h = 1 to proj_bars
            [tot, cnt] = slot_stats(hist, slot + h)
            if cnt == 0
                break
            float avg_move = tot / cnt
            float nu = ref_hi * (1 + width_mult * avg_move)
            float nl = ref_lo * (1 - width_mult * avg_move)
            proj_lines.push(line.new(bar_index + h - 1, last_u, bar_index + h, nu, color = edge_col))
            proj_lines.push(line.new(bar_index + h - 1, last_l, bar_index + h, nl, color = edge_col))
            last_u := nu
            last_l := nl
 
// ── Anchored VWAP with deviation ────────────────────────
var float s_pv  = 0.0
var float s_v   = 0.0
var float s_p2v = 0.0
 
if new_period
    s_pv  := 0.0
    s_v   := 0.0
    s_p2v := 0.0
 
// Symbols without volume data (e.g. some indices) fall back to equal weighting
bool  no_vol = ta.cum(nz(volume)) == 0
float tp     = hlc3
float vol    = no_vol ? 1.0 : nz(volume)
s_pv  += tp * vol
s_v   += vol
s_p2v += tp * tp * vol
 
float vwap     = s_v > 0 ? s_pv / s_v : na
float vwap_var = s_v > 0 ? math.max(0.0, s_p2v / s_v - vwap * vwap) : 0.0
float vwap_sd  = math.sqrt(vwap_var)
 
bool vwap_on = active and show_vwap
plot(vwap_on ? vwap : na, "Anchored VWAP", color = vwap_col, linewidth = 2)
dv_u = plot(vwap_on and show_dev ? vwap + vwap_sd * dev_mult : na, "VWAP Upper Deviation", color = dev_col)
dv_l = plot(vwap_on and show_dev ? vwap - vwap_sd * dev_mult : na, "VWAP Lower Deviation", color = dev_col)
fill(dv_u, dv_l, color = vwap_on and show_dev ? dev_fill : na, title = "VWAP Deviation Fill")
 
// ── Regime signals: price discovery vs. mean reversion ──
// State machine with hysteresis:
//   Close beyond band + brk_buf          -> OUTSIDE (PD fires once per excursion)
//   Close back inside band - re_buf      -> counts toward re-entry (MR fires after hold_bars)
//   Anything in between (dead zone)      -> no state change, so edge-chop is ignored
//   Re-poke outside during re-entry      -> same excursion: no new PD, hold counter resets
float atr_v    = nz(ta.atr(atr_len))
float out_buf  = brk_buf * atr_v
float in_buf   = re_buf * atr_v
bool  has_band = not na(upper) and not na(lower)
 
bool above = has_band and close > upper + out_buf
bool below = has_band and close < lower - out_buf
 
var int out_dir  = 0   // +1 = outside above, -1 = outside below, 0 = none
var int out_bars = 0   // closes spent outside during this excursion
var int in_cnt   = 0   // consecutive closes back inside (re-entry hold counter)
 
var int last_pd_up = -100000
var int last_pd_dn = -100000
var int last_mr_lg = -100000
var int last_mr_sh = -100000
var int n_pd_up = 0
var int n_pd_dn = 0
var int n_mr_lg = 0
var int n_mr_sh = 0
 
if new_period
    out_dir  := 0      // bands reset each period, so reset the regime too
    out_bars := 0
    in_cnt   := 0
    n_pd_up  := 0
    n_pd_dn  := 0
    n_mr_lg  := 0
    n_mr_sh  := 0
 
bool pd_up_raw = false
bool pd_dn_raw = false
bool mr_lg_raw = false
bool mr_sh_raw = false
 
if above
    if out_dir != 1
        pd_up_raw := true
        out_bars  := 1
    else
        out_bars += 1
    out_dir := 1
    in_cnt  := 0
else if below
    if out_dir != -1
        pd_dn_raw := true
        out_bars  := 1
    else
        out_bars += 1
    out_dir := -1
    in_cnt  := 0
else if out_dir != 0
    bool back = has_band and ((out_dir == 1 and close <= upper - in_buf) or (out_dir == -1 and close >= lower + in_buf))
    if back
        in_cnt += 1
        if in_cnt >= hold_bars
            if out_bars >= min_out
                if out_dir == 1 and (not mr_vwap_filt or na(vwap) or close > vwap)
                    mr_sh_raw := true   // came back down from above -> short toward VWAP
                if out_dir == -1 and (not mr_vwap_filt or na(vwap) or close < vwap)
                    mr_lg_raw := true   // came back up from below -> long toward VWAP
            out_dir  := 0
            out_bars := 0
            in_cnt   := 0
    else
        in_cnt := 0   // not decisively back inside: restart the hold count
 
// Cooldown + per-period cap
bool pd_up = pd_up_raw and bar_index - last_pd_up > cooldown and (max_per_side == 0 or n_pd_up < max_per_side)
bool pd_dn = pd_dn_raw and bar_index - last_pd_dn > cooldown and (max_per_side == 0 or n_pd_dn < max_per_side)
bool mr_lg = mr_lg_raw and bar_index - last_mr_lg > cooldown and (max_per_side == 0 or n_mr_lg < max_per_side)
bool mr_sh = mr_sh_raw and bar_index - last_mr_sh > cooldown and (max_per_side == 0 or n_mr_sh < max_per_side)
 
if pd_up
    last_pd_up := bar_index
    n_pd_up += 1
if pd_dn
    last_pd_dn := bar_index
    n_pd_dn += 1
if mr_lg
    last_mr_lg := bar_index
    n_mr_lg += 1
if mr_sh
    last_mr_sh := bar_index
    n_mr_sh += 1
 
bool sig_ok = not confirm_bar or barstate.isconfirmed
 
bool s_pd_up = show_pd and sig_ok and pd_up
bool s_pd_dn = show_pd and sig_ok and pd_dn
bool s_mr_lg = show_mr and sig_ok and mr_lg
bool s_mr_sh = show_mr and sig_ok and mr_sh
 
// ── Markers ─────────────────────────────────────────────
// PD = triangles (direction of the breakout), MR = diamonds (snap-back entry).
// Two sets are plotted; the captioned set or the clean set is hidden depending on the toggle.
c_pd_up = color.new(pd_up_col, mk_transp)
c_pd_dn = color.new(pd_dn_col, mk_transp)
c_mr_lg = color.new(mr_lg_col, mk_transp)
c_mr_sh = color.new(mr_sh_col, mk_transp)
 
disp_txt   = show_txt ? display.all : display.none
disp_clean = show_txt ? display.none : display.all
 
// With captions
plotshape(s_pd_up, "PD Up (caption)",    shape.triangleup,   location.belowbar, c_pd_up, size = size.tiny, text = "PD", textcolor = c_pd_up, display = disp_txt)
plotshape(s_pd_dn, "PD Down (caption)",  shape.triangledown, location.abovebar, c_pd_dn, size = size.tiny, text = "PD", textcolor = c_pd_dn, display = disp_txt)
plotshape(s_mr_lg, "MR Long (caption)",  shape.diamond,      location.belowbar, c_mr_lg, size = size.tiny, text = "MR", textcolor = c_mr_lg, display = disp_txt)
plotshape(s_mr_sh, "MR Short (caption)", shape.diamond,      location.abovebar, c_mr_sh, size = size.tiny, text = "MR", textcolor = c_mr_sh, display = disp_txt)
 
// Clean (shapes only)
plotshape(s_pd_up, "PD Up",    shape.triangleup,   location.belowbar, c_pd_up, size = size.tiny, display = disp_clean)
plotshape(s_pd_dn, "PD Down",  shape.triangledown, location.abovebar, c_pd_dn, size = size.tiny, display = disp_clean)
plotshape(s_mr_lg, "MR Long",  shape.diamond,      location.belowbar, c_mr_lg, size = size.tiny, display = disp_clean)
plotshape(s_mr_sh, "MR Short", shape.diamond,      location.abovebar, c_mr_sh, size = size.tiny, display = disp_clean)
 
// Optional faint highlight on signal bars
bgcolor(sig_flash and s_pd_up ? color.new(pd_up_col, flash_transp) : na, title = "PD Up Flash")
bgcolor(sig_flash and s_pd_dn ? color.new(pd_dn_col, flash_transp) : na, title = "PD Down Flash")
bgcolor(sig_flash and s_mr_lg ? color.new(mr_lg_col, flash_transp) : na, title = "MR Long Flash")
bgcolor(sig_flash and s_mr_sh ? color.new(mr_sh_col, flash_transp) : na, title = "MR Short Flash")
 
barcolor(tint_bars and out_dir == 1 ? color.new(pd_up_col, 30) : tint_bars and out_dir == -1 ? color.new(pd_dn_col, 30) : na, title = "Outside-Band Tint")
 
// ── Status note (replaces the old hard error) ───────────
var table note = table.new(position.bottom_right, 1, 1)
if barstate.islast
    if not active
        table.cell(note, 0, 0, "NT: chart timeframe is too high for any anchor. Switch to a lower timeframe.", text_color = color.white, text_size = size.small, bgcolor = color.new(color.red, 30))
    else if fell_back
        table.cell(note, 0, 0, "NT: chosen anchor must be above the chart timeframe. Using " + tf_code + " instead.", text_color = color.white, text_size = size.small, bgcolor = color.new(color.orange, 30))
    else if hist.size() < lookback
        table.cell(note, 0, 0, "NT: collecting history (" + str.tostring(hist.size()) + "/" + str.tostring(lookback) + " periods). Load more bars or lower the lookback.", text_color = color.white, text_size = size.small, bgcolor = color.new(color.gray, 30))
 
// ── Alerts ──────────────────────────────────────────────
// Gated by sig_ok so alerts match the drawn markers and don't fire on unconfirmed ticks.
alertcondition(pd_up and sig_ok, "Price Discovery Up",   "{{ticker}}: price closed above the normality band (price discovery up).")
alertcondition(pd_dn and sig_ok, "Price Discovery Down", "{{ticker}}: price closed below the normality band (price discovery down).")
alertcondition(mr_lg and sig_ok, "Mean Reversion Long",  "{{ticker}}: price re-entered the band from below (mean-reversion long).")
alertcondition(mr_sh and sig_ok, "Mean Reversion Short", "{{ticker}}: price re-entered the band from above (mean-reversion short).")

← 返回列表