EMA Trend

OptionFlows · study · 559 行 · 点赞 47 · TradingView 原页

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

Pine Script

//@version=6
indicator("EMA Trend", shorttitle="EMA Trend", overlay=true, max_labels_count=500, max_boxes_count=20, max_polylines_count=20)
 
// =====================================================
// PRESET
// =====================================================
grpPre   = "Preset"
presetIn = input.string("Auto", "Settings Preset", options=["Auto", "1 Min", "5 Min", "Custom"], group=grpPre, tooltip="Auto = picks the preset from your chart timeframe (1-minute chart → 1 Min preset, everything else → 5 Min preset).\n1 Min / 5 Min = force that preset.\nCustom = use the values you set below (settings marked 'Custom only').")
 
// =====================================================
// RIBBON EMAs  (checkbox = show line/label/projection)
// =====================================================
grpR  = "Ribbon EMAs"
show1 = input.bool(true, "", inline="e1", group=grpR)
len1  = input.int(9,   "EMA 1 (fastest)", minval=1, inline="e1", group=grpR)
show2 = input.bool(true, "", inline="e2", group=grpR)
len2  = input.int(21,  "EMA 2", minval=1, inline="e2", group=grpR)
show3 = input.bool(false, "", inline="e3", group=grpR)
len3  = input.int(40,  "EMA 3", minval=1, inline="e3", group=grpR)
show4 = input.bool(true, "", inline="e4", group=grpR)
len4  = input.int(50,  "EMA 4", minval=1, inline="e4", group=grpR)
show5 = input.bool(false, "", inline="e5", group=grpR)
len5  = input.int(70,  "EMA 5", minval=1, inline="e5", group=grpR)
show6 = input.bool(true, "", inline="e6", group=grpR)
len6  = input.int(100, "EMA 6 (slowest)", minval=1, inline="e6", group=grpR, tooltip="Checkbox hides the line, label and projection. Hidden EMAs still count toward the trend color unless 'Only Checked EMAs Count' is on. Keep lengths in order from fastest to slowest and never repeat a length.")
src   = input.source(close, "Source", group=grpR)
 
// =====================================================
// EXTRA EMA (200)
// =====================================================
grpX2  = "Extra EMA"
showX  = input.bool(true, "", inline="ex", group=grpX2)
lenX   = input.int(200, "Extra EMA", minval=1, inline="ex", group=grpX2, tooltip="Plotted on its own as a big-picture level. It does NOT affect the trend colors, squeeze, signals or zones. Checkbox hides its line, label and projection.")
matchX = input.bool(true, "Use Trend Color", group=grpX2, tooltip="On = same color as the ribbon. Off = use the custom color below.")
colX   = input.color(color.white, "Custom Color", group=grpX2)
wX     = input.int(2, "Extra EMA Width", minval=1, maxval=4, group=grpX2)
projX  = input.bool(true, "Project Extra EMA", group=grpX2)
 
// =====================================================
// TREND COLORS
// =====================================================
grpC     = "Trend Colors"
bullCol  = input.color(color.rgb(34, 197, 166), "Bull Trend", group=grpC, tooltip="BULL: the EMAs used by your Trend Mode are stacked up (fast on top) AND sloping up. Favor calls / longs.")
bearCol  = input.color(color.rgb(244, 114, 182), "Bear Trend", group=grpC, tooltip="BEAR: the EMAs used by your Trend Mode are stacked down (fast on bottom) AND sloping down. Favor puts / shorts.")
compCol  = input.color(color.rgb(129, 140, 248), "Squeeze", group=grpC, tooltip="SQUEEZE: price is coiling sideways and the EMAs are bunched tight. A breakout may be coming — wait for it to turn Bull or Bear before entering.")
mixedCol = input.color(color.rgb(245, 189, 92), "Chop", group=grpC, tooltip="CHOP: EMAs are tangled or not lined up. No clean trend — stay out or size down.")
 
