CA Demand Reclaim & Trendline Breakout Strategy v1

Crypto_Andy_ · strategy · 589 行 · 点赞 31 · TradingView 原页

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

Pine Script

//@version=6
// CA Demand Reclaim & Trendline Breakout Strategy v1
// Changelog: v1 - initial build: demand-zone defence -> trendline + EMA-cluster reclaim -> retest, with structural targets.
//
// Symbol-agnostic: every level comes from confirmed swing pivots and every distance is an ATR multiple,
// so the same source runs on BTC, ETH, SOL, XRP or any other symbol. Per-coin calibration happens in inputs.
//   Demand zone : band above the latest confirmed swing low; later swing lows inside it count as extra touches.
//   Trendline   : line through the last two confirmed LOWER swing highs (descending resistance).
//   Breakout    : after a recent touch of the demand zone, a confirmed close above BOTH the trendline (+ buffer)
//                 and the EMA cluster. One breakout event per trendline.
//   Retest      : after the breakout and a move away, price returns to the reclaimed level, holds it and closes bullish
//                 before the setup expires. One trade per breakout event.
//   Exits       : swing / zone / ATR / percent stop; structural targets (next swing high, then the trendline origin)
//                 or R multiple / percent; TP1 + break-even, optional ATR trail, close on a sustained break of the zone.
//   Short side  : exact mirror (supply zone, ascending trendline of higher lows, close below the EMA cluster).
 
strategy("CA Demand Reclaim & Trendline Breakout Strategy v1", shorttitle="CA DRTB v1", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, margin_long=100, margin_short=100, commission_type=strategy.commission.percent, commission_value=0.04, slippage=2, pyramiding=0, max_labels_count=500, max_lines_count=500)
 
// ───────────── Inputs: direction and setups ─────────────
string gDir = "Direction and setups"
string tradeDir     = input.string("Long only", "Trade direction", options=["Long only", "Short only", "Long & Short"], group=gDir, tooltip="Default follows a bullish demand-defence thesis. The short side is a full mirror and can be enabled here.")
bool   useBrkEntry  = input.bool(true, "Breakout entry (confirmed close)", group=gDir, tooltip="Enter on the bar that closes above both the trendline and the EMA cluster.")
bool   useRtEntry   = input.bool(true, "Retest entry (conservative)", group=gDir, tooltip="Enter when price comes back to the reclaimed level, holds it and closes in the breakout direction.")
int    cooldownBars = input.int(6, "Cooldown after exit (bars)", minval=0, maxval=100, group=gDir)
 
// ───────────── Inputs: backtest range ─────────────
string gBt = "Backtest range"
bool useDateRange = input.bool(false, "Limit entries to a date range", group=gBt, tooltip="Gates new entries only; open trades still exit normally.")
int  rangeStart   = input.time(timestamp("01 Jan 2023 00:00 +0000"), "Range start", group=gBt)
int  rangeEnd     = input.time(timestamp("31 Dec 2099 00:00 +0000"), "Range end", group=gBt)
 
// ───────────── Inputs: zones ─────────────
string gZone = "Demand / supply zones"
int   pivotLen     = input.int(5, "Swing pivot length (bars each side)", minval=2, maxval=50, group=gZone, tooltip="A swing is confirmed this many bars after it forms; it is used only from the confirmation bar (no lookahead).")
float zoneAtr      = input.float(0.8, "Zone depth from the swing (ATR)", minval=0.1, maxval=10.0, step=0.1, group=gZone, tooltip="Demand zone = swing low up to this many ATR above it (supply: mirror).")
float zoneBufAtr   = input.float(0.15, "Zone buffer beyond the swing (ATR)", minval=0.0, maxval=5.0, step=0.05, group=gZone)
float clusterAtr   = input.float(0.8, "Repeat-touch tolerance (ATR)", minval=0.1, maxval=10.0, step=0.1, group=gZone, tooltip="A new swing low this close to the zone's swing counts as another touch instead of starting a new zone.")
int   minTouches   = input.int(1, "Minimum swing touches", minval=1, maxval=10, group=gZone, tooltip="1 = any confirmed swing low. 2 or more = the zone must already have held that many swing lows.")
int   zoneMaxAge   = input.int(300, "Zone max age (bars)", minval=10, maxval=2000, group=gZone)
int   touchWindow  = input.int(48, "Breakout must follow a zone touch within (bars)", minval=1, maxval=500, group=gZone)
int   fromAboveLen = input.int(10, "Touch counts if price closed outside the zone within (bars)", minval=1, maxval=100, group=gZone, tooltip="Makes sure the touch is a pullback into the zone, not price drifting inside it.")
bool  useManual    = input.bool(false, "Use manual zones", group=gZone, tooltip="Replaces the auto zones from the date below. Leave a pair at 0 to disable that side.")
float manDzTop     = input.float(0.0, "Manual demand top (0 = off)", minval=0.0, group=gZone)
float manDzBot     = input.float(0.0, "Manual demand bottom (0 = off)", minval=0.0, group=gZone)
float manSzTop     = input.float(0.0, "Manual supply top (0 = off)", minval=0.0, group=gZone)
float manSzBot     = input.float(0.0, "Manual supply bottom (0 = off)", minval=0.0, group=gZone)
int   manualFrom   = input.time(timestamp("01 Oct 2026 00:00 +0000"), "Manual zones active from", group=gZone)
 
