Opening Range Retest

BruzX · study · 181 行 · 点赞 823 · 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/
// © BruzX
 
//@version=6
indicator("Opening Range Retest", overlay = true)
 
// ╔───────────────────────────────────────────────────────────────────────────────────╗
// │                                                                                   │
// │ __/\\\\\\\\\\\\\______/\\\\\\\\\______/\\\________/\\\__/\\\\\\\\\\\\\\\_         │
// │  _\/\\\/////////\\\__/\\\///////\\\___\/\\\_______\/\\\_\////////////\\\__        │
// │   _\/\\\_______\/\\\_\/\\\_____\/\\\___\/\\\_______\/\\\___________/\\\/___       │
// │    _\/\\\\\\\\\\\\\\__\/\\\\\\\\\\\/____\/\\\_______\/\\\_________/\\\/_____      │
// │     _\/\\\/////////\\\_\/\\\//////\\\____\/\\\_______\/\\\_______/\\\/_______     │
// │      _\/\\\_______\/\\\_\/\\\____\//\\\___\/\\\_______\/\\\_____/\\\/_________    │
// │       _\/\\\_______\/\\\_\/\\\_____\//\\\__\//\\\______/\\\____/\\\/___________   │
// │        _\/\\\\\\\\\\\\\/__\/\\\______\//\\\__\///\\\\\\\\\/____/\\\\\\\\\\\\\\\_  │
// │         _\/////////////____\///________\///_____\/////////_____\///////////////__ │
// │                                                                                   │
// ╚───────────────────────────────────────────────────────────────────────────────────╝
 
// ---- Enums
//#region ---- Enums
 
//@enum                 Enum to hold to current retest state between bars
//@field inactive       No retest is primed to trigger
//@field primedLong     A top-side retest is primed to trigger
//@field priumedShort   A bottom-side retest is primed to trigger
enum PlayState
    inactive
    primedLong
    primedShort
    
//@enum                 Enum to specify the direction of the marker or alert that was triggered on the current bar
//@field none           Nothing triggered
//@field primedLong     A top-side marker/alert triggered
//@field priumedShort   A bottom-side marker/alert triggered
enum AlertTrigger
    none
    long
    short
 
//#endregion ---- Enums
 
// ---- UDTs
//#region ---- UDTs
//#endregion ---- UDTs
 
// ---- Constants
//#region
 
const bool DEBUG_MODE = false
 
//#endregion
 
// ---- Inputs
//#region
 
string barsOrMinutes = input.string("Bars", "Bars or minutes", [ "Bars", "Minutes"], tooltip = "Specifies whether the periods specifed below are bars or minutes. Fractional periods are always rounded up.")
int orPeriod = input.int(1, "Opening range period", minval = 1, tooltip = "Number of periods on the chart timeframe that are considered to form the opening range")
int restPeriod = input.int(3, "Resting period", minval = 1, tooltip = "Minimum number of periods that must close outside the opening range after it ends or since the last retest until the next retest can be triggered")
float retestTolerance = input.float(0, "Retest tolerance %", minval = 0, maxval = 50, step = 1, tooltip = "Specifies a retest tolerance as a percentage of the opening range. A retest marker or alert will be trigger if the price comes with this percentage of the opening range top or bottom.")
string alertActiveSession = input.session("0930-1000", "Alert active time range", tooltip = "Time range during which retest markers are shown and user-created retest alerts triggered. The indicator always starts looking for retests from the opening range and continues until the end of the regular market, but with this setting, you can limit the markers and alerts to a time range.")
bool extendBox = input.bool(true, "Extend opening range box", tooltip = "Continue to extend the opening range box even after the end of the alert active time range until end of regular market.")
color boxColour = input.color(color.rgb(178,235,242,80), "Opening range box colour")
color lineColour = input.color(color.blue, "Opening range line colour")
 
//#endregion
 
// ---- Functions
//#region
 
//@function             Utility function for debug logging.
//@param logPredicate   Predicate to allow control of which bar the debug function creates output. Setting to true will produce a message on every bar
//@param message        The string to log
//@returns              Nothing
//Dependency            Global const bool DEBUG_MODE controlling whether this produces any log output
debug(bool logPredicate, string message) =>
    if DEBUG_MODE and logPredicate
        log.info(message)
 
//#endregion
 
// ---- Logic
//#region
 
