Chandelier Exit Reaction Zones + Fib Levels

MYNAMEISBRANDON · study · 1807 行 · 点赞 100 · TradingView 原页

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

Pine Script

//@version=6
indicator("Chandelier Exit Reaction Zones + Fib Levels", "CE Zones", overlay=true, max_labels_count=500, calc_bars_count=1500)
 
 
const string G_MAIN      = "Main Settings"
const string G_ACTIVE    = "ATR(14) Multiplier 10 Level"
const string G_EXT       = "ATR(14) Multiplier 10x Level"
const string G_FIB       = "Fib Levels"
const string G_VIS       = "Visuals"
const string G_REACT     = "ATR Reaction Zones"
const string G_REACT_DBG = "ATR Zones Table"
const string G_ALERT     = "Alerts"
 
// ==============================================================================================
// 🟢 REGION: Tooltip Strings
// ==============================================================================================
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Main Settings
// ──────────────────────────────────────────────
const string TT_ATR_LEN =
     "ATR lookback period used by the ladder engine.\n\n" +
     "Higher values smooth the ladder and react more slowly.\n" +
     "Lower values make the ladder more responsive."
 
const string TT_ATR_MULT =
     "ATR multiplier used to build the active 10 / 10x ladder distance.\n\n" +
     "Higher values place the ladder farther from price.\n" +
     "Lower values keep it tighter."
 
const string TT_USE_CLOSE =
     "Controls which price basis the ladder uses.\n\n" +
     "• Close → uses highest/lowest close\n" +
     "• Wicks → uses highest high / lowest low"
 
const string TT_AWAIT_CONFIRM =
     "Controls when the ladder is allowed to flip.\n\n" +
     "• On Bar Close → waits for candle confirmation\n" +
     "• Real Time    → allows intrabar live flipping from the current close"
 
const string TT_PLOT_LAST =
     "Number of most recent bars to draw for ladder plots that use show_last.\n\n" +
     "Lower values shorten visible history and declutter the chart."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Active 10 Level
// ──────────────────────────────────────────────
const string TT_SHOW_ACTIVE_LINE =
     "Shows or hides the current active ATR 10 anchor line."
 
const string TT_SHOW_FLIP_LABELS =
     "Prints a historical left-side label whenever the active 10 anchor flips direction."
 
const string TT_SHOW_ACTIVE_RIGHT_LABEL =
     "Shows or hides the right-side label for the active 10 anchor."
 
const string TT_BULL_ACTIVE_COLOR =
     "Fallback bull color for the active 10 anchor when ladder-based ATR coloring is turned off."
 
const string TT_BEAR_ACTIVE_COLOR =
     "Fallback bear color for the active 10 anchor when ladder-based ATR coloring is turned off."
 
const string TT_ACTIVE_LINE_WIDTH =
     "Line width for the active 10 anchor."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Extension 10x Level
// ──────────────────────────────────────────────
const string TT_SHOW_EXT_LINE =
     "Shows or hides the opposite-side extension 10x anchor line."
 
const string TT_SHOW_EXT_RIGHT_LABEL =
     "Shows or hides the right-side label for the extension 10x anchor."
 
const string TT_BULL_EXT_COLOR =
     "Fallback bull-state extension color when ladder-based ATR coloring is turned off."
 
const string TT_BEAR_EXT_COLOR =
     "Fallback bear-state extension color when ladder-based ATR coloring is turned off."
 
const string TT_EXT_LINE_WIDTH =
     "Line width for the extension 10x anchor."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Fib Ladder
// ──────────────────────────────────────────────
const string TT_SHOW_OUTER_FIB_LINES =
     "Shows the outer extension lines around the main 0 → 1 ATR channel.\n\n" +
     "Includes:\n" +
     "• -0.236\n" +
     "• -0.382\n" +
     "• 1.236\n" +
     "• 1.382"
 
const string TT_SHOW_OUTER_FIB_LABELS =
     "Shows or hides the right-side labels for the outer extension fib levels."
 
const string TT_SHOW_CORE_FIB_LINES =
     "Shows the core fib ladder inside the ATR channel.\n\n" +
     "Includes:\n" +
     "• 0.236\n" +
     "• 0.382\n" +
     "• 0.500\n" +
     "• 0.618\n" +
     "• 0.786"
 
const string TT_SHOW_CORE_FIB_LABELS =
     "Shows or hides the right-side labels for the core fib ladder."
 
const string TT_FIB_LINE_WIDTH =
     "Line width for fib ladder levels."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Visuals
// ──────────────────────────────────────────────
const string TT_USE_ADAPTIVE_FIB_COLORS =
     "Uses the ladder color engine to color fib levels by position in the channel.\n\n" +
     "When off, the two fib color pickers directly below this toggle are used instead."
 
const string TT_BULL_FIB_COLOR =
     "Fallback bull fib color used when Use Adaptive Fib Colors is turned off.\n\n" +
     "This applies to fib lines and fib labels."
 
const string TT_BEAR_FIB_COLOR =
     "Fallback bear fib color used when Use Adaptive Fib Colors is turned off.\n\n" +
     "This applies to fib lines and fib labels."
 
const string TT_SHOW_FIB_BIAS_CANDLES =
     "Recolors candles to match the ladder state color.\n\n" +
     "Candle body transparency is controlled separately."
 
const string TT_COLOR_ATR_LEVELS_AND_LABELS_BY_LADDER =
     "Lets the ladder color engine control both the 10 / 10x lines and their labels.\n\n" +
     "When off, those anchors use their own dedicated color inputs."
 
const string TT_CANDLE_BODY_TRANSP =
     "Transparency for the ladder-colored candle body.\n\n" +
     "• 0   = solid body\n" +
     "• 100 = invisible body\n\n" +
     "Borders and wicks remain full color."
 
const string TT_ATR_ANCHOR_LABEL_MODE =
     "Controls the text used for the 10 / 10x anchor labels.\n\n" +
     "• ATR Only  → 10 and 10x\n" +
     "• Fib Only  → 0 and 1.0\n" +
     "• ATR + Fib → 0/10 and 1.0/10x"
 
const string TT_LABEL_SIZE =
     "Text size used by the right-side ladder labels."
 
const string TT_RIGHT_PAD_MAIN =
     "EM-space padding used before the 10 / 10x right-side labels."
 
const string TT_RIGHT_PAD_FIB =
     "EM-space padding used before the fib right-side labels."
 
const string TT_SHOW_PRICES_IN_LABELS =
     "Controls whether right-side labels include the current price.\n\n" +
     "• Show → append the price level\n" +
     "• Hide → label text only"
 
const string TT_FILL_CHANNEL =
     "Controls the fill between the active ATR 10 anchor and the ATR 10x extension.\n\n" +
     "• Fill → show the channel fill\n" +
     "• None → hide the channel fill"
 
const string TT_FILL_OPACITY =
     "Opacity of the channel fill when fill is enabled.\n\n" +
     "• 0   = solid fill\n" +
     "• 100 = invisible fill"
 
const string TT_BULL_FILL_COLOR =
     "Base fill color used in bull state."
 
const string TT_BEAR_FILL_COLOR =
     "Base fill color used in bear state."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Close Line Settings
// ──────────────────────────────────────────────
const string TT_CLOSE_LINE_MODE =
     "Controls the close-price plot display.\n\n" +
     "• None        → hides the close line\n" +
     "• Last N Bars → shows only the most recent close history"
 
const string TT_CLOSE_LOOKBACK =
     "Number of recent bars shown by the close-price line when Last N Bars mode is selected."
 
const string TT_CLOSE_LINE_WIDTH =
     "Line width for the close-price plot."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Bar Index Follow Line Settings
