Camarilla Pivot Points

sithuphyo_21 · study · 350 行 · 点赞 764 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sithuphyo_21 — Institutional Camarilla Pivot Points Indicator (v6)
//@version=6
indicator("Camarilla Pivot Points", shorttitle="Camarilla Pivots", overlay=true, 
     max_lines_count=500, max_boxes_count=500, max_labels_count=500)
 
// ============================================================================
// SECTION 1: USER INPUTS & CONFIGURATION
// ============================================================================
 
// ── 01. Timeframe & Calculation Engine ──────────────────────────────────────
string grp_calc             = "📐 01. Camarilla Calculation Engine"
string pivotTimeframe       = input.string("Daily", "Camarilla Timeframe",
     options = ["Auto (Chart Adaptive)", "Daily", "Weekly", "Monthly"], group = grp_calc,
     tooltip = "Reference higher timeframe for High, Low, Close calculations:\n• Auto: Automatically selects Daily for intraday (<=15m), Weekly for intermediate (30m-4h), and Monthly for higher timeframes.\n• Daily: Best for intraday day trading & scalping.\n• Weekly: Best for multi-day swing trading.\n• Monthly: Best for macro institutional key levels.")
 
string displayStyle         = input.string("Active Period (Projected Lines & Zones)", "Display Mode",
     options = ["Active Period (Projected Lines & Zones)", "Historical Stepped Lines (Full History)", "Both (Historical + Projected Active)"], group = grp_calc,
     tooltip = "• Active Period: Clean, clutter-free horizontal projection lines with right-side price tags & shaded zones for the current trading day/week.\n• Historical Stepped Lines: Continuous native step lines across all historical chart bars.\n• Both: Continuous historical lines plus extended active projection lines and shaded zones.")
 
int    extendBarsRight      = input.int(20, "Active Line Extension (Bars)", minval = 5, maxval = 100, group = grp_calc,
     tooltip = "Number of bars to project the current active Camarilla lines into the future.")
 
// ── 02. Pivot Levels Visibility ──────────────────────────────────────────────
string grp_levels           = "🎯 02. Camarilla Levels Display"
bool   showR5S5             = input.bool(true, "Show R5 & S5 (Target 2 / Max Expansion)", group = grp_levels,
     tooltip = "Extreme expansion target levels (C ± 1.10 x Range).")
bool   showR4S4             = input.bool(true, "Show R4 & S4 (Breakout / Breakdown Triggers)", group = grp_levels,
     tooltip = "Institutional trend breakout trigger levels (C ± 0.55 x Range).")
bool   showR3S3             = input.bool(true, "Show R3 & S3 (Mean Reversion S/R)", group = grp_levels,
     tooltip = "Statistical range boundaries where 75-80% of days consolidate (C ± 0.275 x Range).")
bool   showR2S2             = input.bool(false, "Show R2 & S2 (Intermediate Buffer)", group = grp_levels,
     tooltip = "Intermediate range buffers (C ± 0.1833 x Range).")
bool   showR1S1             = input.bool(false, "Show R1 & S1 (Minor Range)", group = grp_levels,
     tooltip = "Minor internal buffers (C ± 0.0916 x Range).")
bool   showPivotP           = input.bool(true, "Show Central Pivot (P)", group = grp_levels,
     tooltip = "Central equilibrium pivot level (H + L + C) / 3.")
 
// ── 03. Institutional Shaded Zones ───────────────────────────────────────────
string grp_zones            = "🎨 03. Institutional Shaded Zones"
bool   showRangeZone        = input.bool(true, "Highlight Range Zone (S3 - R3)", group = grp_zones,
     tooltip = "Shades the 75-80% statistical range equilibrium where institutional mean reversion occurs.")
bool   showBufferZone       = input.bool(true, "Highlight Buffer Zones (R3-R4 & S3-S4)", group = grp_zones,
     tooltip = "Shades the caution / no-trade buffer zones between S3-S4 and R3-R4 where price is in limbo before a breakout or reversal.")
