Chandelier Exit Oscillator + State Mapping

MYNAMEISBRANDON · study · 2630 行 · 点赞 103 · TradingView 原页

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

Pine Script

//@version=6
indicator("Chandelier Exit Oscillator + State Mapping", "CE OSC", overlay=false, max_bars_back=5000, calc_bars_count=2000)
 
 
// ================================================================================
// 🟢 REGION: Core Imports (SCL Framework Dependencies)
// ================================================================================
//
// 📌 Purpose:
//     Loads external libraries authored by SimpleCryptoLife (SCL) that help with
//     higher-timeframe stabilization and timeframe text formatting for this script.
//
// 🧠 Behavior:
//     • `HighTimeframeSampling`  — stabilizes HTF oscillator sampling
//     • `LibraryTimeframeHelper` — prettifies timeframe labels for display
//
// ⚙️ Implementation:
//     These imports are version-locked for compatibility with this script.
//
// ================================================================================
 
import SimpleCryptoLife/HighTimeframeSampling/4  as SCL_HTF
import SimpleCryptoLife/LibraryTimeframeHelper/1 as TF
 
// ================================================================================
// 🔚 END REGION: Core Imports
// ================================================================================
 
// ==============================================================================================
// 🟢 REGION: Groups
// ==============================================================================================
 
const string G_MAIN          = "Main Settings"
const string G_REACT         = "Reaction Zones"
const string G_VIS           = "Visuals"
const string G_PRICE_CANDLES = "Price Overlay Candles"
const string G_GUIDE         = "Guide Lines"
const string G_EXT           = "Extreme Zones"
const string G_HIST_LINE     = "Histogram Line"
const string G_OSC_VWA       = "Oscillator Volume-Weighted Average"
const string G_HTF           = "Higher-Timeframe Oscillator"
const string G_CROSS         = "Crossovers"
const string G_CROSS_SMA     = "SMA 20/50 Crossovers"
const string G_TABLE         = "Configuration Table"
const string G_ALERT         = "Alerts"
 
// ==============================================================================================
// 🔴 END REGION: Groups
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Tooltip Strings
// ==============================================================================================
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Main Settings
// ──────────────────────────────────────────────
const string TT_OSC_MAP_MODE =
     "Controls how price is mapped into oscillator space.\n\n" +
     "• Geometry:\n" +
     "  - active level = -100\n" +
     "  - channel midpoint = 0\n" +
     "  - extension level = +100\n\n" +
     "• State-Weighted:\n" +
     "  - bull regimes live mostly above 0\n" +
     "  - bear regimes live mostly below 0\n" +
     "  - 0 acts more like the active boundary than the channel midpoint."
 
const string TT_ATR_LEN =
     "ATR lookback period used by the Chandelier engine.\n\n" +
     "Higher values smooth the stop structure and react more slowly.\n" +
     "Lower values make the oscillator more responsive."
 
const string TT_ATR_MULT =
     "Primary ATR multiplier used to build the main active ↔ extension channel.\n\n" +
     "Higher values widen the channel.\n" +
     "Lower values tighten it."
 
const string TT_USE_CLOSE =
     "Controls which price basis the Chandelier engine uses.\n\n" +
     "• Close → uses highest/lowest close\n" +
     "• Wicks → uses highest high / lowest low"
 
const string TT_FLIP_MODE =
     "Controls when the Chandelier state is allowed to flip.\n\n" +
     "• On Bar Close → waits for candle confirmation\n" +
     "• Real Time → allows live intrabar flips"
 
const string TT_OSC_SMOOTH =
     "EMA smoothing applied to the raw oscillator after price is mapped into pane space.\n\n" +
     "1 = no added smoothing.\n" +
     "Higher values reduce noise but add lag."
 
const string TT_SHOW_LAST =
     "Number of most recent bars shown for histogram columns and oscillator candles."
 
const string TT_SHOW_LAST_HISTLINES =
     "Number of most recent bars shown for the main oscillator line.\n\n" +
     "Use a smaller value if you want the line to behave more like a short follow trace than a full history plot."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Reaction Zones
// ──────────────────────────────────────────────
const string TT_REACTION_MULT =
     "ATR multiplier used by one of the secondary reaction engines.\n\n" +
     "These build the inner reaction layers that are mapped into oscillator space.\n" +
     "Lower multipliers stay closer to the active level.\n" +
     "Higher multipliers sit deeper into the channel."
 
const string TT_SHOW_REACTION_LINES =
     "Shows or hides the mapped reaction-zone lines in the oscillator pane."
 
const string TT_SHOW_REACTION_FILLS =
     "Shows or hides the layered fills between the main oscillator and the mapped reaction levels."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Visuals
// ──────────────────────────────────────────────
const string TT_SHOW_OSC_COLUMNS =
     "Shows or hides histogram columns built from the oscillator series."
 
const string TT_SHOW_OSC_LINE =
     "Shows or hides the main oscillator line."
 
const string TT_SHOW_OSC_CANDLES =
     "Shows or hides oscillator candles built from bar-to-bar oscillator OHLC."
 
const string TT_HIST_TRANSP =
     "Transparency for histogram columns.\n\n" +
     "0 = solid columns\n" +
     "100 = invisible columns"
 
const string TT_CANDLE_TRANSP =
     "Transparency for oscillator candle bodies.\n\n" +
     "Wicks and borders remain full-strength."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Guide Lines
// ──────────────────────────────────────────────
const string TT_SHOW_GUIDES =
     "Shows or hides the oscillator guide rails.\n\n" +
     "The rail positions adapt to the active mapping mode.\n" +
     "State-Weighted mode uses wider directional rails than Geometry mode."
 
const string TT_ZERO_COL =
     "Color used for the 0-line."
 
const string TT_MID_RAIL_COL =
     "Color used for the non-outer guide rails.\n\n" +
     "This input colors:\n" +
     "• the fixed ±50 guides\n" +
     "• the ±100 guides when State-Weighted mode is active\n\n" +
     "The outermost guides continue to use the outer rail color."
 
const string TT_SHOW_EXTREME_ZONES =
     "Shows or hides the top and bottom extreme fill bands."
 
const string TT_EXTREME_LO =
     "Inner boundary of the extreme zone.\n\n" +
     "In State-Weighted mode, values near ±200 are often better 'true extreme' starting points than ±100."
 
const string TT_EXTREME_HI =
     "Outer boundary of the extreme zone.\n\n" +
     "Used together with Extreme Low to define the filled extreme band."
 
const string TT_TOP_EXTREME_FILL =
     "Fill color used for the top extreme zone."
 
const string TT_BOT_EXTREME_FILL =
     "Fill color used for the bottom extreme zone."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Alerts
// ──────────────────────────────────────────────
const string TT_ZERO_ALERTS =
     "Creates alerts when the oscillator crosses 0.\n\n" +
     "Interpretation depends on mapping mode:\n" +
     "• Geometry → 0 is the channel midpoint\n" +
     "• State-Weighted → 0 behaves more like the active regime boundary"
 
const string TT_SIGNAL_ALERTS =
     "Creates alerts when the primary adaptive fast / slow crossover engine crosses."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Histogram Follow Line
// ──────────────────────────────────────────────
const string TT_FOLLOW_LINE_STYLE =
     "Line style used by both left and right histogram follow lines."
 
const string TT_FOLLOW_LINE_WIDTH =
     "Line width used by both histogram follow lines."
 
const string TT_FOLLOW_LINE_RIGHT =
     "How many bars forward the right follow line extends from the current oscillator value."
 
const string TT_FOLLOW_LINE_LEFT =
     "How many bars backward the left follow line extends from the current oscillator value."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Volume-Weighted Average
// ──────────────────────────────────────────────
const string TT_SHOW_EMA_VOL_VWA =
     "Shows a volume-weighted average of the oscillator.\n\n" +
     "Higher-volume bars contribute more heavily to the average."
 
const string TT_EMA_VOL_MODE =
     "Controls how the volume-weighted average is displayed.\n\n" +
     "• Last N Bars → only the most recent segment is shown\n" +
     "• None → hides the plot"
 
const string TT_EMA_VOL_SHOW_LAST =
     "Number of most recent bars shown for the volume-weighted average plot."
 
const string TT_EMA_VOL_TF_MODE =
     "Controls whether the volume-weighted average length is chosen automatically by timeframe or manually."
 
const string TT_EMA_VOL_LEN =
     "Lookback length used for the volume-weighted average when Manual mode is selected.\n\n" +
     "Higher values smooth the plot more.\n" +
     "Lower values make it more reactive."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Adaptive Crossovers
// ──────────────────────────────────────────────
const string TT_CROSS_MODE =
     "Shows or hides the primary adaptive crossover engine."
 
const string TT_CROSS_FILL_MODE =
     "Shows or hides the fill between the primary adaptive fast and slow lines."
 
const string TT_TF_MODE_CROSS =
     "Controls whether the adaptive crossover lengths are chosen automatically by timeframe or manually."
 
const string TT_FAST_MA_TYPE =
     "Moving-average type used by the primary adaptive fast line."
 
const string TT_FAST_LEN_MANUAL =
     "Manual length used by the primary adaptive fast line when Signal Crossover Mode = Manual."
 
const string TT_SLOW_MA_TYPE =
     "Moving-average type used by the primary adaptive slow line."
 
const string TT_SLOW_LEN_MANUAL =
     "Manual length used by the primary adaptive slow line when Signal Crossover Mode = Manual."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: SMA 20 / 50 Crossovers
// ──────────────────────────────────────────────
const string TT_SIGNALS_MODE_SMA =
     "Shows or hides the standalone SMA 20 / 50 crossover engine."
 
const string TT_FILL_MODE_SMA =
     "Shows or hides the fill between the SMA 20 / 50 lines."
 
const string TT_FAST_MA_TYPE_SMA =
     "Moving-average type used by the fast line in the SMA 20 / 50 engine."
 
const string TT_FAST_LEN_SMA =
     "Fast-line length for the standalone SMA 20 / 50 engine.\n\n" +
     "Default is 20."
 
const string TT_SLOW_MA_TYPE_SMA =
     "Moving-average type used by the slow line in the SMA 20 / 50 engine."
 
const string TT_SLOW_LEN_SMA =
     "Slow-line length for the standalone SMA 20 / 50 engine.\n\n" +
     "Default is 50."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Oscillator Volume-Weighted Average
