本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Quantum-Edge-Capital
//@version=6
indicator("Structure Edge - BOS/CHOCH + Order Blocks [Fixed v1.1]", shorttitle="QE Structure Edge", overlay=true, max_lines_count=200, max_labels_count=200, max_boxes_count=100, max_bars_back=500)
// ===================== INPUTS =====================
grpStruct = "Market Structure"
pivotLen = input.int(5, "Pivot Lookback (L/R)", minval=2, maxval=20, group=grpStruct)
grpBand = "Trend Band"
wmaLen = input.int(20, "WMA Basis Length", minval=5, group=grpBand)
atrLen = input.int(14, "ATR Length", minval=5, group=grpBand)
atrMult = input.float(1.5, "ATR Envelope Multiplier", minval=0.5, step=0.1, group=grpBand)
grpScore = "Setup Score"
minScoreShow = input.float(5.0, "Min Score To Mark Setup", minval=0.0, maxval=10.0, step=0.5, group=grpScore)
grpFilt = "Signal Filters"
useHTFFilter = input.bool(true, "Require HTF Structure Alignment", group=grpFilt)
htfRes = input.timeframe("60", "Higher Timeframe", group=grpFilt)
minStrengthReq = input.float(4.0, "Min Trend Strength (0-10)", minval=0, maxval=10, group=grpFilt)
volFilterOn = input.bool(false, "Require Volatility In Range", group=grpFilt)
volMin = input.float(2.0, "Min Volatility Score", minval=0, maxval=10, group=grpFilt)
volMax = input.float(8.0, "Max Volatility Score", minval=0, maxval=10, group=grpFilt)
grpOB = "Order Blocks"
showOB = input.bool(true, "Show Order Blocks", group=grpOB)
obMaxBox = input.int(6, "Max Boxes Per Side", minval=1, maxval=20, group=grpOB)
obExtend = input.int(40, "Box Forward Extend (bars)", minval=5, maxval=200, group=grpOB)
maxChochObjects = input.int(35, "Max CHOCH Reference Lines", minval=1, maxval=80, group=grpOB)
grpVis = "Visuals"
colBull = input.color(color.new(#1fc989, 0), "Bullish Color", group=grpVis)
colBear = input.color(color.new(#ff4d6d, 0), "Bearish Color", group=grpVis)
colReactUp = input.color(color.new(#ff9f43, 0), "Reaction Up (orange)", group=grpVis)
colReactDn = input.color(color.new(#a66bff, 0), "Reaction Down (purple)", group=grpVis)
colBandFill = input.color(color.new(#4f8cff, 85), "Band Fill", group=grpVis)
showDash = input.bool(true, "Show Dashboard", group=grpVis)
showCandles = input.bool(true, "Recolor Candles By Structure", group=grpVis)
// ===================== PIVOTS / STRUCTURE =====================
ph = ta.pivothigh(high, pivotLen, pivotLen)
pl = ta.pivotlow(low, pivotLen, pivotLen)
var float lastSwingHigh = na
var float lastSwingLow = na
var int lastSwingHighBar = na
var int lastSwingLowBar = na
if barstate.isconfirmed and not na(ph)
lastSwingHigh := ph
lastSwingHighBar := bar_index - pivotLen
if barstate.isconfirmed and not na(pl)
lastSwingLow := pl
lastSwingLowBar := bar_index - pivotLen
var int structState = 0
var int trendAge = 0
var float chochLevel = na
var int chochBar = na
var float lastBrokenLevel = na
var float heldStructQuality = 0.0
isBOS = false
isCHOCH = false
var bool highBroken = true
var bool lowBroken = true
if barstate.isconfirmed and not na(ph)
highBroken := false
if barstate.isconfirmed and not na(pl)
lowBroken := false
if barstate.isconfirmed and not na(lastSwingHigh) and not highBroken and close > lastSwingHigh
highBroken := true
lastBrokenLevel := lastSwingHigh
if structState <= 0
isCHOCH := true
chochLevel := lastSwingLow
chochBar := lastSwingLowBar
structState := 1
trendAge := 0
else
isBOS := true
trendAge += 1
if barstate.isconfirmed and not na(lastSwingLow) and not lowBroken and close < lastSwingLow
lowBroken := true
lastBrokenLevel := lastSwingLow
if structState >= 0
isCHOCH := true
chochLevel := lastSwingHigh
chochBar := lastSwingHighBar
structState := -1
trendAge := 0
else
isBOS := true
trendAge += 1
if not isBOS and not isCHOCH
trendAge += 1
// ===================== TREND BAND =====================
basis = ta.wma(close, wmaLen)
atrV = ta.atr(atrLen)
upperBand = basis + atrV * atrMult
lowerBand = basis - atrV * atrMult
activeBand = structState == 1 ? lowerBand : structState == -1 ? upperBand : basis
bandTouchTol = atrV * 0.25
nearBand = math.abs(close - activeBand) <= bandTouchTol
bandUpperPlot = plot(upperBand, "Upper Band", color=color.new(colBear, 60), linewidth=1)
bandLowerPlot = plot(lowerBand, "Lower Band", color=color.new(colBull, 60), linewidth=1)
fill(bandUpperPlot, bandLowerPlot, color=colBandFill, title="Band Fill")
plot(basis, "WMA Basis", color=color.new(color.gray, 30), linewidth=1)
// ===================== VOLATILITY SCORE (0-10) =====================
atrPct = atrV / close * 100
var float atrPctHigh = na
var float atrPctLow = na
atrPctHigh := na(atrPctHigh) ? atrPct : math.max(atrPctHigh * 0.999, atrPct)
atrPctLow := na(atrPctLow) ? atrPct : math.min(atrPctLow * 1.001, atrPct)
volRange = atrPctHigh - atrPctLow
volScore = volRange > 0 ? math.min(10.0, math.max(0.0, (atrPct - atrPctLow) / volRange * 10.0)) : 5.0
// ===================== CANDLE STRENGTH =====================
rng = high - low
body = math.abs(close - open)
bodyPct = rng > 0 ? body / rng : 0.0
upWick = high - math.max(close, open)
dnWick = math.min(close, open) - low
bullReject = rng > 0 and dnWick / rng >= 0.3 and close > open
bearReject = rng > 0 and upWick / rng >= 0.3 and close < open
candleStrength = 0.0
if structState == 1
candleStrength := (bodyPct * 6.0) + (bullReject ? 4.0 : 0.0)
if structState == -1
candleStrength := (bodyPct * 6.0) + (bearReject ? 4.0 : 0.0)
candleStrength := math.min(10.0, candleStrength)
// ===================== HTF ALIGNMENT (non-repainting) =====================
// Strictly higher timeframe required when the HTF filter is enabled.
htfValid = timeframe.in_seconds(htfRes) > timeframe.in_seconds(timeframe.period)
[htfCloseC1, htfBasisC1] = request.security(syminfo.tickerid, htfRes, [close[1], ta.wma(close, wmaLen)[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
htfBull = htfCloseC1 > htfBasisC1
htfBear = htfCloseC1 < htfBasisC1
htfAligned = htfValid and (structState == 1 ? htfBull : structState == -1 ? htfBear : false)
// ===================== STRUCTURE QUALITY / RISK EFFICIENCY =====================
breakDist = (isCHOCH or isBOS) and not na(lastBrokenLevel) ? math.abs(close - lastBrokenLevel) : 0.0
if isCHOCH or isBOS
heldStructQuality := atrV > 0 ? math.min(10.0, breakDist / atrV * 10.0) : 0.0
structQuality = heldStructQuality
stopRef = structState == 1 ? lastSwingLow : lastSwingHigh
// Structural stop must be on the invalidation side; never reward an invalid stop.
stopValid = not na(stopRef) and (structState == 1 ? stopRef < close : structState == -1 ? stopRef > close : false)
riskDist = stopValid ? math.abs(close - stopRef) : na
riskEff = na(riskDist) or riskDist <= 0 ? 0.0 : math.min(10.0, atrV / riskDist * 10.0)
locationScore = nearBand ? 10.0 : math.max(0.0, 10.0 - math.abs(close - activeBand) / (atrV > 0 ? atrV * 2 : 1.0) * 10.0)
alignmentScore = useHTFFilter ? (htfAligned ? 10.0 : 0.0) : 7.0
setupScore = (alignmentScore * 0.25) + (locationScore * 0.2) + (structQuality * 0.2) + (candleStrength * 0.2) + (riskEff * 0.15)
setupScore := math.min(10.0, math.max(0.0, setupScore))
var float initialSignalScore = na
// ===================== FILTERS =====================
trendStrength = math.min(10.0, structQuality)
passFilters = true
if useHTFFilter
passFilters := passFilters and htfValid and htfAligned
if minStrengthReq > 0
passFilters := passFilters and trendStrength >= minStrengthReq
if volFilterOn
passFilters := passFilters and volScore >= volMin and volScore <= volMax
if isCHOCH
initialSignalScore := na
buySignal = barstate.isconfirmed and isCHOCH and structState == 1 and passFilters and setupScore >= minScoreShow
sellSignal = barstate.isconfirmed and isCHOCH and structState == -1 and passFilters and setupScore >= minScoreShow
if buySignal or sellSignal
initialSignalScore := setupScore
scoreDelta = na(initialSignalScore) ? 0.0 : setupScore - initialSignalScore
// Alert only on the first confirmed return into the band to avoid repeated alerts.
contUp = barstate.isconfirmed and structState == 1 and nearBand and not nearBand[1] and not isCHOCH and not isBOS and setupScore >= minScoreShow
contDn = barstate.isconfirmed and structState == -1 and nearBand and not nearBand[1] and not isCHOCH and not isBOS and setupScore >= minScoreShow
// ===================== CANDLE COLORING =====================
candleColor = structState == 1 ? colBull : structState == -1 ? colBear : color.gray
if nearBand and structState != 0
candleColor := structState == 1 ? colReactUp : colReactDn
barcolor(showCandles ? candleColor : na, title="Structure Candles")
// ===================== CHOCH REVERSAL REFERENCE =====================
// Use bounded drawing arrays so older CHOCH references cannot exhaust chart limits.
var line[] chochLines = array.new_line()
var label[] chochLabels = array.new_label()
if isCHOCH and not na(chochLevel) and not na(chochBar) and barstate.isconfirmed
color lineColor = structState == 1 ? colBull : colBear
line ln = line.new(x1=chochBar, y1=chochLevel, x2=bar_index, y2=chochLevel, xloc=xloc.bar_index, extend=extend.right, color=lineColor, width=1, style=line.style_dashed)
label lb = label.new(x=chochBar, y=chochLevel, text="CHOCH", xloc=xloc.bar_index, color=lineColor, style=structState == 1 ? label.style_label_up : label.style_label_down, textcolor=color.white, size=size.tiny)
array.push(chochLines, ln)
array.push(chochLabels, lb)
if array.size(chochLines) > maxChochObjects
line.delete(array.shift(chochLines))
if array.size(chochLabels) > maxChochObjects
label.delete(array.shift(chochLabels))
// ===================== SIGNALS =====================
plotshape(buySignal, title="BUY", style=shape.labelup, location=location.belowbar, color=colBull, textcolor=color.white, text="BUY", size=size.small)
plotshape(sellSignal, title="SELL", style=shape.labeldown, location=location.abovebar, color=colBear, textcolor=color.white, text="SELL", size=size.small)
plotshape(isBOS and structState == 1, title="Bull BOS", style=shape.circle, location=location.belowbar, color=color.new(colBull, 40), size=size.tiny)
plotshape(isBOS and structState == -1, title="Bear BOS", style=shape.circle, location=location.abovebar, color=color.new(colBear, 40), size=size.tiny)
plotshape(contUp, title="Continuation Up", style=shape.triangleup, location=location.belowbar, color=colReactUp, size=size.tiny)
plotshape(contDn, title="Continuation Down", style=shape.triangledown, location=location.abovebar, color=colReactDn, size=size.tiny)
alertcondition(buySignal, "Bullish CHOCH Buy Signal", "Structure shifted bullish, setup score at threshold or above")
alertcondition(sellSignal, "Bearish CHOCH Sell Signal", "Structure shifted bearish, setup score at threshold or above")
alertcondition(contUp, "Bullish Continuation", "Price reacting to trend band in bullish structure")
alertcondition(contDn, "Bearish Continuation", "Price reacting to trend band in bearish structure")
// ===================== ORDER BLOCKS =====================
// OB = most recent opposite candle before a confirmed CHOCH (a heuristic,
// not a verified institutional order-block identification algorithm).
var box[] bullBoxes = array.new_box()
var box[] bearBoxes = array.new_box()
findLastOppositeBar(bool wantBearishCandle) =>
int foundOffset = na
for i = 1 to 50
if i > bar_index
break
bool isBearCandle = close[i] < open[i]
bool isBullCandle = close[i] > open[i]
if (wantBearishCandle and isBearCandle) or (not wantBearishCandle and isBullCandle)
foundOffset := i
break
foundOffset
if showOB and barstate.isconfirmed and isCHOCH and structState == 1
int offs = findLastOppositeBar(true)
if not na(offs)
float obHigh = math.max(open[offs], close[offs])
float obLow = math.min(open[offs], close[offs])
if obHigh > obLow
float relStrength = atrV > 0 ? (obHigh - obLow) / atrV : 0.0
box bx = box.new(left=bar_index - offs, top=obHigh, right=bar_index + obExtend, bottom=obLow, xloc=xloc.bar_index, border_color=colBull, bgcolor=color.new(colBull, 85), text="OB " + str.tostring(relStrength, "#.##") + "x ATR", text_color=colBull, text_size=size.tiny)
array.push(bullBoxes, bx)
if array.size(bullBoxes) > obMaxBox
box.delete(array.shift(bullBoxes))
if showOB and barstate.isconfirmed and isCHOCH and structState == -1
int offs2 = findLastOppositeBar(false)
if not na(offs2)
float obHigh2 = math.max(open[offs2], close[offs2])
float obLow2 = math.min(open[offs2], close[offs2])
if obHigh2 > obLow2
float relStrength2 = atrV > 0 ? (obHigh2 - obLow2) / atrV : 0.0
box bx2 = box.new(left=bar_index - offs2, top=obHigh2, right=bar_index + obExtend, bottom=obLow2, xloc=xloc.bar_index, border_color=colBear, bgcolor=color.new(colBear, 85), text="OB " + str.tostring(relStrength2, "#.##") + "x ATR", text_color=colBear, text_size=size.tiny)
array.push(bearBoxes, bx2)
if array.size(bearBoxes) > obMaxBox
box.delete(array.shift(bearBoxes))
// Delete invalidated boxes. Pine for-loops count down automatically when the
// initial counter is greater than the final counter.
if showOB and array.size(bullBoxes) > 0
for i = array.size(bullBoxes) - 1 to 0
box bbx = array.get(bullBoxes, i)
if close < box.get_bottom(bbx)
box.delete(bbx)
array.remove(bullBoxes, i)
if showOB and array.size(bearBoxes) > 0
for i = array.size(bearBoxes) - 1 to 0
box bbx2 = array.get(bearBoxes, i)
if close > box.get_top(bbx2)
box.delete(bbx2)
array.remove(bearBoxes, i)
// ===================== SESSION CONTEXT =====================
sessionLabel = session.ismarket ? "RTH" : "Off-Hours"
// ===================== DASHBOARD =====================
var table dash = table.new(position.top_right, 2, 8, border_width=1)
if showDash and barstate.islast
table.cell(dash, 0, 0, "Structure", text_color=color.white, bgcolor=color.new(color.gray, 70))
table.cell(dash, 1, 0, structState == 1 ? "Bullish" : structState == -1 ? "Bearish" : "Undefined", text_color=structState == 1 ? colBull : structState == -1 ? colBear : color.gray, bgcolor=color.new(color.gray, 85))
table.cell(dash, 0, 1, "Trend Age (bars)", text_color=color.white, bgcolor=color.new(color.gray, 70))
table.cell(dash, 1, 1, str.tostring(trendAge), text_color=color.white, bgcolor=color.new(color.gray, 85))
table.cell(dash, 0, 2, "Strength (0-10)", text_color=color.white, bgcolor=color.new(color.gray, 70))
table.cell(dash, 1, 2, str.tostring(trendStrength, "#.#"), text_color=color.white, bgcolor=color.new(color.gray, 85))
table.cell(dash, 0, 3, "Volatility (0-10)", text_color=color.white, bgcolor=color.new(color.gray, 70))
table.cell(dash, 1, 3, str.tostring(volScore, "#.#"), text_color=color.white, bgcolor=color.new(color.gray, 85))
table.cell(dash, 0, 4, "Session", text_color=color.white, bgcolor=color.new(color.gray, 70))
table.cell(dash, 1, 4, sessionLabel, text_color=color.white, bgcolor=color.new(color.gray, 85))
table.cell(dash, 0, 5, "HTF Aligned", text_color=color.white, bgcolor=color.new(color.gray, 70))
table.cell(dash, 1, 5, not htfValid ? "INVALID HTF" : (htfAligned ? "Yes" : "No"), text_color=not htfValid ? color.orange : (htfAligned ? colBull : colBear), bgcolor=color.new(color.gray, 85))
table.cell(dash, 0, 6, "Setup Score", text_color=color.white, bgcolor=color.new(color.gray, 70))
table.cell(dash, 1, 6, str.tostring(setupScore, "#.#") + " /10", text_color=setupScore >= minScoreShow ? colBull : color.white, bgcolor=color.new(color.gray, 85))
table.cell(dash, 0, 7, "Score Chg vs Signal", text_color=color.white, bgcolor=color.new(color.gray, 70))
table.cell(dash, 1, 7, na(initialSignalScore) ? "n/a" : str.tostring(scoreDelta, "#.#"), text_color=scoreDelta > 0 ? colBull : scoreDelta < 0 ? colBear : color.white, bgcolor=color.new(color.gray, 85))