本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
strategy("UT Bot + STC Conjunction Strategy Tester (v4.8 Restored Baseline)", overlay=true, precision=5, initial_capital=10000, default_qty_type=strategy.cash, margin_long=0, margin_short=0)
// ==========================================
// --- MANDATORY BOILERPLATE INPUTS ---------
// ==========================================
useSession = input.bool(true, "Enable Session Filter", group="Mandatory Core Settings")
allowedSess = input.session("0730-1900", "Allowed Trading Session", group="Mandatory Core Settings")
sessTimezone = input.string("UTC", "Session Timezone", group="Mandatory Core Settings")
accountRisk = input.float(1.0, "Account Risk % Per Trade", minval=0.1, maxval=10.0, step=0.5, group="Mandatory Core Settings")
minStopDist = input.float(0.00100, "Min Stop Distance (e.g. 0.00100 = 10 Pips)", minval=0.0, step=0.00010, group="Mandatory Core Settings")
// ==========================================
// --- STATIC CIRCUIT BREAKER ---------------
// ==========================================
useCircuitBreaker = input.bool(true, "Enable Weekly Drawdown Circuit Breaker", group="Circuit Breaker Settings")
maxWeeklyLossPct = input.float(3.0, "Max Allowed Weekly Equity Loss %", minval=0.5, maxval=20.0, step=0.5, group="Circuit Breaker Settings")
// ==========================================
// --- DYNAMIC OFFSET SETTINGS --------------
// ==========================================
useDynamicOffset = input.bool(true, "Enable Volatility-Scaled Entry Offset", group="Dynamic Offset Settings")
lowVolOffset = input.float(0.0, "Low Vol Offset (Pippettes)", minval=0.0, step=0.5, group="Dynamic Offset Settings")
normalVolOffset = input.float(2.0, "Normal Vol Offset (Pippettes)", minval=0.0, step=0.5, group="Dynamic Offset Settings")
highVolOffset = input.float(6.0, "High Vol Breakout Filter (Pippettes)", minval=0.0, step=0.5, group="Dynamic Offset Settings")
// ==========================================
// --- DYNAMIC STOP LOSS SETTINGS -----------
// ==========================================
normalSwingLookback = input.int(10, "Normal/Low Vol Swing Lookback", minval=1, group="Dynamic Stop Loss Scaling")
highVolSwingLookback = input.int(7, "High Vol Dynamic Swing Lookback", minval=1, group="Dynamic Stop Loss Scaling")
// ==========================================
// --- CANDLE RANGE FILTERS -----------------
// ==========================================
filterAtrLen = input.int(50, "ATR Volatility Baseline Period", minval=5, group="Candle Range Filters")
useRangeFilter = input.bool(true, "Enable Floor Filter (Block Too Small)", group="Candle Range Filters")
minRangePercent = input.float(65.0, "Min Candle Range (% of ATR)", minval=0.0, maxval=200.0, step=5.0, group="Candle Range Filters", tooltip="v4.8 Fixed Baseline Default")
useMaxCandleFilter = input.bool(true, "Enable Ceiling Filter (Block Too Large)", group="Candle Range Filters")
maxRangePercent = input.float(375.0, "Max Allowed Candle Range (% of ATR)", minval=50.0, maxval=1000.0, step=5.0, group="Candle Range Filters")
// ==========================================
// --- VALUE ZONE BOUNDARIES ----------------
// ==========================================
stcLowerZone = input.float(25.0, "Max STC for Longs (Oversold Floor)", minval=1.0, maxval=50.0, group="Value Zone Settings")
stcUpperZone = input.float(75.0, "Min STC for Shorts (Overbought Ceiling)", minval=50.0, maxval=99.0, group="Value Zone Settings")
// ==========================================
// --- VOLUME INTENSITY SETTINGS ------------
// ==========================================
useVolumeFilter = input.bool(true, "Enable Volume Intensity Filter", group="Volume Filter Settings")
volFastLen = input.int(5, "Volume Fast EMA Length", minval=1, group="Volume Filter Settings")
volSlowLen = input.int(10, "Volume Slow EMA Length", minval=2, group="Volume Filter Settings")
// ==========================================
// --- BREAKEVEN PROTECTION -----------------
// ==========================================
useBreakeven = input.bool(true, "Enable Breakeven Protection", group="Breakeven Settings")
beMilestoneR = input.float(2.0, "Trigger Milestone R-Multiple", minval=0.1, step=0.1, group="Breakeven Settings")
// ==========================================
// --- CANDLE REJECTION SETTINGS ------------
// ==========================================
useWickFilter = input.bool(true, "Enable Rejection Wick Filter", group="Candle Rejection Settings")
maxWickPercent = input.float(50.0, "Max Allowed Counter-Wick %", minval=1.0, maxval=100.0, step=2.5, group="Candle Rejection Settings")
// ==========================================
// --- VELOCITY SETTINGS --------------------
// ==========================================
useVelocityFilter = input.bool(true, "Enable Trend Velocity Blocker", group="Velocity Settings")
trendEmaLen = input.int(25, "Velocity Baseline EMA Length", minval=5, group="Velocity Settings")
velocityLookback = input.int(3, "Velocity Evaluation Window (Bars)", minval=1, group="Velocity Settings")
maxAllowedSlope = input.float(0.0010, "Max Allowed EMA Change (Pips)", step=0.0001, group="Velocity Settings")
// ==========================================
// --- PARTIAL TAKE PROFIT ENGINE -----------
// ==========================================
usePartialTP = input.bool(false, "Enable 50% Partial Take Profit", group="Partial Management")
partialMilestone = input.float(1.5, "Partial TP Milestone R-Multiple", minval=0.1, step=0.1, group="Partial Management")
// ==========================================
// --- DYNAMIC R:R REGIME INPUTS ------------
// ==========================================
regimeFastAtrLen = input.int(14, "Fast Regime ATR Period", minval=3, group="Dynamic R:R Regime Settings")
regimeSlowAtrLen = input.int(200, "Slow Baseline ATR Period", minval=50, group="Dynamic R:R Regime Settings")
highVolThreshold = input.float(1.2, "High Volatility Threshold Ratio", minval=1.0, step=0.05, group="Dynamic R:R Regime Settings")
lowVolThreshold = input.float(0.8, "Low Volatility Threshold Ratio", maxval=1.0, step=0.05, group="Dynamic R:R Regime Settings")
normalRrTarget = input.float(3.0, "Normal Regime R-Multiple Target", minval=0.1, step=0.1, group="Dynamic R:R Regime Settings")
highVolRrTarget = input.float(3.0, "High Volatility Target", minval=0.1, step=0.1, group="Dynamic R:R Regime Settings")
lowVolRrTarget = input.float(4.0, "Low Volatility Compression Target", minval=0.1, step=0.1, group="Dynamic R:R Regime Settings")
// ==========================================
// --- INDICATOR SPECIFIC INPUTS ------------
// ==========================================
utKeyV = input.float(2.0, "UT Bot Key Value (Sensitivity)", step=0.1, group="UT Bot Alerts Settings")
utAtrLen = input.int(1, "UT Bot ATR Period", minval=1, group="UT Bot Alerts Settings")
stcLength = input.int(80, "STC Length", group="STC Settings")
stcFastLen = input.int(27, "STC Fast Length", group="STC Settings")
stcSlowLen = input.int(50, "STC Slow Length", group="STC Settings")
stcAaa = input.float(0.5, "STC AAA Factor", step=0.05, group="STC Settings")
// ==========================================
// --- CORE LOGIC: UT BOT ALERTS ------------
// ==========================================
utSrc = close
utAtr = ta.atr(utAtrLen)
utLoss = utKeyV * utAtr
var float utTrailingStop = na
if na(utTrailingStop)
utTrailingStop := utSrc - utLoss
else
if utSrc > utTrailingStop[1] and utSrc[1] > utTrailingStop[1]
utTrailingStop := math.max(utTrailingStop[1], utSrc - utLoss)
else if utSrc < utTrailingStop[1] and utSrc[1] < utTrailingStop[1]
utTrailingStop := math.min(utTrailingStop[1], utSrc + utLoss)
else
utTrailingStop := utSrc > utTrailingStop[1] ? utSrc - utLoss : utSrc + utLoss
var int utPos = 0
if utSrc[1] < utTrailingStop[1] and utSrc > utTrailingStop
utPos := 1
else if utSrc[1] > utTrailingStop[1] and utSrc < utTrailingStop
utPos := -1
else
utPos := utPos[1]
utEma = ta.ema(utSrc, 1)
utAbove = ta.crossover(utEma, utTrailingStop)
utBelow = ta.crossover(utTrailingStop, utEma)
utBuySignal = utSrc > utTrailingStop and utAbove
utSellSignal = utSrc < utTrailingStop and utBelow
// ==========================================
// --- CORE LOGIC: SCHAFF TREND CYCLE (STC) -
// ==========================================
stcMacdCalc(src, fastLen, slowLen) =>
fastMA = ta.ema(src, fastLen)
slowMA = ta.ema(src, slowLen)
fastMA - slowMA
stcFunction(length, fastLen, slowLen, factor) =>
var float cVal = 0.0
var float dVal = 0.0
var float dVal6 = 0.0
var float eVal = 0.0
macdVal = stcMacdCalc(close, fastLen, slowLen)
lowestMacd = ta.lowest(macdVal, length)
rangeMacd = ta.highest(macdVal, length) - lowestMacd
cVal := rangeMacd > 0 ? (macdVal - lowestMacd) / rangeMacd * 100 : nz(cVal[1])
dVal := na(dVal[1]) ? cVal : dVal[1] + factor * (cVal - dVal[1])
lowestD = ta.lowest(dVal, length)
rangeD = ta.highest(dVal, length) - lowestD
dVal6 := rangeD > 0 ? (dVal - lowestD) / rangeD * 100 : nz(dVal6[1])
eVal := na(eVal[1]) ? dVal6 : eVal[1] + factor * (dVal6 - eVal[1])
eVal
mSTC = stcFunction(stcLength, stcFastLen, stcSlowLen, stcAaa)
stcIsUp = mSTC > mSTC[1]
stcIsDown = mSTC < mSTC[1]
// ==========================================
// --- ENVIRONMENT FILTERS ------------------
// ==========================================
currentBarRange = high - low
baselineFilterAtr = ta.atr(filterAtrLen)
rangeFloorPassed = not useRangeFilter or (currentBarRange >= (baselineFilterAtr * (minRangePercent / 100.0)))
rangeCeilingPassed = not useMaxCandleFilter or (currentBarRange <= (baselineFilterAtr * (maxRangePercent / 100.0)))
fastVolEma = ta.ema(volume, volFastLen)
slowVolEma = ta.ema(volume, volSlowLen)
volumeOscillator = slowVolEma != 0 ? ((fastVolEma - slowVolEma) / slowVolEma) * 100 : 0.0
volumeFilterPassed = not useVolumeFilter or (volumeOscillator > 0.0)
candleTotalRange = high - low
longUpperRejectionWick = high - math.max(open, close)
shortLowerRejectionWick = math.min(open, close) - low
longWickPercent = candleTotalRange > 0 ? (longUpperRejectionWick / candleTotalRange) * 100.0 : 0.0
shortWickPercent = candleTotalRange > 0 ? (shortLowerRejectionWick / candleTotalRange) * 100.0 : 0.0
longWickFilterPassed = not useWickFilter or (longWickPercent <= maxWickPercent)
shortWickFilterPassed = not useWickFilter or (shortWickPercent <= maxWickPercent)
baselineEma = ta.ema(close, trendEmaLen)
emaDelta = baselineEma - baselineEma[velocityLookback]
longVelocityBlock = useVelocityFilter and (emaDelta < -maxAllowedSlope)
shortVelocityBlock = useVelocityFilter and (emaDelta > maxAllowedSlope)
// ==========================================
// --- REGIME DETECTION & TARGET ASSIGNMENT --
// ==========================================
fastRegimeAtr = ta.atr(regimeFastAtrLen)
slowRegimeAtr = ta.atr(regimeSlowAtrLen)
volatilityRatio = slowRegimeAtr != 0 ? (fastRegimeAtr / slowRegimeAtr) : 1.0
currentActiveRr = normalRrTarget
if volatilityRatio >= highVolThreshold
currentActiveRr := highVolRrTarget
else if volatilityRatio <= lowVolThreshold
currentActiveRr := lowVolRrTarget
activeSwingLookback = volatilityRatio >= highVolThreshold ? highVolSwingLookback : normalSwingLookback
var float activeOffsetPippettes = 0.0
if useDynamicOffset
if volatilityRatio >= highVolThreshold
activeOffsetPippettes := highVolOffset
else if volatilityRatio <= lowVolThreshold
activeOffsetPippettes := lowVolOffset
else
activeOffsetPippettes := normalVolOffset
else
activeOffsetPippettes := 0.0
dynamicOffsetValue = activeOffsetPippettes * 0.00001
// ==========================================
// --- STATIC WEEKLY CIRCUIT BREAKER --------
// ==========================================
var float weeklyHighEquity = strategy.equity
var bool circuitBreakerTripped = false
currentWeekTime = time("W")
weekTimeChanged = ta.change(currentWeekTime)
bool isNewWeek = not na(weekTimeChanged) and weekTimeChanged != 0
if isNewWeek
weeklyHighEquity := strategy.equity
circuitBreakerTripped := false
else
weeklyHighEquity := math.max(weeklyHighEquity, strategy.equity)
if useCircuitBreaker and not circuitBreakerTripped and strategy.position_size == 0
weeklyDrawdownPct = ((weeklyHighEquity - strategy.equity) / weeklyHighEquity) * 100.0
if weeklyDrawdownPct >= maxWeeklyLossPct
circuitBreakerTripped := true
// ==========================================
// --- STRATEGY CONDITIONS & EXECUTION ------
// ==========================================
inTradingWindow = not useSession or not na(time(timeframe.period, allowedSess, sessTimezone))
globalLowestLow = ta.lowest(low, activeSwingLookback)
globalHighestHigh = ta.highest(high, activeSwingLookback)
var float slLevel = na
var float tpLevel = na
var float partialTpLevel = na
var float entryPrice = na
var float initialRisk = na
var bool beTriggered = false
var bool partialExecuted = false
var float maxPriceSinceEntry = 0.0
var float minPriceSinceEntry = 0.0
riskCash = strategy.equity * (accountRisk / 100)
buyTrigger = utBuySignal and stcIsUp and (mSTC <= stcLowerZone) and inTradingWindow and rangeFloorPassed and rangeCeilingPassed and volumeFilterPassed and longWickFilterPassed and not longVelocityBlock and not circuitBreakerTripped
sellTrigger = utSellSignal and stcIsDown and (mSTC >= stcUpperZone) and inTradingWindow and rangeFloorPassed and rangeCeilingPassed and volumeFilterPassed and shortWickFilterPassed and not shortVelocityBlock and not circuitBreakerTripped
if strategy.position_size == 0
slLevel := na
tpLevel := na
partialTpLevel := na
entryPrice := na
initialRisk := na
beTriggered := false
partialExecuted := false
maxPriceSinceEntry := 0.0
minPriceSinceEntry := 0.0
if circuitBreakerTripped or not inTradingWindow
strategy.cancel_all()
// LONG ENTRY EXECUTION
if buyTrigger and strategy.position_size == 0
calculatedEntry = close + dynamicOffsetValue
riskPrice = calculatedEntry - globalLowestLow
if riskPrice >= minStopDist
strategy.entry("Long", strategy.long, qty=riskCash / riskPrice, comment="Market Long")
slLevel := globalLowestLow
tpLevel := calculatedEntry + (riskPrice * currentActiveRr)
partialTpLevel := calculatedEntry + (riskPrice * partialMilestone)
entryPrice := close
initialRisk := riskPrice
beTriggered := false
partialExecuted := false
maxPriceSinceEntry := high
// SHORT ENTRY EXECUTION
if sellTrigger and strategy.position_size == 0
calculatedEntry = close - dynamicOffsetValue
riskPrice = globalHighestHigh - calculatedEntry
if riskPrice >= minStopDist
strategy.entry("Short", strategy.short, qty=riskCash / riskPrice, comment="Market Short")
slLevel := globalHighestHigh
tpLevel := calculatedEntry - (riskPrice * currentActiveRr)
partialTpLevel := calculatedEntry - (riskPrice * partialMilestone)
entryPrice := close
initialRisk := riskPrice
beTriggered := false
partialExecuted := false
minPriceSinceEntry := low
// ==========================================
// --- MANAGEMENT & EXITS -------------------
// ==========================================
if strategy.position_size > 0
maxPriceSinceEntry := math.max(maxPriceSinceEntry, high)
if useBreakeven and not beTriggered
highestProfitPoints = maxPriceSinceEntry - entryPrice
beMilestonePoints = initialRisk * beMilestoneR
if highestProfitPoints >= beMilestonePoints
slLevel := entryPrice
beTriggered := true
if strategy.position_size < 0
minPriceSinceEntry := math.min(minPriceSinceEntry, low)
if useBreakeven and not beTriggered
lowestProfitPoints = entryPrice - minPriceSinceEntry
beMilestonePoints = initialRisk * beMilestoneR
if lowestProfitPoints >= beMilestonePoints
slLevel := entryPrice
beTriggered := true
if strategy.position_size > 0
if usePartialTP and not partialExecuted
strategy.exit("Part Long", "Long", qty_percent=50, limit=partialTpLevel, stop=slLevel, comment_profit="Partial TP Long", comment_loss="SL Long")
strategy.exit("Exit Long", "Long", stop=slLevel, limit=tpLevel, comment_profit="Full TP Long", comment_loss="SL Long")
if strategy.position_size < 0
if usePartialTP and not partialExecuted
strategy.exit("Part Short", "Short", qty_percent=50, limit=partialTpLevel, stop=slLevel, comment_profit="Partial TP Short", comment_loss="SL Short")
strategy.exit("Exit Short", "Short", stop=slLevel, limit=tpLevel, comment_profit="Full TP Short", comment_loss="SL Short")
if strategy.position_size != 0 and strategy.position_size[1] != 0 and math.abs(strategy.position_size) < math.abs(strategy.position_size[1])
partialExecuted := true
// ==========================================
// --- VISUAL PLOTS -------------------------
// ==========================================
bgcolor(circuitBreakerTripped ? color.new(color.red, 93) : (useSession and inTradingWindow ? color.new(color.blue, 97) : na), title="Breaker Active vs Session Active")
plot(strategy.position_size != 0 ? slLevel : na, title="Dynamic Stop Loss Line", color=beTriggered ? color.orange : color.red, style=plot.style_linebr, linewidth=2)
plot(strategy.position_size != 0 ? tpLevel : na, title="Active Take Profit", color=color.green, style=plot.style_linebr)