// ──────────────────────────────────────────────
const string TT_EXTEND_LEFT =
     "Shows a persistent close-follow line extending left from the current bar."
 
const string TT_EXTEND_LEFT_BARS =
     "How many bars left the close-follow line extends."
 
const string TT_LEFT_LINE_STYLE =
     "Line style for the left close-follow segment."
 
const string TT_EXTEND_RIGHT =
     "Shows a persistent close-follow line extending right from the current bar."
 
const string TT_EXTEND_RIGHT_BARS =
     "How many bars right the close-follow line extends."
 
const string TT_RIGHT_LINE_STYLE =
     "Line style for the right close-follow segment."
 
const string TT_FOLLOW_LINE_WIDTH =
     "Line width used by the left and right close-follow segments."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Alerts
// ──────────────────────────────────────────────
const string TT_ALERT_ATR10_TOUCH =
     "Creates alerts when price touches the active ATR 10 level.\n\n" +
     "The alert conditions are state-aware, so bull and bear touches are separated."
 
const string TT_ALERT_ATR10X_TOUCH =
     "Creates alerts when price touches the ATR 10x extension level.\n\n" +
     "The alert conditions are state-aware, so bull and bear touches are separated."
 
// ==============================================================================================
// 🔴 END REGION: Tooltip Strings
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Main Inputs
// ==============================================================================================
 
int in_atrLen = input.int(
     defval=14,
     minval=1,
     title="ATR Period",
     group=G_MAIN,
     tooltip=TT_ATR_LEN)
 
float in_atrMult = input.float(
     defval=10.0,
     minval=0.1,
     step=0.1,
     title="ATR Multiplier",
     group=G_MAIN,
     tooltip=TT_ATR_MULT)
 
string in_useCloseMode = input.string(
     defval="Close",
     title="Price Basis",
     options=["Close", "Wicks"],
     group=G_MAIN,
     tooltip=TT_USE_CLOSE)
 
bool in_useClose =
     in_useCloseMode == "Close"
 
string in_awaitBarConfirmationMode = input.string(
     defval="On Bar Close",
     title="Flip Timing",
     options=["On Bar Close", "Real Time"],
     group=G_MAIN,
     tooltip=TT_AWAIT_CONFIRM)
 
bool in_awaitBarConfirmation =
     in_awaitBarConfirmationMode == "On Bar Close"
 
int in_plotLast = input.int(
     defval=233,
     minval=1,
     title="Plot Last N Bars",
     group=G_MAIN,
     tooltip=TT_PLOT_LAST)
 
string in_reactionDebugMode = input.string(
     defval="Show",
     title="ATR Zones Table",
     options=["Show", "None"],
     group=G_REACT_DBG)
 
string in_reactionDebugPos = input.string(
     defval="Middle Right",
     title="Table Position",
     options=["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right", "Middle Left"],
     group=G_REACT_DBG)
 
string in_reactionDebugText = input.string(
     defval="Normal",
     title="Table Size",
     options=["Tiny", "Small", "Normal", "Large"],
     group=G_REACT_DBG)
 
bool in_showReactionDebug =
     in_reactionDebugMode == "Show"
 
bool in_enableAtr10TouchAlerts = input.bool(
     defval=false,
     title="ATR Mult 10 Touch Alerts",
     group=G_ALERT,
     tooltip=TT_ALERT_ATR10_TOUCH)
 
bool in_enableAtr10xTouchAlerts = input.bool(
     defval=false,
     title="ATR Mult 10x Touch Alerts",
     group=G_ALERT,
     tooltip=TT_ALERT_ATR10X_TOUCH)
 
// ==============================================================================================
// 🔴 END REGION: Main Inputs
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Active ATR Multipler 10 Inputs
// ==============================================================================================
 
bool in_showActiveLine = input.bool(
     defval=true,
     title="ATR Mult 10 Line",
     group=G_ACTIVE,
     tooltip=TT_SHOW_ACTIVE_LINE)
 
bool in_showFlipLabels = false// input.bool(
     //defval=false,
     //title="Show Flip Labels @ L",
     //group=G_ACTIVE,
     //tooltip=TT_SHOW_FLIP_LABELS)
 
bool in_showActiveRightLabel = input.bool(
     defval=true,
     title="ATR Mult 10 Label",
     group=G_ACTIVE,
     tooltip=TT_SHOW_ACTIVE_RIGHT_LABEL)
 
color in_bullActiveColor = input.color(
     defval=color.new(color.yellow, 35),
     title="Bull ATR Mult 10 Color",
     group=G_ACTIVE,
     tooltip=TT_BULL_ACTIVE_COLOR)
 
color in_bearActiveColor = input.color(
     defval=color.new(color.gray, 35),
     title="Bear ATR Mult 10 Color",
     group=G_ACTIVE,
     tooltip=TT_BEAR_ACTIVE_COLOR)
 
int in_activeLineWidth = input.int(
     defval=1,
     minval=1,
     maxval=6,
     title="ATR Mult 10 Line Width",
     group=G_ACTIVE,
     tooltip=TT_ACTIVE_LINE_WIDTH)
 
// ==============================================================================================
// 🔴 END REGION: Active ATR Multipler 10 Inputs
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Extension ATR Multiplier 10x Inputs
// ==============================================================================================
 
bool in_showExtLine = input.bool(
     defval=true,
     title="ATR Mult 10x Extension Line",
     group=G_EXT,
     tooltip=TT_SHOW_EXT_LINE)
 
bool in_showExtRightLabel = input.bool(
     defval=true,
     title="ATR Mult 10x Extension Label",
     group=G_EXT,
     tooltip=TT_SHOW_EXT_RIGHT_LABEL)
 
color in_bullExtColor = input.color(
     defval=color.new(color.gray, 20),
     title="Bull ATR Mult 10x Extension Color",
     group=G_EXT,
     tooltip=TT_BULL_EXT_COLOR)
 
color in_bearExtColor = input.color(
     defval=color.new(color.yellow, 20),
     title="Bear ATR Mult 10x Extension Color",
     group=G_EXT,
     tooltip=TT_BEAR_EXT_COLOR)
 
int in_extLineWidth = input.int(
     defval=1,
     minval=1,
     maxval=6,
     title="ATR Mult 10x Extension Line Width",
     group=G_EXT,
     tooltip=TT_EXT_LINE_WIDTH)
 
// ==============================================================================================
// 🔴 END REGION: Extension ATR Multiplier 10x Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Fib Inputs
// ==============================================================================================
 
bool in_showOuterFibLines = input.bool(
     defval=false,
     title="Fib Extensions (-0.236, -0.382, 1.236, 1.382)",
     group=G_FIB,
     tooltip=TT_SHOW_OUTER_FIB_LINES)
 
bool in_showOuterFibLabels = input.bool(
     defval=true,
     title="Fib Extension Labels",
     group=G_FIB,
     tooltip=TT_SHOW_OUTER_FIB_LABELS)
 
bool in_showCoreFibLines = input.bool(
     defval=false,
     title="Core Fib Lines (0.236, 0.382, 0.500, 0.618, 0.786)",
     group=G_FIB,
     tooltip=TT_SHOW_CORE_FIB_LINES)
 
bool in_showCoreFibLabels = input.bool(
     defval=true,
     title="Core Fib Labels",
     group=G_FIB,
     tooltip=TT_SHOW_CORE_FIB_LABELS)
 
int in_fibLineWidth = input.int(
     defval=1,
     minval=1,
     maxval=4,
     title="Fib Line Width",
     group=G_FIB,
     tooltip=TT_FIB_LINE_WIDTH)
 
// ==============================================================================================
// 🔴 END REGION: Fib Inputs
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Visual Inputs
// ==============================================================================================
 
