TradeBee Momentum Flow

tradesafe1 · study · 948 行 · 点赞 46 · TradingView 原页

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

Pine Script

//@version=6
indicator("TradeBee Momentum Flow", shorttitle="TBMFlow", overlay=true, max_lines_count=100, max_labels_count=100, max_bars_back=5000)
//=============================================================================
// TRADEBEE MOMENTUM FLOW — v1.27
// Recommended timeframe: 2 minutes (not enforced)
//=============================================================================
 
//-----------------------------------------------------------------------------
// 01. INPUT GROUPS
 
//-----------------------------------------------------------------------------
string G_SESSION = "01. Session Settings"
string G_SIGNAL  = "02. Setup Rules"
string G_VIS     = "03. Chart Visibility"
string G_DAILY   = "04. Daily High / Low"
string G_LEVELS  = "05. Entry / Stop / Target"
string G_TABLE   = "06. Dashboard"
string G_ROWS    = "07. Dashboard Rows"
 
//-----------------------------------------------------------------------------
// 02. SESSION SETTINGS
 
//-----------------------------------------------------------------------------
string sessionTimezone = input.string("America/New_York", "Session Time Zone", options=["America/New_York", "America/Chicago", "America/Los_Angeles"], group=G_SESSION, tooltip="Configure america/new_york for the indicator.")
string regularSession = input.session("0930-1600:23456", "Regular Trading Session", group=G_SESSION, tooltip="Configure 0930-1600:23456 for the indicator.")
string tradeWindow = input.session("1000-1330:23456", "Allowed Entry Window", group=G_SESSION, tooltip="Configure 1000-1330:23456 for the indicator.")
bool allowShorts = input.bool(true, "Enable Short Setups", group=G_SESSION, tooltip="Allow bearish recovery and EMA/VWAP cross-under entries.")
bool oneTradePerDay = input.bool(true, "Limit to One Trade Per Day", group=G_SESSION, tooltip="Prevent another entry after the first trade is triggered that day.")
bool allowReentryAfterChopExit = input.bool(true, "Allow Re-entry After Chop Exit", group=G_SESSION, tooltip="Allow a fresh setup after a confirmed CHOP EXIT even when Limit to One Trade Per Day is enabled. The separate daily re-entry limit below controls how many re-entries are allowed.")
int maxChopReentriesPerDay = input.int(1, "Maximum Re-entries After Chop Exit Per Day", minval=0, maxval=10, group=G_SESSION, tooltip="Maximum number of fresh entries allowed after a CHOP EXIT each day. Set to 0 to disable chop re-entry.")
bool allowTrendContinuationReentry = input.bool(true, "Allow Trend-Continuation Re-entry After Chop Exit", group=G_SESSION, tooltip="After a CHOP EXIT, permit a fresh directional pullback/rejection entry without requiring a new EMA/VWAP crossover: falling EMA with EMA below VWAP and a candle retesting the EMA then closing below it for shorts; mirrored for longs.")
bool allowTrendContinuationAfterStop = input.bool(true, "Allow Trend-Continuation Re-entry After Stop Hit", group=G_SESSION, tooltip="When enabled, allow a limited trend-continuation re-entry after a STOP HIT, for either LONG or SHORT. Requires EMA/VWAP trend alignment and a pullback/rejection candle within the allowed entry window.")
int maxStopReentriesPerDay = input.int(1, "Maximum Re-entries After Stop Hit Per Day", minval=0, maxval=10, group=G_SESSION, tooltip="Maximum number of trend-continuation re-entries allowed after STOP HIT each day. Set to 0 to disable stop-hit re-entry.")
bool allowEarlyMomentumAfterStop = input.bool(true, "Allow Early Momentum Re-entry After Stop Hit", group=G_SESSION, tooltip="Adds an earlier continuation entry after a stop hit when EMA/VWAP alignment and a confirmed directional close indicate momentum. Applies symmetrically to LONG and SHORT. The existing pullback/rejection path remains available.")
bool clearDashboardAtPremarket = input.bool(true, "Clear Dashboard at Premarket Start", group=G_SESSION, tooltip="When enabled, clear prior trade/setup information at 4:00 AM in the selected session time zone. When disabled, clear it at the regular-session open.")
 
//-----------------------------------------------------------------------------
// 03. SETUP RULES
 