// =====================================================
// TREND ENGINE
// =====================================================
grpE           = "Trend Engine"
trendMode      = input.string("Strict", "Trend Mode", options=["Fast", "Balanced", "Strict"], group=grpE, tooltip="Fast = only the 3 fastest EMAs decide the color. All 3 stacked + sloping. Reacts ~3x faster.\nBalanced = all EMAs, but 1 pair may be out of order and 2 may slope the wrong way.\nStrict = all EMAs fully stacked + 'Min EMAs Sloping' sloping. Slowest, cleanest.")
onlyChecked    = input.bool(true, "Only Checked EMAs Count", group=grpE, tooltip="On = only EMAs with their checkbox ticked are used for the trend color. Off = all 6 count, even hidden ones.")
atrLen         = input.int(14, "ATR Length", minval=1, group=grpE)
slopeLbIn      = input.int(3, "Slope Lookback (Custom only)", minval=1, group=grpE, tooltip="Bars used to check if each EMA is rising or falling. Preset: 5m = 3, 1m = 5.")
minSlopes      = input.int(5, "Min EMAs Sloping (Strict only)", minval=1, maxval=6, group=grpE, tooltip="Strict mode only: how many EMAs must slope with the trend (capped at the number of EMAs used).")
minWidthExpIn  = input.float(0.06, "Min Width Expansion (Custom only)", minval=0.0, step=0.01, group=grpE, tooltip="How fast the ribbon must widen (in ATR) to count as a breakout. Preset: 5m = 0.06, 1m = 0.08.")
launchWindowIn = input.int(6, "Breakout Window (Custom only)", minval=1, maxval=30, group=grpE, tooltip="Bars after a squeeze ends where a breakout can still trigger. Preset: 5m = 6, 1m = 10.")
 
// =====================================================
// SQUEEZE
// =====================================================
grpQ           = "Squeeze"
trendBeatsSqz  = input.bool(true, "Trend Beats Squeeze", group=grpQ, tooltip="On = if the EMAs are lined up Bull or Bear, show the trend color even when tight. Purple only shows during real sideways coiling.\nOff = squeeze always wins (old behavior — can hide trend flips for 1-2 hours).")
sqzType        = input.string("Ribbon", "Squeeze Type", options=["Ribbon", "TTM"], group=grpQ, tooltip="Ribbon = EMAs unusually tight vs recent bars.\nTTM = classic John Carter squeeze: Bollinger Bands inside Keltner Channels. A fixed test that doesn't always find something 'tight'.")
compLookbackIn = input.int(80, "Squeeze Lookback (Custom only)", minval=20, group=grpQ, tooltip="Ribbon type: bars used to judge how tight the ribbon is. Preset: 5m = 80, 1m = 150.")
compThreshIn   = input.float(85.0, "Squeeze Threshold (Custom only)", minval=0, maxval=100, step=0.5, group=grpQ, tooltip="Ribbon type: tightness score (0-100) needed for a squeeze. Higher = fewer, tighter squeezes. Preset: 5m = 85, 1m = 88.")
sqzMinBarsIn   = input.int(5, "Min Squeeze Bars (Custom only)", minval=1, maxval=30, group=grpQ, tooltip="Squeeze must last this many bars in a row before it counts. Filters 1-2 bar flickers. Preset: 5m = 5, 1m = 8.")
ttmLen         = input.int(20, "TTM Length", minval=2, group=grpQ, tooltip="TTM type only. Standard = 20.")
ttmBB          = input.float(2.0, "TTM Bollinger Mult", minval=0.5, step=0.1, group=grpQ, tooltip="TTM type only. Standard = 2.0.")
ttmKC          = input.float(1.5, "TTM Keltner Mult", minval=0.5, step=0.1, group=grpQ, tooltip="TTM type only. Standard = 1.5. Lower = stricter (fewer squeezes).")
 
// =====================================================
// DISPLAY
// =====================================================
grpD       = "Display"
showLines  = input.bool(true, "Show EMA Lines", group=grpD)
showFill   = input.bool(true, "Show Ribbon Fill", group=grpD)
fillMode   = input.string("9 & 21 Only", "Fill Area", options=["All EMAs", "9 & 21 Only"], group=grpD, tooltip="All EMAs = shade the whole ribbon.\n9 & 21 Only = shade only between EMA 1 and EMA 2. Still changes color with the trend.")
fillTransp = input.int(70, "Fill Transparency", minval=50, maxval=95, group=grpD)
lineSoft   = input.int(24, "Line Fade (fast → slow)", minval=0, maxval=60, group=grpD, tooltip="Slower EMAs get more transparent so the fast ones stand out.")
lineW      = input.int(1, "Line Width", minval=1, maxval=4, group=grpD)
barTint    = input.bool(false, "Tint Candles By Trend", group=grpD)
 
