Momentum Candle Entry Planner - By 1Prsnproject

Onepersonproject · study · 1201 行 · 点赞 77 · TradingView 原页

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

Pine Script

//@version=6
// =====================================================
// MOMENTUM CANDLE ENTRY PLANNER — By 1Prsnprojct
// =====================================================
//
// ORIGINAL MOMENTUM CANDLE
// Author: Rizki Aditama / Sekolah Trading.
//
// Permission to modify and share for free was obtained
// from the original author, on the condition that the
// indicator must not be sold.
// Preserve all applicable original license notices.
//
// SUPPORT & RESISTANCE COMPONENT
// Adapted from Support & Resistance Dynamic [LuxAlgo].
// Original SNR code © LuxAlgo.
// License: CC BY-NC-SA 4.0
// https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// Original SNR calculation retained.
// Integration changes: Pine v6 compatibility,
// guarded array access, bounded records,
// normalized box coordinates, visibility controls.
//
// MODIFICATIONS AND INTEGRATION
// By 1Prsnproject.
//
// This version operates on XAUUSD/GOLD, M5 only.
// Pair selection and other momentum timeframes removed.
// Settings, tooltips, panels, and alerts use English.
//
// SNR and session boxes are visual context only.
// This indicator does not place or manage orders.
// Lot estimates use fixed gold contract assumptions.
// PREPARE signals can disappear before candle close.
// The EMA filter may use an unfinished HTF value.
//
// Not compiled or tested directly in Pine Editor.
// No guarantee of profitability or publication approval.
// =====================================================
 
indicator("Momentum Candle Entry Planner - By 1Prsnproject",
     overlay=true,
     max_lines_count=500,
     max_boxes_count=500)
 
// =====================================================
// 1. MOMENTUM SETTINGS
// =====================================================
grpMomentum = "Momentum Settings"
 
candleMode = input.string(
     "Aggressive",
     "Candle Mode",
     options=["Aggressive", "Conservative"],
     group=grpMomentum,
     display=display.none,
     tooltip="Aggressive: minimum body size and wick-ratio checks.\nConservative: also applies a directional wick comparison.")
 
alertMode = input.string(
     "Aggressive",
     "Early Alert Mode",
     options=["Aggressive", "Conservative"],
     group=grpMomentum,
     display=display.none,
     tooltip="Aggressive: when momentum conditions are met.\nConservative: 20–90 seconds before candle close.\nFinal setup levels always require candle-close confirmation.")
 
showPrepare = input.bool(
     true,
     "Show PREPARE During the Final Minute",
     group=grpMomentum,
     display=display.none,
     tooltip="Realtime only; requires incoming price updates.\nAppears during the final 60 seconds when momentum conditions are met.\nThe signal can disappear before candle close.")
 
// =====================================================
// 2. ENTRY SETTINGS
// =====================================================
grpEntry = "Entry Settings"
 
entryMode = input.string(
     "Fibonacci 0.236",
     "Entry Mode",
     options=["Fibonacci 0.236", "Fibonacci 0.382", "Direct Entry"],
     group=grpEntry,
     display=display.none)
 
target382 = input.string(
     "Show Both Targets",
     "Fibonacci 0.382 Targets",
     options=["TP1 - Fibonacci 0", "TP2 - Fibonacci -0.27", "Show Both Targets"],
     group=grpEntry,
     display=display.none,
     tooltip="Applies only to Fibonacci 0.382.\nEntry: 0.382. Stop-loss: 0.745.\nTP1: Fibonacci 0, gray.\nTP2: Fibonacci -0.27, green.\nApproximate reward-to-risk ratios before costs: 1.05 and 1.80.")
 
bool isEntry236 = entryMode == "Fibonacci 0.236"
bool isEntry382 = entryMode == "Fibonacci 0.382"
bool isEntryDirect = entryMode == "Direct Entry"
 
bool show382TP1 = target382 != "TP2 - Fibonacci -0.27"
bool show382TP2 = target382 != "TP1 - Fibonacci 0"
 
float DIRECT_SL_PIPS = 35.0
float DIRECT_TP_PIPS = 35.0
 
// =====================================================
// 3. XAUUSD M5 MOMENTUM THRESHOLDS
// =====================================================
grpThreshold = "XAUUSD M5 - Momentum Thresholds"
 
minBodyPips = input.float(
     65.0,
     "Minimum Candle Body (Pips)",
     minval=1.0,
     step=1.0,
     group=grpThreshold,
     display=display.none,
     tooltip="Momentum signals are available only on XAUUSD/GOLD M5.\nOne pip is defined as a price movement of 0.10.\n65 pips therefore equals a price movement of 6.50.")
 
wickPct = input.float(
     30.0,
     "Maximum Combined Wicks (% of Candle Range)",
     minval=1,
     maxval=99,
     step=1,
     group=grpThreshold,
     display=display.none,
     tooltip="Upper wick plus lower wick, divided by the full high-to-low candle range.")
 
