本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Nasdaq|AMD HTF v5.1", shorttitle="NQ AMD v5.1", overlay=true, scale=scale.none, max_lines_count=80, max_labels_count=80, max_boxes_count=150, max_bars_back=1600)
// QUANTWHEEL: QQQ gamma proxy, NOT CME NQ dealer gamma.
// CME option OI and volume: historical uploaded data.
// Product identity and exact report dates not verified.
// =====================================================
// 01 - DISPLAY
// =====================================================
gView = "Display"
showPanel = input.bool(true, "Show dashboard", group=gView)
panelPosition = input.string("Top right", "Position", options=["Top right", "Bottom right", "Top left", "Bottom left"], group=gView)
fontSize = input.string("Small", "Text size", options=["Small", "Normal"], group=gView)
showLines = input.bool(true, "Show mapped walls and model flip", group=gView)
showLabels = input.bool(true, "Show price labels", group=gView)
showActivity = input.bool(true, "Show CME Call/Put volume levels", group=gView)
activityCount = input.int(9, "Number of activity levels", minval=1, maxval=13, group=gView)
showTouch = input.bool(true, "Show historical reach frequency", group=gView)
showOI = input.bool(false, "Show older OI concentrations", group=gView)
maxDistance = input.float(10.0, "Price distance (%)", minval=0.1, maxval=50, group=gView)
labelOffset = input.int(4, "Label offset", minval=1, maxval=50, group=gView)
// =====================================================
// 02 - QUANTWHEEL QQQ SNAPSHOT
// =====================================================
gLevels = "QQQ snapshot | Optional NQ mapping"
qqqSpot = input.float(704.89, "QQQ reference price", minval=0.01, group=gLevels)
nqReference = input.float(0.0, "NQ price at SAME timestamp", minval=0, group=gLevels)
qqqCall = input.float(715.0, "QQQ Call Wall", minval=0, group=gLevels)
qqqPut = input.float(695.0, "QQQ Put Wall", minval=0, group=gLevels)
qqqFlip = input.float(714.58, "QQQ Gamma Flip", minval=0, group=gLevels)
float ratio = nqReference > 0 ? nqReference / qqqSpot : na
float modelFlip = not na(ratio) ? qqqFlip * ratio : na
// =====================================================
// 03 - TREND AND VOLUME
// =====================================================
gModel = "Trend and volume"
fastLen = input.int(20, "Fast EMA", minval=2, maxval=200, group=gModel)
slowLen = input.int(50, "Slow EMA", minval=3, maxval=400, group=gModel)
slopeLen = input.int(3, "EMA slope lookback", minval=1, maxval=50, group=gModel)
flowLen = input.int(20, "Volume lookback", minval=2, maxval=200, group=gModel)
flowLimit = input.float(15.0, "Volume pressure threshold (%)", minval=1, maxval=100, group=gModel)
pivotLen = input.int(3, "Divergence pivot length", minval=1, maxval=20, group=gModel)
freshBars = input.int(8, "Fresh divergence age", minval=1, group=gModel)
horizon = input.int(8, "Historical outcome horizon", minval=1, maxval=100, group=gModel)
minSamples = input.int(30, "Minimum historical sample", minval=5, group=gModel)
// =====================================================
// 04 - COLORS
// =====================================================
color bg = color.rgb(17, 22, 30)
color muted = color.rgb(151, 164, 181)
color white = color.rgb(230, 237, 245)
color green = color.rgb(55, 202, 151)
color red = color.rgb(244, 116, 126)
color amber = color.rgb(240, 179, 88)
color purple = color.rgb(184, 151, 255)
string textSize = fontSize == "Normal" ? size.normal : size.small
string panelPos = panelPosition == "Top left" ? position.top_left : panelPosition == "Bottom left" ? position.bottom_left : panelPosition == "Bottom right" ? position.bottom_right : position.top_right
f_price(float x) =>
na(x) or x <= 0 ? "N/A" : str.tostring(x, "#.##")
f_pct(float x) =>
na(x) ? "N/A" : str.tostring(x, "#.##") + "%"
f_wall(float x) =>
float change = close > 0 ? (x / close - 1) * 100 : na
na(x) ? "Not loaded" : f_price(x) + " (" + (change > 0 ? "+" : "") + f_pct(change) + ")"
// =====================================================
// 05 - NQ / MNQ VALIDATION
// =====================================================
bool validChart = syminfo.type == "futures" and (syminfo.root == "NQ" or syminfo.root == "MNQ") and chart.is_standard
bool qAvailable = nqReference > 0
float nearCall = qAvailable ? qqqCall * ratio : na
float nearPut = qAvailable ? qqqPut * ratio : na
// =====================================================
// 06 - TREND AND VOLUME PROXY
// =====================================================
float fast = ta.ema(close, fastLen)
float slow = ta.ema(close, slowLen)
bool volOK = not na(volume) and volume > 0
float signedVol = volOK ? volume * (close > open ? 1 : close < open ? -1 : 0) : 0
float validShare = ta.sma(volOK ? 1.0 : 0.0, flowLen)
float avgVol = ta.sma(nz(volume), flowLen)
float avgSigned = ta.sma(signedVol, flowLen)
float pressure = validShare == 1 and avgVol > 0 ? 100 * avgSigned / avgVol : na
float rvol = volOK and avgVol > 0 ? volume / avgVol : na
bool ready = validChart and not na(slow[slopeLen]) and not na(pressure) and not na(rvol)
// Five checks, twenty points each.
// This is a score, not a trading win probability.
int bullPoints = (close > fast ? 1 : 0) + (fast > slow ? 1 : 0) + (fast > fast[slopeLen] ? 1 : 0) + (slow > slow[slopeLen] ? 1 : 0) + (pressure > flowLimit ? 1 : 0)
int bearPoints = (close < fast ? 1 : 0) + (fast < slow ? 1 : 0) + (fast < fast[slopeLen] ? 1 : 0) + (slow < slow[slopeLen] ? 1 : 0) + (pressure < -flowLimit ? 1 : 0)
int trendState = close > fast and fast > slow ? 2 : close < fast and fast < slow ? 0 : 1
int flowState = pressure > flowLimit ? 2 : pressure < -flowLimit ? 0 : 1
int state = ready ? trendState * 6 + flowState * 2 + (rvol >= 1 ? 1 : 0) : na
// =====================================================
// 07 - CVD PROXY DIVERGENCE
// =====================================================
// Candle-direction volume; NOT aggressor-side delta.
float cvd = ta.cum(signedVol)
float gaps = ta.cum(volOK ? 0.0 : 1.0)
float pl = ta.pivotlow(low, pivotLen, pivotLen)
float ph = ta.pivothigh(high, pivotLen, pivotLen)
var float oldLow = na
var float lowCVD = na
var float lowGaps = na
var float oldHigh = na
var float highCVD = na
var float highGaps = na
var int bullBar = na
var int bearBar = na
if validChart and barstate.isconfirmed
if not na(pl)
if not na(oldLow) and volOK[pivotLen] and gaps[pivotLen] == lowGaps and pl < oldLow and cvd[pivotLen] > lowCVD
bullBar := bar_index
oldLow := pl
lowCVD := cvd[pivotLen]
lowGaps := gaps[pivotLen]
if not na(ph)
if not na(oldHigh) and volOK[pivotLen] and gaps[pivotLen] == highGaps and ph > oldHigh and cvd[pivotLen] < highCVD
bearBar := bar_index
oldHigh := ph
highCVD := cvd[pivotLen]
highGaps := gaps[pivotLen]
// =====================================================
// 08 - HISTORICAL FREQUENCIES
// =====================================================
// Only completed, non-overlapping observation windows.
// Descriptive statistics, NOT calibrated predictions.
var int[] counts = array.new_int(18, 0)
var int[] ups = array.new_int(18, 0)
var int[] downs = array.new_int(18, 0)
float windowHigh = ta.highest(high, horizon)
float windowLow = ta.lowest(low, horizon)
var int[] touchStates = array.new_int()
var float[] touchUp = array.new_float()
var float[] touchDown = array.new_float()
var int baseN = 0
var int baseUp = 0
if barstate.isconfirmed and bar_index >= horizon and bar_index % horizon == 0
int prior = state[horizon]
if not na(prior) and ready and close[horizon] > 0
array.set(counts, prior, array.get(counts, prior) + 1)
if close > close[horizon]
array.set(ups, prior, array.get(ups, prior) + 1)
baseUp += 1
if close < close[horizon]
array.set(downs, prior, array.get(downs, prior) + 1)
baseN += 1
array.push(touchStates, prior)
array.push(touchUp, math.max(0.0, (windowHigh / close[horizon] - 1) * 100))
array.push(touchDown, math.max(0.0, (1 - windowLow / close[horizon]) * 100))
if array.size(touchStates) > 2000
array.shift(touchStates)
array.shift(touchUp)
array.shift(touchDown)
// =====================================================
// 09 - ORIGINAL CME OPTIONS DATA
// =====================================================
var float[] oiPrices = array.from(31000.0, 30000.0, 30500.0, 30000.0, 28000.0, 29000.0)
var int[] oiCounts = array.from(444, 383, 339, 873, 446, 446)
var string[] oiTypes = array.from("CALL", "CALL", "CALL", "PUT", "PUT", "PUT")
var float[] activityPrices = array.from(28400.0, 28500.0, 28900.0, 29000.0, 29100.0, 29150.0, 29200.0, 29300.0, 29400.0, 29500.0, 29750.0, 30000.0, 30500.0)
var int[] callVolumes = array.from(0, 9, 0, 48, 60, 35, 181, 77, 149, 109, 80, 497, 104)
var int[] putVolumes = array.from(88, 109, 57, 230, 232, 75, 55, 62, 17, 48, 12, 14, 9)
int closedOffset = barstate.isconfirmed ? 0 : 1
float referenceClose = close[closedOffset]
int referenceState = state[closedOffset]
// =====================================================
// 10 - HISTORICAL REACH RATE
// =====================================================
f_touch(float level) =>
int cases = 0
int hits = 0
float distance = referenceClose > 0 ? math.abs(level / referenceClose - 1) * 100 : na
if not na(referenceState) and not na(distance) and array.size(touchStates) > 0
for j = 0 to array.size(touchStates) - 1
if array.get(touchStates, j) == referenceState
cases += 1
float excursion = level >= referenceClose ? array.get(touchUp, j) : array.get(touchDown, j)
if excursion >= distance
hits += 1
string result = cases >= minSamples ? str.tostring(100.0 * hits / cases, "#") + "%" : "N/A"
if not na(distance) and distance == 0
result := "At close"
[result, cases]
// =====================================================
// 11 - HORIZONTAL LEVEL LINES
// =====================================================
var line[] levelLines = array.new_line()
var label[] levelLabels = array.new_label()
f_draw(float price, string title, color tint, string tip) =>
if not na(price) and price > 0 and close > 0 and math.abs(price / close - 1) * 100 <= maxDistance
array.push(levelLines, line.new(bar_index, price, bar_index + 1, price, extend=extend.right, color=color.new(tint, 15), width=2, force_overlay=true))
if showLabels
string caption = title + " " + f_price(price)
int activityIndex = array.indexof(activityPrices, price)
string fullTip = tip
if showActivity and activityIndex >= 0
caption += "\nCalls traded: " + str.tostring(array.get(callVolumes, activityIndex)) + " | Puts: " + str.tostring(array.get(putVolumes, activityIndex))
if showTouch
[touchRate, cases] = f_touch(price)
caption += "\nPast reach rate (" + str.tostring(horizon) + " bars): " + touchRate
fullTip += "\nHistorical cases: " + str.tostring(cases) + ". Descriptive only, not a validated forecast."
array.push(levelLabels, label.new(bar_index + labelOffset, price, caption, style=label.style_label_left, color=color.new(bg, 8), textcolor=tint, size=size.small, tooltip=fullTip, force_overlay=true))
// Comparison values are displayed in the single main dashboard below.
gCompare = "CME / QQQ comparison | Main dashboard"
cmpQCallGEXk = input.float(122.0, "QQQ CALL GEX (K)", minval=0, group=gCompare)
cmpQPutGEXk = input.float(244.0, "QQQ PUT GEX (K)", minval=0, group=gCompare)
cmpRegime = input.string("NEGATIVE", "QQQ gamma regime", options=["NEGATIVE", "POSITIVE", "UNKNOWN"], group=gCompare)
float cmpCmeCallOI = 83931.0
float cmpCmePutOI = 117418.0
float cmpCmePutCallOI = cmpCmeCallOI > 0 ? cmpCmePutOI / cmpCmeCallOI : na
float cmpQPutCallGEX = cmpQCallGEXk > 0 ? cmpQPutGEXk / cmpQCallGEXk : na
bool cmpBothPutLarger = cmpCmePutCallOI > 1 and cmpQPutCallGEX > 1
// =====================================================
// 12 - SINGLE UNIFIED DASHBOARD
// =====================================================
var table panel = table.new(panelPos, 2, 21, bgcolor=bg, frame_color=color.rgb(45, 55, 69), frame_width=1, border_width=0, force_overlay=true)
f_row(int r, string key, string value, color tint, string tip) =>
color rowBG = r % 2 == 0 ? bg : color.rgb(21, 27, 36)
table.cell(panel, 0, r, key, text_color=muted, bgcolor=rowBG, text_size=textSize, text_halign=text.align_left, tooltip=tip)
table.cell(panel, 1, r, value, text_color=tint, bgcolor=rowBG, text_size=textSize, text_halign=text.align_right, tooltip=tip)
// =====================================================
// 13 - UPDATE LEVELS AND THE SINGLE DASHBOARD
// =====================================================
if barstate.islast
for item in levelLines
line.delete(item)
array.clear(levelLines)
for item in levelLabels
label.delete(item)
array.clear(levelLabels)
string modelTip = "QuantWheel QQQ model, not verified CME NQ dealer gamma. Reference prices must be synchronized."
string wallTip = "QQQ wall mapped to NQ using a synchronized reference price. Proxy only."
if validChart and showLines and qAvailable
f_draw(nearCall, "CALL WALL [QQQ PROXY]", amber, wallTip)
f_draw(nearPut, "PUT WALL [QQQ PROXY]", green, wallTip)
f_draw(modelFlip, "MODEL FLIP [QQQ PROXY]", purple, modelTip)
if validChart and showActivity
float[] distances = array.new_float()
for level in activityPrices
array.push(distances, math.abs(level - close))
int[] sortedIndices = array.sort_indices(distances, order.ascending)
for rank = 0 to activityCount - 1
int idx = array.get(sortedIndices, rank)
float level = array.get(activityPrices, idx)
bool wallAlreadyDrawn = showLines and qAvailable and (level == nearCall or level == nearPut or level == modelFlip)
if not wallAlreadyDrawn
color tint = array.get(callVolumes, idx) >= array.get(putVolumes, idx) ? amber : green
f_draw(level, "OPTION ACTIVITY [HIST]", tint, "Historical CME option volume, not resting liquidity.")
if validChart and showOI
for i = 0 to array.size(oiPrices) - 1
color tint = i < 3 ? amber : green
float oiLevel = array.get(oiPrices, i)
bool alreadyDrawn = false
for drawnLine in levelLines
if line.get_y1(drawnLine) == oiLevel
alreadyDrawn := true
if not alreadyDrawn
f_draw(oiLevel, "OI " + array.get(oiTypes, i) + " [HIST]", tint, "Open interest: " + str.tostring(array.get(oiCounts, i)))
int off = barstate.isconfirmed ? 0 : 1
bool ok = ready[off]
int bull = bullPoints[off]
int bear = bearPoints[off]
int strength = math.max(bull, bear) * 20
string regime = not ok ? "Waiting for data" : bull >= 3 and bull > bear ? "BULLISH" : bear >= 3 and bear > bull ? "BEARISH" : "MIXED"
color regimeColor = regime == "BULLISH" ? green : regime == "BEARISH" ? red : muted
string regimeValue = ok ? regime + " | " + str.tostring(strength) + "/100 score" : regime
int currentState = state[off]
int n = not na(currentState) ? array.get(counts, currentState) : 0
float upRate = n > 0 ? 100.0 * array.get(ups, currentState) / n : na
float downRate = n > 0 ? 100.0 * array.get(downs, currentState) / n : na
float baseline = baseN > 0 ? 100.0 * baseUp / baseN : na
string history = n >= minSamples ? "UP " + f_pct(upRate) + " | DOWN " + f_pct(downRate) : "Not enough examples"
bool latestBull = not na(bullBar) and (na(bearBar) or bullBar > bearBar)
int divBar = latestBull ? bullBar : bearBar
int divAge = na(divBar) ? na : bar_index - divBar
bool fresh = not na(divAge) and divAge <= freshBars
string divergence = not validChart ? "N/A" : na(divAge) ? "None" : (latestBull ? "Bullish" : "Bearish") + " | " + str.tostring(divAge) + " bars" + (fresh ? "" : " (old)")
color divColor = not fresh ? muted : latestBull ? green : red
string volumeText = not ok ? "N/A" : (pressure[off] > flowLimit ? "Buy pressure" : pressure[off] < -flowLimit ? "Sell pressure" : "Balanced") + " | " + str.tostring(rvol[off], "#.##") + "x"
if showPanel
f_row(0, "NASDAQ / NQ", validChart ? "MARKET OVERVIEW" : "USE NQ / MNQ CHART", white, "Trend and options research.")
f_row(1, "Market regime", regimeValue, regimeColor, "Five checks, 20 points each. Not a win probability.")
f_row(2, qAvailable ? "Call wall (proxy)" : "Call wall (QQQ)", validChart and qAvailable ? f_wall(nearCall) : f_price(qqqCall) + " QQQ", amber, wallTip)
f_row(3, qAvailable ? "Put wall (proxy)" : "Put wall (QQQ)", validChart and qAvailable ? f_wall(nearPut) : f_price(qqqPut) + " QQQ", green, wallTip)
f_row(4, "Model flip*", validChart and qAvailable ? f_price(modelFlip) + " proxy" : f_price(qqqFlip) + " QQQ", purple, modelTip)
f_row(5, "Gamma regime*", cmpRegime + " | QQQ snapshot", amber, modelTip)
f_row(6, "Volume pressure", volumeText, ok ? pressure[off] > flowLimit ? green : pressure[off] < -flowLimit ? red : muted : muted, "Estimated from bar direction and volume.")
f_row(7, "CVD divergence", divergence, divColor, "Price versus OHLCV CVD proxy at confirmed pivots.")
f_row(8, "Similar setups | " + str.tostring(horizon) + " bars", history, white, "Historical frequencies only.")
f_row(9, "Similar past examples", str.tostring(n) + " completed examples", muted, "Matched trend and volume states.")
f_row(10, "All setups: finished higher", f_pct(baseline) + " after " + str.tostring(horizon) + " bars", muted, "Historical baseline.")
f_row(11, "Source status*", "Product / dates unverified", muted, "CME and QQQ snapshots are different sources.")
string cmeTip = "CME option OI and volume from the uploaded file, aggregated across expiries. OI is contracts, not dealer gamma. Product and date are unverified."
string qTip = "QuantWheel QQQ GEX snapshot, not direct NQ dealer gamma. QQQ reference 704.89."
string compareTip = "Different instruments, measures and expiries. Put dominance is not a verified directional signal."
f_row(12, "CME Call OI", "83,931 | top 31,000", amber, cmeTip)
f_row(13, "CME Put OI", "117,418 | top 28,000", green, cmeTip)
f_row(14, "CME Put / Call OI", str.tostring(cmpCmePutCallOI, "#.##") + "x", white, cmeTip)
f_row(15, "CME Call / Put volume", "63,021 / 63,483", white, cmeTip)
f_row(16, "QQQ GEX C / P", str.tostring(cmpQCallGEXk, "#") + "K / " + str.tostring(cmpQPutGEXk, "#") + "K", purple, qTip)
f_row(17, "QQQ GEX Put / Call", na(cmpQPutCallGEX) ? "N/A" : str.tostring(cmpQPutCallGEX, "#.##") + "x", purple, qTip)
f_row(18, "Side comparison", cmpBothPutLarger ? "PUT > CALL IN BOTH" : "MIXED / CHECK", cmpBothPutLarger ? amber : muted, compareTip)
f_row(19, "NQ dealer gamma", "UNKNOWN FROM CME OI", amber, compareTip)
f_row(20, "Source alignment", "DATES / EXPIRIES UNVERIFIED", amber, compareTip)
else
table.clear(panel, 0, 0, 1, 20)
// =====================================================
// 14 - NEW CME DATA FROM XLS (3)
// =====================================================
// Uploaded report: 5262 option rows across expiries.
// Call OI 83931 / Put OI 117418.
// Call volume 63021 / Put volume 63483.
// These are NOT gamma exposures.
gNewCME = "NEW CME XLS (3) | Added levels"
addShowOI = input.bool(true, "Show new CME Call/Put OI", group=gNewCME)
addOiPerSide = input.int(4, "Strongest OI per side", minval=1, maxval=6, group=gNewCME)
addShowVolume = input.bool(false, "Show new CME option volume", group=gNewCME)
addVolumePerSide = input.int(2, "Strongest volume per side", minval=1, maxval=5, group=gNewCME)
addFutureBars = input.int(12, "Additional label offset", minval=1, maxval=40, group=gNewCME)
var float[] addCallOiStrikes = array.from(31000.0, 31500.0, 30500.0, 33000.0, 32000.0, 30000.0)
var int[] addCallOiValues = array.from(4127, 3698, 3477, 3362, 3017, 2483)
var float[] addPutOiStrikes = array.from(28000.0, 26000.0, 28500.0, 27000.0, 27500.0, 29500.0)
var int[] addPutOiValues = array.from(7390, 4683, 4618, 4290, 3637, 3620)
var float[] addCallVolStrikes = array.from(31500.0, 29500.0, 29200.0, 29300.0, 29400.0)
var int[] addCallVolValues = array.from(6321, 3566, 2465, 2355, 1923)
var float[] addPutVolStrikes = array.from(29000.0, 28000.0, 28500.0, 26000.0, 26500.0)
var int[] addPutVolValues = array.from(3283, 3163, 2584, 2400, 2090)
var line[] addLines = array.new_line()
var label[] addLabels = array.new_label()
f_newCmeLevel(float price, string description, int qty, color shade, bool isVolume) =>
bool visible = price > 0 and close > 0 and math.abs(price / close - 1) * 100 <= maxDistance
if visible
line addLine = line.new(bar_index, price, bar_index + 1, price, extend=extend.right, color=color.new(shade, 15), width=2, style=isVolume ? line.style_dotted : line.style_dashed, force_overlay=true)
array.push(addLines, addLine)
if showLabels
string unit = isVolume ? "VOL" : "OI"
string tag = "NEW CME " + description + " " + unit + " " + str.tostring(price, "#.##") + " | " + str.tostring(qty)
string note = "Historical CME option data, aggregated across expiries. Not dealer gamma."
label addLabel = label.new(bar_index + labelOffset + addFutureBars, price, tag, style=label.style_label_left, color=color.new(bg, 5), textcolor=shade, size=size.tiny, tooltip=note, force_overlay=true)
array.push(addLabels, addLabel)
if barstate.islast
for ln in addLines
line.delete(ln)
array.clear(addLines)
for lb in addLabels
label.delete(lb)
array.clear(addLabels)
if validChart and addShowOI
for idx = 0 to addOiPerSide - 1
f_newCmeLevel(array.get(addCallOiStrikes, idx), "CALL", array.get(addCallOiValues, idx), amber, false)
f_newCmeLevel(array.get(addPutOiStrikes, idx), "PUT", array.get(addPutOiValues, idx), green, false)
if validChart and addShowVolume
for idx = 0 to addVolumePerSide - 1
f_newCmeLevel(array.get(addCallVolStrikes, idx), "CALL", array.get(addCallVolValues, idx), amber, true)
f_newCmeLevel(array.get(addPutVolStrikes, idx), "PUT", array.get(addPutVolValues, idx), green, true)
// =====================================================
// 15 - AMD SESSION CARPETS
// =====================================================
// A: session accumulation range
// M: sweep observation
// D: continuation after confirmed opposite break
gAMD = "AMD | Session carpets"
amdShow = input.bool(true, "Show AMD zones", group=gAMD)
amdSessionTZ = input.string("America/New_York", "Session timezone", group=gAMD)
amdAccumSession = input.session("0700-0930", "A | Accumulation", group=gAMD)
amdManipSession = input.session("0930-1030", "M | Sweep", group=gAMD)
amdDistSession = input.session("1030-1600", "D | Distribution", group=gAMD)
amdOpacity = input.int(88, "Transparency", minval=65, maxval=97, group=gAMD)
amdHistorySessions = input.int(3, "Session cycles", minval=1, maxval=8, group=gAMD)
amdShowText = input.bool(true, "Show AMD labels", group=gAMD)
bool amdCanDraw = amdShow and validChart and timeframe.isintraday
bool amdInA = amdCanDraw and not na(time(timeframe.period, amdAccumSession, amdSessionTZ))
bool amdInM = amdCanDraw and not na(time(timeframe.period, amdManipSession, amdSessionTZ))
bool amdInD = amdCanDraw and not na(time(timeframe.period, amdDistSession, amdSessionTZ))
bool amdNewA = amdInA and not amdInA[1]
bool amdNewM = amdInM and not amdInM[1]
bool amdNewD = amdInD and not amdInD[1]
var float amdAHi = na
var float amdALo = na
var int amdSweep = 0
var bool amdDConfirmed = false
var box amdABox = na
var box amdMBox = na
var box amdDBox = na
var box[] amdSessionBoxes = array.new_box()
if amdCanDraw and barstate.isconfirmed
if amdNewA
amdAHi := high
amdALo := low
amdSweep := 0
amdDConfirmed := false
amdMBox := na
amdDBox := na
amdABox := box.new(left=bar_index, top=high, right=bar_index + 1, bottom=low, bgcolor=color.new(color.rgb(46, 108, 225), amdOpacity), border_color=color.new(color.blue, 64), text=amdShowText ? "A | RANGE" : "", text_color=color.aqua, text_size=size.tiny, force_overlay=true)
array.push(amdSessionBoxes, amdABox)
else if amdInA and not na(amdABox)
amdAHi := math.max(amdAHi, high)
amdALo := math.min(amdALo, low)
box.set_right(amdABox, bar_index + 1)
box.set_top(amdABox, amdAHi)
box.set_bottom(amdABox, amdALo)
bool haveA = not na(amdAHi) and not na(amdALo) and amdAHi > amdALo
if amdNewM and haveA
amdMBox := box.new(left=bar_index, top=high, right=bar_index + 1, bottom=low, bgcolor=color.new(color.orange, amdOpacity), border_color=color.new(color.orange, 67), text=amdShowText ? "M | WATCH" : "", text_color=color.orange, text_size=size.tiny, force_overlay=true)
array.push(amdSessionBoxes, amdMBox)
if amdInM and haveA and not na(amdMBox)
box.set_right(amdMBox, bar_index + 1)
box.set_top(amdMBox, math.max(box.get_top(amdMBox), high))
box.set_bottom(amdMBox, math.min(box.get_bottom(amdMBox), low))
if amdSweep == 0
bool sweepTop = high > amdAHi and close < amdAHi and close > amdALo
bool sweepBottom = low < amdALo and close > amdALo and close < amdAHi
if sweepTop and not sweepBottom
amdSweep := -1
box.set_text(amdMBox, amdShowText ? "M | HIGH SWEEP" : "")
else if sweepBottom and not sweepTop
amdSweep := 1
box.set_text(amdMBox, amdShowText ? "M | LOW SWEEP" : "")
if amdNewD and haveA
amdDBox := box.new(left=bar_index, top=high, right=bar_index + 1, bottom=low, bgcolor=color.new(color.gray, math.min(98, amdOpacity + 6)), border_color=color.new(color.gray, 88), text=amdShowText ? "D | WATCH" : "", text_color=color.silver, text_size=size.tiny, force_overlay=true)
array.push(amdSessionBoxes, amdDBox)