Myth Busting E01 - First 4-Hour Range False Breakout [PyneSys]

PyneSys · strategy · 582 行 · 点赞 16 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
//              [] ##          PyneSys
//           [] [] ## ##
//        [] [] [] ## ## ##
//     [] [] [] [] ## ## ## ##
//  [] [] [] [] [] ## ## ## ## ##
//              || ||
// ============================================================================
// SCRIPT: First 4-Hour Range False Breakout
// SCRIPT AUTHOR: PyneSys
// Copyright (c) 2026 PyneSys LLC
// SPDX-License-Identifier: MPL-2.0
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// STRATEGY CONCEPT: First four-hour range false-breakout reversal.
// IDEA ATTRIBUTION: Data Trader (trading concept only)
//
// DESCRIPTION
// A testable interpretation of the source idea's 5-minute false-breakout setup.
// By default, the range is New York 00:00-04:00, built from the 5-minute bars.
// Wait for a 5-minute close outside its range, followed by a later close strictly
// inside it on the same day. Fade the breakout: long after a downside breakout,
// short after an upside breakout. Stop at the breakout extreme; target 2R by
// default. More than one setup per day is allowed, with one position at a time.
//
// EXPLICIT INTERPRETATIONS
// - The default New York 00:00-04:00 window is aggregated from the 5-minute
//   bars. Native 4-hour bars are an alternative: they retain the instrument's
//   session alignment, and the chart's display timezone does not realign them.
// - America/New_York defines dates and handles daylight saving time.
// - The breakout extreme includes every wick from the first outside close's
//   candle through the re-entry candle, inclusive. Opposite-side breakouts
//   replace the pending setup. An exact touch of a boundary is not re-entry.
// - Entries are simulated at the confirmed re-entry candle's close. Stop and
//   target prices use that close; slippage can change the realized reward/risk.
// - Stops and targets stay fixed. Open trades can continue into the next day;
//   pending setups reset on the selected range calendar date. Re-entries while a trade is open are
//   consumed, rather than queued. A signal close must stay on that setup date.
// - The first observed NY day is warm-up only. A range must be observed from
//   its opening bar. Missing bars are not reconstructed.
//
// OPTIONAL VARIANTS (OUR ADDITIONS, NOT FULLY SPECIFIED SOURCE RULES)
// Reject an entry if its stop distance exceeds a selected ATR multiple, a
// percentage of the opening range, or a percentage of the previous observed
// NY day's range. ATR is frozen on the bar before the breakout begins. The
// previous-day range uses the last observed completed NY date, not an exchange
// daily candle. Missing/zero reference values reject the filtered setup.
// Threshold defaults are hypotheses, not optimized or validated parameters.
// A minimum-breakout filter measures the greatest confirmed close beyond the
// breached boundary, using pre-breakout ATR or opening-range width. Wicks alone
// do not satisfy this filter. Equality with the threshold qualifies.
// A separate target cap limits profit to the opposite range boundary. When the
// cap binds, derive the stop from that target distance / rewardRisk instead of
// the breakout extreme. This explicitly changes the source's stop placement.
// Comment-derived research switches add EMA50 direction filters, completed 15m
// signals, NY entry-time and weekday filters, fixed-price stops, and midpoint
// targets. These are explicit interpretations of incomplete comments, not
// evidence of profitability. Default switches preserve the source baseline.
// Fixed-clock UTC and 09:00-13:00 windows reset setups on their own local date.
// No discretionary resistance/order-block stop replacement is implemented:
// the source supplies no reproducible definition for it or for "too large".
//
// BACKTEST SETTINGS
// Commission and slippage are zero for a cross-market gross research baseline.
// Broker, venue and instrument costs differ; no universal cost preset is assumed.
// Gross results exclude costs and are not achievable net returns. Set your own
// commission and slippage in Properties before assessing performance. Spread,
// funding and other applicable costs need an explicit model and are not
// automatically included. Separate cost-sensitivity reports are not these fills.
// Use standard 5-minute OHLC candles. Position size defaults to 10% of equity;
// the source does not specify sizing. Adjust it in Properties. Filter defaults
// to None. Commission and slippage default to zero: configure market-specific
// costs in Properties.
// Same-bar stop/target ordering follows the platform's broker emulator; lower
// timeframe data / Bar Magnifier may change results. This script is a research
// implementation, not evidence that the source's profitability claim holds.
// ============================================================================
 
