B3AR's Impulse System

B3AR_Trades · study · 246 行 · 点赞 910 · TradingView 原页

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

Pine Script

//@version=6
indicator("B3AR's Impulse System", shorttitle="Impulse System", overlay=true)
 
// ######:   . ####:     :##:    ######:  
// #######   #######:     ##     #######  
// ##   :##  #:.   ##    ####    ##   :## 
// ##    ##        ##    ####    ##    ## 
// ##   :##        ##   :#  #:   ##   :## 
// #######.    #####     #::#    #######: 
// #######.    #####.   ##  ##   ######   
// ##   :##        ##   ######   ##   ##. 
// ##    ##        ##  .######.  ##   ##  
// ##   :##  #:    ##  :##  ##:  ##   :## 
// ########  #######:  ###  ###  ##    ##:
// ######    :#####:   ##:  :##  ##    ##:
 
// ==================== INPUTS ====================
 
string grpTrend = "Short Trend"
int    almaLen  = input.int(20, "Length", minval=1, group=grpTrend, tooltip="How many bars the trend line uses. Lower = faster. Higher = smoother but slower.")
 
string grpDead  = "Trend Dead Zone"
float  slopeThr = input.float(0.05, "Flat Threshold", minval=0.0, step=0.01, group=grpDead, tooltip="How steep the trend line must be to count as up or down. Anything flatter counts as flat, and candles turn neutral. Higher = more neutral candles. 0 = off.")
int    slopeLb  = input.int(1, "Slope Lookback", minval=1, maxval=20, group=grpDead, tooltip="How many bars back the trend line's slope is measured. 1 = compare to the previous bar. Higher = steadier but slower.")
 
string grpMom     = "Momentum"
int    baseLength = input.int(13, "Length", minval=1, group=grpMom, tooltip="How many bars momentum uses. It also adjusts on its own when the market speeds up or slows down. Lower = faster. Higher = smoother but slower.")
 
string grpHyst = "Momentum Hysteresis"
float  momThr  = input.float(1.0, "Min Momentum Move", minval=0.0, step=0.1, group=grpHyst, tooltip="How much momentum must change in one bar to count as rising or falling. Smaller changes are ignored. Higher = fewer flips. 0 = any change counts.")
int    momBars = input.int(1, "Confirmation Bars", minval=1, maxval=5, group=grpHyst, tooltip="How many bars in a row momentum must move the new way before it flips. Higher = fewer false flips but slower. 1 = flip right away.")
 
string grpExt     = "Fresh vs Extended"
bool   useExt     = input.bool(true, "Classify Impulse Starts", group=grpExt, tooltip="Marks each new impulse as fresh or extended. Extended means momentum was already overbought (bullish) or oversold (bearish) when it started. Extended impulses are drawn faded.")
bool   useAdaptLv = input.bool(true, "Use Adaptive Levels", group=grpExt, tooltip="On = overbought and oversold levels adjust to recent bars. Off = fixed at +70 and -70.")
bool   showStart  = input.bool(true, "Mark Impulse Starts", group=grpExt, tooltip="Shows a triangle where a fresh impulse starts and a small circle where an extended one starts.")
 
string grpTv = "Trend Velocity Confirmation"
bool   useTv = input.bool(true, "Use Trend Velocity", group=grpTv, tooltip="Adds a third check. When trend and momentum agree, Trend Velocity picks the bright color (confirmed) or the darker color (unconfirmed). Off = trend and momentum only.")
int    erLen = input.int(18, "Length", minval=2, group=grpTv, tooltip="How many bars Trend Velocity uses. Lower = faster. Higher = smoother but slower.")
 
