Fibonacci Recursive Exponential Moving Average (FR-EMA)

mei_13 · study · 260 行 · 点赞 1 · TradingView 原页

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

Pine Script

//@version=6
indicator("Fibonacci Recursive Exponential Moving Average (FR-EMA)", shorttitle="FR-EMA", overlay=true)
 
// =============================================================================
// Title:        Fibonacci Recursive Exponential Moving Average (FR-EMA)
// Version:      1.2.1 (Pine Script v6 Clean Verified Edition)
// Author:       Quant Engineering & Statistical Mathematics Group
// Created Date: October 2026
//
// Theoretical Framework:
// - Maximum Entropy Principle (Jaynes 1957): Exponential decay as the unique unbiased model
// - Diophantine Approximation & Hurwitz Theorem: Non-resonant filtering via the golden ratio
// - Three-Tier Fibonacci Hierarchy:
//   - Fast (Micro/Intraday): alpha1 = phi^-2 (approx 0.381966, Equivalent N approx 4.24 days)
//   - Mid (Momentum/Cycle):  alpha2 = phi^-3 (approx 0.236068, Equivalent N approx 7.47 days)
//   - Slow (Anchor/Trend):   alpha3 = 1 - phi^-0.2 (approx 0.091756, Equivalent N approx 20.80 days)
//
// Display Default:
// - Lines only (Fast, Mid, Slow).
// - Ribbon cloud, entry signals, and info dashboard are optional (Default OFF).
// =============================================================================
 
// -----------------------------------------------------------------------------
// 1. Inputs & Model Settings
// -----------------------------------------------------------------------------
grp_model  = "[1] Model Architecture Selection"
model_mode = input.string("FR-EMA (Golden Ratio: 4.2d / 7.5d / 20.8d)", "EMA Parameter System",
             options=[
                 "FR-EMA (Golden Ratio: 4.2d / 7.5d / 20.8d)",
                 "Fibonacci Days EMA (5d / 8d / 21d)",
                 "Standard Market EMA (5d / 10d / 20d)",
                 "Nearest Integer EMA (4d / 8d / 21d)",
                 "Custom Parameters"
             ], group=grp_model, tooltip="Select the mathematical architecture for Fast, Mid, and Slow smoothing factors")
src        = input.source(close, "Price Source", group=grp_model)
 
grp_custom = "[2] Custom Parameters (Enabled only if Custom selected)"
c_alpha1   = input.float(0.381966, "Custom Fast Alpha", minval=0.001, maxval=1.0, group=grp_custom)
c_alpha2   = input.float(0.236068, "Custom Mid Alpha",  minval=0.001, maxval=1.0, group=grp_custom)
c_alpha3   = input.float(0.091756, "Custom Slow Alpha", minval=0.001, maxval=1.0, group=grp_custom)
 
grp_visual = "[3] Visual Style & Visibility (Default: Lines Only)"
show_fast  = input.bool(true, "Show Fast Line", group=grp_visual)
show_mid   = input.bool(true, "Show Mid Line", group=grp_visual)
show_slow  = input.bool(true, "Show Slow Line", group=grp_visual)
show_ribbon= input.bool(false, "Show Perfect Order Ribbon Fill [Default OFF]", group=grp_visual, tooltip="Enable to display the dynamic cloud between Fast and Slow lines")
ribbon_transp = input.int(85, "Ribbon Transparency (0-100)", minval=0, maxval=100, group=grp_visual)
 