// =====================================================
// EMA LABELS
// =====================================================
grpL       = "EMA Labels"
showEmaLbl = input.bool(true, "Show EMA Labels", group=grpL)
lblSide    = input.string("End Of Projection", "Label Position", options=["End Of Projection", "On Line", "Right Of Chart"], group=grpL, tooltip="End Of Projection = label sits right at the tip of the dotted projection line (falls back to right after the last candle if projection is off).\nOn Line = label sits on top of the EMA line, just left of the last candle.\nRight Of Chart = label sits right after the last candle.")
lblOffset  = input.int(0, "Label Offset (bars)", minval=0, maxval=100, group=grpL, tooltip="Extra gap (in bars) between the line end and the label.")
lblSizeIn  = input.string("large", "EMA Label Size", options=["tiny", "small", "normal", "large"], group=grpL)
lblNudge   = input.float(0.0, "Label Height Above Line", minval=0.0, maxval=2.0, step=0.05, group=grpL, tooltip="How far above the line the label sits (in ATR). On Line mode only.")
 
// =====================================================
// SIGNALS
// =====================================================
grpS             = "Signals"
showLaunch       = input.bool(true, "Show Breakout Labels", group=grpS, tooltip="▲ BULL / ▼ BEAR: ribbon breaks out of a squeeze, lined up per your Trend Mode, with price outside the ribbon.")
showCoil         = input.bool(true, "Show Squeeze Labels", group=grpS, tooltip="SQUEEZE: the ribbon just turned purple.")
showChop         = input.bool(true, "Show Chop Labels", group=grpS, tooltip="CHOP: the EMAs just got tangled — no clean trend. Stay out or size down.")
sigSizeIn        = input.string("small", "Signal Label Size", options=["tiny", "small", "normal", "large"], group=grpS, tooltip="Size for BULL, BEAR, SQUEEZE, CHOP and zone labels.")
launchCooldownIn = input.int(8, "Breakout Cooldown (Custom only)", minval=0, maxval=100, group=grpS, tooltip="Preset: 5m = 8, 1m = 15.")
coilCooldownIn   = input.int(6, "Squeeze Label Cooldown (Custom only)", minval=0, maxval=100, group=grpS, tooltip="Preset: 5m = 6, 1m = 10.")
chopCooldownIn   = input.int(6, "Chop Label Cooldown (Custom only)", minval=0, maxval=100, group=grpS, tooltip="Preset: 5m = 6, 1m = 15.")
 
// =====================================================
// ZONES
// =====================================================
grpZ        = "Breakout Zones"
showZones   = input.bool(false, "Show Zones", group=grpZ, tooltip="After a breakout, the squeeze area is drawn as a box. Bull breakout = SUPPORT, Bear breakout = RESISTANCE.")
zoneMinBars = input.int(3, "Min Squeeze Bars For Zone", minval=1, maxval=20, group=grpZ)
zoneBarsIn  = input.int(24, "Zone Length (Custom only)", minval=5, maxval=240, group=grpZ, tooltip="How long a zone stays live. Preset: 5m = 24 (2 hrs), 1m = 60 (1 hr).")
maxZones    = input.int(2, "Max Zones On Chart", minval=1, maxval=8, group=grpZ)
zoneOnClose = input.bool(true, "Break Only On Candle Close", group=grpZ, tooltip="On = zone breaks only when a candle closes through it. Off = a wick through it breaks it.")
 
// =====================================================
// HIT RATE
// =====================================================
grpH           = "Hit Rate"
followWindowIn = input.int(18, "Bars To Hit Target (Custom only)", minval=4, maxval=300, group=grpH, tooltip="Signal times out (not counted) if neither target nor stop is hit. Preset: 5m = 18, 1m = 45.")
tgtAtrIn       = input.float(1.2, "Target ATR (Custom only)", minval=0.2, maxval=6.0, step=0.1, group=grpH, tooltip="Preset: 5m = 1.2, 1m = 1.5.")
stpAtrIn       = input.float(1.2, "Stop ATR (Custom only)", minval=0.2, maxval=6.0, step=0.1, group=grpH, tooltip="Preset: 5m = 1.2, 1m = 1.5.")
 
