本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("VEX | jjart", "VEX", overlay=false, max_labels_count=500, max_boxes_count=100, max_lines_count=500, explicit_plot_zorder=true)
// Original composite design. Derived OHLCV/LTF pressure proxies, NOT reconstructed private order-book metrics.
// M/W implementation is adapted from the author-supplied jjart Structure design, not a third-party proprietary script.
// Score is a confluence index, not a probability or verified backtest win rate.
// Confirmed-bar signals; no negative-offset plotting, lookahead, or future pivots.
string G1 = "01 · SIGNAL CONTROL"
string G2 = "02 · FB EXTREMES"
string G3 = "03 · VOLUME & DELTA"
string G4 = "04 · ABSORPTION & STRUCTURE"
string G5 = "05 · QUANTUM GATE"
string G6 = "06 · VISUALS & ZONES"
string G7 = "07 · MULTI-TF STRUCTURE"
// Plot colors are configured in TradingView's Style tab.
color markerBuy = input.color(#176b5c, "BUY label color", group=G6, tooltip="Price label colors cannot be controlled in the Style tab when drawn with label.new.\n\nЦвета меток label.new нельзя менять во вкладке Стиль.")
color markerSell = input.color(#a73550, "SELL label color", group=G6, tooltip="Price label colors cannot be controlled in the Style tab when drawn with label.new.\n\nЦвета меток label.new нельзя менять во вкладке Стиль.")
color neonBuy = #72d4c5
color neonSell = #e79bb5
color levelBuy = #168f81
color levelSell = #c15b74
string profile = input.string("Conservative", "Sensitivity", options=["Aggressive","Active","Balanced","Conservative"], group=G1, tooltip="Adjusts the event score sensitivity. Balanced is recommended for daily charts.\n\nРегулирует чувствительность оценки событий. Для дневного графика рекомендуется Balanced.")
bool showSignals = input.bool(true, "Price chart markers", group=G1, tooltip="Displays confirmed BUY/SELL labels on price. Keep enabled for visual review.\n\nПоказывает подтверждённые метки BUY/SELL на цене. Для проверки оставьте включённым.")
bool showDashboard = input.bool(false, "Diagnostic dashboard", group=G1, tooltip="Displays source, structure, score and filter state. Recommended: on.\n\nПоказывает источник данных, структуру, оценку и состояние фильтров. Рекомендуется включить.")
bool showEarly = input.bool(true, "Early warnings", group=G1, tooltip="Shows non-tradable WATCH states; never treats them as confirmed entries. Recommended: on for research.\n\nПоказывает предварительные WATCH без торгового подтверждения. Для анализа рекомендуется включить.")
string precisionMode = input.string("Maximum", "Signal precision", options=["Base", "Strict", "Maximum"], group=G1, tooltip="Strictness of the reversal confirmation. Strict is a reasonable starting point.\n\nСтрогость подтверждения разворота. Для начала рекомендуется Strict.")
int confirmBars = input.int(4, "Confirmation window, bars", minval=1, maxval=15, group=G1, tooltip="Maximum bars allowed between candidate and confirmation. Start with 4.\n\nМаксимум свечей между кандидатом и подтверждением. Начните с 4.")
int minEventSpacing = input.int(10, "Global signal spacing, bars", minval=1, maxval=200, group=G1, tooltip="Minimum bars between displayed signals. Larger values reduce repeated markers.\n\nМинимальное число свечей между метками. Увеличение сокращает повторы.")
bool blockCounterTrend = input.bool(true, "Block strong-trend counter signals", group=G1, tooltip="Requires stronger evidence for countertrend reversals. Recommended: on.\n\nТребует дополнительных подтверждений против сильного тренда. Рекомендуется включить.")
bool requireSweep = input.bool(true, "Require liquidity sweep", group=G1, tooltip="Requires a prior-range wick sweep. Very selective; start disabled.\n\nТребует прокола экстремума диапазона. Очень строгий режим; сначала выключите.")
int cooldown = input.int(15, "Signal cooldown, bars", minval=1, maxval=100, group=G1, tooltip="Minimum bars between same-direction events. Start with 10.\n\nМинимум свечей между сигналами одной стороны. Начните с 10.")
int fbLen = input.int(48, "FB oscillator length", minval=5, maxval=200, group=G2, tooltip="Lookback for normalized price and flow pressure. Start with 34.\n\nПериод нормализации цены и потока. Начните с 34.")
int fbSmooth = input.int(9, "FB smoothing", minval=1, maxval=30, group=G2, tooltip="Smooths the orange FB-style oscillator. Start with 5.\n\nСглаживает оранжевый осциллятор FB. Начните с 5.")
float fbLow = input.float(25.0, "Lower extreme", minval=5, maxval=45, group=G2, tooltip="Oversold reference line. Lower values produce fewer candidates.\n\nУровень перепроданности. Чем ниже, тем меньше кандидатов.")
float fbHigh = input.float(83.0, "Upper extreme", minval=55, maxval=95, group=G2, tooltip="Overbought reference line. Higher values produce fewer candidates.\n\nУровень перекупленности. Чем выше, тем меньше кандидатов.")
int recoverWindow = input.int(7, "Recovery window", minval=1, maxval=30, group=G2, tooltip="Bars in which FB can recover from an extreme. Start with 7.\n\nЧисло свечей для восстановления FB после экстремума. Начните с 7.")
int volLen = input.int(70, "Volume baseline", minval=10, maxval=300, group=G3, tooltip="Average volume period used for relative volume. Start with 70.\n\nПериод среднего объёма для расчёта относительного объёма. Начните с 70.")
int flowSmooth = input.int(15, "Flow smoothing", minval=1, maxval=50, group=G3, tooltip="EMA smoothing of estimated directional volume. Start with 15.\n\nEMA-сглаживание оценочного направленного объёма. Начните с 15.")
int ltfDivider = input.int(12, "Lower TF divisor", minval=2, maxval=30, group=G3, tooltip="Chart timeframe divisor for intrabar sampling; does not create order-book data. Start with 12.\n\nДелитель ТФ для младших свечей; не создаёт данные стакана. Начните с 12.")
bool useLtf = input.bool(true, "Use lower-timeframe candles", group=G3, tooltip="Uses intrabar candles to estimate buy/sell volume; not true bid/ask depth. Recommended: on.\n\nИспользует младшие свечи для оценки покупок и продаж, не реальную глубину стакана. Рекомендуется включить.")
float climaxX = input.float(2.6, "Climax volume, x", minval=1, maxval=8, step=0.1, group=G3, tooltip="Relative volume required for climax. Start with 2.6.\n\nКратность объёма для кульминации. Начните с 2.6.")
int structLen = input.int(27, "Local structure window", minval=5, maxval=200, group=G4, tooltip="Range for local extremes, sweeps and position filter. Start with 27.\n\nДиапазон локальных экстремумов, свипов и фильтра положения цены. Начните с 27.")
float maxLongPos = input.float(0.30, "Maximum long range position", minval=0.1, maxval=0.9, step=0.02, group=G4, tooltip="Rejects late longs above this fraction of local range. Start with 0.30.\n\nОтсекает поздние лонги выше доли диапазона. Начните с 0.30.")
float minShortPos = input.float(0.90, "Minimum short range position", minval=0.1, maxval=0.9, step=0.02, group=G4, tooltip="Rejects late shorts below this fraction of local range. Start with 0.90.\n\nОтсекает поздние шорты ниже доли диапазона. Начните с 0.90.")
int absorptionLookback = input.int(4, "Absorption lookback", minval=1, maxval=15, group=G4, tooltip="Recent bars allowed for absorption evidence. Start with 4.\n\nОкно учёта недавнего поглощения. Начните с 4.")
int gateBars = input.int(12, "Gate duration", minval=1, maxval=100, group=G5, tooltip="How many bars a confirmed Quantum permission stays active. Start with 12.\n\nСколько свечей действует подтверждённое разрешение Quantum. Начните с 12.")
string gateMode = input.string("Early or confirmed", "Quantum authorization", options=["Confirmed only","Early or confirmed"], group=G5, tooltip="Early mode can allow qualified setups before final reversal; use Confirmed only for conservative integration.\n\nРанний режим может разрешать подготовленные сетапы до подтверждения; для осторожной интеграции используйте Confirmed only.")
bool useTrendGuard = input.bool(true, "HTF countertrend penalty", group=G5, tooltip="Reduces score against completed higher-timeframe trend. Recommended: on.\n\nСнижает оценку против тренда закрытого старшего ТФ. Рекомендуется включить.")
string higherTf = input.timeframe("D", "Higher timeframe", group=G5, tooltip="Completed higher timeframe for trend context. Use 3D on daily charts.\n\nЗакрытый старший ТФ для контекста тренда. На дневном графике используйте 3D.")
int scoreThreshold = input.int(72, "Strong signal threshold", minval=30, maxval=95, group=G5, tooltip="Minimum confluence score before candidate evaluation. Start with 72.\n\nМинимальная оценка совпадений для кандидата. Начните с 72.")
bool showZones = input.bool(true, "Price concentration zones", group=G6, tooltip="Draws estimated volume-rejection price zones, not verified resting orders. Recommended: on.\n\nРисует оценочные зоны объёмной реакции, а не подтверждённые лимитные заявки. Рекомендуется включить.")
int zoneBars = input.int(71, "Zone extension, bars", minval=5, maxval=200, group=G6, tooltip="Projection length for price zones. Start with 71.\n\nПродление ценовых зон вправо. Начните с 71.")
int maxZones = input.int(15, "Maximum zones", minval=1, maxval=40, group=G6, tooltip="Limit of retained price boxes. Start with 15.\n\nМаксимальное число сохраняемых зон. Начните с 15.")
bool showFlow = input.bool(true, "Flow and histograms", group=G6, tooltip="Displays directional volume estimate in lower band. Recommended: on.\n\nПоказывает оценку направленного объёма в нижней полосе. Рекомендуется включить.")
bool showBalance = input.bool(true, "Book Balance proxy", group=G6, tooltip="Displays candle-derived balance proxy; not order-book bid/ask depth. Recommended: on.\n\nПоказывает баланс по свечам, а не реальный bid/ask стакана. Рекомендуется включить.")
bool showHeat = input.bool(true, "Extreme background bands", group=G6, tooltip="Highlights confluence around FB extremes. Recommended: on.\n\nВыделяет совпадения возле экстремумов FB. Рекомендуется включить.")
bool showMTF = input.bool(true, "Active HTF structure levels", group=G7, tooltip="Draws active M/W structural levels from 4H through 1W. Higher timeframe signals use closed candles. Recommended: on.\n\nПоказывает только последние несломанные уровни M/W от 4ч до недели. Старшие события по закрытым свечам. Рекомендуется включить.")
int maxStructureLevels = input.int(6, "Visible HTF levels", minval=1, maxval=8, group=G7, tooltip="Nearest levels plus additional distant historical levels. Start with 6.\n\nБлижайшие уровни плюс дальние исторические. Начните с 6.")
int structureMaxAge = input.int(5000, "HTF event life, source bars", minval=10, maxval=10000, group=G7, tooltip="Remove stale HTF events after this many source timeframe bars. Start with 120.\n\nУдалять устаревшие события через указанное число свечей исходного ТФ. Начните со 120.")
bool showOscLabels = input.bool(true, "Descriptive oscillator tags", group=G6, tooltip="Show readable SWEEP, ABS, TURN and NO TRADE tags only for actionable changes. Recommended: on.\n\nПоказывает читаемые метки SWEEP, ABS, TURN и NO TRADE только при изменении состояния. Рекомендуется включить.")
clamp(float x, float a, float b) => math.max(a, math.min(b,x))
div(float x, float y) => math.abs(y)>1e-10 ? x/y : 0.0
float eps = math.max(syminfo.mintick, 0.0000001)
float rng = math.max(high-low,eps)
float closePos = clamp((close-low)/rng,0,1)
float body = math.abs(close-open)
float lowerWick = math.min(open,close)-low
float upperWick = high-math.max(open,close)
float atr = ta.atr(14)
float vBase = ta.sma(volume,volLen)
float relVol = div(volume,vBase)
int seconds = nz(timeframe.in_seconds(), 86400)
int targetSec = math.max(60,int(math.floor(seconds/ltfDivider/60.0))*60)
string lowerTf = timeframe.from_seconds(targetSec)
array<float> arrO = array.new_float()
array<float> arrH = array.new_float()
array<float> arrL = array.new_float()
array<float> arrC = array.new_float()
array<float> arrV = array.new_float()
if useLtf and targetSec < seconds
[oArr,hArr,lArr,cArr,vArr] = request.security_lower_tf(syminfo.tickerid, lowerTf, [open,high,low,close,volume], ignore_invalid_timeframe=true)
arrO := oArr
arrH := hArr
arrL := lArr
arrC := cArr
arrV := vArr
float buyerVol = 0.0
float sellerVol = 0.0
int samples = array.size(arrC)
if samples > 0
for i=0 to samples-1
float o = array.get(arrO,i)
float h = array.get(arrH,i)
float l = array.get(arrL,i)
float c = array.get(arrC,i)
float v = nz(array.get(arrV,i))
float share = clamp(div((c-l)+(h-o),2.0*math.max(h-l,eps)),0,1)
buyerVol += v*share
sellerVol += v*(1-share)
else
float share = clamp(((close-low)+(high-open))/(2.0*rng),0,1)
buyerVol := nz(volume)*share
sellerVol := nz(volume)*(1-share)
float totalV = buyerVol+sellerVol
float delta = buyerVol-sellerVol
float deltaPct = 100*div(delta,totalV)
float flowRaw = deltaPct*math.sqrt(clamp(relVol,0,5))
float flow = ta.ema(flowRaw,flowSmooth)
float flowSignal = ta.ema(flow,math.max(2,flowSmooth*2))
float buyBase = ta.sma(buyerVol,volLen)
float sellBase = ta.sma(sellerVol,volLen)
float buyX = div(buyerVol,buyBase)
float sellX = div(sellerVol,sellBase)
float volMedian = ta.percentile_linear_interpolation(volume,200,50)
float volX = div(volume,volMedian)
// FB-like line: range-location, flow recovery and volume weighted close location.
float rangeLo = ta.lowest(low,fbLen)
float rangeHi = ta.highest(high,fbLen)
float rangePos = clamp(div(close-rangeLo,math.max(rangeHi-rangeLo,eps)),0,1)
float cLoc = 100*closePos
float rangeRank = 100*rangePos
float flowNorm = 50+flow*0.42
float fbRaw = clamp(0.48*rangeRank+0.32*cLoc+0.20*flowNorm,0,100)
float fb = ta.ema(fbRaw,fbSmooth)
float fbFast = ta.ema(fbRaw,2)
float fbLowMin = ta.lowest(fb,recoverWindow)
float fbHighMax = ta.highest(fb,recoverWindow)
bool lowExtreme = fb<=fbLow
bool highExtreme = fb>=fbHigh
int sinceLow = nz(ta.barssince(lowExtreme),100000)
int sinceHigh = nz(ta.barssince(highExtreme),100000)
bool lowRecent = sinceLow<=recoverWindow
bool highRecent = sinceHigh<=recoverWindow
bool fbRecover = lowRecent and fb>fb[1] and fb>fbLowMin+2.5
bool fbReject = highRecent and fb<fb[1] and fb<fbHighMax-2.5
// Book Balance proxies: no historical L2 depth data is claimed.
float bookFast = ta.ema(deltaPct,3)
float bookSlow = ta.ema(deltaPct,15)
float bookWide = ta.ema(deltaPct*math.sqrt(clamp(relVol,0,4)),21)
float bookDiff = bookFast-bookSlow
float pressure = ta.ema((buyX-sellX)*25,5)
float buyerStrength = clamp(50+flow*0.35+pressure*0.25,0,100)
float sellerStrength = 100-buyerStrength
float cvd = ta.cum(delta)
float cvdFast = ta.ema(cvd,8)
float cvdSlow = ta.ema(cvd,34)
float cvdMomentum = div(cvdFast-cvdSlow,math.max(vBase,eps))
// Price rejection with negative/positive volume delta = absorption candidate.
float priorLow = ta.lowest(low,structLen)[1]
float priorHigh = ta.highest(high,structLen)[1]
bool sweepLow = not na(priorLow) and low<priorLow and close>priorLow
bool sweepHigh = not na(priorHigh) and high>priorHigh and close<priorHigh
bool rejectDown = lowerWick>body*0.8 and closePos>0.52
bool rejectUp = upperWick>body*0.8 and closePos<0.48
bool bullAbs = relVol>=1.15 and (deltaPct<0 or sellX>1.25) and (rejectDown or sweepLow) and rangePos<0.45
bool bearAbs = relVol>=1.15 and (deltaPct>0 or buyX>1.25) and (rejectUp or sweepHigh) and rangePos>0.55
bool bullClimax = relVol>=climaxX and closePos>0.58 and rangePos<0.4
bool bearClimax = relVol>=climaxX and closePos<0.42 and rangePos>0.6
bool bullDeltaTurn = flow>flow[1] and flow>flowSignal and (deltaPct>0 or bookDiff>0)
bool bearDeltaTurn = flow<flow[1] and flow<flowSignal and (deltaPct<0 or bookDiff<0)
float volBuyPeak = ta.highest(buyerVol,structLen)
float volSellPeak = ta.highest(sellerVol,structLen)
bool buyPeak = buyerVol>=volBuyPeak and buyX>1.2 and rangePos<0.5
bool sellPeak = sellerVol>=volSellPeak and sellX>1.2 and rangePos>0.5
// Structure Fusion: an independent compact M/W state engine informed by jjart's supplied structure architecture.
// Events are registered on the actual break candle, never retroactively at the pivot.
// Confirmed M/W necks. The level originates at the M valley / W peak,
// never at the later breakout candle. No future-bar backdating of signals.
f_mwState() =>
float pH = ta.pivothigh(high, 1, 1)
float pL = ta.pivotlow(low, 1, 1)
float a = math.max(nz(ta.atr(14), high-low), syminfo.mintick)
var int wState = 0
var int mState = 0
var float wFirst = na
var float wNeck = na
var float wSecond = na
var float mFirst = na
var float mNeck = na
var float mSecond = na
var int wBorn = na
var int mBorn = na
var int wNeckOrigin = na
var int mNeckOrigin = na
if wState > 0 and bar_index-wBorn > 120
wState := 0
if mState > 0 and bar_index-mBorn > 120
mState := 0
// A confirmed first outer pivot, followed by the opposite middle pivot.
if not na(pL) and wState == 0
wFirst := pL
wBorn := bar_index-1
wState := 1
if not na(pH) and mState == 0
mFirst := pH
mBorn := bar_index-1
mState := 1
if wState == 1 and not na(pH) and bar_index-1 > wBorn and pH-wFirst >= a*0.8
wNeck := pH
wNeckOrigin := time[1]
wState := 2
if mState == 1 and not na(pL) and bar_index-1 > mBorn and mFirst-pL >= a*0.8
mNeck := pL
mNeckOrigin := time[1]
mState := 2
if wState == 2 and not na(pL) and bar_index-1 > wBorn+1 and pL < wNeck and math.abs(pL-wFirst) <= a*1.8
wSecond := pL
wState := 3
if mState == 2 and not na(pH) and bar_index-1 > mBorn+1 and pH > mNeck and math.abs(pH-mFirst) <= a*1.8
mSecond := pH
mState := 3
// Direction is determined by breaking the correct neck, not candle color alone.
bool up = wState == 3 and close > wNeck and close[1] <= wNeck and close > open and close > math.max(wFirst,wSecond)
bool dn = mState == 3 and close < mNeck and close[1] >= mNeck and close < open and close < math.min(mFirst,mSecond)
if up or (wState > 0 and close < wFirst-a*0.6)
wState := 0
if dn or (mState > 0 and close > mFirst+a*0.6)
mState := 0
var int direction = 0
if up
direction := 1
if dn
direction := -1
[up, dn, direction, up ? wNeck : dn ? mNeck : na, up ? wNeckOrigin : dn ? mNeckOrigin : na]
// For HTF data use the PREVIOUS completed candle, with lookahead_on.
f_mwClosed() =>
[u,d,dir,neck,neckOrigin] = f_mwState()
[u[1],d[1],dir[1]]
[chartMwUp,chartMwDn,chartMwDir,chartMwNeck,chartMwOrigin] = f_mwState()
[mw1hUp,mw1hDn,mw1hDir] = request.security(syminfo.tickerid,"60",f_mwClosed(),lookahead=barmerge.lookahead_on)
[mw4hUp,mw4hDn,mw4hDir] = request.security(syminfo.tickerid,"240",f_mwClosed(),lookahead=barmerge.lookahead_on)
[mw1dUp,mw1dDn,mw1dDir] = request.security(syminfo.tickerid,"1D",f_mwClosed(),lookahead=barmerge.lookahead_on)
// HTF contexts are only valid when their period is above the chart timeframe.
bool mw1hValid = seconds < 3600
bool mw4hValid = seconds < 14400
bool mw1dValid = seconds < 86400
bool mwBullContext = chartMwDir == 1 or (mw1hValid and mw1hDir == 1) or (mw4hValid and mw4hDir == 1) or (mw1dValid and mw1dDir == 1)
bool mwBearContext = chartMwDir == -1 or (mw1hValid and mw1hDir == -1) or (mw4hValid and mw4hDir == -1) or (mw1dValid and mw1dDir == -1)
bool mwBullEvent = chartMwUp or (mw1hValid and mw1hUp and not mw1hUp[1]) or (mw4hValid and mw4hUp and not mw4hUp[1]) or (mw1dValid and mw1dUp and not mw1dUp[1])
bool mwBearEvent = chartMwDn or (mw1hValid and mw1hDn and not mw1hDn[1]) or (mw4hValid and mw4hDn and not mw4hDn[1]) or (mw1dValid and mw1dDn and not mw1dDn[1])
// Historical structural packets. Preserve the last confirmed event per source bar.
// A lower timeframe event is retrieved as an array, not collapsed to one daily value.
f_atlasPacket() =>
[u, d, dir, lev, origin] = f_mwState()
var float lastLev = na
var int lastDir = 0
var int lastTime = na
var int lastOrigin = na
if u or d
lastLev := lev
lastDir := u ? 1 : -1
lastTime := time_close
lastOrigin := origin
[lastDir[1], lastLev[1], lastTime[1], lastOrigin[1]]
f_atlasLivePacket() =>
[u, d, dir, lev, origin] = f_mwState()
[u or d ? (u ? 1 : -1) : 0, lev, time_close, origin]
[dir4,lev4,t4,o4] = request.security(syminfo.tickerid,"240",f_atlasPacket(),lookahead=barmerge.lookahead_on)
[dir6,lev6,t6,o6] = request.security(syminfo.tickerid,"360",f_atlasPacket(),lookahead=barmerge.lookahead_on)
[dir8,lev8,t8,o8] = request.security(syminfo.tickerid,"480",f_atlasPacket(),lookahead=barmerge.lookahead_on)
[dir12,lev12,t12,o12] = request.security(syminfo.tickerid,"720",f_atlasPacket(),lookahead=barmerge.lookahead_on)
[dirD,levD,tD,oD] = request.security(syminfo.tickerid,"D",f_atlasPacket(),lookahead=barmerge.lookahead_on)
[dir3D,lev3D,t3D,o3D] = request.security(syminfo.tickerid,"3D",f_atlasPacket(),lookahead=barmerge.lookahead_on)
[dirW,levW,tW,oW] = request.security(syminfo.tickerid,"W",f_atlasPacket(),lookahead=barmerge.lookahead_on)
[lower4Dir,lower4Lev,lower4Time,lower4Origin] = request.security_lower_tf(syminfo.tickerid,"240",f_atlasLivePacket(),ignore_invalid_timeframe=true)
// HTF uses previous completed higher-timeframe candle, never the developing HTF bar.
float htfEma50 = request.security(syminfo.tickerid,higherTf,ta.ema(close,50)[1],lookahead=barmerge.lookahead_on)
float htfEma200 = request.security(syminfo.tickerid,higherTf,ta.ema(close,200)[1],lookahead=barmerge.lookahead_on)
bool htfUp = htfEma50>htfEma200
bool htfDown = htfEma50<htfEma200
float sensitivity = profile=="Aggressive" ? 0.78 : profile=="Active" ? 1.0 : profile=="Balanced" ? 1.17 : 1.35
float lScore = 0.0
float sScore = 0.0
lScore += lowRecent ? 22 : 0
sScore += highRecent ? 22 : 0
lScore += fbRecover ? 15 : 0
sScore += fbReject ? 15 : 0
lScore += bullDeltaTurn ? 14 : 0
sScore += bearDeltaTurn ? 14 : 0
lScore += bullAbs ? 18 : 0
sScore += bearAbs ? 18 : 0
lScore += sweepLow ? 12 : 0
sScore += sweepHigh ? 12 : 0
lScore += bullClimax ? 10 : 0
sScore += bearClimax ? 10 : 0
lScore += buyPeak ? 9 : 0
sScore += sellPeak ? 9 : 0
lScore += bookDiff>0 and pressure>0 ? 8 : 0
sScore += bookDiff<0 and pressure<0 ? 8 : 0
lScore += cvdMomentum>cvdMomentum[1] ? 6 : 0
lScore += mwBullContext ? 8 : 0
lScore += mwBullEvent ? 12 : 0
sScore += cvdMomentum<cvdMomentum[1] ? 6 : 0
sScore += mwBearContext ? 8 : 0
sScore += mwBearEvent ? 12 : 0
if useTrendGuard
lScore -= htfDown ? 12 : 0
sScore -= htfUp ? 12 : 0
float longScore = clamp(lScore/sensitivity,0,100)
float shortScore = clamp(sScore/sensitivity,0,100)
bool priceLongOk = rangePos<=maxLongPos
bool priceShortOk = rangePos>=minShortPos
// Precision engine: signals are emitted ONLY after a setup and subsequent confirmed price rejection.
// The confirmation candle is the signal candle. Never move a marker back to the pivot.
float ema50Local = ta.ema(close,50)
float ema200Local = ta.ema(close,200)
[diPlus,diMinus,adxValue] = ta.dmi(14,14)
bool strongBull = adxValue > 22 and diPlus > diMinus and ema50Local > ema200Local
bool strongBear = adxValue > 22 and diMinus > diPlus and ema50Local < ema200Local
float previousSwingLow = ta.lowest(low,structLen)[1]
float previousSwingHigh = ta.highest(high,structLen)[1]
float localRangePos = clamp(div(close-ta.lowest(low,structLen),math.max(ta.highest(high,structLen)-ta.lowest(low,structLen),eps)),0,1)
float qualityMultiplier = precisionMode == "Maximum" ? 1.22 : precisionMode == "Strict" ? 1.08 : 1.0
float requiredScore = math.min(95.0,scoreThreshold*qualityMultiplier)
bool lowContext = localRangePos <= 0.28 and (sweepLow or bullAbs or bullClimax or buyPeak)
bool highContext = localRangePos >= 0.72 and (sweepHigh or bearAbs or bearClimax or sellPeak)
bool lowSetup = lowRecent and lowContext and longScore >= requiredScore*0.67 and (not requireSweep or sweepLow)
bool highSetup = highRecent and highContext and shortScore >= requiredScore*0.67 and (not requireSweep or sweepHigh)
var int pendingLongBar = na
var int pendingShortBar = na
var float pendingLongHigh = na
var float pendingShortLow = na
var float pendingLongLow = na
var float pendingShortHigh = na
if barstate.isconfirmed
if lowSetup and na(pendingLongBar)
pendingLongBar := bar_index
pendingLongHigh := high
pendingLongLow := low
if highSetup and na(pendingShortBar)
pendingShortBar := bar_index
pendingShortLow := low
pendingShortHigh := high
bool longPending = not na(pendingLongBar) and bar_index > pendingLongBar and bar_index-pendingLongBar <= confirmBars
bool shortPending = not na(pendingShortBar) and bar_index > pendingShortBar and bar_index-pendingShortBar <= confirmBars
bool bullishRejection = close > open and close > close[1] and close > pendingLongHigh and closePos >= 0.58
bool bearishRejection = close < open and close < close[1] and close < pendingShortLow and closePos <= 0.42
bool flowImproving = flow > flow[1] and (deltaPct > -10 or bookFast > bookFast[1])
bool flowWeakening = flow < flow[1] and (deltaPct < 10 or bookFast < bookFast[1])
bool longTrendAllowed = not blockCounterTrend or not strongBear or (bullAbs and sweepLow)
bool shortTrendAllowed = not blockCounterTrend or not strongBull or (bearAbs and sweepHigh)
bool longConfirm = longPending and bullishRejection and flowImproving and longTrendAllowed and longScore >= requiredScore*0.72 and (mwBullContext or not mwBearContext or bullAbs or sweepLow)
bool shortConfirm = shortPending and bearishRejection and flowWeakening and shortTrendAllowed and shortScore >= requiredScore*0.72 and (mwBearContext or not mwBullContext or bearAbs or sweepHigh)
if precisionMode == "Maximum"
longConfirm := longConfirm and close > ta.ema(close,5) and (bullAbs or sweepLow or bullClimax or bullAbs[1] or sweepLow[1])
shortConfirm := shortConfirm and close < ta.ema(close,5) and (bearAbs or sweepHigh or bearClimax or bearAbs[1] or sweepHigh[1])
var int lastAny = na
var int lastLong = na
var int lastShort = na
// Early structural turning points: separate from delayed confirmation.
// A closed-bar sweep/reclaim or rejection at the bottom/top of a local range is mandatory.
float structLowRef = ta.lowest(low,structLen)[1]
float structHighRef = ta.highest(high,structLen)[1]
bool bottomReaction = (sweepLow or low <= structLowRef + atr*0.20) and closePos >= 0.62 and lowerWick >= rng*0.27
bool topReaction = (sweepHigh or high >= structHighRef - atr*0.20) and closePos <= 0.38 and upperWick >= rng*0.27
// A structural turn can occur before a higher-timeframe trend changes.
// The pivot is confirmed two bars later; the marker is placed on the confirmation bar.
float swingLowConfirmed = ta.pivotlow(low,2,2)
float swingHighConfirmed = ta.pivothigh(high,2,2)
bool structuralPivotLow = not na(swingLowConfirmed) and swingLowConfirmed <= ta.lowest(low,structLen)[2]+atr[2]*0.25 and close>close[2] and (fb[2]<fbLow+16 or lowRecent) and (buyX>0.85 or bullDeltaTurn)
bool structuralPivotHigh = not na(swingHighConfirmed) and swingHighConfirmed >= ta.highest(high,structLen)[2]-atr[2]*0.25 and close<close[2] and (fb[2]>fbHigh-16 or highRecent) and (sellX>0.85 or bearDeltaTurn)
bool earlyStructuralLong = barstate.isconfirmed and ((bottomReaction and (bullAbs or buyX >= 1.15 or bullDeltaTurn) and (lowRecent or fb < fbLow+12) and longScore >= 38) or structuralPivotLow)
bool earlyStructuralShort = barstate.isconfirmed and ((topReaction and (bearAbs or sellX >= 1.15 or bearDeltaTurn) and (highRecent or fb > fbHigh-12) and shortScore >= 38) or structuralPivotHigh)
bool spacingOk = na(lastAny) or bar_index-lastAny >= minEventSpacing
bool longEvent = barstate.isconfirmed and (longConfirm or earlyStructuralLong) and (not (shortConfirm or earlyStructuralShort) or longScore>shortScore) and spacingOk and (na(lastLong) or bar_index-lastLong >= cooldown)
bool shortEvent = barstate.isconfirmed and (shortConfirm or earlyStructuralShort) and (not (longConfirm or earlyStructuralLong) or shortScore>longScore) and spacingOk and (na(lastShort) or bar_index-lastShort >= cooldown)
if barstate.isconfirmed
if longEvent or not na(pendingLongBar) and (bar_index-pendingLongBar >= confirmBars or low < pendingLongLow-atr*0.8)
pendingLongBar := na
if shortEvent or not na(pendingShortBar) and (bar_index-pendingShortBar >= confirmBars or high > pendingShortHigh+atr*0.8)
pendingShortBar := na
if longEvent
lastLong := bar_index
lastAny := bar_index
if shortEvent
lastShort := bar_index
lastAny := bar_index
int sinceLong = nz(ta.barssince(longEvent),100000)
int sinceShort = nz(ta.barssince(shortEvent),100000)
// Quantum gates follow confirmed events only; EARLY cannot authorize entries.
bool longGate = (sinceLong <= gateBars or (gateMode == "Early or confirmed" and lowSetup and longScore >= scoreThreshold and (bullAbs or sweepLow) and not strongBear)) and localRangePos <= maxLongPos and longTrendAllowed
bool shortGate = (sinceShort <= gateBars or (gateMode == "Early or confirmed" and highSetup and shortScore >= scoreThreshold and (bearAbs or sweepHigh) and not strongBull)) and localRangePos >= minShortPos and shortTrendAllowed
bool earlyLong = showEarly and lowSetup and not longEvent
bool earlyShort = showEarly and highSetup and not shortEvent
bool confirmLong = longEvent
bool longNoTrade = (strongBear and not (bullAbs and sweepLow)) or (mwBearContext and not mwBullContext and not bullAbs)
bool shortNoTrade = (strongBull and not (bearAbs and sweepHigh)) or (mwBullContext and not mwBearContext and not bearAbs)
longGate := longGate and not longNoTrade
shortGate := shortGate and not shortNoTrade
float structureBias = (mwBullContext ? 1.0 : 0.0) - (mwBearContext ? 1.0 : 0.0)
bool confirmShort = shortEvent
// Three clearly separated visual bands. Price/flow are never mixed into one scale.
float C_FB = 210.0
float C_BAL = 105.0
float C_FLOW = 0.0
float fby = C_FB + (fb-50)*0.82
float fbLoY = C_FB + (fbLow-50)*0.82
float fbHiY = C_FB + (fbHigh-50)*0.82
float balScale = math.max(nz(ta.ema(math.abs(bookFast),70)),1.0)
float balRaw = clamp(bookFast/balScale,-2.5,2.5)
float balSmooth = ta.ema(balRaw,7)
float balY = C_BAL + balRaw*15
float balSlowY = C_BAL + balSmooth*15
float balHist = (balRaw-balSmooth)*12
float flowScale = math.max(nz(ta.ema(math.abs(flow),70)),1.0)
float flowDisplayNorm = clamp(flow/flowScale,-2.5,2.5)
float flowSignalNorm = ta.ema(flowDisplayNorm,5)
float flowY = flowDisplayNorm*15
float flowSigY = flowSignalNorm*15
hline(158,"FB / balance",color=color.new(color.gray,75),editable=false)
hline(51,"Balance / flow",color=color.new(color.gray,75),editable=false)
pFbTop = plot(C_FB+41,"FB upper",color=color.new(color.red,95),editable=false)
pFbBottom = plot(C_FB-41,"FB lower",color=color.new(color.green,95),editable=false)
fill(pFbTop,pFbBottom,color.new(#1d2939,96),title="FB band")
plot(fbLoY,"FB oversold",color=color.new(#159f89,20),editable=false)
plot(fbHiY,"FB overbought",color=color.new(#c45b76,20),editable=false)
plot(fby,"FB oscillator",color=#e98a2e,linewidth=3)
plot(C_FB+(ta.ema(fb,3)-50)*0.82,"FB recovery",color=color.new(#f9cb8a,70),editable=false)
// Critical-event rail: every qualifying critical bar is shown, without signal cooldown.
// An extreme must combine exceptional relative volume, range rejection and/or structural pivot.
float critVolume = nz(volume / math.max(ta.sma(volume,volLen),1),0)
float critRange = math.max(high-low,syminfo.mintick)
float critClosePos = (close-low)/critRange
bool critBull = barstate.isconfirmed and ((critVolume >= climaxX and critClosePos >= 0.60 and (low <= ta.lowest(low,structLen)[1] or structuralPivotLow)) or (structuralPivotLow and (bullAbs or critVolume >= 1.7)) or (sweepLow and bullAbs and critVolume >= 1.5))
bool critBear = barstate.isconfirmed and ((critVolume >= climaxX and critClosePos <= 0.40 and (high >= ta.highest(high,structLen)[1] or structuralPivotHigh)) or (structuralPivotHigh and (bearAbs or critVolume >= 1.7)) or (sweepHigh and bearAbs and critVolume >= 1.5))
// Mid-band = critical-event columns only; no zigzag balance lines.
plot(showBalance and critBull ? C_BAL+33 : na,"Critical buying",style=plot.style_columns,histbase=C_BAL,color=color.new(neonBuy,18),linewidth=27,editable=false)
plot(showBalance and critBear ? C_BAL-33 : na,"Critical selling",style=plot.style_columns,histbase=C_BAL,color=color.new(neonSell,18),linewidth=27,editable=false)
// Middle band: a blue smoothed RSI and thick vertical critical-event bars.
// RSI is centered on this band's own scale, not on the flow histogram.
float balanceRsi = ta.rsi(close, 14)
float balanceRsiMA = ta.ema(balanceRsi, 9)
float rsiDisplay = C_BAL + (balanceRsiMA-50.0)*0.72
plot(showBalance ? rsiDisplay : na, "RSI EMA 9 (14)", color=#537fce, linewidth=2)
plot(showBalance ? C_BAL : na,"RSI 50 / critical baseline",color=color.new(color.gray,83))
plot(showFlow ? C_FLOW : na,"Flow zero",color=color.new(color.gray,65),editable=false)
plot(showFlow ? math.max(flowY,0) : na,"Buy volume pressure",style=plot.style_columns,histbase=0,color=color.new(neonBuy,20),editable=false)
plot(showFlow ? math.min(flowY,0) : na,"Sell volume pressure",style=plot.style_columns,histbase=0,color=color.new(neonSell,20),editable=false)
plot(showFlow ? flowSigY : na,"Flow trigger",color=#dcae66,linewidth=2)
// Minimal pastel luminous accents, no diamonds or text in oscillator.
plotshape(showOscLabels and longEvent ? C_FB-43 : na,"BUY pulse",style=shape.circle,location=location.absolute,color=neonBuy,size=size.tiny,editable=false)
plotshape(showOscLabels and shortEvent ? C_FB+43 : na,"SELL pulse",style=shape.circle,location=location.absolute,color=neonSell,size=size.tiny,editable=false)
// Demand-only zones, anchored to the candle that rejects a structural low.
// Each zone is invalidated on a confirmed close below its low and removed on expiry.
var array<box> demandZones = array.new<box>()
var array<float> demandLows = array.new<float>()
var array<int> demandBorn = array.new<int>()
if barstate.isconfirmed
if array.size(demandZones)>0
for i=array.size(demandZones)-1 to 0
box b=array.get(demandZones,i)
float floor=array.get(demandLows,i)
int born=array.get(demandBorn,i)
bool dead=close<floor or bar_index-born>zoneBars
if dead
box.delete(b)
array.remove(demandZones,i)
array.remove(demandLows,i)
array.remove(demandBorn,i)
else
box.set_right(b,bar_index+5)
bool newDemand = showZones and (bottomReaction or structuralPivotLow) and (bullAbs or buyPeak or bullClimax or structuralPivotLow) and rangePos<=0.20 and close<=ta.lowest(close,structLen)+atr*1.1 and (na(lastLong) or bar_index-lastLong>=3)
if newDemand
float zTop=structuralPivotLow and not bottomReaction ? math.min(open[2],close[2]) : math.min(open,close)
float zLow=structuralPivotLow and not bottomReaction ? low[2] : low
bool overlap=false
if array.size(demandZones)>0
for j=0 to array.size(demandZones)-1
box other=array.get(demandZones,j)
float shared=math.min(zTop,box.get_top(other))-math.max(zLow,box.get_bottom(other))
overlap:=overlap or shared>0.35*math.min(zTop-zLow,box.get_top(other)-box.get_bottom(other))
if zTop>zLow and not overlap
box b=box.new(structuralPivotLow and not bottomReaction ? bar_index-2 : bar_index,zTop,bar_index+5,zLow,bgcolor=color.new(#0b9d89,91),border_color=color.new(#159f90,52),text="DEMAND · REJECTION",text_color=color.new(#0b8c7c,28),text_size=size.tiny,text_halign=text.align_right,force_overlay=true)
array.push(demandZones,b)
array.push(demandLows,zLow)
array.push(demandBorn,bar_index)
if array.size(demandZones)>maxZones
box.delete(array.shift(demandZones))
array.shift(demandLows)
array.shift(demandBorn)
if showSignals and longEvent
label.new(bar_index,low-atr*0.25,earlyStructuralLong and not longConfirm?"BUY":"BUY",style=label.style_label_up,color=markerBuy,textcolor=color.white,size=size.small,force_overlay=true)
if showSignals and shortEvent
label.new(bar_index,high+atr*0.25,earlyStructuralShort and not shortConfirm?"SELL":"SELL",style=label.style_label_down,color=markerSell,textcolor=color.white,size=size.small,force_overlay=true)
// Historical multi-timeframe registry: never discard valid older events just because a newer one appears.
// Only completed source bars are admitted. The 4H intrabar array retains 4H events on 1D charts.
var array<line> structureLines = array.new<line>()
var array<label> structureLabels = array.new<label>()
var array<float> structurePrices = array.new_float()
var array<int> structureDirections = array.new_int()
var array<int> structureTimes = array.new_int()
var array<int> structureOrigins = array.new_int()
var array<int> structurePeriods = array.new_int()
var array<string> structureNames = array.new_string()
var array<int> structureWrong = array.new_int()
var array<bool> structureTouched = array.new_bool()
var array<bool> structureDeparted = array.new_bool()
f_registerLevel(int d,float level,int eventTime,int originTime,int period,string tf) =>
if d != 0 and not na(level) and not na(eventTime) and not na(originTime) and originTime <= eventTime and eventTime <= time_close
bool found = false
if array.size(structureTimes)>0
for i=0 to array.size(structureTimes)-1
if array.get(structureTimes,i)==eventTime and array.get(structurePeriods,i)==period and array.get(structureDirections,i)==d
found := true
if not found
color col = d>0?levelBuy:levelSell
line ln = line.new(originTime,level,time+int(seconds*1000)*30,level,xloc=xloc.bar_time,color=color.new(col,100),width=2,force_overlay=true)
label lb = label.new(time,level,"",xloc=xloc.bar_time,style=label.style_label_left,color=color.new(col,100),textcolor=color.new(col,100),size=size.tiny,force_overlay=true)
array.push(structureLines,ln)
array.push(structureLabels,lb)
array.push(structurePrices,level)
array.push(structureDirections,d)
array.push(structureTimes,eventTime)
array.push(structureOrigins,originTime)
array.push(structurePeriods,period)
array.push(structureNames,tf)
array.push(structureWrong,0)
array.push(structureTouched,false)
array.push(structureDeparted,false)
if array.size(structureLines)>150
line.delete(array.shift(structureLines))
label.delete(array.shift(structureLabels))
array.shift(structurePrices)
array.shift(structureDirections)
array.shift(structureTimes)
array.shift(structureOrigins)
array.shift(structurePeriods)
array.shift(structureNames)
array.shift(structureWrong)
array.shift(structureTouched)
array.shift(structureDeparted)
true
if barstate.isconfirmed
// Standard HTF requests: only use a TF when it is at least as large as the chart.
if seconds <= 14400
f_registerLevel(dir4,lev4,t4,o4,14400,"4H")
if seconds <= 21600
f_registerLevel(dir6,lev6,t6,o6,21600,"6H")
if seconds <= 28800
f_registerLevel(dir8,lev8,t8,o8,28800,"8H")
if seconds <= 43200
f_registerLevel(dir12,lev12,t12,o12,43200,"12H")
if seconds <= 86400
f_registerLevel(dirD,levD,tD,oD,86400,"1D")
if seconds <= 259200
f_registerLevel(dir3D,lev3D,t3D,o3D,259200,"3D")
if seconds <= 604800
f_registerLevel(dirW,levW,tW,oW,604800,"1W")
// Intrabar 4H events: crucial on 6H/8H/12H/1D/3D/weekly/monthly charts.
if seconds > 14400
int n4 = array.size(lower4Dir)
if n4 > 0
for k=0 to n4-1
int d4 = array.get(lower4Dir,k)
if d4 != 0
f_registerLevel(d4,array.get(lower4Lev,k),array.get(lower4Time,k),array.get(lower4Origin,k),14400,"4H")
if array.size(structureLines)>0
for i=array.size(structureLines)-1 to 0
float level=array.get(structurePrices,i)
int side=array.get(structureDirections,i)
int born=array.get(structureTimes,i)
int sec=array.get(structurePeriods,i)
float buffer=atr*0.35*math.sqrt(clamp(sec/seconds,0.5,4.0))
bool wrong=side>0?close<level-buffer:close>level+buffer
int wrongCount=wrong?array.get(structureWrong,i)+1:0
array.set(structureWrong,i,wrongCount)
bool touched=low<=level+buffer*0.4 and high>=level-buffer*0.4
bool departed=array.get(structureDeparted,i) or (side>0?high>level+atr*0.5:low<level-atr*0.5)
array.set(structureDeparted,i,departed)
array.set(structureTouched,i,array.get(structureTouched,i) or (departed and touched))
// A wick alone never kills a level; two completed closes beyond the buffer do.
bool dead=wrongCount>=2
if dead
line.delete(array.get(structureLines,i))
label.delete(array.get(structureLabels,i))
array.remove(structureLines,i)
array.remove(structureLabels,i)
array.remove(structurePrices,i)
array.remove(structureDirections,i)
array.remove(structureTimes,i)
array.remove(structureOrigins,i)
array.remove(structurePeriods,i)
array.remove(structureNames,i)
array.remove(structureWrong,i)
array.remove(structureTouched,i)
array.remove(structureDeparted,i)
// Preserve nearest levels AND distant historical levels in both directions.
// The second pass selects remote levels from the retained registry, without
// using future data. These are independent from the 3+3 nearest levels.
if barstate.islast and array.size(structureLines)>0
array<float> distances=array.new_float()
for i=0 to array.size(structureLines)-1
float level=array.get(structurePrices,i)
bool departed=array.get(structureDeparted,i)
float dist=math.abs(close-level)/math.max(atr,syminfo.mintick)
bool candidate=showMTF and (departed or time-array.get(structureTimes,i)>array.get(structurePeriods,i)*1000)
array.push(distances,candidate?dist:1e10)
array<int> nearest=array.sort_indices(distances,order.ascending)
array<bool> selected=array.new_bool(array.size(structureLines),false)
array<float> shown=array.new_float()
int nearAbove=0
int nearBelow=0
for i in nearest
float level=array.get(structurePrices,i)
bool duplicate=false
for other in shown
duplicate:=duplicate or math.abs(other-level)<atr*0.25
bool above=level>=close
bool eligible=array.get(distances,i)<1e9 and not duplicate and (above?nearAbove<3:nearBelow<3)
if eligible
array.set(selected,i,true)
array.push(shown,level)
if above
nearAbove+=1
else
nearBelow+=1
// Older, unbroken and preferably untested remote M/W levels.
// Select up to 3 above and 3 below; do not replace nearest levels.
int remoteAbove=0
int remoteBelow=0
for pass=0 to 1
for i in nearest
float level=array.get(structurePrices,i)
bool above=level>=close
bool oldEnough=time-array.get(structureTimes,i)>=90*86400000
bool untouched=not array.get(structureTouched,i)
bool remote=array.get(distances,i)>=2.0
bool duplicate=false
for other in shown
duplicate:=duplicate or math.abs(other-level)<atr*0.25
bool eligible=array.get(distances,i)<1e9 and oldEnough and remote and not duplicate and not array.get(selected,i) and (pass==1 or untouched) and (above?remoteAbove<3:remoteBelow<3)
if eligible
array.set(selected,i,true)
array.push(shown,level)
if above
remoteAbove+=1
else
remoteBelow+=1
for i=0 to array.size(structureLines)-1
float level=array.get(structurePrices,i)
int side=array.get(structureDirections,i)
color col=side>0?levelBuy:levelSell
bool visible=array.get(selected,i)
line ln=array.get(structureLines,i)
label lb=array.get(structureLabels,i)
line.set_color(ln,color.new(col,visible?15:100))
line.set_x2(ln,time+int(seconds*1000)*30)
label.set_xy(lb,time+int(seconds*1000)*30,level)
label.set_text(lb,visible?(side>0?"l ChoCH · ":"s ChoCH · ")+array.get(structureNames,i):"")
label.set_textcolor(lb,color.new(col,visible?5:100))
// Stable numeric outputs for TradingView data window, alerts, and Pine source selection.
plot(structureBias,"STRUCTURE_BIAS",display=display.data_window)
plot(longNoTrade?1:0,"LONG_VETO",display=display.data_window)
plot(shortNoTrade?1:0,"SHORT_VETO",display=display.data_window)
plot(mwBullEvent?1:0,"MW_BULL_EVENT",display=display.data_window)
plot(mwBearEvent?1:0,"MW_BEAR_EVENT",display=display.data_window)
plot(longScore,"LONG_SCORE",display=display.data_window)
plot(longPending?1:0,"LONG_PENDING",display=display.data_window)
plot(shortPending?1:0,"SHORT_PENDING",display=display.data_window)
plot(shortScore,"SHORT_SCORE",display=display.data_window)
plot(longGate?1:0,"LONG_GATE",display=display.data_window)
plot(shortGate?1:0,"SHORT_GATE",display=display.data_window)
plot(longEvent?1:0,"LONG_EVENT",display=display.data_window)
plot(shortEvent?1:0,"SHORT_EVENT",display=display.data_window)
plot(deltaPct,"DELTA_PROXY_PERCENT",display=display.data_window)
plot(samples>0?1:0,"SOURCE_LTF_1_PROXY_0",display=display.data_window)
plot(buyX,"BUY_VOLUME_RELATIVE",display=display.data_window)
plot(sellX,"SELL_VOLUME_RELATIVE",display=display.data_window)
plot(cvdMomentum,"CVD_MOMENTUM",display=display.data_window)
alertcondition(longEvent,"LONG event","QLF: LONG {{ticker}} {{interval}}")
alertcondition(shortEvent,"SHORT event","QLF: SHORT {{ticker}} {{interval}}")
alertcondition(longGate and not longGate[1],"LONG gate ON","QLF: LONG GATE ON {{ticker}}")
alertcondition(shortGate and not shortGate[1],"SHORT gate ON","QLF: SHORT GATE ON {{ticker}}")