// ──────────────────────────────────────────────
const string TT_SHOW_OSC_VWA =
     "Shows a volume-weighted average of the Chandelier Reaction Oscillator.\n\n" +
     "Higher-volume bars contribute more heavily to the average, which helps the line respond more to stronger participation."
 
const string TT_OSC_VWA_DISPLAY_MODE =
     "Controls how the oscillator's volume-weighted average is displayed.\n\n" +
     "• Last 'N' Bars → shows only the most recent segment\n" +
     "• None → hides the plot"
 
const string TT_OSC_VWA_SHOW_LAST =
     "Number of most recent bars shown for the oscillator VWA plot."
 
const string TT_OSC_VWA_LEN_MODE =
     "Controls whether the oscillator VWA length is selected automatically by timeframe or manually."
 
const string TT_OSC_VWA_LEN =
     "Lookback length used by the oscillator's volume-weighted average when Length Mode = Manual.\n\n" +
     "Higher values smooth the line more.\n" +
     "Lower values make it more reactive.\n\n" +
     "Auto reference:\n" +
     "• <1m (Seconds) → 55\n" +
     "• 1–3m          → 21\n" +
     "• 5–10m         → 34\n" +
     "• 15–30m        → 48\n" +
     "• 1–2h          → 55\n" +
     "• 4–8h          → 48\n" +
     "• 1D–21D        → 34\n" +
     "• 1W–10W        → 21\n" +
     "• 1M–12M        → 13"
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Higher-Timeframe Oscillator Reference
// ──────────────────────────────────────────────
const string TT_USE_DYNAMIC_HTF =
     "When enabled, the script automatically selects the next logical higher timeframe for the oscillator reference line.\n\n" +
     "When disabled, the Manual Higher Timeframe selection below is used instead."
 
const string TT_MANUAL_HTF_SELECTION =
     "Selects the fixed higher timeframe used when Dynamic HTF is turned off.\n\n" +
     "• Chart → uses the chart timeframe\n" +
     "• Any other option → requests that exact higher timeframe"
 
const string TT_HTF_OSC_DISPLAY_MODE =
     "Controls how the higher-timeframe oscillator reference line is displayed.\n\n" +
     "• Last N Bars → shows only the most recent segment\n" +
     "• None → hides the HTF oscillator reference line"
 
const string TT_HTF_OSC_SHOW_LAST =
     "Number of most recent bars shown when HTF Oscillator Display Mode = Last N Bars."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Configuration Table
// ──────────────────────────────────────────────
const string TT_TABLE_MODE =
     "Controls whether the configuration table is displayed.\n\n" +
     "This table summarizes:\n" +
     "• the main CE state\n" +
     "• the latest main flip\n" +
     "• reaction multipliers and whether their layers are currently active"
 
const string TT_TABLE_TEXT_SIZE =
     "Controls the text size used by the configuration table."
 
const string TT_TABLE_POSITION =
     "Controls where the configuration table is drawn in the oscillator pane."
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Price Overlay Candles
// ──────────────────────────────────────────────
const string TT_PRICE_CANDLE_MODE =
     "Controls whether the script draws oscillator-colored candles on the main price chart using Pine Script's force_overlay feature.\n\n" +
     "• Last N Bars → shows only the most recent overlay candles\n" +
     "• None → hides the chart-overlay candles"
 
const string TT_PRICE_CANDLE_SHOW_LAST =
     "Number of most recent chart candles shown when Price Overlay Candle Mode = Last N Bars."
 
const string TT_PRICE_CANDLE_BODY_TRANSP =
     "Transparency for the overlay candle bodies drawn on the main chart.\n\n" +
     "0 = solid body\n" +
     "100 = invisible body\n\n" +
     "Wicks and borders remain full-strength."
 
const string TT_PRICE_CANDLE_USE_OSC_COLOR =
     "When enabled, the chart-overlay candles use the same adaptive oscillator color engine as the pane visuals."
 
// ==============================================================================================
// 🔴 END REGION: Tooltip Strings
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Main Inputs
// ==============================================================================================
 
string in_oscMapMode = input.string(
     defval="State-Weighted",
     title="Oscillator Mapping",
     options=["Geometry", "State-Weighted"],
     group=G_MAIN,
     tooltip=TT_OSC_MAP_MODE)
 
bool in_useStateWeighted =
     in_oscMapMode == "State-Weighted"
 
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="Main 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_flipMode = input.string(
     defval="On Bar Close",
     title="Flip Timing",
     options=["On Bar Close", "Real Time"],
     group=G_MAIN,
     tooltip=TT_FLIP_MODE)
 
bool in_awaitBarConfirmation =
     in_flipMode == "On Bar Close"
 
int in_smoothLen = input.int(
     defval=3,
     minval=1,
     title="Oscillator Smoothing",
     group=G_MAIN,
     tooltip=TT_OSC_SMOOTH)
 
int in_showLast = input.int(
     defval=233,
     minval=1,
     title="Show Last N Bars (Hist Columns/Candles)",
     group=G_MAIN,
     tooltip=TT_SHOW_LAST)
 
int in_showLast_histlines = input.int(
     defval=5,
     minval=1,
     title="Last N Bars (Hist Columns Lines)",
     group=G_MAIN,
     tooltip=TT_SHOW_LAST_HISTLINES)
 
// ==============================================================================================
// 🔴 END REGION: Main Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Chandelier Exit Inputs
// ==============================================================================================
 
float in_reactionMult1 = input.float(
     defval=2.5,
     minval=0.1,
     step=0.5,
     title="Chandelier Exit Multiplier 1",
     group=G_REACT,
     tooltip=TT_REACTION_MULT)
 
float in_reactionMult2 = input.float(
     defval=5.0,
     minval=0.1,
     step=0.5,
     title="Chandelier Exit Multiplier 2",
     group=G_REACT,
     tooltip=TT_REACTION_MULT)
 
float in_reactionMult3 = input.float(
     defval=7.5,
     minval=0.1,
     step=0.5,
     title="Chandelier Exit Multiplier 3",
     group=G_REACT,
     tooltip=TT_REACTION_MULT)
 
bool in_showReactionLines = input.bool(
     defval=false,
     title="Show Chandelier Exit Plot Lines",
     group=G_REACT,
     tooltip=TT_SHOW_REACTION_LINES)
 
bool in_showReactionFills = input.bool(
     defval=true,
     title="Show Chandelier Exit Plot Fills",
     group=G_REACT,
     tooltip=TT_SHOW_REACTION_FILLS)
 
// ==============================================================================================
// 🔴 END REGION: Chandelier Exit Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Visual Inputs
// ==============================================================================================
 
bool in_showOscColumns = input.bool(
     defval=false,
     title="Show Histogram Columns",
     group=G_VIS,
     tooltip=TT_SHOW_OSC_COLUMNS)
 
bool in_showOscLine = input.bool(
     defval=true,
     title="Show Oscillator Line",
     group=G_VIS,
     tooltip=TT_SHOW_OSC_LINE)
 
bool in_showOscCandles = input.bool(
     defval=true,
     title="Show Oscillator Candles",
     group=G_VIS,
     tooltip=TT_SHOW_OSC_CANDLES)
 
int in_histTransp = input.int(
     defval=20,
     minval=0,
     maxval=100,
     title="Histogram Transparency",
     group=G_VIS,
     tooltip=TT_HIST_TRANSP)
 
int in_candleTransp = input.int(
     defval=30,
     minval=0,
     maxval=100,
     title="Osc Candle Body Transparency",
     group=G_VIS,
     tooltip=TT_CANDLE_TRANSP)
 
// ==============================================================================================
// 🔴 END REGION: Visual Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Price Overlay Candle Inputs
// ==============================================================================================
//
// 📌 Purpose:
//     Controls the optional oscillator-colored candles drawn on the main price chart.
//
// ==============================================================================================
 
string in_priceCandleMode = input.string(
     defval="Last N Bars",
     title="Price Overlay Candle Mode",
     options=["Last N Bars", "None"],
     group=G_PRICE_CANDLES,
     tooltip=TT_PRICE_CANDLE_MODE)
 
int in_priceCandleShowLast = input.int(
     defval=1500,
     minval=1,
     title="Price Overlay Candles - Show Last 'N' Bars",
     group=G_PRICE_CANDLES,
     tooltip=TT_PRICE_CANDLE_SHOW_LAST)
 
int in_priceCandleBodyTransp = input.int(
     defval=70,
     minval=0,
     maxval=100,
     title="Price Overlay Candle Body Transparency",
     group=G_PRICE_CANDLES,
     tooltip=TT_PRICE_CANDLE_BODY_TRANSP)
 
bool in_useOscColorForPriceCandles = input.bool(
     defval=true,
     title="Use Oscillator Color Engine",
     group=G_PRICE_CANDLES,
     tooltip=TT_PRICE_CANDLE_USE_OSC_COLOR)
 
// ==============================================================================================
// 🔴 END REGION: Price Overlay Candle Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Guide + Extreme Inputs
// ==============================================================================================
//
// 📌 Purpose:
//     Defines the user-facing controls for the oscillator guide rails and
//     extreme-zone fills.
//
// 🧠 Behavior:
//     • Guide inputs control the visibility and colors of the 0-line and
//       internal guide rails
//     • Extreme inputs control whether the top/bottom extreme zones are shown
//       and where those zones begin and end
//     • These settings affect pane structure and visual context only;
//       they do not change the underlying oscillator calculation
//
// 🧩 Why this matters in this script:
//     This region gives users control over the fixed visual reference levels
//     that help interpret oscillator location, directional stretch, and when
//     the oscillator is pushing into extreme territory.
//
// ==============================================================================================
 
bool in_showGuides = input.bool(
     defval=true,
     title="Show Guide Lines",
     group=G_GUIDE,
     tooltip=TT_SHOW_GUIDES)
 
color in_zeroCol = input.color(
     defval=color.gray,
     title="Zero Line Color",
     group=G_GUIDE,
     tooltip=TT_ZERO_COL)
 
color in_railCol = #ffffff00
 
color in_midRailCol = input.color(
     defval=color.new(color.white, 70),
     title="Guide Rail Color (±50 / ±100)",
     group=G_GUIDE,
     tooltip=TT_MID_RAIL_COL)
 