// =====================================================
// PROJECTION
// =====================================================
grpP           = "EMA Projection"
showProj       = input.bool(false, "Show EMA Projection", group=grpP, tooltip="Dotted line showing where each EMA could go next.")
projStyle      = input.string("Curved", "Projection Style", options=["Curved", "Straight"], group=grpP, tooltip="Curved = where each EMA goes if price holds at the chosen level (bends toward price).\nStraight = extends each EMA's recent slope in a straight line.")
projMode       = input.string("Flat Price", "Projection Mode (Curved only)", options=["Flat Price", "Custom Price"], group=grpP, tooltip="Flat Price = price stays at current close.\nCustom Price = price moves to your target and holds there.")
customPrice    = input.float(0.0, "Custom Price", step=0.01, group=grpP, tooltip="Used in Custom Price mode. 0 = use current close.")
straightBarsIn = input.int(10, "Slope Bars (Custom only)", minval=1, maxval=200, group=grpP, tooltip="Bars used to measure slope for the Straight style. Preset: 5m = 10, 1m = 15.")
projBarsIn     = input.int(15, "Bars Ahead (Custom only)", minval=1, maxval=500, group=grpP, tooltip="Preset: 5m = 15, 1m = 20.")
showProjLbl    = input.bool(false, "Show Projection End Values", group=grpP, tooltip="Shows '9 → price' at the tip of each projection. Hidden automatically when EMA labels are set to End Of Projection.")
 
