Mean Reversion Channel [TradingFinder] ATR Band Reversal Signals

TradingFinder · study · 262 行 · 点赞 503 · 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/
// © TradingFinder
 
//@version=6
 
indicator("Mean Reversion Channel [TradingFinder] ATR Band Reversal Signals", shorttitle="MRC", overlay=true, max_bars_back=5000, max_labels_count=500)
 
 
//Inputs
 
Model = input.string("Fusion", "Calculation Mode", options=["Fusion", "Trend Spread"], group="Calculation")
ReactionLength = input.int(10, "Reaction Length", minval=2, maxval=200, group="Calculation")
TrendLength = input.int(38, "Trend Length", minval=3, maxval=300, group="Calculation")
Smoothing = input.string("EMA", "MA Method", options=["EMA", "SMA", "WMA", "HMA", "RMA", "VWMA"], group="Calculation")
ChannelLength = input.int(20, "Pulse Anchor Period", minval=2, maxval=200, group="Calculation")
BandWidth = input.float(3.40, "ATR Multiplier", minval=0.50, maxval=10.00, step=0.10, group="Calculation")
BandAtrLength = input.int(21, "Band ATR Period", minval=1, maxval=200, group="Calculation")
BandSmoothness = input.int(21, "Band Smooth Period", minval=1, maxval=100, group="Calculation")
Activity = input.string("Balanced", "Signal Quality", options=["Responsive", "Balanced", "Selective"], group="Signals", tooltip="Controls the strictness of the reversal confirmation model.")
SignalGap = input.int(10, "Minimum Signal Spacing (Bars)", minval=1, maxval=100, group="Signals")
EntryDepth = input.float(0.08, "Outside Band-1 Buffer", minval=0.00, maxval=0.80, step=0.02, group="Signals", tooltip="Extra distance required beyond the inner band before a setup qualifies.")
TouchDepth = input.float(0.18, "Required Outside Test", minval=0.00, maxval=1.20, step=0.02, group="Signals", tooltip="How deeply price must test outside Band 1 before a reversal is eligible.")
UseEntryFilter = true
UseStructureValidation = true
UseTrendContext = true
UseRegimeFilter = true
UseMeanReversion = true
MaxSmaExtension = 2.0
UseHTF = false
HtfTF = "60"
ShowSignals = true
ShowPulse = true
ShowBand = true
ShowEntryZones = false
ShowRejected = false
 
 
//Logic
 
Cap(float X, float Lo, float Hi) =>
    math.min(math.max(X, Lo), Hi)
Unit(float X, float Lo, float Hi) =>
    Hi > Lo ? Cap((X - Lo) / (Hi - Lo), 0.0, 1.0) : 0.0
Average(float Src, int Period) =>
    switch Smoothing
        "SMA" => ta.sma(Src, Period)
        "WMA" => ta.wma(Src, Period)
        "HMA" => ta.hma(Src, Period)
        "RMA" => ta.rma(Src, Period)
        "VWMA" => ta.vwma(Src, Period)
        => ta.ema(Src, Period)
Rank(int Value) =>
    Value >= 90 ? "A+" : Value >= 80 ? "A" : Value >= 70 ? "B" : Value >= 60 ? "C" : "D"
ModelValues() =>
    Fast = Average(close, ReactionLength)
    Slow = Average(close, TrendLength)
    Atr = ta.atr(14)
    Spread = Atr > 0.0 ? (Fast - Slow) / Atr : 0.0
    [MacdMain, MacdSignal, MacdHist] = ta.macd(close, 12, 26, 9)
    Rsi = ta.rsi(close, 14)
    Stoch = ta.stoch(close, high, low, 14)
    Psar = ta.sar(0.02, 0.02, 0.20)
    Bull = (MacdHist > 0 ? 21.0 : 0.0) + (Rsi > 52 ? 20.0 : Rsi > 49 ? 10.0 : 0.0) + (Stoch > 55 ? 14.0 : Stoch > 48 ? 7.0 : 0.0) + (close > Psar ? 20.0 : 0.0) + (Spread > 0 ? 25.0 : 0.0)
    Bear = (MacdHist < 0 ? 21.0 : 0.0) + (Rsi < 48 ? 20.0 : Rsi < 51 ? 10.0 : 0.0) + (Stoch < 45 ? 14.0 : Stoch < 52 ? 7.0 : 0.0) + (close < Psar ? 20.0 : 0.0) + (Spread < 0 ? 25.0 : 0.0)
    [Fast, Slow, Spread, Bull, Bear]
