Gold Move Size Gauge

deltaterminal · study · 291 行 · 点赞 9 · TradingView 原页

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

Pine Script

//@version=6
// =============================================================================
// Gold Move Size Gauge
// -----------------------------------------------------------------------------
// Measures how far price has travelled over a session window (by default the
// 01:00-14:30 Paris morning on gold), in units of the daily ATR, and tabulates
// on the chart's loaded history how often a move of that size was given back
// before the end of the day.
//
// - Start price  = close of the last bar before the window.
// - Checkpoint   = close of the last bar of the window.
// - "Back to start" = at least one bar CLOSES back through the start price
//   during the follow-up window (close-based, confirmed bars: no repaint).
// - Every rate is shown with its sample size and a Wilson 95% margin.
// - The numbers describe the loaded history of THIS chart. They are base rates,
//   not signals and not a forecast.
// =============================================================================
indicator("Gold Move Size Gauge", shorttitle = "Move Size", overlay = true, max_labels_count = 200)
 
// ─── Inputs ──────────────────────────────────────────────────────────────────
string GRP_W = "Windows"
string GRP_S = "Statistics"
string GRP_V = "Display"
 
string moveSess   = input.session("0100-1430", "Move window", group = GRP_W, tooltip = "The move is measured from the close of the last bar before this window to the close of the last bar inside it. Default: the gold morning, 01:00 to 14:30 Paris time, which ends just before the usual US data releases. Use a chart timeframe of 30 minutes or less.")
string followSess = input.session("1430-2300", "Follow-up window", group = GRP_W, tooltip = "Period during which a close back through the start price counts as 'back to start'. It should begin where the move window ends.")
string tz         = input.string("Europe/Paris", "Timezone", options = ["Europe/Paris", "Europe/London", "America/New_York", "America/Chicago", "Asia/Tokyo", "Asia/Singapore", "Australia/Sydney", "UTC"], group = GRP_W, tooltip = "Both windows follow daylight saving time in this timezone.")
 
int   atrLen     = input.int(14, "Daily ATR length", minval = 5, maxval = 50, group = GRP_S, tooltip = "Wilder ATR of completed daily bars. The value known at the start of the window is used for the whole day, so the size never looks ahead.")
float minMovePct = input.float(0.10, "Minimum move (%)", minval = 0.0, step = 0.05, group = GRP_S, tooltip = "Days on which the move is smaller than this percentage of price are counted as quiet and left out of the size classes.")
float thr1       = input.float(0.15, "Size class 1 upper bound (ATR)", minval = 0.01, step = 0.05, group = GRP_S)
float thr2       = input.float(0.30, "Size class 2 upper bound (ATR)", minval = 0.02, step = 0.05, group = GRP_S)
float thr3       = input.float(0.55, "Size class 3 upper bound (ATR)", minval = 0.03, step = 0.05, group = GRP_S)
 