// =====================================================
// PANEL
// =====================================================
grpX      = "Panel"
showPanel = input.bool(true, "Show Panel", group=grpX)
panelPos  = input.string("Bottom Right", "Panel Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=grpX)
 
// =====================================================
// APPLY PRESET
// =====================================================
is1mChart  = timeframe.isminutes and timeframe.multiplier == 1
useCustom  = presetIn == "Custom"
use1m      = presetIn == "1 Min" or (presetIn == "Auto" and is1mChart)
presetName = useCustom ? "Custom" : (presetIn == "Auto" ? "Auto → " : "") + (use1m ? "1 Min" : "5 Min")
 
compLookback   = useCustom ? compLookbackIn   : use1m ? 150  : 80
compThresh     = useCustom ? compThreshIn     : use1m ? 88.0 : 85.0
sqzMinBars     = useCustom ? sqzMinBarsIn     : use1m ? 8    : 5
slopeLb        = useCustom ? slopeLbIn        : use1m ? 5    : 3
minWidthExp    = useCustom ? minWidthExpIn    : use1m ? 0.08 : 0.06
launchWindow   = useCustom ? launchWindowIn   : use1m ? 10   : 6
launchCooldown = useCustom ? launchCooldownIn : use1m ? 15   : 8
coilCooldown   = useCustom ? coilCooldownIn   : use1m ? 10   : 6
chopCooldown   = useCustom ? chopCooldownIn   : use1m ? 15   : 6
zoneBars       = useCustom ? zoneBarsIn       : use1m ? 60   : 24
followWindow   = useCustom ? followWindowIn   : use1m ? 45   : 18
tgtAtr         = useCustom ? tgtAtrIn         : use1m ? 1.5  : 1.2
stpAtr         = useCustom ? stpAtrIn         : use1m ? 1.5  : 1.2
straightBars   = useCustom ? straightBarsIn   : use1m ? 15   : 10
projBars       = useCustom ? projBarsIn       : use1m ? 20   : 15
 
// =====================================================
// HELPERS
// =====================================================
f_clamp(float x, float lo, float hi) => math.max(lo, math.min(hi, x))
f_slope(float x) => x - nz(x[slopeLb], x)
f_size(string s) =>
    switch s
        "tiny"   => size.tiny
        "normal" => size.normal
        "large"  => size.large
        => size.small
f_pos(string p) =>
    switch p
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
sigSz = f_size(sigSizeIn)
 
// =====================================================
// EMA CALCULATIONS
// =====================================================
e1 = ta.ema(src, len1)
e2 = ta.ema(src, len2)
e3 = ta.ema(src, len3)
e4 = ta.ema(src, len4)
e5 = ta.ema(src, len5)
e6 = ta.ema(src, len6)
eX = ta.ema(src, lenX)
 
ribHi  = math.max(e1, e2, e3, e4, e5, e6)
ribLo  = math.min(e1, e2, e3, e4, e5, e6)
atrV   = math.max(nz(ta.atr(atrLen), ta.tr(true)), syminfo.mintick)
widthN = (ribHi - ribLo) / atrV
 
// =====================================================
// SQUEEZE DETECTION
// =====================================================
// Ribbon type: how tight the ribbon is vs recent bars (100 = tightest)
wLo       = ta.lowest(widthN, compLookback)
wHi       = ta.highest(widthN, compLookback)
wPos      = f_clamp((widthN - wLo) / math.max(wHi - wLo, 0.000001), 0.0, 1.0)
compScore = 100.0 * (1.0 - wPos)
 
// TTM type: Bollinger Bands inside Keltner Channels
bbBasis = ta.sma(src, ttmLen)
bbDev   = ttmBB * ta.stdev(src, ttmLen)
kcBasis = ta.ema(src, ttmLen)
kcRange = ttmKC * ta.atr(ttmLen)
ttmOn   = (bbBasis + bbDev) < (kcBasis + kcRange) and (bbBasis - bbDev) > (kcBasis - kcRange)
 
rawSqz = sqzType == "TTM" ? ttmOn : compScore >= compThresh
 
// Must last Min Squeeze Bars in a row
var int sqzStreak = 0
sqzStreak  := rawSqz ? sqzStreak + 1 : 0
compressed = sqzStreak >= sqzMinBars
 
// Slopes
s1 = f_slope(e1)
s2 = f_slope(e2)
s3 = f_slope(e3)
s4 = f_slope(e4)
s5 = f_slope(e5)
s6 = f_slope(e6)
 
// =====================================================
// TREND CHECK (depends on Trend Mode + Only Checked)
// =====================================================
emaVals = array.from(e1, e2, e3, e4, e5, e6)
emaSlps = array.from(s1, s2, s3, s4, s5, s6)
emaShow = array.from(show1, show2, show3, show4, show5, show6)
 
useSet = array.new<int>()
for i = 0 to 5
    if not onlyChecked or emaShow.get(i)
        useSet.push(i)
if useSet.size() < 2
    useSet.clear()
    for i = 0 to 5
        useSet.push(i)
 
useN   = trendMode == "Fast" ? math.min(3, useSet.size()) : useSet.size()
nPairs = useN - 1
 
int bullPairs = 0
int bearPairs = 0
int upSlopes  = 0
int dnSlopes  = 0
for j = 0 to useN - 1
    idx = useSet.get(j)
    sl  = emaSlps.get(idx)
    upSlopes += sl > 0 ? 1 : 0
    dnSlopes += sl < 0 ? 1 : 0
    if j < useN - 1
        nxt = useSet.get(j + 1)
        bullPairs += emaVals.get(idx) > emaVals.get(nxt) ? 1 : 0
        bearPairs += emaVals.get(idx) < emaVals.get(nxt) ? 1 : 0
 
needPairs  = trendMode == "Balanced" ? math.max(nPairs - 1, 1) : nPairs
needSlopes = trendMode == "Fast" ? useN : trendMode == "Balanced" ? math.max(useN - 2, 1) : math.min(minSlopes, useN)
 
bullTrend = bullPairs >= needPairs and upSlopes >= needSlopes
bearTrend = bearPairs >= needPairs and dnSlopes >= needSlopes
 
// State: 2 = squeeze, 1 = bull, -1 = bear, 0 = chop
showSqz = compressed and not (trendBeatsSqz and (bullTrend or bearTrend))
state   = showSqz ? 2 : bullTrend ? 1 : bearTrend ? -1 : 0
baseCol = state == 2 ? compCol : state == 1 ? bullCol : state == -1 ? bearCol : mixedCol
xCol    = matchX ? baseCol : colX
 
// =====================================================
// SQUEEZE TRACKING (for zones + breakouts)
// =====================================================
compStart = compressed and not compressed[1]
compExit  = not compressed and compressed[1]
 
var bool  coilOn        = false
var int   coilStart     = na
var float coilTop       = na
var float coilBot       = na
var int   coilBars      = 0
var int   lastCoilStart = na
var float lastCoilTop   = na
var float lastCoilBot   = na
var int   lastCoilBars  = 0
var int   lastExit      = na
 
if compStart
    coilOn    := true
    coilStart := bar_index - (sqzMinBars - 1)
    coilTop   := ribHi
    coilBot   := ribLo
    coilBars  := sqzMinBars
else if compressed and coilOn
    coilTop  := math.max(coilTop, ribHi)
    coilBot  := math.min(coilBot, ribLo)
    coilBars += 1
 
if compExit
    lastExit := bar_index
    if coilOn
        lastCoilStart := coilStart
        lastCoilTop   := coilTop
        lastCoilBot   := coilBot
        lastCoilBars  := coilBars
        coilOn        := false
 
// =====================================================
// BREAKOUT / SQUEEZE / CHOP SIGNALS
// =====================================================
var int lastLaunchBar = na
var int lastCoilBar   = na
var int lastChopBar   = na
 
inWindow       = not na(lastExit) and bar_index - lastExit <= launchWindow
widthExpanding = widthN - nz(widthN[1], widthN) > minWidthExp
bullLaunchRaw  = inWindow and bullTrend and close > ribHi and widthExpanding
bearLaunchRaw  = inWindow and bearTrend and close < ribLo and widthExpanding
canLaunch      = na(lastLaunchBar) or bar_index - lastLaunchBar >= launchCooldown
 
bullLaunch = bullLaunchRaw and not bullLaunchRaw[1] and canLaunch
bearLaunch = bearLaunchRaw and not bearLaunchRaw[1] and canLaunch
if bullLaunch or bearLaunch
    lastLaunchBar := bar_index
 
// SQUEEZE label = ribbon just turned purple
sqzTurnedOn = state == 2 and state[1] != 2
coilSig = sqzTurnedOn and (na(lastCoilBar) or bar_index - lastCoilBar >= coilCooldown)
if coilSig
    lastCoilBar := bar_index
 
chopSig = state == 0 and state[1] != 0 and (na(lastChopBar) or bar_index - lastChopBar >= chopCooldown)
if chopSig
    lastChopBar := bar_index
 
// =====================================================
// PLOTS
// =====================================================
lc(float k) => color.new(baseCol, int(math.round(lineSoft * k)))
 
p1 = plot(e1, "EMA 1", showLines and show1 ? lc(0.00) : na, lineW)
p2 = plot(e2, "EMA 2", showLines and show2 ? lc(0.20) : na, lineW)
p3 = plot(e3, "EMA 3", showLines and show3 ? lc(0.40) : na, lineW)
p4 = plot(e4, "EMA 4", showLines and show4 ? lc(0.60) : na, lineW)
p5 = plot(e5, "EMA 5", showLines and show5 ? lc(0.80) : na, lineW)
p6 = plot(e6, "EMA 6", showLines and show6 ? lc(0.95) : na, lineW)
 
// Fill: whole ribbon, or only between EMA 1 and EMA 2 (9 & 21)
fillAll  = fillMode == "All EMAs"
fillCol  = showFill ? color.new(baseCol, fillTransp) : na
fillRest = fillAll ? fillCol : na
fill(p1, p2, fillCol)
fill(p2, p3, fillRest)
fill(p3, p4, fillRest)
fill(p4, p5, fillRest)
fill(p5, p6, fillRest)
 
plot(showX ? eX : na, "Extra EMA", xCol, wX)
 
barcolor(barTint ? color.new(baseCol, 80) : na)
 
// Signal labels (size adjustable)
if showLaunch and bullLaunch
    label.new(bar_index, low, "▲ BULL", xloc.bar_index, yloc.belowbar, bullCol, label.style_label_up, color.black, sigSz)
if showLaunch and bearLaunch
    label.new(bar_index, high, "▼ BEAR", xloc.bar_index, yloc.abovebar, bearCol, label.style_label_down, color.black, sigSz)
if showCoil and coilSig
    label.new(bar_index, high, "SQUEEZE", xloc.bar_index, yloc.abovebar, compCol, label.style_label_down, color.white, sigSz)
if showChop and chopSig
    label.new(bar_index, high, "CHOP", xloc.bar_index, yloc.abovebar, mixedCol, label.style_label_down, color.black, sigSz)
 
// =====================================================
// BREAKOUT ZONES
// =====================================================
var array<box>   zBoxes = array.new<box>()
var array<label> zLbls  = array.new<label>()
var array<int>   zDir   = array.new<int>()
var array<int>   zBorn  = array.new<int>()
var array<bool>  zLive  = array.new<bool>()
var array<float> zTop   = array.new<float>()
var array<float> zBot   = array.new<float>()
 
if showZones and (bullLaunch or bearLaunch) and lastCoilBars >= zoneMinBars and not na(lastCoilStart)
    zc    = bullLaunch ? bullCol : bearCol
    right = bar_index + zoneBars
    zBoxes.push(box.new(left=lastCoilStart, top=lastCoilTop, right=right, bottom=lastCoilBot, xloc=xloc.bar_index, border_color=color.new(zc, 40), border_width=1, bgcolor=color.new(zc, 85)))
    zLbls.push(label.new(int((lastCoilStart + right) / 2), (lastCoilTop + lastCoilBot) / 2, bullLaunch ? "SUPPORT" : "RESISTANCE", xloc=xloc.bar_index, style=label.style_label_center, color=color.new(color.white, 100), textcolor=zc, size=sigSz))
    zDir.push(bullLaunch ? 1 : -1)
    zBorn.push(bar_index)
    zLive.push(true)
    zTop.push(lastCoilTop)
    zBot.push(lastCoilBot)
    lastCoilStart := na
    lastCoilBars  := 0
    if zBoxes.size() > maxZones
        zBoxes.shift().delete()
        zLbls.shift().delete()
        zDir.shift()
        zBorn.shift()
        zLive.shift()
        zTop.shift()
        zBot.shift()
 
zn = zBoxes.size()
if zn > 0
    for i = 0 to zn - 1
        if zLive.get(i)
            dir     = zDir.get(i)
            zt      = zTop.get(i)
            zb      = zBot.get(i)
            expired = bar_index - zBorn.get(i) > zoneBars
            broken  = zoneOnClose ? (dir == 1 ? close < zb : close > zt) : (dir == 1 ? low < zb : high > zt)
            if expired or broken
                b = zBoxes.get(i)
                b.set_right(bar_index)
                b.set_bgcolor(color.new(color.gray, 90))
                b.set_border_color(color.new(color.gray, 70))
                lb = zLbls.get(i)
                lb.set_text(broken ? "BROKEN" : "OLD")
                lb.set_x(int((b.get_left() + bar_index) / 2))
                lb.set_textcolor(color.gray)
                zLive.set(i, false)
 
// =====================================================
// HIT RATE (did breakouts reach target before stop?)
// =====================================================
var int   wins  = 0
var int   total = 0
var bool  pend  = false
var int   pDir  = 0
var float pTgt  = na
var float pStp  = na
var int   pBar  = na
 
if barstate.isconfirmed
    if pend
        hitS = pDir == 1 ? low <= pStp : high >= pStp
        hitT = pDir == 1 ? high >= pTgt : low <= pTgt
        if hitS
            total += 1
            pend  := false
        else if hitT
            wins  += 1
            total += 1
            pend  := false
        else if bar_index - pBar >= followWindow
            pend := false
    if not pend and (bullLaunch or bearLaunch)
        pDir := bullLaunch ? 1 : -1
        pTgt := close + pDir * atrV * tgtAtr
        pStp := close - pDir * atrV * stpAtr
        pBar := bar_index
        pend := true
 
// =====================================================
// EMA LABELS + PROJECTION (last bar)
// Curved:   EMA_k = P + (EMA_now - P) * (1 - alpha)^k , alpha = 2/(len+1)
// Straight: EMA_k = EMA_now + slopePerBar * k
// =====================================================
var array<label>    emaLbls   = array.new<label>()
var array<polyline> projLines = array.new<polyline>()
var array<label>    projLbls  = array.new<label>()
 
if barstate.islast
    for l in emaLbls
        l.delete()
    emaLbls.clear()
    for p in projLines
        p.delete()
    projLines.clear()
    for l in projLbls
        l.delete()
    projLbls.clear()
 
    // Index 6 = extra EMA
    vals   = array.from(e1, e2, e3, e4, e5, e6, eX)
    prevs  = array.from(e1[straightBars], e2[straightBars], e3[straightBars], e4[straightBars], e5[straightBars], e6[straightBars], eX[straightBars])
    lens   = array.from(len1, len2, len3, len4, len5, len6, lenX)
    shows  = array.from(show1, show2, show3, show4, show5, show6, showX)
    target = projMode == "Custom Price" and customPrice > 0 ? customPrice : close
    lblSz  = f_size(lblSizeIn)
    onLine = lblSide == "On Line"
    atEnd  = lblSide == "End Of Projection"
    lblX   = onLine ? bar_index - lblOffset : bar_index + lblOffset
    lblSt  = onLine ? label.style_none : label.style_label_left
 
    for i = 0 to 6
        isX  = i == 6
        e0   = vals.get(i)
        lenI = lens.get(i)
        colI = isX ? xCol : baseCol
        if not na(e0) and shows.get(i)
            doProj  = showProj and (not isX or projX)
            float v = e0
            if doProj
                decay = 1.0 - 2.0 / (lenI + 1)
                slope = (e0 - nz(prevs.get(i), e0)) / straightBars
                pts   = array.new<chart.point>()
                for k = 0 to projBars
                    v := projStyle == "Curved" ? target + (e0 - target) * math.pow(decay, k) : e0 + slope * k
                    pts.push(chart.point.from_index(bar_index + k, v))
                projLines.push(polyline.new(pts, false, false, xloc.bar_index, color.new(colI, 20), na, line.style_dotted, 1))
 
            if showEmaLbl
                if atEnd and doProj
                    emaLbls.push(label.new(bar_index + projBars + lblOffset, v, str.tostring(lenI) + " EMA", xloc.bar_index, yloc.price, color.new(color.white, 100), label.style_label_left, colI, lblSz))
                else
                    lblY = onLine ? e0 + atrV * lblNudge : e0
                    emaLbls.push(label.new(lblX, lblY, str.tostring(lenI) + " EMA", xloc.bar_index, yloc.price, color.new(color.white, 100), lblSt, colI, lblSz))
 
            if doProj and showProjLbl and not (atEnd and showEmaLbl)
                projLbls.push(label.new(bar_index + projBars, v, str.tostring(lenI) + " → " + str.tostring(math.round_to_mintick(v)), xloc.bar_index, yloc.price, color.new(color.white, 100), label.style_label_left, colI, size.tiny))
 
// =====================================================
// PANEL
// =====================================================
var table pnl = table.new(f_pos(panelPos), 2, 7, bgcolor=color.new(#0F172A, 5), border_width=1, border_color=color.new(color.gray, 70))
 
if barstate.islast
    pnl.clear(0, 0, 1, 6)
    if showPanel
        trendTxt = state == 2 ? "SQUEEZE" : state == 1 ? "UP" : state == -1 ? "DOWN" : "CHOP"
        sqzTxt   = sqzType == "TTM" ? (compressed ? "ON (TTM)" : "OFF (TTM)") : str.tostring(math.round(compScore)) + "%" + (compressed ? " ON" : "")
        lineTxt  = bullPairs >= bearPairs ? str.tostring(bullPairs) + " of " + str.tostring(nPairs) + " up" : str.tostring(bearPairs) + " of " + str.tostring(nPairs) + " down"
        hitTxt   = total < 5 ? "need more signals (" + str.tostring(total) + ")" : str.tostring(math.round(wins / total * 100.0)) + "% of " + str.tostring(total)
        modeTxt  = trendMode + (onlyChecked ? " (checked)" : "")
        pnl.cell(0, 0, "Trend", text_color=color.gray, text_size=size.small)
        pnl.cell(1, 0, trendTxt, bgcolor=baseCol, text_color=color.black, text_size=size.small)
        pnl.cell(0, 1, "Squeeze", text_color=color.gray, text_size=size.small)
        pnl.cell(1, 1, sqzTxt, text_color=color.white, text_size=size.small)
        pnl.cell(0, 2, "Lined Up", text_color=color.gray, text_size=size.small)
        pnl.cell(1, 2, lineTxt, text_color=color.white, text_size=size.small)
        pnl.cell(0, 3, "Rising / Falling", text_color=color.gray, text_size=size.small)
        pnl.cell(1, 3, str.tostring(upSlopes) + " / " + str.tostring(dnSlopes), text_color=color.white, text_size=size.small)
        pnl.cell(0, 4, "Hit Rate", text_color=color.gray, text_size=size.small)
        pnl.cell(1, 4, hitTxt, text_color=color.white, text_size=size.small)
        pnl.cell(0, 5, "Preset", text_color=color.gray, text_size=size.small)
        pnl.cell(1, 5, presetName, text_color=color.white, text_size=size.small)
        pnl.cell(0, 6, "Mode", text_color=color.gray, text_size=size.small)
        pnl.cell(1, 6, modeTxt, text_color=color.white, text_size=size.small)
 
// =====================================================
// ALERTS
// =====================================================
alertcondition(bullLaunch, "Bull Breakout", "EMA Trend: BULL breakout from squeeze")
alertcondition(bearLaunch, "Bear Breakout", "EMA Trend: BEAR breakout from squeeze")
alertcondition(sqzTurnedOn, "Squeeze Started", "EMA Trend: squeeze started")
alertcondition(chopSig, "Turned Chop", "EMA Trend: EMAs tangled — CHOP")
alertcondition(state == 1 and state[1] != 1, "Turned Up", "EMA Trend: trend turned UP")
alertcondition(state == -1 and state[1] != -1, "Turned Down", "EMA Trend: trend turned DOWN")

← 返回列表