grp_color  = "[4] Color Settings"
col_fast   = input.color(#00E5FF, "Fast Line (Cyan)", group=grp_color)
col_mid    = input.color(#FFD600, "Mid Line (Gold)", group=grp_color)
col_slow   = input.color(#D500F9, "Slow Line (Purple)", group=grp_color)
col_bull_fill = input.color(#00E676, "Bullish PO Cloud Color", group=grp_color)
col_bear_fill = input.color(#FF1744, "Bearish PO Cloud Color", group=grp_color)
 
grp_sig    = "[5] Signals & Entry Shapes [Default OFF]"
show_sig_po_bull  = input.bool(false, "Show Bullish PO Trigger (Strat_2B)", group=grp_sig)
show_sig_pullback = input.bool(false, "Show Bullish Pullback Dip (Strat_2C)", group=grp_sig)
show_sig_po_bear  = input.bool(false, "Show Bearish PO Trigger (Strat_3B)", group=grp_sig)
show_sig_dev_over = input.bool(false, "Show Slow Over-Deviation Zone (Dev < -7%)", group=grp_sig)
 
grp_dash   = "[6] Information Dashboard [Default OFF]"
show_dash  = input.bool(false, "Show Real-Time Dashboard", group=grp_dash)
dash_pos   = input.string("Top Right", "Dashboard Position", options=["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group=grp_dash)
 
// -----------------------------------------------------------------------------
// 2. Exact Mathematical Smoothing Calculation
// -----------------------------------------------------------------------------
// Recursive IIR Filter: MA_t = alpha * P_t + (1 - alpha) * MA_{t-1}
f_recursive_ema(float source_val, float alpha_val) =>
    var float ema_val = na
    ema_val := na(ema_val) ? source_val : alpha_val * source_val + (1.0 - alpha_val) * ema_val
    ema_val
 
// Golden Ratio Constant
phi = (1.0 + math.sqrt(5.0)) / 2.0  // approx 1.61803398875
 
// Resolve Alphas based on selected architecture
float alpha_fast = na
float alpha_mid  = na
float alpha_slow = na
 
if model_mode == "FR-EMA (Golden Ratio: 4.2d / 7.5d / 20.8d)"
    alpha_fast := math.pow(phi, -2.0)              // phi^-2 approx 0.381966
    alpha_mid  := math.pow(phi, -3.0)              // phi^-3 approx 0.236068
    alpha_slow := 1.0 - math.pow(phi, -0.2)        // 1 - phi^-0.2 approx 0.091756
else if model_mode == "Fibonacci Days EMA (5d / 8d / 21d)"
    alpha_fast := 2.0 / (5.0 + 1.0)                // 0.333333
    alpha_mid  := 2.0 / (8.0 + 1.0)                // 0.222222
    alpha_slow := 2.0 / (21.0 + 1.0)               // 0.090909
else if model_mode == "Standard Market EMA (5d / 10d / 20d)"
    alpha_fast := 2.0 / (5.0 + 1.0)                // 0.333333
    alpha_mid  := 2.0 / (10.0 + 1.0)               // 0.181818
    alpha_slow := 2.0 / (20.0 + 1.0)               // 0.095238
else if model_mode == "Nearest Integer EMA (4d / 8d / 21d)"
    alpha_fast := 2.0 / (4.0 + 1.0)                // 0.400000
    alpha_mid  := 2.0 / (8.0 + 1.0)                // 0.222222
    alpha_slow := 2.0 / (21.0 + 1.0)               // 0.090909
else
    alpha_fast := c_alpha1
    alpha_mid  := c_alpha2
    alpha_slow := c_alpha3
 
// Calculate 3-Tier Lines
val_fast = f_recursive_ema(src, alpha_fast)
val_mid  = f_recursive_ema(src, alpha_mid)
val_slow = f_recursive_ema(src, alpha_slow)
 
// Percentage Deviations
dev_slow_pct = val_slow != 0 ? (src - val_slow) / val_slow * 100.0 : 0.0
dev_fast_pct = val_fast != 0 ? (src - val_fast) / val_fast * 100.0 : 0.0
 
// -----------------------------------------------------------------------------
// 3. State & Permutation Logic (Ribbon Topology)
// -----------------------------------------------------------------------------
bool is_bull_po = (val_fast > val_mid) and (val_mid > val_slow)
bool is_bear_po = (val_fast < val_mid) and (val_mid < val_slow)
 
// Triggers (First-day event)
bool trig_bull_po = (bar_index > 0) and is_bull_po and not is_bull_po[1]
bool trig_bear_po = (bar_index > 0) and is_bear_po and not is_bear_po[1]
 
// Pullback Condition (Strat_2C): Bullish PO active AND Close touches or dips below Fast line
bool is_pullback_dip = is_bull_po and (close <= val_fast)
bool trig_pullback   = (bar_index > 0) and is_pullback_dip and not is_pullback_dip[1]
 
// Rebound Condition: Break back above Fast line after pullback
bool trig_pullback_exit = is_bull_po and ta.crossover(close, val_fast)
 
// Oversold Deviation Condition (Strat_1B)
bool is_oversold_dev = dev_slow_pct < -7.0
 
// -----------------------------------------------------------------------------
// 4. Line Plots & Ribbon Fills
// -----------------------------------------------------------------------------
p_fast = plot(show_fast ? val_fast : na, "FR-EMA Fast", color=col_fast, linewidth=2)
p_mid  = plot(show_mid  ? val_mid  : na, "FR-EMA Mid",  color=col_mid,  linewidth=2)
p_slow = plot(show_slow ? val_slow : na, "FR-EMA Slow", color=col_slow, linewidth=2)
 
// Dynamic Cloud Fills (Default OFF)
color ribbon_color = na
if show_ribbon
    if is_bull_po
        ribbon_color := color.new(col_bull_fill, ribbon_transp)
    else if is_bear_po
        ribbon_color := color.new(col_bear_fill, ribbon_transp)
    else
        ribbon_color := color.new(color.gray, 95)
 
fill(p_fast, p_slow, color=ribbon_color, title="Perfect Order Ribbon Cloud")
 
// -----------------------------------------------------------------------------
// 5. Signal Shapes on Chart (Default OFF)
// -----------------------------------------------------------------------------
// [Strat_2B] Bullish PO Formation Trigger (Strong Momentum Buy)
plotshape(show_sig_po_bull and trig_bull_po, title="Bullish PO Trigger (Strat_2B)",
          style=shape.triangleup, location=location.belowbar,
          color=#00E676, size=size.normal, text="BULL PO", textcolor=color.white)
 
// [Strat_2C] Bullish Pullback Dip Entry
plotshape(show_sig_pullback and trig_pullback, title="PO Pullback Dip (Strat_2C)",
          style=shape.diamond, location=location.belowbar,
          color=#FFD600, size=size.small, text="DIP", textcolor=color.black)
 
// [Strat_3B] Bearish PO Formation Trigger
plotshape(show_sig_po_bear and trig_bear_po, title="Bearish PO Trigger (Strat_3B)",
          style=shape.triangledown, location=location.abovebar,
          color=#FF1744, size=size.normal, text="BEAR PO", textcolor=color.white)
 
// [Strat_1B] Oversold Zone Marker
plotshape(show_sig_dev_over and is_oversold_dev, title="Oversold Deviation Zone (Strat_1B)",
          style=shape.circle, location=location.belowbar,
          color=#2979FF, size=size.tiny)
 
// -----------------------------------------------------------------------------
// 6. Real-Time Dashboard Table (Default OFF)
// -----------------------------------------------------------------------------
string table_position = switch dash_pos
    "Top Right"    => position.top_right
    "Bottom Right" => position.bottom_right
    "Top Left"     => position.top_left
    => position.bottom_left
 
var table dash_table = table.new(table_position, 2, 8,
                       bgcolor=color.new(#131722, 10),
                       border_color=color.new(color.gray, 60),
                       border_width=1,
                       frame_color=color.new(color.gray, 30),
                       frame_width=1)
 
if show_dash and barstate.islast
    // Header
    table.cell(dash_table, 0, 0, "FR-EMA Framework", bgcolor=color.new(#2962FF, 30), text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash_table, 1, 0, "Metric Value", bgcolor=color.new(#2962FF, 30), text_color=color.white, text_size=size.small, text_halign=text.align_right)
 
    // Current State
    string status_txt = is_bull_po ? "Bullish PO" : (is_bear_po ? "Bearish PO" : "Neutral / Range")
    color  status_col = is_bull_po ? #00E676 : (is_bear_po ? #FF1744 : color.gray)
    table.cell(dash_table, 0, 1, "Trend Structure", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash_table, 1, 1, status_txt, text_color=status_col, text_size=size.small, text_halign=text.align_right)
 
    // Fast Line (4.2d)
    table.cell(dash_table, 0, 2, "Fast Line (4.2d)", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash_table, 1, 2, str.tostring(val_fast, "#,###.1"), text_color=col_fast, text_size=size.small, text_halign=text.align_right)
 
    // Mid Line (7.5d)
    table.cell(dash_table, 0, 3, "Mid Line (7.5d)", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash_table, 1, 3, str.tostring(val_mid, "#,###.1"), text_color=col_mid, text_size=size.small, text_halign=text.align_right)
 
    // Slow Line (20.8d)
    table.cell(dash_table, 0, 4, "Slow Line (20.8d)", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash_table, 1, 4, str.tostring(val_slow, "#,###.1"), text_color=col_slow, text_size=size.small, text_halign=text.align_right)
 
    // Slow Deviation
    color dev_col = dev_slow_pct >= 0 ? #00E676 : #FF5252
    table.cell(dash_table, 0, 5, "Slow Deviation", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash_table, 1, 5, (dev_slow_pct >= 0 ? "+" : "") + str.tostring(dev_slow_pct, "0.00") + " %", text_color=dev_col, text_size=size.small, text_halign=text.align_right)
 
    // Pullback Status
    string pb_txt = is_pullback_dip ? "Pullback Active" : (is_bull_po ? "Uptrend Stable" : "None")
    color  pb_col = is_pullback_dip ? #FFD600 : color.white
    table.cell(dash_table, 0, 6, "Pullback Status", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash_table, 1, 6, pb_txt, text_color=pb_col, text_size=size.small, text_halign=text.align_right)
 
    // Recommended Action
    string stance_txt = "Hold / Neutral"
    color  stance_col = color.white
    if trig_bull_po
        stance_txt := "Bull PO Entry (2B)"
        stance_col := #00E676
    else if is_pullback_dip
        stance_txt := "Pullback Entry (2C)"
        stance_col := #FFD600
    else if trig_bear_po
        stance_txt := "Bear PO Warning (3B)"
        stance_col := #FF1744
    else if dev_slow_pct < -7.0
        stance_txt := "Rebound Watch (1B)"
        stance_col := color.white
 
    table.cell(dash_table, 0, 7, "Quant Action", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash_table, 1, 7, stance_txt, text_color=stance_col, text_size=size.small, text_halign=text.align_right)
 
// -----------------------------------------------------------------------------
// 7. TradingView Alerts
// -----------------------------------------------------------------------------
alertcondition(trig_bull_po, title="[FR-EMA] Bullish Perfect Order Trigger (Strat_2B)", 
               message="[FR-EMA Alert] {{ticker}} achieved Bullish Perfect Order. Consider long entry at next open. Close: {{close}}")
 
alertcondition(trig_pullback, title="[FR-EMA] Bullish Pullback Dip Detected (Strat_2C)", 
               message="[FR-EMA Alert] {{ticker}} dipped to/below Fast line during Bullish PO. Consider pullback entry. Close: {{close}}")
 
alertcondition(trig_pullback_exit, title="[FR-EMA] Fast Line Reclaimed (Pullback Exit)", 
               message="[FR-EMA Alert] {{ticker}} crossed back above Fast line. Consider exit / take-profit. Close: {{close}}")
 
alertcondition(trig_bear_po, title="[FR-EMA] Bearish Perfect Order Trigger (Strat_3B)", 
               message="[FR-EMA Alert] {{ticker}} achieved Bearish Perfect Order. Warning / Short consideration. Close: {{close}}")
 
alertcondition(is_oversold_dev, title="[FR-EMA] Slow Line Oversold Deviation (Strat_1B)", 
               message="[FR-EMA Alert] {{ticker}} deviated below -7.0% from Slow line. Monitor for mean-reversion. Close: {{close}}")

← 返回列表