Myth Busting E07 - Two-Candle Bias Breakout [PyneSys]

PyneSys · strategy · 375 行 · 点赞 12 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// ============================================================================
//              [] ##          PyneSys
//           [] [] ## ##
//        [] [] [] ## ## ##
//     [] [] [] [] ## ## ## ##
//  [] [] [] [] [] ## ## ## ## ##
//              || ||
// ============================================================================
// Two-Candle Bias Breakout
// © 2026 PyneSys LLC. Licensed under MPL-2.0: https://mozilla.org/MPL/2.0/
//
// A New York open breakout on a 5-minute chart of the Nasdaq 100. Two candles
// set the direction for the day: if yesterday's daily candle and the last
// closed 4-hour candle are both bullish, we only buy; if both are bearish, we
// only sell; if they disagree, we stay out. A small pullback of at least two
// opposite candles marks a level. When a candle closes through it, we wait
// for a candle with a wick back toward the level, then enter with a stop
// order at the breakout candle's extreme. The stop goes beyond the other end
// of the breakout candle and the target is one times the risk. The idea
// comes from Harry Sharpe's interview on the IQCapital channel; this code is
// our own. The bias follows the rule of his open-source Tradesharpe Session
// Bias indicator (TradeSharpe99): the previous daily and 4-hour candles.
//
// How we read the rules
// - The daily candle runs from 17:00 to 17:00 New York time, and the 4-hour
//   candle before the 9:30 open is the 5:00-9:00 one.
// - The level is the highest body of the last run of two or more bearish
//   candles that follows a bullish candle (the lowest body of a bullish run
//   for shorts). The range runs from that run to the breakout candle.
// - The breakout candle must close beyond the level in its own direction,
//   have a wick past its close, and be no taller than half of the range.
// - The wick candle needs a wick of at least 5 points toward the level.
// - A close back through the level before the fill cancels the setup.
// - Breakouts count from 9:30 to 10:30 New York time, an unfilled order is
//   cancelled at 10:30, and there is at most one trade a day. A trade still
//   open at 16:00 is closed.
//
// Our additions (off by default)
// - A break-even exit: at +1R the stop moves to the entry and the target is
//   2R, the way the trade was managed in the interview's example.
// - Bias variants (no filter, mixed days in both directions, long only), a
//   15-minute chart, a London open window, a longer window, no wick minimum,
//   no breakout size limit, and a coin flip mode that gives each trade a
//   random direction at the same price for comparison.
//
// Before you test it
// Use a 5-minute (or 15-minute) chart of a Nasdaq 100 CFD or future; all
// times are New York time. Commission and slippage are zero, so readings and
// markets 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 two-candle
// bias, 4 the levels, 5 the breakout and wick state, 6 the orders and the
// exits, 7 the chart.
strategy("Two-Candle Bias Breakout [PyneSys]", shorttitle="2CBB", 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 interview: New York open, one hour, a 1:1 target.
string biasMode = input.string("Two-candle bias", "Direction", options=["Two-candle bias", "Bias, mixed days both ways", "No filter", "Long only"], group="Bias", tooltip="Two-candle bias: buy only when yesterday's daily candle and the last closed 4-hour candle are both bullish, sell only when both are bearish, skip mixed days. The other options are for comparison.")
string exitMode = input.string("Fixed 1R", "Exit", options=["Fixed 1R", "Break-even at 1R, 2R target"], group="Risk", tooltip="Fixed 1R: stop beyond the breakout candle, target one times the risk. Break-even: once a candle closes after reaching +1R, the stop moves to the entry and the target is 2R.")
float minWick = input.float(5.0, "Minimum wick (points, 0 = any)", minval=0, step=0.5, group="Entry", tooltip="The wick toward the level that the candle after the breakout must show before the stop order goes in.")
float maxBreakoutPct = input.float(50.0, "Breakout candle max (% of range, 0 = off)", minval=0, step=5, group="Entry", tooltip="A breakout candle taller than this share of the range does not count.")
string sessionName = input.string("New York open", "Session", options=["New York open", "London open"], group="Session", tooltip="New York open starts at 9:30, London open at 3:00, New York time.")
int windowMinutes = input.int(60, "Window (minutes)", options=[60, 120], group="Session", tooltip="How long after the session start a breakout can form and an order can wait.")
int dayStartHour = input.int(17, "Trading day starts (New York hour)", minval=0, maxval=23, group="Bias", tooltip="The daily candle runs from this hour to the same hour the next day; the 4-hour candles start at it.")
int coinSeed = input.int(0, "Coin flip seed (0 = off)", minval=0, group="Research", tooltip="Above 0, each order keeps its price, 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 behaves the same in
// summer and in winter and on charts with any session setting.
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 tfMinutes = timeframe.multiplier
 
if not timeframe.isintraday or (tfMinutes != 5 and tfMinutes != 15)
    runtime.error("This strategy is defined on a 5-minute or a 15-minute chart.")
 
int sessionStart = sessionName == "New York open" ? 9 * 60 + 30 : 3 * 60
int windowEnd = sessionStart + windowMinutes
// A breakout candle must close inside the window: it opens no later than
// one candle before the window ends.
bool inWindow = barMinute >= sessionStart and barMinute + tfMinutes <= windowEnd
// The candle that closes at 16:00 sends the time exit, which fills at the
// open of the next candle.
bool lastCandle = barMinute + tfMinutes == 16 * 60
 
// ---------------------------------------------------------------------------
// 3. The two-candle bias
// ---------------------------------------------------------------------------
// The daily and 4-hour candles are built from the chart's own bars. A
// trading day starts at 17:00 New York time (the CFD and futures day), and
// its 4-hour candles start at 17:00, 21:00, 1:00, 5:00, 9:00 and 13:00. At the
// 9:30 open the previous closed 4-hour candle is the 5:00-9:00 one. Building
// them here keeps the rule the same in every engine; reading close[1] of a
// higher timeframe on historical bars would return one candle older.
int shifted = time + (24 - dayStartHour) * 3600000
int tradingDay = year(shifted, NY) * 10000 + month(shifted, NY) * 100 + dayofmonth(shifted, NY)
int minutesIntoDay = (hour(time, NY) - dayStartHour + 24) % 24 * 60 + minute(time, NY)
int fourHourKey = tradingDay * 10 + int(math.floor(minutesIntoDay / 240))
 
var float dayOpen = na
var float dayClose = na
var float prevDayOpen = na
var float prevDayClose = na
var float fourOpen = na
var float fourClose = na
var float prevFourOpen = na
var float prevFourClose = na
if tradingDay != nz(tradingDay[1])
    prevDayOpen := dayOpen
    prevDayClose := dayClose
    dayOpen := open
if fourHourKey != nz(fourHourKey[1])
    prevFourOpen := fourOpen
    prevFourClose := fourClose
    fourOpen := open
dayClose := close
fourClose := close
 
// Bullish when both previous candles closed up, bearish when both closed
// down; anything else is a mixed day.
bool bothUp = prevDayClose > prevDayOpen and prevFourClose > prevFourOpen
bool bothDown = prevDayClose < prevDayOpen and prevFourClose < prevFourOpen
int biasNow = bothUp ? 1 : bothDown ? -1 : 0
 
// The bias is read once, on the first candle of the session, and holds for
// the rest of the New York day.
var int dayBias = 0
var bool biasRead = false
var bool tradedToday = false
if newDay
    dayBias := 0
    biasRead := false
    tradedToday := false
if not biasRead and barMinute >= sessionStart
    dayBias := biasNow
    biasRead := true
 
bool allowLong = switch biasMode
    "Two-candle bias" => dayBias == 1
    "Bias, mixed days both ways" => dayBias >= 0
    "No filter" => true
    => true
bool allowShort = switch biasMode
    "Two-candle bias" => dayBias == -1
    "Bias, mixed days both ways" => dayBias <= 0
    "No filter" => true
    => false
 
// ---------------------------------------------------------------------------
// 4. Levels
// ---------------------------------------------------------------------------
// A run is two or more candles of one color in a row. A bearish run that
// follows a bullish candle marks a level for longs at its highest body (the
// open of its highest candle). A bullish run after a bearish candle marks a
// level for shorts at its lowest body. The level becomes live when the run
// ends, and the range keeps growing until a candle closes through the level.
bool isBull = close > open
bool isBear = close < open
 
var int bearCount = 0
var float bearTop = na
var float bearHigh = na
var float bearLow = na
var bool bearAfterBull = false
var int bullCount = 0
var float bullBottom = na
var float bullHigh = na
var float bullLow = na
var bool bullAfterBear = false
 
// Live levels and their ranges.
var float upLevel = na
var float upRangeHigh = na
var float upRangeLow = na
var float dnLevel = na
var float dnRangeHigh = na
var float dnRangeLow = na
 
// A run that ended on the previous candle becomes the live level now, so the
// candle that ends a run can already be its breakout.
if not isBear and bearCount >= 2 and bearAfterBull
    upLevel := bearTop
    upRangeHigh := bearHigh
    upRangeLow := bearLow
if not isBull and bullCount >= 2 and bullAfterBear
    dnLevel := bullBottom
    dnRangeHigh := bullHigh
    dnRangeLow := bullLow
 
// ---------------------------------------------------------------------------
// 5. Breakout, wick and the waiting order
// ---------------------------------------------------------------------------
// One setup at a time. state: 0 idle, 1 breakout seen and waiting for the
// wick candle, 2 order working.
var int state = 0
var int setupDir = 0
var float level = na
var float trigger = na
var float risk = na
var int breakoutBar = na
bool flat = strategy.position_size == 0
int breakoutSignal = 0
 
// A fill shows up as one more trade, even when the trade opened and closed
// inside the same candle. It ends the setup and uses up the day's trade.
int tradeCount = strategy.closedtrades + strategy.opentrades
bool filledNow = tradeCount > nz(tradeCount[1])
float fillRisk = filledNow ? risk : na
if filledNow
    state := 0
    tradedToday := true
 
// An order can only wait while the window is open: an order sent on a
// candle that closes at the window's end would never be live. The candle
// that closes at the window's end cancels anything still waiting, so no
// order is live after it.
bool orderTimeLeft = barMinute >= sessionStart and barMinute + tfMinutes < windowEnd
bool windowOver = not orderTimeLeft
if state > 0 and flat and (newDay or windowOver)
    strategy.cancel_all()
    state := 0
 
// A close back through the level cancels the setup before the fill.
if state > 0 and flat and bar_index > breakoutBar
    if (setupDir == 1 and close < level) or (setupDir == -1 and close > level)
        strategy.cancel_all()
        state := 0
 
// Long breakout: a close above the live level. Any such close breaks the
// level; only a qualifying candle inside the window arms a setup.
float upHeight = upRangeHigh - upRangeLow
if not na(upLevel) and close > upLevel
    bool shape = isBull and high > close and (maxBreakoutPct == 0 or high - low <= maxBreakoutPct / 100 * upHeight)
    if shape and inWindow
        breakoutSignal := 1
    if shape and inWindow and allowLong and state == 0 and flat and not tradedToday
        state := 1
        setupDir := 1
        level := upLevel
        trigger := high
        risk := high - low
        breakoutBar := bar_index
    upLevel := na
else if not na(upLevel)
    upRangeHigh := math.max(upRangeHigh, high)
    upRangeLow := math.min(upRangeLow, low)
 
float dnHeight = dnRangeHigh - dnRangeLow
if not na(dnLevel) and close < dnLevel
    bool shape = isBear and low < close and (maxBreakoutPct == 0 or high - low <= maxBreakoutPct / 100 * dnHeight)
    if shape and inWindow
        breakoutSignal := -1
    if shape and inWindow and allowShort and state == 0 and flat and not tradedToday
        state := 1
        setupDir := -1
        level := dnLevel
        trigger := low
        risk := high - low
        breakoutBar := bar_index
    dnLevel := na
else if not na(dnLevel)
    dnRangeHigh := math.max(dnRangeHigh, high)
    dnRangeLow := math.min(dnRangeLow, low)
 
// Update the runs after the levels are read, so the current candle starts or
// extends the next run.
if isBear
    if bearCount == 0
        bearAfterBull := close[1] > open[1]
        bearTop := open
        bearHigh := high
        bearLow := low
    else
        bearTop := math.max(bearTop, open)
        bearHigh := math.max(bearHigh, high)
        bearLow := math.min(bearLow, low)
    bearCount += 1
else
    bearCount := 0
if isBull
    if bullCount == 0
        bullAfterBear := close[1] < open[1]
        bullBottom := open
        bullHigh := high
        bullLow := low
    else
        bullBottom := math.min(bullBottom, open)
        bullHigh := math.max(bullHigh, high)
        bullLow := math.min(bullLow, low)
    bullCount += 1
else
    bullCount := 0
 
// ---------------------------------------------------------------------------
// 6. Orders and exits
// ---------------------------------------------------------------------------
// 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
 
float targetR = exitMode == "Fixed 1R" ? 1.0 : 2.0
var float targetPx = na
 
// The wick candle: after the breakout candle, a wick toward the level of at
// least the minimum. On its close the order goes in at the breakout extreme.
// In coin flip mode a trade against the setup uses a limit order at the same
// price, so it fills on the same touch.
bool wickCandle = setupDir == 1 ? math.min(open, close) - low >= minWick : high - math.max(open, close) >= minWick
if state == 1 and flat and bar_index > breakoutBar and wickCandle and not windowOver
    bool goLong = coinSeed > 0 ? coinIsLong() : setupDir == 1
    float stopPrice = goLong ? trigger - risk : trigger + risk
    float targetPrice = goLong ? trigger + targetR * risk : trigger - targetR * risk
    targetPx := targetPrice
    if goLong
        if setupDir == 1
            strategy.entry("Long", strategy.long, stop=trigger)
        else
            strategy.entry("Long", strategy.long, limit=trigger)
        strategy.exit("Long exit", "Long", stop=stopPrice, limit=targetPrice)
    else
        if setupDir == -1
            strategy.entry("Short", strategy.short, stop=trigger)
        else
            strategy.entry("Short", strategy.short, limit=trigger)
        strategy.exit("Short exit", "Short", stop=stopPrice, limit=targetPrice)
    state := 2
 
// Break-even: once a candle closes after the price has reached +1R from the
// fill, the stop moves to the fill price. The target stays where it was set.
var bool movedToEntry = false
if flat
    movedToEntry := false
else if exitMode != "Fixed 1R" and not movedToEntry
    float entry = strategy.position_avg_price
    if strategy.position_size > 0 and high >= entry + risk
        strategy.exit("Long exit", "Long", stop=entry, limit=targetPx)
        movedToEntry := true
    else if strategy.position_size < 0 and low <= entry - risk
        strategy.exit("Short exit", "Short", stop=entry, limit=targetPx)
        movedToEntry := true
 
// The time exit: sent on the candle that closes at 16:00.
if not flat and (lastCandle or newDay)
    strategy.close_all(comment="Time exit")
 
// ---------------------------------------------------------------------------
// 7. Chart
// ---------------------------------------------------------------------------
plot(state == 2 ? trigger : na, "Order price", color=color.new(color.teal, 0), linewidth=2, style=plot.style_linebr)
plot(state > 0 ? level : na, "Level", color=color.new(color.orange, 0), linewidth=1, style=plot.style_linebr)
plotshape(breakoutSignal == 1, "Bullish breakout", shape.triangleup, location.belowbar, color.teal, size=size.tiny)
plotshape(breakoutSignal == -1, "Bearish breakout", shape.triangledown, location.abovebar, color.orange, size=size.tiny)
// Research values for the Data Window: the risk of the working setup or open
// trade, the day's bias (1, -1, 0), the bias the two candles show on this
// candle, and every qualifying breakout inside the window.
plot(filledNow ? fillRisk : not flat ? risk : na, "Planned risk", display=display.data_window)
plot(dayBias, "Day bias", display=display.data_window)
plot(biasNow, "Bias now", display=display.data_window)
plot(breakoutSignal, "Breakout", display=display.data_window)

← 返回列表