Opening Range Breakout

vinitpandya · study · 311 行 · 点赞 167 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vinitpandya
// @version=6
indicator("Opening Range Breakout", shorttitle="ORB v2025.05.20", overlay=true)
 
// Input parameters
openingRangeMinutes = input.int(30, "Opening Range Minutes", minval=5, maxval=240, step=5)
lookbackDays = input.int(20, "Lookback Days", minval=1, maxval=50)
rangeColor = input.color(color.new(color.blue, 80), "Range Color")
borderColor = input.color(color.blue, "Border Color")
midlineColor = input.color(color.purple, "Midline Color")
openingBoxColor = input.color(color.new(color.blue, 95), "Opening Range Highlight Color")
showMidline = input.bool(true, "Show Midline")
showLabels = input.bool(true, "Show Range Labels")
lineStyle = input.string("Dashed", "Line Style", options=["Solid", "Dashed", "Dotted"])
lineWidth = input.int(1, "Line Width", minval=1, maxval=4)
arrowDistance = input.float(0.5, "Arrow Distance (%)", minval=0.1, maxval=2.0, step=0.1)
 
// Convert line style selection to pine script line style
var line_style = lineStyle == "Solid" ? line.style_solid : lineStyle == "Dashed" ? line.style_dashed : line.style_dotted
 
// Market session parameters (9:30 AM EST)
marketOpenHour = 9
marketOpenMinute = 30
marketCloseHour = 16
chartTimeframe = timeframe.in_seconds() / 60  // Get actual chart timeframe in minutes
 
// Calculate number of bars needed for opening range and trading day
barsInOpeningRange = openingRangeMinutes / chartTimeframe
tradingDayMinutes = (marketCloseHour - marketOpenHour) * 60 - marketOpenMinute  // 6.5 hours minus 30 minutes
barsInTradingDay = tradingDayMinutes / chartTimeframe
 
// Type to store daily range data
type DailyRange
    float high
    float low
    float midpoint
    int startBar
    int endBar
    int dayEndBar
    bool rangeComplete
    line highLine
    line lowLine
    line midLine
    linefill rangeFill
    box openingBox
    label highLabel
    label lowLabel
    label midLabel
 
// Array to store daily ranges
var array<DailyRange> dailyRanges = array.new<DailyRange>()
 
// Function to check if current bar is market open (9:30 AM EST)
isMarketOpen() =>
    hour(time, "America/New_York") == marketOpenHour and 
     minute(time, "America/New_York") == marketOpenMinute
 
// Function to check if it's end of trading day (4:00 PM EST)
isMarketClose() =>
    hour(time, "America/New_York") == marketCloseHour and 
     minute(time, "America/New_York") == 0
 
// Function to check if it's a new trading day
isNewTradingDay() =>
    if barstate.isfirst
        true
    else
        currentDay = dayofmonth(time, "America/New_York")
        prevDay = dayofmonth(time[1], "America/New_York")
        currentDay != prevDay and hour(time, "America/New_York") >= marketOpenHour
 
// Function to get current day's range
getCurrentDayRange() =>
    if array.size(dailyRanges) > 0
        array.get(dailyRanges, array.size(dailyRanges) - 1)
    else
        na
 
// Function to clean old ranges beyond lookback period
cleanOldRanges() =>
    while array.size(dailyRanges) > lookbackDays
        oldRange = array.shift(dailyRanges)
        if not na(oldRange)
            // Clean up drawing objects safely
            if not na(oldRange.highLine)
                line.delete(oldRange.highLine)
            if not na(oldRange.lowLine)
                line.delete(oldRange.lowLine)
            if not na(oldRange.midLine)
                line.delete(oldRange.midLine)
            if not na(oldRange.rangeFill)
                linefill.delete(oldRange.rangeFill)
            if not na(oldRange.openingBox)
                box.delete(oldRange.openingBox)
            if not na(oldRange.highLabel)
                label.delete(oldRange.highLabel)
            if not na(oldRange.lowLabel)
                label.delete(oldRange.lowLabel)
            if not na(oldRange.midLabel)
                label.delete(oldRange.midLabel)
 
