本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ─────────────────────────────────────────────────────────────────────────────
// Price Action Toolkit
// FVG · IFVG · Liquidity Pivots · HH/HL/LH/LL · Session Gaps · V/W/A/M Reversals
// Session Highs/Lows · Opening Range Highs/Lows · Premium/Discount Zones · HTF Liquidity
// All events are evaluated on bar close (no intrabar flicker, no repainting
// of confirmed events). Every element has its own alert condition.
// ─────────────────────────────────────────────────────────────────────────────
indicator("Price Action Toolkit", shorttitle = "PA Toolkit", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100)
// ═════════════════════════════ INPUTS ═════════════════════════════
const string G_STYLE = "◼ Style"
const string G_FVG = "◼ Fair Value Gaps"
const string G_LIQ = "◼ Liquidity Pivots"
const string G_MS = "◼ Market Structure"
const string G_GAP = "◼ Session Gaps"
const string G_PAT = "◼ Reversal Patterns"
// Style
bool monoFont = input.bool(true, "Monospace font", group = G_STYLE, tooltip = "Use a monospace font for all labels and captions on the chart. All other colors, sizes, offsets and transparencies are set in each element's own group.")
// Fair Value Gaps
bool showFvg = input.bool(true, "Show FVGs", group = G_FVG, tooltip = "A fair value gap is a three-candle imbalance: bullish when the low of candle 3 is above the high of candle 1, bearish when the high of candle 3 is below the low of candle 1. Zones extend until price closes through them.")
float fvgMinAtr = input.float(0.1, "Min FVG size (ATR)", minval = 0.0, step = 0.05, group = G_FVG, tooltip = "Ignore gaps smaller than this multiple of ATR(14). 0 shows every gap.")
int fvgMax = input.int(20, "Max active FVGs", minval = 1, maxval = 100, group = G_FVG, tooltip = "Maximum number of unbroken FVGs kept on the chart. The oldest is removed first.")
bool showIfvg = input.bool(true, "Show inverse FVGs", group = G_FVG, tooltip = "When price closes through an FVG, the zone flips polarity and becomes an inverse FVG (IFVG). Requires 'Show FVGs' to be on.")
int ifvgMax = input.int(10, "Max active IFVGs", minval = 1, maxval = 100, group = G_FVG, tooltip = "Maximum number of active IFVGs kept on the chart.")
int fvgOff = input.int(5, "Zone offset right (bars)", minval = 0, maxval = 200, group = G_FVG, tooltip = "How many candles active FVG and IFVG boxes extend to the right beyond the current candle. 0 = they end at the current candle. Broken zones always end at the candle that broke them.")
color fvgColBull = input.color(#00E5B0, "FVG colors", inline = "fvgc", group = G_FVG)
color fvgColBear = input.color(#FF2E63, "", inline = "fvgc", group = G_FVG, tooltip = "Bullish and bearish FVG color.")
int fvgFill = input.int(86, "FVG fill / border transparency", minval = 0, maxval = 100, inline = "fvgt", group = G_FVG)
int fvgBorder = input.int(50, "", minval = 0, maxval = 100, inline = "fvgt", group = G_FVG, tooltip = "Transparency of the FVG fill and of its outline. 0 = solid, 100 = invisible.")
color ifvgColBull = input.color(#3D8BFF, "IFVG colors", inline = "ifvgc", group = G_FVG)
color ifvgColBear = input.color(#FF9F1C, "", inline = "ifvgc", group = G_FVG, tooltip = "Bullish IFVG color (former bearish FVG, now support) and bearish IFVG color (former bullish FVG, now resistance).")
int ifvgFill = input.int(86, "IFVG fill / border transparency", minval = 0, maxval = 100, inline = "ifvgt", group = G_FVG)
int ifvgBorder = input.int(50, "", minval = 0, maxval = 100, inline = "ifvgt", group = G_FVG, tooltip = "Transparency of the IFVG fill and of its outline.")
bool fvgTxt = input.bool(true, "Show captions", inline = "fvgx", group = G_FVG)
string fvgTxtSizeIn = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large"], inline = "fvgx", group = G_FVG, tooltip = "Show the FVG / IFVG text inside the boxes, and its size.")
bool fvgKeepDead = input.bool(false, "Keep invalidated zones", inline = "fvgd", group = G_FVG)
int fvgDeadT = input.int(94, "", minval = 0, maxval = 100, inline = "fvgd", group = G_FVG, tooltip = "When on, broken FVGs and IFVGs stay on the chart as faded grey boxes; the number sets their fill transparency. When off, they are removed.")
// Liquidity
bool showLiq = input.bool(true, "Show liquidity pivots", group = G_LIQ, tooltip = "Swing highs (buy-side liquidity, BSL) and swing lows (sell-side liquidity, SSL). Lines extend until a wick trades through the level, which counts as a sweep.")
int liqLeft = input.int(5, "Pivot left bars", minval = 1, group = G_LIQ, tooltip = "Bars to the left that must be lower (for highs) or higher (for lows) than the pivot.")
int liqRight = input.int(5, "Pivot right bars", minval = 1, group = G_LIQ, tooltip = "Bars to the right needed to confirm the pivot. Higher values mean fewer, stronger pivots but a later confirmation.")
int liqMax = input.int(50, "Max active levels", minval = 1, maxval = 100, group = G_LIQ, tooltip = "Maximum number of unswept liquidity levels kept on the chart.")
bool liqKeepSwept = input.bool(true, "Keep swept levels", group = G_LIQ, tooltip = "When on, swept levels stay visible as dotted lines ending at the sweep candle.")
bool liqLabels = input.bool(true, "Show BSL/SSL labels", group = G_LIQ, tooltip = "Show a small BSL or SSL tag at each pivot.")
color liqCol = input.color(#C9D1D9, "Line color", inline = "liqc", group = G_LIQ)
int liqTransp = input.int(25, "", minval = 0, maxval = 100, inline = "liqc", group = G_LIQ, tooltip = "Color and transparency of active liquidity lines on the chart timeframe.")
string liqStyleIn = input.string("Solid", "Line style", options = ["Solid", "Dashed", "Dotted"], inline = "liqs", group = G_LIQ)
int liqWidth = input.int(1, "", minval = 1, maxval = 4, inline = "liqs", group = G_LIQ, tooltip = "Line style and width of active liquidity lines.")
int liqSweptT = input.int(60, "Swept line transparency", minval = 0, maxval = 100, group = G_LIQ, tooltip = "Transparency of swept levels (when 'Keep swept levels' is on). Also used by the HTF slots.")
int liqOff = input.int(5, "Line offset right (bars)", minval = 0, maxval = 200, group = G_LIQ, tooltip = "How many candles active liquidity lines extend beyond the current candle. Swept lines end at the sweep candle.")
string liqSideIn = input.string("Right", "Label side / size", options = ["Right", "Left"], inline = "liql", group = G_LIQ)
string liqLblSizeIn = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large"], inline = "liql", group = G_LIQ, tooltip = "Right: the BSL/SSL text sits at the right end of the line and moves with it. Left: it sits left of the pivot. Second field: text size.")
// Higher-timeframe liquidity
const string G_HTF = "◼ HTF Liquidity Pivots"
bool h1On = input.bool(true, "", inline = "h1a", group = G_HTF)
string h1Tf = input.timeframe("15", "", inline = "h1a", group = G_HTF)
color h1Col = input.color(#93C5FD, "", inline = "h1a", group = G_HTF, tooltip = "HTF slot 1: on/off, timeframe and color. A slot only draws when its timeframe is higher than the chart timeframe. All unswept pivots of the slot's timeframe are shown, including ones older than the chart history. Uses the switches 'Show liquidity pivots', 'Keep swept levels' and 'Show BSL/SSL labels' above.")
int h1L = input.int(5, "Left", minval = 1, inline = "h1b", group = G_HTF)
int h1R = input.int(3, "Right", minval = 1, inline = "h1b", group = G_HTF)
bool h1Al = input.bool(true, "Alert", inline = "h1b", group = G_HTF)
string h1St = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "h1b", group = G_HTF, tooltip = "HTF slot 1: pivot left and right bars, counted in candles of the slot's timeframe, include in alerts, and line style.")
bool h2On = input.bool(true, "", inline = "h2a", group = G_HTF)
string h2Tf = input.timeframe("60", "", inline = "h2a", group = G_HTF)
color h2Col = input.color(#C4B5FD, "", inline = "h2a", group = G_HTF, tooltip = "HTF slot 2: on/off, timeframe and color.")
int h2L = input.int(5, "Left", minval = 1, inline = "h2b", group = G_HTF)
int h2R = input.int(3, "Right", minval = 1, inline = "h2b", group = G_HTF)
bool h2Al = input.bool(true, "Alert", inline = "h2b", group = G_HTF)
string h2St = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "h2b", group = G_HTF, tooltip = "HTF slot 2: pivot left and right bars in the slot's timeframe, include in alerts, and line style.")
bool h3On = input.bool(true, "", inline = "h3a", group = G_HTF)
string h3Tf = input.timeframe("240", "", inline = "h3a", group = G_HTF)
color h3Col = input.color(#F9A8D4, "", inline = "h3a", group = G_HTF, tooltip = "HTF slot 3: on/off, timeframe and color.")
int h3L = input.int(5, "Left", minval = 1, inline = "h3b", group = G_HTF)
int h3R = input.int(3, "Right", minval = 1, inline = "h3b", group = G_HTF)
bool h3Al = input.bool(true, "Alert", inline = "h3b", group = G_HTF)
string h3St = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "h3b", group = G_HTF, tooltip = "HTF slot 3: pivot left and right bars in the slot's timeframe, include in alerts, and line style.")
bool h4On = input.bool(true, "", inline = "h4a", group = G_HTF)
string h4Tf = input.timeframe("D", "", inline = "h4a", group = G_HTF)
color h4Col = input.color(#F1F5F9, "", inline = "h4a", group = G_HTF, tooltip = "HTF slot 4: on/off, timeframe and color. Daily by default.")
int h4L = input.int(3, "Left", minval = 1, inline = "h4b", group = G_HTF)
int h4R = input.int(2, "Right", minval = 1, inline = "h4b", group = G_HTF)
bool h4Al = input.bool(true, "Alert", inline = "h4b", group = G_HTF)
string h4St = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "h4b", group = G_HTF, tooltip = "HTF slot 4: pivot left and right bars in the slot's timeframe, include in alerts, and line style.")
int htfMax = input.int(20, "HTF max levels per slot", minval = 1, maxval = 100, group = G_HTF, tooltip = "Maximum number of unswept pivot highs and, separately, pivot lows kept per HTF slot. The complete history of the slot's timeframe is scanned, so older unswept levels also appear on low chart timeframes such as 1m. If there are more, the oldest are dropped.")
int htfWidth = input.int(1, "HTF line width", minval = 1, maxval = 4, group = G_HTF, tooltip = "Line width for all HTF liquidity lines.")
int htfTransp = input.int(15, "HTF line transparency", minval = 0, maxval = 100, group = G_HTF, tooltip = "Transparency of active HTF liquidity lines. Swept lines use 'Swept line transparency' from Liquidity Pivots.")
int htfOff = input.int(5, "HTF line offset right (bars)", minval = 0, maxval = 200, group = G_HTF, tooltip = "How many chart candles active HTF liquidity lines extend beyond the current candle.")
string htfSideIn = input.string("Right", "HTF label side / size", options = ["Right", "Left"], inline = "htfl", group = G_HTF)
string htfLblSizeIn = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large"], inline = "htfl", group = G_HTF, tooltip = "Where the HTF BSL/SSL text sits and how large it is.")
// Market structure
bool showMs = input.bool(true, "Show HH / HL / LH / LL", group = G_MS, tooltip = "Labels each confirmed swing point relative to the previous one of the same kind: Higher High, Lower High, Higher Low, Lower Low.")
int msLen = input.int(5, "Swing length", minval = 1, group = G_MS, tooltip = "Bars on each side required to confirm a swing. Labels appear this many bars after the swing.")
bool msLines = input.bool(false, "Connect swings", group = G_MS, tooltip = "Draw a thin line between consecutive swing points.")
bool showShift = input.bool(true, "Highlight trend shift swings", group = G_MS, tooltip = "After a downtrend (latest high is a Lower High and latest low a Lower Low), the first Higher Low and the first Higher High are highlighted, numbered and drawn larger. After an uptrend, the same applies to the first Lower High and Lower Low. Works even when the regular HH/HL/LH/LL labels are off. A swing against the new direction before the count is reached cancels the shift, and the next counter-swing starts again at 1st.")
int shiftCount = input.int(1, "Swings to mark per type", minval = 1, maxval = 10, group = G_MS, tooltip = "How many of the new swings are highlighted after a trend shift, counted separately for highs and lows. 1 = only the 1st HL and 1st HH (or 1st LH and 1st LL). 2 = also the 2nd of each, and so on.")
color colShiftBull = input.color(#C6FF00, "Bullish shift color", group = G_MS, tooltip = "Color of highlighted Higher Lows and Higher Highs after a downtrend.")
color colShiftBear = input.color(#FF3D00, "Bearish shift color", group = G_MS, tooltip = "Color of highlighted Lower Highs and Lower Lows after an uptrend.")
color msColBull = input.color(#00E5B0, "HH/HL color", inline = "msc", group = G_MS)
color msColBear = input.color(#FF2E63, "LH/LL color", inline = "msc", group = G_MS, tooltip = "Colors of the regular structure labels.")
string msLblSizeIn = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal", "Large"], inline = "mss", group = G_MS)
string shiftSizeIn = input.string("Normal", "Shift label size", options = ["Tiny", "Small", "Normal", "Large"], inline = "mss", group = G_MS, tooltip = "Text size of the regular HH/HL/LH/LL labels and of the highlighted trend shift labels.")
color msLineCol = input.color(#8B949E, "Swing line color", inline = "msl", group = G_MS)
int msLineT = input.int(40, "", minval = 0, maxval = 100, inline = "msl", group = G_MS, tooltip = "Color and transparency of the 'Connect swings' lines.")
// Session gaps
bool showGap = input.bool(true, "Show session gaps", group = G_GAP, tooltip = "Gap between the last close of the previous trading day and the first open of the new day. The box shrinks as price fills it and disappears when fully filled. Best used on intraday charts.")
float gapMinPct = input.float(0.05, "Min gap size (%)", minval = 0.0, step = 0.01, group = G_GAP, tooltip = "Ignore gaps smaller than this percentage of the previous close. Useful for 24/7 markets, where day-to-day gaps are usually tiny.")
int gapMax = input.int(10, "Max open gaps", minval = 1, maxval = 100, group = G_GAP, tooltip = "Maximum number of unfilled gaps kept on the chart.")
color gapCol = input.color(#FFD60A, "Gap color", group = G_GAP, tooltip = "Color of the session gap boxes.")
int gapFill = input.int(86, "Fill / border transparency", minval = 0, maxval = 100, inline = "gapt", group = G_GAP)
int gapBorder = input.int(50, "", minval = 0, maxval = 100, inline = "gapt", group = G_GAP, tooltip = "Transparency of the gap fill and of its outline.")
bool gapTxt = input.bool(true, "Show captions", inline = "gapx", group = G_GAP)
string gapTxtSizeIn = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large"], inline = "gapx", group = G_GAP, tooltip = "Show the GAP text inside the boxes, and its size.")
bool gapKeepDead = input.bool(false, "Keep filled gaps", inline = "gapd", group = G_GAP)
int gapDeadT = input.int(94, "", minval = 0, maxval = 100, inline = "gapd", group = G_GAP, tooltip = "When on, filled gaps stay as faded grey boxes; the number sets their fill transparency.")
// Reversal patterns
bool showV = input.bool(true, "V-shape (bullish)", group = G_PAT, tooltip = "Sharp sell-off into a low, then a recovery. Only shown once a candle closes above the V neckline: the last lower high inside the sell-off (or, if there is none, the fallback level below). Signals a possible long after a decline.")
bool showW = input.bool(true, "W-shape (bullish)", group = G_PAT, tooltip = "Double bottom after a decline. Only shown once a candle closes above the neckline (the high between both bottoms).")
bool showA = input.bool(true, "A-shape (bearish)", group = G_PAT, tooltip = "Sharp rally into a high, then a drop (inverted V). Only shown once a candle closes below the A neckline: the last higher low inside the rally (or, if there is none, the fallback level below). Signals a possible short after a rise.")
bool showM = input.bool(true, "M-shape (bearish)", group = G_PAT, tooltip = "Double top after a rise. Only shown once a candle closes below the neckline (the low between both tops).")
int sensV = input.int(3, "Sensitivity V", minval = 1, maxval = 10, inline = "sens1", group = G_PAT)
int sensA = input.int(3, "A", minval = 1, maxval = 10, inline = "sens1", group = G_PAT, tooltip = "How sensitive each pattern is, from 1 (only large, clear patterns) to 10 (also small ones). 5 = the thresholds below as set. Each step down makes the required move and neckline distance about 30 % larger, each step up about 30 % smaller.")
int sensW = input.int(3, "Sensitivity W", minval = 1, maxval = 10, inline = "sens2", group = G_PAT)
int sensM = input.int(3, "M", minval = 1, maxval = 10, inline = "sens2", group = G_PAT, tooltip = "Same as above for W and M. Lower values filter out small double bottoms and tops.")
string patDisp = input.string("Lines + shading", "Pattern display", options = ["Lines + shading", "Candle + letter only"], group = G_PAT, tooltip = "Lines + shading: the confirmed pattern is drawn with its path, shaded body and neckline, plus the letter and the highlighted breakout candle. Candle + letter only: just the highlighted breakout candle and the letter, no lines. The candle highlight is always on in this mode.")
bool volConf = input.bool(true, "Volume confirmation", inline = "volc", group = G_PAT)
string volSym = input.string("★", "", options = ["★", "◆"], inline = "volc", group = G_PAT, tooltip = "Adds a star or diamond next to the pattern letter in the highlighted breakout candle when the breakout candle's volume is clearly above average. Bullish patterns: below the letter. Bearish patterns: above it. Symbols without volume data never get the marker.")
int volLen = input.int(20, "Volume average length", minval = 2, inline = "volp", group = G_PAT)
float volMult = input.float(1.5, "× average", minval = 1.0, step = 0.1, inline = "volp", group = G_PAT, tooltip = "The breakout candle counts as volume-confirmed when its volume is at least this multiple of the simple average volume of the last N candles. 1.5 = 50 % above average.")
int patLen = input.int(3, "Pattern pivot length", minval = 1, group = G_PAT, tooltip = "Bars on each side that define the turning points used by all four patterns.")
int vLook = input.int(15, "V/A: max bars of prior move", minval = 2, group = G_PAT, tooltip = "The move into the turning point must happen within this many bars. Smaller values only catch very fast moves.")
float vDepth = input.float(2.5, "V/A: min prior move (ATR)", minval = 0.1, step = 0.1, group = G_PAT, tooltip = "Minimum size of the move into the turning point, as a multiple of ATR(14).")
float vRecover = input.float(0.5, "V/A: fallback neckline (fraction)", minval = 0.1, maxval = 1.0, step = 0.05, group = G_PAT, tooltip = "Used only when the sell-off (rally) contains no lower high (higher low) to serve as neckline. The neckline is then placed at this share of the move, measured from the low (high). 0.5 = halfway back.")
float vMinNeck = input.float(1.0, "V/A: min neckline distance (ATR)", minval = 0.0, step = 0.1, group = G_PAT, tooltip = "Minimum distance between the V low (A high) and its neckline, as a multiple of ATR(14). Filters out flat, shallow turns.")
int trendLook = input.int(40, "W/M: prior move lookback", minval = 2, group = G_PAT, tooltip = "Bars before the first bottom (or top) that are checked for the preceding decline (or rise).")
float trendDepth = input.float(3.0, "W/M: min prior move (ATR)", minval = 0.1, step = 0.1, group = G_PAT, tooltip = "Minimum decline before a W, or rise before an M, as a multiple of ATR(14).")
float wTol = input.float(0.5, "W/M: max bottom/top difference (ATR)", minval = 0.0, step = 0.05, group = G_PAT, tooltip = "How close both bottoms (or tops) must be to each other, as a multiple of ATR(14).")
float wMinNeck = input.float(1.0, "W/M: min neckline distance (ATR)", minval = 0.0, step = 0.1, group = G_PAT, tooltip = "Minimum distance between the bottoms (or tops) and the neckline, as a multiple of ATR(14).")
int wMaxSpan = input.int(60, "W/M: max bars between bottoms/tops", minval = 2, group = G_PAT, tooltip = "Both bottoms (or tops) must lie within this many bars of each other.")
int wConfirm = input.int(20, "W/M: max bars to neckline break", minval = 1, group = G_PAT, tooltip = "After the V/A turning point or the second W/M bottom (top), price has this many bars to close beyond the neckline. Otherwise the pattern is dropped and nothing is drawn.")
color patColBull = input.color(#00E5B0, "V/W color", inline = "patc", group = G_PAT)
color patColBear = input.color(#FF2E63, "A/M color", inline = "patc", group = G_PAT, tooltip = "Line and label colors of the bullish (V, W) and bearish (A, M) patterns.")
int patWidth = input.int(2, "Pattern line width", minval = 1, maxval = 4, inline = "patw", group = G_PAT)
int patTransp = input.int(0, "", minval = 0, maxval = 100, inline = "patw", group = G_PAT, tooltip = "Width and transparency of the pattern lines.")
string patNeckIn = input.string("Solid", "Neckline style", options = ["Solid", "Dashed", "Dotted"], group = G_PAT, tooltip = "Line style of the neckline.")
string patLblSizeIn = input.string("Large", "Label size", options = ["Tiny", "Small", "Normal", "Large"], group = G_PAT, tooltip = "Text size of the V, W, A and M signal at the breakout candle.")
int patFillT = input.int(82, "Pattern fill transparency", minval = 0, maxval = 100, group = G_PAT, tooltip = "The area between the pattern and its neckline is shaded. 100 = no shading.")
bool patMarkBar = input.bool(true, "Highlight breakout candle", inline = "patb", group = G_PAT)
int patBgT = input.int(80, "", minval = 0, maxval = 100, inline = "patb", group = G_PAT, tooltip = "Colors the background of the candle whose close confirms the pattern. The number is the transparency. Always on in 'Candle + letter only' mode.")
// Session levels
const string G_SES = "◼ Session Levels"
const string G_OR = "◼ Opening Range"
bool showSH = input.bool(true, "Show session highs/lows", group = G_SES, tooltip = "Draws the high and low of each enabled session as a line. Every session is scanned completely, from its first to its last candle, on the current chart timeframe. Intraday charts only.")
string sesTzIn = input.string("America/New_York", "Time zone", options = ["America/New_York", "Europe/London", "Europe/Berlin", "Asia/Tokyo", "UTC", "Exchange"], group = G_SES, tooltip = "Time zone for all session times below. 'Exchange' uses the symbol's own exchange time zone.")
bool s1On = input.bool(true, "", inline = "s1", group = G_SES)
string s1Name = input.string("Asia", "", inline = "s1", group = G_SES)
string s1Ses = input.session("1900-0300:1234567", "", inline = "s1", group = G_SES)
bool s1Al = input.bool(true, "Alert", inline = "s1", group = G_SES)
color s1Col = input.color(#A78BFA, "", inline = "s1", group = G_SES, tooltip = "Session 1: on/off, name used in labels, time window, include in alerts, and color.")
bool s2On = input.bool(true, "", inline = "s2", group = G_SES)
string s2Name = input.string("London", "", inline = "s2", group = G_SES)
string s2Ses = input.session("0300-0930:1234567", "", inline = "s2", group = G_SES)
bool s2Al = input.bool(true, "Alert", inline = "s2", group = G_SES)
color s2Col = input.color(#22D3EE, "", inline = "s2", group = G_SES, tooltip = "Session 2: on/off, name used in labels, time window, include in alerts, and color.")
bool s3On = input.bool(true, "", inline = "s3", group = G_SES)
string s3Name = input.string("New York", "", inline = "s3", group = G_SES)
string s3Ses = input.session("0930-1600:1234567", "", inline = "s3", group = G_SES)
bool s3Al = input.bool(true, "Alert", inline = "s3", group = G_SES)
color s3Col = input.color(#E879F9, "", inline = "s3", group = G_SES, tooltip = "Session 3: on/off, name used in labels, time window, include in alerts, and color.")
bool s4On = input.bool(false, "", inline = "s4", group = G_SES)
string s4Name = input.string("Custom", "", inline = "s4", group = G_SES)
string s4Ses = input.session("0800-1200:1234567", "", inline = "s4", group = G_SES)
bool s4Al = input.bool(true, "Alert", inline = "s4", group = G_SES)
color s4Col = input.color(#94A3B8, "", inline = "s4", group = G_SES, tooltip = "Session 4: on/off, name used in labels, time window, include in alerts, and color.")
bool showDev = input.bool(true, "Show developing levels", group = G_SES, tooltip = "On: lines are drawn while the session is running and move with every new high or low. Off: lines only appear once the session has ended and its final high and low are known.")
string sesExt = input.string("Until next session", "Extend lines", options = ["Session only", "Until broken", "Until next session"], group = G_SES, tooltip = "Session only: the line ends with the session. Until broken: the line runs right until price breaks the level. Until next session: the line runs until the same session starts again.")
string sesStyleIn = input.string("Solid", "Line style", options = ["Solid", "Dashed", "Dotted"], group = G_SES, tooltip = "Line style for session highs and lows.")
int sesWidth = input.int(1, "Line width", minval = 1, maxval = 4, group = G_SES, tooltip = "Line width for session highs and lows.")
int sesTransp = input.int(0, "Line transparency", minval = 0, maxval = 100, group = G_SES, tooltip = "Transparency of session high/low lines. The color comes from each session slot.")
string sesLblMode = input.string("Name + Price", "Label content", options = ["None", "Name", "Price", "Name + Price"], group = G_SES, tooltip = "What the line labels show. Applies to session and opening range lines.")
string sesSideIn = input.string("Right", "Label side / size", options = ["Right", "Left"], inline = "sesl", group = G_SES)
string sesLblSizeIn = input.string("Small", "", options = ["Tiny", "Small", "Normal", "Large"], inline = "sesl", group = G_SES, tooltip = "Right: the text sits at the right end of the line and moves with it. Left: it sits left of where the level was set. Applies to session and opening range lines.")
int sesOff = input.int(5, "Line offset right (bars)", minval = 0, maxval = 200, group = G_SES, tooltip = "How many candles active session and opening range lines extend beyond the current candle.")
int sesKeep = input.int(3, "Sessions to keep", minval = 1, maxval = 50, group = G_SES, tooltip = "How many sessions per slot stay on the chart, including the current one. Older lines are removed.")
string breakMode = input.string("Close", "Break trigger", options = ["Close", "Wick"], group = G_SES, tooltip = "What counts as a break of a session or opening range level, for 'Until broken' and for alerts. Close: a candle closes beyond the level, reported at bar close. Wick: any trade beyond the level, reported immediately while the candle is still open.")
// Opening range
bool showOR = input.bool(true, "Show opening range", group = G_OR, tooltip = "High and low of the first minutes of every enabled session. Uses the session slots, time zone and label settings from 'Session Levels'.")
int orMin = input.int(15, "Opening range (minutes)", minval = 1, group = G_OR, tooltip = "Length of the opening range from the session open. Should be a multiple of the chart timeframe: on a 5-minute chart, 15 means the first three candles. If the chart timeframe is longer, the first candle is used.")
string orExt = input.string("Session end", "Extend lines", options = ["Session end", "Until broken", "Until next session"], group = G_OR, tooltip = "Session end: the lines end with the session. Until broken: each line runs until price breaks it. Until next session: the lines run until the same session starts again.")
string orStyleIn = input.string("Dashed", "Line style", options = ["Solid", "Dashed", "Dotted"], group = G_OR, tooltip = "Line style for opening range highs and lows.")
int orWidth = input.int(1, "Line width", minval = 1, maxval = 4, group = G_OR, tooltip = "Line width for opening range highs and lows.")
int orTransp = input.int(0, "Line transparency", minval = 0, maxval = 100, group = G_OR, tooltip = "Transparency of opening range lines. The color comes from each session slot.")
string sesTz = sesTzIn == "Exchange" ? syminfo.timezone : sesTzIn
// Premium / Discount
const string G_PD = "◼ Premium / Discount"
bool showPD = input.bool(true, "Show premium / discount zones", group = G_PD, tooltip = "Splits the current dealing range into premium (upper part, expensive), equilibrium (middle part) and discount (lower part, cheap). The heights of premium and discount are set in percent below.")
string pdMode = input.string("Session opening range", "Range source", options = ["Session opening range", "Swing range", "Fixed lookback"], group = G_PD, tooltip = "Session opening range: the range starts as the opening range of the currently running session and only moves out once price breaks the OR high or OR low; it then follows the new session high or low. Between sessions and while the next OR is still forming, the last range stays in place. Swing range: from the latest confirmed swing high to the latest confirmed swing low. Fixed lookback: highest high and lowest low of the last N candles.")
string pdSesSel = input.string("Latest active", "Session for range", options = ["Latest active", "Session 1", "Session 2", "Session 3", "Session 4"], group = G_PD, tooltip = "Which session from 'Session Levels' drives the 'Session opening range' source. Latest active: the most recently started session that is running and has a finished opening range. The OR length is the 'Opening range (minutes)' setting; it is tracked even when the OR lines themselves are hidden.")
int pdLen = input.int(10, "Swing length", minval = 1, group = G_PD, tooltip = "Bars on each side that confirm a swing for the 'Swing range' source.")
int pdLook = input.int(100, "Lookback bars", minval = 2, maxval = 5000, group = G_PD, tooltip = "Number of candles used by the 'Fixed lookback' source.")
float pdPremPct = input.float(25.0, "Premium height (%)", minval = 0.0, maxval = 100.0, step = 0.5, group = G_PD, tooltip = "Height of the red premium zone, measured down from the range high as a percentage of the full range. 25 = the upper quarter of the range is premium.")
float pdDiscPct = input.float(25.0, "Discount height (%)", minval = 0.0, maxval = 100.0, step = 0.5, group = G_PD, tooltip = "Height of the green discount zone, measured up from the range low as a percentage of the full range. 25 = the lower quarter is discount. Whatever is left in between is the grey equilibrium zone. If premium and discount add up to more than 100 %, both are scaled down proportionally so they meet without overlapping.")
color pdColP = input.color(#FF3B5C, "Premium", group = G_PD, tooltip = "Color of the premium zone.")
color pdColE = input.color(#8B949E, "Equilibrium", group = G_PD, tooltip = "Color of the equilibrium band.")
color pdColD = input.color(#00C27A, "Discount", group = G_PD, tooltip = "Color of the discount zone.")
int pdTransp = input.int(90, "Zone transparency", minval = 0, maxval = 100, group = G_PD, tooltip = "0 = solid, 100 = invisible.")
bool pdLabels = input.bool(true, "Show zone names", group = G_PD, tooltip = "Writes Premium, Equilibrium and Discount as plain text inside the zones.")
string pdTxtSizeIn = input.string("Small", "Zone name size", options = ["Tiny", "Small", "Normal", "Large"], group = G_PD, tooltip = "Text size of the zone names.")
string pdSideIn = input.string("Right", "Zone name side", options = ["Right", "Left"], group = G_PD, tooltip = "Whether the zone names are aligned to the right or left edge of the zones.")
int pdOff = input.int(5, "Zone offset right (bars)", minval = 0, maxval = 200, group = G_PD, tooltip = "How many candles the zones extend beyond the current candle.")
bool pdUsesOR = showPD and pdMode == "Session opening range"
bool needOR = showOR or pdUsesOR
// Pattern sensitivity factors (5 = 1.0; lower sensitivity = larger thresholds)
float fV = math.pow(1.3, 5 - sensV)
float fA = math.pow(1.3, 5 - sensA)
float fW = math.pow(1.3, 5 - sensW)
float fM = math.pow(1.3, 5 - sensM)
// Alerts
const string G_ALR = "◼ Alerts"
bool detailAlerts = input.bool(true, "Detailed slot alerts via alert()", group = G_ALR, tooltip = "Session and HTF slot alerts are combined into one condition each (for example 'Session · High broken (any slot)'), because TradingView limits a script to 64 plots and every alert condition counts as one. When this is on, the script also sends detailed messages that name the session or timeframe. To receive those, create an alert with the condition 'Any alert() function call'. Only slots with 'Alert' ticked are included in both.")
// Moving averages
const string G_MA = "◼ Moving Averages"
bool ma1On = input.bool(true, "MA 1", inline = "ma1a", group = G_MA)
string ma1Type = input.string("EMA", "", options = ["EMA", "SMA"], inline = "ma1a", group = G_MA)
int ma1Len = input.int(50, "", minval = 1, maxval = 5000, inline = "ma1a", group = G_MA)
float ma1Src = input.source(close, "", inline = "ma1a", group = G_MA, tooltip = "Moving average 1: on/off, type (EMA or SMA), length and source.")
color ma1Col = input.color(#38BDF8, "", inline = "ma1b", group = G_MA)
int ma1W = input.int(2, "", minval = 1, maxval = 4, inline = "ma1b", group = G_MA)
string ma1St = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "ma1b", group = G_MA, tooltip = "Moving average 1: color, line width and line style.")
bool ma2On = input.bool(true, "MA 2", inline = "ma2a", group = G_MA)
string ma2Type = input.string("EMA", "", options = ["EMA", "SMA"], inline = "ma2a", group = G_MA)
int ma2Len = input.int(200, "", minval = 1, maxval = 5000, inline = "ma2a", group = G_MA)
float ma2Src = input.source(close, "", inline = "ma2a", group = G_MA, tooltip = "Moving average 2: on/off, type (EMA or SMA), length and source.")
color ma2Col = input.color(#F5A524, "", inline = "ma2b", group = G_MA)
int ma2W = input.int(2, "", minval = 1, maxval = 4, inline = "ma2b", group = G_MA)
string ma2St = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "ma2b", group = G_MA, tooltip = "Moving average 2: color, line width and line style.")
// Parabolic SAR
const string G_SAR = "◼ Parabolic SAR"
bool showSar = input.bool(true, "Show PSAR", group = G_SAR, tooltip = "Parabolic SAR dots. Below price = uptrend, above price = downtrend. A flip to the other side signals a possible trend change.")
float sarStart = input.float(0.02, "Start", minval = 0.001, step = 0.001, group = G_SAR, tooltip = "Initial acceleration factor.")
float sarInc = input.float(0.02, "Increment", minval = 0.001, step = 0.001, group = G_SAR, tooltip = "How much the acceleration factor grows with every new extreme in trend direction.")
float sarMax = input.float(0.2, "Maximum", minval = 0.01, step = 0.01, group = G_SAR, tooltip = "Upper limit of the acceleration factor.")
color sarColUp = input.color(#00E5B0, "Up / down color", inline = "sarc", group = G_SAR)
color sarColDn = input.color(#FF2E63, "", inline = "sarc", group = G_SAR, tooltip = "Dot color while the SAR is below price (uptrend) and above price (downtrend).")
string sarStIn = input.string("Dots", "Marker / size", options = ["Dots", "Crosses"], inline = "sars", group = G_SAR)
int sarW = input.int(1, "", minval = 1, maxval = 4, inline = "sars", group = G_SAR, tooltip = "Marker shape and size.")
int sarT = input.int(0, "Transparency", minval = 0, maxval = 100, group = G_SAR, tooltip = "0 = solid, 100 = invisible.")
// ═════════════════════════════ TYPES ═════════════════════════════
type Zone
box bx
float top
float bot
bool bull
int born
bool touched = false
type Level
line ln
label lb
float price
bool isHigh
bool useTime = false
color col
int t
type Pattern
int x0
float y0
int x1
float y1
int xn
float yn
int x2
float y2
int start
type SLine
line ln
label lb
float price
bool isHigh
bool isOR
bool live
bool final
string name
string tag
type Sess
bool active = false
float hi
int hiX
float lo
int loX
SLine hiL
SLine loL
bool orDone = true
int orEndT
float orHi
float orLo
int orX
SLine orHiL
SLine orLoL
float wHi
float wLo
float wOrHi
float wOrLo
array<SLine> lines
// ═════════════════════════════ HELPERS ═════════════════════════════
styleOf(string s) =>
s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
szOf(string s) =>
s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : s == "Large" ? size.large : size.small
string fvgSz = szOf(fvgTxtSizeIn)
string liqSz = szOf(liqLblSizeIn)
string htfSz = szOf(htfLblSizeIn)
string msSz = szOf(msLblSizeIn)
string shiftSz = szOf(shiftSizeIn)
string gapSz = szOf(gapTxtSizeIn)
string patSz = szOf(patLblSizeIn)
string sesSz = szOf(sesLblSizeIn)
string pdSz = szOf(pdTxtSizeIn)
bool liqAtEnd = liqSideIn == "Right"
bool htfAtEnd = htfSideIn == "Right"
bool sesAtEnd = sesSideIn == "Right"
bool pdAtEnd = pdSideIn == "Right"
string fontF = monoFont ? font.family_monospace : font.family_default
ordinal(int n) =>
n == 1 ? "1st" : n == 2 ? "2nd" : n == 3 ? "3rd" : str.tostring(n) + "th"
color NONE = #00000000
newZone(float top, float bot, int left, bool bull, color c, string txt, int ext, int fillT, int bordT, string tsz) =>
bx = box.new(left, top, bar_index + ext, bot, border_color = color.new(c, bordT), border_width = 1, bgcolor = color.new(c, fillT), text = txt, text_size = tsz, text_color = color.new(c, 20), text_halign = text.align_right, text_valign = text.align_center, text_font_family = fontF)
Zone.new(bx, top, bot, bull, bar_index)
retire(Zone z, bool keep, int deadT) =>
if keep
box.set_right(z.bx, bar_index)
box.set_bgcolor(z.bx, color.new(chart.fg_color, deadT))
box.set_border_color(z.bx, color.new(chart.fg_color, 80))
box.set_text_color(z.bx, color.new(chart.fg_color, 70))
else
box.delete(z.bx)
trimZones(array<Zone> arr, int maxN) =>
while array.size(arr) > maxN
Zone old = array.shift(arr)
box.delete(old.bx)
bool patFull = patDisp == "Lines + shading"
// Volume confirmation of a pattern breakout
float volAvg = ta.sma(volume, volLen)
bool volHigh = volConf and not na(volume) and volume > 0 and not na(volAvg) and volume >= volAvg * volMult
sigText(string txt, bool bull) =>
string mk = volHigh ? volSym : ""
bull ? "▲\n" + txt + (mk != "" ? "\n" + mk : "") : (mk != "" ? mk + "\n" : "") + txt + "\n▼"
sigTip(string tip) =>
volHigh ? tip + " | volume " + str.tostring(volume / volAvg, "#.0") + "× average" : tip
drawWMLines(Pattern p, color c) =>
if not na(p.x0)
line.new(p.x0, p.y0, p.x1, p.y1, color = color.new(c, math.min(100, patTransp + 50)), width = patWidth)
array<chart.point> body = array.from(chart.point.from_index(p.x1, p.y1), chart.point.from_index(p.xn, p.yn), chart.point.from_index(p.x2, p.y2), chart.point.from_index(bar_index, p.yn), chart.point.from_index(p.x1, p.yn))
polyline.new(body, closed = true, line_color = NONE, fill_color = color.new(c, patFillT))
array<chart.point> path = array.from(chart.point.from_index(p.x1, p.y1), chart.point.from_index(p.xn, p.yn), chart.point.from_index(p.x2, p.y2), chart.point.from_index(bar_index, close))
polyline.new(path, line_color = color.new(c, patTransp), line_width = patWidth)
line.new(p.xn, p.yn, bar_index + 3, p.yn, color = color.new(c, patTransp), width = patWidth, style = styleOf(patNeckIn))
drawVALines(Pattern p, color c) =>
line.new(p.x0, p.y0, p.x1, p.y1, color = color.new(c, math.min(100, patTransp + 50)), width = patWidth)
array<chart.point> body = array.from(chart.point.from_index(p.xn, p.yn), chart.point.from_index(p.x1, p.y1), chart.point.from_index(bar_index, p.yn))
polyline.new(body, closed = true, line_color = NONE, fill_color = color.new(c, patFillT))
line.new(p.x1, p.y1, bar_index, close, color = color.new(c, patTransp), width = patWidth)
line.new(p.xn, p.yn, bar_index + 3, p.yn, color = color.new(c, patTransp), width = patWidth, style = styleOf(patNeckIn))
// Confirmed W / M: shaded body, solid path, neckline to the breakout, signal at the breakout candle
drawWM(Pattern p, color c, string txt, bool bull, string tip) =>
if patFull
drawWMLines(p, c)
label.new(bar_index, close, sigText(txt, bull), yloc = bull ? yloc.belowbar : yloc.abovebar, color = NONE, textcolor = c, style = bull ? label.style_label_up : label.style_label_down, size = patSz, text_font_family = fontF, tooltip = sigTip(tip))
// Confirmed V / A: x0/y0 = start of the move, x1/y1 = turning point, xn/yn = neckline
drawVA(Pattern p, color c, string txt, bool bull, string tip) =>
if patFull
drawVALines(p, c)
label.new(bar_index, close, sigText(txt, bull), yloc = bull ? yloc.belowbar : yloc.abovebar, color = NONE, textcolor = c, style = bull ? label.style_label_up : label.style_label_down, size = patSz, text_font_family = fontF, tooltip = sigTip(tip))
string sesStyle = styleOf(sesStyleIn)
string orStyle = styleOf(orStyleIn)
levelText(string name, string tag, float price) =>
string p = str.tostring(price, format.mintick)
sesLblMode == "Name" ? name + " " + tag : sesLblMode == "Price" ? p : name + " " + tag + " " + p
isBroken(float lvl, bool isHigh) =>
breakMode == "Close" ? (isHigh ? close > lvl : close < lvl) : (isHigh ? high > lvl : low < lvl)
newSLine(int x1, float price, bool isHigh, bool isOR, string name, color c) =>
string tag = isOR ? (isHigh ? "ORH" : "ORL") : (isHigh ? "H" : "L")
line ln = line.new(x1, price, bar_index + sesOff, price, color = color.new(c, isOR ? orTransp : sesTransp), style = isOR ? orStyle : sesStyle, width = isOR ? orWidth : sesWidth)
label lb = sesLblMode == "None" ? na : label.new(sesAtEnd ? bar_index + sesOff : x1, price, levelText(name, tag, price), color = NONE, textcolor = c, style = sesAtEnd ? label.style_label_left : label.style_label_right, size = sesSz, text_font_family = fontF)
SLine.new(ln, lb, price, isHigh, isOR, true, false, name, tag)
moveSLine(SLine sl, int x1, float price) =>
sl.price := price
line.set_xy1(sl.ln, x1, price)
line.set_xy2(sl.ln, bar_index + sesOff, price)
if not na(sl.lb)
label.set_xy(sl.lb, sesAtEnd ? bar_index + sesOff : x1, price)
label.set_text(sl.lb, levelText(sl.name, sl.tag, price))
setEnd(SLine sl, int x2) =>
line.set_x2(sl.ln, x2)
if not na(sl.lb) and sesAtEnd
label.set_x(sl.lb, x2)
completeOR(Sess s, string name, color c) =>
SLine h = newSLine(s.orX, s.orHi, true, true, name, c)
SLine l = newSLine(s.orX, s.orLo, false, true, name, c)
h.final := true
l.final := true
array.push(s.lines, h)
array.push(s.lines, l)
s.orHiL := h
s.orLoL := l
s.wOrHi := s.orHi
s.wOrLo := s.orLo
s.orDone := true
// Runs one session slot. Called on every bar so time() and history stay consistent.
runSess(Sess s, bool on, string sesStr, string name, color c) =>
bool inS = not na(time(timeframe.period, sesStr, sesTz))
bool prevIn = inS[1]
bool gapNew = time - time[1] > 4 * 3600000
bool hB = false
bool lB = false
bool oHB = false
bool oLB = false
// Intrabar check against the state of the last closed bar (Wick mode reports at once)
bool hNow = false
bool lNow = false
bool oHNow = false
bool oLNow = false
if on and timeframe.isintraday and breakMode == "Wick"
bool endBar = s.active and not inS and showSH
hNow := (not na(s.wHi) and high > s.wHi) or (endBar and high > s.hi)
lNow := (not na(s.wLo) and low < s.wLo) or (endBar and low < s.lo)
oHNow := not na(s.wOrHi) and high > s.wOrHi
oLNow := not na(s.wOrLo) and low < s.wOrLo
if on and timeframe.isintraday and barstate.isconfirmed
bool starts = inS and (not prevIn or gapNew)
bool ends = s.active and (not inS or starts)
// 1) Session finished: freeze its levels
if ends
s.active := false
if showSH
if na(s.hiL)
SLine nh = newSLine(s.hiX, s.hi, true, false, name, c)
SLine nl = newSLine(s.loX, s.lo, false, false, name, c)
array.push(s.lines, nh)
array.push(s.lines, nl)
s.hiL := nh
s.loL := nl
SLine h = s.hiL
SLine l = s.loL
setEnd(h, bar_index - 1)
setEnd(l, bar_index - 1)
h.final := true
l.final := true
if sesExt == "Session only"
h.live := false
l.live := false
s.wHi := s.hi
s.wLo := s.lo
s.hiL := na
s.loL := na
if not s.orDone
if showOR
completeOR(s, name, c)
else
s.orDone := true
if showOR
if orExt == "Session end" and not na(s.orHiL)
SLine oh = s.orHiL
SLine ol = s.orLoL
setEnd(oh, bar_index - 1)
setEnd(ol, bar_index - 1)
oh.live := false
ol.live := false
s.orHiL := na
s.orLoL := na
// 2) Break checks on finished levels
if not na(s.wHi) and isBroken(s.wHi, true)
hB := true
s.wHi := na
if not na(s.wLo) and isBroken(s.wLo, false)
lB := true
s.wLo := na
if not na(s.wOrHi) and isBroken(s.wOrHi, true)
oHB := true
s.wOrHi := na
if not na(s.wOrLo) and isBroken(s.wOrLo, false)
oLB := true
s.wOrLo := na
// 3) New session: stop 'until next session' lines, start tracking
if starts
for sl in s.lines
if sl.live and sl.final and (sl.isOR ? orExt == "Until next session" : sesExt == "Until next session")
setEnd(sl, bar_index - 1)
sl.live := false
s.active := true
s.hi := high
s.hiX := bar_index
s.lo := low
s.loX := bar_index
if showSH and showDev
SLine dh = newSLine(bar_index, high, true, false, name, c)
SLine dl = newSLine(bar_index, low, false, false, name, c)
array.push(s.lines, dh)
array.push(s.lines, dl)
s.hiL := dh
s.loL := dl
s.orDone := not needOR
s.orX := bar_index
s.orHi := high
s.orLo := low
s.orEndT := time + orMin * 60000
int maxL = sesKeep * ((showSH ? 2 : 0) + (showOR ? 2 : 0))
while array.size(s.lines) > maxL
SLine old = array.shift(s.lines)
line.delete(old.ln)
if not na(old.lb)
label.delete(old.lb)
// 4) Extend finished lines
for sl in s.lines
if sl.live and sl.final
string m = sl.isOR ? orExt : sesExt
if m == "Until broken" and isBroken(sl.price, sl.isHigh)
setEnd(sl, bar_index)
sl.live := false
else
setEnd(sl, bar_index + sesOff)
// 5) Running session: update high, low and opening range
if s.active and not starts
if high > s.hi
s.hi := high
s.hiX := bar_index
if low < s.lo
s.lo := low
s.loX := bar_index
if not s.orDone and time < s.orEndT
s.orHi := math.max(s.orHi, high)
s.orLo := math.min(s.orLo, low)
if not na(s.hiL)
moveSLine(s.hiL, s.hiX, s.hi)
moveSLine(s.loL, s.loX, s.lo)
if s.active and not s.orDone and (time_close >= s.orEndT or time >= s.orEndT)
if showOR
completeOR(s, name, c)
else
s.orDone := true
bool wick = breakMode == "Wick"
bool rH = wick ? hNow : hB
bool rL = wick ? lNow : lB
bool rOH = wick ? oHNow : oHB
bool rOL = wick ? oLNow : oLB
[rH, rL, rOH, rOL]
// ── HTF liquidity helpers
// Read-only sweep check against the levels as they stood at the last bar close.
// Runs on every tick, so sweep alerts fire the moment price trades through a level.
liqHit(array<Level> arr, bool wantHigh) =>
bool hit = false
if array.size(arr) > 0
for i = 0 to array.size(arr) - 1
Level lv = array.get(arr, i)
if lv.isHigh == wantHigh and (wantHigh ? high > lv.price : low < lv.price)
hit := true
break
hit
int htfOffMs = htfOff * timeframe.in_seconds() * 1000
tfText(string tf) =>
float m = str.tonumber(tf)
na(m) ? tf : m % 60 == 0 ? str.tostring(m / 60) + "H" : str.tostring(m) + "m"
// Runs in the HTF context and keeps every unswept pivot of that timeframe over its whole history.
// Only closed HTF bars are evaluated ([1]); combined with lookahead_on this does not repaint.
htfCalc(int L, int R, int maxN) =>
var array<float> hp = array.new<float>()
var array<int> ht = array.new<int>()
var array<float> lp = array.new<float>()
var array<int> lt = array.new<int>()
var int ver = 0
float ph = ta.pivothigh(high, L, R)
float pl = ta.pivotlow(low, L, R)
float ph1 = ph[1]
float pl1 = pl[1]
float hi1 = high[1]
float lo1 = low[1]
int pt1 = time[R + 1]
if not na(hi1)
if array.size(hp) > 0
for i = array.size(hp) - 1 to 0
if hi1 > array.get(hp, i)
array.remove(hp, i)
array.remove(ht, i)
ver += 1
if array.size(lp) > 0
for i = array.size(lp) - 1 to 0
if lo1 < array.get(lp, i)
array.remove(lp, i)
array.remove(lt, i)
ver += 1
if not na(ph1)
array.push(hp, ph1)
array.push(ht, pt1)
ver += 1
if array.size(hp) > maxN
array.shift(hp)
array.shift(ht)
if not na(pl1)
array.push(lp, pl1)
array.push(lt, pt1)
ver += 1
if array.size(lp) > maxN
array.shift(lp)
array.shift(lt)
[hp, ht, lp, lt, ver]
htfReq(string tf, int L, int R) =>
request.security(syminfo.tickerid, tf, htfCalc(L, R, htfMax), lookahead = barmerge.lookahead_on)
htfKey(int t, bool isHigh) =>
t * 2 + (isHigh ? 1 : 0)
// Intrabar sweep check against the HTF list, ignoring levels already swept on the chart
htfHit(array<float> px, array<int> tm, array<int> reg, bool isHigh) =>
bool hit = false
if not na(px)
for [i, v] in px
if (isHigh ? high > v : low < v) and not array.includes(reg, htfKey(array.get(tm, i), isHigh))
hit := true
break
hit
newHtfLine(float price, int t, bool isHigh, color c, string st, string tag) =>
line ln = line.new(t, price, time + htfOffMs, price, xloc = xloc.bar_time, color = color.new(c, htfTransp), style = st, width = htfWidth)
label lb = liqLabels ? label.new(htfAtEnd ? time + htfOffMs : t, price, tag + (isHigh ? " BSL" : " SSL"), xloc = xloc.bar_time, color = NONE, textcolor = c, style = htfAtEnd ? label.style_label_left : label.style_label_right, size = htfSz, text_font_family = fontF, tooltip = tag + (isHigh ? " buy-side liquidity (unswept swing high)" : " sell-side liquidity (unswept swing low)")) : na
Level.new(ln, lb, price, isHigh, true, c, t)
runHtf(array<Level> act, array<int> reg, bool on, array<float> hp, array<int> ht, array<float> lp, array<int> lt, bool changed, color c, string stIn, string tf) =>
var int lastHT = 0
var int lastLT = 0
bool nB = false
bool nS = false
bool sBNow = false
bool sSNow = false
if on
sBNow := htfHit(hp, ht, reg, true)
sSNow := htfHit(lp, lt, reg, false)
if on and barstate.isconfirmed and not na(hp) and not na(lp)
if changed
// new pivots since the last update (no alert on the initial load)
if array.size(ht) > 0 and array.last(ht) > lastHT
nB := lastHT > 0
lastHT := array.last(ht)
if array.size(lt) > 0 and array.last(lt) > lastLT
nS := lastLT > 0
lastLT := array.last(lt)
// forget chart-side sweeps the HTF list has caught up with
array<int> present = array.new<int>()
for [i, tv] in ht
array.push(present, htfKey(tv, true))
for [i, tv] in lt
array.push(present, htfKey(tv, false))
if array.size(reg) > 0
for i = array.size(reg) - 1 to 0
if not array.includes(present, array.get(reg, i))
array.remove(reg, i)
// redraw all active levels from the HTF list
while array.size(act) > 0
Level o = array.pop(act)
line.delete(o.ln)
if not na(o.lb)
label.delete(o.lb)
string tag = tfText(tf)
string st = styleOf(stIn)
for [i, v] in hp
int tv = array.get(ht, i)
if not array.includes(reg, htfKey(tv, true))
array.push(act, newHtfLine(v, tv, true, c, st, tag))
for [i, v] in lp
int tv = array.get(lt, i)
if not array.includes(reg, htfKey(tv, false))
array.push(act, newHtfLine(v, tv, false, c, st, tag))
// extend, or end at the sweep candle
if array.size(act) > 0
for i = array.size(act) - 1 to 0
Level lv = array.get(act, i)
bool swept = lv.isHigh ? high > lv.price : low < lv.price
int xEnd = swept ? time : time + htfOffMs
line.set_x2(lv.ln, xEnd)
if htfAtEnd and not na(lv.lb)
label.set_x(lv.lb, xEnd)
if swept
array.push(reg, htfKey(lv.t, lv.isHigh))
if liqKeepSwept
line.set_style(lv.ln, line.style_dotted)
line.set_color(lv.ln, color.new(lv.col, liqSweptT))
if not na(lv.lb)
label.set_textcolor(lv.lb, color.new(lv.col, liqSweptT))
else
line.delete(lv.ln)
if not na(lv.lb)
label.delete(lv.lb)
array.remove(act, i)
[nB, nS, sBNow, sSNow]
// ═════════════════════════════ SERIES (every bar) ═════════════════════════════
float atr = ta.atr(14)
float liqPH = ta.pivothigh(high, liqLeft, liqRight)
float liqPL = ta.pivotlow(low, liqLeft, liqRight)
float msPH = ta.pivothigh(high, msLen, msLen)
float msPL = ta.pivotlow(low, msLen, msLen)
float pPH = ta.pivothigh(high, patLen, patLen)
float pPL = ta.pivotlow(low, patLen, patLen)
float vHi = ta.highest(high, vLook)[patLen]
int vHiOff = ta.highestbars(high, vLook)[patLen]
float vLo = ta.lowest(low, vLook)[patLen]
int vLoOff = ta.lowestbars(low, vLook)[patLen]
float tHi = ta.highest(high, trendLook)[patLen]
int tHiOff = ta.highestbars(high, trendLook)[patLen]
float tLo = ta.lowest(low, trendLook)[patLen]
int tLoOff = ta.lowestbars(low, trendLook)[patLen]
float atrP = atr[patLen]
bool bullGap = low > high[2] and (low - high[2]) >= fvgMinAtr * atr
bool bearGap = high < low[2] and (low[2] - high) >= fvgMinAtr * atr
bool newDay = timeframe.change("D")
float prevC = close[1]
float pdPH = ta.pivothigh(high, pdLen, pdLen)
float pdPL = ta.pivotlow(low, pdLen, pdLen)
float pdHiLook = ta.highest(high, pdLook)
int pdHiOff = ta.highestbars(high, pdLook)
float pdLoLook = ta.lowest(low, pdLook)
int pdLoOff = ta.lowestbars(low, pdLook)
// ═════════════════════════════ STATE ═════════════════════════════
var array<Zone> fvgZones = array.new<Zone>()
var array<Zone> ifvgZones = array.new<Zone>()
var array<Zone> gapZones = array.new<Zone>()
var array<Level> liqLevels = array.new<Level>()
var float lastSH = na
var int hiType = 0
var int loType = 0
var int regime = 0
var bool bullAct = false
var bool bearAct = false
var int cHH = 0
var int cHL = 0
var int cLH = 0
var int cLL = 0
var float lastSL = na
var int lastSwX = na
var float lastSwY = na
var float wL0 = na
var int wL0X = na
var float wL1 = na
var int wL1X = na
var bool wL1Ok = false
var float wNk = na
var int wNkX = na
var Pattern wPend = na
var float mH0 = na
var int mH0X = na
var float mH1 = na
var int mH1X = na
var bool mH1Ok = false
var float mNk = na
var int mNkX = na
var Pattern mPend = na
var float lastPPH = na
var int lastPPHX = na
var float lastPPL = na
var int lastPPLX = na
var Pattern vPend = na
var Pattern aPend = na
// Alert flags (reset every bar)
bool aBullFvg = false
bool aBearFvg = false
bool aBullFvgRetest = false
bool aBearFvgRetest = false
bool aBullIfvg = false
bool aBearIfvg = false
bool aBullIfvgRetest = false
bool aBearIfvgRetest = false
bool aNewBsl = false
bool aNewSsl = false
bool aBslSweep = false
bool aSslSweep = false
bool aHH = false
bool aHL = false
bool aLH = false
bool aLL = false
bool a1stHL = false
bool a1stHH = false
bool a1stLH = false
bool a1stLL = false
bool aShiftBull = false
bool aShiftBear = false
bool aGapUp = false
bool aGapDown = false
bool aGapFill = false
bool aV = false
bool aW = false
bool aA = false
bool aM = false
bool aPrem = false
bool aDisc = false
bool aEq = false
var float pdTop = na
var float pdBot = na
var int pdTopX = na
var int pdBotX = na
var box pdBoxP = na
var box pdBoxE = na
var box pdBoxD = na
var int pdState = 0
// Liquidity sweeps are checked on every tick (before any bar-close update below)
bool liqBslNow = showLiq and liqHit(liqLevels, true)
bool liqSslNow = showLiq and liqHit(liqLevels, false)
// ═════════════════════════════ LOGIC (bar close only) ═════════════════════════════
if barstate.isconfirmed
// ── Inverse FVGs: update first, so zones created on this bar are not tested on the same bar
if showFvg and showIfvg and array.size(ifvgZones) > 0
for i = array.size(ifvgZones) - 1 to 0
Zone z = array.get(ifvgZones, i)
bool broken = z.bull ? close < z.bot : close > z.top
if broken
retire(z, fvgKeepDead, fvgDeadT)
array.remove(ifvgZones, i)
else
box.set_right(z.bx, bar_index + fvgOff)
if not z.touched and bar_index > z.born
if z.bull and low <= z.top
z.touched := true
aBullIfvgRetest := true
else if not z.bull and high >= z.bot
z.touched := true
aBearIfvgRetest := true
// ── FVGs: update, flip into IFVG on a close through the far edge
if showFvg and array.size(fvgZones) > 0
for i = array.size(fvgZones) - 1 to 0
Zone z = array.get(fvgZones, i)
bool broken = z.bull ? close < z.bot : close > z.top
if broken
retire(z, fvgKeepDead, fvgDeadT)
array.remove(fvgZones, i)
if showIfvg
if z.bull
array.push(ifvgZones, newZone(z.top, z.bot, bar_index, false, ifvgColBear, fvgTxt ? "IFVG" : "", fvgOff, ifvgFill, ifvgBorder, fvgSz))
aBearIfvg := true
else
array.push(ifvgZones, newZone(z.top, z.bot, bar_index, true, ifvgColBull, fvgTxt ? "IFVG" : "", fvgOff, ifvgFill, ifvgBorder, fvgSz))
aBullIfvg := true
else
box.set_right(z.bx, bar_index + fvgOff)
if not z.touched and bar_index > z.born
if z.bull and low <= z.top
z.touched := true
aBullFvgRetest := true
else if not z.bull and high >= z.bot
z.touched := true
aBearFvgRetest := true
trimZones(ifvgZones, ifvgMax)
// ── New FVGs
if showFvg
if bullGap
array.push(fvgZones, newZone(low, high[2], bar_index - 2, true, fvgColBull, fvgTxt ? "FVG" : "", fvgOff, fvgFill, fvgBorder, fvgSz))
aBullFvg := true
if bearGap
array.push(fvgZones, newZone(low[2], high, bar_index - 2, false, fvgColBear, fvgTxt ? "FVG" : "", fvgOff, fvgFill, fvgBorder, fvgSz))
aBearFvg := true
trimZones(fvgZones, fvgMax)
// ── Liquidity pivots
if showLiq
if array.size(liqLevels) > 0
for i = array.size(liqLevels) - 1 to 0
Level lv = array.get(liqLevels, i)
bool swept = lv.isHigh ? high > lv.price : low < lv.price
line.set_x2(lv.ln, swept ? bar_index : bar_index + liqOff)
if liqAtEnd and not na(lv.lb)
label.set_x(lv.lb, swept ? bar_index : bar_index + liqOff)
if swept
if lv.isHigh
aBslSweep := true
else
aSslSweep := true
if liqKeepSwept
line.set_style(lv.ln, line.style_dotted)
line.set_color(lv.ln, color.new(liqCol, liqSweptT))
if not na(lv.lb)
label.set_textcolor(lv.lb, color.new(liqCol, liqSweptT))
else
line.delete(lv.ln)
if not na(lv.lb)
label.delete(lv.lb)
array.remove(liqLevels, i)
if not na(liqPH)
int x = bar_index - liqRight
line ln = line.new(x, liqPH, bar_index + liqOff, liqPH, color = color.new(liqCol, liqTransp), style = styleOf(liqStyleIn), width = liqWidth)
label lb = liqLabels ? label.new(liqAtEnd ? bar_index + liqOff : x, liqPH, "BSL", color = NONE, textcolor = liqCol, style = liqAtEnd ? label.style_label_left : label.style_label_right, size = liqSz, text_font_family = fontF, tooltip = "Buy-side liquidity (swing high)") : na
array.push(liqLevels, Level.new(ln, lb, liqPH, true))
aNewBsl := true
if not na(liqPL)
int x = bar_index - liqRight
line ln = line.new(x, liqPL, bar_index + liqOff, liqPL, color = color.new(liqCol, liqTransp), style = styleOf(liqStyleIn), width = liqWidth)
label lb = liqLabels ? label.new(liqAtEnd ? bar_index + liqOff : x, liqPL, "SSL", color = NONE, textcolor = liqCol, style = liqAtEnd ? label.style_label_left : label.style_label_right, size = liqSz, text_font_family = fontF, tooltip = "Sell-side liquidity (swing low)") : na
array.push(liqLevels, Level.new(ln, lb, liqPL, false))
aNewSsl := true
while array.size(liqLevels) > liqMax
Level old = array.shift(liqLevels)
line.delete(old.ln)
if not na(old.lb)
label.delete(old.lb)
// ── Market structure + trend shift
if showMs or showShift
if not na(msPH)
int x = bar_index - msLen
if not na(lastSH)
bool isHH = msPH > lastSH
string typ = isHH ? "HH" : "LH"
bool marked = false
int nth = 0
if showShift
if isHH
if not bullAct and regime == -1
bullAct := true
cHH := 0
cHL := 0
bearAct := false
if bullAct
cHH += 1
nth := cHH
marked := cHH <= shiftCount
else
if not bearAct and regime == 1
bearAct := true
cLH := 0
cLL := 0
bullAct := false
if bearAct
cLH += 1
nth := cLH
marked := cLH <= shiftCount
hiType := isHH ? 1 : -1
if hiType == 1 and loType == 1
regime := 1
else if hiType == -1 and loType == -1
regime := -1
if marked
color sc = isHH ? colShiftBull : colShiftBear
label.new(x, msPH, ordinal(nth) + " " + typ, color = NONE, textcolor = sc, style = label.style_label_down, size = shiftSz, text_font_family = fontF, tooltip = ordinal(nth) + (isHH ? " Higher High after downtrend" : " Lower High after uptrend"))
if isHH
aShiftBull := true
a1stHH := nth == 1
else
aShiftBear := true
a1stLH := nth == 1
else if showMs
color c = isHH ? msColBull : msColBear
label.new(x, msPH, typ, color = NONE, textcolor = c, style = label.style_label_down, size = msSz, text_font_family = fontF, tooltip = isHH ? "Higher High" : "Lower High")
if showMs
if isHH
aHH := true
else
aLH := true
lastSH := msPH
if showMs and msLines and not na(lastSwX)
line.new(lastSwX, lastSwY, x, msPH, color = color.new(msLineCol, msLineT), width = 1)
lastSwX := x
lastSwY := msPH
if not na(msPL)
int x = bar_index - msLen
if not na(lastSL)
bool isHL = msPL > lastSL
string typ = isHL ? "HL" : "LL"
bool marked = false
int nth = 0
if showShift
if isHL
if not bullAct and regime == -1
bullAct := true
cHH := 0
cHL := 0
bearAct := false
if bullAct
cHL += 1
nth := cHL
marked := cHL <= shiftCount
else
if not bearAct and regime == 1
bearAct := true
cLH := 0
cLL := 0
bullAct := false
if bearAct
cLL += 1
nth := cLL
marked := cLL <= shiftCount
loType := isHL ? 1 : -1
if hiType == 1 and loType == 1
regime := 1
else if hiType == -1 and loType == -1
regime := -1
if marked
color sc = isHL ? colShiftBull : colShiftBear
label.new(x, msPL, ordinal(nth) + " " + typ, color = NONE, textcolor = sc, style = label.style_label_up, size = shiftSz, text_font_family = fontF, tooltip = ordinal(nth) + (isHL ? " Higher Low after downtrend" : " Lower Low after uptrend"))
if isHL
aShiftBull := true
a1stHL := nth == 1
else
aShiftBear := true
a1stLL := nth == 1
else if showMs
color c = isHL ? msColBull : msColBear
label.new(x, msPL, typ, color = NONE, textcolor = c, style = label.style_label_up, size = msSz, text_font_family = fontF, tooltip = isHL ? "Higher Low" : "Lower Low")
if showMs
if isHL
aHL := true
else
aLL := true
lastSL := msPL
if showMs and msLines and not na(lastSwX)
line.new(lastSwX, lastSwY, x, msPL, color = color.new(msLineCol, msLineT), width = 1)
lastSwX := x
lastSwY := msPL
// ── Session gaps
if showGap
if newDay and not na(prevC) and open != prevC
float gapPct = math.abs(open - prevC) / prevC * 100
if gapPct >= gapMinPct
bool up = open > prevC
array.push(gapZones, newZone(math.max(open, prevC), math.min(open, prevC), bar_index - 1, up, gapCol, gapTxt ? (up ? "GAP ▲" : "GAP ▼") : "", 0, gapFill, gapBorder, gapSz))
if up
aGapUp := true
else
aGapDown := true
trimZones(gapZones, gapMax)
if array.size(gapZones) > 0
for i = array.size(gapZones) - 1 to 0
Zone z = array.get(gapZones, i)
bool filled = z.bull ? low <= z.bot : high >= z.top
if filled
aGapFill := true
retire(z, gapKeepDead, gapDeadT)
array.remove(gapZones, i)
else
if z.bull and low < z.top
z.top := low
box.set_top(z.bx, low)
if not z.bull and high > z.bot
z.bot := high
box.set_bottom(z.bx, high)
box.set_right(z.bx, bar_index)
// ── V-shape (bullish): low after a sharp drop, confirmed only by a close above the neckline
if showV
if not na(pPL)
int px = bar_index - patLen
float drop = vHi - pPL
if drop >= vDepth * fV * atrP
int sx = bar_index - patLen + vHiOff
bool hasLH = not na(lastPPH) and lastPPHX > sx and lastPPHX < px and lastPPH > pPL
float nk = hasLH ? lastPPH : pPL + vRecover * drop
int nkx = hasLH ? lastPPHX : px
if nk - pPL >= vMinNeck * fV * atrP
vPend := Pattern.new(sx, vHi, px, pPL, nkx, nk, px, pPL, bar_index)
if not na(vPend)
if close > vPend.yn
drawVA(vPend, patColBull, "V", true, "V-shape confirmed: close above neckline (bullish)")
aV := true
vPend := na
else if low < vPend.y1 or bar_index - vPend.start > wConfirm
vPend := na
// ── A-shape (bearish): high after a sharp rally, confirmed only by a close below the neckline
if showA
if not na(pPH)
int px = bar_index - patLen
float rise = pPH - vLo
if rise >= vDepth * fA * atrP
int sx = bar_index - patLen + vLoOff
bool hasHL = not na(lastPPL) and lastPPLX > sx and lastPPLX < px and lastPPL < pPH
float nk = hasHL ? lastPPL : pPH - vRecover * rise
int nkx = hasHL ? lastPPLX : px
if pPH - nk >= vMinNeck * fA * atrP
aPend := Pattern.new(sx, vLo, px, pPH, nkx, nk, px, pPH, bar_index)
if not na(aPend)
if close < aPend.yn
drawVA(aPend, patColBear, "A", false, "A-shape confirmed: close below neckline (bearish)")
aA := true
aPend := na
else if high > aPend.y1 or bar_index - aPend.start > wConfirm
aPend := na
// Remember the latest pattern pivots (used as V/A necklines on later bars)
if not na(pPH)
lastPPH := pPH
lastPPHX := bar_index - patLen
if not na(pPL)
lastPPL := pPL
lastPPLX := bar_index - patLen
// ── W-shape (bullish double bottom)
if showW
if not na(pPH) and not na(wL1)
int px = bar_index - patLen
if px > wL1X and (na(wNk) or pPH > wNk)
wNk := pPH
wNkX := px
if not na(pPL)
int px = bar_index - patLen
bool matched = false
if not na(wL1) and wL1Ok and not na(wNk)
bool similar = math.abs(pPL - wL1) <= wTol * atrP
bool neckOk = wNk - math.max(pPL, wL1) >= wMinNeck * fW * atrP
bool spanOk = px - wL1X <= wMaxSpan
if similar and neckOk and spanOk
wPend := Pattern.new(wL0X, wL0, wL1X, wL1, wNkX, wNk, px, pPL, bar_index)
matched := true
if matched
wL1 := na
wL1X := na
wL1Ok := false
wNk := na
wNkX := na
else if na(wL1) or pPL < wL1 or px - wL1X > wMaxSpan
wL1 := pPL
wL1X := px
wL1Ok := tHi - pPL >= trendDepth * fW * atrP
wL0 := tHi
wL0X := bar_index - patLen + tHiOff
wNk := na
wNkX := na
if not na(wPend)
if close > wPend.yn
drawWM(wPend, patColBull, "W", true, "W-shape confirmed: close above neckline (bullish)")
aW := true
wPend := na
else if low < math.min(wPend.y1, wPend.y2) - wTol * atr or bar_index - wPend.start > wConfirm
wPend := na
// ── M-shape (bearish double top)
if showM
if not na(pPL) and not na(mH1)
int px = bar_index - patLen
if px > mH1X and (na(mNk) or pPL < mNk)
mNk := pPL
mNkX := px
if not na(pPH)
int px = bar_index - patLen
bool matched = false
if not na(mH1) and mH1Ok and not na(mNk)
bool similar = math.abs(pPH - mH1) <= wTol * atrP
bool neckOk = math.min(pPH, mH1) - mNk >= wMinNeck * fM * atrP
bool spanOk = px - mH1X <= wMaxSpan
if similar and neckOk and spanOk
mPend := Pattern.new(mH0X, mH0, mH1X, mH1, mNkX, mNk, px, pPH, bar_index)
matched := true
if matched
mH1 := na
mH1X := na
mH1Ok := false
mNk := na
mNkX := na
else if na(mH1) or pPH > mH1 or px - mH1X > wMaxSpan
mH1 := pPH
mH1X := px
mH1Ok := pPH - tLo >= trendDepth * fM * atrP
mH0 := tLo
mH0X := bar_index - patLen + tLoOff
mNk := na
mNkX := na
if not na(mPend)
if close < mPend.yn
drawWM(mPend, patColBear, "M", false, "M-shape confirmed: close below neckline (bearish)")
aM := true
mPend := na
else if high > math.max(mPend.y1, mPend.y2) + wTol * atr or bar_index - mPend.start > wConfirm
mPend := na
// ═════════════════════════════ HTF LIQUIDITY (every bar) ═════════════════════════════
var array<Level> htf1 = array.new<Level>()
var array<Level> htf2 = array.new<Level>()
var array<Level> htf3 = array.new<Level>()
var array<Level> htf4 = array.new<Level>()
var array<int> reg1 = array.new<int>()
var array<int> reg2 = array.new<int>()
var array<int> reg3 = array.new<int>()
var array<int> reg4 = array.new<int>()
[h1HP, h1HT, h1LP, h1LT, h1V] = htfReq(h1Tf, h1L, h1R)
[h2HP, h2HT, h2LP, h2LT, h2V] = htfReq(h2Tf, h2L, h2R)
[h3HP, h3HT, h3LP, h3LT, h3V] = htfReq(h3Tf, h3L, h3R)
[h4HP, h4HT, h4LP, h4LT, h4V] = htfReq(h4Tf, h4L, h4R)
int chartSec = timeframe.in_seconds()
bool h1Act = showLiq and h1On and timeframe.in_seconds(h1Tf) > chartSec
bool h2Act = showLiq and h2On and timeframe.in_seconds(h2Tf) > chartSec
bool h3Act = showLiq and h3On and timeframe.in_seconds(h3Tf) > chartSec
bool h4Act = showLiq and h4On and timeframe.in_seconds(h4Tf) > chartSec
// Redraw when the HTF list changed, or when a slot has nothing drawn yet
bool h1Chg = h1V != h1V[1] or array.size(htf1) == 0
bool h2Chg = h2V != h2V[1] or array.size(htf2) == 0
bool h3Chg = h3V != h3V[1] or array.size(htf3) == 0
bool h4Chg = h4V != h4V[1] or array.size(htf4) == 0
[h1NB, h1NS, h1SB, h1SS] = runHtf(htf1, reg1, h1Act, h1HP, h1HT, h1LP, h1LT, h1Chg, h1Col, h1St, h1Tf)
[h2NB, h2NS, h2SB, h2SS] = runHtf(htf2, reg2, h2Act, h2HP, h2HT, h2LP, h2LT, h2Chg, h2Col, h2St, h2Tf)
[h3NB, h3NS, h3SB, h3SS] = runHtf(htf3, reg3, h3Act, h3HP, h3HT, h3LP, h3LT, h3Chg, h3Col, h3St, h3Tf)
[h4NB, h4NS, h4SB, h4SS] = runHtf(htf4, reg4, h4Act, h4HP, h4HT, h4LP, h4LT, h4Chg, h4Col, h4St, h4Tf)
// ═════════════════════════════ SESSIONS (every bar) ═════════════════════════════
var Sess ses1 = Sess.new(lines = array.new<SLine>())
var Sess ses2 = Sess.new(lines = array.new<SLine>())
var Sess ses3 = Sess.new(lines = array.new<SLine>())
var Sess ses4 = Sess.new(lines = array.new<SLine>())
bool sesAny = showSH or showOR or pdUsesOR
[s1H, s1L, s1OH, s1OL] = runSess(ses1, sesAny and s1On, s1Ses, s1Name, s1Col)
[s2H, s2L, s2OH, s2OL] = runSess(ses2, sesAny and s2On, s2Ses, s2Name, s2Col)
[s3H, s3L, s3OH, s3OL] = runSess(ses3, sesAny and s3On, s3Ses, s3Name, s3Col)
[s4H, s4L, s4OH, s4OL] = runSess(ses4, sesAny and s4On, s4Ses, s4Name, s4Col)
// ═════════════════════════════ PREMIUM / DISCOUNT (bar close, after sessions) ═════════════════════════════
if barstate.isconfirmed
// ── Premium / Discount
if showPD
if pdMode == "Session opening range"
array<Sess> sArr = array.from(ses1, ses2, ses3, ses4)
array<bool> oArr = array.from(s1On, s2On, s3On, s4On)
int want = pdSesSel == "Session 1" ? 0 : pdSesSel == "Session 2" ? 1 : pdSesSel == "Session 3" ? 2 : pdSesSel == "Session 4" ? 3 : -1
Sess ps = na
int bx = -1
for k = 0 to 3
Sess cs = array.get(sArr, k)
if array.get(oArr, k) and cs.active and cs.orDone and (want == -1 ? cs.orX > bx : want == k)
ps := cs
bx := cs.orX
if not na(ps)
pdTop := ps.hi
pdBot := ps.lo
pdTopX := ps.orX
pdBotX := ps.orX
else if pdMode == "Swing range"
if not na(pdPH)
pdTop := pdPH
pdTopX := bar_index - pdLen
if not na(pdPL)
pdBot := pdPL
pdBotX := bar_index - pdLen
if not na(pdTop) and high > pdTop
pdTop := high
pdTopX := bar_index
if not na(pdBot) and low < pdBot
pdBot := low
pdBotX := bar_index
else
pdTop := pdHiLook
pdTopX := bar_index + pdHiOff
pdBot := pdLoLook
pdBotX := bar_index + pdLoOff
if not na(pdTop) and not na(pdBot) and pdTop > pdBot
float rng = pdTop - pdBot
float pSum = pdPremPct + pdDiscPct
float pPct = pSum > 100 ? pdPremPct * 100 / pSum : pdPremPct
float dPct = pSum > 100 ? pdDiscPct * 100 / pSum : pdDiscPct
float eqT = pdTop - rng * pPct / 100
float eqB = pdBot + rng * dPct / 100
int left = math.min(pdTopX, pdBotX)
int right = bar_index + pdOff
if na(pdBoxP)
pdBoxP := box.new(left, pdTop, right, eqT, border_color = NONE, border_width = 0, bgcolor = color.new(pdColP, pdTransp), text = pdLabels ? "Premium" : "", text_size = pdSz, text_color = color.new(pdColP, 30), text_halign = pdAtEnd ? text.align_right : text.align_left, text_valign = text.align_top, text_font_family = fontF)
pdBoxE := box.new(left, eqT, right, eqB, border_color = NONE, border_width = 0, bgcolor = color.new(pdColE, pdTransp), text = pdLabels ? "Equilibrium" : "", text_size = pdSz, text_color = color.new(pdColE, 30), text_halign = pdAtEnd ? text.align_right : text.align_left, text_valign = text.align_center, text_font_family = fontF)
pdBoxD := box.new(left, eqB, right, pdBot, border_color = NONE, border_width = 0, bgcolor = color.new(pdColD, pdTransp), text = pdLabels ? "Discount" : "", text_size = pdSz, text_color = color.new(pdColD, 30), text_halign = pdAtEnd ? text.align_right : text.align_left, text_valign = text.align_bottom, text_font_family = fontF)
else
box.set_lefttop(pdBoxP, left, pdTop)
box.set_rightbottom(pdBoxP, right, eqT)
box.set_lefttop(pdBoxE, left, eqT)
box.set_rightbottom(pdBoxE, right, eqB)
box.set_lefttop(pdBoxD, left, eqB)
box.set_rightbottom(pdBoxD, right, pdBot)
int st = close > eqT ? 1 : close < eqB ? -1 : 0
if st != pdState
if st == 1
aPrem := true
else if st == -1
aDisc := true
else
aEq := true
pdState := st
// ═════════════════════════════ MOVING AVERAGES ═════════════════════════════
// ta functions are computed on every bar, the selected type is picked afterwards
float ma1E = ta.ema(ma1Src, ma1Len)
float ma1S = ta.sma(ma1Src, ma1Len)
float ma2E = ta.ema(ma2Src, ma2Len)
float ma2S = ta.sma(ma2Src, ma2Len)
float ma1 = ma1Type == "EMA" ? ma1E : ma1S
float ma2 = ma2Type == "EMA" ? ma2E : ma2S
// Dashed = 2 bars drawn, 2 bars gap (line breaks at na). Dotted = small circles.
float ma1Plot = ma1On and not (ma1St == "Dashed" and bar_index % 4 >= 2) ? ma1 : na
float ma2Plot = ma2On and not (ma2St == "Dashed" and bar_index % 4 >= 2) ? ma2 : na
plot(ma1Plot, "MA 1", color = ma1Col, linewidth = ma1W, style = ma1St == "Dotted" ? plot.style_circles : plot.style_linebr)
plot(ma2Plot, "MA 2", color = ma2Col, linewidth = ma2W, style = ma2St == "Dotted" ? plot.style_circles : plot.style_linebr)
bool pxUpMa1 = ta.crossover(close, ma1)
bool pxDnMa1 = ta.crossunder(close, ma1)
bool pxUpMa2 = ta.crossover(close, ma2)
bool pxDnMa2 = ta.crossunder(close, ma2)
bool maGolden = ta.crossover(ma1, ma2)
bool maDeath = ta.crossunder(ma1, ma2)
// ═════════════════════════════ PARABOLIC SAR ═════════════════════════════
float sar = ta.sar(sarStart, sarInc, sarMax)
bool sarBull = close > sar
bool sarUp = sarBull and not sarBull[1]
bool sarDn = not sarBull and sarBull[1]
plot(showSar ? sar : na, "PSAR", color = color.new(sarBull ? sarColUp : sarColDn, sarT), linewidth = sarW, style = sarStIn == "Crosses" ? plot.style_cross : plot.style_circles)
// Breakout candle highlight for confirmed V/W (bullish) and A/M (bearish)
color patBg = not patMarkBar and patFull ? na : (aV or aW) ? color.new(patColBull, patBgT) : (aA or aM) ? color.new(patColBear, patBgT) : na
bgcolor(patBg, title = "Pattern breakout")
// ═════════════════════════════ ALERTS ═════════════════════════════
// Session and HTF slots: one combined condition each (plot limit), details via alert()
bool sesHiAny = (s1H and s1Al) or (s2H and s2Al) or (s3H and s3Al) or (s4H and s4Al)
bool sesLoAny = (s1L and s1Al) or (s2L and s2Al) or (s3L and s3Al) or (s4L and s4Al)
bool orHiAny = (s1OH and s1Al) or (s2OH and s2Al) or (s3OH and s3Al) or (s4OH and s4Al)
bool orLoAny = (s1OL and s1Al) or (s2OL and s2Al) or (s3OL and s3Al) or (s4OL and s4Al)
bool htfNBAny = (h1NB and h1Al) or (h2NB and h2Al) or (h3NB and h3Al) or (h4NB and h4Al)
bool htfNSAny = (h1NS and h1Al) or (h2NS and h2Al) or (h3NS and h3Al) or (h4NS and h4Al)
bool htfSBAny = (h1SB and h1Al) or (h2SB and h2Al) or (h3SB and h3Al) or (h4SB and h4Al)
bool htfSSAny = (h1SS and h1Al) or (h2SS and h2Al) or (h3SS and h3Al) or (h4SS and h4Al)
alertcondition(sesHiAny, "Session · High broken (any slot)", "{{ticker}} {{interval}}: Session high broken. Close {{close}}")
alertcondition(sesLoAny, "Session · Low broken (any slot)", "{{ticker}} {{interval}}: Session low broken. Close {{close}}")
alertcondition(orHiAny, "Session · OR high broken (any slot)", "{{ticker}} {{interval}}: Opening range high broken. Close {{close}}")
alertcondition(orLoAny, "Session · OR low broken (any slot)", "{{ticker}} {{interval}}: Opening range low broken. Close {{close}}")
alertcondition(htfNBAny, "HTF · New BSL (any slot)", "{{ticker}}: New HTF buy-side liquidity pivot")
alertcondition(htfNSAny, "HTF · New SSL (any slot)", "{{ticker}}: New HTF sell-side liquidity pivot")
alertcondition(htfSBAny, "HTF · BSL swept (any slot)", "{{ticker}} {{interval}}: HTF buy-side liquidity swept. High {{high}}")
alertcondition(htfSSAny, "HTF · SSL swept (any slot)", "{{ticker}} {{interval}}: HTF sell-side liquidity swept. Low {{low}}")
if detailAlerts
string px = " | " + syminfo.ticker + " " + timeframe.period + " | Close " + str.tostring(close, format.mintick)
if s1Al
if s1H
alert(s1Name + " high broken" + px, alert.freq_once_per_bar)
if s1L
alert(s1Name + " low broken" + px, alert.freq_once_per_bar)
if s1OH
alert(s1Name + " opening range high broken" + px, alert.freq_once_per_bar)
if s1OL
alert(s1Name + " opening range low broken" + px, alert.freq_once_per_bar)
if s2Al
if s2H
alert(s2Name + " high broken" + px, alert.freq_once_per_bar)
if s2L
alert(s2Name + " low broken" + px, alert.freq_once_per_bar)
if s2OH
alert(s2Name + " opening range high broken" + px, alert.freq_once_per_bar)
if s2OL
alert(s2Name + " opening range low broken" + px, alert.freq_once_per_bar)
if s3Al
if s3H
alert(s3Name + " high broken" + px, alert.freq_once_per_bar)
if s3L
alert(s3Name + " low broken" + px, alert.freq_once_per_bar)
if s3OH
alert(s3Name + " opening range high broken" + px, alert.freq_once_per_bar)
if s3OL
alert(s3Name + " opening range low broken" + px, alert.freq_once_per_bar)
if s4Al
if s4H
alert(s4Name + " high broken" + px, alert.freq_once_per_bar)
if s4L
alert(s4Name + " low broken" + px, alert.freq_once_per_bar)
if s4OH
alert(s4Name + " opening range high broken" + px, alert.freq_once_per_bar)
if s4OL
alert(s4Name + " opening range low broken" + px, alert.freq_once_per_bar)
if h1Al
if h1NB
alert("New " + tfText(h1Tf) + " BSL" + px, alert.freq_once_per_bar)
if h1NS
alert("New " + tfText(h1Tf) + " SSL" + px, alert.freq_once_per_bar)
if h1SB
alert(tfText(h1Tf) + " BSL swept" + px, alert.freq_once_per_bar)
if h1SS
alert(tfText(h1Tf) + " SSL swept" + px, alert.freq_once_per_bar)
if h2Al
if h2NB
alert("New " + tfText(h2Tf) + " BSL" + px, alert.freq_once_per_bar)
if h2NS
alert("New " + tfText(h2Tf) + " SSL" + px, alert.freq_once_per_bar)
if h2SB
alert(tfText(h2Tf) + " BSL swept" + px, alert.freq_once_per_bar)
if h2SS
alert(tfText(h2Tf) + " SSL swept" + px, alert.freq_once_per_bar)
if h3Al
if h3NB
alert("New " + tfText(h3Tf) + " BSL" + px, alert.freq_once_per_bar)
if h3NS
alert("New " + tfText(h3Tf) + " SSL" + px, alert.freq_once_per_bar)
if h3SB
alert(tfText(h3Tf) + " BSL swept" + px, alert.freq_once_per_bar)
if h3SS
alert(tfText(h3Tf) + " SSL swept" + px, alert.freq_once_per_bar)
if h4Al
if h4NB
alert("New " + tfText(h4Tf) + " BSL" + px, alert.freq_once_per_bar)
if h4NS
alert("New " + tfText(h4Tf) + " SSL" + px, alert.freq_once_per_bar)
if h4SB
alert(tfText(h4Tf) + " BSL swept" + px, alert.freq_once_per_bar)
if h4SS
alert(tfText(h4Tf) + " SSL swept" + px, alert.freq_once_per_bar)
alertcondition(aBullFvg, "FVG · Bullish formed", "{{ticker}} {{interval}}: Bullish FVG formed. Close {{close}}")
alertcondition(aBearFvg, "FVG · Bearish formed", "{{ticker}} {{interval}}: Bearish FVG formed. Close {{close}}")
alertcondition(aBullFvgRetest, "FVG · Bullish retest", "{{ticker}} {{interval}}: Price retested a bullish FVG. Close {{close}}")
alertcondition(aBearFvgRetest, "FVG · Bearish retest", "{{ticker}} {{interval}}: Price retested a bearish FVG. Close {{close}}")
alertcondition(aBullIfvg, "IFVG · Bullish formed", "{{ticker}} {{interval}}: Bearish FVG broken, bullish IFVG formed. Close {{close}}")
alertcondition(aBearIfvg, "IFVG · Bearish formed", "{{ticker}} {{interval}}: Bullish FVG broken, bearish IFVG formed. Close {{close}}")
alertcondition(aBullIfvgRetest, "IFVG · Bullish retest", "{{ticker}} {{interval}}: Price retested a bullish IFVG. Close {{close}}")
alertcondition(aBearIfvgRetest, "IFVG · Bearish retest", "{{ticker}} {{interval}}: Price retested a bearish IFVG. Close {{close}}")
alertcondition(aNewBsl, "Liquidity · New BSL", "{{ticker}} {{interval}}: New buy-side liquidity pivot. Close {{close}}")
alertcondition(aNewSsl, "Liquidity · New SSL", "{{ticker}} {{interval}}: New sell-side liquidity pivot. Close {{close}}")
alertcondition(liqBslNow, "Liquidity · BSL swept", "{{ticker}} {{interval}}: Buy-side liquidity swept. High {{high}}")
alertcondition(liqSslNow, "Liquidity · SSL swept", "{{ticker}} {{interval}}: Sell-side liquidity swept. Low {{low}}")
alertcondition(aHH, "Structure · Higher High", "{{ticker}} {{interval}}: Higher High confirmed")
alertcondition(aHL, "Structure · Higher Low", "{{ticker}} {{interval}}: Higher Low confirmed")
alertcondition(aLH, "Structure · Lower High", "{{ticker}} {{interval}}: Lower High confirmed")
alertcondition(aLL, "Structure · Lower Low", "{{ticker}} {{interval}}: Lower Low confirmed")
alertcondition(a1stHL, "Shift · 1st HL after downtrend", "{{ticker}} {{interval}}: First Higher Low after downtrend")
alertcondition(a1stHH, "Shift · 1st HH after downtrend", "{{ticker}} {{interval}}: First Higher High after downtrend")
alertcondition(a1stLH, "Shift · 1st LH after uptrend", "{{ticker}} {{interval}}: First Lower High after uptrend")
alertcondition(a1stLL, "Shift · 1st LL after uptrend", "{{ticker}} {{interval}}: First Lower Low after uptrend")
alertcondition(aShiftBull, "Shift · Any marked bullish swing", "{{ticker}} {{interval}}: Highlighted bullish swing after downtrend")
alertcondition(aShiftBear, "Shift · Any marked bearish swing", "{{ticker}} {{interval}}: Highlighted bearish swing after uptrend")
alertcondition(aGapUp, "Gap · Gap up", "{{ticker}} {{interval}}: New session opened with a gap up. Open {{open}}")
alertcondition(aGapDown, "Gap · Gap down", "{{ticker}} {{interval}}: New session opened with a gap down. Open {{open}}")
alertcondition(aGapFill, "Gap · Gap filled", "{{ticker}} {{interval}}: A session gap was filled. Close {{close}}")
alertcondition(aV, "Reversal · V-shape (long)", "{{ticker}} {{interval}}: V-shape reversal after decline. Close {{close}}")
alertcondition(aW, "Reversal · W-shape (long)", "{{ticker}} {{interval}}: W-shape confirmed, neckline broken. Close {{close}}")
alertcondition(aA, "Reversal · A-shape (short)", "{{ticker}} {{interval}}: A-shape reversal after rally. Close {{close}}")
alertcondition(aM, "Reversal · M-shape (short)", "{{ticker}} {{interval}}: M-shape confirmed, neckline broken. Close {{close}}")
alertcondition(aPrem, "PD · Entered premium", "{{ticker}} {{interval}}: Price closed in the premium zone. Close {{close}}")
alertcondition(aEq, "PD · Entered equilibrium", "{{ticker}} {{interval}}: Price closed in the equilibrium band. Close {{close}}")
alertcondition(aDisc, "PD · Entered discount", "{{ticker}} {{interval}}: Price closed in the discount zone. Close {{close}}")
alertcondition(ma1On and pxUpMa1, "MA · Close crosses above MA 1", "{{ticker}} {{interval}}: Close crossed above MA 1. Close {{close}}")
alertcondition(ma1On and pxDnMa1, "MA · Close crosses below MA 1", "{{ticker}} {{interval}}: Close crossed below MA 1. Close {{close}}")
alertcondition(ma2On and pxUpMa2, "MA · Close crosses above MA 2", "{{ticker}} {{interval}}: Close crossed above MA 2. Close {{close}}")
alertcondition(ma2On and pxDnMa2, "MA · Close crosses below MA 2", "{{ticker}} {{interval}}: Close crossed below MA 2. Close {{close}}")
alertcondition(ma1On and ma2On and maGolden, "MA · MA 1 crosses above MA 2", "{{ticker}} {{interval}}: MA 1 crossed above MA 2")
alertcondition(ma1On and ma2On and maDeath, "MA · MA 1 crosses below MA 2", "{{ticker}} {{interval}}: MA 1 crossed below MA 2")
alertcondition(showSar and sarUp, "PSAR · Flip to uptrend", "{{ticker}} {{interval}}: PSAR flipped below price (uptrend). Close {{close}}")
alertcondition(showSar and sarDn, "PSAR · Flip to downtrend", "{{ticker}} {{interval}}: PSAR flipped above price (downtrend). Close {{close}}")
alertcondition((aV or aW) and volHigh, "Reversal · Volume-confirmed V/W (long)", "{{ticker}} {{interval}}: Bullish pattern breakout with above-average volume. Close {{close}}")
alertcondition((aA or aM) and volHigh, "Reversal · Volume-confirmed A/M (short)", "{{ticker}} {{interval}}: Bearish pattern breakout with above-average volume. Close {{close}}")