// Mechanical reading of a first-range false-breakout lesson, not the creator's
// exact system. Range boundaries, re-entry, stop and target details are our
// explicit research assumptions. Only confirmed candle closes make decisions.
//
// Read from top to bottom: the default setup (the New York 00:00-04:00 range, a
// 5-minute close outside it, a later close back inside, a stop at the breakout
// extreme and a 2R target) is complete once section 6 has found the re-entry
// and section 8 has planned its levels. Section 7 holds the optional comment
// filters; they only add a gate, and never change the conditions above them.
//
// Evaluate each candle once it closes. process_orders_on_close lets the broker
// emulator fill a new market entry at that close, which is our price reference.
// pyramiding=0 prevents adding to an existing position. The 10% equity setting
// sizes the position; it does not mean that 10% of equity is at risk at the stop.
strategy("PyneSys E01 - First 4-Hour Range False Breakout", shorttitle="PyneSysE01",
     overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity,
     default_qty_value=10, process_orders_on_close=true,
     calc_on_every_tick=false, calc_on_order_fills=false,
     commission_type=strategy.commission.percent, commission_value=0, slippage=0)
 
// ---------------------------------------------------------------------------
// 1. Inputs
// ---------------------------------------------------------------------------
// Choose a range interpretation and a reward/risk target. Native bars follow
// the instrument's sessions. The fixed NY window instead uses explicit clock
// boundaries for every instrument. EST means fixed UTC-5; New York follows
// daylight saving time. UTC uses its own daily reset.
string rangeMode = input.string("New York 00:00-04:00", "Range definition",
     options=["First native 4h candle", "New York 00:00-04:00", "UTC 00:00-04:00", "New York 09:00-13:00", "Fixed EST 09:00-13:00"], group="Setup",
     tooltip="The default NY window follows daylight saving time. Native bars use the symbol's session alignment.")
// R is the distance from the signal close to the stop, measured in price units.
// At 2R, an entry at 100 with a stop at 95 has a target at 110, before costs.
float rewardRisk = input.float(2.0, "Reward / risk", minval=1.0, step=0.25, group="Setup")
int stopBufferTicks = input.int(0, "Stop buffer (ticks)", minval=0, group="Setup",
     tooltip="Zero puts the stop exactly at the breakout extreme.")
bool capTargetToRange = input.bool(false, "Cap target at opposite range boundary", group="Research variants",
     tooltip="If the original target exceeds the far boundary, cap it and derive the stop from target distance / reward-risk.")
string minimumBreakoutMode = input.string("None", "Minimum confirmed breakout", group="Research variants",
     options=["None", "ATR", "Opening range %"],
     tooltip="Maximum confirmed close beyond the breached boundary; wick-only excursions do not count.")
float minimumBreakoutAtr = input.float(0.25, "Minimum breakout / pre-breakout ATR", minval=0.0,
     step=0.05, group="Research variants")
float minimumBreakoutPercent = input.float(5.0, "Minimum breakout / opening range (%)", minval=0.0,
     step=1.0, group="Research variants")
 
// Comment suggestions are separate hypotheses, not fully specified source rules.
// EMA direction means entry close above the selected EMA for longs, below for
// shorts. The 15m and 1h choices are our proxies for undefined trend rules.
string trendFilter = input.string("None", "EMA50 trend filter", group="Comment variants",
     options=["None", "5 minutes", "15 minutes", "1 hour"])
