本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mark4x
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MarkLeRoy
//@version=6
strategy("ICT Silver Bullet Backtest", shorttitle="LuxAlgo Quant SB TEST", overlay=true, pyramiding=0, default_qty_type=strategy.fixed, default_qty_value=1, initial_capital=1000000, process_orders_on_close=true, max_boxes_count=500)
// --- Session Settings ---
useSession1Input = input.bool(true, "Trade Session 1", group="Sessions", tooltip="Allow entries during the first Silver Bullet window.")
session1Input = input.session("0300-0400:23456", "Session 1 — London", group="Sessions", tooltip="New York time. Default Silver Bullet window: 3:00–4:00 AM, weekdays.")
useSession2Input = input.bool(true, "Trade Session 2", group="Sessions", tooltip="Allow entries during the second Silver Bullet window.")
session2Input = input.session("1000-1100:23456", "Session 2 — New York AM", group="Sessions", tooltip="New York time. Default Silver Bullet window: 10:00–11:00 AM, weekdays.")
useSession3Input = input.bool(true, "Trade Session 3", group="Sessions", tooltip="Allow entries during the third Silver Bullet window.")
session3Input = input.session("1400-1500:23456", "Session 3 — New York PM", group="Sessions", tooltip="New York time. Default Silver Bullet window: 2:00–3:00 PM, weekdays.")
maxTradesInput = input.int(1, "Maximum entries per session", options=[1, 2, 3], group="Sessions", tooltip="Maximum filled entries allowed in each enabled session per day.")
// --- Entry and Risk Settings ---
stopPlacementInput = input.string("Candle 1", "Stop placement", options=["Candle 1", "Candle 2", "FVG boundary"], group="Risk / Targets", tooltip="Bullish stops go below the selected reference; bearish stops go above it.")
stopBufferTicksInput = input.int(1, "Stop buffer (ticks)", minval=0, group="Risk / Targets", tooltip="Extra distance beyond the selected stop reference, in minimum price ticks.")
takeProfitInput = input.string("1:2", "Take profit", options=["No take profit — trailing stop only", "1:1", "1:1.5", "1:2", "1:3", "1:4", "Next support/resistance"], group="Risk / Targets", tooltip="Choose trailing stop only, a fixed reward-to-risk multiple, or the nearest confirmed support/resistance.")
useAtrTrailInput = input.bool(true, "Use ATR trailing stop", group="Risk / Targets", tooltip="Enable or disable the ATR trailing stop.")
atrLengthInput = input.int(14, "ATR period", minval=1, group="Risk / Targets", tooltip="Number of bars used to calculate ATR.")
atrMultiplierInput = input.float(2.0, "ATR trailing multiplier", minval=0.1, step=0.1, group="Risk / Targets", tooltip="Trailing stop distance as a multiple of ATR. Default is 2.0x ATR.")
trailActivationRInput = input.float(1.5, "Start trailing at (R)", minval=0.1, step=0.1, group="Risk / Targets", tooltip="Start trailing after price moves this multiple of initial risk in your favour.")
pivotStrengthInput = input.int(3, "Target swing strength", minval=1, maxval=20, group="Risk / Targets", tooltip="Bars on each side required to confirm pivot-based support and resistance levels used by the Next support/resistance option.")
// --- Display Settings ---
showSetupInput = input.bool(true, "Show active FVG midpoint", group="Display", tooltip="Plot the midpoint of the latest eligible FVG while waiting for a retracement.")
showExitsInput = input.bool(true, "Show active stop and target", group="Display", tooltip="Plot the current strategy position's stop and take-profit levels.")
showTradedFvgsInput = input.bool(true, "Show FVGs used by trades", group="Display", tooltip="Draw a zone only when the strategy enters from that FVG.")
showSessionBgInput = input.bool(true, "Shade trading sessions", group="Display", tooltip="Shade the configured Silver Bullet session windows on the chart background.")
sessionBgTransparencyInput = input.int(88, "Session shade transparency", minval=0, maxval=100, group="Style", tooltip="Higher values make session shading more transparent.")
session1BgColorInput = input.color(#5b9cf6, "London session shade", group="Style", tooltip="Background color for the first configured Silver Bullet session.")
session2BgColorInput = input.color(#a78bfa, "New York AM shade", group="Style", tooltip="Background color for the second configured Silver Bullet session.")
session3BgColorInput = input.color(#f0b45b, "New York PM shade", group="Style", tooltip="Background color for the third configured Silver Bullet session.")
bullishTradedFvgColorInput = input.color(#089981, "Bullish traded FVG", group="Style", tooltip="Color for bullish FVG zones that produced an entry.")
bearishTradedFvgColorInput = input.color(#f23645, "Bearish traded FVG", group="Style", tooltip="Color for bearish FVG zones that produced an entry.")
// --- Session and FVG Logic ---
inSession1 = useSession1Input and not na(time(timeframe.period, session1Input, "America/New_York"))
inSession2 = useSession2Input and not na(time(timeframe.period, session2Input, "America/New_York"))
inSession3 = useSession3Input and not na(time(timeframe.period, session3Input, "America/New_York"))
newSession1 = inSession1 and not inSession1[1]
newSession2 = inSession2 and not inSession2[1]
newSession3 = inSession3 and not inSession3[1]
inTradeSession = inSession1 or inSession2 or inSession3
sessionId = inSession1 ? 1 : inSession2 ? 2 : inSession3 ? 3 : 0
sessionBackgroundColor = not showSessionBgInput ? na : inSession1 ? color.new(session1BgColorInput, sessionBgTransparencyInput) : inSession2 ? color.new(session2BgColorInput, sessionBgTransparencyInput) : inSession3 ? color.new(session3BgColorInput, sessionBgTransparencyInput) : na
bgcolor(sessionBackgroundColor, title="Trading session background")
var int tradesSession1 = 0
var int tradesSession2 = 0
var int tradesSession3 = 0
if newSession1
tradesSession1 := 0
if newSession2
tradesSession2 := 0
if newSession3
tradesSession3 := 0
tradesThisSession = sessionId == 1 ? tradesSession1 : sessionId == 2 ? tradesSession2 : sessionId == 3 ? tradesSession3 : 0
slotAvailable = sessionId != 0 and tradesThisSession < maxTradesInput
// Three-candle FVG: candle 1 is two bars back, candle 2 is one bar back, candle 3 is the current bar.
bullishFvg = low > high[2]
bearishFvg = high < low[2]
pivotHigh = ta.pivothigh(high, pivotStrengthInput, pivotStrengthInput)
pivotLow = ta.pivotlow(low, pivotStrengthInput, pivotStrengthInput)
latestSwingHigh = ta.valuewhen(not na(pivotHigh), pivotHigh, 0)
latestSwingLow = ta.valuewhen(not na(pivotLow), pivotLow, 0)
// Retain confirmed pivot levels so targets can use the nearest valid S/R line.
var array<float> resistanceLevels = array.new_float()
var array<float> supportLevels = array.new_float()
if not na(pivotHigh)
array.push(resistanceLevels, pivotHigh)
if array.size(resistanceLevels) > 100
array.shift(resistanceLevels)
if not na(pivotLow)
array.push(supportLevels, pivotLow)
if array.size(supportLevels) > 100
array.shift(supportLevels)
// --- Setup State ---
var bool setupActive = false
var int setupDirection = 0
var int setupBar = na
var int setupSession = 0
var float setupMidpoint = na
var float setupTop = na
var float setupBottom = na
var box activeTradeFvg = na
var float setupStop = na
var float tradeStop = na
var float tradeTarget = na
// ATR trailing state
var float initialRiskDistance = na
var float trailExtreme = na
atrValue = ta.atr(atrLengthInput)
if not inTradeSession and inTradeSession[1]
setupActive := false
setupDirection := 0
setupMidpoint := na
setupStop := na
if inTradeSession and (bullishFvg or bearishFvg)
setupDirection := bullishFvg ? 1 : -1
setupBar := bar_index
setupSession := sessionId
setupMidpoint := bullishFvg ? (low + high[2]) / 2.0 : (low[2] + high) / 2.0
setupTop := bullishFvg ? low : low[2]
setupBottom := bullishFvg ? high[2] : high
stopReference = stopPlacementInput == "Candle 1" ? (bullishFvg ? low[2] : high[2]) : stopPlacementInput == "Candle 2" ? (bullishFvg ? low[1] : high[1]) : (bullishFvg ? high[2] : low[2])
stopBuffer = stopBufferTicksInput * syminfo.mintick
setupStop := bullishFvg ? stopReference - stopBuffer : stopReference + stopBuffer
setupActive := true
// Entry is triggered only when a later in-session candle trades through the FVG midpoint.
midpointTouched = setupActive and setupBar < bar_index and setupSession == sessionId and inTradeSession and low <= setupMidpoint and high >= setupMidpoint
canEnter = midpointTouched and slotAvailable and strategy.position_size == 0
if canEnter
isLong = setupDirection == 1
riskDistance = isLong ? close - setupStop : setupStop - close
validStop = riskDistance > syminfo.mintick
float nextResistance = na
float nextSupport = na
if array.size(resistanceLevels) > 0
for i = 0 to array.size(resistanceLevels) - 1
resistanceLevel = array.get(resistanceLevels, i)
if resistanceLevel > close and (na(nextResistance) or resistanceLevel < nextResistance)
nextResistance := resistanceLevel
if array.size(supportLevels) > 0
for i = 0 to array.size(supportLevels) - 1
supportLevel = array.get(supportLevels, i)
if supportLevel < close and (na(nextSupport) or supportLevel > nextSupport)
nextSupport := supportLevel
rrMultiple = takeProfitInput == "1:1" ? 1.0 : takeProfitInput == "1:1.5" ? 1.5 : takeProfitInput == "1:2" ? 2.0 : takeProfitInput == "1:3" ? 3.0 : takeProfitInput == "1:4" ? 4.0 : na
noTakeProfit = takeProfitInput == "No take profit — trailing stop only"
targetPrice = noTakeProfit ? na : takeProfitInput == "Next support/resistance" ? (isLong ? nextResistance : nextSupport) : (isLong ? close + riskDistance * rrMultiple : close - riskDistance * rrMultiple)
validTarget = noTakeProfit or (not na(targetPrice) and (isLong ? targetPrice > close : targetPrice < close))
if validStop and validTarget
tradeStop := setupStop
tradeTarget := targetPrice
initialRiskDistance := riskDistance
trailExtreme := close
if showTradedFvgsInput
tradedFvgColor = isLong ? bullishTradedFvgColorInput : bearishTradedFvgColorInput
activeTradeFvg := box.new(left=setupBar - 2, top=setupTop, right=bar_index, bottom=setupBottom, xloc=xloc.bar_index, border_color=color.new(tradedFvgColor, 25), bgcolor=color.new(tradedFvgColor, 88))
if isLong
strategy.entry("Long", strategy.long)
strategy.exit("Long Exit", from_entry="Long", stop=tradeStop, limit=tradeTarget)
else
strategy.entry("Short", strategy.short)
strategy.exit("Short Exit", from_entry="Short", stop=tradeStop, limit=tradeTarget)
if sessionId == 1
tradesSession1 += 1
else if sessionId == 2
tradesSession2 += 1
else if sessionId == 3
tradesSession3 += 1
setupActive := false
setupDirection := 0
if not na(activeTradeFvg) and strategy.position_size != 0
box.set_right(activeTradeFvg, bar_index)
// --- ATR Trailing Stop ---
// Trails the highest high for longs and lowest low for shorts.
// The stop only moves in the direction of profit and never widens.
if useAtrTrailInput and strategy.position_size > 0 and not na(tradeStop) and not na(initialRiskDistance)
trailExtreme := na(trailExtreme) ? high : math.max(trailExtreme, high)
longProfitDistance = trailExtreme - strategy.position_avg_price
if longProfitDistance >= initialRiskDistance * trailActivationRInput
longTrailCandidate = trailExtreme - atrValue * atrMultiplierInput
tradeStop := math.max(tradeStop, longTrailCandidate)
if useAtrTrailInput and strategy.position_size < 0 and not na(tradeStop) and not na(initialRiskDistance)
trailExtreme := na(trailExtreme) ? low : math.min(trailExtreme, low)
shortProfitDistance = strategy.position_avg_price - trailExtreme
if shortProfitDistance >= initialRiskDistance * trailActivationRInput
shortTrailCandidate = trailExtreme + atrValue * atrMultiplierInput
tradeStop := math.min(tradeStop, shortTrailCandidate)
if strategy.position_size > 0 and not na(tradeStop)
strategy.exit("Long Exit", from_entry="Long", stop=tradeStop, limit=tradeTarget)
if strategy.position_size < 0 and not na(tradeStop)
strategy.exit("Short Exit", from_entry="Short", stop=tradeStop, limit=tradeTarget)
if strategy.position_size == 0 and strategy.position_size[1] != 0
if not na(activeTradeFvg)
box.set_right(activeTradeFvg, bar_index)
activeTradeFvg := na
tradeStop := na
tradeTarget := na
initialRiskDistance := na
trailExtreme := na
// --- Visuals ---
plot(showSetupInput and setupActive ? setupMidpoint : na, "Active FVG midpoint", color=color.new(#5b9cf6, 0), linewidth=2, style=plot.style_linebr)
plot(showExitsInput and strategy.position_size != 0 ? tradeStop : na, "Trade stop", color=color.new(#f23645, 0), linewidth=2, style=plot.style_linebr)
plot(showExitsInput and strategy.position_size != 0 and not na(tradeTarget) ? tradeTarget : na, "Trade target", color=color.new(#089981, 0), linewidth=2, style=plot.style_linebr)