本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// =====================================================================================================
// Intraday Momentum, Long-Only (Noise Area breakout) file: intraday_momentum_longonly.pine
// Based on Zarattini, Aziz & Barbon (2024), "Beat the Market: An Effective Intraday Momentum Strategy
// for S&P500 ETF (SPY)". Mirrors run_intraday_momentum_backtest.m / the Python replication, long side only.
//
// WHAT IT DOES (once per check time, e.g. every 60 min from 10:00 to 15:00 ET):
// sigma(t) = average over the prior N days of |Close(t) / Open(09:30) - 1| at the same time of day
// Upper = max(Open, prev close) * (1 + VM * sigma) Lower = min(Open, prev close) * (1 - VM * sigma)
// Flat -> LONG when the check-bar close is above Upper AND above VWAP. Fill = next bar's open.
// Long -> EXIT when a check-bar close falls below max(Upper, VWAP) (trailing stop, evaluated at checks only).
// Always flat by the end of the day (no overnight). Long only: no short signals.
//
// SETUP
// * Use SPY or QQQ on an INTRADAY chart, regular trading hours. 5-minute is the practical choice (TradingView
// keeps a limited number of bars, and 1-minute charts often cannot hold the 20 prior days the bands need).
// * Chart timeframe must divide the check interval (e.g. 1, 5, 15 or 30 min bars for a 60-minute check).
// * Defaults are the "suggested settings" from the study: lookback 20, check every 60 min, VM 1.25.
// The paper's baseline is 14 / 30 / 1.0.
// * Alerts: add an alert on this indicator, condition "Long entry", "Long exit (stop)" or "End of day flatten",
// trigger "Once Per Bar Close". Signals are known at the bar close; the order goes in at the next bar's open.
//
// DIFFERENCES FROM THE BACKTEST (small): VWAP uses the chart bars (hlc3 x volume), so it matches the 1-minute
// backtest only approximately on a 5-minute chart; the end-of-day exit uses the first bar whose close is at or
// after "Flatten at" (default 389 = 15:59) instead of the 15:59 close itself; the simulated P&L in the table is
// gross of financing and uses the cost input below.
// NOT TESTED against TradingView's own backtester. Research tool, not investment advice.
//
// CHANGELOG
// 2026-11-12 v1.0 New file (long-only indicator with bands, VWAP, stop, alerts, simulated P&L table).
// =====================================================================================================
indicator("Intraday Momentum Long-Only (Noise Area)", shorttitle="IMOM-L", overlay=true, max_labels_count=500)
// ---------------------------------------------------------------- inputs
G1 = "Strategy"
lookback = input.int(20, "Lookback days for sigma", minval=5, maxval=60, group=G1)
vm = input.float(1.25, "Band multiplier (VM)", minval=0.25, step=0.05, group=G1)
firstCheck = input.int(30, "First check (minutes after 09:30)", minval=5, maxval=360, group=G1)
checkEvery = input.int(60, "Check every (minutes)", options=[15, 30, 60], group=G1)
lastCheck = input.int(360, "Last check (minutes after 09:30)", minval=30, maxval=380, group=G1)
eodMin = input.int(389, "Flatten at (minutes after 09:30; 390 = 16:00)", minval=300, maxval=390, group=G1)
G2 = "Simulation / display"
costBp = input.float(3.5, "Round-trip cost per trade (bp) for simulated P&L", minval=0.0, step=0.5, group=G2)
showTable = input.bool(true, "Show status table", group=G2)
G3 = "Session"
sess = input.session("0930-1600", "Regular session", group=G3)
tz = input.string("America/New_York", "Exchange time zone", group=G3)
// ---------------------------------------------------------------- session and time of day
inSess = not na(time(timeframe.period, sess, tz))
newDay = inSess and (not inSess[1] or dayofmonth(time, tz) != dayofmonth(time[1], tz))
m = hour(time_close, tz) * 60 + minute(time_close, tz) - 570 // minutes after 09:30 at this bar's close
isCheck = inSess and m >= firstCheck and m <= lastCheck and (m - firstCheck) % checkEvery == 0
tfSec = timeframe.in_seconds()
tfOk = timeframe.isintraday and tfSec >= 60 and (checkEvery * 60) % tfSec == 0 and (firstCheck * 60) % tfSec == 0
nChk = int(math.floor((lastCheck - firstCheck) / checkEvery)) + 1
// ---------------------------------------------------------------- persistent state
var float[] ring = array.new_float(lookback * nChk, na) // |move from open| at each check time, last N days
var int dayN = -1
var float dayOpen = na
var float prevClose = na
var float lastClose = na
var float cumPV = 0.0
var float cumV = 0.0
var float ubC = na
var float lbC = na
var float sigC = na
var float stopC = na
var int pos = 0 // signal state: 1 = long
var bool pendEntry = false
var bool pendExit = false
var bool inTrade = false // simulated fill state
var float entryPx = na
var int trades = 0
var int wins = 0
var float sumNetBp = 0.0
var float eq = 1.0
var float peak = 1.0
var float maxDD = 0.0
// ---------------------------------------------------------------- day reset and VWAP
if newDay
dayN += 1
prevClose := lastClose
dayOpen := open
cumPV := 0.0
cumV := 0.0
ubC := na
lbC := na
sigC := na
stopC := na
if inSess
cumPV += hlc3 * volume
cumV += volume
vwapNow = inSess and cumV > 0 ? cumPV / cumV : na
// ---------------------------------------------------------------- bar-close logic
bool entrySig = false
bool exitSig = false
bool eodSig = false
if barstate.isconfirmed and inSess and tfOk
float exitPx = na
// a new day with an open position (gap in data / half day): close at the previous close
if newDay
if inTrade
exitPx := prevClose
pos := 0
pendEntry := false
pendExit := false
// fills of last bar's signals happen at this bar's open
if pendEntry
inTrade := true
entryPx := open
pendEntry := false
if pendExit and inTrade
exitPx := open
pendExit := false
// signal logic at check times
if isCheck and m < eodMin
int base = (dayN % lookback) * nChk
int slot = int((m - firstCheck) / checkEvery)
float sumMv = 0.0
int cnt = 0
for d = 0 to lookback - 1
float v = array.get(ring, d * nChk + slot)
if not na(v)
sumMv += v
cnt += 1
float mvNow = math.abs(close / dayOpen - 1)
float sigNow = cnt >= lookback ? sumMv / lookback : na
array.set(ring, base + slot, mvNow) // written after the read, so it is not part of today's sigma
if not na(sigNow)
ubC := math.max(dayOpen, prevClose) * (1 + vm * sigNow)
lbC := math.min(dayOpen, prevClose) * (1 - vm * sigNow)
sigC := sigNow
stopC := math.max(ubC, vwapNow)
if pos == 0 and close > ubC and close > vwapNow
pos := 1
pendEntry := true
entrySig := true
else if pos == 1 and close < stopC
pos := 0
pendExit := true
exitSig := true
// end-of-day flatten
if m >= eodMin and na(exitPx) and (pos == 1 or pendEntry or inTrade)
if inTrade and na(exitPx)
exitPx := close
pos := 0
pendEntry := false
pendExit := false
eodSig := true
// book the simulated trade
if not na(exitPx) and inTrade
float r = exitPx / entryPx - 1 - costBp / 10000.0
trades += 1
if r > 0
wins += 1
sumNetBp += r * 10000.0
eq *= (1 + r)
peak := math.max(peak, eq)
maxDD := math.min(maxDD, eq / peak - 1)
inTrade := false
lastClose := close
// ---------------------------------------------------------------- plots
plot(vwapNow, "VWAP", color=color.orange, linewidth=2, style=plot.style_linebr)
pUB = plot(inSess ? ubC : na, "Upper band", color=color.green, style=plot.style_linebr)
pLB = plot(inSess ? lbC : na, "Lower band", color=color.new(color.gray, 20), style=plot.style_linebr)
fill(pUB, pLB, color=color.new(color.gray, 90))
plot(inSess and pos == 1 ? stopC : na, "Long stop (checked at check times)", color=color.red, linewidth=2, style=plot.style_linebr)
bgcolor(inSess and pos == 1 ? color.new(color.green, 92) : na)
plotshape(entrySig, "Long entry", shape.triangleup, location.belowbar, color.green, size=size.small, text="BUY")
plotshape(exitSig, "Exit (stop)", shape.triangledown, location.abovebar, color.red, size=size.small, text="EXIT")
plotshape(eodSig, "End of day flatten", shape.xcross, location.abovebar, color.gray, size=size.tiny, text="EOD")
// ---------------------------------------------------------------- alerts (use "Once Per Bar Close")
alertcondition(entrySig, "Long entry", "IMOM-L {{ticker}}: LONG entry signal. Buy at the next bar's open.")
alertcondition(exitSig, "Long exit (stop)", "IMOM-L {{ticker}}: close fell below max(upper band, VWAP). Sell at the next bar's open.")
alertcondition(eodSig, "End of day flatten", "IMOM-L {{ticker}}: end of day. Flatten any long position now.")
alertcondition(entrySig or exitSig or eodSig, "Any signal", "IMOM-L {{ticker}}: signal (entry, exit or end of day). Check the chart.")
// ---------------------------------------------------------------- status table
var table tbl = table.new(position.top_right, 2, 11, border_width=1, frame_color=color.gray, frame_width=1)
f_row(r, label, val) =>
table.cell(tbl, 0, r, label, text_color=color.white, bgcolor=color.new(color.gray, 30), text_halign=text.align_left, text_size=size.small)
table.cell(tbl, 1, r, val, text_color=color.white, bgcolor=color.new(color.gray, 55), text_halign=text.align_right, text_size=size.small)
if showTable and barstate.islast
f_row(0, "IMOM Long-Only", tfOk ? "OK" : "Bad timeframe")
f_row(1, "Position (signal)", pos == 1 ? "LONG" : "flat")
f_row(2, "Sigma", na(sigC) ? "n/a" : str.tostring(sigC * 100, "#.###") + "%")
f_row(3, "Upper band", na(ubC) ? "n/a" : str.tostring(ubC, "#.##"))
f_row(4, "Lower band", na(lbC) ? "n/a" : str.tostring(lbC, "#.##"))
f_row(5, "VWAP", na(vwapNow) ? "n/a" : str.tostring(vwapNow, "#.##"))
f_row(6, "Sim trades", str.tostring(trades))
f_row(7, "Win rate", trades > 0 ? str.tostring(100.0 * wins / trades, "#.#") + "%" : "n/a")
f_row(8, "Avg net / trade", trades > 0 ? str.tostring(sumNetBp / trades, "#.#") + " bp" : "n/a")
f_row(9, "Sim cum. return (1x)", str.tostring((eq - 1) * 100, "#.#") + "%")
f_row(10, "Sim max drawdown", str.tostring(maxDD * 100, "#.#") + "%")