string signalTimeframe = input.string("5 minutes", "Breakout / re-entry timeframe", group="Comment variants",
     options=["5 minutes", "15 minutes"],
     tooltip="Keep the chart at 5 minutes. The 15-minute option requires complete aggregated candles; exits still run on 5-minute bars.")
string entryTimeFilter = input.string("None", "Entry time filter (New York)", group="Comment variants",
     options=["None", "Skip 09:30-10:30", "From 10:00"],
     tooltip="Checked at the signal close. Does not force an exit at the end of the session.")
bool weekdaysOnly = input.bool(false, "Weekday entries only (New York)", group="Comment variants")
string stopMode = input.string("Breakout extreme", "Stop placement", group="Comment variants",
     options=["Breakout extreme", "Fixed price distance"])
float fixedStopDistance = input.float(10.0, "Fixed stop distance (price units)", minval=0.00001,
     group="Comment variants", tooltip="For GOLD, the tests used 1.0 and 10.0. Pip terminology is ambiguous; this input is an explicit price distance. Target uses Reward / risk.")
bool midpointTarget = input.bool(false, "Target opening-range midpoint", group="Comment variants",
     tooltip="Retain the selected stop. Skip entries already beyond the midpoint. Takes precedence over the opposite-boundary target cap.")
// Test one change at a time to reproduce the report. Combining switches creates
// another hypothesis. Fixed stops ignore the structural stop buffer; midpoint
// targets retain that selected stop, so their reward/risk is variable.
 
// These alternatives define how wide a stop we are willing to accept. They
// change which setups are traded. They check the final planned stop distance,
// including any stop derived from the optional target cap.
// ATR adapts the limit to volatility; the percentages use a reference range.
string stopFilter = input.string("None", "Maximum stop distance",
     options=["None", "ATR", "Opening range %", "Previous NY day %"], group="Stop filter",
     tooltip="Filtered variants skip oversized setups. They never move the stop closer.")
int atrLength = input.int(14, "ATR length (5-minute bars)", minval=1, group="Stop filter")
float atrMultiple = input.float(2.0, "Maximum stop / pre-breakout ATR", minval=0.1,
     step=0.1, group="Stop filter")
float openingRangePercent = input.float(50.0, "Maximum stop / opening range (%)",
     minval=0.1, step=5.0, group="Stop filter")
float previousDayPercent = input.float(25.0, "Maximum stop / previous NY day (%)",
     minval=0.1, step=5.0, group="Stop filter")
 
bool showRange = input.bool(true, "Show completed range", group="Display")
bool showTradeLevels = input.bool(true, "Show stop and target", group="Display")
bool showRejected = input.bool(true, "Mark filter rejections", group="Display")
 
// ---------------------------------------------------------------------------
// 2. Volatility and the confirmed higher-timeframe candles
// ---------------------------------------------------------------------------
// ATR on 5-minute bars is the volatility yardstick of the optional filters.
float atrValue = ta.atr(atrLength)
 
// Aggregate UTC-aligned 15m and 1h candles ourselves. Only consecutive, complete
// 5m groups qualify. This avoids using a forming higher-timeframe EMA or copying
// its eventual close into earlier bars. Each EMA starts at its first close and
// requires 50 completed observations before it can admit a trade.
var float ema5 = na
var int count5 = 0
if barstate.isconfirmed
    ema5 := na(ema5) ? close : ema5 + 2.0 / 51.0 * (close - ema5)
    count5 += 1
 
int bucket15 = int(math.floor(time / 900000.0))
var int count15 = 0
var int groupCount15 = 0
var float groupHigh15 = na
var float groupLow15 = na
var float ema15 = na
bool completed15 = false
if barstate.isconfirmed
    if na(bucket15[1]) or bucket15 != bucket15[1] or time != time[1] + 300000
        groupCount15 := 0
        groupHigh15 := high
        groupLow15 := low
    groupCount15 += 1
    groupHigh15 := math.max(groupHigh15, high)
    groupLow15 := math.min(groupLow15, low)
    completed15 := (time + 300000) % 900000 == 0 and groupCount15 == 3
    if completed15
        count15 += 1
        ema15 := na(ema15) ? close : ema15 + 2.0 / 51.0 * (close - ema15)
 