bool in_showExtremeZones = input.bool(
     defval=true,
     title="Show Extreme Fills",
     group=G_EXT,
     tooltip=TT_SHOW_EXTREME_ZONES)
 
float in_extremeLo = input.float(
     defval=100.0,
     step=0.1,
     title="Extreme Low",
     group=G_EXT,
     tooltip=TT_EXTREME_LO)
 
float in_extremeHi = input.float(
     defval=150.0,
     step=0.1,
     title="Extreme High",
     group=G_EXT,
     tooltip=TT_EXTREME_HI)
 
color in_topExtremeFill = input.color(
     defval=color.new(color.rgb(255, 94, 0), 82),
     title="Top Extreme Fill",
     group=G_EXT,
     tooltip=TT_TOP_EXTREME_FILL)
 
color in_botExtremeFill = input.color(
     defval=color.new(color.rgb(116, 51, 255), 82),
     title="Bottom Extreme Fill",
     group=G_EXT,
     tooltip=TT_BOT_EXTREME_FILL)
 
// ==============================================================================================
// 🔴 END REGION: Guide + Extreme Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Configuration Table Inputs
// ==============================================================================================
//
// 📌 Purpose:
//     Defines the user-facing controls for the single-column configuration table.
//
// ==============================================================================================
 
string in_tableMode = input.string(
     defval="Show Table",
     title="Configuration Table",
     options=["None", "Show Table"],
     group=G_TABLE,
     tooltip=TT_TABLE_MODE)
 
bool in_showConfigTable =
     in_tableMode == "Show Table"
 
string in_tablePos = input.string(
     defval="Bottom Right",
     title="Table Position",
     options=["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right", "Middle Left", "Top Center", "Bottom Center"],
     group=G_TABLE,
     tooltip=TT_TABLE_POSITION)
 
string in_tableTextSize = input.string(
     defval="Normal",
     title="Table Text Size",
     options=["Tiny", "Small", "Normal", "Large"],
     group=G_TABLE,
     tooltip=TT_TABLE_TEXT_SIZE)
 
int in_tableLabelWidth = input.int(
     defval=5,
     title="Label Column Width",
     minval=1,
     maxval=30,
     group=G_TABLE)
 
int in_tableValueWidth = input.int(
     defval=8,
     title="Value Column Width",
     minval=1,
     maxval=30,
     group=G_TABLE)
 
// ==============================================================================================
// 🔴 END REGION: Configuration Table Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Helpers
// ==============================================================================================
 
// 📌 Purpose:
//     Builds a full Chandelier state engine from a single ATR multiplier.
//
// 🧠 What it does:
//     • Calculates bull and bear stop candidates from ATR distance
//     • Applies trailing stop persistence so stops only ratchet in their intended direction
//     • Maintains both confirmed and live direction states
//     • Detects bull and bear flips for both confirmed and live modes
//     • Returns the selected output set based on the user's flip-timing preference
//
// ⚙️ Inputs:
//     • _mult          → ATR multiplier used to size the stop distance
//     • _len           → ATR / lookback length
//     • _useClose      → true = use highest/lowest close, false = use highest high / lowest low
//     • _awaitConfirm  → true = use confirmed bar-close flips, false = use live intrabar flips
//
// 📤 Returns:
//     • dirOut         → active direction state (1 = bull, -1 = bear)
//     • bullStop       → active bull-side trailing stop
//     • bearStop       → active bear-side trailing stop
//     • bullFlipOut    → true on the selected bull flip bar
//     • bearFlipOut    → true on the selected bear flip bar
//
// 🧩 Why this matters in this script:
//     This is the master state engine reused by:
//     • the main oscillator channel
//     • the reaction-zone engines
//     • any logic that needs the script's native bull / bear Chandelier structure
//
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]
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Price-to-Oscillator Mapping
// ──────────────────────────────────────────────
//
// 📌 Purpose:
//     Converts raw price location inside the active ↔ extension channel
//     into oscillator-space coordinates.
//
// 🧠 Mapping Modes:
//     • Geometry:
//         Preserves the original channel geometry.
//         - active level     = -100
//         - channel midpoint = 0
//         - extension level  = +100
//
//     • State-Weighted:
//         Re-biases the oscillator by regime direction so:
//         - bull states live mostly above 0
//         - bear states live mostly below 0
//         - 0 behaves more like the active boundary than the channel midpoint
//
// 🧩 Function Roles:
//     • f_toOscGeometry()
//         Performs the original geometry-only channel remap.
//
//     • f_toOscStateWeighted()
//         Performs the direction-aware remap using the current bull/bear state.
//
//     • f_toOscMapped()
//         Dispatcher function that selects the active mapping mode based on
//         the user's Oscillator Mapping input.
//
// ⚙️ Safety:
//     All three functions return na when the mapping cannot be computed safely,
//     such as when price/levels are missing or when the channel width is zero.
//
// 🧩 Why this matters in this script:
//     These functions are the bridge between:
//     • the Chandelier engine's price-space structure
//     • and the oscillator pane's visual coordinate system
//
//     They are reused by:
//     • the main oscillator
//     • the reaction-zone oscillator layers
//
f_toOscGeometry(float _price, float _active, float _ext) =>
    na(_price) or na(_active) or na(_ext) or _ext == _active ? na :
     (((_price - _active) / (_ext - _active)) - 0.5) * 200.0
 
f_toOscStateWeighted(float _price, float _active, float _ext, int _dir) =>
    float _ratio =
         na(_price) or na(_active) or na(_ext) or _ext == _active ? na :
         (_price - _active) / (_ext - _active)
 
    na(_ratio) ? na :
     _dir == 1 ? _ratio * 200.0 :
     _dir == -1 ? -_ratio * 200.0 :
     na
 
f_toOscMapped(float _price, float _active, float _ext, int _dir, bool _useStateWeighted) =>
    _useStateWeighted
         ? f_toOscStateWeighted(_price, _active, _ext, _dir)
         : f_toOscGeometry(_price, _active, _ext)
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Moving Average Selector
// ──────────────────────────────────────────────
//
// 📌 Purpose:
//     Returns either an EMA or SMA from the same source/length inputs
//     using a single shared helper.
//
// 🧠 Behavior:
//     • Computes both EMA and SMA on every bar
//     • Returns the one selected by the _type input
//     • Keeps TA calculations outside ternary branches so Pine evaluates
//       them consistently bar to bar
//
// ⚙️ Inputs:
//     • _type → moving average type ("EMA" or "SMA")
//     • _src  → source series to average
//     • _len  → averaging length
//
// 🧩 Why this matters in this script:
//     This helper keeps both crossover engines consistent by giving them
//     one shared MA selector for:
//     • the adaptive crossover engine
//     • the SMA 20 / 50 crossover engine
//
f_ma(string _type, float _src, int _len) =>
    float _ema = ta.ema(_src, _len)
    float _sma = ta.sma(_src, _len)
    _type == "EMA" ? _ema : _sma
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Configuration Table Helpers
// ──────────────────────────────────────────────
// Small formatting helpers used by the configuration table.
//
// What these do:
// • convert user text inputs into Pine table size / position enums
// • choose readable text color based on cell background brightness
// • format table numbers cleanly, including signed values and small decimals
// • optionally add directional delta markers for up / down / flat changes
 
f_tableSize(string _s) =>
    switch _s
        "Tiny"  => size.tiny
        "Small" => size.small
        "Large" => size.large
        =>        size.normal
 
f_tablePos(string _p) =>
    switch _p
        "Top Left"      => position.top_left
        "Bottom Right"  => position.bottom_right
        "Bottom Left"   => position.bottom_left
        "Middle Right"  => position.middle_right
        "Middle Left"   => position.middle_left
        "Top Center"    => position.top_center
        "Bottom Center" => position.bottom_center
        =>                position.top_right
 
f_tableContrast(color _c) =>
    float _r = color.r(_c)
    float _g = color.g(_c)
    float _b = color.b(_c)
    float _lum = _r * 0.299 + _g * 0.587 + _b * 0.114
    _lum > 155 ? color.rgb(0, 0, 0) : color.white
 
f_tableStripLead0(string _s) =>
    int _n = str.length(_s)
    bool _neg0 = _n >= 3 and str.substring(_s, 0, 3) == "-0."
    bool _pos0 = _n >= 2 and str.substring(_s, 0, 2) == "0."
    _neg0 ? str.replace(_s, "-0.", "-.") :
     _pos0 ? str.replace(_s, "0.", ".") :
     _s
 
f_tableFmt(float _v) =>
    if na(_v)
        "n/a"
    else
        string _s = str.tostring(_v, "#.##")
        math.abs(_v) < 1 and _v != 0 ? f_tableStripLead0(_s) : _s
 
f_tableFmtSigned(float _v) =>
    if na(_v)
        "n/a"
    else
        _v > 0 ? "+" + f_tableFmt(_v) :
         _v < 0 ? f_tableFmt(_v) :
         "0"
 
f_tableFmtDelta(float _v) =>
    if na(_v)
        "n/a"
    else
        _v > 0 ? "⬆" + f_tableFmt(_v) :
         _v < 0 ? "⬇" + f_tableFmt(math.abs(_v)) :
         "➡0"
 