// ───────────── Inputs: trendline ─────────────
string gTl = "Trendline"
bool  requireTl  = input.bool(true, "Require trendline break", group=gTl, tooltip="Long: close above the line through the last two lower swing highs. Short: close below the line through the last two higher swing lows.")
float minStepAtr = input.float(0.5, "Min step between the two swings (ATR)", minval=0.0, maxval=20.0, step=0.1, group=gTl, tooltip="The second swing high must be at least this much lower than the first (short: higher).")
int   tlMaxAge   = input.int(150, "Trendline max age after its 2nd swing (bars)", minval=10, maxval=450, group=gTl)
 
// ───────────── Inputs: triggers ─────────────
string gTrg = "Triggers"
float breakAtr     = input.float(0.1, "Min close beyond the trendline (ATR)", minval=0.0, maxval=5.0, step=0.05, group=gTrg)
bool  requireEma   = input.bool(true, "Require close beyond the EMA cluster", group=gTrg, tooltip="Long: close above both EMAs. Short: close below both. Keep at least one of the two trigger requirements on.")
int   emaFastLen   = input.int(21, "Cluster EMA fast", minval=2, group=gTrg)
int   emaSlowLen   = input.int(55, "Cluster EMA slow", minval=3, group=gTrg)
bool  useVolume    = input.bool(false, "Require volume above average", group=gTrg, tooltip="Skipped automatically on symbols without volume data.")
int   volLen       = input.int(20, "Volume average length", minval=2, group=gTrg)
float volMult      = input.float(1.2, "Volume multiple", minval=0.5, maxval=10.0, step=0.1, group=gTrg)
float retestTolAtr = input.float(0.4, "Retest zone half-width (ATR)", minval=0.05, maxval=5.0, step=0.05, group=gTrg)
int   retestExpiry = input.int(24, "Retest expiry (bars after breakout)", minval=2, maxval=500, group=gTrg)
 
// ───────────── Inputs: filters ─────────────
string gFlt = "Filters"
int   atrLen         = input.int(14, "ATR length", minval=1, group=gFlt)
int   rsiLen         = input.int(14, "RSI length", minval=2, group=gFlt)
bool  useRsi         = input.bool(true, "Use RSI band", group=gFlt, tooltip="Momentum present but not overheated.")
float rsiLongMin     = input.float(45.0, "Long: RSI min", minval=0, maxval=100, group=gFlt)
float rsiLongMax     = input.float(75.0, "Long: RSI max", minval=0, maxval=100, group=gFlt)
float rsiShortMin    = input.float(25.0, "Short: RSI min", minval=0, maxval=100, group=gFlt)
float rsiShortMax    = input.float(55.0, "Short: RSI max", minval=0, maxval=100, group=gFlt)
bool  useMacd        = input.bool(true, "Use MACD histogram", group=gFlt, tooltip="Long: histogram above zero or rising. Short: below zero or falling.")
int   macdFast       = input.int(12, "MACD fast", minval=1, group=gFlt)
int   macdSlow       = input.int(26, "MACD slow", minval=2, group=gFlt)
int   macdSig        = input.int(9, "MACD signal", minval=1, group=gFlt)
int   maLongLen      = input.int(200, "MA long (EMA)", minval=10, group=gFlt)
float maxChaseAtr    = input.float(1.5, "Max close beyond trigger level (ATR)", minval=0.1, maxval=10.0, step=0.1, group=gFlt, tooltip="Skips entries that already ran away from the level. Raise it for coins with large impulse candles.")
bool  useTrendFilter = input.bool(false, "Require trend side of MA long", group=gFlt, tooltip="Off: MA long is visual regime context only. On: longs only above it, shorts only below it.")
 