int bucket60 = int(math.floor(time / 3600000.0))
var int count60 = 0
var int groupCount60 = 0
var float groupHigh60 = na
var float groupLow60 = na
var float ema60 = na
bool completed60 = false
if barstate.isconfirmed
    if na(bucket60[1]) or bucket60 != bucket60[1] or time != time[1] + 300000
        groupCount60 := 0
        groupHigh60 := high
        groupLow60 := low
    groupCount60 += 1
    groupHigh60 := math.max(groupHigh60, high)
    groupLow60 := math.min(groupLow60, low)
    completed60 := (time + 300000) % 3600000 == 0 and groupCount60 == 12
    if completed60
        count60 += 1
        ema60 := na(ema60) ? close : ema60 + 2.0 / 51.0 * (close - ema60)
 
// ---------------------------------------------------------------------------
// 3. Time boundaries: New York dates and the selected range window
// ---------------------------------------------------------------------------
// Turn a timestamp into a YYYYMMDD key in New York time. Comparing these keys
// detects a local date change even when the feed is UTC.
nyDate(int dateTime) =>
    year(dateTime, "America/New_York") * 10000 +
     month(dateTime, "America/New_York") * 100 + dayofmonth(dateTime, "America/New_York")
 
// The setup is defined on 5-minute closes. Refuse other chart timeframes rather
// than silently testing a different entry rule.
if barstate.isfirst and (not timeframe.isminutes or timeframe.multiplier != 5)
    runtime.error("This strategy requires a 5-minute chart.")
 
int currentDay = nyDate(time)
// [1] refers to the previous chart bar. na means a value is not available yet,
// which is how we also recognize the first bar in the loaded history.
bool newDay = na(currentDay[1]) or currentDay != currentDay[1]
var int firstDataDay = currentDay
// These timestamps identify the native 4-hour bar containing this chart bar.
// Its boundaries come from the symbol's session, not the chart display timezone.
int nativeOpen = time("240")
int nativeClose = time_close("240")
int nativeDay = nyDate(nativeOpen)
// Fixed windows use their own calendar date; UTC and fixed EST do not follow
// New York daylight saving time. Native bars retain their original NY grouping.
string setupZone = switch rangeMode
    "First native 4h candle" => "America/New_York"
    "New York 00:00-04:00" => "America/New_York"
    "UTC 00:00-04:00" => "UTC"
    "New York 09:00-13:00" => "America/New_York"
    "Fixed EST 09:00-13:00" => "GMT-5"
int setupDay = year(time, setupZone) * 10000 + month(time, setupZone) * 100 + dayofmonth(time, setupZone)
bool newSetupDay = na(setupDay[1]) or setupDay != setupDay[1]
var int firstSetupDay = setupDay
int startHour = switch rangeMode
    "First native 4h candle" => 0
    "New York 00:00-04:00" => 0
    "UTC 00:00-04:00" => 0
    "New York 09:00-13:00" => 9
    "Fixed EST 09:00-13:00" => 9
int fixedOpen = timestamp(setupZone, year(time, setupZone), month(time, setupZone), dayofmonth(time, setupZone), startHour, 0)
int fixedClose = timestamp(setupZone, year(time, setupZone), month(time, setupZone), dayofmonth(time, setupZone), startHour + 4, 0)
// Decisions use the actual five-minute decision close, even if feed session
// metadata truncates the last bar's time_close to 23:59:59. A close confirmed
// exactly at local midnight belongs to the next setup date.
int decisionClose = time + 300000
int closeDay = year(decisionClose, setupZone) * 10000 + month(decisionClose, setupZone) * 100 + dayofmonth(decisionClose, setupZone)
bool sameDayClose = closeDay == setupDay
 