bool in_useAdaptiveFibColors = input.bool(
     defval=true,
     title="Adaptive Fib Colors",
     group=G_VIS,
     tooltip=TT_USE_ADAPTIVE_FIB_COLORS)
 
color in_bullFibColor = input.color(
     defval=color.new(color.yellow, 70),
     title="  ↳Bull Fib Color (Adaptive Off)",
     group=G_VIS,
     tooltip=TT_BULL_FIB_COLOR)
 
color in_bearFibColor = input.color(
     defval=color.new(color.gray, 70),
     title="  ↳Bear Fib Color (Adaptive Off)",
     group=G_VIS,
     tooltip=TT_BEAR_FIB_COLOR)
 
bool in_showFibBiasCandles = input.bool(
     defval=true,
     title="Color Candles by Fib Ladder Bias",
     group=G_VIS,
     tooltip=TT_SHOW_FIB_BIAS_CANDLES)
 
bool in_colorAtrLevelsAndLabelsByLadder = input.bool(
     defval=true,
     title="Color ATR 10 Levels + Labels by Ladder",
     group=G_VIS,
     tooltip=TT_COLOR_ATR_LEVELS_AND_LABELS_BY_LADDER)
 
int in_candleBodyTransp = input.int(
     defval=70,
     minval=0,
     maxval=100,
     title="Fib Bias Candle Body Transparency",
     group=G_VIS,
     tooltip=TT_CANDLE_BODY_TRANSP)
 
string in_atrAnchorLabelMode = input.string(
     defval="ATR + Fib",
     title="ATR Label Text",
     options=["ATR Only", "Fib Only", "ATR + Fib"],
     group=G_VIS,
     tooltip=TT_ATR_ANCHOR_LABEL_MODE)
 
string in_labelSizeText = input.string(
     defval="Normal",
     title="Right Label Size",
     options=["Tiny", "Small", "Normal", "Large", "Huge"],
     group=G_VIS,
     tooltip=TT_LABEL_SIZE)
 
int in_rightPadMain = input.int(
     defval=12,
     minval=0,
     maxval=100,
     title="Right Padding - Main Labels",
     group=G_VIS,
     tooltip=TT_RIGHT_PAD_MAIN)
 
int in_rightPadFib = input.int(
     defval=12,
     minval=0,
     maxval=100,
     title="Right Padding - Fib Labels",
     group=G_VIS,
     tooltip=TT_RIGHT_PAD_FIB)
 
string in_showPricesInLabelsMode = input.string(
     defval="Show",
     title="Price In Right Labels",
     options=["Show", "Hide"],
     group=G_VIS,
     tooltip=TT_SHOW_PRICES_IN_LABELS)
 
bool in_showPricesInLabels =
     in_showPricesInLabelsMode == "Show"
 
string in_fillChannelMode = input.string(
     defval="None",
     title="Fill Between Active and Extension",
     options=["Fill", "None"],
     group=G_VIS,
     tooltip=TT_FILL_CHANNEL)
 
bool in_fillChannel =
     in_fillChannelMode == "Fill"
 
int in_fillOpacity = input.int(
     defval=92,
     minval=0,
     maxval=100,
     title="Fill Opacity",
     group=G_VIS,
     tooltip=TT_FILL_OPACITY)
 
color in_bullFillColor = input.color(
     defval=color.yellow,
     title="Bull Fill Color",
     group=G_VIS,
     tooltip=TT_BULL_FILL_COLOR)
 
color in_bearFillColor = input.color(
     defval=color.gray,
     title="Bear Fill Color",
     group=G_VIS,
     tooltip=TT_BEAR_FILL_COLOR)
 
// ==============================================================================================
// 🔴 END REGION: Visual Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: ATR Reaction Zone Inputs
// ==============================================================================================
 
bool in_showReactionZones = input.bool(
     defval=true,
     title="ATR Reaction Zones",
     group=G_REACT)
 
float in_reactionMult1 = input.float(
     defval=5.0,
     minval=0.1,
     step=0.5,
     title="Multiplier 1",
     group=G_REACT)
 
float in_reactionMult2 = input.float(
     defval=7.5,
     minval=0.1,
     step=0.5,
     title="Multiplier 2",
     group=G_REACT)
 
bool in_fillReactionZones = input.bool(
     defval=true,
     title="Fill Zones",
     group=G_REACT)
 
int in_reactionZoneOpacity = input.int(
     defval=85,
     minval=0,
     maxval=100,
     title="Zone Opacity",
     group=G_REACT)
 
int in_reactionZoneLineWidth = input.int(
     defval=1,
     minval=1,
     maxval=4,
     title="Zone Line Width",
     group=G_REACT)
 
// ==============================================================================================
// 🔴 END REGION: ATR Reaction Zone Inputs
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Helpers
// ==============================================================================================
 
labelSize =
     in_labelSizeText == "Tiny"   ? size.tiny  :
     in_labelSizeText == "Small"  ? size.small :
     in_labelSizeText == "Large"  ? size.large :
     in_labelSizeText == "Huge"   ? size.huge  : size.normal
 
color invisibleBg = color.new(color.black, 100)
 
f_spacer(int _count) =>
    var string em = " "
    string out = ""
    for i = 1 to _count
        out += em
    out
 
f_priceStr(float _price) =>
    str.tostring(math.round_to_mintick(_price))
 
f_multText(float _mult) =>
    str.tostring(_mult, "#.##")
 
f_fibText(float _fib) =>
    str.tostring(_fib, "#.###")
 
f_labelText(string _tag, float _price, bool _showPrice, int _pad) =>
    string _priceTxt = _showPrice and not na(_price) ? " " + f_priceStr(_price) : ""
    f_spacer(_pad) + _tag + " -" + _priceTxt
 
f_syncRightLabel(label _lbl, bool _show, float _y, string _txt, color _txtColor) =>
    label out = _lbl
    if _show and not na(_y)
        if na(out)
            out := label.new(
                 x=bar_index,
                 y=_y,
                 text=_txt,
                 xloc=xloc.bar_index,
                 yloc=yloc.price,
                 style=label.style_label_center,
                 color=invisibleBg,
                 textcolor=_txtColor,
                 size=labelSize)
        else
            label.set_xy(out, bar_index, _y)
            label.set_text(out, _txt)
            label.set_textcolor(out, _txtColor)
            label.set_color(out, invisibleBg)
            label.set_size(out, labelSize)
    else
        if not na(out)
            label.delete(out)
            out := na
    out
 
f_fibLevel(float _active, float _ext, float _fib) =>
    na(_active) or na(_ext) ? na : _active + (_ext - _active) * _fib
 
