本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator(title = "Displacement Break OB Retest Pyramid", shorttitle = "DB-OBR Pyr", overlay = true, max_labels_count = 500, max_boxes_count = 200, max_lines_count = 200)
//==================================================================================================
// GROUPS
//==================================================================================================
G_STR = "1) Market Structure"
G_OB = "2) Order Block Retest"
G_FIX = "3) Weakness Fixes / Filters"
G_PYR = "4) Pyramid Orders"
G_VIS = "5) Visuals"
//==================================================================================================
// INPUTS
//==================================================================================================
swingLen = input.int(10, "Swing Pivot Length", minval = 2, maxval = 50, group = G_STR,
tooltip = "Bars on each side needed to confirm a swing high/low. Higher = fewer, stronger swings and later signals. Lower = more swings, more noise.")
atrLen = input.int(14, "ATR Length", minval = 1, maxval = 200, group = G_STR,
tooltip = "ATR period used for displacement, Order Block size limits and plotting offsets. Higher = smoother volatility reading; lower = reacts faster to volatility changes.")
dispOn = input.bool(true, "Require Displacement on Break", group = G_STR,
tooltip = "Only structure breaks with a large candle body create a tradable Order Block. Turn off to trade every break (more signals, more weak ones).")
dispMult = input.float(0.8, "Displacement Body x ATR", minval = 0.1, maxval = 5.0, step = 0.1, group = G_STR,
tooltip = "Minimum candle body on the break bar as a multiple of ATR. Higher = only strong impulsive breaks qualify (fewer signals). Lower = more breaks qualify.")
chochOnly = input.bool(false, "Trade CHoCH Only", group = G_STR,
tooltip = "If on, only Change of Character breaks (trend reversals) create tradable Order Blocks. If off, Break of Structure (continuation) breaks are traded too.")
obLookback = input.int(10, "OB Search Bars", minval = 2, maxval = 50, group = G_OB,
tooltip = "How many bars back from the break to search for the last opposite candle used as the Order Block. Higher finds older blocks; lower keeps blocks close to the break.")
obMaxAge = input.int(50, "OB Max Age (bars)", minval = 5, maxval = 500, group = G_OB,
tooltip = "An untouched Order Block expires after this many bars. Higher keeps zones alive longer (more late entries); lower only trades fresh zones.")
obMinAtr = input.float(0.15, "Min OB Height x ATR", minval = 0.0, maxval = 5.0, step = 0.05, group = G_OB,
tooltip = "Order Blocks thinner than this ATR multiple are ignored. Higher removes tiny noisy zones; lower accepts thin zones.")
obMaxAtr = input.float(3.0, "Max OB Height x ATR", minval = 0.5, maxval = 10.0, step = 0.1, group = G_OB,
tooltip = "Order Blocks taller than this ATR multiple are ignored, filtering news spikes. Lower = stricter; higher = accepts very wide zones with wider risk.")
useRej = input.bool(true, "Require Rejection Candle", group = G_OB,
tooltip = "Entry bar must close in the trade direction and in the favourable part of its range. Turn off for touch-only entries (earlier but less reliable).")
rejRatio = input.float(0.6, "Rejection Close Position", minval = 0.5, maxval = 0.95, step = 0.05, group = G_OB,
tooltip = "For Buy, close must be in the top portion of the bar range (0.6 = top 40%). Mirrored for Sell. Higher = stronger rejection required, fewer signals.")
// FIX inputs
useConfirm = input.bool(true, "Confirmed Bars Only (No Repaint)", group = G_FIX,
tooltip = "Signals and structure updates are evaluated only on closed bars, so arrows never appear and disappear in realtime. Turning off gives earlier but repainting signals.")
useHtf = input.bool(true, "HTF Trend Filter", group = G_FIX,
tooltip = "Buy only above, Sell only below a higher-timeframe EMA (previous closed HTF bar, no lookahead). Reduces counter-trend entries but adds some lag.")
htfTf = input.timeframe("240", "HTF Timeframe", group = G_FIX,
tooltip = "Timeframe of the trend EMA. Use one above your chart timeframe. Higher = slower, broader trend; empty = chart timeframe.")
htfLen = input.int(50, "HTF EMA Length", minval = 2, maxval = 500, group = G_FIX,
tooltip = "EMA period on the HTF. Higher = slower trend filter with more lag; lower = trend flips more often.")
useAdx = input.bool(true, "ADX Sideway Filter", group = G_FIX,
tooltip = "Blocks signals when ADX is below the threshold, i.e. in choppy sideways markets where structure breaks often fail.")
adxLen = input.int(14, "ADX Length", minval = 2, maxval = 100, group = G_FIX,
tooltip = "Period for DMI/ADX. Higher = smoother, slower ADX; lower = faster but noisier.")
adxMin = input.float(18.0, "ADX Minimum", minval = 0.0, maxval = 60.0, step = 1.0, group = G_FIX,
tooltip = "Minimum ADX to allow signals. Higher = only strong trends (fewer signals); lower = allows weaker trends.")
usePD = input.bool(false, "Premium/Discount Filter", group = G_FIX,
tooltip = "Buy only at or below the range equilibrium (discount), Sell only at or above it (premium). Improves price location but removes many continuation entries.")
pdLen = input.int(100, "Premium/Discount Range Bars", minval = 10, maxval = 1000, group = G_FIX,
tooltip = "Lookback used to build the high-low range whose midpoint is the equilibrium. Higher = broader range, slower to change.")
cooldown = input.int(5, "Signal Cooldown (bars)", minval = 0, maxval = 200, group = G_FIX,
tooltip = "Minimum bars between two main signals to avoid clusters of repeated arrows. 0 disables. Higher = fewer, more spaced signals.")
resetShift = input.bool(true, "Reset Position on Opposite CHoCH", group = G_FIX,
tooltip = "If on, an opposite Change of Character closes the tracked side and resets pyramid counters, so stale positions are not added to.")
// Pyramid inputs
pyrOn = input.bool(true, "Enable Pyramid", group = G_PYR,
tooltip = "Allows extra orders on the same side after the first signal, while structure bias still agrees.")
pyrMax = input.int(3, "Max Orders Per Side", minval = 1, maxval = 10, group = G_PYR,
tooltip = "Total orders per side including the first one. Higher = bigger potential position and risk; 1 = no adds.")
pyrDir = input.string("With Trend", "Add Direction", options = ["With Trend", "Against Trend (Average)"], group = G_PYR,
tooltip = "With Trend: add when price moves in profit by the spacing. Against Trend: add when price moves against the last order by the spacing (averaging).")
spMode = input.string("ATR", "Spacing Mode", options = ["Ticks", "ATR"], group = G_PYR,
tooltip = "How the distance between pyramid orders is measured: fixed number of ticks or a multiple of ATR (adapts to volatility).")
spTicks = input.int(100, "Spacing (Ticks)", minval = 1, maxval = 100000, group = G_PYR,
tooltip = "Distance in minimum ticks from the last order before the next add (Ticks mode). Higher = fewer, wider-spaced adds.")
spAtrLen = input.int(14, "Spacing ATR Length", minval = 1, maxval = 200, group = G_PYR,
tooltip = "ATR period used for spacing in ATR mode. Higher = steadier spacing; lower = spacing reacts quickly to volatility.")
spAtrMult = input.float(1.0, "Spacing ATR Multiplier", minval = 0.1, maxval = 10.0, step = 0.1, group = G_PYR,
tooltip = "Spacing = ATR x this value (ATR mode). Higher = wider gaps between adds and fewer adds.")
// Visual inputs
showOB = input.bool(true, "Show Order Blocks", group = G_VIS,
tooltip = "Draws the active tradable Order Block zones as boxes until they are used, invalidated or expire.")
showStr = input.bool(true, "Show BOS / CHoCH", group = G_VIS,
tooltip = "Draws a line and label at each confirmed structure break: CHoCH (solid) for reversals, BOS (dashed) for continuation.")
showLbl = input.bool(true, "Show Order Labels (B1/S1...)", group = G_VIS,
tooltip = "Prints numbered labels for every order: B1, B2... for Buys and S1, S2... for Sells, so pyramid adds are easy to count.")
showEma = input.bool(true, "Show HTF EMA", group = G_VIS,
tooltip = "Plots the higher-timeframe trend EMA used by the HTF filter.")
bullCol = input.color(#089981, "Bullish Color", group = G_VIS,
tooltip = "Color for bullish structure, bullish Order Blocks and Buy orders.")
bearCol = input.color(#F23645, "Bearish Color", group = G_VIS,
tooltip = "Color for bearish structure, bearish Order Blocks and Sell orders.")
//==================================================================================================
// CORE SERIES
//==================================================================================================
atr = ta.atr(atrLen)
spAtr = ta.atr(spAtrLen)
// FIX: repaint - act only on closed bars when enabled
confBar = useConfirm ? barstate.isconfirmed : true
body = math.abs(close - open)
rng = high - low
// FIX: HTF lookahead/repaint - previous closed HTF bar value with lookahead_off
htfEma = request.security(syminfo.tickerid, htfTf, ta.ema(close, htfLen)[1], lookahead = barmerge.lookahead_off)
[diPlus, diMinus, adx] = ta.dmi(adxLen, adxLen)
pdHigh = ta.highest(high, pdLen)
pdLow = ta.lowest(low, pdLen)
pdEq = math.avg(pdHigh, pdLow)
// Confirmed pivots (new mechanism vs. original leg detection): fixed, non-repainting swing levels
ph = ta.pivothigh(high, swingLen, swingLen)
pl = ta.pivotlow(low, swingLen, swingLen)
// Last opposite candle search (called every bar for consistency)
findOB(bool bullish) =>
float t = na
float b = na
int idx = na
for i = 1 to obLookback
bool isOpp = bullish ? close[i] < open[i] : close[i] > open[i]
if isOpp
t := high[i]
b := low[i]
idx := bar_index - i
break
[t, b, idx]
[bullT, bullB, bullI] = findOB(true)
[bearT, bearB, bearI] = findOB(false)
//==================================================================================================
// STRUCTURE STATE
//==================================================================================================
var float swHigh = na
var int swHighBar = na
var bool swHighCrossed = true
var float swLow = na
var int swLowBar = na
var bool swLowCrossed = true
var int bias = 0
if not na(ph)
swHigh := ph
swHighBar := bar_index - swingLen
swHighCrossed := false
if not na(pl)
swLow := pl
swLowBar := bar_index - swingLen
swLowCrossed := false
structBull = confBar and not na(swHigh) and not swHighCrossed and close > swHigh
structBear = confBar and not na(swLow) and not swLowCrossed and close < swLow and not structBull
bool bullChoch = false
bool bearChoch = false
if structBull
bullChoch := bias == -1
swHighCrossed := true
bias := 1
if showStr
line.new(swHighBar, swHigh, bar_index, swHigh, color = bullCol, style = bullChoch ? line.style_solid : line.style_dashed)
label.new(math.round((swHighBar + bar_index) / 2), swHigh, bullChoch ? "CHoCH" : "BOS", color = color(na), textcolor = bullCol, style = label.style_label_down, size = size.tiny)
if structBear
bearChoch := bias == 1
swLowCrossed := true
bias := -1
if showStr
line.new(swLowBar, swLow, bar_index, swLow, color = bearCol, style = bearChoch ? line.style_solid : line.style_dashed)
label.new(math.round((swLowBar + bar_index) / 2), swLow, bearChoch ? "CHoCH" : "BOS", color = color(na), textcolor = bearCol, style = label.style_label_up, size = size.tiny)
//==================================================================================================
// ORDER BLOCK STATE
//==================================================================================================
var float bullObTop = na
var float bullObBot = na
var int bullObBar = na
var bool bullObLive = false
var box bullObBox = na
var float bearObTop = na
var float bearObBot = na
var int bearObBar = na
var bool bearObLive = false
var box bearObBox = na
// FIX: displacement filter - weak breaks update bias but do not create tradable zones
dispOk = not dispOn or body >= dispMult * atr
killBull() =>
if not na(bullObBox)
box.set_right(bullObBox, bar_index)
box.set_bgcolor(bullObBox, color.new(bullCol, 92))
killBear() =>
if not na(bearObBox)
box.set_right(bearObBox, bar_index)
box.set_bgcolor(bearObBox, color.new(bearCol, 92))
// Opposite shift kills the other side's zone
if structBear and bullObLive
killBull()
bullObLive := false
if structBull and bearObLive
killBear()
bearObLive := false
if structBull and dispOk and (not chochOnly or bullChoch) and not na(bullT)
h = bullT - bullB
// FIX: zone size filter (too thin = noise, too wide = spike)
if h >= obMinAtr * atr and h <= obMaxAtr * atr
if bullObLive
killBull()
bullObTop := bullT
bullObBot := bullB
bullObBar := bar_index
bullObLive := true
if showOB
bullObBox := box.new(bullI, bullT, bar_index, bullB, border_color = bullCol, bgcolor = color.new(bullCol, 80))
if structBear and dispOk and (not chochOnly or bearChoch) and not na(bearT)
h = bearT - bearB
if h >= obMinAtr * atr and h <= obMaxAtr * atr
if bearObLive
killBear()
bearObTop := bearT
bearObBot := bearB
bearObBar := bar_index
bearObLive := true
if showOB
bearObBox := box.new(bearI, bearT, bar_index, bearB, border_color = bearCol, bgcolor = color.new(bearCol, 80))
// Invalidation / expiry (not on the creation bar)
if bullObLive and confBar and bar_index > bullObBar
if close < bullObBot or bar_index - bullObBar > obMaxAge
killBull()
bullObLive := false
if bearObLive and confBar and bar_index > bearObBar
if close > bearObTop or bar_index - bearObBar > obMaxAge
killBear()
bearObLive := false
if bullObLive and not na(bullObBox)
box.set_right(bullObBox, bar_index)
if bearObLive and not na(bearObBox)
box.set_right(bearObBox, bar_index)
//==================================================================================================
// ENTRY CONDITIONS
//==================================================================================================
bullRetest = bullObLive and bar_index > bullObBar and low <= bullObTop and close > bullObBot
bearRetest = bearObLive and bar_index > bearObBar and high >= bearObBot and close < bearObTop
bullRej = not useRej or (close > open and rng > 0 and (close - low) / rng >= rejRatio)
bearRej = not useRej or (close < open and rng > 0 and (high - close) / rng >= rejRatio)
// FIX: trend filter (HTF EMA), FIX: sideway filter (ADX), FIX: location filter (premium/discount)
trendUp = not useHtf or close > htfEma
trendDn = not useHtf or close < htfEma
adxOk = not useAdx or adx >= adxMin
pdBuy = not usePD or close <= pdEq
pdSell = not usePD or close >= pdEq
// FIX: duplicate signals - cooldown + one entry per Order Block (zone consumed on entry)
var int lastSigBar = na
coolOk = na(lastSigBar) or bar_index - lastSigBar >= cooldown
//==================================================================================================
// POSITION / PYRAMID STATE
//==================================================================================================
var int posSide = 0
var int buyCount = 0
var int sellCount = 0
var float lastBuyPrice = na
var float lastSellPrice = na
// FIX: stale position - opposite CHoCH resets tracked side
if resetShift and bearChoch and posSide == 1
posSide := 0
buyCount := 0
lastBuyPrice := na
if resetShift and bullChoch and posSide == -1
posSide := 0
sellCount := 0
lastSellPrice := na
buySignal = confBar and bullRetest and bullRej and trendUp and adxOk and pdBuy and coolOk and posSide != 1
sellSignal = confBar and bearRetest and bearRej and trendDn and adxOk and pdSell and coolOk and posSide != -1 and not buySignal
if buySignal
posSide := 1
buyCount := 1
lastBuyPrice := close
sellCount := 0
lastSellPrice := na
lastSigBar := bar_index
killBull()
bullObLive := false
if sellSignal
posSide := -1
sellCount := 1
lastSellPrice := close
buyCount := 0
lastBuyPrice := na
lastSigBar := bar_index
killBear()
bearObLive := false
// Pyramid spacing
spacing = spMode == "Ticks" ? spTicks * syminfo.mintick : spAtr * spAtrMult
// Pyramid rules:
// With Trend -> Buy add when close >= last Buy price + spacing; Sell add when close <= last Sell price - spacing.
// Against Trend (Avg) -> Buy add when close <= last Buy price - spacing; Sell add when close >= last Sell price + spacing.
// Adds require the structure bias to still agree with the side, and stay below Max Orders Per Side.
buyDistOk = pyrDir == "With Trend" ? close >= lastBuyPrice + spacing : close <= lastBuyPrice - spacing
sellDistOk = pyrDir == "With Trend" ? close <= lastSellPrice - spacing : close >= lastSellPrice + spacing
pyrBuy = pyrOn and confBar and not buySignal and posSide == 1 and bias == 1 and buyCount < pyrMax and not na(lastBuyPrice) and buyDistOk
pyrSell = pyrOn and confBar and not sellSignal and posSide == -1 and bias == -1 and sellCount < pyrMax and not na(lastSellPrice) and sellDistOk
if pyrBuy
buyCount := buyCount + 1
lastBuyPrice := close
if pyrSell
sellCount := sellCount + 1
lastSellPrice := close
//==================================================================================================
// PLOTS
//==================================================================================================
plot(showEma and useHtf ? htfEma : na, "HTF EMA", color = color.new(color.orange, 0), linewidth = 2)
plotshape(buySignal, "Buy", shape.triangleup, location.belowbar, bullCol, size = size.small)
plotshape(sellSignal, "Sell", shape.triangledown, location.abovebar, bearCol, size = size.small)
plotshape(pyrBuy, "Pyramid Buy", shape.circle, location.belowbar, color.new(bullCol, 30), size = size.tiny)
plotshape(pyrSell, "Pyramid Sell", shape.circle, location.abovebar, color.new(bearCol, 30), size = size.tiny)
if showLbl and (buySignal or pyrBuy)
label.new(bar_index, low - atr * 1.2, "B" + str.tostring(buyCount), color = bullCol, textcolor = color.white, style = label.style_label_up, size = size.small)
if showLbl and (sellSignal or pyrSell)
label.new(bar_index, high + atr * 1.2, "S" + str.tostring(sellCount), color = bearCol, textcolor = color.white, style = label.style_label_down, size = size.small)
//==================================================================================================
// ALERTS
//==================================================================================================
alertcondition(buySignal, "Buy", "DB-OBR: Buy - bullish Order Block retest")
alertcondition(sellSignal, "Sell", "DB-OBR: Sell - bearish Order Block retest")
alertcondition(pyrBuy, "Pyramid Buy", "DB-OBR: Pyramid Buy add")
alertcondition(pyrSell, "Pyramid Sell", "DB-OBR: Pyramid Sell add")