Fractal Drift Continuity Trend [SchizoQuant]

SchizoQuant · study · 132 行 · 点赞 972 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// 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("Fractal Drift Continuity Trend", overlay=true)
 
// USER INPUTS
string sourceTip       = "Choose the price source used to calculate the fractal-adaptive trendline. The midpoint of each candle is selected by default."
string fractalTip      = "Sets the lookback used to estimate the geometric complexity of price movement. Lower values respond faster, while higher values produce a steadier fractal estimate."
string dimensionTip    = "Sets the smoothing period for the estimated fractal dimension used in reversal protection. The adaptive trendline continues to use the current fractal estimate."
string atrTip          = "Sets the ATR period used to normalize directional drift, price displacement, and impulse-based reversal thresholds."
string driftTip        = "Sets the number of candles used to measure directional progress of the fractal-adaptive trendline."
string influenceTip    = "Controls the contribution of fractal trendline movement to the directional score. Higher values increase the influence of underlying trend drift."
string displacementTip = "Controls the contribution of closing-price displacement relative to the adaptive trendline. Higher values increase sensitivity to price movement away from the trend estimate."
string smoothingTip    = "Sets the smoothing period for combined directional evidence. Higher values reduce sensitivity to short-term fluctuations but can delay reversals."
string thresholdTip    = "Sets the minimum opposing directional evidence required to reverse the persistent trend regime under relatively directional market conditions."
string protectionTip   = "Controls the additional reversal confirmation required as the fractal dimension approaches more complex, choppy market conditions."
string overrideTip     = "Enables strong opposing price impulses to reverse the trend without requiring confirmation from the smoothed directional score."
string impulseTip      = "Sets the minimum opposing price displacement from the adaptive trendline in ATR multiples. An impulse reversal also requires a break of the previous candle's high or low."
string trendTip        = "Shows or hides the fractal-adaptive trendline, colored according to the active bullish or bearish regime."
string signalsTip      = "Shows or hides LONG and SHORT triangles when the persistent trend regime changes on a confirmed candle."
string barsTip         = "Shows or hides candles colored according to the active bullish or bearish trend regime."
string colorTip        = "Bullish Color represents bullish conditions and LONG signals, while Bearish Color represents bearish conditions and SHORT signals."
 
float source                = input.source(title="Price Source", defval=hl2, group="Fractal Settings", tooltip=sourceTip)
int   fractalLength         = input.int(title="Fractal Length", defval=24, minval=8, step=2, group="Fractal Settings", tooltip=fractalTip)
int   dimensionSmoothing    = input.int(title="Dimension Smoothing", defval=3, minval=1, group="Fractal Settings", tooltip=dimensionTip)
int   atrLength             = input.int(title="ATR Length", defval=14, minval=1, group="Fractal Settings", tooltip=atrTip)
int   driftLength           = input.int(title="Drift Lookback", defval=3, minval=1, group="Trend Settings", tooltip=driftTip)
float driftInfluence        = input.float(title="Drift Influence", defval=1.50, minval=0.0, maxval=5.0, step=0.10, group="Trend Settings", tooltip=influenceTip)
float displacementInfluence = input.float(title="Price Displacement Influence", defval=0.30, minval=0.0, maxval=2.0, step=0.05, group="Trend Settings", tooltip=displacementTip)
int   pressureSmoothing     = input.int(title="Directional Smoothing", defval=3, minval=1, group="Trend Settings", tooltip=smoothingTip)
float reversalThreshold     = input.float(title="Base Reversal Threshold", defval=0.18, minval=0.01, maxval=2.0, step=0.01, group="Reversal Settings", tooltip=thresholdTip)
float fractalProtection     = input.float(title="Fractal Reversal Protection", defval=0.25, minval=0.0, maxval=1.5, step=0.05, group="Reversal Settings", tooltip=protectionTip)
bool  useImpulseOverride    = input.bool(title="Enable Impulse Override", defval=true, group="Reversal Settings", tooltip=overrideTip)
float impulseThreshold      = input.float(title="Impulse Override (ATR)", defval=1.20, minval=0.25, maxval=5.0, step=0.05, group="Reversal Settings", tooltip=impulseTip)
bool  showTrend             = input.bool(title="Show Fractal Trendline", defval=true, group="Visualization", tooltip=trendTip)
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
int fullLength = fractalLength - fractalLength % 2
int halfLength = int(fullLength / 2)
 
