Gap-Body Cancellation Audit

ZILLIONAIRE010 · study · 158 行 · 点赞 1 · TradingView 原页

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

Pine Script

//@version=6
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Independently implemented for ZILLIONAIRE010.
indicator("Gap-Body Cancellation Audit", shorttitle = "Gap-Body Audit", overlay = false, precision = 2, max_bars_back = 1001)
 
// An endpoint decomposition, not the price path inside a candle:
// gap = ln(open / close[1]); body = ln(close / open).
// gross = abs(gap) + abs(body).
// cancelled = 2 * min(abs(gap), abs(body)) if the signs oppose, else zero.
// Mathematically: gross = abs(ln(close / close[1])) + cancelled.
// Window sums are over exactly N consecutive chart bar pairs, never N valid samples.
 
int window = input.int(100, "Window (consecutive bar pairs)", minval = 1, maxval = 1000, tooltip = "N pairs require N+1 chart bars. Every pair needs a positive prior close, open and close. An invalid pair invalidates the entire exact window; older valid observations are not substituted.")
bool showGapShare = input.bool(true, "Plot gap share of gross", tooltip = "Absolute gap magnitude divided by absolute gap + body magnitude. It shares its denominator with cancellation; the two plots are related diagnostics, not independent signals.")
bool showTable = input.bool(true, "Show last confirmed audit")
string corner = input.string("Top right", "Table corner", options = ["Top right", "Top left", "Bottom right", "Bottom left"])
 
// Pine comparison operators round floats to nine fractional digits. Comparing
// math.sign() outputs, rather than raw small prices/returns against zero, avoids
// silently discarding small positive prices and small opposing components.
f_positive(float x) =>
    not na(x) and math.sign(x) == 1.0
 
// Stable ln(x/y) for positive prices. The normalized atanh expansion avoids
// cancellation near equal prices; the log difference avoids ratio overflow for
// widely separated prices. At |z| < 0.05, omitted terms are below 1.9e-18.
f_logRatio(float x, float y) =>
    float scale = math.max(x, y)
    float z = ((x - y) / scale) / (x / scale + y / scale)
    float z2 = z * z
    math.abs(z) < 0.05 ? 2.0 * z * (1.0 + z2 * (1.0 / 3.0 + z2 * (1.0 / 5.0 + z2 * (1.0 / 7.0 + z2 * (1.0 / 9.0 + z2 / 11.0))))) : math.log(x) - math.log(y)
 
f_pct(float x) =>
    na(x) ? "n/a" : str.tostring(x, "0.00") + "%"
 
f_num(float x) =>
    na(x) ? "n/a" : math.sign(x) == 1.0 and x < 0.0001 ? "<0.0001" : str.tostring(x, "0.0000")
 
f_cell(table id, int col, int row, string txt, color fg, color bg) =>
    table.cell(id, col, row, txt, text_color = fg, bgcolor = bg, text_size = size.small)
 
// isintraday includes ticks, so use the explicit time-unit whitelist.
bool timeChart = timeframe.isseconds or timeframe.isminutes or timeframe.isdwm
if barstate.isfirst and (not chart.is_standard or not timeChart)
    runtime.error("Use a standard time-based chart (seconds, minutes, days, weeks or months). Synthetic, range and tick charts are not supported.")
 
bool pricesValid = f_positive(close[1]) and f_positive(open) and f_positive(close)
float gap = pricesValid ? f_logRatio(open, close[1]) : na
float body = pricesValid ? f_logRatio(close, open) : na
float closeReturn = pricesValid ? f_logRatio(close, close[1]) : na
// This bound also rejects non-finite arithmetic results; finite positive binary64
// price endpoints cannot have an absolute log ratio of 1500 or more.
bool pairValid = pricesValid and not na(gap) and not na(body) and not na(closeReturn) and math.abs(gap) < 1500.0 and math.abs(body) < 1500.0 and math.abs(closeReturn) < 1500.0
float gapAbs = pairValid ? math.abs(gap) : 0.0
float bodyAbs = pairValid ? math.abs(body) : 0.0
float retainedAbs = pairValid ? math.abs(closeReturn) : 0.0
bool opposed = pairValid and math.sign(gap) * math.sign(body) == -1.0
float cancelled = opposed ? 2.0 * math.min(gapAbs, bodyAbs) : 0.0
 
// Always execute rolling functions. Zero placeholders prevent math.sum from
// skipping invalid observations. A separate validity count forbids using them.
int countLength = math.min(window, bar_index + 1)
float validCount = math.sum(pairValid ? 1.0 : 0.0, countLength)
float sumGap = math.sum(gapAbs, window)
float sumBody = math.sum(bodyAbs, window)
float sumRetained = math.sum(retainedAbs, window)
float sumCancelled = math.sum(cancelled, window)
float gross = sumGap + sumBody
bool fullWindow = bar_index >= window
bool windowValid = fullWindow and validCount == window
bool hasMagnitude = windowValid and math.sign(gross) == 1.0
float cancelShare = hasMagnitude ? math.max(0.0, math.min(100.0, 100.0 * sumCancelled / gross)) : na
float gapShare = hasMagnitude ? math.max(0.0, math.min(100.0, 100.0 * sumGap / gross)) : na
float unitScale = 10000.0 / window
 