// ---------------------------------------------------------------------------
// 4. Previous-day reference: the last completed New York day's range
// ---------------------------------------------------------------------------
// Accumulate the chart's highs and lows by NY date. var initializes a value
// once and preserves it across bars; := updates it. This grouping may differ
// from an exchange's daily-candle boundaries.
var float dayHigh = na
var float dayLow = na
var float previousDayRange = na
if barstate.isconfirmed
    if newDay
        // Save the day that just ended before starting today's accumulation.
        // Discard the first observed day as a reference: history may start
        // partway through it, so its measured range may be incomplete.
        previousDayRange := currentDay[1] != firstDataDay ? dayHigh - dayLow : na
        dayHigh := high
        dayLow := low
    else
        dayHigh := math.max(dayHigh, high)
        dayLow := math.min(dayLow, low)
 
// ---------------------------------------------------------------------------
// 5. The range: the first 4-hour candle of the day
// ---------------------------------------------------------------------------
// rangeReady allows signals only after the selected reference candle closes.
// A pending range belongs to its range-calendar day and resets with it.
var float rangeHigh = na
var float rangeLow = na
var int rangeEnd = na
var bool collectingRange = false
var bool rangeReady = false
bool nativeRange = rangeMode == "First native 4h candle"
// Update only on confirmed closes. A forming candle can move outside the range
// and then return; its temporary close is not a signal.
if barstate.isconfirmed
    if newSetupDay
        rangeHigh := na
        rangeLow := na
        rangeEnd := na
        collectingRange := false
        rangeReady := false
 
    // The first native bucket whose opening date differs from the preceding
    // bucket's date is today's reference candle. Requiring its exact opening
    // bar avoids starting with a partially observed candle after a data gap.
    bool firstNativeBar = not na(nativeOpen[1]) and nativeOpen != nativeOpen[1] and
         nativeDay != nyDate(nativeOpen[1]) and nativeDay == setupDay and time == nativeOpen
    bool startRange = nativeRange ? firstNativeBar : time == fixedOpen
 
    if setupDay != firstSetupDay and startRange
        // Skip the first observed date entirely as warm-up. Seed the range
        // from its opening bar, then extend it as later bars arrive.
        rangeHigh := high
        rangeLow := low
        rangeEnd := nativeRange ? nativeClose : fixedClose
        collectingRange := true
 
    if collectingRange
        // Include all observed highs and lows before the selected window ends.
        // Freeze the result once its closing time is reached. A zero-width
        // range cannot provide meaningful inside/outside boundaries.
        if time < rangeEnd
            rangeHigh := math.max(rangeHigh, high)
            rangeLow := math.min(rangeLow, low)
        if time_close >= rangeEnd
            collectingRange := false
            rangeReady := rangeHigh > rangeLow
 
// ---------------------------------------------------------------------------
// 6. The false breakout: a close outside the range, then a close back inside
// ---------------------------------------------------------------------------
// The signal candle is the 5-minute chart bar. The 15-minute comment variant
// replaces it with the complete aggregated candle from section 2; its signal
// starts 10 minutes before this bar, and exits still run on 5-minute bars.
bool use15 = signalTimeframe == "15 minutes"
bool signalReady = not use15 or completed15
float signalHigh = use15 ? groupHigh15 : high
float signalLow = use15 ? groupLow15 : low
int signalOpen = use15 ? time - 600000 : time
 
// breakoutSide: 0 = no pending setup, +1 = above the range, -1 = below it.
// Keep the episode's extreme prices and its starting ATR until re-entry.
var int breakoutSide = 0
var float breakoutHigh = na
var float breakoutLow = na
var float breakoutAtr = na
var float breakoutDepth = na
// These values start fresh on every bar. A re-entry exists only on the candle
// where it occurs; fadeLong says which side it trades, and the episode values
// hand its extremes, frozen ATR and confirmed depth to sections 7 and 8.
bool reEntry = false
bool fadeLong = false
float episodeHigh = na
float episodeLow = na
float episodeAtr = na
float candidateBreakoutDepth = na
 