// =====================================================
// 4. CONSOLIDATION CHECK
// =====================================================
grpConsolidation = "Consolidation Check"
 
useConsolidation = input.bool(
     false,
     "Enable Previous-Body Check",
     group=grpConsolidation,
     display=display.none,
     tooltip="Each selected preceding candle must have a smaller body than the current candle.\nThis is a body-size comparison, not a complete range-compression detector.")
 
consolidationCount = input.int(
     3,
     "Number of Previous Candles",
     minval=1,
     maxval=10,
     group=grpConsolidation,
     display=display.none)
 
// =====================================================
// 5. EMA FILTER
// =====================================================
// The chart and momentum timeframe remain M5.
// This input changes only the EMA filter's data timeframe.
grpEMA = "EMA Trend Filter"
 
useEMA = input.bool(
     true,
     "Enable EMA Trend Filter",
     group=grpEMA,
     display=display.none,
     tooltip="Buy signals require price above the selected EMA.\nSell signals require price below it.\nThis filter is separate from the H1 trend panel.")
 
emaTF = input.string(
     "H1",
     "EMA Calculation Timeframe",
     options=["M5", "M15", "M30", "H1"],
     group=grpEMA,
     display=display.none,
     tooltip="Changes only the EMA calculation timeframe.\nMomentum signals still require an M5 chart.\nAn unfinished higher-timeframe EMA can change.")
 
emaLength = input.int(
     50,
     "EMA Period",
     minval=1,
     group=grpEMA,
     display=display.none)
 
// =====================================================
// 6. RISK AND LOT SETTINGS
// =====================================================
grpRisk = "Risk and Lot Size - XAUUSD / GOLD"
 
riskUSD = input.float(
     50.0,
     "Primary Entry Risk Budget (USD)",
     minval=0.01,
     step=1.0,
     group=grpRisk,
     display=display.none,
     tooltip="The estimated lot size uses the primary entry-to-stop distance.\nExcludes transaction costs, slippage, and additional-entry exposure.\nNo upper input limit.")
 
lotMin = input.float(
     0.01,
     "Minimum Lot Size",
     minval=0.000001,
     step=0.01,
     group=grpRisk,
     display=display.none,
     tooltip="If the risk-based estimate is below this minimum, the panel displays '< Min lot'.\nThe script does not increase the estimate to force a trade.")
 
lotMax = input.float(
     0.20,
     "Maximum Lot Size",
     minval=0.000001,
     step=0.01,
     group=grpRisk,
     display=display.none,
     tooltip="Enter your own maximum lot size.\nFor example, 0.2 limits the estimate to 0.2 lots.\nNo upper input limit.\nMust be greater than or equal to the minimum lot size.")
 
float LOT_STEP = 0.01
int KEEP_SETUPS = 3
 
// Fixed assumptions; not automatically retrieved from a broker.
float GOLD_TICK_SIZE = 0.01
float GOLD_TICK_VALUE = 1.0
float GOLD_PIP_SIZE = 0.10
 
// =====================================================
// 7. SESSION SETTINGS
// =====================================================
grpSession = "Trading Sessions - WIB (UTC+7)"
 
useTokyo = input.bool(
     true,
     "Show Tokyo Session",
     group=grpSession,
     display=display.none)
 
tokyoSession = input.session(
     "0700-1000",
     "Tokyo Session Hours (WIB)",
     group=grpSession,
     display=display.none)
 
useNewYork = input.bool(
     true,
     "Show New York Session",
     group=grpSession,
     display=display.none)
 
newYorkSession = input.session(
     "1900-2200",
     "New York Session Hours (WIB)",
     group=grpSession,
     display=display.none)
 
string SESSION_TZ = "Asia/Jakarta"
 
// =====================================================
// 8. DISPLAY SETTINGS
// =====================================================
grpDisplay = "Display Settings"
 
displayMode = input.string(
     "Phone",
     "Display Mode",
     options=["Phone", "Laptop"],
     group=grpDisplay,
     display=display.none)
 
showH1Trend = input.bool(
     true,
     "Show H1 Trend",
     group=grpDisplay,
     display=display.none,
     tooltip="Compares the previous completed H1 close with its EMA 50.\nDisplay only; does not filter entry signals.")
 
bool phoneMode = displayMode == "Phone"
 
float PANEL_WIDTH = phoneMode ? 42.0 : 14.0
float PANEL_ROW_HEIGHT = phoneMode ? 2.8 : 3.8
 
color lightBlue = color.rgb(100, 190, 255)
color transparentBg = color.new(color.black, 100)
color panelBg = color.rgb(22, 27, 35)
 
// =====================================================
// 9. DYNAMIC SNR SETTINGS
// =====================================================
grpSNR = "Dynamic Support and Resistance"
 