// ==============================================================================================
// 🔴 END REGION: Helpers
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: Main Chandelier Exit Engine
// ==============================================================================================
//
// 📌 Purpose:
//     Builds the script's primary Chandelier state, selects the active and
//     extension anchors, then maps live price into oscillator space.
//
// 🧠 Workflow:
//     1) Run the shared Chandelier engine using the main ATR multiplier
//     2) Resolve which stop is the active side and which stop is the extension side
//        based on the current bull / bear direction
//     3) Convert live price into pane coordinates using the selected oscillator
//        mapping mode (Geometry or State-Weighted)
//     4) Optionally smooth the mapped oscillator before it is used by the rest
//        of the script
//
// 📤 Outputs:
//     • dir         → current main bull / bear state
//     • activeLevel → current active Chandelier anchor
//     • extLevel    → opposite-side extension anchor
//     • oscRaw      → unsmoothed mapped oscillator
//     • osc         → final oscillator after optional smoothing
//
// 🧩 Why this matters in this script:
//     This is the master channel-and-oscillator build that feeds:
//     • reaction-zone remapping
//     • color logic
//     • crossover engines
//     • guide rails
//     • alerts
//
[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
 
float oscRaw =
     f_toOscMapped(
         close,
         activeLevel,
         extLevel,
         dir,
         in_useStateWeighted)
 
float osc =
     in_smoothLen > 1 ? ta.ema(oscRaw, in_smoothLen) : oscRaw
 
// ==============================================================================================
// 🔴 END REGION: Main CE Engine
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Secondary Chandelier Exit Zones
// ==============================================================================================
//
// 📌 Purpose:
//     Builds three additional Chandelier Exit multiplier layers, then remaps
//     their active levels into oscillator space so they can serve as internal
//     zone references within the main channel.
//
// 🧠 What this block does:
//     • Runs three separate Chandelier Exit calculations using the user-defined
//       secondary multipliers
//     • Resolves each multiplier's currently active level from its own bull / bear state
//     • Only allows a secondary layer to participate when its direction agrees
//       with the main Chandelier state
//     • Remaps each approved level into the current oscillator-space coordinate system
//     • Defines the colors used to visualize these secondary zone layers
//
// 🧩 Why this matters in this script:
//     These secondary Chandelier Exit multipliers create a stacked internal
//     zone structure inside the main oscillator channel.
//
//     In practice, they help users read where additional support / resistance-style
//     zones may be forming within the broader active-to-extension framework.
//
// ==============================================================================================
 
[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)
 
[reactionDir3, bullReaction3, bearReaction3, bullReactionFlip3, bearReactionFlip3] =
     f_chandelier(
         in_reactionMult3,
         in_atrLen,
         in_useClose,
         in_awaitBarConfirmation)
 
float reactionLevel1 =
     reactionDir1 == 1 ? bullReaction1 : bearReaction1
 
float reactionLevel2 =
     reactionDir2 == 1 ? bullReaction2 : bearReaction2
 
float reactionLevel3 =
     reactionDir3 == 1 ? bullReaction3 : bearReaction3
 
bool showReaction1 =
     reactionDir1 == dir
 
bool showReaction2 =
     reactionDir2 == dir
 
bool showReaction3 =
     reactionDir3 == dir
 
float oscReaction1 =
     showReaction1
         ? f_toOscMapped(
              reactionLevel1,
              activeLevel,
              extLevel,
              dir,
              in_useStateWeighted)
         : na
 
float oscReaction2 =
     showReaction2
         ? f_toOscMapped(
              reactionLevel2,
              activeLevel,
              extLevel,
              dir,
              in_useStateWeighted)
         : na
 
float oscReaction3 =
     showReaction3
         ? f_toOscMapped(
              reactionLevel3,
              activeLevel,
              extLevel,
              dir,
              in_useStateWeighted)
         : na
 
color reactionLineColor1 =
     dir == 1 ? color.rgb(255, 225, 110) : color.rgb(255, 140, 190)
 
color reactionLineColor2 =
     dir == 1 ? color.rgb(255, 187, 80) : color.rgb(255, 90, 155)
 
color reactionLineColor3 =
     dir == 1 ? color.rgb(255, 136, 0) : color.rgb(200, 0, 130)
 
color reactionFillFront =
     dir == 1 ? color.new(color.rgb(255, 136, 0), 85) : color.new(color.rgb(245, 22, 115), 90)
 
color reactionFillMid =
     dir == 1 ? color.new(color.rgb(255, 136, 0), 84) : color.new(color.rgb(245, 22, 115), 84)
 
color reactionFillBack =
     dir == 1 ? color.new(color.rgb(255, 136, 0), 78) : color.new(color.rgb(245, 22, 115), 78)
 
// ==============================================================================================
// 🔴 END REGION: Reaction Engines
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Oscillator Color Logic
// ==============================================================================================
//
// 📌 Purpose:
//     Builds the adaptive color system for the Chandelier Reaction Oscillator
//     so the histogram, main line, follow lines, and oscillator candles all
//     share one consistent pane color engine.
//
// 🧠 What this block does:
//     • Converts live price location into a ladder ratio using the current
//       active ↔ extension channel
//     • Applies a direction-aware palette so bull and bear regimes each use
//       their own internal color progression
//     • Adds special out-of-channel override colors when price moves beyond
//       the active boundary or extension boundary
//     • Derives the final pane-ready colors used by:
//         - the oscillator line
//         - histogram columns
//         - candle bodies
//         - candle borders / wicks
//         - histogram follow lines
//
// 🧩 Why this matters in this script:
//     This region is the visual identity layer of the oscillator.
//     It translates the script's Chandelier structure into a color language
//     that reflects:
//     • where price sits inside the channel
//     • which direction is currently active
//     • whether price is still inside the main ladder or pushing beyond it
//
// ==============================================================================================
//
// ──────────────────────────────────────────────
// 🟦 Subregion: Ladder Ratio
// ──────────────────────────────────────────────
f_ladderRatio(float _price) =>
    na(_price) or na(activeLevel) or na(extLevel) or extLevel == activeLevel ? na :
     (_price - activeLevel) / (extLevel - activeLevel)
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Original Ladder Palette
// ──────────────────────────────────────────────
f_levelColorByRatio(float _ratio) =>
    if na(_ratio)
        color.gray
    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)
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Derived Oscillator Colors
// ──────────────────────────────────────────────
float closeRatio =
     f_ladderRatio(close)
 
color oscCol =
     f_stateColorByRatio(closeRatio)
 
color oscHistCol =
     na(oscCol) ? na : color.new(oscCol, in_histTransp)
 
color oscCandleBodyCol =
     na(oscCol) ? na : color.new(oscCol, in_candleTransp)
 
color oscCandleEdgeCol =
     oscCol
 
// ==============================================================================================
// 🔴 END REGION: Oscillator Color Logic
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Price Overlay Candle Colors
// ==============================================================================================
//
// 📌 Purpose:
//     Derives the colors used by the optional chart-overlay candles.
//
// ==============================================================================================
 
color priceOverlayBaseCol =
     in_useOscColorForPriceCandles ? oscCol : color.gray
 
color priceOverlayBodyCol =
     na(priceOverlayBaseCol) ? na : color.new(priceOverlayBaseCol, in_priceCandleBodyTransp)
 
color priceOverlayEdgeCol =
     priceOverlayBaseCol
 
// ==============================================================================================
// 🔴 END REGION: Price Overlay Candle Colors
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Histogram Follow Line
// ==============================================================================================
//
// 📌 Purpose:
//     Draws a left and right follow line from the current oscillator value.
//
// 🧠 Behavior:
//     • Right line extends forward from the current bar by X bars
//     • Left line extends backward from the current bar by X bars
//     • Both lines update every bar to stay locked to the live oscillator value
//
// ==============================================================================================
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Inputs
// ──────────────────────────────────────────────
string in_lineStyleFollow = input.string(
     defval="Solid",
     title="Follow Line Style",
     options=["Solid", "Dotted", "Dashed"],
     group=G_HIST_LINE,
     tooltip=TT_FOLLOW_LINE_STYLE)
 
int in_histFollowLineWidth = input.int(
     defval=1,
     minval=1,
     maxval=10,
     title="Follow Line Width",
     group=G_HIST_LINE,
     tooltip=TT_FOLLOW_LINE_WIDTH)
 
int in_histLineLengthRight = input.int(
     defval=2,
     minval=0,
     maxval=100,
     title="Follow Line Length Right",
     group=G_HIST_LINE,
     tooltip=TT_FOLLOW_LINE_RIGHT)
 
int in_histLineLengthLeft = input.int(
     defval=1,
     minval=0,
     maxval=500,
     title="Follow Line Length Left",
     group=G_HIST_LINE,
     tooltip=TT_FOLLOW_LINE_LEFT)
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Style Mapping
// ──────────────────────────────────────────────
lineStyle_follow =
     in_lineStyleFollow == "Solid"  ? line.style_solid :
     in_lineStyleFollow == "Dotted" ? line.style_dotted :
     line.style_dashed
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Follow Line State
// ──────────────────────────────────────────────
color followLineColor = oscCol
 
var line followLineRight = na
var line followLineLeft = na
 
int x2_followRight = bar_index + in_histLineLengthRight
int x2_followLeft = bar_index - in_histLineLengthLeft
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Follow Line Updater
// ──────────────────────────────────────────────
f_updateFollowLine(line _line, int _x1, float _y1, int _x2, float _y2, color _col, int _width, _style) =>
    line _out = _line
 
    if na(_out)
        _out := line.new(
             x1=_x1,
             y1=_y1,
             x2=_x2,
             y2=_y2,
             xloc=xloc.bar_index,
             color=_col,
             width=_width,
             style=_style)
    else
        line.set_xy1(_out, _x1, _y1)
        line.set_xy2(_out, _x2, _y2)
        line.set_color(_out, _col)
        line.set_width(_out, _width)
        line.set_style(_out, _style)
 
    _out
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Follow Line Updates
// ──────────────────────────────────────────────
followLineRight := f_updateFollowLine(
     followLineRight,
     bar_index,
     osc,
     x2_followRight,
     osc,
     followLineColor,
     in_histFollowLineWidth,
     lineStyle_follow)
 
followLineLeft := f_updateFollowLine(
     followLineLeft,
     bar_index,
     osc,
     x2_followLeft,
     osc,
     followLineColor,
     in_histFollowLineWidth,
     lineStyle_follow)
 
// ==============================================================================================
// 🔴 END REGION: Histogram Follow Line
// ==============================================================================================
 
// ================================================================================
// 🟢 REGION: Oscillator Volume-Weighted Average
// ================================================================================
//
// 📌 Purpose:
//     Builds a volume-weighted average of the Chandelier Reaction Oscillator
//     so the pane can show a smoother participation-aware reference line.
//
// 🧠 Behavior:
//     • Uses the oscillator (`osc`) as the source series
//     • Uses volume as the weighting factor
//     • Supports Auto or Manual length selection
//     • Can display only the most recent N bars or remain hidden
//
// ================================================================================
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Inputs
// ──────────────────────────────────────────────
bool in_showOscVwa = input.bool(
     defval=true,
     title="Show Oscillator VWA",
     group=G_OSC_VWA,
     tooltip=TT_SHOW_OSC_VWA)
 
