本页源码来自 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/
// © SchizoQuant
//@version=6
indicator("Adaptive Structural Trend", overlay=true, max_bars_back=500)
// USER INPUTS
string sourceTip = "Price source used to measure directional efficiency. Closing price is the default."
string efficiencyTip = "Number of candles used to measure how efficiently price progresses in one direction."
string smoothingTip = "Smooths directional efficiency so the adaptive structural lookback does not change too abruptly."
string adaptationTip = "Controls how directional efficiency maps to structural length. Higher values favor shorter lookbacks as efficiency improves."
string minimumTip = "Shortest permitted structural lookback, favored when price movement is highly directional."
string maximumTip = "Longest permitted structural lookback, favored when price movement is less directional."
string atrTip = "ATR lookback used to normalize structural reversal buffers and opposing candle impulses."
string paddingTip = "Base ATR padding beyond the structural boundary used for reversal confirmation."
string congestionTip = "Additional ATR padding applied when price movement becomes less directionally efficient."
string overrideTip = "Allows a strong opposing candle impulse to reverse the trend when price also crosses the structural midpoint and the previous candle extreme."
string impulseTip = "Minimum opposing one-candle movement in ATR multiples required for an impulse reversal."
string defenseTip = "Displays the active ratcheting structural defense level for the current trend regime, including on the live candle."
string midpointTip = "Displays the midpoint of the current adaptive structural range."
string signalsTip = "Displays LONG and SHORT triangles when the trend regime reverses, including intrabar. Signals can change before the candle closes."
string barsTip = "Colors price candles according to the current bullish or bearish trend regime, including intrabar."
string colorTip = "Choose the bullish and bearish colors used for the structural levels, signals, and candles."
float source = input.source(title="Price Source", defval=close, group="Adaptive Efficiency", tooltip=sourceTip)
int efficiencyLength = input.int(title="Efficiency Length", defval=9, minval=2, maxval=100, group="Adaptive Efficiency", tooltip=efficiencyTip)
int efficiencySmoothing = input.int(title="Efficiency Smoothing", defval=3, minval=1, maxval=30, group="Adaptive Efficiency", tooltip=smoothingTip)
float adaptationStrength = input.float(title="Adaptation Strength", defval=1.00, minval=0.25, maxval=4.0, step=0.05, group="Adaptive Efficiency", tooltip=adaptationTip)
int minimumLength = input.int(title="Minimum Structure Length", defval=8, minval=3, maxval=100, group="Market Structure", tooltip=minimumTip)
int maximumLength = input.int(title="Maximum Structure Length", defval=29, minval=5, maxval=100, group="Market Structure", tooltip=maximumTip)
int atrLength = input.int(title="ATR Length", defval=14, minval=1, group="Market Structure", tooltip=atrTip)
float basePadding = input.float(title="Base Structure Padding (ATR)", defval=0.2, minval=0.0, maxval=3.0, step=0.05, group="Market Structure", tooltip=paddingTip)
float congestionPadding = input.float(title="Congestion Protection (ATR)", defval=0.2, minval=0.0, maxval=3.0, step=0.05, group="Market Structure", tooltip=congestionTip)
bool useImpulseOverride = input.bool(title="Enable Impulse Override", defval=true, group="Reversal Settings", tooltip=overrideTip)
float impulseThreshold = input.float(title="Impulse Threshold (ATR)", defval=2.00, minval=0.50, maxval=5.0, step=0.10, group="Reversal Settings", tooltip=impulseTip)
bool showDefense = input.bool(title="Show Active Defense", defval=true, group="Visualization", tooltip=defenseTip)
bool showMidpoint = input.bool(title="Show Structure Midpoint", defval=false, group="Visualization", tooltip=midpointTip)
bool showSignals = input.bool(title="Show Signals", defval=true, group="Visualization", tooltip=signalsTip)
bool colorBars = input.bool(title="Color Bars", defval=true, group="Visualization", tooltip=barsTip)
color longColor = input.color(title="Bullish Color", defval=color.rgb(57, 255, 20), group="Color Settings", inline="COL1", tooltip=colorTip)
color shortColor = input.color(title="Bearish Color", defval=color.rgb(138, 43, 226), group="Color Settings", inline="COL1", tooltip=colorTip)
// CALCULATIONS
float priceChange = math.abs(source - nz(source[1], source))
float averageChange = nz(ta.sma(priceChange, efficiencyLength), 0.0)
float pathDistance = averageChange * efficiencyLength
float netDistance = math.abs(source - nz(source[efficiencyLength], source))
float efficiency = pathDistance > syminfo.mintick ? math.min(netDistance / pathDistance, 1.0) : 0.0
efficiency := nz(efficiency, 0.0)
float stableEfficiency = nz(ta.ema(efficiency, efficiencySmoothing), 0.0)
stableEfficiency := math.max(0.0, math.min(1.0, stableEfficiency))
float marketNoise = 1.0 - stableEfficiency
int shortestLength = math.min(minimumLength, maximumLength)
int longestLength = math.max(minimumLength, maximumLength)
float adaptiveFactor = math.pow(marketNoise, adaptationStrength)
adaptiveFactor := nz(adaptiveFactor, 1.0)
float dynamicLength = shortestLength + (longestLength - shortestLength) * adaptiveFactor
float safeDynamicLength = nz(dynamicLength, longestLength)
int structuralLength = int(math.round(safeDynamicLength))
structuralLength := math.max(shortestLength, math.min(longestLength, structuralLength))
structuralLength := math.max(1, structuralLength)
float upperBoundary = ta.highest(high[1], structuralLength)
float lowerBoundary = ta.lowest(low[1], structuralLength)
float structureMidpoint = (upperBoundary + lowerBoundary) * 0.5
float atrValue = ta.atr(atrLength)
float safeATR = math.max(nz(atrValue, high - low), syminfo.mintick)
float padding = (basePadding + marketNoise * congestionPadding) * safeATR
float bullishDefenseCandidate = lowerBoundary - padding
float bearishDefenseCandidate = upperBoundary + padding
float candleImpulse = (close - nz(close[1], close)) / safeATR
bool bullishImpulse = useImpulseOverride and candleImpulse >= impulseThreshold and close > structureMidpoint and close > high[1]
bool bearishImpulse = useImpulseOverride and candleImpulse <= -impulseThreshold and close < structureMidpoint and close < low[1]
int warmup = longestLength + efficiencyLength + efficiencySmoothing + atrLength
bool ready = bar_index >= warmup and not na(upperBoundary) and not na(lowerBoundary) and not na(atrValue) and not na(structureMidpoint)
// SIGNALS
var int SQ = 0
var float bullishDefense = na
var float bearishDefense = na
bool longSignal = false
bool shortSignal = false
if ready
if SQ == 0
SQ := close >= structureMidpoint ? 1 : -1
bullishDefense := bullishDefenseCandidate
bearishDefense := bearishDefenseCandidate
else if SQ == 1
bullishDefense := math.max(nz(bullishDefense, bullishDefenseCandidate), bullishDefenseCandidate)
if close < bullishDefense or bearishImpulse
SQ := -1
shortSignal := true
bearishDefense := bearishDefenseCandidate
else
bearishDefense := math.min(nz(bearishDefense, bearishDefenseCandidate), bearishDefenseCandidate)
if close > bearishDefense or bullishImpulse
SQ := 1
longSignal := true
bullishDefense := bullishDefenseCandidate
// COLORS
color col = SQ == 1 ? longColor : SQ == -1 ? shortColor : color.gray
color colors = colorBars and SQ != 0 ? col : na
float activeDefense = SQ == 1 ? bullishDefense : bearishDefense
// PLOTS
plot(showDefense and ready and SQ != 0 ? activeDefense : na, title="Active Structural Defense", color=col, linewidth=2, style=plot.style_linebr)
plot(showMidpoint and ready ? structureMidpoint : na, title="Adaptive Structure Midpoint", color=color.new(col, 60))
plot(stableEfficiency, title="Directional Efficiency", display=display.data_window)
plot(marketNoise, title="Market Noise", display=display.data_window)
plot(float(structuralLength), title="Adaptive Structure Length", display=display.data_window)
plot(padding / safeATR, title="Reversal Padding (ATR)", display=display.data_window)
plot(float(SQ), title="Trend State", display=display.data_window)
plotshape(showSignals and longSignal, title="Long Signal", style=shape.triangleup, location=location.belowbar, size=size.small, color=longColor, text="LONG", textcolor=color.white, force_overlay=true)
plotshape(showSignals and shortSignal, title="Short Signal", style=shape.triangledown, location=location.abovebar, size=size.small, color=shortColor, text="SHORT", textcolor=color.white, force_overlay=true)
barcolor(colors, title = "Color Bars")
plotcandle(open, high, low, close, "Color Bars", colors, colors, bordercolor = colors, force_overlay = true)
// ALERTS
alertcondition(longSignal, title="LONG Signal", message="Adaptive Structural Trend: LONG on {{ticker}}")
alertcondition(shortSignal, title="SHORT Signal", message="Adaptive Structural Trend: SHORT on {{ticker}}")