Tzotchev Trend [MiesOnCharts]

MiesOnCharts · study · 154 行 · 点赞 110 · 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/
// © MiesOnCharts
 
//   __  __ _
//  |  \/  (_) ___  ___
//  | |\/| | |/ _ \/ __|
//  | |  | | |  __/\__ \
//  |_|  |_|_|\___||___/
 
//@version=6
// ═══════════════════════════════════════════════════════════════════════════
//  TZOTCHEV TREND
//  The trend strength measure from Tzotchev's "Designing Robust Trend-Following
//  System", read over a few lookbacks and averaged into one line from -1 to +1.
//
//    t  = sqrt(T) * mean return / sd of returns
//    ST = 2 * N(t) - 1
//
//  T is the lookback in bars. The mean and the sd both come from the log returns
//  inside that lookback, and N is the normal curve's cumulative probability. So
//  t is the t statistic of the lookback's average return: how many standard
//  errors the drift sits from zero. N turns that into the odds the drift is above
//  zero, and the doubling and shifting moves those odds onto a -1 to +1 scale.
//
// ═══════════════════════════════════════════════════════════════════════════
indicator("Tzotchev Trend [MiesOnCharts]", shorttitle = "TZT - Mies", overlay = false, precision = 2, max_bars_back = 600)
 
grpM = "Model"
grpS = "States"
grpD = "Display"
 
src  = input.source(ohlc4, "Source", group = grpM, display = display.none)
lenM = input.int(30, "Main Lookback", minval = 5, maxval = 500, group = grpM, display = display.none,
     tooltip = "Bars this reading is measured over, counted on the chart's own timeframe.")
useF = input.bool(true, "Fast Lookback", inline = "f", group = grpM, display = display.none)
lenF = input.int(20, "", minval = 5, maxval = 500, inline = "f", group = grpM, display = display.none,
     tooltip = "A shorter reading in the average. It turns first and is noisier, since fewer returns stand behind it.")
useS = input.bool(true, "Slow Lookback", inline = "s", group = grpM, display = display.none)
lenS = input.int(60, "", minval = 5, maxval = 500, inline = "s", group = grpM, display = display.none,
     tooltip = "A longer reading in the average. It keeps the line anchored to the larger trend and delays flips.")
 
longThr  = input.float(0.2,  "Long Above",  step = 0.05, group = grpS, display = display.none,
     tooltip = "The line has to close above this to turn the state long.")
shortThr = input.float(-0.2, "Short Below", step = 0.05, group = grpS, display = display.none,
     tooltip = "The line has to close below this to turn the state short.")
 
paintBar = input.bool(true, "Paint Candles", group = grpD, display = display.none)
showTbl  = input.bool(true, "Readout", group = grpD, display = display.none,
     tooltip = "Each lookback's own reading next to the average, so you can see which horizons agree.")
colUp    = input.color(color.rgb(0, 255, 21),    "Long",    inline = "c", group = grpD)
colDn    = input.color(color.rgb(255, 0, 0),     "Short",   inline = "c", group = grpD)
colFlat  = input.color(color.rgb(120, 123, 134), "Neutral", inline = "c", group = grpD)
 
// ── Measure ───────────────────────────────────────────────────────────────
// Normal cumulative probability. Pine has no built in, so this is the rational
// approximation from Abramowitz and Stegun (26.2.17), good to about 1e-7.
f_phi(float z) =>
    float a    = math.abs(z)
    float k    = 1.0 / (1.0 + 0.2316419 * a)
    float pdf  = math.exp(-0.5 * a * a) / math.sqrt(2.0 * math.pi)
    float tail = pdf * k * (0.319381530 + k * (-0.356563782 + k * (1.781477937 + k * (-1.821255978 + k * 1.330274429))))
    z >= 0 ? 1.0 - tail : tail
 
// The mean and the sample sd cover exactly the same bars: the t returns that end
// on this bar are the ones that sum to the log change over the lookback.
f_strength(float s, int t) =>
    float lnP  = math.log(s)
    float r1   = lnP - lnP[1]
    float sd   = ta.stdev(r1, t, false)
    float rBar = (lnP - lnP[t]) / t
    float tVal = sd > 0 ? math.sqrt(t) * rBar / sd : na
    2.0 * f_phi(tVal) - 1.0
 
// All three run on every bar so their history stays intact when a toggle changes.
float stM = f_strength(src, lenM)
float stF = f_strength(src, lenF)
float stS = f_strength(src, lenS)
 