// ───────────── Inputs: exits ─────────────
string gExit = "Exits"
string slMethod    = input.string("Swing", "Stop method", options=["Swing", "Zone", "ATR", "Percent"], group=gExit, tooltip="Swing: beyond the latest confirmed swing (retest entries: beyond the retest zone). Zone: beyond the demand / supply zone.")
string tpMethod    = input.string("Structure", "Target method", options=["Structure", "R multiple", "Percent"], group=gExit, tooltip="Structure: TP1 at the next confirmed swing high, TP2 at the trendline origin (falls back to R). Percent: TP1 at half the percent, TP2 at the full percent.")
float  stopBufAtr  = input.float(0.25, "Stop buffer (ATR)", minval=0.0, maxval=5.0, step=0.05, group=gExit)
float  slAtr       = input.float(1.5, "ATR stop (x ATR)", minval=0.1, maxval=20.0, step=0.1, group=gExit)
float  slPerc      = input.float(1.5, "Percent stop %", minval=0.1, maxval=50.0, step=0.1, group=gExit) / 100.0
float  tpPerc      = input.float(4.0, "Percent target %", minval=0.1, maxval=100.0, step=0.1, group=gExit) / 100.0
float  minStopAtr  = input.float(0.6, "Minimum stop distance (ATR)", minval=0.1, maxval=10.0, step=0.1, group=gExit)
float  maxStopPerc = input.float(6.0, "Maximum stop distance % (skip trade if wider)", minval=0.5, maxval=50.0, step=0.5, group=gExit) / 100.0
float  minTp1R     = input.float(0.6, "Structure TP1: minimum distance (R)", minval=0.1, maxval=10.0, step=0.1, group=gExit, tooltip="Swing highs closer than this are skipped as TP1.")
float  tp1R        = input.float(1.0, "TP1 (R)", minval=0.2, maxval=20.0, step=0.1, group=gExit)
float  tp2R        = input.float(2.5, "TP2 (R)", minval=0.2, maxval=20.0, step=0.1, group=gExit)
int    tp1Qty      = input.int(50, "TP1 size (% of position)", minval=10, maxval=100, group=gExit)
bool   useBE       = input.bool(true, "Move stop to break-even after TP1", group=gExit)
int    beTicks     = input.int(2, "Break-even offset (ticks)", minval=0, maxval=1000, group=gExit)
bool   useTrail    = input.bool(false, "ATR trailing stop", group=gExit)
float  trailAtr    = input.float(2.5, "Trail distance (ATR)", minval=0.5, maxval=20.0, step=0.1, group=gExit)
bool   exitOnInval = input.bool(true, "Close on sustained zone break", group=gExit, tooltip="Long: closes below the demand zone bottom. Short: closes above the supply zone top.")
int    invalBars   = input.int(2, "Closes beyond the zone to invalidate", minval=1, maxval=10, group=gExit)
 
// ───────────── Inputs: visuals ─────────────
string gVis = "Visuals"
bool  showZones     = input.bool(true, "Show demand / supply zones", group=gVis)
bool  showTl        = input.bool(true, "Show trendlines", group=gVis)
int   maxTl         = input.int(20, "Max trendlines drawn", minval=2, maxval=100, group=gVis)
bool  showFar       = input.bool(false, "Show zones far from price", group=gVis)
float nearAtr       = input.float(10.0, "Far zone threshold (ATR)", minval=1.0, maxval=100.0, step=0.5, group=gVis)
bool  showMas       = input.bool(true, "Show EMA cluster and MA long", group=gVis)
bool  showLabels    = input.bool(true, "Show trade label (entry / SL / TP)", group=gVis)
bool  showRiskLines = input.bool(true, "Show SL / TP segments at entry", group=gVis)
int   riskLineLen   = input.int(12, "SL / TP segment length (bars)", minval=1, maxval=200, group=gVis)
int   maxDrawn      = input.int(50, "Max trades drawn", minval=1, maxval=150, group=gVis)
bool  showLiveStop  = input.bool(false, "Show live stop", group=gVis)
bool  showRegime    = input.bool(true, "Shade bars below MA long", group=gVis)
bool  showDebug     = input.bool(false, "Show blocked-signal markers", group=gVis, tooltip="Orange x = a breakout or retest happened but a filter, cooldown, stop rule or open position blocked the entry.")
 
// ───────────── Indicators (evaluated on every bar) ─────────────
float atr      = ta.atr(atrLen)
float rsiVal   = ta.rsi(close, rsiLen)
[macdLine, macdSignal, macdHist] = ta.macd(close, macdFast, macdSlow, macdSig)
float emaFast  = ta.ema(close, emaFastLen)
float emaSlow  = ta.ema(close, emaSlowLen)
float clTop    = math.max(emaFast, emaSlow)
float clBot    = math.min(emaFast, emaSlow)
float maLong   = ta.ema(close, maLongLen)
float volAvg   = ta.sma(volume, volLen)
float ph       = ta.pivothigh(high, pivotLen, pivotLen)
float pl       = ta.pivotlow(low, pivotLen, pivotLen)
float hiBack   = ta.highest(close, fromAboveLen)[1]
float loBack   = ta.lowest(close, fromAboveLen)[1]
 
// ───────────── Helpers ─────────────
breakOnChange(float x) => x != x[1] ? na : x
fmt(float x) => na(x) ? "-" : str.tostring(x, format.mintick)
nearPrice(float x) => not na(x) and not na(atr) and (showFar or math.abs(x - close) <= nearAtr * atr)
 
bool manualNow  = useManual and time >= manualFrom
bool allowLong  = tradeDir != "Short only"
bool allowShort = tradeDir != "Long only"
 
// ───────────── Swing memory (confirmed pivots only) ─────────────
var array<float> phArr = array.new<float>()
var array<float> plArr = array.new<float>()
var float lastPh = na
var float lastPl = na
if not na(ph)
    phArr.push(ph)
    if phArr.size() > 20
        phArr.shift()
    lastPh := ph
if not na(pl)
    plArr.push(pl)
    if plArr.size() > 20
        plArr.shift()
    lastPl := pl
 