// Main logic
if barstate.isconfirmed and bar_index >= 1
    // Check if it's a new trading day
    if isNewTradingDay()
        cleanOldRanges()
        
        // Create new daily range
        newRange = DailyRange.new(
           na,           // high
           na,           // low
           na,           // midpoint
           bar_index,    // startBar
           na,           // endBar
           na,           // dayEndBar
           false,        // rangeComplete
           na,           // highLine
           na,           // lowLine
           na,           // midLine
           na,           // rangeFill
           na,           // openingBox
           na,           // highLabel
           na,           // lowLabel
           na            // midLabel
           )
        array.push(dailyRanges, newRange)
    
    // Update current day's range if within opening range period
    currentOpeningRange = getCurrentDayRange()
    if not na(currentOpeningRange) and not currentOpeningRange.rangeComplete
        barsFromOpen = bar_index - currentOpeningRange.startBar
        
        if barsFromOpen < barsInOpeningRange
            // Still within opening range period - update high/low
            if na(currentOpeningRange.high) or high > currentOpeningRange.high
                currentOpeningRange.high := high
            if na(currentOpeningRange.low) or low < currentOpeningRange.low
                currentOpeningRange.low := low
        else if barsFromOpen == barsInOpeningRange
            // Opening range period just completed
            currentOpeningRange.rangeComplete := true
            currentOpeningRange.endBar := bar_index
            currentOpeningRange.midpoint := (currentOpeningRange.high + currentOpeningRange.low) / 2
            
            // Draw range lines and fill
            if not na(currentOpeningRange.high) and not na(currentOpeningRange.low)
                // Determine end point for lines (will be updated when day ends)
                lineEndX = currentOpeningRange.startBar + barsInTradingDay
                
                currentOpeningRange.highLine := line.new(
                   x1=currentOpeningRange.startBar, 
                   y1=currentOpeningRange.high, 
                   x2=lineEndX, 
                   y2=currentOpeningRange.high, 
                   color=borderColor, 
                   style=line_style, 
                   width=lineWidth
                   )
                
                currentOpeningRange.lowLine := line.new(
                   x1=currentOpeningRange.startBar, 
                   y1=currentOpeningRange.low, 
                   x2=lineEndX, 
                   y2=currentOpeningRange.low, 
                   color=borderColor, 
                   style=line_style, 
                   width=lineWidth
                   )
                
                if showMidline and not na(currentOpeningRange.midpoint)
                    currentOpeningRange.midLine := line.new(
                       x1=currentOpeningRange.startBar, 
                       y1=currentOpeningRange.midpoint, 
                       x2=lineEndX, 
                       y2=currentOpeningRange.midpoint, 
                       color=midlineColor, 
                       style=line_style, 
                       width=lineWidth
                       )
                
                currentOpeningRange.rangeFill := linefill.new(
                   currentOpeningRange.highLine, 
                   currentOpeningRange.lowLine, 
                   color=rangeColor
                   )
                
                // Create highlighted box for the opening range period
                currentOpeningRange.openingBox := box.new(
                   left=currentOpeningRange.startBar, 
                   top=currentOpeningRange.high, 
                   right=currentOpeningRange.endBar, 
                   bottom=currentOpeningRange.low, 
                   bgcolor=color.new(openingBoxColor, 70), 
                   border_color=color.new(borderColor, 50), 
                   border_width=1
                   )
                
                // Add labels if enabled
                if showLabels and bar_index == last_bar_index
                    currentOpeningRange.highLabel := label.new(
                       bar_index + 5, 
                       currentOpeningRange.high, 
                       text="OR High: " + str.tostring(currentOpeningRange.high, format.mintick), 
                       color=color.new(color.blue, 100), 
                       textcolor=borderColor, 
                       style=label.style_none
                       )
                    
                    currentOpeningRange.lowLabel := label.new(
                       bar_index + 5, 
                       currentOpeningRange.low, 
                       text="OR Low: " + str.tostring(currentOpeningRange.low, format.mintick), 
                       color=color.new(color.blue, 100), 
                       textcolor=borderColor, 
                       style=label.style_none
                       )
                    
                    if showMidline and not na(currentOpeningRange.midpoint)
                        currentOpeningRange.midLabel := label.new(
                           bar_index + 5, 
                           currentOpeningRange.midpoint, 
                           text="OR Mid: " + str.tostring(currentOpeningRange.midpoint, format.mintick), 
                           color=color.new(color.purple, 100), 
                           textcolor=midlineColor, 
                           style=label.style_none
                           )
    
    // Check if it's end of trading day and update dayEndBar
    if isMarketClose()
        currentOpeningRange := getCurrentDayRange()
        if not na(currentOpeningRange) and currentOpeningRange.rangeComplete
            currentOpeningRange.dayEndBar := bar_index
            
            // Update the line endpoints to market close immediately
            if not na(currentOpeningRange.highLine)
                line.set_x2(currentOpeningRange.highLine, bar_index)
            if not na(currentOpeningRange.lowLine)
                line.set_x2(currentOpeningRange.lowLine, bar_index)
            if not na(currentOpeningRange.midLine)
                line.set_x2(currentOpeningRange.midLine, bar_index)
 
