本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © YOUR_TRADINGVIEW_USERNAME
//@version=6
indicator("Session Volume Profile + Extended Levels", "SVP+", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
// ============================================================
// INPUTS
// ============================================================
grpGen = "General"
grpProf = "Profile"
grpLvl = "Levels"
grpNaked = "Naked POCs"
grpExt = "Extended Levels"
grpSess = "Sessions"
grpKey = "Daily / Weekly Levels"
grpBos = "Structure Break Signals"
grpAlert = "Alerts"
profilePerInput = input.string("Sessions", "Profile Per", options = ["Sessions", "Day"], tooltip = "SESSIONS splits the trading day into Asia 18:00-03:00, London 03:00-09:30 and New York 09:30-17:00, New York time.\n\nDAY uses the full 18:00-17:00 trading day as one profile.", group = grpGen)
profilesToShowInput = input.int(3, "Profiles to Show", minval = 1, maxval = 10, tooltip = "How many completed profiles stay drawn. Older ones are removed with their lines and labels.", group = grpGen)
showDevelopingInput = input.bool(true, "Show developing profile", tooltip = "Draw the session still trading, rebuilt from the candles so far and updated as each new candle prints.\n\nThe developing profile changes until its session ends. Completed profiles never change.", group = grpGen)
resolutionInput = input.string("Normal", "Resolution", options = ["Low", "Normal", "High"], tooltip = "How many equal price rows the session range is split into: Low 24, Normal 40, High 60.\n\nMore rows locate the POC more precisely and cost more to compute.", group = grpProf)
widthPctInput = input.int(40, "Width (%)", minval = 5, maxval = 100, step = 5, tooltip = "How far the busiest row reaches to the right, as a percentage of the session's own width in bars. Every other row is scaled against it.", group = grpProf)
showHistogramInput = input.bool(true, "Histogram", inline = "hist", group = grpProf)
histColorInput = input.color(color.new(#787b86, 70), "", inline = "hist", group = grpProf)
vaColorInput = input.color(color.new(#4985e7, 60), "Value Area", inline = "hist", group = grpProf)
showPocInput = input.bool(true, "POC", inline = "poc", group = grpLvl)
pocColorInput = input.color(#f0a93b, "", inline = "poc", group = grpLvl)
pocStyleInput = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], inline = "poc", group = grpLvl)
showVaInput = input.bool(true, "VAH / VAL", inline = "va", group = grpLvl)
vaLineColorInput = input.color(#3c6ef0, "", inline = "va", group = grpLvl)
vaStyleInput = input.string("Dotted", "", options = ["Solid", "Dashed", "Dotted"], inline = "va", group = grpLvl)
showLabelsInput = input.bool(true, "Labels", inline = "lab", group = grpLvl)
labelGapAtrInput = input.float(0.4, " ↳ Minimum Label Spacing (ATR)", minval = 0.0, maxval = 5.0, step = 0.1, tooltip = "Minimum vertical gap between labels that would otherwise sit on top of each other, as a multiple of ATR.\n\nWhen several levels land at nearly the same price their names overlap into an unreadable smudge. The labels are nudged apart just enough to separate; the LINES stay at their true prices, so nothing is misreported — only the text moves.\n\nMeasured in ATR rather than ticks so the spacing tracks the instrument and the volatility, which is roughly how much price fits on screen. Raise it if names still touch, lower it if they drift too far from their lines.\n\nSet to 0 to leave every label exactly on its level.", group = grpLvl)
labelSizeInput = input.string("Small", "", options = ["Tiny", "Small", "Normal"], inline = "lab", group = grpLvl)
nakedCountInput = input.int(3, "Naked POCs to Show", minval = 0, maxval = 20, tooltip = "When a session ends its POC is stored. It is extended to the right until a later candle trades through it, and is then removed.\n\nThese are the untouched POCs from earlier sessions.", group = grpNaked)
nakedColorInput = input.color(#f0a93b, "", inline = "nk", group = grpNaked)
nakedStyleInput = input.string("Dashed", "", options = ["Solid", "Dashed", "Dotted"], inline = "nk", group = grpNaked)
extCountInput = input.int(2, "Sessions Carried Forward", minval = 0, maxval = 10, tooltip = "How many recent completed sessions keep their POC, VAH and VAL reaching to the right.\n\nNothing new is drawn for these: the session's OWN level line is extended and its label travels with it, so a carried level is the same line you already had, only longer. A level that is not drawn cannot be carried, so this follows the POC and VAH / VAL toggles above.\n\nUnlike naked POCs these are NOT removed when price trades through them. A level price has already visited is still a level, and the alert re-arms once price closes clear of it so a second visit reports as well.\n\nHeld to the number of profiles shown: a session stops being carried before its profile is retired.", group = grpExt)
extShowPocInput = input.bool(true, "Carry POC", inline = "e1", group = grpExt)
extShowVaInput = input.bool(true, "Carry VAH / VAL", inline = "e1", group = grpExt)
extendBarsInput = input.int(20, "Extend Past Price (bars)", minval = 0, maxval = 200, group = grpExt)
extTapTicksInput = input.int(2, "Tap Tolerance (ticks)", minval = 0, maxval = 50, tooltip = "How close a candle's range must come to count as a tap.", group = grpExt)
extRearmTicksInput = input.int(8, "Re-arm Distance (ticks)", minval = 1, maxval = 200, tooltip = "How far price must close away from a level before another tap of it can alert again.\n\nWithout this a level would fire on every bar while price sat on it.", group = grpExt)
extCooldownInput = input.int(30, "Alert Cooldown (minutes)", minval = 0, maxval = 480, tooltip = "After a level alerts, that level stays quiet for this long.\n\nPER LEVEL, not global: the NY VAL alerting does not silence the Asia POC. Every other level keeps reporting normally throughout.\n\nThis sits on top of the re-arm distance above, and the two answer different problems. Re-arm is spatial — it stops a level firing repeatedly while price sits on it. The cooldown is temporal — it stops a level firing repeatedly while price works back and forth across it, closing clear each time and legitimately re-arming.\n\nMeasured in clock time rather than bars, so the figure means the same on any chart timeframe and a cooldown running into a session break expires on its own instead of carrying into the next open.\n\nWhat is held back is only the notification. The level still disarms and re-arms underneath exactly as before, so a tap during a cooldown cannot leave it stuck armed.\n\nThe clock starts only when an alert is actually SENT, so a tap outside your windows does not quietly silence the level for the next half hour.\n\n0 disables it.", group = grpExt)
useSessInput = input.bool(true, "Gate Alerts by Session", tooltip = "Restrict ALERTS to your own trading windows.\n\nProfiles, levels, naked POCs and carried levels are built and tracked around the clock, so the chart is right whenever you look at it and a level formed overnight is correct the moment a window opens. What the gate holds back is only the notification.\n\nThe tap itself is still recorded outside the windows: a carried level touched at 04:00 disarms and re-arms as normal, it simply does not alert. So a level is not left permanently armed by an overnight visit you were never told about.", group = grpSess)
sess1Input = input.session("1800-0000", "Window 1 (New York)", group = grpSess)
sess2Input = input.session("0700-1600", "Window 2 (New York)", group = grpSess)
showPdInput = input.bool(true, "Previous Day High / Low", inline = "k1", tooltip = "The previous DAILY bar's high and low, taken with lookahead on and read one bar back, which is the non-repainting form: the value is the completed prior day and never changes under you.\n\nOn futures a daily bar follows the exchange session, so the previous day runs from the overnight open rather than from midnight.\n\nA level that is not shown is not tracked either, so hiding these also stops them taking taps or producing signals.", group = grpKey)
pdColorInput = input.color(#9c27b0, "", inline = "k1", group = grpKey)
showPwInput = input.bool(true, "Previous Week High / Low", inline = "k2", group = grpKey)
pwColorInput = input.color(#00897b, "", inline = "k2", group = grpKey)
keyStyleInput = input.string("Dashed", "Line Style", options = ["Solid", "Dashed", "Dotted"], group = grpKey)
keyBosInput = input.bool(true, "Feed structure break signals", tooltip = "Let taps of these levels arm reversal setups, exactly as a carried level or naked POC does.\n\nThese are a different KIND of level from the profile ones. A session POC or value area edge is where volume says trade concentrated. A prior day or week extreme is simply where price stopped — a reference point almost every participant can see, which is a separate reason for it to matter and not a better or worse one.\n\nThe signal label names the level, so a sample can be split by source rather than pooling the two.", group = grpKey)
useBosInput = input.bool(true, "Structure Break Signals", tooltip = "After a level is tapped, wait for structure to break, then signal.\n\nThe reference is the most recent CONFIRMED swing that price has not already passed, re-read on every bar rather than fixed at the tap. So when a lower high confirms while a long setup waits, that lower high becomes the level to break — which is how the chart reads, and it does not require price to clear the high it originally fell from.\n\nRe-reading is not hindsight: a swing needs its full confirmation bars before it can be used at all, so every reference is one the market had already set.\n\nOnly reversals are taken. The side price approached from sets the direction and only the swing on that side can fire: came DOWN into the level so it is support and a break UP confirms it, came up into it so it is resistance and only a break down counts. A break the other way is the level failing, which is not a trade this takes.\n\nA level with no known approach side arms nothing rather than guess one.\n\nThe signal fires on the break itself. There is no retest or pullback stage: requiring one delayed every entry, which widened the stop from the level and pushed a 2R target further away in points, and it rejected most setups outright. If signals later look like they break and immediately give the move back, that is the evidence for putting a pullback condition back, and it is worth tuning rather than reinstating at the old threshold.", group = grpBos)
bosCarriedInput = input.bool(true, "From carried levels", inline = "bsrc", group = grpBos)
bosNakedInput = input.bool(true, "From naked POCs", inline = "bsrc", group = grpBos)
bosLenInput = input.int(10, "Structure Pivot Length", minval = 2, maxval = 50, tooltip = "Bars either side of a swing for it to count as structure. Set to match the structure indicator you read the chart with, so the reference the signal uses is the level you would have marked yourself.\n\nSwings are kept as an alternating zigzag, not as raw pivots: between any two highs there must be a low, and two highs in a row collapse to the higher. Without that a pivot function hands back minor swings a structure indicator at the same length never draws.\n\nA swing needs this many bars clear on its RIGHT before it is confirmed, so the swing forming at the tap itself does not exist yet and the reference is the one before it. That is deliberate rather than a lag to tune away — it is a level the market had already set before price arrived, not one drawn around the tap afterwards.\n\nShorter finds more swings and nearer references, so signals come earlier and more often. Longer finds only major swings, so they come later and the entry sits further from the level a stop would reference.", group = grpBos)
bosWindowInput = input.int(120, "Break Window (bars)", minval = 1, maxval = 500, tooltip = "How long after a tap a structure break still counts as belonging to it. A tap that reaches this age without breaking either reference is dropped.\n\nSet from measured examples: a break roughly 15 to 20 bars after the tap, and another roughly 90 bars after. 120 covers both with headroom.\n\nTreat this as the loosest setting in the indicator, not a neutral one. The longer the window, the weaker the claim that the break belongs to the tap at all — at 90 bars on a 1m chart an hour and a half of unrelated trade sits between the two, and price may have spent most of it on the far side of the level. A wide window marks the slow reversals you want AND every break that merely happens to follow a tap.\n\nThe bars-to-break figure on each signal label is there for exactly this: it lets a review separate the fast breaks from the slow ones rather than judging them as one population.", group = grpBos)
bosCooldownInput = input.int(30, "Cooldown per Level (minutes)", minval = 0, maxval = 480, tooltip = "After a level produces a structure-break signal, that level cannot produce another for this long.\n\nSeparate from the alert cooldown above and kept on its own clock, so turning the tap alert off does not quietly leave these uncooled.\n\nNaked POCs ignore it: they are deleted the first time price trades through them and can never signal twice anyway.\n\n0 disables it.", group = grpBos)
showBosLabelsInput = input.bool(true, "Signal markers", inline = "bsl", group = grpBos)
bosLongColorInput = input.color(#26a69a, "", inline = "bsl", group = grpBos)
bosShortColorInput = input.color(#ef5350, "", inline = "bsl", group = grpBos)
alertNakedInput = input.bool(true, "Naked POC touched", group = grpAlert)
alertExtInput = input.bool(true, "Carried level tapped", group = grpAlert)
alertKeyInput = input.bool(true, "Daily / weekly level tapped", group = grpAlert)
alertBosInput = input.bool(true, "Structure break signal", group = grpAlert)
showAlertMarkersInput = input.bool(true, "Mark alerts on chart", tooltip = "Plot a marker on the bar a level alerted, placed by the side price approached from.\n\nPrice came UP into the level, so the level is overhead and resistance: the marker goes ABOVE the candle, the side you would be looking to short from. Price came DOWN into it, so it is support underneath: the marker goes BELOW. At the moment of a tap the approach side and the level's role are the same fact, since a level cannot be touched from above and be resistance on that touch.\n\nThe side is the last close that was CLEAR of the level by the tap tolerance, carried forward while price sits on it. Tracked that way rather than read off the previous candle, so a bar that tapped the level and closed past it still reports where price came from instead of where it ended up. A level price has never closed clear of has no side, and its marker sits on the level itself rather than claim a direction.\n\nPlacement is the only thing the side decides. Nothing here filters a tap, and no entry is implied: the marker says which way the level is facing, not that the trade is good.\n\nThese follow the alerts exactly: the session gate, the re-arm distance, the cooldown and the two toggles below all apply. A tap held back by any of them leaves no marker, which makes the markers a way to SEE what your gates and cooldowns are actually doing.\n\nThey appear on the bar's close, because that is when the alert is sent.", group = grpAlert)
extMarkerColorInput = input.color(#000000, "Carried tap", inline = "mc", group = grpAlert)
nakedMarkerColorInput = input.color(#000000, "Naked touch", inline = "mc", group = grpAlert)
// ============================================================
// HELPERS
// ============================================================
f_style(string s) =>
s == "Solid" ? line.style_solid : s == "Dashed" ? line.style_dashed : line.style_dotted
f_size(string s) =>
s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : size.small
int rowCount = resolutionInput == "Low" ? 24 : resolutionInput == "High" ? 60 : 40
// Top level, because a ta.* series read from inside a conditional gets a broken
// history.
float atr14 = ta.atr(14)
float labelGap = nz(atr14, 0.0) * labelGapAtrInput
float tapTol = extTapTicksInput * syminfo.mintick
// Structure swings, kept as an ALTERNATING zigzag rather than a raw pivot pool.
//
// ta.pivothigh returns every local pivot with the given bars clear either side,
// minor ones included. A zigzag keeps only what survives alternation: between
// any two highs there must be a low, and two highs in a row collapse to the
// higher of them. That is the difference between the swings a pivot function
// finds and the swings a structure indicator draws at the same length, and it
// is why a raw pool produces references price clears far too easily.
var array<float> zzPrice = array.new<float>()
var array<int> zzIsHigh = array.new<int>()
float pivotHi = ta.pivothigh(bosLenInput, bosLenInput)
float pivotLo = ta.pivotlow(bosLenInput, bosLenInput)
f_zzPush(float px, int isHigh) =>
int n = array.size(zzPrice)
bool sameType = n > 0 and array.get(zzIsHigh, n - 1) == isHigh
if sameType
// Same type twice with no opposite swing between them is one swing seen
// twice, so the more extreme of the pair replaces the other instead of
// both being kept.
float prev = array.get(zzPrice, n - 1)
if isHigh == 1 ? px > prev : px < prev
array.set(zzPrice, n - 1, px)
else
array.push(zzPrice, px)
array.push(zzIsHigh, isHigh)
if array.size(zzPrice) > 40
array.shift(zzPrice)
array.shift(zzIsHigh)
// Closing the function on a value of its own, so the if/else above is no
// longer its terminal expression. array.shift hands back the element it
// removed, which made the else branch yield an int while the if branch
// yielded nothing, and Pine requires the two to agree.
not sameType
if not na(pivotHi)
f_zzPush(pivotHi, 1)
if not na(pivotLo)
f_zzPush(pivotLo, 0)
// The most recent CONFIRMED swing of the wanted type that price has not already
// passed.
//
// Most recent, not nearest by price. The nearest swing is whichever happens to
// sit closest to the level, so price clears it on a small move and the signal
// fires early. The swing that matters is the one price came FROM, which is the
// latest confirmed one still standing in front of it.
//
// Confirmed is the operative word: a swing needs bosLenInput bars clear on its
// right before it exists, so the swing forming at the tap itself is not yet
// available and the reference is the one before it.
f_lastSwing(int wantHigh, float ref) =>
float out = na
int n = array.size(zzPrice)
if n > 0
for zs = n - 1 to 0
if array.get(zzIsHigh, zs) == wantHigh
float v = array.get(zzPrice, zs)
if wantHigh == 1 ? v > ref : v < ref
out := v
break
out
float rearmTol = extRearmTicksInput * syminfo.mintick
// Labels that would land on top of each other, pushed apart just enough to read.
//
// Walked from the lowest price upward: the bottom label keeps its exact level
// and each one above is lifted to clear the one below it. Only the TEXT moves;
// every line stays at its true price, so a nudged label never misreports where
// its level is.
//
// Sorted by repeated minimum rather than a sort call: there are only ever a
// handful of labels at one edge, and this keeps the price and label arrays in
// step without a second index array to get wrong.
f_spreadLabels(array<float> pxA, array<label> lbA, float gap) =>
int n = array.size(pxA)
if n > 1 and gap > 0
array<bool> used = array.new<bool>(n, false)
float prevY = na
for k = 0 to n - 1
int best = -1
float bestPx = na
for j = 0 to n - 1
if not array.get(used, j)
float v = array.get(pxA, j)
if na(bestPx) or v < bestPx
bestPx := v
best := j
if best >= 0
array.set(used, best, true)
float y = na(prevY) ? bestPx : math.max(bestPx, prevY + gap)
label.set_y(array.get(lbA, best), y)
prevY := y
// ============================================================
// SESSION ENGINE
// ============================================================
// Session membership is asked of Pine directly so the overnight Asia window
// spanning midnight is handled for us. Times are New York, as the sessions
// themselves are defined in New York.
bool inAsia = not na(time(timeframe.period, "1800-0300:1234567", "America/New_York"))
bool inLondon = not na(time(timeframe.period, "0300-0930:1234567", "America/New_York"))
bool inNy = not na(time(timeframe.period, "0930-1700:1234567", "America/New_York"))
bool inDay = not na(time(timeframe.period, "1800-1700:1234567", "America/New_York"))
bool useDay = profilePerInput == "Day"
int sessId = useDay ? (inDay ? 3 : -1) : (inAsia ? 0 : inLondon ? 1 : inNy ? 2 : -1)
// The trading windows, which are a different thing from the profile sessions
// above: those decide how volume is grouped, these decide when you are told.
bool inSess1 = not na(time(timeframe.period, sess1Input, "America/New_York"))
bool inSess2 = not na(time(timeframe.period, sess2Input, "America/New_York"))
bool inSession = not useSessInput or inSess1 or inSess2
f_sessName(int id) =>
id == 0 ? "Asia" : id == 1 ? "London" : id == 2 ? "NY" : "Day"
// A new profile starts when the session changes, and also after a market halt,
// which shows up as the session id resuming after a gap.
bool sessChanged = sessId != sessId[1]
// ============================================================
// CURRENT SESSION ACCUMULATION
// ============================================================
// The candles of the session being built. The profile has to be recomputed from
// these rather than updated incrementally, because the row boundaries move
// whenever the session's range expands.
var array<float> curHi = array.new<float>()
var array<float> curLo = array.new<float>()
var array<float> curVol = array.new<float>()
var int curStartBar = na
var int curStartTime = na
var int curId = -1
// ============================================================
// PROFILE MATHS
// ============================================================
// Returns [poc, vah, val, pHigh, pLow, maxRowVol] and fills rowOut with each
// row's volume. Each candle's volume is spread evenly across the rows its
// high-to-low range covers, which is the standard assumption when only candle
// data is available.
f_build(array<float> hiA, array<float> loA, array<float> volA, int rows, array<float> rowOut) =>
float pHigh = na
float pLow = na
float poc = na
float vah = na
float val = na
float maxRow = 0.0
int n = array.size(hiA)
if n > 0
pHigh := array.max(hiA)
pLow := array.min(loA)
float span = pHigh - pLow
array.clear(rowOut)
for r = 0 to rows - 1
array.push(rowOut, 0.0)
if span > 0
float rowSize = span / rows
for i = 0 to n - 1
float bh = array.get(hiA, i)
float bl = array.get(loA, i)
float bv = array.get(volA, i)
int firstRow = int(math.floor((bl - pLow) / rowSize))
int lastRow = int(math.floor((bh - pLow) / rowSize))
firstRow := int(math.max(0, math.min(rows - 1, firstRow)))
lastRow := int(math.max(0, math.min(rows - 1, lastRow)))
int spanRows = lastRow - firstRow + 1
float per = bv / spanRows
for r = firstRow to lastRow
array.set(rowOut, r, array.get(rowOut, r) + per)
// Point of Control: the busiest row, priced at its middle.
int pocIdx = 0
float total = 0.0
for r = 0 to rows - 1
float v = array.get(rowOut, r)
total += v
if v > array.get(rowOut, pocIdx)
pocIdx := r
maxRow := array.get(rowOut, pocIdx)
poc := pLow + (pocIdx + 0.5) * rowSize
// Value Area: from the POC row, take whichever neighbour holds more
// volume until the block holds 70% of the session.
float target = total * 0.70
int upIdx = pocIdx
int dnIdx = pocIdx
float acc = array.get(rowOut, pocIdx)
while acc < target and (upIdx < rows - 1 or dnIdx > 0)
float upVol = upIdx < rows - 1 ? array.get(rowOut, upIdx + 1) : -1.0
float dnVol = dnIdx > 0 ? array.get(rowOut, dnIdx - 1) : -1.0
if upVol >= dnVol
upIdx += 1
acc += upVol
else
dnIdx -= 1
acc += dnVol
vah := pLow + (upIdx + 1) * rowSize
val := pLow + dnIdx * rowSize
else
poc := pLow
vah := pHigh
val := pLow
maxRow := 1.0
[poc, vah, val, pHigh, pLow, maxRow]
// ============================================================
// DRAWING STORES
// ============================================================
// Completed profiles. objCount records how many drawings each one contributed,
// so retiring the oldest removes exactly its own objects and no others.
var array<box> profBoxes = array.new<box>()
var array<line> profLines = array.new<line>()
var array<label> profLabels = array.new<label>()
var array<int> profBoxCount = array.new<int>()
var array<int> profLineCount = array.new<int>()
var array<int> profLabelCount = array.new<int>()
// The developing profile is deleted and redrawn whole, so it needs no counts.
var array<box> devBoxes = array.new<box>()
var array<line> devLines = array.new<line>()
var array<label> devLabels = array.new<label>()
f_clearDev() =>
while array.size(devBoxes) > 0
box.delete(array.shift(devBoxes))
while array.size(devLines) > 0
line.delete(array.shift(devLines))
while array.size(devLabels) > 0
label.delete(array.shift(devLabels))
// Retire whole profiles from the front once more than the limit are drawn.
f_trimProfiles() =>
while array.size(profBoxCount) > profilesToShowInput
int nb = array.shift(profBoxCount)
int nl = array.shift(profLineCount)
int nt = array.shift(profLabelCount)
for bi = 1 to nb
if array.size(profBoxes) > 0
box.delete(array.shift(profBoxes))
for li = 1 to nl
if array.size(profLines) > 0
line.delete(array.shift(profLines))
for ti = 1 to nt
if array.size(profLabels) > 0
label.delete(array.shift(profLabels))
// ============================================================
// NAKED POCs
// ============================================================
var array<float> nkPrice = array.new<float>()
var array<int> nkBar = array.new<int>()
var array<string> nkName = array.new<string>()
var array<line> nkLine = array.new<line>()
var array<label> nkLabel = array.new<label>()
// Which side of each level the last CLEAR close sat on: +1 above, -1 below,
// 0 if price has never closed clear of it. A naked POC is deleted the first
// time price trades through it, so the side held at the moment it dies IS
// the side price approached from.
var array<int> nkSide = array.new<int>()
bool nakedTouched = false
float nakedTouchPrice = na
int nakedTouchSide = 0
// ============================================================
// CARRIED LEVELS
// ============================================================
// Three levels per carried session, held with their own armed flag so a tap
// reports once and re-arms only after price has closed clear of the level.
var array<float> extPrice = array.new<float>()
var array<int> extBar = array.new<int>()
var array<string> extName = array.new<string>()
var array<int> extSess = array.new<int>()
var array<bool> extArmed = array.new<bool>()
// Timestamp each level is quiet until, in milliseconds. 0 is free to alert.
// Held per level so one level alerting never silences another's.
var array<int> extCoolUntil = array.new<int>()
// Structure-break signals keep their own cooldown clock, independent of the
// alert cooldown above, so switching the tap alert off cannot leave them
// uncooled as a side effect.
var array<int> bosCoolUntil = array.new<int>()
// These hold the PROFILE's own line and label rather than new drawings. The
// profile owns them; the carried store only moves them, and hands them back
// when the session stops being carried.
var array<line> extLine = array.new<line>()
var array<label> extLabel = array.new<label>()
// Approach side per carried level, same convention as nkSide above.
var array<int> extSide = array.new<int>()
bool extTapped = false
string extTapName = ""
float extTapPrice = na
int extTapSide = 0
f_extPush(float px, int endBar, string nm, int sess, line ln, label lb) =>
if not na(px) and not na(ln)
array.push(extPrice, px)
array.push(extBar, endBar)
array.push(extName, nm)
array.push(extSess, sess)
array.push(extArmed, true)
array.push(extCoolUntil, 0)
array.push(bosCoolUntil, 0)
array.push(extSide, close > px ? 1 : close < px ? -1 : 0)
array.push(extLine, ln)
array.push(extLabel, lb)
// Handed back, not deleted. The drawing belongs to the profile, which may still
// be on the chart, so it is returned to where the session ended.
f_extRemoveAt(int idx) =>
float px = array.get(extPrice, idx)
int endBar = array.get(extBar, idx)
line ln = array.remove(extLine, idx)
label lb = array.remove(extLabel, idx)
if not na(ln)
line.set_xy2(ln, endBar, px)
if not na(lb)
label.set_xy(lb, endBar, px)
array.remove(extPrice, idx)
array.remove(extBar, idx)
array.remove(extName, idx)
array.remove(extSess, idx)
array.remove(extArmed, idx)
array.remove(extCoolUntil, idx)
array.remove(bosCoolUntil, idx)
array.remove(extSide, idx)
// ============================================================
// DAILY / WEEKLY LEVELS
// ============================================================
// PDH, PDL, PWH, PWL, in that fixed order. Four slots that never grow or shrink:
// a new day or week changes a slot's VALUE rather than adding one, so these are
// held in fixed-size arrays and the drawings are reused rather than recreated.
//
// request.security with lookahead on, reading one bar back, is the
// non-repainting form. The lookahead gives the completed prior period rather
// than one still forming, and the [1] offset is what stops it being the current
// period's own data leaking backwards.
[pdhRaw, pdlRaw] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead = barmerge.lookahead_on)
[pwhRaw, pwlRaw] = request.security(syminfo.tickerid, "W", [high[1], low[1]], lookahead = barmerge.lookahead_on)
var array<float> kyPrice = array.new<float>(4, na)
var array<int> kyAnchor = array.new<int>(4, 0)
var array<bool> kyArmed = array.new<bool>(4, true)
var array<int> kySide = array.new<int>(4, 0)
var array<int> kyCool = array.new<int>(4, 0)
var array<int> kyBosCool = array.new<int>(4, 0)
// Sized but unfilled: the one-argument form leaves object slots na without
// asking Pine to infer a type for a bare na.
var array<line> kyLine = array.new<line>(4)
var array<label> kyLabel = array.new<label>(4)
bool keyTapped = false
string keyTapName = ""
float keyTapPrice = na
int keyTapSide = 0
f_keyName(int slot) =>
slot == 0 ? "PDH" : slot == 1 ? "PDL" : slot == 2 ? "PWH" : "PWL"
f_keyShown(int slot) =>
slot < 2 ? showPdInput : showPwInput
f_keyColor(int slot) =>
slot < 2 ? pdColorInput : pwColorInput
// ============================================================
// SESSION ROLL
// ============================================================
var array<float> rowBuf = array.new<float>()
if barstate.isconfirmed
// --- finalise the session that just ended ---
if sessChanged and curId >= 0 and array.size(curHi) > 0
[fPoc, fVah, fVal, fHigh, fLow, fMaxRow] = f_build(curHi, curLo, curVol, rowCount, rowBuf)
if not na(fPoc)
int barsWide = math.max(2, int((bar_index - 1 - curStartBar) * widthPctInput / 100.0))
int boxN = 0
int lineN = 0
int labelN = 0
float rowSize = (fHigh - fLow) / rowCount
if showHistogramInput and fHigh > fLow and fMaxRow > 0
for r = 0 to rowCount - 1
float v = array.get(rowBuf, r)
if v > 0
int w = math.max(1, int(v / fMaxRow * barsWide))
float rTop = fLow + (r + 1) * rowSize
float rBot = fLow + r * rowSize
bool inVa = rBot >= fVal - rowSize * 0.01 and rTop <= fVah + rowSize * 0.01
array.push(profBoxes, box.new(curStartBar, rTop, curStartBar + w, rBot, xloc = xloc.bar_index, border_color = #00000000, bgcolor = inVa ? vaColorInput : histColorInput))
boxN += 1
int xEnd = bar_index - 1
// Kept so the carried store can extend these rather than draw its own.
line pocLn = na
line vahLn = na
line valLn = na
label pocLb = na
label vahLb = na
label valLb = na
if showPocInput
pocLn := line.new(curStartBar, fPoc, xEnd, fPoc, xloc = xloc.bar_index, color = pocColorInput, style = f_style(pocStyleInput), width = 2)
array.push(profLines, pocLn)
lineN += 1
if showLabelsInput
pocLb := label.new(xEnd, fPoc, f_sessName(curId) + " POC", xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = #00000000, textcolor = pocColorInput, size = f_size(labelSizeInput))
array.push(profLabels, pocLb)
labelN += 1
if showVaInput
vahLn := line.new(curStartBar, fVah, xEnd, fVah, xloc = xloc.bar_index, color = vaLineColorInput, style = f_style(vaStyleInput), width = 2)
valLn := line.new(curStartBar, fVal, xEnd, fVal, xloc = xloc.bar_index, color = vaLineColorInput, style = f_style(vaStyleInput), width = 2)
array.push(profLines, vahLn)
array.push(profLines, valLn)
lineN += 2
if showLabelsInput
vahLb := label.new(xEnd, fVah, f_sessName(curId) + " VAH", xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = #00000000, textcolor = vaLineColorInput, size = f_size(labelSizeInput))
valLb := label.new(xEnd, fVal, f_sessName(curId) + " VAL", xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = #00000000, textcolor = vaLineColorInput, size = f_size(labelSizeInput))
array.push(profLabels, vahLb)
array.push(profLabels, valLb)
labelN += 2
array.push(profBoxCount, boxN)
array.push(profLineCount, lineN)
array.push(profLabelCount, labelN)
f_trimProfiles()
// --- the POC joins the naked list, untouched until price returns ---
if nakedCountInput > 0
array.push(nkPrice, fPoc)
array.push(nkBar, xEnd)
array.push(nkName, "nPOC " + f_sessName(curId) + " " + str.format("{0,date,M/d}", curStartTime))
array.push(nkSide, close > fPoc ? 1 : close < fPoc ? -1 : 0)
array.push(nkLine, line.new(xEnd, fPoc, xEnd + 1, fPoc, xloc = xloc.bar_index, color = nakedColorInput, style = f_style(nakedStyleInput), width = 2))
array.push(nkLabel, label.new(xEnd, fPoc, "", xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = #00000000, textcolor = nakedColorInput, size = f_size(labelSizeInput)))
while array.size(nkPrice) > nakedCountInput
array.shift(nkPrice)
array.shift(nkBar)
array.shift(nkName)
array.shift(nkSide)
line.delete(array.shift(nkLine))
label.delete(array.shift(nkLabel))
// --- and its three levels are carried forward ---
// Never more carried sessions than drawn profiles, so a carried
// level always points at a drawing that is still on the chart.
int extN = math.min(extCountInput, profilesToShowInput)
if extN > 0
if extShowPocInput
f_extPush(fPoc, xEnd, f_sessName(curId) + " POC", curId, pocLn, pocLb)
if extShowVaInput
f_extPush(fVah, xEnd, f_sessName(curId) + " VAH", curId, vahLn, vahLb)
f_extPush(fVal, xEnd, f_sessName(curId) + " VAL", curId, valLn, valLb)
// Retired whole, oldest first, so a session never half-disappears.
int perSession = (extShowPocInput and showPocInput ? 1 : 0) + (extShowVaInput and showVaInput ? 2 : 0)
if perSession > 0
while array.size(extPrice) > extN * perSession
f_extRemoveAt(0)
// --- start a new session ---
if sessChanged
array.clear(curHi)
array.clear(curLo)
array.clear(curVol)
curStartBar := bar_index
curStartTime := time
curId := sessId
// --- accumulate ---
if sessId >= 0
array.push(curHi, high)
array.push(curLo, low)
array.push(curVol, nz(volume, 0.0))
// ============================================================
// DEVELOPING PROFILE
// ============================================================
// Rebuilt only on the latest bar. Recomputing the whole session on every
// historical bar would be the same picture for a great deal more work, since
// only the final state of the developing profile is ever seen.
if barstate.islast
f_clearDev()
if showDevelopingInput and sessId >= 0 and array.size(curHi) > 0
[dPoc, dVah, dVal, dHigh, dLow, dMaxRow] = f_build(curHi, curLo, curVol, rowCount, rowBuf)
if not na(dPoc)
int dBarsWide = math.max(2, int((bar_index - curStartBar) * widthPctInput / 100.0))
float dRowSize = (dHigh - dLow) / rowCount
if showHistogramInput and dHigh > dLow and dMaxRow > 0
for r = 0 to rowCount - 1
float v = array.get(rowBuf, r)
if v > 0
int w = math.max(1, int(v / dMaxRow * dBarsWide))
float rTop = dLow + (r + 1) * dRowSize
float rBot = dLow + r * dRowSize
bool inVa = rBot >= dVal - dRowSize * 0.01 and rTop <= dVah + dRowSize * 0.01
array.push(devBoxes, box.new(curStartBar, rTop, curStartBar + w, rBot, xloc = xloc.bar_index, border_color = #00000000, bgcolor = inVa ? vaColorInput : histColorInput))
if showPocInput
array.push(devLines, line.new(curStartBar, dPoc, bar_index, dPoc, xloc = xloc.bar_index, color = pocColorInput, style = f_style(pocStyleInput), width = 2))
if showLabelsInput
array.push(devLabels, label.new(bar_index, dPoc, f_sessName(curId) + " POC", xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = #00000000, textcolor = pocColorInput, size = f_size(labelSizeInput)))
if showVaInput
array.push(devLines, line.new(curStartBar, dVah, bar_index, dVah, xloc = xloc.bar_index, color = vaLineColorInput, style = f_style(vaStyleInput), width = 2))
array.push(devLines, line.new(curStartBar, dVal, bar_index, dVal, xloc = xloc.bar_index, color = vaLineColorInput, style = f_style(vaStyleInput), width = 2))
if showLabelsInput
array.push(devLabels, label.new(bar_index, dVah, f_sessName(curId) + " VAH", xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = #00000000, textcolor = vaLineColorInput, size = f_size(labelSizeInput)))
array.push(devLabels, label.new(bar_index, dVal, f_sessName(curId) + " VAL", xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = #00000000, textcolor = vaLineColorInput, size = f_size(labelSizeInput)))
// ============================================================
// STRUCTURE BREAK SETUPS
// ============================================================
// A level tap arms a setup. The setup waits for structure to break away from
// the level and signals on that break.
//
// Level prices and names are COPIED rather than referenced by index, because a
// naked POC is deleted on the bar it is tapped and the carried array reorders
// whenever a session is retired. By the time a setup resolves, an index taken
// at the tap could point at a different level or at nothing.
//
// The references are frozen at the tap and never refreshed, so a break is
// measured against structure the market had already set before price arrived,
// not against a swing drawn around the tap afterwards.
var array<float> bsPx = array.new<float>()
var array<string> bsName = array.new<string>()
var array<int> bsBar = array.new<int>()
var array<int> bsSide = array.new<int>()
bool bosLong = false
bool bosShort = false
string bosText = ""
f_bsPush(float px, string nm, int side) =>
// One setup per level at a time. A re-tap while a setup is still live is the
// same visit to the same level, not a new event.
bool dup = false
if array.size(bsPx) > 0
for bd = 0 to array.size(bsPx) - 1
if math.abs(array.get(bsPx, bd) - px) <= tapTol
dup := true
// No reference is stored. It is read fresh on every bar of the setup's life,
// so a swing that confirms AFTER the tap becomes the level to break.
//
// All a setup needs at the tap is a known approach side, and reversal mode
// refuses to guess one it does not have.
// A known approach side is the whole requirement. Without one there is no
// reversal direction to look for, and the setup is not guessed into being.
if not dup and side != 0
array.push(bsPx, px)
array.push(bsName, nm)
array.push(bsBar, bar_index)
array.push(bsSide, side)
f_bsRemoveAt(int idx) =>
array.remove(bsPx, idx)
array.remove(bsName, idx)
array.remove(bsBar, idx)
array.remove(bsSide, idx)
f_bosCooldown(float px) =>
if bosCooldownInput > 0
int until = time + bosCooldownInput * 60000
if array.size(extPrice) > 0
for bc = 0 to array.size(extPrice) - 1
if math.abs(array.get(extPrice, bc) - px) <= tapTol
array.set(bosCoolUntil, bc, until)
// Daily and weekly slots are matched the same way, by price, so a signal
// off PDH cools PDH and nothing else.
for bk = 0 to 3
float kp = array.get(kyPrice, bk)
if not na(kp) and math.abs(kp - px) <= tapTol
array.set(kyBosCool, bk, until)
// ============================================================
// STRUCTURE BREAK LIFECYCLE
// ============================================================
// Resolved BEFORE this bar's taps are registered, so a setup can never break on
// the same bar that created it.
if barstate.isconfirmed and useBosInput and array.size(bsPx) > 0
int bsI = array.size(bsPx) - 1
while bsI >= 0
float px = array.get(bsPx, bsI)
bool drop = false
if bar_index - array.get(bsBar, bsI) > bosWindowInput
drop := true
else
// Re-read every bar rather than frozen at the tap.
//
// Frozen, a setup armed after a long decline keeps waiting on the
// high price originally fell from, and ignores every lower high that
// confirms while it waits. Price then has to make a whole new high to
// trigger, which fires far later than reading the chart would.
//
// This is not hindsight: a swing still needs its full confirmation
// bars before f_lastSwing will return it, so the reference is always
// one the market had already set.
//
// Selected against the PREVIOUS close, then broken by this one.
//
// This is the hinge of the whole test. Selecting against the current
// close picks the swing sitting above it and then asks whether the
// close is above that swing, which is a contradiction: the reference
// climbs with price and nothing can ever break it. Anchoring one bar
// back gives the swing that was still unbroken as of last bar, so
// this bar closing through it is a real break.
//
// Still live: a lower high that confirms while the setup waits
// becomes the reference, provided it is above where price sat.
//
// Only ONE reference is ever in play, and the approach side picks it.
// Price came down into the level, so the level is support and the
// trade is long: the swing HIGH above is what has to break. Came up
// into it and only the swing low below counts. A break the other way
// is the level failing, which is not a trade this takes.
int side = array.get(bsSide, bsI)
float ref = side > 0 ? f_lastSwing(1, close[1]) : f_lastSwing(0, close[1])
bool broke = not na(ref) and (side > 0 ? close > ref : close < ref)
// One signal per bar. A second setup breaking on the same bar is left
// pending rather than removed, so it reports on a later bar instead of
// being swallowed silently by the first.
if broke and not (bosLong or bosShort)
if side > 0
bosLong := true
else
bosShort := true
// Carried for the ALERT only. The on-chart marker is a bare
// triangle.
bosText := array.get(bsName, bsI)
f_bosCooldown(px)
drop := true
if drop
f_bsRemoveAt(bsI)
bsI -= 1
// ============================================================
// NAKED POC LIFECYCLE
// ============================================================
// A naked POC is removed the first time a candle trades through it, which is the
// whole point of the word naked.
if barstate.isconfirmed and array.size(nkPrice) > 0
int nkIdx = array.size(nkPrice) - 1
while nkIdx >= 0
float px = array.get(nkPrice, nkIdx)
if low <= px and high >= px
nakedTouched := true
nakedTouchPrice := px
// Read before the level is removed: the approach side dies with it,
// so it has to be taken here or not at all.
nakedTouchSide := array.get(nkSide, nkIdx)
if useBosInput and bosNakedInput
f_bsPush(px, array.get(nkName, nkIdx), array.get(nkSide, nkIdx))
array.remove(nkPrice, nkIdx)
array.remove(nkBar, nkIdx)
array.remove(nkName, nkIdx)
array.remove(nkSide, nkIdx)
line.delete(array.remove(nkLine, nkIdx))
label.delete(array.remove(nkLabel, nkIdx))
else
// Side upkeep for the levels that survived this bar. A close that is
// not clear of the level leaves the recorded side alone, so price
// resting on a level never erases where it arrived from.
if close > px + tapTol
array.set(nkSide, nkIdx, 1)
else if close < px - tapTol
array.set(nkSide, nkIdx, -1)
nkIdx -= 1
if array.size(nkPrice) > 0
for nd = 0 to array.size(nkPrice) - 1
line ln = array.get(nkLine, nd)
label lb = array.get(nkLabel, nd)
float px = array.get(nkPrice, nd)
line.set_xy1(ln, array.get(nkBar, nd), px)
line.set_xy2(ln, bar_index + extendBarsInput, px)
line.set_color(ln, nakedColorInput)
line.set_style(ln, f_style(nakedStyleInput))
label.set_xy(lb, bar_index + extendBarsInput, px)
label.set_text(lb, array.get(nkName, nd))
label.set_textcolor(lb, nakedColorInput)
label.set_size(lb, f_size(labelSizeInput))
// ============================================================
// CARRIED LEVEL TAPS
// ============================================================
// Tested by RANGE, so a wick reaching the level counts: arriving at it is the
// event. The armed flag keeps one visit to one alert, and re-arms only once a
// close has moved clear by the re-arm distance.
//
// On top of that each level carries its own cooldown. Re-arm alone cannot stop a
// level reporting over and over when price works back and forth across it: every
// one of those crossings closes clear, re-arms the level honestly, and alerts
// again. The cooldown is what makes a level report once per visit rather than
// once per crossing.
if barstate.isconfirmed and array.size(extPrice) > 0
for et = 0 to array.size(extPrice) - 1
float px = array.get(extPrice, et)
bool armed = array.get(extArmed, et)
bool touching = low <= px + tapTol and high >= px - tapTol
// Read BEFORE this bar's close updates it at the foot of the loop. A
// candle that tapped the level and closed past it would otherwise report
// the side it ended on rather than the side it came from, which is the
// one thing this has to get right.
int side = array.get(extSide, et)
if armed and touching
// Registered against the SIGNAL cooldown, not the alert cooldown.
// The two answer to different settings on purpose.
if useBosInput and bosCarriedInput and (bosCooldownInput == 0 or time >= array.get(bosCoolUntil, et))
f_bsPush(px, array.get(extName, et), side)
// Disarmed whether or not the alert goes out, exactly as before. The
// cooldown holds back the notification and nothing else, so a tap
// during one can never leave a level permanently armed.
array.set(extArmed, et, false)
bool cooling = extCooldownInput > 0 and time < array.get(extCoolUntil, et)
if not cooling
extTapped := true
extTapName := array.get(extName, et)
extTapPrice := px
extTapSide := side
// Started only when an alert will really be sent. A tap at 04:00
// that your session gate suppressed should not cost you the
// alert at 07:05.
if extCooldownInput > 0 and inSession and alertExtInput
array.set(extCoolUntil, et, time + extCooldownInput * 60000)
else if not armed and math.abs(close - px) > rearmTol
array.set(extArmed, et, true)
// Side upkeep, after the tap has been judged on the side price arrived
// from. A close inside the tap tolerance changes nothing.
if close > px + tapTol
array.set(extSide, et, 1)
else if close < px - tapTol
array.set(extSide, et, -1)
// Only the right-hand end moves. Colour, style and text are the profile's own,
// so a carried level is visibly the same line, just reaching further.
if array.size(extPrice) > 0
for ed = 0 to array.size(extPrice) - 1
line ln = array.get(extLine, ed)
label lb = array.get(extLabel, ed)
float px = array.get(extPrice, ed)
if not na(ln)
line.set_xy2(ln, bar_index + extendBarsInput, px)
if not na(lb)
label.set_xy(lb, bar_index + extendBarsInput, px)
// ============================================================
// DAILY / WEEKLY LEVEL TAPS
// ============================================================
// A new period does not add a level, it moves one. So when a slot's value
// changes the slot is reset whole: re-armed, its approach side re-read from the
// current close, and its line re-anchored. Carrying any of that across would
// describe the old price.
if barstate.isconfirmed
for kz = 0 to 3
float nv = kz == 0 ? pdhRaw : kz == 1 ? pdlRaw : kz == 2 ? pwhRaw : pwlRaw
float ov = array.get(kyPrice, kz)
if not na(nv) and (na(ov) or nv != ov)
array.set(kyPrice, kz, nv)
array.set(kyArmed, kz, true)
array.set(kySide, kz, close > nv ? 1 : close < nv ? -1 : 0)
array.set(kyAnchor, kz, bar_index)
float px = array.get(kyPrice, kz)
if not na(px) and f_keyShown(kz)
bool armed = array.get(kyArmed, kz)
bool touching = low <= px + tapTol and high >= px - tapTol
// Read before this bar's close updates it, for the same reason the
// carried levels do: a candle that tapped and closed past the level
// would otherwise report the side it ended on.
int side = array.get(kySide, kz)
if armed and touching
array.set(kyArmed, kz, false)
bool cooling = extCooldownInput > 0 and time < array.get(kyCool, kz)
if not cooling
keyTapped := true
keyTapName := f_keyName(kz)
keyTapPrice := px
keyTapSide := side
if extCooldownInput > 0 and inSession and alertKeyInput
array.set(kyCool, kz, time + extCooldownInput * 60000)
if useBosInput and keyBosInput and (bosCooldownInput == 0 or time >= array.get(kyBosCool, kz))
f_bsPush(px, f_keyName(kz), side)
else if not armed and math.abs(close - px) > rearmTol
array.set(kyArmed, kz, true)
if close > px + tapTol
array.set(kySide, kz, 1)
else if close < px - tapTol
array.set(kySide, kz, -1)
// Drawings are created once per slot and then only moved, so a level that
// changes price keeps one line rather than leaving a trail of them.
for kd = 0 to 3
float px = array.get(kyPrice, kd)
line ln = array.get(kyLine, kd)
label lb = array.get(kyLabel, kd)
bool shown = f_keyShown(kd) and not na(px)
if shown and na(ln)
ln := line.new(array.get(kyAnchor, kd), px, bar_index, px, xloc = xloc.bar_index, width = 2)
lb := label.new(bar_index, px, "", xloc = xloc.bar_index, yloc = yloc.price, style = label.style_label_left, color = #00000000)
array.set(kyLine, kd, ln)
array.set(kyLabel, kd, lb)
if not na(ln)
if shown
line.set_xy1(ln, array.get(kyAnchor, kd), px)
line.set_xy2(ln, bar_index + extendBarsInput, px)
line.set_color(ln, f_keyColor(kd))
line.set_style(ln, f_style(keyStyleInput))
label.set_xy(lb, bar_index + extendBarsInput, px)
label.set_text(lb, showLabelsInput ? f_keyName(kd) : "")
label.set_textcolor(lb, f_keyColor(kd))
label.set_size(lb, f_size(labelSizeInput))
else
// Hidden rather than deleted: the slot is permanent, so the drawing
// is reused if the toggle comes back on.
line.set_color(ln, #00000000)
label.set_text(lb, "")
// ============================================================
// LABEL COLLISION
// ============================================================
// Everything parked at the right edge competes for the same column, so carried
// levels and naked POCs are spread together rather than separately. The
// developing profile sits at the last bar instead, a different column, so it
// gets its own pass.
var array<float> edgePx = array.new<float>()
var array<label> edgeLb = array.new<label>()
var array<float> devPx = array.new<float>()
var array<label> devLb = array.new<label>()
if showLabelsInput and labelGap > 0
array.clear(edgePx)
array.clear(edgeLb)
if array.size(extPrice) > 0
for ge = 0 to array.size(extPrice) - 1
label lb = array.get(extLabel, ge)
if not na(lb)
array.push(edgePx, array.get(extPrice, ge))
array.push(edgeLb, lb)
if array.size(nkPrice) > 0
for gn = 0 to array.size(nkPrice) - 1
array.push(edgePx, array.get(nkPrice, gn))
array.push(edgeLb, array.get(nkLabel, gn))
// Daily and weekly levels park at the same right-hand edge, so they are
// spread together with the rest rather than against each other.
for gk = 0 to 3
label lb = array.get(kyLabel, gk)
float px = array.get(kyPrice, gk)
if not na(lb) and not na(px) and f_keyShown(gk)
array.push(edgePx, px)
array.push(edgeLb, lb)
f_spreadLabels(edgePx, edgeLb, labelGap)
if barstate.islast and array.size(devLabels) > 0
array.clear(devPx)
array.clear(devLb)
for gd = 0 to array.size(devLabels) - 1
label lb = array.get(devLabels, gd)
array.push(devPx, label.get_y(lb))
array.push(devLb, lb)
f_spreadLabels(devPx, devLb, labelGap)
// ============================================================
// ALERT MARKERS
// ============================================================
// Plotted at the level's own price via location.absolute, so a marker lands on
// the line that fired rather than floating above the candle.
//
// The conditions deliberately mirror the alerts above, the session gate and the
// per-type toggles included. A marker therefore appears if and only if an alert
// was sent, which is what makes it useful for checking that the cooldown and
// the gate are behaving the way you expect.
bool markNaked = showAlertMarkersInput and alertNakedInput and inSession and nakedTouched
bool markExt = showAlertMarkersInput and alertExtInput and inSession and extTapped
bool markKey = showAlertMarkersInput and alertKeyInput and inSession and keyTapped
// Placed by approach side. A level tapped from BELOW is overhead, so its marker
// goes above the candle; tapped from ABOVE it is support, so the marker goes
// below. A level with no recorded side gets its marker on the level itself,
// which claims no direction.
//
// Done with an absolute y rather than location.abovebar and location.belowbar
// because location is a const: splitting by side that way would need four plot
// calls and four rows in the Style tab instead of two.
float markOff = nz(atr14, 0.0) * 0.35
float nakedMarkY = nakedTouchSide < 0 ? high + markOff : nakedTouchSide > 0 ? low - markOff : nakedTouchPrice
float extMarkY = extTapSide < 0 ? high + markOff : extTapSide > 0 ? low - markOff : extTapPrice
plotchar(markNaked ? nakedMarkY : na, "Naked POC touched", "★", location.absolute, nakedMarkerColorInput, size = size.small)
plotshape(markExt ? extMarkY : na, "Carried level tapped", shape.diamond, location.absolute, extMarkerColorInput, size = size.small)
float keyMarkY = keyTapSide < 0 ? high + markOff : keyTapSide > 0 ? low - markOff : keyTapPrice
plotshape(markKey ? keyMarkY : na, "Daily / weekly level tapped", shape.square, location.absolute, extMarkerColorInput, size = size.small)
// Filled triangles, apex in the trade direction: pointing up below the bar for
// a long, down above it for a short. No text — the shape and its colour carry
// everything, and the level name goes out with the alert instead.
//
// Drawn as plots rather than labels, so they cost nothing against the drawing
// pool the profile levels share and need no budget cap to stop them crowding
// those levels out.
plotshape(showBosLabelsInput and bosLong and inSession, "Structure break long", shape.triangleup, location.belowbar, bosLongColorInput, size = size.small)
plotshape(showBosLabelsInput and bosShort and inSession, "Structure break short", shape.triangledown, location.abovebar, bosShortColorInput, size = size.small)
// ============================================================
// ALERTS
// ============================================================
string alertMsg = ""
if alertNakedInput and nakedTouched
alertMsg := syminfo.ticker + " — NAKED POC TOUCHED"
if alertBosInput and (bosLong or bosShort)
alertMsg := alertMsg + (alertMsg == "" ? "" : "\n") + syminfo.ticker + " — " + (bosLong ? "LONG" : "SHORT") + " STRUCTURE BREAK · " + bosText
if alertKeyInput and keyTapped
alertMsg := alertMsg + (alertMsg == "" ? "" : "\n") + syminfo.ticker + " — " + keyTapName + " TAPPED"
if alertExtInput and extTapped
alertMsg := alertMsg + (alertMsg == "" ? "" : "\n") + syminfo.ticker + " — " + extTapName + " TAPPED"
// Gated here rather than where the touch is detected, so the bookkeeping behind
// each level carries on around the clock and only the notification is held back.
if barstate.isconfirmed and inSession and alertMsg != ""
alert(alertMsg, alert.freq_once_per_bar_close)
// The named conditions answer to the same gate, or an alert set from the
// dropdown would fire at times the toggle promised it would not.
alertcondition(inSession and nakedTouched, "Naked POC touched", "Price traded into a naked POC")
alertcondition(inSession and extTapped, "Carried level tapped", "Price tapped a carried session level")
alertcondition(inSession and keyTapped, "Daily / weekly level tapped", "Price tapped PDH, PDL, PWH or PWL")
alertcondition(inSession and bosLong, "Structure break long", "Structure broke up after a volume profile level tap")
alertcondition(inSession and bosShort, "Structure break short", "Structure broke down after a volume profile level tap")