Opening Range Breakout with Multi-Timeframe Liquidity]

Fx-Jithin · study · 740 行 · 点赞 222 · TradingView 原页

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

Pine Script

//@version=6
indicator("Opening Range Breakout with Multi-Timeframe Liquidity]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
//---------------------------------------------------------------------------------------------------------------------}
//inputs
//---------------------------------------------------------------------------------------------------------------------{
 
//Historical Display
showHist = input.bool(false, title = "Show Historical Data", group = "Historical Display", tooltip = "Displays All Data from Previous Sessions")
//Opening Range
orTF = input.timeframe("15", title = "Time Period", group = "Opening Range", tooltip = "Sets the Length of Time used for determining Opening Range.") 
//Custom Range
crTog = input.bool(false, title = "", inline = "Custom", group = "Custom Range")
crSesh = input.session("0930-0945", title = "", inline = "Custom", group = "Custom Range")
tz = input.string("UTC+4", title = "", group = "Custom Range", inline = "Custom", options = ["UTC-10", "UTC-8", "UTC-7", "UTC-6", "UTC-5", "UTC-4", "UTC-3", "UTC+0", "UTC+1", "UTC+2", "UTC+3", "UTC+3:30", "UTC+4", "UTC+5", "UTC+5:30", "UTC+5:45", "UTC+6","UTC+6:30", "UTC+7", "UTC+8", "UTC+9", "UTC+9:30", "UTC+10", "UTC+11", "UTC+12", "UTC+12:45", "UTC+13"])
 
//Trading Sessions - MAIN TOGGLE ADDED
enableTradingSessions = input.bool(true, "Enable Trading Sessions", group = "Trading Sessions", tooltip = "Master switch to enable/disable all trading session displays")
bool showSessionNames     = input.bool(true, "Show Session Names", group = "Trading Sessions")
bool showSessionOC        = input.bool(false, "Draw Session Open/Close Lines", group = "Trading Sessions")
bool showSessionHL        = input.bool(true, "Draw Session High/Low Lines", group = "Trading Sessions")
 
//Session High/Low Line Settings - MODIFIED to have individual session colors
sessionHLWidth = input.int(1, title = "High/Low Line Width", minval = 1, maxval = 10, group = "Session High/Low Settings")
 
const string TZ_TOOLTIP_TEXT = "The session's time zone, specified in either GMT notation (e.g., 'GMT-5') or as an IANA time zone database name (e.g., 'America/New_York')."
 + " We recommend the latter since it includes other time-related changes, such as daylight savings."
 
const string FIRST_SESSION_GROUP = "Tokyo Session"
showFirst         = input.bool(true, "Show Tokyo Session", group = FIRST_SESSION_GROUP)
firstSessionName  = input.string("Tokyo", "Displayed Name", group = FIRST_SESSION_GROUP)
firstSessionTime  = input.session("0400-1300", "Session Time", group = FIRST_SESSION_GROUP)
firstSessionTZ    = input.string("UTC+4", "Session Timezone", group = FIRST_SESSION_GROUP, tooltip = TZ_TOOLTIP_TEXT)
firstSessionColor = input.color(color.new(#2962FF, 95), "Session Color", group = FIRST_SESSION_GROUP)
tokyoHighColor = input.color(#2962FF, title = "Tokyo High Color", group = FIRST_SESSION_GROUP)
tokyoLowColor = input.color(#1E88E5, title = "Tokyo Low Color", group = FIRST_SESSION_GROUP)
 
const string SECOND_SESSION_GROUP = "London Session"
showSecond         = input.bool(true, "Show London Session", group = SECOND_SESSION_GROUP)
secondSessionName  = input.string("London", "Displayed Name", group = SECOND_SESSION_GROUP)
secondSessionTime  = input.session("1100-2000", "Session Time", group = SECOND_SESSION_GROUP)
secondSessionTZ    = input.string("UTC+4", "Session Timezone", group = SECOND_SESSION_GROUP, tooltip = TZ_TOOLTIP_TEXT)
secondSessionColor = input.color(color.new(#FF9800, 95), "Session Color", group = SECOND_SESSION_GROUP)
londonHighColor = input.color(#FF9800, title = "London High Color", group = SECOND_SESSION_GROUP)
londonLowColor = input.color(#F57C00, title = "London Low Color", group = SECOND_SESSION_GROUP)
 
const string THIRD_SESSION_GROUP = "New York Session"
showThird         = input.bool(true, "Show New York Session", group = THIRD_SESSION_GROUP)
thirdSessionName  = input.string("New York", "Displayed Name", group = THIRD_SESSION_GROUP)
thirdSessionTime  = input.session("1600-0100", "Session Time", group = THIRD_SESSION_GROUP)
thirdSessionTZ    = input.string("UTC+4", "Session Timezone", group = THIRD_SESSION_GROUP, tooltip = TZ_TOOLTIP_TEXT)
thirdSessionColor = input.color(color.new(#089981, 95), "Session Color", group = THIRD_SESSION_GROUP)
nyHighColor = input.color(#089981, title = "New York High Color", group = THIRD_SESSION_GROUP)
nyLowColor = input.color(#00695C, title = "New York Low Color", group = THIRD_SESSION_GROUP)
 
const string FOURTH_SESSION_GROUP = "Sydney Session"
showFourth         = input.bool(true, "Show Sydney Session", group = FOURTH_SESSION_GROUP)
fourthSessionName  = input.string("Sydney", "Displayed Name", group = FOURTH_SESSION_GROUP)
fourthSessionTime  = input.session("0100-1000", "Session Time", group = FOURTH_SESSION_GROUP)
fourthSessionTZ    = input.string("UTC+4", "Session Timezone", group = FOURTH_SESSION_GROUP, tooltip = TZ_TOOLTIP_TEXT)
fourthSessionColor = input.color(color.new(#9C27B0, 95), "Session Color", group = FOURTH_SESSION_GROUP)
sydneyHighColor = input.color(#9C27B0, title = "Sydney High Color", group = FOURTH_SESSION_GROUP)
sydneyLowColor = input.color(#7B1FA2, title = "Sydney Low Color", group = FOURTH_SESSION_GROUP)
 
//LIQUIDITY LEVELS SETTINGS
enableLiquidity = input.bool(true, title = "Enable Key Liquidity Levels", group = "Key Liquidity")
// Quick Reference Notes
majorForexNote = input.string("✅ EUR/USD, GBP/USD: Current settings optimal", title = "", group = "🎯 Quick Reference", options = ["✅ EUR/USD, GBP/USD: Current settings optimal"])
cryptoNote = input.string("🪙 BTC/ETH: Left=12, Right=4, Display=7", title = "", group = "🎯 Quick Reference", options = ["🪙 BTC/ETH: Left=12, Right=4, Display=7"])
goldNote = input.string("🥇 Gold: HTF=1D, Left=20", title = "", group = "🎯 Quick Reference", options = ["🥇 Gold: HTF=1D, Left=20"])
leftBars = input.int(15, title = "Left Bars", group = "Key Liquidity", tooltip = "Set the lookback point for what determines a Liquidity Level")
rightBars = input.int(5, title = "Right Bars", group = "Key Liquidity", tooltip = "Set the number of bars to confirm a Liquidity Level")
removeMitigated = input.bool(true, title = "Remove Mitigated", group = "Key Liquidity")
mitiOptions = input.string("Remove", title = "Mitigation Display", options=["Remove", "Show"], group = "Key Liquidity")
candleType = input.string("Wick", title = "Mitigation Type", options=["Close", "Wick"], group = "Key Liquidity")
displayLimit = input.int(7, title = "Display Limit", group = "Key Liquidity")
 
//Higher Timeframe Key Liquidity
enableHTFLiquidity = input.bool(true, title = "Enable HTF Key Liquidity", group = "Key Liquidity", inline="htf")
htfLiquidityTF = input.timeframe("240", title = "", group = "Key Liquidity", inline="htf", tooltip="Higher Timeframe for Major Key Liquidity Levels (240=4H, 1D, 1W)")
 
//Lower Timeframe Key Liquidity  
enableLTFLiquidity = input.bool(true, title = "Enable LTF Key Liquidity", group = "Key Liquidity", inline="ltf")
ltfLiquidityTF = input.timeframe("60", title = "", group = "Key Liquidity", inline="ltf", tooltip="Lower Timeframe for Precision Key Liquidity Levels (60=1H, 240=4H)")
 
//Key Liquidity Colors
//HTF Key Liquidity
htfHighLiquidityColor = input.color(#4c9650, "HTF High", group = "Key Liquidity Colors", inline = "htf")
htfLowLiquidityColor = input.color(#fd1c49, "HTF Low", group = "Key Liquidity Colors", inline = "htf")
 
//LTF Key Liquidity
ltfHighLiquidityColor = input.color(#2196F3, "LTF High", group = "Key Liquidity Colors", inline = "ltf")
ltfLowLiquidityColor = input.color(#FF9800, "LTF Low", group = "Key Liquidity Colors", inline = "ltf")
 
keyLiquidityLineWidth = input.int(1, title = "Line Width", group = "Key Liquidity Colors", minval = 1, maxval = 5)
liquidityExtension = input.string("Current", title = "Extension Options", options=["Short", "Current", "Max"], group = "Key Liquidity Colors", tooltip = "Choose how Key Liquidity Levels are extended on the chart")
liquidityExtMax = liquidityExtension=="Max" ? true : false
liquidityExtCurrent = liquidityExtension=="Current" ? true : false
 
//EMA Settings
showEMA = input.bool(true, title = "Show EMA", group = "EMA")
emaLength = input.int(20, title = "EMA Length", minval = 1, group = "EMA")
emaColor = input.color(#e91e63, title = "EMA Color", group = "EMA")
emaWidth = input.int(1, title = "EMA Width", minval = 1, maxval = 4, group = "EMA")
 
//Volume Analysis
showVolumeAnalysis = input.bool(true, title = "Enable Volume Analysis", group = "Volume Analysis")
volumeMALength = input.int(20, title = "Volume MA Length", minval = 5, group = "Volume Analysis")
volumeSpikeMultiplier = input.float(1.5, title = "Volume Spike Multiplier", minval = 1.0, step = 0.1, group = "Volume Analysis", tooltip = "Volume spike when current volume > MA * this multiplier")
 
//Multi-Timeframe Confirmation
enableMTF = input.bool(true, title = "Enable Multi-Timeframe", group = "Multi-Timeframe")
htfTimeframe1 = input.timeframe("60", title = "Higher TF 1 (Trend)", group = "Multi-Timeframe")
htfTimeframe2 = input.timeframe("240", title = "Higher TF 2 (Bias)", group = "Multi-Timeframe")
 
//Style
green = input.color(color.new(#089981,60), title = " Bull Color", group = "Style", inline = "Bull")
red = input.color(color.new(#f23645,60), title = "Bear Color", group = "Style", inline = "Bear")
greenFill = input.color(color.new(#089981,80), title = " Bull Fill Color", group = "Style", inline = "Bull")
redFill = input.color(color.new(#f23645,80), title = "Bear Fill Color", group = "Style", inline = "Bear")
orColor = input.color(#787b86, title = "   OR Levels Color", group = "Style", inline = "Range")
orFillColor = input.color(color.new(color.gray,60), title = "OR Highlight Color", group = "Style", inline = "Range")
fillMethod = input.string("Breakout Direction", title = "Fill Color Method", options = ["Session Comparison","Breakout Direction"], group = "Style", tooltip = "Session Comparison: Green when current OR mid > previous OR mid\nBreakout Direction: Green when price > ORH, Red when price < ORL")
txtSize = str.lower(input.string("Small", title = "Text Size", options = ["Tiny","Small","Normal","Large","Huge"], group = "Style"))
 
//ALERT SETTINGS
alertsEnabled = input.bool(true, title = "Enable Alerts", group = "Alert Settings")
alertORBreakout = input.bool(true, title = "ORB Breakout Alerts", group = "Alert Settings", tooltip = "Alert when price breaks above ORH or below ORL")
 
invis = color.rgb(0,0,0,100)
 
//---------------------------------------------------------------------------------------------------------------------}
//Error
//---------------------------------------------------------------------------------------------------------------------{
if timeframe.in_seconds(timeframe.period) >= timeframe.in_seconds("D")
    runtime.error("Timeframe is too High! Please Reduce Timeframe to be Less-Than 1 Day.")
 
if timeframe.isdwm
    runtime.error("This indicator can only be used on intraday timeframes.")
 
//Performance Optimization
 
max_bars_back(time, 500)
max_bars_back(high, 200)
max_bars_back(low, 200)
max_bars_back(close, 200)
max_bars_back(open, 200)
max_bars_back(volume, 200)
 
//---------------------------------------------------------------------------------------------------------------------}
//UDTs for Trading Sessions
//---------------------------------------------------------------------------------------------------------------------{
 
type SessionDisplay
    box   sessionBox
    label sessionLabel
    line  openLine
    line  closeLine
    line  highLine
    line  lowLine
    float sessionOpen
    float sessionHigh
    float sessionLow
 
type SessionInfo
    color  color
    string name
    string session
    string timezone
    color  highColor
    color  lowColor
    SessionDisplay active = na
 
//---------------------------------------------------------------------------------------------------------------------}
//Variables
//---------------------------------------------------------------------------------------------------------------------{
 
var bool or_sesh = false
var bool or_token = false
 
var float orh = na 
var float orl = na
var float prev_orm = na
 
var box or_bx = na
var int day_dir = 0
 
var line h_ln = na
var line l_ln = na
var line m_ln = na
var label h_lab = na
var label l_lab = na
var or_fill = linefill.new(na,na,na)
 
// Trading Sessions Variables
var array<SessionInfo> sessionInfos = na
 
// Alert Variables
var bool orbBullishBreakSent = false
var bool orbBearishBreakSent = false
 
// Key Liquidity Variables
// HTF Key Liquidity
var array<line> htfHighLiquidityArray = array.new_line()
var array<line> htfLowLiquidityArray = array.new_line()
var array<label> htfHighLiquidityLabels = array.new_label()
var array<label> htfLowLiquidityLabels = array.new_label()
 
// LTF Key Liquidity
var array<line> ltfHighLiquidityArray = array.new_line()
var array<line> ltfLowLiquidityArray = array.new_line()
var array<label> ltfHighLiquidityLabels = array.new_label()
var array<label> ltfLowLiquidityLabels = array.new_label()
 
//---------------------------------------------------------------------------------------------------------------------}
//Liquidity Functions
//---------------------------------------------------------------------------------------------------------------------{
 
// Helper function for timeframe multiplier
tfMulti(tf) =>
    ts = timeframe.in_seconds("")
    htfs = timeframe.in_seconds(tf)
    htfs/ts
 
// Helper function to convert timeframe to display text
tfToText(tf) =>
    switch tf
        "1" => "1m"
        "5" => "5m"
        "15" => "15m"
        "30" => "30m"
        "60" => "1H"
        "240" => "4H"
        "1D" => "1D"
        "1W" => "1W"
        "1M" => "1M"
        => tf
 
displayLimitLine(_array) =>
    if array.size(_array) > displayLimit/2
        a = array.shift(_array)
        line.delete(a)
 
displayLimitLabel(_array) =>
    if array.size(_array) > displayLimit/2
        a = array.shift(_array)
        label.delete(a)
 
removeMitigatedLines(_array, _hl) =>
    m = false
    if array.size(_array) > 0 and removeMitigated        
        for i = array.size(_array) - 1 to 0 by 1
            l = array.get(_array, i)
            hh = candleType == "Close" ? close[1] : high
            ll = candleType == "Close" ? close[1] : low
            if _hl == "High" and hh > line.get_y1(l)
                array.remove(_array, i)
                if mitiOptions == "Show"
                    line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l), xloc=xloc.bar_time, color = color.new(htfHighLiquidityColor, 70))
                line.delete(l)
                m := true
            if _hl == "Low" and ll < line.get_y1(l)
                array.remove(_array, i)
                if mitiOptions == "Show"
                    line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l), xloc=xloc.bar_time, color = color.new(htfLowLiquidityColor, 70))
                line.delete(l) 
                m := true  
    displayLimitLine(_array) 
    m
 
removeMitigatedLinesWithLabels(_array, _arrayLabels, _hl, _isHTF = true) =>
    m = false
    if array.size(_array) > 0 and removeMitigated        
        for i = array.size(_array) - 1 to 0 by 1
            l = array.get(_array, i)
            hh = candleType == "Close" ? close[1] : high
            ll = candleType == "Close" ? close[1] : low
            if _hl == "High" and hh > line.get_y1(l)
                array.remove(_array, i)
                // Remove corresponding label
                if array.size(_arrayLabels) > i
                    labelToDelete = array.get(_arrayLabels, i)
                    array.remove(_arrayLabels, i)
                    label.delete(labelToDelete)
                if mitiOptions == "Show"
                    colorToUse = _isHTF ? htfHighLiquidityColor : ltfHighLiquidityColor
                    line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l), xloc=xloc.bar_time, color = color.new(colorToUse, 70))
                line.delete(l)
                m := true
            if _hl == "Low" and ll < line.get_y1(l)
                array.remove(_array, i)
                // Remove corresponding label
                if array.size(_arrayLabels) > i
                    labelToDelete = array.get(_arrayLabels, i)
                    array.remove(_arrayLabels, i)
                    label.delete(labelToDelete)
                if mitiOptions == "Show"
                    colorToUse = _isHTF ? htfLowLiquidityColor : ltfLowLiquidityColor
                    line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l), xloc=xloc.bar_time, color = color.new(colorToUse, 70))
                line.delete(l) 
                m := true  
    displayLimitLine(_array) 
    displayLimitLabel(_arrayLabels)
    m
 
extendLineToCurrent(lineArray) =>
    if array.size(lineArray) > 0
        for i = array.size(lineArray) - 1 to 0 by 1
            l = array.get(lineArray, i)
            timeExt = time + ((time[1]-time[2])*20)
            line.set_x2(l, timeExt)
 
extendBoxToCurrent(boxArray) =>
    if array.size(boxArray) > 0
        for i = array.size(boxArray) - 1 to 0 by 1
            b = array.get(boxArray, i)
            timeExt = time + ((time[1]-time[2])*20)
            box.set_right(b, timeExt)
 
//---------------------------------------------------------------------------------------------------------------------}
//Trading Sessions Functions
//---------------------------------------------------------------------------------------------------------------------{
 
method setName(SessionDisplay this, string name) =>
    sessionLabel = this.sessionLabel
    sessionBox = this.sessionBox
    boxText = array.new<string>()
    if showSessionNames
        boxText.push(name)
    
    sessionLabel.set_y(sessionBox.get_bottom())
    sessionLabel.set_text(array.join(boxText, "\n"))
 
method createSessionDisplay(SessionInfo this) =>
    boxColor = this.color
    opaqueColor = color.new(boxColor, 0)
    dis = SessionDisplay.new(
      sessionBox = box.new(bar_index, high, bar_index, low, bgcolor = boxColor, border_color = na),
      sessionLabel = label.new(bar_index, low, "", style = label.style_label_upper_left, textalign = text.align_left, textcolor = opaqueColor, color = color(na)),
      openLine   = showSessionOC ? line.new(bar_index, open, bar_index, open, color = opaqueColor, style = line.style_dashed, width = 1) : na,
      closeLine  = showSessionOC ? line.new(bar_index, close, bar_index, close, color = opaqueColor, style = line.style_dashed, width = 1) : na,
      highLine   = showSessionHL ? line.new(bar_index, high, bar_index, high, color = this.highColor, style = line.style_solid, width = sessionHLWidth) : na,
      lowLine    = showSessionHL ? line.new(bar_index, low, bar_index, low, color = this.lowColor, style = line.style_solid, width = sessionHLWidth) : na,
      sessionOpen = open,
      sessionHigh = high,
      sessionLow = low
      )
    if showSessionOC
        linefill.new(dis.openLine, dis.closeLine, boxColor)
    dis.setName(this.name)
    this.active := dis
    
method updateSessionDisplay(SessionInfo this) =>
    sessionDisp = this.active
    sessionBox = sessionDisp.sessionBox
    openLine = sessionDisp.openLine
    closeLine = sessionDisp.closeLine
    highLine = sessionDisp.highLine
    lowLine = sessionDisp.lowLine
    
    sessionDisp.sessionHigh := math.max(sessionDisp.sessionHigh, high)
    sessionDisp.sessionLow := math.min(sessionDisp.sessionLow, low)
 
    sessionBox.set_top(math.max(sessionBox.get_top(), high))
    sessionBox.set_bottom(math.min(sessionBox.get_bottom(), low))
    sessionBox.set_right(bar_index)
    sessionDisp.setName(this.name)
 
    if showSessionOC
        openLine.set_x2(bar_index)
        closeLine.set_x2(bar_index)
        closeLine.set_y1(close)
        closeLine.set_y2(close)
 
    if showSessionHL
        highLine.set_x2(bar_index)
        lowLine.set_x2(bar_index)
        highLine.set_y1(sessionDisp.sessionHigh)
        highLine.set_y2(sessionDisp.sessionHigh)
        lowLine.set_y1(sessionDisp.sessionLow)
        lowLine.set_y2(sessionDisp.sessionLow)
 
    sessionDisp
 
method deleteSessionDisplay(SessionDisplay this) =>
    if not na(this)
        if not na(this.sessionBox)
            this.sessionBox.delete()
        if not na(this.sessionLabel)
            this.sessionLabel.delete()
        if not na(this.openLine)
            this.openLine.delete()
        if not na(this.closeLine)
            this.closeLine.delete()
        if not na(this.highLine)
            this.highLine.delete()
        if not na(this.lowLine)
            this.lowLine.delete()
 
method update(SessionInfo this) =>
	bool isChange = timeframe.change("1D")
    bool inSession = not na(time("", this.session, this.timezone))
    
    if isChange and not na(this.active)
        this.active.deleteSessionDisplay()
        this.active := na
    
    if inSession
        if na(this.active)
            this.createSessionDisplay()
        else 
            this.updateSessionDisplay()
    else if not na(this.active) and not inSession
        this.active.deleteSessionDisplay()
        this.active := na
 
getSessionInfos()=>
    sessionInfosArray = array.new<SessionInfo>()
    if enableTradingSessions
        if showFirst
            sessionInfosArray.push(SessionInfo.new(firstSessionColor, firstSessionName, firstSessionTime, firstSessionTZ, tokyoHighColor, tokyoLowColor))
        if showSecond
            sessionInfosArray.push(SessionInfo.new(secondSessionColor, secondSessionName, secondSessionTime, secondSessionTZ, londonHighColor, londonLowColor))
        if showThird
            sessionInfosArray.push(SessionInfo.new(thirdSessionColor, thirdSessionName, thirdSessionTime, thirdSessionTZ, nyHighColor, nyLowColor))
        if showFourth
            sessionInfosArray.push(SessionInfo.new(fourthSessionColor, fourthSessionName, fourthSessionTime, fourthSessionTZ, sydneyHighColor, sydneyLowColor))
    sessionInfosArray
 
//---------------------------------------------------------------------------------------------------------------------}
//Calculations
//---------------------------------------------------------------------------------------------------------------------{
 
orm = math.avg(orh,orl)
orw = math.abs(orh-orl)    
 
// EMA Calculation
ema = ta.ema(close, emaLength)
 
// Volume Analysis
volumeMA = showVolumeAnalysis ? ta.sma(volume, volumeMALength) : na
volumeSpike = showVolumeAnalysis ? volume > volumeMA * volumeSpikeMultiplier : false
highVolume = showVolumeAnalysis ? volume > ta.percentile_linear_interpolation(volume, 50, 80) : false
volumeStrength = showVolumeAnalysis ? math.round((volume / volumeMA) * 100) : 0
 
// Multi-Timeframe Analysis
htf1_ema = enableMTF ? request.security(syminfo.tickerid, htfTimeframe1, ema, lookahead=barmerge.lookahead_off) : na
htf2_trend = enableMTF ? request.security(syminfo.tickerid, htfTimeframe2, ta.ema(close, 50), lookahead=barmerge.lookahead_off) : na
htf2_close = enableMTF ? request.security(syminfo.tickerid, htfTimeframe2, close, lookahead=barmerge.lookahead_off) : na
 
// MTF Trend Bias
bullishBias = enableMTF ? (htf2_close > htf2_trend and ema > htf1_ema) : true
bearishBias = enableMTF ? (htf2_close < htf2_trend and ema < htf1_ema) : true
neutralBias = enableMTF ? (not bullishBias and not bearishBias) : false
 
// EMA Stack Analysis
emaStack = enableMTF ? (ema > htf1_ema ? 1 : ema < htf1_ema ? -1 : 0) : 0
 
// Key Liquidity Pivot Calculations
// HTF Key Liquidity
var htfTime = 0
var htfOpen = 0.0
var htfHigh = 0.0
var htfLow = 0.0
var htfClose = 0.0
if enableHTFLiquidity
    [_htfTime, _htfOpen, _htfHigh, _htfLow, _htfClose] = request.security(syminfo.tickerid, htfLiquidityTF, [time, open, high, low, close], lookahead=barmerge.lookahead_off)
    htfTime := _htfTime
    htfOpen := _htfOpen  
    htfHigh := _htfHigh
    htfLow := _htfLow
    htfClose := _htfClose
 
pivotHighHTF = enableHTFLiquidity ? ta.pivothigh(htfHigh, leftBars*tfMulti(htfLiquidityTF), rightBars+tfMulti(htfLiquidityTF)) : na
pivotLowHTF = enableHTFLiquidity ? ta.pivotlow(htfLow, leftBars*tfMulti(htfLiquidityTF), rightBars+tfMulti(htfLiquidityTF)) : na
 
// LTF Key Liquidity  
var ltfTime = 0
var ltfOpen = 0.0
var ltfHigh = 0.0
var ltfLow = 0.0
var ltfClose = 0.0
if enableLTFLiquidity
    [_ltfTime, _ltfOpen, _ltfHigh, _ltfLow, _ltfClose] = request.security(syminfo.tickerid, ltfLiquidityTF, [time, open, high, low, close], lookahead=barmerge.lookahead_off)
    ltfTime := _ltfTime
    ltfOpen := _ltfOpen
    ltfHigh := _ltfHigh  
    ltfLow := _ltfLow
    ltfClose := _ltfClose
 
pivotHighLTF = enableLTFLiquidity ? ta.pivothigh(ltfHigh, leftBars*tfMulti(ltfLiquidityTF), rightBars+tfMulti(ltfLiquidityTF)) : na
pivotLowLTF = enableLTFLiquidity ? ta.pivotlow(ltfLow, leftBars*tfMulti(ltfLiquidityTF), rightBars+tfMulti(ltfLiquidityTF)) : na
 
// Extract all ta.* function calls for consistency
orbBullishBreak = ta.crossover(close, orh)
orbBearishBreak = ta.crossunder(close, orl)
emaCrossUp = ta.crossover(close, ema)
emaCrossDown = ta.crossunder(close, ema)
 
//Establishing When the OR Sesssion is
new_tf = timeframe.change(orTF)
if crTog
    or_sesh := not na(time(timeframe.period, crSesh, tz))
else 
    if session.isfirstbar
        or_sesh := true
    else if not session.isfirstbar and new_tf
        or_sesh := false
 
or_start = or_sesh and not or_sesh[1]
or_end = or_sesh[1] and not or_sesh
 
//On Start of OR Session
if or_start
    if showHist == false
        or_bx.delete()
        h_ln.delete()
        l_ln.delete()
        m_ln.delete()
        or_fill.delete()
 
    h_lab.delete()
    l_lab.delete()
 
    orh := high
    orl := low
    prev_orm := orm[1]
 
    or_bx := box.new(bar_index,high,bar_index,low, bgcolor = orFillColor, border_width = 0)
 
    or_token := false
    
    // Reset alert flags
    orbBullishBreakSent := false
    orbBearishBreakSent := false
 
// Initialize Trading Sessions
if na(sessionInfos) and enableTradingSessions
    sessionInfos := getSessionInfos()
 
//Running while OR Session is Live
if or_sesh
    if high > orh
        orh := high
    if low < orl
        orl := low
    or_bx.set_top(orh)
    or_bx.set_bottom(orl)
    or_bx.set_right(bar_index)
    if orh != orl
        or_token := true
        
//On End of OR Session
if or_end and or_token
    h_ln := line.new(bar_index,orh,bar_index,orh, color = orColor)
    l_ln := line.new(bar_index,orl,bar_index,orl, color = orColor)
    m_ln := line.new(bar_index,orm,bar_index,orm, style = line.style_dashed, color = orColor)
    h_lab := label.new(bar_index,orh,text = "ORH",tooltip = str.tostring(orh,format.mintick), style = label.style_label_left, color = invis, textcolor = color.new(orColor,0), size = txtSize)
    l_lab := label.new(bar_index,orl,text = "ORL",tooltip = str.tostring(orl,format.mintick), style = label.style_label_left, color = invis, textcolor = color.new(orColor,0), size = txtSize)
    
    // Calculate day direction for session comparison method
    day_dir := orm > prev_orm ? 1 : orm < prev_orm ? -1 : 0
    
    // Create fill with initial color based on selected method
    initial_fill_color = fillMethod == "Session Comparison" ? 
     (day_dir == 1 ? greenFill : day_dir == -1 ? redFill : orFillColor) : orFillColor
    or_fill := linefill.new(h_ln,l_ln, initial_fill_color)
 
//Running outside of OR Session
if not or_sesh and or_token
    h_ln.set_x2(bar_index)
    l_ln.set_x2(bar_index)
    m_ln.set_x2(bar_index)
    h_lab.set_x(bar_index)
    l_lab.set_x(bar_index)
 
//Fill Color Logic Based on Selected Method
if not or_sesh and or_token and not na(or_fill)
    if fillMethod == "Breakout Direction"
        if close > orh
            or_fill.set_color(greenFill)
        else if close < orl
            or_fill.set_color(redFill)
        else
            or_fill.set_color(orFillColor)
 
//---------------------------------------------------------------------------------------------------------------------}
//Key Liquidity Level Processing
//---------------------------------------------------------------------------------------------------------------------{
 
// HTF Key Liquidity Levels (Higher Timeframe - Major Levels)
if enableLiquidity and enableHTFLiquidity
    dis = rightBars+tfMulti(htfLiquidityTF)
    if not na(pivotHighHTF)
        newLine = line.new(htfTime[dis],htfHigh[dis],htfTime[+1],htfHigh[dis],color = htfHighLiquidityColor, xloc=xloc.bar_time, extend=liquidityExtMax?extend.right:extend.none, width = keyLiquidityLineWidth)
        array.push(htfHighLiquidityArray, newLine)
        // Add timeframe text label like ORB style
        newLabel = label.new(htfTime[+1], htfHigh[dis], text = tfToText(htfLiquidityTF), tooltip = str.tostring(htfHigh[dis], format.mintick), style = label.style_label_left, color = invis, textcolor = color.new(htfHighLiquidityColor, 0), size = txtSize, xloc=xloc.bar_time)
        array.push(htfHighLiquidityLabels, newLabel)
            
    if not na(pivotLowHTF)
        newLine = line.new(htfTime[dis],htfLow[dis],htfTime[+1],htfLow[dis],color = htfLowLiquidityColor, xloc=xloc.bar_time, extend=liquidityExtMax?extend.right:extend.none, width = keyLiquidityLineWidth)
        array.push(htfLowLiquidityArray, newLine)
        // Add timeframe text label like ORB style
        newLabel = label.new(htfTime[+1], htfLow[dis], text = tfToText(htfLiquidityTF), tooltip = str.tostring(htfLow[dis], format.mintick), style = label.style_label_left, color = invis, textcolor = color.new(htfLowLiquidityColor, 0), size = txtSize, xloc=xloc.bar_time)
        array.push(htfLowLiquidityLabels, newLabel)
 
    // Process HTF liquidity mitigation
    htfHighLineAlert = removeMitigatedLinesWithLabels(htfHighLiquidityArray, htfHighLiquidityLabels, "High", true)
    htfLowLineAlert = removeMitigatedLinesWithLabels(htfLowLiquidityArray, htfLowLiquidityLabels, "Low", true)
    
    // Extend HTF liquidity lines and update label positions
    if liquidityExtCurrent
        extendLineToCurrent(htfHighLiquidityArray)
        extendLineToCurrent(htfLowLiquidityArray)
        // Update label positions to end of extended lines
        if array.size(htfHighLiquidityLabels) > 0
            for i = 0 to array.size(htfHighLiquidityLabels) - 1
                lbl = array.get(htfHighLiquidityLabels, i)
                if not na(lbl)
                    timeExt = time + ((time[1]-time[2])*20)
                    label.set_x(lbl, timeExt)
        if array.size(htfLowLiquidityLabels) > 0
            for i = 0 to array.size(htfLowLiquidityLabels) - 1
                lbl = array.get(htfLowLiquidityLabels, i)
                if not na(lbl)
                    timeExt = time + ((time[1]-time[2])*20)
                    label.set_x(lbl, timeExt)
 
// LTF Key Liquidity Levels (Lower Timeframe - Precision Levels)
if enableLiquidity and enableLTFLiquidity
    dis = rightBars+tfMulti(ltfLiquidityTF)
    if not na(pivotHighLTF)
        newLine = line.new(ltfTime[dis],ltfHigh[dis],ltfTime[+1],ltfHigh[dis],color = ltfHighLiquidityColor, xloc=xloc.bar_time, extend=liquidityExtMax?extend.right:extend.none, width = keyLiquidityLineWidth)
        array.push(ltfHighLiquidityArray, newLine)
        // Add timeframe text label like ORB style
        newLabel = label.new(ltfTime[+1], ltfHigh[dis], text = tfToText(ltfLiquidityTF), tooltip = str.tostring(ltfHigh[dis], format.mintick), style = label.style_label_left, color = invis, textcolor = color.new(ltfHighLiquidityColor, 0), size = txtSize, xloc=xloc.bar_time)
        array.push(ltfHighLiquidityLabels, newLabel)
            
    if not na(pivotLowLTF)
        newLine = line.new(ltfTime[dis],ltfLow[dis],ltfTime[+1],ltfLow[dis],color = ltfLowLiquidityColor, xloc=xloc.bar_time, extend=liquidityExtMax?extend.right:extend.none, width = keyLiquidityLineWidth)
        array.push(ltfLowLiquidityArray, newLine)
        // Add timeframe text label like ORB style
        newLabel = label.new(ltfTime[+1], ltfLow[dis], text = tfToText(ltfLiquidityTF), tooltip = str.tostring(ltfLow[dis], format.mintick), style = label.style_label_left, color = invis, textcolor = color.new(ltfLowLiquidityColor, 0), size = txtSize, xloc=xloc.bar_time)
        array.push(ltfLowLiquidityLabels, newLabel)
 
    // Process LTF liquidity mitigation
    ltfHighLineAlert = removeMitigatedLinesWithLabels(ltfHighLiquidityArray, ltfHighLiquidityLabels, "High", false)
    ltfLowLineAlert = removeMitigatedLinesWithLabels(ltfLowLiquidityArray, ltfLowLiquidityLabels, "Low", false)
    
    // Extend LTF liquidity lines and update label positions
    if liquidityExtCurrent
        extendLineToCurrent(ltfHighLiquidityArray)
        extendLineToCurrent(ltfLowLiquidityArray)
        // Update label positions to end of extended lines
        if array.size(ltfHighLiquidityLabels) > 0
            for i = 0 to array.size(ltfHighLiquidityLabels) - 1
                lbl = array.get(ltfHighLiquidityLabels, i)
                if not na(lbl)
                    timeExt = time + ((time[1]-time[2])*20)
                    label.set_x(lbl, timeExt)
        if array.size(ltfLowLiquidityLabels) > 0
            for i = 0 to array.size(ltfLowLiquidityLabels) - 1
                lbl = array.get(ltfLowLiquidityLabels, i)
                if not na(lbl)
                    timeExt = time + ((time[1]-time[2])*20)
                    label.set_x(lbl, timeExt)
 
//---------------------------------------------------------------------------------------------------------------------}
//Alert Logic - ORB and Liquidity Breakouts
//---------------------------------------------------------------------------------------------------------------------{
 
if alertsEnabled and not or_sesh and or_token
 
    // ORB BULLISH BREAKOUT
    if alertORBreakout and orbBullishBreak and not orbBullishBreakSent
        volumeConfirmed = not showVolumeAnalysis or volume > volumeMA * 1.2
        mtfConfirmed = not enableMTF or bullishBias or neutralBias
        
        alertType = volumeConfirmed and mtfConfirmed ? "HIGH QUALITY" : "STANDARD"
        alertIcon = volumeConfirmed and mtfConfirmed ? "🚀⭐" : "🚀"
        
        alertMessage = alertIcon + " " + alertType + " BULLISH ORB BREAKOUT!\n"
        alertMessage := alertMessage + "Price broke above ORH: " + str.tostring(orh, format.mintick) + "\n"
        alertMessage := alertMessage + "Current Price: " + str.tostring(close, format.mintick) + "\n"
        
        if showVolumeAnalysis
            alertMessage := alertMessage + "Volume: " + str.tostring(volumeStrength) + "% of avg " + (volumeConfirmed ? "✅" : "❌") + "\n"
        if enableMTF
            mtfStatus = bullishBias ? "Bullish" : bearishBias ? "Bearish" : "Neutral"
            alertMessage := alertMessage + "MTF Bias: " + mtfStatus + " " + (mtfConfirmed ? "✅" : "❌") + "\n"
        
        alertMessage := alertMessage + "Action: " + (volumeConfirmed and mtfConfirmed ? "Strong bullish momentum" : "Standard breakout")
        
        alert(alertMessage, alert.freq_once_per_bar)
        orbBullishBreakSent := true
 
    // ORB BEARISH BREAKOUT  
    if alertORBreakout and orbBearishBreak and not orbBearishBreakSent
        volumeConfirmed = not showVolumeAnalysis or volume > volumeMA * 1.2
        mtfConfirmed = not enableMTF or bearishBias or neutralBias
        
        alertType = volumeConfirmed and mtfConfirmed ? "HIGH QUALITY" : "STANDARD"
        alertIcon = volumeConfirmed and mtfConfirmed ? "🔻⭐" : "🔻"
        
        alertMessage = alertIcon + " " + alertType + " BEARISH ORB BREAKOUT!\n"
        alertMessage := alertMessage + "Price broke below ORL: " + str.tostring(orl, format.mintick) + "\n"
        alertMessage := alertMessage + "Current Price: " + str.tostring(close, format.mintick) + "\n"
        
        if showVolumeAnalysis
            alertMessage := alertMessage + "Volume: " + str.tostring(volumeStrength) + "% of avg " + (volumeConfirmed ? "✅" : "❌") + "\n"
        if enableMTF
            mtfStatus = bullishBias ? "Bullish" : bearishBias ? "Bearish" : "Neutral"
            alertMessage := alertMessage + "MTF Bias: " + mtfStatus + " " + (mtfConfirmed ? "✅" : "❌") + "\n"
        
        alertMessage := alertMessage + "Action: " + (volumeConfirmed and mtfConfirmed ? "Strong bearish momentum" : "Standard breakdown")
        
        alert(alertMessage, alert.freq_once_per_bar)
        orbBearishBreakSent := true
 
//---------------------------------------------------------------------------------------------------------------------}
//Trading Sessions Processing
//---------------------------------------------------------------------------------------------------------------------{
 
if enableTradingSessions and not na(sessionInfos)
    for info in sessionInfos
        info.update()
 
//---------------------------------------------------------------------------------------------------------------------}
//Display
//---------------------------------------------------------------------------------------------------------------------{
 
// EMA Plot
plot(showEMA ? ema : na, title = "EMA", color = emaColor, linewidth = emaWidth)
 
// Liquidity Alert Conditions for TradingView Alert Creation (Visual Only)
alertcondition(orbBullishBreak, "ORB Bullish Breakout", "Price broke above ORH!")
alertcondition(orbBearishBreak, "ORB Bearish Breakout", "Price broke below ORL!")
 
//---------------------------------------------------------------------------------------------------------------------}

← 返回列表