// Signal detection logic
var bool lastBarAboveRange = false
var bool lastBarBelowRange = false
 
// Initialize signal variables
bullishCloseBreakout = false
bullishWickRejection = false
bearishCloseBreakout = false
bearishWickRejection = false
 
// Check for signals on completed ranges
if array.size(dailyRanges) > 0
    currentOpeningRange = getCurrentDayRange()
    if not na(currentOpeningRange) and currentOpeningRange.rangeComplete and 
       not na(currentOpeningRange.high) and not na(currentOpeningRange.low)
        
        // Calculate arrow positions
        arrowDistancePrice = (high - low) * (arrowDistance / 100)
        
        // Close breakout signals
        closeAboveRange = close > currentOpeningRange.high
        closeBelowRange = close < currentOpeningRange.low
        closeInRange = close <= currentOpeningRange.high and close >= currentOpeningRange.low
        
        // Wick rejection signals
        wickAboveRange = high > currentOpeningRange.high and close <= currentOpeningRange.high
        wickBelowRange = low < currentOpeningRange.low and close >= currentOpeningRange.low
        
        // Bullish signals
        bullishCloseBreakout := closeAboveRange and not closeAboveRange[1]
        bullishWickRejection := wickBelowRange and not wickBelowRange[1]
        
        // Bearish signals
        bearishCloseBreakout := closeBelowRange and not closeBelowRange[1]
        bearishWickRejection := wickAboveRange and not wickAboveRange[1]
 
// Plot arrows using plotchar for better positioning
plotchar(bullishCloseBreakout, char="⬆", location=location.belowbar, size=size.tiny, title='Bullish Close Breakout', color=color.green)
plotchar(bullishWickRejection, char="⬆", location=location.belowbar, size=size.tiny, title='Bullish Wick Rejection', color=color.green)
plotchar(bearishCloseBreakout, char="⬇", location=location.abovebar, size=size.tiny, title='Bearish Close Breakout', color=color.red)
plotchar(bearishWickRejection, char="⬇", location=location.abovebar, size=size.tiny, title='Bearish Wick Rejection', color=color.red)
 
// Update range lines to extend to appropriate end point
if barstate.islast
    for i = 0 to array.size(dailyRanges) - 1
        openingRange = array.get(dailyRanges, i)
        if not na(openingRange) and openingRange.rangeComplete
            // Determine end point based on whether day has ended
            int endPoint = na
            if not na(openingRange.dayEndBar)
                // Day has ended, use the stored end bar
                endPoint := openingRange.dayEndBar
            else
                // Day hasn't ended yet, check if this is the current day's range
                if i == array.size(dailyRanges) - 1
                    // This is the current day's range, extend to current bar
                    endPoint := bar_index + math.round(10 / chartTimeframe)
                else
                    // This is a previous day without a proper end - calculate from start
                    endPoint := openingRange.startBar + math.round(barsInTradingDay)
            
            // Only update lines if they exist and endPoint is valid
            if not na(endPoint) and endPoint > openingRange.startBar
                if not na(openingRange.highLine)
                    line.set_x2(openingRange.highLine, endPoint)
                if not na(openingRange.lowLine)
                    line.set_x2(openingRange.lowLine, endPoint)
                if not na(openingRange.midLine)
                    line.set_x2(openingRange.midLine, endPoint)

← 返回列表