// ───────────── Demand zone (auto) ─────────────
var float aDzTop     = na
var float aDzBot     = na
var float aDzSwing   = na
var int   aDzBar     = na
var int   aDzTouches = 0
var int   lastDzTouch = na
if not na(pl) and not na(atr)
    int pBar = bar_index - pivotLen
    if not na(aDzSwing) and math.abs(pl - aDzSwing) <= clusterAtr * atr
        aDzTouches += 1
        aDzBot   := math.min(aDzBot, pl - zoneBufAtr * atr)
        aDzSwing := math.min(aDzSwing, pl)
    else
        aDzSwing   := pl
        aDzBot     := pl - zoneBufAtr * atr
        aDzTop     := pl + zoneAtr * atr
        aDzTouches := 1
    aDzBar := pBar
    // The swing bar itself touched the zone; recorded only now, on its confirmation bar
    if not manualNow
        lastDzTouch := pBar
if not na(aDzBot) and (close < aDzBot or bar_index - aDzBar > zoneMaxAge)
    aDzTop     := na
    aDzBot     := na
    aDzSwing   := na
    aDzTouches := 0
 
// ───────────── Supply zone (auto, mirror) ─────────────
var float aSzTop     = na
var float aSzBot     = na
var float aSzSwing   = na
var int   aSzBar     = na
var int   aSzTouches = 0
var int   lastSzTouch = na
if not na(ph) and not na(atr)
    int hBar = bar_index - pivotLen
    if not na(aSzSwing) and math.abs(ph - aSzSwing) <= clusterAtr * atr
        aSzTouches += 1
        aSzTop   := math.max(aSzTop, ph + zoneBufAtr * atr)
        aSzSwing := math.max(aSzSwing, ph)
    else
        aSzSwing   := ph
        aSzTop     := ph + zoneBufAtr * atr
        aSzBot     := ph - zoneAtr * atr
        aSzTouches := 1
    aSzBar := hBar
    if not manualNow
        lastSzTouch := hBar
if not na(aSzTop) and (close > aSzTop or bar_index - aSzBar > zoneMaxAge)
    aSzTop     := na
    aSzBot     := na
    aSzSwing   := na
    aSzTouches := 0
 
// ───────────── Effective zones and touches ─────────────
bool  manDzOk = manDzBot > 0 and manDzTop > manDzBot
bool  manSzOk = manSzBot > 0 and manSzTop > manSzBot
float dzTop   = manualNow ? (manDzOk ? manDzTop : na) : aDzTop
float dzBot   = manualNow ? (manDzOk ? manDzBot : na) : aDzBot
float szTop   = manualNow ? (manSzOk ? manSzTop : na) : aSzTop
float szBot   = manualNow ? (manSzOk ? manSzBot : na) : aSzBot
int   dzTouch = manualNow ? minTouches : aDzTouches
int   szTouch = manualNow ? minTouches : aSzTouches
 
// A touch is a pullback INTO the zone: price closed outside it within the lookback and did not close through it
bool touchDz = not na(dzTop) and not na(hiBack) and low <= dzTop and close >= dzBot and hiBack > dzTop
bool touchSz = not na(szBot) and not na(loBack) and high >= szBot and close <= szTop and loBack < szBot
if touchDz
    lastDzTouch := bar_index
if touchSz
    lastSzTouch := bar_index
bool demandOk = not na(dzTop) and dzTouch >= minTouches and not na(lastDzTouch) and bar_index - lastDzTouch <= touchWindow
bool supplyOk = not na(szBot) and szTouch >= minTouches and not na(lastSzTouch) and bar_index - lastSzTouch <= touchWindow
 
// ───────────── Trendlines ─────────────
// Long: through the last two confirmed swing highs, only when the second is lower (descending resistance)
var float th1 = na
var int   tb1 = na
var float th2 = na
var int   tb2 = na
var bool  tlUsedL = false
if not na(ph)
    th1 := th2
    tb1 := tb2
    th2 := ph
    tb2 := bar_index - pivotLen
    tlUsedL := false
bool  tlShapeL = not na(th1) and not na(th2) and not na(atr) and tb2 > tb1 and th1 - th2 >= minStepAtr * atr
float tlSlopeL = tlShapeL ? (th2 - th1) / (tb2 - tb1) : na
float tlValL   = tlShapeL ? th2 + tlSlopeL * (bar_index - tb2) : na
bool  tlLiveL  = tlShapeL and not tlUsedL and bar_index - tb2 <= tlMaxAge and tlValL > 0
 
// Short: through the last two confirmed swing lows, only when the second is higher (ascending support)
var float tl1 = na
var int   lb1 = na
var float tl2 = na
var int   lb2 = na
var bool  tlUsedS = false
if not na(pl)
    tl1 := tl2
    lb1 := lb2
    tl2 := pl
    lb2 := bar_index - pivotLen
    tlUsedS := false
bool  tlShapeS = not na(tl1) and not na(tl2) and not na(atr) and lb2 > lb1 and tl2 - tl1 >= minStepAtr * atr
float tlSlopeS = tlShapeS ? (tl2 - tl1) / (lb2 - lb1) : na
float tlValS   = tlShapeS ? tl2 + tlSlopeS * (bar_index - lb2) : na
bool  tlLiveS  = tlShapeS and not tlUsedS and bar_index - lb2 <= tlMaxAge and tlValS > 0
 