if barstate.isconfirmed
    if newSetupDay
        // A pending breakout belongs to its range-calendar day. Reset it with
        // the range, but leave any open position's stop and target intact.
        breakoutSide := 0
        breakoutHigh := na
        breakoutLow := na
        breakoutAtr := na
        breakoutDepth := na
 
    // The reference range must be complete before the breakout bar opens, and
    // the signal close must stay on that setup date.
    if rangeReady and signalOpen >= rangeEnd and sameDayClose and signalReady
        bool aboveRange = close > rangeHigh
        bool belowRange = close < rangeLow
        // Strict inequalities keep a close exactly on either boundary from
        // being counted as a return inside the range. Wicks alone never qualify.
        bool insideRange = close > rangeLow and close < rangeHigh
 
        // A jump through both boundaries starts a fresh opposite-side episode.
        bool startBreakout = (aboveRange and breakoutSide != 1) or
             (belowRange and breakoutSide != -1)
        if startBreakout
            breakoutSide := aboveRange ? 1 : -1
            breakoutHigh := signalHigh
            breakoutLow := signalLow
            // Freeze ATR from before this breakout candle. Otherwise a large
            // breakout could inflate the threshold used to judge its own stop.
            breakoutAtr := use15 ? atrValue[3] : atrValue[1]
            breakoutDepth := aboveRange ? close - rangeHigh : rangeLow - close
        else if breakoutSide != 0
            // Track every wick in the episode, including the re-entry candle.
            // A later, deeper excursion therefore moves the prospective stop.
            breakoutHigh := math.max(breakoutHigh, signalHigh)
            breakoutLow := math.min(breakoutLow, signalLow)
            // Track confirmed closes rather than intrabar wicks. The re-entry
            // close is inside, so it cannot increase the breakout's depth.
            float closeDepth = breakoutSide == 1 ? close - rangeHigh : rangeLow - close
            breakoutDepth := math.max(breakoutDepth, closeDepth)
 
            if insideRange
                // Fade the move: a downside breakout gives a long setup, and
                // an upside breakout gives a short setup.
                reEntry := true
                fadeLong := breakoutSide == -1
                episodeHigh := breakoutHigh
                episodeLow := breakoutLow
                episodeAtr := breakoutAtr
                candidateBreakoutDepth := breakoutDepth
                // Every confirmed re-entry consumes the episode, even if a
                // position is already open. A skipped setup is not queued for
                // a delayed entry when the existing trade eventually closes.
                breakoutSide := 0
                breakoutHigh := na
                breakoutLow := na
                breakoutAtr := na
                breakoutDepth := na
 
// ---------------------------------------------------------------------------
// 7. Optional comment filters
// ---------------------------------------------------------------------------
// Each filter is one extra gate on a re-entry; "None" passes every signal.
// The EMA direction gate reads the selected confirmed EMA50 from section 2.
float selectedEma = switch trendFilter
    "5 minutes" => count5 >= 50 ? ema5 : na
    "15 minutes" => count15 >= 50 ? ema15 : na
    "1 hour" => count60 >= 50 ? ema60 : na
    => na
bool trendLong = trendFilter == "None" or (not na(selectedEma) and close > selectedEma)
bool trendShort = trendFilter == "None" or (not na(selectedEma) and close < selectedEma)
// Entry time and weekday gates are checked at the New York decision close.
int decisionMinute = hour(decisionClose, "America/New_York") * 60 + minute(decisionClose, "America/New_York")
int decisionWeekday = dayofweek(decisionClose, "America/New_York")
bool passesTime = switch entryTimeFilter
    "None" => true
    "Skip 09:30-10:30" => decisionMinute < 570 or decisionMinute >= 630
    "From 10:00" => decisionMinute >= 600
