本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ============================================================================
// [] ## PyneSys
// [] [] ## ##
// [] [] [] ## ## ##
// [] [] [] [] ## ## ## ##
// [] [] [] [] [] ## ## ## ## ##
// || ||
// ============================================================================
// Sneaky Pivot - Previous-Day Range Reversal at the New York Open
// © 2026 PyneSys LLC. Licensed under MPL-2.0: https://mozilla.org/MPL/2.0/
//
// Every day this script draws four levels: yesterday's regular-session high
// and low, and the next swing beyond each of them. Longs are taken only at the
// lower levels, shorts only at the upper ones. When the first 15-minute candle
// of the New York session tags a level and the second one, the "sneaky"
// candle, closes the other way, the script trades the break of that candle.
// The stop goes just beyond the setup's extreme, and the target is the other
// side of yesterday's range. The idea comes from The Rumers' video; this code
// is our own.
//
// How we read the rules
// - New York time, regular session 09:30-16:00.
// - The swing level is the extreme of the first run of candles beyond
// yesterday's high or low, looking back from the start of yesterday's
// session. Extended-hours candles count when the chart has them.
// - "At the line" means the first candle reaches the level. A candle that
// reaches both sides is skipped.
// - The sneaky candle is the 09:45 candle: green for a long, red for a short.
// - Entry: a stop order one tick beyond the sneaky candle, valid only during
// the next candle. Stop: one tick beyond the setup's extreme. A trade still
// open at the session close is closed there.
// - One trade a day at most, and none when the entry would sit beyond the
// stop or the target.
//
// Our additions (off by default)
// - Other entry timings: early, on the next candle's close, at the sneaky
// candle's midpoint, or one candle late.
// - A level tolerance in multiples of the daily ATR(14).
// - A sneaky candle allowed up to 10:15.
// - Swing levels from daily highs and lows; the swing level as the target.
//
// Before you test it
// Use standard 15-minute candles (the script stops on any other timeframe),
// one unit per trade. Commission and slippage are zero, so very different
// markets can be compared before costs. Set your own in Properties before you
// judge the results. When a stop and a target fall inside the same candle,
// TradingView's broker emulator assumes which one filled first; it does not
// see the ticks.
// ============================================================================
strategy("Sneaky Pivot [PyneSys]", shorttitle="SneakyPivot", overlay=true,
pyramiding=0, initial_capital=1000000, default_qty_type=strategy.fixed,
default_qty_value=1, process_orders_on_close=false, calc_on_every_tick=false,
calc_on_order_fills=false, commission_type=strategy.commission.percent,
commission_value=0, slippage=0)
// ---------------------------------------------------------------------------
// 1. Inputs
// ---------------------------------------------------------------------------
// The defaults are the rules taught in the video. Every other setting is one
// of our research variants; change one at a time.
string entryMode = input.string("Break", "Entry timing", options=["Break", "Early", "Candle close", "Half candle", "Late"])
float toleranceAtr = input.float(0.0, "Level tolerance (x daily ATR)", minval=0, step=0.05)
bool lateSneaky = input.bool(false, "Allow the sneaky candle up to 10:15")
string swingMode = input.string("15m run", "Swing levels from", options=["15m run", "Daily extremes"])
string targetMode = input.string("Range level", "Target", options=["Range level", "Swing level"])
// Calendar data the candles cannot tell: days without a real New York open
// (CFDs still trade on US holidays) and early-close days. YYYYMMDD, commas.
string skipDates = input.string("", "Non-trading dates")
string earlyCloseDates = input.string("", "Early-close dates (13:00)")
// ---------------------------------------------------------------------------
// 2. The New York clock
// ---------------------------------------------------------------------------
// 570 is 09:30 and 960 is 16:00 in minutes after midnight.
string zone = "America/New_York"
int dateKey = year(time, zone) * 10000 + month(time, zone) * 100 + dayofmonth(time, zone)
int minuteOfDay = hour(time, zone) * 60 + minute(time, zone)
int closeMinute = hour(time_close, zone) * 60 + minute(time_close, zone)
bool tradingDay = not str.contains(skipDates, str.tostring(dateKey))
bool earlyClose = str.contains(earlyCloseDates, str.tostring(dateKey))
int sessionEnd = earlyClose ? 780 : 960
bool rth = tradingDay and minuteOfDay >= 570 and minuteOfDay < sessionEnd
if barstate.isfirst and timeframe.period != "15"
runtime.error("Use standard 15-minute candles.")
// Every candle's high and low, oldest first, for the swing scan in section 4.
var array<float> barHighs = array.new<float>()
var array<float> barLows = array.new<float>()
array.push(barHighs, high)
array.push(barLows, low)
int barSlot = array.size(barHighs) - 1
// ---------------------------------------------------------------------------
// 3. Regular-session statistics: range levels and the daily ATR
// ---------------------------------------------------------------------------
// The running session is collected in cur*. When the next session opens, it
// becomes the "previous session" that today's range levels come from.
var int sessionDate = na
var float curHigh = na
var float curLow = na
var float curClose = na
var int curStart = na
var float prevHigh = na
var float prevLow = na
var int prevStart = na
var float lastClose = na
var float dailyAtr = na
var int atrCount = 0
var float atrSum = 0.0
// Completed session highs and lows, oldest first, for daily swing levels.
var array<float> sessionHighs = array.new<float>()
var array<float> sessionLows = array.new<float>()
bool firstRthBar = rth and (na(sessionDate) or dateKey != sessionDate)
if firstRthBar
if not na(curHigh)
// Wilder's ATR(14) over regular sessions: a plain average of the first
// 14 true ranges, then smoothing with weight 1/14.
float tr = na(lastClose) ? curHigh - curLow : math.max(curHigh - curLow, math.abs(curHigh - lastClose), math.abs(curLow - lastClose))
atrCount += 1
if atrCount <= 14
atrSum += tr
dailyAtr := atrCount == 14 ? atrSum / 14 : na
else
dailyAtr := (dailyAtr * 13 + tr) / 14
array.push(sessionHighs, curHigh)
array.push(sessionLows, curLow)
prevHigh := curHigh
prevLow := curLow
prevStart := curStart
lastClose := curClose
sessionDate := dateKey
curHigh := high
curLow := low
curStart := barSlot
else if rth
curHigh := math.max(curHigh, high)
curLow := math.min(curLow, low)
curClose := rth ? close : curClose
// ---------------------------------------------------------------------------
// 4. The four levels of the day
// ---------------------------------------------------------------------------
// Computed once, on the session's first candle. The swing scan walks left
// from the candle before the previous session's first one: it finds the first
// candle beyond the range level, then follows that run of candles beyond the
// level and keeps its extreme. No candle beyond the level means no swing level.
var float rangeHigh = na
var float rangeLow = na
var float swingHigh = na
var float swingLow = na
var float tolerance = na
findSwing(array<float> values, int fromSlot, float level, bool above) =>
float extreme = na
int i = fromSlot
while i >= 0
float v = array.get(values, i)
bool beyond = above ? v > level : v < level
if beyond
extreme := na(extreme) ? v : above ? math.max(extreme, v) : math.min(extreme, v)
else if not na(extreme)
break
i -= 1
extreme
// Daily variant: the most recent earlier session whose extreme is beyond the
// range level. The last element of the arrays is the previous session itself.
findDailySwing(array<float> values, float level, bool above) =>
float found = na
int i = array.size(values) - 2
while i >= 0 and na(found)
float v = array.get(values, i)
if above ? v > level : v < level
found := v
i -= 1
found
if firstRthBar
rangeHigh := prevHigh
rangeLow := prevLow
tolerance := toleranceAtr > 0 ? toleranceAtr * dailyAtr : 0.0
if na(prevStart)
swingHigh := na
swingLow := na
else if swingMode == "15m run"
swingHigh := findSwing(barHighs, prevStart - 1, rangeHigh, true)
swingLow := findSwing(barLows, prevStart - 1, rangeLow, false)
else
swingHigh := findDailySwing(sessionHighs, rangeHigh, true)
swingLow := findDailySwing(sessionLows, rangeLow, false)
// ---------------------------------------------------------------------------
// 5. The three-candle setup
// ---------------------------------------------------------------------------
// slot counts the 15-minute candles of the session: 0 is 09:30, 1 is 09:45,
// 2 is 10:00. side is +1 for a long setup, -1 for a short, 0 for none.
int slot = rth ? int(math.floor((minuteOfDay - 570) / 15)) : -1
var int side = 0
var float setupHigh = na
var float setupLow = na
var int sneakySlot = na
var float sneakyHigh = na
var float sneakyLow = na
var float stopLevel = na
var float targetLevel = na
var float entryLevel = na
var int waitUntil = na
var bool tradedToday = false
if firstRthBar
side := 0
sneakySlot := na
entryLevel := na
waitUntil := na
tradedToday := false
setupHigh := high
setupLow := low
// The first candle has to be the 09:30 candle and has to reach exactly
// one of the two level groups.
if minuteOfDay == 570 and not na(rangeHigh) and not na(tolerance)
bool reachesLow = low <= rangeLow + tolerance
bool reachesHigh = high >= rangeHigh - tolerance
side := reachesLow and not reachesHigh ? 1 : reachesHigh and not reachesLow ? -1 : 0
else if rth and side != 0 and na(sneakySlot)
setupHigh := math.max(setupHigh, high)
setupLow := math.min(setupLow, low)
int lastSneaky = lateSneaky ? 3 : 1
if slot >= 1 and slot <= lastSneaky
bool confirms = side == 1 ? close > open : close < open
if confirms
sneakySlot := slot
sneakyHigh := high
sneakyLow := low
stopLevel := side == 1 ? setupLow - syminfo.mintick : setupHigh + syminfo.mintick
targetLevel := targetMode == "Range level" ? (side == 1 ? rangeHigh : rangeLow) : (side == 1 ? swingHigh : swingLow)
else if slot == lastSneaky
side := 0
// ---------------------------------------------------------------------------
// 6. Entry timing
// ---------------------------------------------------------------------------
// Orders placed on a candle's close work from the next candle. A level is
// usable only between the stop and the target; market entries are checked
// against the close they are decided on.
bool isLong = side == 1
usable(float price) =>
not na(price) and not na(targetLevel) and (isLong ? price > stopLevel and price < targetLevel : price < stopLevel and price > targetLevel)
placeExit() =>
strategy.exit("Exit", from_entry="Entry", stop=stopLevel, limit=targetLevel)
bool onSneaky = rth and not na(sneakySlot) and slot == sneakySlot and not tradedToday
bool afterSneaky = rth and not na(sneakySlot) and slot == sneakySlot + 1 and not tradedToday
float breakLevel = isLong ? sneakyHigh + syminfo.mintick : sneakyLow - syminfo.mintick
if onSneaky
if entryMode == "Break" and usable(breakLevel)
// A stop order beyond the sneaky candle, alive for one candle.
entryLevel := breakLevel
strategy.entry("Entry", isLong ? strategy.long : strategy.short, stop=entryLevel)
placeExit()
waitUntil := slot + 1
else if entryMode == "Half candle" and usable((sneakyHigh + sneakyLow) / 2)
// A limit order at the sneaky candle's midpoint, alive for two candles.
entryLevel := (sneakyHigh + sneakyLow) / 2
strategy.entry("Entry", isLong ? strategy.long : strategy.short, limit=entryLevel)
placeExit()
waitUntil := slot + 2
else if entryMode == "Early" and usable(close)
// A market order at the sneaky candle's close, filled at the next open.
entryLevel := close
strategy.entry("Entry", isLong ? strategy.long : strategy.short)
placeExit()
tradedToday := true
if afterSneaky and (entryMode == "Candle close" or entryMode == "Late")
// Both wait for the candle after the sneaky one. "Candle close" needs that
// candle to close beyond the sneaky candle; "Late" only needs it to have
// traded beyond it. Either one enters at the market on the next open.
bool broke = entryMode == "Candle close" ? (isLong ? close > sneakyHigh : close < sneakyLow) : (isLong ? high > sneakyHigh : low < sneakyLow)
if broke and usable(close)
entryLevel := close
strategy.entry("Entry", isLong ? strategy.long : strategy.short)
placeExit()
tradedToday := true
// Cancel an unfilled stop or limit order when its window ends.
if strategy.position_size != 0
tradedToday := true
if not na(waitUntil) and rth and slot >= waitUntil and strategy.position_size == 0
strategy.cancel("Entry")
waitUntil := na
// ---------------------------------------------------------------------------
// 7. Session close
// ---------------------------------------------------------------------------
// An open position is closed at the close of the last regular candle. The
// second guard closes anything that is still open on a later candle, which
// only happens when a session ends without its expected last candle.
bool lastRthBar = rth and closeMinute == sessionEnd
if strategy.position_size != 0 and (lastRthBar or (not rth and not na(sessionDate) and dateKey != sessionDate))
strategy.close_all(comment="Session close", immediately=true)
// Only the unfilled entry order is cancelled here: cancel_all() would also
// drop the closing order queued just above.
if lastRthBar
strategy.cancel("Entry")
side := 0
// ---------------------------------------------------------------------------
// 8. Plots: the levels and the setup state, for the chart and the audit
// ---------------------------------------------------------------------------
plot(rth ? rangeHigh : na, "Range high", color=color.new(color.blue, 0), style=plot.style_linebr)
plot(rth ? rangeLow : na, "Range low", color=color.new(color.blue, 0), style=plot.style_linebr)
plot(rth ? swingHigh : na, "Swing high", color=color.new(color.purple, 0), style=plot.style_linebr)
plot(rth ? swingLow : na, "Swing low", color=color.new(color.purple, 0), style=plot.style_linebr)
plot(rth and not na(sneakySlot) ? stopLevel : na, "Stop", color=color.new(color.red, 0), style=plot.style_linebr)
plot(rth and not na(sneakySlot) ? targetLevel : na, "Target", color=color.new(color.green, 0), style=plot.style_linebr)
plot(rth and not na(sneakySlot) ? entryLevel : na, "Entry level", color=color.new(color.orange, 0), style=plot.style_linebr)
plot(rth ? side : na, "Side", display=display.data_window)
plot(rth ? tolerance : na, "Tolerance", display=display.data_window)
plot(rth ? dailyAtr : na, "Daily ATR", display=display.data_window)
plot(strategy.position_size, "Position", display=display.data_window)