Veloxalgotech_Price Break + OB Filter

rakshithradhakrishna · study · 383 行 · 点赞 8 · TradingView 原页

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

Pine Script

//@version=6
indicator("Veloxalgotech_Price Break + OB Filter", shorttitle="NY-BRT-OB", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
 
// Order block detection logic adapted from "Pure Price Action Order & Breaker Blocks" by LuxAlgo
// (CC BY-NC-SA 4.0 - https://creativecommons.org/licenses/by-nc-sa/4.0/)
 
// ─────────────────────────────── Inputs ───────────────────────────────
gSess = "Sessions"
tz       = input.string("America/New_York", "Session timezone", group=gSess)
nySess   = input.session("0800-1700", "New York session", group=gSess)
asiaSess = input.session("1900-0400", "Asian session (entries only)", group=gSess)
refMode  = input.string("Last swing high/low", "NY reference levels", options=["Last swing high/low", "Session high/low"], group=gSess,
     tooltip="Last swing high/low = the most recent swing point formed inside the New York session. Session high/low = the absolute extreme of the session.")
 
gBrk = "Breakout filter"
useMomentum = input.bool(false, "Require momentum candle (large body)", group=gBrk)
minBodyPct  = input.float(70.0, "Min body % of candle range", minval=1, maxval=100, group=gBrk,
     tooltip="70%+ approximates a Marubozu-style candle. The candle BODY must always close beyond the level; a wick alone never counts.")
 
gTrd = "Trade management"
allowLong   = input.bool(true, "Allow longs", group=gTrd)
allowShort  = input.bool(true, "Allow shorts", group=gTrd)
touchPts    = input.float(3.0, "Retest tolerance (points)", minval=0.0, step=0.5, group=gTrd,
     tooltip="How many points before/beyond the level still count as a 'tap'. 0 = price must exactly reach the level (very rare).")
entryMode   = input.string("Any time", "Entry session", options=["Asia only", "Any time"], group=gTrd,
     tooltip="Asia only = retest entries only 19:00-04:00 NY time (original behaviour). Any time = retest entry allowed whenever it happens.")
showDebug   = input.bool(true, "Show debug markers + status table", group=gTrd)
slMode      = input.string("Points", "Stop loss type", options=["Points", "ATR beyond level"], group=gTrd)
slPoints    = input.float(10.0, "SL points (price distance from entry)", minval=0.0, step=1.0, group=gTrd,
     tooltip="Used when Stop loss type = Points. 1 point = 1.0 of price.")
tpMode      = input.string("Points", "Take profit type", options=["Points", "New high/low"], group=gTrd,
     tooltip="Points = fixed distance from entry. New high/low = close once price forms a new higher high (long) / lower low (short) beyond the breakout move.")
tpPoints    = input.float(10.0, "TP points (price distance from entry)", minval=0.0, step=1.0, group=gTrd,
     tooltip="Used when Take profit type = Points.")
atrLen      = input.int(14, "ATR length (used by ATR stop)", minval=1, group=gTrd)
slAtrMult   = input.float(1.0, "Stop distance beyond level (x ATR)", minval=0.1, step=0.1, group=gTrd)
closeAtEnd  = input.bool(false, "Force-close open trade at end of Asian session", group=gTrd)
 
gSw = "Last NY swing high / low"
swLeft     = input.int(5, "Bars to the left", minval=1, group=gSw)
swRight    = input.int(5, "Bars to the right (confirmation)", minval=1, group=gSw,
     tooltip="A swing is confirmed only after this many bars close on the right, so the circle is drawn on the actual swing candle, this many bars back.")
showNYCircles = input.bool(true, "Show last NY swing high / low as continuing circles", group=gSw)
swHighCol  = input.color(color.red,   "Swing high colour", group=gSw)
swLowCol   = input.color(color.green, "Swing low colour",  group=gSw)
 
gOB = "Order block filter"
useOBFilter = input.bool(true, "Use order block filter", group=gOB,
     tooltip="BUY is skipped when an active SELLING (bearish) order block is above/near price. SELL is skipped when an active BUYING (bullish) order block is below/near price.")
obNear      = input.float(30.0, "OB 'near' distance (points)", minval=0.0, step=1.0, group=gOB,
     tooltip="An order block counts as 'near' if it is within this many points of the entry price (or price is inside it).")
obTerm      = input.string("Intermediate Term", "OB detection", options=["Short Term", "Intermediate Term", "Long Term"], group=gOB)
showBull    = input.int(3, "Use / show last bullish OBs", minval=0, group=gOB)
showBear    = input.int(3, "Use / show last bearish OBs", minval=0, group=gOB)
useBody     = input.bool(true, "Use candle body for OB", group=gOB)
drawOB      = input.bool(true, "Draw order blocks", group=gOB)
bullCss     = input.color(color.new(#2157f3, 80), "Bullish OB (buying)", group=gOB)
bearCss     = input.color(color.new(#ff5d00, 80), "Bearish OB (selling)", group=gOB)
 
// ─────────────────────────────── Order block types ────────────────────
type ob
    float top = na
    float btm = na
    int   loc = bar_index
    bool  breaker = false
    int   break_loc = na
 
type swing
    float y = na
    int   x = na
    bool  crossed = false
 
type vector
    array<swing> v
 
method detect(array<vector> id, string mode, int depth) =>
    var swing swingLevel = swing.new(na, na)
    for i = 0 to depth - 1
        get_v = id.get(i).v
        if get_v.size() == 3
            pivot = switch mode
                'bull' => math.max(get_v.get(0).y, get_v.get(1).y, get_v.get(2).y)
                'bear' => math.min(get_v.get(0).y, get_v.get(1).y, get_v.get(2).y)
            if pivot == get_v.get(1).y
                if i < depth - 1
                    id.get(i + 1).v.unshift(get_v.get(1))
                    if id.get(i + 1).v.size() > 3
                        id.get(i + 1).v.pop()
                else
                    swingLevel := swing.new(get_v.get(1).y, get_v.get(1).x)
                get_v.pop()
                get_v.pop()
    swingLevel
 
method drawBlock(ob id, color css) =>
    box.new(id.loc, id.top, time, id.btm, border_color=na, bgcolor=css, extend=extend.right, xloc=xloc.bar_time)
 
// ─────────────────────────────── Order block detection ────────────────
n = bar_index
obDepth = switch obTerm
    'Short Term' => 1
    'Intermediate Term' => 2
    => 3
 
var fh = array.new<vector>(0)
var fl = array.new<vector>(0)
 
if barstate.isfirst
    for i = 0 to obDepth - 1
        fh.push(vector.new(array.new<swing>(0)))
        fl.push(vector.new(array.new<swing>(0)))
 
fh.get(0).v.unshift(swing.new(high, n))
fl.get(0).v.unshift(swing.new(low, n))
if fh.get(0).v.size() > 3
    fh.get(0).v.pop()
if fl.get(0).v.size() > 3
    fl.get(0).v.pop()
 
obTop = fh.detect('bull', obDepth)
obBtm = fl.detect('bear', obDepth)
 
bMax = useBody ? math.max(close, open) : high
bMin = useBody ? math.min(close, open) : low
 
// Bullish OB (buying block, support)
var bullish_ob = array.new<ob>(0)
if close > obTop.y and not obTop.crossed
    obTop.crossed := true
    minima = bMax[1]
    maxima = bMin[1]
    loc = time[1]
    for i = 1 to (n - obTop.x) - 1
        minima := math.min(bMin[i], minima)
        maxima := minima == bMin[i] ? bMax[i] : maxima
        loc := minima == bMin[i] ? time[i] : loc
    bullish_ob.unshift(ob.new(maxima, minima, loc))
 
if bullish_ob.size() > 0
    for i = bullish_ob.size() - 1 to 0
        element = bullish_ob.get(i)
        if not element.breaker
            if math.min(close, open) < element.btm
                element.breaker := true
                element.break_loc := time
        else
            if close > element.top
                bullish_ob.remove(i)
 
// Bearish OB (selling block, resistance)
var bearish_ob = array.new<ob>(0)
if close < obBtm.y and not obBtm.crossed
    obBtm.crossed := true
    minima = bMin[1]
    maxima = bMax[1]
    loc = time[1]
    for i = 1 to (n - obBtm.x) - 1
        maxima := math.max(bMax[i], maxima)
        minima := maxima == bMax[i] ? bMin[i] : minima
        loc := maxima == bMax[i] ? time[i] : loc
    bearish_ob.unshift(ob.new(maxima, minima, loc))
 
if bearish_ob.size() > 0
    for i = bearish_ob.size() - 1 to 0
        element = bearish_ob.get(i)
        if not element.breaker
            if math.max(close, open) > element.top
                element.breaker := true
                element.break_loc := time
        else
            if close < element.btm
                bearish_ob.remove(i)
 
// Draw (only the active, non-broken blocks)
if drawOB
    for bx in box.all
        bx.delete()
    if barstate.islast
        if showBull > 0 and bullish_ob.size() > 0
            for i = 0 to math.min(showBull - 1, bullish_ob.size() - 1)
                b = bullish_ob.get(i)
                if not b.breaker
                    b.drawBlock(bullCss)
        if showBear > 0 and bearish_ob.size() > 0
            for i = 0 to math.min(showBear - 1, bearish_ob.size() - 1)
                b = bearish_ob.get(i)
                if not b.breaker
                    b.drawBlock(bearCss)
 
// ── OB filter: is a SELLING block above/near (blocks BUY)? is a BUYING block below/near (blocks SELL)?
obBlocksBuy  = false
obBlocksSell = false
if useOBFilter
    if showBear > 0 and bearish_ob.size() > 0
        for i = 0 to math.min(showBear - 1, bearish_ob.size() - 1)
            b = bearish_ob.get(i)
            // selling block is above price (or price is inside it) and within the 'near' distance
            if not b.breaker and b.top >= close and (b.btm - close) <= obNear
                obBlocksBuy := true
    if showBull > 0 and bullish_ob.size() > 0
        for i = 0 to math.min(showBull - 1, bullish_ob.size() - 1)
            b = bullish_ob.get(i)
            // buying block is below price (or price is inside it) and within the 'near' distance
            if not b.breaker and b.btm <= close and (close - b.top) <= obNear
                obBlocksSell := true
 
// ─────────────────────────────── Sessions ─────────────────────────────
inNY   = not na(time(timeframe.period, nySess, tz))
inAsia = not na(time(timeframe.period, asiaSess, tz))
nyStart   = inNY and not inNY[1]
nyEnd     = not inNY and inNY[1]
asiaEnd   = not inAsia and inAsia[1]
 
// ─────────────────────────────── State ────────────────────────────────
var float nyHigh   = na
var float nyLow    = na
var float prevHigh = na
var float prevLow  = na
var int   bState   = 0    // 0 watching, 1 long pending retest, -1 short pending retest, 2 trade taken
var float lvl      = na
var float legExt   = na
var float slPx     = na
var float tpPx     = na
var int   tradeDir = 0
var int   entryBar = na
var bool  tradedThisAsia = false
var bool  inPosition = false
 
atr = ta.atr(atrLen)
tol = touchPts
rng = high - low
bodyPct = rng > 0 ? math.abs(close - open) / rng * 100 : 0.0
momOK = not useMomentum or bodyPct >= minBodyPct
 
// ───────────────────── Swing points + NY session levels ────────────────
swHigh = ta.pivothigh(high, swLeft, swRight)
swLow  = ta.pivotlow(low,  swLeft, swRight)
useSwing = refMode == "Last swing high/low"
 
var float nySwH = na
var float nySwL = na
 
if nyStart
    nySwH := na
    nySwL := na
 
if inNY
    nyHigh := nyStart ? high : math.max(nyHigh, high)
    nyLow  := nyStart ? low  : math.min(nyLow, low)
 
if not na(swHigh) and inNY[swRight]
    nySwH := swHigh
if not na(swLow) and inNY[swRight]
    nySwL := swLow
 
if nyEnd
    prevHigh := useSwing and not na(nySwH) ? nySwH : nyHigh
    prevLow  := useSwing and not na(nySwL) ? nySwL : nyLow
 
if asiaEnd
    tradedThisAsia := false
    if bState == 1 or bState == -1
        bState := 0
 
if bState == 2 and not inPosition and bar_index > entryBar
    bState := 0
 
// ───────────── Breakout (BODY close beyond level) → retest → entry ─────
// Breakout only counts when the candle CLOSE is beyond the level (wick-only breaks are ignored).
longBreak  = allowLong  and not na(prevHigh) and close > prevHigh and close[1] <= prevHigh and momOK
shortBreak = allowShort and not na(prevLow)  and close < prevLow  and close[1] >= prevLow  and momOK
 
sessOK = entryMode == "Any time" ? not inPosition : (inAsia and not tradedThisAsia)
 
bool longEntrySignal = false
bool shortEntrySignal = false
 
if bState == 0
    if longBreak
        bState := 1
        lvl    := prevHigh
        legExt := high
    else if shortBreak
        bState := -1
        lvl    := prevLow
        legExt := low
 
else if bState == 1
    // Pullback to the broken high: wick may tap, but candle must CLOSE back above the level.
    // Entry skipped if a selling order block is above/near.
    if sessOK and low <= lvl + tol and close >= lvl and not obBlocksBuy
        slPx := slMode == "Points" ? close - slPoints : lvl - atr * slAtrMult
        tpPx := tpMode == "Points" ? close + tpPoints : legExt + syminfo.mintick
        inPosition := true
        longEntrySignal := true
        tradeDir := 1
        entryBar := bar_index
        tradedThisAsia := true
        bState := 2
    else if close < lvl
        bState := 0
    else
        legExt := math.max(legExt, high)
 
else if bState == -1
    // Entry skipped if a buying order block is below/near.
    if sessOK and high >= lvl - tol and close <= lvl and not obBlocksSell
        slPx := slMode == "Points" ? close + slPoints : lvl + atr * slAtrMult
        tpPx := tpMode == "Points" ? close - tpPoints : legExt - syminfo.mintick
        inPosition := true
        shortEntrySignal := true
        tradeDir := -1
        entryBar := bar_index
        tradedThisAsia := true
        bState := 2
    else if close > lvl
        bState := 0
    else
        legExt := math.min(legExt, low)
 
// ───────────────────────────── Exits ───────────────────────────────────
bool longExitSignal = false
bool shortExitSignal = false
 
if bState == 2 and inPosition
    if tradeDir == 1
        if low <= slPx or high >= tpPx
            inPosition := false
            longExitSignal := true
    if tradeDir == -1
        if high >= slPx or low <= tpPx
            inPosition := false
            shortExitSignal := true
    if closeAtEnd and asiaEnd and inPosition
        inPosition := false
        if tradeDir == 1
            longExitSignal := true
        else if tradeDir == -1
            shortExitSignal := true
 
// ───────────────────────────── Debug ───────────────────────────────────
// Orange X = retest happened but an order block blocked the trade
blockedBuy  = bState == 1 and sessOK and low <= lvl + tol and close >= lvl and obBlocksBuy
blockedSell = bState == -1 and sessOK and high >= lvl - tol and close <= lvl and obBlocksSell
plotshape(showDebug and blockedBuy,  "Buy blocked by OB",  shape.xcross, location.belowbar, color.orange, size=size.tiny)
plotshape(showDebug and blockedSell, "Sell blocked by OB", shape.xcross, location.abovebar, color.orange, size=size.tiny)
 
var table dbg = table.new(position.top_right, 2, 6, bgcolor=color.new(color.black, 30), border_width=1)
if showDebug and barstate.islast
    table.cell(dbg, 0, 0, "NY High level", text_color=color.white, text_size=size.small)
    table.cell(dbg, 1, 0, str.tostring(prevHigh), text_color=color.white, text_size=size.small)
    table.cell(dbg, 0, 1, "NY Low level", text_color=color.white, text_size=size.small)
    table.cell(dbg, 1, 1, str.tostring(prevLow), text_color=color.white, text_size=size.small)
    table.cell(dbg, 0, 2, "State", text_color=color.white, text_size=size.small)
    table.cell(dbg, 1, 2, bState == 0 ? "Watching" : bState == 1 ? "Long wait retest" : bState == -1 ? "Short wait retest" : "In trade", text_color=color.white, text_size=size.small)
    table.cell(dbg, 0, 3, "In Asia / NY", text_color=color.white, text_size=size.small)
    table.cell(dbg, 1, 3, (inAsia ? "Asia" : inNY ? "NY" : "Gap"), text_color=color.white, text_size=size.small)
    table.cell(dbg, 0, 4, "OB blocks buy/sell", text_color=color.white, text_size=size.small)
    table.cell(dbg, 1, 4, str.tostring(obBlocksBuy) + " / " + str.tostring(obBlocksSell), text_color=color.white, text_size=size.small)
    table.cell(dbg, 0, 5, "Timeframe", text_color=color.white, text_size=size.small)
    table.cell(dbg, 1, 5, timeframe.period, text_color=color.white, text_size=size.small)
 
// ───────────────────────────── Visuals & Alerts ────────────────────────
bgcolor(inAsia ? color.new(color.blue, 94) : na, title="Asian session")
plot(bState == 2 ? slPx : na, "Stop",   color=color.new(color.red, 40),   style=plot.style_cross)
plot(bState == 2 ? tpPx : na, "Target", color=color.new(color.green, 40), style=plot.style_cross)
 
plotshape(bState == 0 and longBreak,  "Long breakout",  shape.triangleup,   location.belowbar, color.green, size=size.tiny)
plotshape(bState == 0 and shortBreak, "Short breakout", shape.triangledown, location.abovebar, color.red,   size=size.tiny)
 
plotshape(longEntrySignal,  "Long Entry",  shape.labelup,   location.belowbar, color.green, text="L", textcolor=color.white, size=size.small)
plotshape(shortEntrySignal, "Short Entry", shape.labeldown, location.abovebar, color.red,   text="S", textcolor=color.white, size=size.small)
 
plotshape(longExitSignal,  "Long Exit",  shape.xcross, location.belowbar, color.yellow, size=size.small)
plotshape(shortExitSignal, "Short Exit", shape.xcross, location.abovebar, color.yellow, size=size.small)
 
plot(showNYCircles ? prevHigh : na, "Last NY Swing High", color=swHighCol, style=plot.style_circles, linewidth=2)
plot(showNYCircles ? prevLow  : na, "Last NY Swing Low",  color=swLowCol,  style=plot.style_circles, linewidth=2)
 
alertcondition(longEntrySignal,  title="Long Entry",  message="Velox NY-BRT: Long Entry Triggered")
alertcondition(shortEntrySignal, title="Short Entry", message="Velox NY-BRT: Short Entry Triggered")
alertcondition(longExitSignal,   title="Long Exit",   message="Velox NY-BRT: Long Exit Hit")
alertcondition(shortExitSignal,  title="Short Exit",  message="Velox NY-BRT: Short Exit Hit")

← 返回列表