var bool inOR = false //In opening range?
var float orHigh = na // Opening range high
var float orLow = na // Opening range low
var float orRange = na // Opening range
var int biStart = na //bar_index of the resting counter start
var PlayState playState = na // Holds the retest state between bars
AlertTrigger alertTrigger = AlertTrigger.none //Direction of the alert/marker trigger on this bar
var box ORBox = na // Handle for the opening range box drawing
 
if timeframe.isdwm
    runtime.error("Indicator is not intended for a D/W/M timeframe")
 
// If periods are specified in minutes, convert to bars. 
if barsOrMinutes == "Minutes"        
    orPeriod := math.ceil(orPeriod * (timeframe.isseconds? 60 : 1) / timeframe.multiplier)
    restPeriod := math.ceil(orPeriod * (timeframe.isseconds? 60 : 1) / timeframe.multiplier)
 
// Set everything up on the first bar at the regular market open
if session.isfirstbar_regular    
    biStart := bar_index
    inOR := true
    playState := PlayState.inactive
 
// Functions need to run on every for consistent behaviour
float runningHigh = ta.highest(nz(ta.barssince(session.isfirstbar_regular or barstate.isfirst)) + 1)
float runningLow = ta.lowest(nz(ta.barssince(session.isfirstbar_regular or barstate.isfirst)) + 1)
 
if inOR
    // If in opening range time window...
    if bar_index == biStart + orPeriod - 1
        // If the bar is the last one in the opening range time window
 
        orHigh := runningHigh
        orLow := runningLow
        orRange := orHigh - orLow
 
        if barstate.isconfirmed
            ORBox := box.new(biStart, orHigh, bar_index, orLow, border_width = 0, bgcolor = boxColour)
            line.new(bar_index,orLow, bar_index, orHigh, color = lineColour, style = line.style_dashed)
 
        biStart := bar_index
        inOR := false
 
else // not inOR
    if session.ismarket
        // Updates the right side of the OR box during the market (box ends at start or post-market)
        if extendBox or not na(time(timeframe.period, alertActiveSession))
            ORBox.set_right(bar_index) 
    
    // If we're primed to trigger...
    if playState != PlayState.inactive and session.ismarket        
        // Check if we can trigger
        alertTrigger := switch playState
            // Check closes are on same side
            PlayState.primedLong => low <= orHigh + orRange * retestTolerance / 100 ? AlertTrigger.long : AlertTrigger.none
            PlayState.primedShort => high >= orLow - orRange * retestTolerance / 100 ? AlertTrigger.short : AlertTrigger.none
        
        // If we trigered...
        if alertTrigger != AlertTrigger.none
            // Reset variables
            playState := PlayState.inactive
            biStart := bar_index
    
    // Count reset conditions
    if   close >= orLow and close <= orHigh // Close inside OR...
      or close <= orLow and close[1] >= orHigh // Big red bar crossing OR
      or close >= orHigh and close[1] <= orLow // Big green bar crossing OR
        // Reset variables for next bar
        playState := PlayState.inactive
        biStart := bar_index - (close >= orHigh or close <= orLow ? 1 : 0) // If we crossed the OR with a big green/red candle, set biStart to the previous bar, since on this bar we closed outside the OR so it should count towards the resting period.
 
    // If we had "restPeriod" closes outside the OR...
    if bar_index == biStart + restPeriod
        // Prime for next bar
        playState := switch
            close > orHigh => PlayState.primedLong
            close < orLow => PlayState.primedShort    
 
//#endregion
 
// ---- Visuals
//#region
 
plotshape(not na(time(timeframe.period, alertActiveSession)) and alertTrigger == AlertTrigger.long ? orHigh : na, "High side retest", style = shape.labelup, location = location.belowbar, color = color.green, size=size.small)
plotshape(not na(time(timeframe.period, alertActiveSession)) and alertTrigger == AlertTrigger.short ? orLow : na, "Low side retest", style = shape.labeldown, location = location.abovebar, color = color.red, size=size.small)
 
//#endregion
 
// ---- Alerts
//#region ---- Alerts
 
alertcondition(not na(time(timeframe.period, alertActiveSession)) and alertTrigger == AlertTrigger.long, "Top-side opening range retest", "Top-side opening range retest on {{ticker}} at {{time}}")
alertcondition(not na(time(timeframe.period, alertActiveSession)) and alertTrigger == AlertTrigger.short, "Bottom-side opening range retest", "Bottom-side opening range retest on {{ticker}} at {{time}}")
alertcondition(not na(time(timeframe.period, alertActiveSession)) and alertTrigger != AlertTrigger.none, "All opening range retests", "Opening range retest on {{ticker}} at {{time}}")
 
//#endregion ---- Alerts

← 返回列表