f_chandelier(float _mult, int _len, bool _useClose, bool _awaitConfirm) =>
    float atrValue = ta.atr(_len) * _mult
 
    float highestClose = ta.highest(close, _len)
    float highestHigh = ta.highest(high, _len)
    float lowestClose = ta.lowest(close, _len)
    float lowestLow = ta.lowest(low, _len)
 
    float bullBase = _useClose ? highestClose : highestHigh
    float bearBase = _useClose ? lowestClose : lowestLow
 
    float bullStop = bullBase - atrValue
    float bullPrev = nz(bullStop[1], bullStop)
    bullStop := close[1] > bullPrev ? math.max(bullStop, bullPrev) : bullStop
 
    float bearStop = bearBase + atrValue
    float bearPrev = nz(bearStop[1], bearStop)
    bearStop := close[1] < bearPrev ? math.min(bearStop, bearPrev) : bearStop
 
    float confirmedClose = barstate.isconfirmed ? close : close[1]
    float liveClose = close
 
    int dirConfirmed = 1
    dirConfirmed := nz(dirConfirmed[1], 1)
    dirConfirmed := confirmedClose > bearPrev ? 1 : confirmedClose < bullPrev ? -1 : dirConfirmed
 
    int dirLive = 1
    dirLive := nz(dirLive[1], 1)
    dirLive := liveClose > bearPrev ? 1 : liveClose < bullPrev ? -1 : dirLive
 
    bool bullFlipConfirmed = dirConfirmed == 1 and nz(dirConfirmed[1], 1) == -1
    bool bearFlipConfirmed = dirConfirmed == -1 and nz(dirConfirmed[1], 1) == 1
 
    bool bullFlipLive = dirLive == 1 and nz(dirLive[1], 1) == -1
    bool bearFlipLive = dirLive == -1 and nz(dirLive[1], 1) == 1
 
    int dirOut = _awaitConfirm ? dirConfirmed : dirLive
    bool bullFlipOut = _awaitConfirm ? bullFlipConfirmed : bullFlipLive
    bool bearFlipOut = _awaitConfirm ? bearFlipConfirmed : bearFlipLive
 
    [dirOut, bullStop, bearStop, bullFlipOut, bearFlipOut]
 
f_chandelierLevelsOnly(float _mult, int _len, bool _useClose) =>
    float atrValue = ta.atr(_len) * _mult
 
    float highestClose = ta.highest(close, _len)
    float highestHigh = ta.highest(high, _len)
    float lowestClose = ta.lowest(close, _len)
    float lowestLow = ta.lowest(low, _len)
 
    float bullBase = _useClose ? highestClose : highestHigh
    float bearBase = _useClose ? lowestClose : lowestLow
 
    float bullStop = bullBase - atrValue
    float bullPrev = nz(bullStop[1], bullStop)
    bullStop := close[1] > bullPrev ? math.max(bullStop, bullPrev) : bullStop
 
    float bearStop = bearBase + atrValue
    float bearPrev = nz(bearStop[1], bearStop)
    bearStop := close[1] < bearPrev ? math.min(bearStop, bearPrev) : bearStop
 
    [bullStop, bearStop]
 
f_atrAnchorLabelText(string _atrTxt, bool _isExtension) =>
    string _fibTxt = _isExtension ? "1.0" : "0"
    in_atrAnchorLabelMode == "ATR Only" ? _atrTxt :
     in_atrAnchorLabelMode == "Fib Only" ? _fibTxt :
     _fibTxt + "/" + _atrTxt
 
f_reactionDbgPos(string _pos) =>
    _pos == "Top Left" ? position.top_left :
     _pos == "Bottom Right" ? position.bottom_right :
     _pos == "Bottom Left" ? position.bottom_left :
     _pos == "Middle Right" ? position.middle_right :
     _pos == "Middle Left" ? position.middle_left :
     position.top_right
 
f_reactionDbgTextSize(string _txt) =>
    _txt == "Tiny" ? size.tiny :
     _txt == "Small" ? size.small :
     _txt == "Large" ? size.large :
     size.normal
 
// ==============================================================================================
// 🔴 END REGION: Helpers
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Core Engine
// ==============================================================================================
 
[dir, bullLevel, bearLevel, bullFlip, bearFlip] =
     f_chandelier(
         in_atrMult,
         in_atrLen,
         in_useClose,
         in_awaitBarConfirmation)
 
float activeLevel = dir == 1 ? bullLevel : bearLevel
float extLevel    = dir == 1 ? bearLevel : bullLevel
 
string activeTag = f_multText(in_atrMult)
string extTag    = activeTag + "x"
 
string activeAnchorLabelText = f_atrAnchorLabelText(activeTag, false)
string extAnchorLabelText = f_atrAnchorLabelText(extTag, true)
 
color activeColor = dir == 1 ? in_bullActiveColor : in_bearActiveColor
color extColor =
     dir == 1 ? in_bearExtColor :
     in_bullExtColor
 
color fibColor = dir == 1 ? in_bullFibColor : in_bearFibColor
color fillColor =
     dir == 1 ? color.new(in_bullFillColor, in_fillOpacity) :
     color.new(in_bearFillColor, in_fillOpacity)
 
// ==============================================================================================
// 🔴 END REGION: Core Engine
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: ATR Reaction Zones
// ==============================================================================================
//
// 📌 Purpose:
//     Builds ATR 5.0 and ATR 7.5 reaction engines with their own state,
//     then fills from HLC3 to the active level in a Holy-Grail-style structure.
//
// 🧠 Why this version:
//     • behaves much closer to Holy Grail ATR and your older 5.0 / 7.5 CE code
//     • does not rely on touch-arming
//     • keeps 7.5 as the back layer and 5.0 as the front layer
//
// ==============================================================================================
 
[reactionDir1, bullReaction1, bearReaction1, bullReactionFlip1, bearReactionFlip1] =
     f_chandelier(
         in_reactionMult1,
         in_atrLen,
         in_useClose,
         in_awaitBarConfirmation)
 
[reactionDir2, bullReaction2, bearReaction2, bullReactionFlip2, bearReactionFlip2] =
     f_chandelier(
         in_reactionMult2,
         in_atrLen,
         in_useClose,
         in_awaitBarConfirmation)
 
bool showBullReaction1 =
     dir == 1 and reactionDir1 == 1
 
bool showBearReaction1 =
     dir == -1 and reactionDir1 == -1
 
bool showBullReaction2 =
     dir == 1 and reactionDir2 == 1
 
bool showBearReaction2 =
     dir == -1 and reactionDir2 == -1
 
color bullReactionLineColor1 = color.rgb(255, 187, 80)
color bullReactionLineColor2 = color.rgb(255, 136, 0)
 
color bearReactionLineColor1 = color.rgb(255, 90, 155)
color bearReactionLineColor2 = color.rgb(200, 0, 130)
 
int reactionBackTransp =
     in_reactionZoneOpacity
 
int reactionFrontTransp =
     in_reactionZoneOpacity == 100 ? 100 : math.max(0, in_reactionZoneOpacity - 20)
 
color bullReactionFillBack =
     color.new(color.rgb(255, 136, 0), reactionBackTransp)
 
color bullReactionFillFront =
     color.new(color.rgb(255, 136, 0), reactionFrontTransp)
 
