BTM - Volatility Momentum

BeyondTheMarkets · study · 248 行 · 点赞 15 · TradingView 原页

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

Pine Script

//@version=6
// ═════════════════════════════════════════════════════════════════════════════
//  BTM - Volatility Momentum
//
//  How it works
//  • Engine: the gap between a fast and a slow EMA, divided by the Average True
//    Range and scaled ×100. Because the gap is measured in "ATRs", the same
//    levels mean the same thing on any symbol or timeframe.
//  • Quiet zone: trigger crosses close to zero are ignored, because that is
//    where most false starts happen.
//  • Thrust gate: a short EMA's slope plus the histogram's slope decide whether
//    longs or shorts are allowed on a bar. The gate also colours the candles.
//  • Trend filter: momentum entries only in the direction of a long EMA.
//  • Pullback entries: in an uptrend, a turn up from deep negative momentum.
//  • Stretch exits: marks where momentum drops back out of the stretched zone.
//
//  Signals only confirm on closed bars, so they do not repaint.
//  For research and education only. Not financial advice.
// ═════════════════════════════════════════════════════════════════════════════
indicator("BTM - Volatility Momentum", shorttitle = "BTM VolMom", overlay = false, precision = 1)
 
// ─── Settings ────────────────────────────────────────────────────────────────
G_ENG  = "Engine"
G_LVL  = "Levels"
G_GATE = "Gates"
G_ENT  = "Entries"
G_LOOK = "Look"
G_PNL  = "Panel"
 
i_src     = input.source(close, "Price source", group = G_ENG)
i_fast    = input.int(12, "Fast EMA", minval = 1, group = G_ENG)
i_slow    = input.int(26, "Slow EMA", minval = 2, group = G_ENG)
i_trigger = input.int(9, "Trigger line", minval = 1, group = G_ENG)
i_atr     = input.int(26, "ATR length", minval = 1, group = G_ENG, tooltip = "Volatility yardstick. Matching it to the slow EMA keeps the scale steady.")
i_quick   = input.bool(false, "Quick fast line", group = G_ENG, tooltip = "Swaps the fast EMA for a lag-compensated one (2×EMA − EMA of EMA). Turns show sooner; expect a few more false starts in ranges.")
 
i_quiet   = input.float(50, "Quiet zone (±)", minval = 0, group = G_LVL, tooltip = "Trigger crosses inside this band are ignored.")
i_stretch = input.float(150, "Stretch level (±)", minval = 0, group = G_LVL, tooltip = "Beyond this, momentum is stretched and prone to snapping back.")
i_histMax = input.float(40, "Histogram full strength (±)", minval = 1, group = G_LVL, tooltip = "Histogram bars reach full colour at this size.")
 
i_useGate  = input.bool(true, "Thrust gate", group = G_GATE, tooltip = "No longs while thrust is down, no shorts while thrust is up.")
i_gateLen  = input.int(13, "Thrust EMA", minval = 1, group = G_GATE)
i_useTrend = input.bool(true, "Trend filter", group = G_GATE, tooltip = "Momentum longs only above the trend EMA, shorts only below it.")
i_trendLen = input.int(200, "Trend EMA", minval = 1, group = G_GATE)
 
i_mom    = input.bool(true, "Momentum entries", group = G_ENT, tooltip = "Trigger cross between the quiet zone and the stretch level.")
i_pb     = input.bool(true, "Pullback entries", group = G_ENT, tooltip = "Uptrend plus an upward trigger cross at or below −quiet zone. Shorts mirror this.")
i_exits  = input.bool(true, "Stretch-exit marks", group = G_ENT)
i_shorts = input.bool(false, "Include shorts", group = G_ENT, tooltip = "Off by default: short-side momentum signals tend to be less reliable.")
 
i_theme   = input.string("Neon", "Colour theme", options = ["Neon", "Ocean", "Sunset", "Mono"], group = G_LOOK)
i_hist    = input.string("Columns", "Histogram style", options = ["Columns", "Area", "Off"], group = G_LOOK)
i_cloud   = input.bool(true, "Line / trigger cloud", group = G_LOOK)
i_glow    = input.bool(true, "Glow", group = G_LOOK)
i_bands   = input.bool(true, "Shade levels", group = G_LOOK)
i_hiStr   = input.bool(true, "Highlight stretched momentum", group = G_LOOK)
i_candles = input.bool(true, "Colour candles by thrust", group = G_LOOK)
 
