Community scripts › APEX - RAM Liquidation Intelligence v1.3.1

APEX - RAM Liquidation Intelligence v1.3.1

by RAMDEE · v1 · updated 1 h ago Order flowOpen source
APEX - RAM Liquidation Intelligence v1.3.1 by RAMDEE on the live order book chart

What it does

APEX identifies significant reported liquidations and concentrated liquidation waves. Diamonds represent Major liquidation activity, while squares represent Significant activity. Outlined price regions highlight liquidation-wave territories. Customizable marker colors allow traders to distinguish liquidation sides and classifications according to their visual preferences.

How it works

APEX analyzes native liquidation data using execution prices, timestamps, liquidation sides and reported USD values. Three detection mechanisms identify large individual reports, exceptional relative activity and accumulated liquidation waves. Events are grouped by time proximity, price proximity and liquidation side. Automatic sensitivity selects market-specific thresholds. Gold features refined sensitivity settings to better reflect its reported liquidation activity. Adaptive and Manual sensitivity modes are also available.

How to use it

Apply APEX to a supported market with native liquidation data. Start with Automatic sensitivity on a 1-minute or 5-minute chart. - Diamond: Major liquidation activity. - Square: Significant liquidation activity. - Light blue: Long liquidations. - Silver: Short liquidations. - Outlined regions: Active liquidation-wave territories. Marker colors are independently customizable. Select Live wall clock for intrabar monitoring or Chart edge for replay analysis. Observe price reactions around these locations alongside market structure and other order-flow information.

What's original

APEX combines immediate liquidation detection, relative significance and accumulated liquidation activity into a unified wave-clustering system. Market-specific sensitivity, structural invalidation, independent historical marker retention and distinct geometric classifications help traders interpret liquidation activity without excessive chart clutter. Rather than simply displaying individual liquidation reports, APEX organizes forced market participation into meaningful contextual references for discretionary analysis.

Limitations

APEX depends on native liquidation data availability and historical coverage. Missing, delayed or revised reports may affect detection. Historical markers may be unavailable during replay. Automatic sensitivity presets are experimental and may require adjustment across markets. Developing waves may expand or change classification as additional reports arrive. APEX displays reported liquidation activity, not estimated future liquidation levels. Liquidation regions may fail or become invalidated. Intended for discretionary analysis, not automated trading or financial advice.

Source code

Open source under MPL-2.0. Copy it with credit: "Copy to my scripts" adds the credit for you.