// A lookback that is on and still warming up leaves the line blank, so the line
// always means the same mix of horizons.
int   nOn   = 1 + (useF ? 1 : 0) + (useS ? 1 : 0)
float score = (stM + (useF ? stF : 0.0) + (useS ? stS : 0.0)) / nOn
 
// ── State ─────────────────────────────────────────────────────────────────
// The line reads the live bar as a measurement should. The state that paints
// and alerts only moves on a closed bar, and between the two levels it holds.
var int state = 0
if barstate.isconfirmed and not na(score)
    if score > longThr
        state := 1
    else if score < shortThr
        state := -1
 
bool  flipUp = state ==  1 and state[1] !=  1
bool  flipDn = state == -1 and state[1] != -1
color stCol  = state == 1 ? colUp : state == -1 ? colDn : colFlat
 
// ── Render ────────────────────────────────────────────────────────────────
pS = plot(score, "Trend", color = stCol, linewidth = 2)
pZ = plot(0.0, "", color = na, editable = false, display = display.none)
fill(pS, pZ, color = color.new(stCol, 86), title = "Trend Fill", editable = false)
 
hline( 0,       "Zero",        color = color.new(colFlat, 40))
hline(longThr,  "Long Level",  color = color.new(colUp, 60), linestyle = hline.style_dotted)
hline(shortThr, "Short Level", color = color.new(colDn, 60), linestyle = hline.style_dotted)
hline( 0.5,     "+0.5",        color = color.new(colFlat, 75), linestyle = hline.style_dashed)
hline(-0.5,     "-0.5",        color = color.new(colFlat, 75), linestyle = hline.style_dashed)
hline( 1,       "+1",          color = color.new(colFlat, 60), linestyle = hline.style_dashed)
hline(-1,       "-1",          color = color.new(colFlat, 60), linestyle = hline.style_dashed)
 
plotshape(flipUp ? score : na, "Long",  shape.triangleup,   location.absolute, colUp, size = size.tiny)
plotshape(flipDn ? score : na, "Short", shape.triangledown, location.absolute, colDn, size = size.tiny)
 
// Redrawn as candles so the body fills on any candle style. force_overlay
// because this is a pane and the bars live on price.
plotcandle(paintBar and state != 0 ? open  : na,
           paintBar and state != 0 ? high  : na,
           paintBar and state != 0 ? low   : na,
           paintBar and state != 0 ? close : na,
     title = "Trend Candles", color = stCol, wickcolor = stCol, bordercolor = stCol,
     display = display.all - display.status_line, force_overlay = true, editable = false)
 
plot(useF ? stF : na, "Fast Reading", color = color.blue, display = display.data_window)
plot(stM,             "Main Reading", color = color.blue, display = display.data_window)
plot(useS ? stS : na, "Slow Reading", color = color.blue, display = display.data_window)
plot(state,           "State",        color = color.blue, display = display.data_window)
 
// ── Readout ───────────────────────────────────────────────────────────────
f_fmt(float v) =>
    (v >= 0 ? "+" : "") + str.tostring(v, "0.00")
 
f_col(float v) =>
    v > longThr ? colUp : v < shortThr ? colDn : colFlat
 
f_row(table t, int r, string name, string val, color c) =>
    table.cell(t, 0, r, name, text_color = chart.fg_color, text_size = size.small, text_halign = text.align_left)
    table.cell(t, 1, r, val, text_color = c, text_size = size.small)
 
var table tbl = table.new(position.top_right, 2, 5, border_width = 1)
if barstate.islast and showTbl and not na(score)
    int r = 0
    if useF
        f_row(tbl, r, str.tostring(lenF) + " bar", f_fmt(stF), f_col(stF))
        r += 1
    f_row(tbl, r, str.tostring(lenM) + " bar", f_fmt(stM), f_col(stM))
    r += 1
    if useS
        f_row(tbl, r, str.tostring(lenS) + " bar", f_fmt(stS), f_col(stS))
        r += 1
    f_row(tbl, r, "Trend", f_fmt(score), stCol)
    f_row(tbl, r + 1, "State", state == 1 ? "LONG" : state == -1 ? "SHORT" : "NEUTRAL", stCol)
 
alertcondition(flipUp, "Tzotchev Trend Long",  "Tzotchev trend turned long on the close")
alertcondition(flipDn, "Tzotchev Trend Short", "Tzotchev trend turned short on the close")

← 返回列表