i_panel = input.bool(true, "Show panel", group = G_PNL)
i_where = input.string("Top right", "Position", options = ["Top right", "Middle right", "Bottom right", "Top left", "Bottom left"], group = G_PNL)
i_txt   = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal", "Large"], group = G_PNL)
i_mtf   = input.bool(true, "Higher-timeframe reading", group = G_PNL)
i_tf    = input.timeframe("D", "Higher timeframe", group = G_PNL, tooltip = "Reads the last completed bar of that timeframe, so it does not repaint.")
 
// ─── Palette ─────────────────────────────────────────────────────────────────
[UP, DN, HOT, MID, TRG] = switch i_theme
    "Ocean"  => [#00b8d4, #ff4081, #ffd740, #607d8b, chart.fg_color]
    "Sunset" => [#ffab40, #7c4dff, #ff5252, #8d6e63, chart.fg_color]
    "Mono"   => [#26a69a, #ef5350, #ff9800, #9e9e9e, #2962ff]
    => [#00e676, #ff1744, #ffea00, #78909c, #d500f9]
 
// ─── Functions ───────────────────────────────────────────────────────────────
// Lag-compensated EMA: pushes the EMA forward by its own smoothing error.
f_quickEma(series float x, simple int n) =>
    e1 = ta.ema(x, n)
    2 * e1 - ta.ema(e1, n)
 
// Momentum engine: EMA gap expressed in ATR units × 100.
f_engine(series float x, simple int f, simple int s, simple int a, simple bool quick) =>
    qe       = f_quickEma(x, f)
    fe       = ta.ema(x, f)
    se       = ta.ema(x, s)
    vol      = ta.atr(a)
    fastLine = quick ? qe : fe
    vol > 0 ? (fastLine - se) / vol * 100 : na
 
f_state(float v) =>
    na(v) ? "—" : v > i_stretch ? "Stretched ▲" : v > i_quiet ? "Bullish" : v >= -i_quiet ? "Quiet" : v >= -i_stretch ? "Bearish" : "Stretched ▼"
 
f_stateCol(float v) =>
    na(v) ? MID : math.abs(v) > i_stretch ? HOT : v > i_quiet ? UP : v < -i_quiet ? DN : MID
 
// Text meter from −200 to +200, one cell per 20 points.
f_meter(float v) =>
    steps = na(v) ? 0 : int(math.round(math.max(-200, math.min(200, v)) / 20))
    string out = ""
    for i = -10 to 10
        filled = (steps < 0 and i < 0 and i >= steps) or (steps > 0 and i > 0 and i <= steps)
        out += i == 0 ? "│" : filled ? "■" : "·"
    out
 
// ─── Core ────────────────────────────────────────────────────────────────────
mom    = f_engine(i_src, i_fast, i_slow, i_atr, i_quick)
trig   = ta.ema(mom, i_trigger)
diff   = mom - trig
diffUp = diff > diff[1]
diffDn = diff < diff[1]
 
// Higher timeframe: same engine, last completed bar only
htfMom = request.security(syminfo.tickerid, i_tf, f_engine(i_src, i_fast, i_slow, i_atr, i_quick)[1], lookahead = barmerge.lookahead_on)
 
// Thrust gate
gateEma  = ta.ema(close, i_gateLen)
thrustUp = gateEma > gateEma[1] and diffUp
thrustDn = gateEma < gateEma[1] and diffDn
 
// Trend
trendEma = ta.ema(close, i_trendLen)
upTrend  = close > trendEma
dnTrend  = close < trendEma
trendGap = (close - trendEma) / trendEma * 100
 
canLong    = not i_useGate or not thrustDn
canShort   = not i_useGate or not thrustUp
trendLong  = not i_useTrend or upTrend
trendShort = not i_useTrend or dnTrend
 
// Events
xUp    = ta.crossover(mom, trig)
xDn    = ta.crossunder(mom, trig)
outTop = ta.crossunder(mom, i_stretch)
outBot = ta.crossover(mom, -i_stretch)
closed = barstate.isconfirmed
 
inBullBand = mom > i_quiet and mom < i_stretch
inBearBand = mom < -i_quiet and mom > -i_stretch
 
sMomL = i_mom and xUp and inBullBand and canLong and trendLong and closed
sMomS = i_shorts and i_mom and xDn and inBearBand and canShort and trendShort and closed
sPbL  = i_pb and xUp and mom <= -i_quiet and upTrend and canLong and closed
sPbS  = i_shorts and i_pb and xDn and mom >= i_quiet and dnTrend and canShort and closed
sExT  = i_exits and outTop and closed
sExB  = i_exits and outBot and closed
 
// Latest signal for the panel
var string lastTxt = "None yet"
var int    lastBar = na
var color  lastCol = MID
 
string newTxt = sMomL ? "Momentum long ▲" : sPbL ? "Pullback long ▲" : sMomS ? "Momentum short ▼" : sPbS ? "Pullback short ▼" : sExT ? "Stretch exit (top) ◆" : sExB ? "Stretch exit (bottom) ◆" : na
if not na(newTxt)
    lastTxt := newTxt
    lastBar := bar_index
    lastCol := sMomL or sPbL ? UP : sMomS or sPbS ? DN : HOT
 
// ─── Colours ─────────────────────────────────────────────────────────────────
lineCol = math.abs(mom) > i_stretch ? HOT : mom >= 0 ? color.from_gradient(mom, 0, i_stretch, MID, UP) : color.from_gradient(mom, -i_stretch, 0, DN, MID)
histStr = math.min(math.abs(diff) / i_histMax, 1.0)
histCol = color.new(diff >= 0 ? UP : DN, 85 - histStr * 55)
 
// ─── Levels ──────────────────────────────────────────────────────────────────
lvTopS = plot(i_stretch, "Upper stretch", color.new(HOT, 65), 1)
lvTopQ = plot(i_quiet, "Upper quiet", color.new(MID, 75), 1)
plot(0, "Zero", color.new(MID, 55), 1)
lvBotQ = plot(-i_quiet, "Lower quiet", color.new(MID, 75), 1)
lvBotS = plot(-i_stretch, "Lower stretch", color.new(HOT, 65), 1)
 
fill(lvTopQ, lvTopS, i_bands ? color.new(UP, 94) : na, "Bull band")
fill(lvBotQ, lvBotS, i_bands ? color.new(DN, 94) : na, "Bear band")
fill(lvTopQ, lvBotQ, i_bands ? color.new(MID, 95) : na, "Quiet band")
 
bgcolor(i_hiStr and math.abs(mom) > i_stretch ? color.new(HOT, 92) : na, title = "Stretched highlight")
 
// ─── Histogram ───────────────────────────────────────────────────────────────
plot(i_hist == "Columns" ? diff : na, "Histogram (columns)", histCol, style = plot.style_columns)
plot(i_hist == "Area" ? diff : na, "Histogram (area)", histCol, style = plot.style_area)
 
// ─── Lines ───────────────────────────────────────────────────────────────────
plot(i_glow ? mom : na, "Glow", color.new(lineCol, 82), 7)
pMom  = plot(mom, "Momentum", lineCol, 2)
pTrig = plot(trig, "Trigger", color.new(TRG, 25), 1)
fill(pMom, pTrig, i_cloud ? color.new(mom >= trig ? UP : DN, 78) : na, "Cloud")
 
// ─── Signal marks ────────────────────────────────────────────────────────────
plotshape(sMomL ? mom : na, "Momentum long", shape.labelup, location.absolute, UP, text = "MOM", textcolor = color.black, size = size.tiny)
plotshape(sPbL ? mom : na, "Pullback long", shape.labelup, location.absolute, color.new(UP, 35), text = "PB", textcolor = color.black, size = size.tiny)
plotshape(sMomS ? mom : na, "Momentum short", shape.labeldown, location.absolute, DN, text = "MOM", textcolor = color.white, size = size.tiny)
plotshape(sPbS ? mom : na, "Pullback short", shape.labeldown, location.absolute, color.new(DN, 35), text = "PB", textcolor = color.white, size = size.tiny)
plotshape(sExT ? mom : na, "Stretch exit (top)", shape.diamond, location.absolute, HOT, size = size.tiny)
plotshape(sExB ? mom : na, "Stretch exit (bottom)", shape.diamond, location.absolute, HOT, size = size.tiny)
 
barcolor(i_candles ? (thrustUp ? UP : thrustDn ? DN : MID) : na, title = "Thrust candles")
 
// ─── Panel ───────────────────────────────────────────────────────────────────
pnlPos = switch i_where
    "Middle right" => position.middle_right
    "Bottom right" => position.bottom_right
    "Top left"     => position.top_left
    "Bottom left"  => position.bottom_left
    => position.top_right
 
pnlTxt = switch i_txt
    "Tiny"   => size.tiny
    "Normal" => size.normal
    "Large"  => size.large
    => size.small
 
var table panel = table.new(pnlPos, 2, 10, frame_color = color.new(MID, 60), frame_width = 1, border_color = color.new(MID, 85), border_width = 1)
 
f_row(int r, string k, string v, color c) =>
    shade = r % 2 == 0 ? color.new(MID, 88) : chart.bg_color
    table.cell(panel, 0, r, k, text_color = color.new(chart.fg_color, 40), text_size = pnlTxt, bgcolor = shade, text_halign = text.align_left)
    table.cell(panel, 1, r, v, text_color = c, text_size = pnlTxt, bgcolor = shade, text_halign = text.align_right)
 
paceTxt   = diffUp ? "Building ↑" : "Easing ↓"
paceCol   = diffUp ? UP : DN
thrustTxt = thrustUp ? "Up · longs only" : thrustDn ? "Down · shorts only" : "Flat · either way"
thrustCol = thrustUp ? UP : thrustDn ? DN : MID
 
if i_panel and barstate.islast
    sc = f_stateCol(mom)
 
    table.cell(panel, 0, 0, "BTM - Volatility Momentum   " + f_state(mom), text_color = chart.bg_color, text_size = pnlTxt, bgcolor = sc, text_halign = text.align_center)
    table.merge_cells(panel, 0, 0, 1, 0)
 
    table.cell(panel, 0, 1, f_meter(mom), text_color = sc, text_size = pnlTxt, bgcolor = chart.bg_color, text_halign = text.align_center, text_font_family = font.family_monospace)
    table.merge_cells(panel, 0, 1, 1, 1)
 
    trendTxt = (upTrend ? "Up " : "Down ") + (trendGap >= 0 ? "+" : "") + str.tostring(trendGap, "#.0") + "% vs EMA " + str.tostring(i_trendLen)
    agoTxt   = na(lastBar) ? "" : " · " + str.tostring(bar_index - lastBar) + " bars ago"
 
    f_row(2, "Momentum", str.tostring(mom, "#.0") + "  (trigger " + str.tostring(trig, "#.0") + ")", sc)
    f_row(3, "Histogram", (diff >= 0 ? "+" : "") + str.tostring(diff, "#.0"), diff >= 0 ? UP : DN)
    f_row(4, "Pace", paceTxt, paceCol)
    f_row(5, "Trend", trendTxt, upTrend ? UP : DN)
    f_row(6, "Thrust", thrustTxt, thrustCol)
    if i_mtf
        f_row(7, "Momentum " + i_tf, str.tostring(htfMom, "#.0") + " · " + f_state(htfMom), f_stateCol(htfMom))
    f_row(8, "Last signal", lastTxt + agoTxt, lastCol)
    f_row(9, "Shorts", i_shorts ? "On" : "Off", color.new(chart.fg_color, 40))
 
// ─── Alerts (use "Once per bar close") ───────────────────────────────────────
alertcondition(sMomL, "BTM VolMom: momentum long", "BTM VolMom momentum long on {{ticker}} ({{interval}})")
alertcondition(sPbL, "BTM VolMom: pullback long", "BTM VolMom pullback long on {{ticker}} ({{interval}})")
alertcondition(sMomS, "BTM VolMom: momentum short", "BTM VolMom momentum short on {{ticker}} ({{interval}})")
alertcondition(sPbS, "BTM VolMom: pullback short", "BTM VolMom pullback short on {{ticker}} ({{interval}})")
alertcondition(sExT, "BTM VolMom: stretch exit top", "BTM VolMom momentum leaving the upper stretch zone on {{ticker}} ({{interval}})")
alertcondition(sExB, "BTM VolMom: stretch exit bottom", "BTM VolMom momentum leaving the lower stretch zone on {{ticker}} ({{interval}})")

← 返回列表