float recentRange   = ta.highest(high, halfLength) - ta.lowest(low, halfLength)
float previousRange = ta.highest(high[halfLength], halfLength) - ta.lowest(low[halfLength], halfLength)
float completeRange = ta.highest(high, fullLength) - ta.lowest(low, fullLength)
 
float n1 = recentRange / halfLength
float n2 = previousRange / halfLength
float n3 = completeRange / fullLength
 
var float fractalDimension = 1.5
 
if bar_index >= fullLength - 1 and n1 > 0.0 and n2 > 0.0 and n3 > 0.0
    float measuredDimension = (math.log(n1 + n2) - math.log(n3)) / math.log(2.0)
    fractalDimension := math.max(1.0, math.min(2.0, measuredDimension))
else
    fractalDimension := nz(fractalDimension[1], 1.5)
 
float adaptiveAlpha = math.exp(-4.6 * (fractalDimension - 1.0))
adaptiveAlpha := math.max(0.01, math.min(1.0, adaptiveAlpha))
 
var float fractalTrend = na
fractalTrend := na(fractalTrend[1]) ? source : adaptiveAlpha * source + (1.0 - adaptiveAlpha) * fractalTrend[1]
 
float atrValue = ta.atr(atrLength)
float safeATR  = math.max(nz(atrValue, high - low), syminfo.mintick)
 
float historicalTrend  = nz(fractalTrend[driftLength], fractalTrend)
float directionalDrift = (fractalTrend - historicalTrend) / (safeATR * driftLength)
 
float rawDisplacement   = (close - fractalTrend) / safeATR
float priceDisplacement = math.max(-2.5, math.min(2.5, rawDisplacement))
 
float rawPressure         = directionalDrift * driftInfluence + priceDisplacement * displacementInfluence
float directionalPressure = ta.ema(rawPressure, pressureSmoothing)
 
float stableDimension   = ta.ema(fractalDimension, dimensionSmoothing)
float fractalCongestion = math.max(0.0, math.min(1.0, stableDimension - 1.0))
float adaptiveThreshold = reversalThreshold + fractalProtection * fractalCongestion
 
bool bullishEvidence = directionalPressure > adaptiveThreshold and close > fractalTrend
bool bearishEvidence = directionalPressure < -adaptiveThreshold and close < fractalTrend
 
bool bullishImpulse = useImpulseOverride and close > fractalTrend + impulseThreshold * safeATR and close > high[1]
bool bearishImpulse = useImpulseOverride and close < fractalTrend - impulseThreshold * safeATR and close < low[1]
 
int  warmup = math.max(fullLength, atrLength) + driftLength + pressureSmoothing
bool ready  = bar_index >= warmup and not na(atrValue) and not na(directionalPressure)
 
// SIGNALS
var int SQ = 0
 
bool longSignal  = false
bool shortSignal = false
 
if barstate.isconfirmed and ready
    if SQ == 0
        SQ := directionalPressure >= 0.0 ? 1 : -1
    else if SQ == -1 and (bullishEvidence or bullishImpulse)
        SQ         := 1
        longSignal := true
    else if SQ == 1 and (bearishEvidence or bearishImpulse)
        SQ          := -1
        shortSignal := true
 
// COLORS
color col    = SQ == 1 ? longColor : SQ == -1 ? shortColor : color.gray
color colors = colorBars and SQ != 0 ? col : na
 
// PLOTS
plot(showTrend and ready ? fractalTrend : na, title="Fractal Trendline", color=col, linewidth=3)
plot(fractalDimension, title="Fractal Dimension", display=display.data_window)
plot(stableDimension, title="Smoothed Fractal Dimension", display=display.data_window)
plot(adaptiveAlpha, title="Adaptive Alpha", display=display.data_window)
plot(directionalDrift, title="Directional Drift", display=display.data_window)
plot(priceDisplacement, title="Price Displacement", display=display.data_window)
plot(directionalPressure, title="Directional Pressure", display=display.data_window)
plot(fractalCongestion, title="Fractal Congestion", display=display.data_window)
plot(adaptiveThreshold, title="Adaptive Reversal Threshold", 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="Fractal Drift Continuity Trend: LONG on {{ticker}}")
alertcondition(shortSignal, title="SHORT Signal", message="Fractal Drift Continuity Trend: SHORT on {{ticker}}")

← 返回列表