本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
indicator(title = '[blackcat] L1 NinjaTrader and Linear Regression Channel', shorttitle = 'L1-NTC+LRC', overlay = true, max_labels_count = 500)
// =============================================================================
// V2 - On top of the original dual channels (NinjaTrader Channel + Linear Regression Channel) adds:
// two-way signals / exit loop / ATR take-profit & stop-loss / state machine with cooldown /
// label + bgcolor + table visualization / alert system / re-entry / MTF direction gate.
// Every new feature can be switched off to fall back to the original behavior.
// Original channel algorithms and naming (basis/dev/upper/lower, basisLR/devLR/upperLR/lowerLR) unchanged.
// =============================================================================
var string GRP_CH = 'Channels'
var string GRP_SIG = 'Signals'
var string GRP_RSK = 'Risk'
var string GRP_VIZ = 'Visual'
var string GRP_XTF = 'Multi-Timeframe'
// ---- Color semantics constants (green = long / red = short / orange = exit / teal = re-entry long / maroon = re-entry short) ----
color C_LONG = color.new(color.green, 0)
color C_SHORT = color.new(color.red, 0)
color C_EXIT = color.new(color.orange, 0)
color C_RELONG = color.new(color.teal, 0)
color C_RESHORT = color.new(color.maroon, 0)
color C_SL = color.new(color.red, 30)
color C_TP = color.new(color.teal, 30)
color C_BGLONG = color.new(color.green, 95)
color C_BGSHORT = color.new(color.red, 95)
// -----------------------------------------------------------------------------
// NinjaTrader Channel (original logic; only a display toggle and midline plotting added)
// -----------------------------------------------------------------------------
showNTC = input.bool(true, 'Show NinjaTrader Channel', group = GRP_CH)
length = input.int(20, minval = 1, title = 'Channel Length', group = GRP_CH)
mult = input.float(2, minval = 0.1, step = 0.1, title = 'Multiplier', group = GRP_CH)
basis = ta.sma(close, length)
dev = mult * ta.stdev(close, length)
upper = basis + dev
lower = basis - dev
pntcu = plot(upper, color = showNTC ? color.new(color.red, 0) : color.new(color.red, 100), title = 'NTC Upper Channel', linewidth = 1)
pntcl = plot(lower, color = showNTC ? color.new(color.red, 0) : color.new(color.red, 100), title = 'NTC Lower Channel', linewidth = 1)
plot(basis, color = showNTC ? color.new(color.red, 55) : color.new(color.red, 100), title = 'NTC Basis (SMA)', linewidth = 1)
fill(pntcu, pntcl, color = showNTC ? color.new(color.red, 80) : color.new(color.red, 100))
// -----------------------------------------------------------------------------
// Linear Regression Channel (original logic; the implicit 1.0 multiplier is exposed as an input, default 1.0 keeps full compatibility)
// -----------------------------------------------------------------------------
showLRC = input.bool(true, 'Show Linear Regression Channel', group = GRP_CH)
lengthLR = input.int(20, minval = 1, title = 'LR Channel Length', group = GRP_CH)
multLR = input.float(1.0, minval = 0.1, step = 0.1, title = 'LR Multiplier', group = GRP_CH)
basisLR = ta.linreg(close, lengthLR, 0)
devLR = multLR * ta.stdev(close, lengthLR)
upperLR = basisLR + devLR
lowerLR = basisLR - devLR
plrcu = plot(upperLR, color = showLRC ? color.new(color.green, 0) : color.new(color.green, 100), title = 'LRC Upper Channel', linewidth = 1)
plrcl = plot(lowerLR, color = showLRC ? color.new(color.green, 0) : color.new(color.green, 100), title = 'LRC Lower Channel', linewidth = 1)
plot(basisLR, color = showLRC ? color.new(color.green, 55) : color.new(color.green, 100), title = 'LRC Basis (LinReg)', linewidth = 2)
fill(plrcu, plrcl, color = showLRC ? color.new(color.green, 80) : color.new(color.green, 100))
// -----------------------------------------------------------------------------
// Multi-Timeframe direction gate (off by default = behavior falls back to the original)
// -----------------------------------------------------------------------------
useMTF = input.bool(false, 'Enable HTF Direction Gate', group = GRP_XTF)
htfInp = input.timeframe('240', 'HTF Direction Timeframe', group = GRP_XTF)
htfLen = input.int(50, 'HTF EMA Length', minval = 1, group = GRP_XTF)
htfOk = timeframe.in_seconds(htfInp) > timeframe.in_seconds()
htfClose = request.security(syminfo.tickerid, htfInp, close[1], lookahead = barmerge.lookahead_on)
htfEma = request.security(syminfo.tickerid, htfInp, ta.ema(close, htfLen)[1], lookahead = barmerge.lookahead_on)
htfDir = useMTF and htfOk and not na(htfClose) and not na(htfEma) ? htfClose > htfEma ? 1 : htfClose < htfEma ? -1 : 0 : 0
longGate = htfDir >= 0
shortGate = htfDir <= 0
// -----------------------------------------------------------------------------
// Signal parameters (two-way signals / exits / signal governance / re-entry)
// -----------------------------------------------------------------------------
enableLong = input.bool(true, 'Enable Long Signals', group = GRP_SIG)
enableShort = input.bool(true, 'Enable Short Signals', group = GRP_SIG)
useSlope = input.bool(true, 'Require LR Slope Alignment', group = GRP_SIG)
useExclusivity = input.bool(true, 'Same-bar Entry/Exit Exclusivity', group = GRP_SIG)
cooldownBars = input.int(3, 'Cooldown Bars', minval = 0, group = GRP_SIG)
useReentry = input.bool(false, 'Enable Re-entry (RL/RS)', group = GRP_SIG)
reentryWin = input.int(1, 'Anchor Window At Exit Bar', minval = 1, group = GRP_SIG)
reentryMode = input.string('Close', 'Breakout Source', options = ['Close', 'High/Low'], group = GRP_SIG)
// ---- Trigger conditions: all edge-triggered (crossover/crossunder), no level-based repeated firing ----
// ta.cross* is always computed unconditionally in global scope and assigned to a variable; conditions only reference
// that variable (lazy evaluation inside a condition would break the internal history of ta.cross*).
lrSlopeUp = basisLR > nz(basisLR[1], basisLR)
lrSlopeDown = basisLR < nz(basisLR[1], basisLR)
xOverBasisLR = ta.crossover(close, basisLR)
xUnderBasisLR = ta.crossunder(close, basisLR)
xUnderLower = ta.crossunder(close, lower)
xOverUpper = ta.crossover(close, upper)
longEntryCond = xOverBasisLR and (not useSlope or lrSlopeUp)
shortEntryCond = xUnderBasisLR and (not useSlope or lrSlopeDown)
longExitCond = xUnderBasisLR or xUnderLower
shortExitCond = xOverBasisLR or xOverUpper
// ---- Re-entry extreme-value anchoring ----
anchorHi = ta.highest(high, reentryWin * 2 + 1)
anchorLo = ta.lowest(low, reentryWin * 2 + 1)
var float exitHighAnchor = na
var float exitLowAnchor = na
var bool reentryArmed = false
breakUpSrc = reentryMode == 'Close' ? close > exitHighAnchor : high > exitHighAnchor
breakDownSrc = reentryMode == 'Close' ? close < exitLowAnchor : low < exitLowAnchor
RL = useReentry and reentryArmed and breakUpSrc and not breakDownSrc
RS = useReentry and reentryArmed and breakDownSrc and not breakUpSrc
// ---- Position state machine + same-bar exclusivity arbitration + cooldown ----
var int posState = 0
var int lastSignalBar = na
cooldownOK = na(lastSignalBar) or bar_index - lastSignalBar > cooldownBars
cooldownLeft = na(lastSignalBar) ? 0 : math.max(0, cooldownBars - (bar_index - lastSignalBar))
rawLongEntry = enableLong and (longEntryCond or RL) and posState <= 0 and cooldownOK and longGate
rawShortEntry = enableShort and (shortEntryCond or RS) and posState >= 0 and cooldownOK and shortGate
rawLongExit = longExitCond and posState == 1
rawShortExit = shortExitCond and posState == -1
longExit = useExclusivity ? rawLongExit and not rawLongEntry and not rawShortEntry : rawLongExit
shortExit = useExclusivity ? rawShortExit and not rawLongEntry and not rawShortEntry : rawShortExit
longEntry = useExclusivity ? rawLongEntry and not longExit and not shortExit : rawLongEntry
shortEntry = useExclusivity ? rawShortEntry and not longExit and not shortExit : rawShortEntry
if longEntry or shortEntry
posState := longEntry ? 1 : -1
lastSignalBar := bar_index
reentryArmed := false
exitHighAnchor := na
exitLowAnchor := na
else if longExit or shortExit
posState := 0
lastSignalBar := bar_index
exitHighAnchor := anchorHi
exitLowAnchor := anchorLo
reentryArmed := useReentry
plot(posState, 'Position State', display = display.data_window, color = color.white)
plot(cooldownLeft, 'Cooldown Left', display = display.data_window, color = color.white)
plot(htfDir, 'HTF Direction', display = display.data_window, color = color.white)
// -----------------------------------------------------------------------------
// Risk management: ATR take-profit / stop-loss + optional Chandelier trailing stop
// -----------------------------------------------------------------------------
useTPSL = input.bool(true, 'Show TP/SL Levels', group = GRP_RSK)
atrLen = input.int(14, 'ATR Length', minval = 1, group = GRP_RSK)
slMult = input.float(2.0, 'Stop Loss (xATR)', minval = 0.5, step = 0.25, group = GRP_RSK)
tpMult = input.float(3.0, 'Take Profit (xATR)', minval = 0.5, step = 0.25, group = GRP_RSK)
useTrail = input.bool(false, 'Chandelier Trailing Stop', group = GRP_RSK)
trailMult = input.float(3.0, 'Trail Distance (xATR)', minval = 0.5, step = 0.25, group = GRP_RSK)
atrVal = ta.atr(atrLen)
var float entryPrice = na
var int entryDir = 0
var float hhSinceEntry = na
var float llSinceEntry = na
if longEntry
entryPrice := close
entryDir := 1
hhSinceEntry := high
llSinceEntry := na
if shortEntry
entryPrice := close
entryDir := -1
llSinceEntry := low
hhSinceEntry := na
if longExit or shortExit
entryPrice := na
entryDir := 0
hhSinceEntry := na
llSinceEntry := na
if posState == 1 and not na(hhSinceEntry)
hhSinceEntry := math.max(hhSinceEntry, high)
if posState == -1 and not na(llSinceEntry)
llSinceEntry := math.min(llSinceEntry, low)
float slPrice = na
float tpPrice = na
if useTPSL and not na(entryPrice) and not na(atrVal) and entryDir != 0
slPrice := entryPrice - entryDir * slMult * atrVal
tpPrice := entryPrice + entryDir * tpMult * atrVal
if useTrail
slPrice := entryDir == 1 ? hhSinceEntry - trailMult * atrVal : llSinceEntry + trailMult * atrVal
plot(useTPSL ? slPrice : na, 'Stop Loss', color = C_SL, style = plot.style_linebr, linewidth = 2)
plot(useTPSL ? tpPrice : na, 'Take Profit', color = C_TP, style = plot.style_linebr, linewidth = 2)
plot(atrVal, 'ATR (data window)', display = display.data_window, color = color.white)
// -----------------------------------------------------------------------------
// Visualization: signal labels / position background color / status dashboard
// -----------------------------------------------------------------------------
showLabels = input.bool(true, 'Show Signal Labels', group = GRP_VIZ)
showBg = input.bool(true, 'Show Position Background', group = GRP_VIZ)
showDash = input.bool(true, 'Show Dashboard', group = GRP_VIZ)
if showLabels and (longEntry or RL)
tagL = RL ? 'RL' : 'E'
label.new(bar_index, low, tagL, style = label.style_label_up, color = RL ? C_RELONG : C_LONG, textcolor = color.white, size = size.small)
if showLabels and (shortEntry or RS)
tagS = RS ? 'RS' : 'S'
label.new(bar_index, high, tagS, style = label.style_label_down, color = RS ? C_RESHORT : C_SHORT, textcolor = color.white, size = size.small)
if showLabels and (longExit or shortExit)
label.new(bar_index, high, longExit ? 'XL' : 'XS', style = label.style_xcross, color = C_EXIT, textcolor = color.white, size = size.tiny)
color bgState = showBg ? posState == 1 ? C_BGLONG : posState == -1 ? C_BGSHORT : na : na
bgcolor(bgState)
var table dash = table.new(position.top_right, 2, 7, bgcolor = color.new(color.black, 60), border_width = 1, border_color = color.new(color.gray, 70))
if showDash and barstate.islast
string posTxt = posState == 1 ? 'LONG' : posState == -1 ? 'SHORT' : 'FLAT'
color posCol = posState == 1 ? C_LONG : posState == -1 ? C_SHORT : color.gray
string entryTxt = na(entryPrice) ? '-' : str.tostring(entryPrice, format.mintick)
string atrTxt = na(atrVal) ? '-' : str.tostring(atrVal, format.mintick)
string slTxt = na(slPrice) ? '-' : str.tostring(slPrice, format.mintick)
string tpTxt = na(tpPrice) ? '-' : str.tostring(tpPrice, format.mintick)
string htfTxt = not useMTF ? 'OFF' : not htfOk ? 'INVALID TF' : htfDir == 1 ? 'BULL' : htfDir == -1 ? 'BEAR' : 'NEUTRAL'
color htfCol = htfDir == 1 ? C_LONG : htfDir == -1 ? C_SHORT : color.gray
string reTxt = not useReentry ? 'OFF' : reentryArmed ? 'ARMED' : 'IDLE'
table.cell(dash, 0, 0, 'Position', text_color = color.silver, text_size = size.tiny)
table.cell(dash, 1, 0, posTxt, text_color = posCol, text_size = size.tiny)
table.cell(dash, 0, 1, 'Entry / ATR', text_color = color.silver, text_size = size.tiny)
table.cell(dash, 1, 1, entryTxt + ' / ' + atrTxt, text_color = color.white, text_size = size.tiny)
table.cell(dash, 0, 2, 'Stop Loss', text_color = color.silver, text_size = size.tiny)
table.cell(dash, 1, 2, slTxt, text_color = C_SL, text_size = size.tiny)
table.cell(dash, 0, 3, 'Take Profit', text_color = color.silver, text_size = size.tiny)
table.cell(dash, 1, 3, tpTxt, text_color = C_TP, text_size = size.tiny)
table.cell(dash, 0, 4, 'Cooldown Left', text_color = color.silver, text_size = size.tiny)
table.cell(dash, 1, 4, str.tostring(cooldownLeft), text_color = color.white, text_size = size.tiny)
table.cell(dash, 0, 5, 'HTF Gate', text_color = color.silver, text_size = size.tiny)
table.cell(dash, 1, 5, htfTxt, text_color = htfCol, text_size = size.tiny)
table.cell(dash, 0, 6, 'Re-entry Armed', text_color = color.silver, text_size = size.tiny)
table.cell(dash, 1, 6, reTxt, text_color = reentryArmed ? color.yellow : color.gray, text_size = size.tiny)
// -----------------------------------------------------------------------------
// Alert system (alertcondition at global scope; alert() calls are all bar-close confirmed)
// -----------------------------------------------------------------------------
if longEntry
alert('L1-NTC+LRC: LONG entry @ ' + str.tostring(close, format.mintick) + ' | SL ' + (na(slPrice) ? 'n/a' : str.tostring(slPrice, format.mintick)) + ' | TP ' + (na(tpPrice) ? 'n/a' : str.tostring(tpPrice, format.mintick)), alert.freq_once_per_bar_close)
if shortEntry
alert('L1-NTC+LRC: SHORT entry @ ' + str.tostring(close, format.mintick) + ' | SL ' + (na(slPrice) ? 'n/a' : str.tostring(slPrice, format.mintick)) + ' | TP ' + (na(tpPrice) ? 'n/a' : str.tostring(tpPrice, format.mintick)), alert.freq_once_per_bar_close)
if longExit
alert('L1-NTC+LRC: LONG exit @ ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
if shortExit
alert('L1-NTC+LRC: SHORT exit @ ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
if RL
alert('L1-NTC+LRC: LONG re-entry @ ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
if RS
alert('L1-NTC+LRC: SHORT re-entry @ ' + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
alertcondition(longEntry, 'Long Entry', 'L1-NTC+LRC long entry signal')
alertcondition(shortEntry, 'Short Entry', 'L1-NTC+LRC short entry signal')
alertcondition(longExit, 'Long Exit', 'L1-NTC+LRC long exit signal')
alertcondition(shortExit, 'Short Exit', 'L1-NTC+LRC short exit signal')
alertcondition(RL, 'Long Re-entry', 'L1-NTC+LRC long re-entry signal')
alertcondition(RS, 'Short Re-entry', 'L1-NTC+LRC short re-entry signal')