本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChaosTrader63
//@version=6
//====================================================================
// Sigma Analytics ORB Shield v1 R1.8 (short title SA.ORB.Shield)
// Built on "[CT] ORB Suite" by ChaosTrader63 (MPL 2.0; original notice
// above kept). Playbook module and modifications by Hanzo321
// (Sigma Analytics). Suite edits are marked "// SA R1.x:"; the playbook
// module is appended at the end (all names prefixed pb / PB_ / f_pb).
//
// Notes:
// - SPY, 5-minute chart, regular hours 8:30-15:00 CT. OR 15 min, IB 1 hour.
// - Signals evaluate on closed candles only; a label is a candidate,
// not an order.
// - Educational use only; not financial advice.
//
// Major upgrades over the original ORB Suite:
// 1) Chicago session default and a regular-hours fix (new session and
// session end are now detected on RTH charts).
// 2) Context score 0-3: rising/falling 20 EMA, previous session close
// (PSC) side, session VWAP side.
// 3) Entry 1 (breakout close, 8:45-9:30 CT): close beyond the OR + VWAP
// side + volume >= 20-bar average + context 3/3. Stop = OR midpoint
// or a close back inside; Target 1 = 1R. A failed breakout gets a
// pink x (hover for the reason).
// 4) Entry 2 (breach and retreat, paper tracking): 38% touch, 62%
// close-stop, 86% hard stop, Target 1 = the breached edge.
// 5) Rule-based exits and daily state: stop, Target 1, close-stop,
// 45-min time stop, flat by 2:55 PM CT, result in R; one trade a day.
// 6) LONG (CALL) / SHORT (PUT) labels with the entry price, drawn in
// front of the candles; overlapping Suite level labels staggered.
// 7) Two panels: Session (Full / Compact) and Trade plan (call / put
// plan, 1R cap = capital x risk %, 1R at an assumed delta, max entry).
// 8) Manual daily levels at the top of the settings: max pain, OI call /
// put, dark pool 1-3 and a "Levels as of" check.
// 9) Alerts: price-filled alert() messages with CT times, plus
// webhook-ready JSON alert conditions.
//
// R1.8 - 26 Oct 2026. Publish-ready build: header and notes condensed,
// title "Sigma Analytics ORB Shield", private references
// removed from comments and tooltips. No logic or input changes.
// Revision history R1-R1.7 is kept in the author's archive.
// Cosmetic (same revision): all lines 1 px (OR, IB, TP, stop / T1,
// session VWAP); entry labels 65% transparent, PSC tag 85% (Suite level
// labels stay at 75%). Name: Sigma Analytics ORB Shield ("Shield" =
// the rule filters and risk limits; it does not prevent losses).
//====================================================================
// SA R1: title (was "[CT] ORB Suite") and shorttitle added; R1.8 title "Sigma Analytics ORB Shield"
// SA R1.2: behind_chart=false (default true) - drawings in front of the candles
indicator("Sigma Analytics ORB Shield", shorttitle="SA.ORB.Shield",
overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=200, behind_chart=false)
//====================================================================
// DAILY MANUAL INPUTS (Sigma Analytics R1.4) - declared first so they sit at the
// TOP of the settings dialog. Update every morning before 8:30 CT (pre-trade hygiene).
//====================================================================
// R1.4 daily levels - type these each morning (pre-trade hygiene). 0 = off.
pbGrpDaily = "0 · Daily levels (update before 8:30 CT)"
pbLvlDate = input.time(timestamp("2026-10-26T00:00:00"), "Levels as of (date)", group=pbGrpDaily, tooltip="Set to today's date each time you update the levels. The panel shows UPDATE when the date is not today.")
pbMaxPain = input.float(0.0, "Max pain", step=0.5, group=pbGrpDaily, tooltip="Strike where option holders lose the most at expiry (nearest expiry). 0 = off.")
pbCallOI = input.float(0.0, "OI call level (call wall)", step=0.5, group=pbGrpDaily, tooltip="Strike with the largest call open interest. 0 = off.")
pbPutOI = input.float(0.0, "OI put level (put wall)", step=0.5, group=pbGrpDaily, tooltip="Strike with the largest put open interest. 0 = off.")
pbDP1 = input.float(0.0, "Dark pool level 1", step=0.01, group=pbGrpDaily, tooltip="0 = off.")
pbDP2 = input.float(0.0, "Dark pool level 2", step=0.01, group=pbGrpDaily, tooltip="0 = off.")
pbDP3 = input.float(0.0, "Dark pool level 3", step=0.01, group=pbGrpDaily, tooltip="0 = off.")
pbShowDaily = input.bool(true, "Show daily levels on the chart", group=pbGrpDaily)
pbMaxPainColor = input.color(color.rgb(255, 214, 0), "Max pain color", group=pbGrpDaily)
pbCallOIColor = input.color(color.lime, "OI call color", group=pbGrpDaily)
pbPutOIColor = input.color(color.rgb(255, 140, 0), "OI put color (dark orange)", group=pbGrpDaily)
pbDPColor = input.color(color.rgb(179, 136, 255), "Dark pool color", group=pbGrpDaily)
// Trade plan panel - section "1 · Trade plan panel", right below the daily levels
pbGrpPlan = "1 · Trade plan panel"
pbShowPlanPanel = input.bool(true, "Show the Trade plan panel", group=pbGrpPlan)
pbPlanPanelPos = input.string("Bottom Right", "Trade plan panel position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=pbGrpPlan, tooltip="Pick a different corner from the Session panel (PB 2, default Top Center) so they don't overlap.")
pbShowPlan = input.bool(true, "Show call / put plan rows", group=pbGrpPlan)
pbPlanDelta = input.float(0.50, "Assumed option delta (1R estimate)", minval=0.10, maxval=1.00, step=0.05, group=pbGrpPlan, tooltip="Playbook band 0.40-0.55. The real delta comes from the option chain.")
pbTC = input.float(4000.0, "Trading capital ($)", minval=100.0, step=100.0, group=pbGrpPlan, tooltip="Capital used for sizing (example: $4,000).")
pbRiskPct = input.float(2.0, "Risk per trade (% of trading capital)", minval=0.1, maxval=10.0, step=0.1, group=pbGrpPlan, tooltip="1R cap = trading capital x risk %.")
//==================================================================================================
// Helpers
//==================================================================================================
f_lineStyle(_s) =>
switch _s
"Solid" => line.style_solid
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
f_labelSize(_s) =>
switch _s
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
f_alertFreq(_s) =>
switch _s
"Once Per Bar" => alert.freq_once_per_bar
"Once Per Bar Close" => alert.freq_once_per_bar_close
lbBgFrom(_col, _alpha) =>
color.new(_col, _alpha)
f_ibDurMs(_s) =>
switch _s
"1 MIN" => 60000
"5 MINS" => 300000
"10 MINS" => 600000
"15 MINS" => 900000
"30 MINS" => 1800000
"1 HOUR" => 3600000
f_orDurMs(_s) =>
switch _s
"1 MIN" => 60000
"2 MINS" => 120000
"5 MINS" => 300000
"10 MINS" => 600000
"15 MINS" => 900000
"30 MINS" => 1800000
"1 HOUR" => 3600000
// history delete helpers
f_shiftDelLine(array<line> _a) =>
ln = array.shift(_a)
if not na(ln)
line.delete(ln)
f_shiftDelLabel(array<label> _a) =>
lb = array.shift(_a)
if not na(lb)
label.delete(lb)
f_shiftDelBox(array<box> _a) =>
bx = array.shift(_a)
if not na(bx)
box.delete(bx)
//==================================================================================================
// Inputs
//==================================================================================================
grpSess = "Session"
sessStr = input.session("0830-1500", "Session (RTH)", group=grpSess) // SA R1.2: default 0930-1600 NY -> 0830-1500 CT
sessTZ = input.string("America/Chicago", "Session Timezone", group=grpSess) // SA R1.2: default America/New_York -> America/Chicago
grpHist = "History"
histOn = input.bool(true, "Keep History (past sessions)", group=grpHist)
histSessions = input.int(20, "Sessions to keep (≈ 20 = 1 month)", minval=1, maxval=30, group=grpHist)
histIncludeIB = input.bool(false, "Include IB in History", group=grpHist)
grpIB = "Initial Balance"
ibDurStr = input.string("1 HOUR", "IB Duration", options=["1 MIN","5 MINS","10 MINS","15 MINS","30 MINS","1 HOUR"], group=grpIB) // SA R1: default 30 MINS -> 1 HOUR (playbook IB 8:30-9:30 CT)
showIBLines = input.bool(true, "Show IB High/Low Lines", group=grpIB)
ibCol = input.color(color.black, "IB Line Color", group=grpIB)
ibWidth = input.int(1, "IB Line Width", minval=1, maxval=5, group=grpIB)
ibStyleStr = input.string("Solid", "IB Line Style", options=["Solid","Dashed","Dotted"], group=grpIB)
showIBFill = input.bool(true, "Show IB Fill", group=grpIB)
ibFillCol = input.color(color.new(color.blue, 93), "IB Fill Color", group=grpIB)
showIBMid = input.bool(true, "Show IB Mid Line", group=grpIB)
ibMidCol = input.color(color.new(color.black, 0), "IB Mid Color", group=grpIB)
ibMidWidth = input.int(1, "IB Mid Width", minval=1, maxval=5, group=grpIB)
ibMidStyleStr = input.string("Dashed", "IB Mid Style", options=["Solid","Dashed","Dotted"], group=grpIB)
// IB label colors (you asked for this)
ibLblBgCol = input.color(color.new(color.black, 0), "IB Label Background Color", group=grpIB)
ibLblTextCol = input.color(color.white, "IB Label Text Color", group=grpIB)
grpOR = "Opening Range"
orMode = input.string("Duration", "OR Mode", options=["1st bar","Duration"], group=grpOR)
orDurStr = input.string("15 MINS", "OR Duration", options=["1 MIN","2 MINS","5 MINS","10 MINS","15 MINS","30 MINS","1 HOUR"], group=grpOR)
showOR = input.bool(true, "Show OR High/Low Lines", group=grpOR)
orCol = input.color(color.new(color.purple, 0), "OR Line Color", group=grpOR)
orWidth = input.int(1, "OR Line Width", minval=1, maxval=5, group=grpOR)
orStyleStr = input.string("Solid", "OR Line Style", options=["Solid","Dashed","Dotted"], group=grpOR)
showORFill = input.bool(true, "Show OR Fill", group=grpOR)
orFillCol = input.color(color.new(color.red, 85), "OR Fill Color", group=grpOR)
// OR midline + label (you asked for this)
showORMid = input.bool(true, "Show OR Mid Line", group=grpOR)
orMidCol = input.color(color.new(color.purple, 0), "OR Mid Color", group=grpOR)
orMidWidth = input.int(1, "OR Mid Width", minval=1, maxval=5, group=grpOR)
orMidStyleStr = input.string("Dashed", "OR Mid Style", options=["Solid","Dashed","Dotted"], group=grpOR)
showORMidLabel = input.bool(true, "Show OR Mid Label", group=grpOR)
grpLbl = "Labels"
showLabels = input.bool(true, "Show Labels", group=grpLbl)
lblSizeStr = input.string("Small", "Label Size", options=["Tiny","Small","Normal","Large"], group=grpLbl)
lblTextCol = input.color(color.white, "Label Text Color (OR + TP)", group=grpLbl)
lblBgAlpha = input.int(75, "Label BG Alpha (0-100)", minval=0, maxval=100, group=grpLbl)
lblOffsetBars = input.int(20, "Label X Offset (bars)", minval=0, maxval=500, group=grpLbl)
grpT = "Breakout Targets (TP1/TP2/TP3/TP4)"
targetFrom = input.string("Opening Range", "Targets Based On", options=["Opening Range","Initial Balance"], group=grpT)
// defaults in 50% steps to 2x range (you asked for a 4th TP)
r1 = input.float(0.5, "TP1 Multiple", step=0.25, group=grpT)
r2 = input.float(1.0, "TP2 Multiple", step=0.25, group=grpT)
r3 = input.float(1.5, "TP3 Multiple", step=0.25, group=grpT)
r4 = input.float(2.0, "TP4 Multiple", step=0.25, group=grpT)
showTP1Line = input.bool(true, "Show TP1 Line", group=grpT)
showTP2Line = input.bool(false, "Show TP2 Line", group=grpT) // SA R1: default true -> false (playbook uses Target 1 only)
showTP3Line = input.bool(false, "Show TP3 Line", group=grpT) // SA R1: default true -> false (playbook uses Target 1 only)
showTP4Line = input.bool(false, "Show TP4 Line", group=grpT) // SA R1: default true -> false (playbook uses Target 1 only)
showTP1Label = input.bool(true, "Show TP1 Label", group=grpT)
showTP2Label = input.bool(false, "Show TP2 Label", group=grpT) // SA R1: default true -> false (playbook uses Target 1 only)
showTP3Label = input.bool(false, "Show TP3 Label", group=grpT) // SA R1: default true -> false (playbook uses Target 1 only)
showTP4Label = input.bool(false, "Show TP4 Label", group=grpT) // SA R1: default true -> false (playbook uses Target 1 only)
tpCol = input.color(color.new(color.lime, 0), "TP Line Color", group=grpT)
tpWidth = input.int(1, "TP Line Width", minval=1, maxval=5, group=grpT)
tpStyleStr = input.string("Solid", "TP Line Style", options=["Solid","Dashed","Dotted"], group=grpT)
tpLblBgCol = input.color(color.new(color.green, 0), "TP Label Background Color", group=grpT)
// you asked for this toggle
tpAfterBreakoutOnly = input.bool(true, "Only show TP lines after breakout", group=grpT)
// optional projected lines if you turn the toggle OFF
showProjectedTPs = input.bool(true, "When toggle OFF, show projected TPs (both directions)", group=grpT)
tpHitMode = input.string("High/Low Touch", "TP Hit Mode", options=["High/Low Touch","Close Cross"], group=grpT)
grpBO = "Breakout"
confirmMode = input.string("Close Cross", "Confirm Mode", options=["Body Cross","Close Cross","Close Above/Below"], group=grpBO)
resetAtSessionOpen = input.bool(true, "Reset triggers/targets at session open", group=grpBO)
// Breakout candle highlight (you asked for this)
grpBHL = "Breakout Candle Highlight"
hlBreakout = input.bool(true, "Highlight Breakout Candle", group=grpBHL)
hlMode = input.string("Bar", "Highlight Mode", options=["Bar","Background","Both"], group=grpBHL)
hlBull = input.color(color.new(color.lime, 0), "Long Breakout Color", group=grpBHL)
hlBear = input.color(color.new(color.red, 0), "Short Breakout Color", group=grpBHL)
hlBgAlpha = input.int(85, "Background Alpha (0-100)", minval=0, maxval=100, group=grpBHL)
// Alerts
grpA = "Alerts"
alertsOn = input.bool(true, "Enable Alerts", group=grpA)
useAlertCalls = input.bool(true, "Use dynamic alert() messages", group=grpA, tooltip="Create alert using: Condition = 'Any alert() function call' for price-filled messages.")
alertFreqStr = input.string("Once Per Bar Close", "Alert Frequency", options=["Once Per Bar","Once Per Bar Close"], group=grpA)
//==================================================================================================
// Session detection
//==================================================================================================
inSession = not na(time(timeframe.period, sessStr, sessTZ))
// SA R1.3: RTH-chart fix. On a regular-hours chart there is no out-of-session bar between days, so the original
// "not inSession[1]" test fired only once (first bar loaded) and the OR / IB / playbook never reset. Original kept as the first term.
dayChange = inSession and inSession[1] and dayofmonth(time, sessTZ) != dayofmonth(time[1], sessTZ) // SA R1.3
newSession = inSession and (not inSession[1] or dayChange) // SA R1.3: was "inSession and not inSession[1]"
// SA R1.3: on a regular-hours chart, end the session on its last bar (bar closing at the session end time).
sessEndMin = int(str.tonumber(str.substring(sessStr, 5, 7))) * 60 + int(str.tonumber(str.substring(sessStr, 7, 9))) // SA R1.3
lastBarOfRTH = syminfo.session == session.regular and inSession and hour(time_close, sessTZ) * 60 + minute(time_close, sessTZ) >= sessEndMin // SA R1.3
sessionEnd = ((not inSession) and inSession[1]) or lastBarOfRTH // SA R1.3: was "(not inSession) and inSession[1]"
// Freeze all lines/fills at last RTH bar (so nothing extends into next day)
var int lastSessBar = na
if newSession
lastSessBar := bar_index
if inSession
lastSessBar := bar_index
xEnd = nz(lastSessBar, bar_index)
xLbl = xEnd + lblOffsetBars
//==================================================================================================
// State: IB + OR levels
//==================================================================================================
var int sessStartTime = na
var float ibHi = na
var float ibLo = na
var float orHi = na
var float orLo = na
var bool ibFormed = false
var bool orFormed = false
ibDurMs = f_ibDurMs(ibDurStr)
orDurMs = f_orDurMs(orDurStr)
if newSession
sessStartTime := time
ibHi := high
ibLo := low
orHi := high
orLo := low
ibFormed := false
orFormed := false
ibWindow = inSession and not na(sessStartTime) and (time - sessStartTime < ibDurMs)
orWindow = inSession and not na(sessStartTime) and (
orMode == "Duration" ? (time - sessStartTime < orDurMs) : newSession // SA R1.3: was "(not inSession[1])"
)
if ibWindow
ibHi := na(ibHi) ? high : math.max(ibHi, high)
ibLo := na(ibLo) ? low : math.min(ibLo, low)
if inSession and not ibWindow and not ibFormed and not na(ibHi) and not na(ibLo)
ibFormed := true
if orWindow
orHi := na(orHi) ? high : math.max(orHi, high)
orLo := na(orLo) ? low : math.min(orLo, low)
if inSession and not orWindow and not orFormed and not na(orHi) and not na(orLo)
orFormed := true
// events (alerts)
evSessOpen = newSession
evSessClose = sessionEnd
evIBFormed = ibFormed and not ibFormed[1]
evORFormed = orFormed and not orFormed[1]
//==================================================================================================
// History storage arrays
//==================================================================================================
var array<line> h_orHi = array.new_line()
var array<line> h_orLo = array.new_line()
var array<line> h_orMid = array.new_line()
var array<box> h_orBox = array.new_box()
var array<label> h_orHiL = array.new_label()
var array<label> h_orLoL = array.new_label()
var array<label> h_orMidL = array.new_label()
var array<line> h_ibHi = array.new_line()
var array<line> h_ibLo = array.new_line()
var array<line> h_ibMid = array.new_line()
var array<box> h_ibBox = array.new_box()
var array<label> h_ibHiL = array.new_label()
var array<label> h_ibLoL = array.new_label()
var array<label> h_ibMidL = array.new_label()
//==================================================================================================
// Drawing: IB + OR (stop at RTH end)
//==================================================================================================
ibStyle = f_lineStyle(ibStyleStr)
orStyle = f_lineStyle(orStyleStr)
ibMidStyle = f_lineStyle(ibMidStyleStr)
orMidStyle = f_lineStyle(orMidStyleStr)
tpStyle = f_lineStyle(tpStyleStr)
lblSize = f_labelSize(lblSizeStr)
var line ibHiLine = na
var line ibLoLine = na
var line ibMidLine = na
var box ibBox = na
var label ibHiLb = na
var label ibLoLb = na
var label ibMidLb = na
var line orHiLine = na
var line orLoLine = na
var line orMidLine = na
var box orBox = na
var label orHiLb = na
var label orLoLb = na
var label orMidLb = na
var bool pushedThisSession = false
if newSession
pushedThisSession := false
// if history OFF, delete everything
if not histOn
line.delete(ibHiLine)
line.delete(ibLoLine)
line.delete(ibMidLine)
box.delete(ibBox)
label.delete(ibHiLb)
label.delete(ibLoLb)
label.delete(ibMidLb)
line.delete(orHiLine)
line.delete(orLoLine)
line.delete(orMidLine)
box.delete(orBox)
label.delete(orHiLb)
label.delete(orLoLb)
label.delete(orMidLb)
// if history ON but IB history OFF, delete only IB drawings
if histOn and not histIncludeIB
line.delete(ibHiLine)
line.delete(ibLoLine)
line.delete(ibMidLine)
box.delete(ibBox)
label.delete(ibHiLb)
label.delete(ibLoLb)
label.delete(ibMidLb)
ibHiLine := na
ibLoLine := na
ibMidLine := na
ibBox := na
ibHiLb := na
ibLoLb := na
ibMidLb := na
orHiLine := na
orLoLine := na
orMidLine := na
orBox := na
orHiLb := na
orLoLb := na
orMidLb := na
x0 = bar_index
if showIBLines
ibHiLine := line.new(x0, ibHi, x0, ibHi, xloc=xloc.bar_index, extend=extend.none, color=ibCol, width=ibWidth, style=ibStyle)
ibLoLine := line.new(x0, ibLo, x0, ibLo, xloc=xloc.bar_index, extend=extend.none, color=ibCol, width=ibWidth, style=ibStyle)
if showIBFill
ibBox := box.new(x0, ibHi, x0, ibLo, xloc=xloc.bar_index, border_color=ibFillCol, bgcolor=ibFillCol, extend=extend.none)
if showIBLines and showIBMid
midIB0 = (ibHi + ibLo) / 2.0
ibMidLine := line.new(x0, midIB0, x0, midIB0, xloc=xloc.bar_index, extend=extend.none, color=ibMidCol, width=ibMidWidth, style=ibMidStyle)
if showOR
orHiLine := line.new(x0, orHi, x0, orHi, xloc=xloc.bar_index, extend=extend.none, color=orCol, width=orWidth, style=orStyle)
orLoLine := line.new(x0, orLo, x0, orLo, xloc=xloc.bar_index, extend=extend.none, color=orCol, width=orWidth, style=orStyle)
if showORFill
orBox := box.new(x0, orHi, x0, orLo, xloc=xloc.bar_index, border_color=orFillCol, bgcolor=orFillCol, extend=extend.none)
if showOR and showORMid
midOR0 = (orHi + orLo) / 2.0
orMidLine := line.new(x0, midOR0, x0, midOR0, xloc=xloc.bar_index, extend=extend.none, color=orMidCol, width=orMidWidth, style=orMidStyle)
// Update while in session (and once on sessionEnd)
if inSession or sessionEnd
if showIBLines and not na(ibHiLine) and not na(ibHi) and not na(ibLo)
line.set_x2(ibHiLine, xEnd)
line.set_x2(ibLoLine, xEnd)
line.set_y1(ibHiLine, ibHi)
line.set_y2(ibHiLine, ibHi)
line.set_y1(ibLoLine, ibLo)
line.set_y2(ibLoLine, ibLo)
line.set_color(ibHiLine, ibCol)
line.set_color(ibLoLine, ibCol)
line.set_width(ibHiLine, ibWidth)
line.set_width(ibLoLine, ibWidth)
line.set_style(ibHiLine, ibStyle)
line.set_style(ibLoLine, ibStyle)
if showIBMid
midIB = (ibHi + ibLo) / 2.0
if na(ibMidLine)
ibMidLine := line.new(xEnd, midIB, xEnd, midIB, xloc=xloc.bar_index, extend=extend.none, color=ibMidCol, width=ibMidWidth, style=ibMidStyle)
line.set_x2(ibMidLine, xEnd)
line.set_y1(ibMidLine, midIB)
line.set_y2(ibMidLine, midIB)
line.set_color(ibMidLine, ibMidCol)
line.set_width(ibMidLine, ibMidWidth)
line.set_style(ibMidLine, ibMidStyle)
else
line.delete(ibMidLine)
ibMidLine := na
if showIBFill and not na(ibBox) and not na(ibHi) and not na(ibLo)
box.set_right(ibBox, xEnd)
box.set_top(ibBox, ibHi)
box.set_bottom(ibBox, ibLo)
if showOR and not na(orHiLine) and not na(orHi) and not na(orLo)
line.set_x2(orHiLine, xEnd)
line.set_x2(orLoLine, xEnd)
line.set_y1(orHiLine, orHi)
line.set_y2(orHiLine, orHi)
line.set_y1(orLoLine, orLo)
line.set_y2(orLoLine, orLo)
line.set_color(orHiLine, orCol)
line.set_color(orLoLine, orCol)
line.set_width(orHiLine, orWidth)
line.set_width(orLoLine, orWidth)
line.set_style(orHiLine, orStyle)
line.set_style(orLoLine, orStyle)
if showORMid
midOR = (orHi + orLo) / 2.0
if na(orMidLine)
orMidLine := line.new(xEnd, midOR, xEnd, midOR, xloc=xloc.bar_index, extend=extend.none, color=orMidCol, width=orMidWidth, style=orMidStyle)
line.set_x2(orMidLine, xEnd)
line.set_y1(orMidLine, midOR)
line.set_y2(orMidLine, midOR)
line.set_color(orMidLine, orMidCol)
line.set_width(orMidLine, orMidWidth)
line.set_style(orMidLine, orMidStyle)
else
line.delete(orMidLine)
orMidLine := na
if showORFill and not na(orBox) and not na(orHi) and not na(orLo)
box.set_right(orBox, xEnd)
box.set_top(orBox, orHi)
box.set_bottom(orBox, orLo)
// labels
if showLabels
if showIBLines and not na(ibHi) and not na(ibLo)
if na(ibHiLb)
ibHiLb := label.new(xLbl, ibHi, "IB High: " + str.tostring(ibHi, format.mintick),
xloc=xloc.bar_index, style=label.style_label_left, textcolor=ibLblTextCol, color=lbBgFrom(ibLblBgCol, lblBgAlpha), size=lblSize)
else
label.set_x(ibHiLb, xLbl)
label.set_y(ibHiLb, ibHi)
label.set_text(ibHiLb, "IB High: " + str.tostring(ibHi, format.mintick))
label.set_color(ibHiLb, lbBgFrom(ibLblBgCol, lblBgAlpha))
label.set_textcolor(ibHiLb, ibLblTextCol)
label.set_size(ibHiLb, lblSize)
if na(ibLoLb)
ibLoLb := label.new(xLbl, ibLo, "IB Low: " + str.tostring(ibLo, format.mintick),
xloc=xloc.bar_index, style=label.style_label_left, textcolor=ibLblTextCol, color=lbBgFrom(ibLblBgCol, lblBgAlpha), size=lblSize)
else
label.set_x(ibLoLb, xLbl)
label.set_y(ibLoLb, ibLo)
label.set_text(ibLoLb, "IB Low: " + str.tostring(ibLo, format.mintick))
label.set_color(ibLoLb, lbBgFrom(ibLblBgCol, lblBgAlpha))
label.set_textcolor(ibLoLb, ibLblTextCol)
label.set_size(ibLoLb, lblSize)
if showIBMid and not na(ibMidLine)
midY = line.get_y1(ibMidLine)
if na(ibMidLb)
ibMidLb := label.new(xLbl, midY, "IB Mid: " + str.tostring(midY, format.mintick),
xloc=xloc.bar_index, style=label.style_label_left, textcolor=ibLblTextCol, color=lbBgFrom(ibLblBgCol, lblBgAlpha), size=lblSize)
else
label.set_x(ibMidLb, xLbl)
label.set_y(ibMidLb, midY)
label.set_text(ibMidLb, "IB Mid: " + str.tostring(midY, format.mintick))
label.set_color(ibMidLb, lbBgFrom(ibLblBgCol, lblBgAlpha))
label.set_textcolor(ibMidLb, ibLblTextCol)
label.set_size(ibMidLb, lblSize)
else
label.delete(ibMidLb)
ibMidLb := na
if showOR and not na(orHi) and not na(orLo)
if na(orHiLb)
orHiLb := label.new(xLbl, orHi, "OR High: " + str.tostring(orHi, format.mintick),
xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(orCol, lblBgAlpha), size=lblSize)
else
label.set_x(orHiLb, xLbl)
label.set_y(orHiLb, orHi)
label.set_text(orHiLb, "OR High: " + str.tostring(orHi, format.mintick))
label.set_color(orHiLb, lbBgFrom(orCol, lblBgAlpha))
label.set_textcolor(orHiLb, lblTextCol)
label.set_size(orHiLb, lblSize)
if na(orLoLb)
orLoLb := label.new(xLbl, orLo, "OR Low: " + str.tostring(orLo, format.mintick),
xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(orCol, lblBgAlpha), size=lblSize)
else
label.set_x(orLoLb, xLbl)
label.set_y(orLoLb, orLo)
label.set_text(orLoLb, "OR Low: " + str.tostring(orLo, format.mintick))
label.set_color(orLoLb, lbBgFrom(orCol, lblBgAlpha))
label.set_textcolor(orLoLb, lblTextCol)
label.set_size(orLoLb, lblSize)
if showOR and showORMid and showORMidLabel and not na(orMidLine)
midY2 = line.get_y1(orMidLine)
if na(orMidLb)
orMidLb := label.new(xLbl, midY2, "OR Mid: " + str.tostring(midY2, format.mintick),
xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(orMidCol, lblBgAlpha), size=lblSize)
else
label.set_x(orMidLb, xLbl)
label.set_y(orMidLb, midY2)
label.set_text(orMidLb, "OR Mid: " + str.tostring(midY2, format.mintick))
label.set_color(orMidLb, lbBgFrom(orMidCol, lblBgAlpha))
label.set_textcolor(orMidLb, lblTextCol)
label.set_size(orMidLb, lblSize)
else
label.delete(orMidLb)
orMidLb := na
else
label.delete(ibHiLb)
label.delete(ibLoLb)
label.delete(ibMidLb)
label.delete(orHiLb)
label.delete(orLoLb)
label.delete(orMidLb)
ibHiLb := na
ibLoLb := na
ibMidLb := na
orHiLb := na
orLoLb := na
orMidLb := na
// push current session drawings into history at session end
if histOn and sessionEnd and not pushedThisSession
array.push(h_orHi, orHiLine)
array.push(h_orLo, orLoLine)
array.push(h_orMid, orMidLine)
array.push(h_orBox, orBox)
array.push(h_orHiL, orHiLb)
array.push(h_orLoL, orLoLb)
array.push(h_orMidL, orMidLb)
if histIncludeIB
array.push(h_ibHi, ibHiLine)
array.push(h_ibLo, ibLoLine)
array.push(h_ibMid, ibMidLine)
array.push(h_ibBox, ibBox)
array.push(h_ibHiL, ibHiLb)
array.push(h_ibLoL, ibLoLb)
array.push(h_ibMidL, ibMidLb)
while array.size(h_orHi) > histSessions
f_shiftDelLine(h_orHi)
f_shiftDelLine(h_orLo)
f_shiftDelLine(h_orMid)
f_shiftDelBox(h_orBox)
f_shiftDelLabel(h_orHiL)
f_shiftDelLabel(h_orLoL)
f_shiftDelLabel(h_orMidL)
while histIncludeIB and array.size(h_ibHi) > histSessions
f_shiftDelLine(h_ibHi)
f_shiftDelLine(h_ibLo)
f_shiftDelLine(h_ibMid)
f_shiftDelBox(h_ibBox)
f_shiftDelLabel(h_ibHiL)
f_shiftDelLabel(h_ibLoL)
f_shiftDelLabel(h_ibMidL)
pushedThisSession := true
//==================================================================================================
// Breakout + TP1/TP2/TP3/TP4
// Targets are true multiples of the range:
// Long: ORH + multiple*(ORH-ORL)
// Short: ORL - multiple*(ORH-ORL)
//==================================================================================================
topLevel = targetFrom == "Initial Balance" ? ibHi : orHi
botLevel = targetFrom == "Initial Balance" ? ibLo : orLo
ibReady = not na(ibHi) and not na(ibLo) and (ibFormed or sessionEnd)
orReady = not na(orHi) and not na(orLo) and (orFormed or sessionEnd)
rangeReady = targetFrom == "Initial Balance" ? ibReady : orReady
bodyUp = open <= topLevel and close > topLevel
bodyDn = open >= botLevel and close < botLevel
closeUp = close > topLevel and close[1] <= topLevel
closeDn = close < botLevel and close[1] >= botLevel
closeAbv = close > topLevel
closeBlw = close < botLevel
longOK =
confirmMode == "Body Cross" ? bodyUp :
confirmMode == "Close Cross" ? closeUp :
closeAbv
shortOK =
confirmMode == "Body Cross" ? bodyDn :
confirmMode == "Close Cross" ? closeDn :
closeBlw
var bool longTrig = false
var bool shortTrig = false
var int tpDir = 0 // 1 long, -1 short, 0 none
var float tp1V = na
var float tp2V = na
var float tp3V = na
var float tp4V = na
var bool tp1Hit = false
var bool tp2Hit = false
var bool tp3Hit = false
var bool tp4Hit = false
var line tp1Line = na
var line tp2Line = na
var line tp3Line = na
var line tp4Line = na
var label tp1Lb = na
var label tp2Lb = na
var label tp3Lb = na
var label tp4Lb = na
// projected TPs (when tpAfterBreakoutOnly = false)
var line pL1 = na
var line pL2 = na
var line pL3 = na
var line pL4 = na
var line pS1 = na
var line pS2 = na
var line pS3 = na
var line pS4 = na
// breakout highlight
var int brkBar = na
var int brkDir = 0
if newSession and resetAtSessionOpen
longTrig := false
shortTrig := false
tpDir := 0
tp1V := na
tp2V := na
tp3V := na
tp4V := na
tp1Hit := false
tp2Hit := false
tp3Hit := false
tp4Hit := false
line.delete(tp1Line)
line.delete(tp2Line)
line.delete(tp3Line)
line.delete(tp4Line)
label.delete(tp1Lb)
label.delete(tp2Lb)
label.delete(tp3Lb)
label.delete(tp4Lb)
tp1Line := na
tp2Line := na
tp3Line := na
tp4Line := na
tp1Lb := na
tp2Lb := na
tp3Lb := na
tp4Lb := na
line.delete(pL1)
line.delete(pL2)
line.delete(pL3)
line.delete(pL4)
line.delete(pS1)
line.delete(pS2)
line.delete(pS3)
line.delete(pS4)
pL1 := na
pL2 := na
pL3 := na
pL4 := na
pS1 := na
pS2 := na
pS3 := na
pS4 := na
brkBar := na
brkDir := 0
// projected targets (both directions) when toggle is OFF
if (inSession or sessionEnd) and rangeReady and not tpAfterBreakoutOnly and showProjectedTPs and tpDir == 0 and not na(topLevel) and not na(botLevel)
rng = topLevel - botLevel
l1 = topLevel + r1*rng
l2 = topLevel + r2*rng
l3 = topLevel + r3*rng
l4 = topLevel + r4*rng
s1 = botLevel - r1*rng
s2 = botLevel - r2*rng
s3 = botLevel - r3*rng
s4 = botLevel - r4*rng
if na(pL1)
pL1 := line.new(bar_index, l1, xEnd, l1, xloc=xloc.bar_index, extend=extend.none, color=color.new(tpCol, 55), width=1, style=tpStyle)
pL2 := line.new(bar_index, l2, xEnd, l2, xloc=xloc.bar_index, extend=extend.none, color=color.new(tpCol, 55), width=1, style=tpStyle)
pL3 := line.new(bar_index, l3, xEnd, l3, xloc=xloc.bar_index, extend=extend.none, color=color.new(tpCol, 55), width=1, style=tpStyle)
pL4 := line.new(bar_index, l4, xEnd, l4, xloc=xloc.bar_index, extend=extend.none, color=color.new(tpCol, 55), width=1, style=tpStyle)
pS1 := line.new(bar_index, s1, xEnd, s1, xloc=xloc.bar_index, extend=extend.none, color=color.new(tpCol, 55), width=1, style=tpStyle)
pS2 := line.new(bar_index, s2, xEnd, s2, xloc=xloc.bar_index, extend=extend.none, color=color.new(tpCol, 55), width=1, style=tpStyle)
pS3 := line.new(bar_index, s3, xEnd, s3, xloc=xloc.bar_index, extend=extend.none, color=color.new(tpCol, 55), width=1, style=tpStyle)
pS4 := line.new(bar_index, s4, xEnd, s4, xloc=xloc.bar_index, extend=extend.none, color=color.new(tpCol, 55), width=1, style=tpStyle)
line.set_x2(pL1, xEnd), line.set_y1(pL1, l1), line.set_y2(pL1, l1)
line.set_x2(pL2, xEnd), line.set_y1(pL2, l2), line.set_y2(pL2, l2)
line.set_x2(pL3, xEnd), line.set_y1(pL3, l3), line.set_y2(pL3, l3)
line.set_x2(pL4, xEnd), line.set_y1(pL4, l4), line.set_y2(pL4, l4)
line.set_x2(pS1, xEnd), line.set_y1(pS1, s1), line.set_y2(pS1, s1)
line.set_x2(pS2, xEnd), line.set_y1(pS2, s2), line.set_y2(pS2, s2)
line.set_x2(pS3, xEnd), line.set_y1(pS3, s3), line.set_y2(pS3, s3)
line.set_x2(pS4, xEnd), line.set_y1(pS4, s4), line.set_y2(pS4, s4)
else
line.delete(pL1), line.delete(pL2), line.delete(pL3), line.delete(pL4)
line.delete(pS1), line.delete(pS2), line.delete(pS3), line.delete(pS4)
pL1 := na, pL2 := na, pL3 := na, pL4 := na
pS1 := na, pS2 := na, pS3 := na, pS4 := na
longBrk = rangeReady and not longTrig and longOK and not na(topLevel) and not na(botLevel)
shortBrk = rangeReady and not shortTrig and shortOK and not na(topLevel) and not na(botLevel)
evLongBreak = longBrk
evShortBreak = shortBrk
if longBrk
longTrig := true
shortTrig := false
tpDir := 1
brkBar := bar_index
brkDir := 1
line.delete(tp1Line), line.delete(tp2Line), line.delete(tp3Line), line.delete(tp4Line)
label.delete(tp1Lb), label.delete(tp2Lb), label.delete(tp3Lb), label.delete(tp4Lb)
tp1Line := na, tp2Line := na, tp3Line := na, tp4Line := na
tp1Lb := na, tp2Lb := na, tp3Lb := na, tp4Lb := na
tp1Hit := false, tp2Hit := false, tp3Hit := false, tp4Hit := false
rng = topLevel - botLevel
tp1V := topLevel + r1*rng
tp2V := topLevel + r2*rng
tp3V := topLevel + r3*rng
tp4V := topLevel + r4*rng
if showTP1Line
tp1Line := line.new(bar_index, tp1V, xEnd, tp1V, xloc=xloc.bar_index, extend=extend.none, color=tpCol, width=tpWidth, style=tpStyle)
if showTP2Line
tp2Line := line.new(bar_index, tp2V, xEnd, tp2V, xloc=xloc.bar_index, extend=extend.none, color=tpCol, width=tpWidth, style=tpStyle)
if showTP3Line
tp3Line := line.new(bar_index, tp3V, xEnd, tp3V, xloc=xloc.bar_index, extend=extend.none, color=tpCol, width=tpWidth, style=tpStyle)
if showTP4Line
tp4Line := line.new(bar_index, tp4V, xEnd, tp4V, xloc=xloc.bar_index, extend=extend.none, color=tpCol, width=tpWidth, style=tpStyle)
if showLabels
if showTP1Label and showTP1Line
tp1Lb := label.new(xLbl, tp1V, "TP1 " + str.tostring(tp1V, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(tpLblBgCol, lblBgAlpha), size=lblSize)
if showTP2Label and showTP2Line
tp2Lb := label.new(xLbl, tp2V, "TP2 " + str.tostring(tp2V, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(tpLblBgCol, lblBgAlpha), size=lblSize)
if showTP3Label and showTP3Line
tp3Lb := label.new(xLbl, tp3V, "TP3 " + str.tostring(tp3V, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(tpLblBgCol, lblBgAlpha), size=lblSize)
if showTP4Label and showTP4Line
tp4Lb := label.new(xLbl, tp4V, "TP4 " + str.tostring(tp4V, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(tpLblBgCol, lblBgAlpha), size=lblSize)
if shortBrk
shortTrig := true
longTrig := false
tpDir := -1
brkBar := bar_index
brkDir := -1
line.delete(tp1Line), line.delete(tp2Line), line.delete(tp3Line), line.delete(tp4Line)
label.delete(tp1Lb), label.delete(tp2Lb), label.delete(tp3Lb), label.delete(tp4Lb)
tp1Line := na, tp2Line := na, tp3Line := na, tp4Line := na
tp1Lb := na, tp2Lb := na, tp3Lb := na, tp4Lb := na
tp1Hit := false, tp2Hit := false, tp3Hit := false, tp4Hit := false
rng = topLevel - botLevel
tp1V := botLevel - r1*rng
tp2V := botLevel - r2*rng
tp3V := botLevel - r3*rng
tp4V := botLevel - r4*rng
if showTP1Line
tp1Line := line.new(bar_index, tp1V, xEnd, tp1V, xloc=xloc.bar_index, extend=extend.none, color=tpCol, width=tpWidth, style=tpStyle)
if showTP2Line
tp2Line := line.new(bar_index, tp2V, xEnd, tp2V, xloc=xloc.bar_index, extend=extend.none, color=tpCol, width=tpWidth, style=tpStyle)
if showTP3Line
tp3Line := line.new(bar_index, tp3V, xEnd, tp3V, xloc=xloc.bar_index, extend=extend.none, color=tpCol, width=tpWidth, style=tpStyle)
if showTP4Line
tp4Line := line.new(bar_index, tp4V, xEnd, tp4V, xloc=xloc.bar_index, extend=extend.none, color=tpCol, width=tpWidth, style=tpStyle)
if showLabels
if showTP1Label and showTP1Line
tp1Lb := label.new(xLbl, tp1V, "TP1 " + str.tostring(tp1V, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(tpLblBgCol, lblBgAlpha), size=lblSize)
if showTP2Label and showTP2Line
tp2Lb := label.new(xLbl, tp2V, "TP2 " + str.tostring(tp2V, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(tpLblBgCol, lblBgAlpha), size=lblSize)
if showTP3Label and showTP3Line
tp3Lb := label.new(xLbl, tp3V, "TP3 " + str.tostring(tp3V, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(tpLblBgCol, lblBgAlpha), size=lblSize)
if showTP4Label and showTP4Line
tp4Lb := label.new(xLbl, tp4V, "TP4 " + str.tostring(tp4V, format.mintick), xloc=xloc.bar_index, style=label.style_label_left, textcolor=lblTextCol, color=lbBgFrom(tpLblBgCol, lblBgAlpha), size=lblSize)
// Keep TPs frozen to RTH end
if inSession or sessionEnd
if not na(tp1Line)
line.set_x2(tp1Line, xEnd)
if not na(tp2Line)
line.set_x2(tp2Line, xEnd)
if not na(tp3Line)
line.set_x2(tp3Line, xEnd)
if not na(tp4Line)
line.set_x2(tp4Line, xEnd)
if not na(tp1Lb)
label.set_x(tp1Lb, xLbl)
if not na(tp2Lb)
label.set_x(tp2Lb, xLbl)
if not na(tp3Lb)
label.set_x(tp3Lb, xLbl)
if not na(tp4Lb)
label.set_x(tp4Lb, xLbl)
// Breakout candle highlight
isBrk = hlBreakout and not na(brkBar) and bar_index == brkBar
brkColor = brkDir == 1 ? hlBull : brkDir == -1 ? hlBear : na
barcolor((hlMode == "Bar" or hlMode == "Both") and isBrk ? brkColor : na)
bgcolor((hlMode == "Background" or hlMode == "Both") and isBrk ? color.new(brkColor, hlBgAlpha) : na)
//==================================================================================================
// TP hit detection
//==================================================================================================
hitLong(_tp) =>
tpHitMode == "High/Low Touch" ? (high >= _tp) : (close >= _tp and close[1] < _tp)
hitShort(_tp) =>
tpHitMode == "High/Low Touch" ? (low <= _tp) : (close <= _tp and close[1] > _tp)
evTP1 = false
evTP2 = false
evTP3 = false
evTP4 = false
if tpDir != 0 and (inSession or sessionEnd)
if tpDir == 1
if not tp1Hit and not na(tp1V) and hitLong(tp1V)
tp1Hit := true
evTP1 := true
if not tp2Hit and not na(tp2V) and hitLong(tp2V)
tp2Hit := true
evTP2 := true
if not tp3Hit and not na(tp3V) and hitLong(tp3V)
tp3Hit := true
evTP3 := true
if not tp4Hit and not na(tp4V) and hitLong(tp4V)
tp4Hit := true
evTP4 := true
if tpDir == -1
if not tp1Hit and not na(tp1V) and hitShort(tp1V)
tp1Hit := true
evTP1 := true
if not tp2Hit and not na(tp2V) and hitShort(tp2V)
tp2Hit := true
evTP2 := true
if not tp3Hit and not na(tp3V) and hitShort(tp3V)
tp3Hit := true
evTP3 := true
if not tp4Hit and not na(tp4V) and hitShort(tp4V)
tp4Hit := true
evTP4 := true
//==================================================================================================
// ALERTS (all of them)
//==================================================================================================
aFreq = f_alertFreq(alertFreqStr)
sym = syminfo.ticker
tf = timeframe.period
basis = targetFrom == "Initial Balance" ? "IB" : "OR"
msgSessOpen = sym + " " + tf + " , SESSION OPEN (" + sessStr + ")"
msgSessClose = sym + " " + tf + " , SESSION CLOSE (" + sessStr + ")"
msgIBFormed = sym + " " + tf + " , IB FORMED , IBH " + str.tostring(ibHi, format.mintick) + " , IBL " + str.tostring(ibLo, format.mintick)
msgORFormed = sym + " " + tf + " , OR FORMED , ORH " + str.tostring(orHi, format.mintick) + " , ORL " + str.tostring(orLo, format.mintick) + " , ORM " + str.tostring((orHi+orLo)/2.0, format.mintick)
msgLongBrk = sym + " " + tf + " , LONG " + basis + " BREAKOUT , Top " + str.tostring(topLevel, format.mintick) + " , Bot " + str.tostring(botLevel, format.mintick)
msgShortBrk = sym + " " + tf + " , SHORT " + basis + " BREAKOUT , Top " + str.tostring(topLevel, format.mintick) + " , Bot " + str.tostring(botLevel, format.mintick)
tpSideTxt = tpDir == 1 ? "LONG" : tpDir == -1 ? "SHORT" : "NA"
msgTP1 = sym + " " + tf + " , TP1 HIT (" + tpSideTxt + ") , " + str.tostring(tp1V, format.mintick)
msgTP2 = sym + " " + tf + " , TP2 HIT (" + tpSideTxt + ") , " + str.tostring(tp2V, format.mintick)
msgTP3 = sym + " " + tf + " , TP3 HIT (" + tpSideTxt + ") , " + str.tostring(tp3V, format.mintick)
msgTP4 = sym + " " + tf + " , TP4 HIT (" + tpSideTxt + ") , " + str.tostring(tp4V, format.mintick)
alertcondition(evSessOpen, title="Session Open", message="SESSION OPEN")
alertcondition(evSessClose, title="Session Close", message="SESSION CLOSE")
alertcondition(evIBFormed, title="IB Formed", message="IB FORMED")
alertcondition(evORFormed, title="OR Formed", message="OR FORMED")
alertcondition(evLongBreak, title="Long Breakout", message="LONG BREAKOUT")
alertcondition(evShortBreak, title="Short Breakout",message="SHORT BREAKOUT")
alertcondition(evTP1, title="TP1 Hit", message="TP1 HIT")
alertcondition(evTP2, title="TP2 Hit", message="TP2 HIT")
alertcondition(evTP3, title="TP3 Hit", message="TP3 HIT")
alertcondition(evTP4, title="TP4 Hit", message="TP4 HIT")
if alertsOn and useAlertCalls
if evSessOpen
alert(msgSessOpen, aFreq)
if evSessClose
alert(msgSessClose, aFreq)
if evIBFormed
alert(msgIBFormed, aFreq)
if evORFormed
alert(msgORFormed, aFreq)
if evLongBreak
alert(msgLongBrk, aFreq)
if evShortBreak
alert(msgShortBrk, aFreq)
if evTP1
alert(msgTP1, aFreq)
if evTP2
alert(msgTP2, aFreq)
if evTP3
alert(msgTP3, aFreq)
if evTP4
alert(msgTP4, aFreq)
plot(na, editable=false)
//====================================================================
// SIGMA ANALYTICS PLAYBOOK MODULE (appended to the ORB Suite above)
// Author: Hanzo321 (Sigma Analytics). Rule summary: see the header.
// Uses the Suite's orHi/orLo/orFormed, ibHi/ibLo/ibFormed, newSession
// and alertsOn/useAlertCalls/aFreq. Every new name is prefixed pb /
// PB_ / f_pb so the Suite code stays untouched. Stop is checked before
// the target when both are touched in the same candle.
//====================================================================
const string PB_TZ = "America/Chicago"
const string PB_VERSION = "v1.R1.8"
const int PB_MS_IN_MIN = 60 * 1000
//------------------------------------------------------
// PLAYBOOK INPUTS
//------------------------------------------------------
pbGrpEntry = "PB 1 · Entries (playbook defaults)"
pbOn = input.bool(true, "Enable the Playbook module", group=pbGrpEntry)
pbWinSess = input.session("0845-0930", "Entry window (CT)", group=pbGrpEntry, tooltip="The entry candle must close by 9:30 CT.")
pbNeedScore = input.int(3, "Entry 1: minimum context score", minval=0, maxval=3, group=pbGrpEntry)
pbVolLen = input.int(20, "Entry 1: volume average (bars)", minval=1, group=pbGrpEntry)
pbShowE2 = input.bool(true, "Entry 2 (breach-retreat, paper-track)", group=pbGrpEntry)
pbZoneTouch = input.float(0.38, "Entry 2: touch level", step=0.01, group=pbGrpEntry)
pbZoneFail = input.float(0.62, "Entry 2: close-stop level", step=0.01, group=pbGrpEntry)
pbZoneHard = input.float(0.86, "Entry 2: hard stop level", step=0.01, group=pbGrpEntry)
pbTimeStop = input.int(45, "Time stop (minutes)", minval=5, group=pbGrpEntry)
pbFlatH = input.int(14, "Flat by (CT) - hour", group=pbGrpEntry, inline="pbflat")
pbFlatM = input.int(55, "minute", group=pbGrpEntry, inline="pbflat")
pbGrpView = "PB 2 · Context & display"
pbShowPSC = input.bool(true, "Previous session close (PSC)", group=pbGrpView)
pbShowVWAP = input.bool(true, "Session VWAP", group=pbGrpView)
pbShowEMA = input.bool(true, "EMA (5-min trend)", group=pbGrpView, inline="pbema")
pbEmaLen = input.int(20, "length", group=pbGrpView, inline="pbema")
pbShadeWin = input.bool(false, "Shade the entry window", group=pbGrpView)
pbMarkRej = input.bool(true, "Mark a rejected Entry 1 (one small ✕, hover it)", group=pbGrpView)
pbRejColor = input.color(color.rgb(255, 20, 147), "Rejected Entry 1 ✕ color", group=pbGrpView) // R1.5: was gray
pbShowPanel = input.bool(true, "Playbook panel", group=pbGrpView)
pbPanelPos = input.string("Top Center", "Panel position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=pbGrpView)
pbCalColor = input.color(color.rgb(0, 200, 83), "Calls / target color", group=pbGrpView)
pbPutColor = input.color(color.rgb(255, 23, 68), "Puts / stop color", group=pbGrpView)
pbZoneColor = input.color(color.rgb(255, 179, 0), "Entry 2 zone color", group=pbGrpView)
pbPscColor = input.color(color.rgb(255, 152, 0), "PSC color", group=pbGrpView)
// R1.1 entry labels
pbGrpLbl = "PB 3 · Entry labels"
pbShowEntryLabels = input.bool(true, "Show LONG/SHORT Labels on Main Chart", group=pbGrpLbl)
pbLabelTextMode = input.string("LONG / SHORT", "Label text", options=["LONG / SHORT", "E1 / E2 (R1)"], group=pbGrpLbl, tooltip="LONG / SHORT = LONG (CALL) / SHORT (PUT) + price (R1.1). E1 / E2 = the R1 tag text.")
pbLongLabelColor = input.color(color.rgb(34, 197, 94), "Long Label Color", group=pbGrpLbl)
pbShortLabelColor = input.color(color.rgb(220, 38, 38), "Short Label Color", group=pbGrpLbl)
pbLabelTransparency = input.int(65, "Label Transparency (0-100)", minval=0, maxval=100, group=pbGrpLbl)
pbLabelSizeInput = input.string("Small", "Label Size", options=["Tiny", "Small", "Normal"], group=pbGrpLbl)
// R1.2 Suite level-label spacing (Suite code untouched; this only moves label x)
pbGrpSpace = "PB 4 · Suite label spacing"
pbSpaceOn = input.bool(true, "Stagger overlapping Suite level labels", group=pbGrpSpace, tooltip="When two Suite level labels (OR, IB, TP) sit closer than the distance below, the later one moves right by one step. OR labels never move. Prices and lines are unchanged.")
pbSpaceGap = input.float(0.30, "Overlap distance ($)", minval=0.01, step=0.05, group=pbGrpSpace, tooltip="SPY default 0.30. Raise it if labels still touch when zoomed out.")
pbSpaceStep = input.int(20, "Stagger step (bars)", minval=1, maxval=100, group=pbGrpSpace) // R1.6: default 14 -> 20
// Session panel rows (the Trade plan panel settings sit at the top, section "1 · Trade plan panel")
pbGrpSess = "PB 7 · Session panel rows"
pbPanelMode = input.string("Full", "Session panel rows", options=["Full", "Compact"], group=pbGrpSess, tooltip="Compact = version, context, entry window, levels as of. Show / hide and position: PB 2.")
//------------------------------------------------------
// PLAYBOOK HELPERS
//------------------------------------------------------
f_pbPx(float x) =>
str.tostring(x, format.mintick)
f_pbDayTime(int h, int m) =>
timestamp(PB_TZ, year(time, PB_TZ), month(time, PB_TZ), dayofmonth(time, PB_TZ), h, m)
f_pbSideTxt(int d) =>
d == 1 ? "LONG (CALL)" : "SHORT (PUT)"
// Same format as the Suite's own alert() messages: "SPY 5 , EVENT , ..."
f_pbAlert(string msg) =>
if alertsOn and useAlertCalls and barstate.isconfirmed and barstate.isrealtime
alert(syminfo.ticker + " " + timeframe.period + " , " + msg + " , " + str.format_time(time_close, "HH:mm", PB_TZ) + " CT", aFreq)
//------------------------------------------------------
// PLAYBOOK SERIES (computed every bar)
//------------------------------------------------------
pbInWin = not na(time(timeframe.period, pbWinSess, PB_TZ))
pbTfOk = timeframe.isintraday and timeframe.in_seconds() <= 300
pbVwap = ta.vwap(hlc3)
pbEma = ta.ema(close, pbEmaLen)
pbVolAvg = ta.sma(volume, pbVolLen)
// Prior session close, non-repainting idiom: expression offset [1] + lookahead_on
pbPsc = request.security(syminfo.tickerid, "D", close[1], lookahead=barmerge.lookahead_on)
pbMid = (orHi + orLo) / 2.0
pbRange = orHi - orLo
f_pbTrendOk(int d) =>
d == 1 ? (close > pbEma and pbEma > pbEma[3]) : (close < pbEma and pbEma < pbEma[3])
f_pbPscOk(int d) =>
na(pbPsc) ? false : (d == 1 ? close > pbPsc : close < pbPsc)
f_pbVwapOk(int d) =>
d == 1 ? close > pbVwap : close < pbVwap
f_pbScore(int d) =>
(f_pbTrendOk(d) ? 1 : 0) + (f_pbPscOk(d) ? 1 : 0) + (f_pbVwapOk(d) ? 1 : 0)
//------------------------------------------------------
// PLAYBOOK STATE (reset every session)
//------------------------------------------------------
var int pbDayEnd = na
var int pbWinEnd = na
var int pbBreach = 0
var int pbBreachBar = na
var bool pbE2Dead = false
var bool pbE1Rejected = false
var bool pbTraded = false
var string pbTradeTxt = "none"
var int pbDir = 0
var string pbKind = ""
var int pbEntryBar = na
var int pbEntryTime = na
var float pbEntry = na
var float pbR = na
var float pbPriceStop = na
var float pbCloseStop = na
var float pbT1 = na
var string pbLastExit = ""
var string pbEntryTip = ""
// Per-bar events for alertcondition()
pbEvE1Call = false
pbEvE1Put = false
pbEvE1Rej = false
pbEvE2 = false
pbEvE2Fail = false
pbEvExit = false
if newSession
pbDayEnd := f_pbDayTime(15, 0)
pbWinEnd := f_pbDayTime(9, 30)
pbBreach := 0
pbBreachBar := na
pbE2Dead := false
pbE1Rejected := false
pbTraded := false
pbTradeTxt := "none"
pbDir := 0
pbKind := ""
pbLastExit := ""
if pbOn and pbShowPSC and not na(pbPsc)
line.new(time, pbPsc, pbDayEnd, pbPsc, xloc=xloc.bar_time, color=pbPscColor, style=line.style_dotted, width=1)
label.new(
x=pbDayEnd,
y=pbPsc,
text="PSC " + f_pbPx(pbPsc),
xloc=xloc.bar_time,
style=label.style_label_left,
color=color.new(pbPscColor, 85),
textcolor=color.white,
size=size.small
)
//------------------------------------------------------
// ENTRY 1 - CLOSE BEYOND THE RANGE, QUALIFIED (LIVE)
//------------------------------------------------------
// R1.6: evaluate only CLOSED candles (the rule is a 5-min close); stops intrabar flicker of labels on the live candle
pbCanEnter = pbOn and orFormed and pbInWin and not pbTraded and pbDir == 0 and barstate.isconfirmed
pbE1Dir = pbCanEnter ? (close > orHi ? 1 : close < orLo ? -1 : 0) : 0
if pbE1Dir != 0
pbSc = f_pbScore(pbE1Dir)
pbSideOk = f_pbVwapOk(pbE1Dir)
pbVolOk = volume >= pbVolAvg
pbSideTxt = f_pbSideTxt(pbE1Dir)
if pbSideOk and pbVolOk and pbSc >= pbNeedScore
pbDir := pbE1Dir
pbKind := "E1"
pbEntryBar := bar_index
pbEntryTime := time_close
pbEntry := close
pbR := math.abs(close - pbMid)
pbPriceStop := pbMid
pbCloseStop := pbE1Dir == 1 ? orHi : orLo
pbT1 := close + pbE1Dir * pbR
pbTraded := true
pbTradeTxt := "E1 " + pbSideTxt
pbEvE1Call := pbE1Dir == 1
pbEvE1Put := pbE1Dir == -1
pbEntryTip := "Entry 1 " + pbSideTxt + " · " + syminfo.ticker + " " + f_pbPx(close) + "\nstop " + f_pbPx(pbMid) + " (midpoint) or a 5-min close back inside the range\nTarget 1 " + f_pbPx(pbT1) + " (entry +/- 1R)\ncontext " + str.tostring(pbSc) + "/3 · run the GO / NO-GO checklist"
line.new(time, pbPriceStop, pbDayEnd, pbPriceStop, xloc=xloc.bar_time, color=pbPutColor, width=1)
line.new(time, pbT1, pbDayEnd, pbT1, xloc=xloc.bar_time, color=pbCalColor, width=1)
f_pbAlert("ENTRY 1 " + pbSideTxt + " , " + f_pbPx(close) + " , stop " + f_pbPx(pbMid) + " , T1 " + f_pbPx(pbT1) + " , context " + str.tostring(pbSc) + "/3 , run the checklist")
else if pbMarkRej and not pbE1Rejected
pbE1Rejected := true
pbEvE1Rej := true
pbWhy = (pbSideOk ? "" : "VWAP side · ") + (pbVolOk ? "" : "volume · ") + (pbSc >= pbNeedScore ? "" : "context " + str.tostring(pbSc) + "/3")
label.new(
x=bar_index,
y=pbE1Dir == 1 ? high : low,
text="✕",
yloc=pbE1Dir == 1 ? yloc.abovebar : yloc.belowbar,
style=label.style_none,
textcolor=pbRejColor,
size=size.small,
tooltip="Entry 1 NOT qualified (close beyond the range) - fails: " + pbWhy
)
f_pbAlert("ENTRY 1 NOT QUALIFIED " + pbSideTxt + " , fails: " + pbWhy)
//------------------------------------------------------
// ENTRY 2 - BREACH-RETREAT (PAPER-TRACK)
//------------------------------------------------------
if pbOn and pbShowE2 and orFormed and pbInWin and not pbTraded and pbDir == 0 and not pbE2Dead and barstate.isconfirmed // R1.6: closed candles only
pbLvlTouch = pbBreach == 1 ? orHi - pbZoneTouch * pbRange : orLo + pbZoneTouch * pbRange
pbLvlFail = pbBreach == 1 ? orHi - pbZoneFail * pbRange : orLo + pbZoneFail * pbRange
pbLvlHard = pbBreach == 1 ? orHi - pbZoneHard * pbRange : orLo + pbZoneHard * pbRange
if pbBreach == 0
if high > orHi and low < orLo
pbE2Dead := true // outside bar both ways: ambiguous, no Entry 2 today
else if high > orHi or low < orLo
pbBreach := high > orHi ? 1 : -1
pbBreachBar := bar_index
pbB1 = pbBreach == 1 ? orHi - pbZoneTouch * pbRange : orLo + pbZoneTouch * pbRange
pbB2 = pbBreach == 1 ? orHi - pbZoneFail * pbRange : orLo + pbZoneFail * pbRange
pbB3 = pbBreach == 1 ? orHi - pbZoneHard * pbRange : orLo + pbZoneHard * pbRange
box.new(time, math.max(pbB1, pbB2), pbWinEnd, math.min(pbB1, pbB2), xloc=xloc.bar_time, border_color=color.new(pbZoneColor, 40), bgcolor=color.new(pbZoneColor, 85))
line.new(time, pbB3, pbWinEnd, pbB3, xloc=xloc.bar_time, color=color.new(pbPutColor, 30), style=line.style_dotted)
else if bar_index > pbBreachBar
pbFailed = pbBreach == 1 ? close < pbLvlFail : close > pbLvlFail
pbTouched = pbBreach == 1 ? low <= pbLvlTouch : high >= pbLvlTouch
if pbFailed
pbE2Dead := true
pbEvE2Fail := true
label.new(
x=bar_index,
y=close,
text="✕",
style=label.style_none,
textcolor=color.new(pbZoneColor, 10),
size=size.small,
tooltip="Entry 2 setup FAILED - 5-min close beyond the " + str.tostring(pbZoneFail * 100, "#") + "% line"
)
f_pbAlert("ENTRY 2 SETUP FAILED , close beyond the " + str.tostring(pbZoneFail * 100, "#") + "% line")
else if pbTouched
pbEdge = pbBreach == 1 ? orHi : orLo
pbSideTxt2 = f_pbSideTxt(pbBreach)
pbDir := pbBreach
pbKind := "E2"
pbEntryBar := bar_index
pbEntryTime := time_close
pbEntry := close
pbR := math.abs(close - pbLvlHard)
pbPriceStop := pbLvlHard
pbCloseStop := pbLvlFail
pbT1 := (pbEdge - close) * pbBreach > 0 ? pbEdge : close + pbBreach * pbR
pbTraded := true
pbTradeTxt := "E2 " + pbSideTxt2 + " · paper"
pbEvE2 := true
pbEntryTip := "Entry 2 (PAPER-TRACK) " + pbSideTxt2 + " · " + syminfo.ticker + " " + f_pbPx(close) + "\nclose-stop " + f_pbPx(pbLvlFail) + " · hard stop " + f_pbPx(pbLvlHard) + "\nTarget 1 " + f_pbPx(pbT1) + " (breached edge)"
line.new(time, pbT1, pbDayEnd, pbT1, xloc=xloc.bar_time, color=pbCalColor, width=1)
f_pbAlert("ENTRY 2 PAPER " + pbSideTxt2 + " , " + f_pbPx(close) + " , close-stop " + f_pbPx(pbLvlFail) + " , hard stop " + f_pbPx(pbLvlHard) + " , T1 " + f_pbPx(pbT1))
//------------------------------------------------------
// EXITS - TRACKED POSITION (stop checked before target)
//------------------------------------------------------
pbNowMin = hour(time_close, PB_TZ) * 60 + minute(time_close, PB_TZ)
pbFlatNow = pbNowMin >= pbFlatH * 60 + pbFlatM
if pbDir != 0 and bar_index > pbEntryBar and barstate.isconfirmed // R1.6: exits on closed candles
float pbExitPx = na
string pbExitWhy = ""
pbStopHit = pbDir == 1 ? low <= pbPriceStop : high >= pbPriceStop
pbTargetHit = pbDir == 1 ? high >= pbT1 : low <= pbT1
pbCloseHit = pbKind == "E1" ? (pbDir == 1 ? close <= pbCloseStop : close >= pbCloseStop) : (pbDir == 1 ? close < pbCloseStop : close > pbCloseStop)
if pbStopHit
pbExitPx := pbDir == 1 ? math.min(open, pbPriceStop) : math.max(open, pbPriceStop)
pbExitWhy := pbKind == "E1" ? "Stop (midpoint)" : "Hard stop"
else if pbTargetHit
pbExitPx := pbDir == 1 ? math.max(open, pbT1) : math.min(open, pbT1)
pbExitWhy := "Target 1"
else if pbCloseHit
pbExitPx := close
pbExitWhy := pbKind == "E1" ? "Close back inside range" : "Close beyond zone"
else if time_close - pbEntryTime >= pbTimeStop * PB_MS_IN_MIN
pbExitPx := close
pbExitWhy := "Time stop " + str.tostring(pbTimeStop) + " min"
else if pbFlatNow
pbExitPx := close
pbExitWhy := "Flat by 2:55 PM"
if not na(pbExitPx)
pbRes = (pbExitPx - pbEntry) * pbDir / pbR
pbResTxt = str.tostring(pbRes, "+0.00;-0.00") + "R"
pbLastExit := pbKind + " · " + pbExitWhy + " · " + pbResTxt
pbEvExit := true
label.new(
x=bar_index,
y=pbExitPx,
text=pbResTxt,
style=label.style_label_left,
color=pbRes >= 0 ? color.new(pbCalColor, 20) : color.new(pbPutColor, 20),
textcolor=color.white,
size=size.tiny,
tooltip=pbKind + " exit · " + pbExitWhy + " · " + syminfo.ticker + " " + f_pbPx(pbExitPx) + " · " + pbResTxt
)
f_pbAlert("EXIT " + pbKind + " , " + pbExitWhy + " , " + f_pbPx(pbExitPx) + " , " + pbResTxt)
pbDir := 0
//------------------------------------------------------
// PLAYBOOK LABEL SIZE MAPPING
//------------------------------------------------------
pbLabelSize = (
pbLabelSizeInput == "Tiny" ? size.tiny :
pbLabelSizeInput == "Normal" ? size.normal :
size.small
)
//------------------------------------------------------
// PLAYBOOK MAIN-CHART LABELS
//------------------------------------------------------
pbLongEntry = pbEvE1Call or (pbEvE2 and pbDir == 1)
pbShortEntry = pbEvE1Put or (pbEvE2 and pbDir == -1)
pbIsE2Entry = pbEvE2
pbUseSideTxt = pbLabelTextMode == "LONG / SHORT"
if pbShowEntryLabels and pbLongEntry
label.new(
x=bar_index,
y=low,
text=(pbUseSideTxt ? (pbIsE2Entry ? "LONG (CALL) · E2\n" : "LONG (CALL)\n") : (pbIsE2Entry ? "E2\n" : "E1 CALL\n")) + str.tostring(close, format.mintick),
xloc=xloc.bar_index,
yloc=yloc.belowbar,
style=label.style_label_up,
color=color.new(pbLongLabelColor, pbLabelTransparency),
textcolor=color.white,
size=pbLabelSize,
tooltip=pbEntryTip,
force_overlay=true
)
if pbShowEntryLabels and pbShortEntry
label.new(
x=bar_index,
y=high,
text=(pbUseSideTxt ? (pbIsE2Entry ? "SHORT (PUT) · E2\n" : "SHORT (PUT)\n") : (pbIsE2Entry ? "E2\n" : "E1 PUT\n")) + str.tostring(close, format.mintick),
xloc=xloc.bar_index,
yloc=yloc.abovebar,
style=label.style_label_down,
color=color.new(pbShortLabelColor, pbLabelTransparency),
textcolor=color.white,
size=pbLabelSize,
tooltip=pbEntryTip,
force_overlay=true
)
//------------------------------------------------------
// SUITE LABEL SPACING (R1.2) - greedy columns, OR labels placed first
//------------------------------------------------------
f_pbPlace(label lb, array<float> ys, array<int> cols) =>
int placed = 0
if not na(lb)
float y = label.get_y(lb)
int col = 0
bool clash = true
while clash and col < 6
clash := false
for [i, yv] in ys
if array.get(cols, i) == col and math.abs(yv - y) < pbSpaceGap
clash := true
if clash
col += 1
array.push(ys, y)
array.push(cols, col)
label.set_x(lb, xLbl + col * pbSpaceStep)
placed := 1
placed
if pbSpaceOn and showLabels and barstate.islast
pbYs = array.new<float>()
pbCols = array.new<int>()
f_pbPlace(orHiLb, pbYs, pbCols)
f_pbPlace(orLoLb, pbYs, pbCols)
f_pbPlace(orMidLb, pbYs, pbCols)
f_pbPlace(tp1Lb, pbYs, pbCols)
f_pbPlace(ibHiLb, pbYs, pbCols)
f_pbPlace(ibLoLb, pbYs, pbCols)
f_pbPlace(ibMidLb, pbYs, pbCols)
f_pbPlace(tp2Lb, pbYs, pbCols)
f_pbPlace(tp3Lb, pbYs, pbCols)
f_pbPlace(tp4Lb, pbYs, pbCols)
//------------------------------------------------------
// PLAYBOOK VISUALS
//------------------------------------------------------
plot(pbOn and pbShowVWAP ? pbVwap : na, title="PB · session VWAP", color=color.new(color.yellow, 0), linewidth=1)
plot(pbOn and pbShowEMA ? pbEma : na, title="PB · EMA", color=color.new(color.aqua, 20), linewidth=1)
bgcolor(pbOn and pbShadeWin and pbInWin ? color.new(pbCalColor, 92) : na, title="PB · entry window")
//------------------------------------------------------
// DAILY LEVELS (R1.4) - today's session only, redrawn on the last bar
//------------------------------------------------------
var array<line> pbDailyLines = array.new<line>()
var array<label> pbDailyLabels = array.new<label>()
f_pbDailyLevel(float px, string name, color col, int x1, int x2) =>
int made = 0
if px > 0
array.push(pbDailyLines, line.new(x1, px, x2, px, xloc=xloc.bar_time, extend=extend.right, color=col, style=line.style_dashed, width=1))
array.push(pbDailyLabels, label.new(x2, px, name + " " + f_pbPx(px), xloc=xloc.bar_time, style=label.style_label_left, color=color.new(col, 70), textcolor=color.white, size=size.small))
made := 1
made
f_pbDist(float px) =>
px > 0 ? f_pbPx(px) + " (" + str.tostring(px - close, "+0.00;-0.00") + ")" : "-"
if barstate.islast
for ln in pbDailyLines
line.delete(ln)
for lb in pbDailyLabels
label.delete(lb)
array.clear(pbDailyLines)
array.clear(pbDailyLabels)
if pbOn and pbShowDaily
int pbX1 = na(sessStartTime) ? time : sessStartTime
int pbX2 = na(pbDayEnd) ? time : pbDayEnd
f_pbDailyLevel(pbMaxPain, "Max pain", pbMaxPainColor, pbX1, pbX2)
f_pbDailyLevel(pbCallOI, "OI call", pbCallOIColor, pbX1, pbX2)
f_pbDailyLevel(pbPutOI, "OI put", pbPutOIColor, pbX1, pbX2)
f_pbDailyLevel(pbDP1, "DP", pbDPColor, pbX1, pbX2)
f_pbDailyLevel(pbDP2, "DP", pbDPColor, pbX1, pbX2)
f_pbDailyLevel(pbDP3, "DP", pbDPColor, pbX1, pbX2)
// Levels are fresh when their date (exchange time zone) is today
pbLvlFresh = year(pbLvlDate, syminfo.timezone) == year(timenow, syminfo.timezone) and month(pbLvlDate, syminfo.timezone) == month(timenow, syminfo.timezone) and dayofmonth(pbLvlDate, syminfo.timezone) == dayofmonth(timenow, syminfo.timezone)
pbAnyDaily = pbMaxPain > 0 or pbCallOI > 0 or pbPutOI > 0 or pbDP1 > 0 or pbDP2 > 0 or pbDP3 > 0
//------------------------------------------------------
// PLAYBOOK PANEL
//------------------------------------------------------
f_pbPos(string p) =>
switch p
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
=> position.bottom_right
f_pbRow(table t, int r, string k, string v, color tx) =>
table.cell(t, 0, r, k, text_size=size.small, text_halign=text.align_left, bgcolor=color.new(color.black, 20), text_color=color.gray)
table.cell(t, 1, r, v, text_size=size.small, text_halign=text.align_right, bgcolor=color.new(color.black, 20), text_color=tx)
var table pbPanel = table.new(f_pbPos(pbPanelPos), 2, 12, border_width=1)
var table pbPlanPanel = table.new(f_pbPos(pbPlanPanelPos), 2, 8, border_width=1)
// Trade plan math (SPY levels only - Pine cannot read the option chain)
pbRiskCap = pbTC * pbRiskPct / 100.0 // 1R cap in $
pbPlanR = pbRange / 2.0 // entry at the trigger -> stop at the midpoint
pbPlanRisk = pbPlanDelta * pbPlanR * 100.0 // estimated 1R in $ at the assumed delta
pbMaxDist = pbRiskCap / (pbPlanDelta * 100.0) // farthest stop distance the cap allows
pbMaxCall = pbMid + pbMaxDist
pbMaxPut = pbMid - pbMaxDist
pbLastBar = barstate.islast or barstate.islastconfirmedhistory
// ---- Panel 1 · Session (market) ----
if pbOn and pbShowPanel and pbLastBar
bool pbFull = pbPanelMode == "Full"
int pbRow = 0
pbWinTxt = not orFormed ? "range forming" : pbInWin ? "OPEN until 9:30 CT" : pbNowMin < 9 * 60 + 30 ? "opens 8:45 CT" : "CLOSED"
f_pbRow(pbPanel, pbRow, "SA ORB Shield " + PB_VERSION, pbTfOk ? "5-min ✓" : "use a 5-min chart", pbTfOk ? color.lime : color.orange)
pbRow += 1
if pbFull
f_pbRow(pbPanel, pbRow, "OR high / low", orFormed ? f_pbPx(orHi) + " / " + f_pbPx(orLo) : "forming", color.white)
pbRow += 1
f_pbRow(pbPanel, pbRow, "OR mid · width", orFormed ? f_pbPx(pbMid) + " · " + f_pbPx(pbRange) : "-", color.white)
pbRow += 1
f_pbRow(pbPanel, pbRow, "IB high / low", ibFormed ? f_pbPx(ibHi) + " / " + f_pbPx(ibLo) : "forming", color.white)
pbRow += 1
f_pbRow(pbPanel, pbRow, "PSC", na(pbPsc) ? "-" : f_pbPx(pbPsc), pbPscColor)
pbRow += 1
f_pbRow(pbPanel, pbRow, "Context calls / puts", str.tostring(f_pbScore(1)) + "/3 · " + str.tostring(f_pbScore(-1)) + "/3", color.white)
pbRow += 1
f_pbRow(pbPanel, pbRow, "Entry window", pbWinTxt, pbInWin ? color.lime : color.silver)
pbRow += 1
// R1.4 daily levels
f_pbRow(pbPanel, pbRow, "Levels as of", not pbAnyDaily ? "not set" : str.format_time(pbLvlDate, "MM/dd", syminfo.timezone) + (pbLvlFresh ? " ✓ today" : " - UPDATE"), not pbAnyDaily ? color.silver : pbLvlFresh ? color.lime : color.orange)
pbRow += 1
if pbFull
pbDpTxt = (pbDP1 > 0 ? f_pbPx(pbDP1) : "") + (pbDP2 > 0 ? (pbDP1 > 0 ? " · " : "") + f_pbPx(pbDP2) : "") + (pbDP3 > 0 ? ((pbDP1 > 0 or pbDP2 > 0) ? " · " : "") + f_pbPx(pbDP3) : "")
f_pbRow(pbPanel, pbRow, "Max pain", f_pbDist(pbMaxPain), pbMaxPainColor)
pbRow += 1
f_pbRow(pbPanel, pbRow, "OI call", f_pbDist(pbCallOI), pbCallOIColor)
pbRow += 1
f_pbRow(pbPanel, pbRow, "OI put", f_pbDist(pbPutOI), pbPutOIColor)
pbRow += 1
f_pbRow(pbPanel, pbRow, "Dark pool", pbDpTxt == "" ? "-" : pbDpTxt, pbDPColor)
pbRow += 1
// ---- Panel 2 · Trade plan (R1.7) ----
if pbOn and pbShowPlanPanel and pbLastBar
int pbPr = 0
f_pbRow(pbPlanPanel, pbPr, "Trade plan", "1 contract · checklist decides", color.yellow)
pbPr += 1
if pbShowPlan
f_pbRow(pbPlanPanel, pbPr, "Call plan", orFormed ? "> " + f_pbPx(orHi) + " · stop " + f_pbPx(pbMid) + " · T1 " + f_pbPx(orHi + pbPlanR) : "after 8:45", pbCallOIColor)
pbPr += 1
f_pbRow(pbPlanPanel, pbPr, "Put plan", orFormed ? "< " + f_pbPx(orLo) + " · stop " + f_pbPx(pbMid) + " · T1 " + f_pbPx(orLo - pbPlanR) : "after 8:45", pbPutOIColor)
pbPr += 1
f_pbRow(pbPlanPanel, pbPr, "Sizing", "TC $" + str.tostring(pbTC, "#,###") + " · " + str.tostring(pbRiskPct, "0.0#") + "% → 1R cap $" + str.tostring(math.round(pbRiskCap)), color.white)
pbPr += 1
f_pbRow(pbPlanPanel, pbPr, "1R @ Δ" + str.tostring(pbPlanDelta, "0.00"), orFormed ? "$" + str.tostring(math.round(pbPlanRisk)) + (pbPlanRisk <= pbRiskCap ? " ✓" : " > cap") + " · max entry " + f_pbPx(pbMaxCall) + " / " + f_pbPx(pbMaxPut) : "-", not orFormed ? color.silver : pbPlanRisk <= pbRiskCap ? color.lime : color.orange)
pbPr += 1
f_pbRow(pbPlanPanel, pbPr, "Trade today", pbTradeTxt, pbTraded ? color.yellow : color.silver)
pbPr += 1
f_pbRow(pbPlanPanel, pbPr, "Open position", pbDir == 0 ? "-" : pbKind + " stop " + f_pbPx(pbPriceStop) + " · T1 " + f_pbPx(pbT1), pbDir == 0 ? color.silver : color.white)
pbPr += 1
f_pbRow(pbPlanPanel, pbPr, "Last exit", pbLastExit == "" ? "-" : pbLastExit, color.white)
pbPr += 1
//------------------------------------------------------
// PLAYBOOK ALERTS (webhook-ready JSON payloads)
// Webhook alerts: pick one of these conditions. {{time}} is UTC.
//------------------------------------------------------
alertcondition(pbEvE1Call, title="PB Entry 1 LONG (CALL)", message='{"content":"🟢 **SIGMA ANALYTICS ORB · ENTRY 1 LONG (CALL)**\n{{ticker}} | {{interval}}\nPrice: {{close}}\nRun the GO / NO-GO checklist\nTriggered: {{time}} UTC"}')
alertcondition(pbEvE1Put, title="PB Entry 1 SHORT (PUT)", message='{"content":"🔴 **SIGMA ANALYTICS ORB · ENTRY 1 SHORT (PUT)**\n{{ticker}} | {{interval}}\nPrice: {{close}}\nRun the GO / NO-GO checklist\nTriggered: {{time}} UTC"}')
alertcondition(pbEvE1Rej, title="PB Entry 1 not qualified", message='{"content":"⚪ **SIGMA ANALYTICS ORB · ENTRY 1 NOT QUALIFIED**\n{{ticker}} | {{interval}}\nPrice: {{close}}\nTriggered: {{time}} UTC"}')
alertcondition(pbEvE2, title="PB Entry 2 (paper)", message='{"content":"🟡 **SIGMA ANALYTICS ORB · ENTRY 2 (PAPER-TRACK)**\n{{ticker}} | {{interval}}\nPrice: {{close}}\nTriggered: {{time}} UTC"}')
alertcondition(pbEvE2Fail, title="PB Entry 2 setup failed", message='{"content":"⚪ **SIGMA ANALYTICS ORB · ENTRY 2 SETUP FAILED**\n{{ticker}} | {{interval}}\nPrice: {{close}}\nTriggered: {{time}} UTC"}')
alertcondition(pbEvExit, title="PB Exit", message='{"content":"🔵 **SIGMA ANALYTICS ORB · EXIT**\n{{ticker}} | {{interval}}\nPrice: {{close}}\nTriggered: {{time}} UTC"}')
//====================================================================
// END SIGMA ANALYTICS PLAYBOOK MODULE
//====================================================================