bool passesWeekday = not weekdaysOnly or (decisionWeekday != dayofweek.saturday and decisionWeekday != dayofweek.sunday)
// A minimum confirmed breakout compares the deepest close beyond the breached
// boundary with pre-breakout ATR or the opening-range width. Wicks alone do
// not count, and equality with the threshold qualifies.
float minimumBreakout = switch minimumBreakoutMode
    "ATR" => episodeAtr * minimumBreakoutAtr
    "Opening range %" => (rangeHigh - rangeLow) * minimumBreakoutPercent / 100.0
    => na
float candidateMinimumBreakout = reEntry ? minimumBreakout : na
bool passesMinimum = minimumBreakoutMode == "None" or
     (not na(candidateMinimumBreakout) and candidateMinimumBreakout >= 0 and candidateBreakoutDepth >= candidateMinimumBreakout)
// A maximum stop distance converts the chosen reference into a price distance.
// For example, 50% of a 20-point opening range allows 10 points. Section 8
// compares it with the final planned stop.
float maximumStop = switch stopFilter
    "ATR" => episodeAtr * atrMultiple
    "Opening range %" => (rangeHigh - rangeLow) * openingRangePercent / 100.0
    "Previous NY day %" => previousDayRange * previousDayPercent / 100.0
    => na
float candidateMaximum = reEntry ? maximumStop : na
 
// ---------------------------------------------------------------------------
// 8. Orders
// ---------------------------------------------------------------------------
// Trade levels are separate from setup state, so an open trade can keep its
// original stop and target even after the daily range has been reset.
var float activeStop = na
var float activeTarget = na
// Markers appear only on the candle where a decision occurs.
bool longEntry = false
bool shortEntry = false
bool rejectedLong = false
bool rejectedShort = false
float candidateStopDistance = na
 
if barstate.isconfirmed and strategy.position_size == 0
    // Once a position has closed, remove its displayed levels.
    activeStop := na
    activeTarget := na
 
if reEntry
    // The default stop sits at the breakout extreme; the optional buffer moves
    // it farther out by ticks converted to price units. The fixed-distance
    // comment variant replaces it with an explicit price distance.
    float stopPrice = switch stopMode
        "Breakout extreme" => fadeLong ? episodeLow - stopBufferTicks * syminfo.mintick : episodeHigh + stopBufferTicks * syminfo.mintick
        "Fixed price distance" => math.round_to_mintick(fadeLong ? close - fixedStopDistance : close + fixedStopDistance)
    // Measure the distance from the entry reference to that stop. Both long
    // and short formulas produce a positive distance.
    candidateStopDistance := fadeLong ? close - stopPrice : stopPrice - close
    float targetPrice = math.round_to_mintick(fadeLong ? close + rewardRisk * candidateStopDistance :
         close - rewardRisk * candidateStopDistance)
    float oppositeBoundary = fadeLong ? rangeHigh : rangeLow
    bool targetExceedsRange = fadeLong ? targetPrice > oppositeBoundary : targetPrice < oppositeBoundary
    if capTargetToRange and not midpointTarget and targetExceedsRange
        // For entry 100, far boundary 110, and 2R: target=110, stop=95. The
        // structural extreme may be farther away. Round to a tradable tick;
        // tiny distances can change the realized ratio slightly or fail the
        // minimum-tick check.
        targetPrice := oppositeBoundary
        float cappedTargetDistance = math.abs(targetPrice - close)
        stopPrice := math.round_to_mintick(fadeLong ? close - cappedTargetDistance / rewardRisk :
             close + cappedTargetDistance / rewardRisk)
        candidateStopDistance := math.abs(close - stopPrice)
    if midpointTarget
        // Keep the chosen stop. A target behind the entry is not
        // profit-taking, so the signed distance check rejects it.
        targetPrice := math.round_to_mintick((rangeHigh + rangeLow) / 2.0)
    // Require at least one tradable tick of distance. With a maximum-stop
    // filter enabled, an unavailable or zero reference rejects the setup;
    // equality with a valid maximum is accepted.
    bool validDistance = candidateStopDistance >= syminfo.mintick and (fadeLong ? targetPrice - close : close - targetPrice) >= syminfo.mintick
    bool passesFilter = stopFilter == "None" or
         (not na(candidateMaximum) and candidateMaximum > 0 and candidateStopDistance <= candidateMaximum)
    bool passesTrend = fadeLong ? trendLong : trendShort
    if strategy.position_size == 0 and validDistance
        if passesFilter and passesMinimum and passesTrend and passesTime and passesWeekday
            // Fix both levels when the signal is accepted.
            activeStop := stopPrice
            activeTarget := targetPrice
            if fadeLong
                // Submit the entry and its protective bracket in the same
                // calculation. from_entry ties this exit to its entry ID.
                longEntry := true
                strategy.entry("Long", strategy.long)
                strategy.exit("Long exit", from_entry="Long", stop=activeStop, limit=activeTarget)
            else
                shortEntry := true
                strategy.entry("Short", strategy.short)
                strategy.exit("Short exit", from_entry="Short", stop=activeStop, limit=activeTarget)
        else
            // Rejection markers explain why a valid price pattern did not
            // become a trade. Filters reject setups; only the selected stop
            // rule or target cap sets its level.
            rejectedLong := fadeLong
            rejectedShort := not fadeLong
 