string grpViz   = "Display"
color colBull   = input.color(#00FF41, "Bullish (confirmed)",   group=grpViz, tooltip="Trend, momentum and Trend Velocity all up.")
color colBullU  = input.color(#0B8A81, "Bullish (unconfirmed)", group=grpViz, tooltip="Trend and momentum up, Trend Velocity not.")
color colNeut   = input.color(#1565C0, "Neutral",               group=grpViz, tooltip="Trend is flat, or trend and momentum disagree.")
color colBearU  = input.color(#8A0B60, "Bearish (unconfirmed)", group=grpViz, tooltip="Trend and momentum down, Trend Velocity not.")
color colBear   = input.color(#FF0000, "Bearish (confirmed)",   group=grpViz, tooltip="Trend, momentum and Trend Velocity all down.")
bool  showAlma  = input.bool(true, "Show Moving Average Line", group=grpViz, tooltip="Shows the Short Trend line on the chart.")
 
// ==================== FIXED PARAMETERS ====================
 
// Short Trend (ALMA)
float ALMA_OFFSET = 0.85
float ALMA_SIGMA  = 6.0
 
// One ATR shared by the trend slope normalization, the AMF volatility ratio and the AMF score normalization
int ATR_LEN = 14
 
// AMF smoothing (WMA of the raw score)
int AMF_SMOOTH_LEN = 10
 
// AMF adaptive lookback
int   MIN_LOOKBACK     = 3
int   MAX_LOOKBACK     = 40
float VOL_SENS         = 3.5
int   LB_SMOOTH_LEN    = 5
float MEDIUM_DEMA_MULT = 1.5
float SLOW_DEMA_MULT   = 2.5
 
// AMF scoring
float SIGMOID_K     = 4.0
float DIFF_MULT     = 1.5
float W_PRICE_FAST  = 30.0
float W_FAST_MEDIUM = 30.0
float W_MEDIUM_SLOW = 40.0
 
// Fresh vs extended
int   ADAPT_PERIOD = 200
float UPPER_PCT    = 90.0
float LOWER_PCT    = 10.0
float FIXED_OB     = 70.0
float FIXED_OS     = -70.0
int   EXT_TRANSP   = 55
 
// Trend Velocity (KAMA-style adaptive MA)
int ER_FAST = 3
int ER_SLOW = 30
 
// ==================== FUNCTIONS ====================
 
f_sigmoid(float x, float k) =>
    2.0 / (1.0 + math.exp(-k * x)) - 1.0
 
f_ema(float src, int len) =>
    float alpha = 2.0 / (len + 1)
    var float val = na
    if not na(src) and len > 0
        val := alpha * src + (1.0 - alpha) * nz(val[1])
    val
 
f_dema(float src, int len) =>
    float e1 = f_ema(src, len)
    float e2 = f_ema(e1, len)
    2.0 * e1 - e2
 
// ==================== ALMA TREND ====================
 
float atrVal    = ta.atr(ATR_LEN)
float alma      = ta.alma(close, almaLen, ALMA_OFFSET, ALMA_SIGMA)
float normSlope = atrVal > 0 ? (alma - alma[slopeLb]) / slopeLb / atrVal : 0.0
 
bool almaRising  = normSlope >  slopeThr
bool almaFalling = normSlope < -slopeThr
 
// ==================== AMF ====================
 
// Adaptive lookback
float amfAvgAtr = ta.sma(atrVal, 50)
float volRatio  = amfAvgAtr > 0 ? atrVal / amfAvgAtr : 1.0
float rawLb     = float(baseLength) / math.pow(volRatio, VOL_SENS)
float clampedLb = math.max(float(MIN_LOOKBACK), math.min(float(MAX_LOOKBACK), rawLb))
float smoothLb  = ta.ema(clampedLb, LB_SMOOTH_LEN)
 
int demaFastLen   = math.max(1, int(math.round(smoothLb)))
int demaMediumLen = math.max(1, int(math.round(smoothLb * MEDIUM_DEMA_MULT)))
int demaSlowLen   = math.max(1, int(math.round(smoothLb * SLOW_DEMA_MULT)))
 
float demaFast   = f_dema(close, demaFastLen)
float demaMedium = f_dema(close, demaMediumLen)
float demaSlow   = f_dema(close, demaSlowLen)
 
// Sigmoid scoring
float pfDiff = atrVal > 0 ? (close      - demaFast)   / atrVal * DIFF_MULT : 0.0
float fmDiff = atrVal > 0 ? (demaFast   - demaMedium) / atrVal * DIFF_MULT : 0.0
float msDiff = atrVal > 0 ? (demaMedium - demaSlow)   / atrVal * DIFF_MULT : 0.0
 
float oscScore  = f_sigmoid(pfDiff, SIGMOID_K) * W_PRICE_FAST + f_sigmoid(fmDiff, SIGMOID_K) * W_FAST_MEDIUM + f_sigmoid(msDiff, SIGMOID_K) * W_MEDIUM_SLOW
float maxScore  = W_PRICE_FAST + W_FAST_MEDIUM + W_MEDIUM_SLOW
float normScore = maxScore != 0.0 ? oscScore / maxScore * 100.0 : 0.0
 
float amf = ta.wma(normScore, AMF_SMOOTH_LEN)
 
// OB/OS levels
float adaptOB = ta.percentile_nearest_rank(amf, ADAPT_PERIOD, UPPER_PCT)
float adaptOS = ta.percentile_nearest_rank(amf, ADAPT_PERIOD, LOWER_PCT)
float obLevel = useAdaptLv ? nz(adaptOB, FIXED_OB) : FIXED_OB
float osLevel = useAdaptLv ? nz(adaptOS, FIXED_OS) : FIXED_OS
 
// Hysteresis: momentum is the bar-to-bar change in AMF. The state only flips after that
// change has held past the threshold for the required number of consecutive bars; otherwise it holds.
float amfMove = amf - amf[1]
 
var int upRun    = 0
var int dnRun    = 0
var int momState = 0
 
upRun := amfMove >  momThr ? upRun + 1 : 0
dnRun := amfMove < -momThr ? dnRun + 1 : 0
 
if upRun >= momBars
    momState := 1
else if dnRun >= momBars
    momState := -1
 
// ==================== TREND VELOCITY ====================
// Only the sign is used. Every scaling mode in Trend Velocity preserves the sign of
// the raw adaptive-MA change, so the scaling and ATR normalization are not needed here.
 
float erChange = math.abs(close - close[erLen])
float erPath   = math.sum(math.abs(close - close[1]), erLen)
float er       = erPath != 0 ? erChange / erPath : 0.0
 
float fastSc = 2.0 / (ER_FAST + 1)
float slowSc = 2.0 / (ER_SLOW + 1)
float sc     = math.pow(er * (fastSc - slowSc) + slowSc, 2)
 
var float ama = na
ama := na(ama[1]) ? close : sc * close + (1 - sc) * ama[1]
 
float tvVelocity = nz(ama - ama[1])
bool  tvBull     = tvVelocity >= 0   // matches Trend Velocity's own coloring: 0 counts as bullish
bool  tvBear     = not tvBull
 
// ==================== IMPULSE LOGIC ====================
 
bool impulseBull = almaRising  and momState == 1
bool impulseBear = almaFalling and momState == -1
 
bool fullBull = impulseBull and (not useTv or tvBull)
bool fullBear = impulseBear and (not useTv or tvBear)
 
// Fresh vs extended: classified on the first bar of each impulse and held for its run
bool bullStart = impulseBull and not impulseBull[1]
bool bearStart = impulseBear and not impulseBear[1]
 
var bool extended = false
if bullStart
    extended := useExt and amf >= obLevel
else if bearStart
    extended := useExt and amf <= osLevel
else if not impulseBull and not impulseBear
    extended := false
 
color baseColor = fullBull    ? colBull  :
                  impulseBull ? colBullU :
                  fullBear    ? colBear  :
                  impulseBear ? colBearU :
                  colNeut
 
color impulseColor = extended ? color.new(baseColor, EXT_TRANSP) : baseColor
 
// ==================== PLOTS ====================
 
plotcandle(open, high, low, close, title="Impulse Candles", color=impulseColor, wickcolor=impulseColor, bordercolor=impulseColor)
 
plot(showAlma ? alma : na, "Moving Average", color=color.new(color.white, 30), linewidth=2)
 
bool showMarks = showStart and useExt
plotshape(showMarks and bullStart and not extended, "Fresh Bull Start",    shape.triangleup,   location.belowbar, colBull, size=size.tiny)
plotshape(showMarks and bearStart and not extended, "Fresh Bear Start",    shape.triangledown, location.abovebar, colBear, size=size.tiny)
plotshape(showMarks and bullStart and extended,     "Extended Bull Start", shape.circle,       location.belowbar, color.new(colBull, EXT_TRANSP), size=size.tiny)
plotshape(showMarks and bearStart and extended,     "Extended Bear Start", shape.circle,       location.abovebar, color.new(colBear, EXT_TRANSP), size=size.tiny)
 
plot(normSlope, "Trend Slope",      display=display.data_window)
plot(amf,       "Momentum",         display=display.data_window)
plot(amfMove,   "Momentum Change",  display=display.data_window)
plot(momState,  "Momentum State",   display=display.data_window)
plot(obLevel,   "Overbought Level", display=display.data_window)
plot(osLevel,   "Oversold Level",   display=display.data_window)
plot(atrVal != 0 ? tvVelocity / atrVal * 100 : na, "Trend Velocity", display=display.data_window)
 
// ==================== ALERTS ====================
 
// Trend + momentum, regardless of Trend Velocity
alertcondition(impulseBull and not impulseBull[1], "Impulse — Bullish",      "Trend and momentum both up: bullish impulse started")
alertcondition(impulseBear and not impulseBear[1], "Impulse — Bearish",      "Trend and momentum both down: bearish impulse started")
alertcondition(impulseBull[1] and not impulseBull, "Impulse — Exiting Bull", "Bullish impulse ended")
alertcondition(impulseBear[1] and not impulseBear, "Impulse — Exiting Bear", "Bearish impulse ended")
 
// Confirmed impulse (trend, momentum and Trend Velocity all agree)
alertcondition(fullBull and not fullBull[1], "Impulse — Confirmed Bullish", "Trend, momentum and Trend Velocity all up")
alertcondition(fullBear and not fullBear[1], "Impulse — Confirmed Bearish", "Trend, momentum and Trend Velocity all down")
 
// Fresh impulse starts (momentum not already overbought/oversold on the first bar)
alertcondition(useExt and bullStart and not extended, "Impulse — Fresh Bullish Start", "Bullish impulse started before momentum was overbought")
alertcondition(useExt and bearStart and not extended, "Impulse — Fresh Bearish Start", "Bearish impulse started before momentum was oversold")

← 返回列表