bool   showOrigin = input.bool(true, "Draw start price", group = GRP_V)
bool   showZones  = input.bool(true, "Draw size zones", group = GRP_V)
bool   showMarks  = input.bool(true, "Mark checkpoint and back-to-start", group = GRP_V)
bool   showDash   = input.bool(true, "Show dashboard", group = GRP_V)
string dashPos    = input.string("Top right", "Dashboard position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = GRP_V)
string dashSize   = input.string("Normal", "Dashboard text size", options = ["Small", "Normal", "Large"], group = GRP_V)
 
// ─── Constants ───────────────────────────────────────────────────────────────
color C_BULL = #26A69A
color C_BEAR = #EF5350
color C_WARN = #FFA726
color C_NEUT = #787B86
color C_TEXT = #FFFFFF
color C_LBL  = #B2B5BE
color C_HEAD = #2962FF
color C_BG   = #131722
color C_CHIP = #2A2E39
int   MIN_N  = 25
 
// ─── Helpers ─────────────────────────────────────────────────────────────────
f_pos(string _p) =>
    _p == "Top right" ? position.top_right : _p == "Bottom right" ? position.bottom_right : _p == "Top left" ? position.top_left : position.bottom_left
 
f_size(string _s) =>
    _s == "Small" ? size.small : _s == "Large" ? size.large : size.normal
 
// Wilson 95% score interval: returns [centre, half-width] as fractions.
f_wilson(int _k, int _n) =>
    float ctr  = na
    float half = na
    if _n > 0
        float z   = 1.96
        float p   = _k / float(_n)
        float den = 1.0 + z * z / _n
        ctr  := (p + z * z / (2.0 * _n)) / den
        half := z * math.sqrt(p * (1.0 - p) / _n + z * z / (4.0 * _n * _n)) / den
    [ctr, half]
 
f_rate(int _k, int _n) =>
    [ctr, half] = f_wilson(_k, _n)
    string s = _n > 0 ? str.tostring(100.0 * _k / _n, "0") + "% ±" + str.tostring(100.0 * half, "0") : "-"
    bool above = _n > 0 and ctr - half > 0.5
    bool below = _n > 0 and ctr + half < 0.5
    [s, above, below]
 
f_bin(float _s) =>
    int b = _s <= thr1 ? 0 : _s <= thr2 ? 1 : _s <= thr3 ? 2 : 3
    b
 
f_binName(int _b) =>
    string s = _b == 0 ? "≤ " + str.tostring(thr1, "0.00") + " ATR" : _b == 1 ? str.tostring(thr1, "0.00") + " – " + str.tostring(thr2, "0.00") : _b == 2 ? str.tostring(thr2, "0.00") + " – " + str.tostring(thr3, "0.00") : "> " + str.tostring(thr3, "0.00") + " ATR"
    s
 
f_sessLabel(string _s) =>
    string out = str.length(_s) >= 9 ? str.substring(_s, 0, 2) + ":" + str.substring(_s, 2, 4) + "-" + str.substring(_s, 5, 7) + ":" + str.substring(_s, 7, 9) : _s
    out
 
// ─── Windows ─────────────────────────────────────────────────────────────────
bool tfOk      = timeframe.isintraday and timeframe.in_seconds() <= 1800
bool inMove    = tfOk and not na(time(timeframe.period, moveSess, tz))
bool inFollow  = tfOk and not na(time(timeframe.period, followSess, tz))
bool moveStart = inMove and not inMove[1]
bool moveEnd   = not inMove and inMove[1]
bool followEnd = not inFollow and inFollow[1]
 
// ─── Daily ATR from completed daily bars (Wilder), no external request ───────
var float dayHi   = na
var float dayLo   = na
var float prevCls = na
var float atrD    = na
var float trSum   = 0.0
var int   nTr     = 0
var bool  dayFull = false
 
if timeframe.change("D")
    if dayFull and not na(dayHi)
        float tr = na(prevCls) ? dayHi - dayLo : math.max(dayHi - dayLo, math.abs(dayHi - prevCls), math.abs(dayLo - prevCls))
        nTr += 1
        if nTr <= atrLen
            trSum += tr
            atrD  := trSum / nTr
        else
            atrD := (atrD * (atrLen - 1) + tr) / atrLen
    if bar_index > 0
        prevCls := close[1]
        dayFull := true
    dayHi := high
    dayLo := low
else
    dayHi := na(dayHi) ? high : math.max(dayHi, high)
    dayLo := na(dayLo) ? low : math.min(dayLo, low)
 
bool atrReady = nTr >= math.min(atrLen, 5) and not na(atrD) and atrD > 0
 
// ─── State of the current day ────────────────────────────────────────────────
var float origin     = na
var float atrRef     = na
var float cpPrice    = na
var float sizeAtr    = na
var int   moveDir    = 0
var int   binIdx     = -1
var bool  locked     = false
var bool  counted    = false
var bool  returned   = false
var bool  booksDone  = true
var int   followBars = 0
 
// ─── Tallies over the loaded history ─────────────────────────────────────────
var array<int> nBin = array.new<int>(4, 0)
var array<int> kBin = array.new<int>(4, 0)
var int nAll   = 0
var int kAll   = 0
var int nQuiet = 0
 
// ─── Events of the current bar ───────────────────────────────────────────────
bool evLock        = false
bool evBackAfterUp = false
bool evBackAfterDn = false
 
// 1) Close the books on the previous measured day.
if locked and not booksDone and (followEnd or moveStart)
    if followBars > 0
        if counted and binIdx >= 0
            array.set(nBin, binIdx, array.get(nBin, binIdx) + 1)
            nAll += 1
            if returned
                array.set(kBin, binIdx, array.get(kBin, binIdx) + 1)
                kAll += 1
        else
            nQuiet += 1
    booksDone := true
 
// 2) A new window starts: set the start price and freeze the ATR.
if moveStart
    bool gap = bar_index == 0 or (time - time[1]) > 3 * timeframe.in_seconds() * 1000
    origin     := gap ? open : close[1]
    atrRef     := atrReady ? atrD : na
    cpPrice    := na
    sizeAtr    := na
    moveDir    := 0
    binIdx     := -1
    locked     := false
    counted    := false
    returned   := false
    booksDone  := false
    followBars := 0
 
// 3) First bar after the window: lock the size at the checkpoint.
if moveEnd and not locked and not booksDone and not na(origin)
    cpPrice := close[1]
    float mv = cpPrice - origin
    moveDir := mv > 0 ? 1 : mv < 0 ? -1 : 0
    sizeAtr := not na(atrRef) and atrRef > 0 ? math.abs(mv) / atrRef : na
    float mvPct = origin > 0 ? 100.0 * math.abs(mv) / origin : 0.0
    counted := not na(sizeAtr) and moveDir != 0 and mvPct >= minMovePct
    binIdx  := na(sizeAtr) ? -1 : f_bin(sizeAtr)
    locked  := true
    evLock  := true
    if showMarks and not na(sizeAtr)
        string lblTxt = str.tostring(sizeAtr, "0.00") + " ATR"
        if moveDir >= 0
            label.new(bar_index - 1, high[1], lblTxt, style = label.style_label_down, color = color.new(C_HEAD, 10), textcolor = C_TEXT, size = size.small)
        else
            label.new(bar_index - 1, low[1], lblTxt, style = label.style_label_up, color = color.new(C_HEAD, 10), textcolor = C_TEXT, size = size.small)
 
// 4) Follow-up: a confirmed close back through the start price.
if locked and not booksDone and inFollow and barstate.isconfirmed
    followBars += 1
    if not returned and moveDir != 0
        bool back = moveDir == 1 ? close < origin : close > origin
        if back
            returned := true
            if moveDir == 1
                evBackAfterUp := true
            else
                evBackAfterDn := true
 
// ─── Live reading ────────────────────────────────────────────────────────────
bool  dayOn    = not na(origin) and not booksDone and (inMove or inFollow)
float liveSize = dayOn and not na(atrRef) and atrRef > 0 ? math.abs(close - origin) / atrRef : na
float nowSize  = locked ? sizeAtr : liveSize
int   nowDir   = locked ? moveDir : (not na(origin) and close > origin ? 1 : not na(origin) and close < origin ? -1 : 0)
int   nowBin   = na(nowSize) ? -1 : f_bin(nowSize)
bool  haveDay  = not na(origin)
bool  xBig     = ta.crossover(liveSize, thr3)
bool  evBig    = inMove and xBig
 
// ─── Chart drawings ──────────────────────────────────────────────────────────
float oLine = showOrigin and dayOn ? origin : na
float zAtr  = showZones and dayOn and not na(atrRef) ? atrRef : na
 
plot(oLine, "Start price", color = C_HEAD, style = plot.style_linebr, linewidth = 2)
p1u = plot(origin + thr1 * zAtr, "Zone 1 upper", color = color.new(C_WARN, 45), style = plot.style_linebr, display = display.pane)
p1d = plot(origin - thr1 * zAtr, "Zone 1 lower", color = color.new(C_WARN, 45), style = plot.style_linebr, display = display.pane)
p2u = plot(origin + thr2 * zAtr, "Zone 2 upper", color = color.new(C_LBL, 55), style = plot.style_linebr, display = display.pane)
p2d = plot(origin - thr2 * zAtr, "Zone 2 lower", color = color.new(C_LBL, 55), style = plot.style_linebr, display = display.pane)
p3u = plot(origin + thr3 * zAtr, "Zone 3 upper", color = color.new(C_HEAD, 35), style = plot.style_linebr, display = display.pane)
p3d = plot(origin - thr3 * zAtr, "Zone 3 lower", color = color.new(C_HEAD, 35), style = plot.style_linebr, display = display.pane)
fill(p1u, p1d, color = color.new(C_WARN, 90), title = "Zone 1 fill")
fill(p2u, p1u, color = color.new(C_LBL, 94), title = "Zone 2 upper fill")
fill(p1d, p2d, color = color.new(C_LBL, 94), title = "Zone 2 lower fill")
fill(p3u, p2u, color = color.new(C_HEAD, 94), title = "Zone 3 upper fill")
fill(p2d, p3d, color = color.new(C_HEAD, 94), title = "Zone 3 lower fill")
 
plotshape(showMarks and evBackAfterUp, "Up move back to start", style = shape.xcross, location = location.belowbar, color = C_WARN, size = size.tiny)
plotshape(showMarks and evBackAfterDn, "Down move back to start", style = shape.xcross, location = location.abovebar, color = C_WARN, size = size.tiny)
 
// ─── Dashboard ───────────────────────────────────────────────────────────────
var table dash = table.new(f_pos(dashPos), 3, 9, bgcolor = C_BG, border_width = 1, border_color = C_CHIP, frame_width = 2, frame_color = C_HEAD)
 
f_row(table _t, int _r, string _name, string _val, color _valCol, string _chip, color _chipBg, string _tip) =>
    table.cell(_t, 0, _r, _name, text_color = C_LBL, bgcolor = C_BG, text_size = f_size(dashSize), text_halign = text.align_left, tooltip = _tip)
    table.cell(_t, 1, _r, _val, text_color = _valCol, bgcolor = C_BG, text_size = f_size(dashSize), text_halign = text.align_right, tooltip = _tip)
    table.cell(_t, 2, _r, _chip, text_color = C_TEXT, bgcolor = _chipBg, text_size = f_size(dashSize), text_halign = text.align_center, tooltip = _tip)
 
if showDash and barstate.islast
    table.cell(dash, 0, 0, "MOVE SIZE", text_color = C_TEXT, bgcolor = C_HEAD, text_size = f_size(dashSize), text_halign = text.align_left)
    table.cell(dash, 1, 0, "back to start", text_color = C_TEXT, bgcolor = C_HEAD, text_size = f_size(dashSize), text_halign = text.align_right, tooltip = "Share of days on which a bar closed back through the start price during the follow-up window, with the Wilson 95% margin. Closes are read on the bars of this chart, so the rates depend on the timeframe.")
    table.cell(dash, 2, 0, str.tostring(nAll) + " days", text_color = C_TEXT, bgcolor = C_HEAD, text_size = f_size(dashSize), text_halign = text.align_center, tooltip = "Days measured in the loaded history of this chart (move window " + f_sessLabel(moveSess) + ", follow-up " + f_sessLabel(followSess) + ", " + tz + "). Quiet days left out: " + str.tostring(nQuiet) + ".")
    if not tfOk
        f_row(dash, 1, "Use 30 min or less", "", C_WARN, "", C_BG, "The windows are defined in hours and minutes: use an intraday timeframe of 30 minutes or less.")
    else if nAll == 0
        f_row(dash, 1, "No measured day yet", "", C_WARN, "", C_BG, "No complete day in the loaded history. Check the windows and the timezone, or load more bars.")
    else
        string tipLow = " Fewer than " + str.tostring(MIN_N) + " days: indicative only."
        for b = 0 to 3
            int n = array.get(nBin, b)
            int k = array.get(kBin, b)
            [sR, rAbove, rBelow] = f_rate(k, n)
            bool  lowN = n < MIN_N
            color vCol = lowN ? C_LBL : rAbove ? C_WARN : rBelow ? C_BULL : C_TEXT
            color cBg  = b == nowBin and haveDay ? C_HEAD : C_CHIP
            string tip = "Days whose move at the checkpoint was in this size class: " + str.tostring(n) + ". Given back (a close through the start price before the end of the follow-up window): " + str.tostring(k) + "." + (lowN ? tipLow : "") + " Orange = the 95% interval is above 50%, green = below 50%."
            f_row(dash, b + 1, f_binName(b), sR, vCol, "n " + str.tostring(n), cBg, tip)
        [sAll, aAbove, aBelow] = f_rate(kAll, nAll)
        f_row(dash, 5, "All sizes", sAll, C_TEXT, "n " + str.tostring(nAll), C_CHIP, "Base rate over every measured day, whatever the size. Read each size class against this line.")
        string arrow  = nowDir == 1 ? " ▲" : nowDir == -1 ? " ▼" : ""
        string sNow   = na(nowSize) ? "-" : str.tostring(nowSize, "0.00") + " ATR" + arrow
        color  nowCol = nowDir == 1 ? C_BULL : nowDir == -1 ? C_BEAR : C_TEXT
        string nowLbl = locked ? "Checkpoint" : "Now"
        string nowChp = nowBin >= 0 and haveDay ? "class " + str.tostring(nowBin + 1) : ""
        f_row(dash, 6, nowLbl, haveDay ? sNow : "-", nowCol, nowChp, nowBin >= 0 and haveDay ? C_HEAD : C_BG, "Distance from the start price in daily ATR. 'Now' moves with price until the end of the move window, then the size is locked at the checkpoint.")
        string st  = not haveDay ? "Waiting for window" : na(atrRef) ? "ATR warming up" : not locked ? "Window open" : not counted ? "Quiet day" : returned ? "Back to start" : booksDone ? "Held to the end" : "Not back yet"
        color stBg = not haveDay or na(atrRef) or not locked or not counted ? C_NEUT : returned ? C_WARN : C_BULL
        table.cell(dash, 0, 7, "Today", text_color = C_LBL, bgcolor = C_BG, text_size = f_size(dashSize), text_halign = text.align_left)
        table.cell(dash, 1, 7, st, text_color = C_TEXT, bgcolor = stBg, text_size = f_size(dashSize), text_halign = text.align_center, tooltip = "State of the current day. Descriptive only.")
        table.merge_cells(dash, 1, 7, 2, 7)
 
// ─── Alerts (single-bar events, confirmed bars) ──────────────────────────────
alertcondition(evLock, "Move size locked", "Move Size: the size of the move is locked at the checkpoint on {{ticker}}")
alertcondition(evBackAfterUp or evBackAfterDn, "Back to start", "Move Size: price closed back through the start price on {{ticker}}")
alertcondition(evBig, "Move enters the largest size class", "Move Size: the move entered the largest size class on {{ticker}}")
 
// =============================================================================
// No indicator is infallible. Nothing here is financial advice — every trading
// decision is your own.
// =============================================================================

← 返回列表