// Plots and Data Window values exclude the forming bar. The table persists only
// the last confirmed snapshot; even invalid confirmed windows replace old data.
bool emit = barstate.isconfirmed and windowValid
plot(emit ? cancelShare : na, "Within-pair cancellation (% of gross)", color = color.rgb(153, 102, 255), linewidth = 2, style = plot.style_linebr)
plot(emit and showGapShare ? gapShare : na, "Gap absolute share (% of gross)", color = color.orange, linewidth = 1, style = plot.style_linebr)
hline(0.0, "0%", color = color.new(color.gray, 60))
hline(100.0, "100%", color = color.new(color.gray, 60))
plot(emit ? gross * unitScale : na, "Mean gross component magnitude (log bp/pair)", display = display.data_window)
plot(emit ? sumGap * unitScale : na, "Mean absolute gap (log bp/pair)", display = display.data_window)
plot(emit ? sumBody * unitScale : na, "Mean absolute body (log bp/pair)", display = display.data_window)
plot(emit ? sumCancelled * unitScale : na, "Mean cancelled component magnitude (log bp/pair)", display = display.data_window)
plot(emit ? sumRetained * unitScale : na, "Mean absolute close-to-close return (log bp/pair)", display = display.data_window)
plot(emit ? (gross - sumCancelled - sumRetained) * unitScale : na, "Numerical accounting residual (log bp/pair)", display = display.data_window)
plot(barstate.isconfirmed ? validCount : na, "Valid pairs in available window", display = display.data_window)
plot(barstate.isconfirmed ? (windowValid ? 1 : 0) : na, "Exact window valid (1/0)", display = display.data_window)
 
var int savedAvailable = 0
var int savedValid = 0
var int savedEnd = na
var bool savedFull = false
var bool savedReady = false
var bool savedNonzero = false
var float savedCancelShare = na
var float savedGapShare = na
var float savedGross = na
var float savedGap = na
var float savedBody = na
var float savedCancel = na
var float savedRetained = na
if barstate.isconfirmed
    savedAvailable := math.min(window, bar_index)
    savedValid := int(validCount)
    savedEnd := time_close
    savedFull := fullWindow
    savedReady := windowValid
    savedNonzero := hasMagnitude
    savedCancelShare := cancelShare
    savedGapShare := gapShare
    savedGross := windowValid ? gross * unitScale : na
    savedGap := windowValid ? sumGap * unitScale : na
    savedBody := windowValid ? sumBody * unitScale : na
    savedCancel := windowValid ? sumCancelled * unitScale : na
    savedRetained := windowValid ? sumRetained * unitScale : na
 
string tablePosition = switch corner
    "Top left" => position.top_left
    "Bottom right" => position.bottom_right
    "Bottom left" => position.bottom_left
    => position.top_right
var table audit = table.new(tablePosition, 2, 13, border_width = 1, border_color = color.new(color.gray, 70))
if barstate.isfirst
    table.merge_cells(audit, 0, 0, 1, 0)
    table.merge_cells(audit, 0, 1, 1, 1)
    table.merge_cells(audit, 0, 10, 1, 10)
    table.merge_cells(audit, 0, 11, 1, 11)
    table.merge_cells(audit, 0, 12, 1, 12)
if barstate.islast and showTable
    color fg = chart.fg_color
    color bg = color.new(chart.bg_color, 5)
    color head = color.new(color.purple, 80)
    string status = not savedFull ? "Warmup: " + str.tostring(savedAvailable) + "/" + str.tostring(window) + " pairs" : not savedReady ? "Invalid pair data: " + str.tostring(savedValid) + "/" + str.tostring(window) + " valid pairs" : not savedNonzero ? "All endpoints flat: shares undefined" : "Exact " + str.tostring(window) + "-pair window"
    f_cell(audit, 0, 0, "Gap-Body Cancellation Audit", fg, head)
    f_cell(audit, 0, 1, status, fg, bg)
    f_cell(audit, 0, 2, "Cancelled / gross", fg, bg)
    f_cell(audit, 1, 2, f_pct(savedCancelShare), color.rgb(153, 102, 255), bg)
    f_cell(audit, 0, 3, "Absolute gap / gross", fg, bg)
    f_cell(audit, 1, 3, f_pct(savedGapShare), color.orange, bg)
    f_cell(audit, 0, 4, "Mean magnitudes", fg, head)
    f_cell(audit, 1, 4, "log bp / pair", fg, head)
    f_cell(audit, 0, 5, "Gap + body (gross)", fg, bg)
    f_cell(audit, 1, 5, f_num(savedGross), fg, bg)
    f_cell(audit, 0, 6, "Absolute gap", fg, bg)
    f_cell(audit, 1, 6, f_num(savedGap), fg, bg)
    f_cell(audit, 0, 7, "Absolute body", fg, bg)
    f_cell(audit, 1, 7, f_num(savedBody), fg, bg)
    f_cell(audit, 0, 8, "Cancelled magnitude", fg, bg)
    f_cell(audit, 1, 8, f_num(savedCancel), fg, bg)
    f_cell(audit, 0, 9, "Absolute close-to-close", fg, bg)
    f_cell(audit, 1, 9, f_num(savedRetained), fg, bg)
    string endText = na(savedEnd) ? "No confirmed bar" : "Window end: " + str.format_time(savedEnd, "yyyy-MM-dd HH:mm:ss", syminfo.timezone)
    f_cell(audit, 0, 10, endText + " | " + syminfo.timezone, fg, bg)
    f_cell(audit, 0, 11, "Confirmed only | Forming bar excluded", fg, bg)
    f_cell(audit, 0, 12, "Endpoint magnitudes; not path, gap-fill % or forecast", fg, bg)

← 返回列表