// ───────────── Breakout events ─────────────
float lineTrigL = tlLiveL ? tlValL + breakAtr * atr : na
float lineTrigS = tlLiveS ? tlValS - breakAtr * atr : na
float trigL     = requireTl ? (requireEma ? math.max(lineTrigL, clTop) : lineTrigL) : (requireEma ? clTop : na)
float trigS     = requireTl ? (requireEma ? math.min(lineTrigS, clBot) : lineTrigS) : (requireEma ? clBot : na)
float baseL     = requireTl ? (requireEma ? math.max(tlValL, clTop) : tlValL) : clTop
float baseS     = requireTl ? (requireEma ? math.min(tlValS, clBot) : tlValS) : clBot
bool  volOk     = not useVolume or na(volAvg) or volAvg <= 0 or volume > volAvg * volMult
bool  brkUp     = demandOk and not na(trigL) and not na(trigL[1]) and close > trigL and close[1] <= trigL[1] and volOk
bool  brkDn     = supplyOk and not na(trigS) and not na(trigS[1]) and close < trigS and close[1] >= trigS[1] and volOk
 
// Breakout state: armed by a confirmed breakout, retired at the end of the script
var float bLvlL  = na
var int   bBarL  = na
var bool  bUsedL = false
var bool  bLeftL = false
var float bOrgL  = na
var float bLvlS  = na
var int   bBarS  = na
var bool  bUsedS = false
var bool  bLeftS = false
var float bOrgS  = na
if brkUp and barstate.isconfirmed
    bLvlL   := baseL
    bBarL   := bar_index
    bUsedL  := false
    bLeftL  := false
    bOrgL   := th1
    tlUsedL := true
if brkDn and barstate.isconfirmed
    bLvlS   := baseS
    bBarS   := bar_index
    bUsedS  := false
    bLeftS  := false
    bOrgS   := tl1
    tlUsedS := true
 
// ───────────── Retest events ─────────────
bool  liveL  = not na(bLvlL) and not bUsedL and bLeftL and bar_index > bBarL and bar_index - bBarL <= retestExpiry and not na(atr)
float rtTopL = liveL ? bLvlL + retestTolAtr * atr : na
float rtBotL = liveL ? bLvlL - retestTolAtr * atr : na
bool  rtL    = liveL and low <= rtTopL and low >= rtBotL and close > bLvlL and close > open
 
bool  liveS  = not na(bLvlS) and not bUsedS and bLeftS and bar_index > bBarS and bar_index - bBarS <= retestExpiry and not na(atr)
float rtBotS = liveS ? bLvlS - retestTolAtr * atr : na
float rtTopS = liveS ? bLvlS + retestTolAtr * atr : na
bool  rtS    = liveS and high >= rtBotS and high <= rtTopS and close < bLvlS and close < open
 
// ───────────── Filters and state ─────────────
var int lastExitBar = na
if strategy.position_size == 0 and strategy.position_size[1] != 0
    lastExitBar := bar_index
bool cooldownOk = na(lastExitBar) or bar_index - lastExitBar >= cooldownBars
bool inRange    = not useDateRange or (time >= rangeStart and time <= rangeEnd)
bool canTrade   = inRange and strategy.position_size == 0 and cooldownOk and barstate.isconfirmed and not na(atr)
 
bool rsiOkL  = not useRsi or (rsiVal >= rsiLongMin and rsiVal <= rsiLongMax)
bool rsiOkS  = not useRsi or (rsiVal >= rsiShortMin and rsiVal <= rsiShortMax)
bool macdOkL = not useMacd or (not na(macdHist) and not na(macdHist[1]) and (macdHist > 0 or macdHist > macdHist[1]))
bool macdOkS = not useMacd or (not na(macdHist) and not na(macdHist[1]) and (macdHist < 0 or macdHist < macdHist[1]))
bool trendL  = not useTrendFilter or (not na(maLong) and close > maLong)
bool trendS  = not useTrendFilter or (not na(maLong) and close < maLong)
 
// ───────────── Stops and targets ─────────────
calcStop(bool isLong, bool isRt, float lvl) =>
    float zoneStop  = isLong ? (na(dzBot) ? na : dzBot - stopBufAtr * atr) : (na(szTop) ? na : szTop + stopBufAtr * atr)
    float rtStop    = na(lvl) ? na : isLong ? math.min(low, lvl - retestTolAtr * atr) - stopBufAtr * atr : math.max(high, lvl + retestTolAtr * atr) + stopBufAtr * atr
    float swStop    = isLong ? (not na(lastPl) and lastPl < close ? lastPl - stopBufAtr * atr : zoneStop) : (not na(lastPh) and lastPh > close ? lastPh + stopBufAtr * atr : zoneStop)
    float swingStop = isRt ? rtStop : swStop
    float atrStop   = isLong ? close - slAtr * atr : close + slAtr * atr
    float pctStop   = isLong ? close * (1 - slPerc) : close * (1 + slPerc)
    float raw       = slMethod == "Swing" ? swingStop : slMethod == "Zone" ? zoneStop : slMethod == "ATR" ? atrStop : pctStop
    na(raw) ? na : isLong ? math.min(raw, close - minStopAtr * atr) : math.max(raw, close + minStopAtr * atr)
 