//-----------------------------------------------------------------------------
int emaLength = input.int(9, "EMA9 Length", minval=1, group=G_SIGNAL, tooltip="Number of bars used to calculate the 9 EMA.")
float src9 = input.source(close, "EMA9 Source", group=G_SIGNAL, tooltip="Source series used to calculate the 9 EMA. The EMA movement-color conditions still compare against the chart candle close/open as defined.")
int recoveryLookback = input.int(3, "Recovery Lookback Bars", minval=1, maxval=10, group=G_SIGNAL, tooltip="Bars used to evaluate whether price is moving toward VWAP.")
int emaSlopeLookback = input.int(3, "EMA Slope Lookback", minval=1, maxval=10, group=G_SIGNAL, tooltip="Bars used to measure EMA direction and flatness.")
float flatThresholdTicks = input.float(2.0, "Flat EMA Threshold (ticks)", minval=0, step=0.5, group=G_SIGNAL, tooltip="EMA movement at or below this threshold is treated as flat.")
float chopZoneTicks = input.float(5.0, "VWAP Chop Zone Base (ticks)", minval=0, step=0.5, group=G_SIGNAL, tooltip="Used as the minimum fallback/base zone for VWAP chop detection; active-trade proximity is volatility-adaptive below.")
int recoveryExpiryBars = input.int(30, "Recovery Expiry (bars)", minval=3, maxval=200, group=G_SIGNAL, tooltip="Maximum bars a recovery setup remains valid before resetting.")
bool requireSignalCandleDirection = input.bool(false, "Require Signal Candle Direction", group=G_SIGNAL, tooltip="When enabled, arm a valid setup after the existing entry criteria are met, then wait for a confirmed candle closing in the trade direction. A doji confirms either side when the setup direction is already established.")
bool requireEMASlope = input.bool(false, "Require EMA Slope Confirmation", group=G_SIGNAL, tooltip="Require EMA slope to agree with the trade direction.")
bool requireVWAPSlope = input.bool(false, "Require VWAP Direction Confirmation", group=G_SIGNAL, tooltip="Require VWAP slope to agree with the trade direction.")
bool blockChoppyCross = input.bool(false, "Block Entries During VWAP Chop", group=G_SIGNAL, tooltip="Reject cross signals when VWAP conditions indicate chop.")
int chopCrossLookback = input.int(6, "VWAP Cross Lookback", minval=2, maxval=20, group=G_SIGNAL, tooltip="Number of recent bars checked for repeated price/VWAP crosses.")
int maxVWAPCrosses = input.int(3, "Crosses That Indicate Chop", minval=1, maxval=10, group=G_SIGNAL, tooltip="Cross count at or above this value is treated as repeated-cross chop.")
bool exitOnChop = input.bool(true, "Exit Active Trade on Confirmed Chop", group=G_SIGNAL, tooltip="Exit an active trade when repeated 9 EMA interactions occur within the rolling time window and the EMA is flat or price repeatedly crosses the EMA/VWAP.")
int chopWindowMinutes = input.int(10, "Chop Detection Window (minutes)", minval=2, maxval=60, group=G_SIGNAL, tooltip="Rolling elapsed-time window used to count repeated 9 EMA interactions. Automatically converts to bars for the chart timeframe.")
int minEMAInteractions = input.int(3, "Minimum 9 EMA Interactions", minval=1, maxval=20, group=G_SIGNAL, tooltip="Minimum bars with a close/open near or a close crossing the 9 EMA within the rolling window to qualify as chop.")
float trendPersistencePct = input.float(70.0, "Directional Trend Persistence (%)", minval=50, maxval=100, step=5, group=G_SIGNAL, tooltip="If this percentage of recent closes remains on one side of the 9 EMA and the EMA/VWAP are aligned, suppress chop warnings and exits during a directional trend.")
float emaInteractionToleranceTicks = input.float(3.0, "9 EMA Interaction Tolerance (ticks)", minval=0, step=0.5, group=G_SIGNAL, tooltip="An open or close within this distance of the 9 EMA counts as an interaction. Wick-only touches do not count, helping avoid false chop signals during a directional trend.")
int chopExitConfirmBars = input.int(2, "Chop Exit Confirmation Bars", minval=1, maxval=10, group=G_SIGNAL, tooltip="Number of consecutive bars meeting the rolling-window chop rule before signaling an exit." )
string chopExitLabelText = input.string("CHOP EXIT", "Chop Exit Label Text", options=["CHOP EXIT", "CHOP", "EXIT CHOP", "CLOSE TRADE", "SIDEWAYS EXIT"], group=G_SIGNAL, tooltip="Text displayed on the confirmed chop-exit chart label.")
string chopExitLabelSizeInput = input.string("Tiny", "Chop Exit Label Size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=G_SIGNAL, tooltip="Controls the size of the confirmed chop-exit chart label. Tiny is the default.")
string chopWarningLabelText = input.string("CHOP?", "Chop Warning Label Text", options=["CHOP?", "CHOP", "POSSIBLE CHOP", "CAUTION", "SIDEWAYS?"], group=G_SIGNAL, tooltip="Text shown for the early chop-warning label, before a confirmed exit.")
 
//-----------------------------------------------------------------------------
// 04. EMA / VWAP / SIGNAL VISUALS
 
//-----------------------------------------------------------------------------
bool showEMA = input.bool(true, "Show 9 EMA", group=G_VIS, inline="ema", tooltip="Display or hide the 9-period exponential moving average.")
bool highlightMovements = input.bool(true, "Dynamic EMA Colors", group=G_VIS, tooltip="When enabled, color the EMA according to its current movement state using the customizable colors below. When disabled, use EMA Base Color.")
color emaColor = input.color(#6D1E7F, "EMA Base Color", group=G_VIS, tooltip="EMA line and value color when Dynamic EMA Colors is disabled.")
color emaBullishBarColor = input.color(#2962FF, "EMA Color 1 — Blue", group=G_VIS, tooltip="Used by the exact EMA color rules when close is at/below open and EMA is at/above its prior-three-bar average, or when the EMA is rising after higher-priority conditions.")
color emaBelowPriceColor = input.color(#EC5360, "EMA Color 2 — Red", group=G_VIS, tooltip="Used when chart close is below the EMA, after the first blue condition and before the remaining conditions.")
color emaFallingColor = input.color(#FFFFFF, "EMA Color 3 — White", group=G_VIS, tooltip="Used when EMA is at or below the average of its three prior values, after higher-priority conditions.")
color emaAboveRangeColor = input.color(#FF9800, "EMA Color 4 — Bright Orange (Surge Setup)", group=G_VIS, tooltip="Bright orange when EMA is above the average of the prior three candle midpoints (avg3barsHiLo), after the higher-priority conditions. This is the surge-coming highlight.")
color emaOtherColor = input.color(#6D1E7F, "EMA Color 5 — Purple / Other", group=G_VIS, tooltip="Fallback color when none of the preceding EMA movement conditions apply.")
int emaWidth = input.int(2, "Width", minval=1, maxval=4, group=G_VIS, inline="ema", tooltip="Line thickness for the 9 EMA.")
bool showVWAP = input.bool(true, "Show VWAP", group=G_VIS, inline="vwap", tooltip="Display or hide session VWAP.")
bool highlightVwapMovements = input.bool(true, "Dynamic VWAP Colors", group=G_VIS, tooltip="When enabled, use the customizable rising and normal colors below. When disabled, use VWAP Base Color.")
color vwapColor = input.color(#9598A1, "VWAP Base Color", group=G_VIS, tooltip="VWAP line and value color when Dynamic VWAP Colors is disabled.")
color vwapRisingColor = input.color(#E8A241, "VWAP Rising Color", group=G_VIS, tooltip="VWAP color when it meets the rising-momentum condition.")
color vwapNormalColor = input.color(#9598A1, "VWAP Normal Color", group=G_VIS, tooltip="VWAP color when it does not meet the rising-momentum condition.")
int vwapWidth = input.int(2, "Width", minval=1, maxval=4, group=G_VIS, inline="vwap", tooltip="Line thickness for VWAP.")
bool showSignalLabels = input.bool(true, "Show Entry Arrows and Prices", group=G_VIS, tooltip="Display BUY/SELL arrows and entry-price labels.")
bool showRiskLines = input.bool(true, "Show Entry / Stop / Target Lines", group=G_VIS, tooltip="Display the entry, stop-loss, and take-profit levels.")
bool showRecoveryMarkers = input.bool(false, "Show Recovery Markers", group=G_VIS, tooltip="Display markers where potential recovery turns are detected.")
color longColor = input.color(#00C853, "Bullish Color", group=G_VIS, tooltip="Configure bullish color for the indicator.")
color shortColor = input.color(#EF5350, "Bearish Color", group=G_VIS, tooltip="Configure bearish color for the indicator.")
 
//-----------------------------------------------------------------------------
// 05. DAILY HIGH / LOW — INFO LABELS-STYLE REFERENCES
 
//-----------------------------------------------------------------------------
string dailyRangeMode = input.string("Premarket + Regular Session", "Daily High / Low Source", options=["Premarket + Regular Session", "Regular Session Only"], group=G_DAILY, tooltip="Choose whether displayed Daily High/Low include premarket and regular-session bars, or only regular-session bars.")
bool showDailyHigh = input.bool(true, "Show Daily High", group=G_DAILY, tooltip="Display the developing current-day high level.")
bool showDailyLow = input.bool(true, "Show Daily Low", group=G_DAILY, tooltip="Display the developing current-day low level.")
bool showDailyLevelNames = input.bool(true, "Show Level Names", group=G_DAILY, tooltip="Show text labels at the start of daily high/low lines.")
bool showDailyPriceTags = input.bool(true, "Show Price Tags", group=G_DAILY, tooltip="Show the current price value at the right edge of daily levels.")
color dailyHighColor = input.color(#EF5350, "Daily High Color", group=G_DAILY, tooltip="Color used for the developing daily high line and labels.")
color dailyLowColor = input.color(#00C853, "Daily Low Color", group=G_DAILY, tooltip="Color used for the developing daily low line and labels.")
int dailyLineWidth = input.int(1, "Line Width", minval=1, maxval=4, group=G_DAILY, tooltip="Thickness of the daily high/low reference lines.")
string dailyLineStyleInput = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group=G_DAILY, tooltip="Configure solid for the indicator.")
 
//-----------------------------------------------------------------------------
// 06. ENTRY / STOP / TARGET — TBORLMR-STYLE LEVELS
 
//-----------------------------------------------------------------------------
bool calculateLevels = input.bool(true, "Calculate Entry / Stop / Target", group=G_LEVELS, tooltip="Calculate risk levels from the entry price and session extreme.")
bool showEntryLevel = input.bool(true, "Show Entry Level", group=G_LEVELS, tooltip="Display the horizontal entry price line.")
bool showStopLevel = input.bool(true, "Show Stop-Loss Level", group=G_LEVELS, tooltip="Display the calculated stop-loss line.")
bool showTargetLevel = input.bool(true, "Show Take-Profit Level", group=G_LEVELS, tooltip="Display the calculated target line.")
bool showTradeLevelNames = input.bool(true, "Show Level Names", group=G_LEVELS, tooltip="Show text labels at the start of daily high/low lines.")
bool showTradePriceTags = input.bool(true, "Show Price Tags", group=G_LEVELS, tooltip="Show the current price value at the right edge of daily levels.")
float stopDivisor = input.float(3.0, "Stop Distance Divisor", minval=1, step=0.5, group=G_LEVELS, tooltip="Stop distance equals the distance to the session extreme divided by this value.")
float targetMultiple = input.float(1.0, "Target Distance Multiple", minval=0.25, step=0.25, group=G_LEVELS, tooltip="Target distance as a multiple of the entry-to-session-extreme unit.")
bool stopWinsIfBothTouched = input.bool(true, "Assume Stop First If Both Hit", group=G_LEVELS, tooltip="Choose stop-loss outcome when stop and target are both touched in one bar.")
bool trailAfterTarget = input.bool(true, "Trail Stop After Take Profit", group=G_LEVELS, tooltip="When the target is reached, lock it in as the new stop-loss and advance the next target by the original target-distance step. The trade remains active until the trailing stop or a later target/exit is reached.")
color entryColor = input.color(#FFFFFF, "Entry Color", group=G_LEVELS, tooltip="Color used for the entry line, label, and dashboard value.")
color stopColor = input.color(#EF5350, "Stop-Loss Color", group=G_LEVELS, tooltip="Color used for stop-loss line, label, and dashboard value.")
color targetColor = input.color(#7CFC00, "Take-Profit Color", group=G_LEVELS, tooltip="Color used for take-profit line, label, and dashboard value.")
int tradeLineWidth = input.int(1, "Trade Line Width", minval=1, maxval=1, group=G_LEVELS, tooltip="Entry, stop-loss, and take-profit lines are fixed at width 1.")
string tradeLineStyleInput = input.string("Dashed", "Trade Line Style", options=["Solid", "Dashed", "Dotted"], group=G_LEVELS, tooltip="Configure dashed for the indicator.")
 
//-----------------------------------------------------------------------------
// 07. DASHBOARD
 
//-----------------------------------------------------------------------------
bool showTable = input.bool(true, "Display Dashboard", group=G_TABLE, tooltip="Show or hide the dashboard table.")
string tablePositionInput = input.string("Middle Right", "Table Position", options=["Top Right", "Bottom Right", "Top Left", "Bottom Left", "Middle Right"], group=G_TABLE, tooltip="Configure middle right for the indicator.")
string tableTextSizeInput = input.string("Small", "Text Size", options=["Tiny", "Small", "Normal", "Large"], group=G_TABLE, tooltip="Configure small for the indicator.")
bool showTableHeader = input.bool(true, "Show Table Header", group=G_TABLE, tooltip="Show or hide the dashboard title row.")
color tableBg = input.color(color.new(#32373F, 15), "Background", group=G_TABLE, tooltip="Background color for dashboard data cells.")
color tableText = input.color(#D6DCE5, "Text", group=G_TABLE, tooltip="Default text color for dashboard cells.")
color tableHeaderBg = input.color(#263238, "Header Background", group=G_TABLE, tooltip="Background color for the dashboard header.")
color goColor = input.color(#00C853, "GO Color", group=G_TABLE, tooltip="Color used for GO and successful-target status.")
color chopColor = input.color(#FFB300, "CHOP Color", group=G_TABLE, tooltip="Color used when conditions indicate a choppy market.")
color noSetupColor = input.color(#EF5350, "NO SETUP Color", group=G_TABLE, tooltip="Color used when no setup is available or a stop is hit.")
color waitColor = input.color(#90A4AE, "WAIT Color", group=G_TABLE, tooltip="Color used for waiting states.")
 
//-----------------------------------------------------------------------------
// 08. DASHBOARD ROW CONTROLS
 
//-----------------------------------------------------------------------------
bool showStatusRow = input.bool(true, "Show Setup Status", group=G_ROWS, tooltip="Configure show setup status for the indicator.")
bool showDirectionRow = input.bool(true, "Show Direction", group=G_ROWS, tooltip="Configure show direction for the indicator.")
bool showStageRow = input.bool(true, "Show Setup Stage", group=G_ROWS, tooltip="Configure show setup stage for the indicator.")
bool showEMAValueRow = input.bool(true, "Show 9 EMA Value", group=G_ROWS, tooltip="Configure show 9 ema value for the indicator.")
bool showVWAPValueRow = input.bool(true, "Show VWAP Value", group=G_ROWS, tooltip="Configure show vwap value for the indicator.")
bool showPriceRow = input.bool(true, "Show Current Price", group=G_ROWS, tooltip="Configure show current price for the indicator.")
bool showSessionLowRow = input.bool(true, "Show Daily Low Value", group=G_ROWS, tooltip="Configure show daily low value for the indicator.")
bool showSessionHighRow = input.bool(true, "Show Daily High Value", group=G_ROWS, tooltip="Configure show daily high value for the indicator.")
bool showMomentumRow = input.bool(true, "Show Momentum", group=G_ROWS, tooltip="Configure show momentum for the indicator.")
bool showTimeRow = input.bool(true, "Show Entry Window", group=G_ROWS, tooltip="Configure show entry window for the indicator.")
bool showEntryRow = input.bool(true, "Show Entry Price", group=G_ROWS, tooltip="Configure show entry price for the indicator.")
bool showStopRow = input.bool(true, "Show Stop Loss", group=G_ROWS, tooltip="Configure show stop loss for the indicator.")
bool showTargetRow = input.bool(true, "Show Take Profit", group=G_ROWS, tooltip="Configure show take profit for the indicator.")
bool showRRRow = input.bool(true, "Show Reward / Risk", group=G_ROWS, tooltip="Configure show reward / risk for the indicator.")
bool showOutcomeRow = input.bool(true, "Show Trade Outcome", group=G_ROWS, tooltip="Configure show trade outcome for the indicator.")
 
//-----------------------------------------------------------------------------
// 09. HELPERS
 
//-----------------------------------------------------------------------------
f_tablePosition(string p) =>
    switch p
        "Top Right" => position.top_right
        "Bottom Right" => position.bottom_right
        "Top Left" => position.top_left
        "Bottom Left" => position.bottom_left
        => position.middle_right
f_textSize(string s) =>
    switch s
        "Tiny" => size.tiny
        "Normal" => size.normal
        "Large" => size.large
        => size.small
f_price(float p) =>
    na(p) ? "N/A" : "$" + str.tostring(p, format.mintick)
f_lineStyle(string s) =>
    switch s
        "Solid" => line.style_solid
        "Dotted" => line.style_dotted
        => line.style_dashed
f_statusColor(string s) =>
    s == "GO" or s == "ACTIVE" ? goColor : s == "CHOP" or s == "CHOP EXIT" ? chopColor : s == "STOP HIT" ? noSetupColor : s == "TARGET HIT" ? goColor : s == "NO SETUP" ? noSetupColor : waitColor
 
//-----------------------------------------------------------------------------
// 10. SESSION AND INDICATORS
 
//-----------------------------------------------------------------------------
bool inRegularSession = not na(time(timeframe.period, regularSession, sessionTimezone))
bool inTradeWindow = not na(time(timeframe.period, tradeWindow, sessionTimezone))
bool newDay = timeframe.change("D")
bool sessionStart = inRegularSession and not inRegularSession[1]
bool premarketStart = not na(time(timeframe.period, "0400-0401:23456", sessionTimezone)) and na(time(timeframe.period, "0400-0401:23456", sessionTimezone)[1])
bool dashboardReset = clearDashboardAtPremarket ? premarketStart : sessionStart
bool tradeWindowActive = inRegularSession and inTradeWindow
float ema9 = ta.ema(src9, emaLength)
float vwapValue = ta.vwap(hlc3)
// EMA color states are evaluated in the original priority order. Orange remains the
// higher-priority surge highlight only after the blue, red, and white conditions fail.
float avg9ema = math.avg(ema9[1], ema9[2], ema9[3])
float avg3barsHiLo = math.avg(hl2[1], hl2[2], hl2[3])
bool emaBlueBarState = close <= open and ema9 >= avg9ema
bool emaBelowPriceState = close < ema9
bool emaBelowAverageState = ema9 <= avg9ema
bool emaSurgeState = ema9 > avg3barsHiLo
bool emaRisingState = ema9 > ema9[1]
color ema9DynamicColor = emaBlueBarState ? emaBullishBarColor : emaBelowPriceState ? emaBelowPriceColor : emaBelowAverageState ? emaFallingColor : emaSurgeState ? emaAboveRangeColor : emaRisingState ? emaBullishBarColor : emaOtherColor
color ema9Color = highlightMovements ? ema9DynamicColor : emaColor
 
// VWAP highlights only sustained upward momentum across the current and prior bars.
float vwapavg = math.avg(vwapValue[1], vwapValue[2])
bool vwapStrongRise = vwapValue > vwapavg and vwapValue > vwapValue[1] and vwapValue > vwapValue[2] and vwapValue > vwapValue[3]
color vwapDynamicColor = vwapStrongRise ? vwapRisingColor : vwapNormalColor
color vwapPlotColor = highlightVwapMovements ? vwapDynamicColor : vwapColor
plot(showEMA ? ema9 : na, "9 EMA", color=ema9Color, linewidth=emaWidth)
plot(showVWAP ? vwapValue : na, "VWAP", color=vwapPlotColor, linewidth=vwapWidth)
// The 2-minute chart is recommended, never enforced.
bool isRecommendedTimeframe = timeframe.isminutes and timeframe.multiplier == 2
 
//-----------------------------------------------------------------------------
// 11. DAILY HIGH / LOW
// Track the developing high/low of the current exchange day.
// The separate RTH values are used for the Start Late setup calculations.
 
//-----------------------------------------------------------------------------
var float dailyHigh = na
var float dailyLow = na
var float sessionHigh = na
var float sessionLow = na
var int highBar = na
var int lowBar = na
var int sessionHighBar = na
var int sessionLowBar = na
if newDay
    dailyHigh := high
    dailyLow := low
    sessionHigh := na
    sessionLow := na
    sessionHighBar := na
    sessionLowBar := na
    highBar := bar_index
    lowBar := bar_index
else
    if na(dailyHigh) or high > dailyHigh
        dailyHigh := high
        highBar := bar_index
    if na(dailyLow) or low < dailyLow
        dailyLow := low
        lowBar := bar_index
if sessionStart
    sessionHigh := high
    sessionLow := low
    sessionHighBar := bar_index
    sessionLowBar := bar_index
else if inRegularSession
    if na(sessionHigh) or high > sessionHigh
        sessionHigh := high
        sessionHighBar := bar_index
    if na(sessionLow) or low < sessionLow
        sessionLow := low
        sessionLowBar := bar_index
 
// Select displayed references only. Start Late setup calculations continue to use RTH sessionHigh/sessionLow.
float displayedDailyHigh = dailyRangeMode == "Regular Session Only" ? sessionHigh : dailyHigh
float displayedDailyLow = dailyRangeMode == "Regular Session Only" ? sessionLow : dailyLow
int displayedHighBar = dailyRangeMode == "Regular Session Only" ? sessionHighBar : highBar
int displayedLowBar = dailyRangeMode == "Regular Session Only" ? sessionLowBar : lowBar
// Daily reference lines and their labels.
var line dailyHighLine = na
var line dailyLowLine = na
var label dailyHighNameLabel = na
var label dailyLowNameLabel = na
var label dailyHighPriceLabel = na
var label dailyLowPriceLabel = na
if newDay
    if not na(dailyHighLine)
        line.delete(dailyHighLine)
    if not na(dailyLowLine)
        line.delete(dailyLowLine)
    if not na(dailyHighNameLabel)
        label.delete(dailyHighNameLabel)
    if not na(dailyLowNameLabel)
        label.delete(dailyLowNameLabel)
    if not na(dailyHighPriceLabel)
        label.delete(dailyHighPriceLabel)
    if not na(dailyLowPriceLabel)
        label.delete(dailyLowPriceLabel)
    dailyHighLine := na
    dailyLowLine := na
    dailyHighNameLabel := na
    dailyLowNameLabel := na
    dailyHighPriceLabel := na
    dailyLowPriceLabel := na
if barstate.islast
    if showDailyHigh and not na(displayedDailyHigh)
        if na(dailyHighLine)
            dailyHighLine := line.new(bar_index, displayedDailyHigh, bar_index + 1, displayedDailyHigh, color=dailyHighColor, width=dailyLineWidth, style=f_lineStyle(dailyLineStyleInput))
        line.set_xy1(dailyHighLine, math.max(0, nz(displayedHighBar, bar_index)), displayedDailyHigh)
        line.set_xy2(dailyHighLine, bar_index + 1, displayedDailyHigh)
        line.set_color(dailyHighLine, dailyHighColor)
        line.set_width(dailyHighLine, dailyLineWidth)
        line.set_style(dailyHighLine, f_lineStyle(dailyLineStyleInput))
        if showDailyLevelNames
            if na(dailyHighNameLabel)
                dailyHighNameLabel := label.new(math.max(0, nz(displayedHighBar, bar_index)), displayedDailyHigh, "Daily High", style=label.style_label_down, color=dailyHighColor, textcolor=color.white, size=size.tiny)
            label.set_xy(dailyHighNameLabel, math.max(0, nz(displayedHighBar, bar_index)), displayedDailyHigh)
            label.set_text(dailyHighNameLabel, "Daily High")
            label.set_color(dailyHighNameLabel, dailyHighColor)
        else if not na(dailyHighNameLabel)
            label.delete(dailyHighNameLabel)
            dailyHighNameLabel := na
        if showDailyPriceTags
            if na(dailyHighPriceLabel)
                dailyHighPriceLabel := label.new(bar_index + 1, displayedDailyHigh, f_price(displayedDailyHigh), style=label.style_label_left, color=dailyHighColor, textcolor=color.white, size=size.tiny)
            label.set_xy(dailyHighPriceLabel, bar_index + 1, displayedDailyHigh)
            label.set_text(dailyHighPriceLabel, f_price(displayedDailyHigh))
            label.set_color(dailyHighPriceLabel, dailyHighColor)
        else if not na(dailyHighPriceLabel)
            label.delete(dailyHighPriceLabel)
            dailyHighPriceLabel := na
    else
        if not na(dailyHighLine)
            line.delete(dailyHighLine)
            dailyHighLine := na
        if not na(dailyHighNameLabel)
            label.delete(dailyHighNameLabel)
            dailyHighNameLabel := na
        if not na(dailyHighPriceLabel)
            label.delete(dailyHighPriceLabel)
            dailyHighPriceLabel := na
    if showDailyLow and not na(displayedDailyLow)
        if na(dailyLowLine)
            dailyLowLine := line.new(bar_index, displayedDailyLow, bar_index + 1, displayedDailyLow, color=dailyLowColor, width=dailyLineWidth, style=f_lineStyle(dailyLineStyleInput))
        line.set_xy1(dailyLowLine, math.max(0, nz(displayedLowBar, bar_index)), displayedDailyLow)
        line.set_xy2(dailyLowLine, bar_index + 1, displayedDailyLow)
        line.set_color(dailyLowLine, dailyLowColor)
        line.set_width(dailyLowLine, dailyLineWidth)
        line.set_style(dailyLowLine, f_lineStyle(dailyLineStyleInput))
        if showDailyLevelNames
            if na(dailyLowNameLabel)
                dailyLowNameLabel := label.new(math.max(0, nz(displayedLowBar, bar_index)), displayedDailyLow, "Daily Low", style=label.style_label_up, color=dailyLowColor, textcolor=color.black, size=size.tiny)
            label.set_xy(dailyLowNameLabel, math.max(0, nz(displayedLowBar, bar_index)), displayedDailyLow)
            label.set_text(dailyLowNameLabel, "Daily Low")
            label.set_color(dailyLowNameLabel, dailyLowColor)
        else if not na(dailyLowNameLabel)
            label.delete(dailyLowNameLabel)
            dailyLowNameLabel := na
        if showDailyPriceTags
            if na(dailyLowPriceLabel)
                dailyLowPriceLabel := label.new(bar_index + 1, displayedDailyLow, f_price(displayedDailyLow), style=label.style_label_left, color=dailyLowColor, textcolor=color.black, size=size.tiny)
            label.set_xy(dailyLowPriceLabel, bar_index + 1, displayedDailyLow)
            label.set_text(dailyLowPriceLabel, f_price(displayedDailyLow))
            label.set_color(dailyLowPriceLabel, dailyLowColor)
        else if not na(dailyLowPriceLabel)
            label.delete(dailyLowPriceLabel)
            dailyLowPriceLabel := na
    else
        if not na(dailyLowLine)
            line.delete(dailyLowLine)
            dailyLowLine := na
        if not na(dailyLowNameLabel)
            label.delete(dailyLowNameLabel)
            dailyLowNameLabel := na
        if not na(dailyLowPriceLabel)
            label.delete(dailyLowPriceLabel)
            dailyLowPriceLabel := na
 
//-----------------------------------------------------------------------------
// 12. MOMENTUM AND CHOP
 
//-----------------------------------------------------------------------------
float tickSize = syminfo.mintick
float emaSlope = ema9 - ema9[emaSlopeLookback]
float vwapSlope = vwapValue - vwapValue[emaSlopeLookback]
float vwapDistance = math.abs(close - vwapValue)
float emaInteractionTolerance = emaInteractionToleranceTicks * tickSize
int chartSeconds = timeframe.in_seconds()
int chopWindowBars = not na(chartSeconds) and chartSeconds > 0 ? math.max(1, int(math.ceil(chopWindowMinutes * 60.0 / chartSeconds))) : chopWindowMinutes
float priorVwapDistance = math.abs(close[recoveryLookback] - vwapValue[recoveryLookback])
bool emaRising = emaSlope > flatThresholdTicks * tickSize
bool emaFalling = emaSlope < -flatThresholdTicks * tickSize
bool emaFlat = math.abs(emaSlope) <= flatThresholdTicks * tickSize
bool vwapRising = vwapSlope > 0
bool vwapFalling = vwapSlope < 0
bool movingTowardVWAP = vwapDistance < priorVwapDistance
bool priceRising = close > close[recoveryLookback]
bool priceFalling = close < close[recoveryLookback]
float closeCross = ta.cross(close, vwapValue) ? 1.0 : 0.0
float crossCount = math.sum(closeCross, chopCrossLookback)
bool repeatedVWAPCrosses = crossCount >= maxVWAPCrosses
float emaDistance = math.abs(close - ema9)
float emaCross = ta.cross(close, ema9) ? 1.0 : 0.0
float emaCrossCount = math.sum(emaCross, chopCrossLookback)
bool repeatedEMACrosses = emaCrossCount >= maxVWAPCrosses
bool nearVWAP = vwapDistance <= chopZoneTicks * tickSize
bool repeatedPriceCrosses = repeatedVWAPCrosses or repeatedEMACrosses
bool emaOpenCloseNear = math.abs(open - ema9) <= emaInteractionTolerance or math.abs(close - ema9) <= emaInteractionTolerance
bool closeCrossesEMA = ta.cross(close, ema9)
// Count genuine EMA interaction: open/close near the EMA or a close crossing it.
// Wick-only touches are excluded because they can occur during a healthy trend.
float emaInteractionBar = emaOpenCloseNear or closeCrossesEMA ? 1.0 : 0.0
float emaInteractionCount = math.sum(emaInteractionBar, chopWindowBars)
bool enoughEMAInteractions = emaInteractionCount >= minEMAInteractions
float closesBelowEMA = math.sum(close < ema9 ? 1.0 : 0.0, chopWindowBars)
float closesAboveEMA = math.sum(close > ema9 ? 1.0 : 0.0, chopWindowBars)
float requiredTrendBars = chopWindowBars * trendPersistencePct / 100.0
// Directional continuation must not be mislabeled as chop merely because price
// periodically comes close to the EMA while continuing to trend away from VWAP.
bool persistentBearTrend = closesBelowEMA >= requiredTrendBars and emaFalling and ema9 < vwapValue and close < ema9
bool persistentBullTrend = closesAboveEMA >= requiredTrendBars and emaRising and ema9 > vwapValue and close > ema9
bool directionalTrendActive = persistentBearTrend or persistentBullTrend
bool vwapChop = nearVWAP and (emaFlat or repeatedVWAPCrosses) and not directionalTrendActive
bool confirmedTradeChop = enoughEMAInteractions and (emaFlat or repeatedPriceCrosses) and not directionalTrendActive
bool activeTradeChopWarning = emaInteractionCount >= math.max(1, minEMAInteractions - 1) and (emaFlat or repeatedPriceCrosses) and not directionalTrendActive
 
//-----------------------------------------------------------------------------
// 13. RECOVERY STATE AND TRADE STATE
 
//-----------------------------------------------------------------------------
var int longStage = 0
var int shortStage = 0
var int longRecoveryBar = na
var int shortRecoveryBar = na
var bool longDirectionArmed = false
var bool shortDirectionArmed = false
var bool tradeTriggeredToday = false
var int chopReentriesToday = 0
var int stopReentriesToday = 0
var bool tradeActive = false
var int consecutiveTradeChopBars = 0
var bool chopWarningPrintedThisTrade = false
var string setupStatus = "WAIT"
var string setupDirection = "NONE"
var string stageText = "WAITING FOR TURN"
var string momentumText = "WAITING"
var string tradeOutcome = "NONE"
var float entryPrice = na
var float stopPrice = na
var float targetPrice = na
var float targetStepDistance = na
var bool targetTrailed = false
var float rewardRisk = na
var float chopExitPrice = na
var float frozenExtreme = na
var int entryBar = na
var line entryLine = na
var line stopLine = na
var line targetLine = na
var label entryNameLabel = na
var label stopNameLabel = na
var label targetNameLabel = na
var label entryPriceLabel = na
var label stopPriceLabel = na
var label targetPriceLabel = na
var label chopExitLabel = na
var label chopWarningLabel = na
if dashboardReset
    longStage := 0
    shortStage := 0
    longRecoveryBar := na
    shortRecoveryBar := na
    longDirectionArmed := false
    shortDirectionArmed := false
    tradeTriggeredToday := false
    chopReentriesToday := 0
    stopReentriesToday := 0
    tradeActive := false
    consecutiveTradeChopBars := 0
    chopWarningPrintedThisTrade := false
    setupStatus := "WAIT"
    setupDirection := "NONE"
    stageText := "WAITING FOR TURN"
    momentumText := "WAITING"
    tradeOutcome := "NONE"
    entryPrice := na
    stopPrice := na
    targetPrice := na
    targetStepDistance := na
    targetTrailed := false
    rewardRisk := na
    chopExitPrice := na
    frozenExtreme := na
    entryBar := na
    if not na(entryLine)
        line.delete(entryLine)
    if not na(stopLine)
        line.delete(stopLine)
    if not na(targetLine)
        line.delete(targetLine)
    if not na(entryNameLabel)
        label.delete(entryNameLabel)
    if not na(stopNameLabel)
        label.delete(stopNameLabel)
    if not na(targetNameLabel)
        label.delete(targetNameLabel)
    if not na(entryPriceLabel)
        label.delete(entryPriceLabel)
    if not na(stopPriceLabel)
        label.delete(stopPriceLabel)
    if not na(targetPriceLabel)
        label.delete(targetPriceLabel)
    if not na(chopExitLabel)
        label.delete(chopExitLabel)
    if not na(chopWarningLabel)
        label.delete(chopWarningLabel)
    entryLine := na
    stopLine := na
    targetLine := na
    entryNameLabel := na
    stopNameLabel := na
    targetNameLabel := na
    entryPriceLabel := na
    stopPriceLabel := na
    targetPriceLabel := na
    chopExitLabel := na
    chopWarningLabel := na
bool lowTurn = inRegularSession and not na(sessionLow) and low > sessionLow and close > close[1]
bool highTurn = inRegularSession and not na(sessionHigh) and high < sessionHigh and close < close[1]
bool chopReentryAvailable = allowReentryAfterChopExit and tradeOutcome == "CHOP EXIT" and chopReentriesToday < maxChopReentriesPerDay
bool stopReentryAvailable = allowTrendContinuationAfterStop and tradeOutcome == "STOP HIT" and stopReentriesToday < maxStopReentriesPerDay
if inRegularSession and not tradeActive and (not oneTradePerDay or not tradeTriggeredToday or chopReentryAvailable or stopReentryAvailable)
    if longStage == 0 and lowTurn
        longStage := 1
        longRecoveryBar := bar_index
    if shortStage == 0 and highTurn
        shortStage := 1
        shortRecoveryBar := bar_index
    if longStage == 1 and not na(longRecoveryBar) and bar_index - longRecoveryBar > recoveryExpiryBars
        longStage := 0
        longRecoveryBar := na
        longDirectionArmed := false
    if shortStage == 1 and not na(shortRecoveryBar) and bar_index - shortRecoveryBar > recoveryExpiryBars
        shortStage := 0
        shortRecoveryBar := na
        shortDirectionArmed := false
    if longStage == 1 and low <= sessionLow and bar_index > longRecoveryBar
        longStage := 0
        longRecoveryBar := na
        longDirectionArmed := false
    if shortStage == 1 and high >= sessionHigh and bar_index > shortRecoveryBar
        shortStage := 0
        shortRecoveryBar := na
        shortDirectionArmed := false
 
//-----------------------------------------------------------------------------
// 14. ENTRY TRIGGERS
 
//-----------------------------------------------------------------------------
bool bullishCross = ta.crossover(ema9, vwapValue)
bool bearishCross = ta.crossunder(ema9, vwapValue)
// Evaluate cross and barssince series on every bar to avoid conditional-execution warnings.
bool closeCrossedAboveEMA = ta.crossover(close, ema9)
bool closeCrossedBelowEMA = ta.crossunder(close, ema9)
int barsSinceBullishCross = ta.barssince(bullishCross)
int barsSinceBearishCross = ta.barssince(bearishCross)
bool longSlopeOK = not requireEMASlope or emaRising
bool shortSlopeOK = not requireEMASlope or emaFalling
bool longVWAPOK = not requireVWAPSlope or vwapRising
bool shortVWAPOK = not requireVWAPSlope or vwapFalling
bool chopOK = not blockChoppyCross or not vwapChop
bool canEnterStandard = inRegularSession and inTradeWindow and not tradeActive and (not oneTradePerDay or not tradeTriggeredToday or chopReentryAvailable)
bool canEnter = canEnterStandard or (inRegularSession and inTradeWindow and not tradeActive and stopReentryAvailable)
bool longCriteriaMet = canEnterStandard and longStage == 1 and bullishCross and longSlopeOK and longVWAPOK and chopOK
bool shortCriteriaMet = canEnterStandard and allowShorts and shortStage == 1 and bearishCross and shortSlopeOK and shortVWAPOK and chopOK
 
// Optional candle-direction confirmation: arm on the original qualifying cross,
// then wait for a confirmed candle aligned with the already-established side.
if requireSignalCandleDirection and longCriteriaMet
    longDirectionArmed := true
if requireSignalCandleDirection and shortCriteriaMet
    shortDirectionArmed := true
bool longCandleConfirmed = close >= open
bool shortCandleConfirmed = close <= open
bool standardLongSignal = requireSignalCandleDirection ? (canEnter and longStage == 1 and longDirectionArmed and barstate.isconfirmed and longCandleConfirmed) : longCriteriaMet
bool standardShortSignal = requireSignalCandleDirection ? (canEnter and allowShorts and shortStage == 1 and shortDirectionArmed and barstate.isconfirmed and shortCandleConfirmed) : shortCriteriaMet
// After a chop exit, allow a fresh pullback/rejection in the established trend.
// This is deliberately separate from the normal crossover/recovery entry logic.
bool longChopContinuation = allowTrendContinuationReentry and chopReentryAvailable
bool shortChopContinuation = allowTrendContinuationReentry and chopReentryAvailable
bool longStopContinuation = allowTrendContinuationAfterStop and stopReentryAvailable
bool shortStopContinuation = allowTrendContinuationAfterStop and stopReentryAvailable
bool longPullbackContinuation = canEnter and (longChopContinuation or longStopContinuation) and setupDirection == "LONG" and ema9 > vwapValue and emaRising and low <= ema9 and close > ema9 and barstate.isconfirmed
bool shortPullbackContinuation = canEnter and allowShorts and (shortChopContinuation or shortStopContinuation) and setupDirection == "SHORT" and ema9 < vwapValue and emaFalling and high >= ema9 and close < ema9 and barstate.isconfirmed
// Earlier momentum path after STOP HIT: do not require a full retest wick.
// Require established EMA/VWAP alignment plus a confirmed directional close crossing the EMA,
// or a fresh EMA/VWAP cross with price already closing on the trend side. Mirror for both sides.
bool longEarlyMomentumContinuation = allowEarlyMomentumAfterStop and canEnter and stopReentryAvailable and setupDirection == "LONG" and ema9 > vwapValue and emaRising and close > ema9 and close > open and (closeCrossedAboveEMA or (not na(barsSinceBullishCross) and barsSinceBullishCross <= recoveryLookback)) and barstate.isconfirmed
bool shortEarlyMomentumContinuation = allowEarlyMomentumAfterStop and canEnter and allowShorts and stopReentryAvailable and setupDirection == "SHORT" and ema9 < vwapValue and emaFalling and close < ema9 and close < open and (closeCrossedBelowEMA or (not na(barsSinceBearishCross) and barsSinceBearishCross <= recoveryLookback)) and barstate.isconfirmed
bool longContinuationReentry = longPullbackContinuation or longEarlyMomentumContinuation
bool shortContinuationReentry = shortPullbackContinuation or shortEarlyMomentumContinuation
bool longSignal = standardLongSignal or longContinuationReentry
bool shortSignal = standardShortSignal or shortContinuationReentry
 
//-----------------------------------------------------------------------------
// 15. FIX ENTRY, STOP AND TARGET AT THE SIGNAL
 
//-----------------------------------------------------------------------------
if longSignal
    if tradeOutcome == "CHOP EXIT" and chopReentryAvailable
        chopReentriesToday += 1
    if tradeOutcome == "STOP HIT" and stopReentryAvailable
        stopReentriesToday += 1
    setupDirection := "LONG"
    setupStatus := "GO"
    stageText := "CROSSOVER TRIGGERED"
    momentumText := "BULLISH"
    entryPrice := close
    frozenExtreme := sessionLow
    float unit = entryPrice - frozenExtreme
    stopPrice := calculateLevels and unit > 0 ? entryPrice - unit / stopDivisor : na
    targetPrice := calculateLevels and unit > 0 ? entryPrice + unit * targetMultiple : na
    targetStepDistance := not na(targetPrice) ? math.abs(targetPrice - entryPrice) : na
    targetTrailed := false
    rewardRisk := not na(stopPrice) and not na(targetPrice) and entryPrice > stopPrice ? (targetPrice - entryPrice) / (entryPrice - stopPrice) : na
    entryBar := bar_index
    tradeTriggeredToday := true
    tradeActive := true
    consecutiveTradeChopBars := 0
    chopWarningPrintedThisTrade := false
    tradeOutcome := "ACTIVE"
    longStage := 2
    shortStage := 0
    longDirectionArmed := false
    shortDirectionArmed := false
if shortSignal
    if tradeOutcome == "CHOP EXIT" and chopReentryAvailable
        chopReentriesToday += 1
    if tradeOutcome == "STOP HIT" and stopReentryAvailable
        stopReentriesToday += 1
    setupDirection := "SHORT"
    setupStatus := "GO"
    stageText := "CROSSOVER TRIGGERED"
    momentumText := "BEARISH"
    entryPrice := close
    frozenExtreme := sessionHigh
    float unit = frozenExtreme - entryPrice
    stopPrice := calculateLevels and unit > 0 ? entryPrice + unit / stopDivisor : na
    targetPrice := calculateLevels and unit > 0 ? entryPrice - unit * targetMultiple : na
    targetStepDistance := not na(targetPrice) ? math.abs(targetPrice - entryPrice) : na
    targetTrailed := false
    rewardRisk := not na(stopPrice) and not na(targetPrice) and stopPrice > entryPrice ? (entryPrice - targetPrice) / (stopPrice - entryPrice) : na
    entryBar := bar_index
    tradeTriggeredToday := true
    tradeActive := true
    consecutiveTradeChopBars := 0
    chopWarningPrintedThisTrade := false
    tradeOutcome := "ACTIVE"
    shortStage := 2
    longStage := 0
    shortDirectionArmed := false
    longDirectionArmed := false
 
//-----------------------------------------------------------------------------
// 16. TRADE LEVELS — NAMED LABELS + ENDPOINT PRICE TAGS
// Lines advance during regular trading and stop at the last RTH bar.
// Prices remain fixed to the original trade.
 
//-----------------------------------------------------------------------------
if (longSignal or shortSignal) and showRiskLines and calculateLevels
    if not na(entryLine)
        line.delete(entryLine)
    if not na(stopLine)
        line.delete(stopLine)
    if not na(targetLine)
        line.delete(targetLine)
    if not na(entryNameLabel)
        label.delete(entryNameLabel)
    if not na(stopNameLabel)
        label.delete(stopNameLabel)
    if not na(targetNameLabel)
        label.delete(targetNameLabel)
    if not na(entryPriceLabel)
        label.delete(entryPriceLabel)
    if not na(stopPriceLabel)
        label.delete(stopPriceLabel)
    if not na(targetPriceLabel)
        label.delete(targetPriceLabel)
    entryLine := na
    stopLine := na
    targetLine := na
    entryNameLabel := na
    stopNameLabel := na
    targetNameLabel := na
    entryPriceLabel := na
    stopPriceLabel := na
    targetPriceLabel := na
    if showEntryLevel
        entryLine := line.new(bar_index, entryPrice, bar_index + 1, entryPrice, color=entryColor, width=tradeLineWidth, style=f_lineStyle(tradeLineStyleInput))
        if showTradeLevelNames
            entryNameLabel := label.new(bar_index, entryPrice, "ENTRY", style=label.style_label_right, color=entryColor, textcolor=color.black, size=size.tiny)
        if showTradePriceTags
            entryPriceLabel := label.new(bar_index + 1, entryPrice, f_price(entryPrice), style=label.style_label_left, color=entryColor, textcolor=color.black, size=size.tiny)
    if showStopLevel and not na(stopPrice)
        stopLine := line.new(bar_index, stopPrice, bar_index + 1, stopPrice, color=stopColor, width=tradeLineWidth, style=f_lineStyle(tradeLineStyleInput))
        if showTradeLevelNames
            stopNameLabel := label.new(bar_index, stopPrice, "STOP LOSS", style=label.style_label_right, color=stopColor, textcolor=color.white, size=size.tiny)
        if showTradePriceTags
            stopPriceLabel := label.new(bar_index + 1, stopPrice, f_price(stopPrice), style=label.style_label_left, color=stopColor, textcolor=color.white, size=size.tiny)
    if showTargetLevel and not na(targetPrice)
        targetLine := line.new(bar_index, targetPrice, bar_index + 1, targetPrice, color=targetColor, width=tradeLineWidth, style=f_lineStyle(tradeLineStyleInput))
        if showTradeLevelNames
            targetNameLabel := label.new(bar_index, targetPrice, "TAKE PROFIT", style=label.style_label_right, color=targetColor, textcolor=color.black, size=size.tiny)
        if showTradePriceTags
            targetPriceLabel := label.new(bar_index + 1, targetPrice, f_price(targetPrice), style=label.style_label_left, color=targetColor, textcolor=color.black, size=size.tiny)
// Update the right edge and endpoint price labels only during regular hours.
// Once the session ends, the last endpoint is retained.
if inRegularSession and showRiskLines
    if not na(entryLine)
        line.set_x2(entryLine, bar_index)
        line.set_y1(entryLine, entryPrice)
        line.set_y2(entryLine, entryPrice)
    if not na(stopLine)
        line.set_x2(stopLine, bar_index)
        line.set_y1(stopLine, stopPrice)
        line.set_y2(stopLine, stopPrice)
    if not na(targetLine)
        line.set_x2(targetLine, bar_index)
        line.set_y1(targetLine, targetPrice)
        line.set_y2(targetLine, targetPrice)
    if not na(stopNameLabel)
        label.set_y(stopNameLabel, stopPrice)
        label.set_text(stopNameLabel, targetTrailed ? "TRAILING STOP" : "STOP LOSS")
    if not na(targetNameLabel)
        label.set_y(targetNameLabel, targetPrice)
        label.set_text(targetNameLabel, targetTrailed ? "NEXT TAKE PROFIT" : "TAKE PROFIT")
    if not na(entryNameLabel)
        label.set_y(entryNameLabel, entryPrice)
    if not na(entryPriceLabel)
        label.set_x(entryPriceLabel, bar_index)
        label.set_text(entryPriceLabel, f_price(entryPrice))
    if not na(stopPriceLabel)
        label.set_x(stopPriceLabel, bar_index)
        label.set_y(stopPriceLabel, stopPrice)
        label.set_text(stopPriceLabel, f_price(stopPrice))
    if not na(targetPriceLabel)
        label.set_x(targetPriceLabel, bar_index)
        label.set_y(targetPriceLabel, targetPrice)
        label.set_text(targetPriceLabel, f_price(targetPrice))
 
//-----------------------------------------------------------------------------
// 17. TRADE MANAGEMENT
 
//-----------------------------------------------------------------------------
if tradeActive and bar_index > entryBar and calculateLevels and not na(stopPrice) and not na(targetPrice)
    bool stopHit = setupDirection == "LONG" ? low <= stopPrice : high >= stopPrice
    bool targetHit = setupDirection == "LONG" ? high >= targetPrice : low <= targetPrice
    if stopHit and targetHit
        tradeOutcome := stopWinsIfBothTouched ? "STOP HIT" : "TARGET HIT"
        tradeActive := false
        setupStatus := tradeOutcome
        stageText := "TRADE CLOSED"
    else if stopHit
        tradeOutcome := "STOP HIT"
        tradeActive := false
        setupStatus := "STOP HIT"
        stageText := "TRADE CLOSED"
    else if targetHit
        if trailAfterTarget and not na(targetStepDistance) and targetStepDistance > 0
            // Lock the reached target as the new stop and project the next target
            // by the original target-distance step. This is mirrored for LONG/SHORT.
            stopPrice := targetPrice
            targetPrice := setupDirection == "LONG" ? targetPrice + targetStepDistance : targetPrice - targetStepDistance
            targetTrailed := true
            tradeOutcome := "ACTIVE"
            setupStatus := "GO"
            stageText := "TRAILING: TP LOCKED"
        else
            tradeOutcome := "TARGET HIT"
            tradeActive := false
            setupStatus := "TARGET HIT"
            stageText := "TRADE CLOSED"
 
// Confirmed chop exit: allow normal pauses, but exit after sustained proximity
// to both averages plus a flat EMA or repeated price crosses.
if tradeActive and bar_index > entryBar
    if exitOnChop and confirmedTradeChop
        consecutiveTradeChopBars += 1
    else
        consecutiveTradeChopBars := 0
    if exitOnChop and consecutiveTradeChopBars >= chopExitConfirmBars
        tradeOutcome := "CHOP EXIT"
        chopExitPrice := close
        tradeActive := false
        setupStatus := "CHOP EXIT"
        stageText := "EXIT: CONFIRMED CHOP"
        momentumText := "NO FOLLOW-THROUGH"
        // Draw a persistent, BUY/SELL-style label on the exact bar the chop exit triggers.
        chopExitLabel := label.new(bar_index, setupDirection == "LONG" ? high : low, chopExitLabelText + "\n" + f_price(close), style=setupDirection == "LONG" ? label.style_label_down : label.style_label_up, color=chopColor, textcolor=color.black, size=f_textSize(chopExitLabelSizeInput), tooltip="Confirmed chop exit after repeated 9 EMA interactions within the rolling time window plus flat EMA or repeated EMA/VWAP crosses. Close or manage the active position manually.")
else if not tradeActive
    consecutiveTradeChopBars := 0
 
//-----------------------------------------------------------------------------
// 18. PRE-ENTRY STATUS
 
//-----------------------------------------------------------------------------
if not tradeActive and tradeOutcome != "TARGET HIT" and tradeOutcome != "STOP HIT" and tradeOutcome != "CHOP EXIT"
    if not inRegularSession
        setupStatus := "NO SETUP"
        stageText := "OUTSIDE SESSION"
        momentumText := "WAITING"
    else if not inTradeWindow
        setupStatus := "NO SETUP"
        stageText := "OUTSIDE ENTRY WINDOW"
        momentumText := "WAITING"
    else if vwapChop
        setupStatus := "CHOP"
        stageText := (longStage == 1 or shortStage == 1) ? "RECOVERY / CHOP" : "CHOP"
        momentumText := repeatedVWAPCrosses ? "REPEATED VWAP CROSSES" : "FLAT / CHOP"
    else if longStage == 1
        setupStatus := "WAIT"
        stageText := "LONG RECOVERY"
        momentumText := emaRising ? "BUILDING UP" : "RECOVERY"
    else if shortStage == 1
        setupStatus := "WAIT"
        stageText := "SHORT RECOVERY"
        momentumText := emaFalling ? "BUILDING DOWN" : "RECOVERY"
    else
        setupStatus := "WAIT"
        stageText := "WAITING FOR TURN"
        momentumText := emaFlat ? "EMA FLAT" : "MIXED"
if tradeOutcome == "TARGET HIT"
    setupStatus := "TARGET HIT"
if tradeOutcome == "STOP HIT"
    setupStatus := "STOP HIT"
if tradeOutcome == "CHOP EXIT"
    setupStatus := "CHOP EXIT"
    stageText := "EXIT: CONFIRMED CHOP"
 
// Stop-hit continuation diagnostics. Keep STOP HIT as the trade outcome, while
// explaining why a new trend-continuation entry has not yet qualified.
bool shortStopTrendAligned = setupDirection == "SHORT" and ema9 < vwapValue and emaFalling
bool longStopTrendAligned = setupDirection == "LONG" and ema9 > vwapValue and emaRising
bool shortStopRetestRejected = high >= ema9 and close < ema9
bool longStopRetestRejected = low <= ema9 and close > ema9
if not tradeActive and tradeOutcome == "STOP HIT" and allowTrendContinuationAfterStop and stopReentriesToday < maxStopReentriesPerDay and inTradeWindow
    if setupDirection == "SHORT" and shortStopTrendAligned and not shortStopRetestRejected
        stageText := "RE-ENTRY: NO RETEST"
    else if setupDirection == "LONG" and longStopTrendAligned and not longStopRetestRejected
        stageText := "RE-ENTRY: NO RETEST"
    else if setupDirection == "SHORT" and not shortStopTrendAligned
        stageText := "RE-ENTRY: TREND FILTER"
    else if setupDirection == "LONG" and not longStopTrendAligned
        stageText := "RE-ENTRY: TREND FILTER"
 
//-----------------------------------------------------------------------------
// 19. ENTRY SIGNALS
 
//-----------------------------------------------------------------------------
plotshape(showSignalLabels and longSignal, title="Start Late Buy", style=shape.arrowup, location=location.belowbar, color=longColor, size=size.large, text="BUY", textcolor=color.white)
plotshape(showSignalLabels and shortSignal, title="Start Late Sell", style=shape.arrowdown, location=location.abovebar, color=shortColor, size=size.large, text="SELL", textcolor=color.white)
// Print only one early-warning label per active trade. Repeated condition toggles
// or changing chart timeframe must not create a series of warning labels.
bool newChopWarning = tradeActive and activeTradeChopWarning and not chopWarningPrintedThisTrade
if newChopWarning
    chopWarningLabel := label.new(bar_index, high, chopWarningLabelText, style=label.style_label_down, color=chopColor, textcolor=color.black, size=f_textSize(chopExitLabelSizeInput), tooltip="One-time early chop warning for this trade. Persistent directional trends are filtered out. The confirmed chop-exit label appears only if chop conditions persist for the configured confirmation bars.")
    chopWarningPrintedThisTrade := true
if showSignalLabels and longSignal
    label.new(bar_index, low, "BUY\n" + f_price(entryPrice), style=label.style_label_up, color=longColor, textcolor=color.black, size=size.small)
if showSignalLabels and shortSignal
    label.new(bar_index, high, "SELL\n" + f_price(entryPrice), style=label.style_label_down, color=shortColor, textcolor=color.white, size=size.small)
plotshape(showRecoveryMarkers and lowTurn and longStage == 1, title="Potential Long Turn", style=shape.circle, location=location.belowbar, color=longColor, size=size.tiny, text="TURN")
plotshape(showRecoveryMarkers and highTurn and shortStage == 1, title="Potential Short Turn", style=shape.circle, location=location.abovebar, color=shortColor, size=size.tiny, text="TURN")
 
//-----------------------------------------------------------------------------
// 20. ALERTS
 
//-----------------------------------------------------------------------------
alertcondition(longSignal, title="TBStartLate Buy", message="TBStartLate BUY | {{ticker}} | TF {{interval}} | Price ${close} | Bullish recovery entry.")
alertcondition(shortSignal, title="TBStartLate Sell", message="TBStartLate SELL | {{ticker}} | TF {{interval}} | Price ${close} | Bearish recovery entry.")
alertcondition(tradeOutcome == "TARGET HIT" and tradeOutcome[1] != "TARGET HIT", title="TBMFlow Target Hit", message="TBMFlow TARGET HIT | {{ticker}} | TF {{interval}} | Price ${close}.")
alertcondition(tradeOutcome == "STOP HIT" and tradeOutcome[1] != "STOP HIT", title="TBMFlow Stop Hit", message="TBMFlow STOP HIT | {{ticker}} | TF {{interval}} | Price ${close}.")
alertcondition(newChopWarning, title="TBStartLate Chop Warning", message="TBStartLate CHOP WARNING | {{ticker}} | TF {{interval}} | Price ${close} | Repeated 9 EMA interactions in the rolling time window with flat EMA or repeated crosses.")
alertcondition(tradeOutcome == "CHOP EXIT" and tradeOutcome[1] != "CHOP EXIT", title="TBMFlow Confirmed Chop Exit", message="TBMFlow CHOP EXIT | {{ticker}} | TF {{interval}} | Price ${close} | Repeated 9 EMA interactions within the configured rolling time window plus flat EMA or repeated EMA/VWAP crosses persisted for the configured confirmation bars.")
 
//-----------------------------------------------------------------------------
// 21. DASHBOARD
 
//-----------------------------------------------------------------------------
var table dashboard = table.new(f_tablePosition(tablePositionInput), 2, 16, border_width=1)
if barstate.islast
    table.clear(dashboard, 0, 0, 1, 15)
    if showTable
        int r = 0
        if showTableHeader
            table.cell(dashboard, 0, r, "TRADEBEE", bgcolor=tableHeaderBg, text_color=color.white, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, "MOMENTUM FLOW", bgcolor=tableHeaderBg, text_color=color.white, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showStatusRow
            table.cell(dashboard, 0, r, "STATUS", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, setupStatus, bgcolor=f_statusColor(setupStatus), text_color=color.black, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showDirectionRow
            table.cell(dashboard, 0, r, "DIRECTION", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, setupDirection, bgcolor=tableBg, text_color=setupDirection == "LONG" ? longColor : setupDirection == "SHORT" ? shortColor : tableText, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showStageRow
            table.cell(dashboard, 0, r, "SETUP STAGE", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, stageText, bgcolor=tableBg, text_color=setupStatus == "CHOP" ? chopColor : waitColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showEMAValueRow
            table.cell(dashboard, 0, r, "9 EMA", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, f_price(ema9), bgcolor=tableBg, text_color=ema9Color, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showVWAPValueRow
            table.cell(dashboard, 0, r, "VWAP", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, f_price(vwapValue), bgcolor=tableBg, text_color=vwapPlotColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showPriceRow
            table.cell(dashboard, 0, r, "PRICE", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, f_price(close), bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showSessionLowRow
            table.cell(dashboard, 0, r, "DAILY LOW", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, f_price(displayedDailyLow), bgcolor=tableBg, text_color=dailyLowColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showSessionHighRow
            table.cell(dashboard, 0, r, "DAILY HIGH", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, f_price(displayedDailyHigh), bgcolor=tableBg, text_color=dailyHighColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showMomentumRow
            table.cell(dashboard, 0, r, "MOMENTUM", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, momentumText, bgcolor=tableBg, text_color=momentumText == "BUILDING UP" or momentumText == "BULLISH" ? longColor : momentumText == "BUILDING DOWN" or momentumText == "BEARISH" ? shortColor : chopColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showTimeRow
            table.cell(dashboard, 0, r, "ENTRY WINDOW", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, tradeWindowActive ? "OPEN" : "CLOSED", bgcolor=tableBg, text_color=tradeWindowActive ? longColor : noSetupColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showEntryRow
            table.cell(dashboard, 0, r, "ENTRY", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, f_price(entryPrice), bgcolor=tableBg, text_color=entryColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showStopRow
            table.cell(dashboard, 0, r, "STOP LOSS", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, f_price(stopPrice), bgcolor=tableBg, text_color=stopColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showTargetRow
            table.cell(dashboard, 0, r, "TAKE PROFIT", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, f_price(targetPrice), bgcolor=tableBg, text_color=targetColor, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showRRRow
            table.cell(dashboard, 0, r, "REWARD / RISK", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, na(rewardRisk) ? "N/A" : str.tostring(rewardRisk, "#.##") + ":1", bgcolor=tableBg, text_color=not na(rewardRisk) and rewardRisk >= 3 ? goColor : tableText, text_size=f_textSize(tableTextSizeInput))
            r += 1
        if showOutcomeRow
            table.cell(dashboard, 0, r, "TRADE OUTCOME", bgcolor=tableBg, text_color=tableText, text_size=f_textSize(tableTextSizeInput))
            table.cell(dashboard, 1, r, tradeOutcome == "CHOP EXIT" ? "CHOP EXIT (" + f_price(chopExitPrice) + ")" : tradeOutcome, bgcolor=tradeOutcome == "TARGET HIT" or tradeOutcome == "ACTIVE" ? goColor : tradeOutcome == "STOP HIT" ? noSetupColor : tradeOutcome == "CHOP EXIT" ? chopColor : tableBg, text_color=tradeOutcome == "NONE" ? tableText : color.black, text_size=f_textSize(tableTextSizeInput))
            r += 1

← 返回列表