string in_oscVwaDisplayMode = input.string(
     defval="Last 'N' Bars",
     title="Oscillator VWA Display Mode",
     options=["Last 'N' Bars", "None"],
     group=G_OSC_VWA,
     tooltip=TT_OSC_VWA_DISPLAY_MODE)
 
int in_oscVwaShowLast = input.int(
     defval=55,
     minval=1,
     title="Oscillator VWA - Show Last 'N' Bars",
     group=G_OSC_VWA,
     tooltip=TT_OSC_VWA_SHOW_LAST)
 
string in_oscVwaLenMode = input.string(
     defval="Auto",
     title="Oscillator VWA Length Mode",
     options=["Auto", "Manual"],
     group=G_OSC_VWA,
     tooltip=TT_OSC_VWA_LEN_MODE)
 
int in_oscVwaLenManual = input.int(
     defval=55,
     minval=1,
     title="Oscillator VWA Length",
     group=G_OSC_VWA,
     tooltip=TT_OSC_VWA_LEN)
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Adaptive Length Table
// ──────────────────────────────────────────────
int len_OscVwa_0 = 55
int len_OscVwa_1 = 21
int len_OscVwa_2 = 34
int len_OscVwa_3 = 48
int len_OscVwa_4 = 55
int len_OscVwa_5 = 48
int len_OscVwa_6 = 34
int len_OscVwa_7 = 21
int len_OscVwa_8 = 13
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Auto Length Selector
// ──────────────────────────────────────────────
int oscVwaLen_auto =
     timeframe.isseconds and timeframe.multiplier <= 45     ? len_OscVwa_0 :
     timeframe.isminutes and timeframe.multiplier <= 3      ? len_OscVwa_1 :
     timeframe.isminutes and timeframe.multiplier <= 10     ? len_OscVwa_2 :
     timeframe.isminutes and timeframe.multiplier <= 30     ? len_OscVwa_3 :
     timeframe.isminutes and timeframe.multiplier <= 120    ? len_OscVwa_4 :
     timeframe.isminutes and timeframe.multiplier <= 480    ? len_OscVwa_5 :
     timeframe.isdaily   and timeframe.multiplier <= 34     ? len_OscVwa_6 :
     timeframe.isweekly  and timeframe.multiplier <= 21     ? len_OscVwa_7 :
     timeframe.ismonthly and timeframe.multiplier <= 13     ? len_OscVwa_8 :
                                                              in_oscVwaLenManual
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Runtime Length
// ──────────────────────────────────────────────
int oscVwaLen =
     in_oscVwaLenMode == "Auto" ? oscVwaLen_auto : in_oscVwaLenManual
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Volume-Weighted Calculation
// ──────────────────────────────────────────────
float oscVwaVolAdj =
     volume / ta.sma(volume, oscVwaLen)
 
float oscVwaWeightedSum =
     math.sum(osc * oscVwaVolAdj, oscVwaLen)
 
float oscVwaWeightSum =
     math.sum(oscVwaVolAdj, oscVwaLen)
 
