BTM - SuperTrend PRO

BeyondTheMarkets · study · 333 行 · 点赞 60 · TradingView 原页

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

Pine Script

//@version=6
indicator("BTM - SuperTrend PRO", shorttitle = "BTM - SuperTrend PRO", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
// ═════════ BTM - SuperTrend PRO ═════════
 
// ═════════ INPUTS ═════════
grpST       = "Supertrend"
atrPeriod   = input.int(10, "ATR Period", minval = 1, group = grpST)
factor      = input.float(3.0, "ATR Multiplier", minval = 0.1, step = 0.1, group = grpST)
src         = input.source(hl2, "Source", group = grpST)
useRmaAtr   = input.bool(true, "Use standard ATR (off = SMA of True Range)", group = grpST)
upColor     = input.color(color.new(#00C853, 0), "Uptrend colour", group = grpST)
dnColor     = input.color(color.new(#FF1744, 0), "Downtrend colour", group = grpST)
showSignals = input.bool(true, "Show BUY/SELL labels", group = grpST)
highlight   = input.bool(true, "Shade trend area", group = grpST)
 
grpF        = "Signal Filters"
confirmBar  = input.bool(true, "Wait for candle close (no repaint)", group = grpF)
useEma      = input.bool(false, "Only trade in EMA direction", group = grpF)
emaLen      = input.int(200, "EMA length", minval = 1, group = grpF)
minStrength = input.int(0, "Min trend strength % for signals (0 = off)", minval = 0, maxval = 100, group = grpF)
 
grpT        = "Trade Management"
tpMode      = input.string("Risk multiple (R)", "TP method", options = ["Risk multiple (R)", "ATR multiple"], group = grpT)
tp1Mult     = input.float(1.0, "TP1 multiple", minval = 0.1, step = 0.1, group = grpT)
tp2Mult     = input.float(2.0, "TP2 multiple", minval = 0.1, step = 0.1, group = grpT)
partialPct  = input.float(50, "Close % at TP1", minval = 0, maxval = 100, step = 5, group = grpT)
moveBE      = input.bool(true, "Move SL to breakeven after TP1", group = grpT)
 
grpS        = "Style"
entryColor  = input.color(color.yellow, "Entry", group = grpS)
slColor     = input.color(color.red, "Stop-loss", group = grpS)
tpColor     = input.color(color.blue, "Take-profit", group = grpS)
closedColor = input.color(color.new(color.gray, 40), "Closed trade", group = grpS)
lineWidth   = input.int(2, "Line width", minval = 1, maxval = 5, group = grpS)
extendBars  = input.int(8, "Extend open trade (bars)", minval = 0, maxval = 50, group = grpS)
showZones   = input.bool(true, "Shade risk / reward zones", group = grpS)
 
grpTb       = "Trade Table"
showTable   = input.bool(true, "Show table", group = grpTb)
tableStyle  = input.string("3D", "Table style", options = ["3D", "2D"], group = grpTb)
tablePos    = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpTb)
tableSize   = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = grpTb)
buyText     = input.color(#00E676, "Buy text colour", group = grpTb)
sellText    = input.color(#FF5252, "Sell text colour", group = grpTb)
 
grpG        = "Strength Meter"
showGauge   = input.bool(true, "Show strength gauge", group = grpG)
gaugePos    = input.string("Bottom Right", "Gauge position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Top Center", "Bottom Center"], group = grpG)
adxLen      = input.int(14, "ADX length", minval = 1, group = grpG)
adxFloor    = input.float(15, "ADX at 0% (ranging)", minval = 0, group = grpG)
adxCeil     = input.float(45, "ADX at 100% (strong trend)", minval = 1, group = grpG)
segW        = input.float(1.6, "Segment width", minval = 0.5, step = 0.1, group = grpG)
segH        = input.float(2.5, "Segment height", minval = 0.5, step = 0.1, group = grpG)
 
// ═════════ SUPERTREND ═════════
atr = useRmaAtr ? ta.atr(atrPeriod) : ta.sma(ta.tr(true), atrPeriod)
 
float up = src - factor * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
 
float dn = src + factor * atr
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
 
var int trend = 1
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
 
ema = ta.ema(close, emaLen)
 
// ═════════ TREND STRENGTH (ADX → 0-100%) ═════════
[diPlus, diMinus, adx] = ta.dmi(adxLen, adxLen)
strength = math.max(0.0, math.min(100.0, (nz(adx) - adxFloor) / math.max(adxCeil - adxFloor, 1) * 100))
strengthTxt = strength >= 75 ? "STRONG TREND" : strength >= 50 ? "TRENDING" : strength >= 25 ? "WEAK TREND" : "RANGING"
 
flip       = trend != trend[1] and (not confirmBar or barstate.isconfirmed)
strengthOk = strength >= minStrength
buySignal  = flip and trend == 1  and (not useEma or close > ema) and strengthOk
sellSignal = flip and trend == -1 and (not useEma or close < ema) and strengthOk
newSignal  = buySignal or sellSignal
 
// ═════════ HELPERS ═════════
fmt(float p) =>
    str.tostring(p, format.mintick)
 
fmtR(float r) =>
    (r >= 0 ? "+" : "") + str.tostring(r, "#.##") + "R"
 
// ═════════ TRADE STATE ═════════
var float entry = na
var float sl    = na
var float tp1   = na
var float tp2   = na
var float risk  = na
var float r1    = na
var float r2    = na
var float realR = 0.0
var int   pos    = 0
var bool  active = false
var bool  tp1Hit = false
 
var array<line>  lns = array.new<line>()    // 0 entry, 1 sl, 2 tp1, 3 tp2
var array<label> lbs = array.new<label>()
var box riskBox   = na
var box rewardBox = na
 
part = partialPct / 100
 
bool   slHitNow    = false
bool   tp1HitNow   = false
bool   tp2HitNow   = false
bool   closeNow    = false
float  exitLegR    = na
string closeReason = ""
 
// ═════════ MANAGE OPEN TRADE ═════════
if active
    xr = bar_index + extendBars
    for l in lns
        line.set_x2(l, xr)
    for lb in lbs
        label.set_x(lb, xr)
    if showZones
        box.set_right(riskBox, xr)
        box.set_right(rewardBox, xr)
 
    if pos == 1
        if low <= sl
            slHitNow := true
        else
            tp1HitNow := not tp1Hit and high >= tp1
            tp2HitNow := high >= tp2
    else
        if high >= sl
            slHitNow := true
        else
            tp1HitNow := not tp1Hit and low <= tp1
            tp2HitNow := low <= tp2
 
    if tp1HitNow
        tp1Hit := true
        realR  += part * r1
        label.set_text(lbs.get(2), "TP1 ✓  " + fmt(tp1))
        if moveBE and not tp2HitNow
            sl := entry
            line.set_y1(lns.get(1), entry)
            line.set_y2(lns.get(1), entry)
            label.set_y(lbs.get(1), entry)
            label.set_text(lbs.get(1), "SL → BE  " + fmt(entry))
            if showZones
                box.set_top(riskBox, entry)
                box.set_bottom(riskBox, entry)
 
    if tp2HitNow
        exitLegR    := r2
        closeReason := "TP2"
        closeNow    := true
        label.set_text(lbs.get(3), "TP2 ✓  " + fmt(tp2))
 
    if slHitNow
        exitLegR    := (sl - entry) * pos / risk
        closeReason := sl == entry ? "BE" : "SL"
        closeNow    := true
        label.set_text(lbs.get(1), (sl == entry ? "BE STOP  " : "SL HIT ✗  ") + fmt(sl))
 
// Trend flip exits an open trade at the close
if active and flip and not closeNow
    exitLegR    := (close - entry) * pos / risk
    closeReason := "FLIP"
    closeNow    := true
 
// ═════════ CLOSE TRADE: GREY OUT ═════════
if closeNow
    rem    = tp1Hit ? 1 - part : 1.0
    tradeR = realR + rem * exitLegR
    active := false
    for l in lns
        line.set_x2(l, bar_index)
        line.set_color(l, closedColor)
    for lb in lbs
        label.set_x(lb, bar_index)
        label.set_color(lb, closedColor)
        label.set_textcolor(lb, color.white)
    label.set_text(lbs.get(0), label.get_text(lbs.get(0)) + "   " + closeReason + " " + fmtR(tradeR))
    if showZones
        box.set_right(riskBox, bar_index)
        box.set_right(rewardBox, bar_index)
        box.set_bgcolor(riskBox, color.new(color.gray, 92))
        box.set_bgcolor(rewardBox, color.new(color.gray, 92))
 
// ═════════ OPEN NEW TRADE ═════════
if newSignal
    pos    := buySignal ? 1 : -1
    entry  := close
    sl     := pos == 1 ? up : dn
    risk   := math.max(math.abs(entry - sl), syminfo.mintick)
    dist    = tpMode == "Risk multiple (R)" ? risk : atr
    tp1    := entry + pos * dist * tp1Mult
    tp2    := entry + pos * dist * tp2Mult
    r1     := (tp1 - entry) * pos / risk
    r2     := (tp2 - entry) * pos / risk
    realR  := 0.0
    tp1Hit := false
    active := true
 
    xr = bar_index + extendBars
    lns.clear()
    lbs.clear()
    lns.push(line.new(bar_index, entry, xr, entry, color = entryColor, width = lineWidth))
    lns.push(line.new(bar_index, sl,    xr, sl,    color = slColor,    width = lineWidth))
    lns.push(line.new(bar_index, tp1,   xr, tp1,   color = tpColor,    width = lineWidth, style = line.style_dashed))
    lns.push(line.new(bar_index, tp2,   xr, tp2,   color = tpColor,    width = lineWidth))
 
    lbs.push(label.new(xr, entry, (pos == 1 ? "▲ LONG  " : "▼ SHORT  ") + fmt(entry), style = label.style_label_left, color = entryColor, textcolor = color.black, size = size.small))
    lbs.push(label.new(xr, sl,  "SL  " + fmt(sl), style = label.style_label_left, color = slColor, textcolor = color.white, size = size.small))
    lbs.push(label.new(xr, tp1, "TP1 (" + str.tostring(r1, "#.#") + "R)  " + fmt(tp1), style = label.style_label_left, color = tpColor, textcolor = color.white, size = size.small))
    lbs.push(label.new(xr, tp2, "TP2 (" + str.tostring(r2, "#.#") + "R)  " + fmt(tp2), style = label.style_label_left, color = tpColor, textcolor = color.white, size = size.small))
 
    if showZones
        riskBox   := box.new(bar_index, math.max(entry, sl),  xr, math.min(entry, sl),  border_width = 0, border_color = color.new(slColor, 100), bgcolor = color.new(slColor, 85))
        rewardBox := box.new(bar_index, math.max(entry, tp2), xr, math.min(entry, tp2), border_width = 0, border_color = color.new(tpColor, 100), bgcolor = color.new(tpColor, 85))
 
    alert("BTM - SuperTrend PRO | " + (pos == 1 ? "LONG " : "SHORT ") + syminfo.ticker + " | Entry " + fmt(entry) + " | SL " + fmt(sl) + " | TP1 " + fmt(tp1) + " | TP2 " + fmt(tp2) + " | Strength " + str.tostring(strength, "#") + "%", alert.freq_once_per_bar_close)
 
// ═════════ PLOTS ═════════
upPlot = plot(trend == 1 ? up : na, "Uptrend", color = upColor, linewidth = 2, style = plot.style_linebr)
dnPlot = plot(trend == -1 ? dn : na, "Downtrend", color = dnColor, linewidth = 2, style = plot.style_linebr)
plot(useEma ? ema : na, "EMA filter", color = color.new(color.orange, 20), linewidth = 1)
 
plotshape(showSignals and buySignal ? up : na, title = "Buy", style = shape.labelup,
     location = location.absolute, color = upColor, text = "BUY", textcolor = color.white, size = size.small)
plotshape(showSignals and sellSignal ? dn : na, title = "Sell", style = shape.labeldown,
     location = location.absolute, color = dnColor, text = "SELL", textcolor = color.white, size = size.small)
 
midPlot = plot(ohlc4, "Mid", display = display.none, editable = false)
fill(midPlot, upPlot, color = highlight ? color.new(upColor, 90) : na, title = "Uptrend fill")
fill(midPlot, dnPlot, color = highlight ? color.new(dnColor, 90) : na, title = "Downtrend fill")
 
// ═════════ TABLE SETTINGS ═════════
toPos(string p) =>
    switch p
        "Top Left"      => position.top_left
        "Bottom Right"  => position.bottom_right
        "Bottom Left"   => position.bottom_left
        "Top Center"    => position.top_center
        "Bottom Center" => position.bottom_center
        => position.top_right
 
txtSize = switch tableSize
    "Tiny"   => size.tiny
    "Normal" => size.normal
    "Large"  => size.large
    => size.small
 
var table tbl   = table.new(toPos(tablePos), 2, 9)
var table gauge = table.new(toPos(gaugePos), 12, 2)
 
cellRow(table t, int r, string k, string v, color tc, color bg) =>
    table.cell(t, 0, r, k, text_color = tc, bgcolor = bg, text_size = txtSize, text_halign = text.align_left)
    table.cell(t, 1, r, v, text_color = tc, bgcolor = bg, text_size = txtSize, text_halign = text.align_right)
 
// ═════════ TRADE TABLE ═════════
if showTable and barstate.islast
    bull = trend == 1
    is3D = tableStyle == "3D"
 
    // Trend-tinted palette (dark so coloured text stays readable)
    hdrBg    = bull ? #1B5E3A : #6B1A26
    bodyBg   = bull ? #0E2A1C : #2A0E13
    altBg    = bull ? #143A27 : #3A141B
    frameCol = bull ? #00E676 : #FF1744
 
    // Row backgrounds: alternating stripes in 3D, flat in 2D
    bgEven = is3D ? altBg : bodyBg
    bgOdd  = bodyBg
    bgHdr  = is3D ? hdrBg : bodyBg
 
    // All text follows the open trade: green for buy, red for sell, white when flat
    tc = active ? (pos == 1 ? buyText : sellText) : color.white
 
    table.set_bgcolor(tbl, bodyBg)
    table.set_frame_color(tbl, frameCol)
    table.set_frame_width(tbl, is3D ? 3 : 1)
    table.set_border_color(tbl, is3D ? color.new(color.black, 20) : bodyBg)
    table.set_border_width(tbl, is3D ? 1 : 0)
 
    posTxt = active ? (pos == 1 ? "▲ LONG" : "▼ SHORT") : "FLAT"
    openR  = active ? realR + (tp1Hit ? 1 - part : 1.0) * (close - entry) * pos / risk : na
 
    cellRow(tbl, 0, "BTM - SuperTrend PRO", bull ? "▲ BULLISH" : "▼ BEARISH", tc, bgHdr)
    cellRow(tbl, 1, "Position", posTxt, tc, bgOdd)
    cellRow(tbl, 2, "Entry",    active ? fmt(entry) : "—", tc, bgEven)
    cellRow(tbl, 3, "Stop",     active ? fmt(sl) + (sl == entry ? " (BE)" : "") : "—", tc, bgOdd)
    cellRow(tbl, 4, "TP1",      active ? fmt(tp1) + (tp1Hit ? " ✓" : "") : "—", tc, bgEven)
    cellRow(tbl, 5, "TP2",      active ? fmt(tp2) : "—", tc, bgOdd)
    cellRow(tbl, 6, "Open P/L", active ? fmtR(openR) : "—", tc, bgEven)
    cellRow(tbl, 7, "Strength", str.tostring(strength, "#") + "%", tc, bgOdd)
    cellRow(tbl, 8, "Market",   strengthTxt, tc, bgEven)
 
// ═════════ FUEL-GAUGE STRENGTH METER ═════════
if showGauge and barstate.islast
    gBull   = trend == 1
    gCol    = gBull ? #00E676 : #FF1744
    gBg     = gBull ? #0E2A1C : #2A0E13
    emptyC  = #1E222D
    filled  = int(math.round(strength / 10))   // 0..10 segments
 
    table.set_bgcolor(gauge, gBg)
    table.set_frame_color(gauge, gCol)
    table.set_frame_width(gauge, 2)
    table.set_border_color(gauge, color.new(color.black, 10))
    table.set_border_width(gauge, 1)
 
    // Row 0: E [segments] F
    table.cell(gauge, 0, 0, "E", text_color = gCol, text_size = txtSize)
    for i = 1 to 10
        segCol = i <= filled ? color.new(gCol, 70 - i * 6) : emptyC
        table.cell(gauge, i, 0, "", bgcolor = segCol, width = segW, height = segH)
    table.cell(gauge, 11, 0, "F", text_color = gCol, text_size = txtSize)
 
    // Row 1: fuel icon, needle under current level, percentage
    table.cell(gauge, 0, 1, filled == 0 ? "▲" : "⛽", text_color = gCol, text_size = txtSize)
    for i = 1 to 10
        table.cell(gauge, i, 1, i == filled ? "▲" : "", text_color = gCol, text_size = txtSize, width = segW)
    table.cell(gauge, 11, 1, str.tostring(strength, "#") + "%", text_color = gCol, text_size = txtSize)
 
// ═════════ ALERTS ═════════
alertcondition(buySignal,  "BTM - SuperTrend PRO: BUY",     "BTM - SuperTrend PRO | BUY on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(sellSignal, "BTM - SuperTrend PRO: SELL",    "BTM - SuperTrend PRO | SELL on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(tp1HitNow,  "BTM - SuperTrend PRO: TP1 hit", "BTM - SuperTrend PRO | TP1 hit on {{ticker}} ({{interval}})")
alertcondition(tp2HitNow,  "BTM - SuperTrend PRO: TP2 hit", "BTM - SuperTrend PRO | TP2 hit on {{ticker}} ({{interval}})")
alertcondition(slHitNow,   "BTM - SuperTrend PRO: SL hit",  "BTM - SuperTrend PRO | Stop-loss hit on {{ticker}} ({{interval}})")

← 返回列表