// Nearest confirmed swing beyond x (long: swing highs above x, short: swing lows below x)
nearestBeyond(bool isLong, float x) =>
    float best = na
    if not na(x)
        if isLong
            for v in phArr
                if v > x and (na(best) or v < best)
                    best := v
        else
            for v in plArr
                if v < x and (na(best) or v > best)
                    best := v
    best
 
calcTargets(bool isLong, float entry, float risk, float origin) =>
    float dir = isLong ? 1.0 : -1.0
    float t1  = na(risk) ? na : entry + dir * tp1R * risk
    float t2  = na(risk) ? na : entry + dir * tp2R * risk
    if tpMethod == "Percent"
        t1 := entry * (1 + dir * tpPerc * 0.5)
        t2 := entry * (1 + dir * tpPerc)
    else if tpMethod == "Structure" and not na(risk)
        float s1 = nearestBeyond(isLong, entry + dir * minTp1R * risk)
        if not na(s1)
            t1 := s1
        bool  orgOk = not na(origin) and (isLong ? origin > t1 : origin < t1)
        float s2    = orgOk ? origin : nearestBeyond(isLong, t1)
        t2 := na(s2) ? t1 + dir * math.max(tp2R - tp1R, 0.5) * risk : s2
    [t1, t2]
 
validBracket(float risk) => not na(risk) and risk > 2 * syminfo.mintick and risk <= close * maxStopPerc
 
// Each setup gets its own stop and risk
float stopRtL = calcStop(true, true, bLvlL)
float riskRtL = close - stopRtL
float stopBkL = calcStop(true, false, baseL)
float riskBkL = close - stopBkL
float stopRtS = calcStop(false, true, bLvlS)
float riskRtS = stopRtS - close
float stopBkS = calcStop(false, false, baseS)
float riskBkS = stopBkS - close
 
// ───────────── Signals ─────────────
bool chaseBrkL = not na(baseL) and close - baseL <= maxChaseAtr * atr
bool chaseRtL  = not na(bLvlL) and close - bLvlL <= maxChaseAtr * atr
bool sigRtL    = useRtEntry and allowLong and canTrade and rtL and rsiOkL and macdOkL and trendL and chaseRtL and validBracket(riskRtL)
bool sigBrkL   = useBrkEntry and allowLong and canTrade and not sigRtL and brkUp and rsiOkL and macdOkL and trendL and chaseBrkL and validBracket(riskBkL)
bool sigL      = sigRtL or sigBrkL
 
bool chaseBrkS = not na(baseS) and baseS - close <= maxChaseAtr * atr
bool chaseRtS  = not na(bLvlS) and bLvlS - close <= maxChaseAtr * atr
bool sigRtS    = useRtEntry and allowShort and canTrade and not sigL and rtS and rsiOkS and macdOkS and trendS and chaseRtS and validBracket(riskRtS)
bool sigBrkS   = useBrkEntry and allowShort and canTrade and not sigL and not sigRtS and brkDn and rsiOkS and macdOkS and trendS and chaseBrkS and validBracket(riskBkS)
bool sigS      = sigRtS or sigBrkS
 
// ───────────── Orders ─────────────
var float entryRef   = na
var float riskDist   = na
var float stopPx     = na
var float tp1Px      = na
var float tp2Px      = na
var float orgTp      = na
var bool  tp1Done    = false
var float invalLevel = na
var int   invalCnt   = 0
var float trailPx    = na
 
var array<label> tradeLabels = array.new<label>()
var array<line>  tradeLines  = array.new<line>()
 
drawRisk(float sl, float t1, float t2, string txt, bool isLong) =>
    if showLabels
        tradeLabels.push(label.new(bar_index, isLong ? low : high, txt, style=isLong ? label.style_label_up : label.style_label_down, color=color.new(isLong ? color.teal : color.maroon, 15), textcolor=color.white, size=size.small))
        if tradeLabels.size() > maxDrawn
            tradeLabels.shift().delete()
    if showRiskLines
        tradeLines.push(line.new(bar_index, sl, bar_index + riskLineLen, sl, color=color.new(color.red, 0), width=1))
        tradeLines.push(line.new(bar_index, t1, bar_index + riskLineLen, t1, color=color.new(color.green, 30), width=1, style=line.style_dashed))
        tradeLines.push(line.new(bar_index, t2, bar_index + riskLineLen, t2, color=color.new(color.green, 0), width=1))
        while tradeLines.size() > maxDrawn * 3
            tradeLines.shift().delete()
 