// RAM APEX v1.3.1 — Liquidation Intelligence | community release candidate.
// Market sensitivity revision: presets + causal adaptive thresholds; bounded lifecycle.
// All numeric detection defaults are experimental. No entry/exit logic or alerts.
// Current waves are reconstructed; bounded observed-anchor ledger is separate.
// First observation is a script evaluation/draw-call proxy, not provider receipt or screen paint.
script({name:"RAM APEX v1.3.1 — Liquidation Intelligence",bars:1500});
{
const prLiqOn=input.bool(true,"Defeated Prey — reported liquidations");
// Independent display filters; classification never changes detection eligibility.
const prShowMajor=input.bool(true,"Show Major liquidations");
const prShowSignificant=input.bool(true,"Show Significant liquidations");
const prSensitivity=input.select("Automatic","Liquidation sensitivity",["Automatic","Adaptive","Manual"]);
const prManualMajor=input.number(100000,"Manual | Major wave minimum (USD)",{min:1000,step:1000});
const prWindow=input.select("New York","Hunting ground",["New York","London","Tokyo","All hunting windows","All hours"]);
const prOutside=input.bool(true,"Dim outside hunting windows");
const prOrigin=input.bool(true,"Show origin session");
const prCap=input.int(3,"Maximum active liquidation rectangles",{min:1,max:12});
const prDiamondCap=input.int(200,"Maximum historical diamonds",{min:12,max:1000});
const prInspect=input.select("Alt+click","Prey details",["Alt+click","Latest (mobile)","Off"]);
const prDiagnostics=input.bool(false,"Full data diagnostics");
const prOpacity=input.int(80,"Region opacity (%)",{min:10,max:100});
const prMarkerSize=input.select("Normal","Prey marker size",["Small","Normal","Large"]);
const prMarkerFill=input.int(18,"Marker fill opacity (%)",{min:0,max:100});
const prWaveBands=input.bool(true,"Show liquidation wave rectangles");
const prLiqAge=input.int(24,"Liquidation rectangle maximum age (hours)",{min:24,max:72});
const prInstant=input.bool(true,"Immediate large liquidation reports");
const prManualInstant=input.number(100000,"Manual | Immediate liquidation minimum (USD)",{min:100,step:1000});
const prClock=input.select("Chart edge (replay safe)","Liquidation clock",["Chart edge (replay safe)","Live wall clock (live only)"]);
const prBlue=input.color("#9ED8FF","Long-context color");
const prGray=input.color("#D3D5DB","Short-context color");
// Existing colors control wave bands and, by default, marker outlines/fills.
const prCustomMarkerColors=input.bool(false,"Use separate marker colors");
const prMajorLong=input.color("#9ED8FF","Major diamond | Long liquidations");
const prMajorShort=input.color("#D3D5DB","Major diamond | Short liquidations");
const prSignificantLong=input.color("#9ED8FF","Significant square | Long liquidations");
const prSignificantShort=input.color("#D3D5DB","Significant square | Short liquidations");
const prTierMode=input.select("Current wave","Marker classification",["Current wave","First observed tier"]);
const prFinite=Number.isFinite,prPos=x=>prFinite(x)&&x>0;
// Explicit aliases only. Do not guess instrument from price or market cap.
const prSymbol=typeof market!=="undefined"&&market&&market.symbol!=null?String(market.symbol):"";
function prInstrument(symbol){
 const parts=String(symbol).toUpperCase().split(/[:/]/).map(x=>x.replace(/[^A-Z0-9]/g,""));
 const aliases={BTC:["BTC","XBT","BITCOIN"],ETH:["ETH","ETHEREUM"],SOL:["SOL","SOLANA"],XRP:["XRP"],US100:["US100","NASDAQ100","NASDAQ","NAS100","USTEC","NDX","XYZ100","NQ","MNQ"],US500:["US500","SP500","SPX500","SPX","SNP500","ES","MES"],GOLD:["GOLD","XAU","XAUUSD","GC","MGC"]};
 for(const part of parts){for(const key of Object.keys(aliases)){for(const alias of aliases[key]){
  if(part===alias||["USD","USDT","USDC","PERP","USDPERP","USDTPERP","USDCPERP","SWAP"].some(s=>part===alias+s))return key;
 }}}
 return "Unknown";
}
const prPresets={BTC:[100000,100000],ETH:[100000,100000],SOL:[10000,25000],XRP:[1000,5000],US100:[2000,10000],US500:[10000,25000],GOLD:[2500,10000]};
const prAsset=prInstrument(prSymbol),prPreset=prPresets[prAsset]||[100000,100000];
// Automatic-only experiment; preserve Adaptive warm-up and Manual behavior.
const prAutoImmediate={ETH:25000,SOL:5000,XRP:500,GOLD:1000};
const prAutoMajor={GOLD:5000};
const prRelativeFloor=prSensitivity==="Automatic"&&prAsset==="GOLD"?500:0;
const prInstantMin=prSensitivity==="Manual"?prManualInstant:prSensitivity==="Automatic"?(prAutoImmediate[prAsset]??prPreset[0]):prPreset[0];
const prMajorMin=prSensitivity==="Manual"?prManualMajor:prSensitivity==="Automatic"?(prAutoMajor[prAsset]??prPreset[1]):prPreset[1];
// Adaptive uses strictly prior same-side reports; freeze major cutoff at wave birth.
// Floors are experimental safeguards, not guarantees of significance.
function prCutoffs(h){
 if(prSensitivity!=="Adaptive"||h.vol.length<50)return [prInstantMin,prMajorMin];
 return [Math.max(1000,prQuant(h.vol,.99)),Math.max(5000,5*prQuant(h.vol,.95))];
}
function prSeconds(t){return !prFinite(t)?null:t>=946684800&&t<4102444800?t:t>=946684800000&&t<4102444800000?t/1000:null;}
function prTf(){
 if(typeof market==="undefined")return null;
 const x=String(market.timeframe).trim().toLowerCase(),m=/^(\d+)\s*(s|m|min|h|d)$/.exec(x);
 const explicit=m?Number(m[1])*({s:1,m:60,min:60,h:3600,d:86400})[m[2]]:null;
 const counts=new Map();if(typeof bars!=="undefined"&&Array.isArray(bars))for(let i=Math.max(1,bars.length-120);i<bars.length;i++){const t=prSeconds(bars[i]&&bars[i].time),prev=prSeconds(bars[i-1]&&bars[i-1].time),d=t!==null&&prev!==null?t-prev:NaN;if(prPos(d)&&d<=86400)counts.set(d,(counts.get(d)||0)+1);}
 const ranks=[...counts].sort((a,b)=>b[1]-a[1]||a[0]-b[0]),cad=ranks.length&&(!ranks[1]||ranks[0][1]>ranks[1][1])?ranks[0][0]:null;
 if(explicit)return explicit<=86400&&(!cad||cad===explicit||cad%explicit===0)?explicit:null;
 if(!/^\d+$/.test(x)||!cad)return null;
 const n=Number(x);return cad===n||cad===n*60?cad:null;
}
function prValidBar(b){return b&&prSeconds(b.time)!==null&&[b.open,b.high,b.low,b.close].every(prPos)&&b.high>=Math.max(b.open,b.close,b.low)&&b.low<=Math.min(b.open,b.close,b.high);}
const prN=typeof bars!=="undefined"&&Array.isArray(bars)?bars.length:0,prTF=prTf();
const prEdge=prN?prSeconds(bars[prN-1]&&bars[prN-1].time):null;
let prT=prEdge,prClockWarning="";
if(prClock==="Live wall clock (live only)"&&prEdge!==null){let w=null;try{w=prSeconds(Date.now());}catch(e){}if(w!==null&&prTF&&w>=prEdge&&w<prEdge+prTF)prT=w;else prClockWarning="Live clock not aligned; using chart edge";}
const prSessions=[["Tokyo","0900-1130","Asia/Tokyo","TKY"],["London","0800-1030","Europe/London","LON"],["New York","0930-1200","America/New_York","NY"]];
function prTags(t){try{return prSessions.filter(x=>inSession(t,x[1],x[2]));}catch(e){return [];}}
function prInWindow(t){if(prWindow==="All hours")return true;const tags=prTags(t);return prWindow==="All hunting windows"?tags.length>0:tags.some(x=>x[0]===prWindow);}
function prSession(t){const a=prTags(t);return a.length?a.map(x=>x[3]).join("+"):"—";}
function prMoney(x){return x>=1e9?"$"+(x/1e9).toFixed(2)+"B":x>=1e6?"$"+(x/1e6).toFixed(2)+"M":x>=1000?"$"+(x/1000).toFixed(1)+"K":"$"+Math.round(x);}
function prExactUTC(t){try{return new Date(t*1000).toISOString();}catch(e){return "unknown";}}
function prAge(t){const m=Math.max(0,Math.floor((prT-t)/60));return m<60?m+"m":Math.floor(m/60)+"h "+(m%60)+"m";}
function prUTC(t){try{return new Date(t*1000).toISOString().slice(5,16).replace("T"," ")+" UTC";}catch(e){return "unknown";}}
function prQuant(sorted,p){return sorted.length?sorted[Math.max(0,Math.min(sorted.length-1,Math.ceil(p*sorted.length)-1))]:null;}
function prLower(a,x){let l=0,h=a.length;while(l<h){const m=(l+h)>>1;if(a[m]<x)l=m+1;else h=m;}return l;}
function prInsert(a,x){a.splice(prLower(a,x),0,x);}
function prRemove(a,x){const i=prLower(a,x);if(a[i]===x)a.splice(i,1);}
const prATR=[],prBarOK=[],prCloseTime=[];
let prTR=[];
// The last chart bar is always developing. Closing time is its successor's open only
// for contiguous bars; at scheduled gaps use the normal interval, never the next session.
for(let i=0;i<prN-1;i++){
 const b=bars[i],t=prSeconds(b&&b.time),next=prSeconds(bars[i+1]&&bars[i+1].time);
 prBarOK[i]=!!(prTF&&prValidBar(b)&&next!==null&&next>=t+prTF);
 prCloseTime[i]=prBarOK[i]?t+prTF:null;
 if(!prBarOK[i]){prTR=[];continue;}
 const contiguous=i>0&&prBarOK[i-1]&&prCloseTime[i-1]===t;
 if(!contiguous)prTR=[];
 const prev=contiguous?bars[i-1].close:b.open;
 const tr=Math.max(b.high-b.low,Math.abs(b.high-prev),Math.abs(b.low-prev));
 prTR.push(tr);if(prTR.length>20)prTR.shift();
 if(prTR.length===20)prATR[i]=prTR.reduce((a,x)=>a+x,0)/20;
}
// Time index: malformed unrelated slots must not poison marker lookup.
const prTimeIndex=[];
for(let i=0;i<prN;i++){const t=prSeconds(bars[i]&&bars[i].time);if(t!==null)prTimeIndex.push({t,i});}
prTimeIndex.sort((a,b)=>a.t-b.t||a.i-b.i);
const prLiq={regions:[],status:"off",count:0,duplicates:0,oldest:null,latest:null,warm:false,invalid:0,future:0,raw:0,qualified:0,drawable:0,cutoffs:null};
function prLiqRun(){
 if(!prLiqOn)return;if(typeof liquidations==="undefined"||!Array.isArray(liquidations)){prLiq.status="Liquidations unavailable";return;}
 if(prT===null){prLiq.status="No chart clock";return;}
 prLiq.raw=liquidations.length;if(liquidations.length>30000){prLiq.status="Liquidation snapshot exceeds safety limit";return;}
 const seen=new Set(),ev=[];
 for(const x of liquidations){if(!x){prLiq.invalid++;continue;}const t=prSeconds(x.time);if(t===null||!prPos(x.price)||!prPos(x.value)||!(x.side==="long"||x.side==="short")){prLiq.invalid++;continue;}if(t>prT){prLiq.future++;continue;}const key=[t,x.side,x.price,x.value].join("|");if(seen.has(key)){prLiq.duplicates++;continue;}seen.add(key);ev.push({t,p:x.price,v:x.value,s:x.side,key});}
 ev.sort((a,b)=>a.t-b.t||a.s.localeCompare(b.s)||a.p-b.p||a.v-b.v);
 prLiq.count=ev.length;if(!ev.length){prLiq.status="Feed empty at chart time; coverage unverified";return;}
 prLiq.oldest=ev[0].t;prLiq.latest=ev[ev.length-1].t;
 let candidateWork=0;const MAX_CANDIDATE_WORK=2000000;
 const active={long:[],short:[]},history={long:{q:[],head:0,vol:[],gaps:[]},short:{q:[],head:0,vol:[],gaps:[]}};
 // Binary lookup over completed, valid ATR records, avoiding invalid chart slots.
 const av=[];for(let i=0;i<prN-1;i++)if(prCloseTime[i]!==null&&prPos(prATR[i]))av.push({t:prCloseTime[i],v:prATR[i]});
 function volAt(t){let l=0,h=av.length;while(l<h){const m=(l+h)>>1;if(av[m].t<=t)l=m+1;else h=m;}return l&&t-av[l-1].t<=2*prTF?av[l-1].v:null;}
 function trim(h,t){while(h.head<h.q.length&&h.q[h.head].t<t-86400){const old=h.q[h.head++];prRemove(h.vol,old.v);if(h.head<h.q.length)prRemove(h.gaps,h.q[h.head].t-old.t);}}
 function add(h,x){if(h.q.length>h.head)prInsert(h.gaps,x.t-h.q[h.q.length-1].t);h.q.push(x);prInsert(h.vol,x.v);}
 function seal(w,t){if(w.visible!==null)prLiq.regions.push({...w,t,origin:w.first,developing:false,revisits:0,rearm:true,traversed:null});}
 function expire(t){for(const s of ["long","short"]){const keep=[];for(const w of active[s]){const end=Math.min(w.last+w.gap,w.first+600);if(end<t)seal(w,end);else keep.push(w);}active[s]=keep;}}
 for(let i=0;i<ev.length;){const t=ev[i].t;expire(t);for(const s of ["long","short"])trim(history[s],t);let j=i;
   // same timestamp group: no report at t enters another report's baseline at t.
   while(j<ev.length&&ev[j].t===t){const x=ev[j++],h=history[x.s],V=volAt(t);// A single pass preserves nearest-midpoint, earliest-wave, insertion-order ties.
     // In an exceptionally fragmented snapshot, fail closed rather than stall or
     // silently use a partially reconstructed liquidation history.
     candidateWork+=active[x.s].length;
     if(candidateWork>MAX_CANDIDATE_WORK){prLiq.regions=[];prLiq.status="Liquidation clustering safety budget exceeded; no partial waves shown";return;}
     let w=null,best=Infinity;
     for(const c of active[x.s]){if(!prPos(c.V)||t>=c.first+600||t-c.last>c.gap||Math.max(c.hi,x.p)-Math.min(c.lo,x.p)>c.V+1e-9)continue;
       const d=Math.abs(x.p-(c.lo+c.hi)/2);if(d<best||(d===best&&w&&c.first<w.first)){w=c;best=d;}}
     const cuts=prCutoffs(h);if(!w&&(prPos(V)||(prInstant&&x.v>=cuts[0]))){const ready=h.vol.length>=50;const gap=Math.max(15,Math.min(120,3*(prQuant(h.gaps,0.5)||5)));w={s:x.s,V,first:t,last:t,lo:x.p,hi:x.p,v:0,n:0,gap,exception:ready?prQuant(h.vol,.99):null,threshold:ready?5*prQuant(h.vol,.95):null,visible:null,instant:false,immediateMin:cuts[0],majorMin:cuts[1],members:[],route:null,qualTier:null,epochs:[]};active[x.s].push(w);if(!ready)prLiq.warm=true;}
     if(w){const wasHidden=w.visible===null;w.lo=Math.min(w.lo,x.p);w.hi=Math.max(w.hi,x.p);w.last=t;w.v+=x.v;w.n++;w.members.push(x.key);if(prInstant&&x.v>=w.immediateMin){w.instant=true;if(w.visible===null){w.visible=t;w.route="Immediate";}}
     if(w.visible===null&&w.exception!==null&&w.v>=prRelativeFloor&&(x.v>=w.exception||(w.n>=3&&w.v>=w.threshold))){w.visible=t;w.route=x.v>=w.exception?"Exceptional":"Accumulation";}
     // Record the real report that first qualified the wave; never use an invented midpoint.
     if(wasHidden&&w.visible!==null){w.mark={time:x.t,price:x.p,volume:x.v,key:x.key};w.qualTier=w.v>=w.majorMin?"Major":"Significant";}
     if(w.visible!==null){const last=w.epochs[w.epochs.length-1];if(!last||last.lo!==w.lo||last.hi!==w.hi)w.epochs.push({t,lo:w.lo,hi:w.hi});}}
   }
   for(let k=i;k<j;k++)add(history[ev[k].s],ev[k]);i=j;
 }
 // At the exact end of a quiet gap, seal only when no event at that time remains.
 expire(prT+1e-6);
 for(const s of ["long","short"])for(const w of active[s])if(w.visible!==null)prLiq.regions.push({...w,t:prT,origin:w.first,developing:true,revisits:0,rearm:true,traversed:null});
 prLiq.qualified=prLiq.regions.length;
 for(const side of ["long","short"])trim(history[side],prT);
 prLiq.cutoffs={long:prCutoffs(history.long),short:prCutoffs(history.short),longN:history.long.vol.length,shortN:history.short.vol.length};
 // Ignore markers outside loaded bars before doing any lifecycle work. The
 // original renderer already excludes these, so this changes no visible output.
 // Filter after reconciliation: an original anchor may still be in loaded bars.
 prLiq.drawable=prLiq.regions.filter(q=>q.mark&&prBarAt(q.mark.time)>=0).length;
 prLiq.status="ok";
 if(!av.length)prLiq.status="No completed ATR; immediate reports only";
 else if(history.long.vol.length<50||history.short.vol.length<50)prLiq.status="Adaptive liquidation baseline building: longs "+history.long.vol.length+" / shorts "+history.short.vol.length+" (50 each)"+(prInstant?"; immediate threshold active":"");
}
if(prT!==null)prLiqRun();else if(prLiqOn)prLiq.status="No chart clock";
// The source tuple is the only available identity; genuine identical tuples remain ambiguous.
// Store only actually selected/drawn anchors, not inferred historical receipt times.
const prLedgerNotes=[];
const prLedgerSig=JSON.stringify([prSymbol,typeof market!=="undefined"?market.id||"":"",typeof market!=="undefined"?market.exchange||"":"",typeof market!=="undefined"?market.venue||"":"",prTF,prClock,prSensitivity,prInstant,prInstantMin,prMajorMin]);
let prLedger=null,prInitial=false;
const prLedgerKey="ramApex13Observed";
if(typeof state==="object"&&state&&prT!==null){
 let old=state[prLedgerKey];
 if(!old||old.sig!==prLedgerSig||!Array.isArray(old.items)||!prFinite(old.edge)||prT<old.edge){old={sig:prLedgerSig,edge:prT,items:[]};state[prLedgerKey]=old;prInitial=true;prLedgerNotes.push("Observation ledger initialized/reset; earlier visibility unknown");}
 old.edge=prT;prLedger=old;
 const first=prTimeIndex.length?prTimeIndex[0].t:-Infinity;
 old.items=old.items.filter(r=>r&&typeof r.key==="string"&&prFinite(r.time)&&r.time>=first&&r.time<=prT&&prPos(r.price));
}else prLedgerNotes.push("Persistent observation state unavailable; snapshot anchors only");
// Keep newest source-time observations first. Eviction affects anchor persistence,
// never eligibility to draw a report from the current snapshot.
function prPruneLedger(){
 if(!prLedger)return;
 prLedger.items.sort((a,b)=>b.time-a.time||b.observed-a.observed||a.key.localeCompare(b.key));
 let chars=JSON.stringify({...prLedger,items:[]}).length,keep=[];
 for(const r of prLedger.items){const n=JSON.stringify(r).length+1;if(keep.length>=1000||chars+n>74000)break;keep.push(r);chars+=n;}
 if(keep.length<prLedger.items.length){prLedgerNotes.push("Oldest anchor observations evicted; current snapshot markers remain eligible");prLedger.items=keep;}
}
prPruneLedger();
const prByKey=new Map();
if(prLedger)for(const r of prLedger.items)prByKey.set(r.key,r);
// Reconcile only by exact membership of the originally observed report. Never infer a
// match from approximate price/time. If the report disappears, retain an archived marker.
const prObserved=[],prMatched=new Set();
const prHealthy=prLiq.status==="ok"||prLiq.status.startsWith("Adaptive liquidation baseline building")||prLiq.status.startsWith("No completed ATR");
if(prHealthy){
 for(const q of prLiq.regions){
  const found=[];for(const k of q.members||[]){const r=prByKey.get(k);if(r)found.push(r);}
  if(!found.length){prObserved.push(q);continue;}
  found.sort((a,b)=>a.observed-b.observed||a.time-b.time||a.price-b.price);
  for(let j=0;j<found.length;j++){
   const r=found[j];prMatched.add(r.key);
   const revised=q.mark.key!==r.reconstructedKey||q.lo!==r.lo||q.hi!==r.hi||q.v!==r.total||q.n!==r.n||prTier(q)!==r.currentTier||q.developing!==r.developing;
   if(q.lo!==r.lo||q.hi!==r.hi)r.rangeKnown=prT;
   if(revised){r.revisions=(r.revisions||0)+1;r.lastRevision=prT;}
   r.reconstructedKey=q.mark.key;r.lo=q.lo;r.hi=q.hi;r.total=q.v;r.n=q.n;r.currentTier=prTier(q);r.developing=q.developing;
   prObserved.push({...q,mark:{time:r.time,price:r.price,volume:r.volume,key:r.key},visible:r.time,observed:r,rangeKnown:r.rangeKnown,mergedSecondary:j>0});
  }
 }
}
if(prLedger)for(const r of prLedger.items)if(!prMatched.has(r.key)){
 // An absent original report/qualification is NOT evidence of price invalidation.
 prObserved.push({s:r.side,V:r.V,mark:{time:r.time,price:r.price,volume:r.volume,key:r.key},visible:r.time,t:r.time,lo:r.lo,hi:r.hi,v:r.total,n:r.n,majorMin:r.majorMin,developing:false,revisits:0,bandExpired:prT,observed:r,orphan:true,rangeKnown:r.rangeKnown});
}
prLiq.regions=prObserved.filter(q=>q.mark&&prBarAt(q.mark.time)>=0);
function prRemember(q){
 if(q.observed||!prHealthy)return true;
 if(!prLedger){q.rangeKnown=prT;return true;}
 const r={key:q.mark.key,time:q.mark.time,price:q.mark.price,volume:q.mark.volume,side:q.s,V:prPos(q.V)?q.V:null,observed:prT,clock:prClock,initial:prInitial||q.mark.time<prEdge,firstTier:prTier(q),qualTier:q.qualTier,route:q.route,majorMin:q.majorMin,currentTier:prTier(q),reconstructedKey:q.mark.key,lo:q.lo,hi:q.hi,total:q.v,n:q.n,developing:q.developing,rangeKnown:prT,revisions:0};
 // Batch admission, then bounded newest-first retention after drawing.
 prLedger.items.push(r);prByKey.set(r.key,r);q.observed=r;q.rangeKnown=r.rangeKnown;return true;
}
// Binary search completed bars by time. Use a dense valid index so malformed
// slots never break monotonic search. Calculate only the visual revisit flag;
// the unused traversal timestamp and exact revisit count are not rendered.
const prValidIndices=[];
for(let i=0;i<prN-1;i++)if(prBarOK[i])prValidIndices.push(i);
function prLifecycle(q){
 q.bandExpired=null;q.revisits=0;
 // Replay source-time geometry, never the final expanded range at an earlier close.
 // At equal timestamps, a completed close precedes the newly reported event.
 const epochs=q.epochs&&q.epochs.length?q.epochs:[{t:prFinite(q.visible)?q.visible:q.t,lo:q.lo,hi:q.hi}];
 const birth=epochs[0].t,favorable=q.s==="long"?1:-1;
 let l=0,h=prValidIndices.length;
 while(l<h){const m=(l+h)>>1;if(prCloseTime[prValidIndices[m]]<=birth)l=m+1;else h=m;}
 let departed=false,anchor=0,k=0;
 for(let j=l;j<prValidIndices.length;j++){
  const i=prValidIndices[j],b=bars[i],ct=prCloseTime[i];if(ct>prT)break;
  while(k+1<epochs.length&&epochs[k+1].t<ct)k++;
  const g=epochs[k],side=b.close>g.hi?1:b.close<g.lo?-1:0;
  if(side===-favorable||(departed&&side===0)){q.bandExpired=ct;return;}
  if(side===favorable)departed=true;
  if(prSeconds(b.time)>=birth){if(!anchor){if(side)anchor=side;}
   else if(b.high>=g.lo&&b.low<=g.hi)q.revisits=1;}
 }
}
function prTier(q){return q.orphan&&q.observed?q.observed.currentTier:q.v>=q.majorMin?"Major":"Significant";}
function prMarkerTier(q){return prTierMode==="First observed tier"&&q.observed?q.observed.firstTier:prTier(q);}
function prTierVisible(q){return prTier(q)==="Major"?prShowMajor:prShowSignificant;}
function prMarkerVisible(q){return prMarkerTier(q)==="Major"?prShowMajor:prShowSignificant;}
function prTint(c,a){if(/^#[0-9a-f]{6}$/i.test(c))return c+Math.round(a*255).toString(16).padStart(2,"0");return c;}
function prDistance(q,p){return p<q.lo?q.lo-p:p>q.hi?p-q.hi:0;}
const prPrice=prN&&prValidBar(bars[prN-1])?bars[prN-1].close:0;
const prDim=prT!==null&&prOutside&&!prInWindow(prT);
// Display-only: candle-anchored diamonds. Historical markers and active bands are independent.
const prVisible=[];
function prBarAt(t){
 if(!prTF||!prN||!prFinite(t))return -1;
 // Normal chart bars are sorted. Sparse or malformed time slots are rejected
 // rather than mapped to a different candle; binary search is bounded.
 let l=0,h=prTimeIndex.length;while(l<h){const m=(l+h)>>1;if(prTimeIndex[m].t<=t)l=m+1;else h=m;}
 const x=prTimeIndex[l-1];return x&&t>=x.t&&t<x.t+prTF?x.i:-1;
}
function prGeometry(q){
 if(!q.mark||!prPos(q.mark.price))return null;
 const i=prBarAt(q.mark.time);if(i<0)return null;
 const scale=(prMarkerSize==="Small"?.75:prMarkerSize==="Large"?1.25:1)*(prMarkerTier(q)==="Major"?1:.80);
 // The chart API documents time/price coordinates, not pixel conversion for paths.
 // Bounded candle-width and volatility fractions; pixel aspect changes with chart zoom.
 const v=q.observed?(prPos(q.observed.V)?q.observed.V:q.mark.price*.001):(prPos(q.V)?q.V:q.mark.price*.001);
 const x=prSeconds(bars[i].time),y=q.mark.price;
 return {q,layer:"liq",i,x,y,dx:prTF*.30*scale,dy:v*.145*scale};
}
function prGap(){return Math.max((prATR[prN-2]||prPrice*.0005)*.035,prPrice*1e-8);}
function prLabel(q){
 const title=q.s==="long"?"DP: Longs liquidated":"DP: Shorts liquidated";
 const expired=q.bandExpired!==null||prT-q.visible>=prLiqAge*3600;
 return prTier(q)+" | marker "+prMarkerTier(q)+" | "+title+" @ "+q.mark.price+" | "+prMoney(q.v)+" reported | "+q.n+" events"+(q.developing?" | forming":" | sealed")+(expired?" | rectangle expired":"")+" | "+prAge(q.visible)+(prOrigin?" | "+prSession(q.mark.time):"")+(q.observed?" | source "+prExactUTC(q.mark.time)+" | first evaluated "+prExactUTC(q.observed.observed)+(q.observed.initial?" (loaded/delayed history)":"")+" | first tier "+q.observed.firstTier+" | route "+(q.observed.route||"unknown")+" | revisions "+q.observed.revisions:" | snapshot only")+(q.orphan?" | archived: absent from current qualified snapshot":"");
}
// Match ATLAS Big Trades' alpha-aware fill; do not rely on 8-digit hex for canvas fill.
function prMarkerTint(c,a){
 const opacity=Math.max(0,Math.min(1,a));
 if(typeof color!=="undefined"&&color&&typeof color.new==="function")return color.new(c,opacity);
 const m=/^#([0-9a-f]{6})$/i.exec(c);
 if(m){const v=parseInt(m[1],16);return "rgba("+((v>>16)&255)+","+((v>>8)&255)+","+(v&255)+","+opacity+")";}
 return opacity===0?"rgba(0,0,0,0)":"transparent";
}
function prDraw(g,showBand,showDiamond=true){
 const {q,x,y,dx,dy}=g,base=q.s==="long"?prBlue:prGray,major=prMarkerTier(q)==="Major";
 const markerBase=prCustomMarkerColors?(major?(q.s==="long"?prMajorLong:prMajorShort):(q.s==="long"?prSignificantLong:prSignificantShort)):base;
 const alpha=(prOpacity/100)*(prDim?.55:1)*(q.bandExpired!==null?.35:q.revisits?.8:q.developing?.9:1),color=prTint(markerBase,alpha);
 const hollow=!!q.developing,fill=prMarkerTint(markerBase,hollow?0:alpha*prMarkerFill/100);
 // Wave band starts only at the qualifying report candle, never before visibility.
 // A single-price wave remains a thin line rather than inventing a range.
 if(showBand){
   const start=prFinite(q.rangeKnown)?q.rangeKnown:q.visible,end=Math.max(prEdge+prTF*.45,Math.min(prEdge+prTF,prT+prTF*.05));
   if(prFinite(start)&&end>=start){const opt={color:prTint(base,alpha*.42),width:1,style:"dashed"};
     draw.line(start,q.lo,end,q.lo,opt);
     if(q.hi>q.lo){draw.line(start,q.hi,end,q.hi,opt);draw.line(start,q.lo,start,q.hi,opt);draw.line(end,q.lo,end,q.hi,opt);}
     g.bandStart=start;g.bandEnd=end;
   }
 }
 if(showDiamond){
 const pts=major?[[x,y-dy],[x+dx,y],[x,y+dy],[x-dx,y]]:[[x-dx,y-dy],[x+dx,y-dy],[x+dx,y+dy],[x-dx,y+dy]];
 if(typeof canvas!=="undefined"&&typeof canvas.path==="function"){
   canvas.path([["M",...pts[0]],...[1,2,3].map(i=>["L",...pts[i]]),["Z"]],{stroke:color,fill,width:1.5});
 }else{
   for(let i=0;i<4;i++){const a=pts[i],b=pts[(i+1)%4];draw.line(a[0],a[1],b[0],b[1],{color,width:2,style:"solid"});}
 }
 }
 prVisible.push({...g,color:showDiamond?color:prTint(base,alpha),showDiamond,markerTier:major?"Major":"Significant"});
}
function prPick(visible,click){
 if(!click||!prPos(click.price))return [];
 const t=prSeconds(click.time);if(t===null)return [];
 const i=Number.isInteger(click.bar)&&click.bar>=0&&click.bar<prN?click.bar:prBarAt(t);
 const hits=visible.filter(g=>g.showDiamond!==false&& (i===g.i||Math.abs(t-g.x)<=Math.max(g.dx,prTF*.45))&&Math.abs(click.price-g.y)<=Math.max(g.dy*1.5,prGap()));
 // Direct marker hit beats a band hit; no price-only fallback elsewhere on chart.
 if(hits.length)return hits.sort((a,b)=>Math.abs(a.y-click.price)-Math.abs(b.y-click.price)||Math.abs(a.x-t)-Math.abs(b.x-t)||b.q.t-a.q.t);
 return visible.filter(g=>g.layer==="liq"&&prFinite(g.bandEnd)&&t>=g.bandStart&&t<=g.bandEnd&&prDistance(g.q,click.price)<=prGap()).sort((a,b)=>prDistance(a.q,click.price)-prDistance(b.q,click.price)||b.q.t-a.q.t);
}
function prDetails(){
 if(prInspect==="Off"||!prVisible.length)return;
 let hits=[];
 if(prInspect==="Latest (mobile)")hits=prVisible.slice().sort((a,b)=>b.q.mark.time-a.q.mark.time).slice(0,1);
 else {const clicks=typeof interact==="object"&&interact?interact.clicks:null;const c=clicks&&clicks[clicks.length-1];if(!c)return;hits=prPick(prVisible,c);}
 if(!hits.length)return;
 // If two actual markers coincide, disclose both in one local label, not a top card.
 // An anchored label is preferred; fallback canvas text remains at the selected object.
 const g=hits[0],text=hits.slice(0,2).map(v=>prLabel(v.q)+" | anchor "+prMoney(v.q.mark.volume)).join("   /   ")+(hits.length>2?" +"+(hits.length-2)+" overlaps":"");
 const y=g.y+g.dy*1.8;
 if(typeof plot!=="undefined"&&typeof plot.label==="function")plot.label(g.i,y,text,{color:g.color,background:"#151C26",textColor:"#E8EDF4",size:"small",align:"right"});
 else if(typeof canvas!=="undefined"&&typeof canvas.text==="function")canvas.text(g.x+prTF*.45,y,text,{size:12,color:"#E8EDF4",background:"#151C26"});
 else if(typeof draw.text==="function")draw.text(g.x+prTF*.45,y,text);
}
if(prT!==null&&typeof draw!=="undefined"&&typeof draw.line==="function"&&prLiqOn){
 // Select current active regions independently of the historical diamond limit.
 const all=prLiq.regions.map(prGeometry).filter(Boolean);
 const retained=all.filter(g=>prMarkerVisible(g.q)).sort((a,b)=>b.q.visible-a.q.visible||b.q.mark.price-a.q.mark.price).slice(0,prDiamondCap);
 const ranked=prPrice&&prHealthy&&prWaveBands?all.filter(g=>!g.q.orphan&&!g.q.mergedSecondary&&prTierVisible(g.q)&&prT-g.q.visible<prLiqAge*3600).sort((a,b)=>Number(b.q.developing)-Number(a.q.developing)||prDistance(a.q,prPrice)-prDistance(b.q,prPrice)||b.q.visible-a.q.visible):[];
 const active=[];
 for(const g of ranked){
   if(active.length>=prCap)break;
   if(active.some(a=>g.q.lo<=a.q.hi+prGap()&&g.q.hi>=a.q.lo-prGap()))continue;
   prLifecycle(g.q);if(g.q.bandExpired!==null)continue;
   active.push(g);
 }
 const activeSet=new Set(active),markerSet=new Set(retained);
 for(const g of new Set([...retained,...active])){
   if(!g.q.orphan&&!g.q.mergedSecondary&&!activeSet.has(g))prLifecycle(g.q);
   if(g.q.mergedSecondary)g.q.bandExpired=null;
   prRemember(g.q);
   prDraw(g,activeSet.has(g),markerSet.has(g));
 }
 prPruneLedger();
 prDetails();
}
// No permanent top card; diagnostics are opt-in only.
const prWarnings=[];
if(prLiqOn){
 prWarnings.push(prSensitivity+" | "+(prSymbol||"Unknown symbol")+" → "+prAsset+" | immediate "+prMoney(prInstantMin)+" / major "+prMoney(prMajorMin)+(prSensitivity==="Adaptive"?" (warm-up fallback)":""));
 if(prRelativeFloor>0)prWarnings.push("Gold Automatic | relative wave minimum "+prMoney(prRelativeFloor));
 if(prAsset==="Unknown"&&prSensitivity!=="Manual")prWarnings.push("Unrecognized symbol: conservative fallback; use Manual if needed");
 if(prLiq.cutoffs&&prSensitivity==="Adaptive"){const c=prLiq.cutoffs;prWarnings.push("Next wave thresholds: longs "+prMoney(c.long[0])+" / "+prMoney(c.long[1])+" ("+c.longN+"); shorts "+prMoney(c.short[0])+" / "+prMoney(c.short[1])+" ("+c.shortN+")");}
 prWarnings.push("Raw "+prLiq.raw+" | valid "+prLiq.count+" | invalid "+prLiq.invalid+" | future "+prLiq.future+" | duplicate "+prLiq.duplicates+" | qualified "+prLiq.qualified+" | on chart "+prLiq.drawable);
 if(prLiq.count>0&&!prLiq.qualified)prWarnings.push("Reports present; no qualified waves");
}
if(prClockWarning)prWarnings.push(prClockWarning);
if(prLiqOn){if(prLiq.status!=="ok")prWarnings.push(prLiq.status);if(prLiq.oldest!==null)prWarnings.push("Reported feed: "+prLiq.count+" from "+prUTC(prLiq.oldest)+"; coverage unverified");}
if(prLiqOn){
 const health=[];
 if(!prHealthy)health.push(prLiq.status);
 const archived=prLiq.regions.filter(q=>q.orphan).length;if(archived)health.push(archived+" archived anchor(s) absent from current qualified snapshot; no current bands");
 if(prClockWarning)health.push(prClockWarning);
 if(prClock==="Chart edge (replay safe)")health.push("Bar-open cutoff; intrabar reports may wait until next candle");
 if(!prPrice)health.push("Current bar invalid; band ranking unavailable");
 if(prLedgerNotes.length)health.push(...prLedgerNotes);
 if(prDiagnostics)prWarnings.push(...health,"Observation count "+(prLedger?prLedger.items.length:0)+"; script evaluation time, not verified receipt/render latency");
 if(typeof plot!=="undefined"&&typeof plot.info==="function"){
  if(prDiagnostics)plot.info([["RAM APEX",prWarnings.join(" | ")]]);
  // No automatic status cards. Enable diagnostics to inspect feed/retention health.
 }
}
// No alerts, signals, strategies or execution.
}

Comments · 0