POC Backtest + Cycle Top Exit [v6]

rogerroth · study · 243 行 · 点赞 7 · TradingView 原页

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

Pine Script

// CLUSD — POC Distance Backtest + Confirmed Cycle Top Exits
// Pine Script v6
// POC approximation: candle volume assigned to HLC3 price bins.
// Signals are evaluated on confirmed candle closes.
 
//@version=6
indicator("POC Backtest + Cycle Top Exit [v6]", overlay=true, max_bars_back=501, max_labels_count=300)
 
// ─────────────────────────────────────────────
// SETTINGS
// ─────────────────────────────────────────────
lookback   = input.int(150, "POC Lookback", minval=20, maxval=500)
bins       = input.int(24, "Price Bins", minval=5, maxval=100)
horizon    = input.int(12, "Backtest Horizon (bars)", minval=1, maxval=100)
targetPct  = input.float(1.0, "Additional POC Distance (%)", minval=0.1, step=0.1) / 100.0
 
showPoc    = input.bool(true, "Show Rolling POC")
showSignals = input.bool(true, "Show Green POC Entry Signals")
showExits  = input.bool(true, "Show Red Cycle Exit Triangles")
 
rsiLen     = input.int(14, "RSI Length", minval=2)
pivotWidth = input.int(5, "Cycle Pivot Width", minval=2, maxval=20)
pivotRight = input.int(3, "Pivot Confirmation Bars", minval=1, maxval=20)
 
// ─────────────────────────────────────────────
// ROLLING POC — HLC3 APPROXIMATION
// Uses current and historical bars only.
// ─────────────────────────────────────────────
hiRange    = ta.highest(high, lookback)
loRange    = ta.lowest(low, lookback)
priceRange = hiRange - loRange
step       = priceRange / bins
 
float poc = na
 
if bar_index >= lookback - 1 and not na(priceRange) and priceRange > 0 and step > 0
    binVol = array.new_float(bins, 0.0)
 
    for i = 0 to lookback - 1
        price = hlc3[i]
        idxRaw = int(math.floor((price - loRange) / step))
        idx = math.max(0, math.min(bins - 1, idxRaw))
        vol = nz(volume[i], 0.0)
        array.set(binVol, idx, array.get(binVol, idx) + vol)
 
    maxBinVol = array.max(binVol)
    pocIdx = array.indexof(binVol, maxBinVol)
    poc := loRange + (pocIdx + 0.5) * step
 
plot(showPoc ? poc : na, "Rolling POC", color=color.blue, linewidth=2)
 
// ─────────────────────────────────────────────
// GREEN POC CROSS SIGNALS
// ─────────────────────────────────────────────
longEntry = not na(poc) and not na(poc[1]) and close > poc and close[1] <= poc[1]
shortEntry = not na(poc) and not na(poc[1]) and close < poc and close[1] >= poc[1]
 
plotshape(showSignals and barstate.isconfirmed and longEntry, title="POC Cross Up", style=shape.triangleup, location=location.belowbar, color=color.lime, size=size.tiny, text="POC")
plotshape(showSignals and barstate.isconfirmed and shortEntry, title="POC Cross Down", style=shape.triangledown, location=location.abovebar, color=color.orange, size=size.tiny, text="POC")
 
// ─────────────────────────────────────────────
// CYCLE TOP / BOTTOM DETECTION
// ─────────────────────────────────────────────
rsi = ta.rsi(close, rsiLen)
 
pricePH = ta.pivothigh(high, pivotWidth, pivotRight)
rsiPH   = ta.pivothigh(rsi, pivotWidth, pivotRight)
pricePL = ta.pivotlow(low, pivotWidth, pivotRight)
rsiPL   = ta.pivotlow(rsi, pivotWidth, pivotRight)
 
var float previousHigh = na
var float previousHighRsi = na
var float previousLow = na
var float previousLowRsi = na
 
var float lastConfirmedLow = na
var float lastConfirmedHigh = na
 
var bool bearishArmed = false
var bool bullishArmed = false
 
bool bearishWarning = false
bool bullishWarning = false
bool bearishReversal = false
bool bullishReversal = false
 
if barstate.isconfirmed
    // Store confirmed price structure levels.
    if not na(pricePL)
        lastConfirmedLow := pricePL
 
    if not na(pricePH)
        lastConfirmedHigh := pricePH
 
    // Bearish divergence: higher price high, lower RSI high.
    if not na(pricePH) and not na(rsiPH)
        currentHigh = pricePH
        currentHighRsi = rsiPH
 
        bearishWarning := not na(previousHigh) and
             not na(previousHighRsi) and
             currentHigh > previousHigh and
             currentHighRsi < previousHighRsi
 
        if bearishWarning
            bearishArmed := true
 
        previousHigh := currentHigh
        previousHighRsi := currentHighRsi
 
    // Bullish divergence: lower price low, higher RSI low.
    if not na(pricePL) and not na(rsiPL)
        currentLow = pricePL
        currentLowRsi = rsiPL
 
        bullishWarning := not na(previousLow) and
             not na(previousLowRsi) and
             currentLow < previousLow and
             currentLowRsi > previousLowRsi
 
        if bullishWarning
            bullishArmed := true
 
        previousLow := currentLow
        previousLowRsi := currentLowRsi
 
    // Confirmed bearish reversal: divergence, structure break, weaker RSI.
    bearishReversal := bearishArmed and
         not na(lastConfirmedLow) and
         close < lastConfirmedLow and
         rsi < rsi[1]
 
    // Confirmed bullish reversal: bullish divergence, structure break, stronger RSI.
    bullishReversal := bullishArmed and
         not na(lastConfirmedHigh) and
         close > lastConfirmedHigh and
         rsi > rsi[1]
 
    if bearishReversal
        bearishArmed := false
 
    if bullishReversal
        bullishArmed := false
 