if sigL
    float riskL = sigRtL ? riskRtL : riskBkL
    float orgL  = sigRtL ? bOrgL : th1
    [t1, t2]   = calcTargets(true, close, riskL, orgL)
    entryRef   := close
    riskDist   := riskL
    stopPx     := sigRtL ? stopRtL : stopBkL
    orgTp      := orgL
    tp1Px      := t1
    tp2Px      := t2
    tp1Done    := false
    trailPx    := na
    invalCnt   := 0
    invalLevel := dzBot
    bUsedL     := true
    string kind = sigRtL ? "retest" : "breakout"
    strategy.entry("L", strategy.long, comment="L " + kind)
    strategy.exit("L TP1", from_entry="L", qty_percent=tp1Qty, stop=math.round_to_mintick(stopPx), limit=math.round_to_mintick(tp1Px), comment_loss="SL", comment_profit="TP1")
    strategy.exit("L TP2", from_entry="L", stop=math.round_to_mintick(stopPx), limit=math.round_to_mintick(tp2Px), comment_loss="SL", comment_profit="TP2")
    drawRisk(stopPx, tp1Px, tp2Px, "LONG " + kind + " " + fmt(close) + "\nSL " + fmt(stopPx) + "  |  TP " + fmt(tp1Px) + " / " + fmt(tp2Px), true)
    alert("LONG " + kind + " " + syminfo.ticker + " @ " + fmt(close) + " SL " + fmt(stopPx) + " TP1 " + fmt(tp1Px) + " TP2 " + fmt(tp2Px), alert.freq_once_per_bar_close)
 
if sigS
    float riskS = sigRtS ? riskRtS : riskBkS
    float orgS  = sigRtS ? bOrgS : tl1
    [t1, t2]   = calcTargets(false, close, riskS, orgS)
    entryRef   := close
    riskDist   := riskS
    stopPx     := sigRtS ? stopRtS : stopBkS
    orgTp      := orgS
    tp1Px      := t1
    tp2Px      := t2
    tp1Done    := false
    trailPx    := na
    invalCnt   := 0
    invalLevel := szTop
    bUsedS     := true
    string kind = sigRtS ? "retest" : "breakdown"
    strategy.entry("S", strategy.short, comment="S " + kind)
    strategy.exit("S TP1", from_entry="S", qty_percent=tp1Qty, stop=math.round_to_mintick(stopPx), limit=math.round_to_mintick(tp1Px), comment_loss="SL", comment_profit="TP1")
    strategy.exit("S TP2", from_entry="S", stop=math.round_to_mintick(stopPx), limit=math.round_to_mintick(tp2Px), comment_loss="SL", comment_profit="TP2")
    drawRisk(stopPx, tp1Px, tp2Px, "SHORT " + kind + " " + fmt(close) + "\nSL " + fmt(stopPx) + "  |  TP " + fmt(tp1Px) + " / " + fmt(tp2Px), false)
    alert("SHORT " + kind + " " + syminfo.ticker + " @ " + fmt(close) + " SL " + fmt(stopPx) + " TP1 " + fmt(tp1Px) + " TP2 " + fmt(tp2Px), alert.freq_once_per_bar_close)
 
// ───────────── Position management (runs on bar close) ─────────────
bool inLong     = strategy.position_size > 0
bool inShort    = strategy.position_size < 0
bool justFilled = strategy.position_size != 0 and strategy.position_size[1] == 0
 
// Re-anchor to the actual fill (next bar's open): keep the structural stop unless a gap put it on the wrong side
if justFilled and not na(riskDist)
    entryRef := strategy.position_avg_price
    if inLong
        if na(stopPx) or stopPx >= entryRef
            stopPx := entryRef - riskDist
        riskDist := entryRef - stopPx
        [a1, a2] = calcTargets(true, entryRef, riskDist, orgTp)
        tp1Px := a1
        tp2Px := a2
    if inShort
        if na(stopPx) or stopPx <= entryRef
            stopPx := entryRef + riskDist
        riskDist := stopPx - entryRef
        [b1, b2] = calcTargets(false, entryRef, riskDist, orgTp)
        tp1Px := b1
        tp2Px := b2
 
// A partial exit adds a closed trade while the position stays open = TP1 filled
if strategy.position_size != 0 and strategy.closedtrades > strategy.closedtrades[1]
    tp1Done := true
 
if strategy.position_size == 0
    trailPx  := na
    invalCnt := 0
 
if inLong
    float beL = entryRef + beTicks * syminfo.mintick
    if useBE and tp1Done and beL < close
        stopPx := math.max(stopPx, beL)
    if useTrail and not na(atr)
        trailPx := math.max(nz(trailPx, stopPx), close - trailAtr * atr)
        stopPx  := math.max(stopPx, trailPx)
    invalCnt := not na(invalLevel) and close < invalLevel ? invalCnt + 1 : 0
    if exitOnInval and invalCnt >= invalBars
        strategy.close("L", comment="Zone lost")
    if not tp1Done
        strategy.exit("L TP1", from_entry="L", qty_percent=tp1Qty, stop=math.round_to_mintick(stopPx), limit=math.round_to_mintick(tp1Px), comment_loss="SL", comment_profit="TP1")
    strategy.exit("L TP2", from_entry="L", stop=math.round_to_mintick(stopPx), limit=math.round_to_mintick(tp2Px), comment_loss=tp1Done ? "BE/SL" : "SL", comment_profit="TP2")
 
