Asian Range Breakout, London Reversal & Fill Rate [DNA]

DNA_PROFIT · study · 301 行 · 点赞 11 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
//  Asian Range Breakout, London Reversal & Fill Rate [DNA]
// ----------------------------------------------------------------------------
//  Boxes the Asian session high/low each day, watches the first London
//  breakout of that box, and classifies the outcome as a continuation that
//  reaches 1R or a reversal that fails back by the same 1R — then tallies
//  both outcomes live so the split is measured, not assumed.
//
//  NON-REPAINTING: everything is decided on closed bars from the bar's own
//  fixed session time. No higher-timeframe requests, no lookahead.
// ============================================================================
indicator("Asian Range Breakout, London Reversal & Fill Rate [DNA]", "Asian Range [DNA]", overlay = true, max_lines_count = 300, max_labels_count = 300, max_boxes_count = 200)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS
// ─────────────────────────────────────────────────────────────────────────
gL = "Logic"
asianSession  = input.session("0000-0800", "Asian session (HHMM-HHMM)", group = gL, tooltip = "Session window used to build each day's Asian range box.")
londonSession = input.session("0800-1600", "London session (HHMM-HHMM)", group = gL, tooltip = "Session window searched for the first breakout of the Asian range.")
sessionTZ     = input.string("UTC", "Session timezone", options = ["UTC", "Exchange"], group = gL, tooltip = "Exchange uses the chart symbol's own timezone instead of UTC.")
rMult         = input.float(1.0, "Target / invalidation distance (× range)", minval = 0.1, maxval = 5.0, step = 0.1, group = gL, tooltip = "Both the continuation target and the reversal invalidation sit this many range-widths from the breakout close. Kept equal on purpose: a fair measurement, not a stacked deck.")
maxBars       = input.int(100, "Max bars to resolve (bars)", minval = 10, maxval = 500, group = gL, tooltip = "A breakout that touches neither level within this many bars is logged as expired.")
minRangeATR   = input.float(0.1, "Min. range size (× ATR)", minval = 0.0, maxval = 5.0, step = 0.05, group = gL, tooltip = "Asian ranges narrower than this fraction of ATR(14) are skipped as too tight to matter.")
 
gD = "Drawing"
keepLast = input.int(6, "Items kept on the chart", minval = 1, maxval = 30, group = gD, tooltip = "Older finished ranges and breakout markers are removed from the chart. The counters keep all of them.")
labelSz  = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = gD)
 
gT = "Panel"
showPanel = input.bool(true, "Show the panel", group = gT)
panelPos  = input.string("Bottom centre", "Position", options = ["Bottom centre", "Bottom left", "Bottom right", "Top centre", "Top right"], group = gT)
panelSz   = input.string("Normal", "Text size", options = ["Small", "Normal", "Large"], group = gT)
 
gA = "Alerts"
alOn = input.bool(true, "Alerts with full messages (alert() calls)", group = gA)
 
gV = "Visuals"
brandCandles = input.bool(true, "Brand candles", group = gV, tooltip = "Gold for rising candles, periwinkle for falling. Off = your own chart candles.")
glowCandles  = input.bool(true, "Glow candles", group = gV, tooltip = "Each body is drawn in three bands that brighten towards the close. Off = flat bodies.")
 