// Warnings are displayed on the bar when the pivot is confirmed.
plotshape(showExits and bearishWarning, title="Bearish Divergence Warning", style=shape.circle, location=location.abovebar, color=color.orange, size=size.tiny, text="W")
plotshape(showExits and bullishWarning, title="Bullish Divergence Warning", style=shape.circle, location=location.belowbar, color=color.aqua, size=size.tiny, text="W")
 
// Red downward triangle = confirmed cycle top / long exit.
// Red upward triangle = confirmed cycle bottom / short exit.
plotshape(showExits and bearishReversal, title="Confirmed Cycle Top Exit", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.large, text="EXIT", textcolor=color.white)
plotshape(showExits and bullishReversal, title="Confirmed Cycle Bottom Exit", style=shape.triangleup, location=location.belowbar, color=color.red, size=size.large, text="EXIT", textcolor=color.white)
 
// Confirmed structure levels for visual inspection.
plot(lastConfirmedLow, "Last Confirmed Swing Low", color=color.new(color.red, 75), style=plot.style_stepline)
plot(lastConfirmedHigh, "Last Confirmed Swing High", color=color.new(color.green, 75), style=plot.style_stepline)
 
// ─────────────────────────────────────────────
// ORIGINAL POC DISTANCE BACKTEST
// Long POC cross: target is entry close + POC * targetPct.
// ─────────────────────────────────────────────
var float[] targets = array.new_float()
var float[] pocs = array.new_float()
var int[] entries = array.new_int()
 
var int total = 0
var int hits = 0
var int misses = 0
var int pocReturns = 0
var int ambiguous = 0
 
if barstate.isconfirmed and array.size(entries) > 0
    for j = array.size(entries) - 1 to 0
        entryBar = array.get(entries, j)
        target = array.get(targets, j)
        entryPoc = array.get(pocs, j)
        age = bar_index - entryBar
 
        if age >= 1
            targetHit = high >= target
            pocTouched = low <= entryPoc
 
            if targetHit and pocTouched
                ambiguous += 1
                array.remove(entries, j)
                array.remove(targets, j)
                array.remove(pocs, j)
            else if targetHit
                hits += 1
                array.remove(entries, j)
                array.remove(targets, j)
                array.remove(pocs, j)
            else if pocTouched
                pocReturns += 1
                misses += 1
                array.remove(entries, j)
                array.remove(targets, j)
                array.remove(pocs, j)
            else if age >= horizon
                misses += 1
                array.remove(entries, j)
                array.remove(targets, j)
                array.remove(pocs, j)
 
if barstate.isconfirmed and longEntry
    total += 1
    array.push(entries, bar_index)
    array.push(pocs, poc)
    array.push(targets, close + poc * targetPct)
 
// ─────────────────────────────────────────────
// STATISTICS TABLE
// ─────────────────────────────────────────────
var table stats = table.new(position.top_right, 2, 9, border_width=1)
 
if barstate.islast
    decisive = hits + misses
    hitRate = decisive > 0 ? 100.0 * hits / decisive : na
 
    table.cell(stats, 0, 0, "POC Backtest", bgcolor=color.navy, text_color=color.white)
    table.cell(stats, 1, 0, "Value", bgcolor=color.navy, text_color=color.white)
    table.cell(stats, 0, 1, "Lookback / bins")
    table.cell(stats, 1, 1, str.tostring(lookback) + " / " + str.tostring(bins))
    table.cell(stats, 0, 2, "Horizon")
    table.cell(stats, 1, 2, str.tostring(horizon) + " bars")
    table.cell(stats, 0, 3, "Target")
    table.cell(stats, 1, 3, "+" + str.tostring(targetPct * 100, "#.##") + "% of POC")
    table.cell(stats, 0, 4, "Signals started")
    table.cell(stats, 1, 4, str.tostring(total))
    table.cell(stats, 0, 5, "Target hits")
    table.cell(stats, 1, 5, str.tostring(hits))
    table.cell(stats, 0, 6, "Hit rate (decisive)")
    table.cell(stats, 1, 6, na(hitRate) ? "n/a" : str.tostring(hitRate, "#.##") + "%")
    table.cell(stats, 0, 7, "POC returns / ambiguous")
    table.cell(stats, 1, 7, str.tostring(pocReturns) + " / " + str.tostring(ambiguous))
    table.cell(stats, 0, 8, "Open observations")
    table.cell(stats, 1, 8, str.tostring(array.size(entries)))
 
// ─────────────────────────────────────────────
// ALERTS
// ─────────────────────────────────────────────
alertcondition(bearishReversal, "Confirmed Cycle Top Exit", "Confirmed bearish cycle reversal on {{ticker}} {{interval}}")
alertcondition(bullishReversal, "Confirmed Cycle Bottom Exit", "Confirmed bullish cycle reversal on {{ticker}} {{interval}}")

← 返回列表