本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
strategy("Focused STRAT + Volume Strategy v3", overlay=true, max_labels_count=500, initial_capital=100000, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.01, slippage=1, calc_on_every_tick=false, calc_on_order_fills=false, process_orders_on_close=false)
// Closed-bar research engine. Standard US equity/ETF 5-minute charts only.
mode = input.string("Pattern + volume", "Experiment", options=["Pattern only", "Pattern + volume", "Pattern + volume + divergence"])
use312 = input.bool(true, "Enable 3-1-2")
use212 = input.bool(false, "Enable 2-1-2")
kind = input.string("Both", "Trade type", options=["Both", "Reversal", "Continuation"])
volDays = input.int(20, "Prior sessions for volume", minval=5, maxval=60)
minDays = input.int(5, "Minimum prior observations", minval=3, maxval=20)
volThreshold = input.float(1.2, "Minimum relative volume", minval=0.1, step=0.1)
pivotBars = input.int(3, "RSI pivot left/right bars", minval=1, maxval=10)
divLife = input.int(12, "Divergence validity (bars after confirmation)", minval=1, maxval=78)
maxRiskATR = input.float(2.0, "Maximum stop distance / ATR", minval=0.1, step=0.1)
showDiv = input.bool(true, "Show divergence confirmation marks")
if barstate.isfirst and (not timeframe.isminutes or timeframe.multiplier != 5 or not chart.is_standard)
runtime.error("Use standard 5-minute candles on a US equity/ETF with real volume.")
if barstate.isfirst and minDays > volDays
runtime.error("Minimum observations cannot exceed prior sessions.")
string tz = "America/New_York"
int minuteNY = hour(time, tz) * 60 + minute(time, tz)
bool regular = not na(time(timeframe.period, "0930-1600:23456", tz))
int dayKey = year(time, tz) * 10000 + month(time, tz) * 100 + dayofmonth(time, tz)
bool sameDay = dayKey == dayKey[1] and dayKey == dayKey[2] and dayKey == dayKey[3]
bool contiguous = time - time[1] == 300000 and time[1] - time[2] == 300000 and time[2] - time[3] == 300000
bool entryWindow = regular and minuteNY >= 585 and minuteNY < 930
// 09:45-15:25 signal bars; even the first bar's classification stays in-session.
var matrix<float> volumes = matrix.new<float>(78, volDays + 1, na)
var int column = -1
var int storedDay = na
float relVol = na
int observations = 0
if barstate.isconfirmed and regular
if na(storedDay) or dayKey != storedDay
column := (column + 1) % (volDays + 1)
for row = 0 to 77
matrix.set(volumes, row, column, na)
storedDay := dayKey
int slot = int((minuteNY - 570) / 5)
float total = 0.0
for c = 0 to volDays
float sample = matrix.get(volumes, slot, c)
if c != column and not na(sample) and sample > 0
total += sample
observations += 1
relVol := observations >= minDays and total > 0 and not na(volume) ? volume / (total / observations) : na
// Today's sample is written only AFTER computing against previous sessions.
matrix.set(volumes, slot, column, volume)
bool inside = high <= high[1] and low >= low[1]
bool outside = high > high[1] and low < low[1]
bool up2 = high > high[1] and low >= low[1]
bool down2 = low < low[1] and high <= high[1]
bool setup312 = use312 and outside[2] and inside[1]
bool setup212 = use212 and (up2[2] or down2[2]) and inside[1]
bool longPattern = (setup312 or setup212) and up2 and close > high[1]
bool shortPattern = (setup312 or setup212) and down2 and close < low[1]
// For 312, reversal/continuation is relative to the outside candle BODY,
// not an asserted market trend. Doji outside bars remain unclassified.
int initialDirection = setup312 ? (close[2] > open[2] ? 1 : close[2] < open[2] ? -1 : 0) : (up2[2] ? 1 : down2[2] ? -1 : 0)
bool longReversal = initialDirection == -1
bool shortReversal = initialDirection == 1
bool longTypeOK = kind == "Both" or (kind == "Reversal" ? longReversal : initialDirection == 1)
bool shortTypeOK = kind == "Both" or (kind == "Reversal" ? shortReversal : initialDirection == -1)
float rsi = ta.rsi(close, 14)
float pLow = ta.pivotlow(low, pivotBars, pivotBars)
float pHigh = ta.pivothigh(high, pivotBars, pivotBars)
var float lastLow = na
var float lastLowRSI = na
var int lastLowBar = na
var float lastHigh = na
var float lastHighRSI = na
var int lastHighBar = na
var float bullInvalid = na
var float bearInvalid = na
var int bullConfirmed = na
var int bearConfirmed = na
bool bullNew = false
bool bearNew = false
if barstate.isconfirmed
// Clear pivots and active divergence at each NY calendar boundary.
if dayKey != dayKey[1]
lastLow := na
lastHigh := na
bullConfirmed := na
bearConfirmed := na
if regular and not na(pLow) and dayKey == dayKey[pivotBars * 2] and regular[pivotBars * 2]
bullNew := not na(lastLow) and bar_index - pivotBars - lastLowBar <= 60 and pLow < lastLow and rsi[pivotBars] > lastLowRSI
if bullNew
bullInvalid := pLow
bullConfirmed := bar_index
lastLow := pLow
lastLowRSI := rsi[pivotBars]
lastLowBar := bar_index - pivotBars
if regular and not na(pHigh) and dayKey == dayKey[pivotBars * 2] and regular[pivotBars * 2]
bearNew := not na(lastHigh) and bar_index - pivotBars - lastHighBar <= 60 and pHigh > lastHigh and rsi[pivotBars] < lastHighRSI
if bearNew
bearInvalid := pHigh
bearConfirmed := bar_index
lastHigh := pHigh
lastHighRSI := rsi[pivotBars]
lastHighBar := bar_index - pivotBars
if not na(bullConfirmed) and (low < bullInvalid or bar_index - bullConfirmed > divLife)
bullConfirmed := na
if not na(bearConfirmed) and (high > bearInvalid or bar_index - bearConfirmed > divLife)
bearConfirmed := na
bool bullActive = not na(bullConfirmed)
bool bearActive = not na(bearConfirmed)
bool volumeOK = mode == "Pattern only" or (not na(relVol) and relVol >= volThreshold)
bool longDivOK = mode != "Pattern + volume + divergence" or bullActive
bool shortDivOK = mode != "Pattern + volume + divergence" or bearActive
float atr = ta.atr(14)
float longStop = low[1] - syminfo.mintick
float shortStop = high[1] + syminfo.mintick
float longRisk = close - longStop
float shortRisk = shortStop - close
bool eligible = barstate.isconfirmed and entryWindow and regular[1] and regular[2] and regular[3] and sameDay and contiguous
bool rawLong = eligible and longPattern and longTypeOK
bool rawShort = eligible and shortPattern and shortTypeOK
bool signalLong = rawLong and volumeOK and longDivOK and longRisk > syminfo.mintick and longRisk <= atr * maxRiskATR
bool signalShort = rawShort and volumeOK and shortDivOK and shortRisk > syminfo.mintick and shortRisk <= atr * maxRiskATR
string family = setup312 ? "312" : "212"
string longName = family + (initialDirection == 0 ? " U" : longReversal ? " R" : " C")
string shortName = family + (initialDirection == 0 ? " U" : shortReversal ? " R" : " C")
if signalLong
label.new(bar_index, low, longName + " LONG" + (bullActive ? " / DIV" : ""), style=label.style_label_up, color=color.teal, textcolor=color.white, size=size.tiny)
if signalShort
label.new(bar_index, high, shortName + " SHORT" + (bearActive ? " / DIV" : ""), style=label.style_label_down, color=color.maroon, textcolor=color.white, size=size.tiny)
plotshape(showDiv and bullNew, "Bull divergence confirmed NOW", shape.circle, location.belowbar, color.teal, text="D", size=size.tiny)
plotshape(showDiv and bearNew, "Bear divergence confirmed NOW", shape.circle, location.abovebar, color.maroon, text="D", size=size.tiny)
plot(relVol, "Closed-bar relative volume", display=display.data_window)
plot(rsi, "RSI 14", display=display.data_window)
plot(signalLong ? longStop : signalShort ? shortStop : na, "Planned structural stop", color.orange, style=plot.style_circles)
var int rawCount = 0
var int volumeCount = 0
var int signalCount = 0
if rawLong or rawShort
rawCount += 1
if volumeOK
volumeCount += 1
if signalLong or signalShort
signalCount += 1
var table stats = table.new(position.top_right, 2, 4, bgcolor=color.new(color.black, 20))
if barstate.islast
table.cell(stats, 0, 0, "Closed bars only", text_color=color.white)
table.cell(stats, 1, 0, mode, text_color=color.white)
table.cell(stats, 0, 1, "Patterns / volume pass", text_color=color.white)
table.cell(stats, 1, 1, str.tostring(rawCount) + " / " + str.tostring(volumeCount), text_color=color.white)
table.cell(stats, 0, 2, "Qualified signals", text_color=color.white)
table.cell(stats, 1, 2, str.tostring(signalCount), text_color=color.white)
table.cell(stats, 0, 3, "R=reversal C=continuation", text_color=color.white)
table.cell(stats, 1, 3, "Relative to first bar", text_color=color.white)
// Levels are published at confirmation time, never backdated.
showLevels = input.bool(true, "Map support / resistance")
levelPivot = input.int(3, "Swing level left/right bars", minval=1, maxval=10)
var int levelDay = na
var float sessionHigh = na
var float sessionLow = na
var bool startedAtOpen = false
var float previousHigh = na
var float previousLow = na
var float openingHigh = na
var float openingLow = na
var int openingBars = 0
var float fixedOpeningHigh = na
var float fixedOpeningLow = na
var float swingHigh = na
var float swingLow = na
float confirmedHigh = ta.pivothigh(high, levelPivot, levelPivot)
float confirmedLow = ta.pivotlow(low, levelPivot, levelPivot)
if barstate.isconfirmed and regular
if na(levelDay) or dayKey != levelDay
previousHigh := startedAtOpen ? sessionHigh : na
previousLow := startedAtOpen ? sessionLow : na
sessionHigh := high
sessionLow := low
startedAtOpen := minuteNY == 570
openingHigh := na
openingLow := na
openingBars := 0
fixedOpeningHigh := na
fixedOpeningLow := na
swingHigh := na
swingLow := na
levelDay := dayKey
else
sessionHigh := math.max(sessionHigh, high)
sessionLow := math.min(sessionLow, low)
if minuteNY < 600
openingHigh := na(openingHigh) ? high : math.max(openingHigh, high)
openingLow := na(openingLow) ? low : math.min(openingLow, low)
openingBars += 1
// The 09:55 candle closes at 10:00; all six bars must be present.
if minuteNY == 595 and openingBars == 6
fixedOpeningHigh := openingHigh
fixedOpeningLow := openingLow
if not na(confirmedHigh) and dayKey == dayKey[levelPivot * 2] and regular[levelPivot * 2]
swingHigh := confirmedHigh
if not na(confirmedLow) and dayKey == dayKey[levelPivot * 2] and regular[levelPivot * 2]
swingLow := confirmedLow
bool levelsVisible = showLevels and regular and dayKey == levelDay
plot(levelsVisible ? previousHigh : na, "Previous session high", color=color.new(color.red, 20), style=plot.style_stepline)
plot(levelsVisible ? previousLow : na, "Previous session low", color=color.new(color.teal, 20), style=plot.style_stepline)
plot(levelsVisible ? fixedOpeningHigh : na, "Opening range high (known after 10:00)", color=color.new(color.orange, 15), style=plot.style_stepline)
plot(levelsVisible ? fixedOpeningLow : na, "Opening range low (known after 10:00)", color=color.new(color.orange, 15), style=plot.style_stepline)
plot(levelsVisible ? swingHigh : na, "Confirmed swing resistance", color=color.new(color.fuchsia, 25), style=plot.style_stepline)
plot(levelsVisible ? swingLow : na, "Confirmed swing support", color=color.new(color.aqua, 25), style=plot.style_stepline)
float obstacle = na
if signalLong or signalShort
array<float> candidates = array.from(previousHigh, previousLow, fixedOpeningHigh, fixedOpeningLow, swingHigh, swingLow)
for level in candidates
if not na(level)
if signalLong and level > close
obstacle := na(obstacle) ? level : math.min(obstacle, level)
if signalShort and level < close
obstacle := na(obstacle) ? level : math.max(obstacle, level)
plot(obstacle, "Nearest mapped obstacle at signal", color.yellow, style=plot.style_circles)
plot(not na(obstacle) ? math.abs(obstacle - close) / (signalLong ? longRisk : shortRisk) : na, "Room to obstacle (planned R)", display=display.data_window)
startDate = input.time(timestamp("01 Apr 2026 00:00 +0000"), "Test start")
endDate = input.time(timestamp("01 Jan 2027 00:00 +0000"), "Test end (exclusive)")
targetR = input.float(1.5, "Profit target R", minval=0.25, step=0.25)
maxBars = input.int(6, "Maximum holding bars", minval=1, maxval=60)
notionalPct = input.float(10.0, "Equity notional allocation % (not risk %)", minval=0.1, maxval=100)
var float liveStop = na
var float liveTarget = na
bool inDates = time >= startDate and time < endDate
float qty = math.floor(strategy.equity * notionalPct / 100 / close / syminfo.mincontract) * syminfo.mincontract
// Next-bar market fills; bracket prices frozen at signal close.
if strategy.position_size == 0 and inDates and qty > 0
if signalLong
liveStop := longStop
liveTarget := close + longRisk * targetR
strategy.entry("Long", strategy.long, qty=qty, comment=longName)
strategy.exit("Long bracket", "Long", stop=liveStop, limit=liveTarget)
else if signalShort
liveStop := shortStop
liveTarget := close - shortRisk * targetR
strategy.entry("Short", strategy.short, qty=qty, comment=shortName)
strategy.exit("Short bracket", "Short", stop=liveStop, limit=liveTarget)
if strategy.position_size > 0
strategy.exit("Long bracket", "Long", stop=liveStop, limit=liveTarget)
if strategy.position_size < 0
strategy.exit("Short bracket", "Short", stop=liveStop, limit=liveTarget)
if strategy.position_size != 0
bool timedOut = bar_index - strategy.opentrades.entry_bar_index(0) >= maxBars - 1
bool flatten = (regular and minuteNY >= 945) or not regular or not inDates
if timedOut or flatten
strategy.close_all(comment=flatten ? "Session/date exit" : "Time exit")
plot(strategy.position_size != 0 ? liveStop : na, "Active stop", color.red, style=plot.style_linebr)
plot(strategy.position_size != 0 ? liveTarget : na, "Active target", color.green, style=plot.style_linebr)