本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman {
//@version=6
indicator("Ranked Order Block Zones (Zeiierman)", overlay = true, max_boxes_count = 300)
//}
// ~~ Tooltips {
t1 = "Controls how many of the highest-quality Order Block zones are visible on the chart."
t2 = "Maximum number of Order Block zones stored internally before the lowest-quality zones are removed."
t3 = "Length used to calculate the average volume baseline. The OB volume score compares source candle volume against this average."
t4 = "EMA length used to define trend alignment. Bullish OBs above the EMA and bearish OBs below the EMA receive stronger trend scores."
t5 = "Shows or hides the internal bullish and bearish strength bars inside each Order Block zone."
t6 = "Shows or hides the text label inside each Order Block zone."
t7 = "Color used for bullish Order Block zones."
t8 = "Color used for bearish Order Block zones."
t9 = "When enabled, the Order Block zone uses only the candle body. When disabled, the full candle wick range is used."
t10 = "Optional directional filter for visible Order Blocks."
t11 = "Controls the text size used for the strength percentage labels."
t12 = "Controls the text size used for the Order Block text."
t13 = "When enabled, overlapping Order Blocks of the same direction can be merged into one zone."
t14 = "Maximum allowed merged OB height measured in ATR. Prevents overlapping zones from becoming one giant block."
t15 = "Minimum required body size of the flip candle, measured in ATR. This keeps the simple OB logic adaptive across tickers and timeframes."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Inputs {
gRanking = "Ranking"
gStrength = "Strength Engine"
gDetection = "Order Block Detection"
gDisplay = "Display"
gColors = "Colors"
gAlerts = "Alerts"
maxZones = input.int(10, "Show Top Zones", minval = 1, maxval = 20, tooltip = t1, group = gRanking)
maxStored = input.int(50, "Max Stored OBs", minval = 10, maxval = 200, tooltip = t2, group = gRanking)
volLength = input.int(20, "Volume MA Length", minval = 1, tooltip = t3, group = gStrength)
trendLength = input.int(50, "Trend EMA Length", minval = 1, tooltip = t4, group = gStrength)
minFlipBodyAtr = input.float(1.1, "Min Flip Body ATR", minval = 0.05, step = 0.05, tooltip = t15, group = gDetection)
mergeOverlaps = input.bool(true, "Merge Overlapping OBs", tooltip = t13, group = gDetection)
maxMergeAtr = input.float(2.0, "Max Merge Size ATR", minval = 0.5, step = 0.5, tooltip = t14, group = gDetection)
directionFilter = input.string("All", "Direction Filter", options = ["All", "Bullish Only", "Bearish Only"], tooltip = t10, group = gDisplay)
showBars = input.bool(true, "Show Strength Bars", tooltip = t5, group = gDisplay)
showBlockText = input.bool(true, "Show OB Text", tooltip = t6, group = gDisplay)
strengthTextSize = input.string("auto", "Strength Text Size", options = ["auto", "tiny", "small", "normal", "large", "huge"], tooltip = t11, group = gDisplay)
blockTextSize = input.string("auto", "Block Text Size", options = ["auto", "tiny", "small", "normal", "large", "huge"], tooltip = t12, group = gDisplay)
bullColor = input.color(color.rgb(8, 153, 129, 48), "Bullish OB", inline = "colors", tooltip = t7, group = gColors)
bearColor = input.color(color.rgb(242, 54, 69, 48), "Bearish OB", inline = "colors", tooltip = t8, group = gColors)
alertNewBull = input.bool(true, "New Bullish OB", group = gAlerts)
alertNewBear = input.bool(true, "New Bearish OB", group = gAlerts)
alertTopRank = input.bool(true, "New Top-Ranked OB", group = gAlerts)
alertBullTouch = input.bool(true, "Bullish OB Touch", group = gAlerts)
alertBearTouch = input.bool(true, "Bearish OB Touch", group = gAlerts)
alertFullyMitigated = input.bool(true, "OB Fully Mitigated", group = gAlerts)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ UDT {
type OB
float qualityScore
float top
float bottom
int direction
int bornBar
int leftTime
float size
float mitigation
float volumeScore
float trendScore
int bullStrength
int bearStrength
box body
box bullBar
box bearBar
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Helpers {
volumeMA = ta.sma(volume, volLength)
trendEMA = ta.ema(close, trendLength)
atrValue = ta.atr(14)
barMs = timeframe.in_seconds(timeframe.period) * 1000
method isVisibleDirection(OB ob) =>
directionFilter == "All" or directionFilter == "Bullish Only" and ob.direction == 1 or directionFilter == "Bearish Only" and ob.direction == -1
method overlapsWith(OB ob, float newTop, float newBottom, int newDirection) =>
float overlapTop = math.min(ob.top, newTop)
float overlapBottom = math.max(ob.bottom, newBottom)
float overlapSize = math.max(overlapTop - overlapBottom, 0)
float existingSize = math.max(ob.top - ob.bottom, syminfo.mintick)
float newSize = math.max(newTop - newBottom, syminfo.mintick)
float smallestSize = math.min(existingSize, newSize)
float mergedTop = math.max(ob.top, newTop)
float mergedBottom = math.min(ob.bottom, newBottom)
float mergedSize = mergedTop - mergedBottom
bool sameDirection = ob.direction == newDirection
bool hasOverlap = overlapSize > 0
bool meaningfulOverlap = overlapSize / smallestSize >= 0.50
bool mergeNotTooLarge = mergedSize <= atrValue * maxMergeAtr
sameDirection and hasOverlap and meaningfulOverlap and mergeNotTooLarge
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Simple Candle Flip + ATR Body OB Logic {
flipBodySize = math.abs(close - open)
validFlipBody = flipBodySize >= atrValue * minFlipBodyAtr
bullishOB = close[1] < open[1] and close > open and validFlipBody
bearishOB = close[1] > open[1] and close < open and validFlipBody
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables {
var array<OB> obs = array.new<OB>()
var string topObKey = ""
newBullObAlert = false
newBearObAlert = false
newTopRankAlert = false
bullTouchAlert = false
bearTouchAlert = false
fullyMitigatedAlert = false
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Create Order Blocks {
if bullishOB or bearishOB
int direction = bullishOB ? 1 : -1
float top = na
float bottom = na
if direction == 1
top := high[1]
bottom := low[1]
else
top := high[1]
bottom := low[1]
float obSize = math.abs(top - bottom)
float volScore = volumeMA != 0 ? volume[1] / volumeMA : 1.0
float trendScore = direction == 1 and close > trendEMA ? 1.0 : direction == -1 and close < trendEMA ? 1.0 : 0.0
float mitigation = 0.0
float qualityScore = obSize * 100 + volScore * 10 + trendScore * 20 - mitigation * 50
float sizeStrength = math.min(obSize / atrValue, 2.0) / 2.0 * 40
float volStrength = math.min(volScore, 2.0) / 2.0 * 30
float trendStrength = trendScore * 20
float candleStrength = math.abs(close[1] - open[1]) / math.max(high[1] - low[1], syminfo.mintick) * 10
float totalStrength = sizeStrength + volStrength + trendStrength + candleStrength
int mainStrength = int(math.max(math.min(totalStrength, 100), 0))
int bullStrength = direction == 1 ? mainStrength : 100 - mainStrength
int bearStrength = direction == -1 ? mainStrength : 100 - mainStrength
newBullObAlert := direction == 1
newBearObAlert := direction == -1
bool merged = false
if mergeOverlaps and obs.size() > 0
for i = 0 to obs.size() - 1
OB existing = obs.get(i)
if existing.overlapsWith(top, bottom, direction) and not merged
existing.top := math.max(existing.top, top)
existing.bottom := math.min(existing.bottom, bottom)
existing.size := math.abs(existing.top - existing.bottom)
existing.qualityScore := math.max(existing.qualityScore, qualityScore)
existing.volumeScore := math.max(existing.volumeScore, volScore)
existing.trendScore := math.max(existing.trendScore, trendScore)
existing.mitigation := 0.0
existing.bullStrength := math.max(existing.bullStrength, bullStrength)
existing.bearStrength := math.max(existing.bearStrength, bearStrength)
float mergedMid = math.avg(existing.top, existing.bottom)
box.set_top(existing.body, existing.top)
box.set_bottom(existing.body, existing.bottom)
box.set_top(existing.bearBar, existing.top)
box.set_bottom(existing.bearBar, mergedMid)
box.set_top(existing.bullBar, mergedMid)
box.set_bottom(existing.bullBar, existing.bottom)
obs.set(i, existing)
merged := true
if not merged
color bodyColor = direction == 1 ? bullColor : bearColor
int leftTime = time[1]
int rightTime = time + barMs * 5
box body = box.new(
left = leftTime,
right = rightTime,
top = top,
bottom = bottom,
xloc = xloc.bar_time,
bgcolor = color.new(bodyColor, 78),
border_color = color.new(bodyColor, 25)
)
float mid = math.avg(top, bottom)
box bearBar = box.new(
left = leftTime,
right = leftTime,
top = top,
bottom = mid,
xloc = xloc.bar_time,
bgcolor = bearColor,
border_color = na
)
box bullBar = box.new(
left = leftTime,
right = leftTime,
top = mid,
bottom = bottom,
xloc = xloc.bar_time,
bgcolor = bullColor,
border_color = na
)
obs.push(OB.new(
qualityScore,
top,
bottom,
direction,
bar_index,
leftTime,
obSize,
mitigation,
volScore,
trendScore,
bullStrength,
bearStrength,
body,
bullBar,
bearBar
))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Update Order Blocks {
if obs.size() > 0
for i = obs.size() - 1 to 0
OB ob = obs.get(i)
int age = bar_index - ob.bornBar
bool touched = ob.direction == 1 ? low <= ob.top : high >= ob.bottom
bullTouchAlert := bullTouchAlert or touched and ob.direction == 1
bearTouchAlert := bearTouchAlert or touched and ob.direction == -1
if touched
float fillDistance = ob.direction == 1 ? ob.top - low : high - ob.bottom
float zoneSize = math.max(ob.top - ob.bottom, syminfo.mintick)
ob.mitigation := math.min(math.max(fillDistance / zoneSize, 0), 1)
ob.qualityScore := ob.size * 100 + ob.volumeScore * 10 + ob.trendScore * 20 - ob.mitigation * 50 - age * 0.1
box.set_right(ob.body, time + barMs * 25)
if ob.mitigation >= 1
fullyMitigatedAlert := true
box.delete(ob.body)
box.delete(ob.bullBar)
box.delete(ob.bearBar)
obs.remove(i)
else
obs.set(i, ob)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Sort OBs by quality score {
obs.sort(order.descending, sort_field = "qualityScore")
if obs.size() > 0
OB topOb = obs.get(0)
string currentTopKey = str.tostring(topOb.leftTime) + "_" + str.tostring(topOb.direction)
newTopRankAlert := currentTopKey != topObKey
topObKey := currentTopKey
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Limit Stored Zones {
while obs.size() > maxStored
OB removed = obs.pop()
box.delete(removed.body)
box.delete(removed.bullBar)
box.delete(removed.bearBar)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Display Zones {
int visibleCount = 0
if obs.size() > 0
for i = 0 to obs.size() - 1
OB ob = obs.get(i)
bool passDirection = ob.isVisibleDirection()
bool showZone = passDirection and visibleCount < maxZones
if showZone
visibleCount += 1
color bodyColor = ob.direction == 1 ? bullColor : bearColor
int left = ob.leftTime
int right = time + barMs * 25
float top = box.get_top(ob.body)
float bot = box.get_bottom(ob.body)
float mid = math.avg(top, bot)
int barMaxWidth = int((right - left) * 0.45)
int bullWidth = int(barMaxWidth * ob.bullStrength / 100)
int bearWidth = int(barMaxWidth * ob.bearStrength / 100)
box.set_bgcolor(ob.body, showZone ? color.new(bodyColor, 78) : color.new(color.gray, 100))
box.set_border_color(ob.body, showZone ? color.new(bodyColor, 25) : color.new(color.gray, 100))
box.set_right(ob.body, right)
if showZone and showBars
box.set_left(ob.bearBar, left)
box.set_right(ob.bearBar, left + bearWidth)
box.set_top(ob.bearBar, top)
box.set_bottom(ob.bearBar, mid)
box.set_bgcolor(ob.bearBar, color.new(bearColor, 10))
box.set_border_color(ob.bearBar, na)
box.set_text(ob.bearBar, str.tostring(ob.bearStrength) + "%")
box.set_text_color(ob.bearBar, color.white)
box.set_text_halign(ob.bearBar, text.align_center)
box.set_text_valign(ob.bearBar, text.align_center)
box.set_text_size(ob.bearBar, strengthTextSize)
box.set_left(ob.bullBar, left)
box.set_right(ob.bullBar, left + bullWidth)
box.set_top(ob.bullBar, mid)
box.set_bottom(ob.bullBar, bot)
box.set_bgcolor(ob.bullBar, color.new(bullColor, 10))
box.set_border_color(ob.bullBar, na)
box.set_text(ob.bullBar, str.tostring(ob.bullStrength) + "%")
box.set_text_color(ob.bullBar, color.white)
box.set_text_halign(ob.bullBar, text.align_center)
box.set_text_valign(ob.bullBar, text.align_center)
box.set_text_size(ob.bullBar, strengthTextSize)
string labelText = ob.direction == 1 ? "Bullish OB" : "Bearish OB"
box.set_text(ob.body, showBlockText ? labelText : "")
box.set_text_halign(ob.body, text.align_right)
box.set_text_valign(ob.body, text.align_center)
box.set_text_color(ob.body, chart.fg_color)
box.set_text_size(ob.body, blockTextSize)
else
box.set_bgcolor(ob.bullBar, color.new(color.gray, 100))
box.set_bgcolor(ob.bearBar, color.new(color.gray, 100))
box.set_border_color(ob.bullBar, color.new(color.gray, 100))
box.set_border_color(ob.bearBar, color.new(color.gray, 100))
box.set_text(ob.bullBar, "")
box.set_text(ob.bearBar, "")
box.set_text(ob.body, "")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Alerts {
alertcondition(alertNewBull and newBullObAlert, "New Bullish OB", "A new bullish Order Block has formed.")
alertcondition(alertNewBear and newBearObAlert, "New Bearish OB", "A new bearish Order Block has formed.")
alertcondition(alertTopRank and newTopRankAlert, "New Top-Ranked OB", "A new Order Block has become the highest-quality visible zone.")
alertcondition(alertBullTouch and bullTouchAlert, "Bullish OB Touch", "Price has touched or started mitigating a bullish Order Block.")
alertcondition(alertBearTouch and bearTouchAlert, "Bearish OB Touch", "Price has touched or started mitigating a bearish Order Block.")
alertcondition(alertFullyMitigated and fullyMitigatedAlert, "OB Fully Mitigated", "An Order Block has been fully mitigated and removed.")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}