// ─────────────────────────────────────────────────────────────────────────
//  THEME  (adapts to a light or dark chart)
// ─────────────────────────────────────────────────────────────────────────
chartBg = chart.bg_color
isLight = (color.r(chartBg) + color.g(chartBg) + color.b(chartBg)) / 3.0 > 140
UP    = isLight ? #B07D0A : #F7C948   // gold: bullish, rising candles
DN    = isLight ? #5546C8 : #8E7CFF   // periwinkle: bearish, falling candles
ACC   = isLight ? #0E8F7E : #5EEAD4   // mint: the zone / the level that matters
WARN  = isLight ? #C2410C : #FF8A5B   // failed / broken
TXT   = isLight ? #12151C : #F2F3F7
MUTE  = isLight ? #646B7D : #8E95A8
PANEL = isLight ? #FBFBFD : #0D1017
ROW   = isLight ? #ECEEF4 : #171B26
INK   = #0D1017
NONE  = color.new(#000000, 100)
 
lSize = switch labelSz
    "Tiny"  => size.tiny
    "Small" => size.small
    "Large" => size.large
    => size.normal
tSize = switch panelSz
    "Small" => size.small
    "Large" => size.large
    => size.normal
 
fmtPrice(float v) =>
    str.tostring(v, format.mintick)
 
pct(int a, int b) =>
    b > 0 ? str.tostring(math.round(100.0 * a / b)) + "%" : "—"
 
// ─────────────────────────────────────────────────────────────────────────
//  CORE  (Asian range → first London breakout → symmetric 1R outcome)
// ─────────────────────────────────────────────────────────────────────────
atr = ta.atr(14)
 
tzArg       = sessionTZ == "Exchange" ? "" : "UTC"
asianActive  = not na(time(timeframe.period, asianSession, tzArg))
londonActive = not na(time(timeframe.period, londonSession, tzArg))
newAsianBar  = asianActive and not asianActive[1]
endAsianBar  = (not asianActive) and asianActive[1]
 
var float  rangeHi     = na
var float  rangeLo     = na
var float  lastRangeHi = na
var float  lastRangeLo = na
var bool   pending      = false
var int    breakoutDir  = 0
var float  breakoutClose = na
var float  targetLevel  = na
var float  invalidLevel = na
var int    breakoutBar  = na
var string stage = "session building"
 
var int nRanges       = 0   // Asian ranges locked
var int nBreakoutsTotal = 0 // first London breakouts seen
var int nContinued    = 0   // resolved: reached 1R target
var int nReversed     = 0   // resolved: reached 1R invalidation
var int nExpired      = 0   // resolved: neither reached within maxBars
 
evRangeLocked  = false
evBreakout     = false
evContinuation = false
evReversal     = false
evExpired      = false
 
if barstate.isconfirmed
    if newAsianBar
        if pending
            nExpired := nExpired + 1
            evExpired := true
        pending := false
        lastRangeHi := na
        lastRangeLo := na
        rangeHi := high
        rangeLo := low
        stage := "session building"
    else if asianActive
        rangeHi := math.max(rangeHi, high)
        rangeLo := math.min(rangeLo, low)
 
    if endAsianBar
        lastRangeHi := rangeHi
        lastRangeLo := rangeLo
        nRanges := nRanges + 1
        stage := "range locked"
        evRangeLocked := true
 
    rangeSize  = na(lastRangeHi) ? na : lastRangeHi - lastRangeLo
    validRange = not na(rangeSize) and rangeSize >= atr * minRangeATR
 
    if londonActive and not pending and validRange
        triggered = close > lastRangeHi or close < lastRangeLo
        if triggered
            breakoutDir := close > lastRangeHi ? 1 : -1
            breakoutClose := close
            breakoutBar := bar_index
            targetLevel := breakoutClose + breakoutDir * rangeSize * rMult
            invalidLevel := breakoutClose - breakoutDir * rangeSize * rMult
            pending := true
            nBreakoutsTotal := nBreakoutsTotal + 1
            stage := "breakout triggered"
            evBreakout := true
 
    if pending
        hitTarget  = breakoutDir == 1 ? high >= targetLevel  : low  <= targetLevel
        hitInvalid = breakoutDir == 1 ? low  <= invalidLevel : high >= invalidLevel
        isExpired  = (bar_index - breakoutBar) >= maxBars
        if hitInvalid
            // a bar that touches both target and invalidation counts as reversed
            nReversed := nReversed + 1
            stage := "reversal ✕"
            evReversal := true
            pending := false
            lastRangeHi := na
            lastRangeLo := na
        else if hitTarget
            nContinued := nContinued + 1
            stage := "continuation ✓"
            evContinuation := true
            pending := false
            lastRangeHi := na
            lastRangeLo := na
        else if isExpired
            nExpired := nExpired + 1
            stage := "range locked"
            evExpired := true
            pending := false
            lastRangeHi := na
            lastRangeLo := na
 
// ─────────────────────────────────────────────────────────────────────────
//  DRAWING  (box for the zone, lines for 1R levels, small outcome labels)
// ─────────────────────────────────────────────────────────────────────────
var box   curBox = na
var line  tLine  = na
var line  iLine  = na
var array<box>   rangeBoxes = array.new<box>()
var array<line>  evLines    = array.new<line>()
var array<label> evLabels   = array.new<label>()
 
f_trimBoxes(array<box> arr, int keep) =>
    while array.size(arr) > keep
        box.delete(array.shift(arr))
 
f_trimLines(array<line> arr, int keep) =>
    while array.size(arr) > keep
        line.delete(array.shift(arr))
 
f_trimLabels(array<label> arr, int keep) =>
    while array.size(arr) > keep
        label.delete(array.shift(arr))
 
if barstate.isconfirmed
    if newAsianBar
        curBox := box.new(bar_index, high, bar_index, low, border_color = ACC, border_width = 1, bgcolor = color.new(ACC, 88))
        array.push(rangeBoxes, curBox)
        f_trimBoxes(rangeBoxes, keepLast)
    else if asianActive
        box.set_top(curBox, rangeHi)
        box.set_bottom(curBox, rangeLo)
        box.set_right(curBox, bar_index)
 
    if endAsianBar
        box.set_right(curBox, bar_index - 1)
 
    if evBreakout
        dirUp = breakoutDir == 1
        bLabel = label.new(bar_index, dirUp ? low : high, (dirUp ? "▲ BO · " : "▼ BO · ") + fmtPrice(breakoutClose), style = dirUp ? label.style_label_up : label.style_label_down, color = color.new(ACC, 10), textcolor = INK, size = lSize)
        array.push(evLabels, bLabel)
        tLine := line.new(bar_index, targetLevel, bar_index, targetLevel, color = UP, style = line.style_dashed)
        iLine := line.new(bar_index, invalidLevel, bar_index, invalidLevel, color = WARN, style = line.style_dashed)
        array.push(evLines, tLine)
        array.push(evLines, iLine)
        f_trimLabels(evLabels, keepLast * 2)
        f_trimLines(evLines, keepLast * 2)
 
    if not na(tLine) and (pending or evContinuation or evReversal or evExpired)
        line.set_x2(tLine, bar_index)
        line.set_x2(iLine, bar_index)
 
    if evContinuation
        dirUp = breakoutDir == 1
        rLabel = label.new(bar_index, dirUp ? high : low, "✓ CONT · " + fmtPrice(targetLevel), style = dirUp ? label.style_label_up : label.style_label_down, color = color.new(UP, 10), textcolor = INK, size = lSize)
        array.push(evLabels, rLabel)
        f_trimLabels(evLabels, keepLast * 2)
 
    if evReversal
        dirUp = breakoutDir == 1
        rLabel = label.new(bar_index, dirUp ? low : high, "✕ REV · " + fmtPrice(invalidLevel), style = dirUp ? label.style_label_down : label.style_label_up, color = color.new(WARN, 10), textcolor = INK, size = lSize)
        array.push(evLabels, rLabel)
        f_trimLabels(evLabels, keepLast * 2)
 
    if evExpired
        xLabel = label.new(bar_index, close, "— EXP", style = label.style_label_down, color = color.new(MUTE, 20), textcolor = TXT, size = lSize)
        array.push(evLabels, xLabel)
        f_trimLabels(evLabels, keepLast * 2)
 
// ─────────────────────────────────────────────────────────────────────────
//  PANEL  (one strip of tiles: caption row + value row)
// ─────────────────────────────────────────────────────────────────────────
tile(table t, int c, string cap, string val, color vc) =>
    table.cell(t, c, 0, cap, text_color = MUTE, text_size = size.small, bgcolor = PANEL)
    table.cell(t, c, 1, val, text_color = vc, text_size = tSize, bgcolor = PANEL)
 
pos = switch panelPos
    "Bottom left"  => position.bottom_left
    "Bottom right" => position.bottom_right
    "Top centre"   => position.top_center
    "Top right"    => position.top_right
    => position.bottom_center
 
stageColor = switch stage
    "continuation ✓"     => UP
    "reversal ✕"         => WARN
    "breakout triggered" => ACC
    "range locked"       => ACC
    => MUTE
 
var table tb = table.new(pos, 5, 2, bgcolor = NONE, border_width = 6, border_color = NONE, frame_width = 0)
if showPanel and barstate.islast
    tile(tb, 0, "STAGE", stage, stageColor)
    tile(tb, 1, "RANGES SEEN", str.tostring(nRanges), TXT)
    tile(tb, 2, "BREAKOUTS", str.tostring(nBreakoutsTotal), ACC)
    tile(tb, 3, "REVERSED", str.tostring(nReversed), WARN)
    tile(tb, 4, "CONTINUED RATE · " + str.tostring(nContinued + nReversed), pct(nContinued, nContinued + nReversed), UP)
 
// ─────────────────────────────────────────────────────────────────────────
//  ALERTS  (closed bars only, one event per message)
// ─────────────────────────────────────────────────────────────────────────
if alOn and evRangeLocked
    alert(syminfo.ticker + " · Asian range locked", alert.freq_once_per_bar_close)
if alOn and evBreakout
    alert(syminfo.ticker + " · London breakout " + (breakoutDir == 1 ? "up" : "down"), alert.freq_once_per_bar_close)
if alOn and evContinuation
    alert(syminfo.ticker + " · breakout continuation confirmed (1R)", alert.freq_once_per_bar_close)
if alOn and evReversal
    alert(syminfo.ticker + " · breakout reversal confirmed (1R)", alert.freq_once_per_bar_close)
 
alertcondition(evRangeLocked, "Asian range locked", "{{ticker}} Asian range locked")
alertcondition(evBreakout, "London breakout triggered", "{{ticker}} London breakout triggered")
alertcondition(evContinuation, "Continuation confirmed", "{{ticker}} breakout continuation confirmed at 1R")
alertcondition(evReversal, "Reversal confirmed", "{{ticker}} breakout reversal confirmed at 1R")
 
// ─────────────────────────────────────────────────────────────────────────
//  BRAND CANDLES  (keep this block as it is)
// ─────────────────────────────────────────────────────────────────────────
edge  = close >= open ? UP : DN
flat  = brandCandles and not glowCandles
glow  = brandCandles and glowCandles
third = (close - open) / 3.0
b1    = open + third
b2    = open + 2.0 * third
plotcandle(flat ? open : na, high, low, close, "Candles", color = color.new(edge, 25), wickcolor = color.new(edge, 15), bordercolor = edge, display = display.pane)
plotcandle(glow ? open : na, glow ? math.max(open, close) : na, glow ? math.min(open, close) : na, glow ? close : na, "Glow mask", color = chart.bg_color, wickcolor = NONE, bordercolor = chart.bg_color, display = display.pane)
plotcandle(glow ? open : na, glow ? math.max(open, b1) : na, glow ? math.min(open, b1) : na, glow ? b1 : na, "Glow band 1", color = color.new(edge, 72), wickcolor = NONE, bordercolor = NONE, display = display.pane)
plotcandle(glow ? b1 : na, glow ? math.max(b1, b2) : na, glow ? math.min(b1, b2) : na, glow ? b2 : na, "Glow band 2", color = color.new(edge, 44), wickcolor = NONE, bordercolor = NONE, display = display.pane)
plotcandle(glow ? b2 : na, glow ? math.max(b2, close) : na, glow ? math.min(b2, close) : na, glow ? close : na, "Glow band 3", color = color.new(edge, 8), wickcolor = NONE, bordercolor = NONE, display = display.pane)
plotcandle(glow ? open : na, glow ? high : na, glow ? low : na, glow ? close : na, "Glow wick", color = NONE, wickcolor = color.new(edge, 12), bordercolor = color.new(edge, 30), display = display.pane)

← 返回列表