if inShort
    float beS = entryRef - beTicks * syminfo.mintick
    if useBE and tp1Done and beS > close
        stopPx := math.min(stopPx, beS)
    if useTrail and not na(atr)
        trailPx := math.min(nz(trailPx, stopPx), close + trailAtr * atr)
        stopPx  := math.min(stopPx, trailPx)
    invalCnt := not na(invalLevel) and close > invalLevel ? invalCnt + 1 : 0
    if exitOnInval and invalCnt >= invalBars
        strategy.close("S", comment="Zone lost")
    if not tp1Done
        strategy.exit("S TP1", from_entry="S", qty_percent=tp1Qty, stop=math.round_to_mintick(stopPx), limit=math.round_to_mintick(tp1Px), comment_loss="SL", comment_profit="TP1")
    strategy.exit("S TP2", from_entry="S", stop=math.round_to_mintick(stopPx), limit=math.round_to_mintick(tp2Px), comment_loss=tp1Done ? "BE/SL" : "SL", comment_profit="TP2")
 
// ───────────── Breakout state: move-away flag, retire ─────────────
if not na(bLvlL) and not na(atr)
    if close > bLvlL + retestTolAtr * atr
        bLeftL := true
    if close < bLvlL - retestTolAtr * atr or bar_index - bBarL > retestExpiry
        bLvlL := na
if not na(bLvlS) and not na(atr)
    if close < bLvlS - retestTolAtr * atr
        bLeftS := true
    if close > bLvlS + retestTolAtr * atr or bar_index - bBarS > retestExpiry
        bLvlS := na
 
// ───────────── Trendline drawing (extends while live, stops at the break) ─────────────
var array<line> tlLines = array.new<line>()
var line curTlL = na
var int  curAncL = na
var line curTlS = na
var int  curAncS = na
if showTl and allowLong and tlLiveL
    if na(curTlL) or curAncL != tb2
        curTlL  := line.new(tb1, th1, bar_index, tlValL, color=color.new(color.orange, 10), width=2)
        curAncL := tb2
        tlLines.push(curTlL)
        while tlLines.size() > maxTl
            tlLines.shift().delete()
    else
        curTlL.set_xy2(bar_index, tlValL)
if showTl and allowShort and tlLiveS
    if na(curTlS) or curAncS != lb2
        curTlS  := line.new(lb1, tl1, bar_index, tlValS, color=color.new(color.fuchsia, 10), width=2)
        curAncS := lb2
        tlLines.push(curTlS)
        while tlLines.size() > maxTl
            tlLines.shift().delete()
    else
        curTlS.set_xy2(bar_index, tlValS)
 
// ───────────── Plots (price pane: MAs and price zones only) ─────────────
float dzTopPl = breakOnChange(showZones and allowLong and nearPrice(dzTop) ? dzTop : na)
float dzBotPl = breakOnChange(showZones and allowLong and nearPrice(dzBot) ? dzBot : na)
float szTopPl = breakOnChange(showZones and allowShort and nearPrice(szTop) ? szTop : na)
float szBotPl = breakOnChange(showZones and allowShort and nearPrice(szBot) ? szBot : na)
 
plot(showMas ? emaFast : na, "Cluster EMA fast", color=color.new(color.orange, 30), linewidth=1)
plot(showMas ? emaSlow : na, "Cluster EMA slow", color=color.new(color.yellow, 20), linewidth=1)
plot(showMas ? maLong : na, "MA long", color=color.new(color.purple, 0), linewidth=2)
pDzTop = plot(dzTopPl, "Demand top", color=color.new(color.teal, 40), linewidth=1, style=plot.style_linebr, display=display.pane)
pDzBot = plot(dzBotPl, "Demand bottom", color=color.new(color.teal, 10), linewidth=1, style=plot.style_linebr, display=display.pane)
fill(pDzTop, pDzBot, color=color.new(color.teal, 85), title="Demand zone fill")
pSzTop = plot(szTopPl, "Supply top", color=color.new(color.red, 10), linewidth=1, style=plot.style_linebr, display=display.pane)
pSzBot = plot(szBotPl, "Supply bottom", color=color.new(color.red, 40), linewidth=1, style=plot.style_linebr, display=display.pane)
fill(pSzTop, pSzBot, color=color.new(color.red, 88), title="Supply zone fill")
plot(showLiveStop and strategy.position_size != 0 ? stopPx : na, "Live stop", color=color.new(color.red, 30), linewidth=1, style=plot.style_linebr, display=display.pane)
bgcolor(showRegime and not na(maLong) and close < maLong ? color.new(color.red, 92) : na, title="Below MA long (visual only)")
 
// Debug: structural event happened, entry blocked
bool blockedLong  = showDebug and barstate.isconfirmed and allowLong and ((useRtEntry and rtL and not sigRtL) or (useBrkEntry and brkUp and not sigBrkL))
bool blockedShort = showDebug and barstate.isconfirmed and allowShort and ((useRtEntry and rtS and not sigRtS) or (useBrkEntry and brkDn and not sigBrkS))
plotchar(blockedLong, "Blocked long event", "x", location.belowbar, color=color.new(color.orange, 0), size=size.tiny, display=display.pane)
plotchar(blockedShort, "Blocked short event", "x", location.abovebar, color=color.new(color.orange, 0), size=size.tiny, display=display.pane)

← 返回列表