本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Adaptive Regime Signals [Harmony Algo]", "Adaptive Regime", overlay=true, max_lines_count=100, max_bars_back=160)
bool showGuides = input.bool(true, "Show regime guides")
bool showInvalidation = input.bool(true, "Show signal invalidation")
bool showStatus = input.bool(true, "Show current regime")
color buyColor = #018208
color sellColor = #D12208
color rangeColor = #9064D8
int RANGE = 1
int UP = 2
int DOWN = -2
// Context and entry run at different speeds on intraday charts.
bool timeBased = timeframe.isseconds or timeframe.isminutes or timeframe.isdwm
int seconds = timeBased ? timeframe.in_seconds() : na
bool intraday = timeframe.isintraday and not na(seconds)
bool supported = chart.is_standard and not na(seconds)
string contextTf = seconds < 300 ? "15" : seconds <= 900 ? "60" : seconds <= 3600 ? "240" : "1D"
int structureLength = intraday ? (seconds <= 900 ? 44 : 40) : timeframe.isdaily ? 34 : timeframe.isweekly ? 28 : 24
int swingBars = intraday ? 2 : 1
int trendExpiry = intraday ? 13 : timeframe.isdaily ? 9 : 7
int rangeExpiry = intraday ? 5 : timeframe.isdaily ? 4 : 3
int cooldown = intraday ? 8 : timeframe.isdaily ? 5 : 3
marketMode(simple int length, simple int persistence) =>
float unit = ta.atr(21)
float path = math.sum(math.abs(ta.change(close)), length)
float efficiency = path > 0 ? math.abs(close - close[length]) / path : 0.0
float delta = (ta.linreg(close, length, 0) - ta.linreg(close, length, length - 1)) / unit
float lo = ta.percentile_linear_interpolation(close, length, 15)
float hi = ta.percentile_linear_interpolation(close, length, 85)
int half = int(length * 0.5)
float center = ta.sma(close, half)
float shift = math.abs(center - center[half])
float width = hi - lo
bool known = not na(delta) and not na(shift) and unit >= syminfo.mintick and not na(path)
bool rangeEntry = efficiency <= 0.32 and math.abs(delta) <= 2.1 and width >= 1.8 * unit and shift <= width * 0.28
bool rangeHold = efficiency <= 0.43 and math.abs(delta) <= 3.0 and width >= 1.4 * unit and shift <= width * 0.39
int candidate = rangeEntry ? RANGE : efficiency >= 0.24 and delta >= 2.5 ? UP : efficiency >= 0.24 and delta <= -2.5 ? DOWN : 0
var int active = 0
var int previous = 0
var int streak = 0
float currentRange = ta.tr(true)
if not known or currentRange > 4.0 * unit[1]
active := 0
previous := 0
streak := 0
else if active != 0
bool holds = active == RANGE ? rangeHold : efficiency >= 0.15 and math.sign(active) * delta >= 1.25
if not holds
active := 0
previous := 0
streak := 0
else
streak := candidate == 0 ? 0 : candidate == previous ? streak + 1 : 1
previous := candidate
if streak >= persistence
active := candidate
active
// The offset belongs inside the security request, in the context timeframe.
int localMode = marketMode(structureLength, 2)[1]
int contextMode = not supported ? 0 : intraday ? request.security(syminfo.tickerid, contextTf, marketMode(30, 2)[1], lookahead=barmerge.lookahead_on) : localMode
// Inside an indecisive broader market, a locally established range can qualify.
int mode = intraday and contextMode == 0 and localMode == RANGE ? RANGE : contextMode
float unit = ta.atr(21)[1]
float localMean = ta.ema(close, 20)[1]
float lower = ta.percentile_linear_interpolation(close, structureLength, 15)[1]
float upper = ta.percentile_linear_interpolation(close, structureLength, 85)[1]
float width = upper - lower
float midpoint = (upper + lower) * 0.5
bool shock = ta.tr(true) > 3.75 * unit
bool ready = supported and not na(width) and unit >= syminfo.mintick and not shock
// Count completed visits, requiring departure toward the interior before rearming an edge.
testedEdges(float lo, float hi, int length) =>
float band = hi - lo
float zone = 0.16 * band
float departure = 0.32 * band
int lowTests = 0
int highTests = 0
int visited = 0
for offset = length to 1
float p = close[offset]
if visited == -1 and p >= lo + departure
lowTests += 1
visited := 0
else if visited == 1 and p <= hi - departure
highTests += 1
visited := 0
if visited == 0
bool testsLow = low[offset] <= lo + zone
bool testsHigh = high[offset] >= hi - zone
if testsLow != testsHigh
visited := testsLow ? -1 : 1
lowTests >= 2 and highTests >= 2
rangeHasRoom(float entry, float guard, float goal, int direction, float atr) =>
float risk = direction * (entry - guard)
float room = direction * (goal - entry)
risk >= syminfo.mintick and room >= math.max(0.35 * atr, 0.80 * risk)
float pivotHigh = ta.pivothigh(high, swingBars, swingBars)
float pivotLow = ta.pivotlow(low, swingBars, swingBars)
float recentHigh = ta.valuewhen(not na(pivotHigh), pivotHigh, 0)
float recentLow = ta.valuewhen(not na(pivotLow), pivotLow, 0)
float longGuard = ta.valuewhen(not na(pivotHigh), recentLow[1], 0)
float shortGuard = ta.valuewhen(not na(pivotLow), recentHigh[1], 0)
int longAge = ta.barssince(not na(pivotHigh))
int shortAge = ta.barssince(not na(pivotLow))
float closingSwingHigh = ta.pivothigh(close, 1, 1)
float closingSwingLow = ta.pivotlow(close, 1, 1)
float lastClosingHigh = ta.valuewhen(not na(closingSwingHigh), closingSwingHigh, 0)
float lastClosingLow = ta.valuewhen(not na(closingSwingLow), closingSwingLow, 0)
int closingHighAge = ta.barssince(not na(closingSwingHigh))
int closingLowAge = ta.barssince(not na(closingSwingLow))
// A pre-existing wick through the protected swing invalidates the prior impulse.
float confirmationLow = ta.lowest(low, swingBars + 1)
float confirmationHigh = ta.highest(high, swingBars + 1)
var bool longIntact = false
var bool shortIntact = false
if barstate.isconfirmed
if not na(pivotHigh)
longIntact := not na(longGuard) and confirmationLow > longGuard
else if low <= longGuard
longIntact := false
if not na(pivotLow)
shortIntact := not na(shortGuard) and confirmationHigh < shortGuard
else if high >= shortGuard
shortIntact := false
var int phase = 0
var int side = 0
var int started = na
var int phaseAt = na
var int lastSignal = na
var int lastShock = na
var float edge = na
var float limitPrice = na
var float protectedSwing = na
var float extreme = na
var float threshold = na
var float basis = na
int event = 0
int lag = na
float invalidation = na
float objective = na
if barstate.isconfirmed
if shock
lastShock := bar_index
bool rested = na(lastSignal) or bar_index - lastSignal > cooldown
bool quiet = na(lastShock) or bar_index - lastShock > 2
if not ready or mode == 0 or mode != mode[1]
phase := 0
else if phase == 1
// Reclaim with the original range edge and center.
if bar_index - phaseAt > rangeExpiry or side * ((side == 1 ? high : low) - limitPrice) >= 0
phase := 0
else
extreme := side == 1 ? math.min(extreme, low) : math.max(extreme, high)
if side * (close - edge) >= 0.05 * basis
// The reclaim may itself confirm an earlier closed excursion.
if side * (close - edge) >= 0.10 * basis and side * (close - close[1]) >= 0.25 * basis
float guard = extreme - side * 0.08 * basis
if rangeHasRoom(close, guard, limitPrice, side, basis)
event := side
invalidation := guard
objective := limitPrice
phase := 0
else
threshold := close
phaseAt := bar_index
phase := 2
else if phase == 2
float adverse = side == 1 ? low : high
float favorable = side == 1 ? high : low
float guard = extreme - side * 0.08 * basis
if side * (adverse - guard) <= 0 or side * (favorable - limitPrice) >= 0 or bar_index - phaseAt > rangeExpiry
phase := 0
else if side * (close - threshold) >= 0.10 * basis
if rangeHasRoom(close, guard, limitPrice, side, basis)
event := side
invalidation := guard
objective := limitPrice
phase := 0
else if phase == 3
float adverse = side == 1 ? low : high
float favorable = side == 1 ? high : low
if side * (adverse - protectedSwing) <= 0 or side * (favorable - limitPrice) >= 0 or bar_index - started > trendExpiry
phase := 0
else
extreme := side == 1 ? math.min(extreme, low) : math.max(extreme, high)
bool breaks = not na(threshold) and side * (close - threshold) >= 0.05 * basis
if breaks
float guard = extreme - side * 0.08 * basis
float risk = side * (close - guard)
float room = side * (limitPrice - close)
if risk >= syminfo.mintick and room >= math.max(0.30 * basis, risk)
event := 2 * side
invalidation := guard
objective := limitPrice
phase := 0
else if bar_index - started >= 2 and side * (close[1] - close[2]) > 0 and side * (close - close[1]) < 0
// A pullback closing swing is known only after this bar closes.
threshold := close[1]
else if rested and quiet and mode == RANGE and width >= 2.2 * unit and width <= 16.0 * unit
bool cameFromInside = close[1] >= lower - 0.15 * unit and close[1] <= upper + 0.15 * unit
bool sweepLow = low <= lower - 0.13 * unit
bool sweepHigh = high >= upper + 0.13 * unit
if cameFromInside and sweepLow != sweepHigh and testedEdges(lower, upper, structureLength)
side := sweepLow ? 1 : -1
edge := sweepLow ? lower : upper
limitPrice := midpoint
basis := unit
extreme := sweepLow ? low : high
if side * ((side == 1 ? high : low) - limitPrice) < 0
started := bar_index
phaseAt := bar_index
bool reclaimed = side * (close - edge) >= 0.05 * basis
phase := reclaimed ? 2 : 1
threshold := reclaimed ? close : na
else if rested and quiet and math.abs(mode) == 2
int direction = mode == UP ? 1 : -1
float peak = direction == 1 ? recentHigh : recentLow
float guard = direction == 1 ? longGuard : shortGuard
float adverse = direction == 1 ? low : high
float favorable = direction == 1 ? high : low
int age = direction == 1 ? longAge : shortAge
float impulse = direction * (peak - guard)
float depth = direction * (peak - adverse)
bool intact = direction == 1 ? longIntact : shortIntact
if intact and not na(age) and age <= structureLength and impulse >= 1.8 * unit and depth >= 0.60 * unit and depth <= 0.82 * impulse and direction * (favorable - peak) < 0 and direction * (close - close[1]) < 0
side := direction
protectedSwing := guard
limitPrice := peak
basis := unit
extreme := adverse
float closingSwing = direction == 1 ? lastClosingHigh : lastClosingLow
int closingAge = direction == 1 ? closingHighAge : closingLowAge
// Seed from an already confirmed pullback swing only if its origin is after the impulse extreme.
bool recentInternal = not na(closingAge) and closingAge + 1 < age + swingBars and direction * (peak - closingSwing) >= 0.20 * unit and direction * (closingSwing - close) > 0
threshold := recentInternal ? closingSwing : na
started := bar_index
phase := 3
if event != 0
lag := bar_index - started
lastSignal := bar_index
if showInvalidation
line.new(bar_index, invalidation, bar_index + cooldown, invalidation, color=color.new(event > 0 ? buyColor : sellColor, 24), style=line.style_dotted)
rangeUpper = plot(showGuides and mode == RANGE ? upper : na, "Range upper", color=color.new(rangeColor, 34), style=plot.style_linebr)
rangeLower = plot(showGuides and mode == RANGE ? lower : na, "Range lower", color=color.new(rangeColor, 34), style=plot.style_linebr)
fill(rangeUpper, rangeLower, color.new(rangeColor, 93), fillgaps=false)
plot(showGuides and math.abs(mode) == 2 ? localMean : na, "Trend guide", color=color.new(mode > 0 ? buyColor : sellColor, 36), linewidth=2, style=plot.style_linebr)
bool rangeBuy = event == 1
bool rangeSell = event == -1
bool trendBuy = event == 2
bool trendSell = event == -2
plotshape(rangeBuy, "Range Buy", shape.labelup, location.belowbar, buyColor, text="Buy\nRange", textcolor=color.white, size=size.tiny)
plotshape(rangeSell, "Range Sell", shape.labeldown, location.abovebar, sellColor, text="Sell\nRange", textcolor=color.white, size=size.tiny)
plotshape(trendBuy, "Trend Buy", shape.labelup, location.belowbar, buyColor, text="Buy\nTrend", textcolor=color.white, size=size.tiny)
plotshape(trendSell, "Trend Sell", shape.labeldown, location.abovebar, sellColor, text="Sell\nTrend", textcolor=color.white, size=size.tiny)
plot(mode, "Regime code", display=display.data_window)
plot(event, "Signal code", display=display.data_window)
plot(invalidation, "Signal invalidation", display=display.data_window, format=format.price)
plot(objective, "Signal reference objective", display=display.data_window, format=format.price)
plot(lag, "Setup bars", display=display.data_window)
alertcondition(rangeBuy, "Range Buy", "Range Buy on {{ticker}} {{interval}} at {{close}}")
alertcondition(rangeSell, "Range Sell", "Range Sell on {{ticker}} {{interval}} at {{close}}")
alertcondition(trendBuy, "Trend Buy", "Trend Buy on {{ticker}} {{interval}} at {{close}}")
alertcondition(trendSell, "Trend Sell", "Trend Sell on {{ticker}} {{interval}} at {{close}}")
var table badge = table.new(position.top_right, 1, 1)
if barstate.islast and showStatus
int shownMode = barstate.isconfirmed ? mode : nz(mode[1])
string state = not supported ? "Standard time-based chart required" : shownMode == RANGE ? "Range" : shownMode == UP ? "Uptrend" : shownMode == DOWN ? "Downtrend" : "Waiting"
string contextText = not intraday ? "Chart TF" : contextTf == "15" ? "15m context" : contextTf == "60" ? "1h context" : contextTf == "240" ? "4h context" : "Daily context"
color stateColor = shownMode == RANGE ? rangeColor : shownMode == UP ? buyColor : shownMode == DOWN ? sellColor : #505863
table.cell(badge, 0, 0, supported ? state + " · " + contextText : state, text_color=color.white, bgcolor=color.new(stateColor, 16), text_size=size.small)