bool   showBullBreakoutZone = input.bool(true, "Highlight Bullish Breakout Zone (R4 - R5)", group = grp_zones,
     tooltip = "Shades the upside expansion runner zone triggered above R4.")
bool   showBearBreakoutZone = input.bool(true, "Highlight Bearish Breakdown Zone (S4 - S5)", group = grp_zones,
     tooltip = "Shades the downside expansion runner zone triggered below S4.")
bool   showBufferLabel      = input.bool(true, "Show 'NO-TRADE ZONE' Label", group = grp_zones,
     tooltip = "Displays a subtle warning badge inside the buffer zones.")
 
color  rangeZoneColor       = input.color(color.new(#2962ff, 92), "Range Zone (S3-R3) Shading", group = grp_zones)
color  bufferZoneColor      = input.color(color.new(#ff9800, 92), "Buffer Zone (No-Trade) Shading", group = grp_zones)
color  bullBreakColor       = input.color(color.new(#089981, 88), "Bull Breakout (R4-R5) Shading", group = grp_zones)
color  bearBreakColor       = input.color(color.new(#f23645, 88), "Bear Breakdown (S4-S5) Shading", group = grp_zones)
 
// ── 04. Colors & Styling ─────────────────────────────────────────────────────
string grp_style            = "🌈 04. Colors & Styling"
color  colR5                = input.color(#00e676, "R5 (Target 2)", inline = "r5", group = grp_style)
color  colR4                = input.color(#089981, "R4 (Breakout)", inline = "r4", group = grp_style)
color  colR3                = input.color(#26a69a, "R3 (Resistance)", inline = "r3", group = grp_style)
color  colR2                = input.color(#80cbc4, "R2 (Buffer)", inline = "r2", group = grp_style)
color  colR1                = input.color(#b2dfdb, "R1 (Minor)", inline = "r1", group = grp_style)
color  colPivot             = input.color(#fbc02d, "Central Pivot (P)", inline = "p", group = grp_style)
color  colS1                = input.color(#ffcdd2, "S1 (Minor)", inline = "s1", group = grp_style)
color  colS2                = input.color(#ef9a9a, "S2 (Buffer)", inline = "s2", group = grp_style)
color  colS3                = input.color(#e57373, "S3 (Support)", inline = "s3", group = grp_style)
color  colS4                = input.color(#f23645, "S4 (Breakdown)", inline = "s4", group = grp_style)
color  colS5                = input.color(#d50000, "S5 (Target 2)", inline = "s5", group = grp_style)
 
bool   showLabels           = input.bool(true, "Show Level Tags & Prices", group = grp_style)
bool   showPricesInLabels   = input.bool(true, "Include Price Value in Tags", group = grp_style)
string labelSizeStr         = input.string("Small", "Label Size", options = ["Tiny", "Small", "Normal"], group = grp_style)
 
// ── 05. Reversal & Breakout Signals ──────────────────────────────────────────
string grp_signals          = "⚡ 05. Real-Time Signal Markers"
bool   showSignals          = input.bool(true, "Show Buy / Sell Signal Markers", group = grp_signals,
     tooltip = "Plots visual reversal triangles at S3/R3 and momentum breakout arrows at R4/S4.")
bool   enableReversalSigs   = input.bool(true, "S3 / R3 Mean Reversion Signals", group = grp_signals)
bool   enableBreakoutSigs   = input.bool(true, "R4 / S4 Trend Breakout Signals", group = grp_signals)
 
 
// ============================================================================
// SECTION 2: TIMEFRAME RESOLUTION & CAMARILLA CALCULATIONS
// ============================================================================
 
// Resolve reference higher timeframe
f_getAutoTf() =>
    if timeframe.isseconds or (timeframe.isintraday and timeframe.multiplier <= 15)
        "D"
    else if timeframe.isintraday and timeframe.multiplier > 15
        "W"
    else
        "M"
 
string refTf = switch pivotTimeframe
    "Auto (Chart Adaptive)" => f_getAutoTf()
    "Weekly"                => "W"
    "Monthly"               => "M"
    =>                         "D" // "Daily"
 
// Retrieve previous completed HTF bar HLC (100% Non-Repainting, aligned across entire session)
[prevH, prevL, prevC] = request.security(syminfo.tickerid, refTf, [high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
 
float htfRange = math.max(prevH - prevL, syminfo.mintick)
 
// Exact Camarilla Mathematical Equations
float P  = (prevH + prevL + prevC) / 3.0
float R5 = prevC + htfRange * 1.10
float R4 = prevC + htfRange * (1.10 / 2.0)  // 0.55 * Range
float R3 = prevC + htfRange * (1.10 / 4.0)  // 0.275 * Range
float R2 = prevC + htfRange * (1.10 / 6.0)  // 0.1833 * Range
float R1 = prevC + htfRange * (1.10 / 12.0) // 0.0916 * Range
 
float S1 = prevC - htfRange * (1.10 / 12.0)
float S2 = prevC - htfRange * (1.10 / 6.0)
float S3 = prevC - htfRange * (1.10 / 4.0)
float S4 = prevC - htfRange * (1.10 / 2.0)
float S5 = prevC - htfRange * 1.10
 
// Period Change Detection
bool isNewPeriod = ta.change(time(refTf)) != 0
var int periodStartBar = 0
if isNewPeriod
    periodStartBar := bar_index
 
 
// ============================================================================
// SECTION 3: CONTINUOUS HISTORICAL PLOTS (ZERO-LAG STEPPED LINES)
// ============================================================================
 
bool renderHistoricalPlots = displayStyle == "Historical Stepped Lines (Full History)" or displayStyle == "Both (Historical + Projected Active)"
 
// Step lines break cleanly on period transition without diagonal connectors
plot(renderHistoricalPlots and showR5S5 ? R5 : na, "Hist R5", color = colR5, linewidth = 1, style = plot.style_linebr)
plot(renderHistoricalPlots and showR4S4 ? R4 : na, "Hist R4", color = colR4, linewidth = 2, style = plot.style_linebr)
plot(renderHistoricalPlots and showR3S3 ? R3 : na, "Hist R3", color = colR3, linewidth = 2, style = plot.style_linebr)
plot(renderHistoricalPlots and showR2S2 ? R2 : na, "Hist R2", color = colR2, linewidth = 1, style = plot.style_linebr)
plot(renderHistoricalPlots and showR1S1 ? R1 : na, "Hist R1", color = colR1, linewidth = 1, style = plot.style_linebr)
 
plot(renderHistoricalPlots and showPivotP ? P : na, "Hist Pivot P", color = colPivot, linewidth = 1, style = plot.style_linebr)
 
plot(renderHistoricalPlots and showR1S1 ? S1 : na, "Hist S1", color = colS1, linewidth = 1, style = plot.style_linebr)
plot(renderHistoricalPlots and showR2S2 ? S2 : na, "Hist S2", color = colS2, linewidth = 1, style = plot.style_linebr)
plot(renderHistoricalPlots and showR3S3 ? S3 : na, "Hist S3", color = colS3, linewidth = 2, style = plot.style_linebr)
plot(renderHistoricalPlots and showR4S4 ? S4 : na, "Hist S4", color = colS4, linewidth = 2, style = plot.style_linebr)
plot(renderHistoricalPlots and showR5S5 ? S5 : na, "Hist S5", color = colS5, linewidth = 1, style = plot.style_linebr)
 
 
// ============================================================================
// SECTION 4: ACTIVE PROJECTION LINES, LABELS & SHADED ZONES
// ============================================================================
 
bool renderActiveProjections = displayStyle == "Active Period (Projected Lines & Zones)" or displayStyle == "Both (Historical + Projected Active)"
 
f_lblSize(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        =>          size.small
 
var line ln_r5 = na, var line ln_r4 = na, var line ln_r3 = na, var line ln_r2 = na, var line ln_r1 = na
var line ln_p  = na
var line ln_s1 = na, var line ln_s2 = na, var line ln_s3 = na, var line ln_s4 = na, var line ln_s5 = na
 
var label lb_r5 = na, var label lb_r4 = na, var label lb_r3 = na, var label lb_r2 = na, var label lb_r1 = na
var label lb_p  = na
var label lb_s1 = na, var label lb_s2 = na, var label lb_s3 = na, var label lb_s4 = na, var label lb_s5 = na
 
var box bx_range     = na
var box bx_bufUpper  = na
var box bx_bufLower  = na
var box bx_bullBreak = na
var box bx_bearBreak = na
 
// Update Single Active Level Function
f_updateActiveLevel(line ln, label lb, bool enabled, float price, color col, string name, int x1, int x2, string lnStyle) =>
    line  retLn = ln
    label retLb = lb
 
    if renderActiveProjections and enabled and not na(price)
        string linePattern = lnStyle == "Dotted" ? line.style_dotted : (lnStyle == "Dashed" ? line.style_dashed : line.style_solid)
        int    lineWidth   = (str.startswith(name, "R4") or str.startswith(name, "S4") or str.startswith(name, "R3") or str.startswith(name, "S3")) ? 2 : 1
 
        if na(retLn)
            retLn := line.new(x1, price, x2, price, color = col, width = lineWidth, style = linePattern)
        else
            line.set_xy1(retLn, x1, price)
            line.set_xy2(retLn, x2, price)
 
        if showLabels
            string txt = showPricesInLabels ? name + " (" + str.tostring(price, format.mintick) + ")" : name
            if na(retLb)
                retLb := label.new(x2, price, txt, color = color.new(col, 100), textcolor = col, style = label.style_label_left, size = f_lblSize(labelSizeStr))
            else
                label.set_xy(retLb, x2, price)
                label.set_text(retLb, txt)
    else
        if not na(retLn)
            line.delete(retLn)
            retLn := na
        if not na(retLb)
            label.delete(retLb)
            retLb := na
    [retLn, retLb]
 
if not na(prevC)
    int startX = periodStartBar
    int endX   = bar_index + extendBarsRight
 
    // Active Projected Lines & Labels
    [r5L, r5B] = f_updateActiveLevel(ln_r5, lb_r5, showR5S5, R5, colR5, "R5 (Target 2)", startX, endX, "Dotted")
    [r4L, r4B] = f_updateActiveLevel(ln_r4, lb_r4, showR4S4, R4, colR4, "R4 (Breakout)", startX, endX, "Solid")
    [r3L, r3B] = f_updateActiveLevel(ln_r3, lb_r3, showR3S3, R3, colR3, "R3 (Resistance)", startX, endX, "Solid")
    [r2L, r2B] = f_updateActiveLevel(ln_r2, lb_r2, showR2S2, R2, colR2, "R2", startX, endX, "Dashed")
    [r1L, r1B] = f_updateActiveLevel(ln_r1, lb_r1, showR1S1, R1, colR1, "R1", startX, endX, "Dotted")
 
    [pL,  pB]  = f_updateActiveLevel(ln_p,  lb_p,  showPivotP, P,  colPivot, "Pivot (P)", startX, endX, "Dashed")
 
    [s1L, s1B] = f_updateActiveLevel(ln_s1, lb_s1, showR1S1, S1, colS1, "S1", startX, endX, "Dotted")
    [s2L, s2B] = f_updateActiveLevel(ln_s2, lb_s2, showR2S2, S2, colS2, "S2", startX, endX, "Dashed")
    [s3L, s3B] = f_updateActiveLevel(ln_s3, lb_s3, showR3S3, S3, colS3, "S3 (Support)", startX, endX, "Solid")
    [s4L, s4B] = f_updateActiveLevel(ln_s4, lb_s4, showR4S4, S4, colS4, "S4 (Breakdown)", startX, endX, "Solid")
    [s5L, s5B] = f_updateActiveLevel(ln_s5, lb_s5, showR5S5, S5, colS5, "S5 (Target 2)", startX, endX, "Dotted")
 
    ln_r5 := r5L, lb_r5 := r5B
    ln_r4 := r4L, lb_r4 := r4B
    ln_r3 := r3L, lb_r3 := r3B
    ln_r2 := r2L, lb_r2 := r2B
    ln_r1 := r1L, lb_r1 := r1B
    ln_p  := pL,  lb_p  := pB
    ln_s1 := s1L, lb_s1 := s1B
    ln_s2 := s2L, lb_s2 := s2B
    ln_s3 := s3L, lb_s3 := s3B
    ln_s4 := s4L, lb_s4 := s4B
    ln_s5 := s5L, lb_s5 := s5B
 
    // Active Shaded Institutional Zones
    if renderActiveProjections and showRangeZone and showR3S3
        if na(bx_range)
            bx_range := box.new(startX, R3, endX, S3, border_width = 0, bgcolor = rangeZoneColor)
        else
            box.set_left(bx_range, startX)
            box.set_right(bx_range, endX)
            box.set_top(bx_range, R3)
            box.set_bottom(bx_range, S3)
    else if not na(bx_range)
        box.delete(bx_range)
        bx_range := na
 
    // Buffer Zones (Caution / No-Trade Zones: R3-R4 & S3-S4)
    string bufTxt    = showBufferLabel ? "⚠️ NO-TRADE ZONE" : ""
    color  bufTxtCol = color.new(#ff9800, 25)
 
    if renderActiveProjections and showBufferZone and showR3S3 and showR4S4
        // Upper Buffer Zone (R3 to R4)
        if na(bx_bufUpper)
            bx_bufUpper := box.new(startX, R4, endX, R3, border_width = 0, bgcolor = bufferZoneColor,
                                   text = bufTxt, text_size = size.tiny, text_color = bufTxtCol,
                                   text_halign = text.align_right, text_valign = text.align_center)
        else
            box.set_left(bx_bufUpper, startX), box.set_right(bx_bufUpper, endX)
            box.set_top(bx_bufUpper, R4), box.set_bottom(bx_bufUpper, R3)
            box.set_bgcolor(bx_bufUpper, bufferZoneColor)
            box.set_text(bx_bufUpper, bufTxt)
            box.set_text_color(bx_bufUpper, bufTxtCol)
 
        // Lower Buffer Zone (S4 to S3)
        if na(bx_bufLower)
            bx_bufLower := box.new(startX, S3, endX, S4, border_width = 0, bgcolor = bufferZoneColor,
                                   text = bufTxt, text_size = size.tiny, text_color = bufTxtCol,
                                   text_halign = text.align_right, text_valign = text.align_center)
        else
            box.set_left(bx_bufLower, startX), box.set_right(bx_bufLower, endX)
            box.set_top(bx_bufLower, S3), box.set_bottom(bx_bufLower, S4)
            box.set_bgcolor(bx_bufLower, bufferZoneColor)
            box.set_text(bx_bufLower, bufTxt)
            box.set_text_color(bx_bufLower, bufTxtCol)
    else
        if not na(bx_bufUpper)
            box.delete(bx_bufUpper), bx_bufUpper := na
        if not na(bx_bufLower)
            box.delete(bx_bufLower), bx_bufLower := na
 
    if renderActiveProjections and showBullBreakoutZone and showR4S4 and showR5S5
        if na(bx_bullBreak)
            bx_bullBreak := box.new(startX, R5, endX, R4, border_width = 0, bgcolor = bullBreakColor)
        else
            box.set_left(bx_bullBreak, startX)
            box.set_right(bx_bullBreak, endX)
            box.set_top(bx_bullBreak, R5)
            box.set_bottom(bx_bullBreak, R4)
    else if not na(bx_bullBreak)
        box.delete(bx_bullBreak)
        bx_bullBreak := na
 
    if renderActiveProjections and showBearBreakoutZone and showR4S4 and showR5S5
        if na(bx_bearBreak)
            bx_bearBreak := box.new(startX, S4, endX, S5, border_width = 0, bgcolor = bearBreakColor)
        else
            box.set_left(bx_bearBreak, startX)
            box.set_right(bx_bearBreak, endX)
            box.set_top(bx_bearBreak, S4)
            box.set_bottom(bx_bearBreak, S5)
    else if not na(bx_bearBreak)
        box.delete(bx_bearBreak)
        bx_bearBreak := na
 
 
// ============================================================================
// SECTION 5: REAL-TIME REVERSAL & BREAKOUT SIGNALS
// ============================================================================
 
// 1. Mean Reversion Long: Price probed S3 support and closed back above S3 with a bullish candle
bool sigS3Buy = enableReversalSigs and showR3S3 and not isNewPeriod and (low <= S3) and (close > S3) and (close > open)
 
// 2. Mean Reversion Short: Price probed R3 resistance and closed back below R3 with a bearish candle
bool sigR3Sell = enableReversalSigs and showR3S3 and not isNewPeriod and (high >= R3) and (close < R3) and (close < open)
 
// 3. Bullish Breakout: Price broke and closed above R4 (Institutional Trend Expansion)
// Requires: Bullish candle body cleanly closing above R4 zone on a genuine breakout (not an artificial step jump)
bool r4Breakout = not isNewPeriod and (close > R4) and (close > open) and (close[1] <= R4 or open <= R4)
bool sigR4BreakBuy = enableBreakoutSigs and showR4S4 and r4Breakout
 
// 4. Bearish Breakdown: Price broke and closed below S4 (Institutional Trend Expansion)
// Requires: Bearish candle body cleanly closing below S4 zone on a genuine breakdown (not an artificial step jump)
bool s4Breakdown = not isNewPeriod and (close < S4) and (close < open) and (close[1] >= S4 or open >= S4)
bool sigS4BreakSell = enableBreakoutSigs and showR4S4 and s4Breakdown
 
plotshape(showSignals and sigS3Buy, title = "S3 Reversal Buy", style = shape.triangleup, location = location.belowbar,
     color = #00e676, size = size.small, text = "S3 BUY", textcolor = color.white)
 
plotshape(showSignals and sigR3Sell, title = "R3 Reversal Sell", style = shape.triangledown, location = location.abovebar,
     color = #ff1744, size = size.small, text = "R3 SELL", textcolor = color.white)
 
plotshape(showSignals and sigR4BreakBuy, title = "R4 Breakout Buy", style = shape.arrowup, location = location.belowbar,
     color = #00b0ff, size = size.small, text = "R4 BREAK", textcolor = color.white)
 
plotshape(showSignals and sigS4BreakSell, title = "S4 Breakdown Sell", style = shape.arrowdown, location = location.abovebar,
     color = #ff9100, size = size.small, text = "S4 BREAK", textcolor = color.white)
 
 
// ============================================================================
// SECTION 6: TRADINGVIEW ALERT CONDITIONS
// ============================================================================
 
alertcondition(sigS3Buy, "Camarilla: S3 Bullish Reversal", "Camarilla S3 Bullish Reversal on {{ticker}} at {{close}}")
alertcondition(sigR3Sell, "Camarilla: R3 Bearish Reversal", "Camarilla R3 Bearish Reversal on {{ticker}} at {{close}}")
alertcondition(sigR4BreakBuy, "Camarilla: R4 Bullish Breakout", "Camarilla R4 Bullish Breakout on {{ticker}} at {{close}}")
alertcondition(sigS4BreakSell, "Camarilla: S4 Bearish Breakdown", "Camarilla S4 Bearish Breakdown on {{ticker}} at {{close}}")

← 返回列表