本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ============================================================================
// [] ## PyneSys
// [] [] ## ##
// [] [] [] ## ## ##
// [] [] [] [] ## ## ## ##
// [] [] [] [] [] ## ## ## ## ##
// || ||
// ============================================================================
// ORB One-Candle Retest
// © 2026 PyneSys LLC. Licensed under MPL-2.0: https://mozilla.org/MPL/2.0/
//
// An opening range breakout for the New York open on a 1-minute chart. The
// first five minutes (9:30-9:34) set the range. When a 1-minute candle closes
// outside it, we wait for price to come back to the broken level and reject
// it, then trade in the direction of the breakout. The stop sits just beyond
// the entry candle and the target is twice the risk. The idea comes from
// Scarface Trades' video; this code is our own.
//
// How we read the rules
// - "Weak price action" at the retest is not defined in the video. The
// default reading: one candle touches the level (within a small tolerance),
// closes back on the breakout side, and closes in the breakout direction.
// Two other readings can be selected: a later confirming candle after the
// touch, or a hammer (shooting star for shorts) at the level.
// - A candle that closes back inside the range before an entry cancels that
// side for the day. The other side can still break out and trade.
// - Entry at the next candle's open. Stop one tick beyond the entry candle,
// target at twice the distance from the entry candle's close to the stop.
// - At most one trade per direction per day, one position at a time. No new
// signal after 10:30, and an open trade is closed at 11:00 New York time.
//
// Our additions (off by default)
// - A 12:00 exit, a target rounded out to the next whole price unit, and a
// coin flip mode that replaces each trade's direction with a random one
// for comparison.
//
// Before you test it
// Use a 1-minute chart of a US stock; all times are New York time, with or
// without extended hours. Commission and slippage are zero, so markets and
// readings can be compared before costs. Set your own in Properties before
// you judge the results.
// ============================================================================
// Reading guide: section 1 holds the settings, 2 the clock, 3 the opening
// range, 4 the breakout and retest state of each side, 5 the orders and 6 the
// chart.
strategy("ORB One-Candle Retest [PyneSys]", shorttitle="ORB1C", overlay=true,
initial_capital=1000000, default_qty_type=strategy.fixed, default_qty_value=1,
commission_value=0, slippage=0, pyramiding=0)
// ---------------------------------------------------------------------------
// 1. Inputs
// ---------------------------------------------------------------------------
// The defaults follow the video: a five-minute range from 9:30, a 2R target.
string retestRule = input.string("Rejection candle", "Retest rule", options=["Rejection candle", "Close after touch", "Hammer"], group="Retest", tooltip="Rejection candle: the same candle touches the level, closes beyond it and closes in the breakout direction. Close after touch: after any touch, the first candle that closes beyond the level in the breakout direction. Hammer: a candle at the level whose wick against the breakout is at least twice its body and which closes in its outer third.")
float tolerancePct = input.float(5.0, "Touch tolerance (% of the range)", minval=0, step=1, group="Retest", tooltip="How close a candle must come to the broken level to count as a touch, as a percentage of the opening range's height.")
float rewardRatio = input.float(2.0, "Reward-to-risk ratio", minval=0.1, step=0.1, group="Risk")
bool roundTarget = input.bool(false, "Round the target out to a whole price", group="Risk", tooltip="Moves the target away from the entry to the next whole price unit, a reading of \"at least 2R, at a round number\".")
string exitTime = input.string("11:00", "Close open trades at", options=["11:00", "12:00"], group="Session")
int coinSeed = input.int(0, "Coin flip seed (0 = off)", minval=0, group="Research", tooltip="Above 0, each trade keeps its entry time, risk and target distance but gets a random direction. Each seed gives a different, repeatable sequence.")
// ---------------------------------------------------------------------------
// 2. The New York clock
// ---------------------------------------------------------------------------
// Every rule is written in New York time, so the script works the same on
// charts with or without extended hours, in summer and in winter.
string NY = "America/New_York"
int barMinute = hour(time, NY) * 60 + minute(time, NY)
int nyDay = year(time, NY) * 10000 + month(time, NY) * 100 + dayofmonth(time, NY)
bool newDay = nyDay != nyDay[1]
int RANGE_START = 9 * 60 + 30 // first range candle, 9:30
int RANGE_END = 9 * 60 + 34 // last range candle, 9:34
int LAST_SIGNAL = 10 * 60 + 29 // the 10:29 candle closes at 10:30
int closeMinute = exitTime == "11:00" ? 10 * 60 + 59 : 11 * 60 + 59
if timeframe.period != "1"
runtime.error("This strategy is defined on a 1-minute chart.")
// ---------------------------------------------------------------------------
// 3. The opening range
// ---------------------------------------------------------------------------
// The high and low of the five 1-minute candles from 9:30 to 9:34. A day with
// a missing range candle is skipped, because its range would be incomplete.
var float rangeHigh = na
var float rangeLow = na
var int rangeBars = 0
// State of each side: 0 waiting for a breakout, 1 broken out and waiting for
// a retest, 2 touched (used by the "Close after touch" reading), 3 finished
// for the day (traded or cancelled).
var int longState = 0
var int shortState = 0
if newDay
rangeHigh := na
rangeLow := na
rangeBars := 0
longState := 0
shortState := 0
if barMinute >= RANGE_START and barMinute <= RANGE_END
rangeHigh := na(rangeHigh) ? high : math.max(rangeHigh, high)
rangeLow := na(rangeLow) ? low : math.min(rangeLow, low)
rangeBars += 1
bool rangeReady = rangeBars == 5 and barMinute > RANGE_END
float tolerance = rangeReady ? (rangeHigh - rangeLow) * tolerancePct / 100 : na
// ---------------------------------------------------------------------------
// 4. Breakout and retest
// ---------------------------------------------------------------------------
// The retest is checked from the candle after the breakout candle, so the
// breakout candle itself can never be the entry candle.
bool inSignalWindow = rangeReady and barMinute <= LAST_SIGNAL
float body = math.abs(close - open)
// Long side: the broken level is the range high.
bool longTouch = low <= rangeHigh + tolerance
bool longClosesUp = close > rangeHigh and close > open
bool longHammer = longTouch and close > rangeHigh and math.min(open, close) - low >= 2 * body and close >= high - (high - low) / 3
// Short side: the broken level is the range low.
bool shortTouch = high >= rangeLow - tolerance
bool shortClosesDown = close < rangeLow and close < open
bool shortStar = shortTouch and close < rangeLow and high - math.max(open, close) >= 2 * body and close <= low + (high - low) / 3
bool longSignal = false
bool shortSignal = false
bool flat = strategy.position_size == 0
if inSignalWindow
if longState == 1 or longState == 2
if retestRule == "Close after touch" and longTouch
longState := 2
longSignal := switch retestRule
"Rejection candle" => longTouch and longClosesUp
"Close after touch" => longState == 2 and longClosesUp
=> longHammer
// A close back inside the range cancels the long side for the day.
if not longSignal and close < rangeHigh
longState := 3
else if longState == 0 and close > rangeHigh
longState := 1
if shortState == 1 or shortState == 2
if retestRule == "Close after touch" and shortTouch
shortState := 2
shortSignal := switch retestRule
"Rejection candle" => shortTouch and shortClosesDown
"Close after touch" => shortState == 2 and shortClosesDown
=> shortStar
if not shortSignal and close > rangeLow
shortState := 3
else if shortState == 0 and close < rangeLow
shortState := 1
// A signal while a trade is open is dropped, and that side stays available.
if not flat
if longSignal
longState := 2
if shortSignal
shortState := 2
longSignal := false
shortSignal := false
// ---------------------------------------------------------------------------
// 5. Orders
// ---------------------------------------------------------------------------
// The stop and the target are fixed on the signal candle, from the chart's
// prices, so every cost setting trades the same levels.
// Coin flip: a repeatable pseudo-random bit from the seed and the candle's
// minute. All products stay below 2^53, so they are exact in every engine.
coinIsLong() =>
int m = int(math.floor(time / 60000)) % 1000003
int v = (m * 7919 + coinSeed * 104729) % 1000003
v := (v * v + 12345) % 1000003
v := (v * v + 54321) % 1000003
v % 2 == 0
roundAway(float price, bool up) =>
up ? math.ceil(price) : math.floor(price)
float plannedRisk = na
if longSignal or shortSignal
bool setupLong = longSignal
float risk = setupLong ? close - (low - syminfo.mintick) : (high + syminfo.mintick) - close
plannedRisk := risk
bool goLong = coinSeed > 0 ? coinIsLong() : setupLong
float stopPrice = goLong ? close - risk : close + risk
float targetPrice = goLong ? close + rewardRatio * risk : close - rewardRatio * risk
if roundTarget
targetPrice := roundAway(targetPrice, goLong)
if goLong
strategy.entry("Long", strategy.long)
strategy.exit("Long exit", "Long", stop=stopPrice, limit=targetPrice)
else
strategy.entry("Short", strategy.short)
strategy.exit("Short exit", "Short", stop=stopPrice, limit=targetPrice)
if setupLong
longState := 3
else
shortState := 3
// The time exit: the order goes out on the close of the last candle and
// fills at the open of the next one (11:00 or 12:00).
if strategy.position_size != 0 and (barMinute >= closeMinute or newDay)
strategy.close_all(comment="Time exit")
// ---------------------------------------------------------------------------
// 6. Chart
// ---------------------------------------------------------------------------
bool showRange = rangeReady and barMinute <= closeMinute
plot(showRange ? rangeHigh : na, "Range high", color=color.new(color.teal, 0), linewidth=2, style=plot.style_linebr)
plot(showRange ? rangeLow : na, "Range low", color=color.new(color.orange, 0), linewidth=2, style=plot.style_linebr)
plotshape(longSignal, "Long signal", shape.triangleup, location.belowbar, color.teal, size=size.tiny)
plotshape(shortSignal, "Short signal", shape.triangledown, location.abovebar, color.orange, size=size.tiny)
// The risk fixed on a signal candle, in price units, for the Data Window and
// for measuring results in R.
plot(plannedRisk, "Planned risk", display=display.data_window)