color bearReactionFillBack =
     color.new(#f51673, reactionBackTransp)
 
color bearReactionFillFront =
     color.new(#f51673, reactionFrontTransp)
 
// ==============================================================================================
// 🔴 END REGION: ATR Reaction Zones
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Adaptive Ladder Colors
// ==============================================================================================
 
f_ladderRatio(float _price) =>
    na(_price) or na(activeLevel) or na(extLevel) or extLevel == activeLevel ? na :
     (_price - activeLevel) / (extLevel - activeLevel)
 
f_levelColorByRatio(float _ratio) =>
    if na(_ratio)
        fibColor
    else if dir == 1
        _ratio <= -0.382 ? color.gray :
         _ratio < 0 ? color.rgb(205, 205, 205) :
         _ratio <= 0.236 ? #82ffda :
         _ratio <= 0.382 ? color.aqua :
         _ratio <= 0.500 ? color.teal :
         _ratio <= 0.618 ? color.yellow :
         _ratio <= 0.786 ? #ffb23e :
         _ratio <= 1.000 ? #ff8800 :
         _ratio <= 1.236 ? #ff9742 :
         _ratio <= 1.382 ? #ff591d :
         color.rgb(255, 137, 41)
    else
        _ratio <= -0.382 ? color.aqua :
         _ratio < 0 ? color.teal :
         _ratio <= 0.000 ? color.rgb(205, 205, 205) :
         _ratio <= 0.236 ? color.rgb(145, 145, 145) :
         _ratio <= 0.382 ? color.rgb(255, 184, 184) :
         _ratio <= 0.500 ? color.rgb(255, 145, 145) :
         _ratio <= 0.618 ? color.rgb(255, 102, 102) :
         _ratio <= 0.786 ? color.rgb(255, 58, 88) :
         _ratio <= 1.000 ? color.rgb(220, 0, 110) :
         _ratio <= 1.236 ? color.rgb(180, 0, 170) :
         _ratio <= 1.382 ? color.rgb(145, 0, 195) :
         color.rgb(120, 0, 220)
         
f_stateColorByRatio(float _ratio) =>
    if na(_ratio)
        na
    else if _ratio < 0
        dir == 1 ? color.purple : color.rgb(255, 81, 0)
    else if _ratio > 1
        dir == 1 ? color.rgb(255, 81, 0) : #7727b0
    else
        f_levelColorByRatio(_ratio)
 
float closeRatio = f_ladderRatio(close)
 
color ladderStateColor =
     in_useAdaptiveFibColors ? f_stateColorByRatio(closeRatio) : fibColor
 
color fibNeg382Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(-0.382) : fibColor
 
color fibNeg236Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(-0.236) : fibColor
 
color fib236Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(0.236) : fibColor
 
color fib382Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(0.382) : fibColor
 
color fib500Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(0.500) : fibColor
 
color fib618Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(0.618) : fibColor
 
color fib786Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(0.786) : fibColor
 
color fib1236Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(1.236) : fibColor
 
color fib1382Color =
     in_useAdaptiveFibColors ? f_levelColorByRatio(1.382) : fibColor
 
color activeAtrColor =
     in_colorAtrLevelsAndLabelsByLadder and in_useAdaptiveFibColors ? f_levelColorByRatio(0.000) : activeColor
 
color extAtrColor =
     in_colorAtrLevelsAndLabelsByLadder and in_useAdaptiveFibColors ? f_levelColorByRatio(1.000) : extColor
 
// ==============================================================================================
// 🔴 END REGION: Adaptive Ladder Colors
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Fib Ladder Values
// ==============================================================================================
 
float fibNeg382 = f_fibLevel(activeLevel, extLevel, -0.382)
float fibNeg236 = f_fibLevel(activeLevel, extLevel, -0.236)
float fib0      = f_fibLevel(activeLevel, extLevel,  0.000)
float fib236    = f_fibLevel(activeLevel, extLevel,  0.236)
float fib382    = f_fibLevel(activeLevel, extLevel,  0.382)
float fib500    = f_fibLevel(activeLevel, extLevel,  0.500)
float fib618    = f_fibLevel(activeLevel, extLevel,  0.618)
float fib786    = f_fibLevel(activeLevel, extLevel,  0.786)
float fib1      = f_fibLevel(activeLevel, extLevel,  1.000)
float fib1236   = f_fibLevel(activeLevel, extLevel,  1.236)
float fib1382   = f_fibLevel(activeLevel, extLevel,  1.382)
 
// ==============================================================================================
// 🔴 END REGION: Fib Ladder Values
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Historical Flip Labels @ L
// ==============================================================================================
 
if in_showFlipLabels and bullFlip
    label.new(
         x=bar_index,
         y=bullLevel,
         text=activeAnchorLabelText,
         xloc=xloc.bar_index,
         yloc=yloc.price,
         style=label.style_label_center,
         color=invisibleBg,
         textcolor=activeAtrColor,
         size=labelSize)
 
if in_showFlipLabels and bearFlip
    label.new(
         x=bar_index,
         y=bearLevel,
         text=activeAnchorLabelText,
         xloc=xloc.bar_index,
         yloc=yloc.price,
         style=label.style_label_center,
         color=invisibleBg,
         textcolor=activeAtrColor,
         size=labelSize)
 
// ==============================================================================================
// 🔴 END REGION: Historical Flip Labels @ L
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Right-Side Labels
// ==============================================================================================
 
var label lblActive    = na
var label lblExt       = na
var label lblFibNeg382 = na
var label lblFibNeg236 = na
var label lblFib236    = na
var label lblFib382    = na
var label lblFib500    = na
var label lblFib618    = na
var label lblFib786    = na
var label lblFib1236   = na
var label lblFib1382   = na
 
if barstate.islast
    lblActive := f_syncRightLabel(
         lblActive,
         in_showActiveRightLabel,
         activeLevel,
         f_labelText(activeAnchorLabelText, activeLevel, in_showPricesInLabels, in_rightPadMain),
         activeAtrColor)
 
    lblExt := f_syncRightLabel(
         lblExt,
         in_showExtRightLabel,
         extLevel,
         f_labelText(extAnchorLabelText, extLevel, in_showPricesInLabels, in_rightPadMain),
         extAtrColor)
 
    lblFib236 := f_syncRightLabel(
         lblFib236,
         in_showCoreFibLabels,
         fib236,
         f_labelText(f_fibText(0.236), fib236, in_showPricesInLabels, in_rightPadFib),
         fib236Color)
 
    lblFib382 := f_syncRightLabel(
         lblFib382,
         in_showCoreFibLabels,
         fib382,
         f_labelText(f_fibText(0.382), fib382, in_showPricesInLabels, in_rightPadFib),
         fib382Color)
 
    lblFib500 := f_syncRightLabel(
         lblFib500,
         in_showCoreFibLabels,
         fib500,
         f_labelText(f_fibText(0.500), fib500, in_showPricesInLabels, in_rightPadFib),
         fib500Color)
 
    lblFib618 := f_syncRightLabel(
         lblFib618,
         in_showCoreFibLabels,
         fib618,
         f_labelText(f_fibText(0.618), fib618, in_showPricesInLabels, in_rightPadFib),
         fib618Color)
 
    lblFib786 := f_syncRightLabel(
         lblFib786,
         in_showCoreFibLabels,
         fib786,
         f_labelText(f_fibText(0.786), fib786, in_showPricesInLabels, in_rightPadFib),
         fib786Color)
 
    lblFibNeg382 := f_syncRightLabel(
         lblFibNeg382,
         in_showOuterFibLabels,
         fibNeg382,
         f_labelText(f_fibText(-0.382), fibNeg382, in_showPricesInLabels, in_rightPadFib),
         fibNeg382Color)
 
    lblFibNeg236 := f_syncRightLabel(
         lblFibNeg236,
         in_showOuterFibLabels,
         fibNeg236,
         f_labelText(f_fibText(-0.236), fibNeg236, in_showPricesInLabels, in_rightPadFib),
         fibNeg236Color)
 
    lblFib1236 := f_syncRightLabel(
         lblFib1236,
         in_showOuterFibLabels,
         fib1236,
         f_labelText(f_fibText(1.236), fib1236, in_showPricesInLabels, in_rightPadFib),
         fib1236Color)
 
    lblFib1382 := f_syncRightLabel(
         lblFib1382,
         in_showOuterFibLabels,
         fib1382,
         f_labelText(f_fibText(1.382), fib1382, in_showPricesInLabels, in_rightPadFib),
         fib1382Color)
// ==============================================================================================
// 🔴 END REGION: Right-Side Labels
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Plots
// ==============================================================================================
 
activePlot = plot(
     in_showActiveLine ? activeLevel : na,
     title="Multiplier 10 Line",
     color=activeAtrColor,
     linewidth=in_activeLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
extPlot = plot(
     in_showExtLine ? extLevel : na,
     title="Multiplier 10 Extension Line",
     color=extAtrColor,
     linewidth=in_extLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fib236Plot = plot(
     in_showCoreFibLines ? fib236 : na,
     title="Fib 0.236",
     color=fib236Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fib382Plot = plot(
     in_showCoreFibLines ? fib382 : na,
     title="Fib 0.382",
     color=fib382Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fib500Plot = plot(
     in_showCoreFibLines ? fib500 : na,
     title="Fib 0.500",
     color=fib500Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fib618Plot = plot(
     in_showCoreFibLines ? fib618 : na,
     title="Fib 0.618",
     color=fib618Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fib786Plot = plot(
     in_showCoreFibLines ? fib786 : na,
     title="Fib 0.786",
     color=fib786Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fibNeg382Plot = plot(
     in_showOuterFibLines ? fibNeg382 : na,
     title="Fib -0.382",
     color=fibNeg382Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fibNeg236Plot = plot(
     in_showOuterFibLines ? fibNeg236 : na,
     title="Fib -0.236",
     color=fibNeg236Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fib1236Plot = plot(
     in_showOuterFibLines ? fib1236 : na,
     title="Fib 1.236",
     color=fib1236Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
 
fib1382Plot = plot(
     in_showOuterFibLines ? fib1382 : na,
     title="Fib 1.382",
     color=fib1382Color,
     linewidth=in_fibLineWidth,
     style=plot.style_stepline,
     show_last=in_plotLast)
     
reactionMidPlot = plot(
     in_showReactionZones and in_fillReactionZones ? hlc3 : na,
     title="Reaction Zone Mid Anchor",
     color=na,
     display=display.none)
 
bullReactionPlot1 = plot(
     in_showReactionZones and showBullReaction1 ? bullReaction1 : na,
     title="Bull ATR Multiplier 5",
     color=bullReactionLineColor1,
     linewidth=in_reactionZoneLineWidth,
     style=plot.style_linebr,
     show_last=in_plotLast)
 
bearReactionPlot1 = plot(
     in_showReactionZones and showBearReaction1 ? bearReaction1 : na,
     title="Bear ATR Multiplier 5",
     color=bearReactionLineColor1,
     linewidth=in_reactionZoneLineWidth,
     style=plot.style_linebr,
     show_last=in_plotLast)
 
bullReactionPlot2 = plot(
     in_showReactionZones and showBullReaction2 ? bullReaction2 : na,
     title="Bull ATR Multiplier 7.5",
     color=bullReactionLineColor2,
     linewidth=in_reactionZoneLineWidth,
     style=plot.style_linebr,
     show_last=in_plotLast)
 
bearReactionPlot2 = plot(
     in_showReactionZones and showBearReaction2 ? bearReaction2 : na,
     title="Bear ATR Multiplier 7.5",
     color=bearReactionLineColor2,
     linewidth=in_reactionZoneLineWidth,
     style=plot.style_linebr,
     show_last=in_plotLast)
 
// 7.5 goes behind
fill(
     reactionMidPlot,
     bullReactionPlot2,
     title="Bull ATR Mult 7.5 Fill",
     color=in_showReactionZones and in_fillReactionZones ? bullReactionFillBack : na)
 
fill(
     reactionMidPlot,
     bearReactionPlot2,
     title="Bear ATR Mult 7.5 Fill",
     color=in_showReactionZones and in_fillReactionZones ? bearReactionFillBack : na)
 
// 5.0 goes in front
fill(
     reactionMidPlot,
     bullReactionPlot1,
     title="Bull ATR Mult 5 Fill",
     color=in_showReactionZones and in_fillReactionZones ? bullReactionFillFront : na)
 
fill(
     reactionMidPlot,
     bearReactionPlot1,
     title="Bear ATR Mult 5 Fill",
     color=in_showReactionZones and in_fillReactionZones ? bearReactionFillFront : na)
 
// ==============================================================================================
// 🔴 END REGION: Plots
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Fib Bias Candle Coloring
// ==============================================================================================
//
// 📌 Purpose:
//     Recolors the chart candles using the current ladder-state color.
//
// 🧠 Behavior:
//     • Candle body uses the ladder color with user-controlled transparency
//     • Candle border stays full color
//     • Candle wick stays full color
//     • Only renders when Fib Bias Candles is enabled
//
// 🧰 Uses:
//     • ladderStateColor
//     • in_candleBodyTransp
//     • in_showFibBiasCandles
//
// ==============================================================================================
 
color fibBiasCandleBodyColor =
     na(ladderStateColor) ? na : color.new(ladderStateColor, in_candleBodyTransp)
 
color fibBiasCandleEdgeColor =
     ladderStateColor
 
plotcandle(
     open=in_showFibBiasCandles ? open : na,
     high=in_showFibBiasCandles ? high : na,
     low=in_showFibBiasCandles ? low : na,
     close=in_showFibBiasCandles ? close : na,
     color=fibBiasCandleBodyColor,
     wickcolor=fibBiasCandleEdgeColor,
     bordercolor=fibBiasCandleEdgeColor,
     title="ATR Ladder Bias Candle Color")
 
// ==============================================================================================
// 🔴 END REGION: Fib Bias Candle Coloring
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: ATR 10 Touch Alerts
// ==============================================================================================
//
// Purpose:
//     Creates state-aware alerts when price touches the active ATR 10 level
//     or the opposite-side ATR 10x extension.
//
// Behavior:
//     • ATR 10 touch = price touches the current active ladder anchor
//     • ATR 10x touch = price touches the current extension anchor
//     • Bull and bear conditions are separated into distinct alertconditions
//
// Notes:
//     • These are touch alerts, not cross alerts
//     • A touch is defined as the current bar's range spanning the level
//
// ==============================================================================================
 
bool atr10Touched =
     not na(activeLevel) and
     high >= activeLevel and
     low <= activeLevel
 
bool atr10xTouched =
     not na(extLevel) and
     high >= extLevel and
     low <= extLevel
 
bool bullAtr10Touch =
     in_enableAtr10TouchAlerts and
     dir == 1 and
     atr10Touched
 
bool bearAtr10Touch =
     in_enableAtr10TouchAlerts and
     dir == -1 and
     atr10Touched
 
bool bullAtr10xTouch =
     in_enableAtr10xTouchAlerts and
     dir == 1 and
     atr10xTouched
 
bool bearAtr10xTouch =
     in_enableAtr10xTouchAlerts and
     dir == -1 and
     atr10xTouched
 
alertcondition(
     bullAtr10Touch,
     title="Bull ATR 10 Touch",
     message="Bull state: price touched the active ATR 10 level.")
 
alertcondition(
     bearAtr10Touch,
     title="Bear ATR 10 Touch",
     message="Bear state: price touched the active ATR 10 level.")
 
alertcondition(
     bullAtr10xTouch,
     title="Bull ATR 10x Touch",
     message="Bull state: price touched the ATR 10x extension level.")
 
alertcondition(
     bearAtr10xTouch,
     title="Bear ATR 10x Touch",
     message="Bear state: price touched the ATR 10x extension level.")
 
// ==============================================================================================
// 🔴 END REGION: ATR 10 Touch Alerts
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Reaction Debug Table
// ==============================================================================================
//
// 📌 Purpose:
//     Shows the live rules that determine whether the current reaction-multiplier
//     fills are allowed to render.
//
// 🧠 What it answers:
//     • What is the main ladder direction now?
//     • What was the latest ATR 10 flip?
//     • What are the current reaction directions for Mult 1 and Mult 2?
//     • Which bull/bear reaction branches are active?
//     • Which fill branches are actually live right now?
//
// ==============================================================================================
 
var table reactionDbgTable = table.new(
     f_reactionDbgPos(in_reactionDebugPos),
     2,
     10,
     border_width=1,
     border_color=color.new(color.gray, 70))
 
string mainDirTxt =
     dir == 1 ? "Bull" : "Bear"
 
string reactionMult1Txt =
     str.tostring(in_reactionMult1, "#.#")
 
string reactionMult2Txt =
     str.tostring(in_reactionMult2, "#.#")
 
string reactionBandsTxt =
     reactionMult1Txt + " / " + reactionMult2Txt
 
string reaction1DirLabel =
     "Mult " + reactionMult1Txt + " Dir"
 
string reaction1FillLabel =
     "Mult " + reactionMult1Txt + " Fill"
 
string reaction2DirLabel =
     "Mult " + reactionMult2Txt + " Dir"
 
string reaction2FillLabel =
     "Mult " + reactionMult2Txt + " Fill"
 
var string latestFlipTxt = "None Yet"
 
if bullFlip
    latestFlipTxt := "Bull Flip"
else if bearFlip
    latestFlipTxt := "Bear Flip"
 
var int barsSinceFlip = na
 
if bullFlip or bearFlip
    barsSinceFlip := 0
else
    barsSinceFlip := na(barsSinceFlip) ? na : barsSinceFlip + 1
 
string latestFlipDisplay =
     na(barsSinceFlip) ? latestFlipTxt :
     latestFlipTxt + " | " + str.tostring(barsSinceFlip) + " BA"
 
string reaction1DirTxt =
     reactionDir1 == 1 ? "Bull" : "Bear"
 
string reaction2DirTxt =
     reactionDir2 == 1 ? "Bull" : "Bear"
 
bool bullReaction1On =
     in_showReactionZones and
     in_fillReactionZones and
     showBullReaction1
 
bool bearReaction1On =
     in_showReactionZones and
     in_fillReactionZones and
     showBearReaction1
 
bool bullReaction2On =
     in_showReactionZones and
     in_fillReactionZones and
     showBullReaction2
 
bool bearReaction2On =
     in_showReactionZones and
     in_fillReactionZones and
     showBearReaction2
 
string reaction1BranchTxt =
     bullReaction1On ? "✔️" :
     bearReaction1On ? "✔️" : "❌"
 
string reaction2BranchTxt =
     bullReaction2On ? "✔️" :
     bearReaction2On ? "✔️" : "❌"
 
string liveFillTxt =
     (bullReaction1On ? "Bull " + reactionMult1Txt : bearReaction1On ? "Bear " + reactionMult1Txt : reactionMult1Txt + " Off") +
     " | " +
     (bullReaction2On ? "Bull " + reactionMult2Txt : bearReaction2On ? "Bear " + reactionMult2Txt : reactionMult2Txt + " Off")
 
string hlc3Txt =
     close >= hlc3 ? "Close >= HLC3" : "Close < HLC3"
 
color headerBg =
     dir == 1 ? color.new(color.orange, 25) : color.new(#f51673, 25)
 
color headerTxt =
     dir == 1 ? color.rgb(255, 255, 255) : color.white
 
color stateBg =
     dir == 1 ? color.new(color.orange, 70) : color.new(#f51673, 70)
 
color stateTxt =
     dir == 1 ? color.rgb(255, 255, 255) : color.white
 
color neutralBg =
     color.new(color.black, 80)
 
color neutralTxt =
     color.white
 
color reaction1Bg =
     bullReaction1On ? color.new(color.orange, 35) :
     bearReaction1On ? color.new(#f51673, 35) :
     neutralBg
 
color reaction1Txt =
     bullReaction1On ? color.rgb(255, 255, 255) :
     bearReaction1On ? color.white :
     color.white
 
color reaction2Bg =
     bullReaction2On ? color.new(color.orange, 55) :
     bearReaction2On ? color.new(#f51673, 55) :
     neutralBg
 
color reaction2Txt =
     bullReaction2On ? color.rgb(255, 255, 255) :
     bearReaction2On ? color.white :
     color.white
 
color liveFillBg =
     (bullReaction1On or bullReaction2On) ? color.new(color.orange, 20) :
     (bearReaction1On or bearReaction2On) ? color.new(#f51673, 20) :
     neutralBg
 
color liveFillTxtColor =
     (bullReaction1On or bullReaction2On) ? color.rgb(255, 255, 255) :
     (bearReaction1On or bearReaction2On) ? color.white :
     color.white
 
if barstate.islast
    if in_showReactionDebug
        dbgSz = f_reactionDbgTextSize(in_reactionDebugText)
 
        table.cell(reactionDbgTable, 0, 0, "", text_color=headerTxt, bgcolor=headerBg, text_size=dbgSz)
        table.cell(reactionDbgTable, 1, 0, mainDirTxt, text_color=headerTxt, bgcolor=headerBg, text_size=dbgSz)
 
        table.cell(reactionDbgTable, 0, 1, "Main Mult 10", text_color=neutralTxt, bgcolor=neutralBg, text_size=dbgSz)
        table.cell(reactionDbgTable, 1, 1, mainDirTxt + " | " + str.tostring(activeLevel, format.mintick), text_color=neutralTxt, bgcolor=neutralBg, text_size=dbgSz)
 
        table.cell(reactionDbgTable, 0, 2, "Zone Mults", text_color=neutralTxt, bgcolor=neutralBg, text_size=dbgSz)
        table.cell(reactionDbgTable, 1, 2, reactionBandsTxt, text_color=neutralTxt, bgcolor=neutralBg, text_size=dbgSz)
 
        table.cell(reactionDbgTable, 0, 3, "Latest Flip", text_color=stateTxt, bgcolor=stateBg, text_size=dbgSz)
        table.cell(reactionDbgTable, 1, 3, latestFlipDisplay, text_color=stateTxt, bgcolor=stateBg, text_size=dbgSz)
 
        table.cell(reactionDbgTable, 0, 4, reaction1DirLabel, text_color=reaction1Txt, bgcolor=reaction1Bg, text_size=dbgSz)
        table.cell(reactionDbgTable, 1, 4, reaction1DirTxt, text_color=reaction1Txt, bgcolor=reaction1Bg, text_size=dbgSz)
 
        table.cell(reactionDbgTable, 0, 5, reaction1FillLabel, text_color=reaction1Txt, bgcolor=reaction1Bg, text_size=dbgSz)
        table.cell(reactionDbgTable, 1, 5, reaction1BranchTxt, text_color=reaction1Txt, bgcolor=reaction1Bg, text_size=dbgSz)
 
        table.cell(reactionDbgTable, 0, 6, reaction2DirLabel, text_color=reaction2Txt, bgcolor=reaction2Bg, text_size=dbgSz)
        table.cell(reactionDbgTable, 1, 6, reaction2DirTxt, text_color=reaction2Txt, bgcolor=reaction2Bg, text_size=dbgSz)
 
        table.cell(reactionDbgTable, 0, 7, reaction2FillLabel, text_color=reaction2Txt, bgcolor=reaction2Bg, text_size=dbgSz)
        table.cell(reactionDbgTable, 1, 7, reaction2BranchTxt, text_color=reaction2Txt, bgcolor=reaction2Bg, text_size=dbgSz)
 
        //table.cell(reactionDbgTable, 0, 8, "Live Fill", text_color=liveFillTxtColor, bgcolor=liveFillBg, text_size=dbgSz)
        //table.cell(reactionDbgTable, 1, 8, liveFillTxt, text_color=liveFillTxtColor, bgcolor=liveFillBg, text_size=dbgSz)
    else
        table.clear(reactionDbgTable, 0, 0, 1, 8)
 
// ==============================================================================================
// 🔴 END REGION: Reaction Debug Table
// ==============================================================================================
// // ================================================================================
// // 🟢 REGION: CLOSE PRICE LINE PLOT 
// // ================================================================================
// //
// // 📌 Purpose:
// //     Draws the closing price line using selectable display modes:
// //       • "Full Plot" (entire chart)
// //       • "Last N Bars" (plot with show_last)
// //       • "None" (hidden)
// //
// // 🧰 Uses:
// //     • in_closeLineMode → Display toggle
// //     • in_closeLookback → Number of bars for 'Last N Bars'
// //     • in_closeLineWidth, c_closeLine → Styling
// //
// // 🧠 Notes:
// //     • Static titles only (no dynamic strings)
// //     • plot() used only in global scope
// //     • No dynamic label or text functions
// //
// // ================================================================================
 
// const string G_CloseLine = "🔷 Close Line Settings"
 
// string in_closeLineMode = input.string(
//      defval="Last N Bars",
//      title="Close Price Line Mode",
//      options=["Last N Bars", "None"],
//      group=G_CloseLine,
//      tooltip=TT_CLOSE_LINE_MODE)
 
// int in_closeLookback = input.int(
//      defval=13,
//      title="Close Price History Lookback",
//      minval=2,
//      group=G_CloseLine,
//      tooltip=TT_CLOSE_LOOKBACK)
 
// int in_closeLineWidth = input.int(
//      defval=1,
//      title="Close Price Line Width",
//      minval=1,
//      maxval=10,
//      group=G_CloseLine,
//      tooltip=TT_CLOSE_LINE_WIDTH)
 
// // ================================================================================
// // 🔴 END REGION: CLOSE PRICE LINE PLOT
// // ================================================================================
 
 
// // ================================================================================
// // 🟢 REGION: BAR INDEX FOLLOW LINE SETTINGS
// // ================================================================================
// //
// // 📌 Purpose:
// //     Draws two persistent line segments (left and right) that follow
// //     the closing price of the current bar, extending a fixed number of bars
// //     left and right.
// //
// // 🧰 Uses:
// //     • f_manageLine() → creates/updates/deletes lines dynamically
// //
// // 🧠 Behavior:
// //     • Left line extends backward by user-defined bar count
// //     • Right line extends forward by user-defined bar count
// //     • Both lines update each bar to follow the latest close price
// //
// // ================================================================================
 
// const string G_BarFollowLine = "Bar Index Follow Line Settings"
 
// bool in_toggleExtendLeft = input.bool(
//      defval=true,
//      title="Extend Line Left",
//      group=G_BarFollowLine,
//      inline="left",
//      tooltip=TT_EXTEND_LEFT)
 
// int in_extendLeftBars = input.int(
//      defval=2,
//      title="Bars",
//      minval=0,
//      group=G_BarFollowLine,
//      inline="left",
//      tooltip=TT_EXTEND_LEFT_BARS)
 
// string in_leftLineStyle = input.string(
//      defval="Solid",
//      title="",
//      options=["Solid", "Dotted", "Dashed"],
//      group=G_BarFollowLine,
//      inline="left",
//      tooltip=TT_LEFT_LINE_STYLE)
 
// bool in_enableRightLine = input.bool(
//      defval=true,
//      title="Extend Line Right",
//      group=G_BarFollowLine,
//      inline="right",
//      tooltip=TT_EXTEND_RIGHT)
 
// int in_extendRightBars = input.int(
//      defval=2,
//      title="Bars",
//      minval=0,
//      group=G_BarFollowLine,
//      inline="right",
//      tooltip=TT_EXTEND_RIGHT_BARS)
 
// string in_rightLineStyle = input.string(
//      defval="Solid",
//      title="",
//      options=["Solid", "Dotted", "Dashed"],
//      group=G_BarFollowLine,
//      inline="right",
//      tooltip=TT_RIGHT_LINE_STYLE)
 
// int in_lineWidthClose = input.int(
//      defval=1,
//      title="Line Width",
//      minval=1,
//      maxval=10,
//      group=G_BarFollowLine,
//      tooltip=TT_FOLLOW_LINE_WIDTH)
// // ================================================================================
// // 🔴 END REGION: BAR INDEX FOLLOW LINE SETTINGS
// // ================================================================================
 
 
 
// // ================================================================================
// // 🟢 REGION: LINE MANAGEMENT FUNCTION
// // ================================================================================
// //
// // 📌 Purpose:
// //     Creates, updates, or deletes a line object based on enable toggle.
// // 🧠 Behavior:
// //     • If enabled and no existing line → create new
// //     • If enabled and line exists → update its coordinates and style
// //     • If disabled and line exists → delete
// //
// // ================================================================================
 
// f_manageLine(bool _enabled, line _line, int _x1, float _y1, int _x2, float _y2, color _color, int _width, _style) =>
//     var line newLine = _line
//     if _enabled
//         if na(newLine)
//             newLine := line.new(
//               x1 = _x1, y1 = _y1, x2 = _x2, y2 = _y2, xloc = xloc.bar_index, 
//               extend = extend.none, color = _color, width = _width, style = _style)
//         else
//             line.set_xy1(newLine, _x1, _y1)
//             line.set_xy2(newLine, _x2, _y2)
//             line.set_color(newLine, _color)
//             line.set_width(newLine, _width)
//             line.set_style(newLine, _style)
//     else
//         if not na(newLine)
//             line.delete(newLine)
//             newLine := na
//     newLine
 
 
// // ================================================================================
// // 🎨 STYLE CONVERSION HELPER
// // ================================================================================
// //
// // 📌 Purpose:
// //     Converts string input to proper line.style enum
// //
// // ================================================================================
 
// f_lineStyleFromInput(string _style) =>
//     switch _style
//         "Dotted" => line.style_dotted
//         "Dashed" => line.style_dashed
//         "Solid"  => line.style_solid
//         => line.style_solid
 
// // ================================================================================
// // 📏 DRAW FOLLOW LINES
// // ================================================================================
// //
// // 📌 Purpose:
// //     Update or render left/right follow lines based on input toggles.
// //
// // 🧠 Behavior:
// //     • Calculates start/end bar indexes
// //     • Calls f_manageLine() each bar for both sides
// //     • Keeps persistent line handles
// //
// // ================================================================================
 
// // 🔹 Persistent line variables
// var line priceLineLeft  = na
// var line priceLineRight = na
 
// // 🔹 Compute coordinates
// int leftStartX  = bar_index - in_extendLeftBars
// int rightEndX   = bar_index + in_extendRightBars
// float yClose    = close
 
// // 🔹 Update Left Line
// priceLineLeft := f_manageLine(
//   _enabled = in_toggleExtendLeft,
//   _line    = priceLineLeft,
//   _x1      = bar_index,
//   _y1      = yClose,
//   _x2      = leftStartX,
//   _y2      = yClose,
//   _color   = fibBiasCandleBodyColor,
//   _width   = in_lineWidthClose,
//   _style   = f_lineStyleFromInput(in_leftLineStyle))
 
// // 🔹 Update Right Line
// priceLineRight := f_manageLine(
//   _enabled = in_enableRightLine,
//   _line    = priceLineRight,
//   _x1      = bar_index,
//   _y1      = yClose,
//   _x2      = rightEndX,
//   _y2      = yClose,
//   _color   = fibBiasCandleBodyColor,
//   _width   = in_lineWidthClose,
//   _style   = f_lineStyleFromInput(in_rightLineStyle))
 
// // ─────────────────────────────
// // 📈 PLOTS 
// // ─────────────────────────────
 
 
// // 🔹 Last N Bars (recent bars only)
// plot(
//      in_closeLineMode == "Last N Bars" ? close : na,
//      title     = "Close Price Line (Last N Bars)",
//      color     = fibBiasCandleBodyColor,
//      linewidth = in_closeLineWidth,
//      show_last = in_closeLookback)
 
// // ================================================================================
// // 🔴 END REGION: LINE MANAGEMENT FUNCTION
// // ================================================================================

← 返回列表