float oscVwa =
     oscVwaWeightSum != 0 ? oscVwaWeightedSum / oscVwaWeightSum : na
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Plot Color
// ──────────────────────────────────────────────
color oscVwaColor =
     oscVwa > oscVwa[1] ? color.new(#00e5ff, 0) : color.new(#00e5ff, 0)
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Plot
// ──────────────────────────────────────────────
plot(
     in_showOscVwa and in_oscVwaDisplayMode == "Last 'N' Bars" ? oscVwa : na,
     title="Oscillator VWA (Last N Bars)",
     color=oscVwaColor,
     linewidth=1,
     style=plot.style_circles,
     show_last=in_oscVwaShowLast)
 
// ================================================================================
// 🔴 END REGION: Oscillator Volume-Weighted Average
// ================================================================================
 
// ================================================================================
// 🟢 REGION: Higher-Timeframe Oscillator Inputs
// ================================================================================
//
// 📌 Purpose:
//     Defines the user-facing controls for the higher-timeframe oscillator
//     reference line.
//
// 🧠 Behavior:
//     • Dynamic mode automatically selects the next logical HTF
//     • Manual mode allows a fixed HTF override
//     • Display mode controls whether the HTF oscillator shows the most recent
//       segment or remains hidden
//
// ================================================================================
//
bool use_dynamic_timeframe = input.bool(
     defval=true,
     title="Enable Dynamic HTF",
     group=G_HTF,
     tooltip=TT_USE_DYNAMIC_HTF)
 
string htf_dropdown = input.string(
     defval="Chart",
     title="Manual Higher Timeframe",
     options=["Chart", "30S", "1", "2", "3", "4", "5", "10", "15", "30", "45", "60", "120", "240", "480", "D", "W", "2W", "M", "2M"],
     group=G_HTF,
     tooltip=TT_MANUAL_HTF_SELECTION)
 
string in_htfOscMode = input.string(
     defval="Last N Bars",
     title="HTF Oscillator Display Mode",
     options=["Last N Bars", "None"],
     group=G_HTF,
     tooltip=TT_HTF_OSC_DISPLAY_MODE)
 
int in_htfOscShowLast = input.int(
     defval=21,
     minval=1,
     maxval=1000,
     title="HTF Oscillator - Show Last 'N' Bars",
     group=G_HTF,
     tooltip=TT_HTF_OSC_SHOW_LAST)
 
// ================================================================================
// 🔴 END REGION: Higher-Timeframe Oscillator Inputs
// ================================================================================
 
// ================================================================================
// 🟢 REGION: Higher-Timeframe Selector
// ================================================================================
//
// 📌 Purpose:
//     Resolves the higher timeframe used by the oscillator reference line.
//
// 🧠 Behavior:
//     • Supports seconds, minutes, daily, weekly, and monthly charts
//     • Advances to the next logical timeframe in Dynamic mode
//     • Uses the manual selection directly when Dynamic mode is off
//
// 🧩 Why this matters in this script:
//     This lets the oscillator pane show a higher-timeframe reference line
//     without requiring a second indicator instance.
//
// ================================================================================
//
f_getNextTf() =>
    string next_tf = ""
    float mult = timeframe.multiplier
 
    if timeframe.isseconds
        next_tf :=
             timeframe.period == "1S"  ? "5S"  :
             timeframe.period == "5S"  ? "10S" :
             timeframe.period == "10S" ? "15S" :
             timeframe.period == "15S" ? "30S" :
             timeframe.period == "30S" ? "45S" :
             timeframe.period == "45S" ? "1"   : "1"
 
    else if timeframe.isminutes
        next_tf :=
             mult <= 1   ? "3"   :
             mult <= 2   ? "4"   :
             mult <= 3   ? "5"   :
             mult <= 5   ? "10"  :
             mult <= 10  ? "15"  :
             mult <= 15  ? "30"  :
             mult <= 30  ? "60"  :
             mult <= 60  ? "120" :
             mult <= 120 ? "240" :
             mult <= 240 ? "480" : "D"
 
    else if timeframe.isdaily
        next_tf := "1W"
    else if timeframe.isweekly
        next_tf := "2W"
    else if timeframe.ismonthly
        next_tf := "2M"
    else
        next_tf := "1D"
 
    next_tf
 
string selected_htf =
     htf_dropdown == "Chart" ? timeframe.period : htf_dropdown
 
string OneTimeframe =
     use_dynamic_timeframe ? f_getNextTf() : selected_htf
 
// ================================================================================
// 🔴 END REGION: Higher-Timeframe Selector
// ================================================================================
 
// ================================================================================
// 🟢 REGION: Higher-Timeframe Oscillator Sampling
// ================================================================================
//
// 📌 Purpose:
//     Requests the oscillator from the selected higher timeframe and stabilizes
//     it for lower-timeframe use.
//
// 🧠 Behavior:
//     • Pulls the oscillator (`osc`) from the selected HTF with security()
//     • Uses SCL_HTF.f_HTF_Float() to stabilize the returned series
//     • Prevents the HTF reference line from visually desyncing while the
//       higher-timeframe bar is still forming
//
// 🧩 Why this matters in this script:
//     This is the engine that turns the current oscillator into a usable
//     higher-timeframe reference line inside the same pane.
//
// ================================================================================
//
f_secOsc(_TF) =>
    request.security(
       symbol     = syminfo.tickerid,
       timeframe  = _TF,
       expression = osc,
       gaps       = barmerge.gaps_off,
       lookahead  = barmerge.lookahead_off)
 
float htfOscRaw = f_secOsc(OneTimeframe)
 
float htfOscFixed = SCL_HTF.f_HTF_Float(
     _HTF                  = OneTimeframe,
     _source               = htfOscRaw,
     _arrayHistory         = 2,
     _HTF_offset           = 0,
     _useLiveDataOnChartTF = true)
 
// ================================================================================
// 🔴 END REGION: Higher-Timeframe Oscillator Sampling
// ================================================================================
 
// ================================================================================
// 🟢 REGION: Higher-Timeframe Oscillator Plot
// ================================================================================
//
// 📌 Purpose:
//     Draws the stabilized higher-timeframe oscillator reference line in the
//     current pane.
//
// 🧠 Behavior:
//     • Uses the stabilized HTF oscillator series
//     • Can show only the most recent N bars or remain hidden
//
// ================================================================================
//
plot(
     in_htfOscMode == "Last N Bars" ? htfOscFixed : na,
     title="Higher-Timeframe Oscillator (Last N Bars)",
     color=#0066ff,
     linewidth=1,
     show_last=in_htfOscShowLast)
 
// ================================================================================
// 🔴 END REGION: Higher-Timeframe Oscillator Plot
// ================================================================================
 
// ==============================================================================================
// 🟢 REGION: Adaptive Crossover Inputs
// ==============================================================================================
//
// 📌 Purpose:
//     Defines the input controls for the oscillator's primary adaptive
//     fast / slow crossover engine.
//
// 🧠 Behavior:
//     • Show / Hide adaptive crossovers
//     • Show / Hide adaptive crossover fill
//     • Auto or Manual runtime lengths
//     • User-selectable MA types
//
// ==============================================================================================
//
string in_crossMode = input.string(
     defval="Show Crossovers",
     title="Adaptive Crossovers",
     options=["Show Crossovers", "None"],
     group=G_CROSS)
 
bool in_showCrossLines =
     in_crossMode == "Show Crossovers"
 
string in_crossFillMode = input.string(
     defval="Show Fill",
     title="Fill Crossovers",
     options=["Show Fill", "None"],
     group=G_CROSS)
 
bool in_showCrossFill =
     in_crossFillMode == "Show Fill"
 
string in_tfMode_Cross = input.string(
     defval="Auto",
     title="Signal Crossover Mode",
     options=["Auto", "Manual"],
     group=G_CROSS)
 
string in_fastMaType = input.string(
     defval="EMA",
     title="Fast Line Type",
     options=["EMA", "SMA"],
     group=G_CROSS)
 
int in_fastLen_manual = input.int(
     defval=5,
     minval=1,
     title="Fast Line Length",
     group=G_CROSS)
 
string in_slowMaType = input.string(
     defval="EMA",
     title="Slow Line Type",
     options=["EMA", "SMA"],
     group=G_CROSS)
 
int in_slowLen_manual = input.int(
     defval=21,
     minval=1,
     title="Slow Line Length",
     group=G_CROSS)
 
// ==============================================================================================
// 🔴 END REGION: Adaptive Cross Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Adaptive Cross Engine
// ==============================================================================================
//
// 📌 Purpose:
//     Builds the oscillator's primary adaptive fast / slow crossover engine.
//
// 🧠 Behavior:
//     • Auto mode selects timeframe-aware lengths
//     • Manual mode uses the user-entered lengths
//     • Exposes stable downstream variables already used elsewhere in the script
//
// ==============================================================================================
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Adaptive Length Tables + Auto Selector
// ──────────────────────────────────────────────
//
// 📌 Purpose:
//     Defines the fast / slow crossover pair used by the adaptive crossover
//     engine for each supported chart-timeframe bucket, then auto-selects
//     the correct pair from the live chart timeframe.
//
// 🧠 Adaptive crossover pairs by timeframe:
//     • <= 45s        → 8 / 21
//     • 1m–3m         → 5 / 13
//     • 5m–10m        → 8 / 21
//     • 15m–30m       → 13 / 34
//     • 1h–2h         → 13 / 48
//     • 4h–8h         → 21 / 48
//     • 1D–34D        → 13 / 34
//     • 1W–21W        → 8 / 21
//     • 1M–13M        → 5 / 13
//
// 🧩 What happens here:
//     • The fast table stores the first value of each pair
//     • The slow table stores the second value of each pair
//     • The auto selector maps the current chart timeframe into the correct
//       bucket and returns the matching fast / slow pair
//     • If no bucket matches, the script falls back to the manual lengths
//
// 🧩 Why this matters in this script:
//     This gives the primary adaptive crossover engine a timeframe-aware
//     fast / slow structure, so lower timeframes stay responsive while
//     higher timeframes use more stable crossover pairs.
//
int len_Fast_0 = 8
int len_Fast_1 = 5
int len_Fast_2 = 8
int len_Fast_3 = 13
int len_Fast_4 = 13
int len_Fast_5 = 21
int len_Fast_6 = 13
int len_Fast_7 = 8
int len_Fast_8 = 5
 
int len_Slow_0 = 21
int len_Slow_1 = 13
int len_Slow_2 = 21
int len_Slow_3 = 34
int len_Slow_4 = 48
int len_Slow_5 = 48
int len_Slow_6 = 34
int len_Slow_7 = 21
int len_Slow_8 = 13
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Auto Length Selector
// ──────────────────────────────────────────────
int crossFastLen_auto =
     timeframe.isseconds and timeframe.multiplier <= 45     ? len_Fast_0 :
     timeframe.isminutes and timeframe.multiplier <= 3      ? len_Fast_1 :
     timeframe.isminutes and timeframe.multiplier <= 10     ? len_Fast_2 :
     timeframe.isminutes and timeframe.multiplier <= 30     ? len_Fast_3 :
     timeframe.isminutes and timeframe.multiplier <= 120    ? len_Fast_4 :
     timeframe.isminutes and timeframe.multiplier <= 480    ? len_Fast_5 :
     timeframe.isdaily   and timeframe.multiplier <= 34     ? len_Fast_6 :
     timeframe.isweekly  and timeframe.multiplier <= 21     ? len_Fast_7 :
     timeframe.ismonthly and timeframe.multiplier <= 13     ? len_Fast_8 :
                                                              in_fastLen_manual
 
int crossSlowLen_auto =
     timeframe.isseconds and timeframe.multiplier <= 45     ? len_Slow_0 :
     timeframe.isminutes and timeframe.multiplier <= 3      ? len_Slow_1 :
     timeframe.isminutes and timeframe.multiplier <= 10     ? len_Slow_2 :
     timeframe.isminutes and timeframe.multiplier <= 30     ? len_Slow_3 :
     timeframe.isminutes and timeframe.multiplier <= 120    ? len_Slow_4 :
     timeframe.isminutes and timeframe.multiplier <= 480    ? len_Slow_5 :
     timeframe.isdaily   and timeframe.multiplier <= 34     ? len_Slow_6 :
     timeframe.isweekly  and timeframe.multiplier <= 21     ? len_Slow_7 :
     timeframe.ismonthly and timeframe.multiplier <= 13     ? len_Slow_8 :
                                                              in_slowLen_manual
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Runtime Lengths
// ──────────────────────────────────────────────
int crossFastLen_rt =
     in_tfMode_Cross == "Auto" ? crossFastLen_auto : in_fastLen_manual
 
int crossSlowLen_rt =
     in_tfMode_Cross == "Auto" ? crossSlowLen_auto : in_slowLen_manual
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Signal Lines
// ──────────────────────────────────────────────
float fastLine =
     f_ma(in_fastMaType, osc, crossFastLen_rt)
 
float slowLine =
     f_ma(in_slowMaType, osc, crossSlowLen_rt)
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Crossover State
// ──────────────────────────────────────────────
bool bullCross = ta.crossover(fastLine, slowLine)
bool bearCross = ta.crossunder(fastLine, slowLine)
 
var bool crossBullState = false
crossBullState := bullCross ? true : bearCross ? false : crossBullState
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Colors
// ──────────────────────────────────────────────
color crossLineCol =
     crossBullState ? color.rgb(255, 251, 0, 27) : color.rgb(188, 45, 255, 27) 
 
color crossFillCol =
     in_showCrossFill
         ? (crossBullState ? color.rgb(255, 251, 0, 77) : color.rgb(188, 45, 255, 77))
         : na
 
// ==============================================================================================
// 🔴 END REGION: Adaptive Cross Engine
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: SMA 20 / 50 Cross Inputs
// ==============================================================================================
//
// 📌 Purpose:
//     Defines the input controls for the standalone SMA 20 / 50 crossover engine.
//
// 🧠 Behavior:
//     • Show / Hide SMA 20 / 50 crossovers
//     • Show / Hide SMA 20 / 50 crossover fill
//     • Independent fast / slow MA types and lengths
//
// ==============================================================================================
//
string in_SignalsMode_sma = input.string(
     defval="Show Crossovers",
     title="SMA 20/50 Crossovers",
     options=["Show Crossovers", "None"],
     group=G_CROSS_SMA,
     tooltip="Controls whether the SMA 20/50 crossover signals are displayed.\n\n"
           + "• Show Crossovers → display the SMA 20/50 signal lines\n"
           + "• None → hide the SMA 20/50 signal lines")
 
bool in_showSignals_sma =
     in_SignalsMode_sma == "Show Crossovers"
 
string in_FillMode_sma = input.string(
     defval="Show Fill",
     title="Fill SMA 20/50 Crossovers",
     options=["Show Fill", "None"],
     group=G_CROSS_SMA,
     tooltip="Controls whether the SMA 20/50 crossover fill is displayed.\n\n"
           + "• Show Fill → fill between the signal lines\n"
           + "• None → hide the fill")
 
bool in_showFill_sma =
     in_FillMode_sma == "Show Fill"
 
string in_MaType_fast_sma = input.string(
     defval="SMA",
     title="Fast Line Type",
     options=["EMA", "SMA"],
     group=G_CROSS_SMA)
 
int in_Len_fast_sma = input.int(
     defval=20,
     minval=1,
     title="Fast Line Length",
     group=G_CROSS_SMA)
 
string in_MaType_slow_sma = input.string(
     defval="SMA",
     title="Slow Line Type",
     options=["EMA", "SMA"],
     group=G_CROSS_SMA)
 
int in_Len_slow_sma = input.int(
     defval=50,
     minval=1,
     title="Slow Line Length",
     group=G_CROSS_SMA)
 
// ==============================================================================================
// 🔴 END REGION: SMA 20 / 50 Cross Inputs
// ==============================================================================================
 
 
// ==============================================================================================
// 🟢 REGION: SMA 20 / 50 Cross Engine
// ==============================================================================================
//
// 📌 Purpose:
//     Builds the standalone SMA 20 / 50 crossover engine.
//
// 🧠 Behavior:
//     • Uses osc as the source
//     • Runs independently of the adaptive crossover engine
//     • Draws its own plots and fill
//
// ==============================================================================================
//
// ──────────────────────────────────────────────
// 🟦 Subregion: Signal Lines
// ──────────────────────────────────────────────
float fastLine_sma =
     f_ma(in_MaType_fast_sma, osc, in_Len_fast_sma)
 
float slowLine_sma =
     f_ma(in_MaType_slow_sma, osc, in_Len_slow_sma)
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Crossover State
// ──────────────────────────────────────────────
bool bullCross_sma = ta.crossover(fastLine_sma, slowLine_sma)
bool bearCross_sma = ta.crossunder(fastLine_sma, slowLine_sma)
 
var bool crossBullState_sma = false
crossBullState_sma := bullCross_sma ? true : bearCross_sma ? false : crossBullState_sma
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Colors
// ──────────────────────────────────────────────
color crossLineCol_sma =
     crossBullState_sma ? color.rgb(255, 251, 0, 25) : color.rgb(188, 45, 255, 25)
 
color crossFillCol_sma =
     in_showFill_sma
         ? (crossBullState_sma ? color.rgb(255, 251, 0, 75) : color.rgb(188, 45, 255, 75))
         : na
 
// ──────────────────────────────────────────────
// 🟦 Subregion: Plots
// ──────────────────────────────────────────────
plotFast_sma = plot(
     in_showSignals_sma ? fastLine_sma : na,
     title="Fast Line (SMA Engine)",
     color=crossLineCol_sma,
     linewidth=1,
     show_last=in_showLast)
 
plotSlow_sma = plot(
     in_showSignals_sma ? slowLine_sma : na,
     title="Slow Line (SMA Engine)",
     color=crossLineCol_sma,
     linewidth=1,
     show_last=in_showLast)
 
fill(
     plotFast_sma,
     plotSlow_sma,
     color=crossFillCol_sma,
     title="Signal Fill (SMA Engine)")
 
// ==============================================================================================
// 🔴 END REGION: SMA 20 / 50 Cross Engine
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Alert Inputs
// ==============================================================================================
 
bool in_enableZeroCrossAlerts = input.bool(
     defval=false,
     title="Enable Zero Cross Alerts",
     group=G_ALERT,
     tooltip=TT_ZERO_ALERTS)
 
bool in_enableSignalCrossAlerts = input.bool(
     defval=false,
     title="Enable Fast / Slow Cross Alerts",
     group=G_ALERT,
     tooltip=TT_SIGNAL_ALERTS)
 
// ==============================================================================================
// 🔴 END REGION: Alert Inputs
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Guide Lines + Extreme Zones
// ==============================================================================================
 
float guideHalfBull = 50.0
float guideHalfBear = -50.0
 
float guideMidBull =
     in_useStateWeighted ? 100.0 : na
 
float guideMidBear =
     in_useStateWeighted ? -100.0 : na
 
// float guideOuterBull =
//      in_useStateWeighted ? 200.0 : 100.0
 
// float guideOuterBear =
//      in_useStateWeighted ? -200.0 : -100.0
 
plot(
     in_showGuides ? 0 : na,
     title="Zero Line",
     color=in_zeroCol,
     linewidth=1,
     show_last=in_showLast)
 
plot(
     in_showGuides ? guideHalfBull : na,
     title="+50 Guide",
     color=in_midRailCol,
     linewidth=1,
     show_last=in_showLast)
 
plot(
     in_showGuides ? guideHalfBear : na,
     title="-50 Guide",
     color=in_midRailCol,
     linewidth=1,
     show_last=in_showLast)
 
plot(
     in_showGuides and in_useStateWeighted ? guideMidBull : na,
     title="+100 Guide",
     color=in_midRailCol,
     linewidth=1,
     show_last=in_showLast)
 
plot(
     in_showGuides and in_useStateWeighted ? guideMidBear : na,
     title="-100 Guide",
     color=in_midRailCol,
     linewidth=1,
     show_last=in_showLast)
 
// plot(
//      in_showGuides ? guideOuterBull : na,
//      title="+ Outer Rail",
//      color=in_railCol,
//      linewidth=1,
//      show_last=in_showLast)
 
// plot(
//      in_showGuides ? guideOuterBear : na,
//      title="- Outer Rail",
//      color=in_railCol,
//      linewidth=1,
//      show_last=in_showLast)
 
pTopExtremeHi = plot(
     in_showExtremeZones ? in_extremeHi : na,
     title="Top Extreme Hi",
     color=na,
     display=display.none)
 
pTopExtremeLo = plot(
     in_showExtremeZones ? in_extremeLo : na,
     title="Top Extreme Lo",
     color=na,
     display=display.none)
 
fill(
     pTopExtremeHi,
     pTopExtremeLo,
     color=in_topExtremeFill,
     title="Top Extreme Fill")
 
pBotExtremeHi = plot(
     in_showExtremeZones ? -in_extremeLo : na,
     title="Bottom Extreme Hi",
     color=na,
     display=display.none)
 
pBotExtremeLo = plot(
     in_showExtremeZones ? -in_extremeHi : na,
     title="Bottom Extreme Lo",
     color=na,
     display=display.none)
 
fill(
     pBotExtremeHi,
     pBotExtremeLo,
     color=in_botExtremeFill,
     title="Bottom Extreme Fill")
 
// ==============================================================================================
// 🔴 END REGION: Guide Lines + Extreme Zones
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Reaction Zone Fills
// ==============================================================================================
 
pOscFill = plot(
     in_showReactionFills ? osc : na,
     title="Osc Fill Anchor",
     color=na,
     display=display.none)
 
pReact3Fill = plot(
     in_showReactionFills and showReaction3 ? oscReaction3 : na,
     title="Reaction 3 Fill",
     color=na,
     display=display.none)
 
pReact2Fill = plot(
     in_showReactionFills and showReaction2 ? oscReaction2 : na,
     title="Reaction 2 Fill",
     color=na,
     display=display.none)
 
pReact1Fill = plot(
     in_showReactionFills and showReaction1 ? oscReaction1 : na,
     title="Reaction 1 Fill",
     color=na,
     display=display.none)
 
fill(
     pOscFill,
     pReact3Fill,
     color=reactionFillBack,
     title="Reaction Fill 3")
 
fill(
     pOscFill,
     pReact2Fill,
     color=reactionFillMid,
     title="Reaction Fill 2")
 
fill(
     pOscFill,
     pReact1Fill,
     color=reactionFillFront,
     title="Reaction Fill 1")
 
// ==============================================================================================
// 🔴 END REGION: Reaction Fills
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Visible Plots
// ==============================================================================================
 
plot(
     in_showReactionLines and showReaction3 ? oscReaction3 : na,
     title="Reaction Line 3",
     color=reactionLineColor3,
     linewidth=1,
     show_last=in_showLast)
 
plot(
     in_showReactionLines and showReaction2 ? oscReaction2 : na,
     title="Reaction Line 2",
     color=reactionLineColor2,
     linewidth=1,
     show_last=in_showLast)
 
plot(
     in_showReactionLines and showReaction1 ? oscReaction1 : na,
     title="Reaction Line 1",
     color=reactionLineColor1,
     linewidth=1,
     show_last=in_showLast)
 
plot(
     in_showOscColumns ? osc : na,
     title="CE Oscillator Columns",
     style=plot.style_columns,
     color=oscHistCol,
     linewidth=2,
     show_last=in_showLast)
 
plot(
     in_showOscLine ? osc : na,
     title="CE Oscillator Line",
     style=plot.style_line,
     color=oscCol,
     linewidth=2,
     show_last=in_showLast_histlines)
 
plotFast = plot(
     in_showCrossLines ? fastLine : na,
     title="Fast Line",
     color=crossLineCol,
     linewidth=1,
     show_last=in_showLast)
 
plotSlow = plot(
     in_showCrossLines ? slowLine : na,
     title="Slow Line",
     color=crossLineCol,
     linewidth=1,
     show_last=in_showLast)
 
fill(
     plotFast,
     plotSlow,
     color=crossFillCol,
     title="Cross Fill")
 
// ==============================================================================================
// 🔴 END REGION: Visible Plots
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Oscillator Candles
// ==============================================================================================
//
// 📌 Purpose:
//     Renders the oscillator as synthetic candles inside the pane using
//     Pine Script's built-in `plotcandle()` function.
//
// 🧠 What this does:
//     Instead of drawing candles from price OHLC, this block builds a candle
//     from the oscillator itself:
//
//     • oscO = prior oscillator value
//     • oscH = higher of prior/current oscillator value
//     • oscL = lower of prior/current oscillator value
//     • oscC = current oscillator value
//
// 🧩 Why this matters in this script:
//     This gives users a candle-style view of oscillator movement, which can make:
//     • acceleration
//     • deceleration
//     • bar-to-bar expansion
//     • reversal behavior
//     easier to read than a line alone.
//
// 🛠 Pine feature note:
//     `plotcandle()` is not limited to chart price candles.
//     Pine can also use it to draw custom candles from any synthetic OHLC series,
//     which is what this block is doing with the oscillator.
//
// 🎨 Styling:
//     • candle body uses the oscillator body color
//     • wick and border use the full-strength oscillator edge color
//     • visibility is controlled by the Show Oscillator Candles input
//
// ==============================================================================================
 
float oscO =
     nz(osc[1], osc)
 
float oscH =
     math.max(oscO, osc)
 
float oscL =
     math.min(oscO, osc)
 
float oscC =
     osc
 
plotcandle(
     in_showOscCandles ? oscO : na,
     in_showOscCandles ? oscH : na,
     in_showOscCandles ? oscL : na,
     in_showOscCandles ? oscC : na,
     title="Oscillator Candles",
     color=oscCandleBodyCol,
     wickcolor=oscCandleEdgeCol,
     bordercolor=oscCandleEdgeCol,
     show_last=in_showLast)
 
// ==============================================================================================
// 🔴 END REGION: Oscillator Candles
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Price Overlay Candles
// ==============================================================================================
//
// 📌 Purpose:
//     Draws oscillator-colored candles on the main price chart while the script
//     itself remains in a separate pane.
//
// 🧠 Pine feature note:
//     This uses `plotcandle(..., force_overlay=true)` so the candles render in
//     the chart pane even though `overlay=false` at the script level.
//
// ==============================================================================================
//
plotcandle(
     in_priceCandleMode == "Last N Bars" ? open : na,
     in_priceCandleMode == "Last N Bars" ? high : na,
     in_priceCandleMode == "Last N Bars" ? low : na,
     in_priceCandleMode == "Last N Bars" ? close : na,
     title="Price Overlay Candles (Last N Bars)",
     color=priceOverlayBodyCol,
     wickcolor=priceOverlayEdgeCol,
     bordercolor=priceOverlayEdgeCol,
     show_last=in_priceCandleShowLast,
     force_overlay=true)
 
// ==============================================================================================
// 🔴 END REGION: Price Overlay Candles
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Configuration Table Inputs
// ==============================================================================================
//
// 📌 Purpose:
//     Defines the user-facing controls for the 2-column configuration table.
//
// ==============================================================================================
 
string mainDirTxt =
     dir == 1 ? "Bull" : "Bear"
 
string mainMultTxt =
     str.tostring(in_atrMult, "#.#")
 
string mainMultLabel =
     "OSC "
 
string reactionMult1Txt =
     str.tostring(in_reactionMult1, "#.#")
 
string reactionMult2Txt =
     str.tostring(in_reactionMult2, "#.#")
 
string reactionMult3Txt =
     str.tostring(in_reactionMult3, "#.#")
 
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"
 
bool reaction1FillVisible =
     in_showReactionFills and showReaction1
 
bool reaction2FillVisible =
     in_showReactionFills and showReaction2
 
bool reaction3FillVisible =
     in_showReactionFills and showReaction3
 
string reaction1RowLabel =
     "Mult " + reactionMult1Txt
 
string reaction2RowLabel =
     "Mult " + reactionMult2Txt
 
string reaction3RowLabel =
     "Mult " + reactionMult3Txt
 
string reaction1RowValue =
     (reactionDir1 == 1 ? "Bull" : "Bear") + " | " + (reaction1FillVisible ? "✔" : "✖")
 
string reaction2RowValue =
     (reactionDir2 == 1 ? "Bull" : "Bear") + " | " + (reaction2FillVisible ? "✔" : "✖")
 
string reaction3RowValue =
     (reactionDir3 == 1 ? "Bull" : "Bear") + " | " + (reaction3FillVisible ? "✔" : "✖")
 
float oscDelta =
     na(osc[1]) ? na : osc - osc[1]
 
string mainOscValueTxt =
     mainDirTxt + " | " + f_tableFmtSigned(osc) + " (" + f_tableFmtSigned(oscDelta) + ")"
 
var string chartTF_Pretty =
     TF.f_prettifyTF(timeframe.period)
 
string tableHdrLeftTxt =
     syminfo.ticker + " | " + chartTF_Pretty
 
string tableHdrRightTxt =
     in_oscMapMode
 
// ──────────────────────────────────────────────
// 🟦 Row colors
// ──────────────────────────────────────────────
 
color rowBaseBg =
     color.new(color.rgb(120, 76, 28), 0)
 
color rowBaseTxt =
     color.white
 
color neutralBg =
     color.new(color.black, 80)
 
color neutralTxt =
     color.white
 
color rowMainBg =
     na(oscCol) ? rowBaseBg : color.new(oscCol, 0)
 
color rowMainTxt =
     f_tableContrast(rowMainBg)
 
color rowFlipBg =
     latestFlipTxt == "Bull Flip" ? color.new(color.orange, 70) :
     latestFlipTxt == "Bear Flip" ? color.new(#f51673, 70) :
                                     rowBaseBg
 
color stateTxt =
     color.white
 
color rowRx1Bg =
     reaction1FillVisible ? (reactionDir1 == 1 ? color.new(color.orange, 25) : color.new(#f51673, 25)) :
     neutralBg
 
color rowRx1Txt =
     reaction1FillVisible ? color.white : neutralTxt
 
color rowRx2Bg =
     reaction2FillVisible ? (reactionDir2 == 1 ? color.new(color.orange, 40) : color.new(#f51673, 40)) :
     neutralBg
 
color rowRx2Txt =
     reaction2FillVisible ? color.white : neutralTxt
 
color rowRx3Bg =
     reaction3FillVisible ? (reactionDir3 == 1 ? color.new(color.orange, 55) : color.new(#f51673, 55)) :
     neutralBg
 
color rowRx3Txt =
     reaction3FillVisible ? color.white : neutralTxt
 
 
// ──────────────────────────────────────────────
// 🟦 Table Tooltips (Hover your cursor over the table cells)
// ──────────────────────────────────────────────
 
string tableHdrRightTip =
     "Oscillator Mapping Mode\n\n" +
     "Shows which mapping model is currently being used for the oscillator.\n\n" +
     "• Geometry:\n" +
     "  active = -100, midpoint = 0, extension = +100\n\n" +
     "• State-Weighted:\n" +
     "  bull regimes tend to live above 0 and bear regimes tend to live below 0."
 
string mainOscTip =
     "Main Oscillator State\n\n" +
     "Shows:\n" +
     "• the current main Chandelier direction\n" +
     "• the current oscillator value\n" +
     "• the oscillator's change from the prior bar"
 
string latestFlipTip =
     "Latest Main Flip\n\n" +
     "Shows:\n" +
     "• the most recent bull or bear flip from the main Chandelier engine\n" +
     "• how many bars have passed since that flip occurred"
 
string reaction1Tip =
     "Reaction Multiplier 1\n\n" +
     "Shows:\n" +
     "• the current bull / bear direction for Multiplier 1\n" +
     "• whether that reaction layer's fill is currently active"
 
string reaction2Tip =
     "Reaction Multiplier 2\n\n" +
     "Shows:\n" +
     "• the current bull / bear direction for Multiplier 2\n" +
     "• whether that reaction layer's fill is currently active"
 
string reaction3Tip =
     "Reaction Multiplier 3\n\n" +
     "Shows:\n" +
     "• the current bull / bear direction for Multiplier 3\n" +
     "• whether that reaction layer's fill is currently active"
 
// ──────────────────────────────────────────────
// 🟦 Table init
// ──────────────────────────────────────────────
var table ceConfigTable = table.new(
     f_tablePos(in_tablePos),
     2,
     6,
     border_color=color.new(color.gray, 60),
     frame_color=color.new(#787b86, 0),
     frame_width=1,
     border_width=1)
 
 
// ──────────────────────────────────────────────
// 🟦 Paint table
// ──────────────────────────────────────────────
if barstate.islast
    if in_showConfigTable
        _ts = f_tableSize(in_tableTextSize)
 
        table.clear(ceConfigTable, 0, 0, 1, 5)
 
        table.cell(ceConfigTable, 0, 0, tableHdrLeftTxt, text_color=rowMainTxt, bgcolor=rowMainBg, width=in_tableLabelWidth, text_size=_ts)
        table.cell(ceConfigTable, 1, 0, tableHdrRightTxt, text_color=rowMainTxt, bgcolor=rowMainBg, width=in_tableValueWidth, text_size=_ts, tooltip=tableHdrRightTip)
 
        table.cell(ceConfigTable, 0, 1, mainMultLabel, text_color=rowMainTxt, bgcolor=rowMainBg, width=in_tableLabelWidth, text_size=_ts)
        table.cell(ceConfigTable, 1, 1, mainOscValueTxt, text_color=rowMainTxt, bgcolor=rowMainBg, width=in_tableValueWidth, text_size=_ts, tooltip=mainOscTip)
 
        table.cell(ceConfigTable, 0, 2, "Latest Flip", text_color=stateTxt, bgcolor=rowFlipBg, width=in_tableLabelWidth, text_size=_ts)
        table.cell(ceConfigTable, 1, 2, latestFlipDisplay, text_color=stateTxt, bgcolor=rowFlipBg, width=in_tableValueWidth, text_size=_ts, tooltip=latestFlipTip)
 
        table.cell(ceConfigTable, 0, 3, reaction1RowLabel, text_color=rowRx1Txt, bgcolor=rowRx1Bg, width=in_tableLabelWidth, text_size=_ts)
        table.cell(ceConfigTable, 1, 3, reaction1RowValue, text_color=rowRx1Txt, bgcolor=rowRx1Bg, width=in_tableValueWidth, text_size=_ts, tooltip=reaction1Tip)
 
        table.cell(ceConfigTable, 0, 4, reaction2RowLabel, text_color=rowRx2Txt, bgcolor=rowRx2Bg, width=in_tableLabelWidth, text_size=_ts)
        table.cell(ceConfigTable, 1, 4, reaction2RowValue, text_color=rowRx2Txt, bgcolor=rowRx2Bg, width=in_tableValueWidth, text_size=_ts, tooltip=reaction2Tip)
 
        table.cell(ceConfigTable, 0, 5, reaction3RowLabel, text_color=rowRx3Txt, bgcolor=rowRx3Bg, width=in_tableLabelWidth, text_size=_ts)
        table.cell(ceConfigTable, 1, 5, reaction3RowValue, text_color=rowRx3Txt, bgcolor=rowRx3Bg, width=in_tableValueWidth, text_size=_ts, tooltip=reaction3Tip)
    else
        table.clear(ceConfigTable, 0, 0, 1, 5)
 
// ==============================================================================================
// 🔴 END REGION: Configuration Table (Original-Style 2-Column)
// ==============================================================================================
 
// ==============================================================================================
// 🟢 REGION: Alerts
// ==============================================================================================
//
// 📌 Purpose:
//     Defines the script's alert events for the two main trigger types:
//     zero-line crosses and adaptive fast / slow crossover signals.
//
// 🧠 How this works:
//     • First, the script detects the raw event conditions directly from the live series
//     • Then, each raw condition is gated behind its matching user input toggle
//     • Only enabled conditions are passed into `alertcondition()` for TradingView alerts
//
// 🔔 Alert types in this region:
//     • Zero Cross Up   → oscillator crosses above 0
//     • Zero Cross Down → oscillator crosses below 0
//     • Bull Cross      → adaptive fast line crosses above adaptive slow line
//     • Bear Cross      → adaptive fast line crosses below adaptive slow line
//
// 🧩 Why this matters in this script:
//     This keeps alert logic simple and predictable:
//     users can enable only the alert family they want, while the script
//     still tracks the raw crossover events internally.
//
// ==============================================================================================
 
bool zeroCrossUp_raw = ta.crossover(osc, 0.0)
bool zeroCrossDn_raw = ta.crossunder(osc, 0.0)
 
bool bullCross_raw = ta.crossover(fastLine, slowLine)
bool bearCross_raw = ta.crossunder(fastLine, slowLine)
 
bool zeroCrossUp =
     in_enableZeroCrossAlerts and zeroCrossUp_raw
 
bool zeroCrossDn =
     in_enableZeroCrossAlerts and zeroCrossDn_raw
 
bool signalCrossUp =
     in_enableSignalCrossAlerts and bullCross_raw
 
bool signalCrossDn =
     in_enableSignalCrossAlerts and bearCross_raw
 
alertcondition(
     zeroCrossUp,
     title="CE Osc Zero Cross Up",
     message="Chandelier Reaction Oscillator crossed above zero.")
 
alertcondition(
     zeroCrossDn,
     title="CE Osc Zero Cross Down",
     message="Chandelier Reaction Oscillator crossed below zero.")
 
alertcondition(
     signalCrossUp,
     title="CE Osc Fast/Slow Bull Cross",
     message="Chandelier Reaction Oscillator fast line crossed above slow line.")
 
alertcondition(
     signalCrossDn,
     title="CE Osc Fast/Slow Bear Cross",
     message="Chandelier Reaction Oscillator fast line crossed below slow line.")
 
// ==============================================================================================
// 🔴 END REGION: Alerts
// ==============================================================================================

← 返回列表