本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © blackcat1402
//@version=6
// L3 Squeeze Dynamics V2 - polished edition of the original V1 study.
// V2 changes: Pine v6 migration, working Act_* filter switches, position state machine,
// edge triggered signals, cooldown, ATR based TP/SL, squeeze dashboard, full alert set.
indicator(title='[blackcat] L3 Squeeze Dynamics V2', shorttitle='L3 SQZ Dynamics V2', overlay=true, max_labels_count=500)
// ===========================================================================
// 01 · INPUTS
// ===========================================================================
// --- Squeeze momentum -------------------------------------------------------
Act_SMI = input.bool(true, 'SQUEEZE MOMENTUM INDICATOR', group='01 - Squeeze Momentum', tooltip='Bollinger/Keltner squeeze plus momentum filter. Disable it to trade the SAR and RSI confluence alone.')
BB_length = input.int(85, title='BOLLINGER BANDS LENGTH', minval=1, maxval=1000, group='01 - Squeeze Momentum')
BB_mult = input.float(2.1, title='BOLLINGER BANDS MULTI-FACTOR', minval=0.1, maxval=10.0, step=0.1, group='01 - Squeeze Momentum')
KC_length = input.int(38, title='KELTNER CHANNEL LENGTH', minval=1, maxval=1000, group='01 - Squeeze Momentum')
KC_mult = input.float(2.0, title='KELTNER CHANNEL MULTI-FACTOR', minval=0.1, maxval=10.0, step=0.1, group='01 - Squeeze Momentum')
// --- Parabolic SAR ----------------------------------------------------------
Act_SAR = input.bool(true, 'PARABOLIC SAR', group='02 - Parabolic SAR', tooltip='SAR directional filter: long only while price holds above SAR, short only while it holds below.')
Sst = input.float(0.73, 'SAR STAR', step=0.01, minval=0.01, maxval=1.0, group='02 - Parabolic SAR')
Sinc = input.float(0.5, 'SAR INC', step=0.01, minval=0.01, maxval=1.0, group='02 - Parabolic SAR', tooltip='Acceleration step. Keep it below SAR MAX for a classic SAR response.')
Smax = input.float(0.06, 'SAR MAX', step=0.01, minval=0.01, maxval=1.0, group='02 - Parabolic SAR')
// --- Volume weighted RSI ----------------------------------------------------
Act_RSI = input.bool(true, 'RSI VOLUME WEIGHTED', group='03 - Volume Weighted RSI', tooltip='Volume weighted RSI bias filter around the center line.')
RSI_len = input.int(22, 'RSI LENGTH', minval=1, maxval=1000, group='03 - Volume Weighted RSI')
RSI_obos = input.int(45, title='RSI CENTER LINE', minval=1, maxval=99, group='03 - Volume Weighted RSI')
// --- Signal governance ------------------------------------------------------
useStateMachine = input.bool(true, 'POSITION STATE MACHINE', group='04 - Signal Governance', tooltip='One position at a time and no duplicate entries while a trade is open.')
cooldownBars = input.int(3, 'COOLDOWN BARS', minval=0, maxval=100, group='04 - Signal Governance', tooltip='Minimum bars between two consecutive signals. 0 disables the cooldown.')
allowReversal = input.bool(true, 'ALLOW SAME-BAR REVERSAL', group='04 - Signal Governance', tooltip='Flip straight from long to short when the opposite signal appears.')
// --- Risk -------------------------------------------------------------------
useTPSL = input.bool(true, 'SHOW ATR TP/SL LEVELS', group='05 - Risk', tooltip='Plot ATR based take profit and stop loss reference levels.')
useRiskExit = input.bool(true, 'EXIT ON TP/SL HIT', group='05 - Risk', tooltip='Close the virtual position when a plotted TP or SL level is touched.')
atrLen = input.int(14, 'ATR LENGTH', minval=1, maxval=500, group='05 - Risk')
slMult = input.float(2.0, 'STOP LOSS (xATR)', minval=0.5, maxval=20.0, step=0.25, group='05 - Risk')
tpMult = input.float(3.0, 'TAKE PROFIT (xATR)', minval=0.5, maxval=30.0, step=0.25, group='05 - Risk')
// --- Visuals ----------------------------------------------------------------
showLabels = input.bool(true, 'SHOW SIGNAL LABELS', group='06 - Visuals')
showBands = input.bool(true, 'SHOW BB / KC BANDS', group='06 - Visuals')
showSar = input.bool(true, 'SHOW PARABOLIC SAR', group='06 - Visuals')
colorBars = input.bool(true, 'COLOR BARS BY MOMENTUM', group='06 - Visuals')
showBgPos = input.bool(true, 'POSITION BACKGROUND', group='06 - Visuals')
showSqzBg = input.bool(false, 'SQUEEZE BACKGROUND', group='06 - Visuals')
showDash = input.bool(true, 'SHOW DASHBOARD', group='06 - Visuals')
// ===========================================================================
// 02 · COLOR SYSTEM
// ===========================================================================
color C_LONG = color.new(color.lime, 0)
color C_SHORT = color.new(color.red, 0)
color C_EXIT = color.new(color.orange, 0)
color C_REV = color.new(color.purple, 0)
color C_TP = color.new(color.teal, 0)
color C_SL = color.new(color.red, 20)
color C_BGLONG = color.new(color.green, 92)
color C_BGSHORT = color.new(color.red, 92)
color C_BGSQZ = color.new(color.blue, 94)
color C_TXT = color.new(color.white, 0)
color C_DIM = color.new(color.silver, 0)
// ===========================================================================
// 03 · CORE CALCULATION (original V1 algorithm, unchanged)
// ===========================================================================
basis = ta.sma(close, BB_length)
dev = BB_mult * ta.stdev(close, BB_length)
upperBB = basis + dev
lowerBB = basis - dev
ma = ta.sma(close, KC_length)
rangema = ta.sma(ta.tr, KC_length)
upperKC = ma + rangema * KC_mult
lowerKC = ma - rangema * KC_mult
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
nosqz = not sqzOn and not sqzOff
val = ta.linreg(close - math.avg(math.avg(ta.highest(high, KC_length), ta.lowest(low, KC_length)), ta.sma(close, KC_length)), KC_length, 0)
sar = ta.sar(Sst, Sinc, Smax)
chg = nz(close - close[1], 0.0)
up = chg > 0 ? chg * volume : 0.0
dn = chg < 0 ? -chg * volume : 0.0
upt = ta.sma(up, RSI_len)
dnt = ta.sma(dn, RSI_len)
rsiSum = upt + dnt
rsi_v = rsiSum > 0 ? 100.0 * upt / rsiSum : na
// ===========================================================================
// 04 · SIGNAL PREDICATES (V1 longCond / shortCond, filters now switchable)
// ===========================================================================
rsiValid = not na(rsi_v)
sarValid = not na(sar)
momValid = not na(val)
momLong = not Act_SMI or (momValid and val > 0.0 and val > nz(val[1], 0.0) and not nosqz)
momShort = not Act_SMI or (momValid and val < 0.0 and val < nz(val[1], 0.0) and not nosqz)
rsiLong = not Act_RSI or (rsiValid and rsi_v > RSI_obos)
rsiShort = not Act_RSI or (rsiValid and rsi_v < RSI_obos)
sarLong = not Act_SAR or (sarValid and sar < close)
sarShort = not Act_SAR or (sarValid and sar > close)
longCond = momLong and rsiLong and sarLong
shortCond = momShort and rsiShort and sarShort
// Edge detection: a signal is consumed on its first bar only (replaces the V1 xfl() hold).
prevLongCond = longCond[1] == true
prevShortCond = shortCond[1] == true
longEdge = longCond and not prevLongCond
shortEdge = shortCond and not prevShortCond
// ===========================================================================
// 05 · POSITION STATE MACHINE (S1 + S3)
// ===========================================================================
var int posState = 0
var float entryPrice = na
var float entryAtr = na
var int entryBar = na
var int lastSignalBar = na
var int lastExitDir = 0
cooldownOK = na(lastSignalBar) or (bar_index - lastSignalBar) > cooldownBars
atrVal = ta.atr(atrLen)
bool canEnterLong = posState == 0 or (posState == -1 and allowReversal)
bool canEnterShort = posState == 0 or (posState == 1 and allowReversal)
bool longEntry = useStateMachine ? (longEdge and canEnterLong and cooldownOK) : longEdge
bool shortEntry = useStateMachine ? (shortEdge and canEnterShort and cooldownOK) : shortEdge
// Protective levels are frozen at entry so they do not drift with volatility.
bool levelOK = not na(entryPrice) and not na(entryAtr)
float longTP = posState == 1 and levelOK ? entryPrice + tpMult * entryAtr : na
float longSL = posState == 1 and levelOK ? entryPrice - slMult * entryAtr : na
float shortTP = posState == -1 and levelOK ? entryPrice - tpMult * entryAtr : na
float shortSL = posState == -1 and levelOK ? entryPrice + slMult * entryAtr : na
float tpLine = posState == 1 ? longTP : shortTP
float slLine = posState == 1 ? longSL : shortSL
bool riskArmed = useTPSL and useRiskExit and not na(entryBar) and bar_index > entryBar
bool longTPHit = riskArmed and posState == 1 and not na(tpLine) and high >= tpLine
bool longSLHit = riskArmed and posState == 1 and not na(slLine) and low <= slLine
bool shortTPHit = riskArmed and posState == -1 and not na(tpLine) and low <= tpLine
bool shortSLHit = riskArmed and posState == -1 and not na(slLine) and high >= slLine
bool tpExit = (longTPHit or shortTPHit) and not (longSLHit or shortSLHit)
bool slExit = longSLHit or shortSLHit
bool sigLongExit = posState == 1 and shortCond
bool sigShortExit = posState == -1 and longCond
bool anyRiskExit = tpExit or slExit
bool longRiskExit = posState == 1 and anyRiskExit
bool shortRiskExit = posState == -1 and anyRiskExit
bool longExit = sigLongExit or longRiskExit
bool shortExit = sigShortExit or shortRiskExit
bool revShort = sigLongExit and shortEdge and cooldownOK and allowReversal
bool revLong = sigShortExit and longEdge and cooldownOK and allowReversal
// Snapshot before the transition, used for the RL / RS labels.
bool reentryLong = lastExitDir == 1
bool reentryShort = lastExitDir == -1
// Events really applied by the state machine. Labels and alerts read only these flags,
// so the chart can never show a signal the state machine did not execute.
bool evRevShort = false
bool evRevLong = false
bool evExitLong = false
bool evExitShort = false
bool evEntryLong = false
bool evEntryShort = false
// At most one net state change per bar; exits take precedence over entries.
if revShort
posState := -1
entryPrice := close
entryAtr := atrVal
entryBar := bar_index
lastSignalBar := bar_index
lastExitDir := 1
evRevShort := true
else if revLong
posState := 1
entryPrice := close
entryAtr := atrVal
entryBar := bar_index
lastSignalBar := bar_index
lastExitDir := -1
evRevLong := true
else if longExit
posState := 0
entryPrice := na
entryAtr := na
entryBar := na
lastSignalBar := bar_index
lastExitDir := 1
evExitLong := true
else if shortExit
posState := 0
entryPrice := na
entryAtr := na
entryBar := na
lastSignalBar := bar_index
lastExitDir := -1
evExitShort := true
else if longEntry
posState := 1
entryPrice := close
entryAtr := atrVal
entryBar := bar_index
lastSignalBar := bar_index
evEntryLong := true
else if shortEntry
posState := -1
entryPrice := close
entryAtr := atrVal
entryBar := bar_index
lastSignalBar := bar_index
evEntryShort := true
// ===========================================================================
// 06 · VISUALS
// ===========================================================================
if showLabels
if evRevShort
label.new(bar_index, high, 'XL+SE', style=label.style_label_down, color=C_REV, textcolor=C_TXT, size=size.small)
else if evRevLong
label.new(bar_index, low, 'XS+LE', style=label.style_label_up, color=C_REV, textcolor=C_TXT, size=size.small)
else
if evEntryLong
tagLong = reentryLong ? 'RL' : 'LE'
label.new(bar_index, low, tagLong, style=label.style_label_up, color=C_LONG, textcolor=color.black, size=size.small)
if evEntryShort
tagShort = reentryShort ? 'RS' : 'SE'
label.new(bar_index, high, tagShort, style=label.style_label_down, color=C_SHORT, textcolor=C_TXT, size=size.small)
if evExitLong
txtL = longTPHit ? 'TP' : longSLHit ? 'SL' : 'XL'
colL = longTPHit ? C_TP : longSLHit ? C_SL : C_EXIT
label.new(bar_index, high, txtL, style=label.style_xcross, color=colL, textcolor=C_TXT, size=size.tiny)
if evExitShort
txtS = shortTPHit ? 'TP' : shortSLHit ? 'SL' : 'XS'
colS = shortTPHit ? C_TP : shortSLHit ? C_SL : C_EXIT
label.new(bar_index, low, txtS, style=label.style_xcross, color=colS, textcolor=C_TXT, size=size.tiny)
color bgCol = na
if showBgPos and posState == 1
bgCol := C_BGLONG
else if showBgPos and posState == -1
bgCol := C_BGSHORT
else if showSqzBg and sqzOn
bgCol := C_BGSQZ
bgcolor(bgCol, title='L3 State Background')
// Momentum bar coloring (original V1 semantics).
iff_1 = val > nz(val[1], 0.0) ? color.yellow : color.orange
iff_2 = val < nz(val[1], 0.0) ? color.fuchsia : color.purple
barcolor(colorBars and not na(val) ? (val > 0 ? iff_1 : iff_2) : na, title='Momentum Bars')
plot(showSar ? sar : na, title='Parabolic SAR', style=plot.style_cross, color=color.new(color.blue, 0), linewidth=1)
plot(showBands ? upperBB : na, title='BB Upper', color=color.new(color.orange, 50), linewidth=1)
plot(showBands ? lowerBB : na, title='BB Lower', color=color.new(color.orange, 50), linewidth=1)
plot(showBands ? upperKC : na, title='KC Upper', color=color.new(color.gray, 40), linewidth=1)
plot(showBands ? lowerKC : na, title='KC Lower', color=color.new(color.gray, 40), linewidth=1)
plot(useTPSL ? tpLine : na, title='Take Profit', color=C_TP, style=plot.style_linebr, linewidth=1)
plot(useTPSL ? slLine : na, title='Stop Loss', color=C_SL, style=plot.style_linebr, linewidth=1)
plot(val, title='Squeeze Momentum', color=val > 0 ? C_LONG : C_SHORT, display=display.data_window)
plot(rsi_v, title='Volume Weighted RSI', color=color.new(color.purple, 0), display=display.data_window)
plot(posState, title='Position State', color=color.new(color.gray, 0), display=display.data_window)
plot(atrVal, title='ATR', color=color.new(color.gray, 0), display=display.data_window)
// --- Dashboard --------------------------------------------------------------
var table dash = table.new(position.top_right, 2, 10, bgcolor=color.new(color.black, 70), border_width=1, border_color=color.new(color.gray, 60))
if showDash and barstate.islast
sqzTxt = sqzOn ? 'ON' : sqzOff ? 'OFF' : 'MIXED'
posTxt = posState == 1 ? 'LONG' : posState == -1 ? 'SHORT' : 'FLAT'
posCol = posState == 1 ? C_LONG : posState == -1 ? C_SHORT : C_DIM
sarTxt = na(sar) ? '-' : sar < close ? 'BULL' : 'BEAR'
momTxt = na(val) ? '-' : str.tostring(val, '#.##')
rsiTxt = na(rsi_v) ? '-' : str.tostring(rsi_v, '#.#')
entTxt = na(entryPrice) ? '-' : str.tostring(entryPrice, format.mintick)
tpTxt = na(tpLine) ? '-' : str.tostring(tpLine, format.mintick)
slTxt = na(slLine) ? '-' : str.tostring(slLine, format.mintick)
barTxt = na(entryBar) ? '-' : str.tostring(bar_index - entryBar)
table.cell(dash, 0, 0, 'L3 SQUEEZE DYNAMICS', text_color=C_TXT, text_size=size.small, bgcolor=color.new(color.blue, 40))
table.cell(dash, 1, 0, 'V2', text_color=C_TXT, text_size=size.small, bgcolor=color.new(color.blue, 40))
table.cell(dash, 0, 1, 'Position', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 1, posTxt, text_color=posCol, text_size=size.tiny)
table.cell(dash, 0, 2, 'Squeeze', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 2, sqzTxt, text_color=C_TXT, text_size=size.tiny)
table.cell(dash, 0, 3, 'Momentum', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 3, momTxt, text_color=C_TXT, text_size=size.tiny)
table.cell(dash, 0, 4, 'VW RSI', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 4, rsiTxt, text_color=C_TXT, text_size=size.tiny)
table.cell(dash, 0, 5, 'SAR bias', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 5, sarTxt, text_color=C_TXT, text_size=size.tiny)
table.cell(dash, 0, 6, 'Entry', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 6, entTxt, text_color=C_TXT, text_size=size.tiny)
table.cell(dash, 0, 7, 'Take profit', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 7, tpTxt, text_color=C_TP, text_size=size.tiny)
table.cell(dash, 0, 8, 'Stop loss', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 8, slTxt, text_color=C_SL, text_size=size.tiny)
table.cell(dash, 0, 9, 'Bars in trade', text_color=C_DIM, text_size=size.tiny)
table.cell(dash, 1, 9, barTxt, text_color=C_TXT, text_size=size.tiny)
// ===========================================================================
// 07 · ALERTS
// ===========================================================================
string exitTagL = longTPHit ? 'LONG TAKE PROFIT' : longSLHit ? 'LONG STOP LOSS' : 'LONG EXIT'
string exitTagS = shortTPHit ? 'SHORT TAKE PROFIT' : shortSLHit ? 'SHORT STOP LOSS' : 'SHORT EXIT'
string evtTag = evRevShort ? 'REVERSAL LONG>SHORT' : evRevLong ? 'REVERSAL SHORT>LONG' : evEntryLong ? 'LONG ENTRY' : evEntryShort ? 'SHORT ENTRY' : evExitLong ? exitTagL : evExitShort ? exitTagS : ''
if evtTag != ''
alert('L3 SQZ | ' + evtTag + ' | ' + syminfo.ticker + ' ' + timeframe.period + ' | ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
alertcondition(evEntryLong, title='L3 SQZ - Long Entry', message='L3 Squeeze Dynamics: LONG entry at {{close}}')
alertcondition(evEntryShort, title='L3 SQZ - Short Entry', message='L3 Squeeze Dynamics: SHORT entry at {{close}}')
alertcondition(evExitLong, title='L3 SQZ - Long Exit', message='L3 Squeeze Dynamics: LONG exit at {{close}}')
alertcondition(evExitShort, title='L3 SQZ - Short Exit', message='L3 Squeeze Dynamics: SHORT exit at {{close}}')
alertcondition(evRevShort or evRevLong, title='L3 SQZ - Reversal', message='L3 Squeeze Dynamics: position reversal at {{close}}')
alertcondition(longTPHit or shortTPHit, title='L3 SQZ - Target Hit', message='L3 Squeeze Dynamics: take profit reached at {{close}}')
alertcondition(longSLHit or shortSLHit, title='L3 SQZ - Stop Hit', message='L3 Squeeze Dynamics: stop loss reached at {{close}}')