snrEnabled = input.bool(
     true,
     "Show Support and Resistance",
     group=grpSNR,
     display=display.none,
     tooltip="Adapted from Support & Resistance Dynamic by LuxAlgo.\nProvides visual context only; does not filter momentum signals.")
 
snrMultiplier = input.float(
     8.0,
     "Multiplicative Factor",
     minval=0.1,
     step=0.5,
     group=grpSNR,
     display=display.none)
 
snrATRLength = input.int(
     50,
     "ATR Length",
     minval=1,
     group=grpSNR,
     display=display.none)
 
snrExtendLast = input.int(
     4,
     "Number of Recent Levels to Extend",
     minval=0,
     maxval=100,
     group=grpSNR,
     display=display.none,
     tooltip="Controls additional extended levels and areas.\nSetting this to zero does not hide the historical SNR plots.")
 
grpSNRStyle = "Support and Resistance Style"
 
snrSupportColor = input.color(
     #089981,
     "Support",
     inline="sup",
     group=grpSNRStyle,
     display=display.none)
 
snrSupportAreaColor = input.color(
     color.new(#089981, 80),
     "Area",
     inline="sup",
     group=grpSNRStyle,
     display=display.none)
 
snrResistanceColor = input.color(
     #f23645,
     "Resistance",
     inline="res",
     group=grpSNRStyle,
     display=display.none)
 
snrResistanceAreaColor = input.color(
     color.new(#f23645, 80),
     "Area",
     inline="res",
     group=grpSNRStyle,
     display=display.none)
 
snrExtendLevels = input.bool(
     true,
     "Extend Levels",
     group=grpSNRStyle,
     display=display.none)
 
snrExtendAreas = input.bool(
     true,
     "Extend Areas",
     group=grpSNRStyle,
     display=display.none)
 
// =====================================================
// 10. SYMBOL AND TIMEFRAME RESTRICTION
// =====================================================
string tickerUpper = str.upper(syminfo.ticker)
 
bool isGoldSymbol = str.contains(tickerUpper, "XAUUSD") or
     str.startswith(tickerUpper, "GOLD")
 
bool isM5 = timeframe.isminutes and timeframe.multiplier == 5
 
bool supportedChart = isGoldSymbol and isM5
 
float minimumBodyPrice = minBodyPips * GOLD_PIP_SIZE
 
// =====================================================
// 11. MOMENTUM VALIDATION
// =====================================================
float bodySize = math.abs(close - open)
float candleRange = high - low
 
float upperWick = high - math.max(open, close)
float lowerWick = math.min(open, close) - low
float combinedWicks = upperWick + lowerWick
 
bool isBigCandle = supportedChart and
     bodySize >= minimumBodyPrice
 
bool isWickValid = supportedChart and candleRange > 0 and
     combinedWicks / candleRange <= wickPct / 100.0
 
bool bullishAggressive = isBigCandle and isWickValid and close > open
bool bearishAggressive = isBigCandle and isWickValid and close < open
 
bool bullishConservative = bullishAggressive and lowerWick < upperWick
bool bearishConservative = bearishAggressive and upperWick < lowerWick
 
bool bullishSignal = candleMode == "Aggressive" ?
     bullishAggressive : bullishConservative
 
bool bearishSignal = candleMode == "Aggressive" ?
     bearishAggressive : bearishConservative
 
// =====================================================
// 12. PREVIOUS-BODY CHECK
// =====================================================
bool consolidationValid = true
 
if useConsolidation
    for i = 1 to consolidationCount
        float previousBody = math.abs(close[i] - open[i])
 
        if na(previousBody) or previousBody >= bodySize
            consolidationValid := false
 
bullishSignal := bullishSignal and consolidationValid
bearishSignal := bearishSignal and consolidationValid
 
// =====================================================
// 13. EMA FILTER
// =====================================================
string emaTFString = emaTF == "M5" ? "5" :
     emaTF == "M15" ? "15" :
     emaTF == "M30" ? "30" : "60"
 
// Existing filter behavior retained.
// Unfinished HTF EMA values can change.
// Historical signals may differ after reloading.
float emaValue = request.security(
     syminfo.tickerid,
     emaTFString,
     ta.ema(close, emaLength),
     lookahead=barmerge.lookahead_off)
 
if useEMA
    bullishSignal := bullishSignal and close > emaValue
    bearishSignal := bearishSignal and close < emaValue
 
// =====================================================
// 14. CONFIRMED H1 TREND — DISPLAY ONLY
// =====================================================
[h1CloseConfirmed, h1EMAConfirmed] = request.security(
     syminfo.tickerid,
     "60",
     [close[1], ta.ema(close, 50)[1]],
     lookahead=barmerge.lookahead_on)
 
bool h1Ready = supportedChart and
     not na(h1CloseConfirmed) and
     not na(h1EMAConfirmed)
 
bool h1Bullish = h1Ready and h1CloseConfirmed > h1EMAConfirmed
bool h1Bearish = h1Ready and h1CloseConfirmed < h1EMAConfirmed
 
string h1Text = not h1Ready ? "H1: Waiting for data" :
     h1Bullish ? "H1  ↑ BULLISH" :
     h1Bearish ? "H1  ↓ BEARISH" : "H1  → NEUTRAL"
 
color h1Color = h1Bullish ? color.lime :
     h1Bearish ? color.red : color.silver
 
// =====================================================
// 15. PREPARE — FINAL 60 SECONDS
// =====================================================
int barTimeLeft = time_close - timenow
 
bool prepareWindow = supportedChart and
     barstate.isrealtime and
     not barstate.isconfirmed and
     not na(time_close) and
     barTimeLeft > 0 and
     barTimeLeft <= 60000
 
bool prepareBuy = showPrepare and prepareWindow and bullishSignal
bool prepareSell = showPrepare and prepareWindow and bearishSignal
 
plotshape(
     prepareBuy,
     title="PREPARE BUY",
     location=location.belowbar,
     style=shape.labelup,
     color=color.orange,
     text="PREPARE\nBUY",
     textcolor=color.black,
     size=size.tiny)
 
plotshape(
     prepareSell,
     title="PREPARE SELL",
     location=location.abovebar,
     style=shape.labeldown,
     color=color.orange,
     text="PREPARE\nSELL",
     textcolor=color.black,
     size=size.tiny)
 
alertcondition(
     prepareBuy,
     title="PREPARE BUY - Final Minute",
     message="XAUUSD M5: provisional bullish momentum during the final minute. Wait for candle-close confirmation.")
 
alertcondition(
     prepareSell,
     title="PREPARE SELL - Final Minute",
     message="XAUUSD M5: provisional bearish momentum during the final minute. Wait for candle-close confirmation.")
 
// =====================================================
// 16. EARLY MOMENTUM ALERTS
// =====================================================
bool earlyAlertWindow = supportedChart and
     barstate.isrealtime and
     not na(time_close) and
     barTimeLeft <= 90000 and
     barTimeLeft >= 20000
 
bool aggressiveAlerts = alertMode == "Aggressive"
 
bool validBullishAlert = aggressiveAlerts ? bullishSignal :
     bullishSignal and earlyAlertWindow and not barstate.isconfirmed
 
bool validBearishAlert = aggressiveAlerts ? bearishSignal :
     bearishSignal and earlyAlertWindow and not barstate.isconfirmed
 
alertcondition(
     validBullishAlert and aggressiveAlerts,
     title="Bullish Momentum - Aggressive",
     message="XAUUSD M5: bullish momentum detected. Wait for candle close before using the final setup.")
 
alertcondition(
     validBearishAlert and aggressiveAlerts,
     title="Bearish Momentum - Aggressive",
     message="XAUUSD M5: bearish momentum detected. Wait for candle close before using the final setup.")
 
alertcondition(
     validBullishAlert and not aggressiveAlerts,
     title="Bullish Momentum - Conservative",
     message="XAUUSD M5: bullish momentum detected 20–90 seconds before close. The setup is not final.")
 
alertcondition(
     validBearishAlert and not aggressiveAlerts,
     title="Bearish Momentum - Conservative",
     message="XAUUSD M5: bearish momentum detected 20–90 seconds before close. The setup is not final.")
 
// =====================================================
// 17. CONFIRMED MOMENTUM SIGNALS
// =====================================================
bool confirmedBuy = bullishSignal and barstate.isconfirmed
bool confirmedSell = bearishSignal and barstate.isconfirmed
 
plotshape(
     confirmedBuy,
     title="Confirmed Bullish Momentum",
     location=location.belowbar,
     style=shape.triangleup,
     color=color.blue,
     size=size.small)
 
plotshape(
     confirmedSell,
     title="Confirmed Bearish Momentum",
     location=location.abovebar,
     style=shape.triangledown,
     color=color.red,
     size=size.small)
 
// =====================================================
// 18. SESSION BOXES — VISUAL CONTEXT ONLY
// =====================================================
sessionKey(string sessionString) =>
    int startHour = int(
         str.tonumber(str.substring(sessionString, 0, 2)))
 
    int startMinute = int(
         str.tonumber(str.substring(sessionString, 2, 4)))
 
    int shiftedTime = time -
         (startHour * 60 + startMinute) * 60000
 
    year(shiftedTime, SESSION_TZ) * 10000 +
     month(shiftedTime, SESSION_TZ) * 100 +
     dayofmonth(shiftedTime, SESSION_TZ)
 
bool tokyoActive = supportedChart and useTokyo and
     not na(time(timeframe.period, tokyoSession, SESSION_TZ))
 
bool newYorkActive = supportedChart and useNewYork and
     not na(time(timeframe.period, newYorkSession, SESSION_TZ))
 
int tokyoKey = sessionKey(tokyoSession)
int newYorkKey = sessionKey(newYorkSession)
 
bool newTokyoDay = ta.change(tokyoKey) != 0
bool newNewYorkDay = ta.change(newYorkKey) != 0
 
int tokyoSessionClose = time_close(
     timeframe.period, tokyoSession, SESSION_TZ)
 
int newYorkSessionClose = time_close(
     timeframe.period, newYorkSession, SESSION_TZ)
 
int sessionBarRight = na(time_close) ? time : time_close
 
int tokyoRight = na(tokyoSessionClose) ? sessionBarRight :
     math.min(sessionBarRight, tokyoSessionClose)
 
int newYorkRight = na(newYorkSessionClose) ? sessionBarRight :
     math.min(sessionBarRight, newYorkSessionClose)
 
var box tokyoBox = na
var box newYorkBox = na
var array<box> sessionBoxes = array.new<box>()
 
if tokyoActive
    if not tokyoActive[1] or newTokyoDay or na(tokyoBox)
        if array.size(sessionBoxes) >= 180
            box.delete(array.shift(sessionBoxes))
 
        tokyoBox := box.new(
             left=time,
             top=high,
             right=tokyoRight,
             bottom=low,
             xloc=xloc.bar_time,
             border_color=color.orange,
             border_style=line.style_dashed,
             bgcolor=na)
 
        array.push(sessionBoxes, tokyoBox)
    else
        box.set_top(
             tokyoBox, math.max(box.get_top(tokyoBox), high))
 
        box.set_bottom(
             tokyoBox, math.min(box.get_bottom(tokyoBox), low))
 
        box.set_right(tokyoBox, tokyoRight)
 
if newYorkActive
    if not newYorkActive[1] or newNewYorkDay or na(newYorkBox)
        if array.size(sessionBoxes) >= 180
            box.delete(array.shift(sessionBoxes))
 
        newYorkBox := box.new(
             left=time,
             top=high,
             right=newYorkRight,
             bottom=low,
             xloc=xloc.bar_time,
             border_color=lightBlue,
             border_style=line.style_dashed,
             bgcolor=na)
 
        array.push(sessionBoxes, newYorkBox)
    else
        box.set_top(
             newYorkBox, math.max(box.get_top(newYorkBox), high))
 
        box.set_bottom(
             newYorkBox, math.min(box.get_bottom(newYorkBox), low))
 
        box.set_right(newYorkBox, newYorkRight)
 
// =====================================================
// 19. ENTRY PLANS — THREE MOST RECENT SETUPS
// =====================================================
// BUY: Fibonacci 0 = high; Fibonacci 1 = low.
// SELL: Fibonacci 0 = low; Fibonacci 1 = high.
// Full candle range includes wicks.
//
// 0.236: entry 0.236, additional entry 0.618,
// SL 0.745, TP -0.27.
//
// 0.382: entry 0.382, SL 0.745,
// TP1 0, TP2 -0.27.
//
// Direct: reference entry at the confirmed candle close,
// SL 35 pips, TP 35 pips.
//
// Drawings are not orders.
// Three-bar line length is not an order-expiration rule.
 
var float setupEntry = na
var float setupAdditionalEntry = na
var float setupSL = na
var float setupTP1 = na
var float setupTP2 = na
var int setupBar = na
 
var array<line> setupLines = array.new<line>()
var array<int> setupLineCounts = array.new<int>()
 
roundPrice(float value) =>
    math.round(value / GOLD_TICK_SIZE) * GOLD_TICK_SIZE
 
drawSetupLine(float level, color lineColor, string lineStyle) =>
    line.new(
         x1=bar_index,
         y1=level,
         x2=bar_index + 3,
         y2=level,
         xloc=xloc.bar_index,
         extend=extend.none,
         color=lineColor,
         style=lineStyle,
         width=2)
 
bool newBuySetup = false
bool newSellSetup = false
 
if confirmedBuy or confirmedSell
    float direction = confirmedBuy ? 1.0 : -1.0
 
    float fibZero = confirmedBuy ? high : low
    float fibOne = confirmedBuy ? low : high
    float fibSpan = fibOne - fibZero
 
    float candidateEntry = na
    float candidateAdditionalEntry = na
    float candidateSL = na
    float candidateTP1 = na
    float candidateTP2 = na
 
    if isEntryDirect
        candidateEntry := roundPrice(close)
 
        candidateSL := roundPrice(
             candidateEntry -
             direction * DIRECT_SL_PIPS * GOLD_PIP_SIZE)
 
        candidateTP1 := roundPrice(
             candidateEntry +
             direction * DIRECT_TP_PIPS * GOLD_PIP_SIZE)
    else
        float entryLevel = isEntry236 ? 0.236 : 0.382
 
        candidateEntry := roundPrice(
             fibZero + fibSpan * entryLevel)
 
        candidateSL := roundPrice(
             fibZero + fibSpan * 0.745)
 
        if isEntry236
            candidateAdditionalEntry := roundPrice(
                 fibZero + fibSpan * 0.618)
 
            candidateTP1 := roundPrice(
                 fibZero + fibSpan * -0.27)
        else
            if show382TP1
                candidateTP1 := roundPrice(fibZero)
 
            if show382TP2
                candidateTP2 := roundPrice(
                     fibZero + fibSpan * -0.27)
 
    bool validGeometry = not na(candidateEntry) and
         not na(candidateSL) and
         direction * (candidateEntry - candidateSL) > 0
 
    if not na(candidateTP1)
        validGeometry := validGeometry and
             direction * (candidateTP1 - candidateEntry) > 0
 
    if not na(candidateTP2)
        validGeometry := validGeometry and
             direction * (candidateTP2 - candidateEntry) > 0
 
    if not na(candidateAdditionalEntry)
        validGeometry := validGeometry and
             direction * (candidateAdditionalEntry - candidateSL) > 0 and
             direction * (candidateEntry - candidateAdditionalEntry) > 0
 
    if validGeometry
        setupEntry := candidateEntry
        setupAdditionalEntry := candidateAdditionalEntry
        setupSL := candidateSL
        setupTP1 := candidateTP1
        setupTP2 := candidateTP2
        setupBar := bar_index
 
        newBuySetup := confirmedBuy
        newSellSetup := confirmedSell
 
        while array.size(setupLineCounts) >= KEEP_SETUPS
            int oldLineCount = array.shift(setupLineCounts)
 
            if oldLineCount > 0
                for i = 0 to oldLineCount - 1
                    line.delete(array.shift(setupLines))
 
        int newLineCount = 0
 
        array.push(
             setupLines,
             drawSetupLine(
                 setupSL, color.red, line.style_dotted))
        newLineCount += 1
 
        array.push(
             setupLines,
             drawSetupLine(
                 setupEntry, color.yellow, line.style_dotted))
        newLineCount += 1
 
        if not na(setupAdditionalEntry)
            array.push(
                 setupLines,
                 drawSetupLine(
                     setupAdditionalEntry,
                     lightBlue,
                     line.style_dashed))
            newLineCount += 1
 
        if not na(setupTP1)
            color tp1Color = isEntry382 ? color.silver : color.lime
 
            array.push(
                 setupLines,
                 drawSetupLine(
                     setupTP1, tp1Color, line.style_dotted))
            newLineCount += 1
 
        if not na(setupTP2)
            array.push(
                 setupLines,
                 drawSetupLine(
                     setupTP2, color.lime, line.style_dotted))
            newLineCount += 1
 
        array.push(setupLineCounts, newLineCount)
 
// =====================================================
// 20. PRIMARY-ENTRY LOT ESTIMATE
// =====================================================
// Uses the most recent setup, not an actual broker position.
// The displayed risk amount is the input budget.
// Additional-entry exposure is not included.
// Does not enforce funded-account rules.
 
float slDistance = math.abs(setupEntry - setupSL)
 
float slTicks = supportedChart and not na(slDistance) ?
     math.round(slDistance / GOLD_TICK_SIZE) : na
 
float lossPerLot = not na(slTicks) and slTicks > 0 ?
     slTicks * GOLD_TICK_VALUE : na
 
float rawLot = not na(lossPerLot) and lossPerLot > 0 ?
     riskUSD / lossPerLot : na
 
bool lotSettingsValid = lotMin > 0 and
     LOT_STEP > 0 and
     lotMax >= lotMin
 
float recommendedLot = na
 
if lotSettingsValid and not na(rawLot) and rawLot >= lotMin
    float cappedLot = math.min(rawLot, lotMax)
 
    float steps = math.floor(
         (cappedLot - lotMin) / LOT_STEP + 1e-9)
 
    float candidateLot = lotMin + steps * LOT_STEP
    float tolerance = LOT_STEP * 1e-8
 
    if candidateLot > cappedLot + tolerance
        candidateLot -= LOT_STEP
 
    if candidateLot >= lotMin - tolerance
        recommendedLot := math.min(candidateLot, cappedLot)
 
// =====================================================
// 21. DYNAMIC SNR CALCULATION — ADAPTED FROM LUXALGO
// =====================================================
// Original SNR code © LuxAlgo.
// CC BY-NC-SA 4.0.
// Original calculation retained.
// Realtime values can change before candle close.
 
type SnrRecord
    float level
    float area
    int startTime
    bool support
 
var array<SnrRecord> snrRecords = array.new<SnrRecord>()
 
var float snrAverage = close
var float snrHeldATR = 0.0
var int snrDirection = 0
 
bool showSNR = supportedChart and snrEnabled
 
float snrBreakoutATR = nz(ta.atr(snrATRLength)) * snrMultiplier
 
snrAverage := math.abs(close - snrAverage) > snrBreakoutATR ?
     close : snrAverage
 
snrHeldATR := snrAverage == close ?
     snrBreakoutATR : snrHeldATR
 
snrDirection := snrAverage > snrAverage[1] ? 1 :
     snrAverage < snrAverage[1] ? 0 : snrDirection
 
float snrUpperResistance = snrDirection == 0 ?
     snrAverage + snrHeldATR / snrMultiplier : na
 
float snrLowerResistance = snrDirection == 0 ?
     snrAverage + snrHeldATR / snrMultiplier / 2.0 : na
 
float snrUpperSupport = snrDirection == 1 ?
     snrAverage - snrHeldATR / snrMultiplier / 2.0 : na
 
float snrLowerSupport = snrDirection == 1 ?
     snrAverage - snrHeldATR / snrMultiplier : na
 
if showSNR and snrExtendLast > 0 and close == snrAverage
    if snrDirection == 1
        array.unshift(
             snrRecords,
             SnrRecord.new(
                 snrLowerSupport,
                 snrUpperSupport,
                 time,
                 true))
    else
        array.unshift(
             snrRecords,
             SnrRecord.new(
                 snrUpperResistance,
                 snrLowerResistance,
                 time,
                 false))
 
    while array.size(snrRecords) > snrExtendLast
        array.pop(snrRecords)
 
// =====================================================
// 22. EXTENDED SNR LEVELS AND AREAS
// =====================================================
var array<line> snrLines = array.new<line>()
var array<box> snrBoxes = array.new<box>()
 
if barstate.isfirst and showSNR and snrExtendLast > 0
    for i = 0 to snrExtendLast - 1
        if snrExtendLevels
            array.push(
                 snrLines,
                 line.new(
                     x1=time,
                     y1=close,
                     x2=time,
                     y2=close,
                     xloc=xloc.bar_time,
                     color=na,
                     style=line.style_dashed))
 
        if snrExtendAreas
            array.push(
                 snrBoxes,
                 box.new(
                     left=time,
                     top=close,
                     right=time,
                     bottom=close,
                     xloc=xloc.bar_time,
                     border_color=na,
                     bgcolor=na))
 
if barstate.islast and showSNR and snrExtendLast > 0
    int snrCount = math.min(
         snrExtendLast, array.size(snrRecords))
 
    if snrCount > 0
        for i = 0 to snrCount - 1
            SnrRecord currentSR = array.get(snrRecords, i)
 
            if snrExtendLevels and i < array.size(snrLines)
                line currentLine = array.get(snrLines, i)
 
                line.set_xy1(
                     currentLine,
                     currentSR.startTime,
                     currentSR.level)
 
                line.set_xy2(
                     currentLine,
                     time,
                     currentSR.level)
 
                line.set_color(
                     currentLine,
                     currentSR.support ?
                     snrSupportColor : snrResistanceColor)
 
            if snrExtendAreas and i < array.size(snrBoxes)
                box currentBox = array.get(snrBoxes, i)
 
                float zoneTop = math.max(
                     currentSR.area, currentSR.level)
 
                float zoneBottom = math.min(
                     currentSR.area, currentSR.level)
 
                box.set_lefttop(
                     currentBox,
                     currentSR.startTime,
                     zoneTop)
 
                box.set_rightbottom(
                     currentBox,
                     time,
                     zoneBottom)
 
                box.set_bgcolor(
                     currentBox,
                     currentSR.support ?
                     snrSupportAreaColor : snrResistanceAreaColor)
 
// =====================================================
// 23. HISTORICAL SNR PLOTS
// =====================================================
snrPlotUpperSupport = plot(
     showSNR ? snrUpperSupport : na,
     title="SNR Upper Support",
     color=na,
     style=plot.style_linebr)
 
snrPlotLowerSupport = plot(
     showSNR ? snrLowerSupport : na,
     title="SNR Lower Support",
     color=close == snrAverage ? na : snrSupportColor,
     style=plot.style_linebr)
 
snrPlotUpperResistance = plot(
     showSNR ? snrUpperResistance : na,
     title="SNR Upper Resistance",
     color=close == snrAverage ? na : snrResistanceColor,
     style=plot.style_linebr)
 
snrPlotLowerResistance = plot(
     showSNR ? snrLowerResistance : na,
     title="SNR Lower Resistance",
     color=na,
     style=plot.style_linebr)
 
fill(
     snrPlotUpperSupport,
     snrPlotLowerSupport,
     color=showSNR ? snrSupportAreaColor : na,
     title="SNR Support Area")
 
fill(
     snrPlotUpperResistance,
     snrPlotLowerResistance,
     color=showSNR ? snrResistanceAreaColor : na,
     title="SNR Resistance Area")
 
// =====================================================
// 24. CREDITS, STATUS, AND H1 TREND — TOP RIGHT
// =====================================================
var table infoTable = table.new(
     position.top_right,
     1,
     2,
     bgcolor=transparentBg,
     frame_color=transparentBg,
     frame_width=0,
     border_color=transparentBg,
     border_width=0)
 
if barstate.islast
    table.cell(
         infoTable,
         0,
         0,
         "Momentum Candle\nRizki Aditama / Sekolah Trading\nModified by 1Prsnproject\nSNR adapted from LuxAlgo",
         width=PANEL_WIDTH,
         bgcolor=panelBg,
         text_color=color.white,
         text_size=size.tiny,
         text_halign=text.align_center,
         text_valign=text.align_center)
 
    string statusText = not supportedChart ?
         "Use XAUUSD / GOLD on M5" :
         showH1Trend ? h1Text : ""
 
    color statusColor = not supportedChart ?
         color.orange : h1Color
 
    bool showStatus = not supportedChart or showH1Trend
 
    table.cell(
         infoTable,
         0,
         1,
         statusText,
         width=PANEL_WIDTH,
         bgcolor=showStatus ? panelBg : transparentBg,
         text_color=statusColor,
         text_size=size.small,
         text_halign=text.align_center,
         text_valign=text.align_center)
 
// =====================================================
// 25. RISK AND LOT PANEL — BOTTOM RIGHT
// =====================================================
var table lotTable = table.new(
     position.bottom_right,
     2,
     2,
     bgcolor=panelBg,
     frame_color=transparentBg,
     frame_width=0,
     border_color=transparentBg,
     border_width=0)
 
if barstate.islast
    string lotText = not supportedChart ? "XAUUSD M5 only" :
         not lotSettingsValid ? "Check settings" :
         na(setupBar) ? "Waiting" :
         na(recommendedLot) ? "< Min lot" :
         str.tostring(recommendedLot, "0.00######")
 
    string lotLabel = isEntry236 ? "Lot 0.236" :
         isEntry382 ? "Lot 0.382" : "Direct lot"
 
    table.cell(
         lotTable,
         0,
         0,
         "Risk budget",
         width=PANEL_WIDTH / 2.0,
         height=PANEL_ROW_HEIGHT,
         bgcolor=panelBg,
         text_color=color.silver,
         text_size=size.tiny,
         text_halign=text.align_left)
 
    table.cell(
         lotTable,
         1,
         0,
         "$" + str.tostring(riskUSD, "0.00"),
         width=PANEL_WIDTH / 2.0,
         height=PANEL_ROW_HEIGHT,
         bgcolor=panelBg,
         text_color=color.orange,
         text_size=size.tiny,
         text_halign=text.align_right)
 
    table.cell(
         lotTable,
         0,
         1,
         lotLabel,
         width=PANEL_WIDTH / 2.0,
         height=PANEL_ROW_HEIGHT,
         bgcolor=panelBg,
         text_color=color.silver,
         text_size=size.tiny,
         text_halign=text.align_left)
 
    table.cell(
         lotTable,
         1,
         1,
         lotText,
         width=PANEL_WIDTH / 2.0,
         height=PANEL_ROW_HEIGHT,
         bgcolor=panelBg,
         text_color=lightBlue,
         text_size=size.tiny,
         text_halign=text.align_right)
 
// =====================================================
// 26. FINAL SETUP ALERTS
// =====================================================
alertcondition(
     newBuySetup and isEntry236,
     title="BUY Setup - Fibonacci 0.236",
     message="XAUUSD M5 BUY confirmed. Entry 0.236, additional entry 0.618, SL 0.745, TP -0.27. Lot estimate covers the primary entry only.")
 
alertcondition(
     newSellSetup and isEntry236,
     title="SELL Setup - Fibonacci 0.236",
     message="XAUUSD M5 SELL confirmed. Entry 0.236, additional entry 0.618, SL 0.745, TP -0.27. Lot estimate covers the primary entry only.")
 
alertcondition(
     newBuySetup and isEntry382,
     title="BUY Setup - Fibonacci 0.382",
     message="XAUUSD M5 BUY confirmed. Entry 0.382, SL 0.745. Targets follow the selected settings: TP1 at Fibonacci 0 and/or TP2 at Fibonacci -0.27.")
 
alertcondition(
     newSellSetup and isEntry382,
     title="SELL Setup - Fibonacci 0.382",
     message="XAUUSD M5 SELL confirmed. Entry 0.382, SL 0.745. Targets follow the selected settings: TP1 at Fibonacci 0 and/or TP2 at Fibonacci -0.27.")
 
alertcondition(
     newBuySetup and isEntryDirect,
     title="BUY Setup - Direct Entry",
     message="XAUUSD M5 BUY confirmed. Reference entry at momentum candle close. SL 35 pips and TP 35 pips.")
 
alertcondition(
     newSellSetup and isEntryDirect,
     title="SELL Setup - Direct Entry",
     message="XAUUSD M5 SELL confirmed. Reference entry at momentum candle close. SL 35 pips and TP 35 pips.")

← 返回列表