ModelState() =>
    [Fast, Slow, Spread, Bull, Bear] = ModelValues()
    EvidenceFloor = Activity == "Responsive" ? 52.0 : Activity == "Selective" ? 69.0 : 59.0
    SpreadFloor = Activity == "Responsive" ? 0.025 : Activity == "Selective" ? 0.15 : 0.075
    Bullish = Model == "Fusion" ? Bull >= EvidenceFloor and Bull > Bear : Spread > SpreadFloor
    Bearish = Model == "Fusion" ? Bear >= EvidenceFloor and Bear > Bull : Spread < -SpreadFloor
    var Direction = 0
    if Bullish
        Direction := 1
    else if Bearish
        Direction := -1
    [Direction, Fast, Slow, Spread, Bull, Bear]
ModelDirection() =>
    [Direction, Fast, Slow, Spread, Bull, Bear] = ModelState()
    Direction
[Side, FastAverage, SlowAverage, SpreadATR, BullEvidence, BearEvidence] = ModelState()
ValidHTF = timeframe.in_seconds(HtfTF) > timeframe.in_seconds()
if UseHTF and not ValidHTF
    runtime.error("Higher Timeframe must be higher than the chart timeframe.")
HtfSide = request.security(syminfo.tickerid, HtfTF, ModelDirection()[1], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
BuyHTF = not UseHTF or (ValidHTF and HtfSide == 1)
SellHTF = not UseHTF or (ValidHTF and HtfSide == -1)
Anchor = Average(hlc3, ChannelLength)
Volatility = ta.atr(14)
UpTone = #00D5FF
DownTone = #FF477E
NeutralTone = #765CF6
RawPulse = Model == "Fusion" ? Cap((BullEvidence - BearEvidence) / 100.0, -1.0, 1.0) : Cap(SpreadATR / 1.5, -1.0, 1.0)
Pulse = ta.ema(RawPulse, 3)
RawCenter = Anchor + Volatility * 0.60 * Pulse
CenterMA = ta.ema(RawCenter, BandSmoothness)
AtrSmooth = ta.ema(ta.atr(BandAtrLength), BandSmoothness)
InnerRadius = AtrSmooth * BandWidth
OuterRadius = InnerRadius * 1.618
LvlUp = CenterMA + InnerRadius
LvlDown = CenterMA - InnerRadius
Up161 = CenterMA + OuterRadius
Down161 = CenterMA - OuterRadius
RadiusSafe = math.max(nz(InnerRadius), syminfo.mintick)
PriceZone = (close - CenterMA) / RadiusSafe
LowZone = (low - CenterMA) / RadiusSafe
HighZone = (high - CenterMA) / RadiusSafe
BuyZoneBoundary = LvlDown - InnerRadius * EntryDepth
SellZoneBoundary = LvlUp + InnerRadius * EntryDepth
LowerZone = not na(CenterMA) and not na(InnerRadius) and close <= BuyZoneBoundary and close >= Down161
UpperZone = not na(CenterMA) and not na(InnerRadius) and close >= SellZoneBoundary and close <= Up161
LowestRecentZone = ta.lowest(LowZone, 6)
HighestRecentZone = ta.highest(HighZone, 6)
LowerTouched = LowestRecentZone <= -(1.0 + TouchDepth)
UpperTouched = HighestRecentZone >= (1.0 + TouchDepth)
 
 
//Signals
 
[MacdMain, MacdSignal, MacdHist] = ta.macd(close, 12, 26, 9)
Rsi = ta.rsi(close, 14)
Stoch = ta.stoch(close, high, low, 14)
[PlusDI, MinusDI, Adx] = ta.dmi(14, 14)
BarRange = math.max(high - low, syminfo.mintick)
BodyShare = math.abs(close - open) / BarRange
BuyClosePos = (close - low) / BarRange
SellClosePos = (high - close) / BarRange
LowerWick = (math.min(open, close) - low) / BarRange
UpperWick = (high - math.max(open, close)) / BarRange
BarATR = Volatility > 0.0 ? BarRange / Volatility : 0.0
BuyCandle = close > open and BuyClosePos >= (Activity == "Selective" ? 0.73 : 0.64) and BodyShare >= (Activity == "Selective" ? 0.39 : 0.27)
SellCandle = close < open and SellClosePos >= (Activity == "Selective" ? 0.73 : 0.64) and BodyShare >= (Activity == "Selective" ? 0.39 : 0.27)
BuyCandleOK = not UseEntryFilter or BuyCandle
SellCandleOK = not UseEntryFilter or SellCandle
BuyTurns = (Rsi > Rsi[1] ? 1 : 0) + (MacdHist > MacdHist[1] ? 1 : 0) + (Stoch > Stoch[1] ? 1 : 0)
SellTurns = (Rsi < Rsi[1] ? 1 : 0) + (MacdHist < MacdHist[1] ? 1 : 0) + (Stoch < Stoch[1] ? 1 : 0)
MinTurns = Activity == "Responsive" ? 1 : Activity == "Selective" ? 3 : 2
BuyMomentum = BuyTurns >= MinTurns
SellMomentum = SellTurns >= MinTurns
BuyMicroBreak = close > high[1]
SellMicroBreak = close < low[1]
BuyRejection = LowerWick >= (Activity == "Selective" ? 0.25 : 0.15) and BuyClosePos >= 0.71 and close > close[1]
SellRejection = UpperWick >= (Activity == "Selective" ? 0.25 : 0.15) and SellClosePos >= 0.71 and close < close[1]
BuyStructureOK = not UseStructureValidation or (BuyMicroBreak or BuyRejection)
SellStructureOK = not UseStructureValidation or (SellMicroBreak or SellRejection)
BuyRecovery = BuyMicroBreak
SellRecovery = SellMicroBreak
CenterSlopeATR = Volatility > 0.0 ? (CenterMA - CenterMA[5]) / Volatility : 0.0
FallingKnife = Adx >= 29.0 and MinusDI > PlusDI * 1.30 and CenterSlopeATR <= -0.24
RisingKnife = Adx >= 29.0 and PlusDI > MinusDI * 1.30 and CenterSlopeATR >= 0.24
BuyContextOK = not UseTrendContext or not FallingKnife or (BuyTurns == 3 and BuyMicroBreak and LowerWick >= 0.11 and close > close[1])
SellContextOK = not UseTrendContext or not RisingKnife or (SellTurns == 3 and SellMicroBreak and UpperWick >= 0.11 and close < close[1])
ShockOK = not UseRegimeFilter or BarATR <= (Activity == "Responsive" ? 3.2 : Activity == "Selective" ? 2.25 : 2.75)
Sma200 = ta.sma(close, 200)
MeanReversionATR = ta.ema(Volatility, 21)
SmaDistanceATR = not na(Sma200) and MeanReversionATR > 0.0 ? (close - Sma200) / MeanReversionATR : na
BuySmaOK = not UseMeanReversion or (not na(SmaDistanceATR) and SmaDistanceATR <= MaxSmaExtension)
SellSmaOK = not UseMeanReversion or (not na(SmaDistanceATR) and SmaDistanceATR >= -MaxSmaExtension)
ScoreReversion(bool IsBuy, int TurnCount, bool MicroBreak, bool Rejection, float CandleClosePos, bool ContextOK, float RecentDepth) =>
    ZoneAbs = IsBuy ? math.max((-PriceZone) - 1.0, 0.0) : math.max(PriceZone - 1.0, 0.0)
    Deepest = math.max(RecentDepth - 1.0, 0.0)
    RoomToCenter = (ZoneAbs + 1.0) * InnerRadius / math.max(AtrSmooth, syminfo.mintick)
    ZonePts = 14.0 + Unit(ZoneAbs, EntryDepth, 0.62) * 14.0
    TestPts = 9.0 + Unit(Deepest, TouchDepth, 0.65) * 8.0
    TurningPts = TurnCount * 6.0
    CandlePts = Unit(BodyShare, 0.23, 0.74) * 8.0 + Unit(CandleClosePos, 0.58, 0.96) * 8.0
    StructurePts = MicroBreak ? 10.0 : Rejection ? 6.0 : 0.0
    ContextPts = ContextOK ? 8.0 : 0.0
    RoomPts = Unit(RoomToCenter, 0.25, 1.8) * 8.0
    ShockPenalty = Unit(BarATR, 2.0, 3.5) * 12.0
    int(math.round(Cap(ZonePts + TestPts + TurningPts + CandlePts + StructurePts + ContextPts + RoomPts - ShockPenalty, 0.0, 100.0)))
BuyScore = ScoreReversion(true, BuyTurns, BuyMicroBreak, BuyRejection, BuyClosePos, BuyContextOK, -LowestRecentZone)
SellScore = ScoreReversion(false, SellTurns, SellMicroBreak, SellRejection, SellClosePos, SellContextOK, HighestRecentZone)
ScoreFloor = Activity == "Responsive" ? 55 : Activity == "Selective" ? 75 : 63
Spacing = math.max(SignalGap, Activity == "Responsive" ? 7 : Activity == "Selective" ? 18 : 10)
var BuyUsedInExcursion = false
var SellUsedInExcursion = false
var int LastSignalBar = na
if not na(PriceZone) and PriceZone >= -0.025
    BuyUsedInExcursion := false
if not na(PriceZone) and PriceZone <= 0.025
    SellUsedInExcursion := false
SpacingOK = na(LastSignalBar) or bar_index - LastSignalBar >= Spacing
RawBuyAttempt = barstate.isconfirmed and LowerZone and LowerTouched and BuyMomentum and BuyCandleOK and not BuyUsedInExcursion and SpacingOK
RawSellAttempt = barstate.isconfirmed and UpperZone and UpperTouched and SellMomentum and SellCandleOK and not SellUsedInExcursion and SpacingOK
BuyEligible = RawBuyAttempt and BuyStructureOK and BuyContextOK and ShockOK and BuySmaOK and BuyHTF and BuyScore >= ScoreFloor
SellEligible = RawSellAttempt and SellStructureOK and SellContextOK and ShockOK and SellSmaOK and SellHTF and SellScore >= ScoreFloor
BuyRecoverySignal = BuyEligible and BuyRecovery
SellRecoverySignal = SellEligible and SellRecovery
BuyRejectionSignal = BuyEligible and not BuyRecoverySignal and BuyRejection
SellRejectionSignal = SellEligible and not SellRecoverySignal and SellRejection
BuySignal = BuyRecoverySignal or BuyRejectionSignal
SellSignal = SellRecoverySignal or SellRejectionSignal
BuyRejected = RawBuyAttempt and not BuySignal
SellRejected = RawSellAttempt and not SellSignal
if BuySignal or SellSignal
    LastSignalBar := bar_index
    if BuySignal
        BuyUsedInExcursion := true
    if SellSignal
        SellUsedInExcursion := true
ModelFlipUp = barstate.isconfirmed and Side == 1 and Side[1] == -1
ModelFlipDown = barstate.isconfirmed and Side == -1 and Side[1] == 1
HtfAligned = UseHTF and ValidHTF and Side != 0 and Side == HtfSide
NewHTFAlignment = barstate.isconfirmed and HtfAligned and not HtfAligned[1]
WeakADXCrossover = ta.crossunder(Adx, 18.0)
TrendWeakening = barstate.isconfirmed and Side != 0 and WeakADXCrossover
 
 
//Drawing
 
TrendTone = Side == 1 ? UpTone : Side == -1 ? DownTone : NeutralTone
PulseTone = color.from_gradient(math.abs(Pulse), 0.0, 0.8, color.new(NeutralTone, 8), TrendTone)
UpperTone = #FF477E
LowerTone = #00D5FF
CenterPlot = plot(ShowPulse or ShowBand ? CenterMA : na, "Pulse Gradient Reference", color=color.new(PulseTone, 100), editable=false, display=display.pane)
InnerUpPlot = plot(ShowBand ? LvlUp : na, "Inner Band Upper", color=color.new(UpperTone, 76), linewidth=1, display=display.pane)
InnerDownPlot = plot(ShowBand ? LvlDown : na, "Inner Band Lower", color=color.new(LowerTone, 76), linewidth=1, display=display.pane)
OuterUpPlot = plot(ShowBand ? Up161 : na, "Outer Band Upper 161.8", color=color.new(UpperTone, 82), linewidth=1, display=display.pane)
OuterDownPlot = plot(ShowBand ? Down161 : na, "Outer Band Lower 161.8", color=color.new(LowerTone, 82), linewidth=1, display=display.pane)
fill(CenterPlot, OuterUpPlot, Up161, CenterMA, color.new(UpperTone, 96), color.new(UpperTone, 70), title="Upper 161.8 Neon Gradient")
fill(CenterPlot, OuterDownPlot, CenterMA, Down161, color.new(LowerTone, 70), color.new(LowerTone, 96), title="Lower 161.8 Neon Gradient")
fill(InnerUpPlot, InnerDownPlot, color=color.new(NeutralTone, 96), title="Violet Inner Atmosphere")
plot(ShowPulse ? CenterMA : na, "Pulse Outer Glow", color=color.new(PulseTone, 93), linewidth=10, display=display.pane)
plot(ShowPulse ? CenterMA : na, "Pulse Inner Glow", color=color.new(PulseTone, 78), linewidth=6, display=display.pane)
plot(ShowPulse ? CenterMA : na, "MR Pulse", color=PulseTone, linewidth=2, display=display.pane)
plot(ShowEntryZones ? LvlDown : na, "Band 1 Lower", color=color.new(LowerTone, 72), linewidth=1, display=display.pane)
plot(ShowEntryZones ? LvlUp : na, "Band 1 Upper", color=color.new(UpperTone, 72), linewidth=1, display=display.pane)
plot(ShowEntryZones ? BuyZoneBoundary : na, "BUY Zone Boundary", color=color.new(LowerTone, 45), linewidth=1, display=display.pane)
plot(ShowEntryZones ? SellZoneBoundary : na, "SELL Zone Boundary", color=color.new(UpperTone, 45), linewidth=1, display=display.pane)
plot(ShowRejected and BuyRejected ? low - Volatility * 0.65 : na, "Rejected Lower-Band BUY", style=plot.style_circles, color=color.new(LowerTone, 15), linewidth=2, display=display.pane)
plot(ShowRejected and SellRejected ? high + Volatility * 0.65 : na, "Rejected Upper-Band SELL", style=plot.style_circles, color=color.new(UpperTone, 15), linewidth=2, display=display.pane)
BuyMarkerY = low - Volatility * 0.45
SellMarkerY = high + Volatility * 0.45
BuyLabelY = low - Volatility * 0.72
SellLabelY = high + Volatility * 0.72
plotshape(ShowSignals and BuySignal ? BuyMarkerY : na, title="BUY Marker", style=shape.triangleup, location=location.absolute, color=UpTone, size=size.small)
plotshape(ShowSignals and SellSignal ? SellMarkerY : na, title="SELL Marker", style=shape.triangledown, location=location.absolute, color=DownTone, size=size.small)
if ShowSignals and BuySignal
    label.new(bar_index, BuyLabelY, "BUY  •  " + Rank(BuyScore) + "  •  " + str.tostring(BuyScore), yloc=yloc.price, style=label.style_label_up, color=color.new(UpTone, 8), textcolor=#06131A, size=size.small, tooltip="Lower-band mean reversion | " + (BuyRecoverySignal ? "RECOVERY" : "REJECTION"))
if ShowSignals and SellSignal
    label.new(bar_index, SellLabelY, "SELL  •  " + Rank(SellScore) + "  •  " + str.tostring(SellScore), yloc=yloc.price, style=label.style_label_down, color=color.new(DownTone, 8), textcolor=color.white, size=size.small, tooltip="Upper-band mean reversion | " + (SellRecoverySignal ? "RECOVERY" : "REJECTION"))
plot(float(BuyScore), "Buy Score", display=display.data_window)
plot(float(SellScore), "Sell Score", display=display.data_window)
plot(PriceZone, "Position Within Inner Band", display=display.data_window)
plot(SmaDistanceATR, "SMA 200 Distance (ATR)", display=display.data_window)
plot(float(BuyRejected ? 1 : 0), "Rejected BUY Candidate", display=display.data_window)
plot(float(SellRejected ? 1 : 0), "Rejected SELL Candidate", display=display.data_window)
 
 
//Alerts
 
alertcondition(BuySignal, "Confirmed BUY", "{{ticker}} | {{interval}} | MR LOWER BAND BUY | Entry Score: {{plot(\"Buy Score\")}}/100")
alertcondition(SellSignal, "Confirmed SELL", "{{ticker}} | {{interval}} | MR UPPER BAND SELL | Entry Score: {{plot(\"Sell Score\")}}/100")
alertcondition(ModelFlipUp, "Model Turns Bullish", "{{ticker}} | {{interval}} | MR model bullish")
alertcondition(ModelFlipDown, "Model Turns Bearish", "{{ticker}} | {{interval}} | MR model bearish")
alertcondition(NewHTFAlignment, "HTF Alignment", "{{ticker}} | {{interval}} | MR higher timeframe alignment")
alertcondition(TrendWeakening, "Trend Weakening", "{{ticker}} | {{interval}} | MR trend weakening")
alertcondition(BuyRecoverySignal, "BUY · Lower Band Recovery", "{{ticker}} | {{interval}} | MR lower-band recovery")
alertcondition(SellRecoverySignal, "SELL · Upper Band Recovery", "{{ticker}} | {{interval}} | MR upper-band recovery")
alertcondition(BuyRejectionSignal, "BUY · Lower Band Rejection", "{{ticker}} | {{interval}} | MR lower-band rejection")
alertcondition(SellRejectionSignal, "SELL · Upper Band Rejection", "{{ticker}} | {{interval}} | MR upper-band rejection")

← 返回列表