// Maintain the accepted bracket while its trade is open. Reusing the fixed
// levels keeps this a static stop/target strategy rather than a trailing one.
if barstate.isconfirmed
    if strategy.position_size > 0
        strategy.exit("Long exit", from_entry="Long", stop=activeStop, limit=activeTarget)
    if strategy.position_size < 0
        strategy.exit("Short exit", from_entry="Short", stop=activeStop, limit=activeTarget)
 
// ---------------------------------------------------------------------------
// 9. Chart explanations and research diagnostics
// ---------------------------------------------------------------------------
// Show the completed reference range, accepted trade levels, entry markers,
// and filter rejections. na hides an unavailable level; range lines leave gaps
// across hidden intervals. Separate stop/target dots keep successive trade
// brackets visually distinct on a crowded chart.
plot(showRange and rangeReady ? rangeHigh : na, "Range high", color=color.new(color.teal, 15), style=plot.style_linebr)
plot(showRange and rangeReady ? rangeLow : na, "Range low", color=color.new(color.maroon, 15), style=plot.style_linebr)
plot(showTradeLevels ? activeStop : na, "Stop", color=color.red, style=plot.style_circles, linewidth=1, join=false)
plot(showTradeLevels ? activeTarget : na, "Target", color=color.green, style=plot.style_circles, linewidth=1, join=false)
plotshape(longEntry, title="Long entry", style=shape.triangleup, location=location.belowbar,
     color=color.green, size=size.small, text="L")
plotshape(shortEntry, title="Short entry", style=shape.triangledown, location=location.abovebar,
     color=color.red, size=size.small, text="S")
plotshape(showRejected and rejectedLong, title="Rejected long", style=shape.xcross,
     location=location.belowbar, color=color.orange, size=size.tiny)
plotshape(showRejected and rejectedShort, title="Rejected short", style=shape.xcross,
     location=location.abovebar, color=color.orange, size=size.tiny)
// Data Window values let a reader inspect the filter calculation on a re-entry
// candle: compare the candidate stop distance with the maximum allowed distance.
// Frozen ATR is visible while an episode is pending, before it is consumed.
plot(candidateStopDistance, "Candidate stop distance", display=display.data_window)
plot(candidateBreakoutDepth, "Confirmed breakout depth", display=display.data_window)
plot(candidateMinimumBreakout, "Minimum required breakout", display=display.data_window)
plot(candidateMaximum, "Maximum allowed stop", display=display.data_window)
plot(previousDayRange, "Previous NY day range", display=display.data_window)
plot(breakoutSide != 0 ? breakoutAtr : na, "Frozen breakout ATR", display=display.data_window)
 
// Expose the actual confirmed EMA used by the optional direction filter.
plot(trendFilter != "None" ? selectedEma : na, "Confirmed EMA50 filter", color=color.orange)

← 返回列表