@luxalgo/vela 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- var Vela=(function(exports){'use strict';function le(s){return s.kind!=="candle"&&s.kind!=="bar"&&s.kind!=="markers"}var ct=class{constructor(){this.handlers=new Map;}on(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n));let r=n;return r.add(t),()=>{r.delete(t);}}off(e,t){this.handlers.get(e)?.delete(t);}hasListeners(e){return (this.handlers.get(e)?.size??0)>0}emit(e,t){let n=this.handlers.get(e);if(n)for(let r of n)try{r(t);}catch(i){console.error(`[vela] event handler error for "${String(e)}"`,i);}}clear(){this.handlers.clear();}};var hr=class{constructor(){this.records=new Map;this.counter=0;}nextId(e="ind"){return this.counter+=1,`${e}-${this.counter}`}add(e){this.records.set(e.id,e);}get(e){return this.records.get(e)}remove(e){let t=this.records.get(e);return this.records.delete(e),t}all(){return [...this.records.values()]}};var mn=new Map;function _t(s){mn.set(s.type,s);}function ua(s){mn.delete(s);}function fn(s){return mn.get(s)}function pa(){return [...mn.keys()]}function ur(){return [...mn.values()]}var pr=class{constructor(e,t,n){this.feed=e;this.market=t;this.onBar=n;this.unsubscribe=null;}start(){this.unsubscribe||(this.unsubscribe=this.feed.subscribe(this.market,this.onBar));}stop(){this.unsubscribe?.(),this.unsubscribe=null;}};var Nt=class{constructor(e,t,n,r){this.controller=n;this.schema=[];this.visibleState=true;this.bus=new ct;this.id=e,this.title=t,r!==void 0&&(this.source=r);}get inputs(){return this.schema}get visible(){return this.visibleState}setInput(e,t){this.controller.applyInputs(this.id,{[e]:t});}setInputs(e){this.controller.applyInputs(this.id,e);}setVisible(e){this.controller.setVisible(this.id,e);}moveTo(e){this.controller.moveIndicator(this.id,e);}on(e,t){return this.bus.on(e,t)}context(e){return this.controller.getIndicatorContext(this.id,e)}remove(){this.controller.removeIndicator(this.id);}setSchema(e){this.schema=e;}setVisibleState(e){this.visibleState=e;}emit(e,t){this.bus.emit(e,t);}};function Yd(s){let e={};for(let t of s.series)e[t.kind]=(e[t.kind]??0)+1;return {id:s.id,title:s.title,overlay:s.overlay,paneId:s.paneId,native:!!s.native,nativeType:s.native?.type,series:e,fills:s.fills.length,backgrounds:s.backgrounds.length,priceLines:s.priceLines.length,lines:s.lines?.length??0,boxes:s.boxes?.length??0,labels:s.labels?.length??0,polylines:s.polylines?.length??0,linefills:s.linefills?.length??0,tables:s.tables?.length??0,barColors:s.barColors?.length??0,trades:s.trades?.length??0,inputs:s.inputs.length}}function ma(s){let e=s.map(Yd),t=n=>e.reduce((r,i)=>r+n(i),0);return {indicators:e,totals:{panes:new Set(e.map(n=>n.paneId??"price")).size,series:t(n=>Object.values(n.series).reduce((r,i)=>r+i,0)),fills:t(n=>n.fills),backgrounds:t(n=>n.backgrounds),priceLines:t(n=>n.priceLines),lines:t(n=>n.lines),boxes:t(n=>n.boxes),labels:t(n=>n.labels),polylines:t(n=>n.polylines),linefills:t(n=>n.linefills),tables:t(n=>n.tables),barColors:t(n=>n.barColors),trades:t(n=>n.trades)}}}var Xd={"1D":864e5,"1W":6048e5,"1M":2592e6,"3M":7776e6,"6M":15552e6,"1Y":31536e6,"5Y":15768e7};function fa(s,e){if(e.length===0)return null;let t=e[0].time,n=e[e.length-1].time;if(s==="ALL")return {from:t,to:n};let r;return s==="YTD"?r=Date.UTC(new Date(n).getUTCFullYear(),0,1):r=n-Xd[s],{from:Math.max(t,r),to:n}}var ve="#2962ff",mr="#38c0fd",q="#089981",X="#f23645",he="#787b86",ga="#e0b400",bn="#ff9800",_e="#5b9cf6",va="#ff5d00",fr="#0ecb81",br="#f6465d",hv="#f97316",uv="#0ea5e9",pv="#9ca3af",gn="#3b82f6",ya="#9aa0ad",xa="#1e293b",gr="#475569",wa=ve,Sa=X,Ca="#d500f9",ba=[ve,q,X,bn,"#7e57c2","#26a69a",_e,"#e573b5"];function mv(s){let e=0;for(let t=0;t<s.length;t++)e=e*31+s.charCodeAt(t)>>>0;return ba[e%ba.length]}var R=mr;function Ro(){return {lineColor:R,lineWidth:2,lineStyle:"solid"}}function Ne(s=""){return {value:s,size:"normal",hAlign:"left",vAlign:"top"}}var vr=class vr{constructor(e){this.locked=false;this.visible=true;this.zIndex=0;this.id=e.id??`dw-${vr.seq+=1}`,this.paneId=e.paneId,this.anchors=(e.anchors??[]).map(t=>({time:t.time,price:t.price})),this.style=e.style?{...e.style}:Ro(),this.text=e.text?{...e.text}:void 0,this.locked=e.locked??false,this.visible=e.visible??true,this.zIndex=e.zIndex??0,this.createdAt=e.createdAt??Date.now(),e.props&&this.readProps(e.props);}isComplete(){return this.anchors.length>=this.anchorSchema().min}placementMode(){return "click"}onPlaced(e){}constrainHandleDrag(e){}translateBody(e,t,n){return n.map(r=>({time:r.time+e,price:r.price+t}))}timeExtent(){if(this.anchors.length===0)return null;let e=1/0,t=-1/0;for(let n of this.anchors)n.time<e&&(e=n.time),n.time>t&&(t=n.time);return {min:e,max:t}}editableLevels(){return null}applySettings(e){for(let[t,n]of Object.entries(e))t.startsWith("text.")&&!this.text&&(this.text=Ne()),Ta(this,t,n);}applyProps(e){this.readProps(e);}serialize(){return {id:this.id,type:this.type,paneId:this.paneId,anchors:this.anchors.map(e=>({time:e.time,price:e.price})),style:{...this.style},text:this.text?{...this.text}:void 0,locked:this.locked,visible:this.visible,zIndex:this.zIndex,createdAt:this.createdAt,props:this.writeProps()}}writeProps(){}readProps(e){}};vr.seq=0;var B=vr;function Ta(s,e,t){let n=e.split("."),r=s;for(let i=0;i<n.length-1;i+=1){let o=n[i],a=r[o];(a==null||typeof a!="object")&&(a={},r[o]=a),r=a;}r[n[n.length-1]]=t;}var Do=new Map;function D(s,e){Do.set(s,e);}function Ma(s){return Do.get(s)??null}function $(s){return Do.get(s)??""}function oe(s,e){return $(s).replace("<svg ",`<svg width="${e}" height="${e}" `)}function La(s,e=""){return `<svg viewBox="0 0 16 16" width="1em" height="1em" ${e?e+" ":""}fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">${s}</svg>`}function I(s,e=""){return `<svg viewBox="0 0 24 24" width="1em" height="1em" ${e?e+" ":""}fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${s}</svg>`}function Ao(s){return `<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" stroke="none">${s}</svg>`}var _=La;D("style-candles",_('<path d="M4.5 2v2M4.5 12v2M11.5 2v1.5M11.5 11v3"/><rect x="2.8" y="4" width="3.4" height="8" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="9.8" y="3.5" width="3.4" height="7.5" rx="0.6" fill="currentColor"/>'));D("style-bars",_('<path d="M4.5 2.5v11M2.5 5h2M4.5 11h2"/><path d="M11.5 2.5v11M9.5 4.5h2M11.5 10.5h2"/>'));D("style-line",_('<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/>'));D("style-area",_('<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/><path d="M1.5 11.5 5.5 7l3 2.5 5-6V13.5h-12z" fill="currentColor" fill-opacity="0.25" stroke="none"/>'));D("style-baseline",_('<path d="M1.5 8h13" stroke-dasharray="2 2"/><path d="M2.5 8 5.25 4.5 8 8h-5.5z" fill="currentColor" fill-opacity="0.25" stroke="none"/><path d="M2.5 8 5.25 4.5 8 8"/><path d="M8 8l2.75 3.5L13.5 8h-5.5z" fill="currentColor" fill-opacity="0.25" stroke="none"/><path d="M8 8l2.75 3.5L13.5 8"/>'));D("style-heikinashi",_('<path d="M4.5 12v2M11.5 2v2"/><rect x="2.8" y="5" width="3.4" height="7" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="9.8" y="4" width="3.4" height="7" rx="0.6" fill="currentColor"/>'));D("indicators",_('<path d="M1.5 12.5 5 7l2.5 3.5L11 4l3.5 5"/><circle cx="11" cy="4" r="1.4" fill="currentColor" stroke="none"/>'));D("undo",_('<path d="M6.2 9.5 2.7 6l3.5-3.5"/><path d="M2.7 6h6.8a3.65 3.65 0 0 1 0 7.3H7.5"/>'));D("redo",_('<path d="M9.8 9.5 13.3 6 9.8 2.5"/><path d="M13.3 6H6.5a3.65 3.65 0 0 0 0 7.3h2"/>'));D("objects",_('<path d="M8 1.8 14 5 8 8.2 2 5z"/><path d="M2 8l6 3.2L14 8" opacity="0.7"/><path d="M2 11l6 3.2 6-3.2" opacity="0.4"/>'));D("clock",_('<circle cx="8" cy="8" r="6.2"/><path d="M8 4.8V8l2.4 1.6"/>'));D("datawindow",_('<rect x="1.8" y="2.5" width="12.4" height="11" rx="1.5"/><path d="M4.5 5.5h4M4.5 8h7M4.5 10.5h5.5"/>'));D("camera",_('<path d="M5.5 4 6.5 2.5h3L10.5 4h3A1 1 0 0 1 14.5 5v7.5a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z"/><circle cx="8" cy="8.5" r="2.6"/>'));D("gear",_('<path d="M6.55 1.4h2.9l.32 1.72c.48.14.92.38 1.3.7l1.66-.55 1.45 2.5-1.35 1.1c.08.34.12.7.12 1.07s-.04.73-.12 1.07l1.35 1.1-1.45 2.5-1.66-.55a4.3 4.3 0 0 1-1.3.7L9.45 14.6h-2.9l-.32-1.72a4.3 4.3 0 0 1-1.3-.7l-1.66.55-1.45-2.5 1.35-1.1A4.4 4.4 0 0 1 3.05 7.94c0-.37.04-.73.12-1.07l-1.35-1.1 1.45-2.5 1.66.55c.38-.32.82-.56 1.3-.7L6.55 1.4z"/><circle cx="8" cy="8" r="2.2"/>'));D("search",_('<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3.5 3.5"/>'));D("bell",_('<path d="M8 2a4 4 0 0 0-4 4v2.5L2.5 11v1h11v-1L12 8.5V6a4 4 0 0 0-4-4z"/><path d="M6.5 13.5a1.5 1.5 0 0 0 3 0"/>'));D("market-open",I('<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>'));D("market-pre",I('<path d="M12 2v8"/><path d="m4.93 10.93 1.41 1.41"/><path d="M2 18h2"/><path d="M20 18h2"/><path d="m19.07 10.93-1.41 1.41"/><path d="M22 22H2"/><path d="m16 6-4 4-4-4"/><path d="M16 18a4 4 0 0 0-8 0"/>'));D("market-post",I('<path d="M12 10V2"/><path d="m4.93 10.93 1.41 1.41"/><path d="M2 18h2"/><path d="M20 18h2"/><path d="m19.07 10.93-1.41 1.41"/><path d="M22 22H2"/><path d="m16 18-4-4-4 4"/><path d="M16 6a4 4 0 0 0-8 0"/>'));D("market-closed",I('<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>'));D("market-holiday",I('<path d="m10 20-1.25-2.5L6 16"/><path d="M10 4 8.75 6.5 6 8"/><path d="m14 20 1.25-2.5L18 16"/><path d="m14 4 1.25 2.5L18 8"/><path d="m17 10-5 5-5-5"/><path d="M4 12h16"/>'));D("chevron-right",_('<path d="m6 3.5 4.5 4.5L6 12.5"/>'));D("chevron-left",_('<path d="M10 3.5 5.5 8l4.5 4.5"/>'));D("chevron-down",_('<path d="M3.5 6 8 10.5 12.5 6"/>'));D("chevron-up",_('<path d="M3.5 10 8 5.5 12.5 10"/>'));D("chevrons-right",_('<path d="m4 3.5 4.5 4.5L4 12.5"/><path d="m8.5 3.5 4.5 4.5-4.5 4.5"/>'));D("chevrons-left",_('<path d="M12 3.5 7.5 8l4.5 4.5"/><path d="M7.5 3.5 3 8l4.5 4.5"/>'));D("check",_('<path d="m2.8 8.4 3.4 3.4 7-7.6"/>'));D("close",_('<path d="m3.8 3.8 8.4 8.4M12.2 3.8l-8.4 8.4"/>'));D("eye",_('<path d="M1.5 8s2.5-5.4 6.5-5.4S14.5 8 14.5 8 12 13.4 8 13.4 1.5 8 1.5 8z"/><circle cx="8" cy="8" r="1.8"/>'));D("eye-off",_('<path d="M1.5 8s2.5-5.4 6.5-5.4S14.5 8 14.5 8 12 13.4 8 13.4 1.5 8 1.5 8z" opacity="0.45"/><path d="m3 13 10-10"/>'));D("lock",_('<rect x="3.2" y="7" width="9.6" height="6.6" rx="1.2"/><path d="M5.6 7V5.2a2.4 2.4 0 0 1 4.8 0V7"/>'));D("unlock",_('<rect x="3.2" y="7" width="9.6" height="6.6" rx="1.2"/><path d="M5.6 7V5.2a2.4 2.4 0 0 1 4.7-.7"/>'));D("trash",_('<path d="M2.5 4.3h11M6.2 4.3V3.1a1 1 0 0 1 1-1h1.6a1 1 0 0 1 1 1v1.2M4.2 4.3l.5 9.1a1.15 1.15 0 0 0 1.15 1.1h4.3a1.15 1.15 0 0 0 1.15-1.1l.5-9.1M6.5 7v4.5M9.5 7v4.5"/>'));D("group",_('<path d="M1.8 4.5V2.4a.6.6 0 0 1 .6-.6h2.1M11.5 1.8h2.1a.6.6 0 0 1 .6.6v2.1M14.2 11.5v2.1a.6.6 0 0 1-.6.6h-2.1M4.5 14.2H2.4a.6.6 0 0 1-.6-.6v-2.1"/><rect x="4" y="4" width="4.2" height="4.2" rx="0.7"/><rect x="7.8" y="7.8" width="4.2" height="4.2" rx="0.7"/>'));D("ungroup",_('<rect x="1.6" y="1.6" width="6.2" height="6.2" rx="0.9"/><rect x="8.2" y="8.2" width="6.2" height="6.2" rx="0.9" stroke-dasharray="2 1.5"/>'));D("clone",_('<rect x="5.5" y="5.5" width="9" height="9" rx="1.2"/><path d="M11 5.5v-3a1 1 0 0 0-1-1H2.5a1 1 0 0 0-1 1V10a1 1 0 0 0 1 1h3"/>'));D("arrow-up",_('<path d="M8 13.2V3M4.2 6.8 8 3l3.8 3.8"/>'));D("arrow-down",_('<path d="M8 2.8V13M4.2 9.2 8 13l3.8-3.8"/>'));D("move-vertical",_('<path d="M8 2.5v11M5 5.5 8 2.5l3 3M5 10.5l3 3 3-3"/>'));D("move",_('<path d="M8 1.8v12.4M1.8 8h12.4M5.6 4.2 8 1.8l2.4 2.4M5.6 11.8 8 14.2l2.4-2.4M4.2 5.6 1.8 8l2.4 2.4M11.8 5.6 14.2 8l-2.4 2.4"/>'));D("pen",_('<path d="m10.8 2.2 3 3-8 8-3.6.6.6-3.6z"/><path d="m9.2 3.8 3 3"/>'));D("wave",_('<path d="M1.5 10.4c1.6 0 1.9-4.8 3.4-4.8s1.8 4.8 3.4 4.8 1.8-4.8 3.4-4.8 1.6 4.8 2.8 4.8"/>'));D("folder-plus",_('<path d="M1.6 4.4a1 1 0 0 1 1-1h2.7l1.3 1.7h6.8a1 1 0 0 1 1 1v6.5a1 1 0 0 1-1 1h-10.8a1 1 0 0 1-1-1z"/><path d="M8 7.6v3.6M6.2 9.4h3.6"/>'));D("folder-minus",_('<path d="M1.6 4.4a1 1 0 0 1 1-1h2.7l1.3 1.7h6.8a1 1 0 0 1 1 1v6.5a1 1 0 0 1-1 1h-10.8a1 1 0 0 1-1-1z"/><path d="M6.2 9.4h3.6"/>'));D("collapse",_('<path d="M3 8h10"/>'));D("expand",_('<rect x="2.2" y="2.2" width="11.6" height="11.6" rx="1.4"/><path d="M8 5.4v5.2M5.4 8h5.2"/>'));D("maximize",_('<path d="M2.5 6V3a.5.5 0 0 1 .5-.5h3M10 2.5h3a.5.5 0 0 1 .5.5v3M13.5 10v3a.5.5 0 0 1-.5.5h-3M6 13.5H3a.5.5 0 0 1-.5-.5v-3"/>'));D("restore",_('<path d="M6.2 2.5v3.7H2.5M9.8 13.5V9.8h3.7M13.5 6.2H9.8V2.5M2.5 9.8h3.7v3.7"/>'));D("star",_('<path d="M8 2.2l1.75 3.55 3.9.55-2.8 2.75.65 3.9L8 11.1l-3.5 1.85.65-3.9-2.8-2.75 3.9-.55z"/>'));D("star-filled",_('<path d="M8 2.2l1.75 3.55 3.9.55-2.8 2.75.65 3.9L8 11.1l-3.5 1.85.65-3.9-2.8-2.75 3.9-.55z"/>','fill="currentColor"'));D("grip",_('<circle cx="6" cy="3.5" r="1"/><circle cx="10" cy="3.5" r="1"/><circle cx="6" cy="8" r="1"/><circle cx="10" cy="8" r="1"/><circle cx="6" cy="12.5" r="1"/><circle cx="10" cy="12.5" r="1"/>','fill="currentColor" stroke="none"'));D("kebab",_('<circle cx="8" cy="3.2" r="1.2"/><circle cx="8" cy="8" r="1.2"/><circle cx="8" cy="12.8" r="1.2"/>','fill="currentColor" stroke="none"'));D("burger",_('<path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11"/>'));D("reset",_('<rect x="6" y="6" width="4" height="4" rx="0.8"/><path d="M2.2 8a5.8 5.8 0 1 0 1.9-4.3L2.2 5.3"/><path d="M2.2 2.2v3.1h3.1"/>'));D("pane-collapse",_('<path d="M2.6 9.4h4v4M13.4 6.6h-4v-4"/><path d="m9.4 6.6 4.2-4.2M2.4 13.6l4.2-4.2"/>'));D("pane-expand",_('<path d="M9.8 2.4h3.8v3.8M6.2 13.6H2.4V9.8"/><path d="m13.6 2.4-4.4 4.4M2.4 13.6l4.4-4.4"/>'));D("cursor",I('<path d="M5 3l6 16 2-6 6-2z"/>','fill="currentColor" stroke="none"'));D("ruler",I('<path d="M21.3 15.3 8.7 2.7a1 1 0 0 0-1.4 0L2.7 7.3a1 1 0 0 0 0 1.4l12.6 12.6a1 1 0 0 0 1.4 0l4.6-4.6a1 1 0 0 0 0-1.4Z"/><path d="m7.5 10.5 2 2"/><path d="m10.5 7.5 2 2"/><path d="m13.5 4.5 2 2"/><path d="m4.5 13.5 2 2"/>'));D("magnet",I('<path d="m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15"/><path d="m5 8 4 4"/><path d="m12 15 4 4"/>'));D("eraser",I('<path d="m7 21-4.3-4.3a1 1 0 0 1 0-1.4L13 5a2 2 0 0 1 2.8 0l4.2 4.2a2 2 0 0 1 0 2.8L12 20"/><path d="M22 21H7"/><path d="m5 11 9 9"/>'));D("pen-lock",I('<path d="M13.8 4.2a2.1 2.1 0 0 1 3 3L8.5 15.5l-3.5 1 1-3.5Z"/><rect x="13" y="14.5" width="8" height="6" rx="1.2"/><path d="M15 14.5v-1.6a2 2 0 0 1 4 0v1.6"/>'));D("pen-sync",I('<path d="M13.8 4.2a2.1 2.1 0 0 1 3 3L8.5 15.5l-3.5 1 1-3.5Z"/><rect x="12.5" y="13.5" width="6" height="4.8" rx="1"/><path d="M15.5 18.3v1a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-2.8a1 1 0 0 0-1-1h-1"/>'));D("brush",I('<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>'));D("bucket",I('<path d="m18.5 11.5-7-7L4 12a1.8 1.8 0 0 0 0 2.5l5 5a1.8 1.8 0 0 0 2.5 0Z"/><path d="m5 5 4 4"/><path d="M3.5 13.5h13"/><path d="M21 17.5c0 1.1-.9 2-2 2s-2-.9-2-2c0-1 1.2-1.7 2-3 .8 1.3 2 2 2 3Z"/>'));D("type",I('<path d="M5 6V4.5h14V6"/><path d="M12 4.5v15"/><path d="M9.5 19.5h5"/>'));D("bold",I('<path d="M7 5h6a3.5 3.5 0 0 1 0 7H7Z"/><path d="M7 12h7a3.5 3.5 0 0 1 0 7H7Z"/>','stroke-width="2.4"'));D("italic",I('<path d="M15 5h-5M14 19H9M14.5 5 10 19"/>','stroke-width="2.2"'));D("price-delta",I('<path d="M12 4v16"/><path d="M8 8l4-4 4 4"/><path d="M8 16l4 4 4-4"/>'));D("date-delta",I('<path d="M4 12h16"/><path d="M8 8l-4 4 4 4"/><path d="M16 8l4 4-4 4"/>'));D("bring-front",I('<rect x="8.5" y="8.5" width="7" height="7" rx="1.5"/><path d="M4.5 10.5V6a1.5 1.5 0 0 1 1.5-1.5h4.5"/><path d="M19.5 13.5V18a1.5 1.5 0 0 1-1.5 1.5h-4.5"/>'));D("send-back",I('<rect x="8.5" y="8.5" width="7" height="7" rx="1.5" fill="currentColor" stroke="none" opacity="0.35"/><path d="M4.5 10.5V6a1.5 1.5 0 0 1 1.5-1.5h4.5"/><path d="M19.5 13.5V18a1.5 1.5 0 0 1-1.5 1.5h-4.5"/><rect x="8.5" y="8.5" width="7" height="7" rx="1.5"/>'));D("r-squared",'<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" stroke="none"><text x="2.5" y="17.5" font-size="14" font-family="serif">R\xB2</text></svg>');D("bands",I('<path d="M3 6h18"/><path d="M3 18h18"/><path d="M3 12h18" stroke-dasharray="3 3"/>'));D("dedekind",I('<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0"/><path d="M8 20a4 4 0 0 1 8 0"/><path d="M12 4v16"/>'));D("sonic",I('<circle cx="15" cy="12" r="4"/><circle cx="12" cy="12" r="2.5"/><path d="M8 5v14"/>'));D("supersonic",I('<circle cx="16" cy="12" r="3.5"/><path d="M6 12 15 6M6 12 15 18"/>'));var me=[{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"}],O=[{path:"style.lineColor",label:"Line color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Line width",kind:"number",min:1,max:10,step:1,group:"line"},{path:"style.lineStyle",label:"Line style",kind:"lineStyle",options:me,group:"line"}],Z=[{path:"style.fillColor",label:"Fill color",kind:"color",group:"fill"}],Te=[{value:"small",label:"Small"},{value:"normal",label:"Normal"},{value:"large",label:"Large"},{value:"huge",label:"Huge"}],F=[{path:"text.value",label:"Text",kind:"text",group:"text"},{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Te,group:"text"},{path:"text.bold",label:"Bold",kind:"boolean",group:"text"},{path:"text.italic",label:"Italic",kind:"boolean",group:"text"}];function K(s,e,t,n,r,i){let o=r-t,a=i-n,l=o*o+a*a;if(l<=1e-9)return Math.hypot(s-t,e-n);let c=((s-t)*o+(e-n)*a)/l;return c=c<0?0:c>1?1:c,Math.hypot(s-(t+c*o),e-(n+c*a))}function Ht(s,e,t){let n=1/0;for(let r=1;r<t.length;r+=1){let i=t[r-1],o=t[r],a=K(s,e,i[0],i[1],o[0],o[1]);a<n&&(n=a);}return n}function de(s,e,t,n,r,i,o=0){let a=Math.min(t,r)-o,l=Math.max(t,r)+o,c=Math.min(n,i)-o,d=Math.max(n,i)+o;return s>=a&&s<=l&&e>=c&&e<=d}function ke(s,e,t){let n=false;for(let r=0,i=t.length-1;r<t.length;i=r,r+=1){let o=t[r],a=t[i];o[1]>e!=a[1]>e&&s<(a[0]-o[0])*(e-o[1])/(a[1]-o[1])+o[0]&&(n=!n);}return n}function Oo(s,e,t,n,r,i,o,a){let l=t-s,c=n-e,d=o-r,h=a-i,u=d*c-h*l;if(Math.abs(u)<1e-9)return null;let p=((i-e)*l-(r-s)*c)/u;return p<0||p>1?null:[r+p*d,i+p*h]}function N(s,e,t,n=6){for(let r=0;r<t.length;r+=1){let i=t[r];if(Math.hypot(s-i[0],e-i[1])<=n)return r}return -1}function re(s,e,t,n,r,i,o){if(r==="none")return [s,e,t,n];let a=t-s,l=r==="left"||r==="both",c=r==="right"||r==="both";if(Math.abs(a)<1e-6){if(l&&c)return [s,0,t,o];let m=n>=e;return c?m?[s,e,t,o]:[s,e,t,0]:m?[s,0,t,n]:[s,o,t,n]}let d=(n-e)/a,h=m=>e+d*(m-s),u=l?-2:Math.min(s,t),p=c?i+2:Math.max(s,t);return [u,h(u),p,h(p)]}var yr=class extends B{constructor(){super(...arguments);this.type="trendline";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:[t.xOf(n.time),i,t.xOf(r.time),o]}hitTest(t,n,r,i){let o=this.pixels(r);return o!=null&&K(t,n,o[0],o[1],o[2],o[3])<=i}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pixels(t);if(!n)return null;let r=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]);return {x:r,y:i,w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,{path:"style.arrowRight",label:"Arrow",kind:"boolean",group:"line"},...F]}}};var xr=class extends B{constructor(){super(...arguments);this.type="hline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"y"}]}}y(t){let n=this.anchors[0];return n?t.yOf(n.price,this.paneId):null}hitTest(t,n,r,i){let o=this.y(r);return o!=null&&Math.abs(n-o)<=i}handlePoints(t){let n=this.anchors[0],r=this.y(t);return !n||r==null?[]:[[t.xOf(n.time),r]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.y(t);return n==null?null:{x:0,y:n-1,w:t.width,h:2}}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){return null}schema(){return {fields:[...O,...F]}}};var wr=class extends B{constructor(){super(...arguments);this.type="ray";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:[t.xOf(n.time),i,t.xOf(r.time),o]}hitTest(t,n,r,i){let o=this.pixels(r);if(!o)return false;let[a,l,c,d]=re(o[0],o[1],o[2],o[3],"right",r.width,r.height);return K(t,n,a,l,c,d)<=i}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pixels(t);return n?{x:Math.min(n[0],n[2]),y:Math.min(n[1],n[3]),w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,...F]}}};var Je=class extends B{anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);return r==null||i==null?null:[e.xOf(t.time),r,e.xOf(n.time),i]}hitTest(e,t,n,r){let i=this.pixels(n);return i!=null&&K(e,t,i[0],i[1],i[2],i[3])<=r}handlePoints(e){let t=this.pixels(e);return t?[[t[0],t[1]],[t[2],t[3]]]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.pixels(e);return t?{x:Math.min(t[0],t[2]),y:Math.min(t[1],t[3]),w:Math.abs(t[2]-t[0]),h:Math.abs(t[3]-t[1])}:null}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[...O,...F]}}};var Sr=class extends Je{constructor(){super(...arguments);this.type="extendedline";}hitTest(t,n,r,i){let o=this.pixels(r);if(!o)return false;let[a,l,c,d]=re(o[0],o[1],o[2],o[3],"both",r.width,r.height);return K(t,n,a,l,c,d)<=i}timeExtent(){return null}};var Cr=class extends B{constructor(){super(...arguments);this.type="vline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"x"}]}}x(t){let n=this.anchors[0];return n?t.xOf(n.time):null}hitTest(t,n,r,i){let o=this.x(r);return o!=null&&Math.abs(t-o)<=i}handlePoints(t){let n=this.anchors[0],r=this.x(t);if(!n||r==null)return [];let i=t.yOf(n.price,this.paneId);return i==null?[]:[[r,i]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.x(t);return n==null?null:{x:n-1,y:0,w:2,h:t.height}}priceRange(){return null}schema(){return {fields:[...O,...F]}}};var Tr=class extends B{constructor(){super(...arguments);this.type="hray";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}pt(t){let n=this.anchors[0];if(!n)return null;let r=t.yOf(n.price,this.paneId);return r==null?null:[t.xOf(n.time),r]}hitTest(t,n,r,i){let o=this.pt(r);return o!=null&&K(t,n,o[0],o[1],r.width,o[1])<=i}handlePoints(t){let n=this.pt(t);return n?[n]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pt(t);return n?{x:n[0],y:n[1]-1,w:Math.max(0,t.width-n[0]),h:2}:null}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){let t=this.anchors[0];return t?{min:t.time,max:Number.POSITIVE_INFINITY}:null}schema(){return {fields:[...O,...F]}}};var Mr=class extends B{constructor(){super(...arguments);this.type="crossline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}pt(t){let n=this.anchors[0];if(!n)return null;let r=t.yOf(n.price,this.paneId);return r==null?null:[t.xOf(n.time),r]}hitTest(t,n,r,i){let o=this.pt(r);return o!=null&&(Math.abs(n-o[1])<=i||Math.abs(t-o[0])<=i)}handlePoints(t){let n=this.pt(t);return n?[n]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pt(t);return n?{x:n[0]-1,y:n[1]-1,w:2,h:2}:null}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){return null}schema(){return {fields:[...O,...F]}}};var Lr=class extends Je{constructor(){super(...arguments);this.type="infoline";}};var Pr=class extends Je{constructor(){super(...arguments);this.type="trendangle";}};var Er=class extends B{constructor(){super(...arguments);this.type="box";}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}rect(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:{x1:t.xOf(n.time),y1:i,x2:t.xOf(r.time),y2:o}}hitTest(t,n,r,i){let o=this.rect(r);return o?this.style.fillColor&&de(t,n,o.x1,o.y1,o.x2,o.y2)?true:[[o.x1,o.y1,o.x2,o.y1],[o.x2,o.y1,o.x2,o.y2],[o.x2,o.y2,o.x1,o.y2],[o.x1,o.y2,o.x1,o.y1]].some(l=>K(t,n,l[0],l[1],l[2],l[3])<=i):false}handlePoints(t){let n=this.rect(t);return n?[[n.x1,n.y1],[n.x2,n.y2]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.rect(t);return n?{x:Math.min(n.x1,n.x2),y:Math.min(n.y1,n.y2),w:Math.abs(n.x2-n.x1),h:Math.abs(n.y2-n.y1)}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O.map(t=>({...t,label:t.label.replace("Line","Border")})),{path:"style.fillColor",label:"Fill color",kind:"color",group:"fill"},...F]}}};var Kd={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},Qe=class extends B{defaultLabel(){return "Text"}labelText(){return this.text?.value??this.defaultLabel()}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}box(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let r=Kd[this.text?.size??"normal"]??14,i=this.labelText().split(`
2
- `),o=Math.max(1,...i.map(a=>a.length));return {x:e.xOf(t.time),y:n,w:Math.max(12,o*r*.6)+8,h:i.length*r*1.4+4}}hitTest(e,t,n,r){let i=this.box(n);return i!=null&&de(e,t,i.x,i.y,i.x+i.w,i.y+i.h)}handlePoints(e){let t=this.anchors[0],n=t?e.yOf(t.price,this.paneId):null;return t&&n!=null?[[e.xOf(t.time),n]]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){return this.box(e)}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}};var He=class extends Qe{constructor(t){super(t);this.type="text";this.text||(this.text={...Ne(),size:"large"});}schema(){return {fields:[...F],textIsContent:true}}};var dt=class extends Qe{constructor(t){super(t);this.type="note";this.text||(this.text=Ne("Note"));}defaultLabel(){return "Note"}schema(){return {fields:[...O,...Z,...F],textIsContent:true}}};var ht=class extends Qe{constructor(){super(...arguments);this.type="pricelabel";}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return {fields:[...O,...Z,...F.filter(t=>t.path!=="text.value")]}}};var jd={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},we=class extends B{constructor(e){super(e),this.text||(this.text=Ne(this.defaultLabel()));}defaultLabel(){return "Callout"}labelText(){return this.text?.value??this.defaultLabel()}anchorSchema(){return {min:2,max:2,slots:[{role:"target",free:"both"},{role:"box",free:"both"}]}}box(e){let t=this.anchors[1];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let r=jd[this.text?.size??"normal"]??14,i=this.labelText().split(`
3
- `),o=Math.max(1,...i.map(c=>c.length)),a=Math.max(20,o*r*.6)+16,l=i.length*r*1.4+12;return {x:e.xOf(t.time)-a/2,y:n-l/2,w:a,h:l}}points(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);return r==null||i==null?null:[[e.xOf(t.time),r],[e.xOf(n.time),i]]}hitTest(e,t,n,r){let i=this.box(n);if(i&&de(e,t,i.x,i.y,i.x+i.w,i.y+i.h,r))return true;let o=this.points(n);return o!=null&&K(e,t,o[0][0],o[0][1],o[1][0],o[1][1])<=r}handlePoints(e){let t=this.points(e);return t?[t[0]]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}translateBody(e,t,n){let r=n[0],i=n[1];return !r||!i?n.map(o=>({time:o.time+e,price:o.price+t})):[{time:r.time,price:r.price},{time:i.time+e,price:i.price+t}]}bounds(e){return this.box(e)}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[...O,...Z,...F],textIsContent:true}}};var Ie=class extends we{constructor(){super(...arguments);this.type="callout";}};var ut=class extends we{constructor(){super(...arguments);this.type="pricenote";}defaultLabel(){return ""}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return {fields:[...O,...Z,...F.filter(t=>t.path!=="text.value")]}}};var pt=class extends we{constructor(){super(...arguments);this.type="comment";}defaultLabel(){return "Comment"}};var mt=class extends we{constructor(){super(...arguments);this.type="signpost";}defaultLabel(){return "Signpost"}};var J=class extends B{hitTest(e,t,n,r){let i=this.geometry(n);return i?this.style.fillColor&&i.fill&&ke(e,t,i.fill)?true:i.segments.some(o=>K(e,t,o[0],o[1],o[2],o[3])<=r):false}handlePoints(e){let t=[];for(let n of this.anchors){let r=e.yOf(n.price,this.paneId);if(r==null)return [];t.push([e.xOf(n.time),r]);}return t}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),r=t.map(a=>a[1]),i=Math.min(...n),o=Math.min(...r);return {x:i,y:o,w:Math.max(...n)-i,h:Math.max(...r)-o}}};var kr=class extends J{constructor(){super(...arguments);this.type="parallelchannel";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"y"}]}}offset(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];return !t||!n||!r?0:r.price-(t.price+n.price)/2}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return [];let a=[[t.xOf(n.time),i],[t.xOf(r.time),o]],l=this.anchors[2];if(l){let c=t.yOf(l.price,this.paneId);c!=null&&a.push([t.xOf((n.time+r.time)/2),c]);}return a}timeExtent(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.time,n.time),max:Math.max(t.time,n.time)}}geometry(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=this.offset(),o=t.xOf(n.time),a=t.xOf(r.time),l=t.yOf(n.price,this.paneId),c=t.yOf(r.price,this.paneId),d=t.yOf(n.price+i,this.paneId),h=t.yOf(r.price+i,this.paneId);return l==null||c==null||d==null||h==null?null:{segments:[[o,l,a,c],[o,d,a,h]],fill:[[o,l],[a,c],[a,h],[o,d]]}}priceRange(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=this.offset(),i=[t.price,n.price,t.price+r,n.price+r],o=this.anchors[2];return o&&i.push(o.price),{min:Math.min(...i),max:Math.max(...i)}}schema(){return {fields:[...O,...Z,...F]}}};var Ir=class extends J{constructor(){super(...arguments);this.type="disjointchannel";}anchorSchema(){return {min:4,max:4,slots:[{role:"top1",free:"both"},{role:"top2",free:"both"},{role:"bot1",free:"both"},{role:"bot2",free:"both"}]}}seg(t,n,r){let i=this.anchors[t],o=this.anchors[n];if(!i||!o)return null;let a=r.yOf(i.price,this.paneId),l=r.yOf(o.price,this.paneId);return a==null||l==null?null:[r.xOf(i.time),a,r.xOf(o.time),l]}geometry(t){let n=this.seg(0,1,t),r=this.seg(2,3,t),i=[n,r].filter(a=>a!=null);if(i.length===0)return null;let o=n&&r?[[n[0],n[1]],[n[2],n[3]],[r[2],r[3]],[r[0],r[1]]]:null;return {segments:i,fill:o}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...Z,...F]}}};var Rr=class extends J{constructor(){super(...arguments);this.type="flattopbottom";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"flat",free:"y"}]}}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return [];let a=[[t.xOf(n.time),i],[t.xOf(r.time),o]],l=this.anchors[2];if(l){let c=t.yOf(l.price,this.paneId);c!=null&&a.push([t.xOf((n.time+r.time)/2),c]);}return a}timeExtent(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.time,n.time),max:Math.max(t.time,n.time)}}geometry(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.xOf(n.time),o=t.xOf(r.time),a=t.yOf(n.price,this.paneId),l=t.yOf(r.price,this.paneId);if(a==null||l==null)return null;let c=this.anchors[2];if(!c)return {segments:[[i,a,o,l]],fill:null};let d=t.yOf(c.price,this.paneId);return d==null?null:{segments:[[i,a,o,l],[i,d,o,d]],fill:[[i,a],[o,l],[o,d],[i,d]]}}priceRange(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=[t.price,n.price],i=this.anchors[2];return i&&r.push(i.price),{min:Math.min(...r),max:Math.max(...r)}}schema(){return {fields:[...O,...Z,...F]}}};var qd=2;function Pa(){return {midColor:he,midStyle:"solid",upperColor:q,upperStyle:"solid",lowerColor:X,lowerStyle:"solid",upperFill:`${q}26`,lowerFill:`${X}26`,showR2:true}}function Ea(s){let e=s.length;if(e<2)return null;let t=0,n=0,r=0,i=0,o=0;for(let m=0;m<e;m+=1){let f=s[m].close;t+=m,n+=f,r+=m*f,i+=m*m,o+=f*f;}let a=e*i-t*t,l=a===0?0:(e*r-t*n)/a,c=(n-l*t)/e,d=0;for(let m=0;m<e;m+=1){let f=s[m].close-(c+l*m);d+=f*f;}let h=Math.sqrt(d/e),u=Math.sqrt(a*(e*o-n*n)),p=u===0?0:(e*r-t*n)/u;return {t0:s[0].time,t1:s[e-1].time,mid0:c,mid1:c+l*(e-1),dev:qd*h,r2:Math.max(0,Math.min(1,p*p)),n:e}}var ze=class extends B{constructor(t){super(t);this.type="regressionchannel";this.cachedRange=null;this.reg||(this.reg=Pa());}anchorSchema(){return {min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}fit(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=Math.min(n.time,r.time),o=Math.max(n.time,r.time),a=t.barsInRange?.(i,o)??null,l=a?Ea(a):null;return l&&(this.cachedRange={min:Math.min(l.mid0,l.mid1)-l.dev,max:Math.max(l.mid0,l.mid1)+l.dev}),l}layout(t){let n=this.fit(t);if(!n)return null;let r=t.yOf(n.mid0,this.paneId),i=t.yOf(n.mid1,this.paneId),o=t.yOf(n.mid0+n.dev,this.paneId),a=t.yOf(n.mid1+n.dev,this.paneId),l=t.yOf(n.mid0-n.dev,this.paneId),c=t.yOf(n.mid1-n.dev,this.paneId);return r==null||i==null||o==null||a==null||l==null||c==null?null:{x0:t.xOf(n.t0),x1:t.xOf(n.t1),midY0:r,midY1:i,upperY0:o,upperY1:a,lowerY0:l,lowerY1:c,r2:n.r2,showR2:this.reg.showR2}}band(t){let n=this.layout(t);return n?[[n.x0,n.upperY0],[n.x1,n.upperY1],[n.x1,n.lowerY1],[n.x0,n.lowerY0]]:null}hitTest(t,n,r,i){let o=this.layout(r);if(!o)return false;let a=[[o.x0,o.upperY0],[o.x1,o.upperY1],[o.x1,o.lowerY1],[o.x0,o.lowerY0]];return ke(t,n,a)?true:[[o.x0,o.midY0,o.x1,o.midY1],[o.x0,o.upperY0,o.x1,o.upperY1],[o.x0,o.lowerY0,o.x1,o.lowerY1]].some(c=>K(t,n,c[0],c[1],c[2],c[3])<=i)}handlePoints(t){let n=this.layout(t);if(n)return [[n.x0,n.midY0],[n.x1,n.midY1]];let r=[];for(let i of this.anchors){let o=t.yOf(i.price,this.paneId);if(o==null)return [];r.push([t.xOf(i.time),o]);}return r}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.band(t);if(!n)return null;let r=n.map(l=>l[0]),i=n.map(l=>l[1]),o=Math.min(...r),a=Math.min(...i);return {x:o,y:a,w:Math.max(...r)-o,h:Math.max(...i)-a}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"reg.midColor",label:"Midline color",kind:"color",group:"line"},{path:"reg.midStyle",label:"Midline style",kind:"lineStyle",group:"line"},{path:"reg.upperColor",label:"Upper line color",kind:"color",group:"line"},{path:"reg.upperStyle",label:"Upper line style",kind:"lineStyle",group:"line"},{path:"reg.lowerColor",label:"Lower line color",kind:"color",group:"line"},{path:"reg.lowerStyle",label:"Lower line style",kind:"lineStyle",group:"line"},{path:"reg.upperFill",label:"Upper fill",kind:"color",group:"fill"},{path:"reg.lowerFill",label:"Lower fill",kind:"color",group:"fill"},{path:"reg.showR2",label:"Show R\xB2",kind:"boolean",group:"behavior"}]}}writeProps(){return {...this.reg}}readProps(t){this.reg={...Pa(),...t};}};var ka=`${_e}00`;function Ia(){return {midColor:_e,midStyle:"solid",multiplier:1,upperColor:ka,upperStyle:"solid",lowerColor:ka,lowerStyle:"solid",bandFill:`${_e}33`}}function Ra(s,e){let t=s.length;if(t<1)return null;let n=0;for(let c of s)n+=c.volume>0?c.volume:0;let r=n>0,i=0,o=0,a=0,l=[];for(let c=0;c<t;c+=1){let d=s[c],h=(d.high+d.low+d.close)/3,u=r?Math.max(0,d.volume):1;i+=u,o+=h*u,a+=h*h*u;let p=i>0?o/i:h,m=i>0?Math.max(0,a/i-p*p):0,f=Math.sqrt(m)*e;l.push({time:d.time,mid:p,upper:p+f,lower:p-f});}return l}var ft=class extends B{constructor(t){super(t);this.type="anchoredvwap";this.cachedRange=null;this.cachedExtent=null;this.vwap||(this.vwap=Ia());}anchorSchema(){return {min:1,max:1,slots:[{role:"anchor",free:"x"}]}}series(t){let n=this.anchors[0];if(!n)return null;let r=t.barsInRange?.(n.time,Number.POSITIVE_INFINITY)??null;if(!r||r.length<1)return null;let i=Ra(r.map(o=>({time:o.time,high:o.high,low:o.low,close:o.close,volume:o.volume??0})),this.vwap.multiplier);if(i&&i.length>0){let o=1/0,a=-1/0;for(let l of i)l.lower<o&&(o=l.lower),l.upper>a&&(a=l.upper);this.cachedRange={min:o,max:a},this.cachedExtent={min:i[0].time,max:i[i.length-1].time};}return i}layout(t){let n=this.series(t);if(!n)return null;let r=[],i=[],o=[];for(let a of n){let l=t.xOf(a.time),c=t.yOf(a.mid,this.paneId),d=t.yOf(a.upper,this.paneId),h=t.yOf(a.lower,this.paneId);c==null||d==null||h==null||(r.push([l,c]),i.push([l,d]),o.push([l,h]));}return r.length>0?{mid:r,upper:i,lower:o}:null}bandPolygon(t){return [...t.upper,...[...t.lower].reverse()]}hitTest(t,n,r,i){let o=this.layout(r);return o?ke(t,n,this.bandPolygon(o))?true:Fo(t,n,o.mid,i)||Fo(t,n,o.upper,i)||Fo(t,n,o.lower,i):false}handlePoints(t){let n=this.layout(t);if(n&&n.mid.length>0)return [n.mid[0]];let r=this.anchors[0];if(!r)return [];let i=t.yOf(r.price,this.paneId);return i==null?[]:[[t.xOf(r.time),i]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.layout(t);if(!n)return null;let r=[...n.upper,...n.lower],i=r.map(c=>c[0]),o=r.map(c=>c[1]),a=Math.min(...i),l=Math.min(...o);return {x:a,y:l,w:Math.max(...i)-a,h:Math.max(...o)-l}}priceRange(){return this.cachedRange}timeExtent(){return this.cachedExtent}schema(){return {fields:[{path:"vwap.midColor",label:"VWAP color",kind:"color",group:"line"},{path:"vwap.midStyle",label:"VWAP style",kind:"lineStyle",group:"line"},{path:"vwap.multiplier",label:"Band multiplier",kind:"number",min:.5,max:5,step:.5,group:"behavior"},{path:"vwap.upperColor",label:"Upper band color",kind:"color",group:"line"},{path:"vwap.lowerColor",label:"Lower band color",kind:"color",group:"line"},{path:"vwap.bandFill",label:"Band fill",kind:"color",group:"fill"}]}}writeProps(){return {...this.vwap}}readProps(t){this.vwap={...Ia(),...t};}};function Fo(s,e,t,n){for(let r=1;r<t.length;r+=1)if(K(s,e,t[r-1][0],t[r-1][1],t[r][0],t[r][1])<=n)return true;return false}var Zd=`${q}66`,Jd=`${X}66`,Qd=`${q}BF`,eh=`${X}BF`;function Da(){return {rows:24,valueAreaPct:70,widthPct:35,anchor:"left",upColor:Zd,downColor:Jd,vaUpColor:Qd,vaDownColor:eh,showVah:true,vahColor:he,vahStyle:"solid",showVal:true,valColor:he,valStyle:"solid",showPoc:true,pocColor:void 0,pocStyle:"solid",showDevelopingPoc:false,developingPocColor:ve,developingPocStyle:"dotted",showDevelopingVa:false,developingVaColor:ve,developingVaStyle:"dotted"}}function th(s,e){return s<0?0:s>=e?e-1:s}function Aa(s,e,t){let n=s.length,r=0,i=0;for(let d=0;d<n;d+=1){let h=s[d].up+s[d].down;r+=h,h>i&&(i=h);}let o=r*Math.min(1,Math.max(0,t)),a=e,l=e,c=i;for(;c<o&&(a>0||l<n-1);){let d=a>0?s[a-1].up+s[a-1].down:-1,h=l<n-1?s[l+1].up+s[l+1].down:-1;h>d?(l+=1,c+=h):(a-=1,c+=d);}return {vaFrom:a,vaTo:l}}function Oa(s,e,t,n){let r=n.volume;if(!(r>0))return;let i=s.length,o=n.close>=n.open?"up":"down",a=new Set;for(let l of [n.open,n.high,n.low,n.close])a.add(th(Math.floor((l-e)/t),i));for(let l of a)s[l][o]+=r;}function Fa(s){let e=0,t=0;for(let n=0;n<s.length;n+=1){let r=s[n].up+s[n].down;r>e&&(e=r,t=n);}return e>0?{poc:t,maxTotal:e}:null}function Ba(s,e,t){let n=1/0,r=-1/0;for(let p of s)p.volume>0&&(p.low<n&&(n=p.low),p.high>r&&(r=p.high));if(!Number.isFinite(n))return null;let i=r>n?Math.max(1,Math.round(e)):1,o=r>n?(r-n)/i:1,a=Array.from({length:i},(p,m)=>({price:n+m*o,up:0,down:0}));for(let p of s)Oa(a,n,o,p);let l=Fa(a);if(!l)return null;let{poc:c,maxTotal:d}=l,{vaFrom:h,vaTo:u}=Aa(a,c,t);return {rows:a,rowH:o,min:n,maxTotal:d,poc:c,vaFrom:h,vaTo:u}}function Va(s,e,t,n){let r=Ba(s,e,t);if(!r)return null;if(!n||s.length<1)return {profile:r,developingPoc:[],developingVaHigh:[],developingVaLow:[]};let{min:i,rowH:o}=r,a=r.rows.length,l=Array.from({length:a},(u,p)=>({price:i+p*o,up:0,down:0})),c=[],d=[],h=[];for(let u of s){Oa(l,i,o,u);let p=Fa(l);if(!p)continue;let{poc:m}=p,{vaFrom:f,vaTo:b}=Aa(l,m,t);c.push({time:u.time,price:l[m].price+o/2}),d.push({time:u.time,price:l[b].price+o}),h.push({time:u.time,price:l[f].price});}return {profile:r,developingPoc:c,developingVaHigh:d,developingVaLow:h}}var Re=class extends B{constructor(t){super(t);this.type="fixedrangevp";this.cachedRange=null;this.frvp||(this.frvp=Da());}anchorSchema(){return {min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}barsInSpan(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=Math.min(n.time,r.time),o=Math.max(n.time,r.time),a=t.barsInRange?.(i,o)??null;return !a||a.length<1?null:a.map(l=>({time:l.time,open:l.open,high:l.high,low:l.low,close:l.close,volume:l.volume??0}))}compute(t){let n=this.barsInSpan(t);if(!n)return null;let r=this.frvp,i=r.showDevelopingPoc||r.showDevelopingVa,o=Va(n,r.rows,r.valueAreaPct/100,i);if(o){let{profile:a}=o;this.cachedRange={min:a.min,max:a.min+a.rowH*a.rows.length};}return o}layout(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=this.compute(t);if(!i)return null;let{profile:o}=i,a=Math.min(n.time,r.time),l=Math.max(n.time,r.time),c=t.xOf(a),d=t.xOf(l),h=Math.abs(d-c),u=Math.max(1,Math.min(100,Math.max(0,this.frvp.widthPct))/100*h),p=this.frvp.anchor==="left",m=p?Math.min(c,d):Math.max(c,d),f=p?1:-1,b=[];for(let C=0;C<=o.rows.length;C+=1){let T=t.yOf(o.min+C*o.rowH,this.paneId);if(T==null)return null;b.push(T);}let g=C=>t.yOf(C,this.paneId),v=o.rows[o.vaTo].price+o.rowH,y=o.rows[o.vaFrom].price,x=o.rows[o.poc].price+o.rowH/2,S=C=>{let T=[];for(let M of C){let E=g(M.price);E!=null&&T.push([t.xOf(M.time),E]);}return T};return {x0:Math.min(c,d),x1:Math.max(c,d),anchorX:m,maxW:u,grow:f,profile:o,yEdges:b,vahY:g(v),valY:g(y),pocY:g(x),developingPoc:S(i.developingPoc),developingVaHigh:S(i.developingVaHigh),developingVaLow:S(i.developingVaLow)}}hitTest(t,n,r,i){let o=this.layout(r);if(!o)return false;let a=o.grow===1?o.anchorX:o.anchorX-o.maxW,l=o.grow===1?o.anchorX+o.maxW:o.anchorX,c=Math.min(o.yEdges[0],o.yEdges[o.yEdges.length-1]),d=Math.max(o.yEdges[0],o.yEdges[o.yEdges.length-1]);if(ke(t,n,[[a,c],[l,c],[l,d],[a,d]]))return true;let h=[[o.x0,o.vahY],[o.x0,o.valY],[o.x0,o.pocY]];for(let[,u]of h)if(u!=null&&K(t,n,o.x0,u,o.x1,u)<=i)return true;for(let u of [o.developingPoc,o.developingVaHigh,o.developingVaLow])for(let p=1;p<u.length;p+=1)if(K(t,n,u[p-1][0],u[p-1][1],u[p][0],u[p][1])<=i)return true;return false}handlePoints(t){let n=this.layout(t);if(n&&n.pocY!=null)return [[n.x0,n.pocY],[n.x1,n.pocY]];let r=[];for(let i of this.anchors){let o=t.yOf(i.price,this.paneId);if(o==null)return [];r.push([t.xOf(i.time),o]);}return r}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.layout(t);if(!n)return null;let r=Math.min(n.x0,n.grow===1?n.anchorX:n.anchorX-n.maxW),i=Math.max(n.x1,n.grow===1?n.anchorX+n.maxW:n.anchorX),o=Math.min(n.yEdges[0],n.yEdges[n.yEdges.length-1]),a=Math.max(n.yEdges[0],n.yEdges[n.yEdges.length-1]);return {x:r,y:o,w:i-r,h:a-o}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"frvp.rows",label:"Rows",kind:"number",min:1,max:500,step:1,group:"behavior"},{path:"frvp.valueAreaPct",label:"Value Area",kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.widthPct",label:"Width %",kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.anchor",label:"Anchor",kind:"select",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}],group:"behavior"},{path:"frvp.upColor",label:"Up Volume",kind:"color",group:"fill"},{path:"frvp.downColor",label:"Down Volume",kind:"color",group:"fill"},{path:"frvp.vaUpColor",label:"Value Area Up",kind:"color",group:"fill"},{path:"frvp.vaDownColor",label:"Value Area Down",kind:"color",group:"fill"},{path:"frvp.showVah",label:"VAH",kind:"boolean",group:"line"},{path:"frvp.vahColor",label:"VAH color",kind:"color",group:"line"},{path:"frvp.vahStyle",label:"VAH style",kind:"lineStyle",options:me,group:"line"},{path:"frvp.showVal",label:"VAL",kind:"boolean",group:"line"},{path:"frvp.valColor",label:"VAL color",kind:"color",group:"line"},{path:"frvp.valStyle",label:"VAL style",kind:"lineStyle",options:me,group:"line"},{path:"frvp.showPoc",label:"POC",kind:"boolean",group:"line"},{path:"frvp.pocColor",label:"POC color",kind:"color",group:"line"},{path:"frvp.pocStyle",label:"POC style",kind:"lineStyle",options:me,group:"line"},{path:"frvp.showDevelopingPoc",label:"Developing POC",kind:"boolean",group:"line"},{path:"frvp.developingPocColor",label:"Developing POC color",kind:"color",group:"line"},{path:"frvp.developingPocStyle",label:"Developing POC style",kind:"lineStyle",options:me,group:"line"},{path:"frvp.showDevelopingVa",label:"Developing VA",kind:"boolean",group:"line"},{path:"frvp.developingVaColor",label:"Developing VA color",kind:"color",group:"line"},{path:"frvp.developingVaStyle",label:"Developing VA style",kind:"lineStyle",options:me,group:"line"}]}}writeProps(){return {...this.frvp}}readProps(t){this.frvp={...Da(),...t};}};var Dr=class extends J{constructor(){super(...arguments);this.type="pitchfork";}anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=b=>{let g=t.yOf(b.price,this.paneId);return g==null?null:[t.xOf(b.time),g]},a=o(n),l=o(r),c=o(i);if(!a||!l||!c)return null;let d=(l[0]+c[0])/2,h=(l[1]+c[1])/2,u=d-a[0],p=h-a[1],m=t.width,f=t.height;return {segments:[re(a[0],a[1],d,h,"right",m,f),re(l[0],l[1],l[0]+u,l[1]+p,"right",m,f),re(c[0],c[1],c[0]+u,c[1]+p,"right",m,f),[l[0],l[1],c[0],c[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...F]}}};var zt=class extends J{anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(e){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];if(!t||!n||!r)return null;let i=f=>{let b=e.yOf(f.price,this.paneId);return b==null?null:[e.xOf(f.time),b]},o=i(this.medianStart(t,n,r)),a=i(n),l=i(r);if(!o||!a||!l)return null;let c=(a[0]+l[0])/2,d=(a[1]+l[1])/2,h=c-o[0],u=d-o[1],p=e.width,m=e.height;return {segments:[re(o[0],o[1],c,d,"right",p,m),re(a[0],a[1],a[0]+h,a[1]+u,"right",p,m),re(l[0],l[1],l[0]+h,l[1]+u,"right",p,m),[a[0],a[1],l[0],l[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}schema(){return {fields:[...O,...F]}}};var Ar=class extends zt{constructor(){super(...arguments);this.type="schiffpitchfork";}medianStart(t,n){return {time:t.time,price:(t.price+n.price)/2}}};var Or=class extends zt{constructor(){super(...arguments);this.type="modifiedschiffpitchfork";}medianStart(t,n){return {time:(t.time+n.time)/2,price:(t.price+n.price)/2}}};var Fr=class extends J{constructor(){super(...arguments);this.type="insidepitchfork";}anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=g=>{let v=t.yOf(g.price,this.paneId);return v==null?null:[t.xOf(g.time),v]},a=o({time:(n.time+r.time)/2,price:(n.price+r.price)/2}),l=o(n),c=o(r),d=o(i);if(!a||!l||!c||!d)return null;let h=(c[0]+d[0])/2,u=(c[1]+d[1])/2,p=d[0]-a[0],m=d[1]-a[1],f=t.width,b=t.height;return {segments:[re(h,u,h+p,u+m,"right",f,b),re(c[0],c[1],c[0]+p,c[1]+m,"right",f,b),re(d[0],d[1],d[0]+p,d[1]+m,"right",f,b),[c[0],c[1],d[0],d[1]],[a[0],a[1],d[0],d[1]],[l[0],l[1],c[0],c[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...F]}}};var Br=class extends B{constructor(){super(...arguments);this.type="arrow";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:[t.xOf(n.time),i,t.xOf(r.time),o]}hitTest(t,n,r,i){let o=this.pixels(r);return o!=null&&K(t,n,o[0],o[1],o[2],o[3])<=i}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pixels(t);return n?{x:Math.min(n[0],n[2]),y:Math.min(n[1],n[3]),w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,{path:"style.arrowRight",label:"Head (end)",kind:"boolean",group:"line"},{path:"style.arrowLeft",label:"Head (start)",kind:"boolean",group:"line"},...F]}}};var _a=48,Vr=class extends B{constructor(){super(...arguments);this.type="ellipse";}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}oval(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time);return {cx:(a+l)/2,cy:(i+o)/2,rx:Math.abs(l-a)/2,ry:Math.abs(o-i)/2}}perimeter(t){let n=[];for(let r=0;r<=_a;r+=1){let i=r/_a*Math.PI*2;n.push([t.cx+t.rx*Math.cos(i),t.cy+t.ry*Math.sin(i)]);}return n}hitTest(t,n,r,i){let o=this.oval(r);if(!o||o.rx<1||o.ry<1)return false;let a=((t-o.cx)/o.rx)**2+((n-o.cy)/o.ry)**2;return this.style.fillColor&&a<=1?true:Ht(t,n,this.perimeter(o))<=i}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?[]:[[t.xOf(n.time),i],[t.xOf(r.time),o]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.oval(t);return n?{x:n.cx-n.rx,y:n.cy-n.ry,w:n.rx*2,h:n.ry*2}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,...Z,...F]}}};var _r=class extends J{constructor(){super(...arguments);this.type="triangle";}anchorSchema(){return {min:3,max:3,slots:[{role:"v1",free:"both"},{role:"v2",free:"both"},{role:"v3",free:"both"}]}}geometry(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=d=>{let h=t.yOf(d.price,this.paneId);return h==null?null:[t.xOf(d.time),h]},a=o(n),l=o(r),c=o(i);return !a||!l||!c?null:{segments:[[a[0],a[1],l[0],l[1]],[l[0],l[1],c[0],c[1]],[c[0],c[1],a[0],a[1]]],fill:[a,l,c]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...Z,...F]}}};var nh=512,et=class extends J{anchorSchema(){return {min:2,max:nh,slots:[]}}geometry(e){let t=[];for(let r of this.anchors){let i=e.yOf(r.price,this.paneId);if(i==null)return null;t.push([e.xOf(r.time),i]);}if(t.length<2)return null;let n=[];for(let r=1;r<t.length;r+=1)n.push([t[r-1][0],t[r-1][1],t[r][0],t[r][1]]);return {segments:n,fill:null}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}schema(){return {fields:[...O,...F]}}};var Nr=class extends et{constructor(){super(...arguments);this.type="polyline";}};var vn=class extends et{placementMode(){return "freehand"}handlePoints(e){return []}bounds(e){let t=[],n=[];for(let o of this.anchors){let a=e.yOf(o.price,this.paneId);a!=null&&(t.push(e.xOf(o.time)),n.push(a));}if(t.length===0)return null;let r=Math.min(...t),i=Math.min(...n);return {x:r,y:i,w:Math.max(...t)-r,h:Math.max(...n)-i}}},Hr=class extends vn{constructor(){super(...arguments);this.type="freehand";}};var rh=[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Width",kind:"number",min:4,max:60,step:1,group:"line"}],zr=class extends vn{constructor(){super(...arguments);this.type="highlighter";}schema(){return {fields:rh}}};var $r=class extends B{constructor(){super(...arguments);this.type="circle";}anchorSchema(){return {min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}geom(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time);return {cx:a,cy:i,r:Math.hypot(l-a,o-i)}}hitTest(t,n,r,i){let o=this.geom(r);if(!o||o.r<1)return false;let a=Math.hypot(t-o.cx,n-o.cy);return this.style.fillColor&&a<=o.r?true:Math.abs(a-o.r)<=i}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?[]:[[t.xOf(n.time),i],[t.xOf(r.time),o]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.geom(t);return n?{x:n.cx-n.r,y:n.cy-n.r,w:n.r*2,h:n.r*2}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,...Z,...F]}}};var Wr=class extends J{constructor(){super(...arguments);this.type="rotatedrect";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"w",free:"both"}]}}px(t,n){let r=this.anchors[n];if(!r)return null;let i=t.yOf(r.price,this.paneId);return i==null?null:[t.xOf(r.time),i]}geometry(t){let n=this.px(t,0),r=this.px(t,1);if(!n||!r)return null;let i=this.px(t,2);if(!i||this.anchors.length<3)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let o=r[0]-n[0],a=r[1]-n[1],l=Math.hypot(o,a);if(l<1e-6)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let c=-a/l,d=o/l,h=(i[0]-n[0])*c+(i[1]-n[1])*d,u=c*h,p=d*h,m=n,f=r,b=[r[0]+u,r[1]+p],g=[n[0]+u,n[1]+p];return {segments:[[m[0],m[1],f[0],f[1]],[f[0],f[1],b[0],b[1]],[b[0],b[1],g[0],g[1]],[g[0],g[1],m[0],m[1]]],fill:[m,f,b,g]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O.map(t=>({...t,label:t.label.replace("Line","Border")})),...Z,...F]}}};var Ur=class extends et{constructor(){super(...arguments);this.type="path";}};var Na=40,Gr=class extends J{constructor(){super(...arguments);this.type="arc";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"apex",free:"both"}]}}pinApex(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];t&&n&&r&&(r.time=(t.time+n.time)/2);}onPlaced(){this.pinApex();}constrainHandleDrag(){this.pinApex();}px(t,n){let r=this.anchors[n];if(!r)return null;let i=t.yOf(r.price,this.paneId);return i==null?null:[t.xOf(r.time),i]}geometry(t){let n=this.px(t,0),r=this.px(t,1);if(!n||!r)return null;let i=this.anchors[2];if(!i||this.anchors.length<3)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let o=t.yOf(i.price,this.paneId);if(o==null)return null;let a=(n[0]+r[0])/2,l=(n[1]+r[1])/2,c=(r[0]-n[0])/2,d=(r[1]-n[1])/2,h=Math.hypot(c,d);if(h<1e-6)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let u=-d/h,p=c/h,m=(o-l)*p;m<0&&(u=-u,p=-p);let f=Math.abs(m),b=[];for(let v=0;v<=Na;v+=1){let y=v/Na*Math.PI,x=Math.cos(y),S=Math.sin(y);b.push([a+x*c+S*f*u,l+x*d+S*f*p]);}let g=[];for(let v=1;v<b.length;v+=1)g.push([b[v-1][0],b[v-1][1],b[v][0],b[v][1]]);return g.push([b[b.length-1][0],b[b.length-1][1],b[0][0],b[0][1]]),{segments:g,fill:b}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O.map(t=>({...t,label:t.label.replace("Line","Border")})),...Z,...F]}}};var Ha=40,Yr=class extends J{constructor(){super(...arguments);this.type="curve";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"control",free:"both"}]}}px(t,n){let r=this.anchors[n];if(!r)return null;let i=t.yOf(r.price,this.paneId);return i==null?null:[t.xOf(r.time),i]}geometry(t){let n=this.px(t,0),r=this.px(t,1);if(!n||!r)return null;let i=this.px(t,2);if(!i||this.anchors.length<3)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let o=[];for(let l=0;l<=Ha;l+=1){let c=l/Ha,d=1-c;o.push([d*d*n[0]+2*d*c*i[0]+c*c*r[0],d*d*n[1]+2*d*c*i[1]+c*c*r[1]]);}let a=[];for(let l=1;l<o.length;l+=1)a.push([o[l-1][0],o[l-1][1],o[l][0],o[l][1]]);return {segments:a,fill:o}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...Z,...F]}}};var ih={head:11,headW:9,stemW:3.5,len:22},bt=class extends B{anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}glyphPoints(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let r=e.xOf(t.time),{head:i,headW:o,stemW:a,len:l}=ih,c=[[0,0],[-o,i],[-a,i],[-a,l],[a,l],[a,i],[o,i]],d=this.dir(),h=([u,p])=>{switch(d){case "up":return [u,p];case "down":return [u,-p];case "left":return [p,u];default:return [-p,u]}};return c.map(u=>{let[p,m]=h(u);return [r+p,n+m]})}hitTest(e,t,n,r){let i=this.glyphPoints(n);return i!=null&&ke(e,t,i)}handlePoints(e){let t=this.anchors[0];if(!t)return [];let n=e.yOf(t.price,this.paneId);return n==null?[]:[[e.xOf(t.time),n]]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.glyphPoints(e);if(!t)return null;let n=t.map(a=>a[0]),r=t.map(a=>a[1]),i=Math.min(...n),o=Math.min(...r);return {x:i,y:o,w:Math.max(...n)-i,h:Math.max(...r)-o}}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}schema(){return {fields:[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},...F]}}},yn=class extends bt{constructor(){super(...arguments);this.type="arrowmarkup";}dir(){return "up"}},xn=class extends bt{constructor(){super(...arguments);this.type="arrowmarkdown";}dir(){return "down"}};var Cn=["\u2605","\u2606","\u25CF","\u25C6","\u25B2","\u25BC","\u27A4","\u2691","\u271A","\u2715","\u2764","\u2666"],Xr=["small","normal","large","huge"],za={small:16,normal:22,large:32,huge:44},gt=class extends B{constructor(e){super(e),this.glyph||(this.glyph=this.defaultGlyph()),this.size||(this.size="normal");}sizePx(){return za[this.size]??za.normal}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}center(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);return n==null?null:[e.xOf(t.time),n]}hitTest(e,t,n,r){let i=this.center(n);if(!i)return false;let o=this.sizePx()/2+r;return Math.abs(e-i[0])<=o&&Math.abs(t-i[1])<=o}handlePoints(e){let t=this.center(e);return t?[t]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.center(e);if(!t)return null;let n=this.sizePx();return {x:t[0]-n/2,y:t[1]-n/2,w:n,h:n}}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}schema(){return {fields:[{path:"glyph",label:"Icon",kind:"select",options:Cn.map(e=>({value:e,label:e})),group:"line"},{path:"size",label:"Size",kind:"select",options:Xr.map(e=>({value:e,label:e})),group:"line"},{path:"style.lineColor",label:"Color",kind:"color",group:"line"},...F]}}writeProps(){return {glyph:this.glyph,size:this.size}}readProps(e){typeof e.glyph=="string"&&(this.glyph=e.glyph),typeof e.size=="string"&&(this.size=e.size);}},wn=class extends gt{constructor(){super(...arguments);this.type="flagmark";}defaultGlyph(){return "\u2691"}},Sn=class extends gt{constructor(){super(...arguments);this.type="iconstamp";}defaultGlyph(){return "\u2605"}};var $a=s=>s==="small"||s==="normal"||s==="large"||s==="huge";function oh(s){if(!s||typeof s!="object")return null;let e=s;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==false,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var ee=class extends B{constructor(e){super(e),this.levels||(this.levels=this.defaultLevels().map(t=>({...t}))),this.numbersSize||(this.numbersSize="small"),this.labelsSize||(this.labelsSize="normal");}fillBands(e){return []}editableLevels(){return this.levels}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}hitTest(e,t,n,r){let i=this.entryLines(n);return i!=null&&i.some(o=>K(e,t,o.x1,o.y1,o.x2,o.y2)<=r)}handlePoints(e){let t=[];for(let n of this.anchors){let r=e.yOf(n.price,this.paneId);if(r==null)return [];t.push([e.xOf(n.time),r]);}return t}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),r=t.map(a=>a[1]),i=Math.min(...n),o=Math.min(...r);return {x:i,y:o,w:Math.max(...n)-i,h:Math.max(...r)-o}}schema(){return {fields:O.filter(e=>e.path!=="style.lineColor")}}writeProps(){return {levels:this.levels.map(e=>({...e})),numbersSize:this.numbersSize,labelsSize:this.labelsSize}}readProps(e){if(Array.isArray(e.levels)){let t=e.levels.map(oh).filter(n=>n!=null);t.length&&(this.levels=t);}$a(e.numbersSize)&&(this.numbersSize=e.numbersSize),$a(e.labelsSize)&&(this.labelsSize=e.labelsSize);}};var $t=class extends ee{levelLines(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.xOf(t.time),i=e.xOf(n.time),o=Math.min(r,i),a=Math.max(r,i),l=n.price-t.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let h=t.price+d.ratio*l,u=e.yOf(h,this.paneId);u!=null&&c.push({ratio:d.ratio,color:d.color,label:d.label,price:h,x1:o,x2:a,y:u});}return c}entryLines(e){let t=this.levelLines(e);return t?t.map(n=>({color:n.color,label:n.label,x1:n.x1,y1:n.y,x2:n.x2,y2:n.y,numberText:`${n.ratio} (${n.price.toFixed(2)})`,numberX:n.x1+4,numberY:n.y-7,numberAlign:"left",labelX:(n.x1+n.x2)/2,labelY:n.y-7})):null}fillBands(e){let t=this.levelLines(e);if(!t)return [];let n=[];for(let r=1;r<t.length;r+=1){let i=t[r-1],o=t[r];n.push({color:o.color,x:i.x1,y:Math.min(i.y,o.y),w:i.x2-i.x1,h:Math.abs(o.y-i.y)});}return n}priceRange(){let e=this.anchors[0],t=this.anchors[1];if(!e||!t)return null;let n=t.price-e.price,r=this.levels.filter(i=>i.enabled).map(i=>e.price+i.ratio*n);return r.length===0?null:{min:Math.min(...r),max:Math.max(...r)}}};var vt=he,De=X,Ae=bn,yt="#4caf50",tt=q,$e=_e,xt="#9c27b0",sh="#e91e63",Bo="#26a69a",ah="#ab47bc",lh="#ef5350",Wa="#ffb74d",ch="#38c0fd",Kr="#b2b5be",Wt=[ch,$e,tt,yt,Ae,De,sh,xt,vt,Bo,ah,lh];function Ua(s){return Wt[(s%Wt.length+Wt.length)%Wt.length]}var dh=[[0,vt],[.125,De],[.236,De],[.25,De],[.382,Ae],[.5,yt],[.618,tt],[.75,$e],[.786,$e],[1,vt],[1.272,$e],[1.382,Ae],[1.618,De],[2,vt],[2.382,Ae],[2.618,Ae],[3,vt],[4.236,yt],[6.854,tt],[11.09,$e]];function hh(s,e=0){return dh.find(([t])=>t===s)?.[1]??Ua(e)}function Q(s){return s.map((e,t)=>{let n=typeof e=="number"?{ratio:e}:e;return {ratio:n.ratio,color:n.color??hh(n.ratio,t),enabled:n.enabled!==false,...n.label?{label:n.label}:{}}})}function Ga(s,e=s){return Array.from({length:s},(t,n)=>({ratio:n+1,color:Ua(n),enabled:n<e,label:String(n+1)}))}var uh=Q([0,.236,.382,.5,.618,.786,1]),jr=class extends $t{constructor(){super(...arguments);this.type="fibretracement";}defaultLevels(){return uh}};var ph=Q([0,.382,.618,1,1.272,1.618,{ratio:2.618,color:xt}]),qr=class extends $t{constructor(){super(...arguments);this.type="fibextension";}defaultLevels(){return ph}};var mh=Q([0,.382,.5,.618,1,1.618,{ratio:2.618,color:xt}]),Zr=class extends ee{constructor(){super(...arguments);this.type="fibextensiontrend";}anchorSchema(){return {min:3,max:3,slots:[{role:"a",free:"both"},{role:"b",free:"both"},{role:"c",free:"both"}]}}defaultLevels(){return mh}entryLines(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=r.price-n.price,a=[t.xOf(n.time),t.xOf(r.time),t.xOf(i.time)],l=Math.min(...a),c=Math.max(...a),d=[];for(let h of this.levels){if(!h.enabled)continue;let u=i.price+h.ratio*o,p=t.yOf(u,this.paneId);p!=null&&d.push({color:h.color,label:h.label,x1:l,y1:p,x2:c,y2:p,numberText:`${h.ratio} (${u.toFixed(2)})`,numberX:l+4,numberY:p-7,numberAlign:"left",labelX:(l+c)/2,labelY:p-7});}return d}priceRange(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];if(!t||!n||!r)return null;let i=n.price-t.price,o=this.levels.filter(a=>a.enabled).map(a=>r.price+a.ratio*i);return o.push(t.price,n.price,r.price),{min:Math.min(...o),max:Math.max(...o)}}};var fh=Q([.236,.382,.5,.618,.786,1]),Jr=class extends ee{constructor(){super(...arguments);this.type="fibfan";}defaultLevels(){return fh}fanLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.xOf(n.time),o=t.yOf(n.price,this.paneId);if(o==null)return null;let a=t.xOf(r.time),l=r.price-n.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let h=t.yOf(n.price+d.ratio*l,this.paneId);if(h==null)continue;let[u,p,m,f]=re(i,o,a,h,"right",t.width,t.height);c.push({ratio:d.ratio,color:d.color,label:d.label,x1:u,y1:p,x2:m,y2:f,labelX:a+5,labelY:h});}return c}entryLines(t){let n=this.fanLines(t);return n?n.map(r=>({color:r.color,label:r.label,x1:r.x1,y1:r.y1,x2:r.x2,y2:r.y2,numberText:String(r.ratio),numberX:r.labelX,numberY:r.labelY,numberAlign:"left",labelX:r.labelX,labelY:r.labelY+13})):null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var bh=[0,1,2,3,5,8,13,21,34].map(s=>({ratio:s,color:R,enabled:true})),Qr=class extends ee{constructor(){super(...arguments);this.type="fibtimezones";}defaultLevels(){return bh}zoneLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=r.time-n.time;if(Math.abs(i)<1e-9)return null;let o=[];for(let a of this.levels)a.enabled&&o.push({n:a.ratio,color:a.color,label:a.label,x:t.xOf(n.time+a.ratio*i)});return o}entryLines(t){let n=this.zoneLines(t);if(!n)return null;let r=t.height;return n.map(i=>({color:i.color,label:i.label,x1:i.x,y1:0,x2:i.x,y2:r,numberText:String(i.n),numberX:i.x,numberY:9,numberAlign:"center",labelX:i.x,labelY:24}))}priceRange(){return null}timeExtent(){return null}};var gh=Q([0,.236,.382,.5,.618,.786,1,1.618,2.618]),ei=class extends ee{constructor(){super(...arguments);this.type="fibchannel";}defaultLevels(){return gh}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"both"}]}}entryLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time),c=0,d=0,h=this.anchors[2];if(h){let p=t.yOf(h.price,this.paneId);if(p==null)return null;c=t.xOf(h.time)-a,d=p-i;}let u=[];for(let p of this.levels){if(!p.enabled)continue;let m=p.ratio*c,f=p.ratio*d,b=l+m,g=o+f;u.push({color:p.color,label:p.label,x1:a+m,y1:i+f,x2:b,y2:g,numberText:String(p.ratio),numberX:b+5,numberY:g,numberAlign:"left",labelX:b+5,labelY:g+13});}return u}priceRange(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];if(!t||!n)return null;let i=r?r.price-t.price:0,o=1/0,a=-1/0;for(let l of this.levels)if(l.enabled)for(let c of [t.price,n.price]){let d=c+l.ratio*i;d<o&&(o=d),d>a&&(a=d);}return o<=a?{min:o,max:a}:null}};var vh=Q([0,.236,.382,.5,.618,.786,1]),ti=class extends ee{constructor(){super(...arguments);this.type="fibspeedfan";}defaultLevels(){return vh}entryLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),c=t.xOf(r.time)-a,d=o-i,h=c>=0?"right":"left",u=t.width,p=t.height,m=[];for(let f of this.levels){if(!f.enabled)continue;let b=a+c,g=i+d*f.ratio,v=re(a,i,b,g,h,u,p);if(m.push({color:f.color,label:f.label,x1:v[0],y1:v[1],x2:v[2],y2:v[3],numberText:String(f.ratio),numberX:h==="right"?b+5:b-5,numberY:g,numberAlign:h==="right"?"left":"right",labelX:b,labelY:g}),f.ratio===1)continue;let y=a+c*f.ratio,x=i+d,S=re(a,i,y,x,h,u,p);m.push({color:f.color,label:f.label,x1:S[0],y1:S[1],x2:S[2],y2:S[3],numberText:String(f.ratio),numberX:y,numberY:x+(d>=0?12:-12),numberAlign:"center",labelX:y,labelY:x+12});}return m}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var yh=Q([0,.382,{ratio:.5,enabled:false},.618,1,1.382,1.618,2,2.382,2.618,3]),ni=class extends ee{constructor(){super(...arguments);this.type="trendfibtime";}defaultLevels(){return yh}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"p3",free:"both"}]}}entryLines(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=r.time-n.time;if(Math.abs(o)<1e-9)return null;let a=t.height,l=[];for(let c of this.levels){if(!c.enabled)continue;let d=t.xOf(i.time+c.ratio*o);l.push({color:c.color,label:c.label,x1:d,y1:0,x2:d,y2:a,numberText:String(c.ratio),numberX:d,numberY:9,numberAlign:"center",labelX:d,labelY:24});}return l}priceRange(){return null}timeExtent(){return null}};function xh(s,e,t){if(t-e>=Math.PI*2-.001)return true;let n=s-e,r=Math.PI*2;for(;n<0;)n+=r;for(;n>=r;)n-=r;return n<=t-e+1e-6}var Me=class extends ee{boundingLines(e){return []}entryLines(e){return []}hitTest(e,t,n,r){let i=this.radial(n);if(i){let o=Math.hypot(e-i.cx,t-i.cy),a=Math.atan2(t-i.cy,e-i.cx);if(xh(a,i.a0,i.a1)){for(let l of this.levels)if(l.enabled&&Math.abs(o-i.R0*l.ratio)<=r)return true}}return this.boundingLines(n).some(o=>K(e,t,o[0],o[1],o[2],o[3])<=r)}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}};var wh=Q([.236,.382,.5,.618,.786,1,1.618,2.618]),ri=class extends Me{constructor(){super(...arguments);this.type="fibcircles";}defaultLevels(){return wh}radial(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time);return {cx:a,cy:i,R0:Math.hypot(l-a,o-i),a0:0,a1:Math.PI*2}}};var Sh=Q([.236,.382,.5,.618,.786,1,1.618,2.618]),ii=class extends Me{constructor(){super(...arguments);this.type="fibarcs";}defaultLevels(){return Sh}pts(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:{cx:t.xOf(n.time),cy:i,ex:t.xOf(r.time),ey:o}}radial(t){let n=this.pts(t);if(!n)return null;let r=Math.hypot(n.ex-n.cx,n.ey-n.cy),i=Math.atan2(n.ey-n.cy,n.ex-n.cx);return {cx:n.cx,cy:n.cy,R0:r,a0:i-Math.PI/2,a1:i+Math.PI/2}}boundingLines(t){let n=this.pts(t);return n?[[n.cx,n.cy,n.ex,n.ey]]:[]}};var Ch=Q([.236,.382,.5,.618,.786,1]),oi=class extends Me{constructor(){super(...arguments);this.type="fibwedge";}defaultLevels(){return Ch}anchorSchema(){return {min:3,max:3,slots:[{role:"apex",free:"both"},{role:"radius",free:"both"},{role:"angle",free:"both"}]}}px(t,n){let r=this.anchors[n];if(!r)return null;let i=t.yOf(r.price,this.paneId);return i==null?null:[t.xOf(r.time),i]}radial(t){let n=this.px(t,0),r=this.px(t,1),i=this.px(t,2);if(!n||!r||!i)return null;let o=Math.hypot(r[0]-n[0],r[1]-n[1]);if(o<1)return null;let a=Math.atan2(r[1]-n[1],r[0]-n[0]),l=Math.atan2(i[1]-n[1],i[0]-n[0]),c=Math.min(a,l),d=Math.max(a,l);return d-c>Math.PI&&([c,d]=[d,c+Math.PI*2]),{cx:n[0],cy:n[1],R0:o,a0:c,a1:d}}boundingLines(t){let n=this.px(t,0),r=this.px(t,1);if(!n||!r)return [];let i=[[n[0],n[1],r[0],r[1]]],o=this.px(t,2);if(o){let a=Math.hypot(r[0]-n[0],r[1]-n[1]),l=Math.hypot(o[0]-n[0],o[1]-n[1]);l>1e-6&&i.push([n[0],n[1],n[0]+(o[0]-n[0])/l*a,n[1]+(o[1]-n[1])/l*a]);}return i}};var Th=1.6180339887,Ya=Math.log(Th)/(Math.PI/2),Mh=Math.PI/64,Lh=Math.PI,Ph=.5,wt=class extends B{constructor(){super(...arguments);this.type="fibspiral";}anchorSchema(){return {min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}spiralPoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time),c=Math.hypot(l-a,o-i);if(c<1)return null;let d=Math.atan2(o-i,l-a),h=Math.max(Math.log(Ph/c)/Ya,-8*Math.PI*2),u=[];for(let p=h;p<=Lh;p+=Mh){let m=c*Math.exp(Ya*p),f=d+p;u.push([a+m*Math.cos(f),i+m*Math.sin(f)]);}return u}hitTest(t,n,r,i){let o=this.spiralPoints(r);return o!=null&&o.length>=2&&Ht(t,n,o)<=i}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?[]:[[t.xOf(n.time),i],[t.xOf(r.time),o]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.handlePoints(t);if(n.length<2)return null;let r=n.map(l=>l[0]),i=n.map(l=>l[1]),o=Math.min(...r),a=Math.min(...i);return {x:o,y:a,w:Math.max(...r)-o,h:Math.max(...i)-a}}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,...F]}}};var Eh=Q([{ratio:.125,color:De,label:"1/8"},{ratio:.25,color:Ae,label:"1/4"},{ratio:.333,color:Wa,label:"1/3"},{ratio:.5,color:yt,label:"1/2"},{ratio:1,color:Kr,label:"1/1"},{ratio:2,color:tt,label:"2/1"},{ratio:3,color:$e,label:"3/1"},{ratio:4,color:Bo,label:"4/1"},{ratio:8,color:xt,label:"8/1"}]),si=class extends ee{constructor(){super(...arguments);this.type="gannfan";}defaultLevels(){return Eh}entryLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.xOf(n.time),o=t.yOf(n.price,this.paneId);if(o==null)return null;let a=t.xOf(r.time),l=r.price-n.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let h=t.yOf(n.price+l*d.ratio,this.paneId);if(h==null)continue;let[u,p,m,f]=re(i,o,a,h,"right",t.width,t.height);c.push({color:d.color,x1:u,y1:p,x2:m,y2:f,numberText:d.label??String(d.ratio),numberX:a+5,numberY:h,numberAlign:"left",labelX:a+5,labelY:h});}return c}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var kh=Q([0,.25,.382,.5,.618,.75,1].map(s=>({ratio:s,label:String(s)}))),ai=class extends ee{constructor(){super(...arguments);this.type="gannbox";}defaultLevels(){return kh}corners(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.xOf(n.time),o=t.xOf(r.time),a=t.yOf(n.price,this.paneId),l=t.yOf(r.price,this.paneId);return a==null||l==null?null:{c1:n,c2:r,left:Math.min(i,o),right:Math.max(i,o),top:Math.min(a,l),bot:Math.max(a,l)}}entryLines(t){let n=this.corners(t);if(!n)return null;let{c1:r,c2:i,left:o,right:a,top:l,bot:c}=n,d=[];for(let u of this.levels){if(!u.enabled)continue;let p=t.yOf(r.price+u.ratio*(i.price-r.price),this.paneId);p!=null&&d.push({color:u.color,x1:o,y1:p,x2:a,y2:p,numberText:u.label??String(u.ratio),numberX:o-5,numberY:p,numberAlign:"right",labelX:o,labelY:p});let m=t.xOf(r.time+u.ratio*(i.time-r.time));d.push({color:u.color,x1:m,y1:l,x2:m,y2:c,numberText:"",numberX:m,numberY:l,numberAlign:"center",labelX:m,labelY:l});}let h=this.levels.find(u=>u.ratio===1)?.color??vt;return d.push({color:h,x1:o,y1:l,x2:a,y2:c,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),d.push({color:h,x1:o,y1:c,x2:a,y2:l,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),d}hitTest(t,n,r,i){let o=this.corners(r);return o!=null&&de(t,n,o.left,o.top,o.right,o.bot,i)}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var Ih=Q([0,.25,.382,.5,.618,.75,1].map(s=>({ratio:s,label:String(s)}))),Rh=[{label:"3x1",x:3,y:1,color:De},{label:"2x1",x:2,y:1,color:Ae},{label:"1x1",x:1,y:1,color:Kr},{label:"1x2",x:1,y:2,color:tt},{label:"1x3",x:1,y:3,color:$e}],Vo=[{k:.25,color:De},{k:.5,color:Ae},{k:.75,color:yt},{k:1,color:tt}],St=class extends ee{constructor(){super(...arguments);this.type="gannsquare";}defaultLevels(){return Ih}box(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time);return {ox:a,oy:i,bx:l-a,py:o-i,left:Math.min(a,l),top:Math.min(i,o),right:Math.max(a,l),bot:Math.max(i,o)}}arcGeom(t){let n=this.box(t);return n?{ox:n.ox,oy:n.oy,bx:n.bx,py:n.py}:null}entryLines(t){let n=this.box(t);if(!n)return null;let r=this.anchors[0],i=this.anchors[1],o=[];for(let a of this.levels){if(!a.enabled)continue;let l=t.yOf(r.price+a.ratio*(i.price-r.price),this.paneId);l!=null&&o.push({color:a.color,x1:n.left,y1:l,x2:n.right,y2:l,numberText:a.label??String(a.ratio),numberX:n.left-5,numberY:l,numberAlign:"right",labelX:n.left,labelY:l});let c=t.xOf(r.time+a.ratio*(i.time-r.time));o.push({color:a.color,x1:c,y1:n.top,x2:c,y2:n.bot,numberText:"",numberX:c,numberY:n.top,numberAlign:"center",labelX:c,labelY:n.top});}for(let a of Rh){let l,c;a.x>a.y?(l=n.ox+n.bx,c=n.oy+a.y/a.x*n.py):(c=n.oy+n.py,l=n.ox+a.x/a.y*n.bx),o.push({color:a.color,x1:n.ox,y1:n.oy,x2:l,y2:c,numberText:a.label,numberX:l+4,numberY:c,numberAlign:"left",labelX:l+4,labelY:c});}return o}hitTest(t,n,r,i){let o=this.box(r);return o!=null&&de(t,n,o.left,o.top,o.right,o.bot,i)}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var _o=[4,8,12,16,24,32,48,64],Dh=24,Ah=.75;function Xa(s,e){if(!Number.isInteger(s)||!Number.isInteger(e)||e<=0)return false;let t=s*s-1;return e%2===1?t%e===0:e%8===0?t%e!==0?false:t/e%2!==0:false}function Ka(s){let e=[];for(let t=0;t<s;t+=1)Xa(t,s)&&e.push(t);return e}var Ct=class extends B{constructor(t){super(t);this.type="dedekind";this.maxCurvature===void 0&&(this.maxCurvature=Dh);}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}box(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=Math.min(t.xOf(n.time),t.xOf(r.time)),l=Math.max(t.xOf(n.time),t.xOf(r.time)),c=Math.min(i,o),d=Math.max(i,o),h=l-a,u=d-c;if(h<1||u<1)return null;let p=u,m=h/p;return {left:a,right:l,top:c,bot:d,unitPx:p,x0:0,realSpan:m}}geodesics(t){let n=this.box(t);if(!n)return null;let{left:r,top:i,bot:o,unitPx:a,x0:l,realSpan:c}=n,d=Math.max(1,Math.min(64,Math.round(this.maxCurvature))),h=l-1/d,u=l+c+1/d,p=r+c*a,m=[],f=Math.floor(h*2),b=Math.ceil(u*2);for(let g=f;g<=b;g+=1){if(g%2===0)continue;let v=r+(g/2-l)*a;v<r-.5||v>p+.5||m.push({kind:"vline",x:v,y0:o,y1:i});}for(let g=1;g<=d;g+=1){let v=1/g,y=v*a;if(y<Ah)continue;let x=Ka(g);if(x.length===0)continue;let S=Math.floor(h)-1,C=Math.ceil(u)+1;for(let T=S;T<=C;T+=1)for(let M of x){let E=M/g+T;if(E+v<h||E-v>u)continue;let k=r+(E-l)*a;k+y<r-1||k-y>p+1||m.push({kind:"arc",cx:k,cy:o,r:y});}}return m}hitTest(t,n,r,i){let o=this.box(r);return o!=null&&de(t,n,o.left,o.top,o.right,o.bot,i)}handlePoints(t){let n=this.box(t);return n?[[n.left,n.top],[n.right,n.bot]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.box(t);return n?{x:n.left,y:n.top,w:n.right-n.left,h:n.bot-n.top}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,{path:"maxCurvature",label:"Max curvature",kind:"number",min:4,max:64,step:4,group:"behavior"},...F]}}writeProps(){return {maxCurvature:this.maxCurvature}}readProps(t){typeof t.maxCurvature=="number"&&Number.isFinite(t.maxCurvature)&&(this.maxCurvature=Math.max(1,Math.min(64,Math.round(t.maxCurvature))));}};var No=[3,4,5,6,8,10,12],Ho=[1.5,2,2.5,3,4,5],li=6,Oh=2;function zo(s=li){return [...Ga(Wt.length,s)]}function Fh(s){if(!s||typeof s!="object")return null;let e=s;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==false,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var Ut={path:"showRatios",label:"Show ratios",kind:"boolean",group:"behavior"},ye=class extends B{constructor(e){super(e),this.waveCount===void 0&&(this.waveCount=li),this.showRatios===void 0&&(this.showRatios=true);let t=Array.isArray(e.props?.levels);this.levels||(this.levels=this.defaultLevels().map(n=>({...n}))),!t&&this.shouldSyncWaveCount()&&this.syncLevelsToWaveCount();}shouldSyncWaveCount(){return true}syncLevelsToWaveCount(){let e=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=e;for(let t=0;t<this.levels.length;t+=1)this.levels[t].enabled=t<e;}editableLevels(){return this.levels}anchorSchema(){return {min:2,max:2,slots:[{role:"d1",free:"both"},{role:"d2",free:"both"}]}}geom(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);if(r==null||i==null)return null;let o=e.xOf(t.time),a=e.xOf(n.time),l=(o+a)/2,c=(r+i)/2,d=Math.hypot(a-o,i-r)/2;if(d<1)return null;let h=a-o,u=i-r,p=Math.hypot(h,u);p<1e-9?(h=1,u=0):(h/=p,u/=p);let m=this.levels.filter(C=>C.enabled&&C.ratio>0).slice().sort((C,T)=>C.ratio-T.ratio);if(m.length===0)return null;let f=Math.max(1,this.machNumber()),b=[];for(let C of m){let T=C.ratio*d;b.push({cx:l+f*(T-d)*h,cy:c+f*(T-d)*u,r:T,color:C.color,ratio:C.ratio});}let g=l-f*d*h,v=c-f*d*u,y=b[b.length-1].r,x=f*y+2*d,S=[];if(f<=1+1e-9){let C=-u,T=h;S.push([g-C*x,v-T*x,g+C*x,v+T*x]);}else {let C=Math.asin(1/f),T=Math.cos(C),M=Math.sin(C),E=(G,w,H)=>[G*T-w*H*M,G*H*M+w*T],[k,L]=E(h,u,1),[P,V]=E(h,u,-1);S.push([g,v,g+k*x,v+L*x]),S.push([g,v,g+P*x,v+V*x]);}return {c0x:l,c0y:c,R:d,fx:h,fy:u,noseX:g,noseY:v,circles:b,rays:S}}hitTest(e,t,n,r){let i=this.geom(n);if(!i)return false;for(let o of i.circles)if(Math.abs(Math.hypot(e-o.cx,t-o.cy)-o.r)<=r)return true;return i.rays.some(o=>K(e,t,o[0],o[1],o[2],o[3])<=r)}handlePoints(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return [];let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);return r==null||i==null?[]:[[e.xOf(t.time),r],[e.xOf(n.time),i]]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.geom(e);if(!t)return null;let n=t.noseX,r=t.noseX,i=t.noseY,o=t.noseY;for(let a of t.circles)n=Math.min(n,a.cx-a.r),r=Math.max(r,a.cx+a.r),i=Math.min(i,a.cy-a.r),o=Math.max(o,a.cy+a.r);for(let a of t.rays)n=Math.min(n,a[0],a[2]),r=Math.max(r,a[0],a[2]),i=Math.min(i,a[1],a[3]),o=Math.max(o,a[1],a[3]);return {x:n,y:i,w:r-n,h:o-i}}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}applySettings(e){if(super.applySettings(e),Object.prototype.hasOwnProperty.call(e,"waveCount")&&typeof this.waveCount=="number"){let t=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=t;for(let n=0;n<this.levels.length;n+=1)this.levels[n].enabled=n<t;}}schema(){return {fields:[...O,{path:"waveCount",label:"Waves",kind:"number",min:3,max:12,step:1,group:"behavior"},Ut,...F]}}writeProps(){return {waveCount:this.waveCount,showRatios:this.showRatios,levels:this.levels.map(e=>({...e}))}}readProps(e){if(typeof e.waveCount=="number"&&Number.isFinite(e.waveCount)&&(this.waveCount=Math.max(2,Math.min(12,Math.round(e.waveCount)))),typeof e.showRatios=="boolean"&&(this.showRatios=e.showRatios),Array.isArray(e.levels)){let t=e.levels.map(Fh).filter(n=>n!=null);t.length&&(this.levels=t);}}},Tn=class extends ye{constructor(){super(...arguments);this.type="sonic";}defaultLevels(){return zo(li)}machNumber(){return 1}},Mn=class extends ye{constructor(t){super(t);this.type="supersonic";this.mach===void 0&&(this.mach=Oh);}defaultLevels(){return zo(li)}machNumber(){return Math.max(1.01,this.mach)}schema(){return {fields:[...O,{path:"mach",label:"Mach number",kind:"number",min:1.5,max:5,step:.5,group:"behavior"},{path:"waveCount",label:"Waves",kind:"number",min:3,max:12,step:1,group:"behavior"},Ut,...F]}}writeProps(){return {...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)));}};var ja=Q([.236,.382,.5,.618,.786,1,1.618,2.618,4.236,6.854,11.09]),Bh=2,ci=class extends ye{constructor(){super(...arguments);this.type="goldensonic";}shouldSyncWaveCount(){return false}defaultLevels(){return ja}machNumber(){return 1}schema(){return {fields:[...O,Ut,...F]}}},di=class extends ye{constructor(t){super(t);this.type="goldensupersonic";this.mach===void 0&&(this.mach=Bh);}shouldSyncWaveCount(){return false}defaultLevels(){return ja}machNumber(){return Math.max(1.01,this.mach)}schema(){return {fields:[...O,{path:"mach",label:"Mach number",kind:"number",min:1.5,max:5,step:.5,group:"behavior"},Ut,...F]}}writeProps(){return {...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)));}};var ae=class extends B{legRatios(){return false}fillTriangles(){return []}necklineIndices(){return null}anchorSchema(){let e=this.vertexLabels().length,t=[];for(let n=0;n<e;n+=1)t.push({role:`p${n}`,free:"both"});return {min:e,max:e,slots:t}}handlePoints(e){let t=[];for(let n of this.anchors){let r=e.yOf(n.price,this.paneId);if(r==null)return [];t.push([e.xOf(n.time),r]);}return t}hitTest(e,t,n,r){let i=this.handlePoints(n);return i.length>=2&&Ht(e,t,i)<=r}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),r=t.map(a=>a[1]),i=Math.min(...n),o=Math.min(...r);return {x:i,y:o,w:Math.max(...n)-i,h:Math.max(...r)-o}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}patternName(){return null}ratioOk(e){return null}valid(){return null}ratioAt(e){let t=this.anchors[e-2],n=this.anchors[e-1],r=this.anchors[e];if(!t||!n||!r)return null;let i=Math.abs(n.price-t.price);return i<1e-9?null:Math.abs(r.price-n.price)/i}schema(){return {fields:[...O,...this.fillTriangles().length?Z:[]]}}};var hi=class extends ae{constructor(){super(...arguments);this.type="xabcd";}vertexLabels(){return ["X","A","B","C","D"]}legRatios(){return true}fillTriangles(){return [[0,1,2],[2,3,4]]}};var ui=class extends ae{constructor(){super(...arguments);this.type="abcd";}vertexLabels(){return ["A","B","C","D"]}legRatios(){return true}};var pi=class extends ae{constructor(){super(...arguments);this.type="elliottimpulse";}vertexLabels(){return ["1","2","3","4","5"]}};var mi=class extends ae{constructor(){super(...arguments);this.type="elliottcorrection";}vertexLabels(){return ["A","B","C"]}};var fi=class extends ae{constructor(){super(...arguments);this.type="headshoulders";}vertexLabels(){return ["","LS","","H","","RS",""]}necklineIndices(){return [2,4]}};var fe=class extends ae{vertexLabels(){return ["X","A","B","C","D"]}legRatios(){return true}fillTriangles(){return [[0,1,2],[2,3,4]]}legValue(e){let[t,n,r,i,o]=this.anchors;if(!t||!n||!r||!i||!o)return null;let a=(h,u)=>Math.abs(u.price-h.price),l=a(t,n),c=a(n,r),d=a(r,i);switch(e){case "ab":return l<1e-9?null:c/l;case "bc":return c<1e-9?null:d/c;case "cd":return d<1e-9?null:a(i,o)/d;default:return l<1e-9?null:a(n,o)/l}}inBand(e,t){return e!=null&&e>=t.min&&e<=t.max}ratioOk(e){let t=this.ranges();return e===2?this.inBand(this.legValue("ab"),t.ab):e===3?this.inBand(this.legValue("bc"),t.bc):e===4?this.inBand(this.legValue("cd"),t.cd):null}valid(){if(this.anchors.length<5)return null;let e=this.ranges();return this.inBand(this.legValue("ab"),e.ab)&&this.inBand(this.legValue("bc"),e.bc)&&this.inBand(this.legValue("cd"),e.cd)&&this.inBand(this.legValue("ad"),e.ad)}};var bi=class extends fe{constructor(){super(...arguments);this.type="gartley";}patternName(){return "Gartley"}ranges(){return {ab:{min:.55,max:.68},bc:{min:.382,max:.886},cd:{min:1.13,max:1.618},ad:{min:.74,max:.83}}}};var gi=class extends fe{constructor(){super(...arguments);this.type="bat";}patternName(){return "Bat"}ranges(){return {ab:{min:.382,max:.5},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:.84,max:.92}}}};var vi=class extends fe{constructor(){super(...arguments);this.type="butterfly";}patternName(){return "Butterfly"}ranges(){return {ab:{min:.74,max:.83},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:1.272,max:1.618}}}};var yi=class extends fe{constructor(){super(...arguments);this.type="crab";}patternName(){return "Crab"}ranges(){return {ab:{min:.382,max:.618},bc:{min:.382,max:.886},cd:{min:2.618,max:3.618},ad:{min:1.55,max:1.69}}}};var xi=class extends fe{constructor(){super(...arguments);this.type="shark";}patternName(){return "Shark"}ranges(){return {ab:{min:.382,max:.618},bc:{min:1.13,max:1.618},cd:{min:1.618,max:2.24},ad:{min:.886,max:1.13}}}};var Vh={min:1.272,max:1.414},_h={min:.74,max:.83},wi=class extends fe{constructor(){super(...arguments);this.type="cypher";}patternName(){return "Cypher"}ranges(){return {ab:{min:.382,max:.618},bc:{min:0,max:1/0},cd:{min:0,max:1/0},ad:{min:0,max:1/0}}}xcOverXa(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[3];if(!t||!n||!r)return null;let i=Math.abs(n.price-t.price);return i<1e-9?null:Math.abs(r.price-t.price)/i}cdOverXc(){let t=this.anchors[0],n=this.anchors[3],r=this.anchors[4];if(!t||!n||!r)return null;let i=Math.abs(n.price-t.price);return i<1e-9?null:Math.abs(r.price-n.price)/i}ratioOk(t){return t===2?this.inBand(this.legValue("ab"),this.ranges().ab):null}valid(){return this.anchors.length<5?null:this.inBand(this.legValue("ab"),this.ranges().ab)&&this.inBand(this.xcOverXa(),Vh)&&this.inBand(this.cdOverXc(),_h)}};function qa(s){return `${s>=0?"+":""}${s.toFixed(2)}`}function Ln(s){let e=Math.abs(s),t=864e5,n=36e5,r=6e4;if(e>=t){let i=Math.floor(e/t),o=Math.round(e%t/n);return o?`${i}d ${o}h`:`${i}d`}if(e>=n){let i=Math.floor(e/n),o=Math.round(e%n/r);return o?`${i}h ${o}m`:`${i}h`}return e>=r?`${Math.round(e/r)}m`:`${Math.round(e/1e3)}s`}var Tt=class extends B{constructor(e){super(e),this.showPrice===void 0&&(this.showPrice=true),this.showDate===void 0&&(this.showDate=true);}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}measureLabel(e){let t=[];return this.showPrice&&t.push(this.priceLabel()),this.showDate&&t.push(this.timeLabel(e)),t}isUp(){let e=this.anchors[0],t=this.anchors[1];return e!=null&&t!=null&&t.price>=e.price}priceLabel(){let e=this.anchors[0],t=this.anchors[1];if(!e||!t)return "";let n=t.price-e.price,r=e.price!==0?n/e.price*100:0;return `${qa(n)} (${qa(r)}%)`}timeLabel(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return "";let r=Ln(n.time-t.time),i=e.barsBetween?Math.round(e.barsBetween(t.time,n.time)):null;return i!=null?`${i} bars, ${r}`:r}rect(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);return r==null||i==null?null:{x1:e.xOf(t.time),y1:r,x2:e.xOf(n.time),y2:i}}hitTest(e,t,n,r){let i=this.rect(n);return i!=null&&de(e,t,i.x1,i.y1,i.x2,i.y2,r)}handlePoints(e){let t=this.rect(e);return t?[[t.x1,t.y1],[t.x2,t.y2]]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.rect(e);return t?{x:Math.min(t.x1,t.x2),y:Math.min(t.y1,t.y2),w:Math.abs(t.x2-t.x1),h:Math.abs(t.y2-t.y1)}:null}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[{path:"showPrice",label:"Show price",kind:"boolean",group:"behavior"},{path:"showDate",label:"Show date",kind:"boolean",group:"behavior"},...O.filter(e=>e.path!=="style.lineColor"),{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Te,group:"text"}]}}writeProps(){return {showPrice:this.showPrice,showDate:this.showDate}}readProps(e){typeof e.showPrice=="boolean"&&(this.showPrice=e.showPrice),typeof e.showDate=="boolean"&&(this.showDate=e.showDate);}};var Si=class extends Tt{constructor(){super(...arguments);this.type="datepricerange";}};var Ci=[{value:"long",label:"Long"},{value:"short",label:"Short"}],ie=class ie extends B{constructor(t){super(t);this.type="position";this.riskPercent===void 0&&(this.riskPercent=ie.DEFAULT_RISK_PERCENT),this.accountBalance===void 0&&(this.accountBalance=ie.DEFAULT_ACCOUNT_BALANCE),this.showText===void 0&&(this.showText=true),this.showHeader===void 0&&(this.showHeader=true),this.showPrices===void 0&&(this.showPrices=false),this.showLossSize===void 0&&(this.showLossSize=true),this.showTargetLabel===void 0&&(this.showTargetLabel=true),this.showStopLabel===void 0&&(this.showStopLabel=true),this.profitColor===void 0&&(this.profitColor=ie.DEFAULT_PROFIT_COLOR),this.lossColor===void 0&&(this.lossColor=ie.DEFAULT_LOSS_COLOR);}directionLabel(){let t=this.prices();return t&&t.target>=t.entry?"LONG":"SHORT"}get direction(){return this.directionLabel()==="LONG"?"long":"short"}set direction(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];!n||!r||!i||(t==="long"||t==="short")&&t!==this.direction&&(r.price=2*n.price-r.price,i.price=2*n.price-i.price);}get quantity(){return this.positionSize()}set quantity(t){let n=this.prices();if(!n||!Number.isFinite(t)||t<0)return;let r=Math.abs(n.entry-n.stop);r<1e-9||this.accountBalance<=0||(this.riskPercent=t*r/this.accountBalance*100);}get entryPrice(){return this.anchors[0]?.price??0}set entryPrice(t){let n=this.anchors[0];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(0));}get stopPrice(){return this.anchors[1]?.price??0}set stopPrice(t){let n=this.anchors[1];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(1));}get targetPrice(){return this.anchors[2]?.price??0}set targetPrice(t){let n=this.anchors[2];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(2));}anchorSchema(){return {min:2,max:2,slots:[{role:"entry",free:"both"},{role:"stop",free:"both"},{role:"target",free:"both"}]}}onPlaced(t){let n=this.anchors[0];if(!n)return;let r=t.xOf(n.time),i=t.yOf(n.price,this.paneId);if(i==null)return;let o=this.anchors[1],a=o?t.yOf(o.price,this.paneId):null,l,c;o&&a!=null&&Math.abs(a-i)>=ie.MIN_DRAG_PX?(l=a,c=r+Math.max(Math.abs(t.xOf(o.time)-r),ie.MIN_WIDTH_PX)):(l=i-ie.DEFAULT_RISK_PX*ie.DEFAULT_RR,c=r+ie.DEFAULT_WIDTH_PX);let d=i-(l-i)/ie.DEFAULT_RR,h=t.pxToPoint(c,i,this.paneId).time;this.anchors=[{time:n.time,price:n.price},{time:h,price:t.pxToPoint(r,d,this.paneId).price},{time:h,price:t.pxToPoint(r,l,this.paneId).price}];}constrainHandleDrag(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return;let o=Math.sign(r.price-n.price),a=Math.sign(i.price-n.price);o===0||a===0||o!==a||(t===2?r.price=2*n.price-r.price:i.price=2*n.price-i.price);}resolved(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;if(this.anchors[2])return [t,n,this.anchors[2]];let r={time:n.time,price:t.price-(n.price-t.price)/ie.DEFAULT_RR};return [t,r,n]}prices(){let t=this.resolved();return t?{entry:t[0].price,stop:t[1].price,target:t[2].price}:null}rr(){let t=this.prices();if(!t)return 0;let n=Math.abs(t.entry-t.stop);return n<1e-9?0:Math.abs(t.target-t.entry)/n}rewardPct(){let t=this.prices();return t&&t.entry!==0?Math.abs(t.target-t.entry)/t.entry*100:0}riskPct(){let t=this.prices();return t&&t.entry!==0?Math.abs(t.entry-t.stop)/t.entry*100:0}dollarLoss(){return Math.max(0,this.accountBalance)*(Math.max(0,this.riskPercent)/100)}positionSize(){let t=this.prices();if(!t)return 0;let n=Math.abs(t.entry-t.stop);return n<1e-9?0:this.dollarLoss()/n}headerLabel(){return `${this.directionLabel()} \xB7 R:R ${this.rr().toFixed(2)}`}lossSizeLabel(){return `Loss $${Nh(this.dollarLoss())} \xB7 Size ${Hh(this.positionSize())}`}targetLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${Za(t.target)}`:"";return `Target +${this.rewardPct().toFixed(2)}%${n}`}stopLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${Za(t.stop)}`:"";return `Stop \u2212${this.riskPct().toFixed(2)}%${n}`}levelDisplayValue(t,n){let r=this.prices();if(!r)return 0;let i=t==="stop"?r.stop:r.target;return Ja(n==="price"?i:Math.abs(i-r.entry))}levelPriceFromDisplay(t,n,r){let i=this.prices();if(!i||n==="price")return r;let o=t==="stop"?i.stop:i.target,a=Math.sign(o-i.entry);return a===0&&(a=(t==="target"?1:-1)*(this.direction==="long"?1:-1)),i.entry+a*Math.abs(r)}box(t){let n=this.handlePoints(t);if(n.length<3)return null;let r=n.map(i=>i[0]);return {x1:Math.min(...r),x2:Math.max(...r),ey:n[0][1],sy:n[1][1],ty:n[2][1]}}layout(t){return this.box(t)}hitTest(t,n,r,i){let o=this.box(r);if(!o)return false;let a=Math.min(o.ey,o.sy,o.ty),l=Math.max(o.ey,o.sy,o.ty);return de(t,n,o.x1,a,o.x2,l,i)}handlePoints(t){let n=this.resolved();if(!n)return [];let r=[];for(let i of n){let o=t.yOf(i.price,this.paneId);if(o==null)return [];r.push([t.xOf(i.time),o]);}return r}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.box(t);if(!n)return null;let r=Math.min(n.ey,n.sy,n.ty);return {x:n.x1,y:r,w:n.x2-n.x1,h:Math.max(n.ey,n.sy,n.ty)-r}}priceRange(){let t=this.resolved();if(!t)return null;let n=t.map(r=>r.price);return {min:Math.min(...n),max:Math.max(...n)}}schema(){return {fields:[{path:"riskPercent",label:"Risk %",kind:"number",min:0,max:100,step:.1,group:"behavior"},{path:"accountBalance",label:"Account balance",kind:"number",min:0,max:1e12,step:1,group:"behavior"},{path:"quantity",label:"Position size",kind:"number",group:"behavior"},{path:"direction",label:"Direction",kind:"select",options:Ci,group:"behavior"},{path:"entryPrice",label:"Entry price",kind:"number",group:"behavior"},{path:"stopPrice",label:"Stop price",kind:"number",group:"behavior"},{path:"targetPrice",label:"Target price",kind:"number",group:"behavior"},{path:"showText",label:"Show text",kind:"boolean",group:"behavior"},{path:"showHeader",label:"Show direction & ratio",kind:"boolean",group:"behavior"},{path:"showLossSize",label:"Show loss & size",kind:"boolean",group:"behavior"},{path:"showTargetLabel",label:"Show target label",kind:"boolean",group:"behavior"},{path:"showStopLabel",label:"Show stop label",kind:"boolean",group:"behavior"},{path:"showPrices",label:"Show level prices",kind:"boolean",group:"behavior"},{path:"profitColor",label:"Profit zone",kind:"color",group:"fill"},{path:"lossColor",label:"Loss zone",kind:"color",group:"fill"},...O.filter(t=>t.path!=="style.lineColor"),{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Te,group:"text"}]}}writeProps(){return {riskPercent:this.riskPercent,accountBalance:this.accountBalance,showText:this.showText,showHeader:this.showHeader,showPrices:this.showPrices,showLossSize:this.showLossSize,showTargetLabel:this.showTargetLabel,showStopLabel:this.showStopLabel,profitColor:this.profitColor,lossColor:this.lossColor}}readProps(t){typeof t.riskPercent=="number"&&Number.isFinite(t.riskPercent)&&(this.riskPercent=t.riskPercent),typeof t.accountBalance=="number"&&Number.isFinite(t.accountBalance)&&(this.accountBalance=t.accountBalance),typeof t.showText=="boolean"&&(this.showText=t.showText),typeof t.showHeader=="boolean"&&(this.showHeader=t.showHeader),typeof t.showPrices=="boolean"&&(this.showPrices=t.showPrices),typeof t.showLossSize=="boolean"&&(this.showLossSize=t.showLossSize),typeof t.showTargetLabel=="boolean"&&(this.showTargetLabel=t.showTargetLabel),typeof t.showStopLabel=="boolean"&&(this.showStopLabel=t.showStopLabel),typeof t.profitColor=="string"&&(this.profitColor=t.profitColor),typeof t.lossColor=="string"&&(this.lossColor=t.lossColor);}};ie.DEFAULT_RR=2,ie.MIN_DRAG_PX=6,ie.DEFAULT_RISK_PX=64,ie.DEFAULT_WIDTH_PX=150,ie.MIN_WIDTH_PX=48,ie.DEFAULT_RISK_PERCENT=1,ie.DEFAULT_ACCOUNT_BALANCE=1e4,ie.DEFAULT_PROFIT_COLOR=fr,ie.DEFAULT_LOSS_COLOR=br;var Oe=ie;function Nh(s){if(!Number.isFinite(s))return "0";let e=Math.round(s*100)/100;return Number.isInteger(e)?String(e):e.toFixed(2)}function Hh(s){return !Number.isFinite(s)||s===0?"0":s>=100?s.toFixed(2):s>=1?s.toFixed(4).replace(/\.?0+$/,""):s.toPrecision(4).replace(/\.?0+$/,"")}function Za(s){return Number.isFinite(s)?Math.abs(s)>=1?s.toFixed(2):s.toPrecision(4).replace(/\.?0+$/,""):"0"}function Ja(s){return Math.round(s*1e8)/1e8}var Pn=new Map;function A(s){Pn.set(s.type,s);}function nt(s){return Pn.get(s)}function Ti(){return [...Pn.values()]}function rt(s,e){let t=Pn.get(s);if(!t)return null;let n={...t.defaultStyle,...e.style??{}};return t.create({...e,style:n})}function $o(s){let e=rt(s.type,{paneId:s.paneId});if(!e)return;s.style={...e.style};let t=s.text?.value;e.text?(s.text={...e.text},t!==void 0&&(s.text.value=t)):s.text=void 0;let n=e.serialize().props;n!==void 0&&s.applyProps(n);}function Fe(s){let e=Pn.get(s.type);return e?e.create(s):null}var zh=I('<line x1="4" y1="19" x2="20" y2="5"/>'),$h=I('<line x1="3" y1="12" x2="21" y2="12"/>');A({type:"trendline",group:"lines",label:"Trend Line",icon:zh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new yr(s)});A({type:"hline",group:"lines",label:"Horizontal Line",icon:$h,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"dashed"},create:s=>new xr(s)});var Wh=I('<line x1="3" y1="20" x2="21" y2="6"/><circle cx="3" cy="20" r="1.6" fill="currentColor"/>'),Uh=I('<rect x="4" y="6" width="16" height="12" rx="1"/>'),Gh=I('<path d="M5 6h14M12 6v13"/>');A({type:"ray",group:"lines",label:"Ray",icon:Wh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new wr(s)});var Yh=I('<path d="M5 19 19 5"/><path d="M5 19 8.5 19M5 19 5 15.5"/><path d="M19 5 15.5 5M19 5 19 8.5"/>'),Xh=I('<line x1="12" y1="3" x2="12" y2="21"/>'),Kh=I('<line x1="5" y1="12" x2="21" y2="12"/><circle cx="5" cy="12" r="1.6" fill="currentColor"/>'),jh=I('<line x1="3" y1="12" x2="21" y2="12"/><line x1="12" y1="3" x2="12" y2="21"/>'),qh=I('<path d="M4 20 20 4"/><rect x="9" y="9" width="9" height="6" rx="1"/>'),Zh=I('<path d="M4 20 20 6"/><path d="M4 20 15 20"/><path d="M11 20a7 7 0 0 0-2-4.9"/>');A({type:"extendedline",group:"lines",label:"Extended Line",icon:Yh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Sr(s)});A({type:"vline",group:"lines",label:"Vertical Line",icon:Xh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Cr(s)});A({type:"hray",group:"lines",label:"Horizontal Ray",icon:Kh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Tr(s)});A({type:"crossline",group:"lines",label:"Cross Line",icon:jh,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Mr(s)});A({type:"infoline",group:"lines",label:"Info Line",icon:qh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Lr(s)});A({type:"trendangle",group:"lines",label:"Trend Angle",icon:Zh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Pr(s)});A({type:"box",group:"shapes",label:"Rectangle",icon:Uh,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}26`},create:s=>new Er(s)});A({type:"text",group:"annotations",label:"Text",icon:Gh,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new He(s)});var Jh=I('<path d="M5 4h14a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-6l-5 5v-5H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"/>');A({type:"callout",group:"annotations",label:"Callout",icon:Jh,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new Ie(s)});var Qh=I('<path d="M5 4h14a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-7l-4 4v-4H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z"/><path d="M8 8.5h8M8 12h5"/>'),eu=I('<rect x="10" y="4.5" width="11" height="8" rx="1.5"/><path d="M10 8.5 4 16"/><circle cx="3.5" cy="16.5" r="1.6" fill="currentColor" stroke="none"/>'),tu=I('<path d="M5 4.5h14a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-7l-4 4v-4H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2Z"/>'),nu=I('<path d="M3 12 7 8h12a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H7Z"/><path d="M10.5 12.5h6" stroke-width="1.4"/>'),ru=I('<path d="M12 11.5V21"/><rect x="5" y="4" width="14" height="7" rx="1"/><path d="M9 7.5h6"/>');A({type:"note",group:"annotations",label:"Note",icon:Qh,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new dt(s)});A({type:"pricenote",group:"annotations",label:"Price Note",icon:eu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new ut(s)});A({type:"comment",group:"annotations",label:"Comment",icon:tu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new pt(s)});A({type:"pricelabel",group:"annotations",label:"Price Label",icon:nu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new ht(s)});A({type:"signpost",group:"annotations",label:"Signpost",icon:ru,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new mt(s)});var iu=I('<line x1="3" y1="16" x2="21" y2="8"/><line x1="3" y1="21" x2="21" y2="13"/>'),ou=I('<line x1="3" y1="7" x2="21" y2="10"/><line x1="3" y1="18" x2="21" y2="14"/>'),su=I('<circle cx="4" cy="12" r="1.6" fill="currentColor"/><line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>');A({type:"parallelchannel",group:"channels",label:"Parallel Channel",icon:iu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new kr(s)});A({type:"disjointchannel",group:"channels",label:"Disjoint Channel",icon:ou,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new Ir(s)});var au=I('<line x1="3" y1="7" x2="21" y2="7"/><line x1="3" y1="18" x2="21" y2="11"/>');A({type:"flattopbottom",group:"channels",label:"Flat Top/Bottom",icon:au,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new Rr(s)});var lu=I('<line x1="3" y1="8" x2="21" y2="4"/><line x1="3" y1="16" x2="21" y2="12"/><line x1="3" y1="12" x2="21" y2="8" stroke-dasharray="3 3"/>');A({type:"regressionchannel",group:"channels",label:"Linear Regression",icon:lu,defaultStyle:{lineColor:he,lineWidth:1,lineStyle:"solid"},create:s=>new ze(s)});A({type:"pitchfork",group:"pitchforks",label:"Pitchfork",icon:su,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Dr(s)});var cu=I('<circle cx="4" cy="8" r="1.6" fill="currentColor"/><line x1="4" y1="8" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>'),du=I('<circle cx="6" cy="9" r="1.6" fill="currentColor"/><line x1="6" y1="9" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>'),hu=I('<line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="8" x2="10" y2="16"/><line x1="10" y1="8" x2="21" y2="8"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="16" x2="21" y2="16"/>');A({type:"schiffpitchfork",group:"pitchforks",label:"Schiff Pitchfork",icon:cu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Ar(s)});A({type:"modifiedschiffpitchfork",group:"pitchforks",label:"Modified Schiff Pitchfork",icon:du,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Or(s)});A({type:"insidepitchfork",group:"pitchforks",label:"Inside Pitchfork",icon:hu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Fr(s)});var uu=I('<path d="M7 7h10v10"/><path d="M7 17 17 7"/>'),pu=I('<ellipse cx="12" cy="12" rx="9" ry="6"/>'),mu=I('<path d="M12 4 20 19 4 19Z"/>');A({type:"arrow",group:"shapes",label:"Arrow",icon:uu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",arrowRight:true},create:s=>new Br(s)});A({type:"ellipse",group:"shapes",label:"Ellipse",icon:pu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new Vr(s)});A({type:"triangle",group:"shapes",label:"Triangle",icon:mu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new _r(s)});var fu=I('<polyline points="3 17 9 10 13 14 21 5"/>'),bu=I('<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>'),gu=I('<path d="M9 11 15 5l4 4-6 6H9Z"/><path d="M9 15l-2 2"/><path d="M4 21h6"/>');A({type:"polyline",group:"shapes",label:"Polyline",icon:fu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Nr(s)});A({type:"freehand",group:"shapes",label:"Brush",icon:bu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Hr(s)});A({type:"highlighter",group:"shapes",label:"Highlighter",icon:gu,defaultStyle:{lineColor:`${va}59`,lineWidth:14,lineStyle:"solid"},create:s=>new zr(s)});var vu=I('<circle cx="12" cy="12" r="8"/>'),yu=I('<path d="M5 14 9.5 5 19 10 14.5 19 Z"/>'),xu=I('<path d="M4 19 9 11 13 14 17 8 20 4"/><path d="M17.2 5.5 20 4 19.4 7.1"/>'),wu=I('<path d="M4 17a8 8 0 0 1 16 0"/><path d="M4 17 20 17"/>'),Su=I('<path d="M4 18Q12 1 20 14"/>'),Cu=I('<path d="M12 5 12 19"/><path d="M6 11 12 5 18 11"/>'),Tu=I('<path d="M12 5 12 19"/><path d="M6 13 12 19 18 13"/>');A({type:"circle",group:"shapes",label:"Circle",icon:vu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new $r(s)});A({type:"rotatedrect",group:"shapes",label:"Rotated Rectangle",icon:yu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}26`},create:s=>new Wr(s)});A({type:"path",group:"shapes",label:"Path",icon:xu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Ur(s)});A({type:"arc",group:"shapes",label:"Arc",icon:wu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}26`},create:s=>new Gr(s)});A({type:"curve",group:"shapes",label:"Curve",icon:Su,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Yr(s)});A({type:"arrowmarkup",group:"shapes",label:"Arrow Mark Up",icon:Cu,defaultStyle:{lineColor:q,lineWidth:1,lineStyle:"solid"},create:s=>new yn(s)});A({type:"arrowmarkdown",group:"shapes",label:"Arrow Mark Down",icon:Tu,defaultStyle:{lineColor:X,lineWidth:1,lineStyle:"solid"},create:s=>new xn(s)});var Mu=I('<path d="M6 21V4"/><path d="M6 5h11l-2.5 3.5L17 12H6" fill="currentColor" stroke="none"/>'),Lu=I('<path d="m12 3 2.6 5.8 6.4.6-4.8 4.2 1.4 6.2L12 16.9 6.4 19.8 7.8 13.6 3 9.4l6.4-.6Z"/>');A({type:"flagmark",group:"stamps",label:"Flag",icon:Mu,defaultStyle:{lineColor:ve,lineWidth:1,lineStyle:"solid"},create:s=>new wn(s)});A({type:"iconstamp",group:"stamps",label:"Icon",icon:Lu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Sn(s)});var Pu=I('<line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/>'),Eu=I('<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="11" x2="21" y2="11"/><line x1="3" y1="15" x2="14" y2="15"/><line x1="3" y1="20" x2="14" y2="20"/>');A({type:"fibretracement",group:"fibonacci",label:"Fib Retracement",icon:Pu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new jr(s)});A({type:"fibextension",group:"fibonacci",label:"Fib Extension",icon:Eu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new qr(s)});var ku=I('<path d="M3 20 10 9l4 5"/><path d="M14 14h7M14 9h7M14 4h7"/>');A({type:"fibextensiontrend",group:"fibonacci",label:"Trend-Based Fib Extension",icon:ku,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Zr(s)});var Iu=I('<path d="M4 20 20 5M4 20 21 11M4 20 21 17M4 20 20 20"/>'),Ru=I('<path d="M3 5v14M6 5v14M11 5v14M19 5v14"/>');A({type:"fibfan",group:"fibonacci",label:"Fib Fan",icon:Iu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Jr(s)});A({type:"fibtimezones",group:"fibonacci",label:"Fib Time Zones",icon:Ru,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"dashed"},create:s=>new Qr(s)});var Du=I('<path d="M3 18 18 9M5 21 20 12M6 13 21 4"/>'),Au=I('<path d="M4 4 20 20M4 4 20 12M4 4 12 20M4 4 20 4M4 4 4 20"/>'),Ou=I('<path d="M3 19 9 8M9 8 12 5v14M14 5v14M18 5v14M21 5v14"/>');A({type:"fibchannel",group:"fibonacci",label:"Fib Channel",icon:Du,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ei(s)});A({type:"fibspeedfan",group:"fibonacci",label:"Fib Speed Resistance Fan",icon:Au,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ti(s)});A({type:"trendfibtime",group:"fibonacci",label:"Trend-Based Fib Time",icon:Ou,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"dashed"},create:s=>new ni(s)});var Fu=I('<circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="10"/>'),Bu=I('<path d="M8 20a4 4 0 0 1 8 0"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0"/><circle cx="12" cy="20" r="1.4" fill="currentColor" stroke="none"/>'),Vu=I('<path d="M4 20 20 16M4 20 14 4"/><path d="M11.8 18.1A8 8 0 0 0 8.2 13.2"/><path d="M16.6 16.9A13 13 0 0 0 10.9 9"/>'),_u=I('<path d="M13 12a2 2 0 1 1-2-2 4 4 0 0 1 4 4 6 6 0 0 1-9 5.2 9 9 0 0 1 .5-15"/>');A({type:"fibcircles",group:"fibonacci",label:"Fib Circles",icon:Fu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ri(s)});A({type:"fibarcs",group:"fibonacci",label:"Fib Speed Resistance Arcs",icon:Bu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ii(s)});A({type:"fibwedge",group:"fibonacci",label:"Fib Wedge",icon:Vu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new oi(s)});A({type:"fibspiral",group:"fibonacci",label:"Fib Spiral",icon:_u,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new wt(s)});var Nu=I('<path d="M4 20 20 20M4 20 20 13M4 20 20 6M4 20 15 4M4 20 9 4M4 20 4 4"/>'),Hu=I('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 12h16M12 4v16M4 4 20 20" opacity="0.6"/>');A({type:"gannfan",group:"fibonacci",label:"Gann Fan",icon:Nu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new si(s)});A({type:"gannbox",group:"fibonacci",label:"Gann Box",icon:Hu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ai(s)});var zu=I('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 20 20 4M4 20 20 12M4 20 12 4" opacity="0.7"/><path d="M4 20a16 16 0 0 1 16-16" opacity="0.5"/>');A({type:"gannsquare",group:"fibonacci",label:"Gann Square",icon:zu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new St(s)});var $u=I('<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0" opacity="0.9"/><path d="M6 20a4 4 0 0 1 8 0" opacity="0.75"/><path d="M10 20a2 2 0 0 1 4 0" opacity="0.6"/><path d="M8 20v-6M12 20v-9M16 20v-6" opacity="0.45"/>');A({type:"dedekind",group:"geometry",label:"Dedekind Tessellation",icon:$u,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Ct(s)});var Wu=I('<circle cx="16" cy="12" r="5" opacity="0.55"/><circle cx="13" cy="12" r="3.5" opacity="0.75"/><circle cx="10.5" cy="12" r="2"/><path d="M8 4v16"/>'),Uu=I('<circle cx="17" cy="12" r="4.5" opacity="0.45"/><circle cx="13" cy="12" r="3" opacity="0.7"/><circle cx="10" cy="12" r="1.6"/><path d="M6 12 16 5M6 12 16 19"/>');A({type:"sonic",group:"geometry",label:"Sonic",icon:Wu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Tn(s)});A({type:"supersonic",group:"geometry",label:"Supersonic",icon:Uu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Mn(s)});var Gu=I('<circle cx="16" cy="12" r="5" opacity="0.4"/><circle cx="13" cy="12" r="3.2" opacity="0.65"/><circle cx="10.8" cy="12" r="1.8"/><path d="M8 4v16"/><path d="M15 8.5h2M12.5 10h2" opacity="0.5"/>'),Yu=I('<circle cx="17" cy="12" r="4.5" opacity="0.4"/><circle cx="12.5" cy="12" r="2.8" opacity="0.65"/><circle cx="9.8" cy="12" r="1.4"/><path d="M6 12 16 5M6 12 16 19"/>');A({type:"goldensonic",group:"geometry",label:"Golden Sonic",icon:Gu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ci(s)});A({type:"goldensupersonic",group:"geometry",label:"Golden Supersonic",icon:Yu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new di(s)});var Xu=I('<path d="M3 18 7 8 11 14 15 6 20 16"/>'),Ku=I('<path d="M4 17 9 7 14 15 20 5"/>'),ju=I('<path d="M3 19 8 9 12 13 17 5 21 9"/>'),qu=I('<path d="M4 7 11 16 20 9"/>'),Zu=I('<path d="M3 18 6 12 9 16 12 5 15 16 18 12 21 18"/>');A({type:"xabcd",group:"patterns",label:"XABCD Pattern",icon:Xu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new hi(s)});A({type:"abcd",group:"patterns",label:"ABCD Pattern",icon:Ku,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ui(s)});A({type:"elliottimpulse",group:"patterns",label:"Elliott Impulse Wave (1-5)",icon:ju,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new pi(s)});A({type:"elliottcorrection",group:"patterns",label:"Elliott Correction Wave (ABC)",icon:qu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new mi(s)});A({type:"headshoulders",group:"patterns",label:"Head & Shoulders",icon:Zu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new fi(s)});var Ju=I('<path d="M3 17 7 6 12 14 17 5 21 16"/><path d="M3 17 21 16" opacity="0.45"/>'),Gt={group:"patterns",icon:Ju,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"}};A({type:"gartley",label:"Gartley",...Gt,create:s=>new bi(s)});A({type:"bat",label:"Bat",...Gt,create:s=>new gi(s)});A({type:"butterfly",label:"Butterfly",...Gt,create:s=>new vi(s)});A({type:"crab",label:"Crab",...Gt,create:s=>new yi(s)});A({type:"shark",label:"Shark",...Gt,create:s=>new xi(s)});A({type:"cypher",label:"Cypher",...Gt,create:s=>new wi(s)});var Qu=I('<rect x="4" y="6" width="16" height="12" rx="1"/><path d="M4 18 20 6" opacity="0.5"/>');A({type:"datepricerange",group:"measure",label:"Date & Price Range",icon:Qu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Si(s)});var ep=I('<rect x="4.5" y="4.5" width="15" height="7.5" rx="1" fill="currentColor" fill-opacity="0.25"/><rect x="4.5" y="12" width="15" height="7.5" rx="1"/>');A({type:"position",group:"measure",label:"Long/Short Position",icon:ep,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Oe(s)});var tp=I('<line x1="5" y1="3" x2="5" y2="21"/><path d="M5 16c4 0 5-9 8-9s3 5 8 3"/>');A({type:"anchoredvwap",group:"measure",label:"Anchored VWAP",icon:tp,defaultStyle:{lineColor:_e,lineWidth:2,lineStyle:"solid"},create:s=>new ft(s)});var np=I('<path d="M4 4v16"/><path d="M4 8h10"/><path d="M4 12h14"/><path d="M4 16h8"/><path d="M4 20h12"/>');A({type:"fixedrangevp",group:"measure",label:"Fixed Range Volume Profile",icon:np,defaultStyle:{lineColor:q,lineWidth:1,lineStyle:"solid"},create:s=>new Re(s)});var rp=["fibretracement","fibextension","fibextensiontrend","fibfan","fibtimezones","fibchannel","fibspeedfan","trendfibtime","fibcircles","fibarcs","fibwedge","fibspiral"],ip=["gannfan","gannbox","gannsquare"],op=["dedekind","sonic","supersonic","goldensonic","goldensupersonic"],sp=["xabcd","abcd","headshoulders"],ap=["elliottimpulse","elliottcorrection"],lp=["gartley","bat","butterfly","crab","shark","cypher"],cp=["position","datepricerange"],dp=["anchoredvwap","fixedrangevp"],hp=["freehand","highlighter"],up=["arrow","arrowmarkup","arrowmarkdown"],pp=["box","ellipse","triangle","polyline","circle","rotatedrect","path","arc","curve"],mp=["text","callout","note","pricenote","comment","pricelabel","signpost"],fp=["flagmark","iconstamp"],bp=[{id:"lines-channels-pitchforks",label:"Lines",sections:[{label:"Lines",registryGroup:"lines"},{label:"Channels",registryGroup:"channels"},{label:"Pitchforks",registryGroup:"pitchforks"}]},{id:"fibonacci-gann",label:"Fibonacci",sections:[{label:"Fibonacci",types:rp},{label:"Gann",types:ip},{label:"Geometry",types:op}]},{id:"patterns-waves-harmonics",label:"Patterns",sections:[{label:"Patterns",types:sp},{label:"Elliott Waves",types:ap},{label:"Harmonics",types:lp}]},{id:"measurements",label:"Measurements",sections:[{label:"Measurements",types:cp},{label:"Volume",types:dp}]},{id:"brushes-arrows-shapes",label:"Shapes",sections:[{label:"Brushes",types:hp},{label:"Arrows",types:up},{label:"Shapes",types:pp}]},{id:"text",label:"Text",sections:[{label:"Text",types:mp}]},{id:"icons",label:"Icons",sections:[{label:"Icons",types:fp}]}];function gp(s){let e=nt(s);return e?{type:e.type,label:e.label,icon:e.icon}:null}function vp(s){let e=new Map;for(let t of Ti()){if(s&&!s.has(t.type))continue;let n={type:t.type,label:t.label,icon:t.icon};e.has(t.group)||e.set(t.group,[]),e.get(t.group).push(n);}return e}function yp(s,e,t){return "registryGroup"in s?e.get(s.registryGroup)??[]:s.types.map(n=>t.get(n)).filter(n=>n!=null)}function Qa(s){let e=vp(s),t=new Map;for(let r of e.values())for(let i of r)t.set(i.type,i);let n=[];for(let r of bp){let i=[],o=[];for(let a of r.sections){let l=yp(a,e,t);l.length!==0&&(i.push({label:a.label,tools:l}),o.push(...l));}o.length!==0&&n.push({id:r.id,label:r.label,tools:o,sections:i.length>0?i:void 0});}return {groups:n}}function xp(s){let e=new Set;for(let t of s)nt(t)&&e.add(t);return Qa(e)}function wp(s){let e=[];for(let t of s){let n=t.tools.map(gp).filter(r=>r!=null);n.length>0&&e.push({id:t.id,label:t.label,tools:n});}return {groups:e}}function En(){return Qa()}function kn(s){if(s===false)return {definition:En(),visible:false};if(s===void 0||s===true)return {definition:En(),visible:true};let e=s.toolbar??true;return s.groups?{definition:wp(s.groups),visible:e}:s.tools?{definition:xp(s.tools),visible:e}:{definition:En(),visible:e}}function Mt(s){let e=globalThis.structuredClone;return e?e(s):JSON.parse(JSON.stringify(s))}function Sp(s){if(!s||typeof s!="object")return false;let e=s;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.paneId=="string"&&Array.isArray(e.anchors)&&e.anchors.every(t=>t&&typeof t.time=="number"&&typeof t.price=="number")&&!!e.style&&typeof e.style=="object"}function el(s){let e=s;return !e||typeof e!="object"||e.version!==1||!Array.isArray(e.drawings)?{version:1,drawings:[]}:{version:1,drawings:e.drawings.filter(Sp)}}var Yt=class{constructor(){this.byId=new Map;this.seq=0;this.zCounter=1;this.listeners=new Set;}nextId(){return this.seq+=1,`dw-${this.seq}`}add(e){return e.zIndex||(e.zIndex=this.zCounter),this.zCounter=Math.max(this.zCounter,Math.ceil(e.zIndex))+1,this.byId.set(e.id,e),this.emit(),e}remove(e){let t=this.byId.delete(e);return t&&this.emit(),t}get(e){return this.byId.get(e)}has(e){return this.byId.has(e)}update(e,t){let n=this.byId.get(e);return n?(t.anchors&&(n.anchors=t.anchors.map(r=>({time:r.time,price:r.price}))),t.style&&(n.style={...t.style}),t.text!==void 0&&(n.text=t.text?{...t.text}:void 0),t.paneId!==void 0&&(n.paneId=t.paneId),t.locked!==void 0&&(n.locked=t.locked),t.visible!==void 0&&(n.visible=t.visible),t.zIndex!==void 0&&(n.zIndex=t.zIndex),t.props!==void 0&&n.applyProps(t.props),this.emit(),n):null}all(){return [...this.byId.values()].sort((e,t)=>e.zIndex-t.zIndex)}byPane(e){return this.all().filter(t=>t.paneId===e)}bringToFront(e,t=0){let n=this.byId.get(e);n&&(n.zIndex=Math.max(this.zCounter,Math.floor(t)+1),this.zCounter=n.zIndex+1,this.emit());}sendToBack(e,t=1){let n=this.byId.get(e);if(!n)return;let r=Math.min(...[...this.byId.values()].map(i=>i.zIndex),Math.ceil(t));n.zIndex=r-1,this.emit();}setLocked(e,t){let n=this.byId.get(e);n&&(n.locked=t,this.emit());}setVisible(e,t){let n=this.byId.get(e);n&&(n.visible=t,this.emit());}clear(){this.byId.size!==0&&(this.byId.clear(),this.emit());}serialize(){return {version:1,drawings:this.all().map(e=>e.serialize())}}load(e){let t=el(e);this.byId.clear(),this.seq=0,this.zCounter=1;for(let n of t.drawings){let r=Fe(n);r&&(this.byId.set(r.id,r),this.zCounter=Math.max(this.zCounter,r.zIndex)+1,this.bumpSeqPast(r.id));}this.emit();}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}bumpSeqPast(e){let t=/^dw-(\d+)$/.exec(e);t&&(this.seq=Math.max(this.seq,Number(t[1])));}emit(){for(let e of this.listeners)e();}};var Mi=class{constructor(e=100){this.cap=e;this.undoStack=[];this.redoStack=[];this.pending=null;this.dirtied=false;this.depth=0;}begin(e){this.depth+=1,this.depth===1&&(this.pending=Mt(e),this.dirtied=false);}markDirty(){this.depth===0||this.dirtied||!this.pending||(this.push(this.pending),this.dirtied=true);}commit(){this.depth!==0&&(this.depth-=1,this.depth===0&&(this.pending=null,this.dirtied=false));}abort(){this.commit();}record(e){if(this.depth>0){this.markDirty();return}this.push(Mt(e));}undo(e){let t=this.undoStack.pop();return t?(this.redoStack.push(Mt(e)),t):null}redo(e){let t=this.redoStack.pop();return t?(this.undoStack.push(Mt(e)),t):null}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[],this.pending=null,this.dirtied=false,this.depth=0;}push(e){this.undoStack.push(e),this.undoStack.length>this.cap&&this.undoStack.shift(),this.redoStack=[];}};var Li=class{constructor(e,t,n){this.events=t;this.store=new Yt;this.history=new Mi;this.activeTool=null;this.snapMode="off";this.stayInDrawingMode=false;this.mode=null;this.favs=new Set;this.selectedIds=[];this.clipboard=[];this.lastStyle=new Map;this.subs=[];if(this.enabled=!!e.capabilities.userDrawings&&!!e.userDrawingsPort,this.port=this.enabled?e.userDrawingsPort:null,this.port){let{definition:r,visible:i}=kn(n);this.port.setToolbar(r),this.port.showToolbar(i),this.subs.push(this.port.onDrawingIntent(o=>this.onIntent(o))),this.subs.push(this.store.onChange(()=>this.sync()));}}get supported(){return this.enabled}setTool(e){if(!this.port)return;let t=e!==this.activeTool;this.activeTool=e,this.port.setActiveTool(e,e?this.lastStyle.get(e):void 0),t&&this.events.emit("drawing:tool",{type:e});}getTool(){return this.activeTool}getSnapMode(){return this.snapMode}setSnapMode(e){!this.port||e===this.snapMode||(this.snapMode=e,this.port.setSnapMode?.(e),this.events.emit("drawing:snap",{mode:e}));}getStayMode(){return this.stayInDrawingMode}setStayMode(e){!this.port||e===this.stayInDrawingMode||(this.stayInDrawingMode=e,this.port.setStayMode?.(e),this.events.emit("drawing:stay",{on:e}));}getMode(){return this.mode}setMode(e){!this.port||e===this.mode||(this.mode=e,this.port.setMode?.(e),this.events.emit("drawing:mode",{mode:e}));}showToolbar(e){this.port?.showToolbar(e);}favorites(){return [...this.favs]}isFavorite(e){return this.favs.has(e)}setFavorite(e,t){nt(e)&&t!==this.favs.has(e)&&(t?this.favs.add(e):this.favs.delete(e),this.pushFavorites());}setFavorites(e){let t=e.filter(n=>nt(n)!=null);t.length===this.favs.size&&t.every(n=>this.favs.has(n))||(this.favs=new Set(t),this.pushFavorites());}pushFavorites(){let e=[...this.favs];this.port?.setFavorites?.(e),this.events.emit("drawing:favorites",{favorites:e});}setToolbar(e){this.port?.setToolbar(kn(e).definition);}setExternalGhost(e){this.port?.setExternalGhost?.(e);}setToolShortcuts(e){this.port?.setToolShortcuts?.(e);}add(e,t={}){if(!this.enabled)return null;let r={...this.lastStyle.get(e)??{},...t.style??{}},i=rt(e,{id:this.store.nextId(),paneId:t.paneId??"price",anchors:t.anchors,style:r,text:t.text,props:t.props,zIndex:t.zIndex??this.startZ(t.paneId??"price")});return i?(this.history.record(this.store.serialize()),this.store.add(i),this.captureStyle(i.id),this.events.emit("drawing:created",{id:i.id}),i):null}remove(e){this.deleteMany([e]);}update(e,t){let n=this.store.serialize(),r=t.style?this.store.get(e):void 0,i=t.style&&r?{...t,style:{...r.style,...t.style}}:t;this.store.update(e,i)&&(this.history.record(n),this.captureStyle(e),this.events.emit("drawing:edited",{id:e}));}updateMany(e){this.history.begin(this.store.serialize());for(let{id:t,patch:n}of e)this.store.update(t,n)&&(this.history.markDirty(),this.events.emit("drawing:edited",{id:t}));this.history.commit();}removeMany(e){this.deleteMany(e);}setLocked(e,t){let n=this.store.serialize();this.history.record(n),this.store.setLocked(e,t),this.events.emit("drawing:edited",{id:e});}setVisible(e,t){let n=this.store.serialize();this.history.record(n),this.store.setVisible(e,t),this.events.emit("drawing:edited",{id:e});}bringToFront(e){let t=this.store.serialize();this.history.record(t),this.store.bringToFront(e,this.seriesTopZ(this.store.get(e)?.paneId)),this.events.emit("drawing:edited",{id:e});}sendToBack(e){let t=this.store.serialize();this.history.record(t),this.store.sendToBack(e,this.seriesBottomZ(this.store.get(e)?.paneId)),this.events.emit("drawing:edited",{id:e});}seriesTopZ(e){return e!==void 0?this.port?.stackRange?.(e)?.front??0:0}seriesBottomZ(e){return e!==void 0?this.port?.stackRange?.(e)?.back??1:1}startZ(e){let t=this.port?.stackRange?.(e);return t?(t.price??t.front)-.5:void 0}select(e,t=false){this.setSelection(e,t);}openSettings(e){this.port?.openSettings(e);}undo(){let e=this.history.undo(this.store.serialize());e&&this.restoreSnapshot(e);}redo(){let e=this.history.redo(this.store.serialize());e&&this.restoreSnapshot(e);}canUndo(){return this.history.canUndo()}canRedo(){return this.history.canRedo()}duplicate(e){if(!this.enabled)return [];let t=this.resolve(e);return t.length===0?[]:this.insertClones(t.map(n=>n.serialize()))}clone(e){return this.duplicate([e])[0]??null}copy(e){let t=this.resolve(e).map(n=>Mt(n.serialize()));t.length&&(this.clipboard=t);}paste(){return !this.enabled||this.clipboard.length===0?[]:this.insertClones(this.clipboard)}all(){return this.store.serialize().drawings}toJSON(){return this.store.serialize()}fromJSON(e){this.history.clear(),this.selectedIds=[],this.store.load(e);}destroy(){for(let e of this.subs)e();this.subs.length=0;}setSelection(e,t=false){let n;if(t){n=[...this.selectedIds];for(let r of e){let i=n.indexOf(r);i>=0?n.splice(i,1):n.push(r);}}else n=[...e];this.selectedIds=n.filter(r=>this.store.has(r)),this.port?.setSelection(this.selectedIds),this.events.emit("drawing:selected",{id:this.selectedIds[0]??null});}restoreSnapshot(e){this.store.load(e),this.selectedIds=this.selectedIds.filter(t=>this.store.has(t)),this.port?.setSelection(this.selectedIds),this.events.emit("drawing:selected",{id:this.selectedIds[0]??null});}deleteMany(e){this.history.begin(this.store.serialize());let t=[];for(let r of e)this.store.remove(r)&&t.push(r),this.history.markDirty();if(this.history.commit(),t.length===0)return;let n=this.selectedIds.filter(r=>this.store.has(r));n.length!==this.selectedIds.length&&this.setSelection(n);for(let r of t)this.events.emit("drawing:removed",{id:r});}insertClones(e){this.history.begin(this.store.serialize());let t=[];for(let n of e){let r=Fe({...n,id:this.store.nextId()});r&&(this.store.add(r),this.history.markDirty(),t.push(r));}if(this.history.commit(),t.length){this.setSelection(t.map(n=>n.id));for(let n of t)this.events.emit("drawing:created",{id:n.id});}return t}resolve(e){return e.map(t=>this.store.get(t)).filter(t=>t!=null)}captureStyle(e){let t=this.store.get(e);t&&this.lastStyle.set(t.type,{...t.style});}sync(){this.port?.syncDrawings(this.store.serialize().drawings);}onIntent(e){switch(e.kind){case "arm":this.setTool(e.type);break;case "draft":this.events.emit("drawing:draft",{doc:e.doc});break;case "create":{let t=this.store.serialize(),n=this.lastStyle.get(e.doc.type),r=n?{...e.doc.style,...n}:e.doc.style,i=Fe({...e.doc,id:this.store.nextId(),style:r});if(!i)return;i.zIndex||(i.zIndex=this.startZ(i.paneId)??0),this.history.record(t),this.store.add(i),this.captureStyle(i.id),this.events.emit("drawing:created",{id:i.id});break}case "edit":{let t=this.store.serialize();this.store.update(e.doc.id,e.doc)&&(this.history.record(t),this.captureStyle(e.doc.id),this.events.emit("drawing:edited",{id:e.doc.id}));break}case "edit-many":{this.history.begin(this.store.serialize());for(let t of e.docs)this.store.update(t.id,t)&&(this.history.markDirty(),this.events.emit("drawing:edited",{id:t.id}));this.history.commit();break}case "select":this.setSelection(e.ids,e.additive);break;case "delete":this.deleteMany(e.ids);break;case "reorder":e.to==="front"?this.bringToFront(e.id):this.sendToBack(e.id);break;case "settings":this.events.emit("drawing:settings",{id:e.id});break;case "favorite":this.setFavorite(e.type,e.on);break;case "snap-mode":e.mode!==this.snapMode&&(this.snapMode=e.mode,this.events.emit("drawing:snap",{mode:e.mode}));break;case "stay-mode":e.on!==this.stayInDrawingMode&&(this.stayInDrawingMode=e.on,this.events.emit("drawing:stay",{on:e.on}));break;case "mode":e.mode!==this.mode&&(this.mode=e.mode,this.events.emit("drawing:mode",{mode:e.mode}));break;case "tool-finished":!this.stayInDrawingMode&&e.type!=="freehand"&&e.type!=="highlighter"&&this.setTool(null);break;case "undo":this.undo();break;case "redo":this.redo();break;case "duplicate":this.duplicate(e.ids);break;case "copy":this.copy(e.ids);break;case "paste":this.paste();break}}};var tl={D:864e5,W:6048e5,M:2592e6};function In(s){let e=s.trim();if(tl[e])return tl[e];let t=/^(\d+)\s*(m|h|d|w)?$/i.exec(e);if(t){let n=parseInt(t[1],10),r=(t[2]??"m").toLowerCase();return n*(r==="m"?6e4:r==="h"?36e5:r==="d"?864e5:6048e5)}return 36e5}var it=s=>s.trim().toLowerCase(),nl=s=>s.trim().toUpperCase();function We(s){let e=s.trim(),t=/^(?:([A-Za-z0-9_.]+):)?(.+)$/.exec(e);if(!t)return {provider:null,ticker:e};let n=t[1]?it(t[1]):null,r=t[2],i=r.lastIndexOf("."),o=i>0?r.slice(i+1):void 0;return {provider:n,ticker:r,ext:o}}var Pi=class{constructor(){this.entries=new Map;this.changeListeners=new Set;this.waits=new Set;this.unresolvedCbs=new Set;}register(e,t){let n=it(e),r={name:n,provider:t,index:null,descriptors:[],settled:false,settle:Promise.resolve()};return this.entries.set(n,r),r.settle=this.buildIndex(r),queueMicrotask(()=>this.notify(false)),r.settle}async buildIndex(e){await Promise.resolve();try{if(e.provider.listSymbols){let t=await e.provider.listSymbols();e.descriptors=t,e.index=new Set(t.map(n=>nl(n.ticker)));}}catch{e.index=null;}finally{e.settled=true,this.notify(true);}}notify(e){for(let t of [...this.changeListeners])t(e);}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}unregister(e){this.entries.delete(it(e)),this.notify(false);}has(e){return this.entries.has(it(e))}get(e){return this.entries.get(it(e))?.provider}names(){return [...this.entries.keys()]}parse(e){return We(e)}resolve(e,t={}){let{provider:n,ticker:r}=this.parse(e);if(n)return this.entries.has(n)?{provider:n,ticker:r}:null;let i=nl(r);for(let o of this.candidateOrder(t.default))if(this.entries.get(o).index?.has(i))return {provider:o,ticker:r};if(t.lenient&&this.entries.size===1){let o=this.names()[0],a=this.entries.get(o);if(a.settled&&a.index==null)return {provider:o,ticker:r}}return null}whenResolvable(e,t={}){let n=this.resolve(e,{...t,lenient:true});return n?Promise.resolve(n):new Promise(r=>{let i=this.onChange(a=>{let l=this.resolve(e,{...t,lenient:true});l?(o(),r(l)):a&&this.allSettled()&&this.reportUnresolved(e);}),o=()=>{i(),this.waits.delete(o);};this.waits.add(o);})}allSettled(){for(let e of this.entries.values())if(!e.settled)return false;return true}cancelWaits(){for(let e of [...this.waits])e();}onUnresolved(e){return this.unresolvedCbs.add(e),()=>this.unresolvedCbs.delete(e)}reportUnresolved(e){let t=this.names();console.warn(`[vela] symbol "${e}" not yet resolvable \u2014 registered providers: [${t.join(", ")||"none"}]. Register a provider that serves it.`);for(let n of this.unresolvedCbs)n({symbol:e,providers:t});}candidateOrder(e){let t=this.names();if(e){let n=it(e);if(this.entries.has(n))return [n,...t.filter(r=>r!==n)]}return t}symbolsOf(e){return e!=null?this.entries.get(it(e))?.descriptors??[]:[...this.entries.entries()].flatMap(([t,n])=>n.descriptors.map(r=>({...r,provider:t})))}infoOf(e){let t=it(e),n=this.entries.get(t);if(!n)return {name:t,capabilities:{enumerate:false,stream:false,symbolInfo:false}};let r=n.provider;return r.info?.()??{name:n.name,capabilities:{enumerate:!!r.listSymbols,stream:!!r.subscribe,symbolInfo:!!r.getSymbolInfo}}}indexReady(){return Promise.all([...this.entries.values()].map(e=>e.settle)).then(()=>{})}};function Ei(s){switch(s.kind){case "row":return {label:s.label,toggle:s.toggle,controls:s.controls,when:s.when};case "toggle":{let e=[];s.number&&e.push({kind:"number",...s.number});for(let t of s.colors??[])e.push({kind:"color",...t});return s.width&&e.push({kind:"width",...s.width}),{label:s.label,toggle:{key:s.key,defval:s.defval},controls:e,when:s.when}}case "number":return {label:s.label,controls:[{kind:"number",key:s.key,label:s.label,defval:s.defval,min:s.min,max:s.max,step:s.step}],when:s.when};case "color":return {label:s.label,controls:[{kind:"color",key:s.key,label:s.label,defval:s.defval}],when:s.when};case "select":return {label:s.label,controls:[{kind:"select",key:s.key,label:s.label,options:s.options,defval:s.defval}],when:s.when};case "range":return {label:s.label,controls:[{kind:"number",key:s.minKey,label:`${s.label} \u2014 min`,defval:s.defval,min:s.min,max:s.max,step:s.step,placeholder:s.placeholder},{kind:"hint",text:"\u2013"},{kind:"number",key:s.maxKey,label:`${s.label} \u2014 max`,defval:s.defval,min:s.min,max:s.max,step:s.step,placeholder:s.placeholder}],when:s.when}}}function Rn(s){if(s.kind==="heading"||s.kind==="header")return [];let e=Ei(s),t=[];e.toggle&&t.push({key:e.toggle.key,type:"boolean",defval:e.toggle.defval});for(let n of e.controls)n.kind!=="hint"&&(n.kind==="color"||n.kind==="select"?t.push({key:n.key,type:"string",defval:n.defval}):t.push({key:n.key,type:"number",defval:n.defval}));return t}function Lt(s,e){return s?(Array.isArray(s)?s:[s]).every(n=>n.anyOf?n.anyOf.some(r=>r===e[n.key]):e[n.key]===n.equals):true}var Dn=new Map;function Wo(s){Dn.set(s.id,s);}function Tp(s){Dn.delete(s);}function Ue(s){return typeof s=="string"?Dn.get(s):void 0}function Ge(){return [...Dn.values()]}function Uo(){return [...Dn.values()].filter(s=>s.tickerModifier??s.barTransform!=null).map(s=>s.id)}function ki(s){return Ue(s)?.barTransform??null}function rl(s){let e=s.lastIndexOf(";");if(e<=0||e===s.length-1)return {symbol:s,modifier:null,transform:null};let t=s.slice(e+1).toLowerCase();return t!=="standard"&&!Uo().includes(t)?{symbol:s,modifier:null,transform:null}:{symbol:s.slice(0,e),modifier:t,transform:ki(t)}}var Be={background:"#151619",textColor:"#b2b5be",gridColor:"#20222c",borderColor:"#2a2b30",upColor:q,downColor:X,fontFamily:"sans-serif"},An={background:"#ffffff",textColor:"#1e293b",gridColor:"#cccccc",borderColor:"#d4dae3",upColor:q,downColor:X,fontFamily:"sans-serif"};function Xt(s){return !s||s==="dark"?Be:s==="light"?An:s}var Mp=150,Lp=1e3,Pp=300,Ep=5e3,il=1e4,kp=1.5,ol=5e3,Ii=class s{constructor(e,t,n,r,i,o){this.renderer=t;this.feed=n;this.config=i;this.dataControl=o;this.events=new ct;this.registry=new hr;this.paneOrder=["price"];this.collapsedPanes=new Set;this.maximizedPaneId=null;this.paneActionUnsub=null;this.handles=new Map;this.engines=new Map;this.live=null;this.bars=[];this.rawBars=[];this.barTransform=null;this.typeEngines=new Map;this.typeSettings=new Map;this.activeEngineStyle=null;this.priceStyle="candles";this.unresolvedUnsub=null;this.visibleRange=null;this.viewportUnsub=null;this.viewportTimer=null;this.healing=false;this.healBuffer=[];this.lastHealAt=0;this.onVisible=null;this.barCause="tick";this.historyState="complete";this.generation=0;this.supersedeWaiters=[];this.historyCompleted=false;this.historyCompletePromise=new Promise(e=>{this.resolveHistoryComplete=e;});this.switchingMarket=false;this.loadingUp=false;this.volumeOptedOut=false;this.contextEmitAt=new Map;this.runEmitAt=new Map;for(let l of r)this.registerEngine(l.language,l);this.defaultLanguage=i.defaultLanguage,this.renderer.mount(e,i.theme),this.renderer.onInputChange(l=>this.applyInputs(l.indicatorId,{[l.key]:l.value})),this.renderer.onRemoveIndicator(l=>this.removeIndicator(l)),this.renderer.onToggleIndicatorVisible?.((l,c)=>this.setVisible(l,c)),this.paneActionUnsub=this.renderer.onPaneAction?.(l=>this.handlePaneAction(l))??null,this.renderer.onChartTypeSettingsChange?.((l,c)=>{this.typeSettings.set(l,c),this.typeEngines.get(l)?.onSettings?.(c);}),this.renderer.onMoveIndicator?.((l,c)=>this.moveIndicator(l,c)),this.renderer.onThemeSelect?.(l=>this.setTheme(Xt(l))),this.viewportUnsub=this.renderer.onViewportChange(l=>this.onViewportChange(l)),this.renderer.onPriceStyleChange?.(l=>this.syncPriceStyle(l));let a=this.renderer.readFeature("priceStyle");typeof a=="string"&&(this.priceStyle=a),this.barTransform=ki(a),this.drawings=new Li(this.renderer,this.events,i.drawings),this.unresolvedUnsub=this.feed.onUnresolved?.(l=>{this.endLoad(),this.events.emit("data:unresolved",l);})??null,this.readyPromise=this.init(),Ue(a)?.dataEngine&&this.syncChartTypeEngine(a);}currentVisibleRange(){if(this.visibleRange)return this.visibleRange;let e=this.renderer.getVisibleRange();return e?{left:e.from,right:e.to}:void 0}engineFor(e){let t=e??this.defaultLanguage,n=this.engines.get(t);if(!n)throw new Error(`[vela] no scripting engine registered for language "${t}". Vela ships none \u2014 install one (Pine Script: @luxalgo/vela-pinets) and register it before addIndicator, e.g. chart.registerEngine('pine', new PineEngine()).`);return n}market(){return {symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",symbolInfo:this.feed.symbolInfo?.(this.config.market),chartStyle:this.priceStyle}}async fetchSeries(e,t,n){let r=rl(e),i={symbol:r.symbol,timeframe:t},o=await(this.feed.loadRange?this.feed.loadRange(i,n):this.feed.load({...i,bars:n.limit}));return r.transform?r.transform.full(o):o}onViewportChange(e){this.visibleRange={left:e.from,right:e.to},this.events.emit("viewport:changed",{from:e.from,to:e.to}),this.viewportTimer!=null&&clearTimeout(this.viewportTimer),this.viewportTimer=setTimeout(()=>{if(this.viewportTimer=null,this.switchingMarket)return;let t=this.visibleRange;if(t){for(let n of this.registry.all())!n.renderHandle||n.hidden||(n.session&&n.prepared?.reactsToViewport?(n.pendingCause="viewport",n.session.setVisibleRange(t)):n.native?.descriptor.reactsToViewport&&n.native.instance.onViewport({from:t.left,to:t.right}));this.activeEngineStyle&&this.typeEngines.get(this.activeEngineStyle)?.onViewport?.({from:t.left,to:t.right});}},Mp);}async init(){let e=this.bumpGeneration();this.beginLoad(true),await this.loadMarket(e,{firstLoad:true}),this.generation===e&&(this.startLive(),this.events.emit("ready",void 0));}bumpGeneration(){let e=++this.generation;for(let t of this.supersedeWaiters.splice(0))t();return e}beginLoad(e){if(this.loadingUp)return;this.loadingUp=true,this.renderer.setLoading?.(true);let t=this.config.market;this.events.emit("load:start",{symbol:t.symbol??"TEST",timeframe:t.timeframe??"60",firstLoad:e});}endLoad(){if(!this.loadingUp)return;this.loadingUp=false,this.renderer.setLoading?.(false);let e=this.config.market;this.events.emit("load:end",{symbol:e.symbol??"TEST",timeframe:e.timeframe??"60",bars:this.bars.length});}async loadMarket(e,t){try{await this.loadMarketInner(e,t);}finally{this.generation===e&&this.endLoad();}}async loadMarketInner(e,t){let n=this.config.market,r=n.bars??500,i=n.visibleRange,o=!n.data?.length&&i==null&&r>Ep;if(o&&this.feed.loadRange){let a=await this.feed.load({...n,bars:Math.min(r,il)});if(this.generation!==e)return;this.setBarSeries(a),t.firstLoad&&this.activateBarLayers(),a.length>0&&r>a.length?(this.historyState="backfill",this.backfillHistory(e,r)):this.completeHistory("depth");}else if(o){let a=await this.feed.load({...n,bars:Pp});if(this.generation!==e)return;this.setBarSeries(a),t.firstLoad&&this.activateBarLayers();let l=await this.feed.load(n);if(this.generation!==e)return;this.setBarSeries(l,{preserveView:true}),this.completeHistory("depth");}else {let a=await this.feed.load(n);if(this.generation!==e)return;this.setBarSeries(a),t.firstLoad&&this.activateBarLayers(),this.completeHistory("depth");}i!=null&&(typeof i=="string"?this.setVisibleRangePreset(i):this.renderer.setVisibleRange(i)),this.refreshPriceFormat(),this.ensurePriceFormat();}startLive(){this.config.live&&(this.live=new pr(this.feed,this.config.market,e=>this.onBar(e)),this.live.start(),typeof document<"u"&&(this.onVisible=()=>{if(document.visibilityState!=="visible")return;let e=this.bars[this.bars.length-1];!e||this.healing||!this.canHeal()||Date.now()-this.lastHealAt<=ol||this.healGap(e.time);},document.addEventListener("visibilitychange",this.onVisible)));}stopLive(){this.live?.stop(),this.live=null,this.onVisible&&typeof document<"u"&&document.removeEventListener("visibilitychange",this.onVisible),this.onVisible=null,this.healing=false,this.healBuffer=[],this.lastHealAt=0;}resetHistoryTracking(){this.resolveHistoryComplete(),this.historyCompleted=false,this.historyState="complete",this.historyCompletePromise=new Promise(e=>{this.resolveHistoryComplete=e;});}marketSnapshot(){let e=this.config.market;return {symbol:e.symbol,provider:We(e.symbol??"").provider??void 0,timeframe:e.timeframe,bars:e.bars,offline:e.data!==void 0}}async setMarket(e){let t=this.config.market,n=e.symbol!==void 0&&e.symbol!==t.symbol||e.timeframe!==void 0&&e.timeframe!==t.timeframe||e.data!==void 0,r=e.bars!==void 0&&e.bars!==t.bars,i=r&&!n&&this.rawBars.length>0&&!t.data?.length&&((e.bars??0)<=this.rawBars.length||typeof this.feed.loadRange=="function");if(!n&&!r){typeof e.visibleRange=="string"?this.setVisibleRangePreset(e.visibleRange):e.visibleRange&&this.renderer.setVisibleRange(e.visibleRange);return}let o={symbol:t.symbol??"TEST",timeframe:t.timeframe??"60"},a=this.bumpGeneration();this.switchingMarket=true;try{if(this.stopLive(),this.viewportTimer!=null&&(clearTimeout(this.viewportTimer),this.viewportTimer=null),this.visibleRange=null,this.resetHistoryTracking(),e.symbol!==void 0&&(t.symbol=e.symbol),e.timeframe!==void 0&&(t.timeframe=e.timeframe),e.bars!==void 0&&(t.bars=e.bars),e.data!==void 0?t.data=e.data:e.symbol!==void 0&&delete t.data,t.visibleRange=e.visibleRange,n&&(this.beginLoad(!1),this.setBarSeries([],{clearing:!0}),this.activeEngineStyle&&(this.typeEngines.get(this.activeEngineStyle)?.suspend(),this.renderer.setNativeData?.(this.activeEngineStyle,void 0),this.renderer.setNativeData?.(`${this.activeEngineStyle}-pending`,[]))),i?this.extendDepth(a,t.bars??500):await Promise.race([this.loadMarket(a,{firstLoad:!1}),new Promise(l=>this.supersedeWaiters.push(l))]),this.generation!==a)return}finally{this.generation===a&&(this.switchingMarket=false);}i||(this.restartNativeIndicators(),this.restartChartTypeEngine(),this.reexecuteIndicators()),this.startLive(),n&&this.events.emit("market:changed",{symbol:t.symbol??"TEST",timeframe:t.timeframe??"60",prev:o});}restartNativeIndicators(){for(let e of this.registry.all())if(e.native)if(e.native.instance.stop(),e.native.instance=e.native.descriptor.create(),e.pendingStructural=true,e.hidden)e.native.stale=true;else {let t=this.handles.get(e.id);t&&this.startNativeIndicator(e.id,t);}}restartChartTypeEngine(){for(let e of this.typeEngines.values())e.stop();this.typeEngines.clear(),this.activeEngineStyle&&this.startChartTypeEngine(this.activeEngineStyle);}activateBarLayers(){this.maybeAutoAddVolume();}extendDepth(e,t){if(this.rawBars.length>t){this.setBarSeries(this.rawBars.slice(this.rawBars.length-t),{preserveView:true}),this.completeHistory("depth");return}if(this.rawBars.length===t){this.completeHistory("depth");return}this.historyState="backfill",this.backfillHistory(e,t);}async backfillHistory(e,t){try{for(;this.generation===e&&this.rawBars.length<t&&this.rawBars.length>0;){let n=t-this.rawBars.length,r=il,i=await this.feed.loadRange(this.config.market,{to:this.rawBars[0].time,limit:Math.min(r,n)+1});if(this.generation!==e)return;let o=this.rawBars[0].time,a=i.filter(l=>l.time<o);if(a.length===0){this.completeHistory("genesis");return}for(let l=1;l<a.length;l+=1)if(a[l].time<=a[l-1].time){console.warn("[vela] non-monotonic history chunk \u2014 stopping the backfill"),this.completeHistory("aborted");return}this.setBarSeries([...a,...this.rawBars],{preserveView:!0}),this.notifySessionsBars("backfill"),this.events.emit("history:progress",{loaded:this.rawBars.length,target:t});}this.generation===e&&this.completeHistory("depth");}catch(n){console.warn(`[vela] history backfill failed \u2014 keeping ${this.rawBars.length} bars (${n instanceof Error?n.message:String(n)})`),this.generation===e&&this.completeHistory("aborted");}}completeHistory(e){this.historyCompleted||(this.historyCompleted=true,this.historyState="complete",this.notifySessionsBars("complete"),this.events.emit("history:complete",{reason:e,oldestTime:this.rawBars[0]?.time??0,barsLoaded:this.rawBars.length}),this.resolveHistoryComplete());}historyComplete(){return this.historyCompletePromise}qualifiedSymbol(){let e=this.config.market;return e.symbol?e.symbol:null}refreshPriceFormat(){if(!this.renderer.setPricePrecision)return;let e=this.feed.symbolInfo?.(this.config.market)?.mintick;this.renderer.setPricePrecision(typeof e=="number"&&e>0?e:void 0);}async ensurePriceFormat(){if(!this.renderer.setPricePrecision)return;let e=this.qualifiedSymbol();if(e)try{await this.dataControl.symbolInfo(e),this.refreshPriceFormat();}catch{}}maybeAutoAddVolume(){!this.config.volume||this.volumeOptedOut||!this.renderer.setNativeData||fn("volume")&&this.addNativeIndicator("volume");}syncPriceStyle(e){typeof e=="string"&&(this.priceStyle=e),this.syncBarTransform(e),this.syncChartTypeEngine(e);}syncChartTypeEngine(e){let t=typeof e=="string"?e:null,r=Ue(t)?.dataEngine?t:null;r!==this.activeEngineStyle&&(this.activeEngineStyle&&this.typeEngines.get(this.activeEngineStyle)?.suspend(),this.activeEngineStyle=r,r&&this.startChartTypeEngine(r));}async startChartTypeEngine(e){if(!this.renderer.setNativeData||(await this.readyPromise,this.activeEngineStyle!==e))return;let t=this.typeEngines.get(e);if(t){t.resume();return}let n=Ue(e);if(!n?.dataEngine)return;let r=n.dataEngine();this.typeEngines.set(e,r);let i=this.typeSettings.get(e);i&&r.onSettings?.(i),r.start({symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",live:this.config.live??false,bars:()=>this.bars,data:this.dataControl,pushData:o=>this.renderer.setNativeData?.(e,o),pushPending:o=>this.renderer.setNativeData?.(`${e}-pending`,o)});}syncBarTransform(e){let t=ki(e);t!==this.barTransform&&(this.barTransform=t,this.rawBars.length!==0&&(this.bars=t?t.full(this.rawBars):this.rawBars,this.renderer.setBars(this.bars,{preserveView:true}),this.reexecuteIndicators()));}reexecuteIndicators(){for(let e of this.registry.all()){if(e.hidden||!e.session)continue;e.session.stop(),e.session=void 0,e.pendingStructural=true,e.pendingCause="market",this.setLoading(e,true);let t=this.handles.get(e.id);t&&this.executeIndicator(e.id,t);}}onBar(e){if(this.healing){this.healBuffer.push(e);return}let t=this.rawBars[this.rawBars.length-1];if(t&&this.canHeal()&&e.time>t.time+this.barIntervalMs()*kp&&Date.now()-this.lastHealAt>ol){this.healBuffer.push(e),this.healGap(t.time);return}this.applyBar(e);}setBarSeries(e,t){this.rawBars=e,this.bars=this.barTransform?this.barTransform.full(e):e,this.renderer.setBars(this.bars,{preserveView:t?.preserveView}),!t?.clearing&&this.bars.length>0&&this.endLoad();}applyBar(e,t=true){let n=this.rawBars[this.rawBars.length-1],r=e;if(n&&e.time===n.time)this.rawBars[this.rawBars.length-1]=e,this.barCause="tick",this.barTransform&&(r=this.barTransform.next(e,this.bars[this.bars.length-2]),this.bars[this.bars.length-1]=r);else if(!n||e.time>n.time)this.rawBars.push(e),this.barCause="bar",this.barTransform&&(r=this.barTransform.next(e,this.bars[this.bars.length-1]),this.bars.push(r));else return;this.renderer.updateBar(r),this.events.emit("bar",e),t&&this.notifySessionsBars(this.historyState==="backfill"?"backfill":void 0);}notifySessionsBars(e){if(this.switchingMarket)return;let t=e?"history":this.barCause;for(let n of this.registry.all())!n.renderHandle||n.hidden||(n.session?(n.pendingCause=t,n.session.notifyBars(e)):n.native&&n.native.instance.onBars());}canHeal(){return !!this.feed.loadRange&&!this.config.market.data?.length}barIntervalMs(){return In(this.config.market.timeframe??"60")}async healGap(e){let t=this.generation;this.healing=true,this.lastHealAt=Date.now();try{let n=await this.feed.loadRange(this.config.market,{from:e});if(this.generation!==t)return;for(let r of n)this.applyBar(r,!1);}catch{}finally{if(this.generation===t){this.healing=false;let n=this.healBuffer;this.healBuffer=[];for(let r of n)this.applyBar(r,false);this.notifySessionsBars(this.historyState==="backfill"?"backfill":void 0);}}}registerEngine(e,t){let n=this.engines.get(e);n&&n!==t&&console.warn(`[vela] re-registering scripting engine for language "${e}"; replacing ${n.constructor.name} with ${t.constructor.name}.`),this.engines.set(e,t);}addIndicator(e,t={}){let n=this.registry.nextId(),r=t.title??"Indicator",i=new Nt(n,r,this,e);return this.handles.set(n,i),this.registry.add({id:n,title:r,source:e,options:t,inputValues:{...t.inputs??{}}}),this.startIndicator(n,e,t,i),i}addNativeIndicator(e,t={}){let n=this.registry.all().find(c=>c.native?.type===e);if(n)return this.handles.get(n.id)??new Nt(n.id,n.title,this);let r=fn(e),i=this.registry.nextId("native"),o=r?.title??e,a=new Nt(i,o,this);if(this.handles.set(i,a),!r)return console.warn(`[vela] addNativeIndicator("${e}") \u2014 no native indicator registered for this type.`),a;let l={...r.defaultInputs(),...t.inputs??{}};return this.registry.add({id:i,title:o,source:e,inputValues:l,native:{type:e,instance:r.create(),descriptor:r}}),a.setSchema(r.inputsSchema()),this.startNativeIndicator(i,a),a}presentNativeIndicators(){return this.registry.all().map(e=>e.native?.type).filter(e=>!!e)}async availableNativeIndicators(){let e=this.qualifiedSymbol(),t=new Set(this.presentNativeIndicators());return Promise.all(ur().map(async n=>({type:n.type,title:n.title,supported:await this.isNativeSupported(n,e),present:t.has(n.type),beta:n.beta})))}async isNativeSupported(e,t){if(!e.isSupported)return true;if(!t)return false;try{return await e.isSupported(t,this.dataControl)}catch{return false}}applyInputs(e,t){let n=this.registry.get(e);!n||!n.session&&!n.native||(n.inputValues={...n.inputValues,...t},n.renderHandle&&this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues),n.pendingStructural=true,!n.hidden&&!n.native&&this.setLoading(n,true),n.pendingCause="inputs",n.session?n.session.update(n.inputValues):n.native&&!n.hidden&&n.native.instance.setInputs(n.inputValues));}listIndicators(){return [...this.handles.values()]}getIndicatorContext(e,t){return this.registry.get(e)?.session?.getContext?.(t)??Promise.resolve(null)}removeIndicator(e){let t=this.registry.remove(e);t?.native?.type==="volume"&&(this.volumeOptedOut=true),t?.session?.stop(),t?.native?.instance.stop(),this.handles.delete(e),t?.renderHandle&&this.renderer.removeIndicator(t.renderHandle);let n=t?.model?.paneId;n&&n!=="price"&&!this.paneStillUsed(n)&&(this.renderer.removePane(n),this.forgetPane(n),this.events.emit("pane:changed",void 0)),this.events.emit("indicator:removed",{id:e});}setVisible(e,t){let n=this.registry.get(e);if(!(!n||n.hidden===!t)){if(n.hidden=!t,this.handles.get(e)?.setVisibleState(t),!t)n.session?.stop(),n.session=void 0,n.native?.instance.suspend(),n.renderHandle&&this.renderer.setIndicatorVisible?.(n.renderHandle,false);else if(n.renderHandle&&this.renderer.setIndicatorVisible?.(n.renderHandle,true),n.pendingStructural=true,n.native)if(n.native.stale){n.native.stale=false;let r=this.handles.get(e);r&&this.startNativeIndicator(e,r);}else n.native.instance.resume();else {this.setLoading(n,true);let r=this.handles.get(e);r&&this.executeIndicator(e,r);}this.events.emit("indicator:visibility",{id:e,visible:t});}}ready(){return this.readyPromise}inspect(){let e=[...this.registry.all()].filter(t=>!t.loading).sort((t,n)=>(n.native?1:0)-(t.native?1:0));return ma(e.map(t=>t.model).filter(t=>t!=null))}resize(){this.renderer.resize();}setTheme(e){let t=this.config.theme;Object.keys(e).every(n=>e[n]===t[n])||(this.config.theme=e,this.renderer.setTheme(e),this.events.emit("theme:changed",e));}getVisibleRange(){return this.renderer.getVisibleRange()}setVisibleRange(e){this.renderer.setVisibleRange(e);}panBy(e){if(this.renderer.panBy){this.renderer.panBy(e);return}let t=this.renderer.getVisibleRange();if(!t)return;let n=(t.to-t.from)*e;this.renderer.setVisibleRange({from:t.from+n,to:t.to+n});}setVisibleRangePreset(e){let t=fa(e,this.bars);t&&this.renderer.setVisibleRange(t);}destroy(){this.bumpGeneration(),this.resolveHistoryComplete(),this.stopLive(),this.viewportTimer!=null&&clearTimeout(this.viewportTimer),this.viewportUnsub?.(),this.paneActionUnsub?.();for(let e of this.registry.all())e.session?.stop(),e.native?.instance.stop();for(let e of this.typeEngines.values())e.stop();this.typeEngines.clear(),this.activeEngineStyle=null,this.unresolvedUnsub?.(),this.unresolvedUnsub=null,this.feed.destroy?.(),this.drawings.destroy(),this.renderer.destroy(),this.events.clear();}async startIndicator(e,t,n,r){try{if(await this.readyPromise,!this.registry.get(e))return;await Ip();let i=this.registry.get(e);if(!i)return;let o=this.engineFor(n.language);i.engine=o;let a=await o.prepare(t,e);i.prepared=a;let l={};for(let c of a.inputs)l[c.key]=c.defval;i.inputValues={...l,...i.inputValues},r.setSchema(a.inputs),this.mountLoadingPlaceholder(e,i),this.executeIndicator(e,r);}catch(i){this.fail(e,r,i);}}executeIndicator(e,t){let n=this.registry.get(e);if(!n||!n.engine||!n.prepared||n.hidden)return;let r=this.config.live&&!n.prepared.reactsToViewport&&n.engine.capabilities.streaming?"live":"static";n.session=n.engine.execute({prepared:n.prepared,market:this.market(),bars:this.bars,getBars:()=>this.bars,fetchSeries:(i,o,a)=>this.fetchSeries(i,o,a),inputs:n.inputValues,visibleRange:this.currentVisibleRange(),mode:r,historyState:this.historyState},{onModel:i=>{let o=!n.announced,a=n.pendingCause??"history";n.pendingCause=void 0,this.applyModel(e,i),this.emitContextChanged(e),this.emitScriptRun(e,a,o);},onAlert:i=>{this.events.emit("alert",i),t.emit("alert",{id:i.id,message:i.message,title:i.title,time:i.time});},onWarning:i=>this.events.emit("warning",i),onError:i=>this.fail(e,t,i)}),this.emitContextChanged(e);}async startNativeIndicator(e,t){try{await this.readyPromise;let n=this.registry.get(e);if(!n?.native||n.hidden)return;let r={symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",live:this.config.live,bars:()=>this.bars,data:this.dataControl,emit:i=>this.applyModel(e,this.buildNativeModel(n,i)),pushData:i=>this.renderer.setNativeData?.(n.native.type,i),setStatus:i=>{n.renderHandle&&!n.hidden&&this.renderer.setIndicatorStatus?.(n.renderHandle,i);}};n.native.instance.start(r,n.inputValues);}catch(n){this.fail(e,t,n);}}buildNativeModel(e,t){let n=e.native.descriptor;return {id:e.id,title:e.title,...n.shortTitle?{shorttitle:n.shortTitle}:{},overlay:n.overlay,paneHint:n.paneHint,native:{type:e.native.type},series:t.series??[],fills:t.fills??[],backgrounds:t.backgrounds??[],priceLines:t.priceLines??[],...t.lines?{lines:t.lines}:{},...t.boxes?{boxes:t.boxes}:{},...t.labels?{labels:t.labels}:{},...t.polylines?{polylines:t.polylines}:{},...t.linefills?{linefills:t.linefills}:{},...t.tables?{tables:t.tables}:{},inputs:n.inputsSchema(),inputValues:e.inputValues}}mountLoadingPlaceholder(e,t){if(t.renderHandle||t.hidden||!t.prepared)return;let n=t.prepared.meta,r={id:e,title:t.options?.title??n.title,overlay:n.overlay,paneHint:n.overlay?"price":"new",series:[],fills:[],backgrounds:[],priceLines:[],inputs:t.prepared.inputs,inputValues:t.inputValues},i=this.routePane(e,r,t.options??{});this.placeModel(r,e,i),t.model=r,this.ensurePaneFor(i),t.renderHandle=this.renderer.mountIndicator(r),t.pendingStructural=true,this.setLoading(t,true);}setLoading(e,t){e.loading=t,e.renderHandle&&!e.hidden&&this.renderer.setIndicatorStatus?.(e.renderHandle,t?"loading":"idle");}ensurePaneFor(e){this.paneOrder.includes(e)||this.paneOrder.push(e),this.renderer.ensurePane({id:e,kind:e==="price"?"price":"study",order:this.paneOrder.indexOf(e)});}paneStillUsed(e){for(let t of this.registry.all())if(t.model?.paneId===e)return true;return false}forgetPane(e){let t=this.paneOrder.indexOf(e);t>0&&this.paneOrder.splice(t,1),this.collapsedPanes.delete(e),this.maximizedPaneId===e&&(this.maximizedPaneId=null);}paneManagementSupported(){return this.renderer.capabilities.paneManagement===true&&typeof this.renderer.setIndicatorPane=="function"}listPanes(){let e=new Map;for(let n of this.registry.all()){let r=n.model;if(!r)continue;let i=r.paneId??"price";e.has(i)||e.set(i,[]),e.get(i).push({id:n.id,title:r.title||n.title,ownScale:r.ownScale===true});}let t=[];for(let n of this.paneOrder)n!=="price"&&!e.has(n)||t.push({id:n,kind:n==="price"?"price":"study",order:t.length,collapsed:this.collapsedPanes.has(n),maximized:this.maximizedPaneId===n,indicators:e.get(n)??[]});return t}movePane(e,t){if(e==="price")return;let n=this.existingPaneIds(),r=n.indexOf(e);if(r<0)return;let i=t==="up"?r-1:r+1;i<=0||i>=n.length||([n[r],n[i]]=[n[i],n[r]],this.reorderPanes(n),this.events.emit("pane:moved",{paneId:e,dir:t}));}removePaneAndIndicators(e){if(e!=="price")for(let t of [...this.registry.all()])t.model?.paneId===e&&this.removeIndicator(t.id);}collapsePane(e,t){t?this.collapsedPanes.add(e):this.collapsedPanes.delete(e),this.renderer.setPaneCollapsed?.(e,t),this.events.emit("pane:changed",void 0);}maximizePane(e){this.maximizedPaneId=e,this.renderer.setPaneMaximized?.(e),this.events.emit("pane:changed",void 0);}moveIndicator(e,t){if(!this.paneManagementSupported()||!this.renderer.setIndicatorPane){console.warn("[vela] the active renderer does not support moving indicators between panes.");return}let n=this.registry.get(e);if(!n?.renderHandle||!n.model)return;let r=n.model,i=r.paneId??"price",o=this.resolveMoveTarget(e,r,t);if(!o)return;let{paneId:a,ownScale:l,insert:c}=o;a===i&&r.ownScale===true===l||(c?this.insertPaneOrder(a,c):this.paneOrder.includes(a)||this.paneOrder.push(a),r.ownScale=l,n.paneLocked=true,this.placeModel(r,e,a),this.ensurePaneFor(a),this.renderer.setIndicatorPane(n.renderHandle,a,{ownScale:l}),i!=="price"&&i!==a&&!this.paneStillUsed(i)&&(this.renderer.removePane(i),this.forgetPane(i)),this.reorderPanes(this.existingPaneIds()),this.events.emit("indicator:moved",{id:e,paneId:a}),this.events.emit("pane:changed",void 0));}resolveMoveTarget(e,t,n){if(n==="price"||typeof n=="object"&&"pane"in n&&n.pane==="price")return {paneId:"price",ownScale:!t.overlay};if("pane"in n)return this.existingPaneIds().includes(n.pane)?{paneId:n.pane,ownScale:true}:null;let r=n.newPane===true?{}:n.newPane;return {paneId:this.freshPaneId(e,t.paneId??"price"),ownScale:false,insert:r}}freshPaneId(e,t){let n=new Set(this.existingPaneIds()),r=`pane-${e}`;for(let i=2;r===t||n.has(r);i+=1)r=`pane-${e}-${i}`;return r}insertPaneOrder(e,t){let n=this.paneOrder.indexOf(e);n>0&&this.paneOrder.splice(n,1);let r=this.paneOrder.length;t.before&&this.paneOrder.includes(t.before)?r=this.paneOrder.indexOf(t.before):t.after&&this.paneOrder.includes(t.after)&&(r=this.paneOrder.indexOf(t.after)+1),r<1&&(r=1),this.paneOrder.splice(r,0,e);}existingPaneIds(){return this.paneOrder.filter(e=>e==="price"||this.paneStillUsed(e))}reorderPanes(e){this.paneOrder.length=0,this.paneOrder.push(...e),this.renderer.orderPanes?.(e),this.events.emit("pane:changed",void 0);}handlePaneAction(e){switch(e.type){case "remove":this.removePaneAndIndicators(e.paneId);break;case "move":{let t=this.existingPaneIds(),n=t.indexOf(e.paneId),r=e.dir==="up"?n-1:n+1;n>0&&r>0&&r<t.length&&([t[n],t[r]]=[t[r],t[n]],this.paneOrder.length=0,this.paneOrder.push(...t),this.events.emit("pane:changed",void 0),this.events.emit("pane:moved",{paneId:e.paneId,dir:e.dir}));break}case "collapse":e.collapsed?this.collapsedPanes.add(e.paneId):this.collapsedPanes.delete(e.paneId),this.events.emit("pane:changed",void 0);break;case "maximize":this.maximizedPaneId=e.maximized?e.paneId:null,this.events.emit("pane:changed",void 0);break}}announce(e,t){e.announced||(e.announced=true,this.events.emit("indicator:added",{id:e.id}),this.emitContextChanged(e.id),t?.emit("ready",void 0));}applyModel(e,t){let n=this.registry.get(e);if(!n||n.hidden)return;let r=this.handles.get(e);if(!n.renderHandle){let a=this.routePane(e,t,n.options??{});this.placeModel(t,e,a),n.model=t,this.ensurePaneFor(a),n.renderHandle=this.renderer.mountIndicator(t),n.pendingStructural=false,this.announce(n,r);return}let i=n.model?.paneId??"price",o=n.model?.ownScale===true;if(n.loading&&!n.paneLocked){let a=this.routePane(e,t,n.options??{});a!==i&&(i!=="price"&&(this.renderer.removePane(i),this.forgetPane(i)),this.ensurePaneFor(a),n.pendingStructural=true,i=a);}this.placeModel(t,e,i),n.paneLocked&&(t.ownScale=o),n.model=t,n.pendingStructural?(n.renderHandle=this.renderer.mountIndicator(t),this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues),n.pendingStructural=false):this.renderer.updateIndicator(n.renderHandle,Rp(t)),n.loading&&this.setLoading(n,false),this.announce(n,r);}routePane(e,t,n){return n.pane==="new"?`pane-${e}`:n.pane==="price"||(n.overlay??t.overlay)?"price":`pane-${e}`}static plotsAtLastBar(e){let t={};for(let n of e.series)le(n)&&(t[n.title]=n.points[n.points.length-1]?.value??null);return t}placeModel(e,t,n){e.id=t,e.paneId=n;for(let r of e.series)r.paneId=n;for(let r of e.fills)r.paneId=n;for(let r of e.backgrounds)r.paneId=n;for(let r of e.priceLines)r.paneId=n;if(e.lines)for(let r of e.lines)r.paneId=n;if(e.boxes)for(let r of e.boxes)r.paneId=n;if(e.labels)for(let r of e.labels)r.paneId=n;if(e.polylines)for(let r of e.polylines)r.paneId=n;if(e.linefills)for(let r of e.linefills)r.paneId=n;if(e.tables)for(let r of e.tables)r.paneId=n;}emitContextChanged(e){if(!this.registry.get(e)?.session?.getContext)return;let t=Date.now();t-(this.contextEmitAt.get(e)??0)<1e3||(this.contextEmitAt.set(e,t),this.events.emit("context:changed",{id:e}));}emitScriptRun(e,t,n){let r=this.registry.get(e);if(!r||r.native||!this.events.hasListeners("script:run"))return;let i=Date.now();t==="tick"&&i-(this.runEmitAt.get(e)??0)<Lp||(this.runEmitAt.set(e,i),Promise.resolve().then(()=>this.buildScriptRun(r,t,n)).then(o=>{o&&this.registry.get(e)&&this.events.emit("script:run",o);}));}async buildScriptRun(e,t,n){let r=e.model;if(!r)return null;let i=await this.pullContext(e,["variables","strategy","warnings"]),o=this.bars[this.bars.length-1];return {id:e.id,title:r.title,kind:i?.strategy||(r.trades?.length??0)>0?"strategy":"indicator",cause:t,first:n,bar:Math.max(0,this.bars.length-1),time:o?.time??0,forming:this.config.live&&this.bars.length>0,complete:this.historyState!=="backfill",plots:s.plotsAtLastBar(r),vars:i?.variables??{},...i?.strategy?{strategy:i.strategy}:{},warnings:i?.warnings??[],trades:async()=>(await this.pullContext(e,["trades"]))?.trades??[],series:async a=>((await this.pullContext(e,["plots"]))?.plots?.[a]??[]).map(c=>({time:c.time,value:typeof c.value=="number"?c.value:null}))}}async pullContext(e,t){try{return await e.session?.getContext?.(t)??null}catch{return null}}fail(e,t,n){let r=this.registry.get(e);r?.loading&&this.setLoading(r,false);let i=n instanceof Error?n:new Error(String(n));console.error(`[vela] indicator "${e}" failed:`,i.message),this.events.emit("indicator:error",{id:e,error:i}),t?.emit("error",{error:i});}};function Ip(){return typeof requestAnimationFrame=="function"?new Promise(s=>requestAnimationFrame(()=>requestAnimationFrame(()=>s()))):new Promise(s=>setTimeout(s,0))}function Rp(s){let e=[],t=Number.POSITIVE_INFINITY,n=0;for(let r of s.series)if(r.kind==="candle"||r.kind==="bar"){e.push({seriesId:r.id,kind:"bars",bars:r.bars});for(let i of r.bars)i.time<t&&(t=i.time),i.time>n&&(n=i.time);}else if(le(r)){e.push({seriesId:r.id,kind:"points",points:r.points});for(let i of r.points)i.time<t&&(t=i.time),i.time>n&&(n=i.time);}return {kind:"value",indicatorId:s.id,dirty:{from:Number.isFinite(t)?t:0,to:n},anchorTime:s.anchorTime??null,series:e,lines:s.lines??[],boxes:s.boxes??[],labels:s.labels??[],polylines:s.polylines??[],linefills:s.linefills??[],tables:s.tables??[],trades:s.trades??[]}}var On=class{constructor(e){this.renderer=e;}get name(){return this.renderer.name}get capabilities(){return this.renderer.capabilities}supports(e){return this.renderer.features.includes(e)}get(e){return this.renderer.readFeature(e)}set(e,t){let n=typeof e=="string"?[[e,t]]:Object.entries(e);for(let[r,i]of n)this.renderer.features.includes(r)?this.renderer.applyFeature(r,i):console.warn(`[vela] renderer "${this.renderer.name}" has no feature "${r}" \u2014 set ignored.`);return this}setLegendActions(e){this.renderer.setLegendActions?.(e);}setLegendOverviewAction(e){return this.renderer.setLegendOverviewAction?.(e),this}get supportsIndicatorSettings(){return typeof this.renderer.openIndicatorSettings=="function"}openIndicatorSettings(e){return this.renderer.openIndicatorSettings?.(e),this}screenshot(){return typeof this.renderer.screenshot=="function"?this.renderer.screenshot():(console.warn(`[vela] renderer "${this.renderer.name}" does not support screenshot().`),null)}getConfig(){return typeof this.renderer.getConfig=="function"?this.renderer.getConfig():(console.warn(`[vela] renderer "${this.renderer.name}" does not support getConfig().`),null)}applyConfig(e){return typeof this.renderer.applyConfig=="function"?this.renderer.applyConfig(e):console.warn(`[vela] renderer "${this.renderer.name}" does not support applyConfig().`),this}onConfigChanged(e){return this.renderer.onConfigChanged?.(e)??(()=>{})}onCrosshairMove(e){return this.renderer.onCrosshairMove(e)}onAxisLongPress(e){return this.renderer.onAxisLongPress?.(e)??(()=>{})}dataWindowReadout(){return this.renderer.getDataWindowReadout?.()??null}setSymbolPicker(e){return typeof this.renderer.setSymbolPicker=="function"?this.renderer.setSymbolPicker(e):console.warn(`[vela] renderer "${this.renderer.name}" does not support setSymbolPicker().`),this}focus(){return this.renderer.focus?.(),this}get supportsExternalCrosshair(){return typeof this.renderer.setExternalCrosshair=="function"}setExternalCrosshair(e,t=null){return this.renderer.setExternalCrosshair?.(e,t),this}closeDialogs(){return this.renderer.closeDialogs?.(),this}openSettings(e){return this.renderer.openSettingsDialog?.(e),this}setSettingsSections(e){return this.renderer.setSettingsSections?.(e),this}setLayoutMode(e){return this.renderer.setLayoutMode?.(e),this}};var Kt=new Map;function Dp(s){let e=Object.entries(s);for(let[t,n]of e)Kt.set(t,n);return ()=>{for(let[t,n]of e)Kt.get(t)===n&&Kt.delete(t);}}function Ap(...s){if(s.length===0)Kt.clear();else for(let e of s)Kt.delete(e);}function Go(){return Object.fromEntries(Kt)}var Ri=class{constructor(e){this.controller=e;}get supported(){return this.controller.paneManagementSupported()}list(){return this.controller.listPanes()}move(e,t){return this.guard()&&this.controller.movePane(e,t),this}remove(e){return this.guard()&&this.controller.removePaneAndIndicators(e),this}collapse(e,t=true){return this.guard()&&this.controller.collapsePane(e,t),this}maximize(e){return this.guard()&&this.controller.maximizePane(e),this}moveIndicator(e,t){return this.guard()&&this.controller.moveIndicator(e,t),this}guard(){return this.controller.paneManagementSupported()?true:(console.warn("[vela] the active renderer does not support pane management \u2014 chart.panes mutation ignored."),false)}};function sl(s,e,t){return `${s}|${e}|${t}`}function Op(s){return s.split("|")[1]??""}var Di=class{constructor(){this.series=new Map;this.coveredFrom=new Map;this.retained=new Set;}get(e){return this.series.get(e)}markCovered(e,t){this.coveredFrom.set(e,Math.min(this.coveredFrom.get(e)??1/0,t));}coveredFromOf(e){return this.coveredFrom.get(e)}merge(e,t){if(t.length===0)return this.series.get(e)??[];let n=new Map;for(let i of this.series.get(e)??[])n.set(i.time,i);for(let i of t)n.set(i.time,i);let r=[...n.values()].sort((i,o)=>i.time-o.time);return this.series.set(e,r),r}retainSymbol(e){this.currentSymbol!==e&&(this.currentSymbol=e,this.purgeOutside(e));}retain(e){this.retained=new Set(e),this.purgeOutside(this.currentSymbol);}purgeOutside(e){for(let t of [...this.series.keys()]){let n=Op(t);n!==e&&!this.retained.has(n)&&(this.series.delete(t),this.coveredFrom.delete(t));}}clear(){this.series.clear(),this.coveredFrom.clear();}},Fn=new Di;function al(s,e){let{provider:t,ticker:n}=We(s);return sl(t??"",n,e)}var Bn=1e4,Fp=Bn+1,Vn=class{constructor(e,t=Fn){this.inner=e;this.store=t;}async load(e){if(e.data&&e.data.length>0)return this.inner.load(e);let t=e.symbol??"TEST",n=al(t,e.timeframe??"60");this.store.retainSymbol(t);let r=this.store.get(n),i=e.bars??500,o=r?.[r.length-1];if(r&&o&&r.length>=i-1&&this.inner.loadRange){let{bars:l}=await this.fetchRange(e,{from:o.time}),c=this.store.merge(n,Ai(l));return ll(c,l[l.length-1]).slice(-i)}let a=await this.inner.load(e);return this.store.merge(n,Ai(a)),a}async loadRange(e,t){if(!this.inner.loadRange)return this.inner.load(e);let n=al(e.symbol??"TEST",e.timeframe??"60"),r=this.store.get(n),i=r?.[r.length-1];if(t.to!=null&&i&&t.to<i.time){let d=r.filter(f=>f.time<=t.to),h=this.store.coveredFromOf(n)??1/0;if(t.limit!=null?d.length>=t.limit&&(t.from==null||h<=t.from):t.from!=null&&h<=t.from){let f=t.from!=null?d.filter(b=>b.time>=t.from):d;return t.limit!=null&&f.length>t.limit&&(f=f.slice(-t.limit)),f}let p=await this.fetchRange(e,t),m=p.bars.filter(f=>f.time<=t.to);return m.length>0&&(this.store.merge(n,m),this.store.markCovered(n,p.coveredDownTo??m[0].time)),m}if(i&&t.from!=null){let d=this.store.coveredFromOf(n);if(d!=null&&d>t.from){let{bars:h,coveredDownTo:u}=await this.fetchRange(e,{from:t.from,to:d});this.store.merge(n,h.filter(p=>p.time<=d)),this.store.markCovered(n,u??t.from),r=this.store.get(n),i=r?.[r.length-1];}}let o=this.store.coveredFromOf(n);if(!!r&&r.length>0&&!!i&&(t.from!=null?o!=null&&o<=t.from:t.limit==null||r.length>=t.limit)&&i){let{bars:d}=await this.fetchRange(e,{from:i.time,to:t.to,limit:t.limit}),h=this.store.merge(n,Ai(d)),u=ll(h,d[d.length-1]),p=t.from!=null?u.filter(m=>m.time>=t.from):u;return t.to!=null&&(p=p.filter(m=>m.time<=t.to)),p}let{bars:l,coveredDownTo:c}=await this.fetchRange(e,t);return this.store.merge(n,Ai(l)),this.store.markCovered(n,c??t.from??l[0]?.time??0),l}async fetchRange(e,t){let n=In(e.timeframe??"60"),r=Bp(t,n);if(r<=Fp){let c=await this.inner.loadRange(e,{...t,limit:t.limit??r});return {bars:c,coveredDownTo:t.from??c[0]?.time}}let i=new Map,o=t.to??Date.now();for(;!(t.from!=null&&o<t.from);){let c=t.limit!=null?t.limit-i.size:Bn;if(c<=0)break;let d=await this.inner.loadRange(e,{to:o,limit:Math.min(Bn,c)}),h=1/0;for(let u of d)u.time<h&&(h=u.time),u.time<=o&&(t.from==null||u.time>=t.from)&&i.set(u.time,u);if(d.length===0){if(t.from==null)break;o-=Bn*n;continue}if(h-1>=o)break;o=h-1;}let a=[...i.values()].sort((c,d)=>c.time-d.time),l=t.from!=null&&o<t.from;return {bars:a,coveredDownTo:l?t.from:a[0]?.time}}subscribe(e,t){return this.inner.subscribe(e,t)}symbolInfo(e){return this.inner.symbolInfo?.(e)}};function Bp(s,e){if(s.limit!=null)return s.limit;if(s.from==null)return Bn;let t=Math.max(0,(s.to??Date.now())-s.from);return Math.ceil(t/e*1.1)+2}function Ai(s){return s.length>0?s.slice(0,-1):s}function ll(s,e){if(!e)return s;let t=s[s.length-1];return !t||e.time>t.time?[...s,e]:s}function Vp(s){return {"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,1:6e4,5:3e5,15:9e5,30:18e5,60:36e5,240:144e5,D:864e5,W:6048e5}[s]??36e5}var Pt=class{constructor(e=Fn){this.registry=new Pi;this.primaryProvider=null;this.liveBars=[];this.symInfoCache=new Map;this.cache=new Vn(new Ko(this.registry),e);}registerProvider(e,t){return this.registry.register(e,t)}unregisterProvider(e){this.registry.unregister(e);}providers(){return this.registry.names().map(e=>this.registry.infoOf(e))}resolveSymbol(e){return this.registry.resolve(e,{default:this.primaryProvider})}providerInstance(e){return this.registry.get(e)}symbols(e){return this.registry.symbolsOf(e)}onUnresolved(e){return this.registry.onUnresolved(e)}destroy(){this.registry.cancelWaits();}ready(){return this.registry.indexReady()}async symbolInfoFor(e){let t=this.registry.resolve(e,{default:this.primaryProvider});if(!t)return;let n=await this.registry.get(t.provider)?.getSymbolInfo?.(t.ticker);return n&&this.symInfoCache.set(Xo(t),n),n}capabilitiesFor(e){let t=this.registry.resolve(e,{default:this.primaryProvider});if(!t)return null;let n=this.registry.get(t.provider);return n?n.capabilitiesFor?.(t.ticker)??this.registry.infoOf(t.provider).capabilities:null}async load(e){if(e.data&&e.data.length>0)return this.liveBars=e.data.map(n=>({...n})),e.data;let t=await this.registry.whenResolvable(Oi(e),{default:this.primaryProvider});return this.primaryProvider=t.provider,this.prefetchSymbolInfo(t),this.cache.load(Yo(e,t))}symbolInfo(e){if(e.data&&e.data.length>0)return;let t=this.registry.resolve(Oi(e),{default:this.primaryProvider});return t?this.symInfoCache.get(Xo(t)):void 0}prefetchSymbolInfo(e){let t=Xo(e);if(this.symInfoCache.has(t))return;let n=this.registry.get(e.provider);n?.getSymbolInfo&&n.getSymbolInfo(e.ticker).then(r=>{r&&this.symInfoCache.set(t,r);}).catch(()=>{});}async loadRange(e,t){if(e.data&&e.data.length>0)return this.cache.loadRange(e,t);let n=this.registry.resolve(Oi(e),{default:this.primaryProvider});return n?this.cache.loadRange(Yo(e,n),t):[]}subscribe(e,t){if(e.data&&e.data.length>0)return this.synthesizeTicks(e,t);let n=this.registry.resolve(Oi(e),{default:this.primaryProvider});return n?this.cache.subscribe(Yo(e,n),t):()=>{}}synthesizeTicks(e,t){if(this.liveBars.length===0)return ()=>{};let n=Vp(e.timeframe??"60"),r=setInterval(()=>{let i=this.liveBars,o=i[i.length-1];if(!o)return;let a=o.close*.0015*(Math.random()-.5)*2,l=Math.max(0,o.close+a),c={...o,close:l,high:Math.max(o.high,l),low:Math.min(o.low,l)};if(i[i.length-1]=c,t(c),Math.random()<.12){let d={time:c.time+n,open:c.close,high:c.close,low:c.close,close:c.close,volume:0};i.push(d),t(d);}},1e3);return ()=>clearInterval(r)}};function Oi(s){return s.symbol??""}function Yo(s,e){return {...s,symbol:`${e.provider}:${e.ticker}`}}function Xo(s){return `${s.provider}|${s.ticker}`}async function cl(s,e,t,n){try{return await s.getBars(e,t,n)}catch(r){return console.warn(`[vela] data fetch failed for ${e} ${t} \u2014 ${r instanceof Error?r.message:String(r)}`),[]}}var Ko=class{constructor(e){this.registry=e;}load(e){let{provider:t,ticker:n}=We(e.symbol??""),r=this.registry.get(t??"");return r?cl(r,n,e.timeframe??"60",{limit:e.bars??500}):Promise.resolve([])}loadRange(e,t){let{provider:n,ticker:r}=We(e.symbol??""),i=this.registry.get(n??"");return i?cl(i,r,e.timeframe??"60",t):Promise.resolve([])}subscribe(e,t){let{provider:n,ticker:r}=We(e.symbol??""),i=this.registry.get(n??"");if(!i)return ()=>{};let o=e.timeframe??"60";if(i.subscribe)return i.subscribe(r,o,t);let a=false,l=null,c=async()=>{if(!a){try{let d=await i.getBars(r,o,{limit:2});if(a)return;for(let h of d)t(h);}catch{}a||(l=setTimeout(()=>{c();},3e3));}};return l=setTimeout(()=>{c();},3e3),()=>{a=true,l&&clearTimeout(l);}}};var _n=class{constructor(e){this.registry=e instanceof Pt?e:null;}registerProvider(e,t){return this.registry?(this.registry.registerProvider(e,t),this):(console.warn(`[vela] chart.data.registerProvider("${e}") ignored \u2014 the active data feed is a custom feed (deps.dataFeed), not the default provider registry.`),this)}unregisterProvider(e){return this.registry?.unregisterProvider(e),this}providers(){return this.registry?.providers()??[]}resolve(e){return this.registry?.resolveSymbol(e)??null}providerInstance(e){return this.registry?.providerInstance(e)}symbols(e){return this.registry?.symbols(e)??[]}symbolInfo(e){return this.registry?.symbolInfoFor(e)??Promise.resolve(void 0)}capabilities(e){return this.registry?.capabilitiesFor(e)??null}ready(){return this.registry?.ready()??Promise.resolve()}};var Nn=class{constructor(e){this.ctrl=e;}get supported(){return this.ctrl.supported}setTool(e){return this.ok("setTool")&&this.ctrl.setTool(e),this}getTool(){return this.ctrl.getTool()}setSnapMode(e){return this.ok("setSnapMode")&&this.ctrl.setSnapMode(e),this}getSnapMode(){return this.ctrl.getSnapMode()}setStayMode(e){return this.ok("setStayMode")&&this.ctrl.setStayMode(e),this}getStayMode(){return this.ctrl.getStayMode()}setMode(e){return this.ok("setMode")&&this.ctrl.setMode(e),this}getMode(){return this.ctrl.getMode()}showToolbar(e=true){return this.ok("showToolbar")&&this.ctrl.showToolbar(e),this}setToolbar(e){return this.ok("setToolbar")&&this.ctrl.setToolbar(e),this}setToolShortcuts(e){return this.ok("setToolShortcuts")&&this.ctrl.setToolShortcuts(e),this}setExternalGhost(e){return this.ctrl.setExternalGhost(e),this}add(e,t={}){return this.ok("add")?this.ctrl.add(e,t):null}remove(e){return this.ctrl.remove(e),this}update(e,t){return this.ctrl.update(e,t),this}updateMany(e){return this.ctrl.updateMany(e),this}removeMany(e){return this.ctrl.removeMany(e),this}lock(e,t=true){return this.ctrl.setLocked(e,t),this}show(e,t=true){return this.ctrl.setVisible(e,t),this}select(e){return this.ok("select")&&this.ctrl.select(e==null?[]:typeof e=="string"?[e]:e),this}openSettings(e){return this.ok("openSettings")&&this.ctrl.openSettings(e),this}bringToFront(e){return this.ctrl.bringToFront(e),this}sendToBack(e){return this.ctrl.sendToBack(e),this}undo(){return this.ctrl.undo(),this}redo(){return this.ctrl.redo(),this}canUndo(){return this.ctrl.canUndo()}canRedo(){return this.ctrl.canRedo()}clone(e){return this.ok("clone")&&this.ctrl.clone(e),this}duplicate(e){return this.ok("duplicate")&&this.ctrl.duplicate(e),this}copyToClipboard(e){return this.ok("copy")&&this.ctrl.copy(e),this}paste(){return this.ok("paste")&&this.ctrl.paste(),this}all(){return this.ctrl.all()}toJSON(){return this.ctrl.toJSON()}fromJSON(e){return this.ctrl.fromJSON(e),this}favorites(){return this.ctrl.favorites()}isFavorite(e){return this.ctrl.isFavorite(e)}setFavorite(e,t){return this.ok("setFavorite")&&this.ctrl.setFavorite(e,t),this}setFavorites(e){return this.ok("setFavorites")&&this.ctrl.setFavorites([...e]),this}getConfig(){return this.ctrl.toJSON()}applyConfig(e){return this.ctrl.fromJSON(e),this}ok(e){return this.ctrl.supported?true:(console.warn(`[vela] chart.drawings.${e}() ignored \u2014 the active renderer has no userDrawings capability.`),false)}};function Hn(s){let e=s.trim(),t=/^#([0-9a-f]{3})$/i.exec(e);if(t){let r=t[1];return {r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16)}}if(t=/^#([0-9a-f]{6})[0-9a-f]{0,2}$/i.exec(e),t){let r=t[1];return {r:parseInt(r.slice(0,2),16),g:parseInt(r.slice(2,4),16),b:parseInt(r.slice(4,6),16)}}let n=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i.exec(e);return n?{r:parseFloat(n[1]),g:parseFloat(n[2]),b:parseFloat(n[3])}:null}function W(s,e){let t=Hn(s);return t?`rgba(${t.r},${t.g},${t.b},${e})`:s}function dl(s,e,t){let n=Hn(s),r=Hn(e);if(!n||!r)return s;let i=(o,a)=>Math.round(o+(a-o)*t);return `rgb(${i(n.r,r.r)},${i(n.g,r.g)},${i(n.b,r.b)})`}function hl(s,e="#888888"){let t=Hn(s);if(!t)return e;let n=r=>Math.max(0,Math.min(255,Math.round(r))).toString(16).padStart(2,"0");return `#${n(t.r)}${n(t.g)}${n(t.b)}`}function xe(s){let e=Hn(s);return e?.2126*e.r+.7152*e.g+.0722*e.b<128:true}var ul={"--vela-space-1":"4px","--vela-space-2":"8px","--vela-space-3":"12px","--vela-space-4":"16px","--vela-radius-sm":"4px","--vela-radius-md":"6px","--vela-radius-lg":"10px","--vela-z-tooltip":"60","--vela-z-menu":"50","--vela-z-dialog":"40","--vela-ease":"cubic-bezier(0.22, 1, 0.36, 1)","--vela-dur-fast":"90ms","--vela-dur-med":"160ms","--vela-font-size-sm":"11px","--vela-font-size-md":"12px","--vela-font-size-lg":"14px"};function pl(s){let e=xe(s.background),t=r=>e?`rgba(255,255,255,${r})`:W(s.textColor,r+.02),n=dl(s.background,e?"#ffffff":s.textColor,e?.03:.05);return {"--vela-font":s.fontFamily,"--vela-bg":s.background,"--vela-fg":e?"#d1d4dc":s.textColor,"--vela-fg-muted":e?"#868a96":W(s.textColor,.62),"--vela-fg-faint":W(s.textColor,.35),"--vela-fg-bright":e?"#f0f3fa":"#000000","--vela-surface":s.background,"--vela-surface-elev":n,"--vela-surface-overlay":n,"--vela-surface-sunken":s.background,"--vela-border":s.borderColor,"--vela-border-strong":e?"#34353b":W(s.textColor,.28),"--vela-border-soft":s.borderColor,"--vela-border-faint":W(s.textColor,.08),"--vela-hover":t(.06),"--vela-active":t(.1),"--vela-hover-strong":t(.16),"--vela-focus":W(s.textColor,.5),"--vela-focus-soft":W(s.textColor,.12),"--vela-separator-hover-band":W(s.textColor,.1),"--vela-separator-hover-line":W(s.textColor,.55),"--vela-scroll":W(s.textColor,.3),"--vela-accent":ve,"--vela-accent-bright":mr,"--vela-highlight":ga,"--vela-selected-bg":e?"#f0f3fa":s.textColor,"--vela-selected-fg":e?s.background:"#ffffff","--vela-fg-on-fill":"#ffffff","--vela-up":s.upColor,"--vela-down":s.downColor,"--vela-danger":s.downColor,"--vela-shadow":"0 8px 30px rgba(0,0,0,0.5)","--vela-shadow-dialog":"0 20px 60px rgba(0,0,0,0.5)","--vela-backdrop":"rgba(0,0,0,0.45)"}}function ne(s,e){let t=n=>{for(let r in n)s.style.setProperty(r,n[r]);};t(ul),t(pl(e));}function Et(s,e){let t=null,n=null,r=()=>{t!==null&&(clearTimeout(t),t=null),n?.remove(),n=null;},i=()=>{let a=e.text();if(!a)return;n=s.ownerDocument.createElement("div"),n.textContent=a,n.style.cssText="position:absolute;z-index:var(--vela-z-tooltip);pointer-events:none;background:var(--vela-bg);border:1px solid var(--vela-border);color:var(--vela-fg);border-radius:var(--vela-radius-md);padding:4px 9px;box-shadow:var(--vela-shadow);font:var(--vela-font-size-md) var(--vela-font);"+(e.wrap?"max-width:260px;":"white-space:nowrap;"),ne(n,e.theme()),e.host.appendChild(n);let c=s.getBoundingClientRect(),d=e.host.getBoundingClientRect();if(e.placement==="right")n.style.left=`${c.right-d.left+8}px`,n.style.top=`${c.top-d.top+(c.height-n.offsetHeight)/2}px`;else {let h=Math.min(c.left-d.left,Math.max(0,d.width-n.offsetWidth-4));n.style.left=`${Math.max(0,h)}px`,n.style.top=`${c.bottom-d.top+6}px`;}},o=a=>{a.pointerType==="mouse"&&(r(),t=window.setTimeout(i,e.delayMs??700));};return s.addEventListener("pointerenter",o),s.addEventListener("pointerleave",r),s.addEventListener("pointerdown",r),()=>{s.removeEventListener("pointerenter",o),s.removeEventListener("pointerleave",r),s.removeEventListener("pointerdown",r),r();}}function ml(s,e,t){let n=t?.closeSelector??"",r=0,i=0,o=0,a=0,l=0,c=0,d=0,h=false,u=()=>{s.style.transform=r||i?`translate(${r}px, ${i}px)`:"";},p=()=>{r=0,i=0,u(),t?.onReset?.();};e.style.cursor="move",e.style.userSelect="none",e.addEventListener("pointerdown",f=>{if(f.button!==0||n&&f.target.closest(n))return;let b=s.getBoundingClientRect();o=b.left-r,a=b.top-i,l=b.width,c=f.clientX,d=f.clientY,h=true,e.setPointerCapture(f.pointerId),f.preventDefault();}),e.addEventListener("pointermove",f=>{if(!h)return;let b=e.offsetHeight||40,g=o+(f.clientX-c);g=Math.max(120-l,Math.min(g,window.innerWidth-120));let v=a+(f.clientY-d);v=Math.max(0,Math.min(v,window.innerHeight-b)),r=g-o,i=v-a,u();});let m=f=>{if(h){h=false;try{e.releasePointerCapture(f.pointerId);}catch{}}};return e.addEventListener("pointerup",m),e.addEventListener("pointercancel",m),{reset:p}}var _p=["close","open","high","low","hl2","hlc3","ohlc4","volume"],Np="@keyframes vela-ind-pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.3;transform:scale(.6)}}",Le=16,jo=18,Sl=2,fl=6,Hp=6,bl=6,zn=`cursor:pointer;display:inline-flex;align-items:center;justify-content:center;border:none;line-height:0;padding:0;width:${jo}px;height:${jo}px;border-radius:3px;box-sizing:border-box;flex:none;`,zp=jo+Sl*2,gl=oe("eye",Le),$p=oe("eye-off",Le),Wp=oe("gear",Le),Up=oe("close",Le),Gp=oe("chevron-up",Le),Yp=oe("chevron-down",Le),Xp=oe("objects",Le),Bi=class{constructor(e,t,n){this.container=e;this.theme=t;this.paneBoundsOf=n;this.legends=new Map;this.rows=new Map;this.dialog=null;this.backdrop=null;this.openId=null;this.selectedId=null;this.snapshot=null;this.onChange=null;this.onRemove=null;this.onToggleVisible=null;this.symbolPicker=null;this.mobileLayout=false;this.moveApi=null;this.legendActions=null;this.rowTips=new Map;this.extrasTips=new Map;this.dialogTips=[];this.moveMenu=null;this.paneCollapse=new Map;this.legendFolded=false;this.titlesVisible=true;this.valuesVisible=true;this.rowMenu=null;this.foldToggle=null;this.overviewAction=null;this.onDialogKey=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeDialog());};this.onDocClick=e=>{if(!this.selectedId)return;let t=e.target;if(t){for(let n of this.rows.values())if(n.el.contains(t))return}this.clearSelection();};this.dialogHost=null;this.onMoveMenuOutside=e=>{this.moveMenu&&!this.moveMenu.contains(e.target)&&this.closeMoveMenu();};this.onRowMenuOutside=e=>{this.rowMenu&&!this.rowMenu.contains(e.target)&&this.closeRowMenu();};e.style.position||(e.style.position="relative"),typeof document<"u"&&document.addEventListener("click",this.onDocClick);}setDialogHost(e){this.dialogHost=e,e&&getComputedStyle(e).position==="static"&&(e.style.position="relative");}setLayoutMode(e){let t=e==="mobile";if(t!==this.mobileLayout&&(this.mobileLayout=t,this.overviewAction===null&&(this.legendFolded=t),this.syncFoldToggle(),this.openId!==null)){let n=this.openId;this.closeOpenDialog(),this.openDialog(n);}}setLegendOverviewAction(e){e!==this.overviewAction&&(this.overviewAction=e,this.legendFolded=e!==null?true:this.mobileLayout,this.syncFoldToggle());}openSettingsFor(e){this.rows.has(e)&&this.openDialog(e);}tip(e,t,n,r,i=false){let o=e.get(t)??[];o.push(Et(n,{host:this.container,theme:()=>this.theme,text:typeof r=="function"?r:()=>r,wrap:i})),e.set(t,o);}disposeTips(e,t){for(let n of e.get(t)??[])n();e.delete(t);}setOnChange(e){this.onChange=e;}setOnRemove(e){this.onRemove=e;}setOnToggleVisible(e){this.onToggleVisible=e;}setTheme(e){this.theme=e;for(let t of this.legends.values())ne(t,e);for(let t of this.rows.values())t.el.style.background=t.highlighted?e.background:this.idleRowFill(),t.el.style.color=e.textColor;this.foldToggle&&this.syncFoldToggle();}setSymbolPicker(e){this.symbolPicker=e;}setMoveApi(e){this.moveApi=e;}setLegendActions(e){this.legendActions=e;for(let t of this.rows.values())this.renderExtras(t.id,t.extrasEl);}renderExtras(e,t){this.disposeTips(this.extrasTips,e),t.replaceChildren();for(let n of this.legendActions?.(e)??[]){let r=document.createElement("button");r.type="button",r.setAttribute("aria-label",n.tooltip),this.tip(this.extrasTips,e,r,n.tooltip),r.innerHTML=oe(n.icon,Le),r.className="vela-ind-ctl",r.dataset.legendAction=n.id,r.style.cssText=zn,r.addEventListener("click",i=>{i.stopPropagation(),n.run();}),t.appendChild(r);}}reposition(){for(let[e,t]of this.legends)this.positionLegend(t,e);}setTitlesVisible(e){this.titlesVisible!==e&&(this.titlesVisible=e,this.reposition());}setValuesVisible(e){this.valuesVisible=e;for(let t of this.rows.values())t.showValues=null,this.renderRowValues(t);}setPlotValues(e){for(let t of this.rows.values()){let n=e.get(t.id)??[],r=n.map(i=>`${i.value}|${i.color}`).join("\0");r!==t.plotValuesKey&&(t.plotValues=n,t.plotValuesKey=r,this.renderRowValues(t));}}rowValuesShown(e){return e.showValues??this.valuesVisible}renderRowValues(e){if(!this.rowValuesShown(e)||e.plotValues.length===0||e.highlighted){e.valuesEl.style.display="none",e.valuesEl.replaceChildren();return}e.valuesEl.style.display="inline-flex",e.valuesEl.replaceChildren();for(let t of e.plotValues){let n=document.createElement("span");n.textContent=t.value,n.style.color=t.color,e.valuesEl.appendChild(n);}}openMoveMenu(e,t){this.closeMoveMenu();let n=this.moveApi;if(!n)return;let i=this.rows.get(e)?.paneId??"price",o=n.panes(),a=document.createElement("div");a.style.cssText=`position:fixed;z-index:var(--vela-z-tooltip);min-width:150px;padding:4px;border-radius:var(--vela-radius-md);background:var(--vela-surface-elev);color:${this.theme.textColor};border:1px solid var(--vela-border);box-shadow:var(--vela-shadow);font-size:var(--vela-font-size-md);`,ne(a,this.theme);let l=[];for(let p of o)p.id!==i&&l.push({label:`Move to ${p.label}`,target:p.kind==="price"?"price":{pane:p.id}});i!=="price"&&[...this.rows.values()].filter(p=>p.paneId===i).length<=1||(i!=="price"&&l.push({label:"New pane above",target:{newPane:{before:i}}}),l.push({label:"New pane below",target:{newPane:{after:i}}}));for(let p of l){let m=document.createElement("button");m.type="button",m.textContent=p.label,m.className="vela-ind-menuitem",m.style.cssText="display:block;width:100%;text-align:left;padding:6px 10px;border:none;border-radius:var(--vela-radius-sm);color:inherit;cursor:pointer;white-space:nowrap;",m.addEventListener("click",f=>{f.stopPropagation(),this.closeMoveMenu(),n.move(e,p.target);}),a.appendChild(m);}document.body.appendChild(a);let d=t.getBoundingClientRect(),h=a.offsetWidth||160,u=a.offsetHeight||80;a.style.left=`${Math.min(d.left,window.innerWidth-h-6)}px`,a.style.top=`${Math.min(d.bottom+4,window.innerHeight-u-6)}px`,this.moveMenu=a,setTimeout(()=>{typeof document<"u"&&document.addEventListener("pointerdown",this.onMoveMenuOutside,true);},0);}closeMoveMenu(){typeof document<"u"&&document.removeEventListener("pointerdown",this.onMoveMenuOutside,true),this.moveMenu?.remove(),this.moveMenu=null;}openRowMenu(e,t,n){this.closeRowMenu(),this.closeMoveMenu();let r=this.rows.get(e);if(!r)return;let i=document.createElement("div");i.style.cssText=`position:fixed;z-index:var(--vela-z-tooltip);min-width:170px;padding:4px;border-radius:var(--vela-radius-md);background:var(--vela-surface-elev);color:${this.theme.textColor};border:1px solid var(--vela-border);box-shadow:var(--vela-shadow);font-size:var(--vela-font-size-md);`,ne(i,this.theme);let o=document.createElement("button");o.type="button",o.className="vela-ind-menuitem",o.style.cssText="display:flex;align-items:center;gap:8px;width:100%;text-align:left;padding:6px 10px;border:none;border-radius:var(--vela-radius-sm);color:inherit;cursor:pointer;white-space:nowrap;";let a=document.createElement("span");a.style.cssText="display:inline-flex;align-items:center;justify-content:center;width:14px;flex:none;line-height:0;",a.innerHTML=this.rowValuesShown(r)?vl:"";let l=document.createElement("span");l.textContent="Indicator values",o.append(a,l),o.addEventListener("click",h=>{h.stopPropagation(),this.closeRowMenu(),r.showValues=!this.rowValuesShown(r),this.renderRowValues(r);}),i.appendChild(o),document.body.appendChild(i);let c=i.offsetWidth||180,d=i.offsetHeight||40;i.style.left=`${Math.min(t,window.innerWidth-c-6)}px`,i.style.top=`${Math.min(n,window.innerHeight-d-6)}px`,this.rowMenu=i,setTimeout(()=>{typeof document<"u"&&document.addEventListener("pointerdown",this.onRowMenuOutside,true);},0);}closeRowMenu(){typeof document<"u"&&document.removeEventListener("pointerdown",this.onRowMenuOutside,true),this.rowMenu?.remove(),this.rowMenu=null;}setPane(e,t){let n=this.rows.get(e);if(!n||n.paneId===t)return;let r=n.paneId;if(n.paneId=t,this.attach(this.legendFor(t),n.el,n.native),this.syncFoldToggle(),r!=="price"){let i=this.legends.get(r);i&&i.childElementCount===0&&(i.remove(),this.legends.delete(r));}}legendFor(e){let t=this.legends.get(e);return t||(t=document.createElement("div"),t.dataset.velaPane=e,t.style.cssText="position:absolute;left:10px;z-index:5;display:flex;flex-direction:column;align-items:flex-start;gap:0;pointer-events:none;font:12px -apple-system,Segoe UI,sans-serif;",ne(t,this.theme),this.positionLegend(t,e),this.container.appendChild(t),this.legends.set(e,t)),t}positionLegend(e,t){let n=this.paneBoundsOf?this.paneBoundsOf(t):{top:0,height:1/0};e.style.display=n.height<4||!this.titlesVisible?"none":"flex";let r=this.paneCollapse.has(t),i=this.paneCollapse.get(t)??null;for(let a of this.rows.values())a.paneId===t&&(a.el.style.display=(r?a.id!==i:this.legendFolded)?"none":"flex");let o=n.top+8;if(r&&Number.isFinite(n.height)){let a=e.offsetHeight||20;o=n.top+Math.max(1,Math.round((n.height-a)/2));}e.style.top=`${o}px`;}setCollapsedPanes(e){this.paneCollapse=e;}syncFoldToggle(){let e=this.rows.size,t=this.overviewAction!==null||this.mobileLayout?1:2;if(e<t){let a=this.legendFolded;e>0&&(this.legendFolded=false),this.foldToggle&&(this.foldToggle.remove(),this.foldToggle=null,this.disposeTips(this.rowTips,"fold")),a&&e>0&&this.reposition();return}let n=this.foldToggle;n||(n=document.createElement("button"),n.type="button",n.className="vela-ind-fold",this.tip(this.rowTips,"fold",n,()=>this.overviewAction!==null?"Indicators":this.legendFolded?"Show indicator legend":"Hide indicator legend"),n.addEventListener("click",()=>{if(this.overviewAction!==null){this.overviewAction();return}this.legendFolded=!this.legendFolded,this.syncFoldToggle();}),this.foldToggle=n);let r=this.legendFolded;n.setAttribute("aria-label",this.overviewAction!==null?"Indicators":r?"Show indicator legend":"Hide indicator legend");let i=this.theme.textColor;n.style.cssText=`pointer-events:auto;display:inline-flex;align-items:center;gap:4px;background:${this.theme.background};color:${i};border:1px solid ${this.theme.borderColor};border-radius:4px;padding:2px 6px;margin-top:6px;cursor:pointer;font:inherit;line-height:0;`,n.replaceChildren();let o=document.createElement("span");if(o.style.cssText="display:inline-flex;align-items:center;line-height:0;opacity:0.7;",o.innerHTML=this.overviewAction!==null?Xp:r?Yp:Gp,n.appendChild(o),r){let a=document.createElement("span");a.textContent=String(e),a.style.cssText=`font-weight:600;line-height:normal;font-size:12px;color:${i};`,n.appendChild(a);}this.legendFor("price").appendChild(n),this.reposition();}upsert(e,t,n,r,i="price",o={}){let a=o.settingsTitle??t,l=this.rows.get(e);if(l){l.title=t,l.settingsTitle=a,l.inputs=n,l.values={...r},l.titleEl.textContent=t,l.paneId!==i&&(l.paneId=i,this.attach(this.legendFor(i),l.el,l.native),this.syncFoldToggle());return}wl();let c=document.createElement("div");c.style.cssText=`pointer-events:auto;display:flex;align-items:center;background:${this.idleRowFill()};border-radius:4px;padding:${Sl}px ${fl}px;margin-left:-${fl}px;min-height:${zp}px;box-sizing:border-box;color:${this.theme.textColor};user-select:none;-webkit-user-select:none;`,c.addEventListener("mouseleave",()=>{this.selectedId!==e&&this.setRowHighlighted(e,false);}),c.addEventListener("click",v=>{v.button!==0||v.target.closest("button")||this.selectRow(e);}),c.addEventListener("dblclick",v=>{v.target.closest("button")||this.openDialog(e);}),c.addEventListener("mousedown",v=>{v.button===1&&v.preventDefault();}),c.addEventListener("auxclick",v=>{v.button===1&&(v.preventDefault(),this.onRemove?.(e));}),c.addEventListener("contextmenu",v=>{v.preventDefault(),v.stopPropagation(),this.openRowMenu(e,v.clientX,v.clientY);});let d=document.createElement("span");d.style.cssText="display:none;box-sizing:border-box;flex:none;";let h=document.createElement("span");h.style.cssText="white-space:nowrap;",h.addEventListener("mouseenter",()=>this.setRowHighlighted(e,true));let u=document.createElement("span");if(u.textContent=t,u.style.cssText="font-weight:600;",h.appendChild(u),o.beta){let v=document.createElement("sup");v.textContent="beta",v.style.cssText="font-size:8px;font-weight:700;opacity:0.7;margin-left:1px;letter-spacing:0.2px;",h.appendChild(v);}c.appendChild(h);let p=document.createElement("span");p.style.cssText=`display:none;align-items:center;gap:5px;margin-left:${Hp}px;white-space:nowrap;font-variant-numeric:tabular-nums;`,c.appendChild(p);let m=document.createElement("span");m.style.cssText=`display:none;align-items:center;gap:${bl}px;flex:none;margin-left:${bl}px;`;let f=null;if(this.onToggleVisible){let v=document.createElement("button");v.type="button",v.setAttribute("aria-label","Hide"),this.tip(this.rowTips,e,v,()=>this.rows.get(e)?.hidden?"Show":"Hide"),v.innerHTML=gl,v.className="vela-ind-ctl",v.style.cssText=zn,v.addEventListener("click",()=>{let y=this.rows.get(e);this.onToggleVisible?.(e,!!y?.hidden);}),m.appendChild(v),f=v;}if(n.length>0){let v=document.createElement("button");v.type="button",v.setAttribute("aria-label","Settings"),this.tip(this.rowTips,e,v,"Settings"),v.innerHTML=Wp,v.className="vela-ind-ctl",v.style.cssText=zn,v.addEventListener("click",()=>this.openDialog(e)),m.appendChild(v);}if(this.moveApi){let v=document.createElement("button");v.type="button",v.setAttribute("aria-label","Move to pane"),this.tip(this.rowTips,e,v,"Move to pane"),v.innerHTML=oe("move",Le),v.className="vela-ind-ctl",v.style.cssText=zn,v.addEventListener("click",y=>{y.stopPropagation(),this.openMoveMenu(e,v);}),m.appendChild(v);}let b=document.createElement("span");b.style.cssText="display:contents;",this.renderExtras(e,b),m.appendChild(b);let g=document.createElement("button");g.type="button",g.setAttribute("aria-label","Remove indicator"),this.tip(this.rowTips,e,g,"Remove indicator"),g.innerHTML=Up,g.className="vela-ind-close",g.style.cssText=zn,g.addEventListener("click",()=>this.onRemove?.(e)),m.appendChild(g),c.appendChild(m),c.appendChild(d),this.attach(this.legendFor(i),c,!!o.native),this.rows.set(e,{id:e,title:t,settingsTitle:a,inputs:n,values:{...r},el:c,titleEl:u,statusEl:d,valuesEl:p,plotValues:[],plotValuesKey:"",showValues:null,highlighted:false,paneId:i,hidden:false,eyeEl:f,controlsEl:m,extrasEl:b,native:!!o.native}),this.syncFoldToggle();}attach(e,t,n){n?e.prepend(t):e.appendChild(t);}setValues(e,t){let n=this.rows.get(e);n&&(n.values={...n.values,...t});}setStatus(e,t){let n=this.rows.get(e);if(!n)return;let r=n.statusEl;if(r.replaceChildren(),t==="idle"){r.style.cssText="display:none;box-sizing:border-box;flex:none;";return}if(t==="loading"){r.style.cssText="display:inline-flex;align-items:center;gap:3px;box-sizing:border-box;flex:none;";for(let i=0;i<3;i+=1){let o=document.createElement("span");o.style.cssText="width:4px;height:4px;border-radius:50%;background:currentColor;opacity:0.15;flex:none;",o.animate?.([{opacity:.12},{opacity:.55}],{duration:800,iterations:1/0,direction:"alternate",easing:"ease-in-out",delay:-i*260}),r.appendChild(o);}return}this.ensureStatusKeyframes(),r.style.cssText=`display:inline-block;box-sizing:border-box;flex:none;width:8px;height:8px;border-radius:50%;background:${this.theme.upColor};animation:vela-ind-pulse 1.2s ease-in-out infinite;`;}ensureStatusKeyframes(){if(typeof document>"u"||document.getElementById("vela-ind-status-kf"))return;let e=document.createElement("style");e.id="vela-ind-status-kf",e.textContent=Np,document.head.appendChild(e);}setVisible(e,t){let n=this.rows.get(e);n&&(n.hidden=!t,n.el.style.opacity=t?"1":"0.5",n.eyeEl&&(n.eyeEl.innerHTML=t?gl:$p,n.eyeEl.setAttribute("aria-label",t?"Hide":"Show")),this.syncRowActions(n));}selectRow(e){this.selectedId!==e&&(this.clearSelection(),this.selectedId=e,this.setRowHighlighted(e,true));}setRowHighlighted(e,t){let n=this.rows.get(e);n&&(n.highlighted=t,this.renderRowValues(n),n.el.style.boxShadow=t?`inset 0 0 0 1px ${this.neutralBorder()}`:"none",n.el.style.background=t?this.theme.background:this.idleRowFill(),this.syncRowActions(n));}syncRowActions(e){let t=e.highlighted;e.controlsEl.style.display=t||e.hidden?"inline-flex":"none";for(let n of Array.from(e.controlsEl.children))if(!(!(n instanceof HTMLElement)||n===e.eyeEl)){if(n===e.extrasEl){n.style.display=t?"contents":"none";continue}n.style.display=t?"inline-flex":"none";}}clearSelection(){this.selectedId&&(this.setRowHighlighted(this.selectedId,false),this.selectedId=null);}remove(e){let t=this.rows.get(e);if(t?.el.remove(),this.rows.delete(e),this.disposeTips(this.rowTips,e),this.disposeTips(this.extrasTips,e),this.selectedId===e&&(this.selectedId=null),this.openId===e&&this.closeDialog(),this.syncFoldToggle(),t&&t.paneId!=="price"){let n=this.legends.get(t.paneId);n&&n.childElementCount===0&&(n.remove(),this.legends.delete(t.paneId));}}destroy(){this.closeDialog(),this.closeMoveMenu(),this.closeRowMenu();for(let e of [...this.rowTips.keys()])this.disposeTips(this.rowTips,e);for(let e of [...this.extrasTips.keys()])this.disposeTips(this.extrasTips,e);for(let e of this.legends.values())e.remove();this.legends.clear(),this.rows.clear(),this.foldToggle=null,this.legendFolded=false,this.selectedId=null,typeof document<"u"&&document.removeEventListener("click",this.onDocClick);}isDialogOpen(){return this.dialog!==null}closeOpenDialog(){this.closeDialog();}openDialog(e){this.closeDialog();let t=this.rows.get(e);if(!t||t.inputs.length===0)return;this.openId=e,this.snapshot={...t.values},wl();let n=this.theme,r=n.fontFamily||"-apple-system,Segoe UI,sans-serif",i=this.neutralBorder(),o=this.strongText(),a=this.isDarkTheme()?"dark":"light",l=document.createElement("div");l.className="vela-ind-dialog-backdrop",l.style.cssText="position:absolute;inset:0;z-index:40;display:flex;align-items:center;justify-content:center;background:transparent;pointer-events:auto;",l.addEventListener("pointerdown",g=>{g.target===l&&(this.closeDialog(),this.clearSelection());});let c=document.createElement("div");c.className="vela-ind-dialog",c.style.cssText=`display:flex;flex-direction:column;width:fit-content;min-width:min(360px,90%);max-width:min(640px,94%);max-height:82%;background:${n.background};border:1px solid ${i};border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow-dialog);color:${o};color-scheme:${a};font:13px ${r};overflow:hidden;`,this.mobileLayout&&(c.style.cssText+="width:100%;min-width:0;max-width:none;height:100%;max-height:none;border:none;border-radius:0;"),ne(c,n),c.addEventListener("keydown",g=>{g.key!=="Escape"&&g.stopPropagation();});let d=document.createElement("div");d.style.cssText="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;padding:16px 20px 12px;flex:0 0 auto;";let h=document.createElement("span");h.textContent=t.settingsTitle,h.style.cssText="font-weight:600;font-size:16px;line-height:1.3;";let u=document.createElement("button");u.type="button",u.setAttribute("aria-label","Close"),this.dialogTips.push(Et(u,{host:this.container,theme:()=>this.theme,text:()=>"Close"})),u.innerHTML=oe("close",15),u.className="vela-ind-ctl",u.style.cssText="cursor:pointer;display:inline-flex;align-items:center;background:transparent;border:none;line-height:0;padding:2px;flex:0 0 auto;",u.addEventListener("click",()=>this.closeDialog()),d.append(h,u),c.appendChild(d),this.mobileLayout||ml(c,d,{closeSelector:"button"});let p=document.createElement("div");p.style.cssText=`display:flex;gap:16px;padding:0 20px;border-bottom:1px solid ${i};flex:0 0 auto;`;let m=document.createElement("div");m.textContent="Inputs",m.style.cssText=`padding:8px 2px;margin-bottom:-1px;border-bottom:2px solid ${o};font-weight:600;font-size:13px;`,p.appendChild(m),c.appendChild(p);let f=document.createElement("div");f.style.cssText="padding:14px 20px 6px;overflow-y:auto;flex:1 1 auto;display:flex;flex-direction:column;gap:24px;";for(let g of Kp(t.inputs)){let v=document.createElement("div");if(v.style.cssText="display:flex;flex-direction:column;gap:14px;",g.name){let x=document.createElement("div");x.textContent=g.name,x.style.cssText="font-size:var(--vela-font-size-sm);font-weight:600;letter-spacing:0.05em;text-transform:uppercase;color:var(--vela-fg-muted);",v.appendChild(x);}let y=document.createElement("div");y.style.cssText=this.mobileLayout?"display:grid;grid-template-columns:minmax(0,1fr) auto auto max-content;align-items:center;column-gap:12px;row-gap:22px;":"display:grid;grid-template-columns:minmax(140px,auto) auto auto 1fr;align-items:center;column-gap:12px;row-gap:22px;";for(let x of g.rows)this.buildInputRow(y,x,t);v.appendChild(y),f.appendChild(v);}c.appendChild(f);let b=document.createElement("div");b.style.cssText=`display:flex;justify-content:flex-end;gap:8px;padding:14px 20px;border-top:1px solid ${i};flex:0 0 auto;`,b.append(this.dialogButton("Cancel",false,()=>this.revertAndClose()),this.dialogButton("Ok",true,()=>this.closeDialog())),c.appendChild(b),l.appendChild(c),(this.dialogHost??this.container).appendChild(l),this.dialog=c,this.backdrop=l,document.addEventListener("keydown",this.onDialogKey);}closeDialog(){document.removeEventListener("keydown",this.onDialogKey);for(let e of this.dialogTips.splice(0))e();this.backdrop?.remove(),this.backdrop=null,this.dialog=null,this.openId=null,this.snapshot=null;}revertAndClose(){let e=this.openId?this.rows.get(this.openId):null,t=this.snapshot;if(e&&t)for(let n of e.inputs){let r=t[n.key],i=r!==void 0?r:n.defval;e.values[n.key]!==i&&(e.values[n.key]=i,this.onChange?.({indicatorId:e.id,key:n.key,value:i}));}this.closeDialog();}buildInputRow(e,t,n){let r=h=>`vela-inp-${n.id}-${h.key}`;if(t.length>1){let h=document.createElement("div");h.style.cssText="grid-column:1 / -1;display:flex;flex-wrap:wrap;align-items:center;gap:12px;";for(let p of t){let m=p.type==="color"||p.type==="bool",f=p.type==="bool",b=r(p),g=document.createElement("div");g.style.cssText=`display:flex;align-items:center;gap:6px;${f?"flex-direction:row-reverse;":""}`;let v=Fi(p);if(v){let x=document.createElement("label");x.htmlFor=b,x.textContent=v,x.style.cssText=`font-size:13px;opacity:0.9;${f?"cursor:pointer;":""}`,g.appendChild(x);}let y=document.createElement("div");y.style.cssText=m?"":"width:110px;",y.appendChild(this.buildControl(n,p,b)),g.appendChild(y),h.appendChild(g);}let u=[...t].reverse().find(p=>p.tooltip)?.tooltip;u&&h.appendChild(this.infoButton(u)),e.appendChild(h);return}let i=t[0],o=r(i);if(i.type==="bool"){let h=document.createElement("div");h.style.cssText="grid-column:1 / 4;display:flex;align-items:center;gap:8px;";let u=document.createElement("label");u.style.cssText="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;",u.appendChild(this.buildControl(n,i,o)),u.appendChild(document.createTextNode(Fi(i))),h.appendChild(u),i.tooltip&&h.appendChild(this.infoButton(i.tooltip)),e.appendChild(h),e.appendChild(document.createElement("div"));return}if(i.type==="text_area"){let h=document.createElement("div");h.style.cssText="grid-column:1 / -1;display:flex;flex-direction:column;gap:8px;";let u=document.createElement("div");u.style.cssText="display:flex;align-items:center;justify-content:center;gap:8px;";let p=document.createElement("label");p.htmlFor=o,p.textContent=Fi(i),p.style.cssText="font-size:13px;",u.appendChild(p),i.tooltip&&u.appendChild(this.infoButton(i.tooltip)),h.appendChild(u),h.appendChild(this.buildControl(n,i,o)),e.appendChild(h);return}let a=document.createElement("label");a.htmlFor=o,a.textContent=Fi(i),a.style.cssText="font-size:13px;opacity:0.9;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;";let l=document.createElement("div");l.style.cssText="grid-column:span 2;display:flex;align-items:center;gap:8px;";let c=i.type==="color"||i.type==="session"||i.type==="time",d=document.createElement("div");d.style.cssText=c?"":"width:140px;",d.appendChild(this.buildControl(n,i,o)),l.appendChild(d),i.tooltip&&l.appendChild(this.infoButton(i.tooltip)),e.appendChild(a),e.appendChild(l),e.appendChild(document.createElement("div"));}buildControl(e,t,n){let r=e.values[t.key]??t.defval,i=a=>{e.values[t.key]=a,this.onChange?.({indicatorId:e.id,key:t.key,value:a});},o=this.ctrlStyle();if(t.type==="bool")return this.buildToggle(n,!!r,i);if(t.options&&t.options.length>0)return this.select(n,t.options.map(String),String(r),`${o}cursor:pointer;`,i);if(t.type==="source")return this.select(n,_p,String(r),`${o}cursor:pointer;`,i);if(t.type==="color"){let a=document.createElement("input");return a.type="color",a.id=n,a.value=hl(String(r)),a.style.cssText=`flex:0 0 auto;box-sizing:border-box;width:32px;height:32px;padding:2px;border:1px solid ${this.neutralBorder()};border-radius:0;background:transparent;cursor:pointer;`,a.addEventListener("input",()=>i(a.value)),a}if(t.type==="symbol")return this.buildSymbol(n,String(r),i);if(t.type==="timeframe")return this.selectPairs(n,qp,String(r),`${o}cursor:pointer;`,i);if(t.type==="session")return this.buildSession(n,String(r),i);if(t.type==="time")return this.buildTime(n,Number(r)||0,i);if(t.type==="text_area")return this.buildTextArea(n,String(r),i);if(t.type==="int"||t.type==="float"||t.type==="price"){let a=document.createElement("input");a.type="number",a.id=n,a.value=String(r),t.min!==void 0&&(a.min=String(t.min)),t.max!==void 0&&(a.max=String(t.max)),a.step=String(t.step??(t.type==="int"?1:.1)),a.style.cssText=o;let l=String(r),c=()=>{let d=Number(a.value);if(!Number.isFinite(d)){a.value=l;return}t.min!==void 0&&(d=Math.max(t.min,d)),t.max!==void 0&&(d=Math.min(t.max,d)),t.type==="int"&&(d=Math.round(d)),a.value=String(d),String(d)!==l&&(l=String(d),i(d));};return a.addEventListener("blur",c),a.addEventListener("keydown",d=>{d.key==="Enter"&&(d.preventDefault(),a.blur());}),a}return this.buildTextField(n,String(r),i)}buildTextField(e,t,n){let r=document.createElement("input");r.type="text",r.id=e,r.value=t,r.style.cssText=this.ctrlStyle();let i=t;return r.addEventListener("blur",()=>{r.value!==i&&(i=r.value,n(r.value));}),r.addEventListener("keydown",o=>{o.key==="Enter"&&(o.preventDefault(),r.blur());}),r}buildToggle(e,t,n){let r=this.theme,i=this.neutralBorder(),o=this.strongText(),a=document.createElement("button");a.type="button",a.id=e,a.setAttribute("role","switch"),a.innerHTML=vl,a.style.cssText=`width:20px;height:20px;flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;border:1px solid ${i};border-radius:5px;cursor:pointer;padding:0;transition:background .12s ease,border-color .12s ease;`;let l=t,c=d=>{a.setAttribute("aria-checked",d?"true":"false"),a.style.background=d?o:"transparent",a.style.borderColor=d?o:i,a.style.color=d?r.background:"transparent";};return c(t),a.addEventListener("click",()=>{l=!l,c(l),n(l);}),a}infoButton(e){let t=document.createElement("span");return t.textContent="i",this.dialogTips.push(Et(t,{host:this.container,theme:()=>this.theme,text:()=>e,wrap:true,delayMs:250})),t.className="vela-ind-hint",t.style.cssText="flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;font-weight:600;font-size:11px;font-family:inherit;line-height:1;cursor:help;user-select:none;",t}select(e,t,n,r,i){return this.selectPairs(e,t.map(o=>({value:o,label:o})),n,r,i)}selectPairs(e,t,n,r,i){let o=document.createElement("select");if(o.id=e,o.style.cssText=r,n!==""&&!t.some(a=>a.value===n)){let a=document.createElement("option");a.value=n,a.textContent=n,a.selected=true,a.disabled=true,o.appendChild(a);}for(let a of t){let l=document.createElement("option");l.value=a.value,l.textContent=a.label,a.value===n&&(l.selected=true),o.appendChild(l);}return this.styleSelect(o),o.addEventListener("change",()=>i(o.value)),this.wrapSelectChevron(o)}wrapSelectChevron(e){let t=document.createElement("div");t.style.cssText="position:relative;width:100%;",e.style.paddingRight="28px";let n=document.createElement("span");return n.innerHTML=jp,n.style.cssText=`position:absolute;right:10px;top:50%;transform:translateY(-50%);pointer-events:none;display:flex;align-items:center;color:${this.strongText()};opacity:0.85;line-height:0;`,t.append(e,n),t}buildSession(e,t,n){let[r,i]=Jp(t),o=document.createElement("div");o.style.cssText="display:flex;align-items:center;gap:6px;";let a=r,l=i,c=()=>n(Qp(a,l)),d=this.timeSelect(e,a,86,u=>{a=u,c();}),h=this.timeSelect(`${e}-end`,l,86,u=>{l=u,c();});return o.append(d,h),o}buildTime(e,t,n){let r=em(t),i=document.createElement("div");i.style.cssText="display:flex;align-items:center;gap:6px;";let o=r.date,a=r.time,l=()=>{if(!o)return;let h=Date.parse(`${o}T${a}:00`);Number.isFinite(h)&&n(h);},c=document.createElement("input");c.type="date",c.id=e,c.value=o,c.style.cssText=`${this.ctrlStyle()}width:auto;cursor:pointer;`,c.addEventListener("change",()=>{o=c.value,l();});let d=this.timeSelect(`${e}-time`,a,86,h=>{a=h,l();});return i.append(c,d),i}buildTextArea(e,t,n){let r=document.createElement("textarea");r.id=e,r.value=t,r.rows=3,r.style.cssText=`${this.ctrlStyle()}width:100%;height:auto;min-height:64px;padding:8px;resize:vertical;font-family:inherit;line-height:1.4;`;let i=t;return r.addEventListener("blur",()=>{r.value!==i&&(i=r.value,n(r.value));}),r}timeSelect(e,t,n,r){return this.selectPairs(e,Zp,t,`${this.ctrlStyle()}width:${n}px;cursor:pointer;`,r)}buildSymbol(e,t,n){let r=this.symbolPicker;if(!r)return this.buildTextField(e,t,n);let i=t,o=document.createElement("button");o.type="button",o.id=e,o.style.cssText=`${this.ctrlStyle()}display:flex;align-items:center;cursor:pointer;text-align:left;`;let a=document.createElement("span");return a.textContent=i||"Select symbol\u2026",a.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;",o.append(a),o.addEventListener("click",()=>r(i,l=>{l&&(i=l,a.textContent=l,n(l));})),o}ctrlStyle(){return `width:100%;box-sizing:border-box;height:32px;background:transparent;border:1px solid ${this.neutralBorder()};color:${this.strongText()};border-radius:6px;padding:0 8px;font-size:13px;font-family:inherit;outline:none;`}isDarkTheme(){return xe(this.theme.background)}idleRowFill(){return W(this.theme.background,.6)}neutralBorder(){return "var(--vela-border)"}strongText(){return "var(--vela-fg-bright)"}styleSelect(e){let t=this.theme.background,n=this.strongText();e.style.backgroundColor=t;for(let r of Array.from(e.options))r.style.backgroundColor=t,r.style.color=n;}dialogButton(e,t,n){let r=document.createElement("button");return r.type="button",r.textContent=e,r.className=t?"vela-ind-btn vela-ind-btn-primary":"vela-ind-btn",r.addEventListener("click",n),r}};function Fi(s){let e=s.title;return e.length>0?e.charAt(0).toUpperCase()+e.slice(1):""}function Kp(s){let e=[],t=new Map;for(let n of s){let r=n.group&&n.group.length>0?n.group:null;t.has(r)||(t.set(r,[]),e.push(r)),t.get(r).push(n);}return e.map(n=>{let r=t.get(n),i=[],o=new Map;for(let a of r){let l=a.inline&&a.inline.length>0?a.inline:null;l&&o.has(l)?i[o.get(l)].push(a):(l&&o.set(l,i.length),i.push([a]));}return {name:n,rows:i}})}var vl=oe("check",12),jp=oe("chevron-down",16),yl="vela-ind-dialog-styles",xl="10";function wl(){if(typeof document>"u")return;let s=document.getElementById(yl);if(s?.dataset.rev===xl)return;let e=s??document.createElement("style");e.id=yl,e.dataset.rev=xl,e.textContent=`
1
+ var Vela=(function(exports){'use strict';function le(s){return s.kind!=="candle"&&s.kind!=="bar"&&s.kind!=="markers"}var ct=class{constructor(){this.handlers=new Map;}on(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n));let r=n;return r.add(t),()=>{r.delete(t);}}off(e,t){this.handlers.get(e)?.delete(t);}hasListeners(e){return (this.handlers.get(e)?.size??0)>0}emit(e,t){let n=this.handlers.get(e);if(n)for(let r of n)try{r(t);}catch(i){console.error(`[vela] event handler error for "${String(e)}"`,i);}}clear(){this.handlers.clear();}};var ur=class{constructor(){this.records=new Map;this.counter=0;}nextId(e="ind"){return this.counter+=1,`${e}-${this.counter}`}add(e){this.records.set(e.id,e);}get(e){return this.records.get(e)}remove(e){let t=this.records.get(e);return this.records.delete(e),t}all(){return [...this.records.values()]}};var mn=new Map;function _t(s){mn.set(s.type,s);}function pa(s){mn.delete(s);}function fn(s){return mn.get(s)}function ma(){return [...mn.keys()]}function pr(){return [...mn.values()]}var mr=class{constructor(e,t,n){this.feed=e;this.market=t;this.onBar=n;this.unsubscribe=null;}start(){this.unsubscribe||(this.unsubscribe=this.feed.subscribe(this.market,this.onBar));}stop(){this.unsubscribe?.(),this.unsubscribe=null;}};var Nt=class{constructor(e,t,n,r){this.controller=n;this.schema=[];this.visibleState=true;this.bus=new ct;this.id=e,this.title=t,r!==void 0&&(this.source=r);}get inputs(){return this.schema}get visible(){return this.visibleState}setInput(e,t){this.controller.applyInputs(this.id,{[e]:t});}setInputs(e){this.controller.applyInputs(this.id,e);}setVisible(e){this.controller.setVisible(this.id,e);}moveTo(e){this.controller.moveIndicator(this.id,e);}on(e,t){return this.bus.on(e,t)}context(e){return this.controller.getIndicatorContext(this.id,e)}remove(){this.controller.removeIndicator(this.id);}setSchema(e){this.schema=e;}setVisibleState(e){this.visibleState=e;}emit(e,t){this.bus.emit(e,t);}};function Kd(s){let e={};for(let t of s.series)e[t.kind]=(e[t.kind]??0)+1;return {id:s.id,title:s.title,overlay:s.overlay,paneId:s.paneId,native:!!s.native,nativeType:s.native?.type,series:e,fills:s.fills.length,backgrounds:s.backgrounds.length,priceLines:s.priceLines.length,lines:s.lines?.length??0,boxes:s.boxes?.length??0,labels:s.labels?.length??0,polylines:s.polylines?.length??0,linefills:s.linefills?.length??0,tables:s.tables?.length??0,barColors:s.barColors?.length??0,trades:s.trades?.length??0,inputs:s.inputs.length}}function fa(s){let e=s.map(Kd),t=n=>e.reduce((r,i)=>r+n(i),0);return {indicators:e,totals:{panes:new Set(e.map(n=>n.paneId??"price")).size,series:t(n=>Object.values(n.series).reduce((r,i)=>r+i,0)),fills:t(n=>n.fills),backgrounds:t(n=>n.backgrounds),priceLines:t(n=>n.priceLines),lines:t(n=>n.lines),boxes:t(n=>n.boxes),labels:t(n=>n.labels),polylines:t(n=>n.polylines),linefills:t(n=>n.linefills),tables:t(n=>n.tables),barColors:t(n=>n.barColors),trades:t(n=>n.trades)}}}var jd={"1D":864e5,"1W":6048e5,"1M":2592e6,"3M":7776e6,"6M":15552e6,"1Y":31536e6,"5Y":15768e7};function ba(s,e){if(e.length===0)return null;let t=e[0].time,n=e[e.length-1].time;if(s==="ALL")return {from:t,to:n};let r;return s==="YTD"?r=Date.UTC(new Date(n).getUTCFullYear(),0,1):r=n-jd[s],{from:Math.max(t,r),to:n}}var ve="#2962ff",fr="#38c0fd",q="#089981",X="#f23645",he="#787b86",va="#e0b400",bn="#ff9800",_e="#5b9cf6",ya="#ff5d00",br="#0ecb81",gr="#f6465d",pv="#f97316",mv="#0ea5e9",fv="#9ca3af",gn="#3b82f6",xa="#9aa0ad",wa="#1e293b",vr="#475569",Sa=ve,Ca=X,Ta="#d500f9",ga=[ve,q,X,bn,"#7e57c2","#26a69a",_e,"#e573b5"];function bv(s){let e=0;for(let t=0;t<s.length;t++)e=e*31+s.charCodeAt(t)>>>0;return ga[e%ga.length]}var R=fr;function Ro(){return {lineColor:R,lineWidth:2,lineStyle:"solid"}}function Ne(s=""){return {value:s,size:"normal",hAlign:"left",vAlign:"top"}}var yr=class yr{constructor(e){this.locked=false;this.visible=true;this.zIndex=0;this.id=e.id??`dw-${yr.seq+=1}`,this.paneId=e.paneId,this.anchors=(e.anchors??[]).map(t=>({time:t.time,price:t.price})),this.style=e.style?{...e.style}:Ro(),this.text=e.text?{...e.text}:void 0,this.locked=e.locked??false,this.visible=e.visible??true,this.zIndex=e.zIndex??0,this.createdAt=e.createdAt??Date.now(),e.props&&this.readProps(e.props);}isComplete(){return this.anchors.length>=this.anchorSchema().min}placementMode(){return "click"}onPlaced(e){}constrainHandleDrag(e){}translateBody(e,t,n){return n.map(r=>({time:r.time+e,price:r.price+t}))}timeExtent(){if(this.anchors.length===0)return null;let e=1/0,t=-1/0;for(let n of this.anchors)n.time<e&&(e=n.time),n.time>t&&(t=n.time);return {min:e,max:t}}editableLevels(){return null}applySettings(e){for(let[t,n]of Object.entries(e))t.startsWith("text.")&&!this.text&&(this.text=Ne()),Ma(this,t,n);}applyProps(e){this.readProps(e);}serialize(){return {id:this.id,type:this.type,paneId:this.paneId,anchors:this.anchors.map(e=>({time:e.time,price:e.price})),style:{...this.style},text:this.text?{...this.text}:void 0,locked:this.locked,visible:this.visible,zIndex:this.zIndex,createdAt:this.createdAt,props:this.writeProps()}}writeProps(){}readProps(e){}};yr.seq=0;var B=yr;function Ma(s,e,t){let n=e.split("."),r=s;for(let i=0;i<n.length-1;i+=1){let o=n[i],a=r[o];(a==null||typeof a!="object")&&(a={},r[o]=a),r=a;}r[n[n.length-1]]=t;}var Do=new Map;function D(s,e){Do.set(s,e);}function La(s){return Do.get(s)??null}function $(s){return Do.get(s)??""}function oe(s,e){return $(s).replace("<svg ",`<svg width="${e}" height="${e}" `)}function Pa(s,e=""){return `<svg viewBox="0 0 16 16" width="1em" height="1em" ${e?e+" ":""}fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">${s}</svg>`}function I(s,e=""){return `<svg viewBox="0 0 24 24" width="1em" height="1em" ${e?e+" ":""}fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${s}</svg>`}function Ao(s){return `<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" stroke="none">${s}</svg>`}var _=Pa;D("style-candles",_('<path d="M4.5 2v2M4.5 12v2M11.5 2v1.5M11.5 11v3"/><rect x="2.8" y="4" width="3.4" height="8" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="9.8" y="3.5" width="3.4" height="7.5" rx="0.6" fill="currentColor"/>'));D("style-bars",_('<path d="M4.5 2.5v11M2.5 5h2M4.5 11h2"/><path d="M11.5 2.5v11M9.5 4.5h2M11.5 10.5h2"/>'));D("style-line",_('<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/>'));D("style-area",_('<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/><path d="M1.5 11.5 5.5 7l3 2.5 5-6V13.5h-12z" fill="currentColor" fill-opacity="0.25" stroke="none"/>'));D("style-baseline",_('<path d="M1.5 8h13" stroke-dasharray="2 2"/><path d="M2.5 8 5.25 4.5 8 8h-5.5z" fill="currentColor" fill-opacity="0.25" stroke="none"/><path d="M2.5 8 5.25 4.5 8 8"/><path d="M8 8l2.75 3.5L13.5 8h-5.5z" fill="currentColor" fill-opacity="0.25" stroke="none"/><path d="M8 8l2.75 3.5L13.5 8"/>'));D("style-heikinashi",_('<path d="M4.5 12v2M11.5 2v2"/><rect x="2.8" y="5" width="3.4" height="7" rx="0.6" fill="currentColor" fill-opacity="0.25"/><rect x="9.8" y="4" width="3.4" height="7" rx="0.6" fill="currentColor"/>'));D("indicators",_('<path d="M1.5 12.5 5 7l2.5 3.5L11 4l3.5 5"/><circle cx="11" cy="4" r="1.4" fill="currentColor" stroke="none"/>'));D("undo",_('<path d="M6.2 9.5 2.7 6l3.5-3.5"/><path d="M2.7 6h6.8a3.65 3.65 0 0 1 0 7.3H7.5"/>'));D("redo",_('<path d="M9.8 9.5 13.3 6 9.8 2.5"/><path d="M13.3 6H6.5a3.65 3.65 0 0 0 0 7.3h2"/>'));D("objects",_('<path d="M8 1.8 14 5 8 8.2 2 5z"/><path d="M2 8l6 3.2L14 8" opacity="0.7"/><path d="M2 11l6 3.2 6-3.2" opacity="0.4"/>'));D("clock",_('<circle cx="8" cy="8" r="6.2"/><path d="M8 4.8V8l2.4 1.6"/>'));D("datawindow",_('<rect x="1.8" y="2.5" width="12.4" height="11" rx="1.5"/><path d="M4.5 5.5h4M4.5 8h7M4.5 10.5h5.5"/>'));D("camera",_('<path d="M5.5 4 6.5 2.5h3L10.5 4h3A1 1 0 0 1 14.5 5v7.5a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z"/><circle cx="8" cy="8.5" r="2.6"/>'));D("gear",_('<path d="M6.55 1.4h2.9l.32 1.72c.48.14.92.38 1.3.7l1.66-.55 1.45 2.5-1.35 1.1c.08.34.12.7.12 1.07s-.04.73-.12 1.07l1.35 1.1-1.45 2.5-1.66-.55a4.3 4.3 0 0 1-1.3.7L9.45 14.6h-2.9l-.32-1.72a4.3 4.3 0 0 1-1.3-.7l-1.66.55-1.45-2.5 1.35-1.1A4.4 4.4 0 0 1 3.05 7.94c0-.37.04-.73.12-1.07l-1.35-1.1 1.45-2.5 1.66.55c.38-.32.82-.56 1.3-.7L6.55 1.4z"/><circle cx="8" cy="8" r="2.2"/>'));D("search",_('<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3.5 3.5"/>'));D("bell",_('<path d="M8 2a4 4 0 0 0-4 4v2.5L2.5 11v1h11v-1L12 8.5V6a4 4 0 0 0-4-4z"/><path d="M6.5 13.5a1.5 1.5 0 0 0 3 0"/>'));D("market-open",I('<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>'));D("market-pre",I('<path d="M12 2v8"/><path d="m4.93 10.93 1.41 1.41"/><path d="M2 18h2"/><path d="M20 18h2"/><path d="m19.07 10.93-1.41 1.41"/><path d="M22 22H2"/><path d="m16 6-4 4-4-4"/><path d="M16 18a4 4 0 0 0-8 0"/>'));D("market-post",I('<path d="M12 10V2"/><path d="m4.93 10.93 1.41 1.41"/><path d="M2 18h2"/><path d="M20 18h2"/><path d="m19.07 10.93-1.41 1.41"/><path d="M22 22H2"/><path d="m16 18-4-4-4 4"/><path d="M16 6a4 4 0 0 0-8 0"/>'));D("market-closed",I('<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>'));D("market-holiday",I('<path d="m10 20-1.25-2.5L6 16"/><path d="M10 4 8.75 6.5 6 8"/><path d="m14 20 1.25-2.5L18 16"/><path d="m14 4 1.25 2.5L18 8"/><path d="m17 10-5 5-5-5"/><path d="M4 12h16"/>'));D("chevron-right",_('<path d="m6 3.5 4.5 4.5L6 12.5"/>'));D("chevron-left",_('<path d="M10 3.5 5.5 8l4.5 4.5"/>'));D("chevron-down",_('<path d="M3.5 6 8 10.5 12.5 6"/>'));D("chevron-up",_('<path d="M3.5 10 8 5.5 12.5 10"/>'));D("chevrons-right",_('<path d="m4 3.5 4.5 4.5L4 12.5"/><path d="m8.5 3.5 4.5 4.5-4.5 4.5"/>'));D("chevrons-left",_('<path d="M12 3.5 7.5 8l4.5 4.5"/><path d="M7.5 3.5 3 8l4.5 4.5"/>'));D("check",_('<path d="m2.8 8.4 3.4 3.4 7-7.6"/>'));D("close",_('<path d="m3.8 3.8 8.4 8.4M12.2 3.8l-8.4 8.4"/>'));D("eye",_('<path d="M1.5 8s2.5-5.4 6.5-5.4S14.5 8 14.5 8 12 13.4 8 13.4 1.5 8 1.5 8z"/><circle cx="8" cy="8" r="1.8"/>'));D("eye-off",_('<path d="M1.5 8s2.5-5.4 6.5-5.4S14.5 8 14.5 8 12 13.4 8 13.4 1.5 8 1.5 8z" opacity="0.45"/><path d="m3 13 10-10"/>'));D("lock",_('<rect x="3.2" y="7" width="9.6" height="6.6" rx="1.2"/><path d="M5.6 7V5.2a2.4 2.4 0 0 1 4.8 0V7"/>'));D("unlock",_('<rect x="3.2" y="7" width="9.6" height="6.6" rx="1.2"/><path d="M5.6 7V5.2a2.4 2.4 0 0 1 4.7-.7"/>'));D("trash",_('<path d="M2.5 4.3h11M6.2 4.3V3.1a1 1 0 0 1 1-1h1.6a1 1 0 0 1 1 1v1.2M4.2 4.3l.5 9.1a1.15 1.15 0 0 0 1.15 1.1h4.3a1.15 1.15 0 0 0 1.15-1.1l.5-9.1M6.5 7v4.5M9.5 7v4.5"/>'));D("group",_('<path d="M1.8 4.5V2.4a.6.6 0 0 1 .6-.6h2.1M11.5 1.8h2.1a.6.6 0 0 1 .6.6v2.1M14.2 11.5v2.1a.6.6 0 0 1-.6.6h-2.1M4.5 14.2H2.4a.6.6 0 0 1-.6-.6v-2.1"/><rect x="4" y="4" width="4.2" height="4.2" rx="0.7"/><rect x="7.8" y="7.8" width="4.2" height="4.2" rx="0.7"/>'));D("ungroup",_('<rect x="1.6" y="1.6" width="6.2" height="6.2" rx="0.9"/><rect x="8.2" y="8.2" width="6.2" height="6.2" rx="0.9" stroke-dasharray="2 1.5"/>'));D("clone",_('<rect x="5.5" y="5.5" width="9" height="9" rx="1.2"/><path d="M11 5.5v-3a1 1 0 0 0-1-1H2.5a1 1 0 0 0-1 1V10a1 1 0 0 0 1 1h3"/>'));D("arrow-up",_('<path d="M8 13.2V3M4.2 6.8 8 3l3.8 3.8"/>'));D("arrow-down",_('<path d="M8 2.8V13M4.2 9.2 8 13l3.8-3.8"/>'));D("move-vertical",_('<path d="M8 2.5v11M5 5.5 8 2.5l3 3M5 10.5l3 3 3-3"/>'));D("move",_('<path d="M8 1.8v12.4M1.8 8h12.4M5.6 4.2 8 1.8l2.4 2.4M5.6 11.8 8 14.2l2.4-2.4M4.2 5.6 1.8 8l2.4 2.4M11.8 5.6 14.2 8l-2.4 2.4"/>'));D("pen",_('<path d="m10.8 2.2 3 3-8 8-3.6.6.6-3.6z"/><path d="m9.2 3.8 3 3"/>'));D("wave",_('<path d="M1.5 10.4c1.6 0 1.9-4.8 3.4-4.8s1.8 4.8 3.4 4.8 1.8-4.8 3.4-4.8 1.6 4.8 2.8 4.8"/>'));D("folder-plus",_('<path d="M1.6 4.4a1 1 0 0 1 1-1h2.7l1.3 1.7h6.8a1 1 0 0 1 1 1v6.5a1 1 0 0 1-1 1h-10.8a1 1 0 0 1-1-1z"/><path d="M8 7.6v3.6M6.2 9.4h3.6"/>'));D("folder-minus",_('<path d="M1.6 4.4a1 1 0 0 1 1-1h2.7l1.3 1.7h6.8a1 1 0 0 1 1 1v6.5a1 1 0 0 1-1 1h-10.8a1 1 0 0 1-1-1z"/><path d="M6.2 9.4h3.6"/>'));D("collapse",_('<path d="M3 8h10"/>'));D("expand",_('<rect x="2.2" y="2.2" width="11.6" height="11.6" rx="1.4"/><path d="M8 5.4v5.2M5.4 8h5.2"/>'));D("maximize",_('<path d="M2.5 6V3a.5.5 0 0 1 .5-.5h3M10 2.5h3a.5.5 0 0 1 .5.5v3M13.5 10v3a.5.5 0 0 1-.5.5h-3M6 13.5H3a.5.5 0 0 1-.5-.5v-3"/>'));D("restore",_('<path d="M6.2 2.5v3.7H2.5M9.8 13.5V9.8h3.7M13.5 6.2H9.8V2.5M2.5 9.8h3.7v3.7"/>'));D("star",_('<path d="M8 2.2l1.75 3.55 3.9.55-2.8 2.75.65 3.9L8 11.1l-3.5 1.85.65-3.9-2.8-2.75 3.9-.55z"/>'));D("star-filled",_('<path d="M8 2.2l1.75 3.55 3.9.55-2.8 2.75.65 3.9L8 11.1l-3.5 1.85.65-3.9-2.8-2.75 3.9-.55z"/>','fill="currentColor"'));D("grip",_('<circle cx="6" cy="3.5" r="1"/><circle cx="10" cy="3.5" r="1"/><circle cx="6" cy="8" r="1"/><circle cx="10" cy="8" r="1"/><circle cx="6" cy="12.5" r="1"/><circle cx="10" cy="12.5" r="1"/>','fill="currentColor" stroke="none"'));D("kebab",_('<circle cx="8" cy="3.2" r="1.2"/><circle cx="8" cy="8" r="1.2"/><circle cx="8" cy="12.8" r="1.2"/>','fill="currentColor" stroke="none"'));D("burger",_('<path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11"/>'));D("reset",_('<rect x="6" y="6" width="4" height="4" rx="0.8"/><path d="M2.2 8a5.8 5.8 0 1 0 1.9-4.3L2.2 5.3"/><path d="M2.2 2.2v3.1h3.1"/>'));D("pane-collapse",_('<path d="M2.6 9.4h4v4M13.4 6.6h-4v-4"/><path d="m9.4 6.6 4.2-4.2M2.4 13.6l4.2-4.2"/>'));D("pane-expand",_('<path d="M9.8 2.4h3.8v3.8M6.2 13.6H2.4V9.8"/><path d="m13.6 2.4-4.4 4.4M2.4 13.6l4.4-4.4"/>'));D("cursor",I('<path d="M5 3l6 16 2-6 6-2z"/>','fill="currentColor" stroke="none"'));D("ruler",I('<path d="M21.3 15.3 8.7 2.7a1 1 0 0 0-1.4 0L2.7 7.3a1 1 0 0 0 0 1.4l12.6 12.6a1 1 0 0 0 1.4 0l4.6-4.6a1 1 0 0 0 0-1.4Z"/><path d="m7.5 10.5 2 2"/><path d="m10.5 7.5 2 2"/><path d="m13.5 4.5 2 2"/><path d="m4.5 13.5 2 2"/>'));D("magnet",I('<path d="m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15"/><path d="m5 8 4 4"/><path d="m12 15 4 4"/>'));D("eraser",I('<path d="m7 21-4.3-4.3a1 1 0 0 1 0-1.4L13 5a2 2 0 0 1 2.8 0l4.2 4.2a2 2 0 0 1 0 2.8L12 20"/><path d="M22 21H7"/><path d="m5 11 9 9"/>'));D("pen-lock",I('<path d="M13.8 4.2a2.1 2.1 0 0 1 3 3L8.5 15.5l-3.5 1 1-3.5Z"/><rect x="13" y="14.5" width="8" height="6" rx="1.2"/><path d="M15 14.5v-1.6a2 2 0 0 1 4 0v1.6"/>'));D("pen-sync",I('<path d="M13.8 4.2a2.1 2.1 0 0 1 3 3L8.5 15.5l-3.5 1 1-3.5Z"/><rect x="12.5" y="13.5" width="6" height="4.8" rx="1"/><path d="M15.5 18.3v1a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-2.8a1 1 0 0 0-1-1h-1"/>'));D("brush",I('<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>'));D("bucket",I('<path d="m18.5 11.5-7-7L4 12a1.8 1.8 0 0 0 0 2.5l5 5a1.8 1.8 0 0 0 2.5 0Z"/><path d="m5 5 4 4"/><path d="M3.5 13.5h13"/><path d="M21 17.5c0 1.1-.9 2-2 2s-2-.9-2-2c0-1 1.2-1.7 2-3 .8 1.3 2 2 2 3Z"/>'));D("type",I('<path d="M5 6V4.5h14V6"/><path d="M12 4.5v15"/><path d="M9.5 19.5h5"/>'));D("bold",I('<path d="M7 5h6a3.5 3.5 0 0 1 0 7H7Z"/><path d="M7 12h7a3.5 3.5 0 0 1 0 7H7Z"/>','stroke-width="2.4"'));D("italic",I('<path d="M15 5h-5M14 19H9M14.5 5 10 19"/>','stroke-width="2.2"'));D("price-delta",I('<path d="M12 4v16"/><path d="M8 8l4-4 4 4"/><path d="M8 16l4 4 4-4"/>'));D("date-delta",I('<path d="M4 12h16"/><path d="M8 8l-4 4 4 4"/><path d="M16 8l4 4-4 4"/>'));D("bring-front",I('<rect x="8.5" y="8.5" width="7" height="7" rx="1.5"/><path d="M4.5 10.5V6a1.5 1.5 0 0 1 1.5-1.5h4.5"/><path d="M19.5 13.5V18a1.5 1.5 0 0 1-1.5 1.5h-4.5"/>'));D("send-back",I('<rect x="8.5" y="8.5" width="7" height="7" rx="1.5" fill="currentColor" stroke="none" opacity="0.35"/><path d="M4.5 10.5V6a1.5 1.5 0 0 1 1.5-1.5h4.5"/><path d="M19.5 13.5V18a1.5 1.5 0 0 1-1.5 1.5h-4.5"/><rect x="8.5" y="8.5" width="7" height="7" rx="1.5"/>'));D("r-squared",'<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" stroke="none"><text x="2.5" y="17.5" font-size="14" font-family="serif">R\xB2</text></svg>');D("bands",I('<path d="M3 6h18"/><path d="M3 18h18"/><path d="M3 12h18" stroke-dasharray="3 3"/>'));D("dedekind",I('<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0"/><path d="M8 20a4 4 0 0 1 8 0"/><path d="M12 4v16"/>'));D("sonic",I('<circle cx="15" cy="12" r="4"/><circle cx="12" cy="12" r="2.5"/><path d="M8 5v14"/>'));D("supersonic",I('<circle cx="16" cy="12" r="3.5"/><path d="M6 12 15 6M6 12 15 18"/>'));var fe=[{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"}],O=[{path:"style.lineColor",label:"Line color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Line width",kind:"number",min:1,max:10,step:1,group:"line"},{path:"style.lineStyle",label:"Line style",kind:"lineStyle",options:fe,group:"line"}],Z=[{path:"style.fillColor",label:"Fill color",kind:"color",group:"fill"}],Te=[{value:"small",label:"Small"},{value:"normal",label:"Normal"},{value:"large",label:"Large"},{value:"huge",label:"Huge"}],F=[{path:"text.value",label:"Text",kind:"text",group:"text"},{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Te,group:"text"},{path:"text.bold",label:"Bold",kind:"boolean",group:"text"},{path:"text.italic",label:"Italic",kind:"boolean",group:"text"}];function K(s,e,t,n,r,i){let o=r-t,a=i-n,l=o*o+a*a;if(l<=1e-9)return Math.hypot(s-t,e-n);let c=((s-t)*o+(e-n)*a)/l;return c=c<0?0:c>1?1:c,Math.hypot(s-(t+c*o),e-(n+c*a))}function Ht(s,e,t){let n=1/0;for(let r=1;r<t.length;r+=1){let i=t[r-1],o=t[r],a=K(s,e,i[0],i[1],o[0],o[1]);a<n&&(n=a);}return n}function de(s,e,t,n,r,i,o=0){let a=Math.min(t,r)-o,l=Math.max(t,r)+o,c=Math.min(n,i)-o,d=Math.max(n,i)+o;return s>=a&&s<=l&&e>=c&&e<=d}function ke(s,e,t){let n=false;for(let r=0,i=t.length-1;r<t.length;i=r,r+=1){let o=t[r],a=t[i];o[1]>e!=a[1]>e&&s<(a[0]-o[0])*(e-o[1])/(a[1]-o[1])+o[0]&&(n=!n);}return n}function Oo(s,e,t,n,r,i,o,a){let l=t-s,c=n-e,d=o-r,h=a-i,u=d*c-h*l;if(Math.abs(u)<1e-9)return null;let p=((i-e)*l-(r-s)*c)/u;return p<0||p>1?null:[r+p*d,i+p*h]}function N(s,e,t,n=6){for(let r=0;r<t.length;r+=1){let i=t[r];if(Math.hypot(s-i[0],e-i[1])<=n)return r}return -1}function re(s,e,t,n,r,i,o){if(r==="none")return [s,e,t,n];let a=t-s,l=r==="left"||r==="both",c=r==="right"||r==="both";if(Math.abs(a)<1e-6){if(l&&c)return [s,0,t,o];let m=n>=e;return c?m?[s,e,t,o]:[s,e,t,0]:m?[s,0,t,n]:[s,o,t,n]}let d=(n-e)/a,h=m=>e+d*(m-s),u=l?-2:Math.min(s,t),p=c?i+2:Math.max(s,t);return [u,h(u),p,h(p)]}var xr=class extends B{constructor(){super(...arguments);this.type="trendline";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:[t.xOf(n.time),i,t.xOf(r.time),o]}hitTest(t,n,r,i){let o=this.pixels(r);return o!=null&&K(t,n,o[0],o[1],o[2],o[3])<=i}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pixels(t);if(!n)return null;let r=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]);return {x:r,y:i,w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,{path:"style.arrowRight",label:"Arrow",kind:"boolean",group:"line"},...F]}}};var wr=class extends B{constructor(){super(...arguments);this.type="hline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"y"}]}}y(t){let n=this.anchors[0];return n?t.yOf(n.price,this.paneId):null}hitTest(t,n,r,i){let o=this.y(r);return o!=null&&Math.abs(n-o)<=i}handlePoints(t){let n=this.anchors[0],r=this.y(t);return !n||r==null?[]:[[t.xOf(n.time),r]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.y(t);return n==null?null:{x:0,y:n-1,w:t.width,h:2}}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){return null}schema(){return {fields:[...O,...F]}}};var Sr=class extends B{constructor(){super(...arguments);this.type="ray";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:[t.xOf(n.time),i,t.xOf(r.time),o]}hitTest(t,n,r,i){let o=this.pixels(r);if(!o)return false;let[a,l,c,d]=re(o[0],o[1],o[2],o[3],"right",r.width,r.height);return K(t,n,a,l,c,d)<=i}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pixels(t);return n?{x:Math.min(n[0],n[2]),y:Math.min(n[1],n[3]),w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,...F]}}};var Je=class extends B{anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);return r==null||i==null?null:[e.xOf(t.time),r,e.xOf(n.time),i]}hitTest(e,t,n,r){let i=this.pixels(n);return i!=null&&K(e,t,i[0],i[1],i[2],i[3])<=r}handlePoints(e){let t=this.pixels(e);return t?[[t[0],t[1]],[t[2],t[3]]]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.pixels(e);return t?{x:Math.min(t[0],t[2]),y:Math.min(t[1],t[3]),w:Math.abs(t[2]-t[0]),h:Math.abs(t[3]-t[1])}:null}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[...O,...F]}}};var Cr=class extends Je{constructor(){super(...arguments);this.type="extendedline";}hitTest(t,n,r,i){let o=this.pixels(r);if(!o)return false;let[a,l,c,d]=re(o[0],o[1],o[2],o[3],"both",r.width,r.height);return K(t,n,a,l,c,d)<=i}timeExtent(){return null}};var Tr=class extends B{constructor(){super(...arguments);this.type="vline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"x"}]}}x(t){let n=this.anchors[0];return n?t.xOf(n.time):null}hitTest(t,n,r,i){let o=this.x(r);return o!=null&&Math.abs(t-o)<=i}handlePoints(t){let n=this.anchors[0],r=this.x(t);if(!n||r==null)return [];let i=t.yOf(n.price,this.paneId);return i==null?[]:[[r,i]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.x(t);return n==null?null:{x:n-1,y:0,w:2,h:t.height}}priceRange(){return null}schema(){return {fields:[...O,...F]}}};var Mr=class extends B{constructor(){super(...arguments);this.type="hray";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}pt(t){let n=this.anchors[0];if(!n)return null;let r=t.yOf(n.price,this.paneId);return r==null?null:[t.xOf(n.time),r]}hitTest(t,n,r,i){let o=this.pt(r);return o!=null&&K(t,n,o[0],o[1],r.width,o[1])<=i}handlePoints(t){let n=this.pt(t);return n?[n]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pt(t);return n?{x:n[0],y:n[1]-1,w:Math.max(0,t.width-n[0]),h:2}:null}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){let t=this.anchors[0];return t?{min:t.time,max:Number.POSITIVE_INFINITY}:null}schema(){return {fields:[...O,...F]}}};var Lr=class extends B{constructor(){super(...arguments);this.type="crossline";}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}pt(t){let n=this.anchors[0];if(!n)return null;let r=t.yOf(n.price,this.paneId);return r==null?null:[t.xOf(n.time),r]}hitTest(t,n,r,i){let o=this.pt(r);return o!=null&&(Math.abs(n-o[1])<=i||Math.abs(t-o[0])<=i)}handlePoints(t){let n=this.pt(t);return n?[n]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pt(t);return n?{x:n[0]-1,y:n[1]-1,w:2,h:2}:null}priceRange(){let t=this.anchors[0];return t?{min:t.price,max:t.price}:null}timeExtent(){return null}schema(){return {fields:[...O,...F]}}};var Pr=class extends Je{constructor(){super(...arguments);this.type="infoline";}};var Er=class extends Je{constructor(){super(...arguments);this.type="trendangle";}};var kr=class extends B{constructor(){super(...arguments);this.type="box";}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}rect(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:{x1:t.xOf(n.time),y1:i,x2:t.xOf(r.time),y2:o}}hitTest(t,n,r,i){let o=this.rect(r);return o?this.style.fillColor&&de(t,n,o.x1,o.y1,o.x2,o.y2)?true:[[o.x1,o.y1,o.x2,o.y1],[o.x2,o.y1,o.x2,o.y2],[o.x2,o.y2,o.x1,o.y2],[o.x1,o.y2,o.x1,o.y1]].some(l=>K(t,n,l[0],l[1],l[2],l[3])<=i):false}handlePoints(t){let n=this.rect(t);return n?[[n.x1,n.y1],[n.x2,n.y2]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.rect(t);return n?{x:Math.min(n.x1,n.x2),y:Math.min(n.y1,n.y2),w:Math.abs(n.x2-n.x1),h:Math.abs(n.y2-n.y1)}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O.map(t=>({...t,label:t.label.replace("Line","Border")})),{path:"style.fillColor",label:"Fill color",kind:"color",group:"fill"},...F]}}};var qd={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},Qe=class extends B{defaultLabel(){return "Text"}labelText(){return this.text?.value??this.defaultLabel()}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}box(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let r=qd[this.text?.size??"normal"]??14,i=this.labelText().split(`
2
+ `),o=Math.max(1,...i.map(a=>a.length));return {x:e.xOf(t.time),y:n,w:Math.max(12,o*r*.6)+8,h:i.length*r*1.4+4}}hitTest(e,t,n,r){let i=this.box(n);return i!=null&&de(e,t,i.x,i.y,i.x+i.w,i.y+i.h)}handlePoints(e){let t=this.anchors[0],n=t?e.yOf(t.price,this.paneId):null;return t&&n!=null?[[e.xOf(t.time),n]]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){return this.box(e)}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}};var He=class extends Qe{constructor(t){super(t);this.type="text";this.text||(this.text={...Ne(),size:"large"});}schema(){return {fields:[...F],textIsContent:true}}};var dt=class extends Qe{constructor(t){super(t);this.type="note";this.text||(this.text=Ne("Note"));}defaultLabel(){return "Note"}schema(){return {fields:[...O,...Z,...F],textIsContent:true}}};var ht=class extends Qe{constructor(){super(...arguments);this.type="pricelabel";}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return {fields:[...O,...Z,...F.filter(t=>t.path!=="text.value")]}}};var Zd={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},we=class extends B{constructor(e){super(e),this.text||(this.text=Ne(this.defaultLabel()));}defaultLabel(){return "Callout"}labelText(){return this.text?.value??this.defaultLabel()}anchorSchema(){return {min:2,max:2,slots:[{role:"target",free:"both"},{role:"box",free:"both"}]}}box(e){let t=this.anchors[1];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let r=Zd[this.text?.size??"normal"]??14,i=this.labelText().split(`
3
+ `),o=Math.max(1,...i.map(c=>c.length)),a=Math.max(20,o*r*.6)+16,l=i.length*r*1.4+12;return {x:e.xOf(t.time)-a/2,y:n-l/2,w:a,h:l}}points(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);return r==null||i==null?null:[[e.xOf(t.time),r],[e.xOf(n.time),i]]}hitTest(e,t,n,r){let i=this.box(n);if(i&&de(e,t,i.x,i.y,i.x+i.w,i.y+i.h,r))return true;let o=this.points(n);return o!=null&&K(e,t,o[0][0],o[0][1],o[1][0],o[1][1])<=r}handlePoints(e){let t=this.points(e);return t?[t[0]]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}translateBody(e,t,n){let r=n[0],i=n[1];return !r||!i?n.map(o=>({time:o.time+e,price:o.price+t})):[{time:r.time,price:r.price},{time:i.time+e,price:i.price+t}]}bounds(e){return this.box(e)}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[...O,...Z,...F],textIsContent:true}}};var Ie=class extends we{constructor(){super(...arguments);this.type="callout";}};var ut=class extends we{constructor(){super(...arguments);this.type="pricenote";}defaultLabel(){return ""}labelText(){let t=this.anchors[0]?.price;return t==null?"0.00":t.toFixed(2)}schema(){return {fields:[...O,...Z,...F.filter(t=>t.path!=="text.value")]}}};var pt=class extends we{constructor(){super(...arguments);this.type="comment";}defaultLabel(){return "Comment"}};var mt=class extends we{constructor(){super(...arguments);this.type="signpost";}defaultLabel(){return "Signpost"}};var J=class extends B{hitTest(e,t,n,r){let i=this.geometry(n);return i?this.style.fillColor&&i.fill&&ke(e,t,i.fill)?true:i.segments.some(o=>K(e,t,o[0],o[1],o[2],o[3])<=r):false}handlePoints(e){let t=[];for(let n of this.anchors){let r=e.yOf(n.price,this.paneId);if(r==null)return [];t.push([e.xOf(n.time),r]);}return t}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),r=t.map(a=>a[1]),i=Math.min(...n),o=Math.min(...r);return {x:i,y:o,w:Math.max(...n)-i,h:Math.max(...r)-o}}};var Ir=class extends J{constructor(){super(...arguments);this.type="parallelchannel";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"y"}]}}offset(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];return !t||!n||!r?0:r.price-(t.price+n.price)/2}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return [];let a=[[t.xOf(n.time),i],[t.xOf(r.time),o]],l=this.anchors[2];if(l){let c=t.yOf(l.price,this.paneId);c!=null&&a.push([t.xOf((n.time+r.time)/2),c]);}return a}timeExtent(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.time,n.time),max:Math.max(t.time,n.time)}}geometry(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=this.offset(),o=t.xOf(n.time),a=t.xOf(r.time),l=t.yOf(n.price,this.paneId),c=t.yOf(r.price,this.paneId),d=t.yOf(n.price+i,this.paneId),h=t.yOf(r.price+i,this.paneId);return l==null||c==null||d==null||h==null?null:{segments:[[o,l,a,c],[o,d,a,h]],fill:[[o,l],[a,c],[a,h],[o,d]]}}priceRange(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=this.offset(),i=[t.price,n.price,t.price+r,n.price+r],o=this.anchors[2];return o&&i.push(o.price),{min:Math.min(...i),max:Math.max(...i)}}schema(){return {fields:[...O,...Z,...F]}}};var Rr=class extends J{constructor(){super(...arguments);this.type="disjointchannel";}anchorSchema(){return {min:4,max:4,slots:[{role:"top1",free:"both"},{role:"top2",free:"both"},{role:"bot1",free:"both"},{role:"bot2",free:"both"}]}}seg(t,n,r){let i=this.anchors[t],o=this.anchors[n];if(!i||!o)return null;let a=r.yOf(i.price,this.paneId),l=r.yOf(o.price,this.paneId);return a==null||l==null?null:[r.xOf(i.time),a,r.xOf(o.time),l]}geometry(t){let n=this.seg(0,1,t),r=this.seg(2,3,t),i=[n,r].filter(a=>a!=null);if(i.length===0)return null;let o=n&&r?[[n[0],n[1]],[n[2],n[3]],[r[2],r[3]],[r[0],r[1]]]:null;return {segments:i,fill:o}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...Z,...F]}}};var Dr=class extends J{constructor(){super(...arguments);this.type="flattopbottom";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"flat",free:"y"}]}}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return [];let a=[[t.xOf(n.time),i],[t.xOf(r.time),o]],l=this.anchors[2];if(l){let c=t.yOf(l.price,this.paneId);c!=null&&a.push([t.xOf((n.time+r.time)/2),c]);}return a}timeExtent(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.time,n.time),max:Math.max(t.time,n.time)}}geometry(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.xOf(n.time),o=t.xOf(r.time),a=t.yOf(n.price,this.paneId),l=t.yOf(r.price,this.paneId);if(a==null||l==null)return null;let c=this.anchors[2];if(!c)return {segments:[[i,a,o,l]],fill:null};let d=t.yOf(c.price,this.paneId);return d==null?null:{segments:[[i,a,o,l],[i,d,o,d]],fill:[[i,a],[o,l],[o,d],[i,d]]}}priceRange(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=[t.price,n.price],i=this.anchors[2];return i&&r.push(i.price),{min:Math.min(...r),max:Math.max(...r)}}schema(){return {fields:[...O,...Z,...F]}}};var Jd=2;function Ea(){return {midColor:he,midStyle:"solid",upperColor:q,upperStyle:"solid",lowerColor:X,lowerStyle:"solid",upperFill:`${q}26`,lowerFill:`${X}26`,showR2:true}}function ka(s){let e=s.length;if(e<2)return null;let t=0,n=0,r=0,i=0,o=0;for(let m=0;m<e;m+=1){let f=s[m].close;t+=m,n+=f,r+=m*f,i+=m*m,o+=f*f;}let a=e*i-t*t,l=a===0?0:(e*r-t*n)/a,c=(n-l*t)/e,d=0;for(let m=0;m<e;m+=1){let f=s[m].close-(c+l*m);d+=f*f;}let h=Math.sqrt(d/e),u=Math.sqrt(a*(e*o-n*n)),p=u===0?0:(e*r-t*n)/u;return {t0:s[0].time,t1:s[e-1].time,mid0:c,mid1:c+l*(e-1),dev:Jd*h,r2:Math.max(0,Math.min(1,p*p)),n:e}}var ze=class extends B{constructor(t){super(t);this.type="regressionchannel";this.cachedRange=null;this.reg||(this.reg=Ea());}anchorSchema(){return {min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}fit(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=Math.min(n.time,r.time),o=Math.max(n.time,r.time),a=t.barsInRange?.(i,o)??null,l=a?ka(a):null;return l&&(this.cachedRange={min:Math.min(l.mid0,l.mid1)-l.dev,max:Math.max(l.mid0,l.mid1)+l.dev}),l}layout(t){let n=this.fit(t);if(!n)return null;let r=t.yOf(n.mid0,this.paneId),i=t.yOf(n.mid1,this.paneId),o=t.yOf(n.mid0+n.dev,this.paneId),a=t.yOf(n.mid1+n.dev,this.paneId),l=t.yOf(n.mid0-n.dev,this.paneId),c=t.yOf(n.mid1-n.dev,this.paneId);return r==null||i==null||o==null||a==null||l==null||c==null?null:{x0:t.xOf(n.t0),x1:t.xOf(n.t1),midY0:r,midY1:i,upperY0:o,upperY1:a,lowerY0:l,lowerY1:c,r2:n.r2,showR2:this.reg.showR2}}band(t){let n=this.layout(t);return n?[[n.x0,n.upperY0],[n.x1,n.upperY1],[n.x1,n.lowerY1],[n.x0,n.lowerY0]]:null}hitTest(t,n,r,i){let o=this.layout(r);if(!o)return false;let a=[[o.x0,o.upperY0],[o.x1,o.upperY1],[o.x1,o.lowerY1],[o.x0,o.lowerY0]];return ke(t,n,a)?true:[[o.x0,o.midY0,o.x1,o.midY1],[o.x0,o.upperY0,o.x1,o.upperY1],[o.x0,o.lowerY0,o.x1,o.lowerY1]].some(c=>K(t,n,c[0],c[1],c[2],c[3])<=i)}handlePoints(t){let n=this.layout(t);if(n)return [[n.x0,n.midY0],[n.x1,n.midY1]];let r=[];for(let i of this.anchors){let o=t.yOf(i.price,this.paneId);if(o==null)return [];r.push([t.xOf(i.time),o]);}return r}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.band(t);if(!n)return null;let r=n.map(l=>l[0]),i=n.map(l=>l[1]),o=Math.min(...r),a=Math.min(...i);return {x:o,y:a,w:Math.max(...r)-o,h:Math.max(...i)-a}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"reg.midColor",label:"Midline color",kind:"color",group:"line"},{path:"reg.midStyle",label:"Midline style",kind:"lineStyle",group:"line"},{path:"reg.upperColor",label:"Upper line color",kind:"color",group:"line"},{path:"reg.upperStyle",label:"Upper line style",kind:"lineStyle",group:"line"},{path:"reg.lowerColor",label:"Lower line color",kind:"color",group:"line"},{path:"reg.lowerStyle",label:"Lower line style",kind:"lineStyle",group:"line"},{path:"reg.upperFill",label:"Upper fill",kind:"color",group:"fill"},{path:"reg.lowerFill",label:"Lower fill",kind:"color",group:"fill"},{path:"reg.showR2",label:"Show R\xB2",kind:"boolean",group:"behavior"}]}}writeProps(){return {...this.reg}}readProps(t){this.reg={...Ea(),...t};}};var Ia=`${_e}00`;function Ra(){return {midColor:_e,midStyle:"solid",multiplier:1,upperColor:Ia,upperStyle:"solid",lowerColor:Ia,lowerStyle:"solid",bandFill:`${_e}33`}}function Da(s,e){let t=s.length;if(t<1)return null;let n=0;for(let c of s)n+=c.volume>0?c.volume:0;let r=n>0,i=0,o=0,a=0,l=[];for(let c=0;c<t;c+=1){let d=s[c],h=(d.high+d.low+d.close)/3,u=r?Math.max(0,d.volume):1;i+=u,o+=h*u,a+=h*h*u;let p=i>0?o/i:h,m=i>0?Math.max(0,a/i-p*p):0,f=Math.sqrt(m)*e;l.push({time:d.time,mid:p,upper:p+f,lower:p-f});}return l}var ft=class extends B{constructor(t){super(t);this.type="anchoredvwap";this.cachedRange=null;this.cachedExtent=null;this.vwap||(this.vwap=Ra());}anchorSchema(){return {min:1,max:1,slots:[{role:"anchor",free:"x"}]}}series(t){let n=this.anchors[0];if(!n)return null;let r=t.barsInRange?.(n.time,Number.POSITIVE_INFINITY)??null;if(!r||r.length<1)return null;let i=Da(r.map(o=>({time:o.time,high:o.high,low:o.low,close:o.close,volume:o.volume??0})),this.vwap.multiplier);if(i&&i.length>0){let o=1/0,a=-1/0;for(let l of i)l.lower<o&&(o=l.lower),l.upper>a&&(a=l.upper);this.cachedRange={min:o,max:a},this.cachedExtent={min:i[0].time,max:i[i.length-1].time};}return i}layout(t){let n=this.series(t);if(!n)return null;let r=[],i=[],o=[];for(let a of n){let l=t.xOf(a.time),c=t.yOf(a.mid,this.paneId),d=t.yOf(a.upper,this.paneId),h=t.yOf(a.lower,this.paneId);c==null||d==null||h==null||(r.push([l,c]),i.push([l,d]),o.push([l,h]));}return r.length>0?{mid:r,upper:i,lower:o}:null}bandPolygon(t){return [...t.upper,...[...t.lower].reverse()]}hitTest(t,n,r,i){let o=this.layout(r);return o?ke(t,n,this.bandPolygon(o))?true:Fo(t,n,o.mid,i)||Fo(t,n,o.upper,i)||Fo(t,n,o.lower,i):false}handlePoints(t){let n=this.layout(t);if(n&&n.mid.length>0)return [n.mid[0]];let r=this.anchors[0];if(!r)return [];let i=t.yOf(r.price,this.paneId);return i==null?[]:[[t.xOf(r.time),i]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.layout(t);if(!n)return null;let r=[...n.upper,...n.lower],i=r.map(c=>c[0]),o=r.map(c=>c[1]),a=Math.min(...i),l=Math.min(...o);return {x:a,y:l,w:Math.max(...i)-a,h:Math.max(...o)-l}}priceRange(){return this.cachedRange}timeExtent(){return this.cachedExtent}schema(){return {fields:[{path:"vwap.midColor",label:"VWAP color",kind:"color",group:"line"},{path:"vwap.midStyle",label:"VWAP style",kind:"lineStyle",group:"line"},{path:"vwap.multiplier",label:"Band multiplier",kind:"number",min:.5,max:5,step:.5,group:"behavior"},{path:"vwap.upperColor",label:"Upper band color",kind:"color",group:"line"},{path:"vwap.lowerColor",label:"Lower band color",kind:"color",group:"line"},{path:"vwap.bandFill",label:"Band fill",kind:"color",group:"fill"}]}}writeProps(){return {...this.vwap}}readProps(t){this.vwap={...Ra(),...t};}};function Fo(s,e,t,n){for(let r=1;r<t.length;r+=1)if(K(s,e,t[r-1][0],t[r-1][1],t[r][0],t[r][1])<=n)return true;return false}var Qd=`${q}66`,eh=`${X}66`,th=`${q}BF`,nh=`${X}BF`;function Aa(){return {rows:24,valueAreaPct:70,widthPct:35,anchor:"left",upColor:Qd,downColor:eh,vaUpColor:th,vaDownColor:nh,showVah:true,vahColor:he,vahStyle:"solid",showVal:true,valColor:he,valStyle:"solid",showPoc:true,pocColor:void 0,pocStyle:"solid",showDevelopingPoc:false,developingPocColor:ve,developingPocStyle:"dotted",showDevelopingVa:false,developingVaColor:ve,developingVaStyle:"dotted"}}function rh(s,e){return s<0?0:s>=e?e-1:s}function Oa(s,e,t){let n=s.length,r=0,i=0;for(let d=0;d<n;d+=1){let h=s[d].up+s[d].down;r+=h,h>i&&(i=h);}let o=r*Math.min(1,Math.max(0,t)),a=e,l=e,c=i;for(;c<o&&(a>0||l<n-1);){let d=a>0?s[a-1].up+s[a-1].down:-1,h=l<n-1?s[l+1].up+s[l+1].down:-1;h>d?(l+=1,c+=h):(a-=1,c+=d);}return {vaFrom:a,vaTo:l}}function Fa(s,e,t,n){let r=n.volume;if(!(r>0))return;let i=s.length,o=n.close>=n.open?"up":"down",a=new Set;for(let l of [n.open,n.high,n.low,n.close])a.add(rh(Math.floor((l-e)/t),i));for(let l of a)s[l][o]+=r;}function Ba(s){let e=0,t=0;for(let n=0;n<s.length;n+=1){let r=s[n].up+s[n].down;r>e&&(e=r,t=n);}return e>0?{poc:t,maxTotal:e}:null}function Va(s,e,t){let n=1/0,r=-1/0;for(let p of s)p.volume>0&&(p.low<n&&(n=p.low),p.high>r&&(r=p.high));if(!Number.isFinite(n))return null;let i=r>n?Math.max(1,Math.round(e)):1,o=r>n?(r-n)/i:1,a=Array.from({length:i},(p,m)=>({price:n+m*o,up:0,down:0}));for(let p of s)Fa(a,n,o,p);let l=Ba(a);if(!l)return null;let{poc:c,maxTotal:d}=l,{vaFrom:h,vaTo:u}=Oa(a,c,t);return {rows:a,rowH:o,min:n,maxTotal:d,poc:c,vaFrom:h,vaTo:u}}function _a(s,e,t,n){let r=Va(s,e,t);if(!r)return null;if(!n||s.length<1)return {profile:r,developingPoc:[],developingVaHigh:[],developingVaLow:[]};let{min:i,rowH:o}=r,a=r.rows.length,l=Array.from({length:a},(u,p)=>({price:i+p*o,up:0,down:0})),c=[],d=[],h=[];for(let u of s){Fa(l,i,o,u);let p=Ba(l);if(!p)continue;let{poc:m}=p,{vaFrom:f,vaTo:b}=Oa(l,m,t);c.push({time:u.time,price:l[m].price+o/2}),d.push({time:u.time,price:l[b].price+o}),h.push({time:u.time,price:l[f].price});}return {profile:r,developingPoc:c,developingVaHigh:d,developingVaLow:h}}var Re=class extends B{constructor(t){super(t);this.type="fixedrangevp";this.cachedRange=null;this.frvp||(this.frvp=Aa());}anchorSchema(){return {min:2,max:2,slots:[{role:"start",free:"x"},{role:"end",free:"x"}]}}barsInSpan(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=Math.min(n.time,r.time),o=Math.max(n.time,r.time),a=t.barsInRange?.(i,o)??null;return !a||a.length<1?null:a.map(l=>({time:l.time,open:l.open,high:l.high,low:l.low,close:l.close,volume:l.volume??0}))}compute(t){let n=this.barsInSpan(t);if(!n)return null;let r=this.frvp,i=r.showDevelopingPoc||r.showDevelopingVa,o=_a(n,r.rows,r.valueAreaPct/100,i);if(o){let{profile:a}=o;this.cachedRange={min:a.min,max:a.min+a.rowH*a.rows.length};}return o}layout(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=this.compute(t);if(!i)return null;let{profile:o}=i,a=Math.min(n.time,r.time),l=Math.max(n.time,r.time),c=t.xOf(a),d=t.xOf(l),h=Math.abs(d-c),u=Math.max(1,Math.min(100,Math.max(0,this.frvp.widthPct))/100*h),p=this.frvp.anchor==="left",m=p?Math.min(c,d):Math.max(c,d),f=p?1:-1,b=[];for(let C=0;C<=o.rows.length;C+=1){let T=t.yOf(o.min+C*o.rowH,this.paneId);if(T==null)return null;b.push(T);}let g=C=>t.yOf(C,this.paneId),v=o.rows[o.vaTo].price+o.rowH,y=o.rows[o.vaFrom].price,x=o.rows[o.poc].price+o.rowH/2,S=C=>{let T=[];for(let M of C){let E=g(M.price);E!=null&&T.push([t.xOf(M.time),E]);}return T};return {x0:Math.min(c,d),x1:Math.max(c,d),anchorX:m,maxW:u,grow:f,profile:o,yEdges:b,vahY:g(v),valY:g(y),pocY:g(x),developingPoc:S(i.developingPoc),developingVaHigh:S(i.developingVaHigh),developingVaLow:S(i.developingVaLow)}}hitTest(t,n,r,i){let o=this.layout(r);if(!o)return false;let a=o.grow===1?o.anchorX:o.anchorX-o.maxW,l=o.grow===1?o.anchorX+o.maxW:o.anchorX,c=Math.min(o.yEdges[0],o.yEdges[o.yEdges.length-1]),d=Math.max(o.yEdges[0],o.yEdges[o.yEdges.length-1]);if(ke(t,n,[[a,c],[l,c],[l,d],[a,d]]))return true;let h=[[o.x0,o.vahY],[o.x0,o.valY],[o.x0,o.pocY]];for(let[,u]of h)if(u!=null&&K(t,n,o.x0,u,o.x1,u)<=i)return true;for(let u of [o.developingPoc,o.developingVaHigh,o.developingVaLow])for(let p=1;p<u.length;p+=1)if(K(t,n,u[p-1][0],u[p-1][1],u[p][0],u[p][1])<=i)return true;return false}handlePoints(t){let n=this.layout(t);if(n&&n.pocY!=null)return [[n.x0,n.pocY],[n.x1,n.pocY]];let r=[];for(let i of this.anchors){let o=t.yOf(i.price,this.paneId);if(o==null)return [];r.push([t.xOf(i.time),o]);}return r}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.layout(t);if(!n)return null;let r=Math.min(n.x0,n.grow===1?n.anchorX:n.anchorX-n.maxW),i=Math.max(n.x1,n.grow===1?n.anchorX+n.maxW:n.anchorX),o=Math.min(n.yEdges[0],n.yEdges[n.yEdges.length-1]),a=Math.max(n.yEdges[0],n.yEdges[n.yEdges.length-1]);return {x:r,y:o,w:i-r,h:a-o}}priceRange(){if(this.cachedRange)return this.cachedRange;let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[{path:"frvp.rows",label:"Rows",kind:"number",min:1,max:500,step:1,group:"behavior"},{path:"frvp.valueAreaPct",label:"Value Area",kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.widthPct",label:"Width %",kind:"number",min:0,max:100,step:1,group:"behavior"},{path:"frvp.anchor",label:"Anchor",kind:"select",options:[{value:"right",label:"Right"},{value:"left",label:"Left"}],group:"behavior"},{path:"frvp.upColor",label:"Up Volume",kind:"color",group:"fill"},{path:"frvp.downColor",label:"Down Volume",kind:"color",group:"fill"},{path:"frvp.vaUpColor",label:"Value Area Up",kind:"color",group:"fill"},{path:"frvp.vaDownColor",label:"Value Area Down",kind:"color",group:"fill"},{path:"frvp.showVah",label:"VAH",kind:"boolean",group:"line"},{path:"frvp.vahColor",label:"VAH color",kind:"color",group:"line"},{path:"frvp.vahStyle",label:"VAH style",kind:"lineStyle",options:fe,group:"line"},{path:"frvp.showVal",label:"VAL",kind:"boolean",group:"line"},{path:"frvp.valColor",label:"VAL color",kind:"color",group:"line"},{path:"frvp.valStyle",label:"VAL style",kind:"lineStyle",options:fe,group:"line"},{path:"frvp.showPoc",label:"POC",kind:"boolean",group:"line"},{path:"frvp.pocColor",label:"POC color",kind:"color",group:"line"},{path:"frvp.pocStyle",label:"POC style",kind:"lineStyle",options:fe,group:"line"},{path:"frvp.showDevelopingPoc",label:"Developing POC",kind:"boolean",group:"line"},{path:"frvp.developingPocColor",label:"Developing POC color",kind:"color",group:"line"},{path:"frvp.developingPocStyle",label:"Developing POC style",kind:"lineStyle",options:fe,group:"line"},{path:"frvp.showDevelopingVa",label:"Developing VA",kind:"boolean",group:"line"},{path:"frvp.developingVaColor",label:"Developing VA color",kind:"color",group:"line"},{path:"frvp.developingVaStyle",label:"Developing VA style",kind:"lineStyle",options:fe,group:"line"}]}}writeProps(){return {...this.frvp}}readProps(t){this.frvp={...Aa(),...t};}};var Ar=class extends J{constructor(){super(...arguments);this.type="pitchfork";}anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=b=>{let g=t.yOf(b.price,this.paneId);return g==null?null:[t.xOf(b.time),g]},a=o(n),l=o(r),c=o(i);if(!a||!l||!c)return null;let d=(l[0]+c[0])/2,h=(l[1]+c[1])/2,u=d-a[0],p=h-a[1],m=t.width,f=t.height;return {segments:[re(a[0],a[1],d,h,"right",m,f),re(l[0],l[1],l[0]+u,l[1]+p,"right",m,f),re(c[0],c[1],c[0]+u,c[1]+p,"right",m,f),[l[0],l[1],c[0],c[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...F]}}};var zt=class extends J{anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(e){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];if(!t||!n||!r)return null;let i=f=>{let b=e.yOf(f.price,this.paneId);return b==null?null:[e.xOf(f.time),b]},o=i(this.medianStart(t,n,r)),a=i(n),l=i(r);if(!o||!a||!l)return null;let c=(a[0]+l[0])/2,d=(a[1]+l[1])/2,h=c-o[0],u=d-o[1],p=e.width,m=e.height;return {segments:[re(o[0],o[1],c,d,"right",p,m),re(a[0],a[1],a[0]+h,a[1]+u,"right",p,m),re(l[0],l[1],l[0]+h,l[1]+u,"right",p,m),[a[0],a[1],l[0],l[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}schema(){return {fields:[...O,...F]}}};var Or=class extends zt{constructor(){super(...arguments);this.type="schiffpitchfork";}medianStart(t,n){return {time:t.time,price:(t.price+n.price)/2}}};var Fr=class extends zt{constructor(){super(...arguments);this.type="modifiedschiffpitchfork";}medianStart(t,n){return {time:(t.time+n.time)/2,price:(t.price+n.price)/2}}};var Br=class extends J{constructor(){super(...arguments);this.type="insidepitchfork";}anchorSchema(){return {min:3,max:3,slots:[{role:"pivot",free:"both"},{role:"upper",free:"both"},{role:"lower",free:"both"}]}}geometry(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=g=>{let v=t.yOf(g.price,this.paneId);return v==null?null:[t.xOf(g.time),v]},a=o({time:(n.time+r.time)/2,price:(n.price+r.price)/2}),l=o(n),c=o(r),d=o(i);if(!a||!l||!c||!d)return null;let h=(c[0]+d[0])/2,u=(c[1]+d[1])/2,p=d[0]-a[0],m=d[1]-a[1],f=t.width,b=t.height;return {segments:[re(h,u,h+p,u+m,"right",f,b),re(c[0],c[1],c[0]+p,c[1]+m,"right",f,b),re(d[0],d[1],d[0]+p,d[1]+m,"right",f,b),[c[0],c[1],d[0],d[1]],[a[0],a[1],d[0],d[1]],[l[0],l[1],c[0],c[1]]],fill:null}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...F]}}};var Vr=class extends B{constructor(){super(...arguments);this.type="arrow";}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}pixels(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:[t.xOf(n.time),i,t.xOf(r.time),o]}hitTest(t,n,r,i){let o=this.pixels(r);return o!=null&&K(t,n,o[0],o[1],o[2],o[3])<=i}handlePoints(t){let n=this.pixels(t);return n?[[n[0],n[1]],[n[2],n[3]]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.pixels(t);return n?{x:Math.min(n[0],n[2]),y:Math.min(n[1],n[3]),w:Math.abs(n[2]-n[0]),h:Math.abs(n[3]-n[1])}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,{path:"style.arrowRight",label:"Head (end)",kind:"boolean",group:"line"},{path:"style.arrowLeft",label:"Head (start)",kind:"boolean",group:"line"},...F]}}};var Na=48,_r=class extends B{constructor(){super(...arguments);this.type="ellipse";}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}oval(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time);return {cx:(a+l)/2,cy:(i+o)/2,rx:Math.abs(l-a)/2,ry:Math.abs(o-i)/2}}perimeter(t){let n=[];for(let r=0;r<=Na;r+=1){let i=r/Na*Math.PI*2;n.push([t.cx+t.rx*Math.cos(i),t.cy+t.ry*Math.sin(i)]);}return n}hitTest(t,n,r,i){let o=this.oval(r);if(!o||o.rx<1||o.ry<1)return false;let a=((t-o.cx)/o.rx)**2+((n-o.cy)/o.ry)**2;return this.style.fillColor&&a<=1?true:Ht(t,n,this.perimeter(o))<=i}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?[]:[[t.xOf(n.time),i],[t.xOf(r.time),o]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.oval(t);return n?{x:n.cx-n.rx,y:n.cy-n.ry,w:n.rx*2,h:n.ry*2}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,...Z,...F]}}};var Nr=class extends J{constructor(){super(...arguments);this.type="triangle";}anchorSchema(){return {min:3,max:3,slots:[{role:"v1",free:"both"},{role:"v2",free:"both"},{role:"v3",free:"both"}]}}geometry(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=d=>{let h=t.yOf(d.price,this.paneId);return h==null?null:[t.xOf(d.time),h]},a=o(n),l=o(r),c=o(i);return !a||!l||!c?null:{segments:[[a[0],a[1],l[0],l[1]],[l[0],l[1],c[0],c[1]],[c[0],c[1],a[0],a[1]]],fill:[a,l,c]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...Z,...F]}}};var ih=512,et=class extends J{anchorSchema(){return {min:2,max:ih,slots:[]}}geometry(e){let t=[];for(let r of this.anchors){let i=e.yOf(r.price,this.paneId);if(i==null)return null;t.push([e.xOf(r.time),i]);}if(t.length<2)return null;let n=[];for(let r=1;r<t.length;r+=1)n.push([t[r-1][0],t[r-1][1],t[r][0],t[r][1]]);return {segments:n,fill:null}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}schema(){return {fields:[...O,...F]}}};var Hr=class extends et{constructor(){super(...arguments);this.type="polyline";}};var vn=class extends et{placementMode(){return "freehand"}handlePoints(e){return []}bounds(e){let t=[],n=[];for(let o of this.anchors){let a=e.yOf(o.price,this.paneId);a!=null&&(t.push(e.xOf(o.time)),n.push(a));}if(t.length===0)return null;let r=Math.min(...t),i=Math.min(...n);return {x:r,y:i,w:Math.max(...t)-r,h:Math.max(...n)-i}}},zr=class extends vn{constructor(){super(...arguments);this.type="freehand";}};var oh=[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Width",kind:"number",min:4,max:60,step:1,group:"line"}],$r=class extends vn{constructor(){super(...arguments);this.type="highlighter";}schema(){return {fields:oh}}};var Wr=class extends B{constructor(){super(...arguments);this.type="circle";}anchorSchema(){return {min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}geom(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time);return {cx:a,cy:i,r:Math.hypot(l-a,o-i)}}hitTest(t,n,r,i){let o=this.geom(r);if(!o||o.r<1)return false;let a=Math.hypot(t-o.cx,n-o.cy);return this.style.fillColor&&a<=o.r?true:Math.abs(a-o.r)<=i}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?[]:[[t.xOf(n.time),i],[t.xOf(r.time),o]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.geom(t);return n?{x:n.cx-n.r,y:n.cy-n.r,w:n.r*2,h:n.r*2}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,...Z,...F]}}};var Ur=class extends J{constructor(){super(...arguments);this.type="rotatedrect";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"w",free:"both"}]}}px(t,n){let r=this.anchors[n];if(!r)return null;let i=t.yOf(r.price,this.paneId);return i==null?null:[t.xOf(r.time),i]}geometry(t){let n=this.px(t,0),r=this.px(t,1);if(!n||!r)return null;let i=this.px(t,2);if(!i||this.anchors.length<3)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let o=r[0]-n[0],a=r[1]-n[1],l=Math.hypot(o,a);if(l<1e-6)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let c=-a/l,d=o/l,h=(i[0]-n[0])*c+(i[1]-n[1])*d,u=c*h,p=d*h,m=n,f=r,b=[r[0]+u,r[1]+p],g=[n[0]+u,n[1]+p];return {segments:[[m[0],m[1],f[0],f[1]],[f[0],f[1],b[0],b[1]],[b[0],b[1],g[0],g[1]],[g[0],g[1],m[0],m[1]]],fill:[m,f,b,g]}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O.map(t=>({...t,label:t.label.replace("Line","Border")})),...Z,...F]}}};var Gr=class extends et{constructor(){super(...arguments);this.type="path";}};var Ha=40,Yr=class extends J{constructor(){super(...arguments);this.type="arc";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"apex",free:"both"}]}}pinApex(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];t&&n&&r&&(r.time=(t.time+n.time)/2);}onPlaced(){this.pinApex();}constrainHandleDrag(){this.pinApex();}px(t,n){let r=this.anchors[n];if(!r)return null;let i=t.yOf(r.price,this.paneId);return i==null?null:[t.xOf(r.time),i]}geometry(t){let n=this.px(t,0),r=this.px(t,1);if(!n||!r)return null;let i=this.anchors[2];if(!i||this.anchors.length<3)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let o=t.yOf(i.price,this.paneId);if(o==null)return null;let a=(n[0]+r[0])/2,l=(n[1]+r[1])/2,c=(r[0]-n[0])/2,d=(r[1]-n[1])/2,h=Math.hypot(c,d);if(h<1e-6)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let u=-d/h,p=c/h,m=(o-l)*p;m<0&&(u=-u,p=-p);let f=Math.abs(m),b=[];for(let v=0;v<=Ha;v+=1){let y=v/Ha*Math.PI,x=Math.cos(y),S=Math.sin(y);b.push([a+x*c+S*f*u,l+x*d+S*f*p]);}let g=[];for(let v=1;v<b.length;v+=1)g.push([b[v-1][0],b[v-1][1],b[v][0],b[v][1]]);return g.push([b[b.length-1][0],b[b.length-1][1],b[0][0],b[0][1]]),{segments:g,fill:b}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O.map(t=>({...t,label:t.label.replace("Line","Border")})),...Z,...F]}}};var za=40,Xr=class extends J{constructor(){super(...arguments);this.type="curve";}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"control",free:"both"}]}}px(t,n){let r=this.anchors[n];if(!r)return null;let i=t.yOf(r.price,this.paneId);return i==null?null:[t.xOf(r.time),i]}geometry(t){let n=this.px(t,0),r=this.px(t,1);if(!n||!r)return null;let i=this.px(t,2);if(!i||this.anchors.length<3)return {segments:[[n[0],n[1],r[0],r[1]]],fill:null};let o=[];for(let l=0;l<=za;l+=1){let c=l/za,d=1-c;o.push([d*d*n[0]+2*d*c*i[0]+c*c*r[0],d*d*n[1]+2*d*c*i[1]+c*c*r[1]]);}let a=[];for(let l=1;l<o.length;l+=1)a.push([o[l-1][0],o[l-1][1],o[l][0],o[l][1]]);return {segments:a,fill:o}}priceRange(){if(this.anchors.length===0)return null;let t=this.anchors.map(n=>n.price);return {min:Math.min(...t),max:Math.max(...t)}}schema(){return {fields:[...O,...Z,...F]}}};var sh={head:11,headW:9,stemW:3.5,len:22},bt=class extends B{anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}glyphPoints(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);if(n==null)return null;let r=e.xOf(t.time),{head:i,headW:o,stemW:a,len:l}=sh,c=[[0,0],[-o,i],[-a,i],[-a,l],[a,l],[a,i],[o,i]],d=this.dir(),h=([u,p])=>{switch(d){case "up":return [u,p];case "down":return [u,-p];case "left":return [p,u];default:return [-p,u]}};return c.map(u=>{let[p,m]=h(u);return [r+p,n+m]})}hitTest(e,t,n,r){let i=this.glyphPoints(n);return i!=null&&ke(e,t,i)}handlePoints(e){let t=this.anchors[0];if(!t)return [];let n=e.yOf(t.price,this.paneId);return n==null?[]:[[e.xOf(t.time),n]]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.glyphPoints(e);if(!t)return null;let n=t.map(a=>a[0]),r=t.map(a=>a[1]),i=Math.min(...n),o=Math.min(...r);return {x:i,y:o,w:Math.max(...n)-i,h:Math.max(...r)-o}}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}schema(){return {fields:[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},...F]}}},yn=class extends bt{constructor(){super(...arguments);this.type="arrowmarkup";}dir(){return "up"}},xn=class extends bt{constructor(){super(...arguments);this.type="arrowmarkdown";}dir(){return "down"}};var Cn=["\u2605","\u2606","\u25CF","\u25C6","\u25B2","\u25BC","\u27A4","\u2691","\u271A","\u2715","\u2764","\u2666"],Kr=["small","normal","large","huge"],$a={small:16,normal:22,large:32,huge:44},gt=class extends B{constructor(e){super(e),this.glyph||(this.glyph=this.defaultGlyph()),this.size||(this.size="normal");}sizePx(){return $a[this.size]??$a.normal}anchorSchema(){return {min:1,max:1,slots:[{role:"p",free:"both"}]}}center(e){let t=this.anchors[0];if(!t)return null;let n=e.yOf(t.price,this.paneId);return n==null?null:[e.xOf(t.time),n]}hitTest(e,t,n,r){let i=this.center(n);if(!i)return false;let o=this.sizePx()/2+r;return Math.abs(e-i[0])<=o&&Math.abs(t-i[1])<=o}handlePoints(e){let t=this.center(e);return t?[t]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.center(e);if(!t)return null;let n=this.sizePx();return {x:t[0]-n/2,y:t[1]-n/2,w:n,h:n}}priceRange(){let e=this.anchors[0];return e?{min:e.price,max:e.price}:null}schema(){return {fields:[{path:"glyph",label:"Icon",kind:"select",options:Cn.map(e=>({value:e,label:e})),group:"line"},{path:"size",label:"Size",kind:"select",options:Kr.map(e=>({value:e,label:e})),group:"line"},{path:"style.lineColor",label:"Color",kind:"color",group:"line"},...F]}}writeProps(){return {glyph:this.glyph,size:this.size}}readProps(e){typeof e.glyph=="string"&&(this.glyph=e.glyph),typeof e.size=="string"&&(this.size=e.size);}},wn=class extends gt{constructor(){super(...arguments);this.type="flagmark";}defaultGlyph(){return "\u2691"}},Sn=class extends gt{constructor(){super(...arguments);this.type="iconstamp";}defaultGlyph(){return "\u2605"}};var Wa=s=>s==="small"||s==="normal"||s==="large"||s==="huge";function ah(s){if(!s||typeof s!="object")return null;let e=s;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==false,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var ee=class extends B{constructor(e){super(e),this.levels||(this.levels=this.defaultLevels().map(t=>({...t}))),this.numbersSize||(this.numbersSize="small"),this.labelsSize||(this.labelsSize="normal");}fillBands(e){return []}editableLevels(){return this.levels}anchorSchema(){return {min:2,max:2,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"}]}}hitTest(e,t,n,r){let i=this.entryLines(n);return i!=null&&i.some(o=>K(e,t,o.x1,o.y1,o.x2,o.y2)<=r)}handlePoints(e){let t=[];for(let n of this.anchors){let r=e.yOf(n.price,this.paneId);if(r==null)return [];t.push([e.xOf(n.time),r]);}return t}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),r=t.map(a=>a[1]),i=Math.min(...n),o=Math.min(...r);return {x:i,y:o,w:Math.max(...n)-i,h:Math.max(...r)-o}}schema(){return {fields:O.filter(e=>e.path!=="style.lineColor")}}writeProps(){return {levels:this.levels.map(e=>({...e})),numbersSize:this.numbersSize,labelsSize:this.labelsSize}}readProps(e){if(Array.isArray(e.levels)){let t=e.levels.map(ah).filter(n=>n!=null);t.length&&(this.levels=t);}Wa(e.numbersSize)&&(this.numbersSize=e.numbersSize),Wa(e.labelsSize)&&(this.labelsSize=e.labelsSize);}};var $t=class extends ee{levelLines(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.xOf(t.time),i=e.xOf(n.time),o=Math.min(r,i),a=Math.max(r,i),l=n.price-t.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let h=t.price+d.ratio*l,u=e.yOf(h,this.paneId);u!=null&&c.push({ratio:d.ratio,color:d.color,label:d.label,price:h,x1:o,x2:a,y:u});}return c}entryLines(e){let t=this.levelLines(e);return t?t.map(n=>({color:n.color,label:n.label,x1:n.x1,y1:n.y,x2:n.x2,y2:n.y,numberText:`${n.ratio} (${n.price.toFixed(2)})`,numberX:n.x1+4,numberY:n.y-7,numberAlign:"left",labelX:(n.x1+n.x2)/2,labelY:n.y-7})):null}fillBands(e){let t=this.levelLines(e);if(!t)return [];let n=[];for(let r=1;r<t.length;r+=1){let i=t[r-1],o=t[r];n.push({color:o.color,x:i.x1,y:Math.min(i.y,o.y),w:i.x2-i.x1,h:Math.abs(o.y-i.y)});}return n}priceRange(){let e=this.anchors[0],t=this.anchors[1];if(!e||!t)return null;let n=t.price-e.price,r=this.levels.filter(i=>i.enabled).map(i=>e.price+i.ratio*n);return r.length===0?null:{min:Math.min(...r),max:Math.max(...r)}}};var vt=he,De=X,Ae=bn,yt="#4caf50",tt=q,$e=_e,xt="#9c27b0",lh="#e91e63",Bo="#26a69a",ch="#ab47bc",dh="#ef5350",Ua="#ffb74d",hh="#38c0fd",jr="#b2b5be",Wt=[hh,$e,tt,yt,Ae,De,lh,xt,vt,Bo,ch,dh];function Ga(s){return Wt[(s%Wt.length+Wt.length)%Wt.length]}var uh=[[0,vt],[.125,De],[.236,De],[.25,De],[.382,Ae],[.5,yt],[.618,tt],[.75,$e],[.786,$e],[1,vt],[1.272,$e],[1.382,Ae],[1.618,De],[2,vt],[2.382,Ae],[2.618,Ae],[3,vt],[4.236,yt],[6.854,tt],[11.09,$e]];function ph(s,e=0){return uh.find(([t])=>t===s)?.[1]??Ga(e)}function Q(s){return s.map((e,t)=>{let n=typeof e=="number"?{ratio:e}:e;return {ratio:n.ratio,color:n.color??ph(n.ratio,t),enabled:n.enabled!==false,...n.label?{label:n.label}:{}}})}function Ya(s,e=s){return Array.from({length:s},(t,n)=>({ratio:n+1,color:Ga(n),enabled:n<e,label:String(n+1)}))}var mh=Q([0,.236,.382,.5,.618,.786,1]),qr=class extends $t{constructor(){super(...arguments);this.type="fibretracement";}defaultLevels(){return mh}};var fh=Q([0,.382,.618,1,1.272,1.618,{ratio:2.618,color:xt}]),Zr=class extends $t{constructor(){super(...arguments);this.type="fibextension";}defaultLevels(){return fh}};var bh=Q([0,.382,.5,.618,1,1.618,{ratio:2.618,color:xt}]),Jr=class extends ee{constructor(){super(...arguments);this.type="fibextensiontrend";}anchorSchema(){return {min:3,max:3,slots:[{role:"a",free:"both"},{role:"b",free:"both"},{role:"c",free:"both"}]}}defaultLevels(){return bh}entryLines(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=r.price-n.price,a=[t.xOf(n.time),t.xOf(r.time),t.xOf(i.time)],l=Math.min(...a),c=Math.max(...a),d=[];for(let h of this.levels){if(!h.enabled)continue;let u=i.price+h.ratio*o,p=t.yOf(u,this.paneId);p!=null&&d.push({color:h.color,label:h.label,x1:l,y1:p,x2:c,y2:p,numberText:`${h.ratio} (${u.toFixed(2)})`,numberX:l+4,numberY:p-7,numberAlign:"left",labelX:(l+c)/2,labelY:p-7});}return d}priceRange(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];if(!t||!n||!r)return null;let i=n.price-t.price,o=this.levels.filter(a=>a.enabled).map(a=>r.price+a.ratio*i);return o.push(t.price,n.price,r.price),{min:Math.min(...o),max:Math.max(...o)}}};var gh=Q([.236,.382,.5,.618,.786,1]),Qr=class extends ee{constructor(){super(...arguments);this.type="fibfan";}defaultLevels(){return gh}fanLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.xOf(n.time),o=t.yOf(n.price,this.paneId);if(o==null)return null;let a=t.xOf(r.time),l=r.price-n.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let h=t.yOf(n.price+d.ratio*l,this.paneId);if(h==null)continue;let[u,p,m,f]=re(i,o,a,h,"right",t.width,t.height);c.push({ratio:d.ratio,color:d.color,label:d.label,x1:u,y1:p,x2:m,y2:f,labelX:a+5,labelY:h});}return c}entryLines(t){let n=this.fanLines(t);return n?n.map(r=>({color:r.color,label:r.label,x1:r.x1,y1:r.y1,x2:r.x2,y2:r.y2,numberText:String(r.ratio),numberX:r.labelX,numberY:r.labelY,numberAlign:"left",labelX:r.labelX,labelY:r.labelY+13})):null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var vh=[0,1,2,3,5,8,13,21,34].map(s=>({ratio:s,color:R,enabled:true})),ei=class extends ee{constructor(){super(...arguments);this.type="fibtimezones";}defaultLevels(){return vh}zoneLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=r.time-n.time;if(Math.abs(i)<1e-9)return null;let o=[];for(let a of this.levels)a.enabled&&o.push({n:a.ratio,color:a.color,label:a.label,x:t.xOf(n.time+a.ratio*i)});return o}entryLines(t){let n=this.zoneLines(t);if(!n)return null;let r=t.height;return n.map(i=>({color:i.color,label:i.label,x1:i.x,y1:0,x2:i.x,y2:r,numberText:String(i.n),numberX:i.x,numberY:9,numberAlign:"center",labelX:i.x,labelY:24}))}priceRange(){return null}timeExtent(){return null}};var yh=Q([0,.236,.382,.5,.618,.786,1,1.618,2.618]),ti=class extends ee{constructor(){super(...arguments);this.type="fibchannel";}defaultLevels(){return yh}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"offset",free:"both"}]}}entryLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time),c=0,d=0,h=this.anchors[2];if(h){let p=t.yOf(h.price,this.paneId);if(p==null)return null;c=t.xOf(h.time)-a,d=p-i;}let u=[];for(let p of this.levels){if(!p.enabled)continue;let m=p.ratio*c,f=p.ratio*d,b=l+m,g=o+f;u.push({color:p.color,label:p.label,x1:a+m,y1:i+f,x2:b,y2:g,numberText:String(p.ratio),numberX:b+5,numberY:g,numberAlign:"left",labelX:b+5,labelY:g+13});}return u}priceRange(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[2];if(!t||!n)return null;let i=r?r.price-t.price:0,o=1/0,a=-1/0;for(let l of this.levels)if(l.enabled)for(let c of [t.price,n.price]){let d=c+l.ratio*i;d<o&&(o=d),d>a&&(a=d);}return o<=a?{min:o,max:a}:null}};var xh=Q([0,.236,.382,.5,.618,.786,1]),ni=class extends ee{constructor(){super(...arguments);this.type="fibspeedfan";}defaultLevels(){return xh}entryLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),c=t.xOf(r.time)-a,d=o-i,h=c>=0?"right":"left",u=t.width,p=t.height,m=[];for(let f of this.levels){if(!f.enabled)continue;let b=a+c,g=i+d*f.ratio,v=re(a,i,b,g,h,u,p);if(m.push({color:f.color,label:f.label,x1:v[0],y1:v[1],x2:v[2],y2:v[3],numberText:String(f.ratio),numberX:h==="right"?b+5:b-5,numberY:g,numberAlign:h==="right"?"left":"right",labelX:b,labelY:g}),f.ratio===1)continue;let y=a+c*f.ratio,x=i+d,S=re(a,i,y,x,h,u,p);m.push({color:f.color,label:f.label,x1:S[0],y1:S[1],x2:S[2],y2:S[3],numberText:String(f.ratio),numberX:y,numberY:x+(d>=0?12:-12),numberAlign:"center",labelX:y,labelY:x+12});}return m}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var wh=Q([0,.382,{ratio:.5,enabled:false},.618,1,1.382,1.618,2,2.382,2.618,3]),ri=class extends ee{constructor(){super(...arguments);this.type="trendfibtime";}defaultLevels(){return wh}anchorSchema(){return {min:3,max:3,slots:[{role:"p1",free:"both"},{role:"p2",free:"both"},{role:"p3",free:"both"}]}}entryLines(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return null;let o=r.time-n.time;if(Math.abs(o)<1e-9)return null;let a=t.height,l=[];for(let c of this.levels){if(!c.enabled)continue;let d=t.xOf(i.time+c.ratio*o);l.push({color:c.color,label:c.label,x1:d,y1:0,x2:d,y2:a,numberText:String(c.ratio),numberX:d,numberY:9,numberAlign:"center",labelX:d,labelY:24});}return l}priceRange(){return null}timeExtent(){return null}};function Sh(s,e,t){if(t-e>=Math.PI*2-.001)return true;let n=s-e,r=Math.PI*2;for(;n<0;)n+=r;for(;n>=r;)n-=r;return n<=t-e+1e-6}var Me=class extends ee{boundingLines(e){return []}entryLines(e){return []}hitTest(e,t,n,r){let i=this.radial(n);if(i){let o=Math.hypot(e-i.cx,t-i.cy),a=Math.atan2(t-i.cy,e-i.cx);if(Sh(a,i.a0,i.a1)){for(let l of this.levels)if(l.enabled&&Math.abs(o-i.R0*l.ratio)<=r)return true}}return this.boundingLines(n).some(o=>K(e,t,o[0],o[1],o[2],o[3])<=r)}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}};var Ch=Q([.236,.382,.5,.618,.786,1,1.618,2.618]),ii=class extends Me{constructor(){super(...arguments);this.type="fibcircles";}defaultLevels(){return Ch}radial(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time);return {cx:a,cy:i,R0:Math.hypot(l-a,o-i),a0:0,a1:Math.PI*2}}};var Th=Q([.236,.382,.5,.618,.786,1,1.618,2.618]),oi=class extends Me{constructor(){super(...arguments);this.type="fibarcs";}defaultLevels(){return Th}pts(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?null:{cx:t.xOf(n.time),cy:i,ex:t.xOf(r.time),ey:o}}radial(t){let n=this.pts(t);if(!n)return null;let r=Math.hypot(n.ex-n.cx,n.ey-n.cy),i=Math.atan2(n.ey-n.cy,n.ex-n.cx);return {cx:n.cx,cy:n.cy,R0:r,a0:i-Math.PI/2,a1:i+Math.PI/2}}boundingLines(t){let n=this.pts(t);return n?[[n.cx,n.cy,n.ex,n.ey]]:[]}};var Mh=Q([.236,.382,.5,.618,.786,1]),si=class extends Me{constructor(){super(...arguments);this.type="fibwedge";}defaultLevels(){return Mh}anchorSchema(){return {min:3,max:3,slots:[{role:"apex",free:"both"},{role:"radius",free:"both"},{role:"angle",free:"both"}]}}px(t,n){let r=this.anchors[n];if(!r)return null;let i=t.yOf(r.price,this.paneId);return i==null?null:[t.xOf(r.time),i]}radial(t){let n=this.px(t,0),r=this.px(t,1),i=this.px(t,2);if(!n||!r||!i)return null;let o=Math.hypot(r[0]-n[0],r[1]-n[1]);if(o<1)return null;let a=Math.atan2(r[1]-n[1],r[0]-n[0]),l=Math.atan2(i[1]-n[1],i[0]-n[0]),c=Math.min(a,l),d=Math.max(a,l);return d-c>Math.PI&&([c,d]=[d,c+Math.PI*2]),{cx:n[0],cy:n[1],R0:o,a0:c,a1:d}}boundingLines(t){let n=this.px(t,0),r=this.px(t,1);if(!n||!r)return [];let i=[[n[0],n[1],r[0],r[1]]],o=this.px(t,2);if(o){let a=Math.hypot(r[0]-n[0],r[1]-n[1]),l=Math.hypot(o[0]-n[0],o[1]-n[1]);l>1e-6&&i.push([n[0],n[1],n[0]+(o[0]-n[0])/l*a,n[1]+(o[1]-n[1])/l*a]);}return i}};var Lh=1.6180339887,Xa=Math.log(Lh)/(Math.PI/2),Ph=Math.PI/64,Eh=Math.PI,kh=.5,wt=class extends B{constructor(){super(...arguments);this.type="fibspiral";}anchorSchema(){return {min:2,max:2,slots:[{role:"center",free:"both"},{role:"edge",free:"both"}]}}spiralPoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time),c=Math.hypot(l-a,o-i);if(c<1)return null;let d=Math.atan2(o-i,l-a),h=Math.max(Math.log(kh/c)/Xa,-8*Math.PI*2),u=[];for(let p=h;p<=Eh;p+=Ph){let m=c*Math.exp(Xa*p),f=d+p;u.push([a+m*Math.cos(f),i+m*Math.sin(f)]);}return u}hitTest(t,n,r,i){let o=this.spiralPoints(r);return o!=null&&o.length>=2&&Ht(t,n,o)<=i}handlePoints(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return [];let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);return i==null||o==null?[]:[[t.xOf(n.time),i],[t.xOf(r.time),o]]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.handlePoints(t);if(n.length<2)return null;let r=n.map(l=>l[0]),i=n.map(l=>l[1]),o=Math.min(...r),a=Math.min(...i);return {x:o,y:a,w:Math.max(...r)-o,h:Math.max(...i)-a}}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,...F]}}};var Ih=Q([{ratio:.125,color:De,label:"1/8"},{ratio:.25,color:Ae,label:"1/4"},{ratio:.333,color:Ua,label:"1/3"},{ratio:.5,color:yt,label:"1/2"},{ratio:1,color:jr,label:"1/1"},{ratio:2,color:tt,label:"2/1"},{ratio:3,color:$e,label:"3/1"},{ratio:4,color:Bo,label:"4/1"},{ratio:8,color:xt,label:"8/1"}]),ai=class extends ee{constructor(){super(...arguments);this.type="gannfan";}defaultLevels(){return Ih}entryLines(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.xOf(n.time),o=t.yOf(n.price,this.paneId);if(o==null)return null;let a=t.xOf(r.time),l=r.price-n.price,c=[];for(let d of this.levels){if(!d.enabled)continue;let h=t.yOf(n.price+l*d.ratio,this.paneId);if(h==null)continue;let[u,p,m,f]=re(i,o,a,h,"right",t.width,t.height);c.push({color:d.color,x1:u,y1:p,x2:m,y2:f,numberText:d.label??String(d.ratio),numberX:a+5,numberY:h,numberAlign:"left",labelX:a+5,labelY:h});}return c}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var Rh=Q([0,.25,.382,.5,.618,.75,1].map(s=>({ratio:s,label:String(s)}))),li=class extends ee{constructor(){super(...arguments);this.type="gannbox";}defaultLevels(){return Rh}corners(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.xOf(n.time),o=t.xOf(r.time),a=t.yOf(n.price,this.paneId),l=t.yOf(r.price,this.paneId);return a==null||l==null?null:{c1:n,c2:r,left:Math.min(i,o),right:Math.max(i,o),top:Math.min(a,l),bot:Math.max(a,l)}}entryLines(t){let n=this.corners(t);if(!n)return null;let{c1:r,c2:i,left:o,right:a,top:l,bot:c}=n,d=[];for(let u of this.levels){if(!u.enabled)continue;let p=t.yOf(r.price+u.ratio*(i.price-r.price),this.paneId);p!=null&&d.push({color:u.color,x1:o,y1:p,x2:a,y2:p,numberText:u.label??String(u.ratio),numberX:o-5,numberY:p,numberAlign:"right",labelX:o,labelY:p});let m=t.xOf(r.time+u.ratio*(i.time-r.time));d.push({color:u.color,x1:m,y1:l,x2:m,y2:c,numberText:"",numberX:m,numberY:l,numberAlign:"center",labelX:m,labelY:l});}let h=this.levels.find(u=>u.ratio===1)?.color??vt;return d.push({color:h,x1:o,y1:l,x2:a,y2:c,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),d.push({color:h,x1:o,y1:c,x2:a,y2:l,numberText:"",numberX:0,numberY:0,numberAlign:"left",labelX:0,labelY:0}),d}hitTest(t,n,r,i){let o=this.corners(r);return o!=null&&de(t,n,o.left,o.top,o.right,o.bot,i)}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var Dh=Q([0,.25,.382,.5,.618,.75,1].map(s=>({ratio:s,label:String(s)}))),Ah=[{label:"3x1",x:3,y:1,color:De},{label:"2x1",x:2,y:1,color:Ae},{label:"1x1",x:1,y:1,color:jr},{label:"1x2",x:1,y:2,color:tt},{label:"1x3",x:1,y:3,color:$e}],Vo=[{k:.25,color:De},{k:.5,color:Ae},{k:.75,color:yt},{k:1,color:tt}],St=class extends ee{constructor(){super(...arguments);this.type="gannsquare";}defaultLevels(){return Dh}box(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=t.xOf(n.time),l=t.xOf(r.time);return {ox:a,oy:i,bx:l-a,py:o-i,left:Math.min(a,l),top:Math.min(i,o),right:Math.max(a,l),bot:Math.max(i,o)}}arcGeom(t){let n=this.box(t);return n?{ox:n.ox,oy:n.oy,bx:n.bx,py:n.py}:null}entryLines(t){let n=this.box(t);if(!n)return null;let r=this.anchors[0],i=this.anchors[1],o=[];for(let a of this.levels){if(!a.enabled)continue;let l=t.yOf(r.price+a.ratio*(i.price-r.price),this.paneId);l!=null&&o.push({color:a.color,x1:n.left,y1:l,x2:n.right,y2:l,numberText:a.label??String(a.ratio),numberX:n.left-5,numberY:l,numberAlign:"right",labelX:n.left,labelY:l});let c=t.xOf(r.time+a.ratio*(i.time-r.time));o.push({color:a.color,x1:c,y1:n.top,x2:c,y2:n.bot,numberText:"",numberX:c,numberY:n.top,numberAlign:"center",labelX:c,labelY:n.top});}for(let a of Ah){let l,c;a.x>a.y?(l=n.ox+n.bx,c=n.oy+a.y/a.x*n.py):(c=n.oy+n.py,l=n.ox+a.x/a.y*n.bx),o.push({color:a.color,x1:n.ox,y1:n.oy,x2:l,y2:c,numberText:a.label,numberX:l+4,numberY:c,numberAlign:"left",labelX:l+4,labelY:c});}return o}hitTest(t,n,r,i){let o=this.box(r);return o!=null&&de(t,n,o.left,o.top,o.right,o.bot,i)}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}};var _o=[4,8,12,16,24,32,48,64],Oh=24,Fh=.75;function Ka(s,e){if(!Number.isInteger(s)||!Number.isInteger(e)||e<=0)return false;let t=s*s-1;return e%2===1?t%e===0:e%8===0?t%e!==0?false:t/e%2!==0:false}function ja(s){let e=[];for(let t=0;t<s;t+=1)Ka(t,s)&&e.push(t);return e}var Ct=class extends B{constructor(t){super(t);this.type="dedekind";this.maxCurvature===void 0&&(this.maxCurvature=Oh);}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}box(t){let n=this.anchors[0],r=this.anchors[1];if(!n||!r)return null;let i=t.yOf(n.price,this.paneId),o=t.yOf(r.price,this.paneId);if(i==null||o==null)return null;let a=Math.min(t.xOf(n.time),t.xOf(r.time)),l=Math.max(t.xOf(n.time),t.xOf(r.time)),c=Math.min(i,o),d=Math.max(i,o),h=l-a,u=d-c;if(h<1||u<1)return null;let p=u,m=h/p;return {left:a,right:l,top:c,bot:d,unitPx:p,x0:0,realSpan:m}}geodesics(t){let n=this.box(t);if(!n)return null;let{left:r,top:i,bot:o,unitPx:a,x0:l,realSpan:c}=n,d=Math.max(1,Math.min(64,Math.round(this.maxCurvature))),h=l-1/d,u=l+c+1/d,p=r+c*a,m=[],f=Math.floor(h*2),b=Math.ceil(u*2);for(let g=f;g<=b;g+=1){if(g%2===0)continue;let v=r+(g/2-l)*a;v<r-.5||v>p+.5||m.push({kind:"vline",x:v,y0:o,y1:i});}for(let g=1;g<=d;g+=1){let v=1/g,y=v*a;if(y<Fh)continue;let x=ja(g);if(x.length===0)continue;let S=Math.floor(h)-1,C=Math.ceil(u)+1;for(let T=S;T<=C;T+=1)for(let M of x){let E=M/g+T;if(E+v<h||E-v>u)continue;let k=r+(E-l)*a;k+y<r-1||k-y>p+1||m.push({kind:"arc",cx:k,cy:o,r:y});}}return m}hitTest(t,n,r,i){let o=this.box(r);return o!=null&&de(t,n,o.left,o.top,o.right,o.bot,i)}handlePoints(t){let n=this.box(t);return n?[[n.left,n.top],[n.right,n.bot]]:[]}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.box(t);return n?{x:n.left,y:n.top,w:n.right-n.left,h:n.bot-n.top}:null}priceRange(){let t=this.anchors[0],n=this.anchors[1];return !t||!n?null:{min:Math.min(t.price,n.price),max:Math.max(t.price,n.price)}}schema(){return {fields:[...O,{path:"maxCurvature",label:"Max curvature",kind:"number",min:4,max:64,step:4,group:"behavior"},...F]}}writeProps(){return {maxCurvature:this.maxCurvature}}readProps(t){typeof t.maxCurvature=="number"&&Number.isFinite(t.maxCurvature)&&(this.maxCurvature=Math.max(1,Math.min(64,Math.round(t.maxCurvature))));}};var No=[3,4,5,6,8,10,12],Ho=[1.5,2,2.5,3,4,5],ci=6,Bh=2;function zo(s=ci){return [...Ya(Wt.length,s)]}function Vh(s){if(!s||typeof s!="object")return null;let e=s;return typeof e.ratio!="number"||typeof e.color!="string"?null:{ratio:e.ratio,color:e.color,enabled:e.enabled!==false,...typeof e.label=="string"&&e.label?{label:e.label}:{}}}var Ut={path:"showRatios",label:"Show ratios",kind:"boolean",group:"behavior"},ye=class extends B{constructor(e){super(e),this.waveCount===void 0&&(this.waveCount=ci),this.showRatios===void 0&&(this.showRatios=true);let t=Array.isArray(e.props?.levels);this.levels||(this.levels=this.defaultLevels().map(n=>({...n}))),!t&&this.shouldSyncWaveCount()&&this.syncLevelsToWaveCount();}shouldSyncWaveCount(){return true}syncLevelsToWaveCount(){let e=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=e;for(let t=0;t<this.levels.length;t+=1)this.levels[t].enabled=t<e;}editableLevels(){return this.levels}anchorSchema(){return {min:2,max:2,slots:[{role:"d1",free:"both"},{role:"d2",free:"both"}]}}geom(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);if(r==null||i==null)return null;let o=e.xOf(t.time),a=e.xOf(n.time),l=(o+a)/2,c=(r+i)/2,d=Math.hypot(a-o,i-r)/2;if(d<1)return null;let h=a-o,u=i-r,p=Math.hypot(h,u);p<1e-9?(h=1,u=0):(h/=p,u/=p);let m=this.levels.filter(C=>C.enabled&&C.ratio>0).slice().sort((C,T)=>C.ratio-T.ratio);if(m.length===0)return null;let f=Math.max(1,this.machNumber()),b=[];for(let C of m){let T=C.ratio*d;b.push({cx:l+f*(T-d)*h,cy:c+f*(T-d)*u,r:T,color:C.color,ratio:C.ratio});}let g=l-f*d*h,v=c-f*d*u,y=b[b.length-1].r,x=f*y+2*d,S=[];if(f<=1+1e-9){let C=-u,T=h;S.push([g-C*x,v-T*x,g+C*x,v+T*x]);}else {let C=Math.asin(1/f),T=Math.cos(C),M=Math.sin(C),E=(G,w,H)=>[G*T-w*H*M,G*H*M+w*T],[k,L]=E(h,u,1),[P,V]=E(h,u,-1);S.push([g,v,g+k*x,v+L*x]),S.push([g,v,g+P*x,v+V*x]);}return {c0x:l,c0y:c,R:d,fx:h,fy:u,noseX:g,noseY:v,circles:b,rays:S}}hitTest(e,t,n,r){let i=this.geom(n);if(!i)return false;for(let o of i.circles)if(Math.abs(Math.hypot(e-o.cx,t-o.cy)-o.r)<=r)return true;return i.rays.some(o=>K(e,t,o[0],o[1],o[2],o[3])<=r)}handlePoints(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return [];let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);return r==null||i==null?[]:[[e.xOf(t.time),r],[e.xOf(n.time),i]]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.geom(e);if(!t)return null;let n=t.noseX,r=t.noseX,i=t.noseY,o=t.noseY;for(let a of t.circles)n=Math.min(n,a.cx-a.r),r=Math.max(r,a.cx+a.r),i=Math.min(i,a.cy-a.r),o=Math.max(o,a.cy+a.r);for(let a of t.rays)n=Math.min(n,a[0],a[2]),r=Math.max(r,a[0],a[2]),i=Math.min(i,a[1],a[3]),o=Math.max(o,a[1],a[3]);return {x:n,y:i,w:r-n,h:o-i}}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}applySettings(e){if(super.applySettings(e),Object.prototype.hasOwnProperty.call(e,"waveCount")&&typeof this.waveCount=="number"){let t=Math.max(1,Math.min(this.levels.length,Math.round(this.waveCount)));this.waveCount=t;for(let n=0;n<this.levels.length;n+=1)this.levels[n].enabled=n<t;}}schema(){return {fields:[...O,{path:"waveCount",label:"Waves",kind:"number",min:3,max:12,step:1,group:"behavior"},Ut,...F]}}writeProps(){return {waveCount:this.waveCount,showRatios:this.showRatios,levels:this.levels.map(e=>({...e}))}}readProps(e){if(typeof e.waveCount=="number"&&Number.isFinite(e.waveCount)&&(this.waveCount=Math.max(2,Math.min(12,Math.round(e.waveCount)))),typeof e.showRatios=="boolean"&&(this.showRatios=e.showRatios),Array.isArray(e.levels)){let t=e.levels.map(Vh).filter(n=>n!=null);t.length&&(this.levels=t);}}},Tn=class extends ye{constructor(){super(...arguments);this.type="sonic";}defaultLevels(){return zo(ci)}machNumber(){return 1}},Mn=class extends ye{constructor(t){super(t);this.type="supersonic";this.mach===void 0&&(this.mach=Bh);}defaultLevels(){return zo(ci)}machNumber(){return Math.max(1.01,this.mach)}schema(){return {fields:[...O,{path:"mach",label:"Mach number",kind:"number",min:1.5,max:5,step:.5,group:"behavior"},{path:"waveCount",label:"Waves",kind:"number",min:3,max:12,step:1,group:"behavior"},Ut,...F]}}writeProps(){return {...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)));}};var qa=Q([.236,.382,.5,.618,.786,1,1.618,2.618,4.236,6.854,11.09]),_h=2,di=class extends ye{constructor(){super(...arguments);this.type="goldensonic";}shouldSyncWaveCount(){return false}defaultLevels(){return qa}machNumber(){return 1}schema(){return {fields:[...O,Ut,...F]}}},hi=class extends ye{constructor(t){super(t);this.type="goldensupersonic";this.mach===void 0&&(this.mach=_h);}shouldSyncWaveCount(){return false}defaultLevels(){return qa}machNumber(){return Math.max(1.01,this.mach)}schema(){return {fields:[...O,{path:"mach",label:"Mach number",kind:"number",min:1.5,max:5,step:.5,group:"behavior"},Ut,...F]}}writeProps(){return {...super.writeProps(),mach:this.mach}}readProps(t){super.readProps(t),typeof t.mach=="number"&&Number.isFinite(t.mach)&&(this.mach=Math.max(1.01,Math.min(20,t.mach)));}};var ae=class extends B{legRatios(){return false}fillTriangles(){return []}necklineIndices(){return null}anchorSchema(){let e=this.vertexLabels().length,t=[];for(let n=0;n<e;n+=1)t.push({role:`p${n}`,free:"both"});return {min:e,max:e,slots:t}}handlePoints(e){let t=[];for(let n of this.anchors){let r=e.yOf(n.price,this.paneId);if(r==null)return [];t.push([e.xOf(n.time),r]);}return t}hitTest(e,t,n,r){let i=this.handlePoints(n);return i.length>=2&&Ht(e,t,i)<=r}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.handlePoints(e);if(t.length===0)return null;let n=t.map(a=>a[0]),r=t.map(a=>a[1]),i=Math.min(...n),o=Math.min(...r);return {x:i,y:o,w:Math.max(...n)-i,h:Math.max(...r)-o}}priceRange(){if(this.anchors.length===0)return null;let e=this.anchors.map(t=>t.price);return {min:Math.min(...e),max:Math.max(...e)}}patternName(){return null}ratioOk(e){return null}valid(){return null}ratioAt(e){let t=this.anchors[e-2],n=this.anchors[e-1],r=this.anchors[e];if(!t||!n||!r)return null;let i=Math.abs(n.price-t.price);return i<1e-9?null:Math.abs(r.price-n.price)/i}schema(){return {fields:[...O,...this.fillTriangles().length?Z:[]]}}};var ui=class extends ae{constructor(){super(...arguments);this.type="xabcd";}vertexLabels(){return ["X","A","B","C","D"]}legRatios(){return true}fillTriangles(){return [[0,1,2],[2,3,4]]}};var pi=class extends ae{constructor(){super(...arguments);this.type="abcd";}vertexLabels(){return ["A","B","C","D"]}legRatios(){return true}};var mi=class extends ae{constructor(){super(...arguments);this.type="elliottimpulse";}vertexLabels(){return ["1","2","3","4","5"]}};var fi=class extends ae{constructor(){super(...arguments);this.type="elliottcorrection";}vertexLabels(){return ["A","B","C"]}};var bi=class extends ae{constructor(){super(...arguments);this.type="headshoulders";}vertexLabels(){return ["","LS","","H","","RS",""]}necklineIndices(){return [2,4]}};var be=class extends ae{vertexLabels(){return ["X","A","B","C","D"]}legRatios(){return true}fillTriangles(){return [[0,1,2],[2,3,4]]}legValue(e){let[t,n,r,i,o]=this.anchors;if(!t||!n||!r||!i||!o)return null;let a=(h,u)=>Math.abs(u.price-h.price),l=a(t,n),c=a(n,r),d=a(r,i);switch(e){case "ab":return l<1e-9?null:c/l;case "bc":return c<1e-9?null:d/c;case "cd":return d<1e-9?null:a(i,o)/d;default:return l<1e-9?null:a(n,o)/l}}inBand(e,t){return e!=null&&e>=t.min&&e<=t.max}ratioOk(e){let t=this.ranges();return e===2?this.inBand(this.legValue("ab"),t.ab):e===3?this.inBand(this.legValue("bc"),t.bc):e===4?this.inBand(this.legValue("cd"),t.cd):null}valid(){if(this.anchors.length<5)return null;let e=this.ranges();return this.inBand(this.legValue("ab"),e.ab)&&this.inBand(this.legValue("bc"),e.bc)&&this.inBand(this.legValue("cd"),e.cd)&&this.inBand(this.legValue("ad"),e.ad)}};var gi=class extends be{constructor(){super(...arguments);this.type="gartley";}patternName(){return "Gartley"}ranges(){return {ab:{min:.55,max:.68},bc:{min:.382,max:.886},cd:{min:1.13,max:1.618},ad:{min:.74,max:.83}}}};var vi=class extends be{constructor(){super(...arguments);this.type="bat";}patternName(){return "Bat"}ranges(){return {ab:{min:.382,max:.5},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:.84,max:.92}}}};var yi=class extends be{constructor(){super(...arguments);this.type="butterfly";}patternName(){return "Butterfly"}ranges(){return {ab:{min:.74,max:.83},bc:{min:.382,max:.886},cd:{min:1.618,max:2.618},ad:{min:1.272,max:1.618}}}};var xi=class extends be{constructor(){super(...arguments);this.type="crab";}patternName(){return "Crab"}ranges(){return {ab:{min:.382,max:.618},bc:{min:.382,max:.886},cd:{min:2.618,max:3.618},ad:{min:1.55,max:1.69}}}};var wi=class extends be{constructor(){super(...arguments);this.type="shark";}patternName(){return "Shark"}ranges(){return {ab:{min:.382,max:.618},bc:{min:1.13,max:1.618},cd:{min:1.618,max:2.24},ad:{min:.886,max:1.13}}}};var Nh={min:1.272,max:1.414},Hh={min:.74,max:.83},Si=class extends be{constructor(){super(...arguments);this.type="cypher";}patternName(){return "Cypher"}ranges(){return {ab:{min:.382,max:.618},bc:{min:0,max:1/0},cd:{min:0,max:1/0},ad:{min:0,max:1/0}}}xcOverXa(){let t=this.anchors[0],n=this.anchors[1],r=this.anchors[3];if(!t||!n||!r)return null;let i=Math.abs(n.price-t.price);return i<1e-9?null:Math.abs(r.price-t.price)/i}cdOverXc(){let t=this.anchors[0],n=this.anchors[3],r=this.anchors[4];if(!t||!n||!r)return null;let i=Math.abs(n.price-t.price);return i<1e-9?null:Math.abs(r.price-n.price)/i}ratioOk(t){return t===2?this.inBand(this.legValue("ab"),this.ranges().ab):null}valid(){return this.anchors.length<5?null:this.inBand(this.legValue("ab"),this.ranges().ab)&&this.inBand(this.xcOverXa(),Nh)&&this.inBand(this.cdOverXc(),Hh)}};function Za(s){return `${s>=0?"+":""}${s.toFixed(2)}`}function Ln(s){let e=Math.abs(s),t=864e5,n=36e5,r=6e4;if(e>=t){let i=Math.floor(e/t),o=Math.round(e%t/n);return o?`${i}d ${o}h`:`${i}d`}if(e>=n){let i=Math.floor(e/n),o=Math.round(e%n/r);return o?`${i}h ${o}m`:`${i}h`}return e>=r?`${Math.round(e/r)}m`:`${Math.round(e/1e3)}s`}var Tt=class extends B{constructor(e){super(e),this.showPrice===void 0&&(this.showPrice=true),this.showDate===void 0&&(this.showDate=true);}anchorSchema(){return {min:2,max:2,slots:[{role:"c1",free:"both"},{role:"c2",free:"both"}]}}measureLabel(e){let t=[];return this.showPrice&&t.push(this.priceLabel()),this.showDate&&t.push(this.timeLabel(e)),t}isUp(){let e=this.anchors[0],t=this.anchors[1];return e!=null&&t!=null&&t.price>=e.price}priceLabel(){let e=this.anchors[0],t=this.anchors[1];if(!e||!t)return "";let n=t.price-e.price,r=e.price!==0?n/e.price*100:0;return `${Za(n)} (${Za(r)}%)`}timeLabel(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return "";let r=Ln(n.time-t.time),i=e.barsBetween?Math.round(e.barsBetween(t.time,n.time)):null;return i!=null?`${i} bars, ${r}`:r}rect(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;let r=e.yOf(t.price,this.paneId),i=e.yOf(n.price,this.paneId);return r==null||i==null?null:{x1:e.xOf(t.time),y1:r,x2:e.xOf(n.time),y2:i}}hitTest(e,t,n,r){let i=this.rect(n);return i!=null&&de(e,t,i.x1,i.y1,i.x2,i.y2,r)}handlePoints(e){let t=this.rect(e);return t?[[t.x1,t.y1],[t.x2,t.y2]]:[]}hitHandle(e,t,n,r){return N(e,t,this.handlePoints(n),r+3)}bounds(e){let t=this.rect(e);return t?{x:Math.min(t.x1,t.x2),y:Math.min(t.y1,t.y2),w:Math.abs(t.x2-t.x1),h:Math.abs(t.y2-t.y1)}:null}priceRange(){let e=this.anchors[0],t=this.anchors[1];return !e||!t?null:{min:Math.min(e.price,t.price),max:Math.max(e.price,t.price)}}schema(){return {fields:[{path:"showPrice",label:"Show price",kind:"boolean",group:"behavior"},{path:"showDate",label:"Show date",kind:"boolean",group:"behavior"},...O.filter(e=>e.path!=="style.lineColor"),{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Te,group:"text"}]}}writeProps(){return {showPrice:this.showPrice,showDate:this.showDate}}readProps(e){typeof e.showPrice=="boolean"&&(this.showPrice=e.showPrice),typeof e.showDate=="boolean"&&(this.showDate=e.showDate);}};var Ci=class extends Tt{constructor(){super(...arguments);this.type="datepricerange";}};var Ti=[{value:"long",label:"Long"},{value:"short",label:"Short"}],ie=class ie extends B{constructor(t){super(t);this.type="position";this.riskPercent===void 0&&(this.riskPercent=ie.DEFAULT_RISK_PERCENT),this.accountBalance===void 0&&(this.accountBalance=ie.DEFAULT_ACCOUNT_BALANCE),this.showText===void 0&&(this.showText=true),this.showHeader===void 0&&(this.showHeader=true),this.showPrices===void 0&&(this.showPrices=false),this.showLossSize===void 0&&(this.showLossSize=true),this.showTargetLabel===void 0&&(this.showTargetLabel=true),this.showStopLabel===void 0&&(this.showStopLabel=true),this.profitColor===void 0&&(this.profitColor=ie.DEFAULT_PROFIT_COLOR),this.lossColor===void 0&&(this.lossColor=ie.DEFAULT_LOSS_COLOR);}directionLabel(){let t=this.prices();return t&&t.target>=t.entry?"LONG":"SHORT"}get direction(){return this.directionLabel()==="LONG"?"long":"short"}set direction(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];!n||!r||!i||(t==="long"||t==="short")&&t!==this.direction&&(r.price=2*n.price-r.price,i.price=2*n.price-i.price);}get quantity(){return this.positionSize()}set quantity(t){let n=this.prices();if(!n||!Number.isFinite(t)||t<0)return;let r=Math.abs(n.entry-n.stop);r<1e-9||this.accountBalance<=0||(this.riskPercent=t*r/this.accountBalance*100);}get entryPrice(){return this.anchors[0]?.price??0}set entryPrice(t){let n=this.anchors[0];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(0));}get stopPrice(){return this.anchors[1]?.price??0}set stopPrice(t){let n=this.anchors[1];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(1));}get targetPrice(){return this.anchors[2]?.price??0}set targetPrice(t){let n=this.anchors[2];n&&Number.isFinite(t)&&(n.price=t,this.constrainHandleDrag(2));}anchorSchema(){return {min:2,max:2,slots:[{role:"entry",free:"both"},{role:"stop",free:"both"},{role:"target",free:"both"}]}}onPlaced(t){let n=this.anchors[0];if(!n)return;let r=t.xOf(n.time),i=t.yOf(n.price,this.paneId);if(i==null)return;let o=this.anchors[1],a=o?t.yOf(o.price,this.paneId):null,l,c;o&&a!=null&&Math.abs(a-i)>=ie.MIN_DRAG_PX?(l=a,c=r+Math.max(Math.abs(t.xOf(o.time)-r),ie.MIN_WIDTH_PX)):(l=i-ie.DEFAULT_RISK_PX*ie.DEFAULT_RR,c=r+ie.DEFAULT_WIDTH_PX);let d=i-(l-i)/ie.DEFAULT_RR,h=t.pxToPoint(c,i,this.paneId).time;this.anchors=[{time:n.time,price:n.price},{time:h,price:t.pxToPoint(r,d,this.paneId).price},{time:h,price:t.pxToPoint(r,l,this.paneId).price}];}constrainHandleDrag(t){let n=this.anchors[0],r=this.anchors[1],i=this.anchors[2];if(!n||!r||!i)return;let o=Math.sign(r.price-n.price),a=Math.sign(i.price-n.price);o===0||a===0||o!==a||(t===2?r.price=2*n.price-r.price:i.price=2*n.price-i.price);}resolved(){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return null;if(this.anchors[2])return [t,n,this.anchors[2]];let r={time:n.time,price:t.price-(n.price-t.price)/ie.DEFAULT_RR};return [t,r,n]}prices(){let t=this.resolved();return t?{entry:t[0].price,stop:t[1].price,target:t[2].price}:null}rr(){let t=this.prices();if(!t)return 0;let n=Math.abs(t.entry-t.stop);return n<1e-9?0:Math.abs(t.target-t.entry)/n}rewardPct(){let t=this.prices();return t&&t.entry!==0?Math.abs(t.target-t.entry)/t.entry*100:0}riskPct(){let t=this.prices();return t&&t.entry!==0?Math.abs(t.entry-t.stop)/t.entry*100:0}dollarLoss(){return Math.max(0,this.accountBalance)*(Math.max(0,this.riskPercent)/100)}positionSize(){let t=this.prices();if(!t)return 0;let n=Math.abs(t.entry-t.stop);return n<1e-9?0:this.dollarLoss()/n}headerLabel(){return `${this.directionLabel()} \xB7 R:R ${this.rr().toFixed(2)}`}lossSizeLabel(){return `Loss $${zh(this.dollarLoss())} \xB7 Size ${$h(this.positionSize())}`}targetLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${Ja(t.target)}`:"";return `Target +${this.rewardPct().toFixed(2)}%${n}`}stopLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${Ja(t.stop)}`:"";return `Stop \u2212${this.riskPct().toFixed(2)}%${n}`}levelDisplayValue(t,n){let r=this.prices();if(!r)return 0;let i=t==="stop"?r.stop:r.target;return Qa(n==="price"?i:Math.abs(i-r.entry))}levelPriceFromDisplay(t,n,r){let i=this.prices();if(!i||n==="price")return r;let o=t==="stop"?i.stop:i.target,a=Math.sign(o-i.entry);return a===0&&(a=(t==="target"?1:-1)*(this.direction==="long"?1:-1)),i.entry+a*Math.abs(r)}box(t){let n=this.handlePoints(t);if(n.length<3)return null;let r=n.map(i=>i[0]);return {x1:Math.min(...r),x2:Math.max(...r),ey:n[0][1],sy:n[1][1],ty:n[2][1]}}layout(t){return this.box(t)}hitTest(t,n,r,i){let o=this.box(r);if(!o)return false;let a=Math.min(o.ey,o.sy,o.ty),l=Math.max(o.ey,o.sy,o.ty);return de(t,n,o.x1,a,o.x2,l,i)}handlePoints(t){let n=this.resolved();if(!n)return [];let r=[];for(let i of n){let o=t.yOf(i.price,this.paneId);if(o==null)return [];r.push([t.xOf(i.time),o]);}return r}hitHandle(t,n,r,i){return N(t,n,this.handlePoints(r),i+3)}bounds(t){let n=this.box(t);if(!n)return null;let r=Math.min(n.ey,n.sy,n.ty);return {x:n.x1,y:r,w:n.x2-n.x1,h:Math.max(n.ey,n.sy,n.ty)-r}}priceRange(){let t=this.resolved();if(!t)return null;let n=t.map(r=>r.price);return {min:Math.min(...n),max:Math.max(...n)}}schema(){return {fields:[{path:"riskPercent",label:"Risk %",kind:"number",min:0,max:100,step:.1,group:"behavior"},{path:"accountBalance",label:"Account balance",kind:"number",min:0,max:1e12,step:1,group:"behavior"},{path:"quantity",label:"Position size",kind:"number",group:"behavior"},{path:"direction",label:"Direction",kind:"select",options:Ti,group:"behavior"},{path:"entryPrice",label:"Entry price",kind:"number",group:"behavior"},{path:"stopPrice",label:"Stop price",kind:"number",group:"behavior"},{path:"targetPrice",label:"Target price",kind:"number",group:"behavior"},{path:"showText",label:"Show text",kind:"boolean",group:"behavior"},{path:"showHeader",label:"Show direction & ratio",kind:"boolean",group:"behavior"},{path:"showLossSize",label:"Show loss & size",kind:"boolean",group:"behavior"},{path:"showTargetLabel",label:"Show target label",kind:"boolean",group:"behavior"},{path:"showStopLabel",label:"Show stop label",kind:"boolean",group:"behavior"},{path:"showPrices",label:"Show level prices",kind:"boolean",group:"behavior"},{path:"profitColor",label:"Profit zone",kind:"color",group:"fill"},{path:"lossColor",label:"Loss zone",kind:"color",group:"fill"},...O.filter(t=>t.path!=="style.lineColor"),{path:"text.color",label:"Text color",kind:"color",group:"text"},{path:"text.size",label:"Text size",kind:"select",options:Te,group:"text"}]}}writeProps(){return {riskPercent:this.riskPercent,accountBalance:this.accountBalance,showText:this.showText,showHeader:this.showHeader,showPrices:this.showPrices,showLossSize:this.showLossSize,showTargetLabel:this.showTargetLabel,showStopLabel:this.showStopLabel,profitColor:this.profitColor,lossColor:this.lossColor}}readProps(t){typeof t.riskPercent=="number"&&Number.isFinite(t.riskPercent)&&(this.riskPercent=t.riskPercent),typeof t.accountBalance=="number"&&Number.isFinite(t.accountBalance)&&(this.accountBalance=t.accountBalance),typeof t.showText=="boolean"&&(this.showText=t.showText),typeof t.showHeader=="boolean"&&(this.showHeader=t.showHeader),typeof t.showPrices=="boolean"&&(this.showPrices=t.showPrices),typeof t.showLossSize=="boolean"&&(this.showLossSize=t.showLossSize),typeof t.showTargetLabel=="boolean"&&(this.showTargetLabel=t.showTargetLabel),typeof t.showStopLabel=="boolean"&&(this.showStopLabel=t.showStopLabel),typeof t.profitColor=="string"&&(this.profitColor=t.profitColor),typeof t.lossColor=="string"&&(this.lossColor=t.lossColor);}};ie.DEFAULT_RR=2,ie.MIN_DRAG_PX=6,ie.DEFAULT_RISK_PX=64,ie.DEFAULT_WIDTH_PX=150,ie.MIN_WIDTH_PX=48,ie.DEFAULT_RISK_PERCENT=1,ie.DEFAULT_ACCOUNT_BALANCE=1e4,ie.DEFAULT_PROFIT_COLOR=br,ie.DEFAULT_LOSS_COLOR=gr;var Oe=ie;function zh(s){if(!Number.isFinite(s))return "0";let e=Math.round(s*100)/100;return Number.isInteger(e)?String(e):e.toFixed(2)}function $h(s){return !Number.isFinite(s)||s===0?"0":s>=100?s.toFixed(2):s>=1?s.toFixed(4).replace(/\.?0+$/,""):s.toPrecision(4).replace(/\.?0+$/,"")}function Ja(s){return Number.isFinite(s)?Math.abs(s)>=1?s.toFixed(2):s.toPrecision(4).replace(/\.?0+$/,""):"0"}function Qa(s){return Math.round(s*1e8)/1e8}var Pn=new Map;function A(s){Pn.set(s.type,s);}function nt(s){return Pn.get(s)}function Mi(){return [...Pn.values()]}function rt(s,e){let t=Pn.get(s);if(!t)return null;let n={...t.defaultStyle,...e.style??{}};return t.create({...e,style:n})}function $o(s){let e=rt(s.type,{paneId:s.paneId});if(!e)return;s.style={...e.style};let t=s.text?.value;e.text?(s.text={...e.text},t!==void 0&&(s.text.value=t)):s.text=void 0;let n=e.serialize().props;n!==void 0&&s.applyProps(n);}function Fe(s){let e=Pn.get(s.type);return e?e.create(s):null}var Wh=I('<line x1="4" y1="19" x2="20" y2="5"/>'),Uh=I('<line x1="3" y1="12" x2="21" y2="12"/>');A({type:"trendline",group:"lines",label:"Trend Line",icon:Wh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new xr(s)});A({type:"hline",group:"lines",label:"Horizontal Line",icon:Uh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"dashed"},create:s=>new wr(s)});var Gh=I('<line x1="3" y1="20" x2="21" y2="6"/><circle cx="3" cy="20" r="1.6" fill="currentColor"/>'),Yh=I('<rect x="4" y="6" width="16" height="12" rx="1"/>'),Xh=I('<path d="M5 6h14M12 6v13"/>');A({type:"ray",group:"lines",label:"Ray",icon:Gh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Sr(s)});var Kh=I('<path d="M5 19 19 5"/><path d="M5 19 8.5 19M5 19 5 15.5"/><path d="M19 5 15.5 5M19 5 19 8.5"/>'),jh=I('<line x1="12" y1="3" x2="12" y2="21"/>'),qh=I('<line x1="5" y1="12" x2="21" y2="12"/><circle cx="5" cy="12" r="1.6" fill="currentColor"/>'),Zh=I('<line x1="3" y1="12" x2="21" y2="12"/><line x1="12" y1="3" x2="12" y2="21"/>'),Jh=I('<path d="M4 20 20 4"/><rect x="9" y="9" width="9" height="6" rx="1"/>'),Qh=I('<path d="M4 20 20 6"/><path d="M4 20 15 20"/><path d="M11 20a7 7 0 0 0-2-4.9"/>');A({type:"extendedline",group:"lines",label:"Extended Line",icon:Kh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Cr(s)});A({type:"vline",group:"lines",label:"Vertical Line",icon:jh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Tr(s)});A({type:"hray",group:"lines",label:"Horizontal Ray",icon:qh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Mr(s)});A({type:"crossline",group:"lines",label:"Cross Line",icon:Zh,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Lr(s)});A({type:"infoline",group:"lines",label:"Info Line",icon:Jh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Pr(s)});A({type:"trendangle",group:"lines",label:"Trend Angle",icon:Qh,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Er(s)});A({type:"box",group:"shapes",label:"Rectangle",icon:Yh,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}26`},create:s=>new kr(s)});A({type:"text",group:"annotations",label:"Text",icon:Xh,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new He(s)});var eu=I('<path d="M5 4h14a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-6l-5 5v-5H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"/>');A({type:"callout",group:"annotations",label:"Callout",icon:eu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new Ie(s)});var tu=I('<path d="M5 4h14a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-7l-4 4v-4H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z"/><path d="M8 8.5h8M8 12h5"/>'),nu=I('<rect x="10" y="4.5" width="11" height="8" rx="1.5"/><path d="M10 8.5 4 16"/><circle cx="3.5" cy="16.5" r="1.6" fill="currentColor" stroke="none"/>'),ru=I('<path d="M5 4.5h14a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-7l-4 4v-4H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2Z"/>'),iu=I('<path d="M3 12 7 8h12a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H7Z"/><path d="M10.5 12.5h6" stroke-width="1.4"/>'),ou=I('<path d="M12 11.5V21"/><rect x="5" y="4" width="14" height="7" rx="1"/><path d="M9 7.5h6"/>');A({type:"note",group:"annotations",label:"Note",icon:tu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new dt(s)});A({type:"pricenote",group:"annotations",label:"Price Note",icon:nu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new ut(s)});A({type:"comment",group:"annotations",label:"Comment",icon:ru,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new pt(s)});A({type:"pricelabel",group:"annotations",label:"Price Label",icon:iu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new ht(s)});A({type:"signpost",group:"annotations",label:"Signpost",icon:ou,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid",fillColor:`${R}d9`},create:s=>new mt(s)});var su=I('<line x1="3" y1="16" x2="21" y2="8"/><line x1="3" y1="21" x2="21" y2="13"/>'),au=I('<line x1="3" y1="7" x2="21" y2="10"/><line x1="3" y1="18" x2="21" y2="14"/>'),lu=I('<circle cx="4" cy="12" r="1.6" fill="currentColor"/><line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>');A({type:"parallelchannel",group:"channels",label:"Parallel Channel",icon:su,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new Ir(s)});A({type:"disjointchannel",group:"channels",label:"Disjoint Channel",icon:au,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new Rr(s)});var cu=I('<line x1="3" y1="7" x2="21" y2="7"/><line x1="3" y1="18" x2="21" y2="11"/>');A({type:"flattopbottom",group:"channels",label:"Flat Top/Bottom",icon:cu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new Dr(s)});var du=I('<line x1="3" y1="8" x2="21" y2="4"/><line x1="3" y1="16" x2="21" y2="12"/><line x1="3" y1="12" x2="21" y2="8" stroke-dasharray="3 3"/>');A({type:"regressionchannel",group:"channels",label:"Linear Regression",icon:du,defaultStyle:{lineColor:he,lineWidth:1,lineStyle:"solid"},create:s=>new ze(s)});A({type:"pitchfork",group:"pitchforks",label:"Pitchfork",icon:lu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Ar(s)});var hu=I('<circle cx="4" cy="8" r="1.6" fill="currentColor"/><line x1="4" y1="8" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>'),uu=I('<circle cx="6" cy="9" r="1.6" fill="currentColor"/><line x1="6" y1="9" x2="10" y2="12"/><line x1="10" y1="6" x2="10" y2="18"/><line x1="10" y1="6" x2="21" y2="6"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="18" x2="21" y2="18"/>'),pu=I('<line x1="4" y1="12" x2="10" y2="12"/><line x1="10" y1="8" x2="10" y2="16"/><line x1="10" y1="8" x2="21" y2="8"/><line x1="10" y1="12" x2="21" y2="12"/><line x1="10" y1="16" x2="21" y2="16"/>');A({type:"schiffpitchfork",group:"pitchforks",label:"Schiff Pitchfork",icon:hu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Or(s)});A({type:"modifiedschiffpitchfork",group:"pitchforks",label:"Modified Schiff Pitchfork",icon:uu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Fr(s)});A({type:"insidepitchfork",group:"pitchforks",label:"Inside Pitchfork",icon:pu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Br(s)});var mu=I('<path d="M7 7h10v10"/><path d="M7 17 17 7"/>'),fu=I('<ellipse cx="12" cy="12" rx="9" ry="6"/>'),bu=I('<path d="M12 4 20 19 4 19Z"/>');A({type:"arrow",group:"shapes",label:"Arrow",icon:mu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",arrowRight:true},create:s=>new Vr(s)});A({type:"ellipse",group:"shapes",label:"Ellipse",icon:fu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new _r(s)});A({type:"triangle",group:"shapes",label:"Triangle",icon:bu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new Nr(s)});var gu=I('<polyline points="3 17 9 10 13 14 21 5"/>'),vu=I('<path d="M9.5 12 17 4.5a2.12 2.12 0 0 1 3 3L12.5 15"/><path d="M7 14a3 3 0 0 0-3 3c0 1.3-1.2 1.5-1.5 2 .8.9 2 1.5 3.5 1.5a3.5 3.5 0 0 0 3.5-3.5 3 3 0 0 0-2.5-3Z"/>'),yu=I('<path d="M9 11 15 5l4 4-6 6H9Z"/><path d="M9 15l-2 2"/><path d="M4 21h6"/>');A({type:"polyline",group:"shapes",label:"Polyline",icon:gu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Hr(s)});A({type:"freehand",group:"shapes",label:"Brush",icon:vu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new zr(s)});A({type:"highlighter",group:"shapes",label:"Highlighter",icon:yu,defaultStyle:{lineColor:`${ya}59`,lineWidth:14,lineStyle:"solid"},create:s=>new $r(s)});var xu=I('<circle cx="12" cy="12" r="8"/>'),wu=I('<path d="M5 14 9.5 5 19 10 14.5 19 Z"/>'),Su=I('<path d="M4 19 9 11 13 14 17 8 20 4"/><path d="M17.2 5.5 20 4 19.4 7.1"/>'),Cu=I('<path d="M4 17a8 8 0 0 1 16 0"/><path d="M4 17 20 17"/>'),Tu=I('<path d="M4 18Q12 1 20 14"/>'),Mu=I('<path d="M12 5 12 19"/><path d="M6 11 12 5 18 11"/>'),Lu=I('<path d="M12 5 12 19"/><path d="M6 13 12 19 18 13"/>');A({type:"circle",group:"shapes",label:"Circle",icon:xu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}1a`},create:s=>new Wr(s)});A({type:"rotatedrect",group:"shapes",label:"Rotated Rectangle",icon:wu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}26`},create:s=>new Ur(s)});A({type:"path",group:"shapes",label:"Path",icon:Su,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Gr(s)});A({type:"arc",group:"shapes",label:"Arc",icon:Cu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid",fillColor:`${R}26`},create:s=>new Yr(s)});A({type:"curve",group:"shapes",label:"Curve",icon:Tu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new Xr(s)});A({type:"arrowmarkup",group:"shapes",label:"Arrow Mark Up",icon:Mu,defaultStyle:{lineColor:q,lineWidth:1,lineStyle:"solid"},create:s=>new yn(s)});A({type:"arrowmarkdown",group:"shapes",label:"Arrow Mark Down",icon:Lu,defaultStyle:{lineColor:X,lineWidth:1,lineStyle:"solid"},create:s=>new xn(s)});var Pu=I('<path d="M6 21V4"/><path d="M6 5h11l-2.5 3.5L17 12H6" fill="currentColor" stroke="none"/>'),Eu=I('<path d="m12 3 2.6 5.8 6.4.6-4.8 4.2 1.4 6.2L12 16.9 6.4 19.8 7.8 13.6 3 9.4l6.4-.6Z"/>');A({type:"flagmark",group:"stamps",label:"Flag",icon:Pu,defaultStyle:{lineColor:ve,lineWidth:1,lineStyle:"solid"},create:s=>new wn(s)});A({type:"iconstamp",group:"stamps",label:"Icon",icon:Eu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Sn(s)});var ku=I('<line x1="3" y1="5" x2="21" y2="5"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="3" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/>'),Iu=I('<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="11" x2="21" y2="11"/><line x1="3" y1="15" x2="14" y2="15"/><line x1="3" y1="20" x2="14" y2="20"/>');A({type:"fibretracement",group:"fibonacci",label:"Fib Retracement",icon:ku,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new qr(s)});A({type:"fibextension",group:"fibonacci",label:"Fib Extension",icon:Iu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Zr(s)});var Ru=I('<path d="M3 20 10 9l4 5"/><path d="M14 14h7M14 9h7M14 4h7"/>');A({type:"fibextensiontrend",group:"fibonacci",label:"Trend-Based Fib Extension",icon:Ru,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Jr(s)});var Du=I('<path d="M4 20 20 5M4 20 21 11M4 20 21 17M4 20 20 20"/>'),Au=I('<path d="M3 5v14M6 5v14M11 5v14M19 5v14"/>');A({type:"fibfan",group:"fibonacci",label:"Fib Fan",icon:Du,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Qr(s)});A({type:"fibtimezones",group:"fibonacci",label:"Fib Time Zones",icon:Au,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"dashed"},create:s=>new ei(s)});var Ou=I('<path d="M3 18 18 9M5 21 20 12M6 13 21 4"/>'),Fu=I('<path d="M4 4 20 20M4 4 20 12M4 4 12 20M4 4 20 4M4 4 4 20"/>'),Bu=I('<path d="M3 19 9 8M9 8 12 5v14M14 5v14M18 5v14M21 5v14"/>');A({type:"fibchannel",group:"fibonacci",label:"Fib Channel",icon:Ou,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ti(s)});A({type:"fibspeedfan",group:"fibonacci",label:"Fib Speed Resistance Fan",icon:Fu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ni(s)});A({type:"trendfibtime",group:"fibonacci",label:"Trend-Based Fib Time",icon:Bu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"dashed"},create:s=>new ri(s)});var Vu=I('<circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="10"/>'),_u=I('<path d="M8 20a4 4 0 0 1 8 0"/><path d="M4.5 20a7.5 7.5 0 0 1 15 0"/><circle cx="12" cy="20" r="1.4" fill="currentColor" stroke="none"/>'),Nu=I('<path d="M4 20 20 16M4 20 14 4"/><path d="M11.8 18.1A8 8 0 0 0 8.2 13.2"/><path d="M16.6 16.9A13 13 0 0 0 10.9 9"/>'),Hu=I('<path d="M13 12a2 2 0 1 1-2-2 4 4 0 0 1 4 4 6 6 0 0 1-9 5.2 9 9 0 0 1 .5-15"/>');A({type:"fibcircles",group:"fibonacci",label:"Fib Circles",icon:Vu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ii(s)});A({type:"fibarcs",group:"fibonacci",label:"Fib Speed Resistance Arcs",icon:_u,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new oi(s)});A({type:"fibwedge",group:"fibonacci",label:"Fib Wedge",icon:Nu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new si(s)});A({type:"fibspiral",group:"fibonacci",label:"Fib Spiral",icon:Hu,defaultStyle:{lineColor:R,lineWidth:2,lineStyle:"solid"},create:s=>new wt(s)});var zu=I('<path d="M4 20 20 20M4 20 20 13M4 20 20 6M4 20 15 4M4 20 9 4M4 20 4 4"/>'),$u=I('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 12h16M12 4v16M4 4 20 20" opacity="0.6"/>');A({type:"gannfan",group:"fibonacci",label:"Gann Fan",icon:zu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ai(s)});A({type:"gannbox",group:"fibonacci",label:"Gann Box",icon:$u,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new li(s)});var Wu=I('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 20 20 4M4 20 20 12M4 20 12 4" opacity="0.7"/><path d="M4 20a16 16 0 0 1 16-16" opacity="0.5"/>');A({type:"gannsquare",group:"fibonacci",label:"Gann Square",icon:Wu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new St(s)});var Uu=I('<path d="M2 20h20"/><path d="M4 20a8 8 0 0 1 16 0" opacity="0.9"/><path d="M6 20a4 4 0 0 1 8 0" opacity="0.75"/><path d="M10 20a2 2 0 0 1 4 0" opacity="0.6"/><path d="M8 20v-6M12 20v-9M16 20v-6" opacity="0.45"/>');A({type:"dedekind",group:"geometry",label:"Dedekind Tessellation",icon:Uu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Ct(s)});var Gu=I('<circle cx="16" cy="12" r="5" opacity="0.55"/><circle cx="13" cy="12" r="3.5" opacity="0.75"/><circle cx="10.5" cy="12" r="2"/><path d="M8 4v16"/>'),Yu=I('<circle cx="17" cy="12" r="4.5" opacity="0.45"/><circle cx="13" cy="12" r="3" opacity="0.7"/><circle cx="10" cy="12" r="1.6"/><path d="M6 12 16 5M6 12 16 19"/>');A({type:"sonic",group:"geometry",label:"Sonic",icon:Gu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Tn(s)});A({type:"supersonic",group:"geometry",label:"Supersonic",icon:Yu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Mn(s)});var Xu=I('<circle cx="16" cy="12" r="5" opacity="0.4"/><circle cx="13" cy="12" r="3.2" opacity="0.65"/><circle cx="10.8" cy="12" r="1.8"/><path d="M8 4v16"/><path d="M15 8.5h2M12.5 10h2" opacity="0.5"/>'),Ku=I('<circle cx="17" cy="12" r="4.5" opacity="0.4"/><circle cx="12.5" cy="12" r="2.8" opacity="0.65"/><circle cx="9.8" cy="12" r="1.4"/><path d="M6 12 16 5M6 12 16 19"/>');A({type:"goldensonic",group:"geometry",label:"Golden Sonic",icon:Xu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new di(s)});A({type:"goldensupersonic",group:"geometry",label:"Golden Supersonic",icon:Ku,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new hi(s)});var ju=I('<path d="M3 18 7 8 11 14 15 6 20 16"/>'),qu=I('<path d="M4 17 9 7 14 15 20 5"/>'),Zu=I('<path d="M3 19 8 9 12 13 17 5 21 9"/>'),Ju=I('<path d="M4 7 11 16 20 9"/>'),Qu=I('<path d="M3 18 6 12 9 16 12 5 15 16 18 12 21 18"/>');A({type:"xabcd",group:"patterns",label:"XABCD Pattern",icon:ju,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new ui(s)});A({type:"abcd",group:"patterns",label:"ABCD Pattern",icon:qu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new pi(s)});A({type:"elliottimpulse",group:"patterns",label:"Elliott Impulse Wave (1-5)",icon:Zu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new mi(s)});A({type:"elliottcorrection",group:"patterns",label:"Elliott Correction Wave (ABC)",icon:Ju,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new fi(s)});A({type:"headshoulders",group:"patterns",label:"Head & Shoulders",icon:Qu,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new bi(s)});var ep=I('<path d="M3 17 7 6 12 14 17 5 21 16"/><path d="M3 17 21 16" opacity="0.45"/>'),Gt={group:"patterns",icon:ep,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"}};A({type:"gartley",label:"Gartley",...Gt,create:s=>new gi(s)});A({type:"bat",label:"Bat",...Gt,create:s=>new vi(s)});A({type:"butterfly",label:"Butterfly",...Gt,create:s=>new yi(s)});A({type:"crab",label:"Crab",...Gt,create:s=>new xi(s)});A({type:"shark",label:"Shark",...Gt,create:s=>new wi(s)});A({type:"cypher",label:"Cypher",...Gt,create:s=>new Si(s)});var tp=I('<rect x="4" y="6" width="16" height="12" rx="1"/><path d="M4 18 20 6" opacity="0.5"/>');A({type:"datepricerange",group:"measure",label:"Date & Price Range",icon:tp,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Ci(s)});var np=I('<rect x="4.5" y="4.5" width="15" height="7.5" rx="1" fill="currentColor" fill-opacity="0.25"/><rect x="4.5" y="12" width="15" height="7.5" rx="1"/>');A({type:"position",group:"measure",label:"Long/Short Position",icon:np,defaultStyle:{lineColor:R,lineWidth:1,lineStyle:"solid"},create:s=>new Oe(s)});var rp=I('<line x1="5" y1="3" x2="5" y2="21"/><path d="M5 16c4 0 5-9 8-9s3 5 8 3"/>');A({type:"anchoredvwap",group:"measure",label:"Anchored VWAP",icon:rp,defaultStyle:{lineColor:_e,lineWidth:2,lineStyle:"solid"},create:s=>new ft(s)});var ip=I('<path d="M4 4v16"/><path d="M4 8h10"/><path d="M4 12h14"/><path d="M4 16h8"/><path d="M4 20h12"/>');A({type:"fixedrangevp",group:"measure",label:"Fixed Range Volume Profile",icon:ip,defaultStyle:{lineColor:q,lineWidth:1,lineStyle:"solid"},create:s=>new Re(s)});var op=["fibretracement","fibextension","fibextensiontrend","fibfan","fibtimezones","fibchannel","fibspeedfan","trendfibtime","fibcircles","fibarcs","fibwedge","fibspiral"],sp=["gannfan","gannbox","gannsquare"],ap=["dedekind","sonic","supersonic","goldensonic","goldensupersonic"],lp=["xabcd","abcd","headshoulders"],cp=["elliottimpulse","elliottcorrection"],dp=["gartley","bat","butterfly","crab","shark","cypher"],hp=["position","datepricerange"],up=["anchoredvwap","fixedrangevp"],pp=["freehand","highlighter"],mp=["arrow","arrowmarkup","arrowmarkdown"],fp=["box","ellipse","triangle","polyline","circle","rotatedrect","path","arc","curve"],bp=["text","callout","note","pricenote","comment","pricelabel","signpost"],gp=["flagmark","iconstamp"],vp=[{id:"lines-channels-pitchforks",label:"Lines",sections:[{label:"Lines",registryGroup:"lines"},{label:"Channels",registryGroup:"channels"},{label:"Pitchforks",registryGroup:"pitchforks"}]},{id:"fibonacci-gann",label:"Fibonacci",sections:[{label:"Fibonacci",types:op},{label:"Gann",types:sp},{label:"Geometry",types:ap}]},{id:"patterns-waves-harmonics",label:"Patterns",sections:[{label:"Patterns",types:lp},{label:"Elliott Waves",types:cp},{label:"Harmonics",types:dp}]},{id:"measurements",label:"Measurements",sections:[{label:"Measurements",types:hp},{label:"Volume",types:up}]},{id:"brushes-arrows-shapes",label:"Shapes",sections:[{label:"Brushes",types:pp},{label:"Arrows",types:mp},{label:"Shapes",types:fp}]},{id:"text",label:"Text",sections:[{label:"Text",types:bp}]},{id:"icons",label:"Icons",sections:[{label:"Icons",types:gp}]}];function yp(s){let e=nt(s);return e?{type:e.type,label:e.label,icon:e.icon}:null}function xp(s){let e=new Map;for(let t of Mi()){if(s&&!s.has(t.type))continue;let n={type:t.type,label:t.label,icon:t.icon};e.has(t.group)||e.set(t.group,[]),e.get(t.group).push(n);}return e}function wp(s,e,t){return "registryGroup"in s?e.get(s.registryGroup)??[]:s.types.map(n=>t.get(n)).filter(n=>n!=null)}function el(s){let e=xp(s),t=new Map;for(let r of e.values())for(let i of r)t.set(i.type,i);let n=[];for(let r of vp){let i=[],o=[];for(let a of r.sections){let l=wp(a,e,t);l.length!==0&&(i.push({label:a.label,tools:l}),o.push(...l));}o.length!==0&&n.push({id:r.id,label:r.label,tools:o,sections:i.length>0?i:void 0});}return {groups:n}}function Sp(s){let e=new Set;for(let t of s)nt(t)&&e.add(t);return el(e)}function Cp(s){let e=[];for(let t of s){let n=t.tools.map(yp).filter(r=>r!=null);n.length>0&&e.push({id:t.id,label:t.label,tools:n});}return {groups:e}}function En(){return el()}function kn(s){if(s===false)return {definition:En(),visible:false};if(s===void 0||s===true)return {definition:En(),visible:true};let e=s.toolbar??true;return s.groups?{definition:Cp(s.groups),visible:e}:s.tools?{definition:Sp(s.tools),visible:e}:{definition:En(),visible:e}}function Mt(s){let e=globalThis.structuredClone;return e?e(s):JSON.parse(JSON.stringify(s))}function Tp(s){if(!s||typeof s!="object")return false;let e=s;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.paneId=="string"&&Array.isArray(e.anchors)&&e.anchors.every(t=>t&&typeof t.time=="number"&&typeof t.price=="number")&&!!e.style&&typeof e.style=="object"}function tl(s){let e=s;return !e||typeof e!="object"||e.version!==1||!Array.isArray(e.drawings)?{version:1,drawings:[]}:{version:1,drawings:e.drawings.filter(Tp)}}var Yt=class{constructor(){this.byId=new Map;this.seq=0;this.zCounter=1;this.listeners=new Set;}nextId(){return this.seq+=1,`dw-${this.seq}`}add(e){return e.zIndex||(e.zIndex=this.zCounter),this.zCounter=Math.max(this.zCounter,Math.ceil(e.zIndex))+1,this.byId.set(e.id,e),this.emit(),e}remove(e){let t=this.byId.delete(e);return t&&this.emit(),t}get(e){return this.byId.get(e)}has(e){return this.byId.has(e)}update(e,t){let n=this.byId.get(e);return n?(t.anchors&&(n.anchors=t.anchors.map(r=>({time:r.time,price:r.price}))),t.style&&(n.style={...t.style}),t.text!==void 0&&(n.text=t.text?{...t.text}:void 0),t.paneId!==void 0&&(n.paneId=t.paneId),t.locked!==void 0&&(n.locked=t.locked),t.visible!==void 0&&(n.visible=t.visible),t.zIndex!==void 0&&(n.zIndex=t.zIndex),t.props!==void 0&&n.applyProps(t.props),this.emit(),n):null}all(){return [...this.byId.values()].sort((e,t)=>e.zIndex-t.zIndex)}byPane(e){return this.all().filter(t=>t.paneId===e)}bringToFront(e,t=0){let n=this.byId.get(e);n&&(n.zIndex=Math.max(this.zCounter,Math.floor(t)+1),this.zCounter=n.zIndex+1,this.emit());}sendToBack(e,t=1){let n=this.byId.get(e);if(!n)return;let r=Math.min(...[...this.byId.values()].map(i=>i.zIndex),Math.ceil(t));n.zIndex=r-1,this.emit();}setLocked(e,t){let n=this.byId.get(e);n&&(n.locked=t,this.emit());}setVisible(e,t){let n=this.byId.get(e);n&&(n.visible=t,this.emit());}clear(){this.byId.size!==0&&(this.byId.clear(),this.emit());}serialize(){return {version:1,drawings:this.all().map(e=>e.serialize())}}load(e){let t=tl(e);this.byId.clear(),this.seq=0,this.zCounter=1;for(let n of t.drawings){let r=Fe(n);r&&(this.byId.set(r.id,r),this.zCounter=Math.max(this.zCounter,r.zIndex)+1,this.bumpSeqPast(r.id));}this.emit();}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}bumpSeqPast(e){let t=/^dw-(\d+)$/.exec(e);t&&(this.seq=Math.max(this.seq,Number(t[1])));}emit(){for(let e of this.listeners)e();}};var Li=class{constructor(e=100){this.cap=e;this.undoStack=[];this.redoStack=[];this.pending=null;this.dirtied=false;this.depth=0;}begin(e){this.depth+=1,this.depth===1&&(this.pending=Mt(e),this.dirtied=false);}markDirty(){this.depth===0||this.dirtied||!this.pending||(this.push(this.pending),this.dirtied=true);}commit(){this.depth!==0&&(this.depth-=1,this.depth===0&&(this.pending=null,this.dirtied=false));}abort(){this.commit();}record(e){if(this.depth>0){this.markDirty();return}this.push(Mt(e));}undo(e){let t=this.undoStack.pop();return t?(this.redoStack.push(Mt(e)),t):null}redo(e){let t=this.redoStack.pop();return t?(this.undoStack.push(Mt(e)),t):null}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[],this.pending=null,this.dirtied=false,this.depth=0;}push(e){this.undoStack.push(e),this.undoStack.length>this.cap&&this.undoStack.shift(),this.redoStack=[];}};var Pi=class{constructor(e,t,n){this.events=t;this.store=new Yt;this.history=new Li;this.activeTool=null;this.snapMode="off";this.stayInDrawingMode=false;this.mode=null;this.favs=new Set;this.selectedIds=[];this.clipboard=[];this.lastStyle=new Map;this.subs=[];if(this.enabled=!!e.capabilities.userDrawings&&!!e.userDrawingsPort,this.port=this.enabled?e.userDrawingsPort:null,this.port){let{definition:r,visible:i}=kn(n);this.port.setToolbar(r),this.port.showToolbar(i),this.subs.push(this.port.onDrawingIntent(o=>this.onIntent(o))),this.subs.push(this.store.onChange(()=>this.sync()));}}get supported(){return this.enabled}setTool(e){if(!this.port)return;let t=e!==this.activeTool;this.activeTool=e,this.port.setActiveTool(e,e?this.lastStyle.get(e):void 0),t&&this.events.emit("drawing:tool",{type:e});}getTool(){return this.activeTool}getSnapMode(){return this.snapMode}setSnapMode(e){!this.port||e===this.snapMode||(this.snapMode=e,this.port.setSnapMode?.(e),this.events.emit("drawing:snap",{mode:e}));}getStayMode(){return this.stayInDrawingMode}setStayMode(e){!this.port||e===this.stayInDrawingMode||(this.stayInDrawingMode=e,this.port.setStayMode?.(e),this.events.emit("drawing:stay",{on:e}));}getMode(){return this.mode}setMode(e){!this.port||e===this.mode||(this.mode=e,this.port.setMode?.(e),this.events.emit("drawing:mode",{mode:e}));}showToolbar(e){this.port?.showToolbar(e);}favorites(){return [...this.favs]}isFavorite(e){return this.favs.has(e)}setFavorite(e,t){nt(e)&&t!==this.favs.has(e)&&(t?this.favs.add(e):this.favs.delete(e),this.pushFavorites());}setFavorites(e){let t=e.filter(n=>nt(n)!=null);t.length===this.favs.size&&t.every(n=>this.favs.has(n))||(this.favs=new Set(t),this.pushFavorites());}pushFavorites(){let e=[...this.favs];this.port?.setFavorites?.(e),this.events.emit("drawing:favorites",{favorites:e});}setToolbar(e){this.port?.setToolbar(kn(e).definition);}setExternalGhost(e){this.port?.setExternalGhost?.(e);}setToolShortcuts(e){this.port?.setToolShortcuts?.(e);}add(e,t={}){if(!this.enabled)return null;let r={...this.lastStyle.get(e)??{},...t.style??{}},i=rt(e,{id:this.store.nextId(),paneId:t.paneId??"price",anchors:t.anchors,style:r,text:t.text,props:t.props,zIndex:t.zIndex??this.startZ(t.paneId??"price")});return i?(this.history.record(this.store.serialize()),this.store.add(i),this.captureStyle(i.id),this.events.emit("drawing:created",{id:i.id}),i):null}remove(e){this.deleteMany([e]);}update(e,t){let n=this.store.serialize(),r=t.style?this.store.get(e):void 0,i=t.style&&r?{...t,style:{...r.style,...t.style}}:t;this.store.update(e,i)&&(this.history.record(n),this.captureStyle(e),this.events.emit("drawing:edited",{id:e}));}updateMany(e){this.history.begin(this.store.serialize());for(let{id:t,patch:n}of e)this.store.update(t,n)&&(this.history.markDirty(),this.events.emit("drawing:edited",{id:t}));this.history.commit();}removeMany(e){this.deleteMany(e);}setLocked(e,t){let n=this.store.serialize();this.history.record(n),this.store.setLocked(e,t),this.events.emit("drawing:edited",{id:e});}setVisible(e,t){let n=this.store.serialize();this.history.record(n),this.store.setVisible(e,t),this.events.emit("drawing:edited",{id:e});}bringToFront(e){let t=this.store.serialize();this.history.record(t),this.store.bringToFront(e,this.seriesTopZ(this.store.get(e)?.paneId)),this.events.emit("drawing:edited",{id:e});}sendToBack(e){let t=this.store.serialize();this.history.record(t),this.store.sendToBack(e,this.seriesBottomZ(this.store.get(e)?.paneId)),this.events.emit("drawing:edited",{id:e});}seriesTopZ(e){return e!==void 0?this.port?.stackRange?.(e)?.front??0:0}seriesBottomZ(e){return e!==void 0?this.port?.stackRange?.(e)?.back??1:1}startZ(e){let t=this.port?.stackRange?.(e);return t?(t.price??t.front)-.5:void 0}select(e,t=false){this.setSelection(e,t);}openSettings(e){this.port?.openSettings(e);}undo(){let e=this.history.undo(this.store.serialize());e&&this.restoreSnapshot(e);}redo(){let e=this.history.redo(this.store.serialize());e&&this.restoreSnapshot(e);}canUndo(){return this.history.canUndo()}canRedo(){return this.history.canRedo()}duplicate(e){if(!this.enabled)return [];let t=this.resolve(e);return t.length===0?[]:this.insertClones(t.map(n=>n.serialize()))}clone(e){return this.duplicate([e])[0]??null}copy(e){let t=this.resolve(e).map(n=>Mt(n.serialize()));t.length&&(this.clipboard=t);}paste(){return !this.enabled||this.clipboard.length===0?[]:this.insertClones(this.clipboard)}all(){return this.store.serialize().drawings}toJSON(){return this.store.serialize()}fromJSON(e){this.history.clear(),this.selectedIds=[],this.store.load(e);}destroy(){for(let e of this.subs)e();this.subs.length=0;}setSelection(e,t=false){let n;if(t){n=[...this.selectedIds];for(let r of e){let i=n.indexOf(r);i>=0?n.splice(i,1):n.push(r);}}else n=[...e];this.selectedIds=n.filter(r=>this.store.has(r)),this.port?.setSelection(this.selectedIds),this.events.emit("drawing:selected",{id:this.selectedIds[0]??null});}restoreSnapshot(e){this.store.load(e),this.selectedIds=this.selectedIds.filter(t=>this.store.has(t)),this.port?.setSelection(this.selectedIds),this.events.emit("drawing:selected",{id:this.selectedIds[0]??null});}deleteMany(e){this.history.begin(this.store.serialize());let t=[];for(let r of e)this.store.remove(r)&&t.push(r),this.history.markDirty();if(this.history.commit(),t.length===0)return;let n=this.selectedIds.filter(r=>this.store.has(r));n.length!==this.selectedIds.length&&this.setSelection(n);for(let r of t)this.events.emit("drawing:removed",{id:r});}insertClones(e){this.history.begin(this.store.serialize());let t=[];for(let n of e){let r=Fe({...n,id:this.store.nextId()});r&&(this.store.add(r),this.history.markDirty(),t.push(r));}if(this.history.commit(),t.length){this.setSelection(t.map(n=>n.id));for(let n of t)this.events.emit("drawing:created",{id:n.id});}return t}resolve(e){return e.map(t=>this.store.get(t)).filter(t=>t!=null)}captureStyle(e){let t=this.store.get(e);t&&this.lastStyle.set(t.type,{...t.style});}sync(){this.port?.syncDrawings(this.store.serialize().drawings);}onIntent(e){switch(e.kind){case "arm":this.setTool(e.type);break;case "draft":this.events.emit("drawing:draft",{doc:e.doc});break;case "create":{let t=this.store.serialize(),n=this.lastStyle.get(e.doc.type),r=n?{...e.doc.style,...n}:e.doc.style,i=Fe({...e.doc,id:this.store.nextId(),style:r});if(!i)return;i.zIndex||(i.zIndex=this.startZ(i.paneId)??0),this.history.record(t),this.store.add(i),this.captureStyle(i.id),this.events.emit("drawing:created",{id:i.id});break}case "edit":{let t=this.store.serialize();this.store.update(e.doc.id,e.doc)&&(this.history.record(t),this.captureStyle(e.doc.id),this.events.emit("drawing:edited",{id:e.doc.id}));break}case "edit-many":{this.history.begin(this.store.serialize());for(let t of e.docs)this.store.update(t.id,t)&&(this.history.markDirty(),this.events.emit("drawing:edited",{id:t.id}));this.history.commit();break}case "select":this.setSelection(e.ids,e.additive);break;case "delete":this.deleteMany(e.ids);break;case "reorder":e.to==="front"?this.bringToFront(e.id):this.sendToBack(e.id);break;case "settings":this.events.emit("drawing:settings",{id:e.id});break;case "favorite":this.setFavorite(e.type,e.on);break;case "snap-mode":e.mode!==this.snapMode&&(this.snapMode=e.mode,this.events.emit("drawing:snap",{mode:e.mode}));break;case "stay-mode":e.on!==this.stayInDrawingMode&&(this.stayInDrawingMode=e.on,this.events.emit("drawing:stay",{on:e.on}));break;case "mode":e.mode!==this.mode&&(this.mode=e.mode,this.events.emit("drawing:mode",{mode:e.mode}));break;case "tool-finished":!this.stayInDrawingMode&&e.type!=="freehand"&&e.type!=="highlighter"&&this.setTool(null);break;case "undo":this.undo();break;case "redo":this.redo();break;case "duplicate":this.duplicate(e.ids);break;case "copy":this.copy(e.ids);break;case "paste":this.paste();break}}};var nl={D:864e5,W:6048e5,M:2592e6};function In(s){let e=s.trim();if(nl[e])return nl[e];let t=/^(\d+)\s*(m|h|d|w)?$/i.exec(e);if(t){let n=parseInt(t[1],10),r=(t[2]??"m").toLowerCase();return n*(r==="m"?6e4:r==="h"?36e5:r==="d"?864e5:6048e5)}return 36e5}var it=s=>s.trim().toLowerCase(),rl=s=>s.trim().toUpperCase();function We(s){let e=s.trim(),t=/^(?:([A-Za-z0-9_.]+):)?(.+)$/.exec(e);if(!t)return {provider:null,ticker:e};let n=t[1]?it(t[1]):null,r=t[2],i=r.lastIndexOf("."),o=i>0?r.slice(i+1):void 0;return {provider:n,ticker:r,ext:o}}var Ei=class{constructor(){this.entries=new Map;this.changeListeners=new Set;this.waits=new Set;this.unresolvedCbs=new Set;}register(e,t){let n=it(e),r={name:n,provider:t,index:null,descriptors:[],settled:false,settle:Promise.resolve()};return this.entries.set(n,r),r.settle=this.buildIndex(r),queueMicrotask(()=>this.notify(false)),r.settle}async buildIndex(e){await Promise.resolve();try{if(e.provider.listSymbols){let t=await e.provider.listSymbols();e.descriptors=t,e.index=new Set(t.map(n=>rl(n.ticker)));}}catch{e.index=null;}finally{e.settled=true,this.notify(true);}}notify(e){for(let t of [...this.changeListeners])t(e);}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}unregister(e){this.entries.delete(it(e)),this.notify(false);}has(e){return this.entries.has(it(e))}get(e){return this.entries.get(it(e))?.provider}names(){return [...this.entries.keys()]}parse(e){return We(e)}resolve(e,t={}){let{provider:n,ticker:r}=this.parse(e);if(n)return this.entries.has(n)?{provider:n,ticker:r}:null;let i=rl(r);for(let o of this.candidateOrder(t.default))if(this.entries.get(o).index?.has(i))return {provider:o,ticker:r};if(t.lenient&&this.entries.size===1){let o=this.names()[0],a=this.entries.get(o);if(a.settled&&a.index==null)return {provider:o,ticker:r}}return null}whenResolvable(e,t={}){let n=this.resolve(e,{...t,lenient:true});return n?Promise.resolve(n):new Promise(r=>{let i=this.onChange(a=>{let l=this.resolve(e,{...t,lenient:true});l?(o(),r(l)):a&&this.allSettled()&&this.reportUnresolved(e);}),o=()=>{i(),this.waits.delete(o);};this.waits.add(o);})}allSettled(){for(let e of this.entries.values())if(!e.settled)return false;return true}cancelWaits(){for(let e of [...this.waits])e();}onUnresolved(e){return this.unresolvedCbs.add(e),()=>this.unresolvedCbs.delete(e)}reportUnresolved(e){let t=this.names();console.warn(`[vela] symbol "${e}" not yet resolvable \u2014 registered providers: [${t.join(", ")||"none"}]. Register a provider that serves it.`);for(let n of this.unresolvedCbs)n({symbol:e,providers:t});}candidateOrder(e){let t=this.names();if(e){let n=it(e);if(this.entries.has(n))return [n,...t.filter(r=>r!==n)]}return t}symbolsOf(e){return e!=null?this.entries.get(it(e))?.descriptors??[]:[...this.entries.entries()].flatMap(([t,n])=>n.descriptors.map(r=>({...r,provider:t})))}infoOf(e){let t=it(e),n=this.entries.get(t);if(!n)return {name:t,capabilities:{enumerate:false,stream:false,symbolInfo:false}};let r=n.provider;return r.info?.()??{name:n.name,capabilities:{enumerate:!!r.listSymbols,stream:!!r.subscribe,symbolInfo:!!r.getSymbolInfo}}}indexReady(){return Promise.all([...this.entries.values()].map(e=>e.settle)).then(()=>{})}};function ki(s){switch(s.kind){case "row":return {label:s.label,toggle:s.toggle,controls:s.controls,when:s.when};case "toggle":{let e=[];s.number&&e.push({kind:"number",...s.number});for(let t of s.colors??[])e.push({kind:"color",...t});return s.width&&e.push({kind:"width",...s.width}),{label:s.label,toggle:{key:s.key,defval:s.defval},controls:e,when:s.when}}case "number":return {label:s.label,controls:[{kind:"number",key:s.key,label:s.label,defval:s.defval,min:s.min,max:s.max,step:s.step}],when:s.when};case "color":return {label:s.label,controls:[{kind:"color",key:s.key,label:s.label,defval:s.defval}],when:s.when};case "select":return {label:s.label,controls:[{kind:"select",key:s.key,label:s.label,options:s.options,defval:s.defval}],when:s.when};case "range":return {label:s.label,controls:[{kind:"number",key:s.minKey,label:`${s.label} \u2014 min`,defval:s.defval,min:s.min,max:s.max,step:s.step,placeholder:s.placeholder},{kind:"hint",text:"\u2013"},{kind:"number",key:s.maxKey,label:`${s.label} \u2014 max`,defval:s.defval,min:s.min,max:s.max,step:s.step,placeholder:s.placeholder}],when:s.when}}}function Rn(s){if(s.kind==="heading"||s.kind==="header")return [];let e=ki(s),t=[];e.toggle&&t.push({key:e.toggle.key,type:"boolean",defval:e.toggle.defval});for(let n of e.controls)n.kind!=="hint"&&(n.kind==="color"||n.kind==="select"?t.push({key:n.key,type:"string",defval:n.defval}):t.push({key:n.key,type:"number",defval:n.defval}));return t}function Lt(s,e){return s?(Array.isArray(s)?s:[s]).every(n=>n.anyOf?n.anyOf.some(r=>r===e[n.key]):e[n.key]===n.equals):true}var Dn=new Map;function Wo(s){Dn.set(s.id,s);}function Lp(s){Dn.delete(s);}function Ue(s){return typeof s=="string"?Dn.get(s):void 0}function Ge(){return [...Dn.values()]}function Uo(){return [...Dn.values()].filter(s=>s.tickerModifier??s.barTransform!=null).map(s=>s.id)}function Ii(s){return Ue(s)?.barTransform??null}function il(s){let e=s.lastIndexOf(";");if(e<=0||e===s.length-1)return {symbol:s,modifier:null,transform:null};let t=s.slice(e+1).toLowerCase();return t!=="standard"&&!Uo().includes(t)?{symbol:s,modifier:null,transform:null}:{symbol:s.slice(0,e),modifier:t,transform:Ii(t)}}var Be={background:"#151619",textColor:"#b2b5be",gridColor:"#20222c",borderColor:"#2a2b30",upColor:q,downColor:X,fontFamily:"sans-serif"},An={background:"#ffffff",textColor:"#1e293b",gridColor:"#cccccc",borderColor:"#d4dae3",upColor:q,downColor:X,fontFamily:"sans-serif"};function Xt(s){return !s||s==="dark"?Be:s==="light"?An:s}var Pp=150,Ep=1e3,kp=300,Ip=5e3,ol=1e4,Rp=1.5,sl=5e3,Ri=class s{constructor(e,t,n,r,i,o){this.renderer=t;this.feed=n;this.config=i;this.dataControl=o;this.events=new ct;this.registry=new ur;this.paneOrder=["price"];this.collapsedPanes=new Set;this.maximizedPaneId=null;this.paneActionUnsub=null;this.handles=new Map;this.engines=new Map;this.live=null;this.bars=[];this.rawBars=[];this.barTransform=null;this.typeEngines=new Map;this.typeSettings=new Map;this.activeEngineStyle=null;this.priceStyle="candles";this.unresolvedUnsub=null;this.visibleRange=null;this.viewportUnsub=null;this.viewportTimer=null;this.healing=false;this.healBuffer=[];this.lastHealAt=0;this.onVisible=null;this.barCause="tick";this.historyState="complete";this.generation=0;this.supersedeWaiters=[];this.historyCompleted=false;this.historyCompletePromise=new Promise(e=>{this.resolveHistoryComplete=e;});this.switchingMarket=false;this.loadingUp=false;this.volumeOptedOut=false;this.contextEmitAt=new Map;this.runEmitAt=new Map;for(let l of r)this.registerEngine(l.language,l);this.defaultLanguage=i.defaultLanguage,this.renderer.mount(e,i.theme),this.renderer.onInputChange(l=>this.applyInputs(l.indicatorId,{[l.key]:l.value})),this.renderer.onRemoveIndicator(l=>this.removeIndicator(l)),this.renderer.onToggleIndicatorVisible?.((l,c)=>this.setVisible(l,c)),this.paneActionUnsub=this.renderer.onPaneAction?.(l=>this.handlePaneAction(l))??null,this.renderer.onChartTypeSettingsChange?.((l,c)=>{this.typeSettings.set(l,c),this.typeEngines.get(l)?.onSettings?.(c);}),this.renderer.onMoveIndicator?.((l,c)=>this.moveIndicator(l,c)),this.renderer.onThemeSelect?.(l=>this.setTheme(Xt(l))),this.viewportUnsub=this.renderer.onViewportChange(l=>this.onViewportChange(l)),this.renderer.onPriceStyleChange?.(l=>this.syncPriceStyle(l));let a=this.renderer.readFeature("priceStyle");typeof a=="string"&&(this.priceStyle=a),this.barTransform=Ii(a),this.drawings=new Pi(this.renderer,this.events,i.drawings),this.unresolvedUnsub=this.feed.onUnresolved?.(l=>{this.endLoad(),this.events.emit("data:unresolved",l);})??null,this.readyPromise=this.init(),Ue(a)?.dataEngine&&this.syncChartTypeEngine(a);}currentVisibleRange(){if(this.visibleRange)return this.visibleRange;let e=this.renderer.getVisibleRange();return e?{left:e.from,right:e.to}:void 0}engineFor(e){let t=e??this.defaultLanguage,n=this.engines.get(t);if(!n)throw new Error(`[vela] no scripting engine registered for language "${t}". Vela ships none \u2014 install one (Pine Script: @luxalgo/vela-pinets) and register it before addIndicator, e.g. chart.registerEngine('pine', new PineEngine()).`);return n}market(){return {symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",symbolInfo:this.feed.symbolInfo?.(this.config.market),chartStyle:this.priceStyle}}async fetchSeries(e,t,n){let r=il(e),i={symbol:r.symbol,timeframe:t},o=await(this.feed.loadRange?this.feed.loadRange(i,n):this.feed.load({...i,bars:n.limit}));return r.transform?r.transform.full(o):o}onViewportChange(e){this.visibleRange={left:e.from,right:e.to},this.events.emit("viewport:changed",{from:e.from,to:e.to}),this.viewportTimer!=null&&clearTimeout(this.viewportTimer),this.viewportTimer=setTimeout(()=>{if(this.viewportTimer=null,this.switchingMarket)return;let t=this.visibleRange;if(t){for(let n of this.registry.all())!n.renderHandle||n.hidden||(n.session&&n.prepared?.reactsToViewport?(n.pendingCause="viewport",n.session.setVisibleRange(t)):n.native?.descriptor.reactsToViewport&&n.native.instance.onViewport({from:t.left,to:t.right}));this.activeEngineStyle&&this.typeEngines.get(this.activeEngineStyle)?.onViewport?.({from:t.left,to:t.right});}},Pp);}async init(){let e=this.bumpGeneration();this.beginLoad(true),await this.loadMarket(e,{firstLoad:true}),this.generation===e&&(this.startLive(),this.events.emit("ready",void 0));}bumpGeneration(){let e=++this.generation;for(let t of this.supersedeWaiters.splice(0))t();return e}beginLoad(e){if(this.loadingUp)return;this.loadingUp=true,this.renderer.setLoading?.(true);let t=this.config.market;this.events.emit("load:start",{symbol:t.symbol??"TEST",timeframe:t.timeframe??"60",firstLoad:e});}endLoad(){if(!this.loadingUp)return;this.loadingUp=false,this.renderer.setLoading?.(false);let e=this.config.market;this.events.emit("load:end",{symbol:e.symbol??"TEST",timeframe:e.timeframe??"60",bars:this.bars.length});}async loadMarket(e,t){try{await this.loadMarketInner(e,t);}finally{this.generation===e&&this.endLoad();}}async loadMarketInner(e,t){let n=this.config.market,r=n.bars??500,i=n.visibleRange,o=!n.data?.length&&i==null&&r>Ip;if(o&&this.feed.loadRange){let a=await this.feed.load({...n,bars:Math.min(r,ol)});if(this.generation!==e)return;this.setBarSeries(a),t.firstLoad&&this.activateBarLayers(),a.length>0&&r>a.length?(this.historyState="backfill",this.backfillHistory(e,r)):this.completeHistory("depth");}else if(o){let a=await this.feed.load({...n,bars:kp});if(this.generation!==e)return;this.setBarSeries(a),t.firstLoad&&this.activateBarLayers();let l=await this.feed.load(n);if(this.generation!==e)return;this.setBarSeries(l,{preserveView:true}),this.completeHistory("depth");}else {let a=await this.feed.load(n);if(this.generation!==e)return;this.setBarSeries(a),t.firstLoad&&this.activateBarLayers(),this.completeHistory("depth");}i!=null&&(typeof i=="string"?this.setVisibleRangePreset(i):this.renderer.setVisibleRange(i)),this.refreshPriceFormat(),this.ensurePriceFormat();}startLive(){this.config.live&&(this.live=new mr(this.feed,this.config.market,e=>this.onBar(e)),this.live.start(),typeof document<"u"&&(this.onVisible=()=>{if(document.visibilityState!=="visible")return;let e=this.bars[this.bars.length-1];!e||this.healing||!this.canHeal()||Date.now()-this.lastHealAt<=sl||this.healGap(e.time);},document.addEventListener("visibilitychange",this.onVisible)));}stopLive(){this.live?.stop(),this.live=null,this.onVisible&&typeof document<"u"&&document.removeEventListener("visibilitychange",this.onVisible),this.onVisible=null,this.healing=false,this.healBuffer=[],this.lastHealAt=0;}resetHistoryTracking(){this.resolveHistoryComplete(),this.historyCompleted=false,this.historyState="complete",this.historyCompletePromise=new Promise(e=>{this.resolveHistoryComplete=e;});}marketSnapshot(){let e=this.config.market;return {symbol:e.symbol,provider:We(e.symbol??"").provider??void 0,timeframe:e.timeframe,bars:e.bars,offline:e.data!==void 0}}async setMarket(e){let t=this.config.market,n=e.symbol!==void 0&&e.symbol!==t.symbol||e.timeframe!==void 0&&e.timeframe!==t.timeframe||e.data!==void 0,r=e.bars!==void 0&&e.bars!==t.bars,i=r&&!n&&this.rawBars.length>0&&!t.data?.length&&((e.bars??0)<=this.rawBars.length||typeof this.feed.loadRange=="function");if(!n&&!r){typeof e.visibleRange=="string"?this.setVisibleRangePreset(e.visibleRange):e.visibleRange&&this.renderer.setVisibleRange(e.visibleRange);return}let o={symbol:t.symbol??"TEST",timeframe:t.timeframe??"60"},a=this.bumpGeneration();this.switchingMarket=true;try{if(this.stopLive(),this.viewportTimer!=null&&(clearTimeout(this.viewportTimer),this.viewportTimer=null),this.visibleRange=null,this.resetHistoryTracking(),e.symbol!==void 0&&(t.symbol=e.symbol),e.timeframe!==void 0&&(t.timeframe=e.timeframe),e.bars!==void 0&&(t.bars=e.bars),e.data!==void 0?t.data=e.data:e.symbol!==void 0&&delete t.data,t.visibleRange=e.visibleRange,n&&(this.beginLoad(!1),this.setBarSeries([],{clearing:!0}),this.activeEngineStyle&&(this.typeEngines.get(this.activeEngineStyle)?.suspend(),this.renderer.setNativeData?.(this.activeEngineStyle,void 0),this.renderer.setNativeData?.(`${this.activeEngineStyle}-pending`,[]))),i?this.extendDepth(a,t.bars??500):await Promise.race([this.loadMarket(a,{firstLoad:!1}),new Promise(l=>this.supersedeWaiters.push(l))]),this.generation!==a)return}finally{this.generation===a&&(this.switchingMarket=false);}i||(this.restartNativeIndicators(),this.restartChartTypeEngine(),this.reexecuteIndicators()),this.startLive(),n&&this.events.emit("market:changed",{symbol:t.symbol??"TEST",timeframe:t.timeframe??"60",prev:o});}restartNativeIndicators(){for(let e of this.registry.all())if(e.native)if(e.native.instance.stop(),e.native.instance=e.native.descriptor.create(),e.pendingStructural=true,e.hidden)e.native.stale=true;else {let t=this.handles.get(e.id);t&&this.startNativeIndicator(e.id,t);}}restartChartTypeEngine(){for(let e of this.typeEngines.values())e.stop();this.typeEngines.clear(),this.activeEngineStyle&&this.startChartTypeEngine(this.activeEngineStyle);}activateBarLayers(){this.maybeAutoAddVolume();}extendDepth(e,t){if(this.rawBars.length>t){this.setBarSeries(this.rawBars.slice(this.rawBars.length-t),{preserveView:true}),this.completeHistory("depth");return}if(this.rawBars.length===t){this.completeHistory("depth");return}this.historyState="backfill",this.backfillHistory(e,t);}async backfillHistory(e,t){try{for(;this.generation===e&&this.rawBars.length<t&&this.rawBars.length>0;){let n=t-this.rawBars.length,r=ol,i=await this.feed.loadRange(this.config.market,{to:this.rawBars[0].time,limit:Math.min(r,n)+1});if(this.generation!==e)return;let o=this.rawBars[0].time,a=i.filter(l=>l.time<o);if(a.length===0){this.completeHistory("genesis");return}for(let l=1;l<a.length;l+=1)if(a[l].time<=a[l-1].time){console.warn("[vela] non-monotonic history chunk \u2014 stopping the backfill"),this.completeHistory("aborted");return}this.setBarSeries([...a,...this.rawBars],{preserveView:!0}),this.notifySessionsBars("backfill"),this.events.emit("history:progress",{loaded:this.rawBars.length,target:t});}this.generation===e&&this.completeHistory("depth");}catch(n){console.warn(`[vela] history backfill failed \u2014 keeping ${this.rawBars.length} bars (${n instanceof Error?n.message:String(n)})`),this.generation===e&&this.completeHistory("aborted");}}completeHistory(e){this.historyCompleted||(this.historyCompleted=true,this.historyState="complete",this.notifySessionsBars("complete"),this.events.emit("history:complete",{reason:e,oldestTime:this.rawBars[0]?.time??0,barsLoaded:this.rawBars.length}),this.resolveHistoryComplete());}historyComplete(){return this.historyCompletePromise}qualifiedSymbol(){let e=this.config.market;return e.symbol?e.symbol:null}refreshPriceFormat(){if(!this.renderer.setPricePrecision)return;let e=this.feed.symbolInfo?.(this.config.market)?.mintick;this.renderer.setPricePrecision(typeof e=="number"&&e>0?e:void 0);}async ensurePriceFormat(){if(!this.renderer.setPricePrecision)return;let e=this.qualifiedSymbol();if(e)try{await this.dataControl.symbolInfo(e),this.refreshPriceFormat();}catch{}}maybeAutoAddVolume(){!this.config.volume||this.volumeOptedOut||!this.renderer.setNativeData||fn("volume")&&this.addNativeIndicator("volume");}syncPriceStyle(e){typeof e=="string"&&(this.priceStyle=e),this.syncBarTransform(e),this.syncChartTypeEngine(e);}syncChartTypeEngine(e){let t=typeof e=="string"?e:null,r=Ue(t)?.dataEngine?t:null;r!==this.activeEngineStyle&&(this.activeEngineStyle&&this.typeEngines.get(this.activeEngineStyle)?.suspend(),this.activeEngineStyle=r,r&&this.startChartTypeEngine(r));}async startChartTypeEngine(e){if(!this.renderer.setNativeData||(await this.readyPromise,this.activeEngineStyle!==e))return;let t=this.typeEngines.get(e);if(t){t.resume();return}let n=Ue(e);if(!n?.dataEngine)return;let r=n.dataEngine();this.typeEngines.set(e,r);let i=this.typeSettings.get(e);i&&r.onSettings?.(i),r.start({symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",live:this.config.live??false,bars:()=>this.bars,data:this.dataControl,pushData:o=>this.renderer.setNativeData?.(e,o),pushPending:o=>this.renderer.setNativeData?.(`${e}-pending`,o)});}syncBarTransform(e){let t=Ii(e);t!==this.barTransform&&(this.barTransform=t,this.rawBars.length!==0&&(this.bars=t?t.full(this.rawBars):this.rawBars,this.renderer.setBars(this.bars,{preserveView:true}),this.reexecuteIndicators()));}reexecuteIndicators(){for(let e of this.registry.all()){if(e.hidden||!e.session)continue;e.session.stop(),e.session=void 0,e.pendingStructural=true,e.pendingCause="market",this.setLoading(e,true);let t=this.handles.get(e.id);t&&this.executeIndicator(e.id,t);}}onBar(e){if(this.healing){this.healBuffer.push(e);return}let t=this.rawBars[this.rawBars.length-1];if(t&&this.canHeal()&&e.time>t.time+this.barIntervalMs()*Rp&&Date.now()-this.lastHealAt>sl){this.healBuffer.push(e),this.healGap(t.time);return}this.applyBar(e);}setBarSeries(e,t){this.rawBars=e,this.bars=this.barTransform?this.barTransform.full(e):e,this.renderer.setBars(this.bars,{preserveView:t?.preserveView}),!t?.clearing&&this.bars.length>0&&this.endLoad();}applyBar(e,t=true){let n=this.rawBars[this.rawBars.length-1],r=e;if(n&&e.time===n.time)this.rawBars[this.rawBars.length-1]=e,this.barCause="tick",this.barTransform&&(r=this.barTransform.next(e,this.bars[this.bars.length-2]),this.bars[this.bars.length-1]=r);else if(!n||e.time>n.time)this.rawBars.push(e),this.barCause="bar",this.barTransform&&(r=this.barTransform.next(e,this.bars[this.bars.length-1]),this.bars.push(r));else return;this.renderer.updateBar(r),this.events.emit("bar",e),t&&this.notifySessionsBars(this.historyState==="backfill"?"backfill":void 0);}notifySessionsBars(e){if(this.switchingMarket)return;let t=e?"history":this.barCause;for(let n of this.registry.all())!n.renderHandle||n.hidden||(n.session?(n.pendingCause=t,n.session.notifyBars(e)):n.native&&n.native.instance.onBars());}canHeal(){return !!this.feed.loadRange&&!this.config.market.data?.length}barIntervalMs(){return In(this.config.market.timeframe??"60")}async healGap(e){let t=this.generation;this.healing=true,this.lastHealAt=Date.now();try{let n=await this.feed.loadRange(this.config.market,{from:e});if(this.generation!==t)return;for(let r of n)this.applyBar(r,!1);}catch{}finally{if(this.generation===t){this.healing=false;let n=this.healBuffer;this.healBuffer=[];for(let r of n)this.applyBar(r,false);this.notifySessionsBars(this.historyState==="backfill"?"backfill":void 0);}}}registerEngine(e,t){let n=this.engines.get(e);n&&n!==t&&console.warn(`[vela] re-registering scripting engine for language "${e}"; replacing ${n.constructor.name} with ${t.constructor.name}.`),this.engines.set(e,t);}addIndicator(e,t={}){let n=this.registry.nextId(),r=t.title??"Indicator",i=new Nt(n,r,this,e);return this.handles.set(n,i),this.registry.add({id:n,title:r,source:e,options:t,inputValues:{...t.inputs??{}}}),this.startIndicator(n,e,t,i),i}addNativeIndicator(e,t={}){let n=this.registry.all().find(c=>c.native?.type===e);if(n)return this.handles.get(n.id)??new Nt(n.id,n.title,this);let r=fn(e),i=this.registry.nextId("native"),o=r?.title??e,a=new Nt(i,o,this);if(this.handles.set(i,a),!r)return console.warn(`[vela] addNativeIndicator("${e}") \u2014 no native indicator registered for this type.`),a;let l={...r.defaultInputs(),...t.inputs??{}};return this.registry.add({id:i,title:o,source:e,inputValues:l,native:{type:e,instance:r.create(),descriptor:r}}),a.setSchema(r.inputsSchema()),this.startNativeIndicator(i,a),a}presentNativeIndicators(){return this.registry.all().map(e=>e.native?.type).filter(e=>!!e)}async availableNativeIndicators(){let e=this.qualifiedSymbol(),t=new Set(this.presentNativeIndicators());return Promise.all(pr().map(async n=>({type:n.type,title:n.title,supported:await this.isNativeSupported(n,e),present:t.has(n.type),beta:n.beta})))}async isNativeSupported(e,t){if(!e.isSupported)return true;if(!t)return false;try{return await e.isSupported(t,this.dataControl)}catch{return false}}applyInputs(e,t){let n=this.registry.get(e);!n||!n.session&&!n.native||(n.inputValues={...n.inputValues,...t},n.renderHandle&&this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues),n.pendingStructural=true,!n.hidden&&!n.native&&this.setLoading(n,true),n.pendingCause="inputs",n.session?n.session.update(n.inputValues):n.native&&!n.hidden&&n.native.instance.setInputs(n.inputValues));}listIndicators(){return [...this.handles.values()]}getIndicatorContext(e,t){return this.registry.get(e)?.session?.getContext?.(t)??Promise.resolve(null)}removeIndicator(e){let t=this.registry.remove(e);t?.native?.type==="volume"&&(this.volumeOptedOut=true),t?.session?.stop(),t?.native?.instance.stop(),this.handles.delete(e),t?.renderHandle&&this.renderer.removeIndicator(t.renderHandle);let n=t?.model?.paneId;n&&n!=="price"&&!this.paneStillUsed(n)&&(this.renderer.removePane(n),this.forgetPane(n),this.events.emit("pane:changed",void 0)),this.events.emit("indicator:removed",{id:e});}setVisible(e,t){let n=this.registry.get(e);if(!(!n||n.hidden===!t)){if(n.hidden=!t,this.handles.get(e)?.setVisibleState(t),!t)n.session?.stop(),n.session=void 0,n.native?.instance.suspend(),n.renderHandle&&this.renderer.setIndicatorVisible?.(n.renderHandle,false);else if(n.renderHandle&&this.renderer.setIndicatorVisible?.(n.renderHandle,true),n.pendingStructural=true,n.native)if(n.native.stale){n.native.stale=false;let r=this.handles.get(e);r&&this.startNativeIndicator(e,r);}else n.native.instance.resume();else {this.setLoading(n,true);let r=this.handles.get(e);r&&this.executeIndicator(e,r);}this.events.emit("indicator:visibility",{id:e,visible:t});}}ready(){return this.readyPromise}inspect(){let e=[...this.registry.all()].filter(t=>!t.loading).sort((t,n)=>(n.native?1:0)-(t.native?1:0));return fa(e.map(t=>t.model).filter(t=>t!=null))}resize(){this.renderer.resize();}setTheme(e){let t=this.config.theme;Object.keys(e).every(n=>e[n]===t[n])||(this.config.theme=e,this.renderer.setTheme(e),this.events.emit("theme:changed",e));}getVisibleRange(){return this.renderer.getVisibleRange()}setVisibleRange(e){this.renderer.setVisibleRange(e);}panBy(e){if(this.renderer.panBy){this.renderer.panBy(e);return}let t=this.renderer.getVisibleRange();if(!t)return;let n=(t.to-t.from)*e;this.renderer.setVisibleRange({from:t.from+n,to:t.to+n});}setVisibleRangePreset(e){let t=ba(e,this.bars);t&&this.renderer.setVisibleRange(t);}destroy(){this.bumpGeneration(),this.resolveHistoryComplete(),this.stopLive(),this.viewportTimer!=null&&clearTimeout(this.viewportTimer),this.viewportUnsub?.(),this.paneActionUnsub?.();for(let e of this.registry.all())e.session?.stop(),e.native?.instance.stop();for(let e of this.typeEngines.values())e.stop();this.typeEngines.clear(),this.activeEngineStyle=null,this.unresolvedUnsub?.(),this.unresolvedUnsub=null,this.feed.destroy?.(),this.drawings.destroy(),this.renderer.destroy(),this.events.clear();}async startIndicator(e,t,n,r){try{if(await this.readyPromise,!this.registry.get(e))return;await Dp();let i=this.registry.get(e);if(!i)return;let o=this.engineFor(n.language);i.engine=o;let a=await o.prepare(t,e);i.prepared=a;let l={};for(let c of a.inputs)l[c.key]=c.defval;i.inputValues={...l,...i.inputValues},r.setSchema(a.inputs),this.mountLoadingPlaceholder(e,i),this.executeIndicator(e,r);}catch(i){this.fail(e,r,i);}}executeIndicator(e,t){let n=this.registry.get(e);if(!n||!n.engine||!n.prepared||n.hidden)return;let r=this.config.live&&!n.prepared.reactsToViewport&&n.engine.capabilities.streaming?"live":"static";n.session=n.engine.execute({prepared:n.prepared,market:this.market(),bars:this.bars,getBars:()=>this.bars,fetchSeries:(i,o,a)=>this.fetchSeries(i,o,a),inputs:n.inputValues,visibleRange:this.currentVisibleRange(),mode:r,historyState:this.historyState},{onModel:i=>{let o=!n.announced,a=n.pendingCause??"history";n.pendingCause=void 0,this.applyModel(e,i),this.emitContextChanged(e),this.emitScriptRun(e,a,o);},onAlert:i=>{this.events.emit("alert",i),t.emit("alert",{id:i.id,message:i.message,title:i.title,time:i.time});},onWarning:i=>this.events.emit("warning",i),onError:i=>this.fail(e,t,i)}),this.emitContextChanged(e);}async startNativeIndicator(e,t){try{await this.readyPromise;let n=this.registry.get(e);if(!n?.native||n.hidden)return;let r={symbol:this.config.market.symbol??"TEST",timeframe:this.config.market.timeframe??"60",live:this.config.live,bars:()=>this.bars,data:this.dataControl,emit:i=>this.applyModel(e,this.buildNativeModel(n,i)),pushData:i=>this.renderer.setNativeData?.(n.native.type,i),setStatus:i=>{n.renderHandle&&!n.hidden&&this.renderer.setIndicatorStatus?.(n.renderHandle,i);}};n.native.instance.start(r,n.inputValues);}catch(n){this.fail(e,t,n);}}buildNativeModel(e,t){let n=e.native.descriptor;return {id:e.id,title:e.title,...n.shortTitle?{shorttitle:n.shortTitle}:{},overlay:n.overlay,paneHint:n.paneHint,native:{type:e.native.type},series:t.series??[],fills:t.fills??[],backgrounds:t.backgrounds??[],priceLines:t.priceLines??[],...t.lines?{lines:t.lines}:{},...t.boxes?{boxes:t.boxes}:{},...t.labels?{labels:t.labels}:{},...t.polylines?{polylines:t.polylines}:{},...t.linefills?{linefills:t.linefills}:{},...t.tables?{tables:t.tables}:{},inputs:n.inputsSchema(),inputValues:e.inputValues}}mountLoadingPlaceholder(e,t){if(t.renderHandle||t.hidden||!t.prepared)return;let n=t.prepared.meta,r={id:e,title:t.options?.title??n.title,overlay:n.overlay,paneHint:n.overlay?"price":"new",series:[],fills:[],backgrounds:[],priceLines:[],inputs:t.prepared.inputs,inputValues:t.inputValues},i=this.routePane(e,r,t.options??{});this.placeModel(r,e,i),t.model=r,this.ensurePaneFor(i),t.renderHandle=this.renderer.mountIndicator(r),t.pendingStructural=true,this.setLoading(t,true);}setLoading(e,t){e.loading=t,e.renderHandle&&!e.hidden&&this.renderer.setIndicatorStatus?.(e.renderHandle,t?"loading":"idle");}ensurePaneFor(e){this.paneOrder.includes(e)||this.paneOrder.push(e),this.renderer.ensurePane({id:e,kind:e==="price"?"price":"study",order:this.paneOrder.indexOf(e)});}paneStillUsed(e){for(let t of this.registry.all())if(t.model?.paneId===e)return true;return false}forgetPane(e){let t=this.paneOrder.indexOf(e);t>0&&this.paneOrder.splice(t,1),this.collapsedPanes.delete(e),this.maximizedPaneId===e&&(this.maximizedPaneId=null);}paneManagementSupported(){return this.renderer.capabilities.paneManagement===true&&typeof this.renderer.setIndicatorPane=="function"}listPanes(){let e=new Map;for(let n of this.registry.all()){let r=n.model;if(!r)continue;let i=r.paneId??"price";e.has(i)||e.set(i,[]),e.get(i).push({id:n.id,title:r.title||n.title,ownScale:r.ownScale===true});}let t=[];for(let n of this.paneOrder)n!=="price"&&!e.has(n)||t.push({id:n,kind:n==="price"?"price":"study",order:t.length,collapsed:this.collapsedPanes.has(n),maximized:this.maximizedPaneId===n,indicators:e.get(n)??[]});return t}movePane(e,t){if(e==="price")return;let n=this.existingPaneIds(),r=n.indexOf(e);if(r<0)return;let i=t==="up"?r-1:r+1;i<=0||i>=n.length||([n[r],n[i]]=[n[i],n[r]],this.reorderPanes(n),this.events.emit("pane:moved",{paneId:e,dir:t}));}removePaneAndIndicators(e){if(e!=="price")for(let t of [...this.registry.all()])t.model?.paneId===e&&this.removeIndicator(t.id);}collapsePane(e,t){t?this.collapsedPanes.add(e):this.collapsedPanes.delete(e),this.renderer.setPaneCollapsed?.(e,t),this.events.emit("pane:changed",void 0);}maximizePane(e){this.maximizedPaneId=e,this.renderer.setPaneMaximized?.(e),this.events.emit("pane:changed",void 0);}moveIndicator(e,t){if(!this.paneManagementSupported()||!this.renderer.setIndicatorPane){console.warn("[vela] the active renderer does not support moving indicators between panes.");return}let n=this.registry.get(e);if(!n?.renderHandle||!n.model)return;let r=n.model,i=r.paneId??"price",o=this.resolveMoveTarget(e,r,t);if(!o)return;let{paneId:a,ownScale:l,insert:c}=o;a===i&&r.ownScale===true===l||(c?this.insertPaneOrder(a,c):this.paneOrder.includes(a)||this.paneOrder.push(a),r.ownScale=l,n.paneLocked=true,this.placeModel(r,e,a),this.ensurePaneFor(a),this.renderer.setIndicatorPane(n.renderHandle,a,{ownScale:l}),i!=="price"&&i!==a&&!this.paneStillUsed(i)&&(this.renderer.removePane(i),this.forgetPane(i)),this.reorderPanes(this.existingPaneIds()),this.events.emit("indicator:moved",{id:e,paneId:a}),this.events.emit("pane:changed",void 0));}resolveMoveTarget(e,t,n){if(n==="price"||typeof n=="object"&&"pane"in n&&n.pane==="price")return {paneId:"price",ownScale:!t.overlay};if("pane"in n)return this.existingPaneIds().includes(n.pane)?{paneId:n.pane,ownScale:true}:null;let r=n.newPane===true?{}:n.newPane;return {paneId:this.freshPaneId(e,t.paneId??"price"),ownScale:false,insert:r}}freshPaneId(e,t){let n=new Set(this.existingPaneIds()),r=`pane-${e}`;for(let i=2;r===t||n.has(r);i+=1)r=`pane-${e}-${i}`;return r}insertPaneOrder(e,t){let n=this.paneOrder.indexOf(e);n>0&&this.paneOrder.splice(n,1);let r=this.paneOrder.length;t.before&&this.paneOrder.includes(t.before)?r=this.paneOrder.indexOf(t.before):t.after&&this.paneOrder.includes(t.after)&&(r=this.paneOrder.indexOf(t.after)+1),r<1&&(r=1),this.paneOrder.splice(r,0,e);}existingPaneIds(){return this.paneOrder.filter(e=>e==="price"||this.paneStillUsed(e))}reorderPanes(e){this.paneOrder.length=0,this.paneOrder.push(...e),this.renderer.orderPanes?.(e),this.events.emit("pane:changed",void 0);}handlePaneAction(e){switch(e.type){case "remove":this.removePaneAndIndicators(e.paneId);break;case "move":{let t=this.existingPaneIds(),n=t.indexOf(e.paneId),r=e.dir==="up"?n-1:n+1;n>0&&r>0&&r<t.length&&([t[n],t[r]]=[t[r],t[n]],this.paneOrder.length=0,this.paneOrder.push(...t),this.events.emit("pane:changed",void 0),this.events.emit("pane:moved",{paneId:e.paneId,dir:e.dir}));break}case "collapse":e.collapsed?this.collapsedPanes.add(e.paneId):this.collapsedPanes.delete(e.paneId),this.events.emit("pane:changed",void 0);break;case "maximize":this.maximizedPaneId=e.maximized?e.paneId:null,this.events.emit("pane:changed",void 0);break}}announce(e,t){e.announced||(e.announced=true,this.events.emit("indicator:added",{id:e.id}),this.emitContextChanged(e.id),t?.emit("ready",void 0));}applyModel(e,t){let n=this.registry.get(e);if(!n||n.hidden)return;let r=this.handles.get(e);if(!n.renderHandle){let a=this.routePane(e,t,n.options??{});this.placeModel(t,e,a),n.model=t,this.ensurePaneFor(a),n.renderHandle=this.renderer.mountIndicator(t),n.pendingStructural=false,this.announce(n,r);return}let i=n.model?.paneId??"price",o=n.model?.ownScale===true;if(n.loading&&!n.paneLocked){let a=this.routePane(e,t,n.options??{});a!==i&&(i!=="price"&&(this.renderer.removePane(i),this.forgetPane(i)),this.ensurePaneFor(a),n.pendingStructural=true,i=a);}this.placeModel(t,e,i),n.paneLocked&&(t.ownScale=o),n.model=t,n.pendingStructural?(n.renderHandle=this.renderer.mountIndicator(t),this.renderer.setIndicatorInputs(n.renderHandle,n.inputValues),n.pendingStructural=false):this.renderer.updateIndicator(n.renderHandle,Ap(t)),n.loading&&this.setLoading(n,false),this.announce(n,r);}routePane(e,t,n){return n.pane==="new"?`pane-${e}`:n.pane==="price"||(n.overlay??t.overlay)?"price":`pane-${e}`}static plotsAtLastBar(e){let t={};for(let n of e.series)le(n)&&(t[n.title]=n.points[n.points.length-1]?.value??null);return t}placeModel(e,t,n){e.id=t,e.paneId=n;for(let r of e.series)r.paneId=n;for(let r of e.fills)r.paneId=n;for(let r of e.backgrounds)r.paneId=n;for(let r of e.priceLines)r.paneId=n;if(e.lines)for(let r of e.lines)r.paneId=n;if(e.boxes)for(let r of e.boxes)r.paneId=n;if(e.labels)for(let r of e.labels)r.paneId=n;if(e.polylines)for(let r of e.polylines)r.paneId=n;if(e.linefills)for(let r of e.linefills)r.paneId=n;if(e.tables)for(let r of e.tables)r.paneId=n;}emitContextChanged(e){if(!this.registry.get(e)?.session?.getContext)return;let t=Date.now();t-(this.contextEmitAt.get(e)??0)<1e3||(this.contextEmitAt.set(e,t),this.events.emit("context:changed",{id:e}));}emitScriptRun(e,t,n){let r=this.registry.get(e);if(!r||r.native||!this.events.hasListeners("script:run"))return;let i=Date.now();t==="tick"&&i-(this.runEmitAt.get(e)??0)<Ep||(this.runEmitAt.set(e,i),Promise.resolve().then(()=>this.buildScriptRun(r,t,n)).then(o=>{o&&this.registry.get(e)&&this.events.emit("script:run",o);}));}async buildScriptRun(e,t,n){let r=e.model;if(!r)return null;let i=await this.pullContext(e,["variables","strategy","warnings"]),o=this.bars[this.bars.length-1];return {id:e.id,title:r.title,kind:i?.strategy||(r.trades?.length??0)>0?"strategy":"indicator",cause:t,first:n,bar:Math.max(0,this.bars.length-1),time:o?.time??0,forming:this.config.live&&this.bars.length>0,complete:this.historyState!=="backfill",plots:s.plotsAtLastBar(r),vars:i?.variables??{},...i?.strategy?{strategy:i.strategy}:{},warnings:i?.warnings??[],trades:async()=>(await this.pullContext(e,["trades"]))?.trades??[],series:async a=>((await this.pullContext(e,["plots"]))?.plots?.[a]??[]).map(c=>({time:c.time,value:typeof c.value=="number"?c.value:null}))}}async pullContext(e,t){try{return await e.session?.getContext?.(t)??null}catch{return null}}fail(e,t,n){let r=this.registry.get(e);r?.loading&&this.setLoading(r,false);let i=n instanceof Error?n:new Error(String(n));console.error(`[vela] indicator "${e}" failed:`,i.message),this.events.emit("indicator:error",{id:e,error:i}),t?.emit("error",{error:i});}};function Dp(){return typeof requestAnimationFrame=="function"?new Promise(s=>requestAnimationFrame(()=>requestAnimationFrame(()=>s()))):new Promise(s=>setTimeout(s,0))}function Ap(s){let e=[],t=Number.POSITIVE_INFINITY,n=0;for(let r of s.series)if(r.kind==="candle"||r.kind==="bar"){e.push({seriesId:r.id,kind:"bars",bars:r.bars});for(let i of r.bars)i.time<t&&(t=i.time),i.time>n&&(n=i.time);}else if(le(r)){e.push({seriesId:r.id,kind:"points",points:r.points});for(let i of r.points)i.time<t&&(t=i.time),i.time>n&&(n=i.time);}return {kind:"value",indicatorId:s.id,dirty:{from:Number.isFinite(t)?t:0,to:n},anchorTime:s.anchorTime??null,series:e,lines:s.lines??[],boxes:s.boxes??[],labels:s.labels??[],polylines:s.polylines??[],linefills:s.linefills??[],tables:s.tables??[],trades:s.trades??[]}}var On=class{constructor(e){this.renderer=e;}get name(){return this.renderer.name}get capabilities(){return this.renderer.capabilities}supports(e){return this.renderer.features.includes(e)}get(e){return this.renderer.readFeature(e)}set(e,t){let n=typeof e=="string"?[[e,t]]:Object.entries(e);for(let[r,i]of n)this.renderer.features.includes(r)?this.renderer.applyFeature(r,i):console.warn(`[vela] renderer "${this.renderer.name}" has no feature "${r}" \u2014 set ignored.`);return this}setLegendActions(e){this.renderer.setLegendActions?.(e);}setLegendOverviewAction(e){return this.renderer.setLegendOverviewAction?.(e),this}get supportsIndicatorSettings(){return typeof this.renderer.openIndicatorSettings=="function"}openIndicatorSettings(e){return this.renderer.openIndicatorSettings?.(e),this}screenshot(){return typeof this.renderer.screenshot=="function"?this.renderer.screenshot():(console.warn(`[vela] renderer "${this.renderer.name}" does not support screenshot().`),null)}getConfig(){return typeof this.renderer.getConfig=="function"?this.renderer.getConfig():(console.warn(`[vela] renderer "${this.renderer.name}" does not support getConfig().`),null)}applyConfig(e){return typeof this.renderer.applyConfig=="function"?this.renderer.applyConfig(e):console.warn(`[vela] renderer "${this.renderer.name}" does not support applyConfig().`),this}onConfigChanged(e){return this.renderer.onConfigChanged?.(e)??(()=>{})}onCrosshairMove(e){return this.renderer.onCrosshairMove(e)}onAxisLongPress(e){return this.renderer.onAxisLongPress?.(e)??(()=>{})}dataWindowReadout(){return this.renderer.getDataWindowReadout?.()??null}setSymbolPicker(e){return typeof this.renderer.setSymbolPicker=="function"?this.renderer.setSymbolPicker(e):console.warn(`[vela] renderer "${this.renderer.name}" does not support setSymbolPicker().`),this}focus(){return this.renderer.focus?.(),this}get supportsExternalCrosshair(){return typeof this.renderer.setExternalCrosshair=="function"}setExternalCrosshair(e,t=null){return this.renderer.setExternalCrosshair?.(e,t),this}closeDialogs(){return this.renderer.closeDialogs?.(),this}openSettings(e){return this.renderer.openSettingsDialog?.(e),this}setSettingsSections(e){return this.renderer.setSettingsSections?.(e),this}setLayoutMode(e){return this.renderer.setLayoutMode?.(e),this}};var Kt=new Map;function Op(s){let e=Object.entries(s);for(let[t,n]of e)Kt.set(t,n);return ()=>{for(let[t,n]of e)Kt.get(t)===n&&Kt.delete(t);}}function Fp(...s){if(s.length===0)Kt.clear();else for(let e of s)Kt.delete(e);}function Go(){return Object.fromEntries(Kt)}var Di=class{constructor(e){this.controller=e;}get supported(){return this.controller.paneManagementSupported()}list(){return this.controller.listPanes()}move(e,t){return this.guard()&&this.controller.movePane(e,t),this}remove(e){return this.guard()&&this.controller.removePaneAndIndicators(e),this}collapse(e,t=true){return this.guard()&&this.controller.collapsePane(e,t),this}maximize(e){return this.guard()&&this.controller.maximizePane(e),this}moveIndicator(e,t){return this.guard()&&this.controller.moveIndicator(e,t),this}guard(){return this.controller.paneManagementSupported()?true:(console.warn("[vela] the active renderer does not support pane management \u2014 chart.panes mutation ignored."),false)}};function al(s,e,t){return `${s}|${e}|${t}`}function Bp(s){return s.split("|")[1]??""}var Ai=class{constructor(){this.series=new Map;this.coveredFrom=new Map;this.retained=new Set;}get(e){return this.series.get(e)}markCovered(e,t){this.coveredFrom.set(e,Math.min(this.coveredFrom.get(e)??1/0,t));}coveredFromOf(e){return this.coveredFrom.get(e)}merge(e,t){if(t.length===0)return this.series.get(e)??[];let n=new Map;for(let i of this.series.get(e)??[])n.set(i.time,i);for(let i of t)n.set(i.time,i);let r=[...n.values()].sort((i,o)=>i.time-o.time);return this.series.set(e,r),r}retainSymbol(e){this.currentSymbol!==e&&(this.currentSymbol=e,this.purgeOutside(e));}retain(e){this.retained=new Set(e),this.purgeOutside(this.currentSymbol);}purgeOutside(e){for(let t of [...this.series.keys()]){let n=Bp(t);n!==e&&!this.retained.has(n)&&(this.series.delete(t),this.coveredFrom.delete(t));}}clear(){this.series.clear(),this.coveredFrom.clear();}},Fn=new Ai;function ll(s,e){let{provider:t,ticker:n}=We(s);return al(t??"",n,e)}var Bn=1e4,Vp=Bn+1,Vn=class{constructor(e,t=Fn){this.inner=e;this.store=t;}async load(e){if(e.data&&e.data.length>0)return this.inner.load(e);let t=e.symbol??"TEST",n=ll(t,e.timeframe??"60");this.store.retainSymbol(t);let r=this.store.get(n),i=e.bars??500,o=r?.[r.length-1];if(r&&o&&r.length>=i-1&&this.inner.loadRange){let{bars:l}=await this.fetchRange(e,{from:o.time}),c=this.store.merge(n,Oi(l));return cl(c,l[l.length-1]).slice(-i)}let a=await this.inner.load(e);return this.store.merge(n,Oi(a)),a}async loadRange(e,t){if(!this.inner.loadRange)return this.inner.load(e);let n=ll(e.symbol??"TEST",e.timeframe??"60"),r=this.store.get(n),i=r?.[r.length-1];if(t.to!=null&&i&&t.to<i.time){let d=r.filter(f=>f.time<=t.to),h=this.store.coveredFromOf(n)??1/0;if(t.limit!=null?d.length>=t.limit&&(t.from==null||h<=t.from):t.from!=null&&h<=t.from){let f=t.from!=null?d.filter(b=>b.time>=t.from):d;return t.limit!=null&&f.length>t.limit&&(f=f.slice(-t.limit)),f}let p=await this.fetchRange(e,t),m=p.bars.filter(f=>f.time<=t.to);return m.length>0&&(this.store.merge(n,m),this.store.markCovered(n,p.coveredDownTo??m[0].time)),m}if(i&&t.from!=null){let d=this.store.coveredFromOf(n);if(d!=null&&d>t.from){let{bars:h,coveredDownTo:u}=await this.fetchRange(e,{from:t.from,to:d});this.store.merge(n,h.filter(p=>p.time<=d)),this.store.markCovered(n,u??t.from),r=this.store.get(n),i=r?.[r.length-1];}}let o=this.store.coveredFromOf(n);if(!!r&&r.length>0&&!!i&&(t.from!=null?o!=null&&o<=t.from:t.limit==null||r.length>=t.limit)&&i){let{bars:d}=await this.fetchRange(e,{from:i.time,to:t.to,limit:t.limit}),h=this.store.merge(n,Oi(d)),u=cl(h,d[d.length-1]),p=t.from!=null?u.filter(m=>m.time>=t.from):u;return t.to!=null&&(p=p.filter(m=>m.time<=t.to)),p}let{bars:l,coveredDownTo:c}=await this.fetchRange(e,t);return this.store.merge(n,Oi(l)),this.store.markCovered(n,c??t.from??l[0]?.time??0),l}async fetchRange(e,t){let n=In(e.timeframe??"60"),r=_p(t,n);if(r<=Vp){let c=await this.inner.loadRange(e,{...t,limit:t.limit??r});return {bars:c,coveredDownTo:t.from??c[0]?.time}}let i=new Map,o=t.to??Date.now();for(;!(t.from!=null&&o<t.from);){let c=t.limit!=null?t.limit-i.size:Bn;if(c<=0)break;let d=await this.inner.loadRange(e,{to:o,limit:Math.min(Bn,c)}),h=1/0;for(let u of d)u.time<h&&(h=u.time),u.time<=o&&(t.from==null||u.time>=t.from)&&i.set(u.time,u);if(d.length===0){if(t.from==null)break;o-=Bn*n;continue}if(h-1>=o)break;o=h-1;}let a=[...i.values()].sort((c,d)=>c.time-d.time),l=t.from!=null&&o<t.from;return {bars:a,coveredDownTo:l?t.from:a[0]?.time}}subscribe(e,t){return this.inner.subscribe(e,t)}symbolInfo(e){return this.inner.symbolInfo?.(e)}};function _p(s,e){if(s.limit!=null)return s.limit;if(s.from==null)return Bn;let t=Math.max(0,(s.to??Date.now())-s.from);return Math.ceil(t/e*1.1)+2}function Oi(s){return s.length>0?s.slice(0,-1):s}function cl(s,e){if(!e)return s;let t=s[s.length-1];return !t||e.time>t.time?[...s,e]:s}function Np(s){return {"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,1:6e4,5:3e5,15:9e5,30:18e5,60:36e5,240:144e5,D:864e5,W:6048e5}[s]??36e5}var Pt=class{constructor(e=Fn){this.registry=new Ei;this.primaryProvider=null;this.liveBars=[];this.symInfoCache=new Map;this.cache=new Vn(new Ko(this.registry),e);}registerProvider(e,t){return this.registry.register(e,t)}unregisterProvider(e){this.registry.unregister(e);}providers(){return this.registry.names().map(e=>this.registry.infoOf(e))}resolveSymbol(e){return this.registry.resolve(e,{default:this.primaryProvider})}providerInstance(e){return this.registry.get(e)}symbols(e){return this.registry.symbolsOf(e)}onUnresolved(e){return this.registry.onUnresolved(e)}destroy(){this.registry.cancelWaits();}ready(){return this.registry.indexReady()}async symbolInfoFor(e){let t=this.registry.resolve(e,{default:this.primaryProvider});if(!t)return;let n=await this.registry.get(t.provider)?.getSymbolInfo?.(t.ticker);return n&&this.symInfoCache.set(Xo(t),n),n}capabilitiesFor(e){let t=this.registry.resolve(e,{default:this.primaryProvider});if(!t)return null;let n=this.registry.get(t.provider);return n?n.capabilitiesFor?.(t.ticker)??this.registry.infoOf(t.provider).capabilities:null}async load(e){if(e.data&&e.data.length>0)return this.liveBars=e.data.map(n=>({...n})),e.data;let t=await this.registry.whenResolvable(Fi(e),{default:this.primaryProvider});return this.primaryProvider=t.provider,this.prefetchSymbolInfo(t),this.cache.load(Yo(e,t))}symbolInfo(e){if(e.data&&e.data.length>0)return;let t=this.registry.resolve(Fi(e),{default:this.primaryProvider});return t?this.symInfoCache.get(Xo(t)):void 0}prefetchSymbolInfo(e){let t=Xo(e);if(this.symInfoCache.has(t))return;let n=this.registry.get(e.provider);n?.getSymbolInfo&&n.getSymbolInfo(e.ticker).then(r=>{r&&this.symInfoCache.set(t,r);}).catch(()=>{});}async loadRange(e,t){if(e.data&&e.data.length>0)return this.cache.loadRange(e,t);let n=this.registry.resolve(Fi(e),{default:this.primaryProvider});return n?this.cache.loadRange(Yo(e,n),t):[]}subscribe(e,t){if(e.data&&e.data.length>0)return this.synthesizeTicks(e,t);let n=this.registry.resolve(Fi(e),{default:this.primaryProvider});return n?this.cache.subscribe(Yo(e,n),t):()=>{}}synthesizeTicks(e,t){if(this.liveBars.length===0)return ()=>{};let n=Np(e.timeframe??"60"),r=setInterval(()=>{let i=this.liveBars,o=i[i.length-1];if(!o)return;let a=o.close*.0015*(Math.random()-.5)*2,l=Math.max(0,o.close+a),c={...o,close:l,high:Math.max(o.high,l),low:Math.min(o.low,l)};if(i[i.length-1]=c,t(c),Math.random()<.12){let d={time:c.time+n,open:c.close,high:c.close,low:c.close,close:c.close,volume:0};i.push(d),t(d);}},1e3);return ()=>clearInterval(r)}};function Fi(s){return s.symbol??""}function Yo(s,e){return {...s,symbol:`${e.provider}:${e.ticker}`}}function Xo(s){return `${s.provider}|${s.ticker}`}async function dl(s,e,t,n){try{return await s.getBars(e,t,n)}catch(r){return console.warn(`[vela] data fetch failed for ${e} ${t} \u2014 ${r instanceof Error?r.message:String(r)}`),[]}}var Ko=class{constructor(e){this.registry=e;}load(e){let{provider:t,ticker:n}=We(e.symbol??""),r=this.registry.get(t??"");return r?dl(r,n,e.timeframe??"60",{limit:e.bars??500}):Promise.resolve([])}loadRange(e,t){let{provider:n,ticker:r}=We(e.symbol??""),i=this.registry.get(n??"");return i?dl(i,r,e.timeframe??"60",t):Promise.resolve([])}subscribe(e,t){let{provider:n,ticker:r}=We(e.symbol??""),i=this.registry.get(n??"");if(!i)return ()=>{};let o=e.timeframe??"60";if(i.subscribe)return i.subscribe(r,o,t);let a=false,l=null,c=async()=>{if(!a){try{let d=await i.getBars(r,o,{limit:2});if(a)return;for(let h of d)t(h);}catch{}a||(l=setTimeout(()=>{c();},3e3));}};return l=setTimeout(()=>{c();},3e3),()=>{a=true,l&&clearTimeout(l);}}};var _n=class{constructor(e){this.registry=e instanceof Pt?e:null;}registerProvider(e,t){return this.registry?(this.registry.registerProvider(e,t),this):(console.warn(`[vela] chart.data.registerProvider("${e}") ignored \u2014 the active data feed is a custom feed (deps.dataFeed), not the default provider registry.`),this)}unregisterProvider(e){return this.registry?.unregisterProvider(e),this}providers(){return this.registry?.providers()??[]}resolve(e){return this.registry?.resolveSymbol(e)??null}providerInstance(e){return this.registry?.providerInstance(e)}symbols(e){return this.registry?.symbols(e)??[]}symbolInfo(e){return this.registry?.symbolInfoFor(e)??Promise.resolve(void 0)}capabilities(e){return this.registry?.capabilitiesFor(e)??null}ready(){return this.registry?.ready()??Promise.resolve()}};var Nn=class{constructor(e){this.ctrl=e;}get supported(){return this.ctrl.supported}setTool(e){return this.ok("setTool")&&this.ctrl.setTool(e),this}getTool(){return this.ctrl.getTool()}setSnapMode(e){return this.ok("setSnapMode")&&this.ctrl.setSnapMode(e),this}getSnapMode(){return this.ctrl.getSnapMode()}setStayMode(e){return this.ok("setStayMode")&&this.ctrl.setStayMode(e),this}getStayMode(){return this.ctrl.getStayMode()}setMode(e){return this.ok("setMode")&&this.ctrl.setMode(e),this}getMode(){return this.ctrl.getMode()}showToolbar(e=true){return this.ok("showToolbar")&&this.ctrl.showToolbar(e),this}setToolbar(e){return this.ok("setToolbar")&&this.ctrl.setToolbar(e),this}setToolShortcuts(e){return this.ok("setToolShortcuts")&&this.ctrl.setToolShortcuts(e),this}setExternalGhost(e){return this.ctrl.setExternalGhost(e),this}add(e,t={}){return this.ok("add")?this.ctrl.add(e,t):null}remove(e){return this.ctrl.remove(e),this}update(e,t){return this.ctrl.update(e,t),this}updateMany(e){return this.ctrl.updateMany(e),this}removeMany(e){return this.ctrl.removeMany(e),this}lock(e,t=true){return this.ctrl.setLocked(e,t),this}show(e,t=true){return this.ctrl.setVisible(e,t),this}select(e){return this.ok("select")&&this.ctrl.select(e==null?[]:typeof e=="string"?[e]:e),this}openSettings(e){return this.ok("openSettings")&&this.ctrl.openSettings(e),this}bringToFront(e){return this.ctrl.bringToFront(e),this}sendToBack(e){return this.ctrl.sendToBack(e),this}undo(){return this.ctrl.undo(),this}redo(){return this.ctrl.redo(),this}canUndo(){return this.ctrl.canUndo()}canRedo(){return this.ctrl.canRedo()}clone(e){return this.ok("clone")&&this.ctrl.clone(e),this}duplicate(e){return this.ok("duplicate")&&this.ctrl.duplicate(e),this}copyToClipboard(e){return this.ok("copy")&&this.ctrl.copy(e),this}paste(){return this.ok("paste")&&this.ctrl.paste(),this}all(){return this.ctrl.all()}toJSON(){return this.ctrl.toJSON()}fromJSON(e){return this.ctrl.fromJSON(e),this}favorites(){return this.ctrl.favorites()}isFavorite(e){return this.ctrl.isFavorite(e)}setFavorite(e,t){return this.ok("setFavorite")&&this.ctrl.setFavorite(e,t),this}setFavorites(e){return this.ok("setFavorites")&&this.ctrl.setFavorites([...e]),this}getConfig(){return this.ctrl.toJSON()}applyConfig(e){return this.ctrl.fromJSON(e),this}ok(e){return this.ctrl.supported?true:(console.warn(`[vela] chart.drawings.${e}() ignored \u2014 the active renderer has no userDrawings capability.`),false)}};function Hn(s){let e=s.trim(),t=/^#([0-9a-f]{3})$/i.exec(e);if(t){let r=t[1];return {r:parseInt(r[0]+r[0],16),g:parseInt(r[1]+r[1],16),b:parseInt(r[2]+r[2],16)}}if(t=/^#([0-9a-f]{6})[0-9a-f]{0,2}$/i.exec(e),t){let r=t[1];return {r:parseInt(r.slice(0,2),16),g:parseInt(r.slice(2,4),16),b:parseInt(r.slice(4,6),16)}}let n=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i.exec(e);return n?{r:parseFloat(n[1]),g:parseFloat(n[2]),b:parseFloat(n[3])}:null}function W(s,e){let t=Hn(s);return t?`rgba(${t.r},${t.g},${t.b},${e})`:s}function hl(s,e,t){let n=Hn(s),r=Hn(e);if(!n||!r)return s;let i=(o,a)=>Math.round(o+(a-o)*t);return `rgb(${i(n.r,r.r)},${i(n.g,r.g)},${i(n.b,r.b)})`}function ul(s,e="#888888"){let t=Hn(s);if(!t)return e;let n=r=>Math.max(0,Math.min(255,Math.round(r))).toString(16).padStart(2,"0");return `#${n(t.r)}${n(t.g)}${n(t.b)}`}function xe(s){let e=Hn(s);return e?.2126*e.r+.7152*e.g+.0722*e.b<128:true}var pl={"--vela-space-1":"4px","--vela-space-2":"8px","--vela-space-3":"12px","--vela-space-4":"16px","--vela-radius-sm":"4px","--vela-radius-md":"6px","--vela-radius-lg":"10px","--vela-z-tooltip":"60","--vela-z-menu":"50","--vela-z-dialog":"40","--vela-ease":"cubic-bezier(0.22, 1, 0.36, 1)","--vela-dur-fast":"90ms","--vela-dur-med":"160ms","--vela-font-size-sm":"11px","--vela-font-size-md":"12px","--vela-font-size-lg":"14px"};function ml(s){let e=xe(s.background),t=r=>e?`rgba(255,255,255,${r})`:W(s.textColor,r+.02),n=hl(s.background,e?"#ffffff":s.textColor,e?.03:.05);return {"--vela-font":s.fontFamily,"--vela-bg":s.background,"--vela-fg":e?"#d1d4dc":s.textColor,"--vela-fg-muted":e?"#868a96":W(s.textColor,.62),"--vela-fg-faint":W(s.textColor,.35),"--vela-fg-bright":e?"#f0f3fa":"#000000","--vela-surface":s.background,"--vela-surface-elev":n,"--vela-surface-overlay":n,"--vela-surface-sunken":s.background,"--vela-border":s.borderColor,"--vela-border-strong":e?"#34353b":W(s.textColor,.28),"--vela-border-soft":s.borderColor,"--vela-border-faint":W(s.textColor,.08),"--vela-hover":t(.06),"--vela-active":t(.1),"--vela-hover-strong":t(.16),"--vela-focus":W(s.textColor,.5),"--vela-focus-soft":W(s.textColor,.12),"--vela-separator-hover-band":W(s.textColor,.1),"--vela-separator-hover-line":W(s.textColor,.55),"--vela-scroll":W(s.textColor,.3),"--vela-accent":ve,"--vela-accent-bright":fr,"--vela-highlight":va,"--vela-selected-bg":e?"#f0f3fa":s.textColor,"--vela-selected-fg":e?s.background:"#ffffff","--vela-fg-on-fill":"#ffffff","--vela-up":s.upColor,"--vela-down":s.downColor,"--vela-danger":s.downColor,"--vela-shadow":"0 8px 30px rgba(0,0,0,0.5)","--vela-shadow-dialog":"0 20px 60px rgba(0,0,0,0.5)","--vela-backdrop":"rgba(0,0,0,0.45)"}}function ne(s,e){let t=n=>{for(let r in n)s.style.setProperty(r,n[r]);};t(pl),t(ml(e));}function Et(s,e){let t=null,n=null,r=()=>{t!==null&&(clearTimeout(t),t=null),n?.remove(),n=null;},i=()=>{let a=e.text();if(!a)return;n=s.ownerDocument.createElement("div"),n.textContent=a,n.style.cssText="position:absolute;z-index:var(--vela-z-tooltip);pointer-events:none;background:var(--vela-bg);border:1px solid var(--vela-border);color:var(--vela-fg);border-radius:var(--vela-radius-md);padding:4px 9px;box-shadow:var(--vela-shadow);font:var(--vela-font-size-md) var(--vela-font);"+(e.wrap?"max-width:260px;":"white-space:nowrap;"),ne(n,e.theme()),e.host.appendChild(n);let c=s.getBoundingClientRect(),d=e.host.getBoundingClientRect();if(e.placement==="right")n.style.left=`${c.right-d.left+8}px`,n.style.top=`${c.top-d.top+(c.height-n.offsetHeight)/2}px`;else {let h=Math.min(c.left-d.left,Math.max(0,d.width-n.offsetWidth-4));n.style.left=`${Math.max(0,h)}px`,n.style.top=`${c.bottom-d.top+6}px`;}},o=a=>{a.pointerType==="mouse"&&(r(),t=window.setTimeout(i,e.delayMs??700));};return s.addEventListener("pointerenter",o),s.addEventListener("pointerleave",r),s.addEventListener("pointerdown",r),()=>{s.removeEventListener("pointerenter",o),s.removeEventListener("pointerleave",r),s.removeEventListener("pointerdown",r),r();}}function fl(s,e,t){let n=t?.closeSelector??"",r=0,i=0,o=0,a=0,l=0,c=0,d=0,h=false,u=()=>{s.style.transform=r||i?`translate(${r}px, ${i}px)`:"";},p=()=>{r=0,i=0,u(),t?.onReset?.();};e.style.cursor="move",e.style.userSelect="none",e.addEventListener("pointerdown",f=>{if(f.button!==0||n&&f.target.closest(n))return;let b=s.getBoundingClientRect();o=b.left-r,a=b.top-i,l=b.width,c=f.clientX,d=f.clientY,h=true,e.setPointerCapture(f.pointerId),f.preventDefault();}),e.addEventListener("pointermove",f=>{if(!h)return;let b=e.offsetHeight||40,g=o+(f.clientX-c);g=Math.max(120-l,Math.min(g,window.innerWidth-120));let v=a+(f.clientY-d);v=Math.max(0,Math.min(v,window.innerHeight-b)),r=g-o,i=v-a,u();});let m=f=>{if(h){h=false;try{e.releasePointerCapture(f.pointerId);}catch{}}};return e.addEventListener("pointerup",m),e.addEventListener("pointercancel",m),{reset:p}}var Hp=["close","open","high","low","hl2","hlc3","ohlc4","volume"],zp="@keyframes vela-ind-pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.3;transform:scale(.6)}}",Le=16,jo=18,Cl=2,bl=6,$p=6,gl=6,zn=`cursor:pointer;display:inline-flex;align-items:center;justify-content:center;border:none;line-height:0;padding:0;width:${jo}px;height:${jo}px;border-radius:3px;box-sizing:border-box;flex:none;`,Wp=jo+Cl*2,vl=oe("eye",Le),Up=oe("eye-off",Le),Gp=oe("gear",Le),Yp=oe("close",Le),Xp=oe("chevron-up",Le),Kp=oe("chevron-down",Le),jp=oe("objects",Le),Vi=class{constructor(e,t,n){this.container=e;this.theme=t;this.paneBoundsOf=n;this.legends=new Map;this.rows=new Map;this.dialog=null;this.backdrop=null;this.openId=null;this.selectedId=null;this.snapshot=null;this.onChange=null;this.onRemove=null;this.onToggleVisible=null;this.symbolPicker=null;this.mobileLayout=false;this.moveApi=null;this.legendActions=null;this.rowTips=new Map;this.extrasTips=new Map;this.dialogTips=[];this.moveMenu=null;this.paneCollapse=new Map;this.legendFolded=false;this.titlesVisible=true;this.valuesVisible=true;this.rowMenu=null;this.foldToggle=null;this.overviewAction=null;this.onDialogKey=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeDialog());};this.onDocClick=e=>{if(!this.selectedId)return;let t=e.target;if(t){for(let n of this.rows.values())if(n.el.contains(t))return}this.clearSelection();};this.dialogHost=null;this.onMoveMenuOutside=e=>{this.moveMenu&&!this.moveMenu.contains(e.target)&&this.closeMoveMenu();};this.onRowMenuOutside=e=>{this.rowMenu&&!this.rowMenu.contains(e.target)&&this.closeRowMenu();};e.style.position||(e.style.position="relative"),typeof document<"u"&&document.addEventListener("click",this.onDocClick);}setDialogHost(e){this.dialogHost=e,e&&getComputedStyle(e).position==="static"&&(e.style.position="relative");}setLayoutMode(e){let t=e==="mobile";if(t!==this.mobileLayout&&(this.mobileLayout=t,this.overviewAction===null&&(this.legendFolded=t),this.syncFoldToggle(),this.openId!==null)){let n=this.openId;this.closeOpenDialog(),this.openDialog(n);}}setLegendOverviewAction(e){e!==this.overviewAction&&(this.overviewAction=e,this.legendFolded=e!==null?true:this.mobileLayout,this.syncFoldToggle());}openSettingsFor(e){this.rows.has(e)&&this.openDialog(e);}tip(e,t,n,r,i=false){let o=e.get(t)??[];o.push(Et(n,{host:this.container,theme:()=>this.theme,text:typeof r=="function"?r:()=>r,wrap:i})),e.set(t,o);}disposeTips(e,t){for(let n of e.get(t)??[])n();e.delete(t);}setOnChange(e){this.onChange=e;}setOnRemove(e){this.onRemove=e;}setOnToggleVisible(e){this.onToggleVisible=e;}setTheme(e){this.theme=e;for(let t of this.legends.values())ne(t,e);for(let t of this.rows.values())t.el.style.background=t.highlighted?e.background:this.idleRowFill(),t.el.style.color=e.textColor;this.foldToggle&&this.syncFoldToggle();}setSymbolPicker(e){this.symbolPicker=e;}setMoveApi(e){this.moveApi=e;}setLegendActions(e){this.legendActions=e;for(let t of this.rows.values())this.renderExtras(t.id,t.extrasEl);}renderExtras(e,t){this.disposeTips(this.extrasTips,e),t.replaceChildren();for(let n of this.legendActions?.(e)??[]){let r=document.createElement("button");r.type="button",r.setAttribute("aria-label",n.tooltip),this.tip(this.extrasTips,e,r,n.tooltip),r.innerHTML=oe(n.icon,Le),r.className="vela-ind-ctl",r.dataset.legendAction=n.id,r.style.cssText=zn,r.addEventListener("click",i=>{i.stopPropagation(),n.run();}),t.appendChild(r);}}reposition(){for(let[e,t]of this.legends)this.positionLegend(t,e);}setTitlesVisible(e){this.titlesVisible!==e&&(this.titlesVisible=e,this.reposition());}setValuesVisible(e){this.valuesVisible=e;for(let t of this.rows.values())t.showValues=null,this.renderRowValues(t);}setPlotValues(e){for(let t of this.rows.values()){let n=e.get(t.id)??[],r=n.map(i=>`${i.value}|${i.color}`).join("\0");r!==t.plotValuesKey&&(t.plotValues=n,t.plotValuesKey=r,this.renderRowValues(t));}}rowValuesShown(e){return e.showValues??this.valuesVisible}renderRowValues(e){if(!this.rowValuesShown(e)||e.plotValues.length===0||e.highlighted){e.valuesEl.style.display="none",e.valuesEl.replaceChildren();return}e.valuesEl.style.display="inline-flex",e.valuesEl.replaceChildren();for(let t of e.plotValues){let n=document.createElement("span");n.textContent=t.value,n.style.color=t.color,e.valuesEl.appendChild(n);}}openMoveMenu(e,t){this.closeMoveMenu();let n=this.moveApi;if(!n)return;let i=this.rows.get(e)?.paneId??"price",o=n.panes(),a=document.createElement("div");a.style.cssText=`position:fixed;z-index:var(--vela-z-tooltip);min-width:150px;padding:4px;border-radius:var(--vela-radius-md);background:var(--vela-surface-elev);color:${this.theme.textColor};border:1px solid var(--vela-border);box-shadow:var(--vela-shadow);font-size:var(--vela-font-size-md);`,ne(a,this.theme);let l=[];for(let p of o)p.id!==i&&l.push({label:`Move to ${p.label}`,target:p.kind==="price"?"price":{pane:p.id}});i!=="price"&&[...this.rows.values()].filter(p=>p.paneId===i).length<=1||(i!=="price"&&l.push({label:"New pane above",target:{newPane:{before:i}}}),l.push({label:"New pane below",target:{newPane:{after:i}}}));for(let p of l){let m=document.createElement("button");m.type="button",m.textContent=p.label,m.className="vela-ind-menuitem",m.style.cssText="display:block;width:100%;text-align:left;padding:6px 10px;border:none;border-radius:var(--vela-radius-sm);color:inherit;cursor:pointer;white-space:nowrap;",m.addEventListener("click",f=>{f.stopPropagation(),this.closeMoveMenu(),n.move(e,p.target);}),a.appendChild(m);}document.body.appendChild(a);let d=t.getBoundingClientRect(),h=a.offsetWidth||160,u=a.offsetHeight||80;a.style.left=`${Math.min(d.left,window.innerWidth-h-6)}px`,a.style.top=`${Math.min(d.bottom+4,window.innerHeight-u-6)}px`,this.moveMenu=a,setTimeout(()=>{typeof document<"u"&&document.addEventListener("pointerdown",this.onMoveMenuOutside,true);},0);}closeMoveMenu(){typeof document<"u"&&document.removeEventListener("pointerdown",this.onMoveMenuOutside,true),this.moveMenu?.remove(),this.moveMenu=null;}openRowMenu(e,t,n){this.closeRowMenu(),this.closeMoveMenu();let r=this.rows.get(e);if(!r)return;let i=document.createElement("div");i.style.cssText=`position:fixed;z-index:var(--vela-z-tooltip);min-width:170px;padding:4px;border-radius:var(--vela-radius-md);background:var(--vela-surface-elev);color:${this.theme.textColor};border:1px solid var(--vela-border);box-shadow:var(--vela-shadow);font-size:var(--vela-font-size-md);`,ne(i,this.theme);let o=document.createElement("button");o.type="button",o.className="vela-ind-menuitem",o.style.cssText="display:flex;align-items:center;gap:8px;width:100%;text-align:left;padding:6px 10px;border:none;border-radius:var(--vela-radius-sm);color:inherit;cursor:pointer;white-space:nowrap;";let a=document.createElement("span");a.style.cssText="display:inline-flex;align-items:center;justify-content:center;width:14px;flex:none;line-height:0;",a.innerHTML=this.rowValuesShown(r)?yl:"";let l=document.createElement("span");l.textContent="Indicator values",o.append(a,l),o.addEventListener("click",h=>{h.stopPropagation(),this.closeRowMenu(),r.showValues=!this.rowValuesShown(r),this.renderRowValues(r);}),i.appendChild(o),document.body.appendChild(i);let c=i.offsetWidth||180,d=i.offsetHeight||40;i.style.left=`${Math.min(t,window.innerWidth-c-6)}px`,i.style.top=`${Math.min(n,window.innerHeight-d-6)}px`,this.rowMenu=i,setTimeout(()=>{typeof document<"u"&&document.addEventListener("pointerdown",this.onRowMenuOutside,true);},0);}closeRowMenu(){typeof document<"u"&&document.removeEventListener("pointerdown",this.onRowMenuOutside,true),this.rowMenu?.remove(),this.rowMenu=null;}setPane(e,t){let n=this.rows.get(e);if(!n||n.paneId===t)return;let r=n.paneId;if(n.paneId=t,this.attach(this.legendFor(t),n.el,n.native),this.syncFoldToggle(),r!=="price"){let i=this.legends.get(r);i&&i.childElementCount===0&&(i.remove(),this.legends.delete(r));}}legendFor(e){let t=this.legends.get(e);return t||(t=document.createElement("div"),t.dataset.velaPane=e,t.style.cssText="position:absolute;left:10px;z-index:5;display:flex;flex-direction:column;align-items:flex-start;gap:0;pointer-events:none;font:12px -apple-system,Segoe UI,sans-serif;",ne(t,this.theme),this.positionLegend(t,e),this.container.appendChild(t),this.legends.set(e,t)),t}positionLegend(e,t){let n=this.paneBoundsOf?this.paneBoundsOf(t):{top:0,height:1/0};e.style.display=n.height<4||!this.titlesVisible?"none":"flex";let r=this.paneCollapse.has(t),i=this.paneCollapse.get(t)??null;for(let a of this.rows.values())a.paneId===t&&(a.el.style.display=(r?a.id!==i:this.legendFolded)?"none":"flex");let o=n.top+8;if(r&&Number.isFinite(n.height)){let a=e.offsetHeight||20;o=n.top+Math.max(1,Math.round((n.height-a)/2));}e.style.top=`${o}px`;}setCollapsedPanes(e){this.paneCollapse=e;}syncFoldToggle(){let e=this.rows.size,t=this.overviewAction!==null||this.mobileLayout?1:2;if(e<t){let a=this.legendFolded;e>0&&(this.legendFolded=false),this.foldToggle&&(this.foldToggle.remove(),this.foldToggle=null,this.disposeTips(this.rowTips,"fold")),a&&e>0&&this.reposition();return}let n=this.foldToggle;n||(n=document.createElement("button"),n.type="button",n.className="vela-ind-fold",this.tip(this.rowTips,"fold",n,()=>this.overviewAction!==null?"Indicators":this.legendFolded?"Show indicator legend":"Hide indicator legend"),n.addEventListener("click",()=>{if(this.overviewAction!==null){this.overviewAction();return}this.legendFolded=!this.legendFolded,this.syncFoldToggle();}),this.foldToggle=n);let r=this.legendFolded;n.setAttribute("aria-label",this.overviewAction!==null?"Indicators":r?"Show indicator legend":"Hide indicator legend");let i=this.theme.textColor;n.style.cssText=`pointer-events:auto;display:inline-flex;align-items:center;gap:4px;background:${this.theme.background};color:${i};border:1px solid ${this.theme.borderColor};border-radius:4px;padding:2px 6px;margin-top:6px;cursor:pointer;font:inherit;line-height:0;`,n.replaceChildren();let o=document.createElement("span");if(o.style.cssText="display:inline-flex;align-items:center;line-height:0;opacity:0.7;",o.innerHTML=this.overviewAction!==null?jp:r?Kp:Xp,n.appendChild(o),r){let a=document.createElement("span");a.textContent=String(e),a.style.cssText=`font-weight:600;line-height:normal;font-size:12px;color:${i};`,n.appendChild(a);}this.legendFor("price").appendChild(n),this.reposition();}upsert(e,t,n,r,i="price",o={}){let a=o.settingsTitle??t,l=this.rows.get(e);if(l){l.title=t,l.settingsTitle=a,l.inputs=n,l.values={...r},l.titleEl.textContent=t,l.paneId!==i&&(l.paneId=i,this.attach(this.legendFor(i),l.el,l.native),this.syncFoldToggle());return}Sl();let c=document.createElement("div");c.style.cssText=`pointer-events:auto;display:flex;align-items:center;background:${this.idleRowFill()};border-radius:4px;padding:${Cl}px ${bl}px;margin-left:-${bl}px;min-height:${Wp}px;box-sizing:border-box;color:${this.theme.textColor};user-select:none;-webkit-user-select:none;`,c.addEventListener("mouseleave",()=>{this.selectedId!==e&&this.setRowHighlighted(e,false);}),c.addEventListener("click",v=>{v.button!==0||v.target.closest("button")||this.selectRow(e);}),c.addEventListener("dblclick",v=>{v.target.closest("button")||this.openDialog(e);}),c.addEventListener("mousedown",v=>{v.button===1&&v.preventDefault();}),c.addEventListener("auxclick",v=>{v.button===1&&(v.preventDefault(),this.onRemove?.(e));}),c.addEventListener("contextmenu",v=>{v.preventDefault(),v.stopPropagation(),this.openRowMenu(e,v.clientX,v.clientY);});let d=document.createElement("span");d.style.cssText="display:none;box-sizing:border-box;flex:none;";let h=document.createElement("span");h.style.cssText="white-space:nowrap;",h.addEventListener("mouseenter",()=>this.setRowHighlighted(e,true));let u=document.createElement("span");if(u.textContent=t,u.style.cssText="font-weight:600;",h.appendChild(u),o.beta){let v=document.createElement("sup");v.textContent="beta",v.style.cssText="font-size:8px;font-weight:700;opacity:0.7;margin-left:1px;letter-spacing:0.2px;",h.appendChild(v);}c.appendChild(h);let p=document.createElement("span");p.style.cssText=`display:none;align-items:center;gap:5px;margin-left:${$p}px;white-space:nowrap;font-variant-numeric:tabular-nums;`,c.appendChild(p);let m=document.createElement("span");m.style.cssText=`display:none;align-items:center;gap:${gl}px;flex:none;margin-left:${gl}px;`;let f=null;if(this.onToggleVisible){let v=document.createElement("button");v.type="button",v.setAttribute("aria-label","Hide"),this.tip(this.rowTips,e,v,()=>this.rows.get(e)?.hidden?"Show":"Hide"),v.innerHTML=vl,v.className="vela-ind-ctl",v.style.cssText=zn,v.addEventListener("click",()=>{let y=this.rows.get(e);this.onToggleVisible?.(e,!!y?.hidden);}),m.appendChild(v),f=v;}if(n.length>0){let v=document.createElement("button");v.type="button",v.setAttribute("aria-label","Settings"),this.tip(this.rowTips,e,v,"Settings"),v.innerHTML=Gp,v.className="vela-ind-ctl",v.style.cssText=zn,v.addEventListener("click",()=>this.openDialog(e)),m.appendChild(v);}if(this.moveApi){let v=document.createElement("button");v.type="button",v.setAttribute("aria-label","Move to pane"),this.tip(this.rowTips,e,v,"Move to pane"),v.innerHTML=oe("move",Le),v.className="vela-ind-ctl",v.style.cssText=zn,v.addEventListener("click",y=>{y.stopPropagation(),this.openMoveMenu(e,v);}),m.appendChild(v);}let b=document.createElement("span");b.style.cssText="display:contents;",this.renderExtras(e,b),m.appendChild(b);let g=document.createElement("button");g.type="button",g.setAttribute("aria-label","Remove indicator"),this.tip(this.rowTips,e,g,"Remove indicator"),g.innerHTML=Yp,g.className="vela-ind-close",g.style.cssText=zn,g.addEventListener("click",()=>this.onRemove?.(e)),m.appendChild(g),c.appendChild(m),c.appendChild(d),this.attach(this.legendFor(i),c,!!o.native),this.rows.set(e,{id:e,title:t,settingsTitle:a,inputs:n,values:{...r},el:c,titleEl:u,statusEl:d,valuesEl:p,plotValues:[],plotValuesKey:"",showValues:null,highlighted:false,paneId:i,hidden:false,eyeEl:f,controlsEl:m,extrasEl:b,native:!!o.native}),this.syncFoldToggle();}attach(e,t,n){n?e.prepend(t):e.appendChild(t);}setValues(e,t){let n=this.rows.get(e);n&&(n.values={...n.values,...t});}setStatus(e,t){let n=this.rows.get(e);if(!n)return;let r=n.statusEl;if(r.replaceChildren(),t==="idle"){r.style.cssText="display:none;box-sizing:border-box;flex:none;";return}if(t==="loading"){r.style.cssText="display:inline-flex;align-items:center;gap:3px;box-sizing:border-box;flex:none;";for(let i=0;i<3;i+=1){let o=document.createElement("span");o.style.cssText="width:4px;height:4px;border-radius:50%;background:currentColor;opacity:0.15;flex:none;",o.animate?.([{opacity:.12},{opacity:.55}],{duration:800,iterations:1/0,direction:"alternate",easing:"ease-in-out",delay:-i*260}),r.appendChild(o);}return}this.ensureStatusKeyframes(),r.style.cssText=`display:inline-block;box-sizing:border-box;flex:none;width:8px;height:8px;border-radius:50%;background:${this.theme.upColor};animation:vela-ind-pulse 1.2s ease-in-out infinite;`;}ensureStatusKeyframes(){if(typeof document>"u"||document.getElementById("vela-ind-status-kf"))return;let e=document.createElement("style");e.id="vela-ind-status-kf",e.textContent=zp,document.head.appendChild(e);}setVisible(e,t){let n=this.rows.get(e);n&&(n.hidden=!t,n.el.style.opacity=t?"1":"0.5",n.eyeEl&&(n.eyeEl.innerHTML=t?vl:Up,n.eyeEl.setAttribute("aria-label",t?"Hide":"Show")),this.syncRowActions(n));}selectRow(e){this.selectedId!==e&&(this.clearSelection(),this.selectedId=e,this.setRowHighlighted(e,true));}setRowHighlighted(e,t){let n=this.rows.get(e);n&&(n.highlighted=t,this.renderRowValues(n),n.el.style.boxShadow=t?`inset 0 0 0 1px ${this.neutralBorder()}`:"none",n.el.style.background=t?this.theme.background:this.idleRowFill(),this.syncRowActions(n));}syncRowActions(e){let t=e.highlighted;e.controlsEl.style.display=t||e.hidden?"inline-flex":"none";for(let n of Array.from(e.controlsEl.children))if(!(!(n instanceof HTMLElement)||n===e.eyeEl)){if(n===e.extrasEl){n.style.display=t?"contents":"none";continue}n.style.display=t?"inline-flex":"none";}}clearSelection(){this.selectedId&&(this.setRowHighlighted(this.selectedId,false),this.selectedId=null);}remove(e){let t=this.rows.get(e);if(t?.el.remove(),this.rows.delete(e),this.disposeTips(this.rowTips,e),this.disposeTips(this.extrasTips,e),this.selectedId===e&&(this.selectedId=null),this.openId===e&&this.closeDialog(),this.syncFoldToggle(),t&&t.paneId!=="price"){let n=this.legends.get(t.paneId);n&&n.childElementCount===0&&(n.remove(),this.legends.delete(t.paneId));}}destroy(){this.closeDialog(),this.closeMoveMenu(),this.closeRowMenu();for(let e of [...this.rowTips.keys()])this.disposeTips(this.rowTips,e);for(let e of [...this.extrasTips.keys()])this.disposeTips(this.extrasTips,e);for(let e of this.legends.values())e.remove();this.legends.clear(),this.rows.clear(),this.foldToggle=null,this.legendFolded=false,this.selectedId=null,typeof document<"u"&&document.removeEventListener("click",this.onDocClick);}isDialogOpen(){return this.dialog!==null}closeOpenDialog(){this.closeDialog();}openDialog(e){this.closeDialog();let t=this.rows.get(e);if(!t||t.inputs.length===0)return;this.openId=e,this.snapshot={...t.values},Sl();let n=this.theme,r=n.fontFamily||"-apple-system,Segoe UI,sans-serif",i=this.neutralBorder(),o=this.strongText(),a=this.isDarkTheme()?"dark":"light",l=document.createElement("div");l.className="vela-ind-dialog-backdrop",l.style.cssText="position:absolute;inset:0;z-index:40;display:flex;align-items:center;justify-content:center;background:transparent;pointer-events:auto;",l.addEventListener("pointerdown",g=>{g.target===l&&(this.closeDialog(),this.clearSelection());});let c=document.createElement("div");c.className="vela-ind-dialog",c.style.cssText=`display:flex;flex-direction:column;width:fit-content;min-width:min(360px,90%);max-width:min(640px,94%);max-height:82%;background:${n.background};border:1px solid ${i};border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow-dialog);color:${o};color-scheme:${a};font:13px ${r};overflow:hidden;`,this.mobileLayout&&(c.style.cssText+="width:100%;min-width:0;max-width:none;height:100%;max-height:none;border:none;border-radius:0;"),ne(c,n),c.addEventListener("keydown",g=>{g.key!=="Escape"&&g.stopPropagation();});let d=document.createElement("div");d.style.cssText="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;padding:16px 20px 12px;flex:0 0 auto;";let h=document.createElement("span");h.textContent=t.settingsTitle,h.style.cssText="font-weight:600;font-size:16px;line-height:1.3;";let u=document.createElement("button");u.type="button",u.setAttribute("aria-label","Close"),this.dialogTips.push(Et(u,{host:this.container,theme:()=>this.theme,text:()=>"Close"})),u.innerHTML=oe("close",15),u.className="vela-ind-ctl",u.style.cssText="cursor:pointer;display:inline-flex;align-items:center;background:transparent;border:none;line-height:0;padding:2px;flex:0 0 auto;",u.addEventListener("click",()=>this.closeDialog()),d.append(h,u),c.appendChild(d),this.mobileLayout||fl(c,d,{closeSelector:"button"});let p=document.createElement("div");p.style.cssText=`display:flex;gap:16px;padding:0 20px;border-bottom:1px solid ${i};flex:0 0 auto;`;let m=document.createElement("div");m.textContent="Inputs",m.style.cssText=`padding:8px 2px;margin-bottom:-1px;border-bottom:2px solid ${o};font-weight:600;font-size:13px;`,p.appendChild(m),c.appendChild(p);let f=document.createElement("div");f.style.cssText="padding:14px 20px 6px;overflow-y:auto;flex:1 1 auto;display:flex;flex-direction:column;gap:24px;";for(let g of qp(t.inputs)){let v=document.createElement("div");if(v.style.cssText="display:flex;flex-direction:column;gap:14px;",g.name){let x=document.createElement("div");x.textContent=g.name,x.style.cssText="font-size:var(--vela-font-size-sm);font-weight:600;letter-spacing:0.05em;text-transform:uppercase;color:var(--vela-fg-muted);",v.appendChild(x);}let y=document.createElement("div");y.style.cssText=this.mobileLayout?"display:grid;grid-template-columns:minmax(0,1fr) auto auto max-content;align-items:center;column-gap:12px;row-gap:22px;":"display:grid;grid-template-columns:minmax(140px,auto) auto auto 1fr;align-items:center;column-gap:12px;row-gap:22px;";for(let x of g.rows)this.buildInputRow(y,x,t);v.appendChild(y),f.appendChild(v);}c.appendChild(f);let b=document.createElement("div");b.style.cssText=`display:flex;justify-content:flex-end;gap:8px;padding:14px 20px;border-top:1px solid ${i};flex:0 0 auto;`,b.append(this.dialogButton("Cancel",false,()=>this.revertAndClose()),this.dialogButton("Ok",true,()=>this.closeDialog())),c.appendChild(b),l.appendChild(c),(this.dialogHost??this.container).appendChild(l),this.dialog=c,this.backdrop=l,document.addEventListener("keydown",this.onDialogKey);}closeDialog(){document.removeEventListener("keydown",this.onDialogKey);for(let e of this.dialogTips.splice(0))e();this.backdrop?.remove(),this.backdrop=null,this.dialog=null,this.openId=null,this.snapshot=null;}revertAndClose(){let e=this.openId?this.rows.get(this.openId):null,t=this.snapshot;if(e&&t)for(let n of e.inputs){let r=t[n.key],i=r!==void 0?r:n.defval;e.values[n.key]!==i&&(e.values[n.key]=i,this.onChange?.({indicatorId:e.id,key:n.key,value:i}));}this.closeDialog();}buildInputRow(e,t,n){let r=h=>`vela-inp-${n.id}-${h.key}`;if(t.length>1){let h=document.createElement("div");h.style.cssText="grid-column:1 / -1;display:flex;flex-wrap:wrap;align-items:center;gap:12px;";for(let p of t){let m=p.type==="color"||p.type==="bool",f=p.type==="bool",b=r(p),g=document.createElement("div");g.style.cssText=`display:flex;align-items:center;gap:6px;${f?"flex-direction:row-reverse;":""}`;let v=Bi(p);if(v){let x=document.createElement("label");x.htmlFor=b,x.textContent=v,x.style.cssText=`font-size:13px;opacity:0.9;${f?"cursor:pointer;":""}`,g.appendChild(x);}let y=document.createElement("div");y.style.cssText=m?"":"width:110px;",y.appendChild(this.buildControl(n,p,b)),g.appendChild(y),h.appendChild(g);}let u=[...t].reverse().find(p=>p.tooltip)?.tooltip;u&&h.appendChild(this.infoButton(u)),e.appendChild(h);return}let i=t[0],o=r(i);if(i.type==="bool"){let h=document.createElement("div");h.style.cssText="grid-column:1 / 4;display:flex;align-items:center;gap:8px;";let u=document.createElement("label");u.style.cssText="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;",u.appendChild(this.buildControl(n,i,o)),u.appendChild(document.createTextNode(Bi(i))),h.appendChild(u),i.tooltip&&h.appendChild(this.infoButton(i.tooltip)),e.appendChild(h),e.appendChild(document.createElement("div"));return}if(i.type==="text_area"){let h=document.createElement("div");h.style.cssText="grid-column:1 / -1;display:flex;flex-direction:column;gap:8px;";let u=document.createElement("div");u.style.cssText="display:flex;align-items:center;justify-content:center;gap:8px;";let p=document.createElement("label");p.htmlFor=o,p.textContent=Bi(i),p.style.cssText="font-size:13px;",u.appendChild(p),i.tooltip&&u.appendChild(this.infoButton(i.tooltip)),h.appendChild(u),h.appendChild(this.buildControl(n,i,o)),e.appendChild(h);return}let a=document.createElement("label");a.htmlFor=o,a.textContent=Bi(i),a.style.cssText="font-size:13px;opacity:0.9;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;";let l=document.createElement("div");l.style.cssText="grid-column:span 2;display:flex;align-items:center;gap:8px;";let c=i.type==="color"||i.type==="session"||i.type==="time",d=document.createElement("div");d.style.cssText=c?"":"width:140px;",d.appendChild(this.buildControl(n,i,o)),l.appendChild(d),i.tooltip&&l.appendChild(this.infoButton(i.tooltip)),e.appendChild(a),e.appendChild(l),e.appendChild(document.createElement("div"));}buildControl(e,t,n){let r=e.values[t.key]??t.defval,i=a=>{e.values[t.key]=a,this.onChange?.({indicatorId:e.id,key:t.key,value:a});},o=this.ctrlStyle();if(t.type==="bool")return this.buildToggle(n,!!r,i);if(t.options&&t.options.length>0)return this.select(n,t.options.map(String),String(r),`${o}cursor:pointer;`,i);if(t.type==="source")return this.select(n,Hp,String(r),`${o}cursor:pointer;`,i);if(t.type==="color"){let a=document.createElement("input");return a.type="color",a.id=n,a.value=ul(String(r)),a.style.cssText=`flex:0 0 auto;box-sizing:border-box;width:32px;height:32px;padding:2px;border:1px solid ${this.neutralBorder()};border-radius:0;background:transparent;cursor:pointer;`,a.addEventListener("input",()=>i(a.value)),a}if(t.type==="symbol")return this.buildSymbol(n,String(r),i);if(t.type==="timeframe")return this.selectPairs(n,Jp,String(r),`${o}cursor:pointer;`,i);if(t.type==="session")return this.buildSession(n,String(r),i);if(t.type==="time")return this.buildTime(n,Number(r)||0,i);if(t.type==="text_area")return this.buildTextArea(n,String(r),i);if(t.type==="int"||t.type==="float"||t.type==="price"){let a=document.createElement("input");a.type="number",a.id=n,a.value=String(r),t.min!==void 0&&(a.min=String(t.min)),t.max!==void 0&&(a.max=String(t.max)),a.step=String(t.step??(t.type==="int"?1:.1)),a.style.cssText=o;let l=String(r),c=()=>{let d=Number(a.value);if(!Number.isFinite(d)){a.value=l;return}t.min!==void 0&&(d=Math.max(t.min,d)),t.max!==void 0&&(d=Math.min(t.max,d)),t.type==="int"&&(d=Math.round(d)),a.value=String(d),String(d)!==l&&(l=String(d),i(d));};return a.addEventListener("blur",c),a.addEventListener("keydown",d=>{d.key==="Enter"&&(d.preventDefault(),a.blur());}),a}return this.buildTextField(n,String(r),i)}buildTextField(e,t,n){let r=document.createElement("input");r.type="text",r.id=e,r.value=t,r.style.cssText=this.ctrlStyle();let i=t;return r.addEventListener("blur",()=>{r.value!==i&&(i=r.value,n(r.value));}),r.addEventListener("keydown",o=>{o.key==="Enter"&&(o.preventDefault(),r.blur());}),r}buildToggle(e,t,n){let r=this.theme,i=this.neutralBorder(),o=this.strongText(),a=document.createElement("button");a.type="button",a.id=e,a.setAttribute("role","switch"),a.innerHTML=yl,a.style.cssText=`width:20px;height:20px;flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;border:1px solid ${i};border-radius:5px;cursor:pointer;padding:0;transition:background .12s ease,border-color .12s ease;`;let l=t,c=d=>{a.setAttribute("aria-checked",d?"true":"false"),a.style.background=d?o:"transparent",a.style.borderColor=d?o:i,a.style.color=d?r.background:"transparent";};return c(t),a.addEventListener("click",()=>{l=!l,c(l),n(l);}),a}infoButton(e){let t=document.createElement("span");return t.textContent="i",this.dialogTips.push(Et(t,{host:this.container,theme:()=>this.theme,text:()=>e,wrap:true,delayMs:250})),t.className="vela-ind-hint",t.style.cssText="flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;font-weight:600;font-size:11px;font-family:inherit;line-height:1;cursor:help;user-select:none;",t}select(e,t,n,r,i){return this.selectPairs(e,t.map(o=>({value:o,label:o})),n,r,i)}selectPairs(e,t,n,r,i){let o=document.createElement("select");if(o.id=e,o.style.cssText=r,n!==""&&!t.some(a=>a.value===n)){let a=document.createElement("option");a.value=n,a.textContent=n,a.selected=true,a.disabled=true,o.appendChild(a);}for(let a of t){let l=document.createElement("option");l.value=a.value,l.textContent=a.label,a.value===n&&(l.selected=true),o.appendChild(l);}return this.styleSelect(o),o.addEventListener("change",()=>i(o.value)),this.wrapSelectChevron(o)}wrapSelectChevron(e){let t=document.createElement("div");t.style.cssText="position:relative;width:100%;",e.style.paddingRight="28px";let n=document.createElement("span");return n.innerHTML=Zp,n.style.cssText=`position:absolute;right:10px;top:50%;transform:translateY(-50%);pointer-events:none;display:flex;align-items:center;color:${this.strongText()};opacity:0.85;line-height:0;`,t.append(e,n),t}buildSession(e,t,n){let[r,i]=em(t),o=document.createElement("div");o.style.cssText="display:flex;align-items:center;gap:6px;";let a=r,l=i,c=()=>n(tm(a,l)),d=this.timeSelect(e,a,86,u=>{a=u,c();}),h=this.timeSelect(`${e}-end`,l,86,u=>{l=u,c();});return o.append(d,h),o}buildTime(e,t,n){let r=nm(t),i=document.createElement("div");i.style.cssText="display:flex;align-items:center;gap:6px;";let o=r.date,a=r.time,l=()=>{if(!o)return;let h=Date.parse(`${o}T${a}:00`);Number.isFinite(h)&&n(h);},c=document.createElement("input");c.type="date",c.id=e,c.value=o,c.style.cssText=`${this.ctrlStyle()}width:auto;cursor:pointer;`,c.addEventListener("change",()=>{o=c.value,l();});let d=this.timeSelect(`${e}-time`,a,86,h=>{a=h,l();});return i.append(c,d),i}buildTextArea(e,t,n){let r=document.createElement("textarea");r.id=e,r.value=t,r.rows=3,r.style.cssText=`${this.ctrlStyle()}width:100%;height:auto;min-height:64px;padding:8px;resize:vertical;font-family:inherit;line-height:1.4;`;let i=t;return r.addEventListener("blur",()=>{r.value!==i&&(i=r.value,n(r.value));}),r}timeSelect(e,t,n,r){return this.selectPairs(e,Qp,t,`${this.ctrlStyle()}width:${n}px;cursor:pointer;`,r)}buildSymbol(e,t,n){let r=this.symbolPicker;if(!r)return this.buildTextField(e,t,n);let i=t,o=document.createElement("button");o.type="button",o.id=e,o.style.cssText=`${this.ctrlStyle()}display:flex;align-items:center;cursor:pointer;text-align:left;`;let a=document.createElement("span");return a.textContent=i||"Select symbol\u2026",a.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;",o.append(a),o.addEventListener("click",()=>r(i,l=>{l&&(i=l,a.textContent=l,n(l));})),o}ctrlStyle(){return `width:100%;box-sizing:border-box;height:32px;background:transparent;border:1px solid ${this.neutralBorder()};color:${this.strongText()};border-radius:6px;padding:0 8px;font-size:13px;font-family:inherit;outline:none;`}isDarkTheme(){return xe(this.theme.background)}idleRowFill(){return W(this.theme.background,.6)}neutralBorder(){return "var(--vela-border)"}strongText(){return "var(--vela-fg-bright)"}styleSelect(e){let t=this.theme.background,n=this.strongText();e.style.backgroundColor=t;for(let r of Array.from(e.options))r.style.backgroundColor=t,r.style.color=n;}dialogButton(e,t,n){let r=document.createElement("button");return r.type="button",r.textContent=e,r.className=t?"vela-ind-btn vela-ind-btn-primary":"vela-ind-btn",r.addEventListener("click",n),r}};function Bi(s){let e=s.title;return e.length>0?e.charAt(0).toUpperCase()+e.slice(1):""}function qp(s){let e=[],t=new Map;for(let n of s){let r=n.group&&n.group.length>0?n.group:null;t.has(r)||(t.set(r,[]),e.push(r)),t.get(r).push(n);}return e.map(n=>{let r=t.get(n),i=[],o=new Map;for(let a of r){let l=a.inline&&a.inline.length>0?a.inline:null;l&&o.has(l)?i[o.get(l)].push(a):(l&&o.set(l,i.length),i.push([a]));}return {name:n,rows:i}})}var yl=oe("check",12),Zp=oe("chevron-down",16),xl="vela-ind-dialog-styles",wl="10";function Sl(){if(typeof document>"u")return;let s=document.getElementById(xl);if(s?.dataset.rev===wl)return;let e=s??document.createElement("style");e.id=xl,e.dataset.rev=wl,e.textContent=`
4
4
  .vela-ind-dialog input[type=color]{-webkit-appearance:none;appearance:none;}
5
5
  .vela-ind-dialog input[type=color]::-webkit-color-swatch-wrapper{padding:0;}
6
6
  .vela-ind-dialog input[type=color]::-webkit-color-swatch{border:none;border-radius:4px;}
@@ -24,12 +24,12 @@ var Vela=(function(exports){'use strict';function le(s){return s.kind!=="candle"
24
24
  .vela-ind-btn{cursor:pointer;padding:7px 14px;border-radius:var(--vela-radius-md);border:1px solid transparent;background:transparent;color:var(--vela-fg-muted);font-weight:600;font-size:13px;font-family:inherit;transition:background var(--vela-dur-fast) ease,color var(--vela-dur-fast) ease,opacity var(--vela-dur-fast) ease;}
25
25
  .vela-ind-btn:hover{background:var(--vela-hover);color:var(--vela-fg-bright);}
26
26
  .vela-ind-btn-primary{padding:7px 16px;border-color:var(--vela-selected-bg);background:var(--vela-selected-bg);color:var(--vela-selected-fg);}
27
- .vela-ind-btn-primary:hover{background:var(--vela-selected-bg);color:var(--vela-selected-fg);opacity:0.85;}`,s||document.head.appendChild(e);}var qp=[{value:"",label:"Chart"},{value:"1",label:"1 minute"},{value:"3",label:"3 minutes"},{value:"5",label:"5 minutes"},{value:"15",label:"15 minutes"},{value:"30",label:"30 minutes"},{value:"45",label:"45 minutes"},{value:"60",label:"1 hour"},{value:"120",label:"2 hours"},{value:"180",label:"3 hours"},{value:"240",label:"4 hours"},{value:"D",label:"1 day"},{value:"W",label:"1 week"},{value:"M",label:"1 month"}],Zp=Array.from({length:48},(s,e)=>{let t=String(Math.floor(e/2)).padStart(2,"0"),n=e%2===0?"00":"30",r=`${t}:${n}`;return {value:r,label:r}});function Jp(s){let e=/^(\d{2})(\d{2})-(\d{2})(\d{2})$/.exec(s.trim());return e?[`${e[1]}:${e[2]}`,`${e[3]}:${e[4]}`]:["09:00","16:00"]}function Qp(s,e){return `${s.replace(":","")}-${e.replace(":","")}`}function em(s){if(!s)return {date:"",time:"09:30"};let e=s<1e12?s*1e3:s,t=new Date(e);if(Number.isNaN(t.getTime()))return {date:"",time:"09:30"};let n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`,r=Math.round((t.getHours()*60+t.getMinutes())/30)*30,i=String(Math.floor(r/60)%24).padStart(2,"0"),o=String(r%60).padStart(2,"0");return {date:n,time:`${i}:${o}`}}var jt={up:$("chevron-up"),down:$("chevron-down"),collapse:$("pane-collapse"),expand:$("pane-expand"),maximize:$("maximize"),restore:$("restore")},Cl="vela-pane-controls",tm=12,Tl="rgba(0,0,0,0.28)";function nm(){if(typeof document>"u"||document.getElementById(Cl))return;let s=document.createElement("style");s.id=Cl,s.textContent=`
28
- .vela-pc-btn{display:inline-flex;align-items:center;justify-content:center;padding:0;border:none;border-radius:var(--vela-radius-sm);background:transparent;line-height:0;font-size:${tm}px;color:var(--vela-fg-muted);}
27
+ .vela-ind-btn-primary:hover{background:var(--vela-selected-bg);color:var(--vela-selected-fg);opacity:0.85;}`,s||document.head.appendChild(e);}var Jp=[{value:"",label:"Chart"},{value:"1",label:"1 minute"},{value:"3",label:"3 minutes"},{value:"5",label:"5 minutes"},{value:"15",label:"15 minutes"},{value:"30",label:"30 minutes"},{value:"45",label:"45 minutes"},{value:"60",label:"1 hour"},{value:"120",label:"2 hours"},{value:"180",label:"3 hours"},{value:"240",label:"4 hours"},{value:"D",label:"1 day"},{value:"W",label:"1 week"},{value:"M",label:"1 month"}],Qp=Array.from({length:48},(s,e)=>{let t=String(Math.floor(e/2)).padStart(2,"0"),n=e%2===0?"00":"30",r=`${t}:${n}`;return {value:r,label:r}});function em(s){let e=/^(\d{2})(\d{2})-(\d{2})(\d{2})$/.exec(s.trim());return e?[`${e[1]}:${e[2]}`,`${e[3]}:${e[4]}`]:["09:00","16:00"]}function tm(s,e){return `${s.replace(":","")}-${e.replace(":","")}`}function nm(s){if(!s)return {date:"",time:"09:30"};let e=s<1e12?s*1e3:s,t=new Date(e);if(Number.isNaN(t.getTime()))return {date:"",time:"09:30"};let n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`,r=Math.round((t.getHours()*60+t.getMinutes())/30)*30,i=String(Math.floor(r/60)%24).padStart(2,"0"),o=String(r%60).padStart(2,"0");return {date:n,time:`${i}:${o}`}}var jt={up:$("chevron-up"),down:$("chevron-down"),collapse:$("pane-collapse"),expand:$("pane-expand"),maximize:$("maximize"),restore:$("restore")},Tl="vela-pane-controls",rm=12,Ml="rgba(0,0,0,0.28)";function im(){if(typeof document>"u"||document.getElementById(Tl))return;let s=document.createElement("style");s.id=Tl,s.textContent=`
28
+ .vela-pc-btn{display:inline-flex;align-items:center;justify-content:center;padding:0;border:none;border-radius:var(--vela-radius-sm);background:transparent;line-height:0;font-size:${rm}px;color:var(--vela-fg-muted);}
29
29
  .vela-pc-btn svg{display:block;}
30
30
  .vela-pc-btn:not(:disabled):hover{opacity:1 !important;background:var(--vela-active);color:var(--vela-fg-bright);}
31
31
  .vela-pc-on,.vela-pc-on:not(:disabled):hover{background:var(--vela-selected-bg);color:var(--vela-selected-fg);}
32
- `,document.head.appendChild(s);}var Vi=class{constructor(e,t,n){this.plot=e;this.theme=t;this.deps=n;this.clusters=new Map;this.hoverPaneId=null;this.onPlotMove=e=>{let t=this.plot.getBoundingClientRect(),n=e.clientY-t.top,r=null;for(let i of this.deps.panes())if(n>=i.top&&n<=i.top+i.height){r=i.id;break}this.setHoverPane(r);};this.onPlotLeave=()=>this.setHoverPane(null);nm(),this.root=document.createElement("div"),Object.assign(this.root.style,{position:"absolute",inset:"0",pointerEvents:"none",zIndex:"6"}),this.plot.appendChild(this.root),this.plot.addEventListener("pointermove",this.onPlotMove),this.plot.addEventListener("pointerleave",this.onPlotLeave),this.refresh();}setTheme(e){this.theme=e,this.refresh();}refresh(){let e=this.deps.panes(),t=new Set;for(let n of e){t.add(n.id);let r=this.clusters.get(n.id);r||(r=document.createElement("div"),Object.assign(r.style,{position:"absolute",display:"flex",gap:"2px",padding:"2px",borderRadius:"var(--vela-radius-md)",background:Tl,pointerEvents:"auto"}),this.root.appendChild(r),this.clusters.set(n.id,r)),this.buildButtons(r,n);}for(let[n,r]of this.clusters)t.has(n)||(r.remove(),this.clusters.delete(n));this.reposition();}buildButtons(e,t){e.textContent="",t.kind==="study"&&(e.appendChild(this.button(jt.up,"Move pane up",t.index<=1,()=>this.deps.onMove(t.id,"up"),{role:"up"})),e.appendChild(this.button(jt.down,"Move pane down",t.index>=t.count-1,()=>this.deps.onMove(t.id,"down"),{role:"down"})),e.appendChild(this.button(t.collapsed?jt.expand:jt.collapse,t.collapsed?"Expand pane":"Collapse pane",false,()=>this.deps.onToggleCollapse(t.id),{role:"collapse",selected:t.collapsed}))),t.count>1&&e.appendChild(this.button(t.maximized?jt.restore:jt.maximize,t.maximized?"Restore pane":"Maximize pane",false,()=>this.deps.onToggleMaximize(t.id),{role:"maximize"}));}button(e,t,n,r,i){let o=document.createElement("button");o.type="button",o.title=t,o.innerHTML=e,o.disabled=n,o.dataset.role=i.role;let a=i.selected===true;return o.className=a?"vela-pc-btn vela-pc-on":"vela-pc-btn",Object.assign(o.style,{cursor:n?"default":"pointer",width:"20px",height:"20px",opacity:n?"0.3":"1"}),n||o.addEventListener("click",l=>{l.stopPropagation(),r();}),o}reposition(){let e=this.deps.rightAxis()+6,t=new Map(this.deps.panes().map(n=>[n.id,n]));for(let[n,r]of this.clusters){let i=t.get(n);if(!i){r.style.display="none";continue}let o=n===this.hoverPaneId,l=r.children.length>0&&(o||i.collapsed)&&i.height>8;if(r.style.right=`${e}px`,r.style.top=i.collapsed?`${i.top+Math.max(1,Math.round((i.height-24)/2))}px`:`${i.top+4}px`,r.style.display=l?"flex":"none",!l)continue;let c=i.collapsed&&!o;r.style.background=c?"transparent":Tl;for(let d of r.children){let h=d;h.style.display="inline-flex",h.style.visibility=c&&h.dataset.role!=="collapse"?"hidden":"visible";}}}setHoverPane(e){this.hoverPaneId!==e&&(this.hoverPaneId=e,this.reposition());}destroy(){this.plot.removeEventListener("pointermove",this.onPlotMove),this.plot.removeEventListener("pointerleave",this.onPlotLeave),this.root.remove(),this.clusters.clear();}};var rm={auto:13,tiny:10,small:11,normal:13,large:16,huge:20},_i=class{constructor(e,t,n){this.container=e;this.theme=t;this.paneBounds=n;this.lastTables=[];getComputedStyle(e).position==="static"&&(e.style.position="relative"),this.root=document.createElement("div"),Object.assign(this.root.style,{position:"absolute",inset:"0",pointerEvents:"none",overflow:"hidden",zIndex:"3"}),e.appendChild(this.root);}update(e){this.lastTables=e,this.root.replaceChildren();for(let t of e)this.root.appendChild(this.renderTable(t));}reposition(){this.root.isConnected&&this.update(this.lastTables);}setVisible(e){this.root.style.display=e?"":"none";}destroy(){this.root.remove();}renderTable(e){let t=document.createElement("div");t.style.position="absolute",this.anchor(t,e.position,this.paneBounds(e.paneId));let n=document.createElement("table");Object.assign(n.style,{borderCollapse:"collapse",background:e.bgColor??"transparent",fontFamily:this.theme.fontFamily||"sans-serif",boxShadow:e.frameColor&&e.frameWidth>0?`inset 0 0 0 ${e.frameWidth}px ${e.frameColor}`:"none",border:"none",tableLayout:"auto",pointerEvents:"auto"});let r=new Map,i=new Set;for(let a of e.merges){r.set(`${a.startRow}:${a.startCol}`,{cs:a.endCol-a.startCol+1,rs:a.endRow-a.startRow+1});for(let l=a.startRow;l<=a.endRow;l+=1)for(let c=a.startCol;c<=a.endCol;c+=1)(l!==a.startRow||c!==a.startCol)&&i.add(`${l}:${c}`);}let o=e.borderColor&&e.borderWidth>0?`${e.borderWidth}px solid ${e.borderColor}`:"none";for(let a=0;a<e.rows;a+=1){let l=document.createElement("tr");for(let c=0;c<e.columns;c+=1){let d=e.cells[a]?.[c]??null;if(i.has(`${a}:${c}`)||d?.merged)continue;let h=document.createElement("td"),u=r.get(`${a}:${c}`);u&&(u.cs>1&&(h.colSpan=u.cs),u.rs>1&&(h.rowSpan=u.rs)),Object.assign(h.style,{border:o,padding:"2px 6px",background:d?.bgColor??"transparent",color:d?.textColor??this.theme.textColor,textAlign:d?.hAlign??"center",verticalAlign:d?.vAlign==="top"?"top":d?.vAlign==="bottom"?"bottom":"middle",fontSize:`${rm[d?.textSize??"normal"]}px`,fontFamily:d?.fontFamily==="monospace"?"monospace":"inherit",fontWeight:d?.bold?"bold":"normal",fontStyle:d?.italic?"italic":"normal",whiteSpace:"pre-line"}),d?.tooltip&&(h.title=d.tooltip),h.textContent=d?.text??"",l.appendChild(h);}n.appendChild(l);}return t.appendChild(n),t}anchor(e,t,n){let i=this.root.clientHeight||this.container.clientHeight,o=n.top+n.height;t.startsWith("top")?e.style.top=`${n.top+6}px`:t.startsWith("bottom")?e.style.bottom=`${Math.max(0,i-o)+6}px`:e.style.top=`${n.top+n.height/2}px`,t.endsWith("left")?e.style.left="6px":t.endsWith("right")?e.style.right=`${n.rightAxis+6}px`:e.style.left=`calc(50% - ${n.rightAxis/2}px)`;let a=t.endsWith("center")?"-50%":"0",l=t.startsWith("middle")?"-50%":"0";(a!=="0"||l!=="0")&&(e.style.transform=`translate(${a}, ${l})`);}};var Ml={panes:true,paneManagement:true,fills:"native",bgcolor:"native",hline:"native",markers:true,barcolor:"native",perPointColor:true,drawings:true,userDrawings:true,drawingDepth:true,tables:true,trades:true,inputsUI:true},$n=null;function Ll(){if($n!==null)return $n;try{$n=!!document.createElement("canvas").getContext("webgl2");}catch{$n=false;}return $n}function Hi(s,e,t=6){if(!(e>s)||!Number.isFinite(s)||!Number.isFinite(e))return [];let n=(e-s)/Math.max(1,t),r=Math.pow(10,Math.floor(Math.log10(n))),i=n/r,o=(i<1.5?1:i<3?2:i<7?5:10)*r,a=Math.max(0,-Math.floor(Math.log10(o))+1),l=[],c=Math.ceil(s/o)*o;for(let d=c;d<=e+o*1e-6;d+=o)l.push(Number(d.toFixed(a)));return l}function im(s,e,t=6){if(!(e>s))return 2;let n=(e-s)/Math.max(1,t),r=Math.pow(10,Math.floor(Math.log10(n))),i=n/r,o=(i<1.5?1:i<3?2:i<7?5:10)*r;return Math.max(0,Math.min(8,-Math.floor(Math.log10(o))+1))}function om(s,e,t=6){if(s<=0||!(e>s)||!Number.isFinite(s)||!Number.isFinite(e))return [];if(Math.log10(e)-Math.log10(s)<1.1)return Hi(s,e,t);let n=[],r=Math.floor(Math.log10(s)),i=Math.ceil(Math.log10(e));for(let o=r;o<=i;o+=1)for(let a of [1,2,5]){let l=a*Math.pow(10,o);l>=s&&l<=e&&n.push(l);}return n}function es(s){let e=Math.abs(s);return e>=100?0:e>=1?2:e>=.01?4:6}function sm(s){if(!(s>0)||!Number.isFinite(s))return 2;for(let e=0;e<=8;e+=1)if(Math.abs(Number(s.toFixed(e))-s)<=s*1e-6)return e;return 8}function am(s,e,t){let n=t!=null&&t>0?sm(t):im(s.min,s.max,Gn(e));return n===0?2:n}function Gn(s){return Math.max(2,Math.min(16,Math.round(s/50)))}function Pl(s,e){return s.log?om(s.min,s.max,Gn(e)):Hi(s.min,s.max,Gn(e))}function Jo(s,e){return (s/e-1)*100}function Qo(s,e){return s/e*100}function Il(s){return `${s>=0?"+":"-"}${Math.abs(s).toFixed(2)}%`}function Rl(s){return s.toFixed(2)}function Dl(s){let e=Math.abs(s);return e>=1e9?`${Ni(s/1e9)}B`:e>=1e6?`${Ni(s/1e6)}M`:e>=1e3?`${Ni(s/1e3)}K`:Ni(s)}function Ni(s){return Number(s.toFixed(2)).toString()}function kt(s,e,t,n,r){if(t){let{baseline:i,indexed:o}=t,a=Math.min(s.min,s.max),l=Math.max(s.min,s.max);if(o){let h=Qo(a,i),u=Qo(l,i);return Hi(h,u,Gn(e)).map(p=>({price:i*p/100,label:Rl(p)}))}let c=Jo(a,i),d=Jo(l,i);return Hi(c,d,Gn(e)).map(h=>({price:i*(1+h/100),label:Il(h)}))}return r==="volume"?Pl(s,e).map(i=>({price:i,label:Dl(i)})):Pl(s,e).map(i=>({price:i,label:zi(s,e,i,n)}))}function Yn(s,e,t,n,r,i){return n?n.indexed?Rl(Qo(t,n.baseline)):Il(Jo(t,n.baseline)):i==="volume"?Dl(t):zi(s,e,t,r)}function zi(s,e,t,n){if(s.log&&Math.log10(s.max)-Math.log10(s.min)>=1.1){let i=es(t);return t.toFixed(i===0?2:i)}return t.toFixed(am(s,e,n))}var Wn=1e3,Un=60*Wn,qt=60*Un,Zt=24*qt,lm=7*Zt,El=30*Zt,Al=365*Zt,qo=[Wn,5*Wn,15*Wn,30*Wn,Un,5*Un,15*Un,30*Un,qt,2*qt,4*qt,6*qt,12*qt,Zt,2*Zt,lm,El,3*El,Al],Zo=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],kl=s=>s<10?`0${s}`:String(s);function cm(s){for(let e of qo)if(e>=s)return e;return qo[qo.length-1]}function Jt(s,e,t=8,n=0){let r=e-s;if(!(r>0))return [];let i=cm(r/Math.max(1,t)),o=s+n,a=e+n,l=Math.ceil(o/i)*i,c=[];for(let d=l;d<=a;d+=i){let h=d-n,u=new Date(d),p,m=false;if(i<Zt){let f=u.getUTCHours(),b=u.getUTCMinutes();f===0&&b===0?(p=`${Zo[u.getUTCMonth()]} ${u.getUTCDate()}`,m=true):p=`${kl(f)}:${kl(b)}`;}else i<Al?(p=`${Zo[u.getUTCMonth()]} ${u.getUTCDate()}`,u.getUTCDate()===1&&(p=Zo[u.getUTCMonth()],m=true)):(p=String(u.getUTCFullYear()),m=true);c.push({time:h,label:p,major:m});}return c}var ns=1,Qt=q,en=X,Ye=.25,Xe=.05,dm=50;function Ol(){return {chartTypes:{},fontSize:11,gridVert:{visible:true,color:null},gridHorz:{visible:true,color:null},borderColor:null,separatorColor:null,crosshair:{color:ya,width:1,style:"dashed",opacity:.4,labelBackground:gr},candle:{bodyVisible:true,borderVisible:false,borderUpColor:null,borderDownColor:null,wickVisible:true,wickUpColor:null,wickDownColor:null},bars:{upColor:null,downColor:null},line:{color:gn,width:2},area:{lineColor:gn,width:2,topColor:W(gn,.28),bottomColor:W(gn,.02)},baseline:{topLineColor:null,bottomLineColor:null,topFillColor:null,topFillColor2:null,bottomFillColor:null,bottomFillColor2:null,width:2,baselineLevel:dm}}}var hm=["solid","dashed","dotted"],Fl=["candles","bars","line","area","baseline","heikinashi"];function rs(s){for(let e of Ge())if(e.id===s)return e.basePainting??"candles";return "candles"}function is(s){if(Fl.includes(s))return false;for(let e of Ge())if(e.id===s)return (e.basePainting??"candles")==="candles";return false}function $i(s,e){if(!is(s))return null;let t=e[s]??{},n=i=>j(i)?i:null,r=i=>ue(i)?i:null;return {upColor:n(t.candleUpColor),downColor:n(t.candleDownColor),bodyVisible:r(t.candleBodyVisible),borderVisible:r(t.candleBorderVisible),borderUpColor:n(t.candleBorderUpColor),borderDownColor:n(t.candleBorderDownColor),wickVisible:r(t.candleWickVisible),wickUpColor:n(t.candleWickUpColor),wickDownColor:n(t.candleWickDownColor)}}function Wi(s,e,t,n){return e?{up:e.upColor??t,down:e.downColor??n,candle:{bodyVisible:e.bodyVisible??s.bodyVisible,borderVisible:e.borderVisible??s.borderVisible,borderUpColor:e.borderUpColor??s.borderUpColor,borderDownColor:e.borderDownColor??s.borderDownColor,wickVisible:e.wickVisible??s.wickVisible,wickUpColor:e.wickUpColor??s.wickUpColor,wickDownColor:e.wickDownColor??s.wickDownColor}}:{up:t,down:n,candle:s}}function tn(){let s=[...Fl];for(let e of Ge())s.includes(e.id)||s.push(e.id);return s}function j(s){return typeof s=="string"&&s.trim().length>0}function ue(s){return typeof s=="boolean"}function Pe(s){return typeof s=="number"&&Number.isFinite(s)}function um(s){return typeof s=="string"&&hm.includes(s)}function pm(s){return typeof s=="string"&&tn().includes(s)}function mm(s){return s==="price"||s==="percent"||s==="indexed"}function se(s){return s&&typeof s=="object"?s:{}}function fm(s){return s<0?0:s>1?1:s}function ts(s){return s<1?1:s>10?10:s}function bm(s){return s<0?0:s>100?100:s}function gm(s){return s<.1?.1:s>10?10:s}function Bl(s){let e={};for(let t of Ge()){let n=t.settings;if(!n)continue;let r={},i=o=>{for(let a of o??[])for(let l of Rn(a))r[l.key]=l.defval;};for(let o of n.instances??[])o.enableKey&&(r[o.enableKey]=false),i(o.rows);for(let o of n.subsections??[])o.enableKey&&(r[o.enableKey]=false),i(o.rows);n.instances||i(n.rows),e[t.id]=r;}for(let[t,n]of Object.entries(s.chartTypes))e[t]={...e[t]??{},...n};return {...s,chartTypes:e}}function Vl(s,e){let t=se(e),n=se(t.chartTypes),r={...s.chartTypes};for(let[C,T]of Object.entries(n))r[C]={...r[C]??{},...se(T)};let i=se(t.layout),o=se(t.grid),a=se(o.vertLines),l=se(o.horzLines),c=se(t.crosshair),d=se(t.priceScale),h=se(t.panes),u=se(t.trades),p=se(t.timeScale),m=se(t.candles),f=se(t.bars),b=se(t.line),g=se(t.area),v=se(t.baseline),y=se(t.series),x=se(t.stacking),S=se(x.series);return {version:ns,chartTypes:r,layout:{background:j(i.background)?i.background:s.layout.background,textColor:j(i.textColor)?i.textColor:s.layout.textColor,fontFamily:j(i.fontFamily)?i.fontFamily:s.layout.fontFamily,fontSize:Pe(i.fontSize)?Math.max(6,Math.min(32,i.fontSize)):s.layout.fontSize},grid:{vertLines:{visible:ue(a.visible)?a.visible:s.grid.vertLines.visible,color:j(a.color)?a.color:s.grid.vertLines.color},horzLines:{visible:ue(l.visible)?l.visible:s.grid.horzLines.visible,color:j(l.color)?l.color:s.grid.horzLines.color}},crosshair:{color:j(c.color)?c.color:s.crosshair.color,width:Pe(c.width)?Math.max(.5,Math.min(8,c.width)):s.crosshair.width,style:um(c.style)?c.style:s.crosshair.style,opacity:Pe(c.opacity)?fm(c.opacity):s.crosshair.opacity,labelBackground:j(c.labelBackground)?c.labelBackground:s.crosshair.labelBackground},priceScale:{mode:mm(d.mode)?d.mode:s.priceScale.mode,log:ue(d.log)?d.log:s.priceScale.log,invert:ue(d.invert)?d.invert:s.priceScale.invert,borderColor:j(d.borderColor)?d.borderColor:s.priceScale.borderColor,labelsVisible:ue(d.labelsVisible)?d.labelsVisible:s.priceScale.labelsVisible,currentPriceLine:ue(d.currentPriceLine)?d.currentPriceLine:s.priceScale.currentPriceLine,priceLabel:ue(d.priceLabel)?d.priceLabel:s.priceScale.priceLabel,countdown:ue(d.countdown)?d.countdown:s.priceScale.countdown},panes:{separatorColor:j(h.separatorColor)?h.separatorColor:s.panes.separatorColor},trades:{visible:ue(u.visible)?u.visible:s.trades.visible,labels:ue(u.labels)?u.labels:s.trades.labels,qty:ue(u.qty)?u.qty:s.trades.qty,longColor:j(u.longColor)?u.longColor:s.trades.longColor,shortColor:j(u.shortColor)?u.shortColor:s.trades.shortColor,exitColor:j(u.exitColor)?u.exitColor:s.trades.exitColor},timeScale:{timezone:typeof p.timezone=="string"&&p.timezone?p.timezone:s.timeScale.timezone},candles:{upColor:j(m.upColor)?m.upColor:s.candles.upColor,downColor:j(m.downColor)?m.downColor:s.candles.downColor,bodyVisible:ue(m.bodyVisible)?m.bodyVisible:s.candles.bodyVisible,borderVisible:ue(m.borderVisible)?m.borderVisible:s.candles.borderVisible,borderUpColor:j(m.borderUpColor)?m.borderUpColor:s.candles.borderUpColor,borderDownColor:j(m.borderDownColor)?m.borderDownColor:s.candles.borderDownColor,wickVisible:ue(m.wickVisible)?m.wickVisible:s.candles.wickVisible,wickUpColor:j(m.wickUpColor)?m.wickUpColor:s.candles.wickUpColor,wickDownColor:j(m.wickDownColor)?m.wickDownColor:s.candles.wickDownColor},bars:{upColor:j(f.upColor)?f.upColor:s.bars.upColor,downColor:j(f.downColor)?f.downColor:s.bars.downColor},line:{color:j(b.color)?b.color:s.line.color,width:Pe(b.width)?ts(b.width):s.line.width},area:{lineColor:j(g.lineColor)?g.lineColor:s.area.lineColor,width:Pe(g.width)?ts(g.width):s.area.width,topColor:j(g.topColor)?g.topColor:s.area.topColor,bottomColor:j(g.bottomColor)?g.bottomColor:s.area.bottomColor},baseline:{topLineColor:j(v.topLineColor)?v.topLineColor:s.baseline.topLineColor,bottomLineColor:j(v.bottomLineColor)?v.bottomLineColor:s.baseline.bottomLineColor,topFillColor:j(v.topFillColor)?v.topFillColor:s.baseline.topFillColor,topFillColor2:j(v.topFillColor2)?v.topFillColor2:s.baseline.topFillColor2,bottomFillColor:j(v.bottomFillColor)?v.bottomFillColor:s.baseline.bottomFillColor,bottomFillColor2:j(v.bottomFillColor2)?v.bottomFillColor2:s.baseline.bottomFillColor2,width:Pe(v.width)?ts(v.width):s.baseline.width,baselineLevel:Pe(v.baselineLevel)?bm(v.baselineLevel):s.baseline.baselineLevel},series:{style:pm(y.style)?y.style:s.series.style,baseline:y.baseline===null?null:Pe(y.baseline)?y.baseline:s.series.baseline,spacing:Pe(y.spacing)?gm(y.spacing):s.series.spacing},stacking:{candles:Pe(x.candles)?x.candles:s.stacking.candles,series:{...s.stacking.series,...Object.fromEntries(Object.entries(S).filter(([,C])=>Pe(C)))}}}}var vm=wa,ym=Sa,xm=Ca;function Ul(){return {visible:true,labels:true,qty:true,colors:{long:vm,short:ym,exit:xm}}}function Gl(s,e){let t=e&&typeof e=="object"?e:{},n=t.colors&&typeof t.colors=="object"?t.colors:{},r=(o,a)=>typeof o=="boolean"?o:a,i=(o,a)=>typeof o=="string"&&o.trim().length>0?o:a;return {visible:r(t.visible,s.visible),labels:r(t.labels,s.labels),qty:r(t.qty,s.qty),colors:{long:i(n.long,s.colors.long),short:i(n.short,s.colors.short),exit:i(n.exit,s.colors.exit)}}}var os=10,ot=9,It=6,nn=14,Ui=3,ss=2,Yl=2,as=3,ls=6,_l=6,Nl=8;function Xl(s){return s+4}function wm(s){if(s.qty==null||!Number.isFinite(s.qty))return null;let e=Number(Math.abs(s.qty).toFixed(8));return `${s.side==="buy"?"+":"-"}${e}`}function Sm(s,e,t){let n=[];if(e.labels&&s.label&&n.push(s.label),e.qty){let r=wm(s);r&&n.push(r);}return {exec:s,lines:n,height:nn+(n.length?as+n.length*t:0)}}function Kl(s,e,t,n,r,i){let o=new Map;for(let a of s){let l=Math.round(t.timeToLogical(a.time));if(l<n||l>r)continue;let c=o.get(l);c||(c={logical:l,buys:[],sells:[]},o.set(l,c)),(a.side==="buy"?c.buys:c.sells).push(Sm(a,e,i));}return [...o.values()]}function Hl(s){if(s.length===0)return 0;let e=os;for(let t of s)e+=t.height;return e+(s.length-1)*ls}function jl(s,e,t,n,r,i){if(s.length===0)return null;let o=Xl(i),a=1/0,l=-1/0,c=0,d=0;for(let h of Kl(s,e,t,Math.floor(n),Math.ceil(r),o)){let u=t.barAt(h.logical);u&&(u.low<a&&(a=u.low),u.high>l&&(l=u.high),d=Math.max(d,Hl(h.buys)),c=Math.max(c,Hl(h.sells)));}return !Number.isFinite(a)||!Number.isFinite(l)?null:{min:a,max:l,abovePx:c,belowPx:d}}function ql(s,e,t,n,r,i,o,a,l){if(e.length===0)return;let c=Xl(o.fontSize),d=Kl(e,t,n,-1/0,1/0,c);if(d.length!==0){s.save(),s.font=`${o.fontSize}px ${o.fontFamily}`,s.textAlign="center",s.textBaseline="middle";for(let h of d){let u=r(h.logical);if(u<-150||u>a+150)continue;let p=n.barAt(h.logical);if(!p)continue;let m=Math.max(i(p.low),i(p.high)),f=Math.min(i(p.low),i(p.high)),b=m+os;for(let g of h.buys)s.fillStyle=zl(g.exec,t.colors),Cm(s,u,b,g.exec.kind==="exit"),$l(s,g.exec.side,u,i(g.exec.price),l),Wl(s,g.lines,u,b+nn+as+c/2,c,o.color),b+=g.height+ls;b=f-os;for(let g of h.sells)s.fillStyle=zl(g.exec,t.colors),Tm(s,u,b,g.exec.kind==="exit"),$l(s,g.exec.side,u,i(g.exec.price),l),Wl(s,g.lines,u,b-nn-as-c/2,-c,o.color),b-=g.height+ls;}s.restore();}}function zl(s,e){return s.kind==="exit"?e.exit:s.side==="buy"?e.long:e.short}function Cm(s,e,t,n){s.beginPath(),s.moveTo(e,t),s.lineTo(e-ot/2,t+It),s.lineTo(e+ot/2,t+It),s.closePath(),s.fill(),s.fillRect(e-Ui/2,t+It,Ui,nn-It),n&&s.fillRect(e-ot/2,t-Yl-ss,ot,ss);}function Tm(s,e,t,n){s.beginPath(),s.moveTo(e,t),s.lineTo(e-ot/2,t-It),s.lineTo(e+ot/2,t-It),s.closePath(),s.fill(),s.fillRect(e-Ui/2,t-nn,Ui,nn-It),n&&s.fillRect(e-ot/2,t+Yl,ot,ss);}function $l(s,e,t,n,r){let i=e==="buy"?t-r:t+r,o=e==="buy"?i-_l:i+_l;s.beginPath(),s.moveTo(i,n),s.lineTo(o,n-Nl/2),s.lineTo(o,n+Nl/2),s.closePath(),s.fill();}function Wl(s,e,t,n,r,i){if(e.length!==0){s.fillStyle=i;for(let o=0;o<e.length;o+=1)s.fillText(e[o],t,n+o*r);}}var Gi=class{constructor(){this.panes=new Map;this.indicators=new Map;this.bars=[];this.volumeLayer=null;this.nativeData=new Map;this.nativePending=new Map;this.vpvrLayer=null;this.crosshair=null;this.priceStyle="candles";this.basePainting="candles";this.candleOverride=null;this.baselineValue=null;this.showPriceLine=true;this.showPriceLabel=true;this.showCountdown=true;this.logScale=false;this.invertScale=false;this.priceMintick=void 0;this.scaleMode="price";this.percentBaseline=0;this.timezone="UTC";this.showGrid=true;this.style=Ol();this.showAxisLabels=true;this.tradeMarkers=Ul();this.highlights=[];this.candleZ=0;this.candlesHidden=false;this.seriesZ=new Map;this.drawingSlices=new Map;this.anchorOffsets=new Map;this.indicatorScales=new Map;this.orderedCache=null;}orderedPanes(){return this.orderedCache||(this.orderedCache=[...this.panes.values()].sort((e,t)=>e.order-t.order)),this.orderedCache}indicatorsForPane(e){let t=[];for(let n of this.indicators.values())n.paneId===e&&t.push(n);return t}ownScaleIndicatorsForPane(e){return this.orderedIndicatorsForPane(e).filter(t=>t.ownScale===true)}ensureIndicatorScale(e,t){let n=this.indicatorScales.get(e);if(!n){let r=t??{min:0,max:1};n={scale:{...r},scaleTarget:{...r},initialized:false,manualScale:null},this.indicatorScales.set(e,n);}return n}dropIndicatorScale(e){this.indicatorScales.delete(e);}scaleFor(e,t){if(e.ownScale===true){let n=this.indicatorScales.get(e.id);if(n)return n.scale}return t.scale}orderPanes(e){e.forEach((t,n)=>{let r=this.panes.get(t);r&&(r.order=n);}),this.orderedCache=null;}orderedIndicatorsForPane(e){return this.indicatorsForPane(e).sort((t,n)=>this.zOf(t.id)-this.zOf(n.id))}zOf(e){return this.seriesZ.get(e)??0}offsetOf(e){return this.anchorOffsets.get(e)??0}setAnchorOffset(e,t){t!==0&&Number.isFinite(t)?this.anchorOffsets.set(e,t):this.anchorOffsets.delete(e);}forgetAnchorOffset(e){this.anchorOffsets.delete(e);}baselinePriceFor(e){if(this.baselineValue!=null)return this.baselineValue;let t=this.style.baseline.baselineLevel/100;if(e.log&&e.min>0&&e.max>e.min){let n=Math.log(e.min);return Math.exp(n+t*(Math.log(e.max)-n))}return e.min+(e.max-e.min)*t}assignIndicatorZ(e){this.seriesZ.has(e)||this.seriesZ.set(e,this.bottomZ()-1);}forgetIndicatorZ(e){this.seriesZ.delete(e);}setIndicatorZ(e,t){this.seriesZ.set(e,t);}indicatorZOrder(){return [...this.seriesZ.entries()].map(([e,t])=>({id:e,z:t})).sort((e,t)=>e.z-t.z)}seriesBoundaries(e){let t=new Set;e==="price"&&t.add(this.candleZ);for(let n of this.indicatorsForPane(e))t.add(this.zOf(n.id));return [...t].sort((n,r)=>n-r)}bringIndicatorToFront(e){this.seriesZ.set(e,this.topZ()+1);}sendIndicatorToBack(e){this.seriesZ.set(e,this.bottomZ()-1);}topZ(){let e=this.candleZ;for(let t of this.seriesZ.values())t>e&&(e=t);return e}bottomZ(){let e=this.candleZ;for(let t of this.seriesZ.values())t<e&&(e=t);return e}ensurePane(e,t,n,r){this.orderedCache=null;let i=this.panes.get(e);if(i)return i.order=n,i.heightWeight=r,i.kind=t,i;let o={id:e,kind:t,order:n,heightWeight:r,bounds:{top:0,height:0},scale:{min:0,max:1},scaleTarget:{min:0,max:1},initialized:false,manualScale:null,collapsed:false,percentBaseline:0};return this.panes.set(e,o),o}removePane(e){this.panes.delete(e),this.orderedCache=null;}};function cs(s,e){return e.kind==="price"?s.scaleMode:e.scaleMode??"price"}function ds(s,e){return e.kind==="price"?s.logScale:e.logScale??false}function hs(s,e){return e.kind==="price"?s.invertScale:e.invert??false}function Ee(s,e){let t=cs(s,e);if(t!=="percent"&&t!=="indexed")return;let n=e.percentBaseline;if(!(!Number.isFinite(n)||n===0))return {baseline:n,indexed:t==="indexed"}}function Rt(s,e){if(!e||e==="UTC")return 0;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(new Date(s)),r=o=>Number(n.find(a=>a.type===o)?.value);return Date.UTC(r("year"),r("month")-1,r("day"),r("hour")%24,r("minute"),r("second"))-s}catch{return 0}}function Yi(s,e){return new Date(s+Rt(s,e))}function Xn(s){let e=Math.max(.5,Math.floor(s*.7)/2);return Math.max(1,Math.min(1.5,e))}function rn(s){return s<1?"aggregate":s<3?"wick":"full"}function Xi(s,e,t,n=1){let r=Math.max(1,Math.round(Xn(e)*t)),i=Math.round(s*t-r/2),o=Math.max(r,Math.round(Math.floor(e*.7*n)*t));(o-r)%2!==0&&(o+=1);let a=(o-r)/2;return {wickX:i/t,wickW:r/t,bodyX:(i-a)/t,bodyW:o/t,center:(i+r/2)/t}}var Kn=class{constructor(e=4096){this.n=0;this.alpha=1;this.buf=new Float32Array(e*8);}reset(){this.n=0;}get vertexCount(){return this.n/8}get view(){return this.buf.subarray(0,this.n)}ensure(e){let t=this.n+e*8;if(t<=this.buf.length)return;let n=this.buf.length||8;for(;n<t;)n*=2;let r=new Float32Array(n);r.set(this.buf.subarray(0,this.n)),this.buf=r;}v(e,t,n,r=0,i=-1){let o=this.buf,a=this.n;o[a++]=e,o[a++]=t,o[a++]=n[0],o[a++]=n[1],o[a++]=n[2],o[a++]=n[3]*this.alpha,o[a++]=r,o[a++]=i,this.n=a;}tri(e,t,n,r,i,o,a,l,c){this.ensure(3),this.v(e,t,n),this.v(r,i,o),this.v(a,l,c);}quad4(e,t,n,r,i,o,a,l,c,d,h,u){this.ensure(6),this.v(e,t,n),this.v(r,i,o),this.v(a,l,c),this.v(e,t,n),this.v(a,l,c),this.v(d,h,u);}quad(e,t,n,r,i,o,a,l,c){this.quad4(e,t,c,n,r,c,i,o,c,a,l,c);}rect(e,t,n,r,i){this.quad(e,t,e+n,t,e+n,t+r,e,t+r,i);}seg(e,t,n,r,i,o){let a=n-e,l=r-t,c=Math.hypot(a,l);if(c<1e-6)return;let d=i/2,h=d+1,u=-l/c*h,p=a/c*h,m=e+u,f=t+p,b=n+u,g=r+p,v=n-u,y=r-p,x=e-u,S=t-p;this.ensure(6),this.v(m,f,o,h,d),this.v(b,g,o,h,d),this.v(v,y,o,-h,d),this.v(m,f,o,h,d),this.v(v,y,o,-h,d),this.v(x,S,o,-h,d);}dashedSeg(e,t,n,r,i,o,a){if(!a){this.seg(e,t,n,r,i,o);return}let l=n-e,c=r-t,d=Math.hypot(l,c);if(d<1e-6)return;let h=l/d,u=c/d,p=a[0]+a[1];if(p<=0){this.seg(e,t,n,r,i,o);return}let m=0;for(;m<d;){let f=Math.min(a[0],d-m),b=m,g=m+f;this.seg(e+h*b,t+u*b,e+h*g,t+u*g,i,o),m+=p;}}rectStroke(e,t,n,r,i,o){this.seg(e,t,e+n,t,i,o),this.seg(e+n,t,e+n,t+r,i,o),this.seg(e+n,t+r,e,t+r,i,o),this.seg(e,t+r,e,t,i,o);}circle(e,t,n,r,i=16){let o=e+n,a=t;for(let l=1;l<=i;l+=1){let c=l/i*Math.PI*2,d=e+Math.cos(c)*n,h=t+Math.sin(c)*n;this.tri(e,t,r,o,a,r,d,h,r),o=d,a=h;}}};var Jl=[0,0,0,1],st=null,Mm=8192,on=new Map,Zl=new Map;function U(s){if(!s)return Jl;let e=on.get(s);return e||(e=Zl.get(s),e?(on.set(s,e),e):(e=Lm(s),on.set(s,e),on.size>=Mm&&(Zl=on,on=new Map),e))}function Ql(s,e="#000000"){let[t,n,r,i]=U(s),o=t,a=n,l=r;if(i<1){let[u,p,m]=U(e);o=t*i+u*(1-i),a=n*i+p*(1-i),l=r*i+m*(1-i);}let c=.2126*us(o)+.7152*us(a)+.0722*us(l),d=(c+.05)/.05,h=1.05/(c+.05);return d>=h?"#000000":"#ffffff"}function us(s){return s<=.04045?s/12.92:Math.pow((s+.055)/1.055,2.4)}function Lm(s){if(!st){let t=document.createElement("canvas");t.width=1,t.height=1,st=t.getContext("2d",{willReadFrequently:true});}if(!st)return Jl;st.clearRect(0,0,1,1),st.fillStyle="#000",st.fillStyle=s,st.fillRect(0,0,1,1);let e=st.getImageData(0,0,1,1).data;return [e[0]/255,e[1]/255,e[2]/255,e[3]/255]}var Pm=`#version 300 es
32
+ `,document.head.appendChild(s);}var _i=class{constructor(e,t,n){this.plot=e;this.theme=t;this.deps=n;this.clusters=new Map;this.hoverPaneId=null;this.onPlotMove=e=>{let t=this.plot.getBoundingClientRect(),n=e.clientY-t.top,r=null;for(let i of this.deps.panes())if(n>=i.top&&n<=i.top+i.height){r=i.id;break}this.setHoverPane(r);};this.onPlotLeave=()=>this.setHoverPane(null);im(),this.root=document.createElement("div"),Object.assign(this.root.style,{position:"absolute",inset:"0",pointerEvents:"none",zIndex:"6"}),this.plot.appendChild(this.root),this.plot.addEventListener("pointermove",this.onPlotMove),this.plot.addEventListener("pointerleave",this.onPlotLeave),this.refresh();}setTheme(e){this.theme=e,this.refresh();}refresh(){let e=this.deps.panes(),t=new Set;for(let n of e){t.add(n.id);let r=this.clusters.get(n.id);r||(r=document.createElement("div"),Object.assign(r.style,{position:"absolute",display:"flex",gap:"2px",padding:"2px",borderRadius:"var(--vela-radius-md)",background:Ml,pointerEvents:"auto"}),this.root.appendChild(r),this.clusters.set(n.id,r)),this.buildButtons(r,n);}for(let[n,r]of this.clusters)t.has(n)||(r.remove(),this.clusters.delete(n));this.reposition();}buildButtons(e,t){e.textContent="",t.kind==="study"&&(e.appendChild(this.button(jt.up,"Move pane up",t.index<=1,()=>this.deps.onMove(t.id,"up"),{role:"up"})),e.appendChild(this.button(jt.down,"Move pane down",t.index>=t.count-1,()=>this.deps.onMove(t.id,"down"),{role:"down"})),e.appendChild(this.button(t.collapsed?jt.expand:jt.collapse,t.collapsed?"Expand pane":"Collapse pane",false,()=>this.deps.onToggleCollapse(t.id),{role:"collapse",selected:t.collapsed}))),t.count>1&&e.appendChild(this.button(t.maximized?jt.restore:jt.maximize,t.maximized?"Restore pane":"Maximize pane",false,()=>this.deps.onToggleMaximize(t.id),{role:"maximize"}));}button(e,t,n,r,i){let o=document.createElement("button");o.type="button",o.title=t,o.innerHTML=e,o.disabled=n,o.dataset.role=i.role;let a=i.selected===true;return o.className=a?"vela-pc-btn vela-pc-on":"vela-pc-btn",Object.assign(o.style,{cursor:n?"default":"pointer",width:"20px",height:"20px",opacity:n?"0.3":"1"}),n||o.addEventListener("click",l=>{l.stopPropagation(),r();}),o}reposition(){let e=this.deps.rightAxis()+6,t=new Map(this.deps.panes().map(n=>[n.id,n]));for(let[n,r]of this.clusters){let i=t.get(n);if(!i){r.style.display="none";continue}let o=n===this.hoverPaneId,l=r.children.length>0&&(o||i.collapsed)&&i.height>8;if(r.style.right=`${e}px`,r.style.top=i.collapsed?`${i.top+Math.max(1,Math.round((i.height-24)/2))}px`:`${i.top+4}px`,r.style.display=l?"flex":"none",!l)continue;let c=i.collapsed&&!o;r.style.background=c?"transparent":Ml;for(let d of r.children){let h=d;h.style.display="inline-flex",h.style.visibility=c&&h.dataset.role!=="collapse"?"hidden":"visible";}}}setHoverPane(e){this.hoverPaneId!==e&&(this.hoverPaneId=e,this.reposition());}destroy(){this.plot.removeEventListener("pointermove",this.onPlotMove),this.plot.removeEventListener("pointerleave",this.onPlotLeave),this.root.remove(),this.clusters.clear();}};var om={auto:13,tiny:10,small:11,normal:13,large:16,huge:20},Ni=class{constructor(e,t,n){this.container=e;this.theme=t;this.paneBounds=n;this.lastTables=[];getComputedStyle(e).position==="static"&&(e.style.position="relative"),this.root=document.createElement("div"),Object.assign(this.root.style,{position:"absolute",inset:"0",pointerEvents:"none",overflow:"hidden",zIndex:"3"}),e.appendChild(this.root);}update(e){this.lastTables=e,this.root.replaceChildren();for(let t of e)this.root.appendChild(this.renderTable(t));}reposition(){this.root.isConnected&&this.update(this.lastTables);}setVisible(e){this.root.style.display=e?"":"none";}destroy(){this.root.remove();}renderTable(e){let t=document.createElement("div");t.style.position="absolute",this.anchor(t,e.position,this.paneBounds(e.paneId));let n=document.createElement("table");Object.assign(n.style,{borderCollapse:"collapse",background:e.bgColor??"transparent",fontFamily:this.theme.fontFamily||"sans-serif",boxShadow:e.frameColor&&e.frameWidth>0?`inset 0 0 0 ${e.frameWidth}px ${e.frameColor}`:"none",border:"none",tableLayout:"auto",pointerEvents:"auto"});let r=new Map,i=new Set;for(let a of e.merges){r.set(`${a.startRow}:${a.startCol}`,{cs:a.endCol-a.startCol+1,rs:a.endRow-a.startRow+1});for(let l=a.startRow;l<=a.endRow;l+=1)for(let c=a.startCol;c<=a.endCol;c+=1)(l!==a.startRow||c!==a.startCol)&&i.add(`${l}:${c}`);}let o=e.borderColor&&e.borderWidth>0?`${e.borderWidth}px solid ${e.borderColor}`:"none";for(let a=0;a<e.rows;a+=1){let l=document.createElement("tr");for(let c=0;c<e.columns;c+=1){let d=e.cells[a]?.[c]??null;if(i.has(`${a}:${c}`)||d?.merged)continue;let h=document.createElement("td"),u=r.get(`${a}:${c}`);u&&(u.cs>1&&(h.colSpan=u.cs),u.rs>1&&(h.rowSpan=u.rs)),Object.assign(h.style,{border:o,padding:"2px 6px",background:d?.bgColor??"transparent",color:d?.textColor??this.theme.textColor,textAlign:d?.hAlign??"center",verticalAlign:d?.vAlign==="top"?"top":d?.vAlign==="bottom"?"bottom":"middle",fontSize:`${om[d?.textSize??"normal"]}px`,fontFamily:d?.fontFamily==="monospace"?"monospace":"inherit",fontWeight:d?.bold?"bold":"normal",fontStyle:d?.italic?"italic":"normal",whiteSpace:"pre-line"}),d?.tooltip&&(h.title=d.tooltip),h.textContent=d?.text??"",l.appendChild(h);}n.appendChild(l);}return t.appendChild(n),t}anchor(e,t,n){let i=this.root.clientHeight||this.container.clientHeight,o=n.top+n.height;t.startsWith("top")?e.style.top=`${n.top+6}px`:t.startsWith("bottom")?e.style.bottom=`${Math.max(0,i-o)+6}px`:e.style.top=`${n.top+n.height/2}px`,t.endsWith("left")?e.style.left="6px":t.endsWith("right")?e.style.right=`${n.rightAxis+6}px`:e.style.left=`calc(50% - ${n.rightAxis/2}px)`;let a=t.endsWith("center")?"-50%":"0",l=t.startsWith("middle")?"-50%":"0";(a!=="0"||l!=="0")&&(e.style.transform=`translate(${a}, ${l})`);}};var Ll={panes:true,paneManagement:true,fills:"native",bgcolor:"native",hline:"native",markers:true,barcolor:"native",perPointColor:true,drawings:true,userDrawings:true,drawingDepth:true,tables:true,trades:true,inputsUI:true},$n=null;function Pl(){if($n!==null)return $n;try{$n=!!document.createElement("canvas").getContext("webgl2");}catch{$n=false;}return $n}function zi(s,e,t=6){if(!(e>s)||!Number.isFinite(s)||!Number.isFinite(e))return [];let n=(e-s)/Math.max(1,t),r=Math.pow(10,Math.floor(Math.log10(n))),i=n/r,o=(i<1.5?1:i<3?2:i<7?5:10)*r,a=Math.max(0,-Math.floor(Math.log10(o))+1),l=[],c=Math.ceil(s/o)*o;for(let d=c;d<=e+o*1e-6;d+=o)l.push(Number(d.toFixed(a)));return l}function sm(s,e,t=6){if(!(e>s))return 2;let n=(e-s)/Math.max(1,t),r=Math.pow(10,Math.floor(Math.log10(n))),i=n/r,o=(i<1.5?1:i<3?2:i<7?5:10)*r;return Math.max(0,Math.min(8,-Math.floor(Math.log10(o))+1))}function am(s,e,t=6){if(s<=0||!(e>s)||!Number.isFinite(s)||!Number.isFinite(e))return [];if(Math.log10(e)-Math.log10(s)<1.1)return zi(s,e,t);let n=[],r=Math.floor(Math.log10(s)),i=Math.ceil(Math.log10(e));for(let o=r;o<=i;o+=1)for(let a of [1,2,5]){let l=a*Math.pow(10,o);l>=s&&l<=e&&n.push(l);}return n}function es(s){let e=Math.abs(s);return e>=100?0:e>=1?2:e>=.01?4:6}function lm(s){if(!(s>0)||!Number.isFinite(s))return 2;for(let e=0;e<=8;e+=1)if(Math.abs(Number(s.toFixed(e))-s)<=s*1e-6)return e;return 8}function cm(s,e,t){let n=t!=null&&t>0?lm(t):sm(s.min,s.max,Gn(e));return n===0?2:n}function Gn(s){return Math.max(2,Math.min(16,Math.round(s/50)))}function El(s,e){return s.log?am(s.min,s.max,Gn(e)):zi(s.min,s.max,Gn(e))}function Jo(s,e){return (s/e-1)*100}function Qo(s,e){return s/e*100}function Rl(s){return `${s>=0?"+":"-"}${Math.abs(s).toFixed(2)}%`}function Dl(s){return s.toFixed(2)}function Al(s){let e=Math.abs(s);return e>=1e9?`${Hi(s/1e9)}B`:e>=1e6?`${Hi(s/1e6)}M`:e>=1e3?`${Hi(s/1e3)}K`:Hi(s)}function Hi(s){return Number(s.toFixed(2)).toString()}function kt(s,e,t,n,r){if(t){let{baseline:i,indexed:o}=t,a=Math.min(s.min,s.max),l=Math.max(s.min,s.max);if(o){let h=Qo(a,i),u=Qo(l,i);return zi(h,u,Gn(e)).map(p=>({price:i*p/100,label:Dl(p)}))}let c=Jo(a,i),d=Jo(l,i);return zi(c,d,Gn(e)).map(h=>({price:i*(1+h/100),label:Rl(h)}))}return r==="volume"?El(s,e).map(i=>({price:i,label:Al(i)})):El(s,e).map(i=>({price:i,label:$i(s,e,i,n)}))}function Yn(s,e,t,n,r,i){return n?n.indexed?Dl(Qo(t,n.baseline)):Rl(Jo(t,n.baseline)):i==="volume"?Al(t):$i(s,e,t,r)}function $i(s,e,t,n){if(s.log&&Math.log10(s.max)-Math.log10(s.min)>=1.1){let i=es(t);return t.toFixed(i===0?2:i)}return t.toFixed(cm(s,e,n))}var Wn=1e3,Un=60*Wn,qt=60*Un,Zt=24*qt,dm=7*Zt,kl=30*Zt,Ol=365*Zt,qo=[Wn,5*Wn,15*Wn,30*Wn,Un,5*Un,15*Un,30*Un,qt,2*qt,4*qt,6*qt,12*qt,Zt,2*Zt,dm,kl,3*kl,Ol],Zo=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Il=s=>s<10?`0${s}`:String(s);function hm(s){for(let e of qo)if(e>=s)return e;return qo[qo.length-1]}function Jt(s,e,t=8,n=0){let r=e-s;if(!(r>0))return [];let i=hm(r/Math.max(1,t)),o=s+n,a=e+n,l=Math.ceil(o/i)*i,c=[];for(let d=l;d<=a;d+=i){let h=d-n,u=new Date(d),p,m=false;if(i<Zt){let f=u.getUTCHours(),b=u.getUTCMinutes();f===0&&b===0?(p=`${Zo[u.getUTCMonth()]} ${u.getUTCDate()}`,m=true):p=`${Il(f)}:${Il(b)}`;}else i<Ol?(p=`${Zo[u.getUTCMonth()]} ${u.getUTCDate()}`,u.getUTCDate()===1&&(p=Zo[u.getUTCMonth()],m=true)):(p=String(u.getUTCFullYear()),m=true);c.push({time:h,label:p,major:m});}return c}var ns=1,Qt=q,en=X,Ye=.25,Xe=.05,um=50;function Fl(){return {chartTypes:{},fontSize:11,gridVert:{visible:true,color:null},gridHorz:{visible:true,color:null},borderColor:null,separatorColor:null,crosshair:{color:xa,width:1,style:"dashed",opacity:.4,labelBackground:vr},candle:{bodyVisible:true,borderVisible:false,borderUpColor:null,borderDownColor:null,wickVisible:true,wickUpColor:null,wickDownColor:null},bars:{upColor:null,downColor:null},line:{color:gn,width:2},area:{lineColor:gn,width:2,topColor:W(gn,.28),bottomColor:W(gn,.02)},baseline:{topLineColor:null,bottomLineColor:null,topFillColor:null,topFillColor2:null,bottomFillColor:null,bottomFillColor2:null,width:2,baselineLevel:um}}}var pm=["solid","dashed","dotted"],Bl=["candles","bars","line","area","baseline","heikinashi"];function rs(s){for(let e of Ge())if(e.id===s)return e.basePainting??"candles";return "candles"}function is(s){if(Bl.includes(s))return false;for(let e of Ge())if(e.id===s)return (e.basePainting??"candles")==="candles";return false}function Wi(s,e){if(!is(s))return null;let t=e[s]??{},n=i=>j(i)?i:null,r=i=>ue(i)?i:null;return {upColor:n(t.candleUpColor),downColor:n(t.candleDownColor),bodyVisible:r(t.candleBodyVisible),borderVisible:r(t.candleBorderVisible),borderUpColor:n(t.candleBorderUpColor),borderDownColor:n(t.candleBorderDownColor),wickVisible:r(t.candleWickVisible),wickUpColor:n(t.candleWickUpColor),wickDownColor:n(t.candleWickDownColor)}}function Ui(s,e,t,n){return e?{up:e.upColor??t,down:e.downColor??n,candle:{bodyVisible:e.bodyVisible??s.bodyVisible,borderVisible:e.borderVisible??s.borderVisible,borderUpColor:e.borderUpColor??s.borderUpColor,borderDownColor:e.borderDownColor??s.borderDownColor,wickVisible:e.wickVisible??s.wickVisible,wickUpColor:e.wickUpColor??s.wickUpColor,wickDownColor:e.wickDownColor??s.wickDownColor}}:{up:t,down:n,candle:s}}function tn(){let s=[...Bl];for(let e of Ge())s.includes(e.id)||s.push(e.id);return s}function j(s){return typeof s=="string"&&s.trim().length>0}function ue(s){return typeof s=="boolean"}function Pe(s){return typeof s=="number"&&Number.isFinite(s)}function mm(s){return typeof s=="string"&&pm.includes(s)}function fm(s){return typeof s=="string"&&tn().includes(s)}function bm(s){return s==="price"||s==="percent"||s==="indexed"}function se(s){return s&&typeof s=="object"?s:{}}function gm(s){return s<0?0:s>1?1:s}function ts(s){return s<1?1:s>10?10:s}function vm(s){return s<0?0:s>100?100:s}function ym(s){return s<.1?.1:s>10?10:s}function Vl(s){let e={};for(let t of Ge()){let n=t.settings;if(!n)continue;let r={},i=o=>{for(let a of o??[])for(let l of Rn(a))r[l.key]=l.defval;};for(let o of n.instances??[])o.enableKey&&(r[o.enableKey]=false),i(o.rows);for(let o of n.subsections??[])o.enableKey&&(r[o.enableKey]=false),i(o.rows);n.instances||i(n.rows),e[t.id]=r;}for(let[t,n]of Object.entries(s.chartTypes))e[t]={...e[t]??{},...n};return {...s,chartTypes:e}}function _l(s,e){let t=se(e),n=se(t.chartTypes),r={...s.chartTypes};for(let[C,T]of Object.entries(n))r[C]={...r[C]??{},...se(T)};let i=se(t.layout),o=se(t.grid),a=se(o.vertLines),l=se(o.horzLines),c=se(t.crosshair),d=se(t.priceScale),h=se(t.panes),u=se(t.trades),p=se(t.timeScale),m=se(t.candles),f=se(t.bars),b=se(t.line),g=se(t.area),v=se(t.baseline),y=se(t.series),x=se(t.stacking),S=se(x.series);return {version:ns,chartTypes:r,layout:{background:j(i.background)?i.background:s.layout.background,textColor:j(i.textColor)?i.textColor:s.layout.textColor,fontFamily:j(i.fontFamily)?i.fontFamily:s.layout.fontFamily,fontSize:Pe(i.fontSize)?Math.max(6,Math.min(32,i.fontSize)):s.layout.fontSize},grid:{vertLines:{visible:ue(a.visible)?a.visible:s.grid.vertLines.visible,color:j(a.color)?a.color:s.grid.vertLines.color},horzLines:{visible:ue(l.visible)?l.visible:s.grid.horzLines.visible,color:j(l.color)?l.color:s.grid.horzLines.color}},crosshair:{color:j(c.color)?c.color:s.crosshair.color,width:Pe(c.width)?Math.max(.5,Math.min(8,c.width)):s.crosshair.width,style:mm(c.style)?c.style:s.crosshair.style,opacity:Pe(c.opacity)?gm(c.opacity):s.crosshair.opacity,labelBackground:j(c.labelBackground)?c.labelBackground:s.crosshair.labelBackground},priceScale:{mode:bm(d.mode)?d.mode:s.priceScale.mode,log:ue(d.log)?d.log:s.priceScale.log,invert:ue(d.invert)?d.invert:s.priceScale.invert,borderColor:j(d.borderColor)?d.borderColor:s.priceScale.borderColor,labelsVisible:ue(d.labelsVisible)?d.labelsVisible:s.priceScale.labelsVisible,currentPriceLine:ue(d.currentPriceLine)?d.currentPriceLine:s.priceScale.currentPriceLine,priceLabel:ue(d.priceLabel)?d.priceLabel:s.priceScale.priceLabel,countdown:ue(d.countdown)?d.countdown:s.priceScale.countdown},panes:{separatorColor:j(h.separatorColor)?h.separatorColor:s.panes.separatorColor},trades:{visible:ue(u.visible)?u.visible:s.trades.visible,labels:ue(u.labels)?u.labels:s.trades.labels,qty:ue(u.qty)?u.qty:s.trades.qty,longColor:j(u.longColor)?u.longColor:s.trades.longColor,shortColor:j(u.shortColor)?u.shortColor:s.trades.shortColor,exitColor:j(u.exitColor)?u.exitColor:s.trades.exitColor},timeScale:{timezone:typeof p.timezone=="string"&&p.timezone?p.timezone:s.timeScale.timezone},candles:{upColor:j(m.upColor)?m.upColor:s.candles.upColor,downColor:j(m.downColor)?m.downColor:s.candles.downColor,bodyVisible:ue(m.bodyVisible)?m.bodyVisible:s.candles.bodyVisible,borderVisible:ue(m.borderVisible)?m.borderVisible:s.candles.borderVisible,borderUpColor:j(m.borderUpColor)?m.borderUpColor:s.candles.borderUpColor,borderDownColor:j(m.borderDownColor)?m.borderDownColor:s.candles.borderDownColor,wickVisible:ue(m.wickVisible)?m.wickVisible:s.candles.wickVisible,wickUpColor:j(m.wickUpColor)?m.wickUpColor:s.candles.wickUpColor,wickDownColor:j(m.wickDownColor)?m.wickDownColor:s.candles.wickDownColor},bars:{upColor:j(f.upColor)?f.upColor:s.bars.upColor,downColor:j(f.downColor)?f.downColor:s.bars.downColor},line:{color:j(b.color)?b.color:s.line.color,width:Pe(b.width)?ts(b.width):s.line.width},area:{lineColor:j(g.lineColor)?g.lineColor:s.area.lineColor,width:Pe(g.width)?ts(g.width):s.area.width,topColor:j(g.topColor)?g.topColor:s.area.topColor,bottomColor:j(g.bottomColor)?g.bottomColor:s.area.bottomColor},baseline:{topLineColor:j(v.topLineColor)?v.topLineColor:s.baseline.topLineColor,bottomLineColor:j(v.bottomLineColor)?v.bottomLineColor:s.baseline.bottomLineColor,topFillColor:j(v.topFillColor)?v.topFillColor:s.baseline.topFillColor,topFillColor2:j(v.topFillColor2)?v.topFillColor2:s.baseline.topFillColor2,bottomFillColor:j(v.bottomFillColor)?v.bottomFillColor:s.baseline.bottomFillColor,bottomFillColor2:j(v.bottomFillColor2)?v.bottomFillColor2:s.baseline.bottomFillColor2,width:Pe(v.width)?ts(v.width):s.baseline.width,baselineLevel:Pe(v.baselineLevel)?vm(v.baselineLevel):s.baseline.baselineLevel},series:{style:fm(y.style)?y.style:s.series.style,baseline:y.baseline===null?null:Pe(y.baseline)?y.baseline:s.series.baseline,spacing:Pe(y.spacing)?ym(y.spacing):s.series.spacing},stacking:{candles:Pe(x.candles)?x.candles:s.stacking.candles,series:{...s.stacking.series,...Object.fromEntries(Object.entries(S).filter(([,C])=>Pe(C)))}}}}var xm=Sa,wm=Ca,Sm=Ta;function Gl(){return {visible:true,labels:true,qty:true,colors:{long:xm,short:wm,exit:Sm}}}function Yl(s,e){let t=e&&typeof e=="object"?e:{},n=t.colors&&typeof t.colors=="object"?t.colors:{},r=(o,a)=>typeof o=="boolean"?o:a,i=(o,a)=>typeof o=="string"&&o.trim().length>0?o:a;return {visible:r(t.visible,s.visible),labels:r(t.labels,s.labels),qty:r(t.qty,s.qty),colors:{long:i(n.long,s.colors.long),short:i(n.short,s.colors.short),exit:i(n.exit,s.colors.exit)}}}var os=10,ot=9,It=6,nn=14,Gi=3,ss=2,Xl=2,as=3,ls=6,Nl=6,Hl=8;function Kl(s){return s+4}function Cm(s){if(s.qty==null||!Number.isFinite(s.qty))return null;let e=Number(Math.abs(s.qty).toFixed(8));return `${s.side==="buy"?"+":"-"}${e}`}function Tm(s,e,t){let n=[];if(e.labels&&s.label&&n.push(s.label),e.qty){let r=Cm(s);r&&n.push(r);}return {exec:s,lines:n,height:nn+(n.length?as+n.length*t:0)}}function jl(s,e,t,n,r,i){let o=new Map;for(let a of s){let l=Math.round(t.timeToLogical(a.time));if(l<n||l>r)continue;let c=o.get(l);c||(c={logical:l,buys:[],sells:[]},o.set(l,c)),(a.side==="buy"?c.buys:c.sells).push(Tm(a,e,i));}return [...o.values()]}function zl(s){if(s.length===0)return 0;let e=os;for(let t of s)e+=t.height;return e+(s.length-1)*ls}function ql(s,e,t,n,r,i){if(s.length===0)return null;let o=Kl(i),a=1/0,l=-1/0,c=0,d=0;for(let h of jl(s,e,t,Math.floor(n),Math.ceil(r),o)){let u=t.barAt(h.logical);u&&(u.low<a&&(a=u.low),u.high>l&&(l=u.high),d=Math.max(d,zl(h.buys)),c=Math.max(c,zl(h.sells)));}return !Number.isFinite(a)||!Number.isFinite(l)?null:{min:a,max:l,abovePx:c,belowPx:d}}function Zl(s,e,t,n,r,i,o,a,l){if(e.length===0)return;let c=Kl(o.fontSize),d=jl(e,t,n,-1/0,1/0,c);if(d.length!==0){s.save(),s.font=`${o.fontSize}px ${o.fontFamily}`,s.textAlign="center",s.textBaseline="middle";for(let h of d){let u=r(h.logical);if(u<-150||u>a+150)continue;let p=n.barAt(h.logical);if(!p)continue;let m=Math.max(i(p.low),i(p.high)),f=Math.min(i(p.low),i(p.high)),b=m+os;for(let g of h.buys)s.fillStyle=$l(g.exec,t.colors),Mm(s,u,b,g.exec.kind==="exit"),Wl(s,g.exec.side,u,i(g.exec.price),l),Ul(s,g.lines,u,b+nn+as+c/2,c,o.color),b+=g.height+ls;b=f-os;for(let g of h.sells)s.fillStyle=$l(g.exec,t.colors),Lm(s,u,b,g.exec.kind==="exit"),Wl(s,g.exec.side,u,i(g.exec.price),l),Ul(s,g.lines,u,b-nn-as-c/2,-c,o.color),b-=g.height+ls;}s.restore();}}function $l(s,e){return s.kind==="exit"?e.exit:s.side==="buy"?e.long:e.short}function Mm(s,e,t,n){s.beginPath(),s.moveTo(e,t),s.lineTo(e-ot/2,t+It),s.lineTo(e+ot/2,t+It),s.closePath(),s.fill(),s.fillRect(e-Gi/2,t+It,Gi,nn-It),n&&s.fillRect(e-ot/2,t-Xl-ss,ot,ss);}function Lm(s,e,t,n){s.beginPath(),s.moveTo(e,t),s.lineTo(e-ot/2,t-It),s.lineTo(e+ot/2,t-It),s.closePath(),s.fill(),s.fillRect(e-Gi/2,t-nn,Gi,nn-It),n&&s.fillRect(e-ot/2,t+Xl,ot,ss);}function Wl(s,e,t,n,r){let i=e==="buy"?t-r:t+r,o=e==="buy"?i-Nl:i+Nl;s.beginPath(),s.moveTo(i,n),s.lineTo(o,n-Hl/2),s.lineTo(o,n+Hl/2),s.closePath(),s.fill();}function Ul(s,e,t,n,r,i){if(e.length!==0){s.fillStyle=i;for(let o=0;o<e.length;o+=1)s.fillText(e[o],t,n+o*r);}}var Yi=class{constructor(){this.panes=new Map;this.indicators=new Map;this.bars=[];this.volumeLayer=null;this.nativeData=new Map;this.nativePending=new Map;this.vpvrLayer=null;this.crosshair=null;this.priceStyle="candles";this.basePainting="candles";this.candleOverride=null;this.baselineValue=null;this.showPriceLine=true;this.showPriceLabel=true;this.showCountdown=true;this.logScale=false;this.invertScale=false;this.priceMintick=void 0;this.scaleMode="price";this.percentBaseline=0;this.timezone="UTC";this.showGrid=true;this.style=Fl();this.showAxisLabels=true;this.tradeMarkers=Gl();this.highlights=[];this.candleZ=0;this.candlesHidden=false;this.seriesZ=new Map;this.drawingSlices=new Map;this.anchorOffsets=new Map;this.indicatorScales=new Map;this.orderedCache=null;}orderedPanes(){return this.orderedCache||(this.orderedCache=[...this.panes.values()].sort((e,t)=>e.order-t.order)),this.orderedCache}indicatorsForPane(e){let t=[];for(let n of this.indicators.values())n.paneId===e&&t.push(n);return t}ownScaleIndicatorsForPane(e){return this.orderedIndicatorsForPane(e).filter(t=>t.ownScale===true)}ensureIndicatorScale(e,t){let n=this.indicatorScales.get(e);if(!n){let r=t??{min:0,max:1};n={scale:{...r},scaleTarget:{...r},initialized:false,manualScale:null},this.indicatorScales.set(e,n);}return n}dropIndicatorScale(e){this.indicatorScales.delete(e);}scaleFor(e,t){if(e.ownScale===true){let n=this.indicatorScales.get(e.id);if(n)return n.scale}return t.scale}orderPanes(e){e.forEach((t,n)=>{let r=this.panes.get(t);r&&(r.order=n);}),this.orderedCache=null;}orderedIndicatorsForPane(e){return this.indicatorsForPane(e).sort((t,n)=>this.zOf(t.id)-this.zOf(n.id))}zOf(e){return this.seriesZ.get(e)??0}offsetOf(e){return this.anchorOffsets.get(e)??0}setAnchorOffset(e,t){t!==0&&Number.isFinite(t)?this.anchorOffsets.set(e,t):this.anchorOffsets.delete(e);}forgetAnchorOffset(e){this.anchorOffsets.delete(e);}baselinePriceFor(e){if(this.baselineValue!=null)return this.baselineValue;let t=this.style.baseline.baselineLevel/100;if(e.log&&e.min>0&&e.max>e.min){let n=Math.log(e.min);return Math.exp(n+t*(Math.log(e.max)-n))}return e.min+(e.max-e.min)*t}assignIndicatorZ(e){this.seriesZ.has(e)||this.seriesZ.set(e,this.bottomZ()-1);}forgetIndicatorZ(e){this.seriesZ.delete(e);}setIndicatorZ(e,t){this.seriesZ.set(e,t);}indicatorZOrder(){return [...this.seriesZ.entries()].map(([e,t])=>({id:e,z:t})).sort((e,t)=>e.z-t.z)}seriesBoundaries(e){let t=new Set;e==="price"&&t.add(this.candleZ);for(let n of this.indicatorsForPane(e))t.add(this.zOf(n.id));return [...t].sort((n,r)=>n-r)}bringIndicatorToFront(e){this.seriesZ.set(e,this.topZ()+1);}sendIndicatorToBack(e){this.seriesZ.set(e,this.bottomZ()-1);}topZ(){let e=this.candleZ;for(let t of this.seriesZ.values())t>e&&(e=t);return e}bottomZ(){let e=this.candleZ;for(let t of this.seriesZ.values())t<e&&(e=t);return e}ensurePane(e,t,n,r){this.orderedCache=null;let i=this.panes.get(e);if(i)return i.order=n,i.heightWeight=r,i.kind=t,i;let o={id:e,kind:t,order:n,heightWeight:r,bounds:{top:0,height:0},scale:{min:0,max:1},scaleTarget:{min:0,max:1},initialized:false,manualScale:null,collapsed:false,percentBaseline:0};return this.panes.set(e,o),o}removePane(e){this.panes.delete(e),this.orderedCache=null;}};function cs(s,e){return e.kind==="price"?s.scaleMode:e.scaleMode??"price"}function ds(s,e){return e.kind==="price"?s.logScale:e.logScale??false}function hs(s,e){return e.kind==="price"?s.invertScale:e.invert??false}function Ee(s,e){let t=cs(s,e);if(t!=="percent"&&t!=="indexed")return;let n=e.percentBaseline;if(!(!Number.isFinite(n)||n===0))return {baseline:n,indexed:t==="indexed"}}function Rt(s,e){if(!e||e==="UTC")return 0;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(new Date(s)),r=o=>Number(n.find(a=>a.type===o)?.value);return Date.UTC(r("year"),r("month")-1,r("day"),r("hour")%24,r("minute"),r("second"))-s}catch{return 0}}function Xi(s,e){return new Date(s+Rt(s,e))}function Xn(s){let e=Math.max(.5,Math.floor(s*.7)/2);return Math.max(1,Math.min(1.5,e))}function rn(s){return s<1?"aggregate":s<3?"wick":"full"}function Ki(s,e,t,n=1){let r=Math.max(1,Math.round(Xn(e)*t)),i=Math.round(s*t-r/2),o=Math.max(r,Math.round(Math.floor(e*.7*n)*t));(o-r)%2!==0&&(o+=1);let a=(o-r)/2;return {wickX:i/t,wickW:r/t,bodyX:(i-a)/t,bodyW:o/t,center:(i+r/2)/t}}var Kn=class{constructor(e=4096){this.n=0;this.alpha=1;this.buf=new Float32Array(e*8);}reset(){this.n=0;}get vertexCount(){return this.n/8}get view(){return this.buf.subarray(0,this.n)}ensure(e){let t=this.n+e*8;if(t<=this.buf.length)return;let n=this.buf.length||8;for(;n<t;)n*=2;let r=new Float32Array(n);r.set(this.buf.subarray(0,this.n)),this.buf=r;}v(e,t,n,r=0,i=-1){let o=this.buf,a=this.n;o[a++]=e,o[a++]=t,o[a++]=n[0],o[a++]=n[1],o[a++]=n[2],o[a++]=n[3]*this.alpha,o[a++]=r,o[a++]=i,this.n=a;}tri(e,t,n,r,i,o,a,l,c){this.ensure(3),this.v(e,t,n),this.v(r,i,o),this.v(a,l,c);}quad4(e,t,n,r,i,o,a,l,c,d,h,u){this.ensure(6),this.v(e,t,n),this.v(r,i,o),this.v(a,l,c),this.v(e,t,n),this.v(a,l,c),this.v(d,h,u);}quad(e,t,n,r,i,o,a,l,c){this.quad4(e,t,c,n,r,c,i,o,c,a,l,c);}rect(e,t,n,r,i){this.quad(e,t,e+n,t,e+n,t+r,e,t+r,i);}seg(e,t,n,r,i,o){let a=n-e,l=r-t,c=Math.hypot(a,l);if(c<1e-6)return;let d=i/2,h=d+1,u=-l/c*h,p=a/c*h,m=e+u,f=t+p,b=n+u,g=r+p,v=n-u,y=r-p,x=e-u,S=t-p;this.ensure(6),this.v(m,f,o,h,d),this.v(b,g,o,h,d),this.v(v,y,o,-h,d),this.v(m,f,o,h,d),this.v(v,y,o,-h,d),this.v(x,S,o,-h,d);}dashedSeg(e,t,n,r,i,o,a){if(!a){this.seg(e,t,n,r,i,o);return}let l=n-e,c=r-t,d=Math.hypot(l,c);if(d<1e-6)return;let h=l/d,u=c/d,p=a[0]+a[1];if(p<=0){this.seg(e,t,n,r,i,o);return}let m=0;for(;m<d;){let f=Math.min(a[0],d-m),b=m,g=m+f;this.seg(e+h*b,t+u*b,e+h*g,t+u*g,i,o),m+=p;}}rectStroke(e,t,n,r,i,o){this.seg(e,t,e+n,t,i,o),this.seg(e+n,t,e+n,t+r,i,o),this.seg(e+n,t+r,e,t+r,i,o),this.seg(e,t+r,e,t,i,o);}circle(e,t,n,r,i=16){let o=e+n,a=t;for(let l=1;l<=i;l+=1){let c=l/i*Math.PI*2,d=e+Math.cos(c)*n,h=t+Math.sin(c)*n;this.tri(e,t,r,o,a,r,d,h,r),o=d,a=h;}}};var Ql=[0,0,0,1],st=null,Pm=8192,on=new Map,Jl=new Map;function U(s){if(!s)return Ql;let e=on.get(s);return e||(e=Jl.get(s),e?(on.set(s,e),e):(e=Em(s),on.set(s,e),on.size>=Pm&&(Jl=on,on=new Map),e))}function ec(s,e="#000000"){let[t,n,r,i]=U(s),o=t,a=n,l=r;if(i<1){let[u,p,m]=U(e);o=t*i+u*(1-i),a=n*i+p*(1-i),l=r*i+m*(1-i);}let c=.2126*us(o)+.7152*us(a)+.0722*us(l),d=(c+.05)/.05,h=1.05/(c+.05);return d>=h?"#000000":"#ffffff"}function us(s){return s<=.04045?s/12.92:Math.pow((s+.055)/1.055,2.4)}function Em(s){if(!st){let t=document.createElement("canvas");t.width=1,t.height=1,st=t.getContext("2d",{willReadFrequently:true});}if(!st)return Ql;st.clearRect(0,0,1,1),st.fillStyle="#000",st.fillStyle=s,st.fillRect(0,0,1,1);let e=st.getImageData(0,0,1,1).data;return [e[0]/255,e[1]/255,e[2]/255,e[3]/255]}var km=`#version 300 es
33
33
  layout(location=0) in vec2 aPos;
34
34
  layout(location=1) in vec4 aColor;
35
35
  layout(location=2) in vec2 aEdge; // (signed perpendicular distance from line center, half-width)
@@ -41,7 +41,7 @@ void main() {
41
41
  gl_Position = vec4(clip, 0.0, 1.0);
42
42
  vColor = aColor;
43
43
  vEdge = aEdge;
44
- }`,Em=`#version 300 es
44
+ }`,Im=`#version 300 es
45
45
  precision highp float;
46
46
  in vec4 vColor;
47
47
  in vec2 vEdge;
@@ -51,13 +51,13 @@ void main() {
51
51
  float aa = fwidth(vEdge.x);
52
52
  float cov = clamp((vEdge.y - abs(vEdge.x)) / max(aa, 1e-4) + 0.5, 0.0, 1.0);
53
53
  frag = vec4(vColor.rgb, vColor.a * cov);
54
- }`,km=`#version 300 es
54
+ }`,Rm=`#version 300 es
55
55
  layout(location=0) in vec2 aPos;
56
56
  out vec2 vUv;
57
57
  void main() {
58
58
  vUv = aPos * 0.5 + 0.5;
59
59
  gl_Position = vec4(aPos, 0.0, 1.0);
60
- }`,Im=`#version 300 es
60
+ }`,Dm=`#version 300 es
61
61
  precision mediump float;
62
62
  in vec2 vUv;
63
63
  uniform sampler2D uTex;
@@ -77,25 +77,25 @@ void main() {
77
77
  sum += texture(uTex, vUv + o2) * 0.0702702703;
78
78
  sum += texture(uTex, vUv - o2) * 0.0702702703;
79
79
  frag = sum;
80
- }`,ps={solid:null,dashed:[6,4],dotted:[2,3]};function ec(s,e){let t=Math.max(1,Math.round(e));return {pos:Math.round(s*e-t/2)/e,size:t/e}}function tc(s){return Math.max(6,Math.min(20,Math.round(s*4)))}var qi=class{constructor(){this.kind="webgl2";this.modelAlpha=1;this.candleBodyAlpha=1;this.candleStructureAlpha=1;this.gridAlpha=1;this.candleBodyScale=1;this.onNeedsRedraw=null;this.onContextFailed=null;this.glow=0;this.canvas=null;this.gl=null;this.program=null;this.vao=null;this.vbo=null;this.uRes=null;this.batch=new Kn;this.contextLost=false;this.screenProgram=null;this.uTex=null;this.uDir=null;this.uIntensity=null;this.quadVao=null;this.quadVbo=null;this.fboA=null;this.texA=null;this.fboB=null;this.texB=null;this.fboW=0;this.fboH=0;this.glowBatch=new Kn;this.sliceTex=new Map;this.onLost=e=>{e.preventDefault(),this.contextLost=true;};this.onRestored=()=>{this.contextLost=false,this.initGL()?this.onNeedsRedraw?.():this.onContextFailed?.();};}get ok(){return this.gl!==null}mount(e){if(this.canvas=e,this.gl=e.getContext("webgl2",{alpha:true,antialias:true,depth:false,stencil:false,premultipliedAlpha:true}),!!this.gl){if(!this.initGL()){this.gl=null;return}e.addEventListener("webglcontextlost",this.onLost,false),e.addEventListener("webglcontextrestored",this.onRestored,false);}}initGL(){let e=this.gl;if(!e)return false;this.screenProgram=null,this.quadVao=null,this.quadVbo=null,this.fboA=this.fboB=null,this.texA=this.texB=null,this.fboW=this.fboH=0,this.sliceTex.clear();let t=Ki(e,e.VERTEX_SHADER,Pm),n=Ki(e,e.FRAGMENT_SHADER,Em),r=e.createProgram();if(!t||!n||!r)return t&&e.deleteShader(t),n&&e.deleteShader(n),r&&e.deleteProgram(r),false;if(e.attachShader(r,t),e.attachShader(r,n),e.linkProgram(r),!e.getProgramParameter(r,e.LINK_STATUS))return e.deleteProgram(r),e.deleteShader(t),e.deleteShader(n),false;e.deleteShader(t),e.deleteShader(n),this.program=r,this.uRes=e.getUniformLocation(r,"uRes"),this.vbo=e.createBuffer(),this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.vbo);let i=32;return e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,false,i,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,4,e.FLOAT,false,i,8),e.enableVertexAttribArray(2),e.vertexAttribPointer(2,2,e.FLOAT,false,i,24),e.bindVertexArray(null),this.glow>0&&!this.ensureScreenPipeline()&&(this.glow=0),true}ensureScreenPipeline(){if(this.screenProgram&&this.quadVao)return true;let e=this.gl;if(!e)return false;let t=Ki(e,e.VERTEX_SHADER,km),n=Ki(e,e.FRAGMENT_SHADER,Im),r=e.createProgram();return !t||!n||!r?(t&&e.deleteShader(t),n&&e.deleteShader(n),r&&e.deleteProgram(r),false):(e.attachShader(r,t),e.attachShader(r,n),e.linkProgram(r),e.getProgramParameter(r,e.LINK_STATUS)?(e.deleteShader(t),e.deleteShader(n),this.screenProgram=r,this.uTex=e.getUniformLocation(r,"uTex"),this.uDir=e.getUniformLocation(r,"uDir"),this.uIntensity=e.getUniformLocation(r,"uIntensity"),this.quadVbo=e.createBuffer(),this.quadVao=e.createVertexArray(),e.bindVertexArray(this.quadVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadVbo),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,false,0,0),e.bindVertexArray(null),true):(e.deleteProgram(r),false))}ensureFbos(e,t,n){if(this.fboA&&this.fboW===t&&this.fboH===n)return true;this.deleteFbos(e);let r=()=>{let a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,n,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);let l=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,l),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,a,0),{tex:a,fbo:l}},i=r(),o=r();return e.bindFramebuffer(e.FRAMEBUFFER,null),this.texA=i.tex,this.fboA=i.fbo,this.texB=o.tex,this.fboB=o.fbo,this.fboW=t,this.fboH=n,!!(this.fboA&&this.fboB)}deleteFbos(e){this.fboA&&e.deleteFramebuffer(this.fboA),this.fboB&&e.deleteFramebuffer(this.fboB),this.texA&&e.deleteTexture(this.texA),this.texB&&e.deleteTexture(this.texB),this.fboA=this.fboB=null,this.texA=this.texB=null,this.fboW=this.fboH=0;}render(e,t,n){let r=this.gl,i=this.canvas;if(!r||!i||!this.program||this.contextLost||r.isContextLost())return;let o=t.dpr,a=t.width;r.viewport(0,0,i.width,i.height),r.disable(r.SCISSOR_TEST),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT);let l=t.barCount;if(l===0)return;let c=t.visibleLogicalRange(),d=Math.max(0,Math.floor(c.from)),h=Math.min(l-1,Math.ceil(c.to));if(h<d)return;r.enable(r.BLEND),r.enable(r.SCISSOR_TEST);let u=Am(e.indicators),p=e.orderedPanes(),m=new Set;for(let f of p){let b=this.batch;b.reset();let g=Math.round(f.bounds.top*o),v=Math.round((f.bounds.top+f.bounds.height)*o);r.scissor(0,i.height-v,Math.round(a*o),v-g);let y=()=>{b.vertexCount!==0&&(r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA),r.useProgram(this.program),r.bindVertexArray(this.vao),r.uniform2f(this.uRes,i.width/o,i.height/o),r.bindBuffer(r.ARRAY_BUFFER,this.vbo),r.bufferData(r.ARRAY_BUFFER,b.view,r.DYNAMIC_DRAW),r.drawArrays(r.TRIANGLES,0,b.vertexCount),b.reset());},x=f.collapsed?[]:e.drawingSlices.get(f.id)??[],S=0,C=T=>{for(;S<x.length&&x[S].beforeZ<=T;S+=1)y(),this.drawSliceTexture(r,x[S].canvas)&&m.add(x[S].canvas);};if(b.alpha=1,f.collapsed)this.emitGrid(b,t,n,a,f,e);else {this.emitHighlights(b,e,f,t),this.emitGrid(b,t,n,a,f,e);let T=e.orderedIndicatorsForPane(f.id),M=f.kind==="price",E=P=>{let V=e.scaleFor(P,f);return V===f.scale?f:{...f,scale:V}};b.alpha=this.modelAlpha;for(let P of T)for(let V of P.backgrounds)this.emitBackground(b,V,f,t);for(let P of T)for(let V of P.fills)this.emitFill(b,P,V,E(P),t,d,h,e.offsetOf(P.id));let k=M&&!e.candlesHidden,L=false;for(let P of T){k&&!L&&e.zOf(P.id)>=e.candleZ&&(C(e.candleZ),b.alpha=this.candleStructureAlpha,this.emitPriceSeries(b,e,d,h,t,f,n,u,a),L=true),C(e.zOf(P.id)),b.alpha=this.modelAlpha;let V=e.offsetOf(P.id),G=E(P);for(let w of P.series)this.emitSeries(b,w,G,t,d,h,n,V);}k&&!L&&(C(e.candleZ),b.alpha=this.candleStructureAlpha,this.emitPriceSeries(b,e,d,h,t,f,n,u,a)),C(1/0),b.alpha=this.modelAlpha;for(let P of T){let V=E(P);for(let G of P.priceLines)this.emitHline(b,G,V,t,a,n);}b.alpha=1;}y();}r.disable(r.SCISSOR_TEST);for(let[f,b]of this.sliceTex)m.has(f)||(r.deleteTexture(b),this.sliceTex.delete(f));this.glow>0&&!this.screenProgram&&!this.ensureScreenPipeline()&&(this.glow=0),this.glow>0&&this.screenProgram&&(this.glowBatch.alpha=this.modelAlpha,this.renderGlow(r,e,t,d,h));}renderGlow(e,t,n,r,i){let o=this.canvas,a=Math.max(1,o.width>>1),l=Math.max(1,o.height>>1);if(!this.ensureFbos(e,a,l))return;let c=n.dpr,d=n.width;e.bindFramebuffer(e.FRAMEBUFFER,this.fboA),e.viewport(0,0,a,l),e.disable(e.SCISSOR_TEST),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.useProgram(this.program),e.bindVertexArray(this.vao),e.uniform2f(this.uRes,o.width/c,o.height/c),e.enable(e.SCISSOR_TEST);for(let h of t.orderedPanes()){let u=this.glowBatch;if(u.reset(),this.emitGlowSources(u,t.indicatorsForPane(h.id),h,n,r,i,f=>t.offsetOf(f)),u.vertexCount===0)continue;let p=Math.round(h.bounds.top*c*.5),m=Math.round((h.bounds.top+h.bounds.height)*c*.5);e.scissor(0,l-m,Math.round(d*c*.5),m-p),e.bindBuffer(e.ARRAY_BUFFER,this.vbo),e.bufferData(e.ARRAY_BUFFER,u.view,e.DYNAMIC_DRAW),e.drawArrays(e.TRIANGLES,0,u.vertexCount);}e.disable(e.SCISSOR_TEST),e.useProgram(this.screenProgram),e.bindVertexArray(this.quadVao),e.uniform1i(this.uTex,0),e.uniform1f(this.uIntensity,1),e.activeTexture(e.TEXTURE0),e.disable(e.BLEND),e.bindFramebuffer(e.FRAMEBUFFER,this.fboB),e.bindTexture(e.TEXTURE_2D,this.texA),e.uniform2f(this.uDir,1/a,0),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindFramebuffer(e.FRAMEBUFFER,this.fboA),e.bindTexture(e.TEXTURE_2D,this.texB),e.uniform2f(this.uDir,0,1/l),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,o.width,o.height),e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE),e.bindTexture(e.TEXTURE_2D,this.texA),e.uniform2f(this.uDir,0,0),e.uniform1f(this.uIntensity,this.glow),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);}drawSliceTexture(e,t){if(!this.ensureScreenPipeline()||!this.screenProgram)return false;let n=this.sliceTex.get(t)??null;if(!n){if(n=e.createTexture(),!n)return false;this.sliceTex.set(t,n),e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);}return e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,true),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,false),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false),e.useProgram(this.screenProgram),e.bindVertexArray(this.quadVao),e.uniform1i(this.uTex,0),e.uniform2f(this.uDir,0,0),e.uniform1f(this.uIntensity,1),e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindVertexArray(null),true}emitGlowSources(e,t,n,r,i,o,a=()=>0){for(let l of t){let c=a(l.id);for(let d of l.series)!le(d)||d.visible===false||d.kind==="histogram"||d.kind==="columns"||(d.kind==="circles"||d.kind==="cross"?this.emitPointMarkers(e,d,n,r,i,o,c):this.emitPolyline(e,d,n,r,i,o,d.kind==="step",c));}}destroy(){let e=this.gl;if(this.canvas&&(this.canvas.removeEventListener("webglcontextlost",this.onLost),this.canvas.removeEventListener("webglcontextrestored",this.onRestored)),e){this.program&&e.deleteProgram(this.program),this.vbo&&e.deleteBuffer(this.vbo),this.vao&&e.deleteVertexArray(this.vao),this.screenProgram&&e.deleteProgram(this.screenProgram),this.quadVbo&&e.deleteBuffer(this.quadVbo),this.quadVao&&e.deleteVertexArray(this.quadVao);for(let t of this.sliceTex.values())e.deleteTexture(t);this.sliceTex.clear(),this.deleteFbos(e),e.getExtension("WEBGL_lose_context")?.loseContext();}this.gl=null,this.canvas=null,this.program=null,this.vao=null,this.vbo=null,this.screenProgram=null;}emitGrid(e,t,n,r,i,o){let a=i.bounds.top,l=i.bounds.top+i.bounds.height,{gridVert:c,gridHorz:d}=o.style,h=t.dpr;if(e.alpha=this.gridAlpha,o.showGrid&&c.visible&&!i.collapsed){let u=U(c.color??n.gridColor),p=t.visibleTimeRange(),m=Rt((p.from+p.to)/2,o.timezone);for(let f of Jt(p.from,p.to,8,m)){let b=t.timeToX(f.time);if(b<0||b>r)continue;let g=ec(b,h);e.rect(g.pos,a,g.size,l-a,u);}}if(o.showGrid&&d.visible&&!i.collapsed){let u=U(d.color??n.gridColor),p=Ee(o,i);for(let m of kt(i.scale,i.bounds.height,p)){let f=t.priceToY(m.price,i.scale,i.bounds);if(f<a||f>l)continue;let b=ec(f,h);e.rect(0,b.pos,r,b.size,u);}}}emitHighlights(e,t,n,r){if(t.highlights.length!==0)for(let i of t.highlights){let o=r.timeToX(i.from),a=r.timeToX(i.to);if(a<0||o>r.width||a<=o)continue;let l=Math.max(0,o),c=Math.min(r.width,a)-l;c<=0||e.rect(l,n.bounds.top,c,n.bounds.height,U(i.color));}}emitBackground(e,t,n,r){let i=r.timeToX(t.from),o=r.timeToX(t.to);o<0||i>r.width||o<=i||e.rect(i,n.bounds.top,o-i,n.bounds.height,U(t.color));}emitFill(e,t,n,r,i,o,a,l=0){let c=rc(t,n.fromSeriesId),d=rc(t,n.toSeriesId);if(!(!c||!d))for(let h=Math.max(1,o);h<=a;h+=1){let u=c[h-1-l],p=d[h-1-l],m=c[h-l],f=d[h-l];if(!u||!p||!m||!f||u.value===null||p.value===null||m.value===null||f.value===null)continue;let b=i.logicalToX(h-1),g=i.logicalToX(h),v=i.priceToY(u.value,r.scale,r.bounds),y=i.priceToY(p.value,r.scale,r.bounds),x=i.priceToY(m.value,r.scale,r.bounds),S=i.priceToY(f.value,r.scale,r.bounds),C=n.gradient?.[h-1-l];if(C){let T=i.priceToY(C.topValue,r.scale,r.bounds),M=i.priceToY(C.bottomValue,r.scale,r.bounds),E=M===T?T+1:M,k=U(C.topColor),L=U(C.bottomColor),P=E-T,V=G=>ms(k,L,ji((G-T)/P));e.quad4(b,v,V(v),g,x,V(x),g,S,V(S),b,y,V(y));}else {let T=n.colors?n.colors[h-1-l]:n.color;if(!T)continue;e.quad(b,v,g,x,g,S,b,y,U(T));}}}emitPriceSeries(e,t,n,r,i,o,a,l,c){if(t.basePainting==="none")return;let d=t.bars,h=t.style;switch(t.priceStyle){case "bars":this.emitBars(e,d,n,r,i,o,h.bars.upColor??a.upColor,h.bars.downColor??a.downColor,l);return;case "line":this.emitPriceLine(e,d,n,r,i,o,U(h.line.color??a.upColor),h.line.width);return;case "area":{let u=h.area.lineColor??a.upColor;this.emitPriceArea(e,d,n,r,i,o,U(h.area.topColor??u),U(h.area.bottomColor??"rgba(0,0,0,0)")),this.emitPriceLine(e,d,n,r,i,o,U(u),h.area.width);return}case "baseline":this.emitBaseline(e,d,n,r,i,o,t,a,c);return;default:this.emitCandles(e,t,d,n,r,i,o,a,l);}}emitBars(e,t,n,r,i,o,a,l,c){let d=i.bodySpacing(),h=rn(d);if(h==="aggregate"){this.emitCandlesAggregated(e,t,n,r,i,o,a,l,c);return}let u=Math.max(1,Math.round(d*.35)),p=h==="full";for(let m=n;m<=r;m+=1){let f=t[m];if(!f||f.high<=f.low)continue;let b=U(c.get(f.time)??(f.close>=f.open?a:l)),g=Math.round(i.logicalToX(m)),v=i.priceToY(f.high,o.scale,o.bounds),y=i.priceToY(f.low,o.scale,o.bounds);if(e.rect(g-.5,v,1,y-v,b),p){let x=i.priceToY(f.open,o.scale,o.bounds),S=i.priceToY(f.close,o.scale,o.bounds);e.rect(g-u,x-.5,u,1,b),e.rect(g,S-.5,u,1,b);}}}emitPriceLine(e,t,n,r,i,o,a,l){let c=Math.max(1,l)/2,d=tc(c),h=false,u=0,p=0;for(let m=Math.max(0,n-1);m<=r;m+=1){let f=t[m];if(!f){h=false;continue}let b=i.logicalToX(m),g=i.priceToY(f.close,o.scale,o.bounds);h&&e.seg(u,p,b,g,l,a),e.circle(b,g,c,a,d),u=b,p=g,h=true;}}emitPriceArea(e,t,n,r,i,o,a,l){let c=o.bounds.top+o.bounds.height,d=[],h=1/0,u=()=>{if(d.length>=2){let p=c-h,m=f=>ms(a,l,p<1e-6?0:ji((f-h)/p));for(let f=1;f<d.length;f+=1){let b=d[f-1],g=d[f];e.quad4(b.x,b.y,m(b.y),g.x,g.y,m(g.y),g.x,c,l,b.x,c,l);}}d.length=0,h=1/0;};for(let p=Math.max(0,n-1);p<=r;p+=1){let m=t[p];if(!m){u();continue}let f=i.logicalToX(p),b=i.priceToY(m.close,o.scale,o.bounds);d.push({x:f,y:b}),b<h&&(h=b);}u();}emitBaseline(e,t,n,r,i,o,a,l,c){let d=a.baselinePriceFor(o.scale),h=i.priceToY(d,o.scale,o.bounds),u=a.style.baseline,p=u.topLineColor??Qt,m=u.bottomLineColor??en,f=U(p),b=U(m),g=U(u.topFillColor??W(p,Ye)),v=U(u.topFillColor2??W(p,Xe)),y=U(u.bottomFillColor??W(m,Ye)),x=U(u.bottomFillColor2??W(m,Xe)),S=[];for(let k=Math.max(0,n-1);k<=r;k+=1){let L=t[k];L&&S.push({x:i.logicalToX(k),y:i.priceToY(L.close,o.scale,o.bounds)});}if(S.length<2)return;let C=o.bounds.top,T=o.bounds.top+o.bounds.height,M=k=>k<=h?v:x,E=k=>{let L=k<=h,P=L?h-C:T-h,V=P>0?ji(Math.abs(k-h)/P):0;return ms(L?v:x,L?g:y,V)};for(let k=1;k<S.length;k+=1){let L=S[k-1],P=S[k];if(L.y<=h!=P.y<=h&&P.y!==L.y){let V=(h-L.y)/(P.y-L.y),G=L.x+(P.x-L.x)*V;e.tri(L.x,L.y,E(L.y),G,h,M(L.y),L.x,h,M(L.y)),e.tri(G,h,M(P.y),P.x,P.y,E(P.y),P.x,h,M(P.y));}else e.quad4(L.x,L.y,E(L.y),P.x,P.y,E(P.y),P.x,h,M(P.y),L.x,h,M(L.y));}e.dashedSeg(0,h,c,h,1,U(a.style.borderColor??l.borderColor),ps.dashed??null);for(let k=1;k<S.length;k+=1){let L=S[k-1],P=S[k],V=L.y<=h,G=P.y<=h;if(V!==G&&P.y!==L.y){let w=(h-L.y)/(P.y-L.y),H=L.x+(P.x-L.x)*w;e.seg(L.x,L.y,H,h,u.width,V?f:b),e.seg(H,h,P.x,P.y,u.width,G?f:b);}else e.seg(L.x,L.y,P.x,P.y,u.width,V?f:b);}}emitCandles(e,t,n,r,i,o,a,l,c){let d=o.bodySpacing(),h=rn(d),u=Wi(t.style.candle,t.candleOverride,l.upColor,l.downColor);if(h==="aggregate"){this.emitCandlesAggregated(e,n,r,i,o,a,u.up,u.down,c);return}let p=h==="full",m=u.up,f=u.down,b=u.candle,g=this.candleStructureAlpha>this.candleBodyAlpha+.001;for(let v=r;v<=i;v+=1){let y=n[v];if(!y||y.high<=y.low)continue;let x=Xi(o.logicalToX(v),d,o.dpr,this.candleBodyScale),S=y.close>=y.open,C=S?m:f,T=c.get(y.time),M=T??C,E=U(M),k=0,L=0;if(p){let P=o.priceToY(y.open,a.scale,a.bounds),V=o.priceToY(y.close,a.scale,a.bounds);k=Math.min(P,V),L=Math.max(1,Math.abs(V-P));}if(b.wickVisible){let P=o.priceToY(y.high,a.scale,a.bounds),V=o.priceToY(y.low,a.scale,a.bounds);e.alpha=this.candleStructureAlpha;let G=U((S?b.wickUpColor:b.wickDownColor)??(p?C:M));p?(e.rect(x.wickX,P,x.wickW,Math.max(0,k-P),G),e.rect(x.wickX,k+L,x.wickW,Math.max(0,V-(k+L)),G)):e.rect(x.wickX,P,x.wickW,V-P,G);}if(p&&(b.bodyVisible&&(e.alpha=this.candleBodyAlpha,e.rect(x.bodyX,k,x.bodyW,L,E)),b.borderVisible||T||g&&b.bodyVisible)){e.alpha=this.candleStructureAlpha;let P=b.borderVisible||T?U((S?b.borderUpColor:b.borderDownColor)??C):E,V=Math.max(0,x.bodyW-1),G=Math.max(0,L-1);e.rectStroke(x.bodyX+.5,k+.5,V,G,1,P);}}}emitCandlesAggregated(e,t,n,r,i,o,a,l,c){let d=NaN,h=1/0,u=-1/0,p=0,m=0,f=0,b=false,g=()=>{if(!b)return;let v=U(c.get(f)??(m>=p?a:l)),y=i.priceToY(u,o.scale,o.bounds),x=i.priceToY(h,o.scale,o.bounds);e.rect(d-.5,y,1,x-y,v);};for(let v=n;v<=r;v+=1){let y=t[v];if(!y||y.high<=y.low)continue;let x=Math.round(i.logicalToX(v));!b||x!==d?(g(),d=x,h=y.low,u=y.high,p=y.open,f=y.time,b=true):(y.low<h&&(h=y.low),y.high>u&&(u=y.high)),m=y.close;}g();}emitSeries(e,t,n,r,i,o,a,l=0){if(t.kind==="candle"||t.kind==="bar"){this.emitPlotCandles(e,t,n,r,i,o,a,l);return}if(!(!le(t)||t.visible===false))switch(t.kind){case "histogram":case "columns":this.emitHistogram(e,t,n,r,i,o,l);break;case "area":this.emitArea(e,t,n,r,i,o,l),this.emitPolyline(e,t,n,r,i,o,false,l);break;case "circles":case "cross":this.emitPointMarkers(e,t,n,r,i,o,l);break;case "step":this.emitPolyline(e,t,n,r,i,o,true,l);break;default:this.emitPolyline(e,t,n,r,i,o,false,l);}}emitPolyline(e,t,n,r,i,o,a,l=0){let c=Math.max(1,t.style.width),d=c/2,h=ps[t.style.lineStyle]??null,u=!h&&!a,p=tc(d),m=false;for(let f=Math.max(1,i-1);f<=o;f+=1){let b=t.points[f-l],g=t.points[f-1-l];if(!b||b.value===null||!g||g.value===null){m=false;continue}let v=r.logicalToX(f),y=r.priceToY(b.value,n.scale,n.bounds),x=r.logicalToX(f-1),S=r.priceToY(g.value,n.scale,n.bounds),C=U(b.color??t.style.color);a?(e.dashedSeg(x,S,v,S,c,C,h),e.dashedSeg(v,S,v,y,c,C,h)):e.dashedSeg(x,S,v,y,c,C,h),u&&(m||e.circle(x,S,d,U(g.color??t.style.color),p),e.circle(v,y,d,C,p)),m=true;}}emitArea(e,t,n,r,i,o,a=0){let l=n.bounds.top+n.bounds.height,c=U(t.style.color),d=[],h=1/0,u=()=>{if(d.length<1){d=[],h=1/0;return}let p=l-h,m=f=>Rm(c,p<1e-6?0:ji((f-h)/p));for(let f=1;f<d.length;f+=1){let b=d[f-1],g=d[f];e.quad4(b.x,b.y,m(b.y),g.x,g.y,m(g.y),g.x,l,nc,b.x,l,nc);}d=[],h=1/0;};for(let p=i;p<=o;p+=1){let m=t.points[p-a];if(!m||m.value===null){u();continue}let f=r.logicalToX(p),b=r.priceToY(m.value,n.scale,n.bounds);d.push({x:f,y:b}),b<h&&(h=b);}u();}emitHistogram(e,t,n,r,i,o,a=0){let l=r.bodySpacing(),c=Math.max(1,(t.kind==="columns"?.7:.8)*l),d=c/2,h=t.style.base??0,u=r.priceToY(h,n.scale,n.bounds);for(let p=i;p<=o;p+=1){let m=t.points[p-a];if(!m||m.value===null)continue;let f=r.logicalToX(p),b=r.priceToY(m.value,n.scale,n.bounds);e.rect(f-d,Math.min(u,b),c,Math.max(1,Math.abs(b-u)),U(m.color??t.style.color));}}emitPointMarkers(e,t,n,r,i,o,a=0){let l=Math.max(1.5,t.style.width);for(let c=i;c<=o;c+=1){let d=t.points[c-a];if(!d||d.value===null)continue;let h=r.logicalToX(c),u=r.priceToY(d.value,n.scale,n.bounds),p=U(d.color??t.style.color);t.kind==="cross"?(e.seg(h-l,u,h+l,u,1,p),e.seg(h,u-l,h,u+l,1,p)):e.circle(h,u,l,p,Math.max(16,Math.ceil(l*2)));}}emitPlotCandles(e,t,n,r,i,o,a,l=0){let c=r.bodySpacing(),d=t.style?.up??a.upColor,h=t.style?.down??a.downColor,u=t.kind==="bar",p=Math.max(.5,Math.floor(c*.7)/2),m=Math.max(1,Math.round(c*.35));for(let f=i;f<=o;f+=1){let b=t.bars[f-l];if(!b)continue;let g=t.barColors?.[f-l],v=U(g?.color??(b.close>=b.open?d:h)),y=Math.round(r.logicalToX(f)),x=r.priceToY(b.high,n.scale,n.bounds),S=r.priceToY(b.low,n.scale,n.bounds),C=r.priceToY(b.open,n.scale,n.bounds),T=r.priceToY(b.close,n.scale,n.bounds);if(u){e.rect(y-.5,x,1,S-x,v),e.rect(y-m,C-.5,m,1,v),e.rect(y,T-.5,m,1,v);continue}let M=Math.max(1,Math.round(Xn(c)*r.dpr)),E=(Math.round(y*r.dpr)-(M>>1))/r.dpr;e.rect(E,x,M/r.dpr,S-x,U(g?.wickColor??g?.color??(b.close>=b.open?d:h)));let k=Math.min(C,T),L=Math.max(1,Math.abs(T-C));if(e.rect(y-p,k,p*2,L,v),g?.borderColor){let P=U(g.borderColor);e.rect(y-p,k,p*2,1,P),e.rect(y-p,k+L-1,p*2,1,P),e.rect(y-p,k,1,L,P),e.rect(y+p-1,k,1,L,P);}}}emitHline(e,t,n,r,i,o){let a=Math.round(r.priceToY(t.price,n.scale,n.bounds));a<n.bounds.top||a>n.bounds.top+n.bounds.height||e.dashedSeg(0,a,i,a,t.width??1,U(t.color??o.textColor),ps[t.lineStyle??"solid"]??null);}};function Ki(s,e,t){let n=s.createShader(e);return n?(s.shaderSource(n,t),s.compileShader(n),s.getShaderParameter(n,s.COMPILE_STATUS)?n:(s.deleteShader(n),null)):null}var nc=[0,0,0,0];function ji(s){return s<0?0:s>1?1:s}function ms(s,e,t){return [s[0]+(e[0]-s[0])*t,s[1]+(e[1]-s[1])*t,s[2]+(e[2]-s[2])*t,s[3]+(e[3]-s[3])*t]}function Rm(s,e){let t=1-e;return [s[0]*t,s[1]*t,s[2]*t,s[3]*t]}function rc(s,e){let t=s.series.find(n=>n.id===e);return t&&le(t)?t.points:null}var Dm=new Map;function Am(s){let e=false;for(let n of s.values())if(n.barColors&&n.barColors.length>0){e=true;break}if(!e)return Dm;let t=new Map;for(let n of s.values())if(n.barColors)for(let r of n.barColors)t.set(r.time,r.color);return t}function Zi(){return {barSpacing:8,rightOffset:6}}function Ke(s){return Math.max(.5,Math.min(1e3,s))}function fs(s){if(s.length<2)return 0;let e=[];for(let t=1;t<s.length;t+=1){let n=s[t]-s[t-1];n>0&&e.push(n);}return e.length===0?0:(e.sort((t,n)=>t-n),e[Math.floor(e.length/2)])}function ic(s,e,t){let n=e.length;if(n===0)return 0;let r=e[0],i=e[n-1];if(s<=r)return t>0?(s-r)/t:0;if(s>=i)return n-1+(t>0?(s-i)/t:0);let o=0,a=n-1;for(;a-o>1;){let c=o+a>>1;e[c]<=s?o=c:a=c;}let l=e[a]-e[o];return l>0?o+(s-e[o])/l:o}function oc(s,e,t){let n=e.length;if(n===0)return 0;if(s<=0)return e[0]+(t>0?s*t:0);if(s>=n-1)return e[n-1]+(t>0?(s-(n-1))*t:0);let r=Math.floor(s),i=s-r;return e[r]+(e[r+1]-e[r])*i}var Ji=class{constructor(){this.widthPx=0;this.dataHeightPx=0;this.devicePixelRatio=1;this.viewport=Zi();this.pitchScale=1;this.times=[];this.intervalMs=0;}setSize(e,t,n){this.widthPx=e,this.dataHeightPx=t,this.devicePixelRatio=n>0?n:1;}setBars(e){this.times=e.slice(),this.intervalMs=fs(this.times);}appendBar(e){this.times.push(e),this.intervalMs<=0&&this.times.length>=2&&(this.intervalMs=fs(this.times));}setViewport(e){this.viewport=e;}getViewport(){return this.viewport}setPitchScale(e){this.pitchScale=Number.isFinite(e)&&e>0?e:1;}get spacingScale(){return this.pitchScale}pxPerBar(){return this.viewport.barSpacing*this.pitchScale}bodySpacing(){return this.viewport.barSpacing*Math.min(1,this.pitchScale)}get width(){return this.widthPx}get height(){return this.dataHeightPx}get dpr(){return this.devicePixelRatio}get barCount(){return this.times.length}get barInterval(){return this.intervalMs}get rightEdgeLogical(){return this.barCount-1+this.viewport.rightOffset}logicalToX(e){return this.widthPx-(this.rightEdgeLogical-e)*this.pxPerBar()}xToLogical(e){return this.rightEdgeLogical-(this.widthPx-e)/this.pxPerBar()}timeToLogical(e){return ic(e,this.times,this.intervalMs)}logicalToTime(e){return oc(e,this.times,this.intervalMs)}timeToX(e){return this.logicalToX(this.timeToLogical(e))}priceToY(e,t,n){if(t.log&&t.min>0&&t.max>t.min&&e>0){let o=Math.log(t.min),a=(Math.log(e)-o)/(Math.log(t.max)-o);return n.top+n.height*(t.invert?a:1-a)}let r=t.max-t.min;if(r<=0)return n.top+n.height/2;let i=(e-t.min)/r;return n.top+n.height*(t.invert?i:1-i)}yToPrice(e,t,n){if(n.height<=0)return t.min;let r=(e-n.top)/n.height,i=t.invert?r:1-r;if(t.log&&t.min>0&&t.max>t.min){let o=Math.log(t.min);return Math.exp(o+i*(Math.log(t.max)-o))}return t.min+(t.max-t.min)*i}visibleLogicalRange(){return {from:this.xToLogical(0),to:this.xToLogical(this.widthPx)}}visibleTimeRange(){let e=this.visibleLogicalRange();return {from:this.logicalToTime(e.from),to:this.logicalToTime(e.to)}}toBitmap(e){return Math.round(e*this.devicePixelRatio)}};function bs(s){return s>=3}function sc(s){return s>=2}var Qi=class{constructor(e,t,n){this.onFrame=e;this.level=0;this.handle=null;this.raf=t??(r=>requestAnimationFrame(r)),this.cancel=n??(r=>cancelAnimationFrame(r));}invalidate(e){e<=0||(e>this.level&&(this.level=e),this.handle===null&&(this.handle=this.raf(()=>this.flush())));}flushNow(e){this.handle!==null&&(this.cancel(this.handle),this.handle=null),e>this.level&&(this.level=e),this.flush();}flush(){this.handle=null;let e=this.level;this.level=0,e!==0&&this.onFrame(e);}destroy(){this.handle!==null&&(this.cancel(this.handle),this.handle=null),this.level=0;}};var eo=class{constructor(e,t,n,r){this.tick=e;this.handle=null;this.last=0;this.stopped=false;this.loop=()=>{let e=this.now(),t=e-this.last;this.last=e;let n=this.tick(Math.min(t,64));this.handle=n&&!this.stopped?this.raf(this.loop):null;};this.raf=t??(i=>requestAnimationFrame(i)),this.cancel=n??(i=>cancelAnimationFrame(i)),this.now=r??(()=>performance.now());}get active(){return this.handle!==null}start(){this.stopped=false,this.handle===null&&(this.last=this.now(),this.handle=this.raf(this.loop));}stop(){this.stopped=true,this.handle!==null&&(this.cancel(this.handle),this.handle=null);}};function Se(s,e,t,n){return n<=0?e:s+(e-s)*(1-Math.exp(-t/n))}var Om=.04,Fm=60,Bm=2,Vm=350,ac=8,_m=14,Nm=350,Hm=30,zm=.004,$m=.0025;function Wm(s,e,t){return t?{logical:s.rightEdgeLogical,x:s.width}:{logical:s.xToLogical(e),x:e}}function Um(s,e){return Math.abs(s)>Math.abs(e)}function Gm(s,e,t){return s+e/t}function Ym(s,e,t){return Um(s,e)?s:t?e:null}function Xm(s,e){return s?"strong":e}function Km(s,e,t){return Ke(s*(t/Math.max(1,e)))}function jm(s,e,t,n,r){return s-(e-1)+(t-n)/r}var to=class{constructor(e){this.deps=e;this.rightEdgeZoom=true;this.axisDrag=true;this.paneResize=true;this.el=null;this.dragging=false;this.moved=false;this.region="data";this.verticalPan=false;this.startX=0;this.startY=0;this.startRightOffset=0;this.startBarSpacing=0;this.lastX=0;this.lastT=0;this.vx=0;this.middleDeleted=false;this.cursorX=NaN;this.cursorY=NaN;this.touches=new Map;this.lpTimer=null;this.pinchStartDist=1;this.pinchStartBarSpacing=0;this.pinchAnchorLogical=0;this.lastTapT=0;this.lastTapX=0;this.lastTapY=0;this.onTouchContextMenu=e=>{this.touches.size!==0&&(!(e.target instanceof Node)||!this.el?.contains(e.target)||(e.preventDefault(),e.stopImmediatePropagation()));};this.onMiddleGuard=e=>{e.button===1&&this.middleDeleted&&e.preventDefault();};this.onModifier=e=>{e.repeat||e.key!=="Shift"&&e.key!=="Control"&&e.key!=="Meta"||Number.isNaN(this.cursorX)||this.dragging&&this.region!=="drawing"||this.deps.drawingsPointerMove?.(this.cursorX,this.cursorY,this.snapMode(e),e.shiftKey);};this.onDown=e=>{if(e.button===1){let{x:i,y:o}=this.local(e);this.middleDeleted=this.deps.drawingsDeleteAt?.(i,o)??false,this.middleDeleted&&e.preventDefault();return}if(e.button!==0)return;let{x:t,y:n}=this.local(e);if(e.pointerType==="touch"){if(this.touches.size===1&&this.dragging&&(this.region==="data"||this.region==="crosshair")){this.touches.set(e.pointerId,{x:t,y:n}),this.beginPinch(e);return}if(this.touches.size>=1)return;this.touches.set(e.pointerId,{x:t,y:n});}if(this.deps.drawingsClearTransient?.(),this.dragging=true,this.moved=false,this.startX=t,this.startY=n,this.deps.drawingsClaim?.(t,n)){this.region="drawing",this.deps.drawingsPointerDown?.(t,n,this.snapMode(e),e.shiftKey),this.capture(e.pointerId);return}if(e.shiftKey&&this.regionAt(t,n)==="data"&&this.deps.drawingsMeasureStart?.(t,n)){this.region="drawing",this.capture(e.pointerId);return}let r=this.deps.getCoords().getViewport();this.deps.apply(r),this.startRightOffset=r.rightOffset,this.startBarSpacing=r.barSpacing,this.region=this.regionAt(t,n),this.verticalPan=false,this.region==="price"?this.deps.beginPriceScale(t,n):this.region==="separator"?this.deps.beginPaneResize(n):this.region==="data"&&(this.verticalPan=this.deps.beginPricePan(n)),e.pointerType==="touch"&&(this.region==="data"||this.region==="price"||this.region==="time")&&this.startLongPress(t,n,this.region),this.lastX=t,this.lastT=e.timeStamp,this.vx=0,this.capture(e.pointerId);};this.onMove=e=>{let{x:t,y:n}=this.local(e);if(this.cursorX=t,this.cursorY=n,e.pointerType==="touch"&&this.touches.has(e.pointerId)&&this.touches.set(e.pointerId,{x:t,y:n}),this.dragging&&this.region==="pinch"){this.applyPinch();return}if(this.dragging&&this.region==="crosshair"){this.deps.onPointerMove(t,n);return}if(this.dragging&&this.region==="axis-sheet")return;this.lpTimer!==null&&Math.hypot(t-this.startX,n-this.startY)>ac&&this.cancelLongPress();let r=e.pointerType==="touch"?ac:Bm;if(this.dragging)if(this.region==="price")Math.abs(n-this.startY)>r&&(this.moved=true),this.deps.priceScaleBy(n-this.startY);else if(this.region==="separator")Math.abs(n-this.startY)>r&&(this.moved=true),this.deps.paneResizeBy(n-this.startY);else if(this.region==="time"){Math.abs(t-this.startX)>r&&(this.moved=true);let i=Ke(this.startBarSpacing*Math.exp((this.startX-t)*zm));this.deps.apply({barSpacing:i,rightOffset:this.startRightOffset});}else if(this.region==="drawing")(Math.abs(t-this.startX)>r||Math.abs(n-this.startY)>r)&&(this.moved=true),this.deps.drawingsPointerMove?.(t,n,this.snapMode(e),e.shiftKey);else {let i=this.deps.getCoords(),o=i.getViewport(),a=t-this.startX;Math.abs(a)>r&&(this.moved=true),this.deps.apply({barSpacing:o.barSpacing,rightOffset:this.startRightOffset-a/i.pxPerBar()}),this.verticalPan&&(Math.abs(n-this.startY)>r&&(this.moved=true),this.deps.pricePanBy(n-this.startY));let l=e.timeStamp-this.lastT;if(l>0){let c=(t-this.lastX)/l;this.vx=this.vx*.6+c*.4,this.lastX=t,this.lastT=e.timeStamp;}}else if(this.el){let i=this.deps.drawingsCursor?.(t,n),o=this.regionAt(t,n);this.el.style.cursor=i??(o==="price"?"ns-resize":o==="time"?"ew-resize":o==="separator"?"row-resize":""),this.deps.drawingsPointerMove?.(t,n,this.snapMode(e),e.shiftKey);}e.pointerType!=="touch"&&this.deps.onPointerMove(t,n);};this.onUp=e=>{if(e.pointerType==="touch"&&this.touches.delete(e.pointerId),this.cancelLongPress(),this.dragging&&this.region==="pinch"){if(this.touches.size===1){let a=[...this.touches.values()][0],l=this.deps.getCoords().getViewport();this.region="data",this.verticalPan=false,this.startX=a.x,this.startY=a.y,this.startRightOffset=l.rightOffset,this.startBarSpacing=l.barSpacing,this.lastX=a.x,this.lastT=e.timeStamp,this.vx=0;return}this.endGesture(e);return}if(this.dragging&&this.region==="crosshair"){this.deps.onPointerMove(null,null),this.endGesture(e);return}if(this.dragging&&this.region==="axis-sheet"){this.endGesture(e);return}let{x:t,y:n}=this.local(e),r=e.pointerType==="touch",i=this.dragging&&!this.moved&&(!r||Math.hypot(t-this.startX,n-this.startY)<=_m);if(this.dragging&&this.region==="drawing")this.deps.drawingsPointerUp?.(t,n);else if(i&&this.region==="data")this.deps.onClick(t,n);else if(this.dragging&&this.region==="data"&&!(e.timeStamp-this.lastT>Fm)&&Math.abs(this.vx)>Om){let l=this.deps.getCoords().pxPerBar();this.deps.fling(-this.vx/l);}let o=r&&i;this.endGesture(e),r&&this.deps.onPointerMove(null,null),o&&this.registerTap(e.timeStamp,t,n);};this.onCancel=e=>{e.pointerType==="touch"&&this.touches.delete(e.pointerId),this.cancelLongPress(),this.dragging&&(this.region==="drawing"&&!Number.isNaN(this.cursorX)&&this.deps.drawingsPointerUp?.(this.cursorX,this.cursorY),(this.region==="crosshair"||e.pointerType==="touch")&&this.deps.onPointerMove(null,null),this.endGesture(e));};this.onLeave=()=>{this.cursorX=NaN,this.cursorY=NaN,this.deps.onPointerMove(null,null);};this.onDblClick=e=>{let{x:t,y:n}=this.local(e);this.doubleActivate(t,n);};this.onWheel=e=>{e.preventDefault(),this.deps.drawingsClearTransient?.();let t=this.deps.getCoords(),n=t.getViewport(),r=Ym(e.deltaX,e.deltaY,e.shiftKey);if(r!=null){this.deps.apply({barSpacing:n.barSpacing,rightOffset:Gm(n.rightOffset,r,t.pxPerBar())});return}let i=this.local(e).x,o=this.rightEdgeZoom&&!(e.ctrlKey||e.metaKey),a=Wm(t,i,o),l=Ke(n.barSpacing*Math.exp(-e.deltaY*$m));this.deps.zoomTo(l,a.logical,a.x);};}attach(e){this.el=e,e.style!==void 0&&(e.style.touchAction="none",e.style.userSelect="none",e.style.setProperty("-webkit-user-select","none"),e.style.setProperty("-webkit-touch-callout","none")),e.addEventListener("pointerdown",this.onDown),e.addEventListener("pointermove",this.onMove),e.addEventListener("pointerup",this.onUp),e.addEventListener("pointerleave",this.onLeave),e.addEventListener("pointercancel",this.onCancel),e.addEventListener("dblclick",this.onDblClick),e.addEventListener("wheel",this.onWheel,{passive:false}),e.addEventListener("mousedown",this.onMiddleGuard),e.addEventListener("auxclick",this.onMiddleGuard);let t=e.ownerDocument?.defaultView;t?.addEventListener("keydown",this.onModifier),t?.addEventListener("keyup",this.onModifier),t?.addEventListener("contextmenu",this.onTouchContextMenu,true);}detach(){let e=this.el;if(!e)return;let t=e.ownerDocument?.defaultView;t?.removeEventListener("keydown",this.onModifier),t?.removeEventListener("keyup",this.onModifier),t?.removeEventListener("contextmenu",this.onTouchContextMenu,true),e.removeEventListener("pointerdown",this.onDown),e.removeEventListener("pointermove",this.onMove),e.removeEventListener("pointerup",this.onUp),e.removeEventListener("pointerleave",this.onLeave),e.removeEventListener("pointercancel",this.onCancel),e.removeEventListener("dblclick",this.onDblClick),e.removeEventListener("wheel",this.onWheel),e.removeEventListener("mousedown",this.onMiddleGuard),e.removeEventListener("auxclick",this.onMiddleGuard),this.cancelLongPress(),this.touches.clear(),this.el=null;}local(e){let t=this.el.getBoundingClientRect();return {x:e.clientX-t.left,y:e.clientY-t.top}}regionAt(e,t){let n=this.deps.getCoords();if(this.paneResize&&t<=n.height&&this.deps.paneSeparatorAt(t))return "separator";if(this.axisDrag){if(e>n.width&&t<=n.height)return "price";if(t>n.height&&e<=n.width)return "time"}return "data"}snapMode(e){return Xm(e.ctrlKey||e.metaKey,this.deps.drawingsSnapMode?.()??"off")}startLongPress(e,t,n){this.cancelLongPress(),this.lpTimer=setTimeout(()=>{if(this.lpTimer=null,!(!this.dragging||this.region!==n)){if(n==="data"){this.region="crosshair",this.deps.onPointerMove(e,t);return}this.region="axis-sheet",this.moved=true,this.deps.onAxisLongPress?.(n,e,t);}},Vm);}cancelLongPress(){this.lpTimer!==null&&clearTimeout(this.lpTimer),this.lpTimer=null;}beginPinch(e){this.cancelLongPress(),this.region==="crosshair"&&this.deps.onPointerMove(null,null);let t=this.deps.getCoords(),n=t.getViewport();this.deps.apply(n);let[r,i]=[...this.touches.values()];this.pinchStartDist=Math.max(1,Math.hypot(r.x-i.x,r.y-i.y)),this.pinchStartBarSpacing=n.barSpacing,this.pinchAnchorLogical=t.xToLogical((r.x+i.x)/2),this.region="pinch",this.dragging=true,this.moved=true,this.vx=0,this.capture(e.pointerId);}applyPinch(){let e=this.deps.getCoords(),t=[...this.touches.values()];if(t.length<2)return;let[n,r]=t,i=Km(this.pinchStartBarSpacing,this.pinchStartDist,Math.hypot(n.x-r.x,n.y-r.y)),o=e.getViewport(),a=o.barSpacing>0?e.pxPerBar()/o.barSpacing:1,l=(n.x+r.x)/2;this.deps.apply({barSpacing:i,rightOffset:jm(this.pinchAnchorLogical,e.barCount,e.width,l,i*a)});}capture(e){try{this.el?.setPointerCapture(e);}catch{}}registerTap(e,t,n){if(this.lastTapT>0&&e-this.lastTapT<=Nm&&Math.hypot(t-this.lastTapX,n-this.lastTapY)<=Hm){this.lastTapT=0,this.doubleActivate(this.lastTapX,this.lastTapY);return}this.lastTapT=e,this.lastTapX=t,this.lastTapY=n;}endGesture(e){this.dragging=false;try{this.el?.releasePointerCapture(e.pointerId);}catch{}}doubleActivate(e,t){if(this.deps.drawingsDblClick?.(e,t))return;let n=this.regionAt(e,t);n==="price"?this.deps.resetPriceScale(e,t):n==="separator"?this.deps.resetPaneSize(t):n==="time"?this.deps.resetView():this.deps.dataDblClick(e,t);}};function qm(s){if(s.ctrlKey||s.metaKey)return null;switch(s.key){case "ArrowLeft":return s.shiftKey?{kind:"pan",bars:-10}:{kind:"step",delta:-1};case "ArrowRight":return s.altKey&&s.shiftKey?{kind:"realtime"}:s.shiftKey?{kind:"pan",bars:10}:{kind:"step",delta:1};case "+":case "=":return {kind:"zoom",direction:1};case "-":case "_":return {kind:"zoom",direction:-1};case "Home":return {kind:"edge",edge:"first"};case "End":return {kind:"edge",edge:"last"};case "0":return {kind:"reset"};case "Escape":return {kind:"clear"};default:return null}}var no=class{constructor(e){this.deps=e;this.el=null;this.onKey=e=>{if(this.deps.preempt?.(e)){e.preventDefault();return}let t=qm(e);if(t)switch(e.preventDefault(),t.kind){case "pan":this.deps.panByBars(t.bars);break;case "zoom":this.deps.zoomByStep(t.direction);break;case "step":this.deps.stepCrosshair(t.delta);break;case "edge":this.deps.jumpToEdge(t.edge);break;case "reset":this.deps.resetView();break;case "realtime":this.deps.scrollToRealtime();break;case "clear":this.deps.clearCrosshair();break}};}attach(e){this.el=e,e.addEventListener("keydown",this.onKey);}detach(){this.el?.removeEventListener("keydown",this.onKey),this.el=null;}};var jn=class{constructor(){this.kind="canvas2d";this.modelAlpha=1;this.candleBodyAlpha=1;this.candleStructureAlpha=1;this.gridAlpha=1;this.candleBodyScale=1;this.canvas=null;this.ctx=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}render(e,t,n){let r=this.ctx,i=this.canvas;if(!r||!i)return;let o=t.dpr,a=i.width/o,l=i.height/o,c=t.width;r.setTransform(o,0,0,o,0,0),r.clearRect(0,0,a,l);let d=t.barCount;if(d===0)return;let h=t.visibleLogicalRange(),u=Math.max(0,Math.floor(h.from)),p=Math.min(d-1,Math.ceil(h.to));if(p<u)return;let m=Jm(e.indicators),f=e.orderedPanes();this.drawHighlights(r,e,t),this.drawGrid(r,e,t,n,c);for(let b of f){if(b.collapsed)continue;let g=e.orderedIndicatorsForPane(b.id),v=b.kind==="price";r.save(),r.beginPath(),r.rect(0,b.bounds.top,c,b.bounds.height),r.clip();let y=E=>{let k=e.scaleFor(E,b);return k===b.scale?b:{...b,scale:k}};r.globalAlpha=this.modelAlpha;for(let E of g)for(let k of E.backgrounds)this.drawBackground(r,k,b,t);for(let E of g)for(let k of E.fills)this.drawFill(r,E,k,y(E),t,u,p,e.offsetOf(E.id));let x=e.drawingSlices.get(b.id)??[],S=0,C=E=>{for(;S<x.length&&x[S].beforeZ<=E;S+=1)r.globalAlpha=1,r.drawImage(x[S].canvas,0,0,a,l);},T=v&&!e.candlesHidden,M=false;for(let E of g){T&&!M&&e.zOf(E.id)>=e.candleZ&&(C(e.candleZ),r.globalAlpha=this.candleStructureAlpha,this.drawPriceSeries(r,e,u,p,t,b,n,m,c),M=true),C(e.zOf(E.id)),r.globalAlpha=this.modelAlpha;let k=e.offsetOf(E.id),L=y(E);for(let P of E.series)this.drawSeries(r,P,L,t,u,p,n,k);}T&&!M&&(C(e.candleZ),r.globalAlpha=this.candleStructureAlpha,this.drawPriceSeries(r,e,u,p,t,b,n,m,c)),C(1/0),r.globalAlpha=this.modelAlpha;for(let E of g){let k=y(E);for(let L of E.priceLines)this.drawHline(r,L,k,t,c,n);}r.restore();}}destroy(){this.canvas=null,this.ctx=null;}drawPriceSeries(e,t,n,r,i,o,a,l,c){if(t.basePainting==="none")return;let d=t.bars,h=t.style;switch(t.priceStyle){case "bars":this.drawBars(e,d,n,r,i,o,h.bars.upColor??a.upColor,h.bars.downColor??a.downColor,l);return;case "line":this.drawPriceLine(e,d,n,r,i,o,h.line.color??a.upColor,h.line.width);return;case "area":{let u=h.area.lineColor??a.upColor;this.drawPriceArea(e,d,n,r,i,o,h.area.topColor??u,h.area.bottomColor??"rgba(0,0,0,0)"),this.drawPriceLine(e,d,n,r,i,o,u,h.area.width);return}case "baseline":this.drawBaseline(e,d,n,r,i,o,t,a,c);return;default:this.drawCandles(e,t,d,n,r,i,o,a,l);}}drawBars(e,t,n,r,i,o,a,l,c){let d=i.bodySpacing(),h=rn(d);if(h==="aggregate"){this.drawCandlesAggregated(e,t,n,r,i,o,a,l,c);return}let u=Math.max(1,Math.round(d*.35)),p=h==="full";e.lineWidth=1;for(let m=n;m<=r;m+=1){let f=t[m];if(!f||f.high<=f.low)continue;let b=Math.round(i.logicalToX(m))+.5,g=c.get(f.time)??(f.close>=f.open?a:l),v=i.priceToY(f.high,o.scale,o.bounds),y=i.priceToY(f.low,o.scale,o.bounds);if(e.strokeStyle=g,e.beginPath(),e.moveTo(b,v),e.lineTo(b,y),p){let x=i.priceToY(f.open,o.scale,o.bounds),S=i.priceToY(f.close,o.scale,o.bounds);e.moveTo(b-u,x),e.lineTo(b,x),e.moveTo(b,S),e.lineTo(b+u,S);}e.stroke();}}drawPriceLine(e,t,n,r,i,o,a,l){e.lineWidth=l,e.lineJoin="round",e.lineCap="round",e.strokeStyle=a,e.beginPath();let c=false;for(let d=Math.max(0,n-1);d<=r;d+=1){let h=t[d];if(!h){c=false;continue}let u=i.logicalToX(d),p=i.priceToY(h.close,o.scale,o.bounds);c?e.lineTo(u,p):(e.moveTo(u,p),c=true);}e.stroke(),e.lineCap="butt";}drawPriceArea(e,t,n,r,i,o,a,l){let c=o.bounds.top+o.bounds.height,d=[],h=1/0;for(let p=Math.max(0,n-1);p<=r;p+=1){let m=t[p];if(!m)continue;let f=i.logicalToX(p),b=i.priceToY(m.close,o.scale,o.bounds);d.push({x:f,y:b}),b<h&&(h=b);}if(d.length<2)return;let u=e.createLinearGradient(0,h,0,c);u.addColorStop(0,a),u.addColorStop(1,l),e.fillStyle=u,e.beginPath(),e.moveTo(d[0].x,c);for(let p of d)e.lineTo(p.x,p.y);e.lineTo(d[d.length-1].x,c),e.closePath(),e.fill();}drawBaseline(e,t,n,r,i,o,a,l,c){let d=a.baselinePriceFor(o.scale),h=i.priceToY(d,o.scale,o.bounds),u=o.bounds.top,p=o.bounds.top+o.bounds.height,m=a.style.baseline,f=m.topLineColor??Qt,b=m.bottomLineColor??en,g=m.topFillColor??W(f,Ye),v=m.topFillColor2??W(f,Xe),y=m.bottomFillColor??W(b,Ye),x=m.bottomFillColor2??W(b,Xe),S=[];for(let M=Math.max(0,n-1);M<=r;M+=1){let E=t[M];E&&S.push({x:i.logicalToX(M),y:i.priceToY(E.close,o.scale,o.bounds)});}if(S.length<2)return;let C=()=>{e.beginPath(),e.moveTo(S[0].x,h);for(let M of S)e.lineTo(M.x,M.y);e.lineTo(S[S.length-1].x,h),e.closePath();};if(h>u){e.save(),e.beginPath(),e.rect(0,u,c,h-u),e.clip();let M=e.createLinearGradient(0,u,0,h);M.addColorStop(0,g),M.addColorStop(1,v),e.fillStyle=M,C(),e.fill(),e.restore();}if(h<p){e.save(),e.beginPath(),e.rect(0,h,c,p-h),e.clip();let M=e.createLinearGradient(0,h,0,p);M.addColorStop(0,x),M.addColorStop(1,y),e.fillStyle=M,C(),e.fill(),e.restore();}e.strokeStyle=a.style.borderColor??l.borderColor,e.lineWidth=1,sn(e,"dashed"),e.beginPath(),e.moveTo(0,Math.round(h)+.5),e.lineTo(c,Math.round(h)+.5),e.stroke(),sn(e,"solid"),e.lineWidth=m.width,e.lineJoin="round",e.lineCap="round";let T=(M,E,k,L,P)=>{e.strokeStyle=P,e.beginPath(),e.moveTo(M,E),e.lineTo(k,L),e.stroke();};for(let M=1;M<S.length;M+=1){let E=S[M-1],k=S[M],L=E.y<=h,P=k.y<=h;if(L!==P&&k.y!==E.y){let V=(h-E.y)/(k.y-E.y),G=E.x+(k.x-E.x)*V;T(E.x,E.y,G,h,L?f:b),T(G,h,k.x,k.y,P?f:b);}else T(E.x,E.y,k.x,k.y,L?f:b);}e.lineCap="butt";}drawCandles(e,t,n,r,i,o,a,l,c){let d=o.bodySpacing(),h=rn(d),u=Wi(t.style.candle,t.candleOverride,l.upColor,l.downColor);if(h==="aggregate"){this.drawCandlesAggregated(e,n,r,i,o,a,u.up,u.down,c);return}let p=h==="full",m=u.candle,f=this.candleStructureAlpha>this.candleBodyAlpha+.001;for(let b=r;b<=i;b+=1){let g=n[b];if(!g||g.high<=g.low)continue;let v=Xi(o.logicalToX(b),d,o.dpr,this.candleBodyScale),y=v.center,x=g.close>=g.open,S=x?u.up:u.down,C=c.get(g.time),T=C??S,M=0,E=0;if(p){let k=o.priceToY(g.open,a.scale,a.bounds),L=o.priceToY(g.close,a.scale,a.bounds);M=Math.min(k,L),E=Math.max(1,Math.abs(L-k));}if(m.wickVisible){let k=(x?m.wickUpColor:m.wickDownColor)??(p?S:T),L=o.priceToY(g.high,a.scale,a.bounds),P=o.priceToY(g.low,a.scale,a.bounds);e.globalAlpha=this.candleStructureAlpha,e.strokeStyle=k,e.lineWidth=v.wickW,e.beginPath(),p?(e.moveTo(y,L),e.lineTo(y,M),e.moveTo(y,M+E),e.lineTo(y,P)):(e.moveTo(y,L),e.lineTo(y,P)),e.stroke();}if(p&&(m.bodyVisible&&(e.globalAlpha=this.candleBodyAlpha,e.fillStyle=T,e.fillRect(v.bodyX,M,v.bodyW,E)),m.borderVisible||C||f&&m.bodyVisible)){e.globalAlpha=this.candleStructureAlpha,e.strokeStyle=m.borderVisible||C?(x?m.borderUpColor:m.borderDownColor)??S:T,e.lineWidth=1;let k=Math.max(0,v.bodyW-1),L=Math.max(0,E-1);e.strokeRect(v.bodyX+.5,M+.5,k,L);}}}drawCandlesAggregated(e,t,n,r,i,o,a,l,c){let d=NaN,h=1/0,u=-1/0,p=0,m=0,f=0,b=false,g=()=>{if(!b)return;let v=c.get(f)??(m>=p?a:l),y=i.priceToY(u,o.scale,o.bounds),x=i.priceToY(h,o.scale,o.bounds);e.strokeStyle=v,e.lineWidth=1,e.beginPath(),e.moveTo(d,y),e.lineTo(d,x),e.stroke();};for(let v=n;v<=r;v+=1){let y=t[v];if(!y||y.high<=y.low)continue;let x=Math.round(i.logicalToX(v))+.5;!b||x!==d?(g(),d=x,h=y.low,u=y.high,p=y.open,f=y.time,b=true):(y.low<h&&(h=y.low),y.high>u&&(u=y.high)),m=y.close;}g();}drawSeries(e,t,n,r,i,o,a,l=0){if(t.kind==="candle"||t.kind==="bar"){this.drawPlotCandles(e,t,n,r,i,o,a,l);return}if(!(!le(t)||t.visible===false))switch(t.kind){case "histogram":case "columns":this.drawHistogram(e,t,n,r,i,o,l);break;case "area":this.drawArea(e,t,n,r,i,o,l),this.drawPolyline(e,t,n,r,i,o,false,l);break;case "circles":case "cross":this.drawPointMarkers(e,t,n,r,i,o,l);break;case "step":this.drawPolyline(e,t,n,r,i,o,true,l);break;default:this.drawPolyline(e,t,n,r,i,o,false,l);}}drawPolyline(e,t,n,r,i,o,a,l=0){e.lineWidth=Math.max(1,t.style.width),e.lineJoin="round",sn(e,t.style.lineStyle);let c=0,d=0,h=false;for(let u=Math.max(1,i-1);u<=o;u+=1){let p=t.points[u-l],m=t.points[u-1-l];if(!p||p.value===null||!m||m.value===null){h=false;continue}let f=r.logicalToX(u),b=r.priceToY(p.value,n.scale,n.bounds);h||(c=r.logicalToX(u-1),d=r.priceToY(m.value,n.scale,n.bounds)),e.strokeStyle=p.color??t.style.color,e.beginPath(),e.moveTo(c,d),a&&e.lineTo(f,d),e.lineTo(f,b),e.stroke(),c=f,d=b,h=true;}sn(e,"solid");}drawArea(e,t,n,r,i,o,a=0){let l=n.bounds.top+n.bounds.height,c=[],d=1/0,h=()=>{if(c.length===0)return;let u=e.createLinearGradient(0,d,0,l);u.addColorStop(0,t.style.color),u.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=u,e.beginPath(),e.moveTo(c[0].x,l);for(let p of c)e.lineTo(p.x,p.y);e.lineTo(c[c.length-1].x,l),e.closePath(),e.fill(),c=[],d=1/0;};for(let u=i;u<=o;u+=1){let p=t.points[u-a];if(!p||p.value===null){h();continue}let m=r.logicalToX(u),f=r.priceToY(p.value,n.scale,n.bounds);c.push({x:m,y:f}),f<d&&(d=f);}h();}drawHistogram(e,t,n,r,i,o,a=0){let l=r.bodySpacing(),c=Math.max(1,(t.kind==="columns"?.7:.8)*l),d=c/2,h=t.style.base??0,u=r.priceToY(h,n.scale,n.bounds);for(let p=i;p<=o;p+=1){let m=t.points[p-a];if(!m||m.value===null)continue;let f=r.logicalToX(p),b=r.priceToY(m.value,n.scale,n.bounds);e.fillStyle=m.color??t.style.color,e.fillRect(f-d,Math.min(u,b),c,Math.max(1,Math.abs(b-u)));}}drawPointMarkers(e,t,n,r,i,o,a=0){let l=Math.max(1.5,t.style.width);for(let c=i;c<=o;c+=1){let d=t.points[c-a];if(!d||d.value===null)continue;let h=r.logicalToX(c),u=r.priceToY(d.value,n.scale,n.bounds);e.strokeStyle=d.color??t.style.color,e.fillStyle=d.color??t.style.color,t.kind==="cross"?(e.lineWidth=1,e.beginPath(),e.moveTo(h-l,u),e.lineTo(h+l,u),e.moveTo(h,u-l),e.lineTo(h,u+l),e.stroke()):(e.beginPath(),e.arc(h,u,l,0,Math.PI*2),e.fill());}}drawPlotCandles(e,t,n,r,i,o,a,l=0){let c=r.bodySpacing(),d=t.style?.up??a.upColor,h=t.style?.down??a.downColor,u=t.kind==="bar",p=Math.max(.5,Math.floor(c*.7)/2),m=Math.max(1,Math.round(c*.35));for(let f=i;f<=o;f+=1){let b=t.bars[f-l];if(!b)continue;let g=t.barColors?.[f-l],v=g?.color??(b.close>=b.open?d:h),y=Math.round(r.logicalToX(f))+.5,x=r.priceToY(b.high,n.scale,n.bounds),S=r.priceToY(b.low,n.scale,n.bounds),C=r.priceToY(b.open,n.scale,n.bounds),T=r.priceToY(b.close,n.scale,n.bounds);if(u){e.strokeStyle=v,e.lineWidth=1,e.beginPath(),e.moveTo(y,x),e.lineTo(y,S),e.moveTo(y-m,C),e.lineTo(y,C),e.moveTo(y,T),e.lineTo(y+m,T),e.stroke();continue}e.strokeStyle=g?.wickColor??v,e.lineWidth=Xn(c),e.beginPath(),e.moveTo(y,x),e.lineTo(y,S),e.stroke(),e.fillStyle=v,e.fillRect(y-p,Math.min(C,T),p*2,Math.max(1,Math.abs(T-C))),g?.borderColor&&(e.strokeStyle=g.borderColor,e.strokeRect(y-p,Math.min(C,T),p*2,Math.max(1,Math.abs(T-C))));}}drawFill(e,t,n,r,i,o,a,l=0){let c=lc(t,n.fromSeriesId),d=lc(t,n.toSeriesId);if(!c||!d)return;let h=NaN,u=NaN,p="",m="",f=null;for(let b=Math.max(1,o);b<=a;b+=1){let g=c[b-1-l],v=d[b-1-l],y=c[b-l],x=d[b-l];if(!g||!v||!y||!x||g.value===null||v.value===null||y.value===null||x.value===null)continue;let S=i.logicalToX(b-1),C=i.logicalToX(b),T=i.priceToY(g.value,r.scale,r.bounds),M=i.priceToY(v.value,r.scale,r.bounds),E=i.priceToY(y.value,r.scale,r.bounds),k=i.priceToY(x.value,r.scale,r.bounds),L=n.gradient?.[b-1-l];if(L){let P=i.priceToY(L.topValue,r.scale,r.bounds),V=i.priceToY(L.bottomValue,r.scale,r.bounds),G=V===P?P+1:V;(!f||P!==h||G!==u||L.topColor!==p||L.bottomColor!==m)&&(f=e.createLinearGradient(0,P,0,G),f.addColorStop(0,L.topColor),f.addColorStop(1,L.bottomColor),h=P,u=G,p=L.topColor,m=L.bottomColor),e.fillStyle=f;}else {let P=n.colors?n.colors[b-1-l]:n.color;if(!P)continue;e.fillStyle=P;}e.beginPath(),e.moveTo(S,T),e.lineTo(C,E),e.lineTo(C,k),e.lineTo(S,M),e.closePath(),e.fill();}}drawBackground(e,t,n,r){let i=r.timeToX(t.from),o=r.timeToX(t.to);o<0||i>r.width||o<=i||(e.fillStyle=t.color,e.fillRect(i,n.bounds.top,o-i,n.bounds.height));}drawHighlights(e,t,n){if(t.highlights.length!==0)for(let r of t.highlights){let i=n.timeToX(r.from),o=n.timeToX(r.to);if(o<0||i>n.width||o<=i)continue;let a=Math.max(0,i),l=Math.min(n.width,o)-a;l<=0||(e.fillStyle=r.color,e.fillRect(a,0,l,n.height));}}drawHline(e,t,n,r,i,o){let a=Math.round(r.priceToY(t.price,n.scale,n.bounds))+.5;a<n.bounds.top||a>n.bounds.top+n.bounds.height||(e.strokeStyle=t.color??o.textColor,e.lineWidth=t.width??1,sn(e,t.lineStyle??"solid"),e.beginPath(),e.moveTo(0,a),e.lineTo(i,a),e.stroke(),sn(e,"solid"));}drawGrid(e,t,n,r,i){let o=t.orderedPanes(),{gridVert:a,gridHorz:l}=t.style,c=a.color??r.gridColor,d=l.color??r.gridColor;if(e.lineWidth=1,t.showGrid&&a.visible){e.globalAlpha=this.gridAlpha,e.strokeStyle=c;let h=n.visibleTimeRange(),u=Rt((h.from+h.to)/2,t.timezone);e.beginPath();for(let p of Jt(h.from,h.to,8,u)){let m=Math.round(n.timeToX(p.time))+.5;m<0||m>i||(e.moveTo(m,0),e.lineTo(m,n.height));}e.stroke();}for(let h of o)if(t.showGrid&&l.visible&&!h.collapsed){e.globalAlpha=this.gridAlpha,e.strokeStyle=d;let u=Ee(t,h);e.beginPath();for(let p of kt(h.scale,h.bounds.height,u)){let m=Math.round(n.priceToY(p.price,h.scale,h.bounds))+.5;m<h.bounds.top||m>h.bounds.top+h.bounds.height||(e.moveTo(0,m),e.lineTo(i,m));}e.stroke();}e.globalAlpha=1;}};function sn(s,e){e==="dashed"?s.setLineDash([6,4]):e==="dotted"?s.setLineDash([2,3]):s.setLineDash([]);}function lc(s,e){let t=s.series.find(n=>n.id===e);return t&&le(t)?t.points:null}var Zm=new Map;function Jm(s){let e=false;for(let n of s.values())if(n.barColors&&n.barColors.length>0){e=true;break}if(!e)return Zm;let t=new Map;for(let n of s.values())if(n.barColors)for(let r of n.barColors)t.set(r.time,r.color);return t}function Dt(s,e){let t=Math.max(1,e);return s==="dotted"?[t,t*2]:s==="dashed"?[t*4,t*3]:[]}function an(s,e,t,n,r,i,o){if(r==="none")return [s,e,t,n];let a=t-s,l=r==="left"||r==="both",c=r==="right"||r==="both";if(Math.abs(a)<1e-6){if(l&&c)return [s,0,t,o];let m=n>=e;return c?m?[s,e,t,o]:[s,e,t,0]:m?[s,0,t,n]:[s,o,t,n]}let d=(n-e)/a,h=m=>e+d*(m-s),u=l?-2:Math.min(s,t),p=c?i+2:Math.max(s,t);return [u,h(u),p,h(p)]}function Qm(s){let e=s.trim(),t=/^#([0-9a-f]{3})$/i.exec(e);if(t){let n=t[1];return {r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:1}}if(t=/^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(e),t){let n=t[1];return {r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:t[2]?parseInt(t[2],16)/255:1}}if(t=/^rgba?\(([^)]+)\)$/i.exec(e),t){let n=t[1].split(",").map(r=>parseFloat(r.trim()));return {r:n[0]??0,g:n[1]??0,b:n[2]??0,a:n[3]??1}}return null}function ef(s,e,t){return (.299*s+.587*e+.114*t)/255}function be(s){if(!s)return "#000000";let e=Qm(s);return e?ef(e.r,e.g,e.b)>.55?"#000000":"#ffffff":"#000000"}function Ve(s){return Math.round(s*1.4)}var At=5,Ot=3;function ce(s){switch(s){case "tiny":return 10;case "small":return 12;case "large":return 18;case "huge":return 28;case "normal":return 14;default:return 0}}function cc(s,e,t,n){let r=1;for(let l of s)l.length>r&&(r=l.length);let i=n?.62:.55,o=e*.9/(r*i),a=t*.85/(s.length*1.3);return Math.max(6,Math.min(o,a,48))}var tf={lines:[],boxes:[],labels:[],polylines:[],linefills:[]};function dc(s){return s==="auto"?12:ce(s)}var ro=class{constructor(e,t=tf){this.deps=e;this.set=t;this.widthCache=new Map;this.indexOffset=0;}setSet(e,t=0){this.set=e,this.indexOffset=t;}setDeps(e){this.deps=e;}isEmpty(){let e=this.set;return !e.lines.length&&!e.boxes.length&&!e.labels.length&&!e.polylines.length&&!e.linefills.length}render(e,t,n,r,i){this.isEmpty()||(e.save(),this.drawLinefills(e,t,n,r,i),this.drawBoxes(e,t,n,r,i),this.drawPolylines(e,t,r,i),this.drawLines(e,t,n,r,i),this.drawLabels(e,t,n,r,i),e.restore());}priceRange(e,t){let n=Math.min(e,t),r=Math.max(e,t),i=(h,u,p)=>p!=="none"?true:Math.max(h,u)>=n&&Math.min(h,u)<=r,o=1/0,a=-1/0,l=h=>{h<o&&(o=h),h>a&&(a=h);};for(let h of this.set.lines)h.invisible||i(this.logicalOf(h.xloc,h.x1),this.logicalOf(h.xloc,h.x2),h.extend)&&(l(h.y1),l(h.y2));for(let h of this.set.boxes)!h.bgColor&&!(h.borderColor&&h.borderWidth>0)&&!h.text||i(this.logicalOf(h.xloc,h.left),this.logicalOf(h.xloc,h.right),h.extend)&&(l(h.top),l(h.bottom));for(let h of this.set.linefills){if(!h.color)continue;let u=[h.line1.x1,h.line1.x2,h.line2.x1,h.line2.x2].map((m,f)=>this.logicalOf(f<2?h.line1.xloc:h.line2.xloc,m)),p=h.line1.extend!=="none"||h.line2.extend!=="none"?"both":"none";i(Math.min(...u),Math.max(...u),p)&&(l(h.line1.y1),l(h.line1.y2),l(h.line2.y1),l(h.line2.y2));}for(let h of this.set.polylines){if(h.points.length<2)continue;let u=h.points.map(p=>this.logicalOf(p.xloc,p.x));if(i(Math.min(...u),Math.max(...u),"none"))for(let p of h.points)l(p.price);}let c=0,d=0;for(let h of this.set.labels){let u=this.logicalOf(h.xloc,h.x);if(!i(u,u,"none"))continue;if(h.yloc==="price"){l(h.y);continue}if(h.yloc==="top"||h.yloc==="bottom")continue;let p=this.deps.barAt(u);if(!p)continue;l(h.yloc==="abovebar"?p.high:p.low);let m=dc(h.size),f=Math.max(1,(h.text??"").split(`
80
+ }`,ps={solid:null,dashed:[6,4],dotted:[2,3]};function tc(s,e){let t=Math.max(1,Math.round(e));return {pos:Math.round(s*e-t/2)/e,size:t/e}}function nc(s){return Math.max(6,Math.min(20,Math.round(s*4)))}var Zi=class{constructor(){this.kind="webgl2";this.modelAlpha=1;this.candleBodyAlpha=1;this.candleStructureAlpha=1;this.gridAlpha=1;this.candleBodyScale=1;this.onNeedsRedraw=null;this.onContextFailed=null;this.glow=0;this.canvas=null;this.gl=null;this.program=null;this.vao=null;this.vbo=null;this.uRes=null;this.batch=new Kn;this.contextLost=false;this.screenProgram=null;this.uTex=null;this.uDir=null;this.uIntensity=null;this.quadVao=null;this.quadVbo=null;this.fboA=null;this.texA=null;this.fboB=null;this.texB=null;this.fboW=0;this.fboH=0;this.glowBatch=new Kn;this.sliceTex=new Map;this.onLost=e=>{e.preventDefault(),this.contextLost=true;};this.onRestored=()=>{this.contextLost=false,this.initGL()?this.onNeedsRedraw?.():this.onContextFailed?.();};}get ok(){return this.gl!==null}mount(e){if(this.canvas=e,this.gl=e.getContext("webgl2",{alpha:true,antialias:true,depth:false,stencil:false,premultipliedAlpha:true}),!!this.gl){if(!this.initGL()){this.gl=null;return}e.addEventListener("webglcontextlost",this.onLost,false),e.addEventListener("webglcontextrestored",this.onRestored,false);}}initGL(){let e=this.gl;if(!e)return false;this.screenProgram=null,this.quadVao=null,this.quadVbo=null,this.fboA=this.fboB=null,this.texA=this.texB=null,this.fboW=this.fboH=0,this.sliceTex.clear();let t=ji(e,e.VERTEX_SHADER,km),n=ji(e,e.FRAGMENT_SHADER,Im),r=e.createProgram();if(!t||!n||!r)return t&&e.deleteShader(t),n&&e.deleteShader(n),r&&e.deleteProgram(r),false;if(e.attachShader(r,t),e.attachShader(r,n),e.linkProgram(r),!e.getProgramParameter(r,e.LINK_STATUS))return e.deleteProgram(r),e.deleteShader(t),e.deleteShader(n),false;e.deleteShader(t),e.deleteShader(n),this.program=r,this.uRes=e.getUniformLocation(r,"uRes"),this.vbo=e.createBuffer(),this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.vbo);let i=32;return e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,false,i,0),e.enableVertexAttribArray(1),e.vertexAttribPointer(1,4,e.FLOAT,false,i,8),e.enableVertexAttribArray(2),e.vertexAttribPointer(2,2,e.FLOAT,false,i,24),e.bindVertexArray(null),this.glow>0&&!this.ensureScreenPipeline()&&(this.glow=0),true}ensureScreenPipeline(){if(this.screenProgram&&this.quadVao)return true;let e=this.gl;if(!e)return false;let t=ji(e,e.VERTEX_SHADER,Rm),n=ji(e,e.FRAGMENT_SHADER,Dm),r=e.createProgram();return !t||!n||!r?(t&&e.deleteShader(t),n&&e.deleteShader(n),r&&e.deleteProgram(r),false):(e.attachShader(r,t),e.attachShader(r,n),e.linkProgram(r),e.getProgramParameter(r,e.LINK_STATUS)?(e.deleteShader(t),e.deleteShader(n),this.screenProgram=r,this.uTex=e.getUniformLocation(r,"uTex"),this.uDir=e.getUniformLocation(r,"uDir"),this.uIntensity=e.getUniformLocation(r,"uIntensity"),this.quadVbo=e.createBuffer(),this.quadVao=e.createVertexArray(),e.bindVertexArray(this.quadVao),e.bindBuffer(e.ARRAY_BUFFER,this.quadVbo),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,false,0,0),e.bindVertexArray(null),true):(e.deleteProgram(r),false))}ensureFbos(e,t,n){if(this.fboA&&this.fboW===t&&this.fboH===n)return true;this.deleteFbos(e);let r=()=>{let a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,n,0,e.RGBA,e.UNSIGNED_BYTE,null),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);let l=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,l),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,a,0),{tex:a,fbo:l}},i=r(),o=r();return e.bindFramebuffer(e.FRAMEBUFFER,null),this.texA=i.tex,this.fboA=i.fbo,this.texB=o.tex,this.fboB=o.fbo,this.fboW=t,this.fboH=n,!!(this.fboA&&this.fboB)}deleteFbos(e){this.fboA&&e.deleteFramebuffer(this.fboA),this.fboB&&e.deleteFramebuffer(this.fboB),this.texA&&e.deleteTexture(this.texA),this.texB&&e.deleteTexture(this.texB),this.fboA=this.fboB=null,this.texA=this.texB=null,this.fboW=this.fboH=0;}render(e,t,n){let r=this.gl,i=this.canvas;if(!r||!i||!this.program||this.contextLost||r.isContextLost())return;let o=t.dpr,a=t.width;r.viewport(0,0,i.width,i.height),r.disable(r.SCISSOR_TEST),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT);let l=t.barCount;if(l===0)return;let c=t.visibleLogicalRange(),d=Math.max(0,Math.floor(c.from)),h=Math.min(l-1,Math.ceil(c.to));if(h<d)return;r.enable(r.BLEND),r.enable(r.SCISSOR_TEST);let u=Fm(e.indicators),p=e.orderedPanes(),m=new Set;for(let f of p){let b=this.batch;b.reset();let g=Math.round(f.bounds.top*o),v=Math.round((f.bounds.top+f.bounds.height)*o);r.scissor(0,i.height-v,Math.round(a*o),v-g);let y=()=>{b.vertexCount!==0&&(r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA),r.useProgram(this.program),r.bindVertexArray(this.vao),r.uniform2f(this.uRes,i.width/o,i.height/o),r.bindBuffer(r.ARRAY_BUFFER,this.vbo),r.bufferData(r.ARRAY_BUFFER,b.view,r.DYNAMIC_DRAW),r.drawArrays(r.TRIANGLES,0,b.vertexCount),b.reset());},x=f.collapsed?[]:e.drawingSlices.get(f.id)??[],S=0,C=T=>{for(;S<x.length&&x[S].beforeZ<=T;S+=1)y(),this.drawSliceTexture(r,x[S].canvas)&&m.add(x[S].canvas);};if(b.alpha=1,f.collapsed)this.emitGrid(b,t,n,a,f,e);else {this.emitHighlights(b,e,f,t),this.emitGrid(b,t,n,a,f,e);let T=e.orderedIndicatorsForPane(f.id),M=f.kind==="price",E=P=>{let V=e.scaleFor(P,f);return V===f.scale?f:{...f,scale:V}};b.alpha=this.modelAlpha;for(let P of T)for(let V of P.backgrounds)this.emitBackground(b,V,f,t);for(let P of T)for(let V of P.fills)this.emitFill(b,P,V,E(P),t,d,h,e.offsetOf(P.id));let k=M&&!e.candlesHidden,L=false;for(let P of T){k&&!L&&e.zOf(P.id)>=e.candleZ&&(C(e.candleZ),b.alpha=this.candleStructureAlpha,this.emitPriceSeries(b,e,d,h,t,f,n,u,a),L=true),C(e.zOf(P.id)),b.alpha=this.modelAlpha;let V=e.offsetOf(P.id),G=E(P);for(let w of P.series)this.emitSeries(b,w,G,t,d,h,n,V);}k&&!L&&(C(e.candleZ),b.alpha=this.candleStructureAlpha,this.emitPriceSeries(b,e,d,h,t,f,n,u,a)),C(1/0),b.alpha=this.modelAlpha;for(let P of T){let V=E(P);for(let G of P.priceLines)this.emitHline(b,G,V,t,a,n);}b.alpha=1;}y();}r.disable(r.SCISSOR_TEST);for(let[f,b]of this.sliceTex)m.has(f)||(r.deleteTexture(b),this.sliceTex.delete(f));this.glow>0&&!this.screenProgram&&!this.ensureScreenPipeline()&&(this.glow=0),this.glow>0&&this.screenProgram&&(this.glowBatch.alpha=this.modelAlpha,this.renderGlow(r,e,t,d,h));}renderGlow(e,t,n,r,i){let o=this.canvas,a=Math.max(1,o.width>>1),l=Math.max(1,o.height>>1);if(!this.ensureFbos(e,a,l))return;let c=n.dpr,d=n.width;e.bindFramebuffer(e.FRAMEBUFFER,this.fboA),e.viewport(0,0,a,l),e.disable(e.SCISSOR_TEST),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),e.enable(e.BLEND),e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.useProgram(this.program),e.bindVertexArray(this.vao),e.uniform2f(this.uRes,o.width/c,o.height/c),e.enable(e.SCISSOR_TEST);for(let h of t.orderedPanes()){let u=this.glowBatch;if(u.reset(),this.emitGlowSources(u,t.indicatorsForPane(h.id),h,n,r,i,f=>t.offsetOf(f)),u.vertexCount===0)continue;let p=Math.round(h.bounds.top*c*.5),m=Math.round((h.bounds.top+h.bounds.height)*c*.5);e.scissor(0,l-m,Math.round(d*c*.5),m-p),e.bindBuffer(e.ARRAY_BUFFER,this.vbo),e.bufferData(e.ARRAY_BUFFER,u.view,e.DYNAMIC_DRAW),e.drawArrays(e.TRIANGLES,0,u.vertexCount);}e.disable(e.SCISSOR_TEST),e.useProgram(this.screenProgram),e.bindVertexArray(this.quadVao),e.uniform1i(this.uTex,0),e.uniform1f(this.uIntensity,1),e.activeTexture(e.TEXTURE0),e.disable(e.BLEND),e.bindFramebuffer(e.FRAMEBUFFER,this.fboB),e.bindTexture(e.TEXTURE_2D,this.texA),e.uniform2f(this.uDir,1/a,0),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindFramebuffer(e.FRAMEBUFFER,this.fboA),e.bindTexture(e.TEXTURE_2D,this.texB),e.uniform2f(this.uDir,0,1/l),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,o.width,o.height),e.enable(e.BLEND),e.blendFunc(e.ONE,e.ONE),e.bindTexture(e.TEXTURE_2D,this.texA),e.uniform2f(this.uDir,0,0),e.uniform1f(this.uIntensity,this.glow),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindTexture(e.TEXTURE_2D,null),e.bindVertexArray(null);}drawSliceTexture(e,t){if(!this.ensureScreenPipeline()||!this.screenProgram)return false;let n=this.sliceTex.get(t)??null;if(!n){if(n=e.createTexture(),!n)return false;this.sliceTex.set(t,n),e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);}return e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,n),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,true),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,false),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false),e.useProgram(this.screenProgram),e.bindVertexArray(this.quadVao),e.uniform1i(this.uTex,0),e.uniform2f(this.uDir,0,0),e.uniform1f(this.uIntensity,1),e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLE_STRIP,0,4),e.bindVertexArray(null),true}emitGlowSources(e,t,n,r,i,o,a=()=>0){for(let l of t){let c=a(l.id);for(let d of l.series)!le(d)||d.visible===false||d.kind==="histogram"||d.kind==="columns"||(d.kind==="circles"||d.kind==="cross"?this.emitPointMarkers(e,d,n,r,i,o,c):this.emitPolyline(e,d,n,r,i,o,d.kind==="step",c));}}destroy(){let e=this.gl;if(this.canvas&&(this.canvas.removeEventListener("webglcontextlost",this.onLost),this.canvas.removeEventListener("webglcontextrestored",this.onRestored)),e){this.program&&e.deleteProgram(this.program),this.vbo&&e.deleteBuffer(this.vbo),this.vao&&e.deleteVertexArray(this.vao),this.screenProgram&&e.deleteProgram(this.screenProgram),this.quadVbo&&e.deleteBuffer(this.quadVbo),this.quadVao&&e.deleteVertexArray(this.quadVao);for(let t of this.sliceTex.values())e.deleteTexture(t);this.sliceTex.clear(),this.deleteFbos(e),e.getExtension("WEBGL_lose_context")?.loseContext();}this.gl=null,this.canvas=null,this.program=null,this.vao=null,this.vbo=null,this.screenProgram=null;}emitGrid(e,t,n,r,i,o){let a=i.bounds.top,l=i.bounds.top+i.bounds.height,{gridVert:c,gridHorz:d}=o.style,h=t.dpr;if(e.alpha=this.gridAlpha,o.showGrid&&c.visible&&!i.collapsed){let u=U(c.color??n.gridColor),p=t.visibleTimeRange(),m=Rt((p.from+p.to)/2,o.timezone);for(let f of Jt(p.from,p.to,8,m)){let b=t.timeToX(f.time);if(b<0||b>r)continue;let g=tc(b,h);e.rect(g.pos,a,g.size,l-a,u);}}if(o.showGrid&&d.visible&&!i.collapsed){let u=U(d.color??n.gridColor),p=Ee(o,i);for(let m of kt(i.scale,i.bounds.height,p)){let f=t.priceToY(m.price,i.scale,i.bounds);if(f<a||f>l)continue;let b=tc(f,h);e.rect(0,b.pos,r,b.size,u);}}}emitHighlights(e,t,n,r){if(t.highlights.length!==0)for(let i of t.highlights){let o=r.timeToX(i.from),a=r.timeToX(i.to);if(a<0||o>r.width||a<=o)continue;let l=Math.max(0,o),c=Math.min(r.width,a)-l;c<=0||e.rect(l,n.bounds.top,c,n.bounds.height,U(i.color));}}emitBackground(e,t,n,r){let i=r.timeToX(t.from),o=r.timeToX(t.to);o<0||i>r.width||o<=i||e.rect(i,n.bounds.top,o-i,n.bounds.height,U(t.color));}emitFill(e,t,n,r,i,o,a,l=0){let c=ic(t,n.fromSeriesId),d=ic(t,n.toSeriesId);if(!(!c||!d))for(let h=Math.max(1,o);h<=a;h+=1){let u=c[h-1-l],p=d[h-1-l],m=c[h-l],f=d[h-l];if(!u||!p||!m||!f||u.value===null||p.value===null||m.value===null||f.value===null)continue;let b=i.logicalToX(h-1),g=i.logicalToX(h),v=i.priceToY(u.value,r.scale,r.bounds),y=i.priceToY(p.value,r.scale,r.bounds),x=i.priceToY(m.value,r.scale,r.bounds),S=i.priceToY(f.value,r.scale,r.bounds),C=n.gradient?.[h-1-l];if(C){let T=i.priceToY(C.topValue,r.scale,r.bounds),M=i.priceToY(C.bottomValue,r.scale,r.bounds),E=M===T?T+1:M,k=U(C.topColor),L=U(C.bottomColor),P=E-T,V=G=>ms(k,L,qi((G-T)/P));e.quad4(b,v,V(v),g,x,V(x),g,S,V(S),b,y,V(y));}else {let T=n.colors?n.colors[h-1-l]:n.color;if(!T)continue;e.quad(b,v,g,x,g,S,b,y,U(T));}}}emitPriceSeries(e,t,n,r,i,o,a,l,c){if(t.basePainting==="none")return;let d=t.bars,h=t.style;switch(t.priceStyle){case "bars":this.emitBars(e,d,n,r,i,o,h.bars.upColor??a.upColor,h.bars.downColor??a.downColor,l);return;case "line":this.emitPriceLine(e,d,n,r,i,o,U(h.line.color??a.upColor),h.line.width);return;case "area":{let u=h.area.lineColor??a.upColor;this.emitPriceArea(e,d,n,r,i,o,U(h.area.topColor??u),U(h.area.bottomColor??"rgba(0,0,0,0)")),this.emitPriceLine(e,d,n,r,i,o,U(u),h.area.width);return}case "baseline":this.emitBaseline(e,d,n,r,i,o,t,a,c);return;default:this.emitCandles(e,t,d,n,r,i,o,a,l);}}emitBars(e,t,n,r,i,o,a,l,c){let d=i.bodySpacing(),h=rn(d);if(h==="aggregate"){this.emitCandlesAggregated(e,t,n,r,i,o,a,l,c);return}let u=Math.max(1,Math.round(d*.35)),p=h==="full";for(let m=n;m<=r;m+=1){let f=t[m];if(!f||f.high<=f.low)continue;let b=U(c.get(f.time)??(f.close>=f.open?a:l)),g=Math.round(i.logicalToX(m)),v=i.priceToY(f.high,o.scale,o.bounds),y=i.priceToY(f.low,o.scale,o.bounds);if(e.rect(g-.5,v,1,y-v,b),p){let x=i.priceToY(f.open,o.scale,o.bounds),S=i.priceToY(f.close,o.scale,o.bounds);e.rect(g-u,x-.5,u,1,b),e.rect(g,S-.5,u,1,b);}}}emitPriceLine(e,t,n,r,i,o,a,l){let c=Math.max(1,l)/2,d=nc(c),h=false,u=0,p=0;for(let m=Math.max(0,n-1);m<=r;m+=1){let f=t[m];if(!f){h=false;continue}let b=i.logicalToX(m),g=i.priceToY(f.close,o.scale,o.bounds);h&&e.seg(u,p,b,g,l,a),e.circle(b,g,c,a,d),u=b,p=g,h=true;}}emitPriceArea(e,t,n,r,i,o,a,l){let c=o.bounds.top+o.bounds.height,d=[],h=1/0,u=()=>{if(d.length>=2){let p=c-h,m=f=>ms(a,l,p<1e-6?0:qi((f-h)/p));for(let f=1;f<d.length;f+=1){let b=d[f-1],g=d[f];e.quad4(b.x,b.y,m(b.y),g.x,g.y,m(g.y),g.x,c,l,b.x,c,l);}}d.length=0,h=1/0;};for(let p=Math.max(0,n-1);p<=r;p+=1){let m=t[p];if(!m){u();continue}let f=i.logicalToX(p),b=i.priceToY(m.close,o.scale,o.bounds);d.push({x:f,y:b}),b<h&&(h=b);}u();}emitBaseline(e,t,n,r,i,o,a,l,c){let d=a.baselinePriceFor(o.scale),h=i.priceToY(d,o.scale,o.bounds),u=a.style.baseline,p=u.topLineColor??Qt,m=u.bottomLineColor??en,f=U(p),b=U(m),g=U(u.topFillColor??W(p,Ye)),v=U(u.topFillColor2??W(p,Xe)),y=U(u.bottomFillColor??W(m,Ye)),x=U(u.bottomFillColor2??W(m,Xe)),S=[];for(let k=Math.max(0,n-1);k<=r;k+=1){let L=t[k];L&&S.push({x:i.logicalToX(k),y:i.priceToY(L.close,o.scale,o.bounds)});}if(S.length<2)return;let C=o.bounds.top,T=o.bounds.top+o.bounds.height,M=k=>k<=h?v:x,E=k=>{let L=k<=h,P=L?h-C:T-h,V=P>0?qi(Math.abs(k-h)/P):0;return ms(L?v:x,L?g:y,V)};for(let k=1;k<S.length;k+=1){let L=S[k-1],P=S[k];if(L.y<=h!=P.y<=h&&P.y!==L.y){let V=(h-L.y)/(P.y-L.y),G=L.x+(P.x-L.x)*V;e.tri(L.x,L.y,E(L.y),G,h,M(L.y),L.x,h,M(L.y)),e.tri(G,h,M(P.y),P.x,P.y,E(P.y),P.x,h,M(P.y));}else e.quad4(L.x,L.y,E(L.y),P.x,P.y,E(P.y),P.x,h,M(P.y),L.x,h,M(L.y));}e.dashedSeg(0,h,c,h,1,U(a.style.borderColor??l.borderColor),ps.dashed??null);for(let k=1;k<S.length;k+=1){let L=S[k-1],P=S[k],V=L.y<=h,G=P.y<=h;if(V!==G&&P.y!==L.y){let w=(h-L.y)/(P.y-L.y),H=L.x+(P.x-L.x)*w;e.seg(L.x,L.y,H,h,u.width,V?f:b),e.seg(H,h,P.x,P.y,u.width,G?f:b);}else e.seg(L.x,L.y,P.x,P.y,u.width,V?f:b);}}emitCandles(e,t,n,r,i,o,a,l,c){let d=o.bodySpacing(),h=rn(d),u=Ui(t.style.candle,t.candleOverride,l.upColor,l.downColor);if(h==="aggregate"){this.emitCandlesAggregated(e,n,r,i,o,a,u.up,u.down,c);return}let p=h==="full",m=u.up,f=u.down,b=u.candle,g=this.candleStructureAlpha>this.candleBodyAlpha+.001;for(let v=r;v<=i;v+=1){let y=n[v];if(!y||y.high<=y.low)continue;let x=Ki(o.logicalToX(v),d,o.dpr,this.candleBodyScale),S=y.close>=y.open,C=S?m:f,T=c.get(y.time),M=T??C,E=U(M),k=0,L=0;if(p){let P=o.priceToY(y.open,a.scale,a.bounds),V=o.priceToY(y.close,a.scale,a.bounds);k=Math.min(P,V),L=Math.max(1,Math.abs(V-P));}if(b.wickVisible){let P=o.priceToY(y.high,a.scale,a.bounds),V=o.priceToY(y.low,a.scale,a.bounds);e.alpha=this.candleStructureAlpha;let G=U((S?b.wickUpColor:b.wickDownColor)??(p?C:M));p?(e.rect(x.wickX,P,x.wickW,Math.max(0,k-P),G),e.rect(x.wickX,k+L,x.wickW,Math.max(0,V-(k+L)),G)):e.rect(x.wickX,P,x.wickW,V-P,G);}if(p&&(b.bodyVisible&&(e.alpha=this.candleBodyAlpha,e.rect(x.bodyX,k,x.bodyW,L,E)),b.borderVisible||T||g&&b.bodyVisible)){e.alpha=this.candleStructureAlpha;let P=b.borderVisible||T?U((S?b.borderUpColor:b.borderDownColor)??C):E,V=Math.max(0,x.bodyW-1),G=Math.max(0,L-1);e.rectStroke(x.bodyX+.5,k+.5,V,G,1,P);}}}emitCandlesAggregated(e,t,n,r,i,o,a,l,c){let d=NaN,h=1/0,u=-1/0,p=0,m=0,f=0,b=false,g=()=>{if(!b)return;let v=U(c.get(f)??(m>=p?a:l)),y=i.priceToY(u,o.scale,o.bounds),x=i.priceToY(h,o.scale,o.bounds);e.rect(d-.5,y,1,x-y,v);};for(let v=n;v<=r;v+=1){let y=t[v];if(!y||y.high<=y.low)continue;let x=Math.round(i.logicalToX(v));!b||x!==d?(g(),d=x,h=y.low,u=y.high,p=y.open,f=y.time,b=true):(y.low<h&&(h=y.low),y.high>u&&(u=y.high)),m=y.close;}g();}emitSeries(e,t,n,r,i,o,a,l=0){if(t.kind==="candle"||t.kind==="bar"){this.emitPlotCandles(e,t,n,r,i,o,a,l);return}if(!(!le(t)||t.visible===false))switch(t.kind){case "histogram":case "columns":this.emitHistogram(e,t,n,r,i,o,l);break;case "area":this.emitArea(e,t,n,r,i,o,l),this.emitPolyline(e,t,n,r,i,o,false,l);break;case "circles":case "cross":this.emitPointMarkers(e,t,n,r,i,o,l);break;case "step":this.emitPolyline(e,t,n,r,i,o,true,l);break;default:this.emitPolyline(e,t,n,r,i,o,false,l);}}emitPolyline(e,t,n,r,i,o,a,l=0){let c=Math.max(1,t.style.width),d=c/2,h=ps[t.style.lineStyle]??null,u=!h&&!a,p=nc(d),m=false;for(let f=Math.max(1,i-1);f<=o;f+=1){let b=t.points[f-l],g=t.points[f-1-l];if(!b||b.value===null||!g||g.value===null){m=false;continue}let v=r.logicalToX(f),y=r.priceToY(b.value,n.scale,n.bounds),x=r.logicalToX(f-1),S=r.priceToY(g.value,n.scale,n.bounds),C=U(b.color??t.style.color);a?(e.dashedSeg(x,S,v,S,c,C,h),e.dashedSeg(v,S,v,y,c,C,h)):e.dashedSeg(x,S,v,y,c,C,h),u&&(m||e.circle(x,S,d,U(g.color??t.style.color),p),e.circle(v,y,d,C,p)),m=true;}}emitArea(e,t,n,r,i,o,a=0){let l=n.bounds.top+n.bounds.height,c=U(t.style.color),d=[],h=1/0,u=()=>{if(d.length<1){d=[],h=1/0;return}let p=l-h,m=f=>Am(c,p<1e-6?0:qi((f-h)/p));for(let f=1;f<d.length;f+=1){let b=d[f-1],g=d[f];e.quad4(b.x,b.y,m(b.y),g.x,g.y,m(g.y),g.x,l,rc,b.x,l,rc);}d=[],h=1/0;};for(let p=i;p<=o;p+=1){let m=t.points[p-a];if(!m||m.value===null){u();continue}let f=r.logicalToX(p),b=r.priceToY(m.value,n.scale,n.bounds);d.push({x:f,y:b}),b<h&&(h=b);}u();}emitHistogram(e,t,n,r,i,o,a=0){let l=r.bodySpacing(),c=Math.max(1,(t.kind==="columns"?.7:.8)*l),d=c/2,h=t.style.base??0,u=r.priceToY(h,n.scale,n.bounds);for(let p=i;p<=o;p+=1){let m=t.points[p-a];if(!m||m.value===null)continue;let f=r.logicalToX(p),b=r.priceToY(m.value,n.scale,n.bounds);e.rect(f-d,Math.min(u,b),c,Math.max(1,Math.abs(b-u)),U(m.color??t.style.color));}}emitPointMarkers(e,t,n,r,i,o,a=0){let l=Math.max(1.5,t.style.width);for(let c=i;c<=o;c+=1){let d=t.points[c-a];if(!d||d.value===null)continue;let h=r.logicalToX(c),u=r.priceToY(d.value,n.scale,n.bounds),p=U(d.color??t.style.color);t.kind==="cross"?(e.seg(h-l,u,h+l,u,1,p),e.seg(h,u-l,h,u+l,1,p)):e.circle(h,u,l,p,Math.max(16,Math.ceil(l*2)));}}emitPlotCandles(e,t,n,r,i,o,a,l=0){let c=r.bodySpacing(),d=t.style?.up??a.upColor,h=t.style?.down??a.downColor,u=t.kind==="bar",p=Math.max(.5,Math.floor(c*.7)/2),m=Math.max(1,Math.round(c*.35));for(let f=i;f<=o;f+=1){let b=t.bars[f-l];if(!b)continue;let g=t.barColors?.[f-l],v=U(g?.color??(b.close>=b.open?d:h)),y=Math.round(r.logicalToX(f)),x=r.priceToY(b.high,n.scale,n.bounds),S=r.priceToY(b.low,n.scale,n.bounds),C=r.priceToY(b.open,n.scale,n.bounds),T=r.priceToY(b.close,n.scale,n.bounds);if(u){e.rect(y-.5,x,1,S-x,v),e.rect(y-m,C-.5,m,1,v),e.rect(y,T-.5,m,1,v);continue}let M=Math.max(1,Math.round(Xn(c)*r.dpr)),E=(Math.round(y*r.dpr)-(M>>1))/r.dpr;e.rect(E,x,M/r.dpr,S-x,U(g?.wickColor??g?.color??(b.close>=b.open?d:h)));let k=Math.min(C,T),L=Math.max(1,Math.abs(T-C));if(e.rect(y-p,k,p*2,L,v),g?.borderColor){let P=U(g.borderColor);e.rect(y-p,k,p*2,1,P),e.rect(y-p,k+L-1,p*2,1,P),e.rect(y-p,k,1,L,P),e.rect(y+p-1,k,1,L,P);}}}emitHline(e,t,n,r,i,o){let a=Math.round(r.priceToY(t.price,n.scale,n.bounds));a<n.bounds.top||a>n.bounds.top+n.bounds.height||e.dashedSeg(0,a,i,a,t.width??1,U(t.color??o.textColor),ps[t.lineStyle??"solid"]??null);}};function ji(s,e,t){let n=s.createShader(e);return n?(s.shaderSource(n,t),s.compileShader(n),s.getShaderParameter(n,s.COMPILE_STATUS)?n:(s.deleteShader(n),null)):null}var rc=[0,0,0,0];function qi(s){return s<0?0:s>1?1:s}function ms(s,e,t){return [s[0]+(e[0]-s[0])*t,s[1]+(e[1]-s[1])*t,s[2]+(e[2]-s[2])*t,s[3]+(e[3]-s[3])*t]}function Am(s,e){let t=1-e;return [s[0]*t,s[1]*t,s[2]*t,s[3]*t]}function ic(s,e){let t=s.series.find(n=>n.id===e);return t&&le(t)?t.points:null}var Om=new Map;function Fm(s){let e=false;for(let n of s.values())if(n.barColors&&n.barColors.length>0){e=true;break}if(!e)return Om;let t=new Map;for(let n of s.values())if(n.barColors)for(let r of n.barColors)t.set(r.time,r.color);return t}function Ji(){return {barSpacing:8,rightOffset:6}}function Ke(s){return Math.max(.5,Math.min(1e3,s))}function fs(s){if(s.length<2)return 0;let e=[];for(let t=1;t<s.length;t+=1){let n=s[t]-s[t-1];n>0&&e.push(n);}return e.length===0?0:(e.sort((t,n)=>t-n),e[Math.floor(e.length/2)])}function oc(s,e,t){let n=e.length;if(n===0)return 0;let r=e[0],i=e[n-1];if(s<=r)return t>0?(s-r)/t:0;if(s>=i)return n-1+(t>0?(s-i)/t:0);let o=0,a=n-1;for(;a-o>1;){let c=o+a>>1;e[c]<=s?o=c:a=c;}let l=e[a]-e[o];return l>0?o+(s-e[o])/l:o}function sc(s,e,t){let n=e.length;if(n===0)return 0;if(s<=0)return e[0]+(t>0?s*t:0);if(s>=n-1)return e[n-1]+(t>0?(s-(n-1))*t:0);let r=Math.floor(s),i=s-r;return e[r]+(e[r+1]-e[r])*i}var Qi=class{constructor(){this.widthPx=0;this.dataHeightPx=0;this.devicePixelRatio=1;this.viewport=Ji();this.pitchScale=1;this.times=[];this.intervalMs=0;}setSize(e,t,n){this.widthPx=e,this.dataHeightPx=t,this.devicePixelRatio=n>0?n:1;}setBars(e){this.times=e.slice(),this.intervalMs=fs(this.times);}appendBar(e){this.times.push(e),this.intervalMs<=0&&this.times.length>=2&&(this.intervalMs=fs(this.times));}setViewport(e){this.viewport=e;}getViewport(){return this.viewport}setPitchScale(e){this.pitchScale=Number.isFinite(e)&&e>0?e:1;}get spacingScale(){return this.pitchScale}pxPerBar(){return this.viewport.barSpacing*this.pitchScale}bodySpacing(){return this.viewport.barSpacing*Math.min(1,this.pitchScale)}get width(){return this.widthPx}get height(){return this.dataHeightPx}get dpr(){return this.devicePixelRatio}get barCount(){return this.times.length}get barInterval(){return this.intervalMs}get rightEdgeLogical(){return this.barCount-1+this.viewport.rightOffset}logicalToX(e){return this.widthPx-(this.rightEdgeLogical-e)*this.pxPerBar()}xToLogical(e){return this.rightEdgeLogical-(this.widthPx-e)/this.pxPerBar()}timeToLogical(e){return oc(e,this.times,this.intervalMs)}logicalToTime(e){return sc(e,this.times,this.intervalMs)}timeToX(e){return this.logicalToX(this.timeToLogical(e))}priceToY(e,t,n){if(t.log&&t.min>0&&t.max>t.min&&e>0){let o=Math.log(t.min),a=(Math.log(e)-o)/(Math.log(t.max)-o);return n.top+n.height*(t.invert?a:1-a)}let r=t.max-t.min;if(r<=0)return n.top+n.height/2;let i=(e-t.min)/r;return n.top+n.height*(t.invert?i:1-i)}yToPrice(e,t,n){if(n.height<=0)return t.min;let r=(e-n.top)/n.height,i=t.invert?r:1-r;if(t.log&&t.min>0&&t.max>t.min){let o=Math.log(t.min);return Math.exp(o+i*(Math.log(t.max)-o))}return t.min+(t.max-t.min)*i}visibleLogicalRange(){return {from:this.xToLogical(0),to:this.xToLogical(this.widthPx)}}visibleTimeRange(){let e=this.visibleLogicalRange();return {from:this.logicalToTime(e.from),to:this.logicalToTime(e.to)}}toBitmap(e){return Math.round(e*this.devicePixelRatio)}};function bs(s){return s>=3}function ac(s){return s>=2}var eo=class{constructor(e,t,n){this.onFrame=e;this.level=0;this.handle=null;this.raf=t??(r=>requestAnimationFrame(r)),this.cancel=n??(r=>cancelAnimationFrame(r));}invalidate(e){e<=0||(e>this.level&&(this.level=e),this.handle===null&&(this.handle=this.raf(()=>this.flush())));}flushNow(e){this.handle!==null&&(this.cancel(this.handle),this.handle=null),e>this.level&&(this.level=e),this.flush();}flush(){this.handle=null;let e=this.level;this.level=0,e!==0&&this.onFrame(e);}destroy(){this.handle!==null&&(this.cancel(this.handle),this.handle=null),this.level=0;}};var to=class{constructor(e,t,n,r){this.tick=e;this.handle=null;this.last=0;this.stopped=false;this.loop=()=>{let e=this.now(),t=e-this.last;this.last=e;let n=this.tick(Math.min(t,64));this.handle=n&&!this.stopped?this.raf(this.loop):null;};this.raf=t??(i=>requestAnimationFrame(i)),this.cancel=n??(i=>cancelAnimationFrame(i)),this.now=r??(()=>performance.now());}get active(){return this.handle!==null}start(){this.stopped=false,this.handle===null&&(this.last=this.now(),this.handle=this.raf(this.loop));}stop(){this.stopped=true,this.handle!==null&&(this.cancel(this.handle),this.handle=null);}};function Se(s,e,t,n){return n<=0?e:s+(e-s)*(1-Math.exp(-t/n))}var Bm=.04,Vm=60,_m=2,Nm=350,lc=8,Hm=14,zm=350,$m=30,Wm=.004,Um=.004;function Gm(s,e,t){return t?{logical:s.rightEdgeLogical,x:s.width}:{logical:s.xToLogical(e),x:e}}function Ym(s,e){return Math.abs(s)>Math.abs(e)}function Xm(s,e,t){return s+e/t}function Km(s,e,t){return Ym(s,e)?s:t?e:null}function jm(s,e){return s?"strong":e}function qm(s,e,t){return Ke(s*(t/Math.max(1,e)))}function Zm(s,e,t,n,r){return s-(e-1)+(t-n)/r}var no=class{constructor(e){this.deps=e;this.rightEdgeZoom=true;this.axisDrag=true;this.paneResize=true;this.el=null;this.dragging=false;this.moved=false;this.region="data";this.verticalPan=false;this.startX=0;this.startY=0;this.startRightOffset=0;this.startBarSpacing=0;this.lastX=0;this.lastT=0;this.vx=0;this.middleDeleted=false;this.rightCancelled=false;this.cursorX=NaN;this.cursorY=NaN;this.touches=new Map;this.lpTimer=null;this.pinchStartDist=1;this.pinchStartBarSpacing=0;this.pinchAnchorLogical=0;this.lastTapT=0;this.lastTapX=0;this.lastTapY=0;this.onTouchContextMenu=e=>{this.touches.size!==0&&(!(e.target instanceof Node)||!this.el?.contains(e.target)||(e.preventDefault(),e.stopImmediatePropagation()));};this.onMiddleGuard=e=>{e.button===1&&this.middleDeleted&&e.preventDefault();};this.onContextGuard=e=>{this.rightCancelled&&(this.rightCancelled=false,e.preventDefault(),e.stopPropagation());};this.onModifier=e=>{e.repeat||e.key!=="Shift"&&e.key!=="Control"&&e.key!=="Meta"||Number.isNaN(this.cursorX)||this.dragging&&this.region!=="drawing"||this.deps.drawingsPointerMove?.(this.cursorX,this.cursorY,this.snapMode(e),e.shiftKey);};this.onDown=e=>{if(e.button===1){let{x:i,y:o}=this.local(e);this.middleDeleted=this.deps.drawingsDeleteAt?.(i,o)??false,this.middleDeleted&&e.preventDefault();return}if(e.button===2){this.rightCancelled=this.deps.drawingsCancelPlacement?.()??false,this.rightCancelled&&e.preventDefault();return}if(e.button!==0)return;let{x:t,y:n}=this.local(e);if(e.pointerType==="touch"){if(this.touches.size===1&&this.dragging&&(this.region==="data"||this.region==="crosshair")){this.touches.set(e.pointerId,{x:t,y:n}),this.beginPinch(e);return}if(this.touches.size>=1)return;this.touches.set(e.pointerId,{x:t,y:n});}if(this.deps.drawingsClearTransient?.(),this.dragging=true,this.moved=false,this.startX=t,this.startY=n,this.deps.drawingsClaim?.(t,n)){this.region="drawing",this.deps.drawingsPointerDown?.(t,n,this.snapMode(e),e.shiftKey),this.capture(e.pointerId);return}if(e.shiftKey&&this.regionAt(t,n)==="data"&&this.deps.drawingsMeasureStart?.(t,n)){this.region="drawing",this.capture(e.pointerId);return}let r=this.deps.getCoords().getViewport();this.deps.apply(r),this.startRightOffset=r.rightOffset,this.startBarSpacing=r.barSpacing,this.region=this.regionAt(t,n),this.verticalPan=false,this.region==="price"?this.deps.beginPriceScale(t,n):this.region==="separator"?this.deps.beginPaneResize(n):this.region==="data"&&(this.verticalPan=this.deps.beginPricePan(n)),e.pointerType==="touch"&&(this.region==="data"||this.region==="price"||this.region==="time")&&this.startLongPress(t,n,this.region),this.lastX=t,this.lastT=e.timeStamp,this.vx=0,this.capture(e.pointerId);};this.onMove=e=>{let{x:t,y:n}=this.local(e);if(this.cursorX=t,this.cursorY=n,e.pointerType==="touch"&&this.touches.has(e.pointerId)&&this.touches.set(e.pointerId,{x:t,y:n}),this.dragging&&this.region==="pinch"){this.applyPinch();return}if(this.dragging&&this.region==="crosshair"){this.deps.onPointerMove(t,n);return}if(this.dragging&&this.region==="axis-sheet")return;this.lpTimer!==null&&Math.hypot(t-this.startX,n-this.startY)>lc&&this.cancelLongPress();let r=e.pointerType==="touch"?lc:_m;if(this.dragging)if(this.region==="price")Math.abs(n-this.startY)>r&&(this.moved=true),this.deps.priceScaleBy(n-this.startY);else if(this.region==="separator")Math.abs(n-this.startY)>r&&(this.moved=true),this.deps.paneResizeBy(n-this.startY);else if(this.region==="time"){Math.abs(t-this.startX)>r&&(this.moved=true);let i=Ke(this.startBarSpacing*Math.exp((this.startX-t)*Wm));this.deps.apply({barSpacing:i,rightOffset:this.startRightOffset});}else if(this.region==="drawing")(Math.abs(t-this.startX)>r||Math.abs(n-this.startY)>r)&&(this.moved=true),this.deps.drawingsPointerMove?.(t,n,this.snapMode(e),e.shiftKey);else {let i=this.deps.getCoords(),o=i.getViewport(),a=t-this.startX;Math.abs(a)>r&&(this.moved=true),this.deps.apply({barSpacing:o.barSpacing,rightOffset:this.startRightOffset-a/i.pxPerBar()}),this.verticalPan&&(Math.abs(n-this.startY)>r&&(this.moved=true),this.deps.pricePanBy(n-this.startY));let l=e.timeStamp-this.lastT;if(l>0){let c=(t-this.lastX)/l;this.vx=this.vx*.6+c*.4,this.lastX=t,this.lastT=e.timeStamp;}}else if(this.el){let i=this.deps.drawingsCursor?.(t,n),o=this.regionAt(t,n);this.el.style.cursor=i??(o==="price"?"ns-resize":o==="time"?"ew-resize":o==="separator"?"row-resize":""),this.deps.drawingsPointerMove?.(t,n,this.snapMode(e),e.shiftKey);}e.pointerType!=="touch"&&this.deps.onPointerMove(t,n);};this.onUp=e=>{if(e.pointerType==="touch"&&this.touches.delete(e.pointerId),this.cancelLongPress(),this.dragging&&this.region==="pinch"){if(this.touches.size===1){let a=[...this.touches.values()][0],l=this.deps.getCoords().getViewport();this.region="data",this.verticalPan=false,this.startX=a.x,this.startY=a.y,this.startRightOffset=l.rightOffset,this.startBarSpacing=l.barSpacing,this.lastX=a.x,this.lastT=e.timeStamp,this.vx=0;return}this.endGesture(e);return}if(this.dragging&&this.region==="crosshair"){this.deps.onPointerMove(null,null),this.endGesture(e);return}if(this.dragging&&this.region==="axis-sheet"){this.endGesture(e);return}let{x:t,y:n}=this.local(e),r=e.pointerType==="touch",i=this.dragging&&!this.moved&&(!r||Math.hypot(t-this.startX,n-this.startY)<=Hm);if(this.dragging&&this.region==="drawing")this.deps.drawingsPointerUp?.(t,n);else if(i&&this.region==="data")this.deps.onClick(t,n);else if(this.dragging&&this.region==="data"&&!(e.timeStamp-this.lastT>Vm)&&Math.abs(this.vx)>Bm){let l=this.deps.getCoords().pxPerBar();this.deps.fling(-this.vx/l);}let o=r&&i;this.endGesture(e),r&&this.deps.onPointerMove(null,null),o&&this.registerTap(e.timeStamp,t,n);};this.onCancel=e=>{e.pointerType==="touch"&&this.touches.delete(e.pointerId),this.cancelLongPress(),this.dragging&&(this.region==="drawing"&&!Number.isNaN(this.cursorX)&&this.deps.drawingsPointerUp?.(this.cursorX,this.cursorY),(this.region==="crosshair"||e.pointerType==="touch")&&this.deps.onPointerMove(null,null),this.endGesture(e));};this.onLeave=()=>{this.cursorX=NaN,this.cursorY=NaN,this.deps.onPointerMove(null,null);};this.onDblClick=e=>{let{x:t,y:n}=this.local(e);this.doubleActivate(t,n);};this.onWheel=e=>{e.preventDefault(),this.deps.drawingsClearTransient?.();let t=this.deps.getCoords(),n=t.getViewport(),r=Km(e.deltaX,e.deltaY,e.shiftKey);if(r!=null){this.deps.apply({barSpacing:n.barSpacing,rightOffset:Xm(n.rightOffset,r,t.pxPerBar())});return}let i=this.local(e).x,o=this.rightEdgeZoom&&!(e.ctrlKey||e.metaKey),a=Gm(t,i,o),l=Ke(n.barSpacing*Math.exp(-e.deltaY*Um));this.deps.zoomTo(l,a.logical,a.x);};}attach(e){this.el=e,e.style!==void 0&&(e.style.touchAction="none",e.style.userSelect="none",e.style.setProperty("-webkit-user-select","none"),e.style.setProperty("-webkit-touch-callout","none")),e.addEventListener("pointerdown",this.onDown),e.addEventListener("pointermove",this.onMove),e.addEventListener("pointerup",this.onUp),e.addEventListener("pointerleave",this.onLeave),e.addEventListener("pointercancel",this.onCancel),e.addEventListener("dblclick",this.onDblClick),e.addEventListener("wheel",this.onWheel,{passive:false}),e.addEventListener("mousedown",this.onMiddleGuard),e.addEventListener("auxclick",this.onMiddleGuard),e.addEventListener("contextmenu",this.onContextGuard);let t=e.ownerDocument?.defaultView;t?.addEventListener("keydown",this.onModifier),t?.addEventListener("keyup",this.onModifier),t?.addEventListener("contextmenu",this.onTouchContextMenu,true);}detach(){let e=this.el;if(!e)return;let t=e.ownerDocument?.defaultView;t?.removeEventListener("keydown",this.onModifier),t?.removeEventListener("keyup",this.onModifier),t?.removeEventListener("contextmenu",this.onTouchContextMenu,true),e.removeEventListener("pointerdown",this.onDown),e.removeEventListener("pointermove",this.onMove),e.removeEventListener("pointerup",this.onUp),e.removeEventListener("pointerleave",this.onLeave),e.removeEventListener("pointercancel",this.onCancel),e.removeEventListener("dblclick",this.onDblClick),e.removeEventListener("wheel",this.onWheel),e.removeEventListener("mousedown",this.onMiddleGuard),e.removeEventListener("auxclick",this.onMiddleGuard),e.removeEventListener("contextmenu",this.onContextGuard),this.cancelLongPress(),this.touches.clear(),this.el=null;}local(e){let t=this.el.getBoundingClientRect();return {x:e.clientX-t.left,y:e.clientY-t.top}}regionAt(e,t){let n=this.deps.getCoords();if(this.paneResize&&t<=n.height&&this.deps.paneSeparatorAt(t))return "separator";if(this.axisDrag){if(e>n.width&&t<=n.height)return "price";if(t>n.height&&e<=n.width)return "time"}return "data"}snapMode(e){return jm(e.ctrlKey||e.metaKey,this.deps.drawingsSnapMode?.()??"off")}startLongPress(e,t,n){this.cancelLongPress(),this.lpTimer=setTimeout(()=>{if(this.lpTimer=null,!(!this.dragging||this.region!==n)){if(n==="data"){this.region="crosshair",this.deps.onPointerMove(e,t);return}this.region="axis-sheet",this.moved=true,this.deps.onAxisLongPress?.(n,e,t);}},Nm);}cancelLongPress(){this.lpTimer!==null&&clearTimeout(this.lpTimer),this.lpTimer=null;}beginPinch(e){this.cancelLongPress(),this.region==="crosshair"&&this.deps.onPointerMove(null,null);let t=this.deps.getCoords(),n=t.getViewport();this.deps.apply(n);let[r,i]=[...this.touches.values()];this.pinchStartDist=Math.max(1,Math.hypot(r.x-i.x,r.y-i.y)),this.pinchStartBarSpacing=n.barSpacing,this.pinchAnchorLogical=t.xToLogical((r.x+i.x)/2),this.region="pinch",this.dragging=true,this.moved=true,this.vx=0,this.capture(e.pointerId);}applyPinch(){let e=this.deps.getCoords(),t=[...this.touches.values()];if(t.length<2)return;let[n,r]=t,i=qm(this.pinchStartBarSpacing,this.pinchStartDist,Math.hypot(n.x-r.x,n.y-r.y)),o=e.getViewport(),a=o.barSpacing>0?e.pxPerBar()/o.barSpacing:1,l=(n.x+r.x)/2;this.deps.apply({barSpacing:i,rightOffset:Zm(this.pinchAnchorLogical,e.barCount,e.width,l,i*a)});}capture(e){try{this.el?.setPointerCapture(e);}catch{}}registerTap(e,t,n){if(this.lastTapT>0&&e-this.lastTapT<=zm&&Math.hypot(t-this.lastTapX,n-this.lastTapY)<=$m){this.lastTapT=0,this.doubleActivate(this.lastTapX,this.lastTapY);return}this.lastTapT=e,this.lastTapX=t,this.lastTapY=n;}endGesture(e){this.dragging=false;try{this.el?.releasePointerCapture(e.pointerId);}catch{}}doubleActivate(e,t){if(this.deps.drawingsDblClick?.(e,t))return;let n=this.regionAt(e,t);n==="price"?this.deps.resetPriceScale(e,t):n==="separator"?this.deps.resetPaneSize(t):n==="time"?this.deps.resetView():this.deps.dataDblClick(e,t);}};function Jm(s){if(s.ctrlKey||s.metaKey)return null;switch(s.key){case "ArrowLeft":return s.shiftKey?{kind:"pan",bars:-10}:{kind:"step",delta:-1};case "ArrowRight":return s.altKey&&s.shiftKey?{kind:"realtime"}:s.shiftKey?{kind:"pan",bars:10}:{kind:"step",delta:1};case "+":case "=":return {kind:"zoom",direction:1};case "-":case "_":return {kind:"zoom",direction:-1};case "Home":return {kind:"edge",edge:"first"};case "End":return {kind:"edge",edge:"last"};case "0":return {kind:"reset"};case "Escape":return {kind:"clear"};default:return null}}var ro=class{constructor(e){this.deps=e;this.el=null;this.onKey=e=>{if(this.deps.preempt?.(e)){e.preventDefault();return}let t=Jm(e);if(t)switch(e.preventDefault(),t.kind){case "pan":this.deps.panByBars(t.bars);break;case "zoom":this.deps.zoomByStep(t.direction);break;case "step":this.deps.stepCrosshair(t.delta);break;case "edge":this.deps.jumpToEdge(t.edge);break;case "reset":this.deps.resetView();break;case "realtime":this.deps.scrollToRealtime();break;case "clear":this.deps.clearCrosshair();break}};}attach(e){this.el=e,e.addEventListener("keydown",this.onKey);}detach(){this.el?.removeEventListener("keydown",this.onKey),this.el=null;}};var jn=class{constructor(){this.kind="canvas2d";this.modelAlpha=1;this.candleBodyAlpha=1;this.candleStructureAlpha=1;this.gridAlpha=1;this.candleBodyScale=1;this.canvas=null;this.ctx=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}render(e,t,n){let r=this.ctx,i=this.canvas;if(!r||!i)return;let o=t.dpr,a=i.width/o,l=i.height/o,c=t.width;r.setTransform(o,0,0,o,0,0),r.clearRect(0,0,a,l);let d=t.barCount;if(d===0)return;let h=t.visibleLogicalRange(),u=Math.max(0,Math.floor(h.from)),p=Math.min(d-1,Math.ceil(h.to));if(p<u)return;let m=ef(e.indicators),f=e.orderedPanes();this.drawHighlights(r,e,t),this.drawGrid(r,e,t,n,c);for(let b of f){if(b.collapsed)continue;let g=e.orderedIndicatorsForPane(b.id),v=b.kind==="price";r.save(),r.beginPath(),r.rect(0,b.bounds.top,c,b.bounds.height),r.clip();let y=E=>{let k=e.scaleFor(E,b);return k===b.scale?b:{...b,scale:k}};r.globalAlpha=this.modelAlpha;for(let E of g)for(let k of E.backgrounds)this.drawBackground(r,k,b,t);for(let E of g)for(let k of E.fills)this.drawFill(r,E,k,y(E),t,u,p,e.offsetOf(E.id));let x=e.drawingSlices.get(b.id)??[],S=0,C=E=>{for(;S<x.length&&x[S].beforeZ<=E;S+=1)r.globalAlpha=1,r.drawImage(x[S].canvas,0,0,a,l);},T=v&&!e.candlesHidden,M=false;for(let E of g){T&&!M&&e.zOf(E.id)>=e.candleZ&&(C(e.candleZ),r.globalAlpha=this.candleStructureAlpha,this.drawPriceSeries(r,e,u,p,t,b,n,m,c),M=true),C(e.zOf(E.id)),r.globalAlpha=this.modelAlpha;let k=e.offsetOf(E.id),L=y(E);for(let P of E.series)this.drawSeries(r,P,L,t,u,p,n,k);}T&&!M&&(C(e.candleZ),r.globalAlpha=this.candleStructureAlpha,this.drawPriceSeries(r,e,u,p,t,b,n,m,c)),C(1/0),r.globalAlpha=this.modelAlpha;for(let E of g){let k=y(E);for(let L of E.priceLines)this.drawHline(r,L,k,t,c,n);}r.restore();}}destroy(){this.canvas=null,this.ctx=null;}drawPriceSeries(e,t,n,r,i,o,a,l,c){if(t.basePainting==="none")return;let d=t.bars,h=t.style;switch(t.priceStyle){case "bars":this.drawBars(e,d,n,r,i,o,h.bars.upColor??a.upColor,h.bars.downColor??a.downColor,l);return;case "line":this.drawPriceLine(e,d,n,r,i,o,h.line.color??a.upColor,h.line.width);return;case "area":{let u=h.area.lineColor??a.upColor;this.drawPriceArea(e,d,n,r,i,o,h.area.topColor??u,h.area.bottomColor??"rgba(0,0,0,0)"),this.drawPriceLine(e,d,n,r,i,o,u,h.area.width);return}case "baseline":this.drawBaseline(e,d,n,r,i,o,t,a,c);return;default:this.drawCandles(e,t,d,n,r,i,o,a,l);}}drawBars(e,t,n,r,i,o,a,l,c){let d=i.bodySpacing(),h=rn(d);if(h==="aggregate"){this.drawCandlesAggregated(e,t,n,r,i,o,a,l,c);return}let u=Math.max(1,Math.round(d*.35)),p=h==="full";e.lineWidth=1;for(let m=n;m<=r;m+=1){let f=t[m];if(!f||f.high<=f.low)continue;let b=Math.round(i.logicalToX(m))+.5,g=c.get(f.time)??(f.close>=f.open?a:l),v=i.priceToY(f.high,o.scale,o.bounds),y=i.priceToY(f.low,o.scale,o.bounds);if(e.strokeStyle=g,e.beginPath(),e.moveTo(b,v),e.lineTo(b,y),p){let x=i.priceToY(f.open,o.scale,o.bounds),S=i.priceToY(f.close,o.scale,o.bounds);e.moveTo(b-u,x),e.lineTo(b,x),e.moveTo(b,S),e.lineTo(b+u,S);}e.stroke();}}drawPriceLine(e,t,n,r,i,o,a,l){e.lineWidth=l,e.lineJoin="round",e.lineCap="round",e.strokeStyle=a,e.beginPath();let c=false;for(let d=Math.max(0,n-1);d<=r;d+=1){let h=t[d];if(!h){c=false;continue}let u=i.logicalToX(d),p=i.priceToY(h.close,o.scale,o.bounds);c?e.lineTo(u,p):(e.moveTo(u,p),c=true);}e.stroke(),e.lineCap="butt";}drawPriceArea(e,t,n,r,i,o,a,l){let c=o.bounds.top+o.bounds.height,d=[],h=1/0;for(let p=Math.max(0,n-1);p<=r;p+=1){let m=t[p];if(!m)continue;let f=i.logicalToX(p),b=i.priceToY(m.close,o.scale,o.bounds);d.push({x:f,y:b}),b<h&&(h=b);}if(d.length<2)return;let u=e.createLinearGradient(0,h,0,c);u.addColorStop(0,a),u.addColorStop(1,l),e.fillStyle=u,e.beginPath(),e.moveTo(d[0].x,c);for(let p of d)e.lineTo(p.x,p.y);e.lineTo(d[d.length-1].x,c),e.closePath(),e.fill();}drawBaseline(e,t,n,r,i,o,a,l,c){let d=a.baselinePriceFor(o.scale),h=i.priceToY(d,o.scale,o.bounds),u=o.bounds.top,p=o.bounds.top+o.bounds.height,m=a.style.baseline,f=m.topLineColor??Qt,b=m.bottomLineColor??en,g=m.topFillColor??W(f,Ye),v=m.topFillColor2??W(f,Xe),y=m.bottomFillColor??W(b,Ye),x=m.bottomFillColor2??W(b,Xe),S=[];for(let M=Math.max(0,n-1);M<=r;M+=1){let E=t[M];E&&S.push({x:i.logicalToX(M),y:i.priceToY(E.close,o.scale,o.bounds)});}if(S.length<2)return;let C=()=>{e.beginPath(),e.moveTo(S[0].x,h);for(let M of S)e.lineTo(M.x,M.y);e.lineTo(S[S.length-1].x,h),e.closePath();};if(h>u){e.save(),e.beginPath(),e.rect(0,u,c,h-u),e.clip();let M=e.createLinearGradient(0,u,0,h);M.addColorStop(0,g),M.addColorStop(1,v),e.fillStyle=M,C(),e.fill(),e.restore();}if(h<p){e.save(),e.beginPath(),e.rect(0,h,c,p-h),e.clip();let M=e.createLinearGradient(0,h,0,p);M.addColorStop(0,x),M.addColorStop(1,y),e.fillStyle=M,C(),e.fill(),e.restore();}e.strokeStyle=a.style.borderColor??l.borderColor,e.lineWidth=1,sn(e,"dashed"),e.beginPath(),e.moveTo(0,Math.round(h)+.5),e.lineTo(c,Math.round(h)+.5),e.stroke(),sn(e,"solid"),e.lineWidth=m.width,e.lineJoin="round",e.lineCap="round";let T=(M,E,k,L,P)=>{e.strokeStyle=P,e.beginPath(),e.moveTo(M,E),e.lineTo(k,L),e.stroke();};for(let M=1;M<S.length;M+=1){let E=S[M-1],k=S[M],L=E.y<=h,P=k.y<=h;if(L!==P&&k.y!==E.y){let V=(h-E.y)/(k.y-E.y),G=E.x+(k.x-E.x)*V;T(E.x,E.y,G,h,L?f:b),T(G,h,k.x,k.y,P?f:b);}else T(E.x,E.y,k.x,k.y,L?f:b);}e.lineCap="butt";}drawCandles(e,t,n,r,i,o,a,l,c){let d=o.bodySpacing(),h=rn(d),u=Ui(t.style.candle,t.candleOverride,l.upColor,l.downColor);if(h==="aggregate"){this.drawCandlesAggregated(e,n,r,i,o,a,u.up,u.down,c);return}let p=h==="full",m=u.candle,f=this.candleStructureAlpha>this.candleBodyAlpha+.001;for(let b=r;b<=i;b+=1){let g=n[b];if(!g||g.high<=g.low)continue;let v=Ki(o.logicalToX(b),d,o.dpr,this.candleBodyScale),y=v.center,x=g.close>=g.open,S=x?u.up:u.down,C=c.get(g.time),T=C??S,M=0,E=0;if(p){let k=o.priceToY(g.open,a.scale,a.bounds),L=o.priceToY(g.close,a.scale,a.bounds);M=Math.min(k,L),E=Math.max(1,Math.abs(L-k));}if(m.wickVisible){let k=(x?m.wickUpColor:m.wickDownColor)??(p?S:T),L=o.priceToY(g.high,a.scale,a.bounds),P=o.priceToY(g.low,a.scale,a.bounds);e.globalAlpha=this.candleStructureAlpha,e.strokeStyle=k,e.lineWidth=v.wickW,e.beginPath(),p?(e.moveTo(y,L),e.lineTo(y,M),e.moveTo(y,M+E),e.lineTo(y,P)):(e.moveTo(y,L),e.lineTo(y,P)),e.stroke();}if(p&&(m.bodyVisible&&(e.globalAlpha=this.candleBodyAlpha,e.fillStyle=T,e.fillRect(v.bodyX,M,v.bodyW,E)),m.borderVisible||C||f&&m.bodyVisible)){e.globalAlpha=this.candleStructureAlpha,e.strokeStyle=m.borderVisible||C?(x?m.borderUpColor:m.borderDownColor)??S:T,e.lineWidth=1;let k=Math.max(0,v.bodyW-1),L=Math.max(0,E-1);e.strokeRect(v.bodyX+.5,M+.5,k,L);}}}drawCandlesAggregated(e,t,n,r,i,o,a,l,c){let d=NaN,h=1/0,u=-1/0,p=0,m=0,f=0,b=false,g=()=>{if(!b)return;let v=c.get(f)??(m>=p?a:l),y=i.priceToY(u,o.scale,o.bounds),x=i.priceToY(h,o.scale,o.bounds);e.strokeStyle=v,e.lineWidth=1,e.beginPath(),e.moveTo(d,y),e.lineTo(d,x),e.stroke();};for(let v=n;v<=r;v+=1){let y=t[v];if(!y||y.high<=y.low)continue;let x=Math.round(i.logicalToX(v))+.5;!b||x!==d?(g(),d=x,h=y.low,u=y.high,p=y.open,f=y.time,b=true):(y.low<h&&(h=y.low),y.high>u&&(u=y.high)),m=y.close;}g();}drawSeries(e,t,n,r,i,o,a,l=0){if(t.kind==="candle"||t.kind==="bar"){this.drawPlotCandles(e,t,n,r,i,o,a,l);return}if(!(!le(t)||t.visible===false))switch(t.kind){case "histogram":case "columns":this.drawHistogram(e,t,n,r,i,o,l);break;case "area":this.drawArea(e,t,n,r,i,o,l),this.drawPolyline(e,t,n,r,i,o,false,l);break;case "circles":case "cross":this.drawPointMarkers(e,t,n,r,i,o,l);break;case "step":this.drawPolyline(e,t,n,r,i,o,true,l);break;default:this.drawPolyline(e,t,n,r,i,o,false,l);}}drawPolyline(e,t,n,r,i,o,a,l=0){e.lineWidth=Math.max(1,t.style.width),e.lineJoin="round",sn(e,t.style.lineStyle);let c=0,d=0,h=false;for(let u=Math.max(1,i-1);u<=o;u+=1){let p=t.points[u-l],m=t.points[u-1-l];if(!p||p.value===null||!m||m.value===null){h=false;continue}let f=r.logicalToX(u),b=r.priceToY(p.value,n.scale,n.bounds);h||(c=r.logicalToX(u-1),d=r.priceToY(m.value,n.scale,n.bounds)),e.strokeStyle=p.color??t.style.color,e.beginPath(),e.moveTo(c,d),a&&e.lineTo(f,d),e.lineTo(f,b),e.stroke(),c=f,d=b,h=true;}sn(e,"solid");}drawArea(e,t,n,r,i,o,a=0){let l=n.bounds.top+n.bounds.height,c=[],d=1/0,h=()=>{if(c.length===0)return;let u=e.createLinearGradient(0,d,0,l);u.addColorStop(0,t.style.color),u.addColorStop(1,"rgba(0,0,0,0)"),e.fillStyle=u,e.beginPath(),e.moveTo(c[0].x,l);for(let p of c)e.lineTo(p.x,p.y);e.lineTo(c[c.length-1].x,l),e.closePath(),e.fill(),c=[],d=1/0;};for(let u=i;u<=o;u+=1){let p=t.points[u-a];if(!p||p.value===null){h();continue}let m=r.logicalToX(u),f=r.priceToY(p.value,n.scale,n.bounds);c.push({x:m,y:f}),f<d&&(d=f);}h();}drawHistogram(e,t,n,r,i,o,a=0){let l=r.bodySpacing(),c=Math.max(1,(t.kind==="columns"?.7:.8)*l),d=c/2,h=t.style.base??0,u=r.priceToY(h,n.scale,n.bounds);for(let p=i;p<=o;p+=1){let m=t.points[p-a];if(!m||m.value===null)continue;let f=r.logicalToX(p),b=r.priceToY(m.value,n.scale,n.bounds);e.fillStyle=m.color??t.style.color,e.fillRect(f-d,Math.min(u,b),c,Math.max(1,Math.abs(b-u)));}}drawPointMarkers(e,t,n,r,i,o,a=0){let l=Math.max(1.5,t.style.width);for(let c=i;c<=o;c+=1){let d=t.points[c-a];if(!d||d.value===null)continue;let h=r.logicalToX(c),u=r.priceToY(d.value,n.scale,n.bounds);e.strokeStyle=d.color??t.style.color,e.fillStyle=d.color??t.style.color,t.kind==="cross"?(e.lineWidth=1,e.beginPath(),e.moveTo(h-l,u),e.lineTo(h+l,u),e.moveTo(h,u-l),e.lineTo(h,u+l),e.stroke()):(e.beginPath(),e.arc(h,u,l,0,Math.PI*2),e.fill());}}drawPlotCandles(e,t,n,r,i,o,a,l=0){let c=r.bodySpacing(),d=t.style?.up??a.upColor,h=t.style?.down??a.downColor,u=t.kind==="bar",p=Math.max(.5,Math.floor(c*.7)/2),m=Math.max(1,Math.round(c*.35));for(let f=i;f<=o;f+=1){let b=t.bars[f-l];if(!b)continue;let g=t.barColors?.[f-l],v=g?.color??(b.close>=b.open?d:h),y=Math.round(r.logicalToX(f))+.5,x=r.priceToY(b.high,n.scale,n.bounds),S=r.priceToY(b.low,n.scale,n.bounds),C=r.priceToY(b.open,n.scale,n.bounds),T=r.priceToY(b.close,n.scale,n.bounds);if(u){e.strokeStyle=v,e.lineWidth=1,e.beginPath(),e.moveTo(y,x),e.lineTo(y,S),e.moveTo(y-m,C),e.lineTo(y,C),e.moveTo(y,T),e.lineTo(y+m,T),e.stroke();continue}e.strokeStyle=g?.wickColor??v,e.lineWidth=Xn(c),e.beginPath(),e.moveTo(y,x),e.lineTo(y,S),e.stroke(),e.fillStyle=v,e.fillRect(y-p,Math.min(C,T),p*2,Math.max(1,Math.abs(T-C))),g?.borderColor&&(e.strokeStyle=g.borderColor,e.strokeRect(y-p,Math.min(C,T),p*2,Math.max(1,Math.abs(T-C))));}}drawFill(e,t,n,r,i,o,a,l=0){let c=cc(t,n.fromSeriesId),d=cc(t,n.toSeriesId);if(!c||!d)return;let h=NaN,u=NaN,p="",m="",f=null;for(let b=Math.max(1,o);b<=a;b+=1){let g=c[b-1-l],v=d[b-1-l],y=c[b-l],x=d[b-l];if(!g||!v||!y||!x||g.value===null||v.value===null||y.value===null||x.value===null)continue;let S=i.logicalToX(b-1),C=i.logicalToX(b),T=i.priceToY(g.value,r.scale,r.bounds),M=i.priceToY(v.value,r.scale,r.bounds),E=i.priceToY(y.value,r.scale,r.bounds),k=i.priceToY(x.value,r.scale,r.bounds),L=n.gradient?.[b-1-l];if(L){let P=i.priceToY(L.topValue,r.scale,r.bounds),V=i.priceToY(L.bottomValue,r.scale,r.bounds),G=V===P?P+1:V;(!f||P!==h||G!==u||L.topColor!==p||L.bottomColor!==m)&&(f=e.createLinearGradient(0,P,0,G),f.addColorStop(0,L.topColor),f.addColorStop(1,L.bottomColor),h=P,u=G,p=L.topColor,m=L.bottomColor),e.fillStyle=f;}else {let P=n.colors?n.colors[b-1-l]:n.color;if(!P)continue;e.fillStyle=P;}e.beginPath(),e.moveTo(S,T),e.lineTo(C,E),e.lineTo(C,k),e.lineTo(S,M),e.closePath(),e.fill();}}drawBackground(e,t,n,r){let i=r.timeToX(t.from),o=r.timeToX(t.to);o<0||i>r.width||o<=i||(e.fillStyle=t.color,e.fillRect(i,n.bounds.top,o-i,n.bounds.height));}drawHighlights(e,t,n){if(t.highlights.length!==0)for(let r of t.highlights){let i=n.timeToX(r.from),o=n.timeToX(r.to);if(o<0||i>n.width||o<=i)continue;let a=Math.max(0,i),l=Math.min(n.width,o)-a;l<=0||(e.fillStyle=r.color,e.fillRect(a,0,l,n.height));}}drawHline(e,t,n,r,i,o){let a=Math.round(r.priceToY(t.price,n.scale,n.bounds))+.5;a<n.bounds.top||a>n.bounds.top+n.bounds.height||(e.strokeStyle=t.color??o.textColor,e.lineWidth=t.width??1,sn(e,t.lineStyle??"solid"),e.beginPath(),e.moveTo(0,a),e.lineTo(i,a),e.stroke(),sn(e,"solid"));}drawGrid(e,t,n,r,i){let o=t.orderedPanes(),{gridVert:a,gridHorz:l}=t.style,c=a.color??r.gridColor,d=l.color??r.gridColor;if(e.lineWidth=1,t.showGrid&&a.visible){e.globalAlpha=this.gridAlpha,e.strokeStyle=c;let h=n.visibleTimeRange(),u=Rt((h.from+h.to)/2,t.timezone);e.beginPath();for(let p of Jt(h.from,h.to,8,u)){let m=Math.round(n.timeToX(p.time))+.5;m<0||m>i||(e.moveTo(m,0),e.lineTo(m,n.height));}e.stroke();}for(let h of o)if(t.showGrid&&l.visible&&!h.collapsed){e.globalAlpha=this.gridAlpha,e.strokeStyle=d;let u=Ee(t,h);e.beginPath();for(let p of kt(h.scale,h.bounds.height,u)){let m=Math.round(n.priceToY(p.price,h.scale,h.bounds))+.5;m<h.bounds.top||m>h.bounds.top+h.bounds.height||(e.moveTo(0,m),e.lineTo(i,m));}e.stroke();}e.globalAlpha=1;}};function sn(s,e){e==="dashed"?s.setLineDash([6,4]):e==="dotted"?s.setLineDash([2,3]):s.setLineDash([]);}function cc(s,e){let t=s.series.find(n=>n.id===e);return t&&le(t)?t.points:null}var Qm=new Map;function ef(s){let e=false;for(let n of s.values())if(n.barColors&&n.barColors.length>0){e=true;break}if(!e)return Qm;let t=new Map;for(let n of s.values())if(n.barColors)for(let r of n.barColors)t.set(r.time,r.color);return t}function Dt(s,e){let t=Math.max(1,e);return s==="dotted"?[t,t*2]:s==="dashed"?[t*4,t*3]:[]}function an(s,e,t,n,r,i,o){if(r==="none")return [s,e,t,n];let a=t-s,l=r==="left"||r==="both",c=r==="right"||r==="both";if(Math.abs(a)<1e-6){if(l&&c)return [s,0,t,o];let m=n>=e;return c?m?[s,e,t,o]:[s,e,t,0]:m?[s,0,t,n]:[s,o,t,n]}let d=(n-e)/a,h=m=>e+d*(m-s),u=l?-2:Math.min(s,t),p=c?i+2:Math.max(s,t);return [u,h(u),p,h(p)]}function tf(s){let e=s.trim(),t=/^#([0-9a-f]{3})$/i.exec(e);if(t){let n=t[1];return {r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:1}}if(t=/^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(e),t){let n=t[1];return {r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:t[2]?parseInt(t[2],16)/255:1}}if(t=/^rgba?\(([^)]+)\)$/i.exec(e),t){let n=t[1].split(",").map(r=>parseFloat(r.trim()));return {r:n[0]??0,g:n[1]??0,b:n[2]??0,a:n[3]??1}}return null}function nf(s,e,t){return (.299*s+.587*e+.114*t)/255}function ge(s){if(!s)return "#000000";let e=tf(s);return e?nf(e.r,e.g,e.b)>.55?"#000000":"#ffffff":"#000000"}function Ve(s){return Math.round(s*1.4)}var At=5,Ot=3;function ce(s){switch(s){case "tiny":return 10;case "small":return 12;case "large":return 18;case "huge":return 28;case "normal":return 14;default:return 0}}function dc(s,e,t,n){let r=1;for(let l of s)l.length>r&&(r=l.length);let i=n?.62:.55,o=e*.9/(r*i),a=t*.85/(s.length*1.3);return Math.max(6,Math.min(o,a,48))}var rf={lines:[],boxes:[],labels:[],polylines:[],linefills:[]};function hc(s){return s==="auto"?12:ce(s)}var io=class{constructor(e,t=rf){this.deps=e;this.set=t;this.widthCache=new Map;this.indexOffset=0;}setSet(e,t=0){this.set=e,this.indexOffset=t;}setDeps(e){this.deps=e;}isEmpty(){let e=this.set;return !e.lines.length&&!e.boxes.length&&!e.labels.length&&!e.polylines.length&&!e.linefills.length}render(e,t,n,r,i){this.isEmpty()||(e.save(),this.drawLinefills(e,t,n,r,i),this.drawBoxes(e,t,n,r,i),this.drawPolylines(e,t,r,i),this.drawLines(e,t,n,r,i),this.drawLabels(e,t,n,r,i),e.restore());}priceRange(e,t){let n=Math.min(e,t),r=Math.max(e,t),i=(h,u,p)=>p!=="none"?true:Math.max(h,u)>=n&&Math.min(h,u)<=r,o=1/0,a=-1/0,l=h=>{h<o&&(o=h),h>a&&(a=h);};for(let h of this.set.lines)h.invisible||i(this.logicalOf(h.xloc,h.x1),this.logicalOf(h.xloc,h.x2),h.extend)&&(l(h.y1),l(h.y2));for(let h of this.set.boxes)!h.bgColor&&!(h.borderColor&&h.borderWidth>0)&&!h.text||i(this.logicalOf(h.xloc,h.left),this.logicalOf(h.xloc,h.right),h.extend)&&(l(h.top),l(h.bottom));for(let h of this.set.linefills){if(!h.color)continue;let u=[h.line1.x1,h.line1.x2,h.line2.x1,h.line2.x2].map((m,f)=>this.logicalOf(f<2?h.line1.xloc:h.line2.xloc,m)),p=h.line1.extend!=="none"||h.line2.extend!=="none"?"both":"none";i(Math.min(...u),Math.max(...u),p)&&(l(h.line1.y1),l(h.line1.y2),l(h.line2.y1),l(h.line2.y2));}for(let h of this.set.polylines){if(h.points.length<2)continue;let u=h.points.map(p=>this.logicalOf(p.xloc,p.x));if(i(Math.min(...u),Math.max(...u),"none"))for(let p of h.points)l(p.price);}let c=0,d=0;for(let h of this.set.labels){let u=this.logicalOf(h.xloc,h.x);if(!i(u,u,"none"))continue;if(h.yloc==="price"){l(h.y);continue}if(h.yloc==="top"||h.yloc==="bottom")continue;let p=this.deps.barAt(u);if(!p)continue;l(h.yloc==="abovebar"?p.high:p.low);let m=hc(h.size),f=Math.max(1,(h.text??"").split(`
81
81
  `).length),b=this.isPointShape(h.style)?14+Math.max(4,m*.6)+2:14+m*1.25*f+8+7;h.yloc==="abovebar"?c=Math.max(c,b):d=Math.max(d,b);}return !Number.isFinite(o)||!Number.isFinite(a)?null:{min:o,max:a,aboveMargin:c,belowMargin:d}}logicalOf(e,t){return e==="bar_time"?this.deps.timeToLogical(t):t+this.indexOffset}drawLines(e,t,n,r,i){for(let o of this.set.lines){if(o.invisible)continue;let a=r(this.logicalOf(o.xloc,o.x1)),l=r(this.logicalOf(o.xloc,o.x2)),c=i(o.y1),d=i(o.y2);if(c===null||d===null)continue;let h=o.extend==="left"||o.extend==="both",u=o.extend==="right"||o.extend==="both";if(!h&&!u&&(Math.max(a,l)<0||Math.min(a,l)>t))continue;let[p,m,f,b]=an(a,c,l,d,o.extend,t,n),g=o.color??this.deps.theme.textColor;e.beginPath(),e.moveTo(p,m),e.lineTo(f,b),e.strokeStyle=g,e.lineWidth=o.width,e.setLineDash(Dt(o.style,o.width)),e.stroke(),e.setLineDash([]);let v=l>=a;if(o.arrowRight){let y=(v?u:h)?v?[f,b]:[p,m]:[l,d];this.drawArrow(e,y[0],y[1],a,c,o.width,g);}if(o.arrowLeft){let y=(v?h:u)?v?[p,m]:[f,b]:[a,c];this.drawArrow(e,y[0],y[1],l,d,o.width,g);}}}drawArrow(e,t,n,r,i,o,a){let l=Math.atan2(n-i,t-r),c=6+o*2,d=.45;e.beginPath(),e.moveTo(t,n),e.lineTo(t-c*Math.cos(l-d),n-c*Math.sin(l-d)),e.lineTo(t-c*Math.cos(l+d),n-c*Math.sin(l+d)),e.closePath(),e.fillStyle=a,e.fill();}drawLinefills(e,t,n,r,i){for(let o of this.set.linefills){if(!o.color)continue;let a=this.resolveLine(o.line1,t,n,r,i),l=this.resolveLine(o.line2,t,n,r,i);if(!a||!l)continue;let c=u=>u[0]>u[2]||u[0]===u[2]&&u[1]>u[3]?[u[2],u[3],u[0],u[1]]:u,d=c(a),h=c(l);e.beginPath(),e.moveTo(d[0],d[1]),e.lineTo(d[2],d[3]),e.lineTo(h[2],h[3]),e.lineTo(h[0],h[1]),e.closePath(),e.fillStyle=o.color,e.fill();}}resolveLine(e,t,n,r,i){let o=r(this.logicalOf(e.xloc,e.x1)),a=r(this.logicalOf(e.xloc,e.x2)),l=i(e.y1),c=i(e.y2);return l===null||c===null?null:an(o,l,a,c,e.extend,t,n)}drawPolylines(e,t,n,r){for(let i of this.set.polylines){let o=[];for(let c of i.points){let d=r(c.price);d!==null&&o.push([n(this.logicalOf(c.xloc,c.x)),d]);}if(o.length<2)continue;let a=1/0,l=-1/0;for(let c of o)c[0]<a&&(a=c[0]),c[0]>l&&(l=c[0]);if(!(l<0||a>t)){if(e.beginPath(),i.curved)this.curvedPath(e,o,i.closed);else {e.moveTo(o[0][0],o[0][1]);for(let c=1;c<o.length;c+=1)e.lineTo(o[c][0],o[c][1]);}if(i.closed&&e.closePath(),i.fillColor&&(e.fillStyle=i.fillColor,e.fill()),i.lineColor&&(e.strokeStyle=i.lineColor,e.lineWidth=i.lineWidth,e.setLineDash(Dt(i.lineStyle,i.lineWidth)),e.stroke(),e.setLineDash([]),i.arrowLeft||i.arrowRight)){let c=i.closed?o.length:o.length-1;for(let d=0;d<c;d+=1){let h=o[d],u=o[(d+1)%o.length];i.arrowRight&&this.drawArrow(e,u[0],u[1],h[0],h[1],i.lineWidth,i.lineColor),i.arrowLeft&&this.drawArrow(e,h[0],h[1],u[0],u[1],i.lineWidth,i.lineColor);}}}}}curvedPath(e,t,n){let r=t.length,i=a=>n?t[(a%r+r)%r]:t[Math.max(0,Math.min(r-1,a))];e.moveTo(t[0][0],t[0][1]);let o=n?r:r-1;for(let a=0;a<o;a+=1){let l=i(a-1),c=i(a),d=i(a+1),h=i(a+2),u=c[0]+(d[0]-l[0])/6,p=c[1]+(d[1]-l[1])/6,m=d[0]-(h[0]-c[0])/6,f=d[1]-(h[1]-c[1])/6;e.bezierCurveTo(u,p,m,f,d[0],d[1]);}}drawBoxes(e,t,n,r,i){for(let o of this.set.boxes){let a=r(this.logicalOf(o.xloc,o.left)),l=r(this.logicalOf(o.xloc,o.right));(o.extend==="left"||o.extend==="both")&&(a=-2),(o.extend==="right"||o.extend==="both")&&(l=t+2);let c=i(o.top),d=i(o.bottom);if(c===null||d===null)continue;let h=Math.min(a,l),u=Math.max(a,l),p=Math.min(c,d),m=Math.max(c,d),f=u-h,b=m-p;u<0||h>t||m<0||p>n||(o.bgColor&&(e.fillStyle=o.bgColor,e.fillRect(h,p,f,b)),o.borderColor&&o.borderWidth>0&&(e.strokeStyle=o.borderColor,e.lineWidth=o.borderWidth,e.setLineDash(Dt(o.borderStyle,o.borderWidth)),e.strokeRect(h,p,f,b),e.setLineDash([])),o.text&&this.drawBoxText(e,o,h,p,f,b));}}measure(e,t,n){let r=`${t} ${n}`,i=this.widthCache.get(r);return i===void 0&&(e.font=t,i=e.measureText(n).width,this.widthCache.set(r,i)),i}wrapText(e,t,n,r){let i=[];for(let o of n.split(`
82
82
  `)){if(this.measure(e,t,o)<=r){i.push(o);continue}let a="";for(let l of o.split(/(\s+)/)){let c=a+l;a&&this.measure(e,t,c)>r?(i.push(a.trimEnd()),a=l.trimStart()):a=c;}a.trim()&&i.push(a.trimEnd());}return i}drawBoxText(e,t,n,r,i,o){let a=t.text,l=t.fontFamily==="monospace"?"monospace":this.deps.theme.fontFamily||"sans-serif",c=`${t.italic?"italic ":""}${t.bold?"bold ":""}`,d=4,h=ce(t.textSize),u;if(h===0){let g=`${c}14px ${l}`;u=t.wrap?this.wrapText(e,g,a,Math.max(1,i-d*2)):a.split(`
83
- `),h=cc(u,i,o,t.bold);}else {let g=`${c}${h}px ${l}`;u=t.wrap?this.wrapText(e,g,a,Math.max(1,i-d*2)):a.split(`
84
- `);}e.font=`${c}${h}px ${l}`,e.fillStyle=t.textColor??be(t.bgColor);let p=h*1.3,m=p*u.length,f;t.hAlign==="left"?(e.textAlign="left",f=n+d):t.hAlign==="right"?(e.textAlign="right",f=n+i-d):(e.textAlign="center",f=n+i/2),e.textBaseline="top";let b;t.vAlign==="top"?b=r+d:t.vAlign==="bottom"?b=r+o-d-m:b=r+(o-m)/2,e.save(),e.beginPath(),e.rect(n,r,i,o),e.clip();for(let g=0;g<u.length;g+=1)e.fillText(u[g],f,b+g*p);e.restore();}drawLabels(e,t,n,r,i){for(let o of this.set.labels){let a=r(this.logicalOf(o.xloc,o.x));if(a<-50||a>t+50)continue;let l;if(o.yloc==="price")l=i(o.y);else if(o.yloc==="top")l=14;else if(o.yloc==="bottom")l=n-14;else {let h=this.deps.barAt(this.logicalOf(o.xloc,o.x));if(!h)continue;let u=i(o.yloc==="abovebar"?h.high:h.low);l=u===null?null:u+(o.yloc==="abovebar"?-14:14);}if(l===null)continue;let c=o.color??this.deps.theme.textColor,d=dc(o.size);this.isPointShape(o.style)?(o.noFill||this.drawLabelShape(e,o.style,a,l,d,c),o.text&&this.drawLabelText(e,o,a,l+d,d)):o.style==="none"||o.style==="text_outline"||o.noFill?o.text&&this.drawLabelText(e,o,a,l,d,o.style==="text_outline"):this.drawBubble(e,o,a,l,d,c);}}isPointShape(e){switch(e){case "circle":case "square":case "diamond":case "flag":case "arrowup":case "arrowdown":case "triangleup":case "triangledown":case "cross":case "xcross":return true;default:return false}}drawLabelText(e,t,n,r,i,o=false){let a=t.fontFamily==="monospace"?"monospace":this.deps.theme.fontFamily||"sans-serif";e.font=`${i}px ${a}`,e.textAlign=t.textAlign==="left"?"left":t.textAlign==="right"?"right":"center",e.textBaseline="middle";let l=t.text.split(`
85
- `),c=i*1.25,d=r-c*(l.length-1)/2;if(o){e.lineWidth=3,e.strokeStyle=be(t.textColor??this.deps.theme.textColor);for(let h=0;h<l.length;h+=1)e.strokeText(l[h],n,d+h*c);}e.fillStyle=t.textColor??this.deps.theme.textColor;for(let h=0;h<l.length;h+=1)e.fillText(l[h],n,d+h*c);}drawLabelShape(e,t,n,r,i,o){let a=Math.max(4,i*.6);switch(e.fillStyle=o,e.strokeStyle=o,e.lineWidth=Math.max(1,a*.3),e.beginPath(),t){case "circle":e.arc(n,r,a,0,Math.PI*2),e.fill();break;case "square":e.fillRect(n-a,r-a,a*2,a*2);break;case "diamond":e.moveTo(n,r-a),e.lineTo(n+a,r),e.lineTo(n,r+a),e.lineTo(n-a,r),e.closePath(),e.fill();break;case "triangleup":case "arrowup":e.moveTo(n,r-a),e.lineTo(n+a,r+a),e.lineTo(n-a,r+a),e.closePath(),e.fill();break;case "triangledown":case "arrowdown":e.moveTo(n,r+a),e.lineTo(n+a,r-a),e.lineTo(n-a,r-a),e.closePath(),e.fill();break;case "flag":e.moveTo(n-a*.7,r-a),e.lineTo(n-a*.7,r+a),e.moveTo(n-a*.7,r-a),e.lineTo(n+a,r-a*.4),e.lineTo(n-a*.7,r+a*.2),e.stroke(),e.fill();break;case "cross":e.moveTo(n,r-a),e.lineTo(n,r+a),e.moveTo(n-a,r),e.lineTo(n+a,r),e.stroke();break;case "xcross":e.moveTo(n-a,r-a),e.lineTo(n+a,r+a),e.moveTo(n+a,r-a),e.lineTo(n-a,r+a),e.stroke();break;default:e.arc(n,r,a,0,Math.PI*2),e.fill();}}drawBubble(e,t,n,r,i,o){let a=t.fontFamily==="monospace"?"monospace":this.deps.theme.fontFamily||"sans-serif";e.font=`${i}px ${a}`;let l=(t.text??"").split(`
86
- `),c=6,d=4,h=i*1.25,p=Math.max(1,...l.map(y=>this.measure(e,e.font,y)))+c*2,m=h*l.length+d*2,f=7,b=n-p/2,g=r-m-f,v="down";switch(t.style){case "label_up":b=n-p/2,g=r+f,v="up";break;case "label_left":b=n+f,g=r-m/2,v="left";break;case "label_right":b=n-p-f,g=r-m/2,v="right";break;case "label_center":b=n-p/2,g=r-m/2,v="none";break;case "label_lower_left":b=n+f,g=r-m-f,v="none";break;case "label_lower_right":b=n-p-f,g=r-m-f,v="none";break;case "label_upper_left":b=n+f,g=r+f,v="none";break;case "label_upper_right":b=n-p-f,g=r+f,v="none";break;default:b=n-p/2,g=r-m-f,v="down";}if(e.fillStyle=o,this.roundRect(e,b,g,p,m,4),e.fill(),v!=="none"&&(e.beginPath(),v==="down"?(e.moveTo(n-f,g+m),e.lineTo(n+f,g+m),e.lineTo(n,r)):v==="up"?(e.moveTo(n-f,g),e.lineTo(n+f,g),e.lineTo(n,r)):v==="left"?(e.moveTo(b,r-f),e.lineTo(b,r+f),e.lineTo(n,r)):(e.moveTo(b+p,r-f),e.lineTo(b+p,r+f),e.lineTo(n,r)),e.closePath(),e.fill()),t.text){e.fillStyle=t.textColor??be(o),e.textAlign="center",e.textBaseline="middle";let y=g+d+h/2;for(let x=0;x<l.length;x+=1)e.fillText(l[x],b+p/2,y+x*h);}}roundRect(e,t,n,r,i,o){let a=Math.min(o,r/2,i/2);e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath();}};function hc(s,e){return e===0?s:s+64+(e-1)*56}var io=class{constructor(){this.canvas=null;this.ctx=null;this.axisTextColor=Be.textColor;this.drawScene=new ro({timeToLogical:()=>0,barAt:()=>null,theme:{}});}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}prepare(e,t,n){this.drawScene.setDeps({timeToLogical:r=>t.timeToLogical(r),barAt:r=>{let i=e.bars[Math.round(r)];return i?{high:i.high,low:i.low}:null},theme:n});}paneDrawingsRange(e,t,n,r){let i=null;for(let o of e)i=uc(i,this.drawingsRange(this.ownDrawings(o),r,t.offsetOf(o.id)));if(n)for(let o of t.indicators.values())i=uc(i,this.drawingsRange(this.overlayDrawings(o),r,t.offsetOf(o.id)));return i}render(e,t,n,r){let i=this.ctx,o=this.canvas;if(!i||!o)return;let a=t.dpr,l=o.width/a,c=o.height/a,d=t.width,h=t.height;if(this.axisTextColor=r?.textColor??n.textColor,i.setTransform(a,0,0,a,0,0),i.clearRect(0,0,l,c),r&&(l>d||c>h)&&(i.fillStyle=r.background,l>d&&i.fillRect(d,0,l-d,c),c>h&&i.fillRect(0,h,d,c-h)),i.font=`${e.style.fontSize}px ${n.fontFamily}`,i.textBaseline="middle",t.barCount===0)return;let u=e.orderedPanes(),p=u.find(m=>m.kind==="price")??null;for(let m of u)if(!m.collapsed)for(let f of e.indicatorsForPane(m.id)){let b=e.scaleFor(f,m),g=b===m.scale?m:{...m,scale:b};this.renderDrawings(i,t,this.ownDrawings(f),g,d,e.offsetOf(f.id));}if(p)for(let m of e.indicators.values())this.renderDrawings(i,t,this.overlayDrawings(m),p,d,e.offsetOf(m.id));if(p&&!p.collapsed&&e.tradeMarkers.visible)for(let m of e.indicators.values())m.trades?.length&&this.renderTrades(i,t,e,n,m.trades,p,d);this.drawPriceAxes(i,e,t,n,d,u),this.drawMergedScaleColumns(i,e,t,d),this.drawPaneSeparators(i,e,n,l,u),this.drawPriceLineAndCountdown(i,e,t,n,d,p),this.drawTimeAxis(i,e,t,n,d,h,c);}destroy(){this.canvas=null,this.ctx=null;}ownDrawings(e){return {lines:(e.lines??[]).filter(t=>!t.overlay),boxes:(e.boxes??[]).filter(t=>!t.overlay),labels:(e.labels??[]).filter(t=>!t.overlay),polylines:(e.polylines??[]).filter(t=>!t.overlay),linefills:(e.linefills??[]).filter(t=>!t.overlay)}}overlayDrawings(e){return {lines:(e.lines??[]).filter(t=>t.overlay),boxes:(e.boxes??[]).filter(t=>t.overlay),labels:(e.labels??[]).filter(t=>t.overlay),polylines:(e.polylines??[]).filter(t=>t.overlay),linefills:(e.linefills??[]).filter(t=>t.overlay)}}drawingsRange(e,t,n=0){if(this.drawScene.setSet(e,n),this.drawScene.isEmpty())return null;let r=this.drawScene.priceRange(t.from,t.to);return r?{min:r.min,max:r.max}:null}renderTrades(e,t,n,r,i,o,a){e.save(),e.translate(0,o.bounds.top),e.beginPath(),e.rect(0,0,a,o.bounds.height),e.clip(),ql(e,i,n.tradeMarkers,{timeToLogical:l=>t.timeToLogical(l),barAt:l=>{let c=n.bars[Math.round(l)];return c?{high:c.high,low:c.low}:null}},l=>t.logicalToX(l),l=>t.priceToY(l,o.scale,o.bounds)-o.bounds.top,{fontSize:n.style.fontSize,fontFamily:r.fontFamily,color:r.textColor},a,Math.max(1.5,t.bodySpacing()*.4)),e.restore();}renderDrawings(e,t,n,r,i,o=0){this.drawScene.setSet(n,o),!this.drawScene.isEmpty()&&(e.save(),e.translate(0,r.bounds.top),e.beginPath(),e.rect(0,0,i,r.bounds.height),e.clip(),this.drawScene.render(e,i,r.bounds.height,a=>t.logicalToX(a),a=>t.priceToY(a,r.scale,r.bounds)-r.bounds.top),e.restore());}drawPriceAxes(e,t,n,r,i,o){if(e.strokeStyle=t.style.borderColor??r.borderColor,e.lineWidth=1,e.beginPath(),e.moveTo(i+.5,0),e.lineTo(i+.5,n.height),e.stroke(),!!t.showAxisLabels){e.fillStyle=this.axisTextColor,e.textAlign="left";for(let a of o){if(a.collapsed)continue;let l=Ee(t,a);for(let c of kt(a.scale,a.bounds.height,l,t.priceMintick,a.axisFormat)){let d=n.priceToY(c.price,a.scale,a.bounds);d<a.bounds.top+6||d>a.bounds.top+a.bounds.height-4||e.fillText(c.label,i+6,d);}}e.textAlign="start";}}drawPaneSeparators(e,t,n,r,i){e.fillStyle=t.style.separatorColor??n.borderColor;for(let o of i)o.order<=0||e.fillRect(0,Math.round(o.bounds.top)-1,r,3);}drawMergedScaleColumns(e,t,n,r){if(t.showAxisLabels){e.textAlign="left",e.fillStyle=this.axisTextColor;for(let i of t.orderedPanes()){if(i.collapsed)continue;t.ownScaleIndicatorsForPane(i.id).forEach((a,l)=>{let c=t.indicatorScales.get(a.id)?.scale;if(!c)return;let d=hc(r,l+1);for(let h of kt(c,i.bounds.height,void 0,t.priceMintick)){let u=n.priceToY(h.price,c,i.bounds);u<i.bounds.top+6||u>i.bounds.top+i.bounds.height-4||e.fillText(h.label,d+5,u);}});}e.textAlign="start";}}drawPriceLineAndCountdown(e,t,n,r,i,o){let a=t.bars.length;if(!o||a===0||t.candlesHidden||o.collapsed||o.bounds.height<=0)return;let l=t.bars[a-1],c=n.priceToY(l.close,o.scale,o.bounds);if(c<o.bounds.top||c>o.bounds.top+o.bounds.height)return;let d=this.priceElementColor(t,n,r,l);if(t.showPriceLine){let S=Math.round(c)+.5;e.strokeStyle=d,e.lineWidth=1,pc(e,"dotted"),e.beginPath(),e.moveTo(0,S),e.lineTo(i,S),e.stroke(),pc(e,"solid");}let h=n.barInterval,u=t.showCountdown&&h>0,p=t.showPriceLabel;if(!p&&!u)return;let m=Yn(o.scale,o.bounds.height,l.close,Ee(t,o),t.priceMintick),f=u?of(l.time+h-Date.now()):"",b=8,g=i+1,v=rf(d,r.background);if(e.textBaseline="middle",p&&u){let S=Math.max(e.measureText(m).width,e.measureText(f).width)+b,C=c-8,T=g+b/2;e.fillStyle=d,e.fillRect(g,C,S,32),e.fillStyle=v,e.textAlign="left",e.fillText(m,T,C+8),e.fillText(f,T,C+24),e.textAlign="start";return}let y=p?m:f,x=e.measureText(y).width+b;e.fillStyle=d,e.fillRect(g,c-8,x,16),e.fillStyle=v,e.textAlign="center",e.fillText(y,g+x/2,c),e.textAlign="start";}priceElementColor(e,t,n,r){let i=e.style;switch(e.priceStyle){case "bars":return r.close>=r.open?i.bars.upColor??n.upColor:i.bars.downColor??n.downColor;case "line":return i.line.color??n.upColor;case "area":return i.area.lineColor??n.upColor;case "baseline":{let o=Math.max(0,Math.floor(t.visibleLogicalRange().from)),a=e.baselineValue??e.bars[o]?.close??0;return r.close>=a?i.baseline.topLineColor??n.upColor:i.baseline.bottomLineColor??n.downColor}default:return r.close>=r.open?n.upColor:n.downColor}}drawTimeAxis(e,t,n,r,i,o,a){if(e.strokeStyle=t.style.borderColor??r.borderColor,e.lineWidth=1,e.beginPath(),e.moveTo(0,o+.5),e.lineTo(i,o+.5),e.stroke(),!t.showAxisLabels)return;e.fillStyle=this.axisTextColor,e.textAlign="center";let l=o+(a-o)/2,c=n.visibleTimeRange(),d=Rt((c.from+c.to)/2,t.timezone),h=Math.max(3,Math.min(8,Math.floor(i/64))),u=Jt(c.from,c.to,h,d).map(b=>({...b,x:n.timeToX(b.time),half:e.measureText(b.label).width/2})).filter(b=>b.x>=20&&b.x<=i-20),p=12,m=[],f=b=>{let g=b.x-b.half,v=b.x+b.half;m.every(y=>v+p<=y.l||g-p>=y.r)&&(m.push({l:g,r:v}),e.fillText(b.label,b.x,l));};for(let b of u)b.major&&f(b);for(let b of u)b.major||f(b);e.textAlign="start";}};function uc(s,e){return s?e?{min:Math.min(s.min,e.min),max:Math.max(s.max,e.max)}:s:e}function pc(s,e){e==="dashed"?s.setLineDash([6,4]):e==="dotted"?s.setLineDash([2,3]):s.setLineDash([]);}function rf(s,e){let[t,n,r,i]=U(s),o=t,a=n,l=r;if(i<1){let[h,u,p]=U(e);o=t*i+h*(1-i),a=n*i+u*(1-i),l=r*i+p*(1-i);}let c=h=>h<=.04045?h/12.92:Math.pow((h+.055)/1.055,2.4);return .2126*c(o)+.7152*c(a)+.0722*c(l)>=.4?"#000000":"#ffffff"}function of(s){let e=Math.max(0,Math.floor(s/1e3)),t=e%60,n=Math.floor(e/60)%60,r=Math.floor(e/3600),i=o=>String(o).padStart(2,"0");return r>0?`${r}:${i(n)}:${i(t)}`:`${i(n)}:${i(t)}`}var oo=class{constructor(){this.canvas=null;this.ctx=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}render(e,t,n,r=null,i=null){let o=this.ctx,a=this.canvas;if(!o||!a)return;let l=t.dpr;o.setTransform(l,0,0,l,0,0),o.clearRect(0,0,a.width/l,a.height/l),r!==null&&this.drawSeparatorHover(o,a.width/l,n,r),i&&this.drawExternal(o,i,e,t,n);let c=e.crosshair,d=t.width,h=t.height;if(!c||c.x<0||c.x>d||c.y<0||c.y>h)return;let u=e.style.crosshair;o.font=`${e.style.fontSize}px ${n.fontFamily}`,o.textBaseline="middle";let p=Math.round(t.xToLogical(c.x)),m=Math.round(t.logicalToX(p))+.5;o.strokeStyle=u.color??n.textColor,o.lineWidth=u.width,o.globalAlpha=u.opacity,mc(o,u.style),o.beginPath(),o.moveTo(m,0),o.lineTo(m,h),o.moveTo(0,Math.round(c.y)+.5),o.lineTo(d,Math.round(c.y)+.5),o.stroke(),o.setLineDash([]),o.lineWidth=1,o.globalAlpha=1;let f;for(let g of e.panes.values())if(c.y>=g.bounds.top&&c.y<=g.bounds.top+g.bounds.height){f=g;break}let b=u.labelBackground??n.borderColor;if(f){let g=t.yToPrice(c.y,f.scale,f.bounds);this.chip(o,d+1,c.y,Yn(f.scale,f.bounds.height,g,Ee(e,f),e.priceMintick,f.axisFormat),b,"left",false,n.background);}this.chip(o,m,h+1,fc(t.logicalToTime(p),e.timezone),b,"center",true,n.background);}destroy(){this.canvas=null,this.ctx=null;}drawExternal(e,t,n,r,i){let o=n.style.crosshair,a=r.width,l=r.height,c=Math.round(t.x)+.5;if(c<0||c>a)return;e.font=`${n.style.fontSize}px ${i.fontFamily}`,e.textBaseline="middle",e.strokeStyle=o.color??i.textColor,e.lineWidth=o.width,e.globalAlpha=o.opacity*.55,mc(e,o.style),e.beginPath(),e.moveTo(c,0),e.lineTo(c,l),t.y!=null&&(e.moveTo(0,Math.round(t.y)+.5),e.lineTo(a,Math.round(t.y)+.5)),e.stroke(),e.setLineDash([]),e.lineWidth=1,e.globalAlpha=.8;let d=o.labelBackground??i.borderColor;if(t.y!=null&&t.price!=null){let h;for(let u of n.panes.values())if(t.y>=u.bounds.top&&t.y<=u.bounds.top+u.bounds.height){h=u;break}h&&this.chip(e,a+1,t.y,Yn(h.scale,h.bounds.height,t.price,Ee(n,h),n.priceMintick,h.axisFormat),d,"left",false,i.background);}this.chip(e,c,l+1,fc(t.time,n.timezone),d,"center",true,i.background),e.globalAlpha=1;}drawSeparatorHover(e,t,n,r){let i=Math.round(r);e.fillStyle=n.textColor,e.globalAlpha=.1,e.fillRect(0,i-4,t,8),e.globalAlpha=.55,e.fillRect(0,i-1,t,2),e.globalAlpha=1;}chip(e,t,n,r,i,o,a=false,l="#000000"){let c=e.measureText(r).width+8,d=16,h=o==="left"?t:t-c/2,u=a?n:n-d/2;e.fillStyle=i,e.fillRect(h,u,c,d),e.fillStyle=Ql(i,l),e.textAlign="center",e.fillText(r,h+c/2,u+d/2+(a?2:0)),e.textAlign="start";}};function mc(s,e){e==="dashed"?s.setLineDash([6,4]):e==="dotted"?s.setLineDash([2,3]):s.setLineDash([]);}function fc(s,e){let t=Yi(s,e),n=r=>r<10?`0${r}`:String(r);return `${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}var gs=[{value:"Etc/UTC",label:"UTC"},{value:"Etc/GMT+12",label:"International Date Line West"},{value:"Pacific/Pago_Pago",label:"Pago Pago"},{value:"Pacific/Honolulu",label:"Honolulu"},{value:"Pacific/Marquesas",label:"Marquesas Islands"},{value:"America/Anchorage",label:"Anchorage"},{value:"America/Los_Angeles",label:"Los Angeles"},{value:"America/Phoenix",label:"Phoenix"},{value:"America/Denver",label:"Denver"},{value:"America/Chicago",label:"Chicago"},{value:"America/Mexico_City",label:"Mexico City"},{value:"America/New_York",label:"New York"},{value:"America/Bogota",label:"Bogot\xE1"},{value:"America/Caracas",label:"Caracas"},{value:"America/Santiago",label:"Santiago"},{value:"America/St_Johns",label:"St. John's"},{value:"America/Sao_Paulo",label:"S\xE3o Paulo"},{value:"America/Argentina/Buenos_Aires",label:"Buenos Aires"},{value:"America/Noronha",label:"Fernando de Noronha"},{value:"Atlantic/Azores",label:"Azores"},{value:"Atlantic/Reykjavik",label:"Reykjavik"},{value:"Europe/London",label:"London"},{value:"Europe/Paris",label:"Paris"},{value:"Europe/Berlin",label:"Berlin"},{value:"Europe/Athens",label:"Athens"},{value:"Africa/Cairo",label:"Cairo"},{value:"Africa/Johannesburg",label:"Johannesburg"},{value:"Europe/Moscow",label:"Moscow"},{value:"Europe/Istanbul",label:"Istanbul"},{value:"Asia/Tehran",label:"Tehran"},{value:"Asia/Dubai",label:"Dubai"},{value:"Asia/Kabul",label:"Kabul"},{value:"Asia/Karachi",label:"Karachi"},{value:"Asia/Kolkata",label:"Mumbai"},{value:"Asia/Kathmandu",label:"Kathmandu"},{value:"Asia/Dhaka",label:"Dhaka"},{value:"Asia/Yangon",label:"Yangon"},{value:"Asia/Bangkok",label:"Bangkok"},{value:"Asia/Shanghai",label:"Shanghai"},{value:"Asia/Hong_Kong",label:"Hong Kong"},{value:"Asia/Singapore",label:"Singapore"},{value:"Australia/Eucla",label:"Eucla"},{value:"Asia/Tokyo",label:"Tokyo"},{value:"Asia/Seoul",label:"Seoul"},{value:"Australia/Adelaide",label:"Adelaide"},{value:"Australia/Sydney",label:"Sydney"},{value:"Australia/Lord_Howe",label:"Lord Howe Island"},{value:"Pacific/Noumea",label:"Noum\xE9a"},{value:"Pacific/Auckland",label:"Auckland"},{value:"Pacific/Chatham",label:"Chatham Islands"},{value:"Pacific/Apia",label:"Apia"},{value:"Pacific/Kiritimati",label:"Kiritimati"}];function so(s){return s==="UTC"||s==="Etc/UTC"||s==="Etc/GMT"?"Etc/UTC":s}function sf(s,e=new Date){try{let r=(new Intl.DateTimeFormat("en-US",{timeZone:s,timeZoneName:"shortOffset"}).formatToParts(e).find(l=>l.type==="timeZoneName")?.value??"").match(/GMT(?:(\+|-)(\d{1,2})(?::(\d{2}))?)?/);if(!r||!r[1])return "UTC";let i=r[1]==="-"?"-":"+",o=r[2]??"0",a=r[3]??"";return a?`UTC${i}${o}:${a}`:`UTC${i}${o}`}catch{return "UTC"}}function vs(s,e){return so(s)==="Etc/UTC"?e:`(${sf(s)}) ${e}`}var qn=fr,Zn=br;function Ce(s,e){if(s instanceof ae){if(!s.fillTriangles().length)return null;let t=s.valid();return s.style.fillColor??(t==null?s.style.lineColor:t?qn:Zn)}return s instanceof we?s.style.fillColor??e.background:s.style.fillColor??null}function cn(s){let e=String(s??"").trim(),t=/^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(e);if(t)return {hex6:`#${t[1].toLowerCase()}`,alpha:t[2]?parseInt(t[2],16)/255:1};if(t=/^#([0-9a-f]{3})$/i.exec(e),t){let r=t[1].toLowerCase();return {hex6:`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`,alpha:1}}let n=/^rgba?\(([^)]+)\)/i.exec(e);if(n){let r=n[1].split(",").map(a=>a.trim()),i=a=>Math.max(0,Math.min(255,Math.round(a))).toString(16).padStart(2,"0"),o=r[3]!=null?Math.max(0,Math.min(1,parseFloat(r[3]))):1;return {hex6:`#${i(parseInt(r[0]??"0",10))}${i(parseInt(r[1]??"0",10))}${i(parseInt(r[2]??"0",10))}`,alpha:o}}return {hex6:R,alpha:1}}function gc(s,e){let t=Math.max(0,Math.min(1,e));return t>=.999?s:`${s}${Math.round(t*255).toString(16).padStart(2,"0")}`}function vc(s,e,t){let n=u=>{let p=parseInt(cn(u).hex6.slice(1),16);return [p>>16&255,p>>8&255,p&255]},[r,i,o]=n(s),[a,l,c]=n(e),d=Math.max(0,Math.min(1,t)),h=u=>Math.round(u).toString(16).padStart(2,"0");return `#${h(r*d+a*(1-d))}${h(i*d+l*(1-d))}${h(o*d+c*(1-d))}`}function bc(s,e,t){let n=e/100,r=t/100,i=c=>(c+s/30)%12,o=n*Math.min(r,1-r),a=c=>r-o*Math.max(-1,Math.min(i(c)-3,Math.min(9-i(c),1))),l=c=>Math.round(c*255).toString(16).padStart(2,"0");return `#${l(a(0))}${l(a(8))}${l(a(4))}`}function af(){let s=[100,90,80,68,56,45,35,25,14,0].map(n=>bc(0,0,n)),e=[4,28,50,96,140,174,200,224,270,322];return [s,...[[82,56],[58,84],[62,74],[66,62],[70,50],[64,39],[54,29]].map(([n,r])=>e.map(i=>bc(i,n,r)))]}var lf=af();function ys(s){return `repeating-conic-gradient(#9aa0a6 0% 25%, #d3d6da 0% 50%) 0 0 / ${s}px ${s}px`}var cf=ys(10),ln=[ve,q,X,bn,he];function df(s){let e=ln.findIndex(t=>t.toLowerCase()===s.toLowerCase());e>=0&&ln.splice(e,1),ln.unshift(s),ln.length>10&&(ln.length=10);}function Jn(s,e,t){let n=cn(s),r=n.hex6,i=n.alpha,o=document.createElement("div");o.style.cssText="display:flex;flex-direction:column;gap:9px;width:236px;";let a=document.createElement("div");a.style.cssText="display:grid;grid-template-columns:repeat(10,1fr);gap:4px;";let l=[];for(let C of lf)for(let T of C){let M=document.createElement("button");M.type="button",M.dataset.c=T,M.style.cssText=`width:100%;aspect-ratio:1;border-radius:4px;border:none;cursor:pointer;background:${T};padding:0;`,M.addEventListener("click",E=>{E.stopPropagation(),S(T);}),a.appendChild(M),l.push(M);}let c=()=>{for(let C of l){let T=(C.dataset.c??"").toLowerCase()===r.toLowerCase();C.style.outline=T?`2px solid ${e.textColor}`:"none",C.style.outlineOffset="2px",C.style.zIndex=T?"1":"",C.style.position=T?"relative":"";}},d=document.createElement("div");d.style.cssText="display:flex;align-items:center;gap:5px;flex-wrap:wrap;border-top:1px solid var(--vela-border);padding-top:9px;";let h=()=>{d.replaceChildren();for(let M of ln){let E=document.createElement("button");E.type="button",E.style.cssText=`width:17px;height:17px;border-radius:var(--vela-radius-sm);border:1px solid var(--vela-border);cursor:pointer;background:${M};padding:0;`,E.addEventListener("click",k=>{k.stopPropagation(),S(M);}),d.appendChild(E);}let C=document.createElement("label");C.style.cssText=`width:17px;height:17px;border-radius:var(--vela-radius-sm);border:1px dashed var(--vela-border-strong);cursor:pointer;display:flex;align-items:center;justify-content:center;color:${e.textColor};font:14px ${e.fontFamily};position:relative;`,C.textContent="+";let T=document.createElement("input");T.type="color",T.value=r,T.style.cssText="position:absolute;inset:0;opacity:0;cursor:pointer;",T.addEventListener("input",()=>S(T.value,true)),C.appendChild(T),d.appendChild(C);},u=document.createElement("div");u.textContent="Opacity",u.style.cssText=`font:11px ${e.fontFamily};color:var(--vela-fg-muted);`;let p=document.createElement("div");p.style.cssText="display:flex;align-items:center;gap:10px;";let m=document.createElement("div");m.style.cssText="flex:1;position:relative;height:13px;border-radius:7px;cursor:pointer;";let f=document.createElement("div");f.style.cssText="position:absolute;top:50%;width:15px;height:15px;border-radius:50%;background:var(--vela-selected-bg);box-shadow:0 1px 3px rgba(0,0,0,0.55);transform:translate(-50%,-50%);pointer-events:none;",m.appendChild(f);let b=document.createElement("div");b.style.cssText=`min-width:42px;text-align:center;font:var(--vela-font-size-md) ${e.fontFamily};color:var(--vela-fg);border:1px solid var(--vela-border);border-radius:5px;padding:3px 4px;`,p.append(m,b);let g=()=>{m.style.background=`linear-gradient(to right, ${r}00, ${r}ff), ${cf}`,f.style.left=`${i*100}%`,b.textContent=`${Math.round(i*100)}%`;},v=false,y=C=>{let T=m.getBoundingClientRect();i=Math.max(0,Math.min(1,(C-T.left)/T.width)),g(),x();};m.addEventListener("pointerdown",C=>{C.stopPropagation(),v=true,m.setPointerCapture(C.pointerId),y(C.clientX);}),m.addEventListener("pointermove",C=>{v&&y(C.clientX);}),m.addEventListener("pointerup",()=>v=false);function x(){t(gc(r,i));}function S(C,T=false){r=cn(C).hex6,df(r),c(),g(),T&&h(),x();}return h(),c(),g(),o.append(a,d,u,p),o}var hf=ys(8),yc="vela-color-field";function uf(){if(typeof document>"u"||document.getElementById(yc))return;let s=document.createElement("style");s.id=yc,s.textContent=`
83
+ `),h=dc(u,i,o,t.bold);}else {let g=`${c}${h}px ${l}`;u=t.wrap?this.wrapText(e,g,a,Math.max(1,i-d*2)):a.split(`
84
+ `);}e.font=`${c}${h}px ${l}`,e.fillStyle=t.textColor??ge(t.bgColor);let p=h*1.3,m=p*u.length,f;t.hAlign==="left"?(e.textAlign="left",f=n+d):t.hAlign==="right"?(e.textAlign="right",f=n+i-d):(e.textAlign="center",f=n+i/2),e.textBaseline="top";let b;t.vAlign==="top"?b=r+d:t.vAlign==="bottom"?b=r+o-d-m:b=r+(o-m)/2,e.save(),e.beginPath(),e.rect(n,r,i,o),e.clip();for(let g=0;g<u.length;g+=1)e.fillText(u[g],f,b+g*p);e.restore();}drawLabels(e,t,n,r,i){for(let o of this.set.labels){let a=r(this.logicalOf(o.xloc,o.x));if(a<-50||a>t+50)continue;let l;if(o.yloc==="price")l=i(o.y);else if(o.yloc==="top")l=14;else if(o.yloc==="bottom")l=n-14;else {let h=this.deps.barAt(this.logicalOf(o.xloc,o.x));if(!h)continue;let u=i(o.yloc==="abovebar"?h.high:h.low);l=u===null?null:u+(o.yloc==="abovebar"?-14:14);}if(l===null)continue;let c=o.color??this.deps.theme.textColor,d=hc(o.size);this.isPointShape(o.style)?(o.noFill||this.drawLabelShape(e,o.style,a,l,d,c),o.text&&this.drawLabelText(e,o,a,l+d,d)):o.style==="none"||o.style==="text_outline"||o.noFill?o.text&&this.drawLabelText(e,o,a,l,d,o.style==="text_outline"):this.drawBubble(e,o,a,l,d,c);}}isPointShape(e){switch(e){case "circle":case "square":case "diamond":case "flag":case "arrowup":case "arrowdown":case "triangleup":case "triangledown":case "cross":case "xcross":return true;default:return false}}drawLabelText(e,t,n,r,i,o=false){let a=t.fontFamily==="monospace"?"monospace":this.deps.theme.fontFamily||"sans-serif";e.font=`${i}px ${a}`,e.textAlign=t.textAlign==="left"?"left":t.textAlign==="right"?"right":"center",e.textBaseline="middle";let l=t.text.split(`
85
+ `),c=i*1.25,d=r-c*(l.length-1)/2;if(o){e.lineWidth=3,e.strokeStyle=ge(t.textColor??this.deps.theme.textColor);for(let h=0;h<l.length;h+=1)e.strokeText(l[h],n,d+h*c);}e.fillStyle=t.textColor??this.deps.theme.textColor;for(let h=0;h<l.length;h+=1)e.fillText(l[h],n,d+h*c);}drawLabelShape(e,t,n,r,i,o){let a=Math.max(4,i*.6);switch(e.fillStyle=o,e.strokeStyle=o,e.lineWidth=Math.max(1,a*.3),e.beginPath(),t){case "circle":e.arc(n,r,a,0,Math.PI*2),e.fill();break;case "square":e.fillRect(n-a,r-a,a*2,a*2);break;case "diamond":e.moveTo(n,r-a),e.lineTo(n+a,r),e.lineTo(n,r+a),e.lineTo(n-a,r),e.closePath(),e.fill();break;case "triangleup":case "arrowup":e.moveTo(n,r-a),e.lineTo(n+a,r+a),e.lineTo(n-a,r+a),e.closePath(),e.fill();break;case "triangledown":case "arrowdown":e.moveTo(n,r+a),e.lineTo(n+a,r-a),e.lineTo(n-a,r-a),e.closePath(),e.fill();break;case "flag":e.moveTo(n-a*.7,r-a),e.lineTo(n-a*.7,r+a),e.moveTo(n-a*.7,r-a),e.lineTo(n+a,r-a*.4),e.lineTo(n-a*.7,r+a*.2),e.stroke(),e.fill();break;case "cross":e.moveTo(n,r-a),e.lineTo(n,r+a),e.moveTo(n-a,r),e.lineTo(n+a,r),e.stroke();break;case "xcross":e.moveTo(n-a,r-a),e.lineTo(n+a,r+a),e.moveTo(n+a,r-a),e.lineTo(n-a,r+a),e.stroke();break;default:e.arc(n,r,a,0,Math.PI*2),e.fill();}}drawBubble(e,t,n,r,i,o){let a=t.fontFamily==="monospace"?"monospace":this.deps.theme.fontFamily||"sans-serif";e.font=`${i}px ${a}`;let l=(t.text??"").split(`
86
+ `),c=6,d=4,h=i*1.25,p=Math.max(1,...l.map(y=>this.measure(e,e.font,y)))+c*2,m=h*l.length+d*2,f=7,b=n-p/2,g=r-m-f,v="down";switch(t.style){case "label_up":b=n-p/2,g=r+f,v="up";break;case "label_left":b=n+f,g=r-m/2,v="left";break;case "label_right":b=n-p-f,g=r-m/2,v="right";break;case "label_center":b=n-p/2,g=r-m/2,v="none";break;case "label_lower_left":b=n+f,g=r-m-f,v="none";break;case "label_lower_right":b=n-p-f,g=r-m-f,v="none";break;case "label_upper_left":b=n+f,g=r+f,v="none";break;case "label_upper_right":b=n-p-f,g=r+f,v="none";break;default:b=n-p/2,g=r-m-f,v="down";}if(e.fillStyle=o,this.roundRect(e,b,g,p,m,4),e.fill(),v!=="none"&&(e.beginPath(),v==="down"?(e.moveTo(n-f,g+m),e.lineTo(n+f,g+m),e.lineTo(n,r)):v==="up"?(e.moveTo(n-f,g),e.lineTo(n+f,g),e.lineTo(n,r)):v==="left"?(e.moveTo(b,r-f),e.lineTo(b,r+f),e.lineTo(n,r)):(e.moveTo(b+p,r-f),e.lineTo(b+p,r+f),e.lineTo(n,r)),e.closePath(),e.fill()),t.text){e.fillStyle=t.textColor??ge(o),e.textAlign="center",e.textBaseline="middle";let y=g+d+h/2;for(let x=0;x<l.length;x+=1)e.fillText(l[x],b+p/2,y+x*h);}}roundRect(e,t,n,r,i,o){let a=Math.min(o,r/2,i/2);e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath();}};function uc(s,e){return e===0?s:s+64+(e-1)*56}var oo=class{constructor(){this.canvas=null;this.ctx=null;this.axisTextColor=Be.textColor;this.drawScene=new io({timeToLogical:()=>0,barAt:()=>null,theme:{}});}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}prepare(e,t,n){this.drawScene.setDeps({timeToLogical:r=>t.timeToLogical(r),barAt:r=>{let i=e.bars[Math.round(r)];return i?{high:i.high,low:i.low}:null},theme:n});}paneDrawingsRange(e,t,n,r){let i=null;for(let o of e)i=pc(i,this.drawingsRange(this.ownDrawings(o),r,t.offsetOf(o.id)));if(n)for(let o of t.indicators.values())i=pc(i,this.drawingsRange(this.overlayDrawings(o),r,t.offsetOf(o.id)));return i}render(e,t,n,r){let i=this.ctx,o=this.canvas;if(!i||!o)return;let a=t.dpr,l=o.width/a,c=o.height/a,d=t.width,h=t.height;this.axisTextColor=r?.textColor??n.textColor,i.setTransform(a,0,0,a,0,0),i.clearRect(0,0,l,c),r&&(l>d||c>h)&&(i.fillStyle=r.background,l>d&&i.fillRect(d,0,l-d,c),c>h&&i.fillRect(0,h,d,c-h)),i.font=`${e.style.fontSize}px ${n.fontFamily}`,i.textBaseline="middle";let u=e.orderedPanes();if(t.barCount===0){this.drawPaneSeparators(i,e,n,l,u);return}let p=u.find(m=>m.kind==="price")??null;for(let m of u)if(!m.collapsed)for(let f of e.indicatorsForPane(m.id)){let b=e.scaleFor(f,m),g=b===m.scale?m:{...m,scale:b};this.renderDrawings(i,t,this.ownDrawings(f),g,d,e.offsetOf(f.id));}if(p)for(let m of e.indicators.values())this.renderDrawings(i,t,this.overlayDrawings(m),p,d,e.offsetOf(m.id));if(p&&!p.collapsed&&e.tradeMarkers.visible)for(let m of e.indicators.values())m.trades?.length&&this.renderTrades(i,t,e,n,m.trades,p,d);this.drawPriceAxes(i,e,t,n,d,u),this.drawMergedScaleColumns(i,e,t,d),this.drawPaneSeparators(i,e,n,l,u),this.drawPriceLineAndCountdown(i,e,t,n,d,p),this.drawTimeAxis(i,e,t,n,d,h,c);}destroy(){this.canvas=null,this.ctx=null;}ownDrawings(e){return {lines:(e.lines??[]).filter(t=>!t.overlay),boxes:(e.boxes??[]).filter(t=>!t.overlay),labels:(e.labels??[]).filter(t=>!t.overlay),polylines:(e.polylines??[]).filter(t=>!t.overlay),linefills:(e.linefills??[]).filter(t=>!t.overlay)}}overlayDrawings(e){return {lines:(e.lines??[]).filter(t=>t.overlay),boxes:(e.boxes??[]).filter(t=>t.overlay),labels:(e.labels??[]).filter(t=>t.overlay),polylines:(e.polylines??[]).filter(t=>t.overlay),linefills:(e.linefills??[]).filter(t=>t.overlay)}}drawingsRange(e,t,n=0){if(this.drawScene.setSet(e,n),this.drawScene.isEmpty())return null;let r=this.drawScene.priceRange(t.from,t.to);return r?{min:r.min,max:r.max}:null}renderTrades(e,t,n,r,i,o,a){e.save(),e.translate(0,o.bounds.top),e.beginPath(),e.rect(0,0,a,o.bounds.height),e.clip(),Zl(e,i,n.tradeMarkers,{timeToLogical:l=>t.timeToLogical(l),barAt:l=>{let c=n.bars[Math.round(l)];return c?{high:c.high,low:c.low}:null}},l=>t.logicalToX(l),l=>t.priceToY(l,o.scale,o.bounds)-o.bounds.top,{fontSize:n.style.fontSize,fontFamily:r.fontFamily,color:r.textColor},a,Math.max(1.5,t.bodySpacing()*.4)),e.restore();}renderDrawings(e,t,n,r,i,o=0){this.drawScene.setSet(n,o),!this.drawScene.isEmpty()&&(e.save(),e.translate(0,r.bounds.top),e.beginPath(),e.rect(0,0,i,r.bounds.height),e.clip(),this.drawScene.render(e,i,r.bounds.height,a=>t.logicalToX(a),a=>t.priceToY(a,r.scale,r.bounds)-r.bounds.top),e.restore());}drawPriceAxes(e,t,n,r,i,o){if(e.strokeStyle=t.style.borderColor??r.borderColor,e.lineWidth=1,e.beginPath(),e.moveTo(i+.5,0),e.lineTo(i+.5,n.height),e.stroke(),!!t.showAxisLabels){e.fillStyle=this.axisTextColor,e.textAlign="left";for(let a of o){if(a.collapsed)continue;let l=Ee(t,a);for(let c of kt(a.scale,a.bounds.height,l,t.priceMintick,a.axisFormat)){let d=n.priceToY(c.price,a.scale,a.bounds);d<a.bounds.top+6||d>a.bounds.top+a.bounds.height-4||e.fillText(c.label,i+6,d);}}e.textAlign="start";}}drawPaneSeparators(e,t,n,r,i){e.fillStyle=t.style.separatorColor??n.borderColor;for(let o of i)o.order<=0||e.fillRect(0,Math.round(o.bounds.top)-1,r,3);}drawMergedScaleColumns(e,t,n,r){if(t.showAxisLabels){e.textAlign="left",e.fillStyle=this.axisTextColor;for(let i of t.orderedPanes()){if(i.collapsed)continue;t.ownScaleIndicatorsForPane(i.id).forEach((a,l)=>{let c=t.indicatorScales.get(a.id)?.scale;if(!c)return;let d=uc(r,l+1);for(let h of kt(c,i.bounds.height,void 0,t.priceMintick)){let u=n.priceToY(h.price,c,i.bounds);u<i.bounds.top+6||u>i.bounds.top+i.bounds.height-4||e.fillText(h.label,d+5,u);}});}e.textAlign="start";}}drawPriceLineAndCountdown(e,t,n,r,i,o){let a=t.bars.length;if(!o||a===0||t.candlesHidden||o.collapsed||o.bounds.height<=0)return;let l=t.bars[a-1],c=n.priceToY(l.close,o.scale,o.bounds);if(c<o.bounds.top||c>o.bounds.top+o.bounds.height)return;let d=this.priceElementColor(t,n,r,l);if(t.showPriceLine){let S=Math.round(c)+.5;e.strokeStyle=d,e.lineWidth=1,mc(e,"dotted"),e.beginPath(),e.moveTo(0,S),e.lineTo(i,S),e.stroke(),mc(e,"solid");}let h=n.barInterval,u=t.showCountdown&&h>0,p=t.showPriceLabel;if(!p&&!u)return;let m=Yn(o.scale,o.bounds.height,l.close,Ee(t,o),t.priceMintick),f=u?af(l.time+h-Date.now()):"",b=8,g=i+1,v=sf(d,r.background);if(e.textBaseline="middle",p&&u){let S=Math.max(e.measureText(m).width,e.measureText(f).width)+b,C=c-8,T=g+b/2;e.fillStyle=d,e.fillRect(g,C,S,32),e.fillStyle=v,e.textAlign="left",e.fillText(m,T,C+8),e.fillText(f,T,C+24),e.textAlign="start";return}let y=p?m:f,x=e.measureText(y).width+b;e.fillStyle=d,e.fillRect(g,c-8,x,16),e.fillStyle=v,e.textAlign="center",e.fillText(y,g+x/2,c),e.textAlign="start";}priceElementColor(e,t,n,r){let i=e.style;switch(e.priceStyle){case "bars":return r.close>=r.open?i.bars.upColor??n.upColor:i.bars.downColor??n.downColor;case "line":return i.line.color??n.upColor;case "area":return i.area.lineColor??n.upColor;case "baseline":{let o=Math.max(0,Math.floor(t.visibleLogicalRange().from)),a=e.baselineValue??e.bars[o]?.close??0;return r.close>=a?i.baseline.topLineColor??n.upColor:i.baseline.bottomLineColor??n.downColor}default:return r.close>=r.open?n.upColor:n.downColor}}drawTimeAxis(e,t,n,r,i,o,a){if(e.strokeStyle=t.style.borderColor??r.borderColor,e.lineWidth=1,e.beginPath(),e.moveTo(0,o+.5),e.lineTo(i,o+.5),e.stroke(),!t.showAxisLabels)return;e.fillStyle=this.axisTextColor,e.textAlign="center";let l=o+(a-o)/2,c=n.visibleTimeRange(),d=Rt((c.from+c.to)/2,t.timezone),h=Math.max(3,Math.min(8,Math.floor(i/64))),u=Jt(c.from,c.to,h,d).map(b=>({...b,x:n.timeToX(b.time),half:e.measureText(b.label).width/2})).filter(b=>b.x>=20&&b.x<=i-20),p=12,m=[],f=b=>{let g=b.x-b.half,v=b.x+b.half;m.every(y=>v+p<=y.l||g-p>=y.r)&&(m.push({l:g,r:v}),e.fillText(b.label,b.x,l));};for(let b of u)b.major&&f(b);for(let b of u)b.major||f(b);e.textAlign="start";}};function pc(s,e){return s?e?{min:Math.min(s.min,e.min),max:Math.max(s.max,e.max)}:s:e}function mc(s,e){e==="dashed"?s.setLineDash([6,4]):e==="dotted"?s.setLineDash([2,3]):s.setLineDash([]);}function sf(s,e){let[t,n,r,i]=U(s),o=t,a=n,l=r;if(i<1){let[h,u,p]=U(e);o=t*i+h*(1-i),a=n*i+u*(1-i),l=r*i+p*(1-i);}let c=h=>h<=.04045?h/12.92:Math.pow((h+.055)/1.055,2.4);return .2126*c(o)+.7152*c(a)+.0722*c(l)>=.4?"#000000":"#ffffff"}function af(s){let e=Math.max(0,Math.floor(s/1e3)),t=e%60,n=Math.floor(e/60)%60,r=Math.floor(e/3600),i=o=>String(o).padStart(2,"0");return r>0?`${r}:${i(n)}:${i(t)}`:`${i(n)}:${i(t)}`}var so=class{constructor(){this.canvas=null;this.ctx=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}render(e,t,n,r=null,i=null){let o=this.ctx,a=this.canvas;if(!o||!a)return;let l=t.dpr;o.setTransform(l,0,0,l,0,0),o.clearRect(0,0,a.width/l,a.height/l),r!==null&&this.drawSeparatorHover(o,a.width/l,n,r),i&&this.drawExternal(o,i,e,t,n);let c=e.crosshair,d=t.width,h=t.height;if(!c||c.x<0||c.x>d||c.y<0||c.y>h)return;let u=e.style.crosshair;o.font=`${e.style.fontSize}px ${n.fontFamily}`,o.textBaseline="middle";let p=Math.round(t.xToLogical(c.x)),m=Math.round(t.logicalToX(p))+.5;o.strokeStyle=u.color??n.textColor,o.lineWidth=u.width,o.globalAlpha=u.opacity,fc(o,u.style),o.beginPath(),o.moveTo(m,0),o.lineTo(m,h),o.moveTo(0,Math.round(c.y)+.5),o.lineTo(d,Math.round(c.y)+.5),o.stroke(),o.setLineDash([]),o.lineWidth=1,o.globalAlpha=1;let f;for(let g of e.panes.values())if(c.y>=g.bounds.top&&c.y<=g.bounds.top+g.bounds.height){f=g;break}let b=u.labelBackground??n.borderColor;if(f){let g=t.yToPrice(c.y,f.scale,f.bounds);this.chip(o,d+1,c.y,Yn(f.scale,f.bounds.height,g,Ee(e,f),e.priceMintick,f.axisFormat),b,"left",false,n.background);}this.chip(o,m,h+1,bc(t.logicalToTime(p),e.timezone),b,"center",true,n.background);}destroy(){this.canvas=null,this.ctx=null;}drawExternal(e,t,n,r,i){let o=n.style.crosshair,a=r.width,l=r.height,c=Math.round(t.x)+.5;if(c<0||c>a)return;e.font=`${n.style.fontSize}px ${i.fontFamily}`,e.textBaseline="middle",e.strokeStyle=o.color??i.textColor,e.lineWidth=o.width,e.globalAlpha=o.opacity*.55,fc(e,o.style),e.beginPath(),e.moveTo(c,0),e.lineTo(c,l),t.y!=null&&(e.moveTo(0,Math.round(t.y)+.5),e.lineTo(a,Math.round(t.y)+.5)),e.stroke(),e.setLineDash([]),e.lineWidth=1,e.globalAlpha=.8;let d=o.labelBackground??i.borderColor;if(t.y!=null&&t.price!=null){let h;for(let u of n.panes.values())if(t.y>=u.bounds.top&&t.y<=u.bounds.top+u.bounds.height){h=u;break}h&&this.chip(e,a+1,t.y,Yn(h.scale,h.bounds.height,t.price,Ee(n,h),n.priceMintick,h.axisFormat),d,"left",false,i.background);}this.chip(e,c,l+1,bc(t.time,n.timezone),d,"center",true,i.background),e.globalAlpha=1;}drawSeparatorHover(e,t,n,r){let i=Math.round(r);e.fillStyle=n.textColor,e.globalAlpha=.1,e.fillRect(0,i-4,t,8),e.globalAlpha=.55,e.fillRect(0,i-1,t,2),e.globalAlpha=1;}chip(e,t,n,r,i,o,a=false,l="#000000"){let c=e.measureText(r).width+8,d=16,h=o==="left"?t:t-c/2,u=a?n:n-d/2;e.fillStyle=i,e.fillRect(h,u,c,d),e.fillStyle=ec(i,l),e.textAlign="center",e.fillText(r,h+c/2,u+d/2+(a?2:0)),e.textAlign="start";}};function fc(s,e){e==="dashed"?s.setLineDash([6,4]):e==="dotted"?s.setLineDash([2,3]):s.setLineDash([]);}function bc(s,e){let t=Xi(s,e),n=r=>r<10?`0${r}`:String(r);return `${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())} ${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}var gs=[{value:"Etc/UTC",label:"UTC"},{value:"Etc/GMT+12",label:"International Date Line West"},{value:"Pacific/Pago_Pago",label:"Pago Pago"},{value:"Pacific/Honolulu",label:"Honolulu"},{value:"Pacific/Marquesas",label:"Marquesas Islands"},{value:"America/Anchorage",label:"Anchorage"},{value:"America/Los_Angeles",label:"Los Angeles"},{value:"America/Phoenix",label:"Phoenix"},{value:"America/Denver",label:"Denver"},{value:"America/Chicago",label:"Chicago"},{value:"America/Mexico_City",label:"Mexico City"},{value:"America/New_York",label:"New York"},{value:"America/Bogota",label:"Bogot\xE1"},{value:"America/Caracas",label:"Caracas"},{value:"America/Santiago",label:"Santiago"},{value:"America/St_Johns",label:"St. John's"},{value:"America/Sao_Paulo",label:"S\xE3o Paulo"},{value:"America/Argentina/Buenos_Aires",label:"Buenos Aires"},{value:"America/Noronha",label:"Fernando de Noronha"},{value:"Atlantic/Azores",label:"Azores"},{value:"Atlantic/Reykjavik",label:"Reykjavik"},{value:"Europe/London",label:"London"},{value:"Europe/Paris",label:"Paris"},{value:"Europe/Berlin",label:"Berlin"},{value:"Europe/Athens",label:"Athens"},{value:"Africa/Cairo",label:"Cairo"},{value:"Africa/Johannesburg",label:"Johannesburg"},{value:"Europe/Moscow",label:"Moscow"},{value:"Europe/Istanbul",label:"Istanbul"},{value:"Asia/Tehran",label:"Tehran"},{value:"Asia/Dubai",label:"Dubai"},{value:"Asia/Kabul",label:"Kabul"},{value:"Asia/Karachi",label:"Karachi"},{value:"Asia/Kolkata",label:"Mumbai"},{value:"Asia/Kathmandu",label:"Kathmandu"},{value:"Asia/Dhaka",label:"Dhaka"},{value:"Asia/Yangon",label:"Yangon"},{value:"Asia/Bangkok",label:"Bangkok"},{value:"Asia/Shanghai",label:"Shanghai"},{value:"Asia/Hong_Kong",label:"Hong Kong"},{value:"Asia/Singapore",label:"Singapore"},{value:"Australia/Eucla",label:"Eucla"},{value:"Asia/Tokyo",label:"Tokyo"},{value:"Asia/Seoul",label:"Seoul"},{value:"Australia/Adelaide",label:"Adelaide"},{value:"Australia/Sydney",label:"Sydney"},{value:"Australia/Lord_Howe",label:"Lord Howe Island"},{value:"Pacific/Noumea",label:"Noum\xE9a"},{value:"Pacific/Auckland",label:"Auckland"},{value:"Pacific/Chatham",label:"Chatham Islands"},{value:"Pacific/Apia",label:"Apia"},{value:"Pacific/Kiritimati",label:"Kiritimati"}];function ao(s){return s==="UTC"||s==="Etc/UTC"||s==="Etc/GMT"?"Etc/UTC":s}function lf(s,e=new Date){try{let r=(new Intl.DateTimeFormat("en-US",{timeZone:s,timeZoneName:"shortOffset"}).formatToParts(e).find(l=>l.type==="timeZoneName")?.value??"").match(/GMT(?:(\+|-)(\d{1,2})(?::(\d{2}))?)?/);if(!r||!r[1])return "UTC";let i=r[1]==="-"?"-":"+",o=r[2]??"0",a=r[3]??"";return a?`UTC${i}${o}:${a}`:`UTC${i}${o}`}catch{return "UTC"}}function vs(s,e){return ao(s)==="Etc/UTC"?e:`(${lf(s)}) ${e}`}var qn=br,Zn=gr;function Ce(s,e){if(s instanceof ae){if(!s.fillTriangles().length)return null;let t=s.valid();return s.style.fillColor??(t==null?s.style.lineColor:t?qn:Zn)}return s instanceof we?s.style.fillColor??e.background:s.style.fillColor??null}function cn(s){let e=String(s??"").trim(),t=/^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(e);if(t)return {hex6:`#${t[1].toLowerCase()}`,alpha:t[2]?parseInt(t[2],16)/255:1};if(t=/^#([0-9a-f]{3})$/i.exec(e),t){let r=t[1].toLowerCase();return {hex6:`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`,alpha:1}}let n=/^rgba?\(([^)]+)\)/i.exec(e);if(n){let r=n[1].split(",").map(a=>a.trim()),i=a=>Math.max(0,Math.min(255,Math.round(a))).toString(16).padStart(2,"0"),o=r[3]!=null?Math.max(0,Math.min(1,parseFloat(r[3]))):1;return {hex6:`#${i(parseInt(r[0]??"0",10))}${i(parseInt(r[1]??"0",10))}${i(parseInt(r[2]??"0",10))}`,alpha:o}}return {hex6:R,alpha:1}}function vc(s,e){let t=Math.max(0,Math.min(1,e));return t>=.999?s:`${s}${Math.round(t*255).toString(16).padStart(2,"0")}`}function yc(s,e,t){let n=u=>{let p=parseInt(cn(u).hex6.slice(1),16);return [p>>16&255,p>>8&255,p&255]},[r,i,o]=n(s),[a,l,c]=n(e),d=Math.max(0,Math.min(1,t)),h=u=>Math.round(u).toString(16).padStart(2,"0");return `#${h(r*d+a*(1-d))}${h(i*d+l*(1-d))}${h(o*d+c*(1-d))}`}function gc(s,e,t){let n=e/100,r=t/100,i=c=>(c+s/30)%12,o=n*Math.min(r,1-r),a=c=>r-o*Math.max(-1,Math.min(i(c)-3,Math.min(9-i(c),1))),l=c=>Math.round(c*255).toString(16).padStart(2,"0");return `#${l(a(0))}${l(a(8))}${l(a(4))}`}function cf(){let s=[100,90,80,68,56,45,35,25,14,0].map(n=>gc(0,0,n)),e=[4,28,50,96,140,174,200,224,270,322];return [s,...[[82,56],[58,84],[62,74],[66,62],[70,50],[64,39],[54,29]].map(([n,r])=>e.map(i=>gc(i,n,r)))]}var df=cf();function ys(s){return `repeating-conic-gradient(#9aa0a6 0% 25%, #d3d6da 0% 50%) 0 0 / ${s}px ${s}px`}var hf=ys(10),ln=[ve,q,X,bn,he];function uf(s){let e=ln.findIndex(t=>t.toLowerCase()===s.toLowerCase());e>=0&&ln.splice(e,1),ln.unshift(s),ln.length>10&&(ln.length=10);}function Jn(s,e,t){let n=cn(s),r=n.hex6,i=n.alpha,o=document.createElement("div");o.style.cssText="display:flex;flex-direction:column;gap:9px;width:236px;";let a=document.createElement("div");a.style.cssText="display:grid;grid-template-columns:repeat(10,1fr);gap:4px;";let l=[];for(let C of df)for(let T of C){let M=document.createElement("button");M.type="button",M.dataset.c=T,M.style.cssText=`width:100%;aspect-ratio:1;border-radius:4px;border:none;cursor:pointer;background:${T};padding:0;`,M.addEventListener("click",E=>{E.stopPropagation(),S(T);}),a.appendChild(M),l.push(M);}let c=()=>{for(let C of l){let T=(C.dataset.c??"").toLowerCase()===r.toLowerCase();C.style.outline=T?`2px solid ${e.textColor}`:"none",C.style.outlineOffset="2px",C.style.zIndex=T?"1":"",C.style.position=T?"relative":"";}},d=document.createElement("div");d.style.cssText="display:flex;align-items:center;gap:5px;flex-wrap:wrap;border-top:1px solid var(--vela-border);padding-top:9px;";let h=()=>{d.replaceChildren();for(let M of ln){let E=document.createElement("button");E.type="button",E.style.cssText=`width:17px;height:17px;border-radius:var(--vela-radius-sm);border:1px solid var(--vela-border);cursor:pointer;background:${M};padding:0;`,E.addEventListener("click",k=>{k.stopPropagation(),S(M);}),d.appendChild(E);}let C=document.createElement("label");C.style.cssText=`width:17px;height:17px;border-radius:var(--vela-radius-sm);border:1px dashed var(--vela-border-strong);cursor:pointer;display:flex;align-items:center;justify-content:center;color:${e.textColor};font:14px ${e.fontFamily};position:relative;`,C.textContent="+";let T=document.createElement("input");T.type="color",T.value=r,T.style.cssText="position:absolute;inset:0;opacity:0;cursor:pointer;",T.addEventListener("input",()=>S(T.value,true)),C.appendChild(T),d.appendChild(C);},u=document.createElement("div");u.textContent="Opacity",u.style.cssText=`font:11px ${e.fontFamily};color:var(--vela-fg-muted);`;let p=document.createElement("div");p.style.cssText="display:flex;align-items:center;gap:10px;";let m=document.createElement("div");m.style.cssText="flex:1;position:relative;height:13px;border-radius:7px;cursor:pointer;";let f=document.createElement("div");f.style.cssText="position:absolute;top:50%;width:15px;height:15px;border-radius:50%;background:var(--vela-selected-bg);box-shadow:0 1px 3px rgba(0,0,0,0.55);transform:translate(-50%,-50%);pointer-events:none;",m.appendChild(f);let b=document.createElement("div");b.style.cssText=`min-width:42px;text-align:center;font:var(--vela-font-size-md) ${e.fontFamily};color:var(--vela-fg);border:1px solid var(--vela-border);border-radius:5px;padding:3px 4px;`,p.append(m,b);let g=()=>{m.style.background=`linear-gradient(to right, ${r}00, ${r}ff), ${hf}`,f.style.left=`${i*100}%`,b.textContent=`${Math.round(i*100)}%`;},v=false,y=C=>{let T=m.getBoundingClientRect();i=Math.max(0,Math.min(1,(C-T.left)/T.width)),g(),x();};m.addEventListener("pointerdown",C=>{C.stopPropagation(),v=true,m.setPointerCapture(C.pointerId),y(C.clientX);}),m.addEventListener("pointermove",C=>{v&&y(C.clientX);}),m.addEventListener("pointerup",()=>v=false);function x(){t(vc(r,i));}function S(C,T=false){r=cn(C).hex6,uf(r),c(),g(),T&&h(),x();}return h(),c(),g(),o.append(a,d,u,p),o}var pf=ys(8),xc="vela-color-field";function mf(){if(typeof document>"u"||document.getElementById(xc))return;let s=document.createElement("style");s.id=xc,s.textContent=`
87
87
  .vela-color-field{width:24px;height:24px;padding:2px;border:1px solid var(--vela-border);border-radius:0;background:var(--vela-surface-sunken);cursor:pointer;display:inline-flex;flex:none;}
88
88
  .vela-color-field:hover{border-color:var(--vela-fg-muted);}
89
89
  .vela-color-field-swatch{display:block;width:100%;height:100%;border-radius:0;box-shadow:inset 0 0 0 1px rgba(0,0,0,0.25);}
90
90
  .vela-color-field-pop{position:fixed;z-index:6000;background:var(--vela-surface-overlay);border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);padding:10px;}
91
- `,document.head.appendChild(s);}var at=null;function ao(){at&&(document.removeEventListener("pointerdown",at.onOutside,true),window.removeEventListener("resize",at.reflow,true),at.el.remove(),at=null);}function xc(s,e){let t=e.getBoundingClientRect(),n=s.offsetWidth,r=s.offsetHeight,i=t.right-n,o=t.bottom+6;i<6&&(i=6),i+n>window.innerWidth-6&&(i=window.innerWidth-n-6),o+r>window.innerHeight-6&&(o=t.top-r-6),o<6&&(o=6),s.style.left=`${Math.round(i)}px`,s.style.top=`${Math.round(o)}px`;}function xs(s,e,t){uf();let n=document.createElement("button");n.type="button",n.className="vela-color-field";let r=document.createElement("span");r.className="vela-color-field-swatch",n.appendChild(r);let i=()=>{let o=e();r.style.background=`linear-gradient(${o}, ${o}), ${hf}`;};return i(),n.addEventListener("vela-sync",i),n.addEventListener("click",o=>{if(o.stopPropagation(),at&&at.trigger===n){ao();return}ao();let a=document.createElement("div");a.className="vela-color-field-pop",ne(a,s),a.addEventListener("pointerdown",d=>d.stopPropagation()),a.appendChild(Jn(e(),s,d=>{t(d),i();})),document.body.appendChild(a),xc(a,n);let l=d=>{let h=d.target;a.contains(h)||n.contains(h)||ao();},c=()=>xc(a,n);setTimeout(()=>document.addEventListener("pointerdown",l,true),0),window.addEventListener("resize",c,true),at={el:a,trigger:n,onOutside:l,reflow:c};}),n}function wc(){ao();}var pf=[1,2,3,4,5],Sc="vela-width-field";function mf(){if(typeof document>"u"||document.getElementById(Sc))return;let s=document.createElement("style");s.id=Sc,s.textContent=`
91
+ `,document.head.appendChild(s);}var at=null;function lo(){at&&(document.removeEventListener("pointerdown",at.onOutside,true),window.removeEventListener("resize",at.reflow,true),at.el.remove(),at=null);}function wc(s,e){let t=e.getBoundingClientRect(),n=s.offsetWidth,r=s.offsetHeight,i=t.right-n,o=t.bottom+6;i<6&&(i=6),i+n>window.innerWidth-6&&(i=window.innerWidth-n-6),o+r>window.innerHeight-6&&(o=t.top-r-6),o<6&&(o=6),s.style.left=`${Math.round(i)}px`,s.style.top=`${Math.round(o)}px`;}function xs(s,e,t){mf();let n=document.createElement("button");n.type="button",n.className="vela-color-field";let r=document.createElement("span");r.className="vela-color-field-swatch",n.appendChild(r);let i=()=>{let o=e();r.style.background=`linear-gradient(${o}, ${o}), ${pf}`;};return i(),n.addEventListener("vela-sync",i),n.addEventListener("click",o=>{if(o.stopPropagation(),at&&at.trigger===n){lo();return}lo();let a=document.createElement("div");a.className="vela-color-field-pop",ne(a,s),a.addEventListener("pointerdown",d=>d.stopPropagation()),a.appendChild(Jn(e(),s,d=>{t(d),i();})),document.body.appendChild(a),wc(a,n);let l=d=>{let h=d.target;a.contains(h)||n.contains(h)||lo();},c=()=>wc(a,n);setTimeout(()=>document.addEventListener("pointerdown",l,true),0),window.addEventListener("resize",c,true),at={el:a,trigger:n,onOutside:l,reflow:c};}),n}function Sc(){lo();}var ff=[1,2,3,4,5],Cc="vela-width-field";function bf(){if(typeof document>"u"||document.getElementById(Cc))return;let s=document.createElement("style");s.id=Cc,s.textContent=`
92
92
  .vela-width-field{height:28px;padding:0 8px;border:1px solid var(--vela-border-strong);border-radius:var(--vela-radius-sm);background:var(--vela-surface-elev);cursor:pointer;display:inline-flex;align-items:center;gap:8px;flex:none;color:var(--vela-fg);font-family:inherit;outline:none;}
93
93
  .vela-width-field:hover{border-color:var(--vela-fg-muted);}
94
94
  .vela-width-field-pop{position:fixed;z-index:6000;background:var(--vela-surface-overlay);border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);padding:4px;display:flex;flex-direction:column;gap:1px;color:var(--vela-fg);}
95
95
  .vela-width-field-item{display:flex;align-items:center;gap:8px;min-width:96px;padding:5px 8px;border:none;border-radius:5px;background:transparent;color:inherit;cursor:pointer;text-align:left;font:inherit;}
96
96
  .vela-width-field-item:hover{background:var(--vela-hover-strong);}
97
97
  .vela-width-field-item[data-active='1']{background:var(--vela-active);}
98
- `,document.head.appendChild(s);}function Cc(s){return `<svg width="22" height="14" viewBox="0 0 22 14" fill="none"><line x1="2" y1="7" x2="20" y2="7" stroke="currentColor" stroke-width="${s}" stroke-linecap="round"/></svg>`}var ff='<svg width="8" height="5" viewBox="0 0 8 5" fill="none"><path d="M1 1l3 3 3-3" stroke="#868a96" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',lt=null;function Qn(){lt&&(document.removeEventListener("pointerdown",lt.onOutside,true),window.removeEventListener("resize",lt.reflow,true),lt.el.remove(),lt=null);}function Tc(s,e){let t=e.getBoundingClientRect(),n=s.offsetWidth,r=s.offsetHeight,i=t.right-n,o=t.bottom+6;i<6&&(i=6),i+n>window.innerWidth-6&&(i=window.innerWidth-n-6),o+r>window.innerHeight-6&&(o=t.top-r-6),o<6&&(o=6),s.style.left=`${Math.round(i)}px`,s.style.top=`${Math.round(o)}px`;}function Mc(s,e,t){mf();let n=document.createElement("button");n.type="button",n.className="vela-width-field";let r=()=>{n.innerHTML=`<span style="display:flex;">${Cc(e())}</span><span style="display:flex;">${ff}</span>`;};return r(),n.addEventListener("click",i=>{if(i.stopPropagation(),lt&&lt.trigger===n){Qn();return}Qn();let o=document.createElement("div");o.className="vela-width-field-pop",ne(o,s),o.style.font=`var(--vela-font-size-md) ${s.fontFamily}`,o.addEventListener("pointerdown",c=>c.stopPropagation());for(let c of pf){let d=document.createElement("button");d.type="button",d.className="vela-width-field-item",d.dataset.active=c===e()?"1":"0",d.innerHTML=`<span style="display:flex;flex:none;">${Cc(c)}</span><span style="flex:1;font-variant-numeric:tabular-nums;">${c}px</span>`,d.addEventListener("click",h=>{h.stopPropagation(),Qn(),t(c),r();}),o.appendChild(d);}document.body.appendChild(o),Tc(o,n);let a=c=>{let d=c.target;o.contains(d)||n.contains(d)||Qn();},l=()=>Tc(o,n);setTimeout(()=>document.addEventListener("pointerdown",a,true),0),window.addEventListener("resize",l,true),lt={el:o,trigger:n,onOutside:a,reflow:l};}),n}function Lc(){Qn();}var bf={candles:"Candles",bars:"Bars",line:"Line",area:"Area",baseline:"Baseline"};function gf(s){return Ue(s)?.label??bf[s]??s}var Pc="vela-settings-controls",vf="var(--vela-surface)",lo="var(--vela-border)",yf="var(--vela-fg)";function xf(){if(typeof document>"u"||document.getElementById(Pc))return;let s=document.createElement("style");s.id=Pc,s.textContent=`
98
+ `,document.head.appendChild(s);}function Tc(s){return `<svg width="22" height="14" viewBox="0 0 22 14" fill="none"><line x1="2" y1="7" x2="20" y2="7" stroke="currentColor" stroke-width="${s}" stroke-linecap="round"/></svg>`}var gf='<svg width="8" height="5" viewBox="0 0 8 5" fill="none"><path d="M1 1l3 3 3-3" stroke="#868a96" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',lt=null;function Qn(){lt&&(document.removeEventListener("pointerdown",lt.onOutside,true),window.removeEventListener("resize",lt.reflow,true),lt.el.remove(),lt=null);}function Mc(s,e){let t=e.getBoundingClientRect(),n=s.offsetWidth,r=s.offsetHeight,i=t.right-n,o=t.bottom+6;i<6&&(i=6),i+n>window.innerWidth-6&&(i=window.innerWidth-n-6),o+r>window.innerHeight-6&&(o=t.top-r-6),o<6&&(o=6),s.style.left=`${Math.round(i)}px`,s.style.top=`${Math.round(o)}px`;}function Lc(s,e,t){bf();let n=document.createElement("button");n.type="button",n.className="vela-width-field";let r=()=>{n.innerHTML=`<span style="display:flex;">${Tc(e())}</span><span style="display:flex;">${gf}</span>`;};return r(),n.addEventListener("click",i=>{if(i.stopPropagation(),lt&&lt.trigger===n){Qn();return}Qn();let o=document.createElement("div");o.className="vela-width-field-pop",ne(o,s),o.style.font=`var(--vela-font-size-md) ${s.fontFamily}`,o.addEventListener("pointerdown",c=>c.stopPropagation());for(let c of ff){let d=document.createElement("button");d.type="button",d.className="vela-width-field-item",d.dataset.active=c===e()?"1":"0",d.innerHTML=`<span style="display:flex;flex:none;">${Tc(c)}</span><span style="flex:1;font-variant-numeric:tabular-nums;">${c}px</span>`,d.addEventListener("click",h=>{h.stopPropagation(),Qn(),t(c),r();}),o.appendChild(d);}document.body.appendChild(o),Mc(o,n);let a=c=>{let d=c.target;o.contains(d)||n.contains(d)||Qn();},l=()=>Mc(o,n);setTimeout(()=>document.addEventListener("pointerdown",a,true),0),window.addEventListener("resize",l,true),lt={el:o,trigger:n,onOutside:a,reflow:l};}),n}function Pc(){Qn();}var vf={candles:"Candles",bars:"Bars",line:"Line",area:"Area",baseline:"Baseline"};function yf(s){return Ue(s)?.label??vf[s]??s}var Ec="vela-settings-controls",xf="var(--vela-surface)",co="var(--vela-border)",wf="var(--vela-fg)";function Sf(){if(typeof document>"u"||document.getElementById(Ec))return;let s=document.createElement("style");s.id=Ec,s.textContent=`
99
99
  .vela-sd-check{width:18px;height:18px;flex:none;display:inline-flex;align-items:center;justify-content:center;padding:0;border:1px solid var(--vela-border-strong);border-radius:5px;background:transparent;color:transparent;cursor:pointer;}
100
100
  .vela-sd-check:hover{border-color:var(--vela-fg-muted);}
101
101
  .vela-sd-check.on{background:var(--vela-selected-bg);border-color:var(--vela-selected-bg);color:var(--vela-selected-fg);}
@@ -182,11 +182,11 @@ void main() {
182
182
  .vela-sd-mobile .vela-sd-close{width:40px;height:40px;}
183
183
  .vela-sd-mobile .vela-sd-btn{height:38px;}
184
184
  .vela-sd-mobile .vela-sd-row span,.vela-sd-mobile .vela-sd-bool span{white-space:normal !important;}
185
- `,document.head.appendChild(s);}var er=class{constructor(e,t){this.container=e;this.theme=t;this.root=null;this.onChange=null;this.onImport=null;this.onReset=null;this.config=null;this.syncTypeTabs=null;this.hostSections=[];this.themeControl=null;this.tabs=[];this.typeActiveInstance=new Map;this.typeActiveGroup=new Map;this.activeSection=null;this.mobileLayout=false;getComputedStyle(e).position==="static"&&(e.style.position="relative");}setHostSections(e){this.hostSections=e;}setThemeControl(e,t){this.themeControl={current:e,onSelect:t};}refreshConfig(e){this.config&&(this.config=e);}setTheme(e){this.theme=e,this.reopenIfLive();}setLayoutMode(e){let t=e==="mobile";t!==this.mobileLayout&&(this.mobileLayout=t,this.reopenIfLive());}reopenIfLive(){if(!this.root)return;let e=this.config,t=this.onChange,n=this.onImport,r=this.onReset,i=this.activeSection;this.close(),e&&t&&this.open(e,t,n??void 0,r??void 0,i??void 0);}isOpen(){return this.root!==null}toggle(e,t,n,r,i){this.root?this.close():this.open(e,t,n,r,i);}showSection(e){this.tabs.find(t=>t.title.toLowerCase()===e.toLowerCase())?.show();}open(e,t,n,r,i){this.close(),this.config=e,this.onChange=t,this.onImport=n??null,this.onReset=r??null,xf();let o=this.mobileLayout,a=document.createElement("div");a.style.cssText="position:absolute;inset:0;z-index:var(--vela-z-dialog);display:flex;align-items:flex-start;justify-content:center;background:transparent;padding-top:8vh;pointer-events:auto;",o&&(a.classList.add("vela-sd-mobile"),a.style.paddingTop="0",a.style.alignItems="stretch"),a.addEventListener("mousedown",w=>{w.target===a&&this.close();});let l=document.createElement("div");l.style.cssText=`width:fit-content;min-width:min(560px,94vw);max-width:min(720px,94vw);max-height:70vh;display:flex;flex-direction:column;background:${vf};border:1px solid ${lo};border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow-dialog);color:${yf};font:13px var(--vela-font);overflow:hidden;cursor:default;`,o&&(l.style.cssText+="width:100%;min-width:0;max-width:none;max-height:none;flex:1 1 auto;border:none;border-radius:0;");let c=document.createElement("div");c.style.cssText=`display:flex;justify-content:space-between;align-items:center;padding:9px 9px 9px 16px;border-bottom:1px solid ${lo};flex:0 0 auto;user-select:none;`,o&&(c.style.paddingLeft="8px");let d=document.createElement("span");d.textContent="Chart settings",d.style.cssText="font-size:17px;font-weight:600;letter-spacing:0.2px;",o&&(d.style.cssText+="flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;");let h=null;if(o){let w=document.createElement("button");w.type="button",w.className="vela-sd-burger",w.innerHTML=oe("burger",16),w.title="Sections",w.addEventListener("click",()=>h?.()),c.append(w);}let u=document.createElement("button");if(u.type="button",u.innerHTML=oe("close",15),u.title="Close",u.className="vela-sd-close",u.addEventListener("click",()=>this.close()),c.append(d,u),!o){c.style.cursor="move";let w=0,H=0,z=0,te=0,pe=false;c.addEventListener("pointerdown",Y=>{Y.target?.closest(".vela-sd-close")||(pe=true,w=Y.clientX-z,H=Y.clientY-te,c.setPointerCapture(Y.pointerId));}),c.addEventListener("pointermove",Y=>{pe&&(z=Y.clientX-w,te=Y.clientY-H,l.style.transform=`translate(${z}px, ${te}px)`);}),c.addEventListener("pointerup",()=>pe=false);}l.appendChild(c);let p=document.createElement("div");p.style.cssText="display:flex;flex-direction:column;gap:0;",p.append(this.section("Symbol")),p.append(this.sectionTitle("Chart type"));let m={},f=w=>{let H=w==="heikinashi"?"candles":w;for(let z of tn()){let te=m[z];te&&(te.style.display=z===H?"contents":"none");}};p.append(this.selectRowLabeled("Type",e.series.style,tn().map(w=>[w,gf(w)]),w=>{this.emit({series:{style:w}}),f(w),this.syncTypeTabs?.(w);}));let b=this.group();b.append(this.sectionTitle("Candles")),b.append(this.toggleRow("Body",e.candles.bodyVisible,w=>this.emit({candles:{bodyVisible:w}}),[this.swatch(e.candles.upColor,w=>this.emit({candles:{upColor:w}})),this.swatch(e.candles.downColor,w=>this.emit({candles:{downColor:w}}))])),b.append(this.toggleRow("Borders",e.candles.borderVisible,w=>this.emit({candles:{borderVisible:w}}),[this.swatch(e.candles.borderUpColor,w=>this.emit({candles:{borderUpColor:w}})),this.swatch(e.candles.borderDownColor,w=>this.emit({candles:{borderDownColor:w}}))])),b.append(this.toggleRow("Wick",e.candles.wickVisible,w=>this.emit({candles:{wickVisible:w}}),[this.swatch(e.candles.wickUpColor,w=>this.emit({candles:{wickUpColor:w}})),this.swatch(e.candles.wickDownColor,w=>this.emit({candles:{wickDownColor:w}}))])),b.append(this.numberRow("Spacing",e.series.spacing,.1,10,.1,w=>this.emit({series:{spacing:w}}))),m.candles=b,p.append(b);let g=this.group();g.append(this.sectionTitle("Bars")),g.append(this.colorRow("Color Up",e.bars.upColor,w=>this.emit({bars:{upColor:w}}))),g.append(this.colorRow("Color Down",e.bars.downColor,w=>this.emit({bars:{downColor:w}}))),g.append(this.numberRow("Spacing",e.series.spacing,.1,10,.1,w=>this.emit({series:{spacing:w}}))),m.bars=g,p.append(g);let v=this.group();v.append(this.sectionTitle("Line")),v.append(this.colorRow("Color",e.line.color,w=>this.emit({line:{color:w}}))),v.append(this.numberRow("Width",e.line.width,1,10,1,w=>this.emit({line:{width:w}}))),m.line=v,p.append(v);let y=this.group();y.append(this.sectionTitle("Area")),y.append(this.colorRow("Line color",e.area.lineColor,w=>this.emit({area:{lineColor:w}}))),y.append(this.numberRow("Width",e.area.width,1,10,1,w=>this.emit({area:{width:w}}))),y.append(this.colorRow("Top fill",e.area.topColor,w=>this.emit({area:{topColor:w}}))),y.append(this.colorRow("Bottom fill",e.area.bottomColor,w=>this.emit({area:{bottomColor:w}}))),m.area=y,p.append(y);let x=this.group();x.append(this.sectionTitle("Baseline")),x.append(this.rowWith("Top line",[this.swatch(e.baseline.topLineColor,w=>this.emit({baseline:{topLineColor:w}}))])),x.append(this.rowWith("Bottom line",[this.swatch(e.baseline.bottomLineColor,w=>this.emit({baseline:{bottomLineColor:w}}))])),x.append(this.rowWith("Fill top area",[this.swatch(e.baseline.topFillColor,w=>this.emit({baseline:{topFillColor:w}})),this.swatch(e.baseline.topFillColor2,w=>this.emit({baseline:{topFillColor2:w}}))])),x.append(this.rowWith("Fill bottom area",[this.swatch(e.baseline.bottomFillColor2,w=>this.emit({baseline:{bottomFillColor2:w}})),this.swatch(e.baseline.bottomFillColor,w=>this.emit({baseline:{bottomFillColor:w}}))])),x.append(this.numberRow("Base level %",e.baseline.baselineLevel,0,100,1,w=>this.emit({baseline:{baselineLevel:w}}))),x.append(this.numberRow("Width",e.baseline.width,1,10,1,w=>this.emit({baseline:{width:w}}))),m.baseline=x,p.append(x);for(let w of Ge()){if(!is(w.id))continue;let H=e.chartTypes[w.id]??{},z=(Y,Io)=>typeof H[Y]=="string"&&H[Y]!==""?H[Y]:Io,te=(Y,Io)=>typeof H[Y]=="boolean"?H[Y]:Io,pe=this.group();pe.append(this.sectionTitle("Candles")),pe.append(this.toggleRow("Body",te("candleBodyVisible",e.candles.bodyVisible),Y=>this.emitType(w.id,"candleBodyVisible",Y),[this.swatch(z("candleUpColor",e.candles.upColor),Y=>this.emitType(w.id,"candleUpColor",Y)),this.swatch(z("candleDownColor",e.candles.downColor),Y=>this.emitType(w.id,"candleDownColor",Y))])),pe.append(this.toggleRow("Borders",te("candleBorderVisible",e.candles.borderVisible),Y=>this.emitType(w.id,"candleBorderVisible",Y),[this.swatch(z("candleBorderUpColor",e.candles.borderUpColor),Y=>this.emitType(w.id,"candleBorderUpColor",Y)),this.swatch(z("candleBorderDownColor",e.candles.borderDownColor),Y=>this.emitType(w.id,"candleBorderDownColor",Y))])),pe.append(this.toggleRow("Wick",te("candleWickVisible",e.candles.wickVisible),Y=>this.emitType(w.id,"candleWickVisible",Y),[this.swatch(z("candleWickUpColor",e.candles.wickUpColor),Y=>this.emitType(w.id,"candleWickUpColor",Y)),this.swatch(z("candleWickDownColor",e.candles.wickDownColor),Y=>this.emitType(w.id,"candleWickDownColor",Y))])),pe.append(this.numberRow("Spacing",e.series.spacing,.1,10,.1,Y=>this.emit({series:{spacing:Y}}))),m[w.id]=pe,p.append(pe);}f(e.series.style),p.append(this.sectionTitle("Time zone")),p.append(this.selectRowLabeled("Time zone",so(e.timeScale.timezone),Sf(e.timeScale.timezone),w=>this.emit({timeScale:{timezone:w}})));let S=w=>{for(let H of this.hostSections)if((H.placement??"after-symbol")===w){p.append(w==="symbol"?this.sectionTitle(H.title):this.section(H.title));for(let z of H.rows)z.kind==="heading"?p.append(this.sectionTitle(z.label)):z.kind==="toggle"?p.append(this.boolRow(z.label,z.get(),te=>z.set(te))):p.append(this.selectRowLabeled(z.label,z.get(),z.options.map(te=>[te,te]),te=>z.set(te)));}},C=w=>{for(let H of Ge()){let z=H.settings;z&&(z.placement??"end")===w&&this.chartTypeSection(H.id,z,e,p);}};if(S("symbol"),C("after-symbol"),S("after-symbol"),p.append(this.section("Scales and lines")),p.append(this.sectionTitle("Price scale")),p.append(this.selectRowLabeled("Mode",e.priceScale.log?"log":e.priceScale.mode,[["price","Regular"],["percent","Percent"],["indexed","Indexed to 100"],["log","Logarithmic"]],w=>this.emit({priceScale:w==="log"?{mode:"price",log:true}:{mode:w,log:false}}))),p.append(this.boolRow("Invert scale",e.priceScale.invert,w=>this.emit({priceScale:{invert:w}}))),p.append(this.separator()),p.append(this.boolRow("Last Price Line",e.priceScale.currentPriceLine,w=>this.emit({priceScale:{currentPriceLine:w}}))),p.append(this.boolRow("Last price label",e.priceScale.priceLabel,w=>this.emit({priceScale:{priceLabel:w}}))),p.append(this.boolRow("Countdown to bar close",e.priceScale.countdown,w=>this.emit({priceScale:{countdown:w}}))),p.append(this.boolRow("Axis labels",e.priceScale.labelsVisible,w=>this.emit({priceScale:{labelsVisible:w}}))),p.append(this.colorRow("Scale border color",e.priceScale.borderColor,w=>this.emit({priceScale:{borderColor:w}}))),p.append(this.sectionTitle("Crosshair")),p.append(this.colorRow("Color",e.crosshair.color,w=>this.emit({crosshair:{color:w}}))),p.append(this.numberRow("Width",e.crosshair.width,.5,8,.5,w=>this.emit({crosshair:{width:w}}))),p.append(this.selectRowLabeled("Style",e.crosshair.style,[["solid","Solid"],["dashed","Dashed"],["dotted","Dotted"]],w=>this.emit({crosshair:{style:w}}))),p.append(this.section("Canvas")),p.append(this.sectionTitle("Background & text")),p.append(this.colorRow("Background",e.layout.background,w=>this.emit({layout:{background:w}}))),p.append(this.colorRow("Text color",e.layout.textColor,w=>this.emit({layout:{textColor:w}}))),p.append(this.numberRow("Text size",e.layout.fontSize,6,32,1,w=>this.emit({layout:{fontSize:w}}))),p.append(this.colorRow("Pane separator color",e.panes.separatorColor,w=>this.emit({panes:{separatorColor:w}}))),p.append(this.sectionTitle("Grid")),p.append(this.toggleRow("Vertical",e.grid.vertLines.visible,w=>this.emit({grid:{vertLines:{visible:w}}}),[this.swatch(e.grid.vertLines.color,w=>this.emit({grid:{vertLines:{color:w}}}))])),p.append(this.toggleRow("Horizontal",e.grid.horzLines.visible,w=>this.emit({grid:{horzLines:{visible:w}}}),[this.swatch(e.grid.horzLines.color,w=>this.emit({grid:{horzLines:{color:w}}}))])),this.themeControl){let w=this.themeControl;p.append(this.sectionTitle("Theme")),p.append(this.selectRow("Color theme",w.current==="dark"?"Dark":"Light",["Dark","Light"],H=>w.onSelect(H==="Dark"?"dark":"light")));}C("end"),S("end");let T=document.createElement("div");T.style.cssText=o?"display:flex;min-height:0;flex:1 1 auto;position:relative;overflow:hidden;":"display:flex;min-height:360px;max-height:calc(70vh - 100px);flex:1 1 auto;";let M=document.createElement("div");M.className="vela-sd-rail",M.style.cssText=o?"display:flex;flex-direction:column;gap:2px;padding:10px 8px;overflow-y:auto;":`flex:0 0 170px;display:flex;flex-direction:column;gap:2px;padding:10px 8px;border-right:1px solid ${lo};overflow-y:auto;`;let E=null;o&&(E=document.createElement("div"),E.className="vela-sd-railscrim",E.addEventListener("click",()=>h?.()),h=w=>{let H=w??!M.classList.contains("open");M.classList.toggle("open",H),E?.classList.toggle("open",H);});let k=document.createElement("div");k.className="vela-sd-pane",k.style.cssText=o?"flex:1;min-width:0;overflow-y:auto;padding:6px 14px calc(14px + env(safe-area-inset-bottom, 0px));":"flex:1;overflow-y:auto;padding:6px 18px 14px;";let L=[],P=null;for(let w of [...p.children]){let H=w.dataset.sdTab;if(H!==void 0){let z=document.createElement("div");z.style.display="none";let te=document.createElement("button");te.type="button",te.textContent=H,te.className="vela-sd-tab"+(w.dataset.sdSub!==void 0?" vela-sd-tab-sub":""),L.push({title:H,el:z,tab:te,style:w.dataset.sdStyle,visibility:w.dataset.sdVisibility}),P=z,w.remove();continue}P&&P.appendChild(w);}this.syncTypeTabs=w=>{let H=false;L.forEach((z,te)=>{if(!z.style)return;let pe=z.visibility==="always"||z.style===w||w==="heikinashi"&&z.style==="heikinashi";z.tab.style.display=pe?"":"none",!pe&&z.el.style.display==="block"&&(H=true);}),H&&V(0);};let V=w=>{L.forEach((H,z)=>{H.el.style.display=z===w?"block":"none",H.tab.classList.toggle("on",z===w);}),this.activeSection=L[w]?.title??null,o&&(d.textContent=L[w]?.title??"Chart settings",h?.(false));};L.forEach((w,H)=>{w.tab.addEventListener("click",()=>V(H)),M.appendChild(w.tab),k.appendChild(w.el);}),this.tabs=L.map((w,H)=>({title:w.title,show:()=>V(H)}));let G=i!==void 0?L.findIndex(w=>w.title.toLowerCase()===i.toLowerCase()):L.findIndex(w=>w.style===e.series.style&&!w.tab.classList.contains("vela-sd-tab-sub"));V(G>=0?G:0),this.syncTypeTabs?.(e.series.style),T.append(M,k),E&&T.append(E),l.appendChild(T),l.appendChild(this.footer(e)),a.appendChild(l),this.container.appendChild(a),this.root=a;for(let w of L){let H=[...w.el.querySelectorAll("[data-sd-rows-host]")];if(H.length===0){this.layoutSettingsGrids(w.el,l);continue}for(let z of H)this.layoutSettingsGrids(z,l);}}close(){wc(),Lc(),this.root?.remove(),this.root=null,this.tabs=[];}destroy(){this.close(),this.onChange=null,this.onImport=null,this.config=null;}emitType(e,t,n){this.emit({chartTypes:{[e]:{[t]:n}}});}emit(e){this.onChange?.(e);}sectionTitle(e){let t=document.createElement("div");return t.className="vela-sd-sect",t.style.cssText="margin:24px 0 0;padding-bottom:8px;font-size:var(--vela-font-size-sm);font-weight:700;letter-spacing:0.05em;text-transform:uppercase;color:var(--vela-fg-muted);",t.textContent=e,t}chartTypeSection(e,t,n,r){let i=this.section(t.title);i.dataset.sdStyle=e,i.dataset.sdVisibility=t.visibility??"active",r.append(i);let o=n.chartTypes[e]??{},a={},l=h=>{for(let u of h)for(let p of Rn(u)){let m=o[p.key];a[p.key]=typeof m===p.type?m:p.defval;}};t.rows&&l(t.rows);for(let h of t.instances??[])l(h.rows);for(let h of t.subsections??[])l(h.rows);for(let h of t.instances??[])!h.enableKey||h.enableKey in a||(a[h.enableKey]=o[h.enableKey]===true);for(let h of t.subsections??[])!h.enableKey||h.enableKey in a||(a[h.enableKey]=o[h.enableKey]===true);let c=[],d=(h,u)=>{a[h]=u,this.emitType(e,h,u);for(let p of c)p();};t.instances&&t.instances.length>0?r.append(this.instancesBlock(e,t.instances,a,d,c)):t.rows&&(t.layout==="grouped"?r.append(this.groupedRows(`${e}/rows`,t.rows,a,d,c)):this.flatTypeRows(t.rows,a,d,c,r));for(let h of t.subsections??[]){let u=this.section(h.title);u.dataset.sdStyle=e,u.dataset.sdVisibility=t.visibility??"active",u.dataset.sdSub="1",r.append(u),r.append(this.groupedRows(`${e}/${h.title}`,h.rows,a,d,c,h.enableKey));}for(let h of c)h();}flatTypeRows(e,t,n,r,i){let o=[];for(let a of e){let l=a.kind==="heading"||a.kind==="header"?this.sectionTitle(a.label):this.typeRow(a,t,n,r);o.push({el:l,when:a.when}),i.append(l);}r.push(()=>{for(let a of o)a.el.classList.toggle("vela-sd-hide",!Lt(a.when,t));});}typeRow(e,t,n,r){let i=Ei(e),o=[];for(let a of i.controls){let l=this.inlineControl(a,t,n,i.toggle!==void 0);if(a.kind!=="hint"&&r.push(()=>l.dispatchEvent(new Event("vela-sync"))),a.kind!=="hint"&&a.when){l.dataset.sdSelfGated="1";let c=a.when;r.push(()=>{l.style.display=Lt(c,t)?"":"none";});}o.push(l);}if(i.toggle){let a=i.toggle,l=this.toggleRow(i.label,t[a.key],c=>n(a.key,c),o,()=>t[a.key]===true);return r.push(()=>l.dispatchEvent(new Event("vela-sync"))),l}return this.rowWith(i.label,o)}inlineControl(e,t,n,r){if(e.kind==="hint"){let a=document.createElement("span");return a.textContent=e.text,a.style.cssText="color:var(--vela-fg-muted);",a}if(e.kind==="color"){let a=this.swatch(t[e.key],l=>n(e.key,l),()=>t[e.key]);return a.title=e.label,a}if(e.kind==="width"){let a=typeof t[e.key]=="number"?t[e.key]:e.defval,l=Mc(this.theme,()=>a,c=>{a=c,n(e.key,c);});return l.title=e.label,l}if(e.kind==="select"){let a=document.createElement("select");a.className="vela-sd-select",a.style.cssText="max-width:200px;flex:0 0 auto;",a.title=e.label;let l=typeof t[e.key]=="string"?t[e.key]:e.defval;for(let[c,d]of wf(e.options)){let h=document.createElement("option");h.value=c,h.textContent=d,c===l&&(h.selected=true),a.appendChild(h);}return a.addEventListener("change",()=>n(e.key,a.value)),a.addEventListener("vela-sync",()=>{a.value=typeof t[e.key]=="string"?t[e.key]:e.defval;}),a}let i=document.createElement("input");i.type="number",i.className="vela-sd-number",r&&(i.style.width="56px"),e.min!==void 0&&(i.min=String(e.min)),e.max!==void 0&&(i.max=String(e.max)),i.step=String(e.step??1),i.title=e.label;let o=typeof t[e.key]=="number"?t[e.key]:e.defval;return e.placeholder!==void 0?(i.placeholder=e.placeholder,o!==e.defval&&(i.value=String(o)),i.addEventListener("change",()=>{let a=i.value.trim()===""?e.defval:Number(i.value),l=Number.isFinite(a)?Math.min(e.max??1/0,Math.max(e.min??-1/0,a)):e.defval;i.value=l===e.defval?"":String(l),n(e.key,l);})):(i.value=String(o),i.addEventListener("input",()=>{let a=Number(i.value);Number.isFinite(a)&&n(e.key,a);})),i}instancesBlock(e,t,n,r,i){let o=document.createElement("div"),a=document.createElement("div");a.className="vela-sd-itabs",(t.length>1||t[0]?.enableKey!==void 0)&&o.append(a);let l=t.map((h,u)=>{let p=this.groupedRows(`${e}/#${u}`,h.rows,n,r,i);return o.append(p),p}),c=h=>!h.enableKey||n[h.enableKey]===true,d=()=>{let h=this.typeActiveInstance.get(e)??0;c(t[h]??t[0])||(h=0),this.typeActiveInstance.set(e,h),a.replaceChildren(),t.forEach((p,m)=>{if(!c(p))return;let f=document.createElement("button");f.type="button",f.className="vela-sd-itab"+(m===h?" on":"");let b=document.createElement("span");if(b.textContent=p.label,f.append(b),m===h&&p.enableKey){let g=document.createElement("span");g.className="vela-sd-ix",g.textContent="\u2715",g.title=`Remove ${p.label}`,g.addEventListener("click",v=>{v.stopPropagation(),this.typeActiveInstance.set(e,0),r(p.enableKey,false);}),f.append(g);}f.addEventListener("click",()=>{this.typeActiveInstance.set(e,m),d();}),a.append(f);});let u=t.findIndex(p=>!c(p));if(u>=0){let p=document.createElement("button");p.type="button",p.className="vela-sd-itab vela-sd-itab-add",p.textContent="+",p.title=`Add ${t[u].label}`,p.addEventListener("click",()=>{this.typeActiveInstance.set(e,u),r(t[u].enableKey,true);}),a.append(p);}l.forEach((p,m)=>p.classList.toggle("vela-sd-hide",m!==h));};return i.push(d),o}groupedRows(e,t,n,r,i,o){let a=document.createElement("div");a.className="vela-sd-struct";let l=document.createElement("div");l.className="vela-sd-toc";let c=document.createElement("div");c.dataset.sdRowsHost="1",c.style.cssText="flex:1 1 auto;min-width:0;",a.append(l,c);let d=[],h=[],u=[],p=-1;for(let f of t){if(f.kind==="heading"){p=h.length,h.push(f.label),u.push(f.when);continue}if(f.kind==="header"){d.push({el:this.sectionTitle(f.label),when:f.when,group:p,header:true}),c.append(d[d.length-1].el);continue}let b=this.typeRow(f,n,r,i),g=f.kind==="row"?f.toggle?.key:f.kind==="range"?void 0:f.key;d.push({el:b,when:f.when,group:p,key:g}),c.append(b);}let m=()=>{let f=h.map((y,x)=>Lt(u[x],n)&&d.some(S=>S.group===x&&!S.header&&Lt(S.when,n))),b=h.indexOf(this.typeActiveGroup.get(e)??"");(b<0||!f[b])&&(b=f.findIndex(Boolean)),b>=0&&this.typeActiveGroup.set(e,h[b]),l.replaceChildren(),h.forEach((y,x)=>{if(!f[x])return;let S=document.createElement("button");S.type="button",S.className="vela-sd-toc-btn"+(x===b?" on":""),S.textContent=y,S.addEventListener("click",()=>{this.typeActiveGroup.set(e,y),m();}),l.append(S);});let g=f.some(Boolean);l.classList.toggle("vela-sd-hide",!g),a.classList.toggle("no-toc",!g);let v=!o||n[o]===true;for(let y=0;y<d.length;y++){let x=d[y],S=(x.group===-1||x.group===b)&&Lt(x.when,n);if(S&&x.header){let C=false;for(let T=y+1;T<d.length;T++){let M=d[T];if(M.group!==x.group||M.header)break;if(Lt(M.when,n)){C=true;break}}S=C;}x.el.classList.toggle("vela-sd-hide",!S),x.el.classList.toggle("vela-sd-soft",S&&!v&&x.key!==o);}};return i.push(m),a}separator(){let e=document.createElement("div");return e.className="vela-sd-sep",e.style.cssText="height:14px;",e}layoutSettingsGrids(e,t){if(e.childElementCount===0)return;if(this.mobileLayout){let l=document.createElement("div");for(l.style.cssText="display:grid;grid-template-columns:minmax(0,1fr) max-content;align-items:center;column-gap:12px;row-gap:16px;";e.firstChild;)l.appendChild(e.firstChild);e.appendChild(l),this.prepareGridItems(l);return}let n=[...e.querySelectorAll(".vela-sd-row")],r=document.createElement("div");r.style.cssText="position:absolute;left:-9999px;top:0;visibility:hidden;display:flex;flex-direction:column;font:13px var(--vela-font);pointer-events:none;",t.appendChild(r);let i=0;for(let l of n){let c=l.children[0];if(!c)continue;let d=c.cloneNode(true);r.appendChild(d),i=Math.max(i,d.getBoundingClientRect().width);}r.remove();let o=i>0?`${Math.ceil(i)}px`:"max-content",a=document.createElement("div");for(a.style.cssText=`display:grid;grid-template-columns:${o} max-content;align-items:center;column-gap:12px;row-gap:16px;`;e.firstChild;)a.appendChild(e.firstChild);e.appendChild(a),this.prepareGridItems(a);}prepareGridItems(e){for(let t of [...e.children]){if(t.dataset.sdGroup!==void 0){this.prepareGridItems(t);continue}t.classList.contains("vela-sd-row")?t.style.display="contents":(t.classList.contains("vela-sd-bool")||t.classList.contains("vela-sd-sect")||t.classList.contains("vela-sd-sep"))&&(t.style.gridColumn="1 / -1");}}swatch(e,t,n){let r=e;return xs(this.theme,()=>n?n():r,i=>{r=i,t(i);})}rowWith(e,t){let{wrap:n}=this.row(e),r=document.createElement("div");r.style.cssText="display:flex;align-items:center;gap:6px;flex:0 0 auto;";for(let i of t)r.appendChild(i);return n.appendChild(r),n}section(e){let t=document.createElement("div");return t.dataset.sdTab=e,t.style.display="none",t}group(){let e=document.createElement("div");return e.dataset.sdGroup="",e.style.cssText="display:contents;",e}row(e){let t=document.createElement("div");t.className="vela-sd-row";let n=document.createElement("span");return n.textContent=e,n.style.cssText="opacity:0.85;white-space:nowrap;",t.appendChild(n),{wrap:t}}colorRow(e,t,n){let{wrap:r}=this.row(e),i=t;return r.appendChild(xs(this.theme,()=>i,o=>{i=o,n(o);})),r}boolRow(e,t,n){return this.toggleRow(e,t,n,[])}toggleRow(e,t,n,r,i){let o=document.createElement("div"),a=document.createElement("button");a.type="button",a.className="vela-sd-check"+(t?" on":""),a.innerHTML=oe("check",11);let l=t,c=()=>(l=!l,a.classList.toggle("on",l),l),d=document.createElement("span");if(d.textContent=e,d.style.cssText="opacity:0.85;white-space:nowrap;",r.length===0)return o.className="vela-sd-bool",o.style.cssText="display:flex;align-items:center;gap:8px;min-height:22px;",o.append(a,d),a.addEventListener("click",()=>n(c())),i&&o.addEventListener("vela-sync",()=>{l=i(),a.classList.toggle("on",l);}),o;o.className="vela-sd-row";let h=document.createElement("div");h.style.cssText="display:flex;align-items:center;gap:8px;",h.append(a,d);let u=document.createElement("div");u.style.cssText="display:flex;align-items:center;gap:6px;";for(let m of r)u.appendChild(m);let p=m=>{for(let f of r)f.dataset.sdSelfGated!=="1"&&(f.style.opacity=m?"1":"0.4",f.style.pointerEvents=m?"":"none");};return p(t),a.addEventListener("click",()=>{let m=c();n(m),p(m);}),i&&o.addEventListener("vela-sync",()=>{l=i(),a.classList.toggle("on",l),p(l);}),o.append(h,u),o}numberRow(e,t,n,r,i,o){let{wrap:a}=this.row(e),l=document.createElement("input");return l.type="number",l.value=String(t),l.min=String(n),l.max=String(r),l.step=String(i),l.className="vela-sd-number",l.addEventListener("input",()=>{let c=Number(l.value);Number.isFinite(c)&&o(c);}),a.appendChild(l),a}selectRowLabeled(e,t,n,r){let{wrap:i}=this.row(e),o=document.createElement("select");o.className="vela-sd-select",o.style.cssText="max-width:200px;flex:0 0 auto;";for(let[a,l]of n){let c=document.createElement("option");c.value=a,c.textContent=l,a===t&&(c.selected=true),o.appendChild(c);}return o.addEventListener("change",()=>r(o.value)),i.appendChild(o),i}selectRow(e,t,n,r){let{wrap:i}=this.row(e),o=document.createElement("select");o.className="vela-sd-select",o.style.cssText="max-width:200px;flex:0 0 auto;";for(let a of n){let l=document.createElement("option");l.value=a,l.textContent=a,a===t&&(l.selected=true),o.appendChild(l);}return o.addEventListener("change",()=>r(o.value)),i.appendChild(o),i}footer(e){let t=document.createElement("div");t.style.cssText=`border-top:1px solid ${lo};padding:10px 14px;display:flex;align-items:center;justify-content:flex-start;gap:8px;flex:0 0 auto;`;let n=document.createElement("button");return n.type="button",n.textContent="Reset defaults",n.className="vela-sd-btn",n.addEventListener("click",()=>this.onReset?.()),t.appendChild(n),t}};function wf(s){return s.map(e=>typeof e=="string"?[e,e]:e)}function Sf(s){let e=gs.map(n=>[n.value,vs(n.value,n.label)]),t=so(s);return gs.some(n=>n.value===t)?e:[[t,vs(t,t)],...e]}var Cf=4.5,Tf=R,Mf=W(he,.55),Lf=.7,Ec=xa,Pf=gr,kc={selected:.3,hovered:.12};function ws(s){let e=new Set(s.selected);return s.dragged&&e.add(s.dragged),s.hovered&&e.add(s.hovered),s.mutedLabel&&e.delete(s.mutedLabel),e}var co=class{constructor(){this.targets={};}paintAll(e,t,n,r,i={}){this.targets=i;for(let o of t)o.visible&&this.paintClipped(e,o,n,()=>this.paintOne(e,o,n,r));this.targets={},this.paintHighlights(e,t,n,ws(i));}paintHighlights(e,t,n,r){if(r.size!==0)for(let i of t)i.visible&&r.has(i.id)&&this.paintClipped(e,i,n,()=>this.paintHandles(e,i.handlePoints(n)));}paintClipped(e,t,n,r){if(!n.paneRect){r();return}let i=n.paneRect(t.paneId);!i||i.height<=0||(e.save(),e.beginPath(),e.rect(0,i.top,n.width,i.height),e.clip(),r(),e.restore());}paintGhost(e,t,n,r){e.globalAlpha=Lf,t instanceof ze||t instanceof Re?this.paintTimeSpanGhost(e,t,n):this.paintOne(e,t,n,r),e.globalAlpha=1;}paintTimeSpanGhost(e,t,n){let r=t.anchors[0],i=t.anchors[1];if(!r)return;let o=t instanceof ze?t.reg?.midColor||he:he,a=h=>{let u=n.xOf(h);e.save(),e.strokeStyle=o,e.globalAlpha=.6*e.globalAlpha,e.lineWidth=1,e.setLineDash([4,4]),e.beginPath(),e.moveTo(u,0),e.lineTo(u,n.height),e.stroke(),e.restore();};a(r.time),i&&a(i.time);let l=n.yOf(r.price,t.paneId),c=i?n.yOf(i.price,t.paneId):null,d=[];l!=null&&d.push([n.xOf(r.time),l]),i&&c!=null&&(e.save(),e.strokeStyle=o,e.lineWidth=1,e.setLineDash([]),e.beginPath(),e.moveTo(n.xOf(r.time),l??c),e.lineTo(n.xOf(i.time),c),e.stroke(),e.restore(),d.push([n.xOf(i.time),c])),this.paintHandles(e,d);}paintSnapRing(e,t,n,r){e.setLineDash([]),e.globalAlpha=.9,e.beginPath(),e.arc(t,n,5.5,0,Math.PI*2),e.strokeStyle=r.textColor,e.lineWidth=1.5,e.stroke(),e.globalAlpha=1;}paintOne(e,t,n,r){if(t.type==="highlighter"&&t instanceof J){this.paintHighlighter(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof J){if(this.paintSegments(e,t,n),t.type==="path"){let i=t.handlePoints(n);i.length>=2&&this.paintArrowhead(e,i[i.length-2],i[i.length-1],t.style);}this.paintLabel(e,t,n,r);return}if(t instanceof bt){this.paintArrowMark(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof gt){this.paintGlyphStamp(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof Me){this.paintRadialFib(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof wt){this.paintFibSpiral(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof Ct){this.paintDedekind(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof ye){this.paintMachFigure(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof St){this.paintFibRatios(e,t,n,r),this.paintGannArcs(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof ee){this.paintFibRatios(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof Tt){this.paintMeasureBox(e,t,n,r);return}if(t instanceof Oe){this.paintPosition(e,t,n,r);return}if(t instanceof ze){this.paintRegressionChannel(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof ft){this.paintAnchoredVwap(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof Re){this.paintFixedRangeVp(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof ae){this.paintPattern(e,t,n,r);return}if(t instanceof pt){this.paintComment(e,t,n,r);return}if(t instanceof ut){this.paintPriceNote(e,t,n,r);return}if(t instanceof mt){this.paintSignpost(e,t,n,r);return}if(t instanceof Ie){this.paintCallout(e,t,n,r);return}if(t instanceof dt){this.paintNote(e,t,n,r);return}if(t instanceof ht){this.paintPriceLabel(e,t,n,r);return}switch(t.type){case "hline":{let i=t.handlePoints(n);if(i.length===0)return;this.stroke(e,t.style,()=>{e.moveTo(0,i[0][1]),e.lineTo(n.width,i[0][1]);});break}case "trendline":case "arrow":{let i=t.handlePoints(n);if(i.length<2)return;this.stroke(e,t.style,()=>{e.moveTo(i[0][0],i[0][1]),e.lineTo(i[1][0],i[1][1]);}),t.style.arrowRight&&this.paintArrowhead(e,i[0],i[1],t.style),t.style.arrowLeft&&this.paintArrowhead(e,i[1],i[0],t.style);break}case "ellipse":{let i=t.handlePoints(n);if(i.length<2)return;let o=(i[0][0]+i[1][0])/2,a=(i[0][1]+i[1][1])/2,l=Math.abs(i[1][0]-i[0][0])/2,c=Math.abs(i[1][1]-i[0][1])/2;t.style.fillColor&&(e.save(),e.fillStyle=t.style.fillColor,e.beginPath(),e.ellipse(o,a,l,c,0,0,Math.PI*2),e.fill(),e.restore()),this.applyStroke(e,t.style),e.beginPath(),e.ellipse(o,a,l,c,0,0,Math.PI*2),e.stroke(),e.setLineDash([]);break}case "ray":{let i=t.handlePoints(n);if(i.length<2)return;let[o,a,l,c]=an(i[0][0],i[0][1],i[1][0],i[1][1],"right",n.width,n.height);this.stroke(e,t.style,()=>{e.moveTo(o,a),e.lineTo(l,c);});break}case "extendedline":{let i=t.handlePoints(n);if(i.length<2)return;let[o,a,l,c]=an(i[0][0],i[0][1],i[1][0],i[1][1],"both",n.width,n.height);this.stroke(e,t.style,()=>{e.moveTo(o,a),e.lineTo(l,c);});break}case "vline":{let i=t.handlePoints(n);if(i.length===0)return;this.stroke(e,t.style,()=>{e.moveTo(i[0][0],0),e.lineTo(i[0][0],n.height);});break}case "hray":{let i=t.handlePoints(n);if(i.length===0)return;this.stroke(e,t.style,()=>{e.moveTo(i[0][0],i[0][1]),e.lineTo(n.width,i[0][1]);});break}case "crossline":{let i=t.handlePoints(n);if(i.length===0)return;this.stroke(e,t.style,()=>{e.moveTo(0,i[0][1]),e.lineTo(n.width,i[0][1]),e.moveTo(i[0][0],0),e.lineTo(i[0][0],n.height);});break}case "infoline":this.paintInfoLine(e,t,n);break;case "trendangle":this.paintTrendAngle(e,t,n,r);break;case "circle":{let i=t.handlePoints(n);if(i.length<2)return;let o=i[0][0],a=i[0][1],l=Math.hypot(i[1][0]-o,i[1][1]-a);if(l<1)return;t.style.fillColor&&(e.save(),e.fillStyle=t.style.fillColor,e.beginPath(),e.arc(o,a,l,0,Math.PI*2),e.fill(),e.restore()),this.applyStroke(e,t.style),e.beginPath(),e.arc(o,a,l,0,Math.PI*2),e.stroke(),e.setLineDash([]);break}case "box":{let i=t.handlePoints(n);if(i.length<2)return;let o=Math.min(i[0][0],i[1][0]),a=Math.min(i[0][1],i[1][1]),l=Math.abs(i[1][0]-i[0][0]),c=Math.abs(i[1][1]-i[0][1]);t.style.fillColor&&(e.save(),e.fillStyle=t.style.fillColor,e.fillRect(o,a,l,c),e.restore()),this.applyStroke(e,t.style),e.strokeRect(o,a,l,c),e.setLineDash([]);break}}this.paintLabel(e,t,n,r);}paintLabel(e,t,n,r){let i=t.text;if(!i||!i.value||t.id===this.targets.mutedLabel)return;let o=kf(t,n);if(!o)return;let a=ce(i.size);e.font=`${i.bold?"bold ":""}${i.italic?"italic ":""}${a}px ${r.fontFamily}`,e.textBaseline="top",e.textAlign=o.align,e.fillStyle=i.color??r.textColor;let l=Ve(a),c=i.value.split(`
186
- `);c.forEach((d,h)=>e.fillText(d,o.x,o.top+h*l)),e.textAlign="left",t.type==="text"&&this.paintTextFrame(e,t.id,o.x,o.top,c,a,r);}paintTextFrame(e,t,n,r,i,o,a){let l=this.targets,c=l.selected?.has(t)?kc.selected:l.hovered===t?kc.hovered:0;if(c===0)return;let d=Ve(o),h=Math.max(8,...i.map(u=>e.measureText(u).width));e.save(),e.setLineDash([]),e.lineWidth=1,e.strokeStyle=W(a.textColor,c),je(e,n-At,r-(d-o)/2-Ot,h+At*2,i.length*d+Ot*2,4),e.stroke(),e.restore();}paintFibRatios(e,t,n,r){let i=t.entryLines(n);if(!i||i.length===0)return;for(let l of t.fillBands(n))e.save(),e.globalAlpha=.06*e.globalAlpha,e.fillStyle=l.color,e.fillRect(l.x,l.y,l.w,l.h),e.restore();e.textBaseline="middle";let o=`${ce(t.numbersSize)}px ${r.fontFamily}`,a=`${ce(t.labelsSize)}px ${r.fontFamily}`;for(let l of i)this.stroke(e,{...t.style,lineColor:l.color},()=>{e.moveTo(l.x1,l.y1),e.lineTo(l.x2,l.y2);}),e.fillStyle=l.color,e.font=o,e.textAlign=l.numberAlign,e.fillText(l.numberText,l.numberX,l.numberY),l.label&&(e.font=a,e.textAlign="center",e.fillText(l.label,l.labelX,l.labelY));e.textAlign="left",e.textBaseline="alphabetic";}paintRadialFib(e,t,n,r){let i=t.radial(n);if(i&&i.R0>=1){let o=`${ce(t.numbersSize)}px ${r.fontFamily}`,a=(i.a0+i.a1)/2;e.textBaseline="middle";for(let l of t.levels){if(!l.enabled)continue;let c=i.R0*l.ratio;c<.5||(this.applyStroke(e,{...t.style,lineColor:l.color}),e.beginPath(),e.arc(i.cx,i.cy,c,i.a0,i.a1),e.stroke(),e.setLineDash([]),e.fillStyle=l.color,e.font=o,e.textAlign="left",e.fillText(String(l.ratio),i.cx+Math.cos(a)*c+3,i.cy+Math.sin(a)*c));}e.textBaseline="alphabetic",e.textAlign="left";}for(let o of t.boundingLines(n))this.stroke(e,t.style,()=>{e.moveTo(o[0],o[1]),e.lineTo(o[2],o[3]);});}paintGannArcs(e,t,n){let r=t.arcGeom(n);if(!r||Math.abs(r.bx)<1||Math.abs(r.py)<1)return;let i=24;for(let o of Vo){this.applyStroke(e,{...t.style,lineColor:o.color}),e.beginPath();for(let a=0;a<=i;a+=1){let l=a/i*(Math.PI/2),c=r.ox+o.k*r.bx*Math.cos(l),d=r.oy+o.k*r.py*Math.sin(l);a===0?e.moveTo(c,d):e.lineTo(c,d);}e.stroke();}e.setLineDash([]);}paintFibSpiral(e,t,n){let r=t.spiralPoints(n);!r||r.length<2||this.stroke(e,t.style,()=>{e.moveTo(r[0][0],r[0][1]);for(let i=1;i<r.length;i+=1)e.lineTo(r[i][0],r[i][1]);});}paintMachFigure(e,t,n,r){let i=t.geom(n);if(i){for(let o of i.circles)this.applyStroke(e,{...t.style,lineColor:o.color}),e.beginPath(),e.arc(o.cx,o.cy,o.r,0,Math.PI*2),e.stroke();this.applyStroke(e,t.style),e.lineWidth=t.style.lineWidth+.5;for(let o of i.rays)e.beginPath(),e.moveTo(o[0],o[1]),e.lineTo(o[2],o[3]),e.stroke();if(e.beginPath(),e.arc(i.noseX,i.noseY,Math.max(2.5,t.style.lineWidth+1.5),0,Math.PI*2),e.fillStyle=t.style.lineColor,e.fill(),e.setLineDash([]),t.showRatios!==false){let o=`${ce("small")}px ${r.fontFamily}`;e.font=o,e.textBaseline="middle",e.textAlign="left";for(let a of i.circles){let l=a.cx+i.fx*a.r+4,c=a.cy+i.fy*a.r;e.fillStyle=a.color,e.fillText(Ef(a.ratio),l,c);}e.textBaseline="alphabetic",e.textAlign="left";}}}paintDedekind(e,t,n){let r=t.box(n),i=t.geodesics(n);if(!r||!i)return;let{left:o,right:a,top:l,bot:c}=r;e.save(),this.applyStroke(e,t.style),e.globalAlpha*=.45,e.strokeRect(o,l,a-o,c-l),e.restore(),e.save(),e.beginPath(),e.rect(o,l,a-o,c-l),e.clip(),this.applyStroke(e,t.style);for(let d of i)e.beginPath(),d.kind==="vline"?(e.moveTo(d.x,d.y0),e.lineTo(d.x,d.y1)):e.arc(d.cx,d.cy,d.r,Math.PI,0,false),e.stroke();e.setLineDash([]),e.restore();}paintMeasureBox(e,t,n,r){let i=t.handlePoints(n);if(i.length<2)return;let o=Math.min(i[0][0],i[1][0]),a=Math.min(i[0][1],i[1][1]),l=Math.abs(i[1][0]-i[0][0]),c=Math.abs(i[1][1]-i[0][1]),d=t.isUp()?q:X;e.save(),e.globalAlpha=.12*e.globalAlpha,e.fillStyle=d,e.fillRect(o,a,l,c),e.restore(),e.setLineDash(Dt(t.style.lineStyle,t.style.lineWidth)),e.strokeStyle=d,e.lineWidth=t.style.lineWidth,e.strokeRect(o,a,l,c),e.setLineDash([]);let h=t.measureLabel(n),u=ce(t.text?.size??"normal");e.fillStyle=t.text?.color??r.textColor,e.font=`${u}px ${r.fontFamily}`,e.textAlign="center",e.textBaseline="middle";let p=Math.round(u*1.35),m=a+c/2-(h.length-1)*p/2;h.forEach((f,b)=>e.fillText(f,o+l/2,m+b*p)),e.textAlign="left",e.textBaseline="alphabetic";}paintPosition(e,t,n,r){let i=t.layout(n);if(!i)return;let{x1:o,x2:a,ey:l,sy:c,ty:d}=i,h=a-o,u=(g,v,y)=>{e.save(),e.globalAlpha=.13*e.globalAlpha,e.fillStyle=y,e.fillRect(o,Math.min(g,v),h,Math.abs(v-g)),e.restore();};u(l,d,t.profitColor),u(l,c,t.lossColor);let p=(g,v)=>this.stroke(e,{...t.style,lineColor:v},()=>{e.moveTo(o,g),e.lineTo(a,g);});if(p(d,t.profitColor),p(c,t.lossColor),p(l,t.style.lineColor),!t.showText)return;let m=ce(t.text?.size??"normal");e.fillStyle=t.text?.color??r.textColor,e.textAlign="center",e.textBaseline="middle",e.font=`${m}px ${r.fontFamily}`;let f=o+h/2,b=Math.min(l,c,d)-9;t.showHeader&&e.fillText(t.headerLabel(),f,t.showLossSize?b-Math.round(m*1.15):b),e.font=`${Math.max(10,m-1)}px ${r.fontFamily}`,t.showLossSize&&e.fillText(t.lossSizeLabel(),f,b),t.showTargetLabel&&e.fillText(t.targetLabel(),f,(l+d)/2),t.showStopLabel&&e.fillText(t.stopLabel(),f,(l+c)/2),e.textAlign="left",e.textBaseline="alphabetic";}paintRegressionChannel(e,t,n,r){let i=t.layout(n);if(!i)return;let o=t.reg,a=(c,d,h,u,p)=>{e.save(),e.fillStyle=c,e.beginPath(),e.moveTo(i.x0,d),e.lineTo(i.x1,h),e.lineTo(i.x1,p),e.lineTo(i.x0,u),e.closePath(),e.fill(),e.restore();};a(o.upperFill,i.midY0,i.midY1,i.upperY0,i.upperY1),a(o.lowerFill,i.midY0,i.midY1,i.lowerY0,i.lowerY1);let l=(c,d,h,u)=>this.stroke(e,{lineColor:c,lineWidth:t.style.lineWidth,lineStyle:d},()=>{e.moveTo(i.x0,h),e.lineTo(i.x1,u);});if(l(o.upperColor,o.upperStyle,i.upperY0,i.upperY1),l(o.lowerColor,o.lowerStyle,i.lowerY0,i.lowerY1),l(o.midColor,o.midStyle,i.midY0,i.midY1),i.showR2){let c=`R\xB2 ${Math.round(i.r2*100)}%`;e.font=`11px ${r.fontFamily}`;let d=e.measureText(c).width,h=5,u=4,p=d+h*2,m=i.x0-u-p,f=i.midY0-9;e.save(),e.globalAlpha=.9*e.globalAlpha,je(e,m,f-8,p,16,3),e.fillStyle=Ec,e.fill(),e.restore(),e.fillStyle=r.textColor,e.textAlign="left",e.textBaseline="middle",e.fillText(c,m+h,f),e.textBaseline="alphabetic";}}paintFixedRangeVp(e,t,n,r){let i=t.layout(n);if(!i)return;let o=t.frvp,{profile:a,maxW:l,anchorX:c,grow:d,yEdges:h}=i;if(a.maxTotal<=0||l<=0)return;for(let f=0;f<a.rows.length;f+=1){let b=a.rows[f],g=b.up+b.down;if(g<=0)continue;let v=h[f],y=h[f+1],x=Math.min(v,y),S=Math.max(1,Math.abs(y-v)-1),C=g/a.maxTotal*l,T=b.up/g*C,M=f>=a.vaFrom&&f<=a.vaTo,E=M?o.vaUpColor:o.upColor,k=M?o.vaDownColor:o.downColor,L=d===1?c:c-C;T>0&&(e.fillStyle=E,e.fillRect(L,x,T,S)),C-T>0&&(e.fillStyle=k,e.fillRect(L+T,x,C-T,S));}let u=t.style.lineWidth,p=(f,b,g,v)=>{!f||v==null||Ic(b)||this.stroke(e,{lineColor:b,lineWidth:u,lineStyle:g},()=>{e.moveTo(i.x0,v),e.lineTo(i.x1,v);});};p(o.showVah,o.vahColor,o.vahStyle,i.vahY),p(o.showVal,o.valColor,o.valStyle,i.valY),p(o.showPoc,o.pocColor??be(r.background),o.pocStyle,i.pocY);let m=Math.max(1,u);if(o.showDevelopingPoc&&this.strokePolyline(e,i.developingPoc,{lineColor:o.developingPocColor,lineWidth:m,lineStyle:o.developingPocStyle}),o.showDevelopingVa){let f={lineColor:o.developingVaColor,lineWidth:m,lineStyle:o.developingVaStyle};this.strokePolyline(e,i.developingVaHigh,f),this.strokePolyline(e,i.developingVaLow,f);}}paintAnchoredVwap(e,t,n){let r=t.layout(n);if(!r)return;let i=t.vwap,o=t.style.lineWidth;if(r.upper.length>=2&&i.bandFill){e.save(),e.fillStyle=i.bandFill,e.beginPath(),e.moveTo(r.upper[0][0],r.upper[0][1]);for(let a=1;a<r.upper.length;a+=1)e.lineTo(r.upper[a][0],r.upper[a][1]);for(let a=r.lower.length-1;a>=0;a-=1)e.lineTo(r.lower[a][0],r.lower[a][1]);e.closePath(),e.fill(),e.restore();}this.strokePolyline(e,r.upper,{lineColor:i.upperColor,lineWidth:o,lineStyle:i.upperStyle}),this.strokePolyline(e,r.lower,{lineColor:i.lowerColor,lineWidth:o,lineStyle:i.lowerStyle}),this.strokePolyline(e,r.mid,{lineColor:i.midColor,lineWidth:o,lineStyle:i.midStyle});}strokePolyline(e,t,n){t.length<2||Ic(n.lineColor)||this.stroke(e,n,()=>{e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);});}paintCallout(e,t,n,r){this.paintBubble(e,t,n,r,5);}paintComment(e,t,n,r){this.paintBubble(e,t,n,r,999);}paintBubble(e,t,n,r,i){let o=t.points(n);if(!o)return;let a=o[0][0],l=o[0][1],c=o[1][0],d=o[1][1],h=t.text,u=ce(h?.size??"normal");e.font=`${h?.bold?"bold ":""}${h?.italic?"italic ":""}${u}px ${r.fontFamily}`;let p=(h?.value??"").split(`
187
- `),m=Math.max(8,...p.map(P=>e.measureText(P).width)),f=9,b=6,g=Ve(u),v=m+f*2,y=p.length*g+b*2,x=c-v/2,S=d-y/2,C=v/2,T=y/2,M=a-c,E=l-d,k=Math.min(i,v/2,y/2),L=null;if(Math.abs(M)>C||Math.abs(E)>T){let P=Math.max(6,Math.min(v,y)*.18);if(Math.abs(M)/C>=Math.abs(E)/T){let V=M>0?x+v:x,G=Math.max(S+k+P,Math.min(S+y-k-P,d+E*(V-c)/(M||1)));L={edge:M>0?"right":"left",at:G,apex:[a,l],half:P};}else {let V=E>0?S+y:S,G=Math.max(x+k+P,Math.min(x+v-k-P,c+M*(V-d)/(E||1)));L={edge:E>0?"bottom":"top",at:G,apex:[a,l],half:P};}}e.save(),e.fillStyle=Ce(t,r)??r.background,Dc(e,x,S,v,y,k,L),e.fill(),e.restore(),this.applyStroke(e,t.style),Dc(e,x,S,v,y,k,L),e.stroke(),e.setLineDash([]),e.fillStyle=h?.color??be(Ce(t,r)??r.background),e.textBaseline="top",e.textAlign="left",p.forEach((P,V)=>e.fillText(P,x+f,S+b+V*g));}paintTextPlate(e,t,n,r,i,o,a,l,c,d,h){e.save(),e.fillStyle=Ce(t,n)??n.background,je(e,r,i,o,a,5),e.fill(),e.restore(),this.applyStroke(e,t.style),je(e,r,i,o,a,5),e.stroke(),e.setLineDash([]),e.fillStyle=t.text?.color??be(Ce(t,n)??n.background),e.textBaseline="top",e.textAlign="left",l.forEach((u,p)=>e.fillText(u,r+d,i+h+p*c));}measureText(e,t,n,r){let i=t.text,o=ce(i?.size??"normal");e.font=`${i?.bold?"bold ":""}${i?.italic?"italic ":""}${o}px ${n.fontFamily}`;let a=(i?.value||r).split(`
188
- `),l=Math.max(8,...a.map(c=>e.measureText(c).width));return {lines:a,tw:l,fs:o,lh:Ve(o)}}paintNote(e,t,n,r){let i=t.handlePoints(n);if(!i.length)return;let[o,a]=i[0],{lines:l,tw:c,lh:d}=this.measureText(e,t,r,"Note"),h=8,u=5;this.paintTextPlate(e,t,r,o,a,c+h*2,l.length*d+u*2,l,d,h,u);}paintPriceNote(e,t,n,r){let i=t.points(n),o=t.anchors[0];if(!i||!o)return;let[a,l]=i[0],[c,d]=i[1],h=Rc(o.price),u=t.text,p=ce(u?.size??"normal");e.font=`${u?.bold?"bold ":""}${u?.italic?"italic ":""}${p}px ${r.fontFamily}`;let m=9,f=6,b=e.measureText(h).width+m*2,g=Ve(p)+f*2,v=c-b/2,y=d-g/2;this.stroke(e,t.style,()=>{e.moveTo(a,l),e.lineTo(c,d);}),e.fillStyle=t.style.lineColor,e.beginPath(),e.arc(a,l,3,0,Math.PI*2),e.fill(),e.save(),e.fillStyle=Ce(t,r)??r.background,je(e,v,y,b,g,5),e.fill(),e.restore(),this.applyStroke(e,t.style),je(e,v,y,b,g,5),e.stroke(),e.setLineDash([]),e.fillStyle=u?.color??be(Ce(t,r)??r.background),e.textBaseline="middle",e.textAlign="center",e.fillText(h,c,d+.5);}paintSignpost(e,t,n,r){let i=t.points(n);if(!i)return;let[o,a]=i[0],[l,c]=i[1],{lines:d,tw:h,lh:u}=this.measureText(e,t,r,"Signpost"),p=9,m=6,f=h+p*2,b=d.length*u+m*2;this.stroke(e,t.style,()=>{e.moveTo(o,a),e.lineTo(l,c);}),e.fillStyle=t.style.lineColor,e.beginPath(),e.arc(o,a,3.5,0,Math.PI*2),e.fill(),this.paintTextPlate(e,t,r,l-f/2,c-b/2,f,b,d,u,p,m);}paintPriceLabel(e,t,n,r){let i=t.handlePoints(n),o=t.anchors[0];if(!i.length||!o)return;let[a,l]=i[0],c=Rc(o.price),d=t.text,h=ce(d?.size??"normal");e.font=`${d?.bold?"bold ":""}${d?.italic?"italic ":""}${h}px ${r.fontFamily}`;let u=e.measureText(c).width,p=8,m=4,f=6,b=u+p*2,g=Ve(h)+m*2,v=l-g/2,y=Ce(t,r)??r.background;e.save(),e.fillStyle=y,e.beginPath(),e.moveTo(a,l),e.lineTo(a+f,l-5),e.lineTo(a+f,l+5),e.closePath(),e.fill(),je(e,a+f,v,b,g,4),e.fill(),e.restore(),this.applyStroke(e,t.style),je(e,a+f,v,b,g,4),e.stroke(),e.setLineDash([]),e.fillStyle=d?.color??be(y),e.textBaseline="middle",e.textAlign="left",e.fillText(c,a+f+p,l+.5);}paintPattern(e,t,n,r){let i=t.handlePoints(n);if(i.length<2)return;let o=t.valid(),a=Ce(t,r)??t.style.lineColor,l=t.style.fillColor?1:.1;for(let[u,p,m]of t.fillTriangles()){let f=i[u],b=i[p],g=i[m];!f||!b||!g||(e.save(),e.globalAlpha=l*e.globalAlpha,e.fillStyle=a,e.beginPath(),e.moveTo(f[0],f[1]),e.lineTo(b[0],b[1]),e.lineTo(g[0],g[1]),e.closePath(),e.fill(),e.restore());}this.stroke(e,t.style,()=>{e.moveTo(i[0][0],i[0][1]);for(let u=1;u<i.length;u+=1)e.lineTo(i[u][0],i[u][1]);});let c=t.necklineIndices();if(c){let u=i[c[0]],p=i[c[1]],m=i.length;if(u&&p&&m>=2){let f=Oo(u[0],u[1],p[0],p[1],i[0][0],i[0][1],i[1][0],i[1][1])??u,b=Oo(u[0],u[1],p[0],p[1],i[m-2][0],i[m-2][1],i[m-1][0],i[m-1][1])??p;this.stroke(e,{...t.style,lineStyle:"dashed"},()=>{e.moveTo(f[0],f[1]),e.lineTo(b[0],b[1]);});}}let d=t.vertexLabels();if(e.fillStyle=r.textColor,e.font=`bold 12px ${r.fontFamily}`,e.textAlign="center",i.forEach((u,p)=>{let m=d[p];if(!m)return;let f=((i[p-1]?.[1]??u[1])+(i[p+1]?.[1]??u[1]))/2,b=u[1]<=f;e.textBaseline=b?"bottom":"top",e.fillText(m,u[0],b?u[1]-7:u[1]+7);}),t.legRatios()){e.font=`11px ${r.fontFamily}`,e.textAlign="left",e.textBaseline="middle";for(let u=2;u<i.length;u+=1){let p=t.ratioAt(u),m=i[u-1],f=i[u];if(p==null||!m||!f)continue;let b=t.ratioOk(u);e.fillStyle=b===true?qn:b===false?Zn:r.textColor,e.fillText(p.toFixed(3),(m[0]+f[0])/2+6,(m[1]+f[1])/2);}}let h=t.patternName();if(h&&i.length>=2){let u=i[i.length-1],p=i[i.length-2],m=p?u[1]<=p[1]:false;e.font=`bold 12px ${r.fontFamily}`,e.fillStyle=o===false?Zn:qn,e.textAlign="center",e.textBaseline=m?"bottom":"top",e.fillText(`${h} ${o?"\u2713":"\u2717"}`,u[0],m?u[1]-22:u[1]+22);}e.textAlign="left",e.textBaseline="alphabetic";}paintHighlighter(e,t,n){let r=t.geometry(n);if(!r||r.segments.length===0)return;e.save(),e.strokeStyle=t.style.lineColor,e.lineWidth=t.style.lineWidth,e.lineCap="round",e.lineJoin="round",e.setLineDash([]),e.beginPath();let i=r.segments[0];e.moveTo(i[0],i[1]);for(let o of r.segments)e.lineTo(o[2],o[3]);e.stroke(),e.restore();}paintSegments(e,t,n){let r=t.geometry(n);if(r){if(r.fill&&r.fill.length>=3&&t.style.fillColor){e.save(),e.fillStyle=t.style.fillColor,e.beginPath(),e.moveTo(r.fill[0][0],r.fill[0][1]);for(let i=1;i<r.fill.length;i+=1)e.lineTo(r.fill[i][0],r.fill[i][1]);e.closePath(),e.fill(),e.restore();}for(let i of r.segments)this.stroke(e,t.style,()=>{e.moveTo(i[0],i[1]),e.lineTo(i[2],i[3]);});}}paintInfoLine(e,t,n){let r=t.handlePoints(n);if(r.length<2)return;let[i,o]=r[0],[a,l]=r[1];this.stroke(e,t.style,()=>{e.moveTo(i,o),e.lineTo(a,l);});let c=t.anchors[0],d=t.anchors[1];if(!c||!d)return;let h=d.price-c.price,u=c.price!==0?h/c.price*100:0,p=n.barsBetween?Math.abs(Math.round(n.barsBetween(c.time,d.time))):0,m=h>=0?"+":"",f=`${m}${h.toFixed(2)} (${m}${u.toFixed(2)}%) ${p} bars`,b=(i+a)/2,g=(o+l)/2;e.font="11px monospace";let v=e.measureText(f).width+12,y=18,x=b-2,S=g-y-4;e.save(),e.globalAlpha=.9*e.globalAlpha,je(e,x,S,v,y,3),e.fillStyle=Ec,e.fill(),e.strokeStyle=Pf,e.lineWidth=1,e.stroke(),e.restore(),e.fillStyle=h>=0?q:X,e.textAlign="left",e.textBaseline="middle",e.fillText(f,x+6,S+y/2),e.textBaseline="alphabetic";}paintTrendAngle(e,t,n,r){let i=t.handlePoints(n);if(i.length<2)return;let[o,a]=i[0],[l,c]=i[1];this.stroke(e,t.style,()=>{e.moveTo(o,a),e.lineTo(l,c);});let d=l-o,h=c-a,u=Math.atan2(-h,d),p=u*(180/Math.PI),m=Math.min(30,Math.hypot(d,h)*.3),f=t.style.lineColor;if(e.save(),e.globalAlpha=.4*e.globalAlpha,e.strokeStyle=f,e.lineWidth=1,e.setLineDash([4,4]),e.beginPath(),e.moveTo(o,a),e.lineTo(o+Math.max(Math.abs(d),m+20),a),e.stroke(),e.restore(),e.setLineDash([]),m>1){let b=-u;e.strokeStyle=f,e.lineWidth=1.5,e.beginPath(),e.arc(o,a,m,Math.min(0,b),Math.max(0,b)),e.stroke();}e.fillStyle=f,e.font=`11px ${r.fontFamily}`,e.textAlign="left",e.textBaseline="alphabetic",e.fillText(`${p.toFixed(1)}\xB0`,o+m+6,a+(h<0?-14:2));}paintArrowMark(e,t,n){let r=t.glyphPoints(n);if(!(!r||r.length<3)){e.save(),e.setLineDash([]),e.fillStyle=t.style.lineColor,e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let i=1;i<r.length;i+=1)e.lineTo(r[i][0],r[i][1]);e.closePath(),e.fill(),e.restore();}}paintGlyphStamp(e,t,n,r){let i=t.center(n);i&&(e.save(),e.setLineDash([]),e.font=`${t.sizePx()}px ${r.fontFamily}`,e.fillStyle=t.style.lineColor,e.textAlign="center",e.textBaseline="middle",e.fillText(t.glyph,i[0],i[1]),e.textAlign="left",e.textBaseline="alphabetic",e.restore());}paintArrowhead(e,t,n,r){let i=Math.atan2(n[1]-t[1],n[0]-t[0]),o=Math.max(9,r.lineWidth*3.5),a=Math.PI/7;e.save(),e.setLineDash([]),e.fillStyle=r.lineColor,e.beginPath(),e.moveTo(n[0],n[1]),e.lineTo(n[0]-o*Math.cos(i-a),n[1]-o*Math.sin(i-a)),e.lineTo(n[0]-o*Math.cos(i+a),n[1]-o*Math.sin(i+a)),e.closePath(),e.fill(),e.restore();}stroke(e,t,n){this.applyStroke(e,t),e.beginPath(),n(),e.stroke(),e.setLineDash([]);}applyStroke(e,t){e.strokeStyle=t.lineColor,e.lineWidth=t.lineWidth,e.setLineDash(Dt(t.lineStyle,t.lineWidth));}paintHandles(e,t){e.setLineDash([]),e.lineWidth=1.5;for(let[n,r]of t)e.beginPath(),e.arc(n,r,Cf,0,Math.PI*2),e.fillStyle=Mf,e.fill(),e.strokeStyle=Tf,e.stroke();}};function Ic(s){let e=s.trim().toLowerCase();if(/^#[0-9a-f]{8}$/.test(e))return e.endsWith("00");let t=/rgba?\([^)]*,\s*([\d.]+)\s*\)$/.exec(e);return t?parseFloat(t[1])===0:false}function Rc(s){let e=es(s);return s.toLocaleString("en-US",{minimumFractionDigits:e,maximumFractionDigits:e})}function je(s,e,t,n,r,i){let o=Math.min(i,n/2,r/2);s.beginPath(),s.moveTo(e+o,t),s.arcTo(e+n,t,e+n,t+r,o),s.arcTo(e+n,t+r,e,t+r,o),s.arcTo(e,t+r,e,t,o),s.arcTo(e,t,e+n,t,o),s.closePath();}function Dc(s,e,t,n,r,i,o){let a=(l,c,d)=>{if(o&&o.edge===l){let[h,u]=o.apex;l==="top"?(s.lineTo(o.at-o.half,t),s.lineTo(h,u),s.lineTo(o.at+o.half,t)):l==="bottom"?(s.lineTo(o.at+o.half,t+r),s.lineTo(h,u),s.lineTo(o.at-o.half,t+r)):l==="right"?(s.lineTo(e+n,o.at-o.half),s.lineTo(h,u),s.lineTo(e+n,o.at+o.half)):(s.lineTo(e,o.at+o.half),s.lineTo(h,u),s.lineTo(e,o.at-o.half));}s.lineTo(c,d);};s.beginPath(),s.moveTo(e+i,t),a("top",e+n-i,t),s.arcTo(e+n,t,e+n,t+i,i),a("right",e+n,t+r-i),s.arcTo(e+n,t+r,e+n-i,t+r,i),a("bottom",e+i,t+r),s.arcTo(e,t+r,e,t+r-i,i),a("left",e,t+i),s.arcTo(e,t,e+i,t,i),s.closePath();}function Ef(s){if(!Number.isFinite(s))return "";let e=Math.round(s*1e3)/1e3;return String(e)}function kf(s,e){let t=s.text;if(!t)return null;let n=s.handlePoints(e),r=t.value.split(`
189
- `).length,i=Ve(ce(t.size));switch(s.type){case "text":return n[0]?{x:n[0][0]+2,top:n[0][1]+2,align:"left"}:null;case "hline":return n[0]?{x:n[0][0]+8,top:n[0][1]-4-i*r,align:"left"}:null;case "trendline":case "ray":case "extendedline":case "infoline":case "trendangle":return n.length<2?null:{x:(n[0][0]+n[1][0])/2,top:(n[0][1]+n[1][1])/2-6-i*r,align:"center"};case "box":return n.length<2?null:{x:(n[0][0]+n[1][0])/2,top:(n[0][1]+n[1][1])/2-i*r/2,align:"center"};default:return n[0]?{x:n[0][0],top:n[0][1],align:"left"}:null}}function dn(s,e,t,n,r=6){for(let i=s.length-1;i>=0;i-=1){let o=s[i];if(!o.visible)continue;let a=n.paneRect?.(o.paneId);if(!(a&&a.height<=0)&&o.hitTest(e,t,n,r))return o}return null}var Ac=3,If=4,Oc=Math.PI/4,Fc=new Set(["trendline","ray","extendedline","infoline","trendangle","arrow"]),ho=class{constructor(e){this.deps=e;this.state={kind:"idle"};this.snapAt=null;}snapMarker(){return this.snapAt}placingMarkers(e){if(this.state.kind!=="placing")return null;let{draft:t}=this.state;if(t.placementMode()==="freehand")return null;let n=[];for(let r of t.anchors){let i=e.yOf(r.price,t.paneId);i!=null&&n.push([e.xOf(r.time),i]);}return n.length?n:null}resolve(e,t,n,r){let i=this.deps.projector().pxToPoint(e,t,n);if(r==="off")return this.snapAt=null,i;let o=this.deps.snap(i,n,r,{x:e,y:t}),a=o.time!==i.time||o.price!==i.price;return this.snapAt=a?{point:o,paneId:n}:null,o}resolveAngleSnapped(e,t,n,r){let i=this.deps.projector(),o=i.xOf(e.time),a=i.yOf(e.price,t);if(this.snapAt=null,a==null)return i.pxToPoint(n,r,t);let l=Math.hypot(n-o,r-a);if(l<1)return i.pxToPoint(n,r,t);let c=Math.round(Math.atan2(r-a,n-o)/Oc)*Oc;return i.pxToPoint(o+l*Math.cos(c),a+l*Math.sin(c),t)}placingPivot(e){return Fc.has(e.type)?e.anchors[e.anchors.length-1]??null:null}claim(e,t){return this.deps.activeTool()!=null||this.state.kind!=="idle"?true:this.hitAt(e,t)!=null}cursorAt(e,t){return this.deps.activeTool()!=null?null:this.hitAt(e,t)?"pointer":null}isPlacing(){return this.state.kind==="placing"}isDragging(){return this.state.kind==="pressed"&&this.state.moved}activeDragId(){return this.state.kind==="pressed"&&this.state.moved?this.state.id:null}down(e,t,n="off",r=false){let i=this.deps.projector();if(this.state.kind==="placing"){if(this.state.draft.placementMode()!=="click")return;let l=r?this.placingPivot(this.state.draft):null,c=l?this.resolveAngleSnapped(l,this.state.draft.paneId,e,t):this.resolve(e,t,this.state.draft.paneId,n);this.state.draft.anchors.push(this.placementAnchor(this.state.draft,c)),this.state.draft.anchors.length>=this.state.need?this.finalize():this.deps.changed();return}let o=this.deps.activeTool();if(o){let l=i.paneIdAtY(t)??"price",c=rt(o,{paneId:l,anchors:[this.resolve(e,t,l,n)],style:this.deps.lastStyle()});if(!c)return;this.state={kind:"placing",draft:c,need:c.anchorSchema().max,cursor:null},c.placementMode()==="click"&&c.anchors.length>=this.state.need?this.finalize():this.deps.changed();return}let a=this.hitAt(e,t);if(a){if(r){this.deps.emit({kind:"select",ids:[a.id],additive:true});return}let l=a.hitHandle(e,t,i,6);this.state={kind:"pressed",id:a.id,handle:l,grab:i.pxToPoint(e,t,a.paneId),orig:Rf(a),px:e,py:t,moved:false};}}move(e,t,n="off",r=false){if(this.state.kind==="idle"){let o=this.deps.activeTool(),a=this.snapAt!=null;o&&n!=="off"?this.resolve(e,t,this.deps.projector().paneIdAtY(t)??"price",n):this.snapAt=null,(this.snapAt!=null||a)&&this.deps.changed();return}if(this.state.kind==="placing"){if(this.state.draft.placementMode()==="freehand"){this.captureFreehand(e,t);return}let o=r?this.placingPivot(this.state.draft):null;this.state.cursor=o?this.resolveAngleSnapped(o,this.state.draft.paneId,e,t):this.resolve(e,t,this.state.draft.paneId,n),this.deps.changed();return}if(this.state.kind!=="pressed")return;let i=this.byId(this.state.id);if(!(!i||i.locked)&&!(!this.state.moved&&Math.abs(e-this.state.px)<=Ac&&Math.abs(t-this.state.py)<=Ac)){if(this.state.moved=true,this.state.handle>=0){let o=i.anchors[this.state.handle];if(o){let a=r&&Fc.has(i.type)&&i.anchors.length===2?i.anchors[1-this.state.handle]:void 0,l=a?this.resolveAngleSnapped(a,i.paneId,e,t):this.resolve(e,t,i.paneId,n);Df(o,l,i.anchorSchema().slots[this.state.handle]?.free??"both");}i.constrainHandleDrag(this.state.handle);}else {let o=this.deps.projector().pxToPoint(e,t,i.paneId);this.snapAt=null;let a=o.time-this.state.grab.time,l=o.price-this.state.grab.price;i.anchors=i.translateBody(a,l,this.state.orig);}this.deps.changed();}}up(e,t){if(this.snapAt=null,this.state.kind==="placing"){let o=this.state.draft.placementMode();o==="drag"?(this.state.cursor&&this.state.draft.anchors.push(this.state.cursor),this.state.draft.anchors.length>=this.state.draft.anchorSchema().min?this.finalize():this.discardPlacing()):o==="freehand"&&(this.state.draft.anchors.length>=this.state.draft.anchorSchema().min?this.finalize():this.discardPlacing());return}if(this.state.kind!=="pressed")return;let{id:n,moved:r}=this.state;this.state={kind:"idle"};let i=this.byId(n);r?(i&&this.deps.emit({kind:"edit",doc:i.serialize()}),this.deps.changed()):this.deps.openSettings(n,e,t);}cancel(){if(this.snapAt=null,this.state.kind==="placing"){let e=this.state.draft.type;return this.state={kind:"idle"},this.deps.emit({kind:"tool-finished",type:e}),this.deps.changed(),true}if(this.state.kind==="pressed"){let e=this.byId(this.state.id);return e&&this.state.moved&&(e.anchors=this.state.orig.map(t=>({time:t.time,price:t.price}))),this.state={kind:"idle"},this.deps.changed(),true}return false}onToolCleared(){this.state.kind==="placing"&&(this.state={kind:"idle"},this.deps.changed());}ghost(){if(this.state.kind!=="placing")return null;let{draft:e,cursor:t}=this.state;return t?rt(e.type,{paneId:e.paneId,anchors:[...e.anchors,this.placementAnchor(e,t)],style:e.style}):e.anchors.length>=1&&e.type==="hline"?e:null}placementAnchor(e,t){if(e.type!=="parallelchannel"||e.anchors.length!==2)return t;let n=e.anchors[0],r=e.anchors[1],i=r.time-n.time,o=i===0?n.price:n.price+(r.price-n.price)*(t.time-n.time)/i,a=t.price-o;return {time:(n.time+r.time)/2,price:(n.price+r.price)/2+a}}captureFreehand(e,t){if(this.state.kind!=="placing")return;this.snapAt=null;let n=this.state.draft,r=this.deps.projector(),i=n.anchors[n.anchors.length-1],o=i?r.xOf(i.time):NaN,a=i?r.yOf(i.price,n.paneId)??NaN:NaN;if(Math.hypot(e-o,t-a)>If){if(n.anchors.length>=this.state.need){let l=n.anchors.length-1;n.anchors=n.anchors.filter((c,d)=>d%2===0||d===l);}n.anchors.push(r.pxToPoint(e,t,n.paneId));}this.state.cursor=r.pxToPoint(e,t,n.paneId),this.deps.changed();}finishPlacing(e){if(this.state.kind!=="placing")return false;let t=this.state.draft,n=t.anchorSchema();return t.placementMode()!=="click"||n.max<=n.min||(e&&t.anchors.length>n.min&&t.anchors.pop(),t.anchors.length<n.min)?false:(this.finalize(),true)}discardPlacing(){if(this.state.kind!=="placing")return;let e=this.state.draft.type;this.state={kind:"idle"},this.deps.emit({kind:"tool-finished",type:e}),this.deps.changed();}finalize(){if(this.state.kind!=="placing")return;this.snapAt=null;let e=this.state.draft;e.onPlaced(this.deps.projector());let t=e.type;this.state={kind:"idle"},this.deps.emit({kind:"create",doc:e.serialize()}),this.deps.emit({kind:"tool-finished",type:t}),this.deps.changed();}hitAt(e,t){let n=this.deps.projector();for(let r of this.handleDrawings())if(r.hitHandle(e,t,n,6)>=0)return r;return dn(this.deps.drawings(),e,t,n,6)}handleDrawings(){let e=new Set(this.deps.selectedIds()),t=this.deps.hoveredId();t&&e.add(t);let n=[];for(let r of e){let i=this.byId(r);i&&n.push(i);}return n}byId(e){return this.deps.drawings().find(t=>t.id===e)??null}};function Rf(s){return s.anchors.map(e=>({time:e.time,price:e.price}))}function Df(s,e,t){(t==="both"||t==="x")&&(s.time=e.time),(t==="both"||t==="y")&&(s.price=e.price);}var Ze=30,Af=21,Bc="vela-drawing-popup-styles";function Of(){if(typeof document>"u"||document.getElementById(Bc))return;let s=document.createElement("style");s.id=Bc,s.textContent=`
185
+ `,document.head.appendChild(s);}var er=class{constructor(e,t){this.container=e;this.theme=t;this.root=null;this.onChange=null;this.onImport=null;this.onReset=null;this.config=null;this.syncTypeTabs=null;this.hostSections=[];this.themeControl=null;this.tabs=[];this.typeActiveInstance=new Map;this.typeActiveGroup=new Map;this.activeSection=null;this.mobileLayout=false;getComputedStyle(e).position==="static"&&(e.style.position="relative");}setHostSections(e){this.hostSections=e;}setThemeControl(e,t){this.themeControl={current:e,onSelect:t};}refreshConfig(e){this.config&&(this.config=e);}setTheme(e){this.theme=e,this.reopenIfLive();}setLayoutMode(e){let t=e==="mobile";t!==this.mobileLayout&&(this.mobileLayout=t,this.reopenIfLive());}reopenIfLive(){if(!this.root)return;let e=this.config,t=this.onChange,n=this.onImport,r=this.onReset,i=this.activeSection;this.close(),e&&t&&this.open(e,t,n??void 0,r??void 0,i??void 0);}isOpen(){return this.root!==null}toggle(e,t,n,r,i){this.root?this.close():this.open(e,t,n,r,i);}showSection(e){this.tabs.find(t=>t.title.toLowerCase()===e.toLowerCase())?.show();}open(e,t,n,r,i){this.close(),this.config=e,this.onChange=t,this.onImport=n??null,this.onReset=r??null,Sf();let o=this.mobileLayout,a=document.createElement("div");a.style.cssText="position:absolute;inset:0;z-index:var(--vela-z-dialog);display:flex;align-items:flex-start;justify-content:center;background:transparent;padding-top:8vh;pointer-events:auto;",o&&(a.classList.add("vela-sd-mobile"),a.style.paddingTop="0",a.style.alignItems="stretch"),a.addEventListener("mousedown",w=>{w.target===a&&this.close();});let l=document.createElement("div");l.style.cssText=`width:fit-content;min-width:min(560px,94vw);max-width:min(720px,94vw);max-height:70vh;display:flex;flex-direction:column;background:${xf};border:1px solid ${co};border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow-dialog);color:${wf};font:13px var(--vela-font);overflow:hidden;cursor:default;`,o&&(l.style.cssText+="width:100%;min-width:0;max-width:none;max-height:none;flex:1 1 auto;border:none;border-radius:0;");let c=document.createElement("div");c.style.cssText=`display:flex;justify-content:space-between;align-items:center;padding:9px 9px 9px 16px;border-bottom:1px solid ${co};flex:0 0 auto;user-select:none;`,o&&(c.style.paddingLeft="8px");let d=document.createElement("span");d.textContent="Chart settings",d.style.cssText="font-size:17px;font-weight:600;letter-spacing:0.2px;",o&&(d.style.cssText+="flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;");let h=null;if(o){let w=document.createElement("button");w.type="button",w.className="vela-sd-burger",w.innerHTML=oe("burger",16),w.title="Sections",w.addEventListener("click",()=>h?.()),c.append(w);}let u=document.createElement("button");if(u.type="button",u.innerHTML=oe("close",15),u.title="Close",u.className="vela-sd-close",u.addEventListener("click",()=>this.close()),c.append(d,u),!o){c.style.cursor="move";let w=0,H=0,z=0,te=0,me=false;c.addEventListener("pointerdown",Y=>{Y.target?.closest(".vela-sd-close")||(me=true,w=Y.clientX-z,H=Y.clientY-te,c.setPointerCapture(Y.pointerId));}),c.addEventListener("pointermove",Y=>{me&&(z=Y.clientX-w,te=Y.clientY-H,l.style.transform=`translate(${z}px, ${te}px)`);}),c.addEventListener("pointerup",()=>me=false);}l.appendChild(c);let p=document.createElement("div");p.style.cssText="display:flex;flex-direction:column;gap:0;",p.append(this.section("Symbol")),p.append(this.sectionTitle("Chart type"));let m={},f=w=>{let H=w==="heikinashi"?"candles":w;for(let z of tn()){let te=m[z];te&&(te.style.display=z===H?"contents":"none");}};p.append(this.selectRowLabeled("Type",e.series.style,tn().map(w=>[w,yf(w)]),w=>{this.emit({series:{style:w}}),f(w),this.syncTypeTabs?.(w);}));let b=this.group();b.append(this.sectionTitle("Candles")),b.append(this.toggleRow("Body",e.candles.bodyVisible,w=>this.emit({candles:{bodyVisible:w}}),[this.swatch(e.candles.upColor,w=>this.emit({candles:{upColor:w}})),this.swatch(e.candles.downColor,w=>this.emit({candles:{downColor:w}}))])),b.append(this.toggleRow("Borders",e.candles.borderVisible,w=>this.emit({candles:{borderVisible:w}}),[this.swatch(e.candles.borderUpColor,w=>this.emit({candles:{borderUpColor:w}})),this.swatch(e.candles.borderDownColor,w=>this.emit({candles:{borderDownColor:w}}))])),b.append(this.toggleRow("Wick",e.candles.wickVisible,w=>this.emit({candles:{wickVisible:w}}),[this.swatch(e.candles.wickUpColor,w=>this.emit({candles:{wickUpColor:w}})),this.swatch(e.candles.wickDownColor,w=>this.emit({candles:{wickDownColor:w}}))])),b.append(this.numberRow("Spacing",e.series.spacing,.1,10,.1,w=>this.emit({series:{spacing:w}}))),m.candles=b,p.append(b);let g=this.group();g.append(this.sectionTitle("Bars")),g.append(this.colorRow("Color Up",e.bars.upColor,w=>this.emit({bars:{upColor:w}}))),g.append(this.colorRow("Color Down",e.bars.downColor,w=>this.emit({bars:{downColor:w}}))),g.append(this.numberRow("Spacing",e.series.spacing,.1,10,.1,w=>this.emit({series:{spacing:w}}))),m.bars=g,p.append(g);let v=this.group();v.append(this.sectionTitle("Line")),v.append(this.colorRow("Color",e.line.color,w=>this.emit({line:{color:w}}))),v.append(this.numberRow("Width",e.line.width,1,10,1,w=>this.emit({line:{width:w}}))),m.line=v,p.append(v);let y=this.group();y.append(this.sectionTitle("Area")),y.append(this.colorRow("Line color",e.area.lineColor,w=>this.emit({area:{lineColor:w}}))),y.append(this.numberRow("Width",e.area.width,1,10,1,w=>this.emit({area:{width:w}}))),y.append(this.colorRow("Top fill",e.area.topColor,w=>this.emit({area:{topColor:w}}))),y.append(this.colorRow("Bottom fill",e.area.bottomColor,w=>this.emit({area:{bottomColor:w}}))),m.area=y,p.append(y);let x=this.group();x.append(this.sectionTitle("Baseline")),x.append(this.rowWith("Top line",[this.swatch(e.baseline.topLineColor,w=>this.emit({baseline:{topLineColor:w}}))])),x.append(this.rowWith("Bottom line",[this.swatch(e.baseline.bottomLineColor,w=>this.emit({baseline:{bottomLineColor:w}}))])),x.append(this.rowWith("Fill top area",[this.swatch(e.baseline.topFillColor,w=>this.emit({baseline:{topFillColor:w}})),this.swatch(e.baseline.topFillColor2,w=>this.emit({baseline:{topFillColor2:w}}))])),x.append(this.rowWith("Fill bottom area",[this.swatch(e.baseline.bottomFillColor2,w=>this.emit({baseline:{bottomFillColor2:w}})),this.swatch(e.baseline.bottomFillColor,w=>this.emit({baseline:{bottomFillColor:w}}))])),x.append(this.numberRow("Base level %",e.baseline.baselineLevel,0,100,1,w=>this.emit({baseline:{baselineLevel:w}}))),x.append(this.numberRow("Width",e.baseline.width,1,10,1,w=>this.emit({baseline:{width:w}}))),m.baseline=x,p.append(x);for(let w of Ge()){if(!is(w.id))continue;let H=e.chartTypes[w.id]??{},z=(Y,Io)=>typeof H[Y]=="string"&&H[Y]!==""?H[Y]:Io,te=(Y,Io)=>typeof H[Y]=="boolean"?H[Y]:Io,me=this.group();me.append(this.sectionTitle("Candles")),me.append(this.toggleRow("Body",te("candleBodyVisible",e.candles.bodyVisible),Y=>this.emitType(w.id,"candleBodyVisible",Y),[this.swatch(z("candleUpColor",e.candles.upColor),Y=>this.emitType(w.id,"candleUpColor",Y)),this.swatch(z("candleDownColor",e.candles.downColor),Y=>this.emitType(w.id,"candleDownColor",Y))])),me.append(this.toggleRow("Borders",te("candleBorderVisible",e.candles.borderVisible),Y=>this.emitType(w.id,"candleBorderVisible",Y),[this.swatch(z("candleBorderUpColor",e.candles.borderUpColor),Y=>this.emitType(w.id,"candleBorderUpColor",Y)),this.swatch(z("candleBorderDownColor",e.candles.borderDownColor),Y=>this.emitType(w.id,"candleBorderDownColor",Y))])),me.append(this.toggleRow("Wick",te("candleWickVisible",e.candles.wickVisible),Y=>this.emitType(w.id,"candleWickVisible",Y),[this.swatch(z("candleWickUpColor",e.candles.wickUpColor),Y=>this.emitType(w.id,"candleWickUpColor",Y)),this.swatch(z("candleWickDownColor",e.candles.wickDownColor),Y=>this.emitType(w.id,"candleWickDownColor",Y))])),me.append(this.numberRow("Spacing",e.series.spacing,.1,10,.1,Y=>this.emit({series:{spacing:Y}}))),m[w.id]=me,p.append(me);}f(e.series.style),p.append(this.sectionTitle("Time zone")),p.append(this.selectRowLabeled("Time zone",ao(e.timeScale.timezone),Tf(e.timeScale.timezone),w=>this.emit({timeScale:{timezone:w}})));let S=w=>{for(let H of this.hostSections)if((H.placement??"after-symbol")===w){p.append(w==="symbol"?this.sectionTitle(H.title):this.section(H.title));for(let z of H.rows)z.kind==="heading"?p.append(this.sectionTitle(z.label)):z.kind==="toggle"?p.append(this.boolRow(z.label,z.get(),te=>z.set(te))):p.append(this.selectRowLabeled(z.label,z.get(),z.options.map(te=>[te,te]),te=>z.set(te)));}},C=w=>{for(let H of Ge()){let z=H.settings;z&&(z.placement??"end")===w&&this.chartTypeSection(H.id,z,e,p);}};if(S("symbol"),C("after-symbol"),S("after-symbol"),p.append(this.section("Scales and lines")),p.append(this.sectionTitle("Price scale")),p.append(this.selectRowLabeled("Mode",e.priceScale.log?"log":e.priceScale.mode,[["price","Regular"],["percent","Percent"],["indexed","Indexed to 100"],["log","Logarithmic"]],w=>this.emit({priceScale:w==="log"?{mode:"price",log:true}:{mode:w,log:false}}))),p.append(this.boolRow("Invert scale",e.priceScale.invert,w=>this.emit({priceScale:{invert:w}}))),p.append(this.separator()),p.append(this.boolRow("Last Price Line",e.priceScale.currentPriceLine,w=>this.emit({priceScale:{currentPriceLine:w}}))),p.append(this.boolRow("Last price label",e.priceScale.priceLabel,w=>this.emit({priceScale:{priceLabel:w}}))),p.append(this.boolRow("Countdown to bar close",e.priceScale.countdown,w=>this.emit({priceScale:{countdown:w}}))),p.append(this.boolRow("Axis labels",e.priceScale.labelsVisible,w=>this.emit({priceScale:{labelsVisible:w}}))),p.append(this.colorRow("Scale border color",e.priceScale.borderColor,w=>this.emit({priceScale:{borderColor:w}}))),p.append(this.sectionTitle("Crosshair")),p.append(this.colorRow("Color",e.crosshair.color,w=>this.emit({crosshair:{color:w}}))),p.append(this.numberRow("Width",e.crosshair.width,.5,8,.5,w=>this.emit({crosshair:{width:w}}))),p.append(this.selectRowLabeled("Style",e.crosshair.style,[["solid","Solid"],["dashed","Dashed"],["dotted","Dotted"]],w=>this.emit({crosshair:{style:w}}))),p.append(this.section("Canvas")),p.append(this.sectionTitle("Background & text")),p.append(this.colorRow("Background",e.layout.background,w=>this.emit({layout:{background:w}}))),p.append(this.colorRow("Text color",e.layout.textColor,w=>this.emit({layout:{textColor:w}}))),p.append(this.numberRow("Text size",e.layout.fontSize,6,32,1,w=>this.emit({layout:{fontSize:w}}))),p.append(this.colorRow("Pane separator color",e.panes.separatorColor,w=>this.emit({panes:{separatorColor:w}}))),p.append(this.sectionTitle("Grid")),p.append(this.toggleRow("Vertical",e.grid.vertLines.visible,w=>this.emit({grid:{vertLines:{visible:w}}}),[this.swatch(e.grid.vertLines.color,w=>this.emit({grid:{vertLines:{color:w}}}))])),p.append(this.toggleRow("Horizontal",e.grid.horzLines.visible,w=>this.emit({grid:{horzLines:{visible:w}}}),[this.swatch(e.grid.horzLines.color,w=>this.emit({grid:{horzLines:{color:w}}}))])),this.themeControl){let w=this.themeControl;p.append(this.sectionTitle("Theme")),p.append(this.selectRow("Color theme",w.current==="dark"?"Dark":"Light",["Dark","Light"],H=>w.onSelect(H==="Dark"?"dark":"light")));}C("end"),S("end");let T=document.createElement("div");T.style.cssText=o?"display:flex;min-height:0;flex:1 1 auto;position:relative;overflow:hidden;":"display:flex;min-height:360px;max-height:calc(70vh - 100px);flex:1 1 auto;";let M=document.createElement("div");M.className="vela-sd-rail",M.style.cssText=o?"display:flex;flex-direction:column;gap:2px;padding:10px 8px;overflow-y:auto;":`flex:0 0 170px;display:flex;flex-direction:column;gap:2px;padding:10px 8px;border-right:1px solid ${co};overflow-y:auto;`;let E=null;o&&(E=document.createElement("div"),E.className="vela-sd-railscrim",E.addEventListener("click",()=>h?.()),h=w=>{let H=w??!M.classList.contains("open");M.classList.toggle("open",H),E?.classList.toggle("open",H);});let k=document.createElement("div");k.className="vela-sd-pane",k.style.cssText=o?"flex:1;min-width:0;overflow-y:auto;padding:6px 14px calc(14px + env(safe-area-inset-bottom, 0px));":"flex:1;overflow-y:auto;padding:6px 18px 14px;";let L=[],P=null;for(let w of [...p.children]){let H=w.dataset.sdTab;if(H!==void 0){let z=document.createElement("div");z.style.display="none";let te=document.createElement("button");te.type="button",te.textContent=H,te.className="vela-sd-tab"+(w.dataset.sdSub!==void 0?" vela-sd-tab-sub":""),L.push({title:H,el:z,tab:te,style:w.dataset.sdStyle,visibility:w.dataset.sdVisibility}),P=z,w.remove();continue}P&&P.appendChild(w);}this.syncTypeTabs=w=>{let H=false;L.forEach((z,te)=>{if(!z.style)return;let me=z.visibility==="always"||z.style===w||w==="heikinashi"&&z.style==="heikinashi";z.tab.style.display=me?"":"none",!me&&z.el.style.display==="block"&&(H=true);}),H&&V(0);};let V=w=>{L.forEach((H,z)=>{H.el.style.display=z===w?"block":"none",H.tab.classList.toggle("on",z===w);}),this.activeSection=L[w]?.title??null,o&&(d.textContent=L[w]?.title??"Chart settings",h?.(false));};L.forEach((w,H)=>{w.tab.addEventListener("click",()=>V(H)),M.appendChild(w.tab),k.appendChild(w.el);}),this.tabs=L.map((w,H)=>({title:w.title,show:()=>V(H)}));let G=i!==void 0?L.findIndex(w=>w.title.toLowerCase()===i.toLowerCase()):L.findIndex(w=>w.style===e.series.style&&!w.tab.classList.contains("vela-sd-tab-sub"));V(G>=0?G:0),this.syncTypeTabs?.(e.series.style),T.append(M,k),E&&T.append(E),l.appendChild(T),l.appendChild(this.footer(e)),a.appendChild(l),this.container.appendChild(a),this.root=a;for(let w of L){let H=[...w.el.querySelectorAll("[data-sd-rows-host]")];if(H.length===0){this.layoutSettingsGrids(w.el,l);continue}for(let z of H)this.layoutSettingsGrids(z,l);}}close(){Sc(),Pc(),this.root?.remove(),this.root=null,this.tabs=[];}destroy(){this.close(),this.onChange=null,this.onImport=null,this.config=null;}emitType(e,t,n){this.emit({chartTypes:{[e]:{[t]:n}}});}emit(e){this.onChange?.(e);}sectionTitle(e){let t=document.createElement("div");return t.className="vela-sd-sect",t.style.cssText="margin:24px 0 0;padding-bottom:8px;font-size:var(--vela-font-size-sm);font-weight:700;letter-spacing:0.05em;text-transform:uppercase;color:var(--vela-fg-muted);",t.textContent=e,t}chartTypeSection(e,t,n,r){let i=this.section(t.title);i.dataset.sdStyle=e,i.dataset.sdVisibility=t.visibility??"active",r.append(i);let o=n.chartTypes[e]??{},a={},l=h=>{for(let u of h)for(let p of Rn(u)){let m=o[p.key];a[p.key]=typeof m===p.type?m:p.defval;}};t.rows&&l(t.rows);for(let h of t.instances??[])l(h.rows);for(let h of t.subsections??[])l(h.rows);for(let h of t.instances??[])!h.enableKey||h.enableKey in a||(a[h.enableKey]=o[h.enableKey]===true);for(let h of t.subsections??[])!h.enableKey||h.enableKey in a||(a[h.enableKey]=o[h.enableKey]===true);let c=[],d=(h,u)=>{a[h]=u,this.emitType(e,h,u);for(let p of c)p();};t.instances&&t.instances.length>0?r.append(this.instancesBlock(e,t.instances,a,d,c)):t.rows&&(t.layout==="grouped"?r.append(this.groupedRows(`${e}/rows`,t.rows,a,d,c)):this.flatTypeRows(t.rows,a,d,c,r));for(let h of t.subsections??[]){let u=this.section(h.title);u.dataset.sdStyle=e,u.dataset.sdVisibility=t.visibility??"active",u.dataset.sdSub="1",r.append(u),r.append(this.groupedRows(`${e}/${h.title}`,h.rows,a,d,c,h.enableKey));}for(let h of c)h();}flatTypeRows(e,t,n,r,i){let o=[];for(let a of e){let l=a.kind==="heading"||a.kind==="header"?this.sectionTitle(a.label):this.typeRow(a,t,n,r);o.push({el:l,when:a.when}),i.append(l);}r.push(()=>{for(let a of o)a.el.classList.toggle("vela-sd-hide",!Lt(a.when,t));});}typeRow(e,t,n,r){let i=ki(e),o=[];for(let a of i.controls){let l=this.inlineControl(a,t,n,i.toggle!==void 0);if(a.kind!=="hint"&&r.push(()=>l.dispatchEvent(new Event("vela-sync"))),a.kind!=="hint"&&a.when){l.dataset.sdSelfGated="1";let c=a.when;r.push(()=>{l.style.display=Lt(c,t)?"":"none";});}o.push(l);}if(i.toggle){let a=i.toggle,l=this.toggleRow(i.label,t[a.key],c=>n(a.key,c),o,()=>t[a.key]===true);return r.push(()=>l.dispatchEvent(new Event("vela-sync"))),l}return this.rowWith(i.label,o)}inlineControl(e,t,n,r){if(e.kind==="hint"){let a=document.createElement("span");return a.textContent=e.text,a.style.cssText="color:var(--vela-fg-muted);",a}if(e.kind==="color"){let a=this.swatch(t[e.key],l=>n(e.key,l),()=>t[e.key]);return a.title=e.label,a}if(e.kind==="width"){let a=typeof t[e.key]=="number"?t[e.key]:e.defval,l=Lc(this.theme,()=>a,c=>{a=c,n(e.key,c);});return l.title=e.label,l}if(e.kind==="select"){let a=document.createElement("select");a.className="vela-sd-select",a.style.cssText="max-width:200px;flex:0 0 auto;",a.title=e.label;let l=typeof t[e.key]=="string"?t[e.key]:e.defval;for(let[c,d]of Cf(e.options)){let h=document.createElement("option");h.value=c,h.textContent=d,c===l&&(h.selected=true),a.appendChild(h);}return a.addEventListener("change",()=>n(e.key,a.value)),a.addEventListener("vela-sync",()=>{a.value=typeof t[e.key]=="string"?t[e.key]:e.defval;}),a}let i=document.createElement("input");i.type="number",i.className="vela-sd-number",r&&(i.style.width="56px"),e.min!==void 0&&(i.min=String(e.min)),e.max!==void 0&&(i.max=String(e.max)),i.step=String(e.step??1),i.title=e.label;let o=typeof t[e.key]=="number"?t[e.key]:e.defval;return e.placeholder!==void 0?(i.placeholder=e.placeholder,o!==e.defval&&(i.value=String(o)),i.addEventListener("change",()=>{let a=i.value.trim()===""?e.defval:Number(i.value),l=Number.isFinite(a)?Math.min(e.max??1/0,Math.max(e.min??-1/0,a)):e.defval;i.value=l===e.defval?"":String(l),n(e.key,l);})):(i.value=String(o),i.addEventListener("input",()=>{let a=Number(i.value);Number.isFinite(a)&&n(e.key,a);})),i}instancesBlock(e,t,n,r,i){let o=document.createElement("div"),a=document.createElement("div");a.className="vela-sd-itabs",(t.length>1||t[0]?.enableKey!==void 0)&&o.append(a);let l=t.map((h,u)=>{let p=this.groupedRows(`${e}/#${u}`,h.rows,n,r,i);return o.append(p),p}),c=h=>!h.enableKey||n[h.enableKey]===true,d=()=>{let h=this.typeActiveInstance.get(e)??0;c(t[h]??t[0])||(h=0),this.typeActiveInstance.set(e,h),a.replaceChildren(),t.forEach((p,m)=>{if(!c(p))return;let f=document.createElement("button");f.type="button",f.className="vela-sd-itab"+(m===h?" on":"");let b=document.createElement("span");if(b.textContent=p.label,f.append(b),m===h&&p.enableKey){let g=document.createElement("span");g.className="vela-sd-ix",g.textContent="\u2715",g.title=`Remove ${p.label}`,g.addEventListener("click",v=>{v.stopPropagation(),this.typeActiveInstance.set(e,0),r(p.enableKey,false);}),f.append(g);}f.addEventListener("click",()=>{this.typeActiveInstance.set(e,m),d();}),a.append(f);});let u=t.findIndex(p=>!c(p));if(u>=0){let p=document.createElement("button");p.type="button",p.className="vela-sd-itab vela-sd-itab-add",p.textContent="+",p.title=`Add ${t[u].label}`,p.addEventListener("click",()=>{this.typeActiveInstance.set(e,u),r(t[u].enableKey,true);}),a.append(p);}l.forEach((p,m)=>p.classList.toggle("vela-sd-hide",m!==h));};return i.push(d),o}groupedRows(e,t,n,r,i,o){let a=document.createElement("div");a.className="vela-sd-struct";let l=document.createElement("div");l.className="vela-sd-toc";let c=document.createElement("div");c.dataset.sdRowsHost="1",c.style.cssText="flex:1 1 auto;min-width:0;",a.append(l,c);let d=[],h=[],u=[],p=-1;for(let f of t){if(f.kind==="heading"){p=h.length,h.push(f.label),u.push(f.when);continue}if(f.kind==="header"){d.push({el:this.sectionTitle(f.label),when:f.when,group:p,header:true}),c.append(d[d.length-1].el);continue}let b=this.typeRow(f,n,r,i),g=f.kind==="row"?f.toggle?.key:f.kind==="range"?void 0:f.key;d.push({el:b,when:f.when,group:p,key:g}),c.append(b);}let m=()=>{let f=h.map((y,x)=>Lt(u[x],n)&&d.some(S=>S.group===x&&!S.header&&Lt(S.when,n))),b=h.indexOf(this.typeActiveGroup.get(e)??"");(b<0||!f[b])&&(b=f.findIndex(Boolean)),b>=0&&this.typeActiveGroup.set(e,h[b]),l.replaceChildren(),h.forEach((y,x)=>{if(!f[x])return;let S=document.createElement("button");S.type="button",S.className="vela-sd-toc-btn"+(x===b?" on":""),S.textContent=y,S.addEventListener("click",()=>{this.typeActiveGroup.set(e,y),m();}),l.append(S);});let g=f.some(Boolean);l.classList.toggle("vela-sd-hide",!g),a.classList.toggle("no-toc",!g);let v=!o||n[o]===true;for(let y=0;y<d.length;y++){let x=d[y],S=(x.group===-1||x.group===b)&&Lt(x.when,n);if(S&&x.header){let C=false;for(let T=y+1;T<d.length;T++){let M=d[T];if(M.group!==x.group||M.header)break;if(Lt(M.when,n)){C=true;break}}S=C;}x.el.classList.toggle("vela-sd-hide",!S),x.el.classList.toggle("vela-sd-soft",S&&!v&&x.key!==o);}};return i.push(m),a}separator(){let e=document.createElement("div");return e.className="vela-sd-sep",e.style.cssText="height:14px;",e}layoutSettingsGrids(e,t){if(e.childElementCount===0)return;if(this.mobileLayout){let l=document.createElement("div");for(l.style.cssText="display:grid;grid-template-columns:minmax(0,1fr) max-content;align-items:center;column-gap:12px;row-gap:16px;";e.firstChild;)l.appendChild(e.firstChild);e.appendChild(l),this.prepareGridItems(l);return}let n=[...e.querySelectorAll(".vela-sd-row")],r=document.createElement("div");r.style.cssText="position:absolute;left:-9999px;top:0;visibility:hidden;display:flex;flex-direction:column;font:13px var(--vela-font);pointer-events:none;",t.appendChild(r);let i=0;for(let l of n){let c=l.children[0];if(!c)continue;let d=c.cloneNode(true);r.appendChild(d),i=Math.max(i,d.getBoundingClientRect().width);}r.remove();let o=i>0?`${Math.ceil(i)}px`:"max-content",a=document.createElement("div");for(a.style.cssText=`display:grid;grid-template-columns:${o} max-content;align-items:center;column-gap:12px;row-gap:16px;`;e.firstChild;)a.appendChild(e.firstChild);e.appendChild(a),this.prepareGridItems(a);}prepareGridItems(e){for(let t of [...e.children]){if(t.dataset.sdGroup!==void 0){this.prepareGridItems(t);continue}t.classList.contains("vela-sd-row")?t.style.display="contents":(t.classList.contains("vela-sd-bool")||t.classList.contains("vela-sd-sect")||t.classList.contains("vela-sd-sep"))&&(t.style.gridColumn="1 / -1");}}swatch(e,t,n){let r=e;return xs(this.theme,()=>n?n():r,i=>{r=i,t(i);})}rowWith(e,t){let{wrap:n}=this.row(e),r=document.createElement("div");r.style.cssText="display:flex;align-items:center;gap:6px;flex:0 0 auto;";for(let i of t)r.appendChild(i);return n.appendChild(r),n}section(e){let t=document.createElement("div");return t.dataset.sdTab=e,t.style.display="none",t}group(){let e=document.createElement("div");return e.dataset.sdGroup="",e.style.cssText="display:contents;",e}row(e){let t=document.createElement("div");t.className="vela-sd-row";let n=document.createElement("span");return n.textContent=e,n.style.cssText="opacity:0.85;white-space:nowrap;",t.appendChild(n),{wrap:t}}colorRow(e,t,n){let{wrap:r}=this.row(e),i=t;return r.appendChild(xs(this.theme,()=>i,o=>{i=o,n(o);})),r}boolRow(e,t,n){return this.toggleRow(e,t,n,[])}toggleRow(e,t,n,r,i){let o=document.createElement("div"),a=document.createElement("button");a.type="button",a.className="vela-sd-check"+(t?" on":""),a.innerHTML=oe("check",11);let l=t,c=()=>(l=!l,a.classList.toggle("on",l),l),d=document.createElement("span");if(d.textContent=e,d.style.cssText="opacity:0.85;white-space:nowrap;",r.length===0)return o.className="vela-sd-bool",o.style.cssText="display:flex;align-items:center;gap:8px;min-height:22px;",o.append(a,d),a.addEventListener("click",()=>n(c())),i&&o.addEventListener("vela-sync",()=>{l=i(),a.classList.toggle("on",l);}),o;o.className="vela-sd-row";let h=document.createElement("div");h.style.cssText="display:flex;align-items:center;gap:8px;",h.append(a,d);let u=document.createElement("div");u.style.cssText="display:flex;align-items:center;gap:6px;";for(let m of r)u.appendChild(m);let p=m=>{for(let f of r)f.dataset.sdSelfGated!=="1"&&(f.style.opacity=m?"1":"0.4",f.style.pointerEvents=m?"":"none");};return p(t),a.addEventListener("click",()=>{let m=c();n(m),p(m);}),i&&o.addEventListener("vela-sync",()=>{l=i(),a.classList.toggle("on",l),p(l);}),o.append(h,u),o}numberRow(e,t,n,r,i,o){let{wrap:a}=this.row(e),l=document.createElement("input");return l.type="number",l.value=String(t),l.min=String(n),l.max=String(r),l.step=String(i),l.className="vela-sd-number",l.addEventListener("input",()=>{let c=Number(l.value);Number.isFinite(c)&&o(c);}),a.appendChild(l),a}selectRowLabeled(e,t,n,r){let{wrap:i}=this.row(e),o=document.createElement("select");o.className="vela-sd-select",o.style.cssText="max-width:200px;flex:0 0 auto;";for(let[a,l]of n){let c=document.createElement("option");c.value=a,c.textContent=l,a===t&&(c.selected=true),o.appendChild(c);}return o.addEventListener("change",()=>r(o.value)),i.appendChild(o),i}selectRow(e,t,n,r){let{wrap:i}=this.row(e),o=document.createElement("select");o.className="vela-sd-select",o.style.cssText="max-width:200px;flex:0 0 auto;";for(let a of n){let l=document.createElement("option");l.value=a,l.textContent=a,a===t&&(l.selected=true),o.appendChild(l);}return o.addEventListener("change",()=>r(o.value)),i.appendChild(o),i}footer(e){let t=document.createElement("div");t.style.cssText=`border-top:1px solid ${co};padding:10px 14px;display:flex;align-items:center;justify-content:flex-start;gap:8px;flex:0 0 auto;`;let n=document.createElement("button");return n.type="button",n.textContent="Reset defaults",n.className="vela-sd-btn",n.addEventListener("click",()=>this.onReset?.()),t.appendChild(n),t}};function Cf(s){return s.map(e=>typeof e=="string"?[e,e]:e)}function Tf(s){let e=gs.map(n=>[n.value,vs(n.value,n.label)]),t=ao(s);return gs.some(n=>n.value===t)?e:[[t,vs(t,t)],...e]}var Mf=4.5,Lf=R,Pf=W(he,.55),Ef=.7,kc=wa,kf=vr,Ic={selected:.3,hovered:.12};function ws(s){let e=new Set(s.selected);return s.dragged&&e.add(s.dragged),s.hovered&&e.add(s.hovered),s.mutedLabel&&e.delete(s.mutedLabel),e}var ho=class{constructor(){this.targets={};}paintAll(e,t,n,r,i={}){this.targets=i;for(let o of t)o.visible&&this.paintClipped(e,o,n,()=>this.paintOne(e,o,n,r));this.targets={},this.paintHighlights(e,t,n,ws(i));}paintHighlights(e,t,n,r){if(r.size!==0)for(let i of t)i.visible&&r.has(i.id)&&this.paintClipped(e,i,n,()=>this.paintHandles(e,i.handlePoints(n)));}paintClipped(e,t,n,r){if(!n.paneRect){r();return}let i=n.paneRect(t.paneId);!i||i.height<=0||(e.save(),e.beginPath(),e.rect(0,i.top,n.width,i.height),e.clip(),r(),e.restore());}paintGhost(e,t,n,r){e.globalAlpha=Ef,t instanceof ze||t instanceof Re?this.paintTimeSpanGhost(e,t,n):this.paintOne(e,t,n,r),e.globalAlpha=1;}paintTimeSpanGhost(e,t,n){let r=t.anchors[0],i=t.anchors[1];if(!r)return;let o=t instanceof ze?t.reg?.midColor||he:he,a=h=>{let u=n.xOf(h);e.save(),e.strokeStyle=o,e.globalAlpha=.6*e.globalAlpha,e.lineWidth=1,e.setLineDash([4,4]),e.beginPath(),e.moveTo(u,0),e.lineTo(u,n.height),e.stroke(),e.restore();};a(r.time),i&&a(i.time);let l=n.yOf(r.price,t.paneId),c=i?n.yOf(i.price,t.paneId):null,d=[];l!=null&&d.push([n.xOf(r.time),l]),i&&c!=null&&(e.save(),e.strokeStyle=o,e.lineWidth=1,e.setLineDash([]),e.beginPath(),e.moveTo(n.xOf(r.time),l??c),e.lineTo(n.xOf(i.time),c),e.stroke(),e.restore(),d.push([n.xOf(i.time),c])),this.paintHandles(e,d);}paintSnapRing(e,t,n,r){e.setLineDash([]),e.globalAlpha=.9,e.beginPath(),e.arc(t,n,5.5,0,Math.PI*2),e.strokeStyle=r.textColor,e.lineWidth=1.5,e.stroke(),e.globalAlpha=1;}paintOne(e,t,n,r){if(t.type==="highlighter"&&t instanceof J){this.paintHighlighter(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof J){if(this.paintSegments(e,t,n),t.type==="path"){let i=t.handlePoints(n);i.length>=2&&this.paintArrowhead(e,i[i.length-2],i[i.length-1],t.style);}this.paintLabel(e,t,n,r);return}if(t instanceof bt){this.paintArrowMark(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof gt){this.paintGlyphStamp(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof Me){this.paintRadialFib(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof wt){this.paintFibSpiral(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof Ct){this.paintDedekind(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof ye){this.paintMachFigure(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof St){this.paintFibRatios(e,t,n,r),this.paintGannArcs(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof ee){this.paintFibRatios(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof Tt){this.paintMeasureBox(e,t,n,r);return}if(t instanceof Oe){this.paintPosition(e,t,n,r);return}if(t instanceof ze){this.paintRegressionChannel(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof ft){this.paintAnchoredVwap(e,t,n),this.paintLabel(e,t,n,r);return}if(t instanceof Re){this.paintFixedRangeVp(e,t,n,r),this.paintLabel(e,t,n,r);return}if(t instanceof ae){this.paintPattern(e,t,n,r);return}if(t instanceof pt){this.paintComment(e,t,n,r);return}if(t instanceof ut){this.paintPriceNote(e,t,n,r);return}if(t instanceof mt){this.paintSignpost(e,t,n,r);return}if(t instanceof Ie){this.paintCallout(e,t,n,r);return}if(t instanceof dt){this.paintNote(e,t,n,r);return}if(t instanceof ht){this.paintPriceLabel(e,t,n,r);return}switch(t.type){case "hline":{let i=t.handlePoints(n);if(i.length===0)return;this.stroke(e,t.style,()=>{e.moveTo(0,i[0][1]),e.lineTo(n.width,i[0][1]);});break}case "trendline":case "arrow":{let i=t.handlePoints(n);if(i.length<2)return;this.stroke(e,t.style,()=>{e.moveTo(i[0][0],i[0][1]),e.lineTo(i[1][0],i[1][1]);}),t.style.arrowRight&&this.paintArrowhead(e,i[0],i[1],t.style),t.style.arrowLeft&&this.paintArrowhead(e,i[1],i[0],t.style);break}case "ellipse":{let i=t.handlePoints(n);if(i.length<2)return;let o=(i[0][0]+i[1][0])/2,a=(i[0][1]+i[1][1])/2,l=Math.abs(i[1][0]-i[0][0])/2,c=Math.abs(i[1][1]-i[0][1])/2;t.style.fillColor&&(e.save(),e.fillStyle=t.style.fillColor,e.beginPath(),e.ellipse(o,a,l,c,0,0,Math.PI*2),e.fill(),e.restore()),this.applyStroke(e,t.style),e.beginPath(),e.ellipse(o,a,l,c,0,0,Math.PI*2),e.stroke(),e.setLineDash([]);break}case "ray":{let i=t.handlePoints(n);if(i.length<2)return;let[o,a,l,c]=an(i[0][0],i[0][1],i[1][0],i[1][1],"right",n.width,n.height);this.stroke(e,t.style,()=>{e.moveTo(o,a),e.lineTo(l,c);});break}case "extendedline":{let i=t.handlePoints(n);if(i.length<2)return;let[o,a,l,c]=an(i[0][0],i[0][1],i[1][0],i[1][1],"both",n.width,n.height);this.stroke(e,t.style,()=>{e.moveTo(o,a),e.lineTo(l,c);});break}case "vline":{let i=t.handlePoints(n);if(i.length===0)return;this.stroke(e,t.style,()=>{e.moveTo(i[0][0],0),e.lineTo(i[0][0],n.height);});break}case "hray":{let i=t.handlePoints(n);if(i.length===0)return;this.stroke(e,t.style,()=>{e.moveTo(i[0][0],i[0][1]),e.lineTo(n.width,i[0][1]);});break}case "crossline":{let i=t.handlePoints(n);if(i.length===0)return;this.stroke(e,t.style,()=>{e.moveTo(0,i[0][1]),e.lineTo(n.width,i[0][1]),e.moveTo(i[0][0],0),e.lineTo(i[0][0],n.height);});break}case "infoline":this.paintInfoLine(e,t,n);break;case "trendangle":this.paintTrendAngle(e,t,n,r);break;case "circle":{let i=t.handlePoints(n);if(i.length<2)return;let o=i[0][0],a=i[0][1],l=Math.hypot(i[1][0]-o,i[1][1]-a);if(l<1)return;t.style.fillColor&&(e.save(),e.fillStyle=t.style.fillColor,e.beginPath(),e.arc(o,a,l,0,Math.PI*2),e.fill(),e.restore()),this.applyStroke(e,t.style),e.beginPath(),e.arc(o,a,l,0,Math.PI*2),e.stroke(),e.setLineDash([]);break}case "box":{let i=t.handlePoints(n);if(i.length<2)return;let o=Math.min(i[0][0],i[1][0]),a=Math.min(i[0][1],i[1][1]),l=Math.abs(i[1][0]-i[0][0]),c=Math.abs(i[1][1]-i[0][1]);t.style.fillColor&&(e.save(),e.fillStyle=t.style.fillColor,e.fillRect(o,a,l,c),e.restore()),this.applyStroke(e,t.style),e.strokeRect(o,a,l,c),e.setLineDash([]);break}}this.paintLabel(e,t,n,r);}paintLabel(e,t,n,r){let i=t.text;if(!i||!i.value||t.id===this.targets.mutedLabel)return;let o=Rf(t,n);if(!o)return;let a=ce(i.size);e.font=`${i.bold?"bold ":""}${i.italic?"italic ":""}${a}px ${r.fontFamily}`,e.textBaseline="top",e.textAlign=o.align,e.fillStyle=i.color??r.textColor;let l=Ve(a),c=i.value.split(`
186
+ `);c.forEach((d,h)=>e.fillText(d,o.x,o.top+h*l)),e.textAlign="left",t.type==="text"&&this.paintTextFrame(e,t.id,o.x,o.top,c,a,r);}paintTextFrame(e,t,n,r,i,o,a){let l=this.targets,c=l.selected?.has(t)?Ic.selected:l.hovered===t?Ic.hovered:0;if(c===0)return;let d=Ve(o),h=Math.max(8,...i.map(u=>e.measureText(u).width));e.save(),e.setLineDash([]),e.lineWidth=1,e.strokeStyle=W(a.textColor,c),je(e,n-At,r-(d-o)/2-Ot,h+At*2,i.length*d+Ot*2,4),e.stroke(),e.restore();}paintFibRatios(e,t,n,r){let i=t.entryLines(n);if(!i||i.length===0)return;for(let l of t.fillBands(n))e.save(),e.globalAlpha=.06*e.globalAlpha,e.fillStyle=l.color,e.fillRect(l.x,l.y,l.w,l.h),e.restore();e.textBaseline="middle";let o=`${ce(t.numbersSize)}px ${r.fontFamily}`,a=`${ce(t.labelsSize)}px ${r.fontFamily}`;for(let l of i)this.stroke(e,{...t.style,lineColor:l.color},()=>{e.moveTo(l.x1,l.y1),e.lineTo(l.x2,l.y2);}),e.fillStyle=l.color,e.font=o,e.textAlign=l.numberAlign,e.fillText(l.numberText,l.numberX,l.numberY),l.label&&(e.font=a,e.textAlign="center",e.fillText(l.label,l.labelX,l.labelY));e.textAlign="left",e.textBaseline="alphabetic";}paintRadialFib(e,t,n,r){let i=t.radial(n);if(i&&i.R0>=1){let o=`${ce(t.numbersSize)}px ${r.fontFamily}`,a=(i.a0+i.a1)/2;e.textBaseline="middle";for(let l of t.levels){if(!l.enabled)continue;let c=i.R0*l.ratio;c<.5||(this.applyStroke(e,{...t.style,lineColor:l.color}),e.beginPath(),e.arc(i.cx,i.cy,c,i.a0,i.a1),e.stroke(),e.setLineDash([]),e.fillStyle=l.color,e.font=o,e.textAlign="left",e.fillText(String(l.ratio),i.cx+Math.cos(a)*c+3,i.cy+Math.sin(a)*c));}e.textBaseline="alphabetic",e.textAlign="left";}for(let o of t.boundingLines(n))this.stroke(e,t.style,()=>{e.moveTo(o[0],o[1]),e.lineTo(o[2],o[3]);});}paintGannArcs(e,t,n){let r=t.arcGeom(n);if(!r||Math.abs(r.bx)<1||Math.abs(r.py)<1)return;let i=24;for(let o of Vo){this.applyStroke(e,{...t.style,lineColor:o.color}),e.beginPath();for(let a=0;a<=i;a+=1){let l=a/i*(Math.PI/2),c=r.ox+o.k*r.bx*Math.cos(l),d=r.oy+o.k*r.py*Math.sin(l);a===0?e.moveTo(c,d):e.lineTo(c,d);}e.stroke();}e.setLineDash([]);}paintFibSpiral(e,t,n){let r=t.spiralPoints(n);!r||r.length<2||this.stroke(e,t.style,()=>{e.moveTo(r[0][0],r[0][1]);for(let i=1;i<r.length;i+=1)e.lineTo(r[i][0],r[i][1]);});}paintMachFigure(e,t,n,r){let i=t.geom(n);if(i){for(let o of i.circles)this.applyStroke(e,{...t.style,lineColor:o.color}),e.beginPath(),e.arc(o.cx,o.cy,o.r,0,Math.PI*2),e.stroke();this.applyStroke(e,t.style),e.lineWidth=t.style.lineWidth+.5;for(let o of i.rays)e.beginPath(),e.moveTo(o[0],o[1]),e.lineTo(o[2],o[3]),e.stroke();if(e.beginPath(),e.arc(i.noseX,i.noseY,Math.max(2.5,t.style.lineWidth+1.5),0,Math.PI*2),e.fillStyle=t.style.lineColor,e.fill(),e.setLineDash([]),t.showRatios!==false){let o=`${ce("small")}px ${r.fontFamily}`;e.font=o,e.textBaseline="middle",e.textAlign="left";for(let a of i.circles){let l=a.cx+i.fx*a.r+4,c=a.cy+i.fy*a.r;e.fillStyle=a.color,e.fillText(If(a.ratio),l,c);}e.textBaseline="alphabetic",e.textAlign="left";}}}paintDedekind(e,t,n){let r=t.box(n),i=t.geodesics(n);if(!r||!i)return;let{left:o,right:a,top:l,bot:c}=r;e.save(),this.applyStroke(e,t.style),e.globalAlpha*=.45,e.strokeRect(o,l,a-o,c-l),e.restore(),e.save(),e.beginPath(),e.rect(o,l,a-o,c-l),e.clip(),this.applyStroke(e,t.style);for(let d of i)e.beginPath(),d.kind==="vline"?(e.moveTo(d.x,d.y0),e.lineTo(d.x,d.y1)):e.arc(d.cx,d.cy,d.r,Math.PI,0,false),e.stroke();e.setLineDash([]),e.restore();}paintMeasureBox(e,t,n,r){let i=t.handlePoints(n);if(i.length<2)return;let o=Math.min(i[0][0],i[1][0]),a=Math.min(i[0][1],i[1][1]),l=Math.abs(i[1][0]-i[0][0]),c=Math.abs(i[1][1]-i[0][1]),d=t.isUp()?q:X;e.save(),e.globalAlpha=.12*e.globalAlpha,e.fillStyle=d,e.fillRect(o,a,l,c),e.restore(),e.setLineDash(Dt(t.style.lineStyle,t.style.lineWidth)),e.strokeStyle=d,e.lineWidth=t.style.lineWidth,e.strokeRect(o,a,l,c),e.setLineDash([]);let h=t.measureLabel(n),u=ce(t.text?.size??"normal");e.fillStyle=t.text?.color??r.textColor,e.font=`${u}px ${r.fontFamily}`,e.textAlign="center",e.textBaseline="middle";let p=Math.round(u*1.35),m=a+c/2-(h.length-1)*p/2;h.forEach((f,b)=>e.fillText(f,o+l/2,m+b*p)),e.textAlign="left",e.textBaseline="alphabetic";}paintPosition(e,t,n,r){let i=t.layout(n);if(!i)return;let{x1:o,x2:a,ey:l,sy:c,ty:d}=i,h=a-o,u=(g,v,y)=>{e.save(),e.globalAlpha=.13*e.globalAlpha,e.fillStyle=y,e.fillRect(o,Math.min(g,v),h,Math.abs(v-g)),e.restore();};u(l,d,t.profitColor),u(l,c,t.lossColor);let p=(g,v)=>this.stroke(e,{...t.style,lineColor:v},()=>{e.moveTo(o,g),e.lineTo(a,g);});if(p(d,t.profitColor),p(c,t.lossColor),p(l,t.style.lineColor),!t.showText)return;let m=ce(t.text?.size??"normal");e.fillStyle=t.text?.color??r.textColor,e.textAlign="center",e.textBaseline="middle",e.font=`${m}px ${r.fontFamily}`;let f=o+h/2,b=Math.min(l,c,d)-9;t.showHeader&&e.fillText(t.headerLabel(),f,t.showLossSize?b-Math.round(m*1.15):b),e.font=`${Math.max(10,m-1)}px ${r.fontFamily}`,t.showLossSize&&e.fillText(t.lossSizeLabel(),f,b),t.showTargetLabel&&e.fillText(t.targetLabel(),f,(l+d)/2),t.showStopLabel&&e.fillText(t.stopLabel(),f,(l+c)/2),e.textAlign="left",e.textBaseline="alphabetic";}paintRegressionChannel(e,t,n,r){let i=t.layout(n);if(!i)return;let o=t.reg,a=(c,d,h,u,p)=>{e.save(),e.fillStyle=c,e.beginPath(),e.moveTo(i.x0,d),e.lineTo(i.x1,h),e.lineTo(i.x1,p),e.lineTo(i.x0,u),e.closePath(),e.fill(),e.restore();};a(o.upperFill,i.midY0,i.midY1,i.upperY0,i.upperY1),a(o.lowerFill,i.midY0,i.midY1,i.lowerY0,i.lowerY1);let l=(c,d,h,u)=>this.stroke(e,{lineColor:c,lineWidth:t.style.lineWidth,lineStyle:d},()=>{e.moveTo(i.x0,h),e.lineTo(i.x1,u);});if(l(o.upperColor,o.upperStyle,i.upperY0,i.upperY1),l(o.lowerColor,o.lowerStyle,i.lowerY0,i.lowerY1),l(o.midColor,o.midStyle,i.midY0,i.midY1),i.showR2){let c=`R\xB2 ${Math.round(i.r2*100)}%`;e.font=`11px ${r.fontFamily}`;let d=e.measureText(c).width,h=5,u=4,p=d+h*2,m=i.x0-u-p,f=i.midY0-9;e.save(),e.globalAlpha=.9*e.globalAlpha,je(e,m,f-8,p,16,3),e.fillStyle=kc,e.fill(),e.restore(),e.fillStyle=r.textColor,e.textAlign="left",e.textBaseline="middle",e.fillText(c,m+h,f),e.textBaseline="alphabetic";}}paintFixedRangeVp(e,t,n,r){let i=t.layout(n);if(!i)return;let o=t.frvp,{profile:a,maxW:l,anchorX:c,grow:d,yEdges:h}=i;if(a.maxTotal<=0||l<=0)return;for(let f=0;f<a.rows.length;f+=1){let b=a.rows[f],g=b.up+b.down;if(g<=0)continue;let v=h[f],y=h[f+1],x=Math.min(v,y),S=Math.max(1,Math.abs(y-v)-1),C=g/a.maxTotal*l,T=b.up/g*C,M=f>=a.vaFrom&&f<=a.vaTo,E=M?o.vaUpColor:o.upColor,k=M?o.vaDownColor:o.downColor,L=d===1?c:c-C;T>0&&(e.fillStyle=E,e.fillRect(L,x,T,S)),C-T>0&&(e.fillStyle=k,e.fillRect(L+T,x,C-T,S));}let u=t.style.lineWidth,p=(f,b,g,v)=>{!f||v==null||Rc(b)||this.stroke(e,{lineColor:b,lineWidth:u,lineStyle:g},()=>{e.moveTo(i.x0,v),e.lineTo(i.x1,v);});};p(o.showVah,o.vahColor,o.vahStyle,i.vahY),p(o.showVal,o.valColor,o.valStyle,i.valY),p(o.showPoc,o.pocColor??ge(r.background),o.pocStyle,i.pocY);let m=Math.max(1,u);if(o.showDevelopingPoc&&this.strokePolyline(e,i.developingPoc,{lineColor:o.developingPocColor,lineWidth:m,lineStyle:o.developingPocStyle}),o.showDevelopingVa){let f={lineColor:o.developingVaColor,lineWidth:m,lineStyle:o.developingVaStyle};this.strokePolyline(e,i.developingVaHigh,f),this.strokePolyline(e,i.developingVaLow,f);}}paintAnchoredVwap(e,t,n){let r=t.layout(n);if(!r)return;let i=t.vwap,o=t.style.lineWidth;if(r.upper.length>=2&&i.bandFill){e.save(),e.fillStyle=i.bandFill,e.beginPath(),e.moveTo(r.upper[0][0],r.upper[0][1]);for(let a=1;a<r.upper.length;a+=1)e.lineTo(r.upper[a][0],r.upper[a][1]);for(let a=r.lower.length-1;a>=0;a-=1)e.lineTo(r.lower[a][0],r.lower[a][1]);e.closePath(),e.fill(),e.restore();}this.strokePolyline(e,r.upper,{lineColor:i.upperColor,lineWidth:o,lineStyle:i.upperStyle}),this.strokePolyline(e,r.lower,{lineColor:i.lowerColor,lineWidth:o,lineStyle:i.lowerStyle}),this.strokePolyline(e,r.mid,{lineColor:i.midColor,lineWidth:o,lineStyle:i.midStyle});}strokePolyline(e,t,n){t.length<2||Rc(n.lineColor)||this.stroke(e,n,()=>{e.moveTo(t[0][0],t[0][1]);for(let r=1;r<t.length;r+=1)e.lineTo(t[r][0],t[r][1]);});}paintCallout(e,t,n,r){this.paintBubble(e,t,n,r,5);}paintComment(e,t,n,r){this.paintBubble(e,t,n,r,999);}paintBubble(e,t,n,r,i){let o=t.points(n);if(!o)return;let a=o[0][0],l=o[0][1],c=o[1][0],d=o[1][1],h=t.text,u=ce(h?.size??"normal");e.font=`${h?.bold?"bold ":""}${h?.italic?"italic ":""}${u}px ${r.fontFamily}`;let p=(h?.value??"").split(`
187
+ `),m=Math.max(8,...p.map(P=>e.measureText(P).width)),f=9,b=6,g=Ve(u),v=m+f*2,y=p.length*g+b*2,x=c-v/2,S=d-y/2,C=v/2,T=y/2,M=a-c,E=l-d,k=Math.min(i,v/2,y/2),L=null;if(Math.abs(M)>C||Math.abs(E)>T){let P=Math.max(6,Math.min(v,y)*.18);if(Math.abs(M)/C>=Math.abs(E)/T){let V=M>0?x+v:x,G=Math.max(S+k+P,Math.min(S+y-k-P,d+E*(V-c)/(M||1)));L={edge:M>0?"right":"left",at:G,apex:[a,l],half:P};}else {let V=E>0?S+y:S,G=Math.max(x+k+P,Math.min(x+v-k-P,c+M*(V-d)/(E||1)));L={edge:E>0?"bottom":"top",at:G,apex:[a,l],half:P};}}e.save(),e.fillStyle=Ce(t,r)??r.background,Ac(e,x,S,v,y,k,L),e.fill(),e.restore(),this.applyStroke(e,t.style),Ac(e,x,S,v,y,k,L),e.stroke(),e.setLineDash([]),e.fillStyle=h?.color??ge(Ce(t,r)??r.background),e.textBaseline="top",e.textAlign="left",p.forEach((P,V)=>e.fillText(P,x+f,S+b+V*g));}paintTextPlate(e,t,n,r,i,o,a,l,c,d,h){e.save(),e.fillStyle=Ce(t,n)??n.background,je(e,r,i,o,a,5),e.fill(),e.restore(),this.applyStroke(e,t.style),je(e,r,i,o,a,5),e.stroke(),e.setLineDash([]),e.fillStyle=t.text?.color??ge(Ce(t,n)??n.background),e.textBaseline="top",e.textAlign="left",l.forEach((u,p)=>e.fillText(u,r+d,i+h+p*c));}measureText(e,t,n,r){let i=t.text,o=ce(i?.size??"normal");e.font=`${i?.bold?"bold ":""}${i?.italic?"italic ":""}${o}px ${n.fontFamily}`;let a=(i?.value||r).split(`
188
+ `),l=Math.max(8,...a.map(c=>e.measureText(c).width));return {lines:a,tw:l,fs:o,lh:Ve(o)}}paintNote(e,t,n,r){let i=t.handlePoints(n);if(!i.length)return;let[o,a]=i[0],{lines:l,tw:c,lh:d}=this.measureText(e,t,r,"Note"),h=8,u=5;this.paintTextPlate(e,t,r,o,a,c+h*2,l.length*d+u*2,l,d,h,u);}paintPriceNote(e,t,n,r){let i=t.points(n),o=t.anchors[0];if(!i||!o)return;let[a,l]=i[0],[c,d]=i[1],h=Dc(o.price),u=t.text,p=ce(u?.size??"normal");e.font=`${u?.bold?"bold ":""}${u?.italic?"italic ":""}${p}px ${r.fontFamily}`;let m=9,f=6,b=e.measureText(h).width+m*2,g=Ve(p)+f*2,v=c-b/2,y=d-g/2;this.stroke(e,t.style,()=>{e.moveTo(a,l),e.lineTo(c,d);}),e.fillStyle=t.style.lineColor,e.beginPath(),e.arc(a,l,3,0,Math.PI*2),e.fill(),e.save(),e.fillStyle=Ce(t,r)??r.background,je(e,v,y,b,g,5),e.fill(),e.restore(),this.applyStroke(e,t.style),je(e,v,y,b,g,5),e.stroke(),e.setLineDash([]),e.fillStyle=u?.color??ge(Ce(t,r)??r.background),e.textBaseline="middle",e.textAlign="center",e.fillText(h,c,d+.5);}paintSignpost(e,t,n,r){let i=t.points(n);if(!i)return;let[o,a]=i[0],[l,c]=i[1],{lines:d,tw:h,lh:u}=this.measureText(e,t,r,"Signpost"),p=9,m=6,f=h+p*2,b=d.length*u+m*2;this.stroke(e,t.style,()=>{e.moveTo(o,a),e.lineTo(l,c);}),e.fillStyle=t.style.lineColor,e.beginPath(),e.arc(o,a,3.5,0,Math.PI*2),e.fill(),this.paintTextPlate(e,t,r,l-f/2,c-b/2,f,b,d,u,p,m);}paintPriceLabel(e,t,n,r){let i=t.handlePoints(n),o=t.anchors[0];if(!i.length||!o)return;let[a,l]=i[0],c=Dc(o.price),d=t.text,h=ce(d?.size??"normal");e.font=`${d?.bold?"bold ":""}${d?.italic?"italic ":""}${h}px ${r.fontFamily}`;let u=e.measureText(c).width,p=8,m=4,f=6,b=u+p*2,g=Ve(h)+m*2,v=l-g/2,y=Ce(t,r)??r.background;e.save(),e.fillStyle=y,e.beginPath(),e.moveTo(a,l),e.lineTo(a+f,l-5),e.lineTo(a+f,l+5),e.closePath(),e.fill(),je(e,a+f,v,b,g,4),e.fill(),e.restore(),this.applyStroke(e,t.style),je(e,a+f,v,b,g,4),e.stroke(),e.setLineDash([]),e.fillStyle=d?.color??ge(y),e.textBaseline="middle",e.textAlign="left",e.fillText(c,a+f+p,l+.5);}paintPattern(e,t,n,r){let i=t.handlePoints(n);if(i.length<2)return;let o=t.valid(),a=Ce(t,r)??t.style.lineColor,l=t.style.fillColor?1:.1;for(let[u,p,m]of t.fillTriangles()){let f=i[u],b=i[p],g=i[m];!f||!b||!g||(e.save(),e.globalAlpha=l*e.globalAlpha,e.fillStyle=a,e.beginPath(),e.moveTo(f[0],f[1]),e.lineTo(b[0],b[1]),e.lineTo(g[0],g[1]),e.closePath(),e.fill(),e.restore());}this.stroke(e,t.style,()=>{e.moveTo(i[0][0],i[0][1]);for(let u=1;u<i.length;u+=1)e.lineTo(i[u][0],i[u][1]);});let c=t.necklineIndices();if(c){let u=i[c[0]],p=i[c[1]],m=i.length;if(u&&p&&m>=2){let f=Oo(u[0],u[1],p[0],p[1],i[0][0],i[0][1],i[1][0],i[1][1])??u,b=Oo(u[0],u[1],p[0],p[1],i[m-2][0],i[m-2][1],i[m-1][0],i[m-1][1])??p;this.stroke(e,{...t.style,lineStyle:"dashed"},()=>{e.moveTo(f[0],f[1]),e.lineTo(b[0],b[1]);});}}let d=t.vertexLabels();if(e.fillStyle=r.textColor,e.font=`bold 12px ${r.fontFamily}`,e.textAlign="center",i.forEach((u,p)=>{let m=d[p];if(!m)return;let f=((i[p-1]?.[1]??u[1])+(i[p+1]?.[1]??u[1]))/2,b=u[1]<=f;e.textBaseline=b?"bottom":"top",e.fillText(m,u[0],b?u[1]-7:u[1]+7);}),t.legRatios()){e.font=`11px ${r.fontFamily}`,e.textAlign="left",e.textBaseline="middle";for(let u=2;u<i.length;u+=1){let p=t.ratioAt(u),m=i[u-1],f=i[u];if(p==null||!m||!f)continue;let b=t.ratioOk(u);e.fillStyle=b===true?qn:b===false?Zn:r.textColor,e.fillText(p.toFixed(3),(m[0]+f[0])/2+6,(m[1]+f[1])/2);}}let h=t.patternName();if(h&&i.length>=2){let u=i[i.length-1],p=i[i.length-2],m=p?u[1]<=p[1]:false;e.font=`bold 12px ${r.fontFamily}`,e.fillStyle=o===false?Zn:qn,e.textAlign="center",e.textBaseline=m?"bottom":"top",e.fillText(`${h} ${o?"\u2713":"\u2717"}`,u[0],m?u[1]-22:u[1]+22);}e.textAlign="left",e.textBaseline="alphabetic";}paintHighlighter(e,t,n){let r=t.geometry(n);if(!r||r.segments.length===0)return;e.save(),e.strokeStyle=t.style.lineColor,e.lineWidth=t.style.lineWidth,e.lineCap="round",e.lineJoin="round",e.setLineDash([]),e.beginPath();let i=r.segments[0];e.moveTo(i[0],i[1]);for(let o of r.segments)e.lineTo(o[2],o[3]);e.stroke(),e.restore();}paintSegments(e,t,n){let r=t.geometry(n);if(r){if(r.fill&&r.fill.length>=3&&t.style.fillColor){e.save(),e.fillStyle=t.style.fillColor,e.beginPath(),e.moveTo(r.fill[0][0],r.fill[0][1]);for(let i=1;i<r.fill.length;i+=1)e.lineTo(r.fill[i][0],r.fill[i][1]);e.closePath(),e.fill(),e.restore();}for(let i of r.segments)this.stroke(e,t.style,()=>{e.moveTo(i[0],i[1]),e.lineTo(i[2],i[3]);});}}paintInfoLine(e,t,n){let r=t.handlePoints(n);if(r.length<2)return;let[i,o]=r[0],[a,l]=r[1];this.stroke(e,t.style,()=>{e.moveTo(i,o),e.lineTo(a,l);});let c=t.anchors[0],d=t.anchors[1];if(!c||!d)return;let h=d.price-c.price,u=c.price!==0?h/c.price*100:0,p=n.barsBetween?Math.abs(Math.round(n.barsBetween(c.time,d.time))):0,m=h>=0?"+":"",f=`${m}${h.toFixed(2)} (${m}${u.toFixed(2)}%) ${p} bars`,b=(i+a)/2,g=(o+l)/2;e.font="11px monospace";let v=e.measureText(f).width+12,y=18,x=b-2,S=g-y-4;e.save(),e.globalAlpha=.9*e.globalAlpha,je(e,x,S,v,y,3),e.fillStyle=kc,e.fill(),e.strokeStyle=kf,e.lineWidth=1,e.stroke(),e.restore(),e.fillStyle=h>=0?q:X,e.textAlign="left",e.textBaseline="middle",e.fillText(f,x+6,S+y/2),e.textBaseline="alphabetic";}paintTrendAngle(e,t,n,r){let i=t.handlePoints(n);if(i.length<2)return;let[o,a]=i[0],[l,c]=i[1];this.stroke(e,t.style,()=>{e.moveTo(o,a),e.lineTo(l,c);});let d=l-o,h=c-a,u=Math.atan2(-h,d),p=u*(180/Math.PI),m=Math.min(30,Math.hypot(d,h)*.3),f=t.style.lineColor;if(e.save(),e.globalAlpha=.4*e.globalAlpha,e.strokeStyle=f,e.lineWidth=1,e.setLineDash([4,4]),e.beginPath(),e.moveTo(o,a),e.lineTo(o+Math.max(Math.abs(d),m+20),a),e.stroke(),e.restore(),e.setLineDash([]),m>1){let b=-u;e.strokeStyle=f,e.lineWidth=1.5,e.beginPath(),e.arc(o,a,m,Math.min(0,b),Math.max(0,b)),e.stroke();}e.fillStyle=f,e.font=`11px ${r.fontFamily}`,e.textAlign="left",e.textBaseline="alphabetic",e.fillText(`${p.toFixed(1)}\xB0`,o+m+6,a+(h<0?-14:2));}paintArrowMark(e,t,n){let r=t.glyphPoints(n);if(!(!r||r.length<3)){e.save(),e.setLineDash([]),e.fillStyle=t.style.lineColor,e.beginPath(),e.moveTo(r[0][0],r[0][1]);for(let i=1;i<r.length;i+=1)e.lineTo(r[i][0],r[i][1]);e.closePath(),e.fill(),e.restore();}}paintGlyphStamp(e,t,n,r){let i=t.center(n);i&&(e.save(),e.setLineDash([]),e.font=`${t.sizePx()}px ${r.fontFamily}`,e.fillStyle=t.style.lineColor,e.textAlign="center",e.textBaseline="middle",e.fillText(t.glyph,i[0],i[1]),e.textAlign="left",e.textBaseline="alphabetic",e.restore());}paintArrowhead(e,t,n,r){let i=Math.atan2(n[1]-t[1],n[0]-t[0]),o=Math.max(9,r.lineWidth*3.5),a=Math.PI/7;e.save(),e.setLineDash([]),e.fillStyle=r.lineColor,e.beginPath(),e.moveTo(n[0],n[1]),e.lineTo(n[0]-o*Math.cos(i-a),n[1]-o*Math.sin(i-a)),e.lineTo(n[0]-o*Math.cos(i+a),n[1]-o*Math.sin(i+a)),e.closePath(),e.fill(),e.restore();}stroke(e,t,n){this.applyStroke(e,t),e.beginPath(),n(),e.stroke(),e.setLineDash([]);}applyStroke(e,t){e.strokeStyle=t.lineColor,e.lineWidth=t.lineWidth,e.setLineDash(Dt(t.lineStyle,t.lineWidth));}paintHandles(e,t){e.setLineDash([]),e.lineWidth=1.5;for(let[n,r]of t)e.beginPath(),e.arc(n,r,Mf,0,Math.PI*2),e.fillStyle=Pf,e.fill(),e.strokeStyle=Lf,e.stroke();}};function Rc(s){let e=s.trim().toLowerCase();if(/^#[0-9a-f]{8}$/.test(e))return e.endsWith("00");let t=/rgba?\([^)]*,\s*([\d.]+)\s*\)$/.exec(e);return t?parseFloat(t[1])===0:false}function Dc(s){let e=es(s);return s.toLocaleString("en-US",{minimumFractionDigits:e,maximumFractionDigits:e})}function je(s,e,t,n,r,i){let o=Math.min(i,n/2,r/2);s.beginPath(),s.moveTo(e+o,t),s.arcTo(e+n,t,e+n,t+r,o),s.arcTo(e+n,t+r,e,t+r,o),s.arcTo(e,t+r,e,t,o),s.arcTo(e,t,e+n,t,o),s.closePath();}function Ac(s,e,t,n,r,i,o){let a=(l,c,d)=>{if(o&&o.edge===l){let[h,u]=o.apex;l==="top"?(s.lineTo(o.at-o.half,t),s.lineTo(h,u),s.lineTo(o.at+o.half,t)):l==="bottom"?(s.lineTo(o.at+o.half,t+r),s.lineTo(h,u),s.lineTo(o.at-o.half,t+r)):l==="right"?(s.lineTo(e+n,o.at-o.half),s.lineTo(h,u),s.lineTo(e+n,o.at+o.half)):(s.lineTo(e,o.at+o.half),s.lineTo(h,u),s.lineTo(e,o.at-o.half));}s.lineTo(c,d);};s.beginPath(),s.moveTo(e+i,t),a("top",e+n-i,t),s.arcTo(e+n,t,e+n,t+i,i),a("right",e+n,t+r-i),s.arcTo(e+n,t+r,e+n-i,t+r,i),a("bottom",e+i,t+r),s.arcTo(e,t+r,e,t+r-i,i),a("left",e,t+i),s.arcTo(e,t,e+i,t,i),s.closePath();}function If(s){if(!Number.isFinite(s))return "";let e=Math.round(s*1e3)/1e3;return String(e)}function Rf(s,e){let t=s.text;if(!t)return null;let n=s.handlePoints(e),r=t.value.split(`
189
+ `).length,i=Ve(ce(t.size));switch(s.type){case "text":return n[0]?{x:n[0][0]+2,top:n[0][1]+2,align:"left"}:null;case "hline":return n[0]?{x:n[0][0]+8,top:n[0][1]-4-i*r,align:"left"}:null;case "trendline":case "ray":case "extendedline":case "infoline":case "trendangle":return n.length<2?null:{x:(n[0][0]+n[1][0])/2,top:(n[0][1]+n[1][1])/2-6-i*r,align:"center"};case "box":return n.length<2?null:{x:(n[0][0]+n[1][0])/2,top:(n[0][1]+n[1][1])/2-i*r/2,align:"center"};default:return n[0]?{x:n[0][0],top:n[0][1],align:"left"}:null}}function dn(s,e,t,n,r=6){for(let i=s.length-1;i>=0;i-=1){let o=s[i];if(!o.visible)continue;let a=n.paneRect?.(o.paneId);if(!(a&&a.height<=0)&&o.hitTest(e,t,n,r))return o}return null}var Oc=3,Df=4,Fc=Math.PI/4,Bc=new Set(["trendline","ray","extendedline","infoline","trendangle","arrow"]),uo=class{constructor(e){this.deps=e;this.state={kind:"idle"};this.snapAt=null;}snapMarker(){return this.snapAt}placingMarkers(e){if(this.state.kind!=="placing")return null;let{draft:t}=this.state;if(t.placementMode()==="freehand")return null;let n=[];for(let r of t.anchors){let i=e.yOf(r.price,t.paneId);i!=null&&n.push([e.xOf(r.time),i]);}return n.length?n:null}resolve(e,t,n,r){let i=this.deps.projector().pxToPoint(e,t,n);if(r==="off")return this.snapAt=null,i;let o=this.deps.snap(i,n,r,{x:e,y:t}),a=o.time!==i.time||o.price!==i.price;return this.snapAt=a?{point:o,paneId:n}:null,o}resolveAngleSnapped(e,t,n,r){let i=this.deps.projector(),o=i.xOf(e.time),a=i.yOf(e.price,t);if(this.snapAt=null,a==null)return i.pxToPoint(n,r,t);let l=Math.hypot(n-o,r-a);if(l<1)return i.pxToPoint(n,r,t);let c=Math.round(Math.atan2(r-a,n-o)/Fc)*Fc;return i.pxToPoint(o+l*Math.cos(c),a+l*Math.sin(c),t)}placingPivot(e){return Bc.has(e.type)?e.anchors[e.anchors.length-1]??null:null}claim(e,t){return this.deps.activeTool()!=null||this.state.kind!=="idle"?true:this.hitAt(e,t)!=null}cursorAt(e,t){return this.deps.activeTool()!=null?null:this.hitAt(e,t)?"pointer":null}isPlacing(){return this.state.kind==="placing"}isDragging(){return this.state.kind==="pressed"&&this.state.moved}activeDragId(){return this.state.kind==="pressed"&&this.state.moved?this.state.id:null}down(e,t,n="off",r=false){let i=this.deps.projector();if(this.state.kind==="placing"){if(this.state.draft.placementMode()!=="click")return;let l=r?this.placingPivot(this.state.draft):null,c=l?this.resolveAngleSnapped(l,this.state.draft.paneId,e,t):this.resolve(e,t,this.state.draft.paneId,n);this.state.draft.anchors.push(this.placementAnchor(this.state.draft,c)),this.state.draft.anchors.length>=this.state.need?this.finalize():this.deps.changed();return}let o=this.deps.activeTool();if(o){let l=i.paneIdAtY(t)??"price",c=rt(o,{paneId:l,anchors:[this.resolve(e,t,l,n)],style:this.deps.lastStyle()});if(!c)return;this.state={kind:"placing",draft:c,need:c.anchorSchema().max,cursor:null},c.placementMode()==="click"&&c.anchors.length>=this.state.need?this.finalize():this.deps.changed();return}let a=this.hitAt(e,t);if(a){if(r){this.deps.emit({kind:"select",ids:[a.id],additive:true});return}let l=a.hitHandle(e,t,i,6);this.state={kind:"pressed",id:a.id,handle:l,grab:i.pxToPoint(e,t,a.paneId),orig:Af(a),px:e,py:t,moved:false};}}move(e,t,n="off",r=false){if(this.state.kind==="idle"){let o=this.deps.activeTool(),a=this.snapAt!=null;o&&n!=="off"?this.resolve(e,t,this.deps.projector().paneIdAtY(t)??"price",n):this.snapAt=null,(this.snapAt!=null||a)&&this.deps.changed();return}if(this.state.kind==="placing"){if(this.state.draft.placementMode()==="freehand"){this.captureFreehand(e,t);return}let o=r?this.placingPivot(this.state.draft):null;this.state.cursor=o?this.resolveAngleSnapped(o,this.state.draft.paneId,e,t):this.resolve(e,t,this.state.draft.paneId,n),this.deps.changed();return}if(this.state.kind!=="pressed")return;let i=this.byId(this.state.id);if(!(!i||i.locked)&&!(!this.state.moved&&Math.abs(e-this.state.px)<=Oc&&Math.abs(t-this.state.py)<=Oc)){if(this.state.moved=true,this.state.handle>=0){let o=i.anchors[this.state.handle];if(o){let a=r&&Bc.has(i.type)&&i.anchors.length===2?i.anchors[1-this.state.handle]:void 0,l=a?this.resolveAngleSnapped(a,i.paneId,e,t):this.resolve(e,t,i.paneId,n);Of(o,l,i.anchorSchema().slots[this.state.handle]?.free??"both");}i.constrainHandleDrag(this.state.handle);}else {let o=this.deps.projector().pxToPoint(e,t,i.paneId);this.snapAt=null;let a=o.time-this.state.grab.time,l=o.price-this.state.grab.price;i.anchors=i.translateBody(a,l,this.state.orig);}this.deps.changed();}}up(e,t){if(this.snapAt=null,this.state.kind==="placing"){let o=this.state.draft.placementMode();o==="drag"?(this.state.cursor&&this.state.draft.anchors.push(this.state.cursor),this.state.draft.anchors.length>=this.state.draft.anchorSchema().min?this.finalize():this.discardPlacing()):o==="freehand"&&(this.state.draft.anchors.length>=this.state.draft.anchorSchema().min?this.finalize():this.discardPlacing());return}if(this.state.kind!=="pressed")return;let{id:n,moved:r}=this.state;this.state={kind:"idle"};let i=this.byId(n);r?(i&&this.deps.emit({kind:"edit",doc:i.serialize()}),this.deps.changed()):this.deps.openSettings(n,e,t);}cancel(){if(this.snapAt=null,this.state.kind==="placing"){let e=this.state.draft.type;return this.state={kind:"idle"},this.deps.emit({kind:"tool-finished",type:e}),this.deps.changed(),true}if(this.state.kind==="pressed"){let e=this.byId(this.state.id);return e&&this.state.moved&&(e.anchors=this.state.orig.map(t=>({time:t.time,price:t.price}))),this.state={kind:"idle"},this.deps.changed(),true}return false}onToolCleared(){this.state.kind==="placing"&&(this.state={kind:"idle"},this.deps.changed());}ghost(){if(this.state.kind!=="placing")return null;let{draft:e,cursor:t}=this.state;return t?rt(e.type,{paneId:e.paneId,anchors:[...e.anchors,this.placementAnchor(e,t)],style:e.style}):e.anchors.length>=1&&e.type==="hline"?e:null}placementAnchor(e,t){if(e.type!=="parallelchannel"||e.anchors.length!==2)return t;let n=e.anchors[0],r=e.anchors[1],i=r.time-n.time,o=i===0?n.price:n.price+(r.price-n.price)*(t.time-n.time)/i,a=t.price-o;return {time:(n.time+r.time)/2,price:(n.price+r.price)/2+a}}captureFreehand(e,t){if(this.state.kind!=="placing")return;this.snapAt=null;let n=this.state.draft,r=this.deps.projector(),i=n.anchors[n.anchors.length-1],o=i?r.xOf(i.time):NaN,a=i?r.yOf(i.price,n.paneId)??NaN:NaN;if(Math.hypot(e-o,t-a)>Df){if(n.anchors.length>=this.state.need){let l=n.anchors.length-1;n.anchors=n.anchors.filter((c,d)=>d%2===0||d===l);}n.anchors.push(r.pxToPoint(e,t,n.paneId));}this.state.cursor=r.pxToPoint(e,t,n.paneId),this.deps.changed();}finishPlacing(e){if(this.state.kind!=="placing")return false;let t=this.state.draft,n=t.anchorSchema();return t.placementMode()!=="click"||n.max<=n.min||(e&&t.anchors.length>n.min&&t.anchors.pop(),t.anchors.length<n.min)?false:(this.finalize(),true)}discardPlacing(){if(this.state.kind!=="placing")return;let e=this.state.draft.type;this.state={kind:"idle"},this.deps.emit({kind:"tool-finished",type:e}),this.deps.changed();}finalize(){if(this.state.kind!=="placing")return;this.snapAt=null;let e=this.state.draft;e.onPlaced(this.deps.projector());let t=e.type;this.state={kind:"idle"},this.deps.emit({kind:"create",doc:e.serialize()}),this.deps.emit({kind:"tool-finished",type:t}),this.deps.changed();}hitAt(e,t){let n=this.deps.projector();for(let r of this.handleDrawings())if(r.hitHandle(e,t,n,6)>=0)return r;return dn(this.deps.drawings(),e,t,n,6)}handleDrawings(){let e=new Set(this.deps.selectedIds()),t=this.deps.hoveredId();t&&e.add(t);let n=[];for(let r of e){let i=this.byId(r);i&&n.push(i);}return n}byId(e){return this.deps.drawings().find(t=>t.id===e)??null}};function Af(s){return s.anchors.map(e=>({time:e.time,price:e.price}))}function Of(s,e,t){(t==="both"||t==="x")&&(s.time=e.time),(t==="both"||t==="y")&&(s.price=e.price);}var Ze=30,Ff=21,Vc="vela-drawing-popup-styles";function Bf(){if(typeof document>"u"||document.getElementById(Vc))return;let s=document.createElement("style");s.id=Vc,s.textContent=`
190
190
  .vela-dpop input[type=color]{-webkit-appearance:none;appearance:none;border:none;padding:0;background:none;cursor:pointer;border-radius:0;}
191
191
  .vela-dpop input[type=color]::-webkit-color-swatch-wrapper{padding:0;}
192
192
  .vela-dpop input[type=color]::-webkit-color-swatch{border:none;border-radius:0;}
@@ -207,7 +207,7 @@ void main() {
207
207
  .vela-dpop-item[data-active='1']{background:var(--vela-active);}
208
208
  /* A finger needs a wider grab zone than a cursor \u2014 grow the move handle on touch-first
209
209
  devices (the glyph stays centered; only the hit target widens). */
210
- @media (pointer: coarse){.vela-dpop-grip{width:${Ze+14}px !important;}}`,document.head.appendChild(s);}var uo=class{constructor(e,t){this.host=e;this.el=null;this.tipEl=null;this.textPanel=null;this.levelsPanel=null;this.colorPop=null;this.colorOwner=null;this.menuEl=null;this.menuOwner=null;this.onClose=null;this.onOutside=e=>{let t=e.target;if(!this.colorPop?.contains(t)&&!this.menuEl?.contains(t)&&this.el&&!this.el.contains(t)){let n=this.onClose;this.close(),n?.();}};this.theme=t;}setTheme(e){this.theme=e;}isOpen(){return this.el!=null}contains(e){return e?this.el?.contains(e)===true||this.colorPop?.contains(e)===true||this.menuEl?.contains(e)===true:false}open(e,t,n,r){this.close(),Of(),this.onClose=r??null;let i=this.theme,o=e.schema(),a=new Set(o.fields.map(v=>v.path)),l=o.textIsContent===true||!a.has("text.value"),c=document.createElement("div");c.className="vela-dpop",c.style.cssText=`position:absolute;z-index:22;background:${i.background};border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);color:${i.textColor};font:var(--vela-font-size-md) ${i.fontFamily};display:flex;flex-direction:column;pointer-events:auto;overflow:hidden;`,ne(c,i),c.addEventListener("pointerdown",()=>{this.closeColorPopover(),this.closeMenu();});let d=document.createElement("div");if(d.style.cssText="display:flex;align-items:center;gap:2px;padding:4px;",d.appendChild(this.dragHandle()),a.has("glyph")){let v=e.glyph??Cn[0];d.appendChild(this.dropdown("Icon",Cn,v,y=>Zf(y),y=>n.patch({glyph:y})));}if(a.has("size")){let v=e.size??"normal";d.appendChild(this.dropdown("Icon size",Xr,v,y=>Jf(y),y=>n.patch({size:y}),{label:tr}));}if(a.has("style.lineColor")&&d.appendChild(this.colorButton("Line color",Bt,e.style.lineColor||R,v=>n.patch({"style.lineColor":v}))),a.has("style.lineWidth")){let v=o.fields.find(y=>y.path==="style.lineWidth");v?.kind==="number"&&(v.min??1)>1?d.appendChild(this.widthInput("Line width",e.style.lineWidth,v.min??1,v.max??60,v.step??1,y=>n.patch({"style.lineWidth":y}))):d.appendChild(this.dropdown("Line width",[1,2,3,4],e.style.lineWidth,y=>Vt(y,"solid"),y=>n.patch({"style.lineWidth":y}),{label:y=>`${y}px`,labelInTrigger:true}));}a.has("style.lineStyle")&&d.appendChild(this.dropdown("Line style",me.map(v=>v.value),e.style.lineStyle,v=>Vt(2,v),v=>n.patch({"style.lineStyle":v}),{label:un})),a.has("style.fillColor")&&d.appendChild(this.colorButton("Fill",hn,Ce(e,this.theme)??e.style.fillColor??R,v=>n.patch({"style.fillColor":v})));let h=a.has("frvp.rows")&&e instanceof Re,u=a.has("riskPercent")&&e instanceof Oe;if(u){let v=e;d.appendChild(this.colorButton("Profit zone",hn,v.profitColor,y=>n.patch({profitColor:y}))),d.appendChild(this.colorButton("Loss zone",hn,v.lossColor,y=>n.patch({lossColor:y})));}let p=e.reg;if(a.has("reg.midColor")&&p){let v=me.map(y=>y.value);d.appendChild(this.colorButton("Midline color",Bt,p.midColor,y=>n.patch({"reg.midColor":y}))),d.appendChild(this.dropdown("Midline style",v,p.midStyle,y=>Vt(2,y),y=>n.patch({"reg.midStyle":y}),{label:un})),d.appendChild(this.colorButton("Upper line color",Bt,p.upperColor,y=>n.patch({"reg.upperColor":y}))),d.appendChild(this.dropdown("Upper line style",v,p.upperStyle,y=>Vt(2,y),y=>n.patch({"reg.upperStyle":y}),{label:un})),d.appendChild(this.colorButton("Lower line color",Bt,p.lowerColor,y=>n.patch({"reg.lowerColor":y}))),d.appendChild(this.dropdown("Lower line style",v,p.lowerStyle,y=>Vt(2,y),y=>n.patch({"reg.lowerStyle":y}),{label:un})),d.appendChild(this.colorButton("Upper fill",hn,p.upperFill,y=>n.patch({"reg.upperFill":y}))),d.appendChild(this.colorButton("Lower fill",hn,p.lowerFill,y=>n.patch({"reg.lowerFill":y}))),d.appendChild(this.toggle("Show R\xB2",Gf,p.showR2,y=>n.patch({"reg.showR2":y})));}let m=e.vwap;if(a.has("vwap.midColor")&&m){let v=me.map(x=>x.value),y=[.5,1,1.5,2,2.5,3,4,5];d.appendChild(this.colorButton("VWAP color",Bt,m.midColor,x=>n.patch({"vwap.midColor":x}))),d.appendChild(this.dropdown("VWAP style",v,m.midStyle,x=>Vt(2,x),x=>n.patch({"vwap.midStyle":x}),{label:un})),d.appendChild(this.dropdown("Band multiplier",y,m.multiplier,()=>Yf,x=>n.patch({"vwap.multiplier":x}),{label:x=>`${x}\u03C3`,labelInTrigger:true})),d.appendChild(this.colorButton("Upper band color",Bt,m.upperColor,x=>n.patch({"vwap.upperColor":x}))),d.appendChild(this.colorButton("Lower band color",Bt,m.lowerColor,x=>n.patch({"vwap.lowerColor":x}))),d.appendChild(this.colorButton("Band fill",hn,m.bandFill,x=>n.patch({"vwap.bandFill":x})));}if(a.has("maxCurvature")){let v=e.maxCurvature??24;d.appendChild(this.dropdown("Max curvature",_o,v,()=>Xf,y=>n.patch({maxCurvature:y}),{label:y=>`n=${y}`,labelInTrigger:true}));}if(a.has("mach")){let v=e.mach??2;d.appendChild(this.dropdown("Mach number",Ho,v,()=>jf,y=>n.patch({mach:y}),{label:y=>`M=${y}`,labelInTrigger:true}));}if(a.has("waveCount")){let v=e.waveCount??6;d.appendChild(this.dropdown("Waves",No,v,()=>Kf,y=>n.patch({waveCount:y}),{label:y=>`${y}`,labelInTrigger:true}));}let f=e;a.has("showPrice")&&d.appendChild(this.toggle("Show price",Ff,f.showPrice!==false,v=>n.patch({showPrice:v}))),a.has("showDate")&&d.appendChild(this.toggle("Show date",Bf,f.showDate!==false,v=>n.patch({showDate:v}))),a.has("text.color")&&l&&d.appendChild(this.colorButton("Text color",Ss,e.text?.color||i.textColor,v=>n.patch({"text.color":v}))),a.has("text.size")&&l&&d.appendChild(this.dropdown("Text size",Te.map(v=>v.value),e.text?.size??"normal",v=>Hc(v),v=>n.patch({"text.size":v}),{label:tr})),a.has("text.bold")&&!a.has("text.value")&&d.appendChild(this.toggle("Bold",Vc,!!e.text?.bold,v=>n.patch({"text.bold":v}))),a.has("text.italic")&&!a.has("text.value")&&d.appendChild(this.toggle("Italic",_c,!!e.text?.italic,v=>n.patch({"text.italic":v}))),a.has("text.value")&&d.appendChild(this.iconBtn("Text",Ss,()=>this.toggleTextPanel(e,n,!l)));let b=e.editableLevels();if(b&&!(e instanceof ye)){let v=e,y=Te.map(x=>x.value);d.appendChild(this.dropdown("Numbers size",y,v.numbersSize??"small",x=>eb(x),x=>n.patch({numbersSize:x}),{label:tr})),d.appendChild(this.dropdown("Label size",y,v.labelsSize??"normal",x=>Hc(x),x=>n.patch({labelsSize:x}),{label:tr}));}d.appendChild(this.divider()),h&&d.appendChild(this.iconBtn("Settings",Cs,()=>this.toggleFrvpPanel(e,n))),u&&d.appendChild(this.iconBtn("Position size",Cs,()=>this.togglePositionPanel(e,n))),b&&d.appendChild(this.iconBtn("Levels",Cs,()=>this.toggleLevelsPanel(e,n))),d.appendChild(this.toggle("Lock",Vf,e.locked,v=>n.setLocked(v)));let g=this.iconBtn("Delete",Hf,()=>n.remove());g.style.color="var(--vela-danger)",d.appendChild(g),d.appendChild(this.kebabButton(n)),c.append(d),this.host.appendChild(c),this.el=c,c.addEventListener("mouseover",v=>{let y=v.target.closest("[data-tip]");y?this.showTip(y):this.hideTip();}),c.addEventListener("mouseleave",()=>this.hideTip()),this.position(t),setTimeout(()=>document.addEventListener("pointerdown",this.onOutside),0);}close(){document.removeEventListener("pointerdown",this.onOutside),this.closeColorPopover(),this.closeMenu(),this.hideTip(),this.el?.remove(),this.el=null,this.textPanel=null,this.levelsPanel=null,this.onClose=null;}destroy(){this.close();}toggleTextPanel(e,t,n){if(this.textPanel){this.textPanel.remove(),this.textPanel=null,this.reposition();return}let r=this.theme,i=e.text,o=document.createElement("div");o.style.cssText="padding:6px;border-top:1px solid var(--vela-border);display:flex;flex-direction:column;gap:4px;";let a=document.createElement("textarea");a.placeholder="Label\u2026",a.value=i?.value??"",a.rows=1,a.style.cssText=`display:block;width:100%;box-sizing:border-box;min-width:220px;min-height:46px;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:6px;padding:6px 9px;font:13px/18px ${r.fontFamily};resize:none;overflow-y:hidden;`,a.addEventListener("input",()=>{t.patch({"text.value":a.value}),Nc(a),this.reposition();}),a.addEventListener("keydown",c=>{if(c.stopPropagation(),c.key==="Escape"){c.preventDefault();let d=this.onClose;this.close(),d?.();}});let l=document.createElement("div");l.style.cssText="display:flex;align-items:center;justify-content:flex-start;gap:0;transform:scale(0.8);transform-origin:left center;",n&&l.append(this.colorButton("Text color",Ss,i?.color||this.theme.textColor,c=>t.patch({"text.color":c}),14),this.dropdown("Text size",Te.map(c=>c.value),i?.size??"normal",c=>Qf(c),c=>t.patch({"text.size":c}),{label:tr})),l.append(this.toggle("Bold",Vc,!!i?.bold,c=>t.patch({"text.bold":c})),this.toggle("Italic",_c,!!i?.italic,c=>t.patch({"text.italic":c}))),o.append(a,l),this.el?.appendChild(o),this.textPanel=o,Nc(a),this.reposition(),a.focus();}togglePositionPanel(e,t){if(this.levelsPanel){this.levelsPanel.remove(),this.levelsPanel=null,this.reposition();return}let n=this.theme,r=document.createElement("div");r.style.cssText="padding:8px 10px;border-top:1px solid var(--vela-border);display:flex;flex-direction:column;gap:6px;min-width:280px;";let i=()=>{let y=t.resolve();return y instanceof Oe?y:e},o=[],a=()=>o.forEach(y=>y()),l=y=>String(Math.round(y*1e8)/1e8),c=()=>{let y=document.createElement("input");return y.type="number",y.style.cssText=`width:96px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:4px 6px;font:12px ${n.fontFamily};font-variant-numeric:tabular-nums;outline:none;`,y},d=y=>{let x=document.createElement("div");x.style.cssText="display:flex;align-items:center;gap:10px;";let S=document.createElement("span");return S.textContent=y,S.style.cssText="flex:1;opacity:0.9;",x.appendChild(S),r.appendChild(x),x},h=(y,x)=>{y.addEventListener("change",x),y.addEventListener("keydown",S=>{S.stopPropagation(),S.key==="Enter"&&(S.preventDefault(),x(),y.blur());});},u=(y,x,S)=>{let C=d(y),T=c();S?(T.min=String(S.min),T.max=String(S.max),T.step=String(S.step)):T.step="any",T.value=l(i()[x]),h(T,()=>{let E=parseFloat(T.value);if(!Number.isFinite(E)){T.value=l(i()[x]);return}let k=S?Math.min(S.max,Math.max(S.min,E)):E;t.patch({[x]:k}),a();}),o.push(()=>{document.activeElement!==T&&(T.value=l(i()[x]));}),C.appendChild(T);},p=()=>{let y=document.createElement("select");return y.style.cssText=`width:76px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:4px 4px;font:12px ${n.fontFamily};outline:none;cursor:pointer;`,y.addEventListener("keydown",x=>x.stopPropagation()),y},m=(y,x,S)=>{let C="price",T=d(y),M=c();M.step="any",M.style.width="84px";let E=()=>l(i().levelDisplayValue(S,C));M.value=E(),h(M,()=>{let P=parseFloat(M.value);if(!Number.isFinite(P)){M.value=E();return}t.patch({[x]:i().levelPriceFromDisplay(S,C,P)}),a();});let L=p();for(let P of [{value:"price",label:"Price"},{value:"points",label:"Points"}]){let V=document.createElement("option");V.value=P.value,V.textContent=P.label,L.appendChild(V);}L.addEventListener("change",()=>{C=L.value,M.value=E();}),o.push(()=>{document.activeElement!==M&&(M.value=E());}),T.append(M,L);},f=()=>{let y=d("Direction"),x=p();x.style.width="96px";for(let S of Ci){let C=document.createElement("option");C.value=S.value,C.textContent=S.label,x.appendChild(C);}x.value=i().direction,x.addEventListener("change",()=>{t.patch({direction:x.value}),a();}),o.push(()=>{x.value=i().direction;}),y.appendChild(x);},b=(y,x)=>{let S=document.createElement("label");S.style.cssText="display:flex;align-items:center;gap:8px;cursor:pointer;user-select:none;";let C=document.createElement("input");C.type="checkbox",C.checked=i()[x],C.style.cssText=`accent-color:${n.textColor};width:15px;height:15px;flex:none;cursor:pointer;`,C.addEventListener("change",()=>{t.patch({[x]:C.checked}),a();});let T=document.createElement("span");T.textContent=y,T.style.cssText="flex:1;opacity:0.9;",o.push(()=>{C.checked=i()[x];}),S.append(C,T),r.appendChild(S);},g=y=>{let x=document.createElement("div");x.style.cssText="opacity:0.5;font-size:10px;letter-spacing:0.6px;text-transform:uppercase;padding-top:4px;",x.textContent=y,r.appendChild(x);};g("Account"),u("Risk %","riskPercent",{min:0,max:100,step:.1}),u("Account balance","accountBalance",{min:0,max:1e12,step:1}),u("Position size","quantity"),g("Levels"),f(),u("Entry price","entryPrice"),m("Stop","stopPrice","stop"),m("Target","targetPrice","target"),g("Display"),b("Show text","showText"),b("Show direction & ratio","showHeader"),b("Show loss & size","showLossSize"),b("Show target label","showTargetLabel"),b("Show stop label","showStopLabel"),b("Show level prices","showPrices");let v=document.createElement("div");v.style.cssText="opacity:0.7;font-size:11px;line-height:1.4;border-top:1px solid var(--vela-border);padding-top:6px;font-variant-numeric:tabular-nums;",o.push(()=>{let y=i();v.textContent=`${y.headerLabel()} \u2014 ${y.lossSizeLabel()}`;}),r.appendChild(v),a(),this.el?.appendChild(r),this.levelsPanel=r,this.reposition();}toggleFrvpPanel(e,t){if(this.levelsPanel){this.levelsPanel.remove(),this.levelsPanel=null,this.reposition();return}let n=this.theme,r=e.frvp,i=document.createElement("div");i.className="vela-frvp",i.style.cssText="padding:8px 10px;border-top:1px solid var(--vela-border);max-height:360px;overflow-y:auto;display:flex;flex-direction:column;gap:6px;min-width:280px;";let o=(d,h,u,p,m)=>{let f=document.createElement("div");f.style.cssText="display:flex;align-items:center;gap:10px;";let b=document.createElement("span");b.textContent=d,b.style.cssText="flex:1;opacity:0.9;";let g=document.createElement("input");g.type="number",g.min=String(u),g.max=String(p),g.step=String(m),g.value=String(r[h]),g.style.cssText=`width:72px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:4px 6px;font:12px ${n.fontFamily};font-variant-numeric:tabular-nums;outline:none;`;let v=()=>{let y=parseFloat(g.value);if(!Number.isFinite(y)){g.value=String(r[h]);return}let x=Math.min(p,Math.max(u,y));g.value=String(x),t.patch({[`frvp.${h}`]:x});};g.addEventListener("change",v),g.addEventListener("keydown",y=>{y.stopPropagation(),y.key==="Enter"&&(y.preventDefault(),v(),g.blur());}),f.append(b,g),i.appendChild(f);};o("Rows","rows",1,500,1),o("Value Area","valueAreaPct",0,100,1),o("Width %","widthPct",0,100,1);{let d=document.createElement("div");d.style.cssText="display:flex;align-items:center;gap:10px;";let h=document.createElement("span");h.textContent="Anchor",h.style.cssText="flex:1;opacity:0.9;";let u=document.createElement("select");u.style.cssText=`width:96px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:4px 6px;font:12px ${n.fontFamily};outline:none;cursor:pointer;`;for(let p of [{value:"right",label:"Right"},{value:"left",label:"Left"}]){let m=document.createElement("option");m.value=p.value,m.textContent=p.label,m.selected=r.anchor===p.value,u.appendChild(m);}u.addEventListener("change",()=>t.patch({"frvp.anchor":u.value})),u.addEventListener("keydown",p=>p.stopPropagation()),d.append(h,u),i.appendChild(d);}let a=(d,h)=>{let u=document.createElement("div");u.style.cssText="display:flex;align-items:center;gap:10px;";let p=document.createElement("span");p.textContent=d,p.style.cssText="flex:1;opacity:0.9;";let m=document.createElement("button");m.type="button";let f=r[h];m.style.cssText=`width:18px;height:18px;flex:none;border:1px solid var(--vela-border);border-radius:0;cursor:pointer;background:${f};padding:0;`,m.addEventListener("pointerdown",b=>b.stopPropagation()),m.addEventListener("click",b=>{b.stopPropagation(),this.toggleColorPopover(m,f,g=>{f=g,m.style.background=g,t.patch({[`frvp.${h}`]:g});});}),u.append(p,m),i.appendChild(u);};a("Up Volume","upColor"),a("Down Volume","downColor"),a("Value Area Up","vaUpColor"),a("Value Area Down","vaDownColor");let l=me.map(d=>d.value),c=(d,h,u,p)=>{let m=document.createElement("div");m.style.cssText="display:flex;align-items:center;gap:8px;";let f=document.createElement("input");f.type="checkbox",f.checked=!!r[h];let b=r[u]??be(n.background);f.style.cssText=`accent-color:${b};width:15px;height:15px;flex:none;cursor:pointer;`,f.addEventListener("change",()=>t.patch({[`frvp.${h}`]:f.checked}));let g=document.createElement("span");g.textContent=d,g.style.cssText="flex:1;min-width:0;opacity:0.9;";let v=document.createElement("button");v.type="button";let y=b;v.style.cssText=`width:18px;height:18px;flex:none;border:1px solid var(--vela-border);border-radius:0;cursor:pointer;background:${y};padding:0;`,v.addEventListener("pointerdown",S=>S.stopPropagation()),v.addEventListener("click",S=>{S.stopPropagation(),this.toggleColorPopover(v,y,C=>{y=C,v.style.background=C,f.style.accentColor=C,t.patch({[`frvp.${u}`]:C});});});let x=this.dropdown(`${d} style`,l,r[p],S=>Vt(2,S),S=>t.patch({[`frvp.${p}`]:S}),{label:un});x.style.width="auto",m.append(f,g,v,x),i.appendChild(m);};c("VAH","showVah","vahColor","vahStyle"),c("VAL","showVal","valColor","valStyle"),c("POC","showPoc","pocColor","pocStyle"),c("Developing POC","showDevelopingPoc","developingPocColor","developingPocStyle"),c("Developing VA","showDevelopingVa","developingVaColor","developingVaStyle"),this.el?.appendChild(i),this.levelsPanel=i,this.reposition();}toggleLevelsPanel(e,t){if(this.levelsPanel){this.levelsPanel.remove(),this.levelsPanel=null,this.reposition();return}let n=e.editableLevels();if(!n)return;let r=this.theme,i=e instanceof ye,o=document.createElement("div");if(o.className="vela-fiblevels",o.style.cssText=`padding:6px;border-top:1px solid var(--vela-border);max-height:260px;overflow-y:auto;display:flex;flex-direction:column;gap:3px;min-width:${i?200:248}px;`,i){let a=e,l=document.createElement("label");l.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 2px 8px;margin-bottom:2px;border-bottom:1px solid var(--vela-border);cursor:pointer;user-select:none;";let c=document.createElement("input");c.type="checkbox",c.checked=a.showRatios!==false,c.style.cssText=`accent-color:${r.textColor};width:15px;height:15px;flex:none;cursor:pointer;`,c.addEventListener("change",()=>t.patch({showRatios:c.checked}));let d=document.createElement("span");d.textContent="Show ratio labels",d.style.cssText="opacity:0.9;",l.append(c,d),o.appendChild(l);}n.forEach((a,l)=>{let c=document.createElement("div");c.style.cssText="display:flex;align-items:center;gap:8px;";let d=document.createElement("input");d.type="checkbox",d.checked=a.enabled,d.style.cssText=`accent-color:${a.color};width:15px;height:15px;flex:none;cursor:pointer;`,d.addEventListener("change",()=>t.patch({[`levels.${l}.enabled`]:d.checked}));let h=document.createElement("button");h.type="button",h.style.cssText=`width:18px;height:18px;flex:none;border:1px solid var(--vela-border);border-radius:0;cursor:pointer;background:${a.color};padding:0;`;let u=a.color;h.addEventListener("pointerdown",b=>b.stopPropagation()),h.addEventListener("click",b=>{b.stopPropagation(),this.toggleColorPopover(h,u,g=>{u=g,h.style.background=g,d.style.accentColor=g,t.patch({[`levels.${l}.color`]:g});});});let p=document.createElement("input");p.type="number",p.step="any",p.min="0";let m=a.ratio;p.value=String(m),p.title="Ratio",p.style.cssText=i?`width:88px;flex:1;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:5px 8px;font:13px ${r.fontFamily};font-variant-numeric:tabular-nums;outline:none;`:`width:52px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:3px 4px;font:12px ${r.fontFamily};font-variant-numeric:tabular-nums;outline:none;`;let f=()=>{let b=parseFloat(p.value);if(!Number.isFinite(b)||b<=0){p.value=String(m);return}m=b,t.patch({[`levels.${l}.ratio`]:b});};if(p.addEventListener("change",f),p.addEventListener("keydown",b=>{b.stopPropagation(),b.key==="Enter"&&(b.preventDefault(),f(),p.blur());}),c.append(d,h,p),!i){let b=document.createElement("input");b.type="text",b.placeholder="label\u2026",b.value=a.label??"",b.style.cssText=`flex:1;min-width:60px;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:3px 7px;font:12px ${r.fontFamily};outline:none;`,b.addEventListener("input",()=>t.patch({[`levels.${l}.label`]:b.value})),b.addEventListener("keydown",g=>g.stopPropagation()),c.appendChild(b);}o.appendChild(c);}),this.el?.appendChild(o),this.levelsPanel=o,this.reposition();}position(e){let t=this.el;if(!t)return;let n=this.host.getBoundingClientRect(),r=t.offsetWidth,i=t.offsetHeight,o=10,a=n.width/2-r/2,l=12;e&&(a=e.x+e.w/2-r/2,l=e.y-i-o,l<4&&(l=e.y+e.h+o)),t.style.left=`${Math.max(4,Math.min(a,n.width-r-4))}px`,t.style.top=`${Math.max(4,Math.min(l,n.height-i-4))}px`;}reposition(){let e=this.el;if(!e)return;let t=this.host.getBoundingClientRect(),n=e.offsetWidth,r=e.offsetHeight,i=parseFloat(e.style.left)||0,o=parseFloat(e.style.top)||0;e.style.left=`${Math.max(4,Math.min(i,t.width-n-4))}px`,e.style.top=`${Math.max(4,Math.min(o,t.height-r-4))}px`;}base(e){let t=document.createElement("button");return t.type="button",t.dataset.tip=e,t.className="vela-dpop-btn",t.style.cssText=`width:${Ze}px;height:${Ze}px;display:flex;align-items:center;justify-content:center;cursor:pointer;color:inherit;border:none;border-radius:5px;padding:0;`,t}iconBtn(e,t,n){let r=this.base(e);return r.innerHTML=qe(t),r.addEventListener("click",n),r}dragHandle(){let e=document.createElement("button");return e.type="button",e.className="vela-dpop-grip",e.style.cssText=`width:${Ze}px;height:${Ze}px;display:flex;align-items:center;justify-content:center;background:transparent;border:none;padding:0;cursor:grab;touch-action:none;color:var(--vela-fg-faint);`,e.innerHTML=qe(zf),e.addEventListener("pointerdown",t=>{let n=this.el;if(!n||t.button!==0)return;t.preventDefault(),t.stopPropagation(),this.hideTip(),this.closeColorPopover(),this.closeMenu();let r=this.host.getBoundingClientRect(),i=t.clientX,o=t.clientY,a=parseFloat(n.style.left)||0,l=parseFloat(n.style.top)||0;e.style.cursor="grabbing";try{e.setPointerCapture(t.pointerId);}catch{}let c=h=>{let u=n.offsetWidth,p=n.offsetHeight,m=a+(h.clientX-i),f=l+(h.clientY-o);n.style.left=`${Math.max(4,Math.min(m,r.width-u-4))}px`,n.style.top=`${Math.max(4,Math.min(f,r.height-p-4))}px`;},d=()=>{e.style.cursor="grab",window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",d);};window.addEventListener("pointermove",c),window.addEventListener("pointerup",d),window.addEventListener("pointercancel",d);}),e}kebabButton(e){let t=this.base("More");return t.innerHTML=qe($f),t.addEventListener("pointerdown",n=>n.stopPropagation()),t.addEventListener("click",n=>{if(n.stopPropagation(),this.menuOwner===t){this.closeMenu();return}this.openActionMenu(t,[{icon:_f,label:"Bring to front",onClick:()=>e.reorder("front")},{icon:Nf,label:"Send to back",onClick:()=>e.reorder("back")},{icon:Wf,label:"Reset settings",onClick:()=>e.resetSettings()}]);}),t}openActionMenu(e,t){this.closeMenu(),this.closeColorPopover();let n=this.theme,r=document.createElement("div");r.className="vela-dpop",r.style.cssText=`position:absolute;z-index:26;background:${n.background};border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);padding:4px;pointer-events:auto;display:flex;flex-direction:column;gap:1px;color:${n.textColor};font:var(--vela-font-size-md) ${n.fontFamily};`,ne(r,n),r.addEventListener("pointerdown",h=>h.stopPropagation());for(let h of t){let u=document.createElement("button");u.type="button",u.className="vela-dpop-item",u.style.cssText="display:flex;align-items:center;gap:9px;min-width:150px;padding:6px 9px;border:none;border-radius:5px;color:inherit;cursor:pointer;text-align:left;font:inherit;";let p=document.createElement("span");p.style.cssText="display:flex;flex:none;width:20px;justify-content:center;",p.innerHTML=qe(h.icon,18);let m=document.createElement("span");m.textContent=h.label,m.style.cssText="flex:1;",u.append(p,m),u.addEventListener("click",f=>{f.stopPropagation(),this.closeMenu(),h.onClick();}),r.appendChild(u);}this.host.appendChild(r);let i=e.getBoundingClientRect(),o=this.host.getBoundingClientRect(),a=r.offsetWidth,l=r.offsetHeight,c=i.right-o.left-a,d=i.bottom-o.top+6;c+a>o.width-4&&(c=o.width-a-4),c<4&&(c=4),d+l>o.height-4&&(d=i.top-o.top-l-6),d<4&&(d=4),r.style.left=`${Math.round(c)}px`,r.style.top=`${Math.round(d)}px`,this.menuEl=r,this.menuOwner=e;}showTip(e){let t=e.dataset.tip;if(!t){this.hideTip();return}let n=this.theme;if(!this.tipEl){let p=document.createElement("div");p.style.cssText=`position:absolute;z-index:27;pointer-events:none;white-space:nowrap;background:${n.textColor};color:${n.background};padding:3px 7px;border-radius:5px;font:var(--vela-font-size-sm) ${n.fontFamily};box-shadow:var(--vela-shadow);`,this.host.appendChild(p),this.tipEl=p;}let r=this.tipEl;r.textContent=t;let i=this.host.getBoundingClientRect(),o=e.getBoundingClientRect(),a=r.offsetWidth,l=r.offsetHeight,c=6,d=o.left-i.left+o.width/2-a/2;d=Math.max(4,Math.min(d,i.width-a-4));let h=o.top-i.top-l-c,u=h>=4?h:o.bottom-i.top+c;r.style.left=`${Math.round(d)}px`,r.style.top=`${Math.round(u)}px`;}hideTip(){this.tipEl?.remove(),this.tipEl=null;}toggle(e,t,n,r){let i=this.base(e);i.innerHTML=qe(t);let o=l=>{i.dataset.active=l?"1":"0";};o(n);let a=n;return i.addEventListener("click",()=>{a=!a,o(a),r(a);}),i}widthInput(e,t,n,r,i,o){let a=document.createElement("input");a.type="number",a.dataset.tip=e,a.min=String(n),a.max=String(r),a.step=String(i),a.value=String(t),a.style.cssText=`width:52px;height:${Ze}px;box-sizing:border-box;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:0 4px;font:12px ${this.theme.fontFamily};font-variant-numeric:tabular-nums;outline:none;`;let l=()=>{let c=parseFloat(a.value);if(!Number.isFinite(c)){a.value=String(t);return}let d=Math.min(r,Math.max(n,c));a.value=String(d),t=d,o(d);};return a.addEventListener("change",l),a.addEventListener("keydown",c=>{c.stopPropagation(),c.key==="Enter"&&(c.preventDefault(),l(),a.blur());}),a}dropdown(e,t,n,r,i,o={}){let a=this.base(e);a.style.width="auto",a.style.minWidth=`${Ze}px`,a.style.padding="0 4px",a.style.gap="2px";let l=n,c=d=>{a.replaceChildren();let h=document.createElement("span");if(h.style.cssText="display:flex;",h.innerHTML=qe(r(d)),a.appendChild(h),o.label&&o.labelInTrigger){let p=document.createElement("span");p.textContent=o.label(d),p.style.cssText="font-size:11px;opacity:0.85;font-variant-numeric:tabular-nums;",a.appendChild(p);}let u=document.createElement("span");u.style.cssText="display:flex;opacity:0.55;",u.innerHTML=qe(Uf,12),a.appendChild(u);};return c(l),a.addEventListener("pointerdown",d=>d.stopPropagation()),a.addEventListener("click",d=>{if(d.stopPropagation(),this.menuOwner===a){this.closeMenu();return}this.openMenu(a,t,l,r,o.label,h=>{l=h,c(h),i(h);});}),a}openMenu(e,t,n,r,i,o){this.closeMenu(),this.closeColorPopover();let a=this.theme,l=document.createElement("div");l.className="vela-dpop",l.style.cssText=`position:absolute;z-index:26;background:${a.background};border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);padding:4px;pointer-events:auto;display:flex;flex-direction:column;gap:1px;color:${a.textColor};font:var(--vela-font-size-md) ${a.fontFamily};`,ne(l,a),l.addEventListener("pointerdown",f=>f.stopPropagation());for(let f of t){let b=f===n,g=document.createElement("button");g.type="button",g.className="vela-dpop-item",g.dataset.active=b?"1":"0",g.style.cssText=`display:flex;align-items:center;gap:8px;${i?"min-width:118px;":""}padding:5px 8px;border:none;border-radius:5px;color:inherit;cursor:pointer;text-align:left;font:inherit;`;let v=document.createElement("span");if(v.style.cssText="display:flex;flex:none;width:22px;justify-content:center;",v.innerHTML=qe(r(f),18),g.appendChild(v),i){let y=document.createElement("span");y.textContent=i(f),y.style.cssText="flex:1;font-variant-numeric:tabular-nums;",g.appendChild(y);}g.addEventListener("click",y=>{y.stopPropagation(),this.closeMenu(),o(f);}),l.appendChild(g);}this.host.appendChild(l);let c=e.getBoundingClientRect(),d=this.host.getBoundingClientRect(),h=l.offsetWidth,u=l.offsetHeight,p=c.left-d.left,m=c.bottom-d.top+6;p+h>d.width-4&&(p=d.width-h-4),p<4&&(p=4),m+u>d.height-4&&(m=c.top-d.top-u-6),m<4&&(m=4),l.style.left=`${Math.round(p)}px`,l.style.top=`${Math.round(m)}px`,this.menuEl=l,this.menuOwner=e;}closeMenu(){this.menuEl&&(this.menuEl.remove(),this.menuEl=null),this.menuOwner=null;}colorButton(e,t,n,r,i=17){let o=document.createElement("button");o.type="button",o.dataset.tip=e,o.className="vela-dpop-btn",o.style.cssText=`position:relative;width:${Ze}px;height:${Ze}px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;cursor:pointer;border-radius:5px;border:none;color:inherit;padding:0;`;let a=document.createElement("span");a.style.cssText="display:flex;",a.innerHTML=qe(t,i);let l=document.createElement("span");l.style.cssText=`display:block;height:3px;width:${Math.round(i*.85)}px;border-radius:2px;background:${n};`,o.append(a,l);let c=n;return o.addEventListener("pointerdown",d=>d.stopPropagation()),o.addEventListener("click",d=>{d.stopPropagation(),this.toggleColorPopover(o,c,h=>{c=h,l.style.background=h,r(h);});}),o}toggleColorPopover(e,t,n){if(this.colorOwner===e){this.closeColorPopover();return}this.openColorPopover(e,t,n);}openColorPopover(e,t,n){this.closeColorPopover(),this.closeMenu();let r=this.theme,i=document.createElement("div");i.style.cssText=`position:absolute;z-index:25;background:${r.background};border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);padding:10px;pointer-events:auto;`,ne(i,r),i.addEventListener("pointerdown",u=>u.stopPropagation()),i.appendChild(Jn(t,r,n)),this.host.appendChild(i);let o=e.getBoundingClientRect(),a=this.host.getBoundingClientRect(),l=i.offsetWidth,c=i.offsetHeight,d=o.left-a.left,h=o.bottom-a.top+6;d+l>a.width-4&&(d=a.width-l-4),d<4&&(d=4),h+c>a.height-4&&(h=o.top-a.top-c-6),h<4&&(h=4),i.style.left=`${Math.round(d)}px`,i.style.top=`${Math.round(h)}px`,this.colorPop=i,this.colorOwner=e;}closeColorPopover(){this.colorPop&&(this.colorPop.remove(),this.colorPop=null),this.colorOwner=null;}divider(){let e=document.createElement("div");return e.style.cssText="width:1px;height:18px;margin:0 3px;background:var(--vela-border);",e}},Bt=$("brush"),hn=$("bucket"),Ss=$("type"),Ff=$("price-delta"),Bf=$("date-delta"),Vf=$("lock"),_f=$("bring-front"),Nf=$("send-back"),Hf=$("trash"),Vc=$("bold"),_c=$("italic"),zf=$("grip"),$f=$("kebab"),Wf=$("reset"),Cs=$("gear"),Uf=$("chevron-down"),Gf=$("r-squared"),Yf=$("bands"),Xf=$("dedekind"),Kf=$("sonic"),jf=$("supersonic");function Vt(s,e){let t=e==="dashed"?"5,3":e==="dotted"?"1.5,3":"";return I(`<line x1="3.5" y1="12" x2="20.5" y2="12" stroke-width="${Number(s)||2}" stroke-dasharray="${t}"/>`)}var qf=4;function Nc(s){s.style.height="auto";let e=18*qf+10+2;s.style.height=`${Math.min(s.scrollHeight,e)}px`,s.style.overflowY=s.scrollHeight>e?"auto":"hidden";}function nr(s,e,t=17,n=""){return Ao(`<text x="12" y="${t}" font-size="${e}" text-anchor="middle"${n?" "+n:""}>${s}</text>`)}function Zf(s){return nr(String(s),15)}function Jf(s){return nr("\u25CF",(Ts[String(s)]??13)+4)}function Qf(s){return nr(String(s).charAt(0).toUpperCase(),15)}var Ts={small:10,normal:13,large:16,huge:20};function eb(s){return nr("12",(Ts[String(s)]??13)-1,16.5,'font-weight="600"')}function Hc(s){return nr("T",(Ts[String(s)]??13)+2)}function zc(s){return s.charAt(0).toUpperCase()+s.slice(1)}function tr(s){return Te.find(e=>e.value===s)?.label??zc(String(s))}function un(s){return me.find(e=>e.value===s)?.label??zc(String(s))}function qe(s,e=Af){return s.replace("<svg ",`<svg width="${e}" height="${e}" `)}var Ms=44,Ls=16,rr=class{constructor(e,t,n,r=()=>{},i=()=>{},o=()=>{},a=()=>{},l=()=>{},c={}){this.host=e;this.theme=t;this.onArm=n;this.onMagnet=r;this.onMeasure=i;this.onEraser=o;this.onToggleFavorite=a;this.onStayMode=l;this.def={groups:[]};this.active=null;this.lastUsed=new Map;this.favorites=new Set;this.shortcuts=new Map;this.starEls=new Map;this.flyout=null;this.flyoutOwnerId=null;this.flyoutCell=null;this.groupCells=new Map;this.groupIcons=new Map;this.cursorBtn=null;this.magnetCell=null;this.magnetIcon=null;this.magnetMode="off";this.lastMagnetOn="weak";this.measureBtn=null;this.measureActive=false;this.eraserBtn=null;this.eraserActive=false;this.stayBtn=null;this.stayActive=false;this.syncBtn=null;this.syncActive=false;this.collapseBtn=null;this.collapsed=false;this.visible=false;this.tipText=new WeakMap;this.tipDisposers=[];this.onOutside=e=>{let t=e.target;this.flyout&&!this.flyout.contains(t)&&!this.root.contains(t)&&this.closeFlyout();};this.borderOverride=c.borderColor??null,this.width=c.width??Ms,this.dock=c.dock??"absolute",this.onCollapse=c.onCollapse??(()=>{}),this.onDrawingsSync=c.onDrawingsSync??null,tb(),this.root=document.createElement("div"),this.root.className="vela-dtb",this.styleRoot(),e.appendChild(this.root);}get borderColor(){return this.borderOverride??this.theme.borderColor}styleRoot(){let e=this.theme;ne(this.root,e);let t=this.collapsed?Ls:this.width;this.root.dataset.collapsed=this.collapsed?"1":"";let n=this.dock==="absolute"?`position:absolute;left:0;top:0;height:100%;width:${t}px;z-index:21;`:`position:relative;height:100%;width:${t}px;flex:none;`;this.root.style.cssText=n+`display:${this.visible?"flex":"none"};flex-direction:column;gap:4px;padding:6px 0;box-sizing:border-box;background:${e.background};border-right:1px solid ${this.borderColor};color:var(--vela-fg-muted);pointer-events:auto;overflow-y:auto;overflow-x:hidden;`;}setDefinition(e){this.def=e;for(let t of e.groups){let n=t.tools[0];n&&!this.lastUsed.has(t.id)&&this.lastUsed.set(t.id,n.type);}this.rebuild();}setFavorites(e){this.favorites=new Set(e);for(let[t,n]of this.starEls)this.paintStar(n,t);}setShortcuts(e){this.shortcuts=new Map(Object.entries(e));}paintStar(e,t){let n=this.favorites.has(t);e.classList.toggle("vela-fav",n),e.setAttribute("aria-label",n?"Remove from favorites":"Add to favorites"),e.setAttribute("aria-pressed",n?"true":"false"),e.innerHTML=mo(n?ub:hb);}setVisible(e){this.visible=e,this.root.style.display=e?"flex":"none";}setActiveTool(e){if(this.active=e,e){let t=this.def.groups.find(n=>n.tools.some(r=>r.type===e));t&&(this.lastUsed.set(t.id,e),this.paintGroupIcon(t));}this.closeFlyout(),this.highlight();}setTheme(e){this.theme=e,this.styleRoot(),this.rebuild();}destroy(){this.closeFlyout();for(let e of this.tipDisposers.splice(0))e();this.root.remove();}rebuild(){for(let e of this.tipDisposers.splice(0))e();this.root.replaceChildren(),this.groupCells.clear(),this.groupIcons.clear(),this.cursorBtn=this.makeButton(nb,"Cursor",()=>this.onArm(null)),this.root.appendChild(this.cursorBtn),this.def.groups.length>0&&this.root.appendChild(this.divider());for(let e of this.def.groups){let t=this.makeGroupCell(e);this.root.appendChild(t),this.paintGroupIcon(e);}this.root.appendChild(this.divider()),this.measureBtn=this.makeButton(rb,"Measure",()=>this.onMeasure()),this.root.appendChild(this.measureBtn),this.eraserBtn=this.makeButton(lb,"Eraser (click/drag to delete)",()=>this.onEraser()),this.root.appendChild(this.eraserBtn),this.root.appendChild(this.makeMagnetCell()),this.stayBtn=this.makeButton(sb,"Stay in drawing mode",()=>this.toggleStay()),this.root.appendChild(this.stayBtn),this.onDrawingsSync&&(this.syncBtn=this.makeButton(ab,"Sync drawings on all charts",()=>this.toggleDrawingsSync()),this.root.appendChild(this.syncBtn)),this.collapseBtn=this.makeButton(Uc,"Collapse toolbar",()=>this.toggleCollapsed()),this.collapseBtn.classList.add("vela-dtb-collapse"),this.root.appendChild(this.collapseBtn),this.paintMeasure(),this.paintEraser(),this.paintMagnet(),this.paintStay(),this.paintDrawingsSync(),this.paintCollapse(),this.highlight();}toggleCollapsed(){this.collapsed=!this.collapsed,this.closeFlyout(),this.styleRoot(),this.paintCollapse(),this.onCollapse(this.collapsed);}paintCollapse(){let e=this.collapseBtn;if(!e)return;let t=this.collapsed?"Expand toolbar":"Collapse toolbar";e.innerHTML=po(this.collapsed?ib:Uc,12),e.setAttribute("aria-label",t),this.tipText.set(e,t);}makeCell(e,t){let n=document.createElement("div");n.className="vela-dtb-cell";let r=document.createElement("button");r.type="button",r.className="vela-dtb-icon",r.setAttribute("aria-label",e),t.iconSvg&&(r.innerHTML=po(t.iconSvg)),r.addEventListener("click",t.onIcon),n.appendChild(r);let i=null;if(t.multi&&t.onArrow){let o=t.onArrow;i=document.createElement("button"),i.type="button",i.className="vela-dtb-arrow",i.setAttribute("aria-label",`${e} \u2014 more`),i.innerHTML=pb(cb),i.addEventListener("click",a=>{a.stopPropagation(),o();}),n.appendChild(i);}return this.tipDisposers.push(Et(n,{host:this.host,theme:()=>this.theme,text:()=>this.tipText.get(n)??e,placement:"right"})),{cell:n,icon:r,arrow:i}}makeGroupCell(e){let t=e.tools.length>1,{cell:n,icon:r}=this.makeCell(e.label,{multi:t,onIcon:()=>this.onGroupIconClick(e),onArrow:t?()=>this.onArrowClick(e):void 0});return this.groupCells.set(e.id,n),this.groupIcons.set(e.id,r),n}makeMagnetCell(){let{cell:e,icon:t}=this.makeCell("Magnet snap",{iconSvg:ob,multi:true,onIcon:()=>this.toggleMagnet(),onArrow:()=>this.onMagnetArrowClick()});return this.magnetCell=e,this.magnetIcon=t,e}onGroupIconClick(e){let t=this.lastUsed.get(e.id)??e.tools[0]?.type;t&&this.onArm(t);}onArrowClick(e){let t=this.flyoutOwnerId===e.id;this.closeFlyout(),t||this.openGroupFlyout(e);}toggleMagnet(){this.applyMagnet(this.magnetMode==="off"?this.lastMagnetOn:"off");}onMagnetArrowClick(){let e=this.flyoutOwnerId===$c;this.closeFlyout(),e||this.openMagnetFlyout();}applyMagnet(e){this.magnetMode=e,e!=="off"&&(this.lastMagnetOn=e),this.onMagnet(e),this.paintMagnet(),this.highlight();}setMagnetMode(e){this.magnetMode=e,e!=="off"&&(this.lastMagnetOn=e),this.paintMagnet(),this.highlight();}setMeasureActive(e){this.measureActive=e,this.paintMeasure(),this.highlight();}paintMeasure(){let e=this.measureBtn;e&&(e.dataset.active=this.measureActive?"1":"");}setEraserActive(e){this.eraserActive=e,this.paintEraser(),this.highlight();}paintEraser(){let e=this.eraserBtn;e&&(e.dataset.active=this.eraserActive?"1":"");}paintMagnet(){let e=this.magnetCell,t=this.magnetIcon;if(!e||!t)return;let n=this.magnetMode==="off"?"Off":this.magnetMode==="weak"?"Weak":"Strong";this.tipText.set(e,`Magnet snap: ${n}`);let r=this.magnetMode!=="off";e.dataset.active=r?"1":"",t.style.opacity=r?"1":"0.5";}toggleStay(){this.stayActive=!this.stayActive,this.onStayMode(this.stayActive),this.paintStay();}setStayMode(e){this.stayActive=e,this.paintStay();}paintStay(){let e=this.stayBtn;e&&(e.dataset.active=this.stayActive?"1":"",e.style.opacity=this.stayActive?"1":"0.5");}toggleDrawingsSync(){this.syncActive=!this.syncActive,this.onDrawingsSync?.(this.syncActive),this.paintDrawingsSync();}setDrawingsSyncMode(e){this.syncActive=e,this.paintDrawingsSync();}paintDrawingsSync(){let e=this.syncBtn;e&&(e.dataset.active=this.syncActive?"1":"",e.style.opacity=this.syncActive?"1":"0.5");}beginFlyout(e,t){let n=this.theme,r=document.createElement("div");r.className="vela-dtb-flyout",r.style.cssText=`position:absolute;z-index:23;display:flex;flex-direction:column;gap:2px;padding:4px;border-radius:0 8px 8px 0;background:var(--vela-surface-elev);border:1px solid ${this.borderColor};border-left:none;box-shadow:var(--vela-shadow);pointer-events:auto;overflow-y:auto;overscroll-behavior:contain;`,ne(r,n),this.host.appendChild(r);let i=t.getBoundingClientRect(),o=this.root.getBoundingClientRect(),a=this.host.getBoundingClientRect(),l=i.top-a.top;return r.style.left=`${o.right-a.left-1}px`,r.style.top=`${l}px`,r.style.maxHeight=`${Math.max(120,a.height-l-8)}px`,this.flyout=r,this.flyoutOwnerId=e,this.flyoutCell=t,t.classList.add("vela-open"),this.highlight(),document.addEventListener("pointerdown",this.onOutside),r}openGroupFlyout(e){let t=this.groupCells.get(e.id);if(!t)return;let n=this.beginFlyout(e.id,t),r=e.sections??[{label:"",tools:e.tools}];for(let i=0;i<r.length;i++){let o=r[i];o.label&&(i>0&&n.appendChild(this.flyoutSeparator()),n.appendChild(this.flyoutHeader(o.label)));for(let a of o.tools)n.appendChild(this.makeFlyoutItem({icon:a.icon,label:a.label,selected:a.type===this.active,shortcut:this.shortcuts.get(a.type),onSelect:()=>this.onArm(a.type),favorite:{type:a.type,toggle:()=>this.onToggleFavorite(a.type,!this.favorites.has(a.type))}}));}}openMagnetFlyout(){let e=this.magnetCell;if(!e)return;let t=this.beginFlyout($c,e);t.appendChild(this.flyoutHeader("Magnet"));let n=[["off","Off"],["weak","Weak"],["strong","Strong"]];for(let[r,i]of n)t.appendChild(this.makeFlyoutItem({label:i,selected:r===this.magnetMode,onSelect:()=>{this.applyMagnet(r),this.closeFlyout();}}));}flyoutHeader(e){let t=this.theme,n=document.createElement("div");return n.textContent=e.toUpperCase(),n.style.cssText=`padding:6px 12px 2px 8px;font:var(--vela-font-size-sm) ${t.fontFamily};font-weight:600;letter-spacing:0.04em;color:var(--vela-fg-muted);user-select:none;`,n}flyoutSeparator(){let e=document.createElement("div");return e.style.cssText=`height:1px;margin:4px 8px;background:${this.borderColor};`,e}makeFlyoutItem(e){let t=this.theme,n=document.createElement("button");if(n.type="button",n.className="vela-dtb-item",n.setAttribute("aria-label",e.label),n.style.cssText=`display:flex;align-items:center;gap:8px;padding:5px 10px 5px 8px;cursor:pointer;color:${t.textColor};border-radius:var(--vela-radius-sm);font:13px ${t.fontFamily};white-space:nowrap;min-width:148px;`,e.icon){let o=document.createElement("span");o.style.cssText="width:18px;height:18px;display:flex;align-items:center;justify-content:center;flex:none;",o.innerHTML=mo(e.icon),n.appendChild(o);}let r=document.createElement("span");r.textContent=e.label,r.style.cssText="flex:1 1 auto;text-align:left;",n.appendChild(r);let i=document.createElement("span");if(i.style.cssText="width:14px;height:14px;display:flex;align-items:center;justify-content:center;flex:none;",e.selected&&(i.innerHTML=mo(db)),n.appendChild(i),e.shortcut){let o=document.createElement("span");o.className="vela-dtb-hint",o.textContent=e.shortcut,o.style.cssText=`flex:none;font:var(--vela-font-size-md) ${t.fontFamily};color:var(--vela-fg-muted);`,n.appendChild(o);}if(e.favorite){let o=document.createElement("span");o.className="vela-dtb-star",o.setAttribute("role","button"),this.paintStar(o,e.favorite.type),this.starEls.set(e.favorite.type,o);for(let a of ["pointerdown","pointerup","mousedown","mouseup"])o.addEventListener(a,l=>l.stopPropagation());o.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),e.favorite.toggle();}),n.appendChild(o);}return n.addEventListener("click",o=>{o.stopPropagation(),e.onSelect();}),n}closeFlyout(){this.starEls.clear(),this.flyout&&(this.flyout.remove(),this.flyout=null,this.flyoutCell?.classList.remove("vela-open"),this.flyoutCell=null,this.flyoutOwnerId=null,document.removeEventListener("pointerdown",this.onOutside),this.highlight());}paintGroupIcon(e){let t=this.groupIcons.get(e.id);if(!t)return;let n=this.lastUsed.get(e.id)??e.tools[0]?.type,r=e.tools.find(o=>o.type===n)??e.tools[0];t.innerHTML=po(r?.icon??"");let i=this.groupCells.get(e.id);i&&this.tipText.set(i,r?.label??e.label);}highlight(){let e=this.active?this.def.groups.find(t=>t.tools.some(n=>n.type===this.active)):null;for(let[t,n]of this.groupCells){let r=t===e?.id;n.dataset.active=r?"1":"";}this.cursorBtn&&(this.cursorBtn.dataset.active=this.active==null&&!this.measureActive&&!this.eraserActive?"1":""),this.paintMeasure(),this.paintEraser(),this.paintMagnet(),this.paintStay();}makeButton(e,t,n){let r=document.createElement("button");return r.type="button",r.className="vela-dtb-btn",r.setAttribute("aria-label",t),this.tipText.set(r,t),e&&(r.innerHTML=po(e)),this.tipDisposers.push(Et(r,{host:this.host,theme:()=>this.theme,text:()=>this.tipText.get(r)??t,placement:"right"})),r.addEventListener("click",n),r}divider(){let e=document.createElement("div");return e.style.cssText=`width:24px;height:1px;margin:2px auto;flex:none;background:${this.borderColor};`,e}},$c="__magnet__",Wc="vela-drawing-toolbar-styles";function tb(){if(typeof document>"u")return;let s=document.getElementById(Wc);s||(s=document.createElement("style"),s.id=Wc,document.head.appendChild(s)),s.textContent=`
210
+ @media (pointer: coarse){.vela-dpop-grip{width:${Ze+14}px !important;}}`,document.head.appendChild(s);}var po=class{constructor(e,t){this.host=e;this.el=null;this.tipEl=null;this.textPanel=null;this.levelsPanel=null;this.colorPop=null;this.colorOwner=null;this.menuEl=null;this.menuOwner=null;this.onClose=null;this.onOutside=e=>{let t=e.target;if(!this.colorPop?.contains(t)&&!this.menuEl?.contains(t)&&this.el&&!this.el.contains(t)){let n=this.onClose;this.close(),n?.();}};this.theme=t;}setTheme(e){this.theme=e;}isOpen(){return this.el!=null}contains(e){return e?this.el?.contains(e)===true||this.colorPop?.contains(e)===true||this.menuEl?.contains(e)===true:false}open(e,t,n,r){this.close(),Bf(),this.onClose=r??null;let i=this.theme,o=e.schema(),a=new Set(o.fields.map(v=>v.path)),l=o.textIsContent===true||!a.has("text.value"),c=document.createElement("div");c.className="vela-dpop",c.style.cssText=`position:absolute;z-index:22;background:${i.background};border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);color:${i.textColor};font:var(--vela-font-size-md) ${i.fontFamily};display:flex;flex-direction:column;pointer-events:auto;overflow:hidden;`,ne(c,i),c.addEventListener("pointerdown",()=>{this.closeColorPopover(),this.closeMenu();});let d=document.createElement("div");if(d.style.cssText="display:flex;align-items:center;gap:2px;padding:4px;",d.appendChild(this.dragHandle()),a.has("glyph")){let v=e.glyph??Cn[0];d.appendChild(this.dropdown("Icon",Cn,v,y=>Qf(y),y=>n.patch({glyph:y})));}if(a.has("size")){let v=e.size??"normal";d.appendChild(this.dropdown("Icon size",Kr,v,y=>eb(y),y=>n.patch({size:y}),{label:tr}));}if(a.has("style.lineColor")&&d.appendChild(this.colorButton("Line color",Bt,e.style.lineColor||R,v=>n.patch({"style.lineColor":v}))),a.has("style.lineWidth")){let v=o.fields.find(y=>y.path==="style.lineWidth");v?.kind==="number"&&(v.min??1)>1?d.appendChild(this.widthInput("Line width",e.style.lineWidth,v.min??1,v.max??60,v.step??1,y=>n.patch({"style.lineWidth":y}))):d.appendChild(this.dropdown("Line width",[1,2,3,4],e.style.lineWidth,y=>Vt(y,"solid"),y=>n.patch({"style.lineWidth":y}),{label:y=>`${y}px`,labelInTrigger:true}));}a.has("style.lineStyle")&&d.appendChild(this.dropdown("Line style",fe.map(v=>v.value),e.style.lineStyle,v=>Vt(2,v),v=>n.patch({"style.lineStyle":v}),{label:un})),a.has("style.fillColor")&&d.appendChild(this.colorButton("Fill",hn,Ce(e,this.theme)??e.style.fillColor??R,v=>n.patch({"style.fillColor":v})));let h=a.has("frvp.rows")&&e instanceof Re,u=a.has("riskPercent")&&e instanceof Oe;if(u){let v=e;d.appendChild(this.colorButton("Profit zone",hn,v.profitColor,y=>n.patch({profitColor:y}))),d.appendChild(this.colorButton("Loss zone",hn,v.lossColor,y=>n.patch({lossColor:y})));}let p=e.reg;if(a.has("reg.midColor")&&p){let v=fe.map(y=>y.value);d.appendChild(this.colorButton("Midline color",Bt,p.midColor,y=>n.patch({"reg.midColor":y}))),d.appendChild(this.dropdown("Midline style",v,p.midStyle,y=>Vt(2,y),y=>n.patch({"reg.midStyle":y}),{label:un})),d.appendChild(this.colorButton("Upper line color",Bt,p.upperColor,y=>n.patch({"reg.upperColor":y}))),d.appendChild(this.dropdown("Upper line style",v,p.upperStyle,y=>Vt(2,y),y=>n.patch({"reg.upperStyle":y}),{label:un})),d.appendChild(this.colorButton("Lower line color",Bt,p.lowerColor,y=>n.patch({"reg.lowerColor":y}))),d.appendChild(this.dropdown("Lower line style",v,p.lowerStyle,y=>Vt(2,y),y=>n.patch({"reg.lowerStyle":y}),{label:un})),d.appendChild(this.colorButton("Upper fill",hn,p.upperFill,y=>n.patch({"reg.upperFill":y}))),d.appendChild(this.colorButton("Lower fill",hn,p.lowerFill,y=>n.patch({"reg.lowerFill":y}))),d.appendChild(this.toggle("Show R\xB2",Xf,p.showR2,y=>n.patch({"reg.showR2":y})));}let m=e.vwap;if(a.has("vwap.midColor")&&m){let v=fe.map(x=>x.value),y=[.5,1,1.5,2,2.5,3,4,5];d.appendChild(this.colorButton("VWAP color",Bt,m.midColor,x=>n.patch({"vwap.midColor":x}))),d.appendChild(this.dropdown("VWAP style",v,m.midStyle,x=>Vt(2,x),x=>n.patch({"vwap.midStyle":x}),{label:un})),d.appendChild(this.dropdown("Band multiplier",y,m.multiplier,()=>Kf,x=>n.patch({"vwap.multiplier":x}),{label:x=>`${x}\u03C3`,labelInTrigger:true})),d.appendChild(this.colorButton("Upper band color",Bt,m.upperColor,x=>n.patch({"vwap.upperColor":x}))),d.appendChild(this.colorButton("Lower band color",Bt,m.lowerColor,x=>n.patch({"vwap.lowerColor":x}))),d.appendChild(this.colorButton("Band fill",hn,m.bandFill,x=>n.patch({"vwap.bandFill":x})));}if(a.has("maxCurvature")){let v=e.maxCurvature??24;d.appendChild(this.dropdown("Max curvature",_o,v,()=>jf,y=>n.patch({maxCurvature:y}),{label:y=>`n=${y}`,labelInTrigger:true}));}if(a.has("mach")){let v=e.mach??2;d.appendChild(this.dropdown("Mach number",Ho,v,()=>Zf,y=>n.patch({mach:y}),{label:y=>`M=${y}`,labelInTrigger:true}));}if(a.has("waveCount")){let v=e.waveCount??6;d.appendChild(this.dropdown("Waves",No,v,()=>qf,y=>n.patch({waveCount:y}),{label:y=>`${y}`,labelInTrigger:true}));}let f=e;a.has("showPrice")&&d.appendChild(this.toggle("Show price",Vf,f.showPrice!==false,v=>n.patch({showPrice:v}))),a.has("showDate")&&d.appendChild(this.toggle("Show date",_f,f.showDate!==false,v=>n.patch({showDate:v}))),a.has("text.color")&&l&&d.appendChild(this.colorButton("Text color",Ss,e.text?.color||i.textColor,v=>n.patch({"text.color":v}))),a.has("text.size")&&l&&d.appendChild(this.dropdown("Text size",Te.map(v=>v.value),e.text?.size??"normal",v=>zc(v),v=>n.patch({"text.size":v}),{label:tr})),a.has("text.bold")&&!a.has("text.value")&&d.appendChild(this.toggle("Bold",_c,!!e.text?.bold,v=>n.patch({"text.bold":v}))),a.has("text.italic")&&!a.has("text.value")&&d.appendChild(this.toggle("Italic",Nc,!!e.text?.italic,v=>n.patch({"text.italic":v}))),a.has("text.value")&&d.appendChild(this.iconBtn("Text",Ss,()=>this.toggleTextPanel(e,n,!l)));let b=e.editableLevels();if(b&&!(e instanceof ye)){let v=e,y=Te.map(x=>x.value);d.appendChild(this.dropdown("Numbers size",y,v.numbersSize??"small",x=>nb(x),x=>n.patch({numbersSize:x}),{label:tr})),d.appendChild(this.dropdown("Label size",y,v.labelsSize??"normal",x=>zc(x),x=>n.patch({labelsSize:x}),{label:tr}));}d.appendChild(this.divider()),h&&d.appendChild(this.iconBtn("Settings",Cs,()=>this.toggleFrvpPanel(e,n))),u&&d.appendChild(this.iconBtn("Position size",Cs,()=>this.togglePositionPanel(e,n))),b&&d.appendChild(this.iconBtn("Levels",Cs,()=>this.toggleLevelsPanel(e,n))),d.appendChild(this.toggle("Lock",Nf,e.locked,v=>n.setLocked(v)));let g=this.iconBtn("Delete",$f,()=>n.remove());g.style.color="var(--vela-danger)",d.appendChild(g),d.appendChild(this.kebabButton(n)),c.append(d),this.host.appendChild(c),this.el=c,c.addEventListener("mouseover",v=>{let y=v.target.closest("[data-tip]");y?this.showTip(y):this.hideTip();}),c.addEventListener("mouseleave",()=>this.hideTip()),this.position(t),setTimeout(()=>document.addEventListener("pointerdown",this.onOutside),0);}close(){document.removeEventListener("pointerdown",this.onOutside),this.closeColorPopover(),this.closeMenu(),this.hideTip(),this.el?.remove(),this.el=null,this.textPanel=null,this.levelsPanel=null,this.onClose=null;}destroy(){this.close();}toggleTextPanel(e,t,n){if(this.textPanel){this.textPanel.remove(),this.textPanel=null,this.reposition();return}let r=this.theme,i=e.text,o=document.createElement("div");o.style.cssText="padding:6px;border-top:1px solid var(--vela-border);display:flex;flex-direction:column;gap:4px;";let a=document.createElement("textarea");a.placeholder="Label\u2026",a.value=i?.value??"",a.rows=1,a.style.cssText=`display:block;width:100%;box-sizing:border-box;min-width:220px;min-height:46px;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:6px;padding:6px 9px;font:13px/18px ${r.fontFamily};resize:none;overflow-y:hidden;`,a.addEventListener("input",()=>{t.patch({"text.value":a.value}),Hc(a),this.reposition();}),a.addEventListener("keydown",c=>{if(c.stopPropagation(),c.key==="Escape"){c.preventDefault();let d=this.onClose;this.close(),d?.();}});let l=document.createElement("div");l.style.cssText="display:flex;align-items:center;justify-content:flex-start;gap:0;transform:scale(0.8);transform-origin:left center;",n&&l.append(this.colorButton("Text color",Ss,i?.color||this.theme.textColor,c=>t.patch({"text.color":c}),14),this.dropdown("Text size",Te.map(c=>c.value),i?.size??"normal",c=>tb(c),c=>t.patch({"text.size":c}),{label:tr})),l.append(this.toggle("Bold",_c,!!i?.bold,c=>t.patch({"text.bold":c})),this.toggle("Italic",Nc,!!i?.italic,c=>t.patch({"text.italic":c}))),o.append(a,l),this.el?.appendChild(o),this.textPanel=o,Hc(a),this.reposition(),a.focus();}togglePositionPanel(e,t){if(this.levelsPanel){this.levelsPanel.remove(),this.levelsPanel=null,this.reposition();return}let n=this.theme,r=document.createElement("div");r.style.cssText="padding:8px 10px;border-top:1px solid var(--vela-border);display:flex;flex-direction:column;gap:6px;min-width:280px;";let i=()=>{let y=t.resolve();return y instanceof Oe?y:e},o=[],a=()=>o.forEach(y=>y()),l=y=>String(Math.round(y*1e8)/1e8),c=()=>{let y=document.createElement("input");return y.type="number",y.style.cssText=`width:96px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:4px 6px;font:12px ${n.fontFamily};font-variant-numeric:tabular-nums;outline:none;`,y},d=y=>{let x=document.createElement("div");x.style.cssText="display:flex;align-items:center;gap:10px;";let S=document.createElement("span");return S.textContent=y,S.style.cssText="flex:1;opacity:0.9;",x.appendChild(S),r.appendChild(x),x},h=(y,x)=>{y.addEventListener("change",x),y.addEventListener("keydown",S=>{S.stopPropagation(),S.key==="Enter"&&(S.preventDefault(),x(),y.blur());});},u=(y,x,S)=>{let C=d(y),T=c();S?(T.min=String(S.min),T.max=String(S.max),T.step=String(S.step)):T.step="any",T.value=l(i()[x]),h(T,()=>{let E=parseFloat(T.value);if(!Number.isFinite(E)){T.value=l(i()[x]);return}let k=S?Math.min(S.max,Math.max(S.min,E)):E;t.patch({[x]:k}),a();}),o.push(()=>{document.activeElement!==T&&(T.value=l(i()[x]));}),C.appendChild(T);},p=()=>{let y=document.createElement("select");return y.style.cssText=`width:76px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:4px 4px;font:12px ${n.fontFamily};outline:none;cursor:pointer;`,y.addEventListener("keydown",x=>x.stopPropagation()),y},m=(y,x,S)=>{let C="price",T=d(y),M=c();M.step="any",M.style.width="84px";let E=()=>l(i().levelDisplayValue(S,C));M.value=E(),h(M,()=>{let P=parseFloat(M.value);if(!Number.isFinite(P)){M.value=E();return}t.patch({[x]:i().levelPriceFromDisplay(S,C,P)}),a();});let L=p();for(let P of [{value:"price",label:"Price"},{value:"points",label:"Points"}]){let V=document.createElement("option");V.value=P.value,V.textContent=P.label,L.appendChild(V);}L.addEventListener("change",()=>{C=L.value,M.value=E();}),o.push(()=>{document.activeElement!==M&&(M.value=E());}),T.append(M,L);},f=()=>{let y=d("Direction"),x=p();x.style.width="96px";for(let S of Ti){let C=document.createElement("option");C.value=S.value,C.textContent=S.label,x.appendChild(C);}x.value=i().direction,x.addEventListener("change",()=>{t.patch({direction:x.value}),a();}),o.push(()=>{x.value=i().direction;}),y.appendChild(x);},b=(y,x)=>{let S=document.createElement("label");S.style.cssText="display:flex;align-items:center;gap:8px;cursor:pointer;user-select:none;";let C=document.createElement("input");C.type="checkbox",C.checked=i()[x],C.style.cssText=`accent-color:${n.textColor};width:15px;height:15px;flex:none;cursor:pointer;`,C.addEventListener("change",()=>{t.patch({[x]:C.checked}),a();});let T=document.createElement("span");T.textContent=y,T.style.cssText="flex:1;opacity:0.9;",o.push(()=>{C.checked=i()[x];}),S.append(C,T),r.appendChild(S);},g=y=>{let x=document.createElement("div");x.style.cssText="opacity:0.5;font-size:10px;letter-spacing:0.6px;text-transform:uppercase;padding-top:4px;",x.textContent=y,r.appendChild(x);};g("Account"),u("Risk %","riskPercent",{min:0,max:100,step:.1}),u("Account balance","accountBalance",{min:0,max:1e12,step:1}),u("Position size","quantity"),g("Levels"),f(),u("Entry price","entryPrice"),m("Stop","stopPrice","stop"),m("Target","targetPrice","target"),g("Display"),b("Show text","showText"),b("Show direction & ratio","showHeader"),b("Show loss & size","showLossSize"),b("Show target label","showTargetLabel"),b("Show stop label","showStopLabel"),b("Show level prices","showPrices");let v=document.createElement("div");v.style.cssText="opacity:0.7;font-size:11px;line-height:1.4;border-top:1px solid var(--vela-border);padding-top:6px;font-variant-numeric:tabular-nums;",o.push(()=>{let y=i();v.textContent=`${y.headerLabel()} \u2014 ${y.lossSizeLabel()}`;}),r.appendChild(v),a(),this.el?.appendChild(r),this.levelsPanel=r,this.reposition();}toggleFrvpPanel(e,t){if(this.levelsPanel){this.levelsPanel.remove(),this.levelsPanel=null,this.reposition();return}let n=this.theme,r=e.frvp,i=document.createElement("div");i.className="vela-frvp",i.style.cssText="padding:8px 10px;border-top:1px solid var(--vela-border);max-height:360px;overflow-y:auto;display:flex;flex-direction:column;gap:6px;min-width:280px;";let o=(d,h,u,p,m)=>{let f=document.createElement("div");f.style.cssText="display:flex;align-items:center;gap:10px;";let b=document.createElement("span");b.textContent=d,b.style.cssText="flex:1;opacity:0.9;";let g=document.createElement("input");g.type="number",g.min=String(u),g.max=String(p),g.step=String(m),g.value=String(r[h]),g.style.cssText=`width:72px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:4px 6px;font:12px ${n.fontFamily};font-variant-numeric:tabular-nums;outline:none;`;let v=()=>{let y=parseFloat(g.value);if(!Number.isFinite(y)){g.value=String(r[h]);return}let x=Math.min(p,Math.max(u,y));g.value=String(x),t.patch({[`frvp.${h}`]:x});};g.addEventListener("change",v),g.addEventListener("keydown",y=>{y.stopPropagation(),y.key==="Enter"&&(y.preventDefault(),v(),g.blur());}),f.append(b,g),i.appendChild(f);};o("Rows","rows",1,500,1),o("Value Area","valueAreaPct",0,100,1),o("Width %","widthPct",0,100,1);{let d=document.createElement("div");d.style.cssText="display:flex;align-items:center;gap:10px;";let h=document.createElement("span");h.textContent="Anchor",h.style.cssText="flex:1;opacity:0.9;";let u=document.createElement("select");u.style.cssText=`width:96px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:4px 6px;font:12px ${n.fontFamily};outline:none;cursor:pointer;`;for(let p of [{value:"right",label:"Right"},{value:"left",label:"Left"}]){let m=document.createElement("option");m.value=p.value,m.textContent=p.label,m.selected=r.anchor===p.value,u.appendChild(m);}u.addEventListener("change",()=>t.patch({"frvp.anchor":u.value})),u.addEventListener("keydown",p=>p.stopPropagation()),d.append(h,u),i.appendChild(d);}let a=(d,h)=>{let u=document.createElement("div");u.style.cssText="display:flex;align-items:center;gap:10px;";let p=document.createElement("span");p.textContent=d,p.style.cssText="flex:1;opacity:0.9;";let m=document.createElement("button");m.type="button";let f=r[h];m.style.cssText=`width:18px;height:18px;flex:none;border:1px solid var(--vela-border);border-radius:0;cursor:pointer;background:${f};padding:0;`,m.addEventListener("pointerdown",b=>b.stopPropagation()),m.addEventListener("click",b=>{b.stopPropagation(),this.toggleColorPopover(m,f,g=>{f=g,m.style.background=g,t.patch({[`frvp.${h}`]:g});});}),u.append(p,m),i.appendChild(u);};a("Up Volume","upColor"),a("Down Volume","downColor"),a("Value Area Up","vaUpColor"),a("Value Area Down","vaDownColor");let l=fe.map(d=>d.value),c=(d,h,u,p)=>{let m=document.createElement("div");m.style.cssText="display:flex;align-items:center;gap:8px;";let f=document.createElement("input");f.type="checkbox",f.checked=!!r[h];let b=r[u]??ge(n.background);f.style.cssText=`accent-color:${b};width:15px;height:15px;flex:none;cursor:pointer;`,f.addEventListener("change",()=>t.patch({[`frvp.${h}`]:f.checked}));let g=document.createElement("span");g.textContent=d,g.style.cssText="flex:1;min-width:0;opacity:0.9;";let v=document.createElement("button");v.type="button";let y=b;v.style.cssText=`width:18px;height:18px;flex:none;border:1px solid var(--vela-border);border-radius:0;cursor:pointer;background:${y};padding:0;`,v.addEventListener("pointerdown",S=>S.stopPropagation()),v.addEventListener("click",S=>{S.stopPropagation(),this.toggleColorPopover(v,y,C=>{y=C,v.style.background=C,f.style.accentColor=C,t.patch({[`frvp.${u}`]:C});});});let x=this.dropdown(`${d} style`,l,r[p],S=>Vt(2,S),S=>t.patch({[`frvp.${p}`]:S}),{label:un});x.style.width="auto",m.append(f,g,v,x),i.appendChild(m);};c("VAH","showVah","vahColor","vahStyle"),c("VAL","showVal","valColor","valStyle"),c("POC","showPoc","pocColor","pocStyle"),c("Developing POC","showDevelopingPoc","developingPocColor","developingPocStyle"),c("Developing VA","showDevelopingVa","developingVaColor","developingVaStyle"),this.el?.appendChild(i),this.levelsPanel=i,this.reposition();}toggleLevelsPanel(e,t){if(this.levelsPanel){this.levelsPanel.remove(),this.levelsPanel=null,this.reposition();return}let n=e.editableLevels();if(!n)return;let r=this.theme,i=e instanceof ye,o=document.createElement("div");if(o.className="vela-fiblevels",o.style.cssText=`padding:6px;border-top:1px solid var(--vela-border);max-height:260px;overflow-y:auto;display:flex;flex-direction:column;gap:3px;min-width:${i?200:248}px;`,i){let a=e,l=document.createElement("label");l.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 2px 8px;margin-bottom:2px;border-bottom:1px solid var(--vela-border);cursor:pointer;user-select:none;";let c=document.createElement("input");c.type="checkbox",c.checked=a.showRatios!==false,c.style.cssText=`accent-color:${r.textColor};width:15px;height:15px;flex:none;cursor:pointer;`,c.addEventListener("change",()=>t.patch({showRatios:c.checked}));let d=document.createElement("span");d.textContent="Show ratio labels",d.style.cssText="opacity:0.9;",l.append(c,d),o.appendChild(l);}n.forEach((a,l)=>{let c=document.createElement("div");c.style.cssText="display:flex;align-items:center;gap:8px;";let d=document.createElement("input");d.type="checkbox",d.checked=a.enabled,d.style.cssText=`accent-color:${a.color};width:15px;height:15px;flex:none;cursor:pointer;`,d.addEventListener("change",()=>t.patch({[`levels.${l}.enabled`]:d.checked}));let h=document.createElement("button");h.type="button",h.style.cssText=`width:18px;height:18px;flex:none;border:1px solid var(--vela-border);border-radius:0;cursor:pointer;background:${a.color};padding:0;`;let u=a.color;h.addEventListener("pointerdown",b=>b.stopPropagation()),h.addEventListener("click",b=>{b.stopPropagation(),this.toggleColorPopover(h,u,g=>{u=g,h.style.background=g,d.style.accentColor=g,t.patch({[`levels.${l}.color`]:g});});});let p=document.createElement("input");p.type="number",p.step="any",p.min="0";let m=a.ratio;p.value=String(m),p.title="Ratio",p.style.cssText=i?`width:88px;flex:1;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:5px 8px;font:13px ${r.fontFamily};font-variant-numeric:tabular-nums;outline:none;`:`width:52px;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:3px 4px;font:12px ${r.fontFamily};font-variant-numeric:tabular-nums;outline:none;`;let f=()=>{let b=parseFloat(p.value);if(!Number.isFinite(b)||b<=0){p.value=String(m);return}m=b,t.patch({[`levels.${l}.ratio`]:b});};if(p.addEventListener("change",f),p.addEventListener("keydown",b=>{b.stopPropagation(),b.key==="Enter"&&(b.preventDefault(),f(),p.blur());}),c.append(d,h,p),!i){let b=document.createElement("input");b.type="text",b.placeholder="label\u2026",b.value=a.label??"",b.style.cssText=`flex:1;min-width:60px;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:3px 7px;font:12px ${r.fontFamily};outline:none;`,b.addEventListener("input",()=>t.patch({[`levels.${l}.label`]:b.value})),b.addEventListener("keydown",g=>g.stopPropagation()),c.appendChild(b);}o.appendChild(c);}),this.el?.appendChild(o),this.levelsPanel=o,this.reposition();}position(e){let t=this.el;if(!t)return;let n=this.host.getBoundingClientRect(),r=t.offsetWidth,i=t.offsetHeight,o=10,a=n.width/2-r/2,l=12;e&&(a=e.x+e.w/2-r/2,l=e.y-i-o,l<4&&(l=e.y+e.h+o)),t.style.left=`${Math.max(4,Math.min(a,n.width-r-4))}px`,t.style.top=`${Math.max(4,Math.min(l,n.height-i-4))}px`;}reposition(){let e=this.el;if(!e)return;let t=this.host.getBoundingClientRect(),n=e.offsetWidth,r=e.offsetHeight,i=parseFloat(e.style.left)||0,o=parseFloat(e.style.top)||0;e.style.left=`${Math.max(4,Math.min(i,t.width-n-4))}px`,e.style.top=`${Math.max(4,Math.min(o,t.height-r-4))}px`;}base(e){let t=document.createElement("button");return t.type="button",t.dataset.tip=e,t.className="vela-dpop-btn",t.style.cssText=`width:${Ze}px;height:${Ze}px;display:flex;align-items:center;justify-content:center;cursor:pointer;color:inherit;border:none;border-radius:5px;padding:0;`,t}iconBtn(e,t,n){let r=this.base(e);return r.innerHTML=qe(t),r.addEventListener("click",n),r}dragHandle(){let e=document.createElement("button");return e.type="button",e.className="vela-dpop-grip",e.style.cssText=`width:${Ze}px;height:${Ze}px;display:flex;align-items:center;justify-content:center;background:transparent;border:none;padding:0;cursor:grab;touch-action:none;color:var(--vela-fg-faint);`,e.innerHTML=qe(Wf),e.addEventListener("pointerdown",t=>{let n=this.el;if(!n||t.button!==0)return;t.preventDefault(),t.stopPropagation(),this.hideTip(),this.closeColorPopover(),this.closeMenu();let r=this.host.getBoundingClientRect(),i=t.clientX,o=t.clientY,a=parseFloat(n.style.left)||0,l=parseFloat(n.style.top)||0;e.style.cursor="grabbing";try{e.setPointerCapture(t.pointerId);}catch{}let c=h=>{let u=n.offsetWidth,p=n.offsetHeight,m=a+(h.clientX-i),f=l+(h.clientY-o);n.style.left=`${Math.max(4,Math.min(m,r.width-u-4))}px`,n.style.top=`${Math.max(4,Math.min(f,r.height-p-4))}px`;},d=()=>{e.style.cursor="grab",window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",d);};window.addEventListener("pointermove",c),window.addEventListener("pointerup",d),window.addEventListener("pointercancel",d);}),e}kebabButton(e){let t=this.base("More");return t.innerHTML=qe(Uf),t.addEventListener("pointerdown",n=>n.stopPropagation()),t.addEventListener("click",n=>{if(n.stopPropagation(),this.menuOwner===t){this.closeMenu();return}this.openActionMenu(t,[{icon:Hf,label:"Bring to front",onClick:()=>e.reorder("front")},{icon:zf,label:"Send to back",onClick:()=>e.reorder("back")},{icon:Gf,label:"Reset settings",onClick:()=>e.resetSettings()}]);}),t}openActionMenu(e,t){this.closeMenu(),this.closeColorPopover();let n=this.theme,r=document.createElement("div");r.className="vela-dpop",r.style.cssText=`position:absolute;z-index:26;background:${n.background};border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);padding:4px;pointer-events:auto;display:flex;flex-direction:column;gap:1px;color:${n.textColor};font:var(--vela-font-size-md) ${n.fontFamily};`,ne(r,n),r.addEventListener("pointerdown",h=>h.stopPropagation());for(let h of t){let u=document.createElement("button");u.type="button",u.className="vela-dpop-item",u.style.cssText="display:flex;align-items:center;gap:9px;min-width:150px;padding:6px 9px;border:none;border-radius:5px;color:inherit;cursor:pointer;text-align:left;font:inherit;";let p=document.createElement("span");p.style.cssText="display:flex;flex:none;width:20px;justify-content:center;",p.innerHTML=qe(h.icon,18);let m=document.createElement("span");m.textContent=h.label,m.style.cssText="flex:1;",u.append(p,m),u.addEventListener("click",f=>{f.stopPropagation(),this.closeMenu(),h.onClick();}),r.appendChild(u);}this.host.appendChild(r);let i=e.getBoundingClientRect(),o=this.host.getBoundingClientRect(),a=r.offsetWidth,l=r.offsetHeight,c=i.right-o.left-a,d=i.bottom-o.top+6;c+a>o.width-4&&(c=o.width-a-4),c<4&&(c=4),d+l>o.height-4&&(d=i.top-o.top-l-6),d<4&&(d=4),r.style.left=`${Math.round(c)}px`,r.style.top=`${Math.round(d)}px`,this.menuEl=r,this.menuOwner=e;}showTip(e){let t=e.dataset.tip;if(!t){this.hideTip();return}let n=this.theme;if(!this.tipEl){let p=document.createElement("div");p.style.cssText=`position:absolute;z-index:27;pointer-events:none;white-space:nowrap;background:${n.textColor};color:${n.background};padding:3px 7px;border-radius:5px;font:var(--vela-font-size-sm) ${n.fontFamily};box-shadow:var(--vela-shadow);`,this.host.appendChild(p),this.tipEl=p;}let r=this.tipEl;r.textContent=t;let i=this.host.getBoundingClientRect(),o=e.getBoundingClientRect(),a=r.offsetWidth,l=r.offsetHeight,c=6,d=o.left-i.left+o.width/2-a/2;d=Math.max(4,Math.min(d,i.width-a-4));let h=o.top-i.top-l-c,u=h>=4?h:o.bottom-i.top+c;r.style.left=`${Math.round(d)}px`,r.style.top=`${Math.round(u)}px`;}hideTip(){this.tipEl?.remove(),this.tipEl=null;}toggle(e,t,n,r){let i=this.base(e);i.innerHTML=qe(t);let o=l=>{i.dataset.active=l?"1":"0";};o(n);let a=n;return i.addEventListener("click",()=>{a=!a,o(a),r(a);}),i}widthInput(e,t,n,r,i,o){let a=document.createElement("input");a.type="number",a.dataset.tip=e,a.min=String(n),a.max=String(r),a.step=String(i),a.value=String(t),a.style.cssText=`width:52px;height:${Ze}px;box-sizing:border-box;flex:none;background:transparent;color:inherit;border:1px solid var(--vela-border);border-radius:5px;padding:0 4px;font:12px ${this.theme.fontFamily};font-variant-numeric:tabular-nums;outline:none;`;let l=()=>{let c=parseFloat(a.value);if(!Number.isFinite(c)){a.value=String(t);return}let d=Math.min(r,Math.max(n,c));a.value=String(d),t=d,o(d);};return a.addEventListener("change",l),a.addEventListener("keydown",c=>{c.stopPropagation(),c.key==="Enter"&&(c.preventDefault(),l(),a.blur());}),a}dropdown(e,t,n,r,i,o={}){let a=this.base(e);a.style.width="auto",a.style.minWidth=`${Ze}px`,a.style.padding="0 4px",a.style.gap="2px";let l=n,c=d=>{a.replaceChildren();let h=document.createElement("span");if(h.style.cssText="display:flex;",h.innerHTML=qe(r(d)),a.appendChild(h),o.label&&o.labelInTrigger){let p=document.createElement("span");p.textContent=o.label(d),p.style.cssText="font-size:11px;opacity:0.85;font-variant-numeric:tabular-nums;",a.appendChild(p);}let u=document.createElement("span");u.style.cssText="display:flex;opacity:0.55;",u.innerHTML=qe(Yf,12),a.appendChild(u);};return c(l),a.addEventListener("pointerdown",d=>d.stopPropagation()),a.addEventListener("click",d=>{if(d.stopPropagation(),this.menuOwner===a){this.closeMenu();return}this.openMenu(a,t,l,r,o.label,h=>{l=h,c(h),i(h);});}),a}openMenu(e,t,n,r,i,o){this.closeMenu(),this.closeColorPopover();let a=this.theme,l=document.createElement("div");l.className="vela-dpop",l.style.cssText=`position:absolute;z-index:26;background:${a.background};border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);padding:4px;pointer-events:auto;display:flex;flex-direction:column;gap:1px;color:${a.textColor};font:var(--vela-font-size-md) ${a.fontFamily};`,ne(l,a),l.addEventListener("pointerdown",f=>f.stopPropagation());for(let f of t){let b=f===n,g=document.createElement("button");g.type="button",g.className="vela-dpop-item",g.dataset.active=b?"1":"0",g.style.cssText=`display:flex;align-items:center;gap:8px;${i?"min-width:118px;":""}padding:5px 8px;border:none;border-radius:5px;color:inherit;cursor:pointer;text-align:left;font:inherit;`;let v=document.createElement("span");if(v.style.cssText="display:flex;flex:none;width:22px;justify-content:center;",v.innerHTML=qe(r(f),18),g.appendChild(v),i){let y=document.createElement("span");y.textContent=i(f),y.style.cssText="flex:1;font-variant-numeric:tabular-nums;",g.appendChild(y);}g.addEventListener("click",y=>{y.stopPropagation(),this.closeMenu(),o(f);}),l.appendChild(g);}this.host.appendChild(l);let c=e.getBoundingClientRect(),d=this.host.getBoundingClientRect(),h=l.offsetWidth,u=l.offsetHeight,p=c.left-d.left,m=c.bottom-d.top+6;p+h>d.width-4&&(p=d.width-h-4),p<4&&(p=4),m+u>d.height-4&&(m=c.top-d.top-u-6),m<4&&(m=4),l.style.left=`${Math.round(p)}px`,l.style.top=`${Math.round(m)}px`,this.menuEl=l,this.menuOwner=e;}closeMenu(){this.menuEl&&(this.menuEl.remove(),this.menuEl=null),this.menuOwner=null;}colorButton(e,t,n,r,i=17){let o=document.createElement("button");o.type="button",o.dataset.tip=e,o.className="vela-dpop-btn",o.style.cssText=`position:relative;width:${Ze}px;height:${Ze}px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;cursor:pointer;border-radius:5px;border:none;color:inherit;padding:0;`;let a=document.createElement("span");a.style.cssText="display:flex;",a.innerHTML=qe(t,i);let l=document.createElement("span");l.style.cssText=`display:block;height:3px;width:${Math.round(i*.85)}px;border-radius:2px;background:${n};`,o.append(a,l);let c=n;return o.addEventListener("pointerdown",d=>d.stopPropagation()),o.addEventListener("click",d=>{d.stopPropagation(),this.toggleColorPopover(o,c,h=>{c=h,l.style.background=h,r(h);});}),o}toggleColorPopover(e,t,n){if(this.colorOwner===e){this.closeColorPopover();return}this.openColorPopover(e,t,n);}openColorPopover(e,t,n){this.closeColorPopover(),this.closeMenu();let r=this.theme,i=document.createElement("div");i.style.cssText=`position:absolute;z-index:25;background:${r.background};border:1px solid var(--vela-border);border-radius:var(--vela-radius-lg);box-shadow:var(--vela-shadow);padding:10px;pointer-events:auto;`,ne(i,r),i.addEventListener("pointerdown",u=>u.stopPropagation()),i.appendChild(Jn(t,r,n)),this.host.appendChild(i);let o=e.getBoundingClientRect(),a=this.host.getBoundingClientRect(),l=i.offsetWidth,c=i.offsetHeight,d=o.left-a.left,h=o.bottom-a.top+6;d+l>a.width-4&&(d=a.width-l-4),d<4&&(d=4),h+c>a.height-4&&(h=o.top-a.top-c-6),h<4&&(h=4),i.style.left=`${Math.round(d)}px`,i.style.top=`${Math.round(h)}px`,this.colorPop=i,this.colorOwner=e;}closeColorPopover(){this.colorPop&&(this.colorPop.remove(),this.colorPop=null),this.colorOwner=null;}divider(){let e=document.createElement("div");return e.style.cssText="width:1px;height:18px;margin:0 3px;background:var(--vela-border);",e}},Bt=$("brush"),hn=$("bucket"),Ss=$("type"),Vf=$("price-delta"),_f=$("date-delta"),Nf=$("lock"),Hf=$("bring-front"),zf=$("send-back"),$f=$("trash"),_c=$("bold"),Nc=$("italic"),Wf=$("grip"),Uf=$("kebab"),Gf=$("reset"),Cs=$("gear"),Yf=$("chevron-down"),Xf=$("r-squared"),Kf=$("bands"),jf=$("dedekind"),qf=$("sonic"),Zf=$("supersonic");function Vt(s,e){let t=e==="dashed"?"5,3":e==="dotted"?"1.5,3":"";return I(`<line x1="3.5" y1="12" x2="20.5" y2="12" stroke-width="${Number(s)||2}" stroke-dasharray="${t}"/>`)}var Jf=4;function Hc(s){s.style.height="auto";let e=18*Jf+10+2;s.style.height=`${Math.min(s.scrollHeight,e)}px`,s.style.overflowY=s.scrollHeight>e?"auto":"hidden";}function nr(s,e,t=17,n=""){return Ao(`<text x="12" y="${t}" font-size="${e}" text-anchor="middle"${n?" "+n:""}>${s}</text>`)}function Qf(s){return nr(String(s),15)}function eb(s){return nr("\u25CF",(Ts[String(s)]??13)+4)}function tb(s){return nr(String(s).charAt(0).toUpperCase(),15)}var Ts={small:10,normal:13,large:16,huge:20};function nb(s){return nr("12",(Ts[String(s)]??13)-1,16.5,'font-weight="600"')}function zc(s){return nr("T",(Ts[String(s)]??13)+2)}function $c(s){return s.charAt(0).toUpperCase()+s.slice(1)}function tr(s){return Te.find(e=>e.value===s)?.label??$c(String(s))}function un(s){return fe.find(e=>e.value===s)?.label??$c(String(s))}function qe(s,e=Ff){return s.replace("<svg ",`<svg width="${e}" height="${e}" `)}var Ms=44,Ls=16,rr=class{constructor(e,t,n,r=()=>{},i=()=>{},o=()=>{},a=()=>{},l=()=>{},c={}){this.host=e;this.theme=t;this.onArm=n;this.onMagnet=r;this.onMeasure=i;this.onEraser=o;this.onToggleFavorite=a;this.onStayMode=l;this.def={groups:[]};this.active=null;this.lastUsed=new Map;this.favorites=new Set;this.shortcuts=new Map;this.starEls=new Map;this.flyout=null;this.flyoutOwnerId=null;this.flyoutCell=null;this.groupCells=new Map;this.groupIcons=new Map;this.cursorBtn=null;this.magnetCell=null;this.magnetIcon=null;this.magnetMode="off";this.lastMagnetOn="weak";this.measureBtn=null;this.measureActive=false;this.eraserBtn=null;this.eraserActive=false;this.stayBtn=null;this.stayActive=false;this.syncBtn=null;this.syncActive=false;this.collapseBtn=null;this.collapsed=false;this.visible=false;this.tipText=new WeakMap;this.tipDisposers=[];this.onOutside=e=>{let t=e.target;this.flyout&&!this.flyout.contains(t)&&!this.root.contains(t)&&this.closeFlyout();};this.borderOverride=c.borderColor??null,this.width=c.width??Ms,this.dock=c.dock??"absolute",this.onCollapse=c.onCollapse??(()=>{}),this.onDrawingsSync=c.onDrawingsSync??null,rb(),this.root=document.createElement("div"),this.root.className="vela-dtb",this.styleRoot(),e.appendChild(this.root);}get borderColor(){return this.borderOverride??this.theme.borderColor}styleRoot(){let e=this.theme;ne(this.root,e);let t=this.collapsed?Ls:this.width;this.root.dataset.collapsed=this.collapsed?"1":"";let n=this.dock==="absolute"?`position:absolute;left:0;top:0;height:100%;width:${t}px;z-index:21;`:`position:relative;height:100%;width:${t}px;flex:none;`;this.root.style.cssText=n+`display:${this.visible?"flex":"none"};flex-direction:column;gap:4px;padding:6px 0;box-sizing:border-box;background:${e.background};border-right:1px solid ${this.borderColor};color:var(--vela-fg-muted);pointer-events:auto;overflow-y:auto;overflow-x:hidden;`;}setDefinition(e){this.def=e;for(let t of e.groups){let n=t.tools[0];n&&!this.lastUsed.has(t.id)&&this.lastUsed.set(t.id,n.type);}this.rebuild();}setFavorites(e){this.favorites=new Set(e);for(let[t,n]of this.starEls)this.paintStar(n,t);}setShortcuts(e){this.shortcuts=new Map(Object.entries(e));}paintStar(e,t){let n=this.favorites.has(t);e.classList.toggle("vela-fav",n),e.setAttribute("aria-label",n?"Remove from favorites":"Add to favorites"),e.setAttribute("aria-pressed",n?"true":"false"),e.innerHTML=fo(n?mb:pb);}setVisible(e){this.visible=e,this.root.style.display=e?"flex":"none";}setActiveTool(e){if(this.active=e,e){let t=this.def.groups.find(n=>n.tools.some(r=>r.type===e));t&&(this.lastUsed.set(t.id,e),this.paintGroupIcon(t));}this.closeFlyout(),this.highlight();}setTheme(e){this.theme=e,this.styleRoot(),this.rebuild();}destroy(){this.closeFlyout();for(let e of this.tipDisposers.splice(0))e();this.root.remove();}rebuild(){for(let e of this.tipDisposers.splice(0))e();this.root.replaceChildren(),this.groupCells.clear(),this.groupIcons.clear(),this.cursorBtn=this.makeButton(ib,"Cursor",()=>this.onArm(null)),this.root.appendChild(this.cursorBtn),this.def.groups.length>0&&this.root.appendChild(this.divider());for(let e of this.def.groups){let t=this.makeGroupCell(e);this.root.appendChild(t),this.paintGroupIcon(e);}this.root.appendChild(this.divider()),this.measureBtn=this.makeButton(ob,"Measure",()=>this.onMeasure()),this.root.appendChild(this.measureBtn),this.eraserBtn=this.makeButton(db,"Eraser (click/drag to delete)",()=>this.onEraser()),this.root.appendChild(this.eraserBtn),this.root.appendChild(this.makeMagnetCell()),this.stayBtn=this.makeButton(lb,"Stay in drawing mode",()=>this.toggleStay()),this.root.appendChild(this.stayBtn),this.onDrawingsSync&&(this.syncBtn=this.makeButton(cb,"Sync drawings on all charts",()=>this.toggleDrawingsSync()),this.root.appendChild(this.syncBtn)),this.collapseBtn=this.makeButton(Gc,"Collapse toolbar",()=>this.toggleCollapsed()),this.collapseBtn.classList.add("vela-dtb-collapse"),this.root.appendChild(this.collapseBtn),this.paintMeasure(),this.paintEraser(),this.paintMagnet(),this.paintStay(),this.paintDrawingsSync(),this.paintCollapse(),this.highlight();}toggleCollapsed(){this.collapsed=!this.collapsed,this.closeFlyout(),this.styleRoot(),this.paintCollapse(),this.onCollapse(this.collapsed);}paintCollapse(){let e=this.collapseBtn;if(!e)return;let t=this.collapsed?"Expand toolbar":"Collapse toolbar";e.innerHTML=mo(this.collapsed?sb:Gc,12),e.setAttribute("aria-label",t),this.tipText.set(e,t);}makeCell(e,t){let n=document.createElement("div");n.className="vela-dtb-cell";let r=document.createElement("button");r.type="button",r.className="vela-dtb-icon",r.setAttribute("aria-label",e),t.iconSvg&&(r.innerHTML=mo(t.iconSvg)),r.addEventListener("click",t.onIcon),n.appendChild(r);let i=null;if(t.multi&&t.onArrow){let o=t.onArrow;i=document.createElement("button"),i.type="button",i.className="vela-dtb-arrow",i.setAttribute("aria-label",`${e} \u2014 more`),i.innerHTML=fb(hb),i.addEventListener("click",a=>{a.stopPropagation(),o();}),n.appendChild(i);}return this.tipDisposers.push(Et(n,{host:this.host,theme:()=>this.theme,text:()=>this.tipText.get(n)??e,placement:"right"})),{cell:n,icon:r,arrow:i}}makeGroupCell(e){let t=e.tools.length>1,{cell:n,icon:r}=this.makeCell(e.label,{multi:t,onIcon:()=>this.onGroupIconClick(e),onArrow:t?()=>this.onArrowClick(e):void 0});return this.groupCells.set(e.id,n),this.groupIcons.set(e.id,r),n}makeMagnetCell(){let{cell:e,icon:t}=this.makeCell("Magnet snap",{iconSvg:ab,multi:true,onIcon:()=>this.toggleMagnet(),onArrow:()=>this.onMagnetArrowClick()});return this.magnetCell=e,this.magnetIcon=t,e}onGroupIconClick(e){let t=this.lastUsed.get(e.id)??e.tools[0]?.type;t&&this.onArm(t);}onArrowClick(e){let t=this.flyoutOwnerId===e.id;this.closeFlyout(),t||this.openGroupFlyout(e);}toggleMagnet(){this.applyMagnet(this.magnetMode==="off"?this.lastMagnetOn:"off");}onMagnetArrowClick(){let e=this.flyoutOwnerId===Wc;this.closeFlyout(),e||this.openMagnetFlyout();}applyMagnet(e){this.magnetMode=e,e!=="off"&&(this.lastMagnetOn=e),this.onMagnet(e),this.paintMagnet(),this.highlight();}setMagnetMode(e){this.magnetMode=e,e!=="off"&&(this.lastMagnetOn=e),this.paintMagnet(),this.highlight();}setMeasureActive(e){this.measureActive=e,this.paintMeasure(),this.highlight();}paintMeasure(){let e=this.measureBtn;e&&(e.dataset.active=this.measureActive?"1":"");}setEraserActive(e){this.eraserActive=e,this.paintEraser(),this.highlight();}paintEraser(){let e=this.eraserBtn;e&&(e.dataset.active=this.eraserActive?"1":"");}paintMagnet(){let e=this.magnetCell,t=this.magnetIcon;if(!e||!t)return;let n=this.magnetMode==="off"?"Off":this.magnetMode==="weak"?"Weak":"Strong";this.tipText.set(e,`Magnet snap: ${n}`);let r=this.magnetMode!=="off";e.dataset.active=r?"1":"",t.style.opacity=r?"1":"0.5";}toggleStay(){this.stayActive=!this.stayActive,this.onStayMode(this.stayActive),this.paintStay();}setStayMode(e){this.stayActive=e,this.paintStay();}paintStay(){let e=this.stayBtn;e&&(e.dataset.active=this.stayActive?"1":"",e.style.opacity=this.stayActive?"1":"0.5");}toggleDrawingsSync(){this.syncActive=!this.syncActive,this.onDrawingsSync?.(this.syncActive),this.paintDrawingsSync();}setDrawingsSyncMode(e){this.syncActive=e,this.paintDrawingsSync();}paintDrawingsSync(){let e=this.syncBtn;e&&(e.dataset.active=this.syncActive?"1":"",e.style.opacity=this.syncActive?"1":"0.5");}beginFlyout(e,t){let n=this.theme,r=document.createElement("div");r.className="vela-dtb-flyout",r.style.cssText=`position:absolute;z-index:23;display:flex;flex-direction:column;gap:2px;padding:4px;border-radius:0 8px 8px 0;background:var(--vela-surface-elev);border:1px solid ${this.borderColor};border-left:none;box-shadow:var(--vela-shadow);pointer-events:auto;overflow-y:auto;overscroll-behavior:contain;`,ne(r,n),this.host.appendChild(r);let i=t.getBoundingClientRect(),o=this.root.getBoundingClientRect(),a=this.host.getBoundingClientRect(),l=i.top-a.top;return r.style.left=`${o.right-a.left-1}px`,r.style.top=`${l}px`,r.style.maxHeight=`${Math.max(120,a.height-l-8)}px`,this.flyout=r,this.flyoutOwnerId=e,this.flyoutCell=t,t.classList.add("vela-open"),this.highlight(),document.addEventListener("pointerdown",this.onOutside),r}openGroupFlyout(e){let t=this.groupCells.get(e.id);if(!t)return;let n=this.beginFlyout(e.id,t),r=e.sections??[{label:"",tools:e.tools}];for(let i=0;i<r.length;i++){let o=r[i];o.label&&(i>0&&n.appendChild(this.flyoutSeparator()),n.appendChild(this.flyoutHeader(o.label)));for(let a of o.tools)n.appendChild(this.makeFlyoutItem({icon:a.icon,label:a.label,selected:a.type===this.active,shortcut:this.shortcuts.get(a.type),onSelect:()=>this.onArm(a.type),favorite:{type:a.type,toggle:()=>this.onToggleFavorite(a.type,!this.favorites.has(a.type))}}));}}openMagnetFlyout(){let e=this.magnetCell;if(!e)return;let t=this.beginFlyout(Wc,e);t.appendChild(this.flyoutHeader("Magnet"));let n=[["off","Off"],["weak","Weak"],["strong","Strong"]];for(let[r,i]of n)t.appendChild(this.makeFlyoutItem({label:i,selected:r===this.magnetMode,onSelect:()=>{this.applyMagnet(r),this.closeFlyout();}}));}flyoutHeader(e){let t=this.theme,n=document.createElement("div");return n.textContent=e.toUpperCase(),n.style.cssText=`padding:6px 12px 2px 8px;font:var(--vela-font-size-sm) ${t.fontFamily};font-weight:600;letter-spacing:0.04em;color:var(--vela-fg-muted);user-select:none;`,n}flyoutSeparator(){let e=document.createElement("div");return e.style.cssText=`height:1px;margin:4px 8px;background:${this.borderColor};`,e}makeFlyoutItem(e){let t=this.theme,n=document.createElement("button");if(n.type="button",n.className="vela-dtb-item",n.setAttribute("aria-label",e.label),n.style.cssText=`display:flex;align-items:center;gap:8px;padding:5px 10px 5px 8px;cursor:pointer;color:${t.textColor};border-radius:var(--vela-radius-sm);font:13px ${t.fontFamily};white-space:nowrap;min-width:148px;`,e.icon){let o=document.createElement("span");o.style.cssText="width:18px;height:18px;display:flex;align-items:center;justify-content:center;flex:none;",o.innerHTML=fo(e.icon),n.appendChild(o);}let r=document.createElement("span");r.textContent=e.label,r.style.cssText="flex:1 1 auto;text-align:left;",n.appendChild(r);let i=document.createElement("span");if(i.style.cssText="width:14px;height:14px;display:flex;align-items:center;justify-content:center;flex:none;",e.selected&&(i.innerHTML=fo(ub)),n.appendChild(i),e.shortcut){let o=document.createElement("span");o.className="vela-dtb-hint",o.textContent=e.shortcut,o.style.cssText=`flex:none;font:var(--vela-font-size-md) ${t.fontFamily};color:var(--vela-fg-muted);`,n.appendChild(o);}if(e.favorite){let o=document.createElement("span");o.className="vela-dtb-star",o.setAttribute("role","button"),this.paintStar(o,e.favorite.type),this.starEls.set(e.favorite.type,o);for(let a of ["pointerdown","pointerup","mousedown","mouseup"])o.addEventListener(a,l=>l.stopPropagation());o.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),e.favorite.toggle();}),n.appendChild(o);}return n.addEventListener("click",o=>{o.stopPropagation(),e.onSelect();}),n}closeFlyout(){this.starEls.clear(),this.flyout&&(this.flyout.remove(),this.flyout=null,this.flyoutCell?.classList.remove("vela-open"),this.flyoutCell=null,this.flyoutOwnerId=null,document.removeEventListener("pointerdown",this.onOutside),this.highlight());}paintGroupIcon(e){let t=this.groupIcons.get(e.id);if(!t)return;let n=this.lastUsed.get(e.id)??e.tools[0]?.type,r=e.tools.find(o=>o.type===n)??e.tools[0];t.innerHTML=mo(r?.icon??"");let i=this.groupCells.get(e.id);i&&this.tipText.set(i,r?.label??e.label);}highlight(){let e=this.active?this.def.groups.find(t=>t.tools.some(n=>n.type===this.active)):null;for(let[t,n]of this.groupCells){let r=t===e?.id;n.dataset.active=r?"1":"";}this.cursorBtn&&(this.cursorBtn.dataset.active=this.active==null&&!this.measureActive&&!this.eraserActive?"1":""),this.paintMeasure(),this.paintEraser(),this.paintMagnet(),this.paintStay();}makeButton(e,t,n){let r=document.createElement("button");return r.type="button",r.className="vela-dtb-btn",r.setAttribute("aria-label",t),this.tipText.set(r,t),e&&(r.innerHTML=mo(e)),this.tipDisposers.push(Et(r,{host:this.host,theme:()=>this.theme,text:()=>this.tipText.get(r)??t,placement:"right"})),r.addEventListener("click",n),r}divider(){let e=document.createElement("div");return e.style.cssText=`width:24px;height:1px;margin:2px auto;flex:none;background:${this.borderColor};`,e}},Wc="__magnet__",Uc="vela-drawing-toolbar-styles";function rb(){if(typeof document>"u")return;let s=document.getElementById(Uc);s||(s=document.createElement("style"),s.id=Uc,document.head.appendChild(s)),s.textContent=`
211
211
  .vela-dtb-hit{width:22px;height:22px;display:flex;align-items:center;justify-content:center;border-radius:var(--vela-radius-md);transition:background var(--vela-dur-fast) ease,color var(--vela-dur-fast) ease;}
212
212
  .vela-dtb-hit--arrow{width:11px;height:22px;}
213
213
  .vela-dtb-btn{position:relative;width:100%;height:30px;flex:none;display:flex;align-items:center;justify-content:center;cursor:pointer;color:inherit;background:transparent;border:none;padding:0;transition:color var(--vela-dur-fast) ease;}
@@ -244,9 +244,9 @@ void main() {
244
244
  .vela-dtb-flyout::-webkit-scrollbar-button{display:none;width:0;height:0;}
245
245
  .vela-dtb-flyout::-webkit-scrollbar-track,.vela-dtb-flyout::-webkit-scrollbar-track-piece,.vela-dtb-flyout::-webkit-scrollbar-corner{background:transparent;}
246
246
  .vela-dtb-flyout::-webkit-scrollbar-thumb{background:var(--vela-scroll);border-radius:var(--vela-radius-sm);}
247
- .vela-dtb-flyout::-webkit-scrollbar-thumb:hover{background:var(--vela-fg-muted);}`;}var nb=$("cursor"),rb=$("ruler"),Uc=$("chevrons-left"),ib=$("chevrons-right"),ob=$("magnet"),sb=$("pen-lock"),ab=$("pen-sync"),lb=$("eraser"),cb=$("chevron-right"),db=$("check"),hb=$("star"),ub=$("star-filled");function mo(s){return s.replace("<svg ",'<svg width="100%" height="100%" ')}function Gc(s,e=18){return s?`<span style="width:${e}px;height:${e}px;display:flex;align-items:center;justify-content:center;">${mo(s)}</span>`:""}function po(s,e=18){return `<span class="vela-dtb-hit">${Gc(s,e)}</span>`}function pb(s){return `<span class="vela-dtb-hit vela-dtb-hit--arrow">${Gc(s,11)}</span>`}function Yc(s){return `${s>=0?"+":""}${s.toFixed(2)}`}var mb=q,fb=X,bb=3,fo=class{constructor(){this.state="idle";this.start=null;this.end=null;this.pressX=0;this.pressY=0;}isActive(){return this.state!=="idle"}isFinished(){return this.state==="finished"}down(e,t){if(this.state==="measuring"){this.end={x:e,y:t},this.state="finished";return}this.start={x:e,y:t},this.end={x:e,y:t},this.pressX=e,this.pressY=t,this.state="measuring";}move(e,t){this.state==="measuring"&&(this.end={x:e,y:t});}up(e,t){this.state==="measuring"&&Math.hypot(e-this.pressX,t-this.pressY)>bb&&(this.end={x:e,y:t},this.state="finished");}clear(){this.state="idle",this.start=null,this.end=null;}paint(e,t,n){if(!this.start||!this.end)return;let{x:r,y:i}=this.start,{x:o,y:a}=this.end,l=t.paneIdAtY(i)??t.paneIdAtY(a);if(!l)return;let c=t.pxToPoint(r,i,l),d=t.pxToPoint(o,a,l),h=d.price-c.price,u=c.price!==0?h/c.price*100:0,p=t.barsBetween?Math.round(t.barsBetween(c.time,d.time)):null,m=h>=0,f=m?mb:fb,b=Math.min(r,o),g=Math.max(r,o),v=Math.min(i,a),y=Math.max(i,a),x=(r+o)/2,S=(i+a)/2;e.save(),e.globalAlpha=.12,e.fillStyle=f,e.fillRect(b,v,g-b,y-v),e.globalAlpha=1,e.strokeStyle=f,e.lineWidth=1,e.setLineDash([4,4]),e.beginPath(),e.moveTo(x,i),e.lineTo(x,a),e.moveTo(r,S),e.lineTo(o,S),e.stroke(),e.setLineDash([]);let C=m?v:y,T=m?1:-1;e.fillStyle=f,e.beginPath(),e.moveTo(x,C),e.lineTo(x-5,C+T*7),e.lineTo(x+5,C+T*7),e.closePath(),e.fill(),e.restore(),this.paintLabel(e,t,n,x,v,y,f,[`${Yc(h)} (${Yc(u)}%)`,p!=null?`${p} bars \xB7 ${Ln(d.time-c.time)}`:Ln(d.time-c.time)]);}paintLabel(e,t,n,r,i,o,a,l){e.save(),e.font=`12px ${n.fontFamily}`;let c=Math.max(...l.map(f=>e.measureText(f).width))+16,d=16,h=l.length*d+8,u=o+8;u+h>t.height&&(u=i-h-8);let p=r-c/2;e.fillStyle=n.background,e.strokeStyle=a,e.lineWidth=1,e.beginPath(),e.roundRect(p,u,c,h,4),e.fill(),e.stroke(),e.fillStyle=n.textColor,e.textAlign="center",e.textBaseline="middle",l.forEach((f,b)=>e.fillText(f,r,u+8+d/2+b*d)),e.restore();}};function Xc(s,e){if(e.editingText)return null;if(s.ctrlKey||s.metaKey)switch(s.key.toLowerCase()){case "z":return s.shiftKey?{kind:"redo"}:{kind:"undo"};case "y":return {kind:"redo"};case "c":return e.hasSelection?{kind:"copy"}:null;case "v":return {kind:"paste"};case "d":return e.hasSelection?{kind:"duplicate"}:null;default:return null}if(s.key==="Delete"||s.key==="Backspace")return e.hasTarget?{kind:"delete"}:null;if(e.hasSelection){let n=s.shiftKey?10:1;switch(s.key){case "ArrowLeft":return {kind:"nudge",dx:-n,dy:0};case "ArrowRight":return {kind:"nudge",dx:n,dy:0};case "ArrowUp":return {kind:"nudge",dx:0,dy:-n};case "ArrowDown":return {kind:"nudge",dx:0,dy:n}}}return null}function Kc(s){let e=s;return !e||!e.tagName?false:e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable===true}var jc="Enter Text",gb=8,Ps=1;function Es(s){return s instanceof Ie||s instanceof He}var vb={};function qc(s,e){return e.length===0||s>e[e.length-1]?null:e.find(t=>t>=s)}var bo=class{constructor(e,t,n,r){this.toolbarHost=e;this.overlayHost=t;this.canvas=n;this.deps=r;this.ctx=null;this.drawings=[];this.sliced=new Set;this.sliceCache=new Map;this.lastBounds=new Map;this.selectedIds=new Set;this.hoveredId=null;this.activeTool=null;this.intentCb=null;this.externalGhost=null;this.lastDraftKey=null;this.measure=new fo;this.toolbarVisible=false;this.toolbarCollapsed=false;this.mobileLayout=false;this.historyChords=true;this.measureMode=false;this.eraserMode=false;this.erasing=false;this.textEditor=null;this.painter=new co;this.ctx=n.getContext("2d"),this.popup=new uo(t,r.theme()),this.toolbar=new rr(e,r.theme(),i=>this.emit({kind:"arm",type:i}),i=>{this.deps.setSnapMode(i),this.emit({kind:"snap-mode",mode:i});},()=>this.withModeIntent(()=>this.toggleMeasure()),()=>this.withModeIntent(()=>this.toggleEraser()),(i,o)=>this.emit({kind:"favorite",type:i,on:o}),i=>this.emit({kind:"stay-mode",on:i}),{onCollapse:i=>{this.toolbarCollapsed=i,this.syncToolbarGutter();}}),this.interaction=new ho({projector:()=>this.deps.projector(),activeTool:()=>this.activeTool,drawings:()=>this.drawings,hoveredId:()=>this.hoveredId,selectedIds:()=>this.selectedIds,emit:i=>this.emit(i),changed:()=>{this.invalidateSlices(),this.render();},openSettings:(i,o,a)=>this.openSettingsById(i,o,a),snap:(i,o,a,l)=>this.deps.snap(i,o,a,l),lastStyle:()=>this.activeToolStyle});}setToolbar(e){this.toolbar.setDefinition(e);}showToolbar(e){this.toolbarVisible=e,this.toolbar.setVisible(e&&!this.mobileLayout),this.syncToolbarGutter();}setLayoutMode(e){this.mobileLayout=e==="mobile",this.toolbar.setVisible(this.toolbarVisible&&!this.mobileLayout),this.syncToolbarGutter();}syncToolbarGutter(){let e=this.toolbarVisible&&!this.mobileLayout;this.deps.setToolbarGutter(e?this.toolbarCollapsed?Ls:Ms:0);}setExternalGhost(e){this.externalGhost=e?Fe(e):null,this.render();}syncDrawings(e){this.drawings=e.map(t=>Fe(t)).filter(t=>t!=null),this.textEditor&&!this.editedDrawing(this.textEditor.id)&&this.closeTextEditor(),this.invalidateSlices(),this.render(),this.deps.requestScaleUpdate();}stackRange(e){let t=this.deps.seriesBoundaries(e);return {front:Math.max(0,...t),back:Math.min(0,...t),price:this.deps.priceZ(e)??void 0}}priceRangeForPane(e,t,n){let r=1/0,i=-1/0;for(let o of this.drawings){if(!o.visible||o.paneId!==e)continue;let a=o.timeExtent();if(a&&(a.max<t||a.min>n))continue;let l=o.priceRange();l&&(l.min<r&&(r=l.min),l.max>i&&(i=l.max));}return r<=i?{min:r,max:i}:null}setActiveTool(e,t){e!=null&&(this.finishTextEditor(true),this.withModeIntent(()=>{this.measureMode&&this.exitMeasure(),this.eraserMode&&this.exitEraser();})),this.activeTool=e,this.activeToolStyle=t,this.toolbar.setActiveTool(e),e==null?this.interaction.onToolCleared():this.clearSelection(),this.render();}setFavorites(e){this.toolbar.setFavorites(e);}setToolShortcuts(e){this.toolbar.setShortcuts(e);}setSnapMode(e){this.deps.setSnapMode(e),this.toolbar.setMagnetMode(e);}setStayMode(e){this.toolbar.setStayMode(e);}setMode(e){this.withModeIntent(()=>{e==="measure"?this.measureMode||this.toggleMeasure():e==="eraser"?this.eraserMode||this.toggleEraser():(this.measureMode&&this.exitMeasure(),this.eraserMode&&this.exitEraser());});}modeOf(){return this.measureMode?"measure":this.eraserMode?"eraser":null}withModeIntent(e){let t=this.modeOf();e();let n=this.modeOf();n!==t&&this.emit({kind:"mode",mode:n});}setSelection(e){this.selectedIds=new Set(e),this.render();}openSettings(e){this.openSettingsById(e,0,0);}onDrawingIntent(e){return this.intentCb=e,()=>{this.intentCb===e&&(this.intentCb=null);}}claim(e,t){return this.measureMode||this.eraserMode?true:this.interaction.claim(e,t)}deleteAt(e,t){let n=dn(this.drawings,e,t,this.deps.projector(),6);return !n||n.locked?false:(this.popup.close(),this.emit({kind:"delete",ids:[n.id]}),true)}beginMeasureAt(e,t){return this.measureMode||this.eraserMode||this.activeTool!=null?false:(this.withModeIntent(()=>this.toggleMeasure()),this.measure.down(e,t),this.render(),true)}clearTransient(){this.textEditor&&this.finishTextEditor(true),this.measure.isFinished()&&(this.measure.clear(),this.render());}pointerDown(e,t,n="off",r=false){if(this.eraserMode){this.erasing=true,this.deleteAt(e,t);return}if(this.measureMode){this.measure.down(e,t),this.measure.isFinished()&&this.withModeIntent(()=>this.exitMeasure(false)),this.render();return}this.interaction.down(e,t,n,r);}pointerMove(e,t,n="off",r=false){if(this.eraserMode){this.erasing&&this.deleteAt(e,t);return}if(this.measureMode){this.measure.move(e,t),this.render();return}this.interaction.move(e,t,n,r),this.updateHover(e,t);}updateHover(e,t){let n=null;this.activeTool==null&&!this.interaction.isPlacing()&&!this.interaction.isDragging()&&(n=dn(this.drawings,e,t,this.deps.projector(),6)?.id??null),n!==this.hoveredId&&(this.hoveredId=n,this.render());}pointerUp(e,t){if(this.eraserMode){this.erasing=false;return}if(this.measureMode){this.measure.up(e,t),this.measure.isFinished()&&this.withModeIntent(()=>this.exitMeasure(false)),this.render();return}this.interaction.up(e,t);}toggleMeasure(){if(this.measureMode){this.exitMeasure();return}this.eraserMode&&this.exitEraser(),this.measure.clear(),this.measureMode=true,this.emit({kind:"arm",type:null}),this.clearSelection(),this.toolbar.setMeasureActive(true),this.render();}toggleEraser(){if(this.eraserMode){this.exitEraser();return}this.measureMode&&this.exitMeasure(),this.eraserMode=true,this.erasing=false,this.emit({kind:"arm",type:null}),this.clearSelection(),this.toolbar.setEraserActive(true),this.render();}exitEraser(){this.eraserMode=false,this.erasing=false,this.toolbar.setEraserActive(false),this.render();}exitMeasure(e=true){this.measureMode=false,e&&this.measure.clear(),this.toolbar.setMeasureActive(false),this.render();}editTextInline(e){let t=this.editedDrawing(e);if(!t)return;this.closeTextEditor();let n=t.text?.value??"",r=this.inlineEditorCss(t,n);if(!r)return;let i=document.createElement("textarea");i.value=n,i.placeholder=jc,i.spellcheck=false,i.style.cssText=r;let o=()=>{this.editedDrawing(e)?.applySettings({"text.value":i.value}),this.render();};i.addEventListener("input",o),i.addEventListener("pointerdown",a=>a.stopPropagation()),i.addEventListener("keydown",a=>{if(a.stopPropagation(),a.key==="Enter"&&!a.ctrlKey&&!a.metaKey){a.preventDefault();let l=i.selectionStart;i.setRangeText(`
248
- `,l,i.selectionEnd,"end"),o();}else a.key==="Enter"?(a.preventDefault(),this.finishTextEditor(true)):a.key==="Escape"&&(a.preventDefault(),this.finishTextEditor(false));}),i.addEventListener("blur",a=>{this.popup.contains(a.relatedTarget)?this.storeText(i.value):this.finishTextEditor(true);}),this.overlayHost.appendChild(i),this.textEditor={el:i,id:e,initial:n,stored:n},i.focus(),i.setSelectionRange(i.value.length,i.value.length);}storeText(e){let t=this.textEditor,n=t&&this.editedDrawing(t.id);!t||!n||(n.applySettings({"text.value":e}),e!==t.stored&&(t.stored=e,this.emit({kind:"edit",doc:n.serialize()})));}editedDrawing(e){let t=this.drawings.find(n=>n.id===e);return Es(t)?t:null}finishTextEditor(e){let t=this.textEditor;if(!t)return;let n=e?t.el.value:t.initial;this.closeTextEditor();let r=this.editedDrawing(t.id);r&&(r.applySettings({"text.value":n}),this.render(),r instanceof He&&n.trim()===""?(this.clearSelection(),this.emit({kind:"delete",ids:[r.id]})):n!==t.stored&&this.emit({kind:"edit",doc:r.serialize()}));}inlineEditorCss(e,t){let n=this.deps.projector(),r=this.deps.theme(),i=e.text,o=ce(i?.size??"normal"),a=`${i?.italic?"italic ":""}${i?.bold?"bold ":""}${o}px ${r.fontFamily}`,l="position:absolute;z-index:24;box-sizing:border-box;resize:none;overflow:hidden;margin:0;outline:none;pointer-events:auto;text-align:left;";if(e instanceof Ie){let p=e.box(n);if(!p)return null;let m=e.style.fillColor??r.background;return l+`left:${Math.round(p.x)}px;top:${Math.round(p.y)}px;width:${Math.round(p.w)}px;height:${Math.round(p.h)}px;padding:5px 8px;border-radius:5px;border:1px solid ${e.style.lineColor??r.borderColor};background:${vc(m,r.background,cn(m).alpha)};color:${i?.color??r.textColor};font:${a};`}let c=e.handlePoints(n)[0];if(!c)return null;let d=Ve(o),h=(t||jc).split(`
249
- `),u=Math.ceil(this.measureTextWidth(h,a))+gb;return l+`left:${Math.round(c[0]+2)-At}px;top:${Math.round(c[1]+2-(d-o)/2)-Ot}px;width:${u+At*2}px;height:${h.length*d+Ot*2}px;padding:${Ot-Ps}px ${At-Ps}px;border:${Ps}px solid ${W(r.textColor,.3)};border-radius:4px;background:transparent;color:${i?.color??r.textColor};font:${a};line-height:${d}px;white-space:pre;`}measureTextWidth(e,t){let n=this.ctx;if(!n)return 120;let r=n.font;n.font=t;let i=Math.max(8,...e.map(o=>n.measureText(o).width));return n.font=r,i}layoutTextEditor(){let e=this.textEditor;if(!e)return;let t=this.editedDrawing(e.id),n=t&&this.inlineEditorCss(t,e.el.value);n&&(e.el.style.cssText=n);}closeTextEditor(){let e=this.textEditor;e&&(this.textEditor=null,e.el.remove(),this.render());}cursorAt(e,t){return this.eraserMode?"pointer":this.interaction.cursorAt(e,t)}dblClick(e,t){if(this.interaction.finishPlacing(true))return true;let n=dn(this.drawings,e,t,this.deps.projector(),6);return Es(n)?(this.editTextInline(n.id),true):n!=null}handleKey(e){if(e.key==="Escape")return this.textEditor?(this.finishTextEditor(false),true):this.popup.isOpen()?(this.clearSelection(),true):this.interaction.cancel()?true:this.selectedIds.size?(this.clearSelection(),true):false;if(e.key==="Enter"&&this.interaction.finishPlacing(false))return true;let t=Xc(e,{hasSelection:this.selectedIds.size>0,hasTarget:this.selectedIds.size>0||this.hoveredId!=null,editingText:Kc(e.target)});if(!t)return false;switch(t.kind){case "undo":if(!this.historyChords)return false;this.emit({kind:"undo"});break;case "redo":if(!this.historyChords)return false;this.emit({kind:"redo"});break;case "copy":this.emit({kind:"copy",ids:this.selectionIds()});break;case "paste":this.emit({kind:"paste"});break;case "duplicate":this.emit({kind:"duplicate",ids:this.selectionIds()});break;case "delete":{let n=this.selectedIds.size?this.selectionIds():this.hoveredId?[this.hoveredId]:[];n.length&&(this.popup.close(),this.emit({kind:"delete",ids:n}));break}case "nudge":this.nudgeSelection(t.dx,t.dy);break}return true}selectionIds(){return [...this.selectedIds]}nudgeSelection(e,t){let n=this.deps.projector(),r=[];for(let i of this.drawings){if(!this.selectedIds.has(i.id)||i.locked)continue;let o=i.anchors.map(l=>{let c=n.yOf(l.price,i.paneId);return c==null?{time:l.time,price:l.price}:n.pxToPoint(n.xOf(l.time)+e,c+t,i.paneId)}),a=i.serialize();a.anchors=o,r.push(a);}r.length===1?this.emit({kind:"edit",doc:r[0]}):r.length>1&&this.emit({kind:"edit-many",docs:r});}setTheme(e){this.popup.setTheme(e),this.toolbar.setTheme(e),this.render();}onResize(){this.finishTextEditor(true),this.popup.close(),this.render();}isInterleaved(e){return qc(e.zIndex,this.lastBounds.get(e.paneId)??[])!==null}invalidateSlices(){(this.sliced.size>0||this.drawings.some(e=>this.isInterleaved(e)))&&this.deps.requestDataPaint();}prepareSlices(e){this.sliced.clear(),this.lastBounds=new Map(e.map(a=>[a,this.deps.seriesBoundaries(a)]));let t=new Map,n=this.deps.dpr(),r=this.deps.projector(),i=this.deps.theme(),o=new Map;for(let a of this.drawings){if(!a.visible)continue;let l=qc(a.zIndex,this.lastBounds.get(a.paneId)??[]);if(l===null)continue;let c=`${a.paneId}|${l}`,d=o.get(c);d?d.drawings.push(a):o.set(c,{paneId:a.paneId,beforeZ:l,drawings:[a]}),this.sliced.add(a.id);}for(let[a,{paneId:l,beforeZ:c,drawings:d}]of o){let h=this.sliceCache.get(a);h||(h=document.createElement("canvas"),this.sliceCache.set(a,h)),(h.width!==this.canvas.width||h.height!==this.canvas.height)&&(h.width=this.canvas.width,h.height=this.canvas.height);let u=h.getContext("2d");if(!u)continue;u.setTransform(n,0,0,n,0,0),u.clearRect(0,0,h.width/n,h.height/n),this.painter.paintAll(u,d,r,i,vb);let p=t.get(l)??[];p.push({beforeZ:c,canvas:h}),t.set(l,p);}for(let a of [...this.sliceCache.keys()])o.has(a)||this.sliceCache.delete(a);for(let a of t.values())a.sort((l,c)=>l.beforeZ-c.beforeZ);return t}render(){let e=this.ctx;if(!e)return;let t=this.deps.dpr();e.setTransform(t,0,0,t,0,0),e.clearRect(0,0,this.canvas.width/t,this.canvas.height/t);let n=this.deps.projector(),r=this.textEditor?this.editedDrawing(this.textEditor.id):null,i={selected:this.selectedIds,hovered:this.hoveredId,dragged:this.interaction.activeDragId(),mutedLabel:r instanceof He?r.id:null};this.painter.paintAll(e,this.drawings.filter(d=>!this.isInterleaved(d)),n,this.deps.theme(),i),this.painter.paintHighlights(e,this.drawings.filter(d=>this.isInterleaved(d)),n,ws(i)),this.layoutTextEditor();let o=this.interaction.ghost();o&&this.painter.paintGhost(e,o,n,this.deps.theme()),this.externalGhost&&this.painter.paintGhost(e,this.externalGhost,n,this.deps.theme()),this.emitDraft(o);let a=this.interaction.placingMarkers(n);a&&this.painter.paintHandles(e,a);let l=this.interaction.snapMarker(),c=l?n.yOf(l.point.price,l.paneId):null;l&&c!=null&&this.painter.paintSnapRing(e,n.xOf(l.point.time),c,this.deps.theme()),this.measure.isActive()&&this.measure.paint(e,n,this.deps.theme());}destroy(){this.closeTextEditor(),this.popup.destroy(),this.toolbar.destroy(),this.intentCb=null,this.drawings=[];}clearSelection(){this.popup.close(),this.selectedIds.size&&this.emit({kind:"select",ids:[]}),this.render();}openSettingsById(e,t,n){let r=this.drawings.find(a=>a.id===e);if(!r)return;let i=()=>this.drawings.find(a=>a.id===e);this.emit({kind:"select",ids:[e]}),this.emit({kind:"settings",id:e});let o=r.bounds(this.deps.projector());this.popup.open(r,o,{resolve:()=>i()??null,patch:a=>{let l=i();l&&(l.applySettings(a),this.render(),this.emit({kind:"edit",doc:l.serialize()}));},setLocked:a=>{let l=i();l&&(l.locked=a,this.emit({kind:"edit",doc:l.serialize()}));},reorder:a=>this.emit({kind:"reorder",id:e,to:a}),resetSettings:()=>{let a=i();a&&($o(a),this.render(),this.emit({kind:"edit",doc:a.serialize()}),this.openSettingsById(e,0,0));},remove:()=>{this.closeTextEditor(),this.popup.close(),this.emit({kind:"delete",ids:[e]});}},()=>this.clearSelection());}emitDraft(e){let t=e?JSON.stringify({t:e.type,p:e.paneId,a:e.anchors,s:e.style,x:e.text}):null;t!==this.lastDraftKey&&(this.lastDraftKey=t,this.intentCb?.({kind:"draft",doc:e?e.serialize():null}));}emit(e){if(e.kind==="create"){e.doc.text&&e.doc.text.color===void 0&&(e.doc.text={...e.doc.text,color:be(this.deps.theme().background)});let t=new Set(this.drawings.map(n=>n.id));this.intentCb?.(e),setTimeout(()=>{let n=this.drawings.find(r=>!t.has(r.id));n&&(this.openSettingsById(n.id,0,0),Es(n)&&this.editTextInline(n.id));},0);return}this.intentCb?.(e);}};function Zc(s,e,t,n){return {xOf:r=>s.timeToX(r),yOf:(r,i)=>{let o=e(i);return o?s.priceToY(r,o.scale,o.bounds):null},pxToPoint:(r,i,o)=>{let a=e(o),l=s.logicalToTime(s.xToLogical(r)),c=a?s.yToPrice(i,a.scale,a.bounds):0;return {time:l,price:c}},paneIdAtY:t,paneRect:r=>{let i=e(r);return i?{top:i.bounds.top,height:i.collapsed?0:i.bounds.height}:null},barsBetween:(r,i)=>Math.abs(s.timeToLogical(i)-s.timeToLogical(r)),barsInRange:n?(r,i)=>n(r,i):void 0,width:s.width,height:s.height}}var Jc=2/7,Qc=1/7;function ks(s,e,t,n,r,i,o=false,a=()=>0){let l=1/0,c=-1/0,d=u=>{u!=null&&Number.isFinite(u)&&(u<l&&(l=u),u>c&&(c=u));};if(t)for(let u=n;u<=r;u+=1){let p=e[u];p&&(d(p.high),d(p.low));}for(let u of s){let p=a(u.id);for(let m of u.series)if(m.kind==="candle"||m.kind==="bar")for(let f=n;f<=r;f+=1){let b=m.bars[f-p];b&&(d(b.high),d(b.low));}else if(le(m)){for(let f=n;f<=r;f+=1)d(m.points[f-p]?.value);m.kind==="histogram"||m.kind==="columns"?d(m.style?.base??0):m.style?.base!=null&&d(m.style.base);}for(let m of u.priceLines)d(m.price);}if(i&&(d(i.min),d(i.max)),l===1/0||c===-1/0)return {min:0,max:1};if(l===c){let u=Math.abs(l)*.1||1;return {min:l-u,max:c+u,log:o&&l-u>0}}if(o&&l>0){let u=Math.log(l),p=Math.log(c),m=p-u;return {min:Math.exp(u-m*Qc),max:Math.exp(p+m*Jc),log:true}}let h=c-l;return {min:l-h*Qc,max:c+h*Jc}}function ed(s,e,t,n){if(t<=0&&n<=0)return s;let r=e-t-n;if(!(r>=8))return s;if(s.log&&s.min>0&&s.max>s.min){let o=Math.log(s.min),a=Math.log(s.max),l=(a-o)/r;return {...s,min:Math.exp(o-n*l),max:Math.exp(a+t*l)}}if(s.max<=s.min)return s;let i=(s.max-s.min)/r;return {...s,min:s.min-n*i,max:s.max+t*i}}function td(s,e){if(s.log&&s.min>0&&s.max>s.min){let r=Math.log(s.min),i=Math.log(s.max),o=(r+i)/2,a=(i-r)/2*e;return {min:Math.exp(o-a),max:Math.exp(o+a),log:true}}let t=(s.min+s.max)/2,n=(s.max-s.min)/2*e;return {min:t-n,max:t+n,log:s.log}}function nd(s,e,t){if(t<=0)return {...s};if(s.log&&s.min>0&&s.max>s.min){let r=Math.log(s.min),i=Math.log(s.max),o=(i-r)*e/t;return {min:Math.exp(r+o),max:Math.exp(i+o),log:true}}let n=(s.max-s.min)*e/t;return {min:s.min+n,max:s.max+n,log:s.log}}function rd(s,e,t=24){let{combinedTop:n,combinedHeight:r,combinedWeight:i,startBoundaryY:o}=s,a=Math.min(t,r/2),l=n+a,c=n+r-a,h=Math.max(l,Math.min(c,o+e))-n,u=r>0?i*(h/r):i/2;return {above:u,below:i-u}}function id(s,e,t,n){let{i0:r,i1:i,xOf:o,halfW:a,bottomY:l,maxH:c,maxVol:d}=t;if(!(d<=0||c<=0)){s.globalAlpha=.5;for(let h=r;h<=i;h+=1){let u=e[h],p=u?.volume;if(u==null||p==null||!(p>0))continue;let m=Math.max(1,p/d*c);s.fillStyle=u.close>=u.open?n.up:n.down,s.fillRect(o(h)-a,l-m,a*2,m);}s.globalAlpha=1;}}var Is=.96;function yb(s){return Math.max(.5,Math.floor(s*.7)/2)}var go=class{constructor(){this.canvas=null;this.ctx=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}destroy(){this.canvas=null,this.ctx=null;}render(e){let t=this.ctx,n=this.canvas;if(!t||!n)return;let{bars:r,data:i,visible:o,coords:a,bounds:l,fillPane:c}=e,d=a.dpr;if(t.setTransform(d,0,0,d,0,0),t.clearRect(0,0,n.width/d,n.height/d),!i||!o||r.length===0||l.height<=0)return;let h=a.visibleLogicalRange(),u=Math.max(0,Math.floor(h.from)),p=Math.min(r.length-1,Math.ceil(h.to));if(u>p)return;let m=0;for(let f=u;f<=p;f+=1){let b=r[f]?.volume;b!=null&&b>m&&(m=b);}m<=0||(t.save(),t.beginPath(),t.rect(0,l.top,a.width,l.height),t.clip(),id(t,r,{i0:u,i1:p,xOf:f=>a.logicalToX(f),halfW:yb(a.bodySpacing()),bottomY:l.top+l.height,maxH:l.height*(c?Is:i.heightFrac),maxVol:m},{up:i.upColor,down:i.downColor}),t.restore());}};var Rs=new Map;function xb(s){Rs.set(s.id,s);}function wb(s){Rs.delete(s);}function Ds(){return [...Rs.values()]}var od='<svg viewBox="0 0 45 40" aria-hidden="true"><g fill="currentColor"><path d="m40.25 38 4.58-7.998L28.802 2l-16.03 28 9.16-.001 6.87-12z"/><path d="M34.525 32.002 9.33 31.997 27.655 0h-9.158L.18 31.993 4.759 40h34.347z"/></g></svg>',sd='<svg viewBox="0 0 964 252" aria-hidden="true"><path fill="currentColor" fill-rule="evenodd" d="M 614 94.500 L 614 189 633.500 189 L 653 189 653 94.500 L 653 0 633.500 0 L 614 0 614 94.500 M 0 97.500 L 0 189 63.023 189 L 126.045 189 125.773 170.750 L 125.500 152.500 84.250 152.239 L 43 151.978 43 78.989 L 43 6 21.500 6 L 0 6 0 97.500 M 450.387 96.451 C 421.871 146.253, 398.306 186.994, 398.020 186.987 C 397.423 186.972, 362 124.724, 362 123.691 C 362 123.316, 370.100 108.818, 380 91.472 C 389.900 74.127, 398 59.500, 398 58.968 C 398 58.380, 391.007 58, 380.210 58 L 362.420 58 348.060 83.138 C 334.400 107.052, 333.637 108.160, 332.399 105.888 C 331.682 104.575, 325.287 93.375, 318.187 81 L 305.277 58.500 287.139 58.227 C 277.162 58.078, 269 58.186, 269 58.469 C 269 58.751, 277.154 73.274, 287.120 90.741 C 297.086 108.209, 305.261 122.983, 305.287 123.574 C 305.312 124.164, 297.318 138.789, 287.522 156.074 C 277.725 173.358, 269.524 187.838, 269.296 188.250 C 269.068 188.662, 276.977 189, 286.870 189 L 304.859 189 319.163 163.959 C 331.321 142.674, 333.647 139.165, 334.670 140.563 C 335.331 141.468, 341.864 152.737, 349.186 165.606 L 362.500 189.003 402.442 188.752 L 442.384 188.500 472.080 136.695 C 488.413 108.203, 501.939 84.729, 502.138 84.531 C 502.337 84.333, 516 107.757, 532.500 136.583 L 562.500 188.994 584.750 188.997 C 596.987 188.999, 607 188.854, 607 188.675 C 607 188.319, 503.014 6.686, 502.532 6.201 C 502.369 6.037, 478.904 46.649, 450.387 96.451 M 717.500 55.017 C 697.175 57.389, 680.641 68.752, 672.036 86.264 C 665.866 98.818, 663.840 108.024, 663.840 123.500 C 663.840 133.409, 664.328 138.355, 665.892 144.300 C 672.076 167.810, 689.191 184.757, 711.529 189.489 C 730.549 193.518, 747.264 189.540, 761.282 177.648 C 764.944 174.542, 768.178 172, 768.470 172 C 769.345 172, 769.030 185.018, 767.979 192.285 C 765.618 208.613, 755.148 218.672, 738.473 220.632 C 732.586 221.324, 723.136 219.599, 717.709 216.843 C 712.693 214.295, 706.636 207.946, 703.972 202.443 C 702.789 199.999, 701.749 198, 701.661 198.001 C 700.201 198.007, 665.596 205.071, 665.230 205.437 C 664.326 206.341, 669.156 218.313, 672.607 223.721 C 682.146 238.672, 700.008 248.257, 723.500 251.033 C 758.132 255.124, 788.930 241.875, 800.287 218 C 806.923 204.047, 807 203.001, 807 126.542 L 807 58 788.500 58 L 770 58 770 66.500 C 770 71.175, 769.641 75, 769.203 75 C 768.765 75, 766.627 73.142, 764.453 70.872 C 752.805 58.708, 735.614 52.903, 717.500 55.017 M 878.500 55.031 C 850.107 59.412, 830.755 75.064, 822.285 100.500 C 819.905 107.644, 819.614 110.051, 819.565 123 C 819.501 139.581, 820.786 145.825, 826.763 158 C 832.104 168.880, 842.842 179.424, 854.077 184.822 C 867.651 191.343, 873.132 192.462, 891.500 192.462 C 909.868 192.462, 915.349 191.343, 928.923 184.822 C 944.653 177.265, 956.667 162.306, 961.710 144 C 963.074 139.048, 963.481 134.047, 963.418 123 C 963.346 110.140, 963.038 107.595, 960.694 100.500 C 953.325 78.193, 936.695 62.854, 913.500 56.969 C 904.262 54.625, 887.240 53.682, 878.500 55.031 M 134.015 102.750 C 134.027 139.250, 134.310 148.689, 135.549 153.947 C 141.139 177.663, 159.815 193, 183.105 193 C 196.453 193, 210.163 186.171, 217.936 175.650 C 219.826 173.093, 221.738 171, 222.186 171 C 222.634 171, 223 175.050, 223 180 L 223 189 242.507 189 L 262.014 189 261.757 123.750 L 261.500 58.500 242.500 58.500 L 223.500 58.500 223 99.500 C 222.513 139.406, 222.441 140.610, 220.289 144.634 C 209.729 164.377, 183.014 164.880, 174.299 145.500 C 172.677 141.895, 172.469 137.382, 172.190 99.750 L 171.880 58 152.940 58 L 134 58 134.015 102.750 M 729.932 87.998 C 719.311 89.821, 710.155 97.164, 705.141 107.880 C 702.851 112.772, 702.510 114.798, 702.505 123.521 C 702.500 132.834, 702.732 134.014, 705.787 140.218 C 709.761 148.290, 715.989 154.097, 723.853 157.063 C 731.409 159.912, 744.359 159.466, 750.795 156.136 C 767.289 147.601, 774.103 127.713, 767.019 108.780 C 761.433 93.851, 746.051 85.232, 729.932 87.998 M 883.972 88.348 C 865.749 92.310, 854.873 109.966, 858.119 130.316 C 860.933 147.963, 872.346 158.830, 889.084 159.799 C 900.714 160.472, 906.867 158.234, 914.650 150.497 C 919.856 145.323, 921.123 143.340, 922.900 137.587 C 925.412 129.456, 925.655 118.570, 923.489 111.275 C 918.479 94.405, 901.478 84.541, 883.972 88.348"/></svg>';var Sb="https://luxalgo.com/vela",ad="vela-attribution-styles",Cb=`
247
+ .vela-dtb-flyout::-webkit-scrollbar-thumb:hover{background:var(--vela-fg-muted);}`;}var ib=$("cursor"),ob=$("ruler"),Gc=$("chevrons-left"),sb=$("chevrons-right"),ab=$("magnet"),lb=$("pen-lock"),cb=$("pen-sync"),db=$("eraser"),hb=$("chevron-right"),ub=$("check"),pb=$("star"),mb=$("star-filled");function fo(s){return s.replace("<svg ",'<svg width="100%" height="100%" ')}function Yc(s,e=18){return s?`<span style="width:${e}px;height:${e}px;display:flex;align-items:center;justify-content:center;">${fo(s)}</span>`:""}function mo(s,e=18){return `<span class="vela-dtb-hit">${Yc(s,e)}</span>`}function fb(s){return `<span class="vela-dtb-hit vela-dtb-hit--arrow">${Yc(s,11)}</span>`}function Xc(s){return `${s>=0?"+":""}${s.toFixed(2)}`}var bb=q,gb=X,vb=3,bo=class{constructor(){this.state="idle";this.start=null;this.end=null;this.pressX=0;this.pressY=0;}isActive(){return this.state!=="idle"}isFinished(){return this.state==="finished"}down(e,t){if(this.state==="measuring"){this.end={x:e,y:t},this.state="finished";return}this.start={x:e,y:t},this.end={x:e,y:t},this.pressX=e,this.pressY=t,this.state="measuring";}move(e,t){this.state==="measuring"&&(this.end={x:e,y:t});}up(e,t){this.state==="measuring"&&Math.hypot(e-this.pressX,t-this.pressY)>vb&&(this.end={x:e,y:t},this.state="finished");}clear(){this.state="idle",this.start=null,this.end=null;}paint(e,t,n){if(!this.start||!this.end)return;let{x:r,y:i}=this.start,{x:o,y:a}=this.end,l=t.paneIdAtY(i)??t.paneIdAtY(a);if(!l)return;let c=t.pxToPoint(r,i,l),d=t.pxToPoint(o,a,l),h=d.price-c.price,u=c.price!==0?h/c.price*100:0,p=t.barsBetween?Math.round(t.barsBetween(c.time,d.time)):null,m=h>=0,f=m?bb:gb,b=Math.min(r,o),g=Math.max(r,o),v=Math.min(i,a),y=Math.max(i,a),x=(r+o)/2,S=(i+a)/2;e.save(),e.globalAlpha=.12,e.fillStyle=f,e.fillRect(b,v,g-b,y-v),e.globalAlpha=1,e.strokeStyle=f,e.lineWidth=1,e.setLineDash([4,4]),e.beginPath(),e.moveTo(x,i),e.lineTo(x,a),e.moveTo(r,S),e.lineTo(o,S),e.stroke(),e.setLineDash([]);let C=m?v:y,T=m?1:-1;e.fillStyle=f,e.beginPath(),e.moveTo(x,C),e.lineTo(x-5,C+T*7),e.lineTo(x+5,C+T*7),e.closePath(),e.fill(),e.restore(),this.paintLabel(e,t,n,x,v,y,f,[`${Xc(h)} (${Xc(u)}%)`,p!=null?`${p} bars \xB7 ${Ln(d.time-c.time)}`:Ln(d.time-c.time)]);}paintLabel(e,t,n,r,i,o,a,l){e.save(),e.font=`12px ${n.fontFamily}`;let c=Math.max(...l.map(f=>e.measureText(f).width))+16,d=16,h=l.length*d+8,u=o+8;u+h>t.height&&(u=i-h-8);let p=r-c/2;e.fillStyle=n.background,e.strokeStyle=a,e.lineWidth=1,e.beginPath(),e.roundRect(p,u,c,h,4),e.fill(),e.stroke(),e.fillStyle=n.textColor,e.textAlign="center",e.textBaseline="middle",l.forEach((f,b)=>e.fillText(f,r,u+8+d/2+b*d)),e.restore();}};function Kc(s,e){if(e.editingText)return null;if(s.ctrlKey||s.metaKey)switch(s.key.toLowerCase()){case "z":return s.shiftKey?{kind:"redo"}:{kind:"undo"};case "y":return {kind:"redo"};case "c":return e.hasSelection?{kind:"copy"}:null;case "v":return {kind:"paste"};case "d":return e.hasSelection?{kind:"duplicate"}:null;default:return null}if(s.key==="Delete"||s.key==="Backspace")return e.hasTarget?{kind:"delete"}:null;if(e.hasSelection){let n=s.shiftKey?10:1;switch(s.key){case "ArrowLeft":return {kind:"nudge",dx:-n,dy:0};case "ArrowRight":return {kind:"nudge",dx:n,dy:0};case "ArrowUp":return {kind:"nudge",dx:0,dy:-n};case "ArrowDown":return {kind:"nudge",dx:0,dy:n}}}return null}function jc(s){let e=s;return !e||!e.tagName?false:e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable===true}var qc="Enter Text",yb=8,Ps=1;function Es(s){return s instanceof Ie||s instanceof He}var xb={};function Zc(s,e){return e.length===0||s>e[e.length-1]?null:e.find(t=>t>=s)}var go=class{constructor(e,t,n,r){this.toolbarHost=e;this.overlayHost=t;this.canvas=n;this.deps=r;this.ctx=null;this.drawings=[];this.sliced=new Set;this.sliceCache=new Map;this.lastBounds=new Map;this.selectedIds=new Set;this.hoveredId=null;this.activeTool=null;this.intentCb=null;this.externalGhost=null;this.lastDraftKey=null;this.measure=new bo;this.toolbarVisible=false;this.toolbarCollapsed=false;this.mobileLayout=false;this.historyChords=true;this.measureMode=false;this.eraserMode=false;this.erasing=false;this.textEditor=null;this.painter=new ho;this.ctx=n.getContext("2d"),this.popup=new po(t,r.theme()),this.toolbar=new rr(e,r.theme(),i=>this.emit({kind:"arm",type:i}),i=>{this.deps.setSnapMode(i),this.emit({kind:"snap-mode",mode:i});},()=>this.withModeIntent(()=>this.toggleMeasure()),()=>this.withModeIntent(()=>this.toggleEraser()),(i,o)=>this.emit({kind:"favorite",type:i,on:o}),i=>this.emit({kind:"stay-mode",on:i}),{onCollapse:i=>{this.toolbarCollapsed=i,this.syncToolbarGutter();}}),this.interaction=new uo({projector:()=>this.deps.projector(),activeTool:()=>this.activeTool,drawings:()=>this.drawings,hoveredId:()=>this.hoveredId,selectedIds:()=>this.selectedIds,emit:i=>this.emit(i),changed:()=>{this.invalidateSlices(),this.render();},openSettings:(i,o,a)=>this.openSettingsById(i,o,a),snap:(i,o,a,l)=>this.deps.snap(i,o,a,l),lastStyle:()=>this.activeToolStyle});}setToolbar(e){this.toolbar.setDefinition(e);}showToolbar(e){this.toolbarVisible=e,this.toolbar.setVisible(e&&!this.mobileLayout),this.syncToolbarGutter();}setLayoutMode(e){this.mobileLayout=e==="mobile",this.toolbar.setVisible(this.toolbarVisible&&!this.mobileLayout),this.syncToolbarGutter();}syncToolbarGutter(){let e=this.toolbarVisible&&!this.mobileLayout;this.deps.setToolbarGutter(e?this.toolbarCollapsed?Ls:Ms:0);}setExternalGhost(e){this.externalGhost=e?Fe(e):null,this.render();}syncDrawings(e){this.drawings=e.map(t=>Fe(t)).filter(t=>t!=null),this.textEditor&&!this.editedDrawing(this.textEditor.id)&&this.closeTextEditor(),this.invalidateSlices(),this.render(),this.deps.requestScaleUpdate();}stackRange(e){let t=this.deps.seriesBoundaries(e);return {front:Math.max(0,...t),back:Math.min(0,...t),price:this.deps.priceZ(e)??void 0}}priceRangeForPane(e,t,n){let r=1/0,i=-1/0;for(let o of this.drawings){if(!o.visible||o.paneId!==e)continue;let a=o.timeExtent();if(a&&(a.max<t||a.min>n))continue;let l=o.priceRange();l&&(l.min<r&&(r=l.min),l.max>i&&(i=l.max));}return r<=i?{min:r,max:i}:null}setActiveTool(e,t){e!=null&&(this.finishTextEditor(true),this.withModeIntent(()=>{this.measureMode&&this.exitMeasure(),this.eraserMode&&this.exitEraser();})),this.activeTool=e,this.activeToolStyle=t,this.toolbar.setActiveTool(e),e==null?this.interaction.onToolCleared():this.clearSelection(),this.render();}setFavorites(e){this.toolbar.setFavorites(e);}setToolShortcuts(e){this.toolbar.setShortcuts(e);}setSnapMode(e){this.deps.setSnapMode(e),this.toolbar.setMagnetMode(e);}setStayMode(e){this.toolbar.setStayMode(e);}setMode(e){this.withModeIntent(()=>{e==="measure"?this.measureMode||this.toggleMeasure():e==="eraser"?this.eraserMode||this.toggleEraser():(this.measureMode&&this.exitMeasure(),this.eraserMode&&this.exitEraser());});}modeOf(){return this.measureMode?"measure":this.eraserMode?"eraser":null}withModeIntent(e){let t=this.modeOf();e();let n=this.modeOf();n!==t&&this.emit({kind:"mode",mode:n});}setSelection(e){this.selectedIds=new Set(e),this.render();}openSettings(e){this.openSettingsById(e,0,0);}onDrawingIntent(e){return this.intentCb=e,()=>{this.intentCb===e&&(this.intentCb=null);}}claim(e,t){return this.measureMode||this.eraserMode?true:this.interaction.claim(e,t)}deleteAt(e,t){let n=dn(this.drawings,e,t,this.deps.projector(),6);return !n||n.locked?false:(this.popup.close(),this.emit({kind:"delete",ids:[n.id]}),true)}beginMeasureAt(e,t){return this.measureMode||this.eraserMode||this.activeTool!=null?false:(this.withModeIntent(()=>this.toggleMeasure()),this.measure.down(e,t),this.render(),true)}clearTransient(){this.textEditor&&this.finishTextEditor(true),this.measure.isFinished()&&(this.measure.clear(),this.render());}pointerDown(e,t,n="off",r=false){if(this.eraserMode){this.erasing=true,this.deleteAt(e,t);return}if(this.measureMode){this.measure.down(e,t),this.measure.isFinished()&&this.withModeIntent(()=>this.exitMeasure(false)),this.render();return}this.interaction.down(e,t,n,r);}pointerMove(e,t,n="off",r=false){if(this.eraserMode){this.erasing&&this.deleteAt(e,t);return}if(this.measureMode){this.measure.move(e,t),this.render();return}this.interaction.move(e,t,n,r),this.updateHover(e,t);}updateHover(e,t){let n=null;this.activeTool==null&&!this.interaction.isPlacing()&&!this.interaction.isDragging()&&(n=dn(this.drawings,e,t,this.deps.projector(),6)?.id??null),n!==this.hoveredId&&(this.hoveredId=n,this.render());}pointerUp(e,t){if(this.eraserMode){this.erasing=false;return}if(this.measureMode){this.measure.up(e,t),this.measure.isFinished()&&this.withModeIntent(()=>this.exitMeasure(false)),this.render();return}this.interaction.up(e,t);}toggleMeasure(){if(this.measureMode){this.exitMeasure();return}this.eraserMode&&this.exitEraser(),this.measure.clear(),this.measureMode=true,this.emit({kind:"arm",type:null}),this.clearSelection(),this.toolbar.setMeasureActive(true),this.render();}toggleEraser(){if(this.eraserMode){this.exitEraser();return}this.measureMode&&this.exitMeasure(),this.eraserMode=true,this.erasing=false,this.emit({kind:"arm",type:null}),this.clearSelection(),this.toolbar.setEraserActive(true),this.render();}exitEraser(){this.eraserMode=false,this.erasing=false,this.toolbar.setEraserActive(false),this.render();}exitMeasure(e=true){this.measureMode=false,e&&this.measure.clear(),this.toolbar.setMeasureActive(false),this.render();}editTextInline(e){let t=this.editedDrawing(e);if(!t)return;this.closeTextEditor();let n=t.text?.value??"",r=this.inlineEditorCss(t,n);if(!r)return;let i=document.createElement("textarea");i.value=n,i.placeholder=qc,i.spellcheck=false,i.style.cssText=r;let o=()=>{this.editedDrawing(e)?.applySettings({"text.value":i.value}),this.render();};i.addEventListener("input",o),i.addEventListener("pointerdown",a=>a.stopPropagation()),i.addEventListener("keydown",a=>{if(a.stopPropagation(),a.key==="Enter"&&!a.ctrlKey&&!a.metaKey){a.preventDefault();let l=i.selectionStart;i.setRangeText(`
248
+ `,l,i.selectionEnd,"end"),o();}else a.key==="Enter"?(a.preventDefault(),this.finishTextEditor(true)):a.key==="Escape"&&(a.preventDefault(),this.finishTextEditor(false));}),i.addEventListener("blur",a=>{this.popup.contains(a.relatedTarget)?this.storeText(i.value):this.finishTextEditor(true);}),this.overlayHost.appendChild(i),this.textEditor={el:i,id:e,initial:n,stored:n},i.focus(),i.setSelectionRange(i.value.length,i.value.length);}storeText(e){let t=this.textEditor,n=t&&this.editedDrawing(t.id);!t||!n||(n.applySettings({"text.value":e}),e!==t.stored&&(t.stored=e,this.emit({kind:"edit",doc:n.serialize()})));}editedDrawing(e){let t=this.drawings.find(n=>n.id===e);return Es(t)?t:null}finishTextEditor(e){let t=this.textEditor;if(!t)return;let n=e?t.el.value:t.initial;this.closeTextEditor();let r=this.editedDrawing(t.id);r&&(r.applySettings({"text.value":n}),this.render(),r instanceof He&&n.trim()===""?(this.clearSelection(),this.emit({kind:"delete",ids:[r.id]})):n!==t.stored&&this.emit({kind:"edit",doc:r.serialize()}));}inlineEditorCss(e,t){let n=this.deps.projector(),r=this.deps.theme(),i=e.text,o=ce(i?.size??"normal"),a=`${i?.italic?"italic ":""}${i?.bold?"bold ":""}${o}px ${r.fontFamily}`,l="position:absolute;z-index:24;box-sizing:border-box;resize:none;overflow:hidden;margin:0;outline:none;pointer-events:auto;text-align:left;";if(e instanceof Ie){let p=e.box(n);if(!p)return null;let m=e.style.fillColor??r.background;return l+`left:${Math.round(p.x)}px;top:${Math.round(p.y)}px;width:${Math.round(p.w)}px;height:${Math.round(p.h)}px;padding:5px 8px;border-radius:5px;border:1px solid ${e.style.lineColor??r.borderColor};background:${yc(m,r.background,cn(m).alpha)};color:${i?.color??r.textColor};font:${a};`}let c=e.handlePoints(n)[0];if(!c)return null;let d=Ve(o),h=(t||qc).split(`
249
+ `),u=Math.ceil(this.measureTextWidth(h,a))+yb;return l+`left:${Math.round(c[0]+2)-At}px;top:${Math.round(c[1]+2-(d-o)/2)-Ot}px;width:${u+At*2}px;height:${h.length*d+Ot*2}px;padding:${Ot-Ps}px ${At-Ps}px;border:${Ps}px solid ${W(r.textColor,.3)};border-radius:4px;background:transparent;color:${i?.color??r.textColor};font:${a};line-height:${d}px;white-space:pre;`}measureTextWidth(e,t){let n=this.ctx;if(!n)return 120;let r=n.font;n.font=t;let i=Math.max(8,...e.map(o=>n.measureText(o).width));return n.font=r,i}layoutTextEditor(){let e=this.textEditor;if(!e)return;let t=this.editedDrawing(e.id),n=t&&this.inlineEditorCss(t,e.el.value);n&&(e.el.style.cssText=n);}closeTextEditor(){let e=this.textEditor;e&&(this.textEditor=null,e.el.remove(),this.render());}cursorAt(e,t){return this.eraserMode?"pointer":this.interaction.cursorAt(e,t)}cancelPlacement(){return this.interaction.isPlacing()?(this.interaction.cancel(),this.activeTool!=null&&this.emit({kind:"arm",type:null}),true):false}dblClick(e,t){if(this.interaction.finishPlacing(true))return true;let n=dn(this.drawings,e,t,this.deps.projector(),6);return Es(n)?(this.editTextInline(n.id),true):n!=null}handleKey(e){if(e.key==="Escape")return this.textEditor?(this.finishTextEditor(false),true):this.popup.isOpen()?(this.clearSelection(),true):this.interaction.cancel()?true:this.selectedIds.size?(this.clearSelection(),true):false;if(e.key==="Enter"&&this.interaction.finishPlacing(false))return true;let t=Kc(e,{hasSelection:this.selectedIds.size>0,hasTarget:this.selectedIds.size>0||this.hoveredId!=null,editingText:jc(e.target)});if(!t)return false;switch(t.kind){case "undo":if(!this.historyChords)return false;this.emit({kind:"undo"});break;case "redo":if(!this.historyChords)return false;this.emit({kind:"redo"});break;case "copy":this.emit({kind:"copy",ids:this.selectionIds()});break;case "paste":this.emit({kind:"paste"});break;case "duplicate":this.emit({kind:"duplicate",ids:this.selectionIds()});break;case "delete":{let n=this.selectedIds.size?this.selectionIds():this.hoveredId?[this.hoveredId]:[];n.length&&(this.popup.close(),this.emit({kind:"delete",ids:n}));break}case "nudge":this.nudgeSelection(t.dx,t.dy);break}return true}selectionIds(){return [...this.selectedIds]}nudgeSelection(e,t){let n=this.deps.projector(),r=[];for(let i of this.drawings){if(!this.selectedIds.has(i.id)||i.locked)continue;let o=i.anchors.map(l=>{let c=n.yOf(l.price,i.paneId);return c==null?{time:l.time,price:l.price}:n.pxToPoint(n.xOf(l.time)+e,c+t,i.paneId)}),a=i.serialize();a.anchors=o,r.push(a);}r.length===1?this.emit({kind:"edit",doc:r[0]}):r.length>1&&this.emit({kind:"edit-many",docs:r});}setTheme(e){this.popup.setTheme(e),this.toolbar.setTheme(e),this.render();}onResize(){this.finishTextEditor(true),this.popup.close(),this.render();}isInterleaved(e){return Zc(e.zIndex,this.lastBounds.get(e.paneId)??[])!==null}invalidateSlices(){(this.sliced.size>0||this.drawings.some(e=>this.isInterleaved(e)))&&this.deps.requestDataPaint();}prepareSlices(e){this.sliced.clear(),this.lastBounds=new Map(e.map(a=>[a,this.deps.seriesBoundaries(a)]));let t=new Map,n=this.deps.dpr(),r=this.deps.projector(),i=this.deps.theme(),o=new Map;for(let a of this.drawings){if(!a.visible)continue;let l=Zc(a.zIndex,this.lastBounds.get(a.paneId)??[]);if(l===null)continue;let c=`${a.paneId}|${l}`,d=o.get(c);d?d.drawings.push(a):o.set(c,{paneId:a.paneId,beforeZ:l,drawings:[a]}),this.sliced.add(a.id);}for(let[a,{paneId:l,beforeZ:c,drawings:d}]of o){let h=this.sliceCache.get(a);h||(h=document.createElement("canvas"),this.sliceCache.set(a,h)),(h.width!==this.canvas.width||h.height!==this.canvas.height)&&(h.width=this.canvas.width,h.height=this.canvas.height);let u=h.getContext("2d");if(!u)continue;u.setTransform(n,0,0,n,0,0),u.clearRect(0,0,h.width/n,h.height/n),this.painter.paintAll(u,d,r,i,xb);let p=t.get(l)??[];p.push({beforeZ:c,canvas:h}),t.set(l,p);}for(let a of [...this.sliceCache.keys()])o.has(a)||this.sliceCache.delete(a);for(let a of t.values())a.sort((l,c)=>l.beforeZ-c.beforeZ);return t}render(){let e=this.ctx;if(!e)return;let t=this.deps.dpr();e.setTransform(t,0,0,t,0,0),e.clearRect(0,0,this.canvas.width/t,this.canvas.height/t);let n=this.deps.projector(),r=this.textEditor?this.editedDrawing(this.textEditor.id):null,i={selected:this.selectedIds,hovered:this.hoveredId,dragged:this.interaction.activeDragId(),mutedLabel:r instanceof He?r.id:null};this.painter.paintAll(e,this.drawings.filter(d=>!this.isInterleaved(d)),n,this.deps.theme(),i),this.painter.paintHighlights(e,this.drawings.filter(d=>this.isInterleaved(d)),n,ws(i)),this.layoutTextEditor();let o=this.interaction.ghost();o&&this.painter.paintGhost(e,o,n,this.deps.theme()),this.externalGhost&&this.painter.paintGhost(e,this.externalGhost,n,this.deps.theme()),this.emitDraft(o);let a=this.interaction.placingMarkers(n);a&&this.painter.paintHandles(e,a);let l=this.interaction.snapMarker(),c=l?n.yOf(l.point.price,l.paneId):null;l&&c!=null&&this.painter.paintSnapRing(e,n.xOf(l.point.time),c,this.deps.theme()),this.measure.isActive()&&this.measure.paint(e,n,this.deps.theme());}destroy(){this.closeTextEditor(),this.popup.destroy(),this.toolbar.destroy(),this.intentCb=null,this.drawings=[];}clearSelection(){this.popup.close(),this.selectedIds.size&&this.emit({kind:"select",ids:[]}),this.render();}openSettingsById(e,t,n){let r=this.drawings.find(a=>a.id===e);if(!r)return;let i=()=>this.drawings.find(a=>a.id===e);this.emit({kind:"select",ids:[e]}),this.emit({kind:"settings",id:e});let o=r.bounds(this.deps.projector());this.popup.open(r,o,{resolve:()=>i()??null,patch:a=>{let l=i();l&&(l.applySettings(a),this.render(),this.emit({kind:"edit",doc:l.serialize()}));},setLocked:a=>{let l=i();l&&(l.locked=a,this.emit({kind:"edit",doc:l.serialize()}));},reorder:a=>this.emit({kind:"reorder",id:e,to:a}),resetSettings:()=>{let a=i();a&&($o(a),this.render(),this.emit({kind:"edit",doc:a.serialize()}),this.openSettingsById(e,0,0));},remove:()=>{this.closeTextEditor(),this.popup.close(),this.emit({kind:"delete",ids:[e]});}},()=>this.clearSelection());}emitDraft(e){let t=e?JSON.stringify({t:e.type,p:e.paneId,a:e.anchors,s:e.style,x:e.text}):null;t!==this.lastDraftKey&&(this.lastDraftKey=t,this.intentCb?.({kind:"draft",doc:e?e.serialize():null}));}emit(e){if(e.kind==="create"){e.doc.text&&e.doc.text.color===void 0&&(e.doc.text={...e.doc.text,color:ge(this.deps.theme().background)});let t=new Set(this.drawings.map(n=>n.id));this.intentCb?.(e),setTimeout(()=>{let n=this.drawings.find(r=>!t.has(r.id));n&&(this.openSettingsById(n.id,0,0),Es(n)&&this.editTextInline(n.id));},0);return}this.intentCb?.(e);}};function Jc(s,e,t,n){return {xOf:r=>s.timeToX(r),yOf:(r,i)=>{let o=e(i);return o?s.priceToY(r,o.scale,o.bounds):null},pxToPoint:(r,i,o)=>{let a=e(o),l=s.logicalToTime(s.xToLogical(r)),c=a?s.yToPrice(i,a.scale,a.bounds):0;return {time:l,price:c}},paneIdAtY:t,paneRect:r=>{let i=e(r);return i?{top:i.bounds.top,height:i.collapsed?0:i.bounds.height}:null},barsBetween:(r,i)=>Math.abs(s.timeToLogical(i)-s.timeToLogical(r)),barsInRange:n?(r,i)=>n(r,i):void 0,width:s.width,height:s.height}}var Qc=2/7,ed=1/7;function ks(s,e,t,n,r,i,o=false,a=()=>0){let l=1/0,c=-1/0,d=u=>{u!=null&&Number.isFinite(u)&&(u<l&&(l=u),u>c&&(c=u));};if(t)for(let u=n;u<=r;u+=1){let p=e[u];p&&(d(p.high),d(p.low));}for(let u of s){let p=a(u.id);for(let m of u.series)if(m.kind==="candle"||m.kind==="bar")for(let f=n;f<=r;f+=1){let b=m.bars[f-p];b&&(d(b.high),d(b.low));}else if(le(m)){for(let f=n;f<=r;f+=1)d(m.points[f-p]?.value);m.kind==="histogram"||m.kind==="columns"?d(m.style?.base??0):m.style?.base!=null&&d(m.style.base);}for(let m of u.priceLines)d(m.price);}if(i&&(d(i.min),d(i.max)),l===1/0||c===-1/0)return {min:0,max:1};if(l===c){let u=Math.abs(l)*.1||1;return {min:l-u,max:c+u,log:o&&l-u>0}}if(o&&l>0){let u=Math.log(l),p=Math.log(c),m=p-u;return {min:Math.exp(u-m*ed),max:Math.exp(p+m*Qc),log:true}}let h=c-l;return {min:l-h*ed,max:c+h*Qc}}function td(s,e,t,n){if(t<=0&&n<=0)return s;let r=e-t-n;if(!(r>=8))return s;if(s.log&&s.min>0&&s.max>s.min){let o=Math.log(s.min),a=Math.log(s.max),l=(a-o)/r;return {...s,min:Math.exp(o-n*l),max:Math.exp(a+t*l)}}if(s.max<=s.min)return s;let i=(s.max-s.min)/r;return {...s,min:s.min-n*i,max:s.max+t*i}}function nd(s,e){if(s.log&&s.min>0&&s.max>s.min){let r=Math.log(s.min),i=Math.log(s.max),o=(r+i)/2,a=(i-r)/2*e;return {min:Math.exp(o-a),max:Math.exp(o+a),log:true}}let t=(s.min+s.max)/2,n=(s.max-s.min)/2*e;return {min:t-n,max:t+n,log:s.log}}function rd(s,e,t){if(t<=0)return {...s};if(s.log&&s.min>0&&s.max>s.min){let r=Math.log(s.min),i=Math.log(s.max),o=(i-r)*e/t;return {min:Math.exp(r+o),max:Math.exp(i+o),log:true}}let n=(s.max-s.min)*e/t;return {min:s.min+n,max:s.max+n,log:s.log}}function id(s,e,t=24){let{combinedTop:n,combinedHeight:r,combinedWeight:i,startBoundaryY:o}=s,a=Math.min(t,r/2),l=n+a,c=n+r-a,h=Math.max(l,Math.min(c,o+e))-n,u=r>0?i*(h/r):i/2;return {above:u,below:i-u}}function od(s,e,t,n){let{i0:r,i1:i,xOf:o,halfW:a,bottomY:l,maxH:c,maxVol:d}=t;if(!(d<=0||c<=0)){s.globalAlpha=.5;for(let h=r;h<=i;h+=1){let u=e[h],p=u?.volume;if(u==null||p==null||!(p>0))continue;let m=Math.max(1,p/d*c);s.fillStyle=u.close>=u.open?n.up:n.down,s.fillRect(o(h)-a,l-m,a*2,m);}s.globalAlpha=1;}}var Is=.96;function wb(s){return Math.max(.5,Math.floor(s*.7)/2)}var vo=class{constructor(){this.canvas=null;this.ctx=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}destroy(){this.canvas=null,this.ctx=null;}render(e){let t=this.ctx,n=this.canvas;if(!t||!n)return;let{bars:r,data:i,visible:o,coords:a,bounds:l,fillPane:c}=e,d=a.dpr;if(t.setTransform(d,0,0,d,0,0),t.clearRect(0,0,n.width/d,n.height/d),!i||!o||r.length===0||l.height<=0)return;let h=a.visibleLogicalRange(),u=Math.max(0,Math.floor(h.from)),p=Math.min(r.length-1,Math.ceil(h.to));if(u>p)return;let m=0;for(let f=u;f<=p;f+=1){let b=r[f]?.volume;b!=null&&b>m&&(m=b);}m<=0||(t.save(),t.beginPath(),t.rect(0,l.top,a.width,l.height),t.clip(),od(t,r,{i0:u,i1:p,xOf:f=>a.logicalToX(f),halfW:wb(a.bodySpacing()),bottomY:l.top+l.height,maxH:l.height*(c?Is:i.heightFrac),maxVol:m},{up:i.upColor,down:i.downColor}),t.restore());}};function sd(s,e){return e==null?s:s==null?{...e}:{candleBodyScale:Rs(s.candleBodyScale,e.candleBodyScale),candleBodyAlpha:Rs(s.candleBodyAlpha,e.candleBodyAlpha),gridAlpha:Rs(s.gridAlpha,e.gridAlpha)}}function Rs(s,e){return s==null?e:e==null?s:Math.min(s,e)}var Ds=new Map;function Sb(s){Ds.set(s.id,s);}function Cb(s){Ds.delete(s);}function As(){return [...Ds.values()]}var ad='<svg viewBox="0 0 45 40" aria-hidden="true"><g fill="currentColor"><path d="m40.25 38 4.58-7.998L28.802 2l-16.03 28 9.16-.001 6.87-12z"/><path d="M34.525 32.002 9.33 31.997 27.655 0h-9.158L.18 31.993 4.759 40h34.347z"/></g></svg>',ld='<svg viewBox="0 0 964 252" aria-hidden="true"><path fill="currentColor" fill-rule="evenodd" d="M 614 94.500 L 614 189 633.500 189 L 653 189 653 94.500 L 653 0 633.500 0 L 614 0 614 94.500 M 0 97.500 L 0 189 63.023 189 L 126.045 189 125.773 170.750 L 125.500 152.500 84.250 152.239 L 43 151.978 43 78.989 L 43 6 21.500 6 L 0 6 0 97.500 M 450.387 96.451 C 421.871 146.253, 398.306 186.994, 398.020 186.987 C 397.423 186.972, 362 124.724, 362 123.691 C 362 123.316, 370.100 108.818, 380 91.472 C 389.900 74.127, 398 59.500, 398 58.968 C 398 58.380, 391.007 58, 380.210 58 L 362.420 58 348.060 83.138 C 334.400 107.052, 333.637 108.160, 332.399 105.888 C 331.682 104.575, 325.287 93.375, 318.187 81 L 305.277 58.500 287.139 58.227 C 277.162 58.078, 269 58.186, 269 58.469 C 269 58.751, 277.154 73.274, 287.120 90.741 C 297.086 108.209, 305.261 122.983, 305.287 123.574 C 305.312 124.164, 297.318 138.789, 287.522 156.074 C 277.725 173.358, 269.524 187.838, 269.296 188.250 C 269.068 188.662, 276.977 189, 286.870 189 L 304.859 189 319.163 163.959 C 331.321 142.674, 333.647 139.165, 334.670 140.563 C 335.331 141.468, 341.864 152.737, 349.186 165.606 L 362.500 189.003 402.442 188.752 L 442.384 188.500 472.080 136.695 C 488.413 108.203, 501.939 84.729, 502.138 84.531 C 502.337 84.333, 516 107.757, 532.500 136.583 L 562.500 188.994 584.750 188.997 C 596.987 188.999, 607 188.854, 607 188.675 C 607 188.319, 503.014 6.686, 502.532 6.201 C 502.369 6.037, 478.904 46.649, 450.387 96.451 M 717.500 55.017 C 697.175 57.389, 680.641 68.752, 672.036 86.264 C 665.866 98.818, 663.840 108.024, 663.840 123.500 C 663.840 133.409, 664.328 138.355, 665.892 144.300 C 672.076 167.810, 689.191 184.757, 711.529 189.489 C 730.549 193.518, 747.264 189.540, 761.282 177.648 C 764.944 174.542, 768.178 172, 768.470 172 C 769.345 172, 769.030 185.018, 767.979 192.285 C 765.618 208.613, 755.148 218.672, 738.473 220.632 C 732.586 221.324, 723.136 219.599, 717.709 216.843 C 712.693 214.295, 706.636 207.946, 703.972 202.443 C 702.789 199.999, 701.749 198, 701.661 198.001 C 700.201 198.007, 665.596 205.071, 665.230 205.437 C 664.326 206.341, 669.156 218.313, 672.607 223.721 C 682.146 238.672, 700.008 248.257, 723.500 251.033 C 758.132 255.124, 788.930 241.875, 800.287 218 C 806.923 204.047, 807 203.001, 807 126.542 L 807 58 788.500 58 L 770 58 770 66.500 C 770 71.175, 769.641 75, 769.203 75 C 768.765 75, 766.627 73.142, 764.453 70.872 C 752.805 58.708, 735.614 52.903, 717.500 55.017 M 878.500 55.031 C 850.107 59.412, 830.755 75.064, 822.285 100.500 C 819.905 107.644, 819.614 110.051, 819.565 123 C 819.501 139.581, 820.786 145.825, 826.763 158 C 832.104 168.880, 842.842 179.424, 854.077 184.822 C 867.651 191.343, 873.132 192.462, 891.500 192.462 C 909.868 192.462, 915.349 191.343, 928.923 184.822 C 944.653 177.265, 956.667 162.306, 961.710 144 C 963.074 139.048, 963.481 134.047, 963.418 123 C 963.346 110.140, 963.038 107.595, 960.694 100.500 C 953.325 78.193, 936.695 62.854, 913.500 56.969 C 904.262 54.625, 887.240 53.682, 878.500 55.031 M 134.015 102.750 C 134.027 139.250, 134.310 148.689, 135.549 153.947 C 141.139 177.663, 159.815 193, 183.105 193 C 196.453 193, 210.163 186.171, 217.936 175.650 C 219.826 173.093, 221.738 171, 222.186 171 C 222.634 171, 223 175.050, 223 180 L 223 189 242.507 189 L 262.014 189 261.757 123.750 L 261.500 58.500 242.500 58.500 L 223.500 58.500 223 99.500 C 222.513 139.406, 222.441 140.610, 220.289 144.634 C 209.729 164.377, 183.014 164.880, 174.299 145.500 C 172.677 141.895, 172.469 137.382, 172.190 99.750 L 171.880 58 152.940 58 L 134 58 134.015 102.750 M 729.932 87.998 C 719.311 89.821, 710.155 97.164, 705.141 107.880 C 702.851 112.772, 702.510 114.798, 702.505 123.521 C 702.500 132.834, 702.732 134.014, 705.787 140.218 C 709.761 148.290, 715.989 154.097, 723.853 157.063 C 731.409 159.912, 744.359 159.466, 750.795 156.136 C 767.289 147.601, 774.103 127.713, 767.019 108.780 C 761.433 93.851, 746.051 85.232, 729.932 87.998 M 883.972 88.348 C 865.749 92.310, 854.873 109.966, 858.119 130.316 C 860.933 147.963, 872.346 158.830, 889.084 159.799 C 900.714 160.472, 906.867 158.234, 914.650 150.497 C 919.856 145.323, 921.123 143.340, 922.900 137.587 C 925.412 129.456, 925.655 118.570, 923.489 111.275 C 918.479 94.405, 901.478 84.541, 883.972 88.348"/></svg>';var Tb="https://luxalgo.com/vela",cd="vela-attribution-styles",Mb=`
250
250
  .vela-attribution {
251
251
  text-decoration: none;
252
252
  display: flex;
@@ -307,5 +307,5 @@ void main() {
307
307
  [data-layout='mobile'] .vela-attribution .vela-attr-wordmark svg { height: 21px; }
308
308
  [data-vela-layout='mobile'] .vela-attribution:hover .vela-attr-wordmark,
309
309
  [data-layout='mobile'] .vela-attribution:hover .vela-attr-wordmark { transform: translateX(0); }
310
- `;function Tb(s){let e=s.getElementById(ad);e||(e=s.createElement("style"),e.id=ad,s.head.appendChild(e)),e.textContent=Cb;}function As(s){return xe(s)?"#ffffff":"#000000"}function Os(s,e){let t=xe(e);s.style.color=t?"#ffffff":"#000000",s.style.setProperty("--vela-attr-shadow",t?"rgba(0,0,0,0.45)":"rgba(255,255,255,0.55)");}function ld(s,e,t){let n=s.createElement("div");return n.className="vela-attribution-custom",Object.assign(n.style,{position:"absolute",zIndex:"6",pointerEvents:"auto",display:"flex",alignItems:"center",lineHeight:"1"}),n.style.color=As(t),n.innerHTML=e,n}function cd(s,e){Tb(s);let t=s.createElement("a");t.className="vela-attribution",t.href=Sb,t.target="_blank",t.rel="noopener",t.title="Charting by Vela",t.setAttribute("aria-label","Charting by Vela"),Object.assign(t.style,{position:"absolute",zIndex:"6",pointerEvents:"auto",cursor:"pointer"}),Os(t,e);let n=s.createElement("span");n.className="vela-attr-symbol",n.setAttribute("aria-hidden","true"),n.innerHTML=od;let r=s.createElement("span");return r.className="vela-attr-wordmark",r.innerHTML=sd,t.append(n,r),t}function vo(s){if(!s||s==="transparent")return false;let e=/rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*,\s*([\d.]+)\s*\)/.exec(s);return e?parseFloat(e[1])>.001:true}function dd(s,e,t){let n=s.borderTopLeftRadius,r=parseFloat(n)||0,i=n.endsWith("%")?r/100*Math.min(e,t):r;return Math.max(0,Math.min(i,Math.min(e,t)/2))}function Fs(s,e,t,n,r,i){s.beginPath(),i>0&&typeof s.roundRect=="function"?s.roundRect(e,t,n,r,i):s.rect(e,t,n,r);}function Mb(s){try{let e=s.ownerDocument.createElement("canvas");e.width=1,e.height=1;let t=e.getContext("2d");return t?(t.drawImage(s,0,0,1,1),e.toDataURL(),!0):!1}catch{return false}}function yo(s,e,t){let n=e.ownerDocument.defaultView;if(!n)return;s.save(),s.scale(t.dpr,t.dpr);let r=(c,d,h)=>{let u=c.textContent?.replace(/\s+/g," ").trim();if(!u)return;let p=c.ownerDocument.createRange();p.selectNodeContents(c);let m=p.getBoundingClientRect();m.width<=0||m.height<=0||(s.globalAlpha=h,s.fillStyle=d.color,s.font=`${d.fontStyle} ${d.fontWeight} ${d.fontSize} ${d.fontFamily}`,s.textBaseline="middle",s.textAlign="left",s.fillText(u,m.left-t.left,m.top-t.top+m.height/2));},i=(c,d,h)=>{if(!c.complete||c.naturalWidth<=0||!Mb(c))return;let u=c.getBoundingClientRect();if(u.width<=0||u.height<=0)return;let p=u.left-t.left,m=u.top-t.top;s.save(),s.globalAlpha=h,Fs(s,p,m,u.width,u.height,dd(d,u.width,u.height)),s.clip(),s.drawImage(c,p,m,u.width,u.height),s.restore();},o=(c,d)=>{for(let h of c.children){if(h.hasAttribute("transform"))continue;let u=h.tagName.toLowerCase();if(u==="g"){o(h,d);continue}let p=g=>parseFloat(h.getAttribute(g)??"0")||0,m=null;if(u==="path"){let g=h.getAttribute("d");g&&(m=new Path2D(g));}else if(u==="circle")m=new Path2D,m.arc(p("cx"),p("cy"),p("r"),0,Math.PI*2);else if(u==="ellipse")m=new Path2D,m.ellipse(p("cx"),p("cy"),p("rx"),p("ry"),0,0,Math.PI*2);else if(u==="rect")m=new Path2D,m.rect(p("x"),p("y"),p("width"),p("height"));else if(u==="line")m=new Path2D,m.moveTo(p("x1"),p("y1")),m.lineTo(p("x2"),p("y2"));else if(u==="polyline"||u==="polygon"){let g=(h.getAttribute("points")??"").trim().split(/[\s,]+/).map(Number);if(g.length<4||g.some(Number.isNaN))continue;m=new Path2D,m.moveTo(g[0],g[1]);for(let v=2;v+1<g.length;v+=2)m.lineTo(g[v],g[v+1]);u==="polygon"&&m.closePath();}if(!m)continue;let f=n.getComputedStyle(h);f.fill&&f.fill!=="none"&&vo(f.fill)&&(s.globalAlpha=d*(parseFloat(f.fillOpacity)||1),s.fillStyle=f.fill,s.fill(m));let b=parseFloat(f.strokeWidth)||0;f.stroke&&f.stroke!=="none"&&vo(f.stroke)&&b>0&&(s.globalAlpha=d*(parseFloat(f.strokeOpacity)||1),s.strokeStyle=f.stroke,s.lineWidth=b,(f.strokeLinecap==="round"||f.strokeLinecap==="square"||f.strokeLinecap==="butt")&&(s.lineCap=f.strokeLinecap),(f.strokeLinejoin==="round"||f.strokeLinejoin==="bevel"||f.strokeLinejoin==="miter")&&(s.lineJoin=f.strokeLinejoin),s.stroke(m));}},a=(c,d)=>{let h=c.getBoundingClientRect();if(h.width<=0||h.height<=0)return;let u=n.getComputedStyle(c);if(u.display==="none"||u.visibility==="hidden")return;let p=d*(parseFloat(u.opacity)||1);if(p<=.001)return;let m=c.viewBox.baseVal,f=m&&m.width>0?m.width:h.width,b=m&&m.height>0?m.height:h.height;s.save(),s.translate(h.left-t.left,h.top-t.top),s.scale(h.width/f,h.height/b),m&&s.translate(-m.x,-m.y),o(c,p),s.restore();},l=(c,d)=>{let h=n.getComputedStyle(c);if(h.display==="none"||h.visibility==="hidden")return;let u=d*(parseFloat(h.opacity)||1);if(u<=.001)return;let p=c.getBoundingClientRect();if(p.width>0&&p.height>0){let m=p.left-t.left,f=p.top-t.top,b=dd(h,p.width,p.height);vo(h.backgroundColor)&&(s.globalAlpha=u,s.fillStyle=h.backgroundColor,Fs(s,m,f,p.width,p.height,b),s.fill());let g=parseFloat(h.borderTopWidth)||0;g>0&&h.borderTopStyle!=="none"&&vo(h.borderTopColor)&&(s.globalAlpha=u,s.strokeStyle=h.borderTopColor,s.lineWidth=g,Fs(s,m+g/2,f+g/2,p.width-g,p.height-g,Math.max(0,b-g/2)),s.stroke());}for(let m of c.childNodes)m.nodeType===3?r(m,h,u):m instanceof n.HTMLImageElement?i(m,n.getComputedStyle(m),u):m instanceof n.SVGSVGElement?a(m,u):m instanceof n.HTMLElement&&l(m,u);};e instanceof n.HTMLElement&&l(e,1),s.restore();}function hd(s,e,t,n,r){let i=Math.max(0,e),o=Math.min(s.length-1,t);if(i>o)return null;let a=1/0,l=-1/0;for(let y=i;y<=o;y+=1){let x=s[y];x.volume!=null&&x.volume>0&&(x.low<a&&(a=x.low),x.high>l&&(l=x.high));}if(!Number.isFinite(a))return null;let c=l>a?Math.max(1,Math.round(n)):1,d=l>a?(l-a)/c:1,h=Array.from({length:c},(y,x)=>({price:a+x*d,up:0,down:0}));for(let y=i;y<=o;y+=1){let x=s[y],S=x.volume;if(!(S!=null&&S>0))continue;let C=x.close>=x.open?"up":"down",T=x.high-x.low;if(T<=0){let k=Bs(Math.floor((x.low-a)/d),c);h[k][C]+=S;continue}let M=Bs(Math.floor((x.low-a)/d),c),E=Bs(Math.floor((x.high-a)/d-1e-9),c);for(let k=M;k<=E;k+=1){let L=a+k*d,P=Math.min(x.high,L+d)-Math.max(x.low,L);P>0&&(h[k][C]+=S*P/T);}}let u=0,p=0,m=0;for(let y=0;y<c;y+=1){let x=h[y].up+h[y].down;u+=x,x>p&&(p=x,m=y);}if(p<=0)return null;let f=u*Math.min(1,Math.max(0,r)),b=m,g=m,v=p;for(;v<f&&(b>0||g<c-1);){let y=b>0?h[b-1].up+h[b-1].down:-1,x=g<c-1?h[g+1].up+h[g+1].down:-1;x>y?(g+=1,v+=x):(b-=1,v+=y);}return {rows:h,rowH:d,min:a,maxTotal:p,poc:m,vaFrom:b,vaTo:g}}function Bs(s,e){return s<0?0:s>=e?e-1:s}function ud(s,e,t,n){let{rows:r,rowH:i,maxTotal:o,poc:a,vaFrom:l,vaTo:c}=e,{rightX:d,maxW:h,yOf:u}=t;if(!(o<=0||h<=0)){for(let p=0;p<r.length;p+=1){let m=r[p],f=m.up+m.down;if(f<=0)continue;let b=u(m.price+i),g=Math.max(1,u(m.price)-b-1),v=f/o*h,y=m.up/f*v;s.globalAlpha=p>=l&&p<=c?.62:.28,y>0&&(s.fillStyle=n.upColor,s.fillRect(d-v,b,y,g)),v-y>0&&(s.fillStyle=n.downColor,s.fillRect(d-v+y,b,v-y,g));}if(n.showPoc){let p=r[a],m=u(p.price+i),f=Math.max(1,u(p.price)-m-1);s.globalAlpha=.9,s.strokeStyle=n.pocColor,s.lineWidth=1,s.strokeRect(d-h+.5,m+.5,h-1,f);}s.globalAlpha=1;}}var xo=class{constructor(){this.canvas=null;this.ctx=null;this.memoKey="";this.memo=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}destroy(){this.canvas=null,this.ctx=null,this.memoKey="",this.memo=null;}render(e){let t=this.ctx,n=this.canvas;if(!t||!n)return;let{bars:r,data:i,visible:o,coords:a,scale:l,bounds:c,theme:d}=e,h=a.dpr;if(t.setTransform(h,0,0,h,0,0),t.clearRect(0,0,n.width/h,n.height/h),!i||!o||r.length===0||c.height<=0)return;let u=a.visibleLogicalRange(),p=Math.max(0,Math.floor(u.from)),m=Math.min(r.length-1,Math.ceil(u.to));if(p>m)return;let f=r[m],b=`${p}:${m}:${r.length}:${f.high}:${f.low}:${f.close}:${f.volume??0}:${i.rows}:${i.valueAreaFrac}`;b!==this.memoKey&&(this.memoKey=b,this.memo=hd(r,p,m,i.rows,i.valueAreaFrac));let g=this.memo;g&&(t.save(),t.beginPath(),t.rect(0,c.top,a.width,c.height),t.clip(),ud(t,g,{rightX:a.width,maxW:a.width*i.widthFrac,yOf:v=>a.priceToY(v,l,c)},{upColor:i.upColor,downColor:i.downColor,showPoc:i.showPoc,pocColor:d.textColor}),t.restore());}};var ge="price",kb=8,Ib="rgba(0,0,0,0)",wo=64,Rb=56,md=26,So=22,ir=26,Vs=24,Db=5,Ab="0 2px 8px rgba(0,0,0,0.4)",Ob=12,yd=12,fd=wo+yd,_s=So+14,Fb=120,Bb=2,bd=6,Vb=70,pn=80,_b=110,Ns=90,Nb=130,Hb=.02,zb=.004,$b=.2,Wb=4,or=class{constructor(e){this.capabilities=Ml;this.surfaceBackground=Be.background;this.surfaceTextColor=Be.textColor;this.toolbarGutter=0;this.mountContainer=null;this.userDrawings=null;this.volumeRenderer=new go;this.extLayers=[];this.attributionEl=null;this.attributionEnabled=true;this.attributionHtml=null;this.vpvrRenderer=new xo;this.resizeObserver=null;this.dprMedia=null;this.coords=new Ji;this.scene=new Gi;this.backendMode="auto";this.glowAmount=0;this.chrome=new io;this.crosshairLayer=new oo;this.countdownTimer=null;this.symbolPicker=null;this.indicatorTitlesOn=true;this.indicatorValuesOn=true;this.legendActionsProvider=null;this.legendOverviewAction=null;this.keyboard=null;this.keyboardEnabled=true;this.historyChordsEnabled=true;this.liveRegion=null;this.animZoom=true;this.animPan=true;this.candleUp=q;this.candleDown=X;this.introStyle="settle";this.introPlayed=false;this.introRaf=null;this.loadingEl=null;this.modelAlpha=1;this.targetBarSpacing=0;this.zoomAnchorLogical=0;this.zoomAnchorX=0;this.zoomAnchorMode="right";this.panVelocity=0;this.bars=[];this.didInitialFit=false;this.paintedData=false;this.skeletonClockMs=0;this.candleBodyAlpha=1;this.candleStructureAlpha=1;this.lastPointer=null;this.volumeActive=false;this.volumeHidden=false;this.vpvrActive=false;this.vpvrHidden=false;this.liveEaseTime=0;this.liveEaseHigh=0;this.liveEaseLow=0;this.liveEaseClose=0;this.axisDragEnabled=true;this.scaleDragHolder=null;this.scaleDragHeight=0;this.scaleDragStart=null;this.paneResizeEnabled=true;this.resizeAbove=null;this.resizeBelow=null;this.resizeSplitStart=null;this.hoverSeparatorY=null;this.maximizedPaneId=null;this.rightAxisW=wo;this.paneControls=null;this.paneActionCbs=new Set;this.hoverLogical=null;this.settingsDialog=null;this.dialogHost=null;this.settingsButton=null;this.settingsEnabled=false;this.scrollButton=null;this.pointerNearScrollBtn=false;this.scrollTargetRO=null;this.scrollBtnBottomPx=_s;this.scrollBtnRightPx=fd;this.layoutMode="desktop";this.viewportCbs=new Set;this.crosshairCbs=new Set;this.chartTypeSettingsCbs=new Set;this.configChangedCbs=new Set;this.themeSelectCbs=new Set;this.factoryConfig=null;this.hostSettingsSections=[];this.clickCbs=new Set;this.axisLongPressCbs=new Set;this.inputChangeCbs=new Set;this.removeIndicatorCbs=new Set;this.toggleVisibleCbs=new Set;this.moveIndicatorCbs=new Set;this.priceStyleCbs=new Set;this.tableOverlays=new Map;this.name="native";this.features=["logScale","currentPriceLine","priceLabel","countdown","upColor","downColor","glow","animZoom","animPan","intro","zoomAnchor","axisDrag","paneResize","candleZOrder","candleVisible","seriesOrder","highlights","gridlines","axisLabels","scaleMode","invertScale","paneScales","autoScale","timezone","keyboard","historyChords","priceStyle","priceBaseline","baselinePrice","settings","attribution","dialogHost","tradeMarkers","indicatorTitles","indicatorValues"];this.onScrollProximityMove=e=>{if(!this.scrollButton||!this.plot)return;let t=this.plot.getBoundingClientRect(),n=t.width-this.scrollBtnRightPx-ir/2,r=t.height-this.scrollBtnBottomPx-ir/2,i=Math.hypot(e.clientX-t.left-n,e.clientY-t.top-r)<=Fb;i!==this.pointerNearScrollBtn&&(this.pointerNearScrollBtn=i,this.updateScrollToRealtimeButton());};this.onScrollProximityLeave=()=>{this.pointerNearScrollBtn&&(this.pointerNearScrollBtn=false,this.updateScrollToRealtimeButton());};this.onDprChange=()=>{this.watchDpr(),this.resize();};this.externalCross=null;this.snapMode="off";e&&(this.scene.showPriceLine=e.currentPriceLine,this.scene.logScale=e.logScale,this.backendMode=e.nativeBackend,this.animZoom=e.animZoom,this.animPan=e.animPan,this.glowAmount=e.glow,this.candleUp=e.upColor,this.candleDown=e.downColor,this.scene.priceStyle=e.priceStyle,this.scene.basePainting=rs(e.priceStyle),this.scene.candleOverride=$i(e.priceStyle,this.scene.style.chartTypes)),this.theme=this.deriveTheme(Be);}applyFeature(e,t){switch(e){case "logScale":if(t&&typeof t=="object"){let n=t;this.setPaneLog(n.pane??ge,!!n.value);return}this.scene.logScale=!!t;break;case "currentPriceLine":this.scene.showPriceLine=!!t;break;case "priceLabel":this.scene.showPriceLabel=!!t;break;case "countdown":this.scene.showCountdown=!!t,this.syncCountdownTimer();break;case "upColor":this.candleUp=String(t),this.theme&&(this.theme=this.deriveTheme(this.theme));break;case "downColor":this.candleDown=String(t),this.theme&&(this.theme=this.deriveTheme(this.theme));break;case "glow":this.glowAmount=Number(t)||0,this.backend&&"glow"in this.backend&&(this.backend.glow=this.glowAmount);break;case "animZoom":this.animZoom=!!t;return;case "animPan":this.animPan=!!t;return;case "intro":{let n=t===false||t==="none"||t==="off"||t==null?"":String(t);this.introStyle=n,n&&this.playIntro(n);return}case "zoomAnchor":this.zoomAnchorMode=t==="right"?"right":"cursor",this.input&&(this.input.rightEdgeZoom=this.zoomAnchorMode==="right");return;case "axisDrag":this.axisDragEnabled=!!t,this.input&&(this.input.axisDrag=this.axisDragEnabled);return;case "paneResize":this.paneResizeEnabled=!!t,this.input&&(this.input.paneResize=this.paneResizeEnabled);return;case "candleZOrder":this.scene.candleZ=Number(t)||0;break;case "candleVisible":this.scene.candlesHidden=t===false;break;case "seriesOrder":this.applySeriesOrder(t);break;case "highlights":this.scene.highlights=Xb(t);break;case "gridlines":this.scene.showGrid=!!t;break;case "axisLabels":this.scene.showAxisLabels=!!t;break;case "scaleMode":if(t&&typeof t=="object"){let n=t;this.setPaneScaleMode(n.pane??ge,gd(n.mode));return}this.scene.scaleMode=gd(t);break;case "invertScale":if(t&&typeof t=="object"){let n=t;this.setPaneInvert(n.pane??ge,!!n.value);return}this.scene.invertScale=!!t;break;case "autoScale":for(let n of this.scene.panes.values())n.manualScale=t?null:{...n.scale};break;case "timezone":this.scene.timezone=typeof t=="string"&&t?t:"UTC";break;case "priceStyle":this.setPriceStyle(Kb(t)?t:"candles");break;case "priceBaseline":this.scene.baselineValue=t==null?null:Number(t);break;case "tradeMarkers":this.scene.tradeMarkers=Gl(this.scene.tradeMarkers,t);break;case "keyboard":this.setKeyboardEnabled(!!t);return;case "historyChords":this.historyChordsEnabled=!!t,this.userDrawings&&(this.userDrawings.historyChords=this.historyChordsEnabled);return;case "settings":this.setSettingsEnabled(!!t);return;case "indicatorTitles":this.indicatorTitlesOn=t!==false,this.inputsUI?.setTitlesVisible(this.indicatorTitlesOn);return;case "indicatorValues":this.indicatorValuesOn=t!==false,this.inputsUI?.setValuesVisible(this.indicatorValuesOn);return;case "attribution":this.attributionHtml=typeof t=="string"&&t.trim()?t:null,this.attributionEnabled=this.attributionHtml!==null||!!t,this.rebuildAttribution();return;case "dialogHost":this.dialogHost=t instanceof HTMLElement?t:null,this.settingsDialog?.close(),this.settingsDialog=null,this.inputsUI?.setDialogHost(this.dialogHost);return;default:return}this.scheduler?.invalidate(4);}readFeature(e){switch(e){case "logScale":return this.scene.logScale;case "currentPriceLine":return this.scene.showPriceLine;case "priceLabel":return this.scene.showPriceLabel;case "countdown":return this.scene.showCountdown;case "upColor":return this.candleUp;case "downColor":return this.candleDown;case "glow":return this.glowAmount;case "animZoom":return this.animZoom;case "animPan":return this.animPan;case "intro":return this.introStyle;case "zoomAnchor":return this.zoomAnchorMode;case "axisDrag":return this.input?this.input.axisDrag:this.axisDragEnabled;case "paneResize":return this.input?this.input.paneResize:this.paneResizeEnabled;case "candleZOrder":return this.scene.candleZ;case "candleVisible":return !this.scene.candlesHidden;case "seriesOrder":return this.scene.indicatorZOrder();case "highlights":return this.scene.highlights;case "gridlines":return this.scene.showGrid;case "axisLabels":return this.scene.showAxisLabels;case "scaleMode":return this.scene.scaleMode;case "invertScale":return this.scene.invertScale;case "paneScales":return this.paneScaleInfos();case "autoScale":{let t=this.scene.orderedPanes().find(n=>n.kind==="price");return t?t.manualScale==null:true}case "timezone":return this.scene.timezone;case "priceStyle":return this.scene.priceStyle;case "priceBaseline":return this.scene.baselineValue;case "baselinePrice":{let t=this.scene.panes.get(ge);return t?this.scene.baselinePriceFor(t.scale):this.scene.baselineValue}case "tradeMarkers":return {...this.scene.tradeMarkers,colors:{...this.scene.tradeMarkers.colors}};case "keyboard":return this.keyboardEnabled;case "historyChords":return this.historyChordsEnabled;case "settings":return this.settingsEnabled;case "indicatorTitles":return this.indicatorTitlesOn;case "indicatorValues":return this.indicatorValuesOn;case "attribution":return this.attributionHtml??this.attributionEnabled;case "dialogHost":return this.dialogHost??void 0;default:return}}setNativeData(e,t){e==="volume"?(this.scene.volumeLayer=t??null,this.scheduler?.invalidate(3)):e==="vpvr"?(this.scene.vpvrLayer=t??null,this.scheduler?.invalidate(3)):e.endsWith("-pending")?(this.scene.nativePending.set(e.slice(0,-8),t??[]),this.scheduler?.invalidate(3)):(this.scene.nativeData.set(e,t),this.scheduler?.invalidate(3));}setIndicatorStatus(e,t){this.inputsUI.setStatus(e.id,t);}setLoading(e){for(let r of this.tableOverlays.values())r.setVisible(!e);if(!e||!this.wrapper){this.loadingEl?.remove(),this.loadingEl=null;return}if(this.loadingEl)return;let t=this.wrapper.ownerDocument,n=t.createElement("div");n.className="vela-loading",Object.assign(n.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",gap:"7px",pointerEvents:"none"});for(let r=0;r<3;r+=1){let i=t.createElement("span");Object.assign(i.style,{width:"7px",height:"7px",borderRadius:"50%",background:this.chromeTheme().textColor,opacity:"0.15"}),i.animate([{opacity:.12},{opacity:.55}],{duration:800,iterations:1/0,direction:"alternate",easing:"ease-in-out",delay:-r*260}),n.appendChild(i);}this.wrapper.appendChild(n),this.loadingEl=n;}setPricePrecision(e){let t=typeof e=="number"&&e>0?e:void 0;t!==this.scene.priceMintick&&(this.scene.priceMintick=t,this.scheduler?.invalidate(4));}getConfig(){let e=this.scene.style,t=Object.fromEntries(Object.entries(e.chartTypes).map(([r,i])=>[r,{...i}])),n=this.theme;return {version:ns,chartTypes:t,layout:{background:n.background,textColor:n.textColor,fontFamily:n.fontFamily,fontSize:e.fontSize},grid:{vertLines:{visible:e.gridVert.visible,color:e.gridVert.color??n.gridColor},horzLines:{visible:e.gridHorz.visible,color:e.gridHorz.color??n.gridColor}},crosshair:{color:e.crosshair.color??n.textColor,width:e.crosshair.width,style:e.crosshair.style,opacity:e.crosshair.opacity,labelBackground:e.crosshair.labelBackground??n.textColor},priceScale:{mode:this.scene.scaleMode,log:this.scene.logScale,invert:this.scene.invertScale,borderColor:e.borderColor??n.borderColor,labelsVisible:this.scene.showAxisLabels,currentPriceLine:this.scene.showPriceLine,priceLabel:this.scene.showPriceLabel,countdown:this.scene.showCountdown},panes:{separatorColor:e.separatorColor??n.borderColor},trades:{visible:this.scene.tradeMarkers.visible,labels:this.scene.tradeMarkers.labels,qty:this.scene.tradeMarkers.qty,longColor:this.scene.tradeMarkers.colors.long,shortColor:this.scene.tradeMarkers.colors.short,exitColor:this.scene.tradeMarkers.colors.exit},timeScale:{timezone:this.scene.timezone},candles:{upColor:this.candleUp,downColor:this.candleDown,bodyVisible:e.candle.bodyVisible,borderVisible:e.candle.borderVisible,borderUpColor:e.candle.borderUpColor??this.candleUp,borderDownColor:e.candle.borderDownColor??this.candleDown,wickVisible:e.candle.wickVisible,wickUpColor:e.candle.wickUpColor??this.candleUp,wickDownColor:e.candle.wickDownColor??this.candleDown},bars:{upColor:e.bars.upColor??this.candleUp,downColor:e.bars.downColor??this.candleDown},line:{color:e.line.color??this.candleUp,width:e.line.width},stacking:{candles:this.scene.candleZ,series:Object.fromEntries(this.scene.indicatorZOrder().map(({id:r,z:i})=>[r,i]))},area:(()=>{let r=e.area.lineColor??this.candleUp;return {lineColor:r,width:e.area.width,topColor:e.area.topColor??r,bottomColor:e.area.bottomColor??Ib}})(),baseline:(()=>{let r=e.baseline.topLineColor??Qt,i=e.baseline.bottomLineColor??en;return {topLineColor:r,bottomLineColor:i,topFillColor:e.baseline.topFillColor??W(r,Ye),topFillColor2:e.baseline.topFillColor2??W(r,Xe),bottomFillColor:e.baseline.bottomFillColor??W(i,Ye),bottomFillColor2:e.baseline.bottomFillColor2??W(i,Xe),width:e.baseline.width,baselineLevel:e.baseline.baselineLevel}})(),series:{style:this.scene.priceStyle,baseline:this.scene.baselineValue,spacing:this.coords.spacingScale}}}applyConfig(e){let t=Vl(this.getConfig(),e),n=this.scene.style;for(let[d,h]of Object.entries(t.chartTypes))if(JSON.stringify(n.chartTypes[d])!==JSON.stringify(h)){this.scene.nativeData.set(`${d}-settings`,{...h});for(let u of this.chartTypeSettingsCbs)u(d,{...h});}n.chartTypes=Object.fromEntries(Object.entries(t.chartTypes).map(([d,h])=>[d,{...h}]));let r=e&&typeof e=="object"?e.layout:void 0,i=r&&typeof r=="object"?r.textColor:void 0,o=typeof i=="string"&&i.trim().length>0,a=this.theme,l={textColor:t.layout.textColor,gridColor:a.gridColor,borderColor:a.borderColor};if(!o&&xe(t.layout.textColor)===xe(t.layout.background)){let d=xe(t.layout.background)?Be:An;l={textColor:d.textColor,gridColor:d.gridColor,borderColor:d.borderColor};}this.theme={...this.theme,background:t.layout.background,textColor:l.textColor,gridColor:l.gridColor,borderColor:l.borderColor,fontFamily:t.layout.fontFamily},n.fontSize=t.layout.fontSize;let c=(d,h,u)=>d===null&&h===u?null:h;n.gridVert={visible:t.grid.vertLines.visible,color:c(n.gridVert.color,t.grid.vertLines.color,a.gridColor)},n.gridHorz={visible:t.grid.horzLines.visible,color:c(n.gridHorz.color,t.grid.horzLines.color,a.gridColor)},n.crosshair={color:t.crosshair.color,width:t.crosshair.width,style:t.crosshair.style,opacity:t.crosshair.opacity,labelBackground:t.crosshair.labelBackground},this.scene.scaleMode=t.priceScale.mode,this.scene.logScale=t.priceScale.log,this.scene.invertScale=t.priceScale.invert,n.borderColor=c(n.borderColor,t.priceScale.borderColor,a.borderColor),this.scene.showAxisLabels=t.priceScale.labelsVisible,this.scene.showPriceLine=t.priceScale.currentPriceLine,this.scene.showPriceLabel=t.priceScale.priceLabel,this.scene.showCountdown=t.priceScale.countdown,this.syncCountdownTimer(),n.separatorColor=c(n.separatorColor,t.panes.separatorColor,a.borderColor),this.scene.tradeMarkers={visible:t.trades.visible,labels:t.trades.labels,qty:t.trades.qty,colors:{long:t.trades.longColor,short:t.trades.shortColor,exit:t.trades.exitColor}},this.scene.timezone=t.timeScale.timezone,this.candleUp=t.candles.upColor,this.candleDown=t.candles.downColor,n.candle={bodyVisible:t.candles.bodyVisible,borderVisible:t.candles.borderVisible,borderUpColor:t.candles.borderUpColor,borderDownColor:t.candles.borderDownColor,wickVisible:t.candles.wickVisible,wickUpColor:t.candles.wickUpColor,wickDownColor:t.candles.wickDownColor},this.scene.candleZ=t.stacking.candles;for(let[d,h]of Object.entries(t.stacking.series))this.scene.setIndicatorZ(d,h);n.bars={upColor:t.bars.upColor,downColor:t.bars.downColor},n.line={color:t.line.color,width:t.line.width},n.area={lineColor:t.area.lineColor,width:t.area.width,topColor:t.area.topColor,bottomColor:t.area.bottomColor},n.baseline={topLineColor:t.baseline.topLineColor,bottomLineColor:t.baseline.bottomLineColor,topFillColor:t.baseline.topFillColor,topFillColor2:t.baseline.topFillColor2,bottomFillColor:t.baseline.bottomFillColor,bottomFillColor2:t.baseline.bottomFillColor2,width:t.baseline.width,baselineLevel:t.baseline.baselineLevel},this.setPriceStyle(t.series.style),this.scene.candleOverride=$i(this.scene.priceStyle,n.chartTypes),this.scene.baselineValue=t.series.baseline,this.coords.setPitchScale(t.series.spacing),this.coords.setViewport(this.clampViewport(this.coords.getViewport().barSpacing,this.coords.getViewport().rightOffset)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.theme=this.deriveTheme(this.theme),this.wrapper&&(ne(this.wrapper,this.chromeTheme()),this.applyBackground()),this.inputsUI?.setTheme(this.theme),this.paneControls?.setTheme(this.theme),this.userDrawings?.setTheme(this.chromeTheme()),this.refreshScrollButtonTheme(),this.refreshAttributionColor(),this.scheduler?.invalidate(4);for(let d of this.configChangedCbs)d();}applySeriesOrder(e){if(!e||typeof e!="object")return;let t=e;typeof t.id=="string"&&(typeof t.z=="number"?this.scene.setIndicatorZ(t.id,t.z):t.to==="front"?this.scene.bringIndicatorToFront(t.id):t.to==="back"&&this.scene.sendIndicatorToBack(t.id));}setSettingsEnabled(e){this.settingsEnabled=e,e?(this.plot&&!this.settingsButton&&(this.settingsButton=this.makeSettingsButton(),this.plot.appendChild(this.settingsButton)),this.settingsButton&&(this.settingsButton.style.display="flex"),this.plot&&!this.settingsDialog&&(this.settingsDialog=new er(this.dialogHost??this.plot,this.theme))):(this.settingsButton?.style.setProperty("display","none"),this.settingsDialog?.close());}makeSettingsButton(){let e=document.createElement("button");return e.type="button",e.title="Chart settings",e.innerHTML=oe("gear",14),Object.assign(e.style,{position:"absolute",bottom:`${So+10}px`,right:`${wo+10}px`,zIndex:"6",width:"26px",height:"26px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:"50%",border:`1px solid ${this.theme.borderColor}`,background:this.theme.background,color:this.theme.textColor,fontSize:"14px",lineHeight:"1",opacity:"0.75",pointerEvents:"auto",padding:"0"}),e.addEventListener("mouseenter",()=>e.style.opacity="1"),e.addEventListener("mouseleave",()=>e.style.opacity="0.75"),e.addEventListener("click",()=>this.toggleSettingsDialog()),e}openSettingsDialog(e){!this.settingsDialog&&this.plot&&(this.settingsDialog=new er(this.dialogHost??this.plot,this.theme),this.settingsDialog.setLayoutMode(this.layoutMode)),this.toggleSettingsDialog(e);}syncThemeControl(){this.settingsDialog?.setThemeControl(xe(this.surfaceBackground)?"dark":"light",e=>{for(let t of this.themeSelectCbs)t(e);});}toggleSettingsDialog(e){if(this.settingsDialog){if(e!==void 0&&this.settingsDialog.isOpen()){this.settingsDialog.showSection(e);return}this.settingsDialog.setTheme(this.theme),this.settingsDialog.setHostSections(this.hostSettingsSections),this.syncThemeControl(),this.settingsDialog.toggle(this.getConfig(),t=>this.applyConfig(t),t=>this.applyConfig(t),()=>{this.factoryConfig&&this.applyConfig(Bl(this.factoryConfig)),this.settingsDialog?.close(),this.openSettingsDialog();},e);}}closeDialogs(){this.inputsUI?.closeOpenDialog(),this.settingsDialog?.close();}makeScrollToRealtimeButton(){let e=document.createElement("button");return e.type="button",e.title="Scroll to most recent bar (Alt+Shift+\u2192)",e.setAttribute("aria-label","Scroll to most recent bar"),e.innerHTML=this.scrollButtonIcon(),Object.assign(e.style,{position:"absolute",bottom:`${_s}px`,right:`${fd}px`,zIndex:"6",width:`${ir}px`,height:`${ir}px`,boxSizing:"border-box",display:"none",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:`${Db}px`,border:`1px solid ${this.theme.borderColor}`,boxShadow:Ab,background:this.scrollButtonSurface(),color:this.theme.textColor,lineHeight:"0",opacity:"0.85",pointerEvents:"auto",padding:"0"}),e.addEventListener("mouseenter",()=>e.style.opacity="1"),e.addEventListener("mouseleave",()=>e.style.opacity="0.85"),e.addEventListener("click",()=>this.scrollToRealtime()),e}scrollButtonIcon(){return oe("chevrons-right",Ob)}scrollButtonSurface(){return W(this.theme.background,.5)}refreshScrollButtonTheme(){this.scrollButton&&(this.scrollButton.style.background=this.scrollButtonSurface(),this.scrollButton.style.color=this.theme.textColor,this.scrollButton.style.borderColor=this.theme.borderColor);}updateScrollToRealtimeButton(){let e=this.scrollButton;if(!e)return;let t=this.coords.barCount>0&&this.coords.getViewport().rightOffset<0;if(this.layoutMode==="mobile"){e.style.display=t?"flex":"none";return}e.style.display=t&&this.pointerNearScrollBtn?"flex":"none";}scrollToRealtime(){this.coords.barCount!==0&&this.glideRightOffset(bd);}glideRightOffset(e){let t=this.coords.getViewport();if(!this.animPan){this.applyViewport({barSpacing:t.barSpacing,rightOffset:e});return}this.panVelocity=0,this.targetBarSpacing=t.barSpacing,this.scrollTargetRO=e,this.animator.start();}screenshot(){if(!this.dataCanvas)return null;this.computeScales(),this.paintData();let e=document.createElement("canvas");e.width=this.dataCanvas.width,e.height=this.dataCanvas.height;let t=e.getContext("2d");if(!t)return null;t.fillStyle=this.theme.background,t.fillRect(0,0,e.width,e.height);let n=this.plot?.getBoundingClientRect(),r=n&&n.width>0?{left:n.left,top:n.top,dpr:e.width/n.width}:null,i=[...this.mountContainer?.querySelectorAll("[data-vela-screenshot]")??[]];if(r)for(let l of i)l.getAttribute("data-vela-screenshot")==="under"&&yo(t,l,r);let o=this.extLayers.filter(l=>l.def.placement==="below-data").map(l=>l.canvas),a=this.extLayers.filter(l=>l.def.placement!=="below-data").map(l=>l.canvas);for(let l of [...o,this.dataCanvas,this.volumeCanvas,this.vpvrCanvas,...a,this.chromeCanvas,this.drawingsCanvas])l&&l.width>0&&l.height>0&&t.drawImage(l,0,0);if(r){for(let l of this.plot?.querySelectorAll("[data-vela-pane]")??[])yo(t,l,r);for(let l of i)l.getAttribute("data-vela-screenshot")!=="under"&&yo(t,l,r);}return e.toDataURL("image/png")}playIntro(e){this.introRaf!=null&&cancelAnimationFrame(this.introRaf),this.introRaf=null;let t=this.bars,n=t.length;if(n===0)return;this.computeScales();for(let a of this.scene.panes.values())a.scale={...a.scaleTarget};this.modelAlpha=0;let r=650,i=performance.now(),o=a=>{let l=Math.min(1,(a-i)/r);this.scene.bars=l>=1?t:t.map((c,d)=>this.revealCandle(c,d,l,n,e)),this.paintData(),l<1?this.introRaf=requestAnimationFrame(o):(this.scene.bars=t,this.fadeInModels());};this.introRaf=requestAnimationFrame(o);}fadeInModels(){let t=performance.now(),n=r=>{this.modelAlpha=Math.min(1,(r-t)/350),this.paintData(),this.modelAlpha<1?this.introRaf=requestAnimationFrame(n):(this.modelAlpha=1,this.introRaf=null);};this.introRaf=requestAnimationFrame(n);}revealCandle(e,t,n,r,i){let a=Math.max(0,Math.min(1,(n-t/Math.max(1,r-1)*.55)/.44999999999999996)),l;if(i==="settle"){let h=a-1;l=1+(1.70158+1)*h*h*h+1.70158*h*h;}else {let d=1-a;l=1-d*d*d;}let c=e.open;return {...e,high:c+(e.high-c)*l,low:c+(e.low-c)*l,close:c+(e.close-c)*l}}deriveTheme(e){return {...e,upColor:this.candleUp,downColor:this.candleDown}}chromeTheme(){return {...this.theme,background:this.surfaceBackground,textColor:this.surfaceTextColor,borderColor:xe(this.surfaceBackground)?Be.borderColor:An.borderColor}}axisSurface(){return {background:this.theme.background,textColor:this.theme.textColor}}mount(e,t){this.mountContainer=e,this.publishGutters(),this.theme=this.deriveTheme(t),this.surfaceBackground=t.background,this.surfaceTextColor=t.textColor,this.wrapper=document.createElement("div"),Object.assign(this.wrapper.style,{position:"relative",width:"100%",height:"100%",overflow:"hidden",cursor:"crosshair"}),ne(this.wrapper,this.chromeTheme()),this.volumeCanvas=document.createElement("canvas"),Object.assign(this.volumeCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.dataCanvas=this.createGeometryBackend(),this.vpvrCanvas=document.createElement("canvas"),Object.assign(this.vpvrCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.chromeCanvas=document.createElement("canvas"),Object.assign(this.chromeCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.drawingsCanvas=document.createElement("canvas"),Object.assign(this.drawingsCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.cursorCanvas=document.createElement("canvas"),Object.assign(this.cursorCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.overlayRoot=document.createElement("div"),Object.assign(this.overlayRoot.style,{position:"absolute",inset:"0",pointerEvents:"none"}),this.plot=document.createElement("div"),Object.assign(this.plot.style,{position:"absolute",top:"0",right:"0",bottom:"0",left:"0"}),this.extLayers=Ds().map(i=>{let o=document.createElement("canvas");return Object.assign(o.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),{def:i,instance:i.create(),canvas:o}});let n=this.extLayers.filter(i=>i.def.placement==="below-data").map(i=>i.canvas),r=this.extLayers.filter(i=>i.def.placement!=="below-data").map(i=>i.canvas);this.plot.append(...n,this.dataCanvas,this.volumeCanvas,this.vpvrCanvas,...r,this.chromeCanvas,this.drawingsCanvas,this.cursorCanvas,this.overlayRoot),this.wrapper.appendChild(this.plot),this.factoryConfig=this.getConfig(),this.attributionEl=this.buildAttributionEl(),this.attributionEnabled||(this.attributionEl.style.display="none"),this.positionAttribution(),this.wrapper.appendChild(this.attributionEl),e.appendChild(this.wrapper),this.applyBackground(),this.volumeRenderer.mount(this.volumeCanvas),this.vpvrRenderer.mount(this.vpvrCanvas);for(let i of this.extLayers)i.instance.mount(i.canvas);this.chrome.mount(this.chromeCanvas),this.crosshairLayer.mount(this.cursorCanvas),this.coords.setViewport(Zi()),this.scene.ensurePane(ge,"price",0,3),this.scheduler=new Qi(i=>this.renderFrame(i)),this.animator=new eo(i=>this.animTick(i)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.input=new to({getCoords:()=>this.coords,apply:i=>this.applyViewport(i),zoomTo:(i,o,a)=>this.zoomTo(i,o,a),fling:i=>this.fling(i),onPointerMove:(i,o)=>this.handlePointerMove(i,o),onClick:i=>this.handleClick(i),onAxisLongPress:(i,o,a)=>{for(let l of this.axisLongPressCbs)l({axis:i,x:o,y:a});},beginPriceScale:(i,o)=>this.beginPriceScale(i,o),priceScaleBy:i=>this.priceScaleBy(i),beginPricePan:i=>this.beginPricePan(i),pricePanBy:i=>this.pricePanBy(i),resetPriceScale:(i,o)=>this.resetPriceScale(i,o),dataDblClick:(i,o)=>this.dataDblClick(i,o),paneSeparatorAt:i=>this.paneSeparatorAt(i),beginPaneResize:i=>this.beginPaneResize(i),paneResizeBy:i=>this.paneResizeBy(i),resetPaneSize:i=>this.resetPaneSize(i),resetView:()=>this.resetView(),drawingsClaim:(i,o)=>this.userDrawings?.claim(i,o)??false,drawingsMeasureStart:(i,o)=>this.userDrawings?.beginMeasureAt(i,o)??false,drawingsDeleteAt:(i,o)=>this.userDrawings?.deleteAt(i,o)??false,drawingsSnapMode:()=>this.snapMode,drawingsPointerDown:(i,o,a,l)=>this.userDrawings?.pointerDown(i,o,a,l),drawingsPointerMove:(i,o,a,l)=>this.userDrawings?.pointerMove(i,o,a,l),drawingsPointerUp:(i,o)=>this.userDrawings?.pointerUp(i,o),drawingsCursor:(i,o)=>this.userDrawings?.cursorAt(i,o)??null,drawingsDblClick:(i,o)=>this.userDrawings?.dblClick(i,o)??false,drawingsClearTransient:()=>this.userDrawings?.clearTransient()}),this.input.rightEdgeZoom=this.zoomAnchorMode==="right",this.input.axisDrag=this.axisDragEnabled,this.input.paneResize=this.paneResizeEnabled,this.input.attach(this.dataCanvas),this.settingsEnabled&&this.setSettingsEnabled(true),this.syncCountdownTimer(),this.scrollButton=this.makeScrollToRealtimeButton(),this.plot.appendChild(this.scrollButton),this.plot.addEventListener("pointermove",this.onScrollProximityMove),this.plot.addEventListener("pointerleave",this.onScrollProximityLeave),this.userDrawings=new bo(this.wrapper,this.plot,this.drawingsCanvas,{projector:()=>this.drawingProjector(),dpr:()=>this.coords.dpr,theme:()=>this.theme,requestScaleUpdate:()=>this.scheduler.invalidate(3),seriesBoundaries:i=>this.scene.seriesBoundaries(i),priceZ:i=>i===ge?this.scene.candleZ:null,requestDataPaint:()=>this.scheduler.invalidate(3),snap:(i,o,a,l)=>this.snapToCandle(i,o,a,l),setSnapMode:i=>this.setSnapMode(i),setToolbarGutter:i=>this.setToolbarGutter(i)}),this.userDrawings.historyChords=this.historyChordsEnabled,this.layoutMode==="mobile"&&(this.mountContainer?.setAttribute("data-vela-layout",this.layoutMode),this.userDrawings.setLayoutMode(this.layoutMode),this.scrollButton&&(this.scrollButton.style.width=`${Vs}px`,this.scrollButton.style.height=`${Vs}px`)),this.keyboard=new no({panByBars:i=>this.panByBars(i),zoomByStep:i=>this.zoomByStep(i),stepCrosshair:i=>this.stepCrosshair(i),jumpToEdge:i=>this.focusBar(i==="first"?0:this.coords.barCount-1),resetView:()=>this.resetView(),scrollToRealtime:()=>this.scrollToRealtime(),clearCrosshair:()=>this.handlePointerMove(null,null),preempt:i=>this.userDrawings?.handleKey(i)??false}),this.setKeyboardEnabled(this.keyboardEnabled),this.inputsUI=new Bi(this.plot,t,i=>this.paneBoundsFor(i)),this.inputsUI.setLayoutMode(this.layoutMode),this.inputsUI.setTitlesVisible(this.indicatorTitlesOn),this.inputsUI.setValuesVisible(this.indicatorValuesOn),this.inputsUI.setDialogHost(this.dialogHost),this.inputsUI.setSymbolPicker(this.symbolPicker),this.inputsUI.setLegendActions(this.legendActionsProvider),this.inputsUI.setLegendOverviewAction(this.legendOverviewAction),this.inputsUI.setOnChange(i=>{for(let o of this.inputChangeCbs)o({indicatorId:i.indicatorId,key:i.key,value:i.value});}),this.inputsUI.setOnRemove(i=>{for(let o of this.removeIndicatorCbs)o(i);}),this.inputsUI.setOnToggleVisible((i,o)=>{for(let a of this.toggleVisibleCbs)a(i,o);}),this.inputsUI.setMoveApi({panes:()=>this.scene.orderedPanes().map((i,o)=>({id:i.id,kind:i.kind,label:i.kind==="price"?"Main chart":this.paneMasterTitle(i.id)??`Pane ${o}`,top:i.bounds.top,height:i.bounds.height})),move:(i,o)=>{for(let a of this.moveIndicatorCbs)a(i,o);}}),this.paneControls=new Vi(this.plot,t,{panes:()=>this.paneControlViews(),rightAxis:()=>this.rightAxisW,onMove:(i,o)=>this.movePaneLocal(i,o),onToggleCollapse:i=>{let o=this.scene.panes.get(i);if(!o)return;let a=!o.collapsed;o.collapsed=a,this.afterPaneLayoutChange(),this.emitPaneAction({type:"collapse",paneId:i,collapsed:a});},onToggleMaximize:i=>{let o=this.maximizedPaneId!==i;this.maximizedPaneId=o?i:null,this.afterPaneLayoutChange(),this.emitPaneAction({type:"maximize",paneId:i,maximized:o});}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(this.wrapper),this.watchDpr(),this.syncSize();}makeDataCanvas(){let e=document.createElement("canvas");return Object.assign(e.style,{position:"absolute",inset:"0",width:"100%",height:"100%"}),e}createGeometryBackend(){if((this.backendMode==="auto"||this.backendMode==="webgl2")&&Ll()){let n=this.makeDataCanvas(),r=new qi;if(r.glow=this.glowAmount,r.onNeedsRedraw=()=>this.scheduler?.invalidate(4),r.onContextFailed=()=>this.swapToCanvas2dFallback(),r.mount(n),r.ok)return this.backend=r,n;r.destroy();}let e=this.makeDataCanvas(),t=new jn;return t.mount(e),this.backend=t,e}swapToCanvas2dFallback(){if(this.backend.kind==="canvas2d")return;let e=this.dataCanvas;this.input?.detach(),this.backend.destroy();let t=this.makeDataCanvas(),n=new jn;n.mount(t),this.backend=n,e.replaceWith(t),this.dataCanvas=t,this.input?.attach(t),this.syncSize();}watchDpr(){typeof window.matchMedia=="function"&&(this.dprMedia?.removeEventListener("change",this.onDprChange),this.dprMedia=window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.dprMedia.addEventListener("change",this.onDprChange,{once:true}));}setTheme(e){this.theme=this.deriveTheme(e),this.surfaceBackground=e.background,this.surfaceTextColor=e.textColor,this.wrapper&&ne(this.wrapper,this.chromeTheme()),this.applyBackground(),this.inputsUI.setTheme(e),this.paneControls?.setTheme(this.theme),this.settingsDialog?.refreshConfig(this.getConfig()),this.syncThemeControl(),this.settingsDialog?.setTheme(this.theme),this.settingsButton&&(this.settingsButton.style.background=this.theme.background,this.settingsButton.style.color=this.theme.textColor,this.settingsButton.style.borderColor=this.theme.borderColor),this.refreshScrollButtonTheme(),this.userDrawings?.setTheme(this.chromeTheme()),this.refreshAttributionColor(),this.scheduler.invalidate(4);}resize(){this.syncSize();}syncCountdownTimer(){this.scene.showCountdown?this.countdownTimer==null&&(this.countdownTimer=setInterval(()=>{this.scene.showCountdown&&this.scene.bars.length>0&&this.scheduler?.invalidate(2);},1e3)):this.countdownTimer!=null&&(clearInterval(this.countdownTimer),this.countdownTimer=null);}destroy(){this.introRaf!=null&&cancelAnimationFrame(this.introRaf),this.loadingEl?.remove(),this.loadingEl=null,this.countdownTimer!=null&&(clearInterval(this.countdownTimer),this.countdownTimer=null),this.scheduler?.destroy(),this.animator?.stop(),this.input?.detach(),this.keyboard?.detach(),this.keyboard=null,this.liveRegion=null,this.inputsUI?.destroy(),this.paneControls?.destroy();for(let e of this.tableOverlays.values())e.destroy();this.tableOverlays.clear(),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.dprMedia?.removeEventListener("change",this.onDprChange),this.dprMedia=null,this.userDrawings?.destroy(),this.userDrawings=null,this.settingsDialog?.destroy(),this.settingsDialog=null,this.settingsButton?.remove(),this.settingsButton=null,this.plot?.removeEventListener("pointermove",this.onScrollProximityMove),this.plot?.removeEventListener("pointerleave",this.onScrollProximityLeave),this.scrollButton?.remove(),this.scrollButton=null;for(let e of this.extLayers)e.instance.destroy?.();this.extLayers=[],this.volumeRenderer.destroy(),this.vpvrRenderer.destroy(),this.backend.destroy(),this.chrome.destroy(),this.crosshairLayer.destroy(),this.attributionEl?.remove(),this.attributionEl=null,this.mountContainer?.style.removeProperty("--vela-toolbar-gutter"),this.mountContainer?.style.removeProperty("--vela-scale-gutter"),this.mountContainer=null,this.wrapper?.remove();}setBars(e,t){this.introRaf!=null&&(cancelAnimationFrame(this.introRaf),this.introRaf=null,this.modelAlpha=1),this.liveEaseTime=0;let n=this.bars,r=n[0]?.time;this.bars=jb(e),this.scene.bars=this.bars,this.coords.setBars(this.bars.map(o=>o.time));for(let o of this.scene.indicators.values())this.refreshAnchorOffset(o);if(t?.preserveView===true&&r!=null&&this.bars.length>0){let o=this.bars[0].time,a=0;if(o!==r){let l=this.bars.findIndex(c=>c.time===r);if(l>0)a=l;else {let c=n.findIndex(d=>d.time===o);c>0&&(a=-c);}}a!==0&&(this.zoomAnchorLogical+=a,this.hoverLogical!=null&&(this.hoverLogical+=a));}let i=t?.preserveView===true&&this.didInitialFit;if(this.coords.width>0&&!i&&(this.fitContent(),this.didInitialFit=true),!this.introPlayed&&this.bars.length>0&&(this.introPlayed=true,this.introStyle)){this.playIntro(this.introStyle);return}this.scheduler.invalidate(4);}updateBar(e){let t=this.bars.length,n=this.bars[t-1];if(n&&e.time===n.time)this.bars[t-1]=e,this.liveEaseTime!==e.time&&this.syncLiveEase(e),this.animator.start();else if(!n||e.time>n.time)this.bars.push(e),this.syncLiveEase(e),this.coords.barInterval>0?this.coords.appendBar(e.time):this.coords.setBars(this.bars.map(r=>r.time));else return;this.scene.bars=this.bars,this.scheduler.invalidate(4);}syncLiveEase(e){this.liveEaseTime=e.time,this.liveEaseHigh=e.high,this.liveEaseLow=e.low,this.liveEaseClose=e.close;}easeLiveBar(e){let t=this.bars[this.bars.length-1];if(!t||this.liveEaseTime!==t.time)return false;let n=Math.max(1e-9,Math.abs(t.close)*1e-6),r=Se(this.liveEaseHigh,t.high,e,Ns),i=Se(this.liveEaseLow,t.low,e,Ns),o=Se(this.liveEaseClose,t.close,e,Ns),a=Math.abs(r-t.high)>n||Math.abs(i-t.low)>n||Math.abs(o-t.close)>n;return this.liveEaseHigh=a?r:t.high,this.liveEaseLow=a?i:t.low,this.liveEaseClose=a?o:t.close,a}ensurePane(e){this.scene.ensurePane(e.id,e.kind,e.order,e.heightWeight??(e.kind==="price"?3:1)),this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}removePane(e){e!==ge&&(this.scene.removePane(e),this.maximizedPaneId===e&&(this.maximizedPaneId=null),this.refreshAxisWidth(),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}setIndicatorPane(e,t,n){let r=this.scene.indicators.get(e.id);r&&(r.paneId=t,r.ownScale=n?.ownScale===true,r.ownScale||this.scene.dropIndicatorScale(e.id),this.inputsUI.setPane(e.id,t),this.refreshAnchorOffset(r),this.syncTables(r),this.refreshAxisWidth(),this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}orderPanes(e){this.scene.orderPanes(e),this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}setPaneCollapsed(e,t){let n=this.scene.panes.get(e);!n||n.collapsed===t||(n.collapsed=t,this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}setPaneMaximized(e){e!==null&&!this.scene.panes.has(e)&&(e=null),this.maximizedPaneId=e,this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}onPaneAction(e){return this.paneActionCbs.add(e),()=>this.paneActionCbs.delete(e)}emitPaneAction(e){for(let t of this.paneActionCbs)t(e);}onMoveIndicator(e){return this.moveIndicatorCbs.add(e),()=>this.moveIndicatorCbs.delete(e)}maxOwnScaleColumns(){let e=0;for(let t of this.scene.panes.values()){let n=this.scene.ownScaleIndicatorsForPane(t.id).length;n>e&&(e=n);}return e}refreshAxisWidth(){let e=wo+Rb*this.maxOwnScaleColumns();return e===this.rightAxisW?false:(this.rightAxisW=e,this.publishGutters(),this.coords.width>0&&this.syncSize(),true)}refreshAnchorOffset(e){let t=e.anchorTime;if(t==null||this.bars.length===0){this.scene.setAnchorOffset(e.id,0);return}let n=this.bars[0].time;if(t===n){this.scene.setAnchorOffset(e.id,0);return}if(t<n){let a=Ub(e,n);if(a==null){console.warn(`[vela] indicator "${e.id}" starts before the first bar with no series to align on \u2014 rendering unanchored`),this.scene.setAnchorOffset(e.id,0);return}this.scene.setAnchorOffset(e.id,-a);return}let r=0,i=this.bars.length-1,o=this.bars.length;for(;r<=i;){let a=r+i>>1;this.bars[a].time>=t?(o=a,i=a-1):r=a+1;}if(o>=this.bars.length||this.bars[o].time!==t){console.warn(`[vela] indicator "${e.id}" anchorTime matches no chart bar \u2014 rendering unanchored`),this.scene.setAnchorOffset(e.id,0);return}this.scene.setAnchorOffset(e.id,o);}mountIndicator(e){return this.scene.indicators.set(e.id,e),this.refreshAnchorOffset(e),this.scene.assignIndicatorZ(e.id),this.inputsUI.upsert(e.id,e.shorttitle??e.title,e.inputs,e.inputValues,e.paneId,{native:!!e.native,...e.shorttitle?{settingsTitle:e.title}:{}}),this.syncTables(e),e.native?.type==="volume"?(this.volumeActive=true,this.volumeHidden=false):e.native?.type==="vpvr"&&(this.vpvrActive=true,this.vpvrHidden=false),e.ownScale&&this.refreshAxisWidth(),this.paneControls?.refresh(),this.scheduler.invalidate(4),{id:e.id}}updateIndicator(e,t){let n=this.scene.indicators.get(e.id);if(n){if(t.kind==="value"&&t.anchorTime!==void 0){let r=t.anchorTime??void 0;r!==n.anchorTime&&(n.anchorTime=r,this.refreshAnchorOffset(n));}Gb(n,t),this.syncTables(n),this.scheduler.invalidate(3);}}removeIndicator(e){let t=this.scene.indicators.get(e.id)?.native?.type;t==="volume"?(this.volumeActive=false,this.volumeHidden=false,this.scene.volumeLayer=null):t==="vpvr"&&(this.vpvrActive=false,this.vpvrHidden=false,this.scene.vpvrLayer=null),this.scene.indicators.delete(e.id),this.scene.forgetIndicatorZ(e.id),this.scene.forgetAnchorOffset(e.id),this.scene.dropIndicatorScale(e.id),this.inputsUI.remove(e.id),this.tableOverlays.get(e.id)?.destroy(),this.tableOverlays.delete(e.id),this.refreshAxisWidth(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}setIndicatorInputs(e,t){this.inputsUI.setValues(e.id,t);}setSymbolPicker(e){this.symbolPicker=e,this.inputsUI?.setSymbolPicker(e);}setLegendActions(e){this.legendActionsProvider=e,this.inputsUI?.setLegendActions(e);}setLegendOverviewAction(e){this.legendOverviewAction=e,this.inputsUI?.setLegendOverviewAction(e);}openIndicatorSettings(e){this.inputsUI?.openSettingsFor(e);}setIndicatorVisible(e,t){let n=this.scene.indicators.get(e.id)?.native?.type;if(n==="volume"||n==="vpvr"){n==="volume"?this.volumeHidden=!t:this.vpvrHidden=!t,this.inputsUI.setVisible(e.id,t),this.scheduler.invalidate(4);return}t||(this.scene.indicators.delete(e.id),this.tableOverlays.get(e.id)?.destroy(),this.tableOverlays.delete(e.id)),this.inputsUI.setVisible(e.id,t),this.scheduler.invalidate(4);}onInputChange(e){return this.inputChangeCbs.add(e),()=>this.inputChangeCbs.delete(e)}onToggleIndicatorVisible(e){return this.toggleVisibleCbs.add(e),()=>this.toggleVisibleCbs.delete(e)}onPriceStyleChange(e){return this.priceStyleCbs.add(e),()=>this.priceStyleCbs.delete(e)}setPriceStyle(e){if(e!==this.scene.priceStyle){this.scene.priceStyle=e,this.scene.basePainting=rs(e),this.scene.candleOverride=$i(e,this.scene.style.chartTypes);for(let t of this.priceStyleCbs)t(e);}}onRemoveIndicator(e){return this.removeIndicatorCbs.add(e),()=>this.removeIndicatorCbs.delete(e)}setLayoutMode(e){if(e!==this.layoutMode){if(this.layoutMode=e,this.mountContainer?.setAttribute("data-vela-layout",e),this.userDrawings?.setLayoutMode(e),this.settingsDialog?.setLayoutMode(e),this.inputsUI?.setLayoutMode(e),this.scrollButton){let t=e==="mobile"?Vs:ir;this.scrollButton.style.width=`${t}px`,this.scrollButton.style.height=`${t}px`;}this.updateScrollToRealtimeButton();}}setSettingsSections(e){this.hostSettingsSections=e,this.settingsDialog?.setHostSections(e);}onChartTypeSettingsChange(e){return this.chartTypeSettingsCbs.add(e),()=>this.chartTypeSettingsCbs.delete(e)}onConfigChanged(e){return this.configChangedCbs.add(e),()=>this.configChangedCbs.delete(e)}onThemeSelect(e){return this.themeSelectCbs.add(e),()=>this.themeSelectCbs.delete(e)}onCrosshairMove(e){return this.crosshairCbs.add(e),()=>this.crosshairCbs.delete(e)}onClick(e){return this.clickCbs.add(e),()=>this.clickCbs.delete(e)}onAxisLongPress(e){return this.axisLongPressCbs.add(e),()=>this.axisLongPressCbs.delete(e)}onViewportChange(e){return this.viewportCbs.add(e),()=>this.viewportCbs.delete(e)}getVisibleRange(){let e=this.coords.barCount;if(e===0||this.coords.width===0)return null;let t=this.coords.visibleLogicalRange(),n=Math.max(0,Math.ceil(t.from)),r=Math.min(e-1,Math.floor(t.to));return r<n?null:{from:this.coords.logicalToTime(n),to:this.coords.logicalToTime(r)}}setVisibleRange(e){let t=this.coords.timeToLogical(e.from),n=this.coords.timeToLogical(e.to),r=Math.max(1e-6,n-t),i=Ke(this.coords.width/(r*this.coords.spacingScale)),o=n-(this.coords.barCount-1);this.applyViewport({barSpacing:i,rightOffset:o});}panBy(e){if(this.coords.barCount===0||this.coords.width===0)return;let t=this.coords.getViewport(),n=this.coords.width/this.coords.pxPerBar(),r=this.scrollTargetRO??t.rightOffset;this.glideRightOffset(this.clampViewport(t.barSpacing,r+e*n).rightOffset);}applyViewport(e){this.animator.stop(),this.panVelocity=0,this.scrollTargetRO=null;let t=this.clampViewport(e.barSpacing,e.rightOffset);this.coords.setViewport(t),this.targetBarSpacing=t.barSpacing,this.scheduler.invalidate(4),this.emitViewportChange();}zoomTo(e,t,n){let r=this.clampViewport(e,this.coords.getViewport().rightOffset).barSpacing;if(this.zoomAnchorLogical=t,this.zoomAnchorX=n,this.panVelocity=0,this.scrollTargetRO=null,!this.animZoom){let i=this.clampViewport(r,this.anchoredRightOffset(r));this.coords.setViewport(i),this.targetBarSpacing=i.barSpacing,this.scheduler.invalidate(4),this.emitViewportChange();return}this.targetBarSpacing=r,this.animator.start();}fling(e){this.animPan&&(this.scrollTargetRO=null,this.panVelocity=e,this.animator.start());}anchoredRightOffset(e){let t=e*this.coords.spacingScale;return this.zoomAnchorLogical+(this.coords.width-this.zoomAnchorX)/t-(this.coords.barCount-1)}clampViewport(e,t){let n=this.coords.barCount,r=this.coords.width;if(n<=1||r<=0)return {barSpacing:Ke(e),rightOffset:t};let i=Math.min(Bb,n),o=this.coords.spacingScale,a=Math.min(1e3,r/(i*o)),l=Math.max(.5,Math.min(a,r/((n+bd)*o))),c=Math.max(l,Math.min(a,e)),h=r/(c*o)-(i-1),u=i-n,p=Math.max(u,Math.min(h,t));return {barSpacing:c,rightOffset:p}}animTick(e){let t=this.coords.getViewport(),n=t.barSpacing,r=t.rightOffset,i=false,o=this.targetBarSpacing;Math.abs(n-o)>o*.001?(n=Ke(Se(n,o,e,Vb)),r=this.anchoredRightOffset(n),i=true):n!==o&&(n=o,r=this.anchoredRightOffset(n));let a=Hb/Math.max(1e-6,n*this.coords.spacingScale);if(Math.abs(this.panVelocity)>a&&(r+=this.panVelocity*e,this.panVelocity*=Math.exp(-e/_b),Math.abs(this.panVelocity)<=a?this.panVelocity=0:i=true),this.scrollTargetRO!=null){let c=this.scrollTargetRO,d=Se(r,c,e,Nb);Math.abs(d-c)<.001?(r=c,this.scrollTargetRO=null):(r=d,i=true);}let l=this.clampViewport(n,r);return l.barSpacing!==n&&(this.targetBarSpacing=l.barSpacing),this.scrollTargetRO!=null&&l.rightOffset!==r&&(this.scrollTargetRO=l.rightOffset),this.coords.setViewport(l),this.computeScales(),this.easeScales(e)&&(i=true),this.easeLiveBar(e)&&(i=true),this.skeletonClockMs+=e,this.paintData(),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx()),this.updateLegendValues(),this.emitViewportChange(),i}easeScales(e){let t=false;for(let n of this.scene.panes.values()){let r=n.scaleTarget,i=n.scale;if(r.log&&i.min>0&&r.min>0){let c=Math.log(r.min),d=Math.log(r.max),h=Math.max(1e-9,Math.abs(d-c)),u=Se(Math.log(i.min),c,e,pn),p=Se(Math.log(i.max),d,e,pn);Math.abs(u-c)<=h*.001&&Math.abs(p-d)<=h*.001?n.scale={min:r.min,max:r.max,log:true}:(t=true,n.scale={min:Math.exp(u),max:Math.exp(p),log:true});continue}let o=Math.max(1e-9,Math.abs(r.max-r.min)),a=Se(i.min,r.min,e,pn),l=Se(i.max,r.max,e,pn);Math.abs(a-r.min)<=o*.001&&Math.abs(l-r.max)<=o*.001?(a=r.min,l=r.max):t=true,n.scale={min:a,max:l,log:r.log};}for(let n of this.scene.indicatorScales.values()){let r=n.scaleTarget,i=n.scale,o=Math.max(1e-9,Math.abs(r.max-r.min)),a=Se(i.min,r.min,e,pn),l=Se(i.max,r.max,e,pn);Math.abs(a-r.min)<=o*.001&&Math.abs(l-r.max)<=o*.001?(a=r.min,l=r.max):t=true,n.scale={min:a,max:l};}return t}emitViewportChange(){this.updateScrollToRealtimeButton();let e=this.getVisibleRange();if(e)for(let t of this.viewportCbs)t(e);}handlePointerMove(e,t){if(e===null||t===null||this.coords.barCount===0){this.scene.crosshair=null,this.hoverSeparatorY=null,this.lastPointer=null,this.scheduler.invalidate(1),this.hoverLogical=null;let p={time:null,price:null,paneKind:null,values:new Map,ohlc:null};for(let m of this.crosshairCbs)m(p);return}let n=e>=0&&t>=0&&e<=this.coords.width&&t<=this.coords.height;this.scene.crosshair=n?{x:e,y:t}:null,this.lastPointer=n?{x:e,y:t}:null,this.hoverSeparatorY=e>=0&&t>=0&&t<=this.coords.height?this.separatorHoverY(t):null,this.scheduler.invalidate(1);let r=Math.round(this.coords.xToLogical(e)),i=r>=0&&r<this.coords.barCount,o=i?this.coords.logicalToTime(r):null,a=this.paneNodeAtY(t),l=n&&a?this.coords.yToPrice(t,a.scale,a.bounds):null,c=new Map;if(i)for(let p of this.scene.indicators.values()){let m=this.scene.offsetOf(p.id);for(let f of p.series)if(le(f)){let b=f.points[r-m]?.value;b!=null&&c.set(f.id,b);}}let d=i?this.bars[r]:void 0,h=d?{time:d.time,open:d.open,high:d.high,low:d.low,close:d.close,volume:d.volume}:null;this.hoverLogical=i?r:null;let u={time:o,price:l,paneKind:n&&a?a.kind:null,values:c,ohlc:h};for(let p of this.crosshairCbs)p(u);}handleClick(e){if(this.coords.barCount===0)return;let t=Math.round(this.coords.xToLogical(e)),n=t>=0&&t<this.coords.barCount;for(let r of this.clickCbs)r({time:n?this.coords.logicalToTime(t):null,price:null});}paneAtY(e){return this.paneNodeAtY(e)}paneNodeAtY(e){for(let t of this.scene.panes.values())if(e>=t.bounds.top&&e<=t.bounds.top+t.bounds.height)return t;return null}nearestPaneToY(e){let t=null,n=1/0;for(let r of this.scene.panes.values()){let i=e<r.bounds.top?r.bounds.top-e:e-(r.bounds.top+r.bounds.height);i<n&&(n=i,t=r);}return t}resolveScaleHolder(e,t){let n=this.paneNodeAtY(t);if(!n)return null;let r=this.coords.width,i=this.scene.ownScaleIndicatorsForPane(n.id);if(e>=r+64&&i.length>0){let o=Math.floor((e-r-64)/56),a=i[o];if(a)return {holder:this.scene.ensureIndicatorScale(a.id,n.scaleTarget),height:n.bounds.height}}return {holder:n,height:n.bounds.height}}beginPriceScale(e,t){let n=this.resolveScaleHolder(e,t);n&&(this.scaleDragHolder=n.holder,this.scaleDragHeight=n.height,this.scaleDragStart={...n.holder.scale},n.holder.manualScale={...n.holder.scale},this.scheduler.invalidate(4));}priceScaleBy(e){let t=this.scaleDragHolder,n=this.scaleDragStart;!t||!n||this.setManualScale(t,td(n,Math.exp(e*zb)));}beginPricePan(e){let t=this.paneNodeAtY(e);return !t||!t.manualScale?false:(this.scaleDragHolder=t,this.scaleDragHeight=t.bounds.height,this.scaleDragStart={...t.scale},true)}pricePanBy(e){let t=this.scaleDragHolder,n=this.scaleDragStart;!t||!n||this.setManualScale(t,nd(n,e,this.scaleDragHeight));}resetPriceScale(e,t){let n=this.resolveScaleHolder(e,t);n&&(n.holder.manualScale=null,this.scheduler.invalidate(4));}dataDblClick(e,t){let n=this.paneNodeAtY(t)??this.nearestPaneToY(t);if(!n)return;let r=this.maximizedPaneId!==n.id;this.maximizedPaneId=r?n.id:null,this.afterPaneLayoutChange(),this.emitPaneAction({type:"maximize",paneId:n.id,maximized:r});}resetView(){this.fitContent(),this.scheduler.invalidate(4),this.emitViewportChange();}setManualScale(e,t){e.manualScale=t,e.scale={...t},e.scaleTarget={...t},e.initialized=true,this.scheduler.invalidate(4);}afterPaneLayoutChange(){this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}paneControlViews(){let e=this.scene.orderedPanes();return e.map((t,n)=>({id:t.id,kind:t.kind,collapsed:t.collapsed,maximized:this.maximizedPaneId===t.id,top:t.bounds.top,height:t.bounds.height,index:n,count:e.length}))}movePaneLocal(e,t){let n=this.scene.orderedPanes(),r=n.findIndex(l=>l.id===e);if(r<0)return;let i=t==="up"?r-1:r+1;if(i<1||i>=n.length)return;let o=n.map(l=>l.id),a=o[r];o[r]=o[i],o[i]=a,this.scene.orderPanes(o),this.afterPaneLayoutChange(),this.emitPaneAction({type:"move",paneId:e,dir:t});}paneSeparatorAt(e){return this.separatorPaneIndexAt(e)!==null}separatorHoverY(e){if(!this.paneResizeEnabled)return null;let t=this.separatorPaneIndexAt(e);return t===null?null:this.scene.orderedPanes()[t].bounds.top}separatorPaneIndexAt(e){let t=this.scene.orderedPanes();for(let n=1;n<t.length;n++)if(Math.abs(e-t[n].bounds.top)<=Wb)return n;return null}beginPaneResize(e){let t=this.separatorPaneIndexAt(e);if(t===null)return;let n=this.scene.orderedPanes(),r=n[t-1],i=n[t];this.resizeAbove=r,this.resizeBelow=i,this.resizeSplitStart={combinedTop:r.bounds.top,combinedHeight:r.bounds.height+i.bounds.height,combinedWeight:r.heightWeight+i.heightWeight,startBoundaryY:i.bounds.top};}paneResizeBy(e){let t=this.resizeAbove,n=this.resizeBelow,r=this.resizeSplitStart;if(!t||!n||!r)return;let i=rd(r,e);t.heightWeight=i.above,n.heightWeight=i.below,this.layoutPanes(),this.repositionTables(),this.scheduler.invalidate(4);}resetPaneSize(e){let t=this.separatorPaneIndexAt(e);if(t===null)return;let n=this.scene.orderedPanes(),r=n[t-1],i=n[t],o=(r.heightWeight+i.heightWeight)/2;r.heightWeight=o,i.heightWeight=o,this.layoutPanes(),this.repositionTables(),this.scheduler.invalidate(4);}setKeyboardEnabled(e){this.keyboardEnabled=e,!(!this.dataCanvas||!this.keyboard)&&(e?(this.dataCanvas.tabIndex=0,this.dataCanvas.setAttribute("role","application"),this.dataCanvas.setAttribute("aria-label","Interactive price chart. Use Left/Right arrows to move between bars, Shift+Arrow to pan, plus/minus to zoom, Home/End to jump, 0 to reset."),!this.liveRegion&&this.wrapper&&(this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("role","status"),Object.assign(this.liveRegion.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:"0"}),this.wrapper.appendChild(this.liveRegion)),this.keyboard.attach(this.dataCanvas)):(this.keyboard.detach(),this.dataCanvas.removeAttribute("tabindex"),this.dataCanvas.removeAttribute("role"),this.dataCanvas.removeAttribute("aria-label")));}panByBars(e){let t=this.coords.getViewport();this.applyViewport({barSpacing:t.barSpacing,rightOffset:t.rightOffset+e});}zoomByStep(e){let t=this.coords.getViewport(),n=Ke(t.barSpacing*Math.exp(e*$b));this.zoomTo(n,this.coords.rightEdgeLogical,this.coords.width);}stepCrosshair(e){let t=this.coords.barCount;if(t===0)return;let n=this.hoverLogical??Math.min(t-1,Math.round(this.coords.xToLogical(this.coords.width)));this.focusBar(n+e);}focusBar(e){let t=this.coords.barCount;if(t===0)return;let n=Math.max(0,Math.min(t-1,e)),r=this.coords.getViewport(),i=2,o=this.coords.xToLogical(0),a=this.coords.xToLogical(this.coords.width),l=r.rightOffset;n<o+i?l-=o+i-n:n>a-i&&(l+=n-(a-i)),l!==r.rightOffset&&this.applyViewport({barSpacing:r.barSpacing,rightOffset:l});let c=this.scene.orderedPanes().find(h=>h.kind==="price")??this.scene.orderedPanes()[0]??null,d=this.scene.crosshair?.y??(c?c.bounds.top+c.bounds.height/2:this.coords.height/2);this.handlePointerMove(this.coords.logicalToX(n),d),this.announceBar(n);}announceBar(e){if(!this.liveRegion)return;let t=this.bars[e],n=this.dataWindowPricePane(),r=this.dataWindowOHLC(t,n),i=[];t&&i.push(Yb(t.time,this.scene.timezone)),r&&i.push(`Open ${r.o}, High ${r.h}, Low ${r.l}, Close ${r.c}`);for(let o of this.dataWindowGroups(e,n))for(let a of o.rows)i.push(`${a.label} ${a.value}`);this.liveRegion.textContent=i.join(". ");}getDataWindowReadout(){let e=this.bars.length;if(e===0)return {date:"",time:"",ohlc:null,groups:[]};let t=this.hoverLogical!=null?this.hoverLogical:e-1,n=this.bars[t],r=this.dataWindowPricePane(),i=n?xd(n.time,this.scene.timezone):{date:"",time:""};return {date:i.date,time:i.time,ohlc:this.dataWindowOHLC(n,r),groups:this.dataWindowGroups(t,r)}}dataWindowPricePane(){return this.scene.orderedPanes().find(e=>e.kind==="price")??null}dataWindowFmt(e,t){return t?zi(t.scale,t.bounds.height,e,this.scene.priceMintick):String(e)}dataWindowOHLC(e,t){return e?{o:this.dataWindowFmt(e.open,t),h:this.dataWindowFmt(e.high,t),l:this.dataWindowFmt(e.low,t),c:this.dataWindowFmt(e.close,t),vol:e.volume!=null?vd(e.volume):void 0,up:e.close>=e.open}:null}dataWindowGroups(e,t){let n=[];for(let r of this.scene.indicators.values()){let i=this.dataWindowRowsFor(r,e,t);i.length&&n.push({name:r.title,rows:i});}return n}dataWindowRowsFor(e,t,n){if(e.native?.type==="volume")return this.volumeReadoutRows(e,t);let r=(e.paneId?this.scene.panes.get(e.paneId):null)??n,i=this.scene.offsetOf(e.id),o=[];for(let a of e.series){let l,c;if(a.kind==="candle"||a.kind==="bar")l=a.bars[t-i]?.close,c=a.style?.up??this.theme.upColor;else if(le(a)){if(a.visible===false)continue;l=a.points[t-i]?.value,c=a.points[t-i]?.color??a.style.color;}else continue;l==null||!Number.isFinite(l)||o.push({label:a.title||e.title,value:this.dataWindowFmt(l,r),color:c});}return o}volumeReadoutRows(e,t){if(this.volumeHidden)return [];let n=this.bars[t],r=n?.volume;if(n==null||r==null||!Number.isFinite(r))return [];let i=this.scene.volumeLayer,o=n.close>=n.open?i?.upColor??this.theme.upColor:i?.downColor??this.theme.downColor;return [{label:e.title,value:vd(r),color:o}]}updateLegendValues(){if(!this.inputsUI)return;let e=this.bars.length,t=new Map;if(e>0){let n=this.hoverLogical!=null?this.hoverLogical:e-1,r=this.dataWindowPricePane();for(let i of this.scene.indicators.values())t.set(i.id,this.dataWindowRowsFor(i,n,r).map(o=>({value:o.value,color:o.color})));}this.inputsUI.setPlotValues(t);}renderFrame(e){this.animator.active||(bs(e)?(this.computeScales(),this.paintData()):sc(e)&&this.paintedData&&(this.chrome.prepare(this.scene,this.coords,this.theme),this.chrome.render(this.scene,this.coords,this.theme,this.axisSurface())),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx()),!bs(e)&&this.paintedData&&this.repaintCursorLayers(),this.updateLegendValues());}repaintCursorLayers(){let e=this.scene.panes.get(ge);if(!e)return;let t=typeof performance<"u"?performance.now():Date.now();for(let n of this.extLayers)n.def.repaintOnCursor&&(n.instance.render(this.extLayerArgs(n.def.id,e.scale,e.bounds,t)),this.animZoom&&n.instance.animating?.()&&this.animator.start());}extLayerArgs(e,t,n,r){return {bars:this.scene.bars,data:this.scene.nativeData.get(e),settings:this.scene.nativeData.get(`${e}-settings`)??{},pending:this.scene.nativePending.get(e)??[],coords:this.coords,scale:t,bounds:n,theme:this.theme,priceStyle:this.scene.priceStyle,nowMs:r,cursor:this.lastPointer}}paintData(){this.stampScaleInvert(),this.backend.modelAlpha=this.modelAlpha,this.backend.candleBodyAlpha=this.candleBodyAlpha,this.backend.candleStructureAlpha=this.candleStructureAlpha,this.backend.gridAlpha=1;let e=1;this.backend.candleBodyScale=e;let t=this.scene.panes.get(ge);if(t){let o=this.nativeLayerPane("volume")??t;this.volumeRenderer.render({bars:this.scene.bars,data:this.scene.volumeLayer,visible:this.volumeActive&&!this.volumeHidden&&!o.collapsed,coords:this.coords,bounds:o.bounds,fillPane:o.kind!=="price"}),this.vpvrRenderer.render({bars:this.scene.bars,data:this.scene.vpvrLayer,visible:this.vpvrActive&&!this.vpvrHidden,coords:this.coords,scale:t.scale,bounds:t.bounds,theme:this.theme});let a=typeof performance<"u"?performance.now():Date.now();for(let l of this.extLayers){let c=this.extLayerArgs(l.def.id,t.scale,t.bounds,a);if(l.instance.render(c),l.def.id===this.scene.priceStyle&&l.instance.modulateBase){let d=l.instance.modulateBase(c);d&&(d.candleBodyScale!=null&&(this.backend.candleBodyScale=Hs(d.candleBodyScale)||.01),d.candleBodyAlpha!=null&&(this.backend.candleBodyAlpha=Hs(d.candleBodyAlpha)*this.candleBodyAlpha),d.gridAlpha!=null&&(this.backend.gridAlpha=Hs(d.gridAlpha)));}this.animZoom&&l.instance.animating?.()&&this.animator.start();}}let n=this.bars.length-1,r=n>=0?this.bars[n]:void 0,i=!!r&&this.liveEaseTime===r.time&&(r.high!==this.liveEaseHigh||r.low!==this.liveEaseLow||r.close!==this.liveEaseClose);i&&r&&(this.bars[n]={...r,high:this.liveEaseHigh,low:this.liveEaseLow,close:this.liveEaseClose}),this.scene.drawingSlices=this.userDrawings?.prepareSlices(this.scene.orderedPanes().map(o=>o.id))??new Map,this.backend.render(this.scene,this.coords,this.theme),this.chrome.render(this.scene,this.coords,this.theme,this.axisSurface()),this.userDrawings?.render(),i&&r&&(this.bars[n]=r),this.paintedData=true;}drawingProjector(){return Zc(this.coords,e=>{let t=this.scene.panes.get(e);return t?{scale:t.scale,bounds:t.bounds,collapsed:t.collapsed}:null},e=>this.paneNodeAtY(e)?.id??null,(e,t)=>this.barsInTimeRange(e,t))}barsInTimeRange(e,t){let n=Math.min(e,t),r=Math.max(e,t),i=[];for(let o of this.bars)if(!(o.time<n)){if(o.time>r)break;i.push(o);}return i}get userDrawingsPort(){return this.userDrawings??void 0}focus(){this.dataCanvas?.focus({preventScroll:true});}setExternalCrosshair(e,t=null){let n=e==null?null:{time:e,price:t},r=this.externalCross;!n&&!r||n&&r&&r.time===n.time&&r.price===n.price||(this.externalCross=n,this.scheduler.invalidate(1));}externalCrossPx(){let e=this.externalCross;if(!e||this.coords.barCount===0)return null;let t=Math.floor(this.coords.timeToLogical(e.time));if(t<0||t>=this.coords.barCount)return null;let n=this.coords.logicalToX(t);if(!Number.isFinite(n)||n<0||n>this.coords.width)return null;let r=null;if(e.price!=null){let i=this.scene.orderedPanes().find(o=>o.kind==="price");i&&(r=this.coords.priceToY(e.price,i.scale,i.bounds),(!Number.isFinite(r)||r<i.bounds.top||r>i.bounds.top+i.bounds.height)&&(r=null));}return {x:n,y:r,time:this.coords.logicalToTime(t),price:r!=null?e.price:null}}setSnapMode(e){this.snapMode=e;}snapToCandle(e,t,n="strong",r){if(n==="off")return e;let i=this.bars.length;if(i===0)return e;let o=Math.max(0,Math.min(i-1,Math.round(this.coords.timeToLogical(e.time)))),a=this.bars[o];if(!a)return e;let l;if(t!==ge)l={time:a.time,price:e.price};else {let c=a.open;for(let d of [a.high,a.low,a.close])Math.abs(d-e.price)<Math.abs(c-e.price)&&(c=d);l={time:a.time,price:c};}if(n==="weak"&&r){let c=this.drawingProjector(),d=c.yOf(l.price,t);if(Math.hypot(c.xOf(l.time)-r.x,(d??r.y)-r.y)>kb)return e}return l}computeScales(){let e=this.coords.barCount;if(e===0)return;let t=this.coords.visibleLogicalRange(),n=this.coords.visibleTimeRange(),r=Math.max(0,Math.floor(t.from)),i=Math.min(e-1,Math.ceil(t.to));if(i<r)return;this.scene.percentBaseline=this.bars[r]?.close??0;let o=this.scene.orderedPanes(),a=o.find(c=>c.kind==="price")??null;this.chrome.prepare(this.scene,this.coords,this.theme);let l=this.animator.active;for(let c of o){if(c.manualScale){c.scaleTarget=c.manualScale,c.scale={...c.manualScale},c.initialized=true;continue}let h=this.scene.indicatorsForPane(c.id).filter(f=>f.ownScale!==true),u=this.chrome.paneDrawingsRange(h,this.scene,c===a,t),p=this.userDrawings?.priceRangeForPane(c.id,n.from,n.to)??null;p&&(u=u?{min:Math.min(u.min,p.min),max:Math.max(u.max,p.max)}:p);let m=c.kind==="price"&&!this.scene.candlesHidden;if(c.scaleTarget=ks(h,this.bars,m,r,i,u,ds(this.scene,c),f=>this.scene.offsetOf(f)),c.percentBaseline=c.kind==="price"?this.bars[r]?.close??0:this.firstVisibleValue(h,r),c.axisFormat=void 0,this.volumeOwnsPane(c,h)){let f=this.maxVisibleVolume(r,i);f>0&&(c.scaleTarget={min:0,max:f/Is},c.axisFormat="volume");}if(c===a&&this.scene.tradeMarkers.visible&&c.bounds.height>0){let f=this.tradesScaleHints(t);if(f){let b=c.scaleTarget,g={...b,min:Math.min(b.min,f.min),max:Math.max(b.max,f.max)};c.scaleTarget=ed(g,c.bounds.height,f.abovePx,f.belowPx);}}(!l||!c.initialized)&&(c.scale={...c.scaleTarget},c.initialized=true);for(let f of this.scene.ownScaleIndicatorsForPane(c.id)){let b=this.scene.ensureIndicatorScale(f.id,c.scaleTarget);if(b.manualScale){b.scaleTarget=b.manualScale,b.scale={...b.manualScale},b.initialized=true;continue}let g=this.chrome.paneDrawingsRange([f],this.scene,false,t);b.scaleTarget=ks([f],this.bars,false,r,i,g,false,v=>this.scene.offsetOf(v)),(!l||!b.initialized)&&(b.scale={...b.scaleTarget},b.initialized=true);}}}tradesScaleHints(e){let t=null,n={timeToLogical:r=>this.coords.timeToLogical(r),barAt:r=>{let i=this.bars[Math.round(r)];return i?{high:i.high,low:i.low}:null}};for(let r of this.scene.indicators.values()){if(!r.trades?.length)continue;let i=jl(r.trades,this.scene.tradeMarkers,n,e.from,e.to,this.scene.style.fontSize);i&&(t=t?{min:Math.min(t.min,i.min),max:Math.max(t.max,i.max),abovePx:Math.max(t.abovePx,i.abovePx),belowPx:Math.max(t.belowPx,i.belowPx)}:i);}return t}fitContent(){let e=this.coords.barCount,t=this.coords.width;if(e<=0||t<=0)return;this.animator?.stop(),this.panVelocity=0;for(let o of this.scene.panes.values())o.manualScale=null;for(let o of this.scene.indicatorScales.values())o.manualScale=null;let n=Math.min(e,200),r=6,i=this.clampViewport(t/((n+r)*this.coords.spacingScale),r);this.coords.setViewport(i),this.targetBarSpacing=i.barSpacing;}paneBoundsFor(e){let t=this.scene.panes.get(e);return {top:t?.bounds.top??0,height:t?.bounds.height??0,rightAxis:this.rightAxisW}}paneMasterTitle(e){let t=this.scene.orderedIndicatorsForPane(e);return (t.find(r=>r.ownScale!==true)??t[0])?.title||null}nativeLayerPane(e){for(let t of this.scene.indicators.values())if(t.native?.type===e)return this.scene.panes.get(t.paneId??ge)??null;return null}volumeOwnsPane(e,t){return e.kind==="price"||!this.volumeActive||this.volumeHidden||!this.scene.volumeLayer||this.nativeLayerPane("volume")!==e?false:t.every(n=>n.native?.type==="volume")}paneScaleInfos(){return this.scene.orderedPanes().map(e=>({id:e.id,kind:e.kind,top:e.bounds.top,height:e.bounds.height,mode:cs(this.scene,e),log:ds(this.scene,e),invert:hs(this.scene,e)}))}setPaneScaleMode(e,t){if(e===ge)this.scene.scaleMode=t;else {let n=this.scene.panes.get(e);if(!n)return;n.scaleMode=t;}this.scheduler?.invalidate(4);}setPaneLog(e,t){if(e===ge){this.scene.logScale=t;let n=this.scene.orderedPanes().find(r=>r.kind==="price");n&&(n.manualScale=null);}else {let n=this.scene.panes.get(e);if(!n)return;n.logScale=t,n.manualScale=null;}this.scheduler?.invalidate(4);}setPaneInvert(e,t){if(e===ge)this.scene.invertScale=t;else {let n=this.scene.panes.get(e);if(!n)return;n.invert=t;}this.scheduler?.invalidate(4);}stampScaleInvert(){for(let e of this.scene.panes.values()){let t=hs(this.scene,e);e.scale.invert=t,e.scaleTarget.invert=t,e.manualScale&&(e.manualScale.invert=t);for(let n of this.scene.ownScaleIndicatorsForPane(e.id)){let r=this.scene.indicatorScales.get(n.id);r&&(r.scale.invert=t,r.scaleTarget.invert=t,r.manualScale&&(r.manualScale.invert=t));}}}firstVisibleValue(e,t){for(let n of e){let r=this.scene.offsetOf(n.id);for(let i of n.series)if(le(i)){let o=i.points[t-r]?.value;if(o!=null&&Number.isFinite(o))return o}else if(i.kind==="candle"||i.kind==="bar"){let o=i.bars[t-r];if(o&&Number.isFinite(o.close))return o.close}}return 0}maxVisibleVolume(e,t){let n=0;for(let r=e;r<=t;r+=1){let i=this.bars[r]?.volume;i!=null&&i>n&&(n=i);}return n}syncTables(e){let t=e.tables??[],n=this.tableOverlays.get(e.id);if(t.length===0){n&&(n.destroy(),this.tableOverlays.delete(e.id));return}n||(n=new _i(this.plot,this.theme,r=>this.paneBoundsFor(r)),n.setVisible(this.loadingEl===null),this.tableOverlays.set(e.id,n)),n.update(t);}repositionTables(){for(let e of this.tableOverlays.values())e.reposition();}layoutPanes(){let e=this.scene.orderedPanes(),t=this.coords.height;this.inputsUI?.setCollapsedPanes(this.collapsedMasterMap());let n=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null;if(n){let d=0;for(let h of e)h===n?h.bounds={top:0,height:t}:h.bounds={top:t,height:0},d+=h.bounds.height;this.inputsUI?.reposition(),this.paneControls?.reposition(),this.repositionScrollButton(),this.positionAttribution();return}let r=e.filter(d=>d.collapsed),i=e.filter(d=>!d.collapsed),o=r.length*md,a=Math.max(0,t-o),l=i.reduce((d,h)=>d+(h.heightWeight||1),0)||1,c=0;for(let d of e){let h=d.collapsed?md:a*(d.heightWeight||1)/l;d.bounds={top:c,height:h},c+=h;}this.inputsUI?.reposition(),this.paneControls?.reposition(),this.repositionScrollButton(),this.positionAttribution();}repositionScrollButton(){let e=this.coords.height;if(e<=0)return;let t=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null,n=t?[t]:this.scene.orderedPanes().filter(i=>!i.collapsed),r=n.length?Math.max(...n.map(i=>i.bounds.top+i.bounds.height)):e;this.scrollBtnBottomPx=_s+Math.max(0,e-r),this.scrollBtnRightPx=this.rightAxisW+yd,this.scrollButton&&(this.scrollButton.style.bottom=`${this.scrollBtnBottomPx}px`,this.scrollButton.style.right=`${this.scrollBtnRightPx}px`);}collapsedMasterMap(){let e=new Map;for(let t of this.scene.panes.values()){if(!t.collapsed)continue;let n=this.scene.orderedIndicatorsForPane(t.id),r=new Set(this.scene.ownScaleIndicatorsForPane(t.id).map(o=>o.id)),i=n.find(o=>!r.has(o.id))??n[0];e.set(t.id,i?.id??null);}return e}setToolbarGutter(e){e!==this.toolbarGutter&&(this.toolbarGutter=e,this.publishGutters(),this.positionAttribution(),this.syncSize());}publishGutters(){this.mountContainer?.style.setProperty("--vela-toolbar-gutter",`${this.toolbarGutter}px`),this.mountContainer?.style.setProperty("--vela-scale-gutter",`${this.rightAxisW}px`);}buildAttributionEl(){return this.attributionHtml!==null?ld(document,this.attributionHtml,this.theme.background):cd(document,this.theme.background)}rebuildAttribution(){this.attributionEl&&(this.attributionEl.remove(),this.attributionEl=this.buildAttributionEl(),this.attributionEnabled||(this.attributionEl.style.display="none"),this.positionAttribution(),this.wrapper.appendChild(this.attributionEl));}positionAttribution(){if(!this.attributionEl)return;let e=this.coords?.height??0,t=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null,n=t?[t]:this.scene.orderedPanes().filter(i=>!i.collapsed),r=e>0&&n.length?Math.max(...n.map(i=>i.bounds.top+i.bounds.height)):e;Object.assign(this.attributionEl.style,{left:`${(this.toolbarGutter||0)+12}px`,bottom:`${So+10+Math.max(0,e-r)}px`});}refreshAttributionColor(){this.attributionEl&&(this.attributionHtml!==null?this.attributionEl.style.color=As(this.theme.background):Os(this.attributionEl,this.theme.background));}syncSize(){let e=this.wrapper.clientWidth,t=this.wrapper.clientHeight;if(e<=0||t<=0)return;let n=window.devicePixelRatio||1;this.plot.style.left=`${this.toolbarGutter}px`;let r=Math.max(1,e-this.toolbarGutter),i=t;this.dataCanvas.width=Math.round(r*n),this.dataCanvas.height=Math.round(i*n),this.volumeCanvas.width=this.dataCanvas.width,this.volumeCanvas.height=this.dataCanvas.height;for(let o of this.extLayers)o.canvas.width=this.dataCanvas.width,o.canvas.height=this.dataCanvas.height;this.vpvrCanvas.width=this.dataCanvas.width,this.vpvrCanvas.height=this.dataCanvas.height,this.chromeCanvas.width=this.dataCanvas.width,this.chromeCanvas.height=this.dataCanvas.height,this.drawingsCanvas.width=this.dataCanvas.width,this.drawingsCanvas.height=this.dataCanvas.height,this.cursorCanvas.width=this.dataCanvas.width,this.cursorCanvas.height=this.dataCanvas.height,this.coords.setSize(Math.max(1,r-this.rightAxisW),Math.max(1,i-So),n),this.scene.crosshair=null,this.layoutPanes(),this.repositionTables(),this.userDrawings?.onResize(),!this.didInitialFit&&this.coords.barCount>0&&(this.fitContent(),this.didInitialFit=true),this.animator.active?(this.computeScales(),this.paintData(),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx())):this.scheduler.flushNow(4);}applyBackground(){this.wrapper.style.background=this.theme.background;}};function Ub(s,e){for(let t of s.series){let n=t.kind==="candle"||t.kind==="bar"?t.bars:le(t)?t.points:null;if(!n||n.length===0)continue;let r=0,i=n.length;for(;r<i;){let o=r+i>>1;n[o].time<e?r=o+1:i=o;}return r}return null}function Gb(s,e){if(e.kind==="value"){for(let t of e.series){let n=s.series.find(r=>r.id===t.seriesId);n&&(t.kind==="points"&&le(n)?n.points=t.points:t.kind==="bars"&&(n.kind==="candle"||n.kind==="bar")&&(n.bars=t.bars));}e.lines&&(s.lines=e.lines),e.boxes&&(s.boxes=e.boxes),e.labels&&(s.labels=e.labels),e.polylines&&(s.polylines=e.polylines),e.linefills&&(s.linefills=e.linefills),e.tables&&(s.tables=e.tables),e.trades&&(s.trades=e.trades);return}for(let t of e.removed){let n=s.series.findIndex(r=>r.id===t);n>=0&&s.series.splice(n,1);}for(let t of e.added)s.series.push(t);}function xd(s,e){let t=Yi(s,e),n=r=>r<10?`0${r}`:String(r);return {date:`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())}`,time:`${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}}function Yb(s,e){let{date:t,time:n}=xd(s,e);return `${t} ${n}`}function Xb(s){if(!Array.isArray(s))return [];let e=[];for(let t of s){if(!t||typeof t!="object")continue;let n=t,r=Number(n.from),i=Number(n.to);!Number.isFinite(r)||!Number.isFinite(i)||i<=r||e.push({from:r,to:i,color:typeof n.color=="string"?n.color:"rgba(120,130,160,0.10)"});}return e.sort((t,n)=>t.from-n.from)}function Hs(s){return Math.max(0,Math.min(1,s))}function Kb(s){return typeof s=="string"&&tn().includes(s)}function gd(s){return s==="percent"||s==="indexed"?s:"price"}function vd(s){let e=Math.abs(s);return e>=1e9?`${(s/1e9).toFixed(2)}B`:e>=1e6?`${(s/1e6).toFixed(2)}M`:e>=1e3?`${(s/1e3).toFixed(2)}K`:s.toFixed(2)}function jb(s){let e=[...s].sort((n,r)=>n.time-r.time),t=[];for(let n of e){let r=t[t.length-1];r&&r.time===n.time?t[t.length-1]=n:t.push(n);}return t}function zs(s,e){let t=(s.open+s.high+s.low+s.close)/4,n=e?(e.open+e.close)/2:(s.open+s.close)/2;return {time:s.time,open:n,high:Math.max(s.high,n,t),low:Math.min(s.low,n,t),close:t,...s.volume!=null?{volume:s.volume}:{}}}function wd(s){let e=new Array(s.length),t;for(let n=0;n<s.length;n+=1)t=zs(s[n],t),e[n]=t;return e}var qb={full:wd,next:zs};function Sd(){Wo({id:"heikinashi",label:"Heikin Ashi",barTransform:qb});}var $s=q,Ws=X,Us=20;function Zb(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Cd(s,e){return typeof s=="string"&&s!==""?s:e}function Co(s){return {upColor:Cd(s.upColor,$s),downColor:Cd(s.downColor,Ws),heightFrac:Math.min(.5,Math.max(.05,Zb(s.heightPct,Us)/100))}}var Gs=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(Co(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData(Co(e));}suspend(){}resume(){this.ctx.pushData(Co(this.inputs));}stop(){}},Td={type:"volume",title:"Volume",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"upColor",title:"Up color",type:"color",defval:$s},{key:"downColor",title:"Down color",type:"color",defval:Ws},{key:"heightPct",title:"Height %",type:"int",defval:Us,min:5,max:50,step:1,tooltip:"Pane height the tallest visible bar occupies"}],defaultInputs:()=>({upColor:$s,downColor:Ws,heightPct:Us}),create:()=>new Gs};function Ys(){_t(Td);}var Ks=24,js=30,qs=ve,Zs=X,Js=70;function Xs(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Md(s,e){return typeof s=="string"&&s!==""?s:e}function To(s){return {rows:Math.round(Math.min(400,Math.max(2,Xs(s.rows,Ks)))),widthFrac:Math.min(.9,Math.max(.05,Xs(s.widthPct,js)/100)),upColor:Md(s.upColor,qs),downColor:Md(s.downColor,Zs),showPoc:s.showPoc!==false,valueAreaFrac:Math.min(1,Math.max(0,Xs(s.valueAreaPct,Js)/100))}}var Qs=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(To(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData(To(e));}suspend(){}resume(){this.ctx.pushData(To(this.inputs));}stop(){}},Ld={type:"vpvr",title:"Visible Range Volume Profile",shortTitle:"VRVP",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"rows",title:"Rows",type:"int",defval:Ks,min:2,max:400,step:1},{key:"widthPct",title:"Width %",type:"int",defval:js,min:5,max:90,step:1,tooltip:"Pane width the largest row occupies"},{key:"upColor",title:"Up color",type:"color",defval:qs},{key:"downColor",title:"Down color",type:"color",defval:Zs},{key:"showPoc",title:"Point of control",type:"bool",defval:true},{key:"valueAreaPct",title:"Value area %",type:"int",defval:Js,min:0,max:100,step:1}],defaultInputs:()=>({rows:Ks,widthPct:js,upColor:qs,downColor:Zs,showPoc:true,valueAreaPct:Js}),create:()=>new Qs};function ea(){_t(Ld);}var ta=class{constructor(e,t={},n={}){Sd(),Ys(),ea();let r=Jb(e),i=Xt(t.theme),o=true,a=true;typeof t.animations=="boolean"?(o=t.animations,a=t.animations):t.animations&&(o=t.animations.zoom??true,a=t.animations.pan??true);let l={currentPriceLine:t.currentPriceLine??true,logScale:t.logScale??false,nativeBackend:t.nativeBackend??"auto",animZoom:o,animPan:a,glow:t.glow??0,upColor:t.upColor??q,downColor:t.downColor??X,priceStyle:t.priceStyle??"candles"},c=t.renderer??or;if(typeof c!="function")throw new Error("[vela] options.renderer must be a renderer class, e.g. import { LwcRenderer } from 'vela/renderers/lwc'. The 'lwc'/'native' string options were removed.");let d=n.renderer??new c(l),h=n.engines??[],u=n.dataFeed??new Pt,p={market:{symbol:t.symbol,timeframe:t.timeframe,bars:t.bars,visibleRange:t.visibleRange,data:t.data},live:t.live??false,theme:i,defaultLanguage:t.defaultLanguage??h[0]?.language??"pine",drawings:t.drawings,volume:t.volume??true};this.rendererControl=new On(d),this.dataControl=new _n(u),this.orchestrator=new Ii(r,d,u,h,p,this.dataControl);let m=Go();Object.keys(m).length>0&&this.rendererControl.set(m),this.panesControl=new Ri(this.orchestrator),this.drawingsControl=new Nn(this.orchestrator.drawings);}registerEngine(e,t){return this.orchestrator.registerEngine(e,t),this}addIndicator(e,t){return this.orchestrator.addIndicator(e,t)}addNativeIndicator(e,t){return this.orchestrator.addNativeIndicator(e,t)}availableNativeIndicators(){return this.orchestrator.availableNativeIndicators()}presentNativeIndicators(){return this.orchestrator.presentNativeIndicators()}indicators(){return this.orchestrator.listIndicators()}runScript(e,t){let n=this.addIndicator(e,t),r=new Set,i=()=>{try{n.remove();}catch{}};return new Promise(o=>{let a=false,l=this.on("script:run",d=>{if(d.id===n.id){if(a){for(let h of r)h(d);return}a=true,c(),o({ok:true,run:d,error:null,onUpdate:h=>(r.add(h),()=>r.delete(h)),remove:()=>{l(),r.clear(),i();}});}}),c=n.on("error",({error:d})=>{a||(a=true,l(),c(),i(),o({ok:false,run:null,error:d,onUpdate:()=>()=>{},remove:()=>{}}));});})}runIndicator(e,t){let n=this.addIndicator(e,t);return new Promise(r=>{let i=n.on("ready",()=>{i(),o(),r({ok:true,handle:n,error:null,context:null});}),o=n.on("error",({error:a})=>{i(),o(),n.context().catch(()=>null).then(l=>{try{n.remove();}catch{}r({ok:false,handle:null,error:a,context:l});});});})}setMarket(e){return this.orchestrator.setMarket(e)}get market(){return this.orchestrator.marketSnapshot()}ready(){return this.orchestrator.ready()}historyComplete(){return this.orchestrator.historyComplete()}inspect(){return this.orchestrator.inspect()}get renderer(){return this.rendererControl}get panes(){return this.panesControl}get data(){return this.dataControl}get drawings(){return this.drawingsControl}on(e,t){return this.orchestrator.events.on(e,t)}getVisibleRange(){return this.orchestrator.getVisibleRange()}setVisibleRange(e){return this.orchestrator.setVisibleRange(e),this}panBy(e){return this.orchestrator.panBy(e),this}setVisibleRangePreset(e){return this.orchestrator.setVisibleRangePreset(e),this}resize(){this.orchestrator.resize();}setTheme(e){return this.orchestrator.setTheme(Xt(e)),this}destroy(){this.orchestrator.destroy();}};function Jb(s){if(typeof s!="string")return s;let e=document.querySelector(s);if(!e)throw new Error(`[vela] container not found for selector "${s}"`);return e}var sr=new Map,ar=new Map,lr=new Map;function Qb(s){return ar.set(s.id,s),()=>{ar.get(s.id)===s&&ar.delete(s.id);}}function eg(s){ar.delete(s);}function tg(){return [...ar.values()]}var Pd=100;function ng(s){return lr.set(s.id,s),()=>{lr.get(s.id)===s&&lr.delete(s.id);}}function rg(s){lr.delete(s);}function ig(){return [...lr.values()].sort((s,e)=>(s.order??Pd)-(e.order??Pd))}function og(s){return sr.set(s.id,s),()=>{sr.get(s.id)===s&&sr.delete(s.id);}}function sg(s){sr.delete(s);}function ag(s,e){let t=[...sr.values()].filter(n=>n.target===s);return t.sort((n,r)=>(n.order??0)-(r.order??0)),e?t.filter(n=>!n.when||n.when(e)):t}var cr=new Map;function lg(s){return cr.set(s.id,s),()=>{cr.get(s.id)===s&&cr.delete(s.id);}}function cg(s){cr.delete(s);}function dg(){return [...cr.values()].sort((s,e)=>(s.order??0)-(e.order??0))}var dr=new Map;function hg(s,e){return dr.set(s,e),()=>{dr.get(s)===e&&dr.delete(s);}}function ug(s){dr.delete(s);}function pg(s){return {...Object.fromEntries(dr),...s}}var Ed=280,na=200,kd=640;function mg(s,e=na,t=kd){let n=Number.isFinite(e)&&e>0?e:na,r=Number.isFinite(t)?Math.max(t,n):Number.POSITIVE_INFINITY;return Number.isFinite(s)?Math.round(Math.min(Math.max(s,n),r)):n}function Id(s){let e=s.title.trim().toLowerCase().replace(/\s+/g,"-");return `${s.instanceId}:${s.kind}:${e}#${s.ordinal}`}var Rd="https://api.binance.com/api/v3",fg="https://api.binance.us/api/v3",ra="https://fapi.binance.com/fapi/v1",bg="wss://stream.binance.com:9443",gg="wss://stream.binance.us:9443",vg="wss://fstream.binance.com";var Dd={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h",D:"1d",W:"1w",M:"1M"},Ad={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},yg=[1,3,5,15,30,60,120,240,360,480,720],xg={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h"},wg=["1","3","5","15","30","45","60","120","180","240","D","W","M"];function Od(s){return Ad[s]??Ad[s.toLowerCase()]??s}function ia(s){let e=s.trim().toUpperCase();return e.endsWith(".P")?{apiSymbol:e.slice(0,-2),isFutures:true}:{apiSymbol:e,isFutures:false}}function Fd(s){return s.map(e=>({time:Number(e[0]),open:Number(e[1]),high:Number(e[2]),low:Number(e[3]),close:Number(e[4]),volume:Number(e[5])}))}function Sg(s){return {time:Number(s.t),open:Number(s.o),high:Number(s.h),low:Number(s.l),close:Number(s.c),volume:Number(s.v)}}function Cg(s){let e=new Map;for(let t of s)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function Tg(s,e){let t=new Map;for(let n of s){let r=Math.floor(n.time/e)*e,i=t.get(r);i?(i.high=Math.max(i.high,n.high),i.low=Math.min(i.low,n.low),i.close=n.close,i.volume=(i.volume??0)+(n.volume??0)):t.set(r,{time:r,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,r)=>n.time-r.time)}function Mg(s){return yg.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}var Mo=class{constructor(){this.spotBaseUrl=null;this.spotBaseProbe=null;this.symbolsPromise=null;}info(){return {name:"binance",displayName:"Binance",requiresApiKey:false,supportedTimeframes:wg,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let{apiSymbol:r,isFutures:i}=ia(e),o=i?ra:await this.spotBase(),a=Od(t),l=Dd[a];if(l)return Cg(Fd(await this.fetchKlines(o,r,l,n)));let c=/^\d+$/.test(a)?parseInt(a,10):null,d=c!=null?Mg(c):null;if(c==null||d==null)return console.warn(`[vela] Binance: timeframe "${t}" is not supported and cannot be aggregated.`),[];let h=c/d,u={...n,limit:n.limit!=null?n.limit*h+h:void 0},p=Fd(await this.fetchKlines(o,r,xg[d],u)),m=Tg(p,c*6e4);return n.limit!=null&&m.length>n.limit?m.slice(-n.limit):m}catch(r){return console.warn(`[vela] Binance: failed to fetch ${e} ${t} \u2014 ${r instanceof Error?r.message:String(r)}`),[]}}async getSymbolInfo(e){let{apiSymbol:t,isFutures:n}=ia(e),r=n?ra:await this.spotBase(),i=n?`${r}/exchangeInfo`:`${r}/exchangeInfo?symbol=${t}`,a=(await this.json(i).catch(()=>null))?.symbols??[],l=n?a.find(h=>h.symbol===t):a[0];if(!l)return;let c=l.filters?.find(h=>h.filterType==="PRICE_FILTER"),d=c?parseFloat(c.tickSize??"0.01"):.01;return {ticker:e,tickerid:`BINANCE:${e}`,prefix:"BINANCE",description:`${l.baseAsset} / ${l.quoteAsset}${n?" Perpetual":""}`,type:n?"futures":"crypto",basecurrency:l.baseAsset,currency:l.quoteAsset,mintick:d,pricescale:Math.round(1/d),timezone:"Etc/UTC",session:"24x7"}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=Promise.all([this.listSpot().catch(()=>[]),this.listFutures().catch(()=>[])]).then(([e,t])=>[...e,...t])),this.symbolsPromise}subscribe(e,t,n){let{apiSymbol:r,isFutures:i}=ia(e),o=Dd[Od(t)];return o&&typeof WebSocket<"u"?this.streamKlines(e,t,r,i,o,n):this.pollBars(e,t,n)}streamKlines(e,t,n,r,i,o){let a=false,l=null,c=null,d=null,h=null,u=`${n.toLowerCase()}@kline_${i}`,p=()=>{d&&(clearTimeout(d),d=null);},m=()=>{if(!(a||h)){p(),c&&(clearTimeout(c),c=null);try{l?.close();}catch{}l=null,console.warn(`[vela] Binance: ${e} ${t} stream delivered no data; falling back to polling.`),h=this.pollBars(e,t,o);}},f=async()=>{if(a)return;let b=r?vg:await this.spotWsBase();a||(l=new WebSocket(`${b}/ws/${u}`),d=setTimeout(m,15e3),l.onmessage=g=>{if(!(a||h))try{let v=JSON.parse(typeof g.data=="string"?g.data:"");v.k&&(p(),o(Sg(v.k)));}catch{}},l.onclose=()=>{!a&&!h&&(c=setTimeout(()=>{f();},2e3));},l.onerror=()=>{try{l?.close();}catch{}});};return f(),()=>{a=true,p(),c&&clearTimeout(c),h?.();try{l?.close();}catch{}}}async spotWsBase(){return (await this.spotBase()).includes("binance.us")?gg:bg}pollBars(e,t,n){let r=false,i=null,o=async()=>{if(!r){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}r||(i=setTimeout(()=>{o();},3e3));}};return i=setTimeout(()=>{o();},3e3),()=>{r=true,i&&clearTimeout(i);}}async listSpot(){let e=await this.spotBase();return ((await this.json(`${e}/exchangeInfo`)).symbols??[]).filter(n=>n.status==="TRADING").map(n=>({ticker:n.symbol,description:`${n.baseAsset} / ${n.quoteAsset}`,type:"crypto"}))}async listFutures(){return ((await this.json(`${ra}/exchangeInfo`)).symbols??[]).filter(t=>t.contractType==="PERPETUAL"&&t.status==="TRADING").map(t=>({ticker:`${t.symbol}.P`,description:`${t.baseAsset} / ${t.quoteAsset} Perpetual`,type:"futures"}))}async fetchKlines(e,t,n,r){if(r.from!=null)return this.paginateForward(e,t,n,r.from,r.to??Date.now(),r.limit);let i=r.limit??500;return i>1e3?this.paginateBackward(e,t,n,i,r.to):this.klinesChunk(e,{symbol:t,interval:n,limit:i,endTime:r.to})}async paginateForward(e,t,n,r,i,o){let a=[],l=r;for(;l<i;){let c=await this.klinesChunk(e,{symbol:t,interval:n,limit:1e3,startTime:l,endTime:i});if(c.length===0||(a.push(...c),l=Number(c[c.length-1][6])+1,c.length<1e3)||o&&a.length>=o)break}return o?a.slice(0,o):a}async paginateBackward(e,t,n,r,i){let o=[],a=r,l=i,c=Math.ceil(r/1e3)+5;for(;a>0&&c-- >0;){let d=Math.min(a,1e3),h=await this.klinesChunk(e,{symbol:t,interval:n,limit:d,endTime:l});if(h.length===0||(o=h.concat(o),a-=h.length,l=Number(h[0][0])-1,h.length<d))break}return o}async klinesChunk(e,t){let n=new URL(`${e}/klines`);n.searchParams.set("symbol",t.symbol),n.searchParams.set("interval",t.interval),t.limit&&n.searchParams.set("limit",String(Math.min(t.limit,1e3))),t.startTime!=null&&n.searchParams.set("startTime",String(t.startTime)),t.endTime!=null&&n.searchParams.set("endTime",String(t.endTime));let r=await this.json(n.toString());return Array.isArray(r)?r.length>0&&!Array.isArray(r[0])?[]:r:[]}spotBase(){return this.spotBaseUrl?Promise.resolve(this.spotBaseUrl):(this.spotBaseProbe||(this.spotBaseProbe=(async()=>{try{for(let e of [Rd,fg])try{if((await fetch(`${e}/ping`,{signal:AbortSignal.timeout(5e3)})).ok)return this.spotBaseUrl=e}catch{}return Rd}finally{this.spotBaseProbe=null;}})()),this.spotBaseProbe)}async json(e){let t=await fetch(e);if(!t.ok)throw new Error(`Binance HTTP ${t.status} for ${e}`);return t.json()}};var Lg="https://api.hyperliquid.xyz/info",Pg="wss://api.hyperliquid.xyz/ws";var Bd={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h",D:"1d",W:"1w",M:"1M"},Vd={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},Eg=[1,3,5,15,30,60,120,240,480,720],kg={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h"},Ig=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],_d={D:864e5,W:6048e5,M:2592e6};function Rg(s){if(_d[s])return _d[s];let e=parseInt(s,10);return Number.isFinite(e)&&e>0?e*6e4:36e5}function Nd(s){return Vd[s]??Vd[s.toLowerCase()]??s}function oa(s){let e=s.trim();return e.includes("/")?e:e.toUpperCase()}function sa(s){return {time:Number(s.t),open:Number(s.o),high:Number(s.h),low:Number(s.l),close:Number(s.c),volume:Number(s.v)}}function Dg(s){let e=new Map;for(let t of s)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function Ag(s,e){let t=new Map;for(let n of s){let r=Math.floor(n.time/e)*e,i=t.get(r);i?(i.high=Math.max(i.high,n.high),i.low=Math.min(i.low,n.low),i.close=n.close,i.volume=(i.volume??0)+(n.volume??0)):t.set(r,{time:r,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,r)=>n.time-r.time)}function Og(s){return Eg.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}var Lo=class{constructor(){this.metaPromise=null;this.spotMetaPromise=null;this.symbolsPromise=null;}info(){return {name:"hyperliquid",displayName:"Hyperliquid",requiresApiKey:false,supportedTimeframes:Ig,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let r=oa(e),i=Nd(t),o=Bd[i];if(o)return Dg((await this.fetchCandles(r,o,Rg(i),n)).map(sa));let a=/^\d+$/.test(i)?parseInt(i,10):null,l=a!=null?Og(a):null;if(a==null||l==null)return console.warn(`[vela] Hyperliquid: timeframe "${t}" is not supported and cannot be aggregated.`),[];let c=a/l,d={...n,limit:n.limit!=null?n.limit*c+c:void 0},h=(await this.fetchCandles(r,kg[l],l*6e4,d)).map(sa),u=Ag(h,a*6e4);return n.limit!=null&&u.length>n.limit?u.slice(-n.limit):u}catch(r){return console.warn(`[vela] Hyperliquid: failed to fetch ${e} ${t} \u2014 ${r instanceof Error?r.message:String(r)}`),[]}}async getSymbolInfo(e){let t=oa(e),r=(await this.fetchMeta().catch(()=>null))?.universe?.find(i=>i.name===t);if(r){let i=zd(Math.max(0,6-(r.szDecimals??2)));return Hd(e,t,"USD","futures",`${t} / USD Perpetual`,i)}if(t.includes("/")){let i=await this.fetchSpotMeta().catch(()=>null),o=i?.universe?.find(h=>h.name===t),a=o&&i?.tokens?i.tokens[o.tokens?.[0]??-1]:void 0,[l=t,c="USDC"]=t.split("/"),d=zd(Math.max(0,8-(a?.szDecimals??2)));return Hd(e,l,c,"crypto",`${l} / ${c}`,d)}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=Promise.all([this.listPerps().catch(()=>[]),this.listSpot().catch(()=>[])]).then(([e,t])=>[...e,...t])),this.symbolsPromise}subscribe(e,t,n){let r=oa(e),i=Bd[Nd(t)];return i&&typeof WebSocket<"u"?this.streamCandles(e,t,r,i,n):this.pollBars(e,t,n)}async listPerps(){return ((await this.fetchMeta()).universe??[]).filter(t=>!t.isDelisted).map(t=>({ticker:t.name,description:`${t.name} / USD Perpetual`,type:"futures"}))}async listSpot(){let e=await this.fetchSpotMeta(),t=e.tokens??[],n=r=>r!=null?t[r]?.name??null:null;return (e.universe??[]).map(r=>{let i=n(r.tokens?.[0]),o=n(r.tokens?.[1]),a=i&&o?`${i} / ${o}`:r.name;return {ticker:r.name,description:a,type:"crypto"}})}async fetchCandles(e,t,n,r){let i=r.to??Date.now(),o=r.from!=null?r.from:i-((r.limit??500)+2)*n,a=await this.candleSnapshot(e,t,o,i);return r.from==null&&r.limit!=null&&a.length>r.limit?a.slice(-r.limit):a}async candleSnapshot(e,t,n,r){let i=await this.post({type:"candleSnapshot",req:{coin:e,interval:t,startTime:Math.floor(n),endTime:Math.floor(r)}});return Array.isArray(i)?i:[]}streamCandles(e,t,n,r,i){let o=false,a=null,l=null,c=null,d=null,h=null,u=()=>{d&&(clearTimeout(d),d=null);},p=()=>{l&&(clearInterval(l),l=null);},m=()=>{if(!(o||h)){u(),p(),c&&(clearTimeout(c),c=null);try{a?.close();}catch{}a=null,console.warn(`[vela] Hyperliquid: ${e} ${t} stream delivered no data; falling back to polling.`),h=this.pollBars(e,t,i);}},f=()=>{o||h||(a=new WebSocket(Pg),d=setTimeout(m,15e3),a.onopen=()=>{try{a?.send(JSON.stringify({method:"subscribe",subscription:{type:"candle",coin:n,interval:r}}));}catch{}l=setInterval(()=>{try{a?.send(JSON.stringify({method:"ping"}));}catch{}},3e4);},a.onmessage=b=>{if(!(o||h))try{let g=JSON.parse(typeof b.data=="string"?b.data:"");g.channel==="candle"&&g.data&&g.data.s===n&&(u(),i(sa(g.data)));}catch{}},a.onclose=()=>{p(),!o&&!h&&(c=setTimeout(f,2e3));},a.onerror=()=>{try{a?.close();}catch{}});};return f(),()=>{o=true,u(),p(),c&&clearTimeout(c),h?.();try{a?.close();}catch{}}}pollBars(e,t,n){let r=false,i=null,o=async()=>{if(!r){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}r||(i=setTimeout(()=>{o();},3e3));}};return i=setTimeout(()=>{o();},3e3),()=>{r=true,i&&clearTimeout(i);}}fetchMeta(){return this.metaPromise??(this.metaPromise=this.post({type:"meta"}).then(e=>e))}fetchSpotMeta(){return this.spotMetaPromise??(this.spotMetaPromise=this.post({type:"spotMeta"}).then(e=>e))}async post(e){let t=await fetch(Lg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Hyperliquid HTTP ${t.status}`);return t.json()}};function Hd(s,e,t,n,r,i){return {ticker:s,tickerid:`HYPERLIQUID:${s}`,prefix:"HYPERLIQUID",description:r,type:n,basecurrency:e,currency:t,mintick:i,pricescale:Math.round(1/i),timezone:"Etc/UTC",session:"24x7"}}function zd(s){return Math.pow(10,-s)}var Fg={now:()=>Date.now(),delay:s=>new Promise(e=>setTimeout(e,s))},Po=class{constructor(e,t,n=Fg){this.maxConcurrent=e;this.minIntervalMs=t;this.clock=n;this.active=0;this.waiters=[];this.nextStartAt=0;this.pausedUntil=0;}async run(e){await this.acquire();try{return await this.waitForTurn(),await e()}finally{this.release();}}pauseFor(e){e>0&&(this.pausedUntil=Math.max(this.pausedUntil,this.clock.now()+e));}async waitForTurn(){for(;;){let e=this.clock.now(),t=Math.max(this.pausedUntil-e,this.nextStartAt-e);if(t<=0)break;await this.clock.delay(t);}this.nextStartAt=Math.max(this.clock.now(),this.nextStartAt)+this.minIntervalMs;}acquire(){return this.active<this.maxConcurrent?(this.active+=1,Promise.resolve()):new Promise(e=>{this.waiters.push(()=>{this.active+=1,e();});})}release(){this.active-=1;let e=this.waiters.shift();e&&e();}};var aa="https://api.exchange.coinbase.com",Bg="wss://ws-feed.exchange.coinbase.com",Vg={Accept:"application/json"},_g=15e3,Ng=2e3,Hg=5e3,Eo=300,zg=4,$g=120,Wg=4,Ug=600,Gg=400;function Yg(s,e){let t=Number(s.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t*1e3:e}var $d={1:60,5:300,15:900,60:3600,360:21600,D:86400},Wd={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},Xg=[1,5,15,60,360,1440],Kg={1:60,5:300,15:900,60:3600,360:21600,1440:86400},jg=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],la=864e5;function Ud(s){return Wd[s]??Wd[s.toLowerCase()]??s}function ca(s){return s.trim().toUpperCase()}function qg(s){return {time:Number(s[0])*1e3,open:Number(s[3]),high:Number(s[2]),low:Number(s[1]),close:Number(s[4]),volume:Number(s[5])}}function da(s){let e=new Map;for(let t of s)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function Zg(s,e){return Gd(s,t=>Math.floor(t/e)*e)}function Jg(s,e){return Gd(s,e==="W"?Qg:ev)}function Gd(s,e){let t=new Map;for(let n of s){let r=e(n.time),i=t.get(r);i?(i.high=Math.max(i.high,n.high),i.low=Math.min(i.low,n.low),i.close=n.close,i.volume=(i.volume??0)+(n.volume??0)):t.set(r,{time:r,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,r)=>n.time-r.time)}function Qg(s){let e=new Date(s),t=(e.getUTCDay()+6)%7;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()-t)}function ev(s){let e=new Date(s);return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)}function tv(s){return Xg.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}function ha(s,e){return e!=null&&s.length>e?s.slice(-e):s}var ko=class{constructor(){this.symbolsPromise=null;this.gate=new Po(zg,$g);}info(){return {name:"coinbase",displayName:"Coinbase",requiresApiKey:false,supportedTimeframes:jg,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let r=ca(e),i=Ud(t),o=$d[i];if(o)return da(await this.fetchCandles(r,o,n));if(i==="W"||i==="M"){let u=i==="W"?7*la:31*la,p=n.from!=null?n:{...n,limit:n.limit!=null?Math.ceil(n.limit*u/la)+31:void 0},m=await this.fetchCandles(r,86400,p);return ha(Jg(m,i),n.limit)}let a=/^\d+$/.test(i)?parseInt(i,10):null,l=a!=null?tv(a):null;if(a==null||l==null)return console.warn(`[vela] Coinbase: timeframe "${t}" is not supported and cannot be aggregated.`),[];let c=a/l,d={...n,limit:n.limit!=null?n.limit*c+c:void 0},h=await this.fetchCandles(r,Kg[l],d);return ha(Zg(h,a*6e4),n.limit)}catch(r){return console.warn(`[vela] Coinbase: failed to fetch ${e} ${t} \u2014 ${r instanceof Error?r.message:String(r)}`),[]}}async getSymbolInfo(e){let t=ca(e),n=await this.json(`${aa}/products/${t}`).catch(()=>null);if(!n||!n.id)return;let r=n.quote_increment!=null?parseFloat(n.quote_increment):.01,i=r>0?r:.01;return {ticker:e,tickerid:`COINBASE:${e}`,prefix:"COINBASE",description:`${n.base_currency} / ${n.quote_currency}`,type:"crypto",basecurrency:n.base_currency,currency:n.quote_currency,mintick:i,pricescale:Math.round(1/i),timezone:"Etc/UTC",session:"24x7"}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=this.fetchProducts().then(e=>e.filter(t=>t.status==="online"&&!t.trading_disabled).map(t=>({ticker:t.id,description:`${t.base_currency} / ${t.quote_currency}`,type:"crypto"}))).catch(()=>[])),this.symbolsPromise}subscribe(e,t,n){let r=$d[Ud(t)];return r&&typeof WebSocket<"u"?this.streamTicker(e,t,r,n):this.pollBars(e,t,n)}async fetchProducts(){let e=await this.json(`${aa}/products`);return Array.isArray(e)?e:[]}async fetchCandles(e,t,n){return n.from!=null?this.paginateForward(e,t,n.from,n.to??Date.now(),n.limit):this.paginateBackward(e,t,n.limit??500,n.to??Date.now())}async paginateBackward(e,t,n,r){let i=t*1e3,o=[],a=n,l=r,c=Math.ceil(n/Eo)+4;for(;a>0&&c-- >0;){let d=Math.min(a,Eo),h=l-d*i,u=await this.candlesChunk(e,t,h,l);if(u.length===0||(o=u.concat(o),a-=u.length,l=u[0].time-1,u.length<d))break}return ha(da(o),n)}async paginateForward(e,t,n,r,i){let o=t*1e3,a=[],l=n,c=Math.ceil((r-n)/(Eo*o))+4;for(;l<r&&c-- >0;){let h=Math.min(l+Eo*o,r),u=await this.candlesChunk(e,t,l,h);if(u.length>0&&a.push(...u),l=h,i!=null&&a.length>=i)break}let d=da(a);return i!=null?d.slice(0,i):d}async candlesChunk(e,t,n,r){let i=new URL(`${aa}/products/${e}/candles`);i.searchParams.set("granularity",String(t)),i.searchParams.set("start",String(Math.floor(n/1e3))),i.searchParams.set("end",String(Math.floor(r/1e3)));let o=await this.json(i.toString());return !Array.isArray(o)||o.length>0&&!Array.isArray(o[0])?[]:o.map(qg).sort((a,l)=>a.time-l.time)}streamTicker(e,t,n,r){let i=ca(e),o=n*1e3,a=C=>Math.floor(C/o)*o,l=false,c=null,d=null,h=null,u=null,p=null,m=null,f=()=>{h&&(clearTimeout(h),h=null);},b=()=>{u&&(clearInterval(u),u=null);},g=()=>{m&&r({...m});},v=async C=>{try{let T=await this.getBars(e,t,{limit:2});if(l||T.length===0)return;C&&T.length>=2&&r(T[T.length-2]);let M=T[T.length-1];m=m&&m.time===M.time?{...M,high:Math.max(M.high,m.high),low:Math.min(M.low,m.low),close:m.close}:{...M},g();}catch{}},y=(C,T)=>{let M=Number(C);if(!Number.isFinite(M))return;let E=a(T);!m||E>m.time?(m={time:E,open:M,high:M,low:M,close:M,volume:0},g(),v(false)):E===m.time&&(m={...m,close:M,high:Math.max(m.high,M),low:Math.min(m.low,M)},g());},x=()=>{if(!(l||p)){f(),b(),d&&(clearTimeout(d),d=null);try{c?.close();}catch{}c=null,console.warn(`[vela] Coinbase: ${e} ${t} stream delivered no data; falling back to polling.`),p=this.pollBars(e,t,r);}},S=()=>{l||p||(c=new WebSocket(Bg),h=setTimeout(x,_g),c.onopen=()=>{try{c?.send(JSON.stringify({type:"subscribe",product_ids:[i],channels:["ticker"]}));}catch{}v(false),u=setInterval(()=>{v(false);},Hg);},c.onmessage=C=>{if(!(l||p))try{let T=JSON.parse(typeof C.data=="string"?C.data:"");T.type==="ticker"&&T.product_id===i&&T.price!=null&&(f(),y(T.price,T.time?Date.parse(T.time):Date.now()));}catch{}},c.onclose=()=>{b(),!l&&!p&&(d=setTimeout(S,Ng));},c.onerror=()=>{try{c?.close();}catch{}});};return S(),()=>{l=true,f(),b(),d&&clearTimeout(d),p?.();try{c?.close();}catch{}}}pollBars(e,t,n){let r=false,i=null,o=async()=>{if(!r){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}r||(i=setTimeout(()=>{o();},3e3));}};return i=setTimeout(()=>{o();},3e3),()=>{r=true,i&&clearTimeout(i);}}async json(e){return (await this.request(e)).json()}async request(e){for(let t=0;;t+=1){let n=await this.gate.run(()=>fetch(e,{headers:Vg}));if(n.status===429&&t<Wg){let r=Ug*2**t+Math.random()*Gg;this.gate.pauseFor(Math.max(Yg(n,0),r));continue}if(!n.ok)throw new Error(`Coinbase HTTP ${n.status} for ${e}`);return n}}};
311
- exports.ACCENT=ve;exports.ACCENT_BRIGHT=mr;exports.BEARISH=X;exports.BULLISH=q;exports.BarStore=Di;exports.BinanceProvider=Mo;exports.CATEGORICAL=ba;exports.CROSSHAIR=ya;exports.CachingDataFeed=Vn;exports.CoinbaseProvider=ko;exports.DARK_THEME=Be;exports.DEFAULT_PANEL_MAX_WIDTH=kd;exports.DEFAULT_PANEL_MIN_WIDTH=na;exports.DEFAULT_PANEL_WIDTH=Ed;exports.DataControl=_n;exports.Drawing=B;exports.DrawingStore=Yt;exports.DrawingToolbar=rr;exports.DrawingsControl=Nn;exports.HIGHLIGHT=ga;exports.HyperliquidProvider=Lo;exports.INFO=_e;exports.INVALID=br;exports.LIGHT_THEME=An;exports.MARKER=va;exports.MultiProviderFeed=Pt;exports.NEUTRAL=he;exports.NativeRenderer=or;exports.RendererControl=On;exports.SERIES_LINE=gn;exports.SESSION_OFF=pv;exports.SESSION_POST=uv;exports.SESSION_PRE=hv;exports.SLATE=gr;exports.SLATE_DEEP=xa;exports.TRADE_EXIT=Ca;exports.TRADE_LONG=wa;exports.TRADE_SHORT=Sa;exports.TypedEventBus=ct;exports.VALID=fr;exports.Vela=ta;exports.WARNING=bn;exports.buildColorPicker=Jn;exports.buildToolbar=kn;exports.categoricalColor=mv;exports.chartType=Ue;exports.chartTypes=Ge;exports.clampPanelWidth=mg;exports.combineColor=gc;exports.createDrawing=rt;exports.defaultToolbar=En;exports.deserializeDrawing=Fe;exports.drawingTypes=Ti;exports.getDrawingType=nt;exports.getNativeIndicator=fn;exports.iconMarkup=Ma;exports.legendActions=dg;exports.nativeIndicatorDescriptors=ur;exports.nativeIndicatorTypes=pa;exports.normalizeSettingsRow=Ei;exports.registerChartType=Wo;exports.registerDefaultEngine=hg;exports.registerDrawingType=A;exports.registerIcon=D;exports.registerLegendAction=lg;exports.registerNativeIndicator=_t;exports.registerRendererDefaults=Dp;exports.registerRendererLayer=xb;exports.registerSidePanel=ng;exports.registerWidgetAction=og;exports.registerWidgetAttachment=Qb;exports.rendererDefaults=Go;exports.rendererLayers=Ds;exports.resolveEngines=pg;exports.resolveTheme=Xt;exports.settingsRowValueKeys=Rn;exports.sharedBarStore=Fn;exports.sidePanels=ig;exports.splitColor=cn;exports.stableSeriesId=Id;exports.tickerModifierIds=Uo;exports.timeframeToMs=In;exports.unregisterChartType=Tp;exports.unregisterDefaultEngine=ug;exports.unregisterLegendAction=cg;exports.unregisterNativeIndicator=ua;exports.unregisterRendererDefaults=Ap;exports.unregisterRendererLayer=wb;exports.unregisterSidePanel=rg;exports.unregisterWidgetAction=sg;exports.unregisterWidgetAttachment=eg;exports.widgetActions=ag;exports.widgetAttachments=tg;return exports;})({});
310
+ `;function Lb(s){let e=s.getElementById(cd);e||(e=s.createElement("style"),e.id=cd,s.head.appendChild(e)),e.textContent=Mb;}function Os(s){return xe(s)?"#ffffff":"#000000"}function Fs(s,e){let t=xe(e);s.style.color=t?"#ffffff":"#000000",s.style.setProperty("--vela-attr-shadow",t?"rgba(0,0,0,0.45)":"rgba(255,255,255,0.55)");}function dd(s,e,t){let n=s.createElement("div");return n.className="vela-attribution-custom",Object.assign(n.style,{position:"absolute",zIndex:"6",pointerEvents:"auto",display:"flex",alignItems:"center",lineHeight:"1"}),n.style.color=Os(t),n.innerHTML=e,n}function hd(s,e){Lb(s);let t=s.createElement("a");t.className="vela-attribution",t.href=Tb,t.target="_blank",t.rel="noopener",t.title="Charting by Vela",t.setAttribute("aria-label","Charting by Vela"),Object.assign(t.style,{position:"absolute",zIndex:"6",pointerEvents:"auto",cursor:"pointer"}),Fs(t,e);let n=s.createElement("span");n.className="vela-attr-symbol",n.setAttribute("aria-hidden","true"),n.innerHTML=ad;let r=s.createElement("span");return r.className="vela-attr-wordmark",r.innerHTML=ld,t.append(n,r),t}function yo(s){if(!s||s==="transparent")return false;let e=/rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*,\s*([\d.]+)\s*\)/.exec(s);return e?parseFloat(e[1])>.001:true}function ud(s,e,t){let n=s.borderTopLeftRadius,r=parseFloat(n)||0,i=n.endsWith("%")?r/100*Math.min(e,t):r;return Math.max(0,Math.min(i,Math.min(e,t)/2))}function Bs(s,e,t,n,r,i){s.beginPath(),i>0&&typeof s.roundRect=="function"?s.roundRect(e,t,n,r,i):s.rect(e,t,n,r);}function Pb(s){try{let e=s.ownerDocument.createElement("canvas");e.width=1,e.height=1;let t=e.getContext("2d");return t?(t.drawImage(s,0,0,1,1),e.toDataURL(),!0):!1}catch{return false}}function xo(s,e,t){let n=e.ownerDocument.defaultView;if(!n)return;s.save(),s.scale(t.dpr,t.dpr);let r=(c,d,h)=>{let u=c.textContent?.replace(/\s+/g," ").trim();if(!u)return;let p=c.ownerDocument.createRange();p.selectNodeContents(c);let m=p.getBoundingClientRect();m.width<=0||m.height<=0||(s.globalAlpha=h,s.fillStyle=d.color,s.font=`${d.fontStyle} ${d.fontWeight} ${d.fontSize} ${d.fontFamily}`,s.textBaseline="middle",s.textAlign="left",s.fillText(u,m.left-t.left,m.top-t.top+m.height/2));},i=(c,d,h)=>{if(!c.complete||c.naturalWidth<=0||!Pb(c))return;let u=c.getBoundingClientRect();if(u.width<=0||u.height<=0)return;let p=u.left-t.left,m=u.top-t.top;s.save(),s.globalAlpha=h,Bs(s,p,m,u.width,u.height,ud(d,u.width,u.height)),s.clip(),s.drawImage(c,p,m,u.width,u.height),s.restore();},o=(c,d)=>{for(let h of c.children){if(h.hasAttribute("transform"))continue;let u=h.tagName.toLowerCase();if(u==="g"){o(h,d);continue}let p=g=>parseFloat(h.getAttribute(g)??"0")||0,m=null;if(u==="path"){let g=h.getAttribute("d");g&&(m=new Path2D(g));}else if(u==="circle")m=new Path2D,m.arc(p("cx"),p("cy"),p("r"),0,Math.PI*2);else if(u==="ellipse")m=new Path2D,m.ellipse(p("cx"),p("cy"),p("rx"),p("ry"),0,0,Math.PI*2);else if(u==="rect")m=new Path2D,m.rect(p("x"),p("y"),p("width"),p("height"));else if(u==="line")m=new Path2D,m.moveTo(p("x1"),p("y1")),m.lineTo(p("x2"),p("y2"));else if(u==="polyline"||u==="polygon"){let g=(h.getAttribute("points")??"").trim().split(/[\s,]+/).map(Number);if(g.length<4||g.some(Number.isNaN))continue;m=new Path2D,m.moveTo(g[0],g[1]);for(let v=2;v+1<g.length;v+=2)m.lineTo(g[v],g[v+1]);u==="polygon"&&m.closePath();}if(!m)continue;let f=n.getComputedStyle(h);f.fill&&f.fill!=="none"&&yo(f.fill)&&(s.globalAlpha=d*(parseFloat(f.fillOpacity)||1),s.fillStyle=f.fill,s.fill(m));let b=parseFloat(f.strokeWidth)||0;f.stroke&&f.stroke!=="none"&&yo(f.stroke)&&b>0&&(s.globalAlpha=d*(parseFloat(f.strokeOpacity)||1),s.strokeStyle=f.stroke,s.lineWidth=b,(f.strokeLinecap==="round"||f.strokeLinecap==="square"||f.strokeLinecap==="butt")&&(s.lineCap=f.strokeLinecap),(f.strokeLinejoin==="round"||f.strokeLinejoin==="bevel"||f.strokeLinejoin==="miter")&&(s.lineJoin=f.strokeLinejoin),s.stroke(m));}},a=(c,d)=>{let h=c.getBoundingClientRect();if(h.width<=0||h.height<=0)return;let u=n.getComputedStyle(c);if(u.display==="none"||u.visibility==="hidden")return;let p=d*(parseFloat(u.opacity)||1);if(p<=.001)return;let m=c.viewBox.baseVal,f=m&&m.width>0?m.width:h.width,b=m&&m.height>0?m.height:h.height;s.save(),s.translate(h.left-t.left,h.top-t.top),s.scale(h.width/f,h.height/b),m&&s.translate(-m.x,-m.y),o(c,p),s.restore();},l=(c,d)=>{let h=n.getComputedStyle(c);if(h.display==="none"||h.visibility==="hidden")return;let u=d*(parseFloat(h.opacity)||1);if(u<=.001)return;let p=c.getBoundingClientRect();if(p.width>0&&p.height>0){let m=p.left-t.left,f=p.top-t.top,b=ud(h,p.width,p.height);yo(h.backgroundColor)&&(s.globalAlpha=u,s.fillStyle=h.backgroundColor,Bs(s,m,f,p.width,p.height,b),s.fill());let g=parseFloat(h.borderTopWidth)||0;g>0&&h.borderTopStyle!=="none"&&yo(h.borderTopColor)&&(s.globalAlpha=u,s.strokeStyle=h.borderTopColor,s.lineWidth=g,Bs(s,m+g/2,f+g/2,p.width-g,p.height-g,Math.max(0,b-g/2)),s.stroke());}for(let m of c.childNodes)m.nodeType===3?r(m,h,u):m instanceof n.HTMLImageElement?i(m,n.getComputedStyle(m),u):m instanceof n.SVGSVGElement?a(m,u):m instanceof n.HTMLElement&&l(m,u);};e instanceof n.HTMLElement&&l(e,1),s.restore();}function pd(s,e,t,n,r){let i=Math.max(0,e),o=Math.min(s.length-1,t);if(i>o)return null;let a=1/0,l=-1/0;for(let y=i;y<=o;y+=1){let x=s[y];x.volume!=null&&x.volume>0&&(x.low<a&&(a=x.low),x.high>l&&(l=x.high));}if(!Number.isFinite(a))return null;let c=l>a?Math.max(1,Math.round(n)):1,d=l>a?(l-a)/c:1,h=Array.from({length:c},(y,x)=>({price:a+x*d,up:0,down:0}));for(let y=i;y<=o;y+=1){let x=s[y],S=x.volume;if(!(S!=null&&S>0))continue;let C=x.close>=x.open?"up":"down",T=x.high-x.low;if(T<=0){let k=Vs(Math.floor((x.low-a)/d),c);h[k][C]+=S;continue}let M=Vs(Math.floor((x.low-a)/d),c),E=Vs(Math.floor((x.high-a)/d-1e-9),c);for(let k=M;k<=E;k+=1){let L=a+k*d,P=Math.min(x.high,L+d)-Math.max(x.low,L);P>0&&(h[k][C]+=S*P/T);}}let u=0,p=0,m=0;for(let y=0;y<c;y+=1){let x=h[y].up+h[y].down;u+=x,x>p&&(p=x,m=y);}if(p<=0)return null;let f=u*Math.min(1,Math.max(0,r)),b=m,g=m,v=p;for(;v<f&&(b>0||g<c-1);){let y=b>0?h[b-1].up+h[b-1].down:-1,x=g<c-1?h[g+1].up+h[g+1].down:-1;x>y?(g+=1,v+=x):(b-=1,v+=y);}return {rows:h,rowH:d,min:a,maxTotal:p,poc:m,vaFrom:b,vaTo:g}}function Vs(s,e){return s<0?0:s>=e?e-1:s}function md(s,e,t,n){let{rows:r,rowH:i,maxTotal:o,poc:a,vaFrom:l,vaTo:c}=e,{rightX:d,maxW:h,yOf:u}=t;if(!(o<=0||h<=0)){for(let p=0;p<r.length;p+=1){let m=r[p],f=m.up+m.down;if(f<=0)continue;let b=u(m.price+i),g=Math.max(1,u(m.price)-b-1),v=f/o*h,y=m.up/f*v;s.globalAlpha=p>=l&&p<=c?.62:.28,y>0&&(s.fillStyle=n.upColor,s.fillRect(d-v,b,y,g)),v-y>0&&(s.fillStyle=n.downColor,s.fillRect(d-v+y,b,v-y,g));}if(n.showPoc){let p=r[a],m=u(p.price+i),f=Math.max(1,u(p.price)-m-1);s.globalAlpha=.9,s.strokeStyle=n.pocColor,s.lineWidth=1,s.strokeRect(d-h+.5,m+.5,h-1,f);}s.globalAlpha=1;}}var wo=class{constructor(){this.canvas=null;this.ctx=null;this.memoKey="";this.memo=null;}mount(e){this.canvas=e,this.ctx=e.getContext("2d");}destroy(){this.canvas=null,this.ctx=null,this.memoKey="",this.memo=null;}render(e){let t=this.ctx,n=this.canvas;if(!t||!n)return;let{bars:r,data:i,visible:o,coords:a,scale:l,bounds:c,theme:d}=e,h=a.dpr;if(t.setTransform(h,0,0,h,0,0),t.clearRect(0,0,n.width/h,n.height/h),!i||!o||r.length===0||c.height<=0)return;let u=a.visibleLogicalRange(),p=Math.max(0,Math.floor(u.from)),m=Math.min(r.length-1,Math.ceil(u.to));if(p>m)return;let f=r[m],b=`${p}:${m}:${r.length}:${f.high}:${f.low}:${f.close}:${f.volume??0}:${i.rows}:${i.valueAreaFrac}`;b!==this.memoKey&&(this.memoKey=b,this.memo=pd(r,p,m,i.rows,i.valueAreaFrac));let g=this.memo;g&&(t.save(),t.beginPath(),t.rect(0,c.top,a.width,c.height),t.clip(),md(t,g,{rightX:a.width,maxW:a.width*i.widthFrac,yOf:v=>a.priceToY(v,l,c)},{upColor:i.upColor,downColor:i.downColor,showPoc:i.showPoc,pocColor:d.textColor}),t.restore());}};var pe="price",Rb=8,Db="rgba(0,0,0,0)",So=64,Ab=56,bd=26,or=22,ir=26,_s=24,Ob=5,Fb="0 2px 8px rgba(0,0,0,0.4)",Bb=12,wd=12,gd=So+wd,Ns=or+14,Vb=120,_b=2,vd=6,Nb=70,pn=80,Hb=110,Hs=90,zb=130,$b=.02,Wb=.004,Ub=.2,Gb=4,sr=class{constructor(e){this.capabilities=Ll;this.surfaceBackground=Be.background;this.surfaceTextColor=Be.textColor;this.toolbarGutter=0;this.mountContainer=null;this.userDrawings=null;this.volumeRenderer=new vo;this.extLayers=[];this.attributionEl=null;this.attributionEnabled=true;this.attributionHtml=null;this.vpvrRenderer=new wo;this.resizeObserver=null;this.dprMedia=null;this.coords=new Qi;this.scene=new Yi;this.backendMode="auto";this.glowAmount=0;this.chrome=new oo;this.crosshairLayer=new so;this.countdownTimer=null;this.symbolPicker=null;this.indicatorTitlesOn=true;this.indicatorValuesOn=true;this.legendActionsProvider=null;this.legendOverviewAction=null;this.keyboard=null;this.keyboardEnabled=true;this.historyChordsEnabled=true;this.liveRegion=null;this.animZoom=true;this.animPan=true;this.candleUp=q;this.candleDown=X;this.introStyle="settle";this.introPlayed=false;this.introRaf=null;this.loadingEl=null;this.modelAlpha=1;this.targetBarSpacing=0;this.zoomAnchorLogical=0;this.zoomAnchorX=0;this.zoomAnchorMode="right";this.panVelocity=0;this.bars=[];this.didInitialFit=false;this.paintedData=false;this.skeletonClockMs=0;this.candleBodyAlpha=1;this.candleStructureAlpha=1;this.lastPointer=null;this.volumeActive=false;this.volumeHidden=false;this.vpvrActive=false;this.vpvrHidden=false;this.liveEaseTime=0;this.liveEaseHigh=0;this.liveEaseLow=0;this.liveEaseClose=0;this.axisDragEnabled=true;this.scaleDragHolder=null;this.scaleDragHeight=0;this.scaleDragStart=null;this.paneResizeEnabled=true;this.resizeAbove=null;this.resizeBelow=null;this.resizeSplitStart=null;this.hoverSeparatorY=null;this.maximizedPaneId=null;this.rightAxisW=So;this.paneControls=null;this.paneActionCbs=new Set;this.hoverLogical=null;this.settingsDialog=null;this.dialogHost=null;this.settingsButton=null;this.settingsEnabled=false;this.scrollButton=null;this.pointerNearScrollBtn=false;this.scrollTargetRO=null;this.scrollBtnBottomPx=Ns;this.scrollBtnRightPx=gd;this.layoutMode="desktop";this.viewportCbs=new Set;this.crosshairCbs=new Set;this.chartTypeSettingsCbs=new Set;this.configChangedCbs=new Set;this.themeSelectCbs=new Set;this.factoryConfig=null;this.hostSettingsSections=[];this.clickCbs=new Set;this.axisLongPressCbs=new Set;this.inputChangeCbs=new Set;this.removeIndicatorCbs=new Set;this.toggleVisibleCbs=new Set;this.moveIndicatorCbs=new Set;this.priceStyleCbs=new Set;this.tableOverlays=new Map;this.name="native";this.features=["logScale","currentPriceLine","priceLabel","countdown","upColor","downColor","glow","animZoom","animPan","intro","zoomAnchor","axisDrag","paneResize","candleZOrder","candleVisible","seriesOrder","highlights","gridlines","axisLabels","scaleMode","invertScale","paneScales","autoScale","timezone","keyboard","historyChords","priceStyle","priceBaseline","baselinePrice","settings","attribution","dialogHost","tradeMarkers","indicatorTitles","indicatorValues"];this.onScrollProximityMove=e=>{if(!this.scrollButton||!this.plot)return;let t=this.plot.getBoundingClientRect(),n=t.width-this.scrollBtnRightPx-ir/2,r=t.height-this.scrollBtnBottomPx-ir/2,i=Math.hypot(e.clientX-t.left-n,e.clientY-t.top-r)<=Vb;i!==this.pointerNearScrollBtn&&(this.pointerNearScrollBtn=i,this.updateScrollToRealtimeButton());};this.onScrollProximityLeave=()=>{this.pointerNearScrollBtn&&(this.pointerNearScrollBtn=false,this.updateScrollToRealtimeButton());};this.onDprChange=()=>{this.watchDpr(),this.resize();};this.externalCross=null;this.snapMode="off";e&&(this.scene.showPriceLine=e.currentPriceLine,this.scene.logScale=e.logScale,this.backendMode=e.nativeBackend,this.animZoom=e.animZoom,this.animPan=e.animPan,this.glowAmount=e.glow,this.candleUp=e.upColor,this.candleDown=e.downColor,this.scene.priceStyle=e.priceStyle,this.scene.basePainting=rs(e.priceStyle),this.scene.candleOverride=Wi(e.priceStyle,this.scene.style.chartTypes)),this.theme=this.deriveTheme(Be);}applyFeature(e,t){switch(e){case "logScale":if(t&&typeof t=="object"){let n=t;this.setPaneLog(n.pane??pe,!!n.value);return}this.scene.logScale=!!t;break;case "currentPriceLine":this.scene.showPriceLine=!!t;break;case "priceLabel":this.scene.showPriceLabel=!!t;break;case "countdown":this.scene.showCountdown=!!t,this.syncCountdownTimer();break;case "upColor":this.candleUp=String(t),this.theme&&(this.theme=this.deriveTheme(this.theme));break;case "downColor":this.candleDown=String(t),this.theme&&(this.theme=this.deriveTheme(this.theme));break;case "glow":this.glowAmount=Number(t)||0,this.backend&&"glow"in this.backend&&(this.backend.glow=this.glowAmount);break;case "animZoom":this.animZoom=!!t;return;case "animPan":this.animPan=!!t;return;case "intro":{let n=t===false||t==="none"||t==="off"||t==null?"":String(t);this.introStyle=n,n&&this.playIntro(n);return}case "zoomAnchor":this.zoomAnchorMode=t==="right"?"right":"cursor",this.input&&(this.input.rightEdgeZoom=this.zoomAnchorMode==="right");return;case "axisDrag":this.axisDragEnabled=!!t,this.input&&(this.input.axisDrag=this.axisDragEnabled);return;case "paneResize":this.paneResizeEnabled=!!t,this.input&&(this.input.paneResize=this.paneResizeEnabled);return;case "candleZOrder":this.scene.candleZ=Number(t)||0;break;case "candleVisible":this.scene.candlesHidden=t===false;break;case "seriesOrder":this.applySeriesOrder(t);break;case "highlights":this.scene.highlights=jb(t);break;case "gridlines":this.scene.showGrid=!!t;break;case "axisLabels":this.scene.showAxisLabels=!!t;break;case "scaleMode":if(t&&typeof t=="object"){let n=t;this.setPaneScaleMode(n.pane??pe,yd(n.mode));return}this.scene.scaleMode=yd(t);break;case "invertScale":if(t&&typeof t=="object"){let n=t;this.setPaneInvert(n.pane??pe,!!n.value);return}this.scene.invertScale=!!t;break;case "autoScale":for(let n of this.scene.panes.values())n.manualScale=t?null:{...n.scale};break;case "timezone":this.scene.timezone=typeof t=="string"&&t?t:"UTC";break;case "priceStyle":this.setPriceStyle(qb(t)?t:"candles");break;case "priceBaseline":this.scene.baselineValue=t==null?null:Number(t);break;case "tradeMarkers":this.scene.tradeMarkers=Yl(this.scene.tradeMarkers,t);break;case "keyboard":this.setKeyboardEnabled(!!t);return;case "historyChords":this.historyChordsEnabled=!!t,this.userDrawings&&(this.userDrawings.historyChords=this.historyChordsEnabled);return;case "settings":this.setSettingsEnabled(!!t);return;case "indicatorTitles":this.indicatorTitlesOn=t!==false,this.inputsUI?.setTitlesVisible(this.indicatorTitlesOn);return;case "indicatorValues":this.indicatorValuesOn=t!==false,this.inputsUI?.setValuesVisible(this.indicatorValuesOn);return;case "attribution":this.attributionHtml=typeof t=="string"&&t.trim()?t:null,this.attributionEnabled=this.attributionHtml!==null||!!t,this.rebuildAttribution();return;case "dialogHost":this.dialogHost=t instanceof HTMLElement?t:null,this.settingsDialog?.close(),this.settingsDialog=null,this.inputsUI?.setDialogHost(this.dialogHost);return;default:return}this.scheduler?.invalidate(4);}readFeature(e){switch(e){case "logScale":return this.scene.logScale;case "currentPriceLine":return this.scene.showPriceLine;case "priceLabel":return this.scene.showPriceLabel;case "countdown":return this.scene.showCountdown;case "upColor":return this.candleUp;case "downColor":return this.candleDown;case "glow":return this.glowAmount;case "animZoom":return this.animZoom;case "animPan":return this.animPan;case "intro":return this.introStyle;case "zoomAnchor":return this.zoomAnchorMode;case "axisDrag":return this.input?this.input.axisDrag:this.axisDragEnabled;case "paneResize":return this.input?this.input.paneResize:this.paneResizeEnabled;case "candleZOrder":return this.scene.candleZ;case "candleVisible":return !this.scene.candlesHidden;case "seriesOrder":return this.scene.indicatorZOrder();case "highlights":return this.scene.highlights;case "gridlines":return this.scene.showGrid;case "axisLabels":return this.scene.showAxisLabels;case "scaleMode":return this.scene.scaleMode;case "invertScale":return this.scene.invertScale;case "paneScales":return this.paneScaleInfos();case "autoScale":{let t=this.scene.orderedPanes().find(n=>n.kind==="price");return t?t.manualScale==null:true}case "timezone":return this.scene.timezone;case "priceStyle":return this.scene.priceStyle;case "priceBaseline":return this.scene.baselineValue;case "baselinePrice":{let t=this.scene.panes.get(pe);return t?this.scene.baselinePriceFor(t.scale):this.scene.baselineValue}case "tradeMarkers":return {...this.scene.tradeMarkers,colors:{...this.scene.tradeMarkers.colors}};case "keyboard":return this.keyboardEnabled;case "historyChords":return this.historyChordsEnabled;case "settings":return this.settingsEnabled;case "indicatorTitles":return this.indicatorTitlesOn;case "indicatorValues":return this.indicatorValuesOn;case "attribution":return this.attributionHtml??this.attributionEnabled;case "dialogHost":return this.dialogHost??void 0;default:return}}setNativeData(e,t){e==="volume"?(this.scene.volumeLayer=t??null,this.scheduler?.invalidate(3)):e==="vpvr"?(this.scene.vpvrLayer=t??null,this.scheduler?.invalidate(3)):e.endsWith("-pending")?(this.scene.nativePending.set(e.slice(0,-8),t??[]),this.scheduler?.invalidate(3)):(this.scene.nativeData.set(e,t),this.scheduler?.invalidate(3));}setIndicatorStatus(e,t){this.inputsUI.setStatus(e.id,t);}setLoading(e){for(let r of this.tableOverlays.values())r.setVisible(!e);if(!e||!this.wrapper){this.loadingEl?.remove(),this.loadingEl=null;return}if(this.loadingEl)return;let t=this.wrapper.ownerDocument,n=t.createElement("div");n.className="vela-loading",Object.assign(n.style,{position:"absolute",inset:"0",display:"flex",alignItems:"center",justifyContent:"center",gap:"7px",pointerEvents:"none"});for(let r=0;r<3;r+=1){let i=t.createElement("span");Object.assign(i.style,{width:"7px",height:"7px",borderRadius:"50%",background:this.chromeTheme().textColor,opacity:"0.15"}),i.animate([{opacity:.12},{opacity:.55}],{duration:800,iterations:1/0,direction:"alternate",easing:"ease-in-out",delay:-r*260}),n.appendChild(i);}this.wrapper.appendChild(n),this.loadingEl=n;}setPricePrecision(e){let t=typeof e=="number"&&e>0?e:void 0;t!==this.scene.priceMintick&&(this.scene.priceMintick=t,this.scheduler?.invalidate(4));}getConfig(){let e=this.scene.style,t=Object.fromEntries(Object.entries(e.chartTypes).map(([r,i])=>[r,{...i}])),n=this.theme;return {version:ns,chartTypes:t,layout:{background:n.background,textColor:n.textColor,fontFamily:n.fontFamily,fontSize:e.fontSize},grid:{vertLines:{visible:e.gridVert.visible,color:e.gridVert.color??n.gridColor},horzLines:{visible:e.gridHorz.visible,color:e.gridHorz.color??n.gridColor}},crosshair:{color:e.crosshair.color??n.textColor,width:e.crosshair.width,style:e.crosshair.style,opacity:e.crosshair.opacity,labelBackground:e.crosshair.labelBackground??n.textColor},priceScale:{mode:this.scene.scaleMode,log:this.scene.logScale,invert:this.scene.invertScale,borderColor:e.borderColor??n.borderColor,labelsVisible:this.scene.showAxisLabels,currentPriceLine:this.scene.showPriceLine,priceLabel:this.scene.showPriceLabel,countdown:this.scene.showCountdown},panes:{separatorColor:e.separatorColor??n.borderColor},trades:{visible:this.scene.tradeMarkers.visible,labels:this.scene.tradeMarkers.labels,qty:this.scene.tradeMarkers.qty,longColor:this.scene.tradeMarkers.colors.long,shortColor:this.scene.tradeMarkers.colors.short,exitColor:this.scene.tradeMarkers.colors.exit},timeScale:{timezone:this.scene.timezone},candles:{upColor:this.candleUp,downColor:this.candleDown,bodyVisible:e.candle.bodyVisible,borderVisible:e.candle.borderVisible,borderUpColor:e.candle.borderUpColor??this.candleUp,borderDownColor:e.candle.borderDownColor??this.candleDown,wickVisible:e.candle.wickVisible,wickUpColor:e.candle.wickUpColor??this.candleUp,wickDownColor:e.candle.wickDownColor??this.candleDown},bars:{upColor:e.bars.upColor??this.candleUp,downColor:e.bars.downColor??this.candleDown},line:{color:e.line.color??this.candleUp,width:e.line.width},stacking:{candles:this.scene.candleZ,series:Object.fromEntries(this.scene.indicatorZOrder().map(({id:r,z:i})=>[r,i]))},area:(()=>{let r=e.area.lineColor??this.candleUp;return {lineColor:r,width:e.area.width,topColor:e.area.topColor??r,bottomColor:e.area.bottomColor??Db}})(),baseline:(()=>{let r=e.baseline.topLineColor??Qt,i=e.baseline.bottomLineColor??en;return {topLineColor:r,bottomLineColor:i,topFillColor:e.baseline.topFillColor??W(r,Ye),topFillColor2:e.baseline.topFillColor2??W(r,Xe),bottomFillColor:e.baseline.bottomFillColor??W(i,Ye),bottomFillColor2:e.baseline.bottomFillColor2??W(i,Xe),width:e.baseline.width,baselineLevel:e.baseline.baselineLevel}})(),series:{style:this.scene.priceStyle,baseline:this.scene.baselineValue,spacing:this.coords.spacingScale}}}applyConfig(e){let t=_l(this.getConfig(),e),n=this.scene.style;for(let[d,h]of Object.entries(t.chartTypes))if(JSON.stringify(n.chartTypes[d])!==JSON.stringify(h)){this.scene.nativeData.set(`${d}-settings`,{...h});for(let u of this.chartTypeSettingsCbs)u(d,{...h});}n.chartTypes=Object.fromEntries(Object.entries(t.chartTypes).map(([d,h])=>[d,{...h}]));let r=e&&typeof e=="object"?e.layout:void 0,i=r&&typeof r=="object"?r.textColor:void 0,o=typeof i=="string"&&i.trim().length>0,a=this.theme,l={textColor:t.layout.textColor,gridColor:a.gridColor,borderColor:a.borderColor};if(!o&&xe(t.layout.textColor)===xe(t.layout.background)){let d=xe(t.layout.background)?Be:An;l={textColor:d.textColor,gridColor:d.gridColor,borderColor:d.borderColor};}this.theme={...this.theme,background:t.layout.background,textColor:l.textColor,gridColor:l.gridColor,borderColor:l.borderColor,fontFamily:t.layout.fontFamily},n.fontSize=t.layout.fontSize;let c=(d,h,u)=>d===null&&h===u?null:h;n.gridVert={visible:t.grid.vertLines.visible,color:c(n.gridVert.color,t.grid.vertLines.color,a.gridColor)},n.gridHorz={visible:t.grid.horzLines.visible,color:c(n.gridHorz.color,t.grid.horzLines.color,a.gridColor)},n.crosshair={color:t.crosshair.color,width:t.crosshair.width,style:t.crosshair.style,opacity:t.crosshair.opacity,labelBackground:t.crosshair.labelBackground},this.scene.scaleMode=t.priceScale.mode,this.scene.logScale=t.priceScale.log,this.scene.invertScale=t.priceScale.invert,n.borderColor=c(n.borderColor,t.priceScale.borderColor,a.borderColor),this.scene.showAxisLabels=t.priceScale.labelsVisible,this.scene.showPriceLine=t.priceScale.currentPriceLine,this.scene.showPriceLabel=t.priceScale.priceLabel,this.scene.showCountdown=t.priceScale.countdown,this.syncCountdownTimer(),n.separatorColor=c(n.separatorColor,t.panes.separatorColor,a.borderColor),this.scene.tradeMarkers={visible:t.trades.visible,labels:t.trades.labels,qty:t.trades.qty,colors:{long:t.trades.longColor,short:t.trades.shortColor,exit:t.trades.exitColor}},this.scene.timezone=t.timeScale.timezone,this.candleUp=t.candles.upColor,this.candleDown=t.candles.downColor,n.candle={bodyVisible:t.candles.bodyVisible,borderVisible:t.candles.borderVisible,borderUpColor:t.candles.borderUpColor,borderDownColor:t.candles.borderDownColor,wickVisible:t.candles.wickVisible,wickUpColor:t.candles.wickUpColor,wickDownColor:t.candles.wickDownColor},this.scene.candleZ=t.stacking.candles;for(let[d,h]of Object.entries(t.stacking.series))this.scene.setIndicatorZ(d,h);n.bars={upColor:t.bars.upColor,downColor:t.bars.downColor},n.line={color:t.line.color,width:t.line.width},n.area={lineColor:t.area.lineColor,width:t.area.width,topColor:t.area.topColor,bottomColor:t.area.bottomColor},n.baseline={topLineColor:t.baseline.topLineColor,bottomLineColor:t.baseline.bottomLineColor,topFillColor:t.baseline.topFillColor,topFillColor2:t.baseline.topFillColor2,bottomFillColor:t.baseline.bottomFillColor,bottomFillColor2:t.baseline.bottomFillColor2,width:t.baseline.width,baselineLevel:t.baseline.baselineLevel},this.setPriceStyle(t.series.style),this.scene.candleOverride=Wi(this.scene.priceStyle,n.chartTypes),this.scene.baselineValue=t.series.baseline,this.coords.setPitchScale(t.series.spacing),this.coords.setViewport(this.clampViewport(this.coords.getViewport().barSpacing,this.coords.getViewport().rightOffset)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.theme=this.deriveTheme(this.theme),this.wrapper&&(ne(this.wrapper,this.chromeTheme()),this.applyBackground()),this.inputsUI?.setTheme(this.theme),this.paneControls?.setTheme(this.theme),this.userDrawings?.setTheme(this.chromeTheme()),this.refreshScrollButtonTheme(),this.refreshAttributionColor(),this.scheduler?.invalidate(4);for(let d of this.configChangedCbs)d();}applySeriesOrder(e){if(!e||typeof e!="object")return;let t=e;typeof t.id=="string"&&(typeof t.z=="number"?this.scene.setIndicatorZ(t.id,t.z):t.to==="front"?this.scene.bringIndicatorToFront(t.id):t.to==="back"&&this.scene.sendIndicatorToBack(t.id));}setSettingsEnabled(e){this.settingsEnabled=e,e?(this.plot&&!this.settingsButton&&(this.settingsButton=this.makeSettingsButton(),this.plot.appendChild(this.settingsButton)),this.settingsButton&&(this.settingsButton.style.display="flex"),this.plot&&!this.settingsDialog&&(this.settingsDialog=new er(this.dialogHost??this.plot,this.theme))):(this.settingsButton?.style.setProperty("display","none"),this.settingsDialog?.close());}makeSettingsButton(){let e=document.createElement("button");return e.type="button",e.title="Chart settings",e.innerHTML=oe("gear",14),Object.assign(e.style,{position:"absolute",bottom:`${or+10}px`,right:`${So+10}px`,zIndex:"6",width:"26px",height:"26px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:"50%",border:`1px solid ${this.theme.borderColor}`,background:this.theme.background,color:this.theme.textColor,fontSize:"14px",lineHeight:"1",opacity:"0.75",pointerEvents:"auto",padding:"0"}),e.addEventListener("mouseenter",()=>e.style.opacity="1"),e.addEventListener("mouseleave",()=>e.style.opacity="0.75"),e.addEventListener("click",()=>this.toggleSettingsDialog()),e}openSettingsDialog(e){!this.settingsDialog&&this.plot&&(this.settingsDialog=new er(this.dialogHost??this.plot,this.theme),this.settingsDialog.setLayoutMode(this.layoutMode)),this.toggleSettingsDialog(e);}syncThemeControl(){this.settingsDialog?.setThemeControl(xe(this.surfaceBackground)?"dark":"light",e=>{for(let t of this.themeSelectCbs)t(e);});}toggleSettingsDialog(e){if(this.settingsDialog){if(e!==void 0&&this.settingsDialog.isOpen()){this.settingsDialog.showSection(e);return}this.settingsDialog.setTheme(this.theme),this.settingsDialog.setHostSections(this.hostSettingsSections),this.syncThemeControl(),this.settingsDialog.toggle(this.getConfig(),t=>this.applyConfig(t),t=>this.applyConfig(t),()=>{this.factoryConfig&&this.applyConfig(Vl(this.factoryConfig)),this.settingsDialog?.close(),this.openSettingsDialog();},e);}}closeDialogs(){this.inputsUI?.closeOpenDialog(),this.settingsDialog?.close();}makeScrollToRealtimeButton(){let e=document.createElement("button");return e.type="button",e.title="Scroll to most recent bar (Alt+Shift+\u2192)",e.setAttribute("aria-label","Scroll to most recent bar"),e.innerHTML=this.scrollButtonIcon(),Object.assign(e.style,{position:"absolute",bottom:`${Ns}px`,right:`${gd}px`,zIndex:"6",width:`${ir}px`,height:`${ir}px`,boxSizing:"border-box",display:"none",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:`${Ob}px`,border:`1px solid ${this.theme.borderColor}`,boxShadow:Fb,background:this.scrollButtonSurface(),color:this.theme.textColor,lineHeight:"0",opacity:"0.85",pointerEvents:"auto",padding:"0"}),e.addEventListener("mouseenter",()=>e.style.opacity="1"),e.addEventListener("mouseleave",()=>e.style.opacity="0.85"),e.addEventListener("click",()=>this.scrollToRealtime()),e}scrollButtonIcon(){return oe("chevrons-right",Bb)}scrollButtonSurface(){return W(this.theme.background,.5)}refreshScrollButtonTheme(){this.scrollButton&&(this.scrollButton.style.background=this.scrollButtonSurface(),this.scrollButton.style.color=this.theme.textColor,this.scrollButton.style.borderColor=this.theme.borderColor);}updateScrollToRealtimeButton(){let e=this.scrollButton;if(!e)return;let t=this.coords.barCount>0&&this.coords.getViewport().rightOffset<0;if(this.layoutMode==="mobile"){e.style.display=t?"flex":"none";return}e.style.display=t&&this.pointerNearScrollBtn?"flex":"none";}scrollToRealtime(){this.coords.barCount!==0&&this.glideRightOffset(vd);}glideRightOffset(e){let t=this.coords.getViewport();if(!this.animPan){this.applyViewport({barSpacing:t.barSpacing,rightOffset:e});return}this.panVelocity=0,this.targetBarSpacing=t.barSpacing,this.scrollTargetRO=e,this.animator.start();}screenshot(){if(!this.dataCanvas)return null;this.computeScales(),this.paintData();let e=document.createElement("canvas");e.width=this.dataCanvas.width,e.height=this.dataCanvas.height;let t=e.getContext("2d");if(!t)return null;t.fillStyle=this.theme.background,t.fillRect(0,0,e.width,e.height);let n=this.plot?.getBoundingClientRect(),r=n&&n.width>0?{left:n.left,top:n.top,dpr:e.width/n.width}:null,i=[...this.mountContainer?.querySelectorAll("[data-vela-screenshot]")??[]];if(r)for(let l of i)l.getAttribute("data-vela-screenshot")==="under"&&xo(t,l,r);let o=this.extLayers.filter(l=>l.def.placement==="below-data").map(l=>l.canvas),a=this.extLayers.filter(l=>l.def.placement!=="below-data").map(l=>l.canvas);for(let l of [...o,this.dataCanvas,this.volumeCanvas,this.vpvrCanvas,...a,this.chromeCanvas,this.drawingsCanvas])l&&l.width>0&&l.height>0&&t.drawImage(l,0,0);if(r){for(let l of this.plot?.querySelectorAll("[data-vela-pane]")??[])xo(t,l,r);for(let l of i)l.getAttribute("data-vela-screenshot")!=="under"&&xo(t,l,r);}return e.toDataURL("image/png")}playIntro(e){this.introRaf!=null&&cancelAnimationFrame(this.introRaf),this.introRaf=null;let t=this.bars,n=t.length;if(n===0)return;this.computeScales();for(let a of this.scene.panes.values())a.scale={...a.scaleTarget};this.modelAlpha=0;let r=650,i=performance.now(),o=a=>{let l=Math.min(1,(a-i)/r);this.scene.bars=l>=1?t:t.map((c,d)=>this.revealCandle(c,d,l,n,e)),this.paintData(),l<1?this.introRaf=requestAnimationFrame(o):(this.scene.bars=t,this.fadeInModels());};this.introRaf=requestAnimationFrame(o);}fadeInModels(){let t=performance.now(),n=r=>{this.modelAlpha=Math.min(1,(r-t)/350),this.paintData(),this.modelAlpha<1?this.introRaf=requestAnimationFrame(n):(this.modelAlpha=1,this.introRaf=null);};this.introRaf=requestAnimationFrame(n);}revealCandle(e,t,n,r,i){let a=Math.max(0,Math.min(1,(n-t/Math.max(1,r-1)*.55)/.44999999999999996)),l;if(i==="settle"){let h=a-1;l=1+(1.70158+1)*h*h*h+1.70158*h*h;}else {let d=1-a;l=1-d*d*d;}let c=e.open;return {...e,high:c+(e.high-c)*l,low:c+(e.low-c)*l,close:c+(e.close-c)*l}}deriveTheme(e){return {...e,upColor:this.candleUp,downColor:this.candleDown}}chromeTheme(){return {...this.theme,background:this.surfaceBackground,textColor:this.surfaceTextColor,borderColor:xe(this.surfaceBackground)?Be.borderColor:An.borderColor}}axisSurface(){return {background:this.theme.background,textColor:this.theme.textColor}}mount(e,t){this.mountContainer=e,this.publishGutters(),this.theme=this.deriveTheme(t),this.surfaceBackground=t.background,this.surfaceTextColor=t.textColor,this.wrapper=document.createElement("div"),Object.assign(this.wrapper.style,{position:"relative",width:"100%",height:"100%",overflow:"hidden",cursor:"crosshair"}),ne(this.wrapper,this.chromeTheme()),this.volumeCanvas=document.createElement("canvas"),Object.assign(this.volumeCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.dataCanvas=this.createGeometryBackend(),this.vpvrCanvas=document.createElement("canvas"),Object.assign(this.vpvrCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.chromeCanvas=document.createElement("canvas"),Object.assign(this.chromeCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.drawingsCanvas=document.createElement("canvas"),Object.assign(this.drawingsCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.cursorCanvas=document.createElement("canvas"),Object.assign(this.cursorCanvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),this.overlayRoot=document.createElement("div"),Object.assign(this.overlayRoot.style,{position:"absolute",inset:"0",pointerEvents:"none"}),this.plot=document.createElement("div"),Object.assign(this.plot.style,{position:"absolute",top:"0",right:"0",bottom:"0",left:"0"}),this.extLayers=As().map(i=>{let o=document.createElement("canvas");return Object.assign(o.style,{position:"absolute",inset:"0",width:"100%",height:"100%",pointerEvents:"none"}),{def:i,instance:i.create(),canvas:o}});let n=this.extLayers.filter(i=>i.def.placement==="below-data").map(i=>i.canvas),r=this.extLayers.filter(i=>i.def.placement!=="below-data").map(i=>i.canvas);this.plot.append(...n,this.dataCanvas,this.volumeCanvas,this.vpvrCanvas,...r,this.chromeCanvas,this.drawingsCanvas,this.cursorCanvas,this.overlayRoot),this.wrapper.appendChild(this.plot),this.factoryConfig=this.getConfig(),this.attributionEl=this.buildAttributionEl(),this.attributionEnabled||(this.attributionEl.style.display="none"),this.positionAttribution(),this.wrapper.appendChild(this.attributionEl),e.appendChild(this.wrapper),this.applyBackground(),this.volumeRenderer.mount(this.volumeCanvas),this.vpvrRenderer.mount(this.vpvrCanvas);for(let i of this.extLayers)i.instance.mount(i.canvas);this.chrome.mount(this.chromeCanvas),this.crosshairLayer.mount(this.cursorCanvas),this.coords.setViewport(Ji()),this.scene.ensurePane(pe,"price",0,3),this.scheduler=new eo(i=>this.renderFrame(i)),this.animator=new to(i=>this.animTick(i)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.input=new no({getCoords:()=>this.coords,apply:i=>this.applyViewport(i),zoomTo:(i,o,a)=>this.zoomTo(i,o,a),fling:i=>this.fling(i),onPointerMove:(i,o)=>this.handlePointerMove(i,o),onClick:i=>this.handleClick(i),onAxisLongPress:(i,o,a)=>{for(let l of this.axisLongPressCbs)l({axis:i,x:o,y:a});},beginPriceScale:(i,o)=>this.beginPriceScale(i,o),priceScaleBy:i=>this.priceScaleBy(i),beginPricePan:i=>this.beginPricePan(i),pricePanBy:i=>this.pricePanBy(i),resetPriceScale:(i,o)=>this.resetPriceScale(i,o),dataDblClick:(i,o)=>this.dataDblClick(i,o),paneSeparatorAt:i=>this.paneSeparatorAt(i),beginPaneResize:i=>this.beginPaneResize(i),paneResizeBy:i=>this.paneResizeBy(i),resetPaneSize:i=>this.resetPaneSize(i),resetView:()=>this.resetView(),drawingsClaim:(i,o)=>this.userDrawings?.claim(i,o)??false,drawingsMeasureStart:(i,o)=>this.userDrawings?.beginMeasureAt(i,o)??false,drawingsDeleteAt:(i,o)=>this.userDrawings?.deleteAt(i,o)??false,drawingsCancelPlacement:()=>this.userDrawings?.cancelPlacement()??false,drawingsSnapMode:()=>this.snapMode,drawingsPointerDown:(i,o,a,l)=>this.userDrawings?.pointerDown(i,o,a,l),drawingsPointerMove:(i,o,a,l)=>this.userDrawings?.pointerMove(i,o,a,l),drawingsPointerUp:(i,o)=>this.userDrawings?.pointerUp(i,o),drawingsCursor:(i,o)=>this.userDrawings?.cursorAt(i,o)??null,drawingsDblClick:(i,o)=>this.userDrawings?.dblClick(i,o)??false,drawingsClearTransient:()=>this.userDrawings?.clearTransient()}),this.input.rightEdgeZoom=this.zoomAnchorMode==="right",this.input.axisDrag=this.axisDragEnabled,this.input.paneResize=this.paneResizeEnabled,this.input.attach(this.dataCanvas),this.settingsEnabled&&this.setSettingsEnabled(true),this.syncCountdownTimer(),this.scrollButton=this.makeScrollToRealtimeButton(),this.plot.appendChild(this.scrollButton),this.plot.addEventListener("pointermove",this.onScrollProximityMove),this.plot.addEventListener("pointerleave",this.onScrollProximityLeave),this.userDrawings=new go(this.wrapper,this.plot,this.drawingsCanvas,{projector:()=>this.drawingProjector(),dpr:()=>this.coords.dpr,theme:()=>this.theme,requestScaleUpdate:()=>this.scheduler.invalidate(3),seriesBoundaries:i=>this.scene.seriesBoundaries(i),priceZ:i=>i===pe?this.scene.candleZ:null,requestDataPaint:()=>this.scheduler.invalidate(3),snap:(i,o,a,l)=>this.snapToCandle(i,o,a,l),setSnapMode:i=>this.setSnapMode(i),setToolbarGutter:i=>this.setToolbarGutter(i)}),this.userDrawings.historyChords=this.historyChordsEnabled,this.layoutMode==="mobile"&&(this.mountContainer?.setAttribute("data-vela-layout",this.layoutMode),this.userDrawings.setLayoutMode(this.layoutMode),this.scrollButton&&(this.scrollButton.style.width=`${_s}px`,this.scrollButton.style.height=`${_s}px`)),this.keyboard=new ro({panByBars:i=>this.panByBars(i),zoomByStep:i=>this.zoomByStep(i),stepCrosshair:i=>this.stepCrosshair(i),jumpToEdge:i=>this.focusBar(i==="first"?0:this.coords.barCount-1),resetView:()=>this.resetView(),scrollToRealtime:()=>this.scrollToRealtime(),clearCrosshair:()=>this.handlePointerMove(null,null),preempt:i=>this.userDrawings?.handleKey(i)??false}),this.setKeyboardEnabled(this.keyboardEnabled),this.inputsUI=new Vi(this.plot,t,i=>this.paneBoundsFor(i)),this.inputsUI.setLayoutMode(this.layoutMode),this.inputsUI.setTitlesVisible(this.indicatorTitlesOn),this.inputsUI.setValuesVisible(this.indicatorValuesOn),this.inputsUI.setDialogHost(this.dialogHost),this.inputsUI.setSymbolPicker(this.symbolPicker),this.inputsUI.setLegendActions(this.legendActionsProvider),this.inputsUI.setLegendOverviewAction(this.legendOverviewAction),this.inputsUI.setOnChange(i=>{for(let o of this.inputChangeCbs)o({indicatorId:i.indicatorId,key:i.key,value:i.value});}),this.inputsUI.setOnRemove(i=>{for(let o of this.removeIndicatorCbs)o(i);}),this.inputsUI.setOnToggleVisible((i,o)=>{for(let a of this.toggleVisibleCbs)a(i,o);}),this.inputsUI.setMoveApi({panes:()=>this.scene.orderedPanes().map((i,o)=>({id:i.id,kind:i.kind,label:i.kind==="price"?"Main chart":this.paneMasterTitle(i.id)??`Pane ${o}`,top:i.bounds.top,height:i.bounds.height})),move:(i,o)=>{for(let a of this.moveIndicatorCbs)a(i,o);}}),this.paneControls=new _i(this.plot,t,{panes:()=>this.paneControlViews(),rightAxis:()=>this.rightAxisW,onMove:(i,o)=>this.movePaneLocal(i,o),onToggleCollapse:i=>{let o=this.scene.panes.get(i);if(!o)return;let a=!o.collapsed;o.collapsed=a,this.afterPaneLayoutChange(),this.emitPaneAction({type:"collapse",paneId:i,collapsed:a});},onToggleMaximize:i=>{let o=this.maximizedPaneId!==i;this.maximizedPaneId=o?i:null,this.afterPaneLayoutChange(),this.emitPaneAction({type:"maximize",paneId:i,maximized:o});}}),this.resizeObserver=new ResizeObserver(()=>this.resize()),this.resizeObserver.observe(this.wrapper),this.watchDpr(),this.syncSize();}makeDataCanvas(){let e=document.createElement("canvas");return Object.assign(e.style,{position:"absolute",inset:"0",width:"100%",height:"100%"}),e}createGeometryBackend(){if((this.backendMode==="auto"||this.backendMode==="webgl2")&&Pl()){let n=this.makeDataCanvas(),r=new Zi;if(r.glow=this.glowAmount,r.onNeedsRedraw=()=>this.scheduler?.invalidate(4),r.onContextFailed=()=>this.swapToCanvas2dFallback(),r.mount(n),r.ok)return this.backend=r,n;r.destroy();}let e=this.makeDataCanvas(),t=new jn;return t.mount(e),this.backend=t,e}swapToCanvas2dFallback(){if(this.backend.kind==="canvas2d")return;let e=this.dataCanvas;this.input?.detach(),this.backend.destroy();let t=this.makeDataCanvas(),n=new jn;n.mount(t),this.backend=n,e.replaceWith(t),this.dataCanvas=t,this.input?.attach(t),this.syncSize();}watchDpr(){typeof window.matchMedia=="function"&&(this.dprMedia?.removeEventListener("change",this.onDprChange),this.dprMedia=window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.dprMedia.addEventListener("change",this.onDprChange,{once:true}));}setTheme(e){this.theme=this.deriveTheme(e),this.surfaceBackground=e.background,this.surfaceTextColor=e.textColor,this.wrapper&&ne(this.wrapper,this.chromeTheme()),this.applyBackground(),this.inputsUI.setTheme(e),this.paneControls?.setTheme(this.theme),this.settingsDialog?.refreshConfig(this.getConfig()),this.syncThemeControl(),this.settingsDialog?.setTheme(this.theme),this.settingsButton&&(this.settingsButton.style.background=this.theme.background,this.settingsButton.style.color=this.theme.textColor,this.settingsButton.style.borderColor=this.theme.borderColor),this.refreshScrollButtonTheme(),this.userDrawings?.setTheme(this.chromeTheme()),this.refreshAttributionColor(),this.scheduler.invalidate(4);}resize(){this.syncSize();}syncCountdownTimer(){this.scene.showCountdown?this.countdownTimer==null&&(this.countdownTimer=setInterval(()=>{this.scene.showCountdown&&this.scene.bars.length>0&&this.scheduler?.invalidate(2);},1e3)):this.countdownTimer!=null&&(clearInterval(this.countdownTimer),this.countdownTimer=null);}destroy(){this.introRaf!=null&&cancelAnimationFrame(this.introRaf),this.loadingEl?.remove(),this.loadingEl=null,this.countdownTimer!=null&&(clearInterval(this.countdownTimer),this.countdownTimer=null),this.scheduler?.destroy(),this.animator?.stop(),this.input?.detach(),this.keyboard?.detach(),this.keyboard=null,this.liveRegion=null,this.inputsUI?.destroy(),this.paneControls?.destroy();for(let e of this.tableOverlays.values())e.destroy();this.tableOverlays.clear(),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.dprMedia?.removeEventListener("change",this.onDprChange),this.dprMedia=null,this.userDrawings?.destroy(),this.userDrawings=null,this.settingsDialog?.destroy(),this.settingsDialog=null,this.settingsButton?.remove(),this.settingsButton=null,this.plot?.removeEventListener("pointermove",this.onScrollProximityMove),this.plot?.removeEventListener("pointerleave",this.onScrollProximityLeave),this.scrollButton?.remove(),this.scrollButton=null;for(let e of this.extLayers)e.instance.destroy?.();this.extLayers=[],this.volumeRenderer.destroy(),this.vpvrRenderer.destroy(),this.backend.destroy(),this.chrome.destroy(),this.crosshairLayer.destroy(),this.attributionEl?.remove(),this.attributionEl=null,this.mountContainer?.style.removeProperty("--vela-toolbar-gutter"),this.mountContainer?.style.removeProperty("--vela-scale-gutter"),this.mountContainer?.style.removeProperty("--vela-price-pane-top"),this.mountContainer?.style.removeProperty("--vela-price-pane-bottom"),this.mountContainer=null,this.wrapper?.remove();}setBars(e,t){this.introRaf!=null&&(cancelAnimationFrame(this.introRaf),this.introRaf=null,this.modelAlpha=1),this.liveEaseTime=0;let n=this.bars,r=n[0]?.time;this.bars=Zb(e),this.scene.bars=this.bars,this.coords.setBars(this.bars.map(o=>o.time));for(let o of this.scene.indicators.values())this.refreshAnchorOffset(o);if(t?.preserveView===true&&r!=null&&this.bars.length>0){let o=this.bars[0].time,a=0;if(o!==r){let l=this.bars.findIndex(c=>c.time===r);if(l>0)a=l;else {let c=n.findIndex(d=>d.time===o);c>0&&(a=-c);}}a!==0&&(this.zoomAnchorLogical+=a,this.hoverLogical!=null&&(this.hoverLogical+=a));}let i=t?.preserveView===true&&this.didInitialFit;if(this.coords.width>0&&!i&&(this.fitContent(),this.didInitialFit=true),!this.introPlayed&&this.bars.length>0&&(this.introPlayed=true,this.introStyle)){this.playIntro(this.introStyle);return}this.scheduler.invalidate(4);}updateBar(e){let t=this.bars.length,n=this.bars[t-1];if(n&&e.time===n.time)this.bars[t-1]=e,this.liveEaseTime!==e.time&&this.syncLiveEase(e),this.animator.start();else if(!n||e.time>n.time)this.bars.push(e),this.syncLiveEase(e),this.coords.barInterval>0?this.coords.appendBar(e.time):this.coords.setBars(this.bars.map(r=>r.time));else return;this.scene.bars=this.bars,this.scheduler.invalidate(4);}syncLiveEase(e){this.liveEaseTime=e.time,this.liveEaseHigh=e.high,this.liveEaseLow=e.low,this.liveEaseClose=e.close;}easeLiveBar(e){let t=this.bars[this.bars.length-1];if(!t||this.liveEaseTime!==t.time)return false;let n=Math.max(1e-9,Math.abs(t.close)*1e-6),r=Se(this.liveEaseHigh,t.high,e,Hs),i=Se(this.liveEaseLow,t.low,e,Hs),o=Se(this.liveEaseClose,t.close,e,Hs),a=Math.abs(r-t.high)>n||Math.abs(i-t.low)>n||Math.abs(o-t.close)>n;return this.liveEaseHigh=a?r:t.high,this.liveEaseLow=a?i:t.low,this.liveEaseClose=a?o:t.close,a}ensurePane(e){this.scene.ensurePane(e.id,e.kind,e.order,e.heightWeight??(e.kind==="price"?3:1)),this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}removePane(e){e!==pe&&(this.scene.removePane(e),this.maximizedPaneId===e&&(this.maximizedPaneId=null),this.refreshAxisWidth(),this.layoutPanes(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}setIndicatorPane(e,t,n){let r=this.scene.indicators.get(e.id);r&&(r.paneId=t,r.ownScale=n?.ownScale===true,r.ownScale||this.scene.dropIndicatorScale(e.id),this.inputsUI.setPane(e.id,t),this.refreshAnchorOffset(r),this.syncTables(r),this.refreshAxisWidth(),this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}orderPanes(e){this.scene.orderPanes(e),this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}setPaneCollapsed(e,t){let n=this.scene.panes.get(e);!n||n.collapsed===t||(n.collapsed=t,this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4));}setPaneMaximized(e){e!==null&&!this.scene.panes.has(e)&&(e=null),this.maximizedPaneId=e,this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}onPaneAction(e){return this.paneActionCbs.add(e),()=>this.paneActionCbs.delete(e)}emitPaneAction(e){for(let t of this.paneActionCbs)t(e);}onMoveIndicator(e){return this.moveIndicatorCbs.add(e),()=>this.moveIndicatorCbs.delete(e)}maxOwnScaleColumns(){let e=0;for(let t of this.scene.panes.values()){let n=this.scene.ownScaleIndicatorsForPane(t.id).length;n>e&&(e=n);}return e}refreshAxisWidth(){let e=So+Ab*this.maxOwnScaleColumns();return e===this.rightAxisW?false:(this.rightAxisW=e,this.publishGutters(),this.coords.width>0&&this.syncSize(),true)}refreshAnchorOffset(e){let t=e.anchorTime;if(t==null||this.bars.length===0){this.scene.setAnchorOffset(e.id,0);return}let n=this.bars[0].time;if(t===n){this.scene.setAnchorOffset(e.id,0);return}if(t<n){let a=Yb(e,n);if(a==null){console.warn(`[vela] indicator "${e.id}" starts before the first bar with no series to align on \u2014 rendering unanchored`),this.scene.setAnchorOffset(e.id,0);return}this.scene.setAnchorOffset(e.id,-a);return}let r=0,i=this.bars.length-1,o=this.bars.length;for(;r<=i;){let a=r+i>>1;this.bars[a].time>=t?(o=a,i=a-1):r=a+1;}if(o>=this.bars.length||this.bars[o].time!==t){console.warn(`[vela] indicator "${e.id}" anchorTime matches no chart bar \u2014 rendering unanchored`),this.scene.setAnchorOffset(e.id,0);return}this.scene.setAnchorOffset(e.id,o);}mountIndicator(e){return this.scene.indicators.set(e.id,e),this.refreshAnchorOffset(e),this.scene.assignIndicatorZ(e.id),this.inputsUI.upsert(e.id,e.shorttitle??e.title,e.inputs,e.inputValues,e.paneId,{native:!!e.native,...e.shorttitle?{settingsTitle:e.title}:{}}),this.syncTables(e),e.native?.type==="volume"?(this.volumeActive=true,this.volumeHidden=false):e.native?.type==="vpvr"&&(this.vpvrActive=true,this.vpvrHidden=false),e.ownScale&&this.refreshAxisWidth(),this.paneControls?.refresh(),this.scheduler.invalidate(4),{id:e.id}}updateIndicator(e,t){let n=this.scene.indicators.get(e.id);if(n){if(t.kind==="value"&&t.anchorTime!==void 0){let r=t.anchorTime??void 0;r!==n.anchorTime&&(n.anchorTime=r,this.refreshAnchorOffset(n));}Xb(n,t),this.syncTables(n),this.scheduler.invalidate(3);}}removeIndicator(e){let t=this.scene.indicators.get(e.id)?.native?.type;t==="volume"?(this.volumeActive=false,this.volumeHidden=false,this.scene.volumeLayer=null):t==="vpvr"&&(this.vpvrActive=false,this.vpvrHidden=false,this.scene.vpvrLayer=null),this.scene.indicators.delete(e.id),this.scene.forgetIndicatorZ(e.id),this.scene.forgetAnchorOffset(e.id),this.scene.dropIndicatorScale(e.id),this.inputsUI.remove(e.id),this.tableOverlays.get(e.id)?.destroy(),this.tableOverlays.delete(e.id),this.refreshAxisWidth(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}setIndicatorInputs(e,t){this.inputsUI.setValues(e.id,t);}setSymbolPicker(e){this.symbolPicker=e,this.inputsUI?.setSymbolPicker(e);}setLegendActions(e){this.legendActionsProvider=e,this.inputsUI?.setLegendActions(e);}setLegendOverviewAction(e){this.legendOverviewAction=e,this.inputsUI?.setLegendOverviewAction(e);}openIndicatorSettings(e){this.inputsUI?.openSettingsFor(e);}setIndicatorVisible(e,t){let n=this.scene.indicators.get(e.id)?.native?.type;if(n==="volume"||n==="vpvr"){n==="volume"?this.volumeHidden=!t:this.vpvrHidden=!t,this.inputsUI.setVisible(e.id,t),this.scheduler.invalidate(4);return}t||(this.scene.indicators.delete(e.id),this.tableOverlays.get(e.id)?.destroy(),this.tableOverlays.delete(e.id)),this.inputsUI.setVisible(e.id,t),this.scheduler.invalidate(4);}onInputChange(e){return this.inputChangeCbs.add(e),()=>this.inputChangeCbs.delete(e)}onToggleIndicatorVisible(e){return this.toggleVisibleCbs.add(e),()=>this.toggleVisibleCbs.delete(e)}onPriceStyleChange(e){return this.priceStyleCbs.add(e),()=>this.priceStyleCbs.delete(e)}setPriceStyle(e){if(e!==this.scene.priceStyle){this.scene.priceStyle=e,this.scene.basePainting=rs(e),this.scene.candleOverride=Wi(e,this.scene.style.chartTypes);for(let t of this.priceStyleCbs)t(e);}}onRemoveIndicator(e){return this.removeIndicatorCbs.add(e),()=>this.removeIndicatorCbs.delete(e)}setLayoutMode(e){if(e!==this.layoutMode){if(this.layoutMode=e,this.mountContainer?.setAttribute("data-vela-layout",e),this.userDrawings?.setLayoutMode(e),this.settingsDialog?.setLayoutMode(e),this.inputsUI?.setLayoutMode(e),this.scrollButton){let t=e==="mobile"?_s:ir;this.scrollButton.style.width=`${t}px`,this.scrollButton.style.height=`${t}px`;}this.updateScrollToRealtimeButton();}}setSettingsSections(e){this.hostSettingsSections=e,this.settingsDialog?.setHostSections(e);}onChartTypeSettingsChange(e){return this.chartTypeSettingsCbs.add(e),()=>this.chartTypeSettingsCbs.delete(e)}onConfigChanged(e){return this.configChangedCbs.add(e),()=>this.configChangedCbs.delete(e)}onThemeSelect(e){return this.themeSelectCbs.add(e),()=>this.themeSelectCbs.delete(e)}onCrosshairMove(e){return this.crosshairCbs.add(e),()=>this.crosshairCbs.delete(e)}onClick(e){return this.clickCbs.add(e),()=>this.clickCbs.delete(e)}onAxisLongPress(e){return this.axisLongPressCbs.add(e),()=>this.axisLongPressCbs.delete(e)}onViewportChange(e){return this.viewportCbs.add(e),()=>this.viewportCbs.delete(e)}getVisibleRange(){let e=this.coords.barCount;if(e===0||this.coords.width===0)return null;let t=this.coords.visibleLogicalRange(),n=Math.max(0,Math.ceil(t.from)),r=Math.min(e-1,Math.floor(t.to));return r<n?null:{from:this.coords.logicalToTime(n),to:this.coords.logicalToTime(r)}}setVisibleRange(e){let t=this.coords.timeToLogical(e.from),n=this.coords.timeToLogical(e.to),r=Math.max(1e-6,n-t),i=Ke(this.coords.width/(r*this.coords.spacingScale)),o=n-(this.coords.barCount-1);this.applyViewport({barSpacing:i,rightOffset:o});}panBy(e){if(this.coords.barCount===0||this.coords.width===0)return;let t=this.coords.getViewport(),n=this.coords.width/this.coords.pxPerBar(),r=this.scrollTargetRO??t.rightOffset;this.glideRightOffset(this.clampViewport(t.barSpacing,r+e*n).rightOffset);}applyViewport(e){this.animator.stop(),this.panVelocity=0,this.scrollTargetRO=null;let t=this.clampViewport(e.barSpacing,e.rightOffset);this.coords.setViewport(t),this.targetBarSpacing=t.barSpacing,this.scheduler.invalidate(4),this.emitViewportChange();}zoomTo(e,t,n){let r=this.clampViewport(e,this.coords.getViewport().rightOffset).barSpacing;if(this.zoomAnchorLogical=t,this.zoomAnchorX=n,this.panVelocity=0,this.scrollTargetRO=null,!this.animZoom){let i=this.clampViewport(r,this.anchoredRightOffset(r));this.coords.setViewport(i),this.targetBarSpacing=i.barSpacing,this.scheduler.invalidate(4),this.emitViewportChange();return}this.targetBarSpacing=r,this.animator.start();}fling(e){this.animPan&&(this.scrollTargetRO=null,this.panVelocity=e,this.animator.start());}anchoredRightOffset(e){let t=e*this.coords.spacingScale;return this.zoomAnchorLogical+(this.coords.width-this.zoomAnchorX)/t-(this.coords.barCount-1)}clampViewport(e,t){let n=this.coords.barCount,r=this.coords.width;if(n<=1||r<=0)return {barSpacing:Ke(e),rightOffset:t};let i=Math.min(_b,n),o=this.coords.spacingScale,a=Math.min(1e3,r/(i*o)),l=Math.max(.5,Math.min(a,r/((n+vd)*o))),c=Math.max(l,Math.min(a,e)),h=r/(c*o)-(i-1),u=i-n,p=Math.max(u,Math.min(h,t));return {barSpacing:c,rightOffset:p}}animTick(e){let t=this.coords.getViewport(),n=t.barSpacing,r=t.rightOffset,i=false,o=this.targetBarSpacing;Math.abs(n-o)>o*.001?(n=Ke(Se(n,o,e,Nb)),r=this.anchoredRightOffset(n),i=true):n!==o&&(n=o,r=this.anchoredRightOffset(n));let a=$b/Math.max(1e-6,n*this.coords.spacingScale);if(Math.abs(this.panVelocity)>a&&(r+=this.panVelocity*e,this.panVelocity*=Math.exp(-e/Hb),Math.abs(this.panVelocity)<=a?this.panVelocity=0:i=true),this.scrollTargetRO!=null){let c=this.scrollTargetRO,d=Se(r,c,e,zb);Math.abs(d-c)<.001?(r=c,this.scrollTargetRO=null):(r=d,i=true);}let l=this.clampViewport(n,r);return l.barSpacing!==n&&(this.targetBarSpacing=l.barSpacing),this.scrollTargetRO!=null&&l.rightOffset!==r&&(this.scrollTargetRO=l.rightOffset),this.coords.setViewport(l),this.computeScales(),this.easeScales(e)&&(i=true),this.easeLiveBar(e)&&(i=true),this.skeletonClockMs+=e,this.paintData(),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx()),this.updateLegendValues(),this.emitViewportChange(),i}easeScales(e){let t=false;for(let n of this.scene.panes.values()){let r=n.scaleTarget,i=n.scale;if(r.log&&i.min>0&&r.min>0){let c=Math.log(r.min),d=Math.log(r.max),h=Math.max(1e-9,Math.abs(d-c)),u=Se(Math.log(i.min),c,e,pn),p=Se(Math.log(i.max),d,e,pn);Math.abs(u-c)<=h*.001&&Math.abs(p-d)<=h*.001?n.scale={min:r.min,max:r.max,log:true}:(t=true,n.scale={min:Math.exp(u),max:Math.exp(p),log:true});continue}let o=Math.max(1e-9,Math.abs(r.max-r.min)),a=Se(i.min,r.min,e,pn),l=Se(i.max,r.max,e,pn);Math.abs(a-r.min)<=o*.001&&Math.abs(l-r.max)<=o*.001?(a=r.min,l=r.max):t=true,n.scale={min:a,max:l,log:r.log};}for(let n of this.scene.indicatorScales.values()){let r=n.scaleTarget,i=n.scale,o=Math.max(1e-9,Math.abs(r.max-r.min)),a=Se(i.min,r.min,e,pn),l=Se(i.max,r.max,e,pn);Math.abs(a-r.min)<=o*.001&&Math.abs(l-r.max)<=o*.001?(a=r.min,l=r.max):t=true,n.scale={min:a,max:l};}return t}emitViewportChange(){this.updateScrollToRealtimeButton();let e=this.getVisibleRange();if(e)for(let t of this.viewportCbs)t(e);}handlePointerMove(e,t){if(e===null||t===null||this.coords.barCount===0){this.scene.crosshair=null,this.hoverSeparatorY=null,this.lastPointer=null,this.scheduler.invalidate(1),this.hoverLogical=null;let p={time:null,price:null,paneKind:null,values:new Map,ohlc:null};for(let m of this.crosshairCbs)m(p);return}let n=e>=0&&t>=0&&e<=this.coords.width&&t<=this.coords.height;this.scene.crosshair=n?{x:e,y:t}:null,this.lastPointer=n?{x:e,y:t}:null,this.hoverSeparatorY=e>=0&&t>=0&&t<=this.coords.height?this.separatorHoverY(t):null,this.scheduler.invalidate(1);let r=Math.round(this.coords.xToLogical(e)),i=r>=0&&r<this.coords.barCount,o=i?this.coords.logicalToTime(r):null,a=this.paneNodeAtY(t),l=n&&a?this.coords.yToPrice(t,a.scale,a.bounds):null,c=new Map;if(i)for(let p of this.scene.indicators.values()){let m=this.scene.offsetOf(p.id);for(let f of p.series)if(le(f)){let b=f.points[r-m]?.value;b!=null&&c.set(f.id,b);}}let d=i?this.bars[r]:void 0,h=d?{time:d.time,open:d.open,high:d.high,low:d.low,close:d.close,volume:d.volume}:null;this.hoverLogical=i?r:null;let u={time:o,price:l,paneKind:n&&a?a.kind:null,values:c,ohlc:h};for(let p of this.crosshairCbs)p(u);}handleClick(e){if(this.coords.barCount===0)return;let t=Math.round(this.coords.xToLogical(e)),n=t>=0&&t<this.coords.barCount;for(let r of this.clickCbs)r({time:n?this.coords.logicalToTime(t):null,price:null});}paneAtY(e){return this.paneNodeAtY(e)}paneNodeAtY(e){for(let t of this.scene.panes.values())if(e>=t.bounds.top&&e<=t.bounds.top+t.bounds.height)return t;return null}nearestPaneToY(e){let t=null,n=1/0;for(let r of this.scene.panes.values()){let i=e<r.bounds.top?r.bounds.top-e:e-(r.bounds.top+r.bounds.height);i<n&&(n=i,t=r);}return t}resolveScaleHolder(e,t){let n=this.paneNodeAtY(t);if(!n)return null;let r=this.coords.width,i=this.scene.ownScaleIndicatorsForPane(n.id);if(e>=r+64&&i.length>0){let o=Math.floor((e-r-64)/56),a=i[o];if(a)return {holder:this.scene.ensureIndicatorScale(a.id,n.scaleTarget),height:n.bounds.height}}return {holder:n,height:n.bounds.height}}beginPriceScale(e,t){let n=this.resolveScaleHolder(e,t);n&&(this.scaleDragHolder=n.holder,this.scaleDragHeight=n.height,this.scaleDragStart={...n.holder.scale},n.holder.manualScale={...n.holder.scale},this.scheduler.invalidate(4));}priceScaleBy(e){let t=this.scaleDragHolder,n=this.scaleDragStart;!t||!n||this.setManualScale(t,nd(n,Math.exp(e*Wb)));}beginPricePan(e){let t=this.paneNodeAtY(e);return !t||!t.manualScale?false:(this.scaleDragHolder=t,this.scaleDragHeight=t.bounds.height,this.scaleDragStart={...t.scale},true)}pricePanBy(e){let t=this.scaleDragHolder,n=this.scaleDragStart;!t||!n||this.setManualScale(t,rd(n,e,this.scaleDragHeight));}resetPriceScale(e,t){let n=this.resolveScaleHolder(e,t);n&&(n.holder.manualScale=null,this.scheduler.invalidate(4));}dataDblClick(e,t){let n=this.paneNodeAtY(t)??this.nearestPaneToY(t);if(!n)return;let r=this.maximizedPaneId!==n.id;this.maximizedPaneId=r?n.id:null,this.afterPaneLayoutChange(),this.emitPaneAction({type:"maximize",paneId:n.id,maximized:r});}resetView(){this.fitContent(),this.scheduler.invalidate(4),this.emitViewportChange();}setManualScale(e,t){e.manualScale=t,e.scale={...t},e.scaleTarget={...t},e.initialized=true,this.scheduler.invalidate(4);}afterPaneLayoutChange(){this.layoutPanes(),this.repositionTables(),this.paneControls?.refresh(),this.scheduler.invalidate(4);}paneControlViews(){let e=this.scene.orderedPanes();return e.map((t,n)=>({id:t.id,kind:t.kind,collapsed:t.collapsed,maximized:this.maximizedPaneId===t.id,top:t.bounds.top,height:t.bounds.height,index:n,count:e.length}))}movePaneLocal(e,t){let n=this.scene.orderedPanes(),r=n.findIndex(l=>l.id===e);if(r<0)return;let i=t==="up"?r-1:r+1;if(i<1||i>=n.length)return;let o=n.map(l=>l.id),a=o[r];o[r]=o[i],o[i]=a,this.scene.orderPanes(o),this.afterPaneLayoutChange(),this.emitPaneAction({type:"move",paneId:e,dir:t});}paneSeparatorAt(e){return this.separatorPaneIndexAt(e)!==null}separatorHoverY(e){if(!this.paneResizeEnabled)return null;let t=this.separatorPaneIndexAt(e);return t===null?null:this.scene.orderedPanes()[t].bounds.top}separatorPaneIndexAt(e){let t=this.scene.orderedPanes();for(let n=1;n<t.length;n++)if(Math.abs(e-t[n].bounds.top)<=Gb)return n;return null}beginPaneResize(e){let t=this.separatorPaneIndexAt(e);if(t===null)return;let n=this.scene.orderedPanes(),r=n[t-1],i=n[t];this.resizeAbove=r,this.resizeBelow=i,this.resizeSplitStart={combinedTop:r.bounds.top,combinedHeight:r.bounds.height+i.bounds.height,combinedWeight:r.heightWeight+i.heightWeight,startBoundaryY:i.bounds.top};}paneResizeBy(e){let t=this.resizeAbove,n=this.resizeBelow,r=this.resizeSplitStart;if(!t||!n||!r)return;let i=id(r,e);t.heightWeight=i.above,n.heightWeight=i.below,this.layoutPanes(),this.repositionTables(),this.scheduler.invalidate(4);}resetPaneSize(e){let t=this.separatorPaneIndexAt(e);if(t===null)return;let n=this.scene.orderedPanes(),r=n[t-1],i=n[t],o=(r.heightWeight+i.heightWeight)/2;r.heightWeight=o,i.heightWeight=o,this.layoutPanes(),this.repositionTables(),this.scheduler.invalidate(4);}setKeyboardEnabled(e){this.keyboardEnabled=e,!(!this.dataCanvas||!this.keyboard)&&(e?(this.dataCanvas.tabIndex=0,this.dataCanvas.setAttribute("role","application"),this.dataCanvas.setAttribute("aria-label","Interactive price chart. Use Left/Right arrows to move between bars, Shift+Arrow to pan, plus/minus to zoom, Home/End to jump, 0 to reset."),!this.liveRegion&&this.wrapper&&(this.liveRegion=document.createElement("div"),this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("role","status"),Object.assign(this.liveRegion.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:"0"}),this.wrapper.appendChild(this.liveRegion)),this.keyboard.attach(this.dataCanvas)):(this.keyboard.detach(),this.dataCanvas.removeAttribute("tabindex"),this.dataCanvas.removeAttribute("role"),this.dataCanvas.removeAttribute("aria-label")));}panByBars(e){let t=this.coords.getViewport();this.applyViewport({barSpacing:t.barSpacing,rightOffset:t.rightOffset+e});}zoomByStep(e){let t=this.coords.getViewport(),n=Ke(t.barSpacing*Math.exp(e*Ub));this.zoomTo(n,this.coords.rightEdgeLogical,this.coords.width);}stepCrosshair(e){let t=this.coords.barCount;if(t===0)return;let n=this.hoverLogical??Math.min(t-1,Math.round(this.coords.xToLogical(this.coords.width)));this.focusBar(n+e);}focusBar(e){let t=this.coords.barCount;if(t===0)return;let n=Math.max(0,Math.min(t-1,e)),r=this.coords.getViewport(),i=2,o=this.coords.xToLogical(0),a=this.coords.xToLogical(this.coords.width),l=r.rightOffset;n<o+i?l-=o+i-n:n>a-i&&(l+=n-(a-i)),l!==r.rightOffset&&this.applyViewport({barSpacing:r.barSpacing,rightOffset:l});let c=this.scene.orderedPanes().find(h=>h.kind==="price")??this.scene.orderedPanes()[0]??null,d=this.scene.crosshair?.y??(c?c.bounds.top+c.bounds.height/2:this.coords.height/2);this.handlePointerMove(this.coords.logicalToX(n),d),this.announceBar(n);}announceBar(e){if(!this.liveRegion)return;let t=this.bars[e],n=this.dataWindowPricePane(),r=this.dataWindowOHLC(t,n),i=[];t&&i.push(Kb(t.time,this.scene.timezone)),r&&i.push(`Open ${r.o}, High ${r.h}, Low ${r.l}, Close ${r.c}`);for(let o of this.dataWindowGroups(e,n))for(let a of o.rows)i.push(`${a.label} ${a.value}`);this.liveRegion.textContent=i.join(". ");}getDataWindowReadout(){let e=this.bars.length;if(e===0)return {date:"",time:"",ohlc:null,groups:[]};let t=this.hoverLogical!=null?this.hoverLogical:e-1,n=this.bars[t],r=this.dataWindowPricePane(),i=n?Sd(n.time,this.scene.timezone):{date:"",time:""};return {date:i.date,time:i.time,ohlc:this.dataWindowOHLC(n,r),groups:this.dataWindowGroups(t,r)}}dataWindowPricePane(){return this.scene.orderedPanes().find(e=>e.kind==="price")??null}dataWindowFmt(e,t){return t?$i(t.scale,t.bounds.height,e,this.scene.priceMintick):String(e)}dataWindowOHLC(e,t){return e?{o:this.dataWindowFmt(e.open,t),h:this.dataWindowFmt(e.high,t),l:this.dataWindowFmt(e.low,t),c:this.dataWindowFmt(e.close,t),vol:e.volume!=null?xd(e.volume):void 0,up:e.close>=e.open}:null}dataWindowGroups(e,t){let n=[];for(let r of this.scene.indicators.values()){let i=this.dataWindowRowsFor(r,e,t);i.length&&n.push({name:r.title,rows:i});}return n}dataWindowRowsFor(e,t,n){if(e.native?.type==="volume")return this.volumeReadoutRows(e,t);let r=(e.paneId?this.scene.panes.get(e.paneId):null)??n,i=this.scene.offsetOf(e.id),o=[];for(let a of e.series){let l,c;if(a.kind==="candle"||a.kind==="bar")l=a.bars[t-i]?.close,c=a.style?.up??this.theme.upColor;else if(le(a)){if(a.visible===false)continue;l=a.points[t-i]?.value,c=a.points[t-i]?.color??a.style.color;}else continue;l==null||!Number.isFinite(l)||o.push({label:a.title||e.title,value:this.dataWindowFmt(l,r),color:c});}return o}volumeReadoutRows(e,t){if(this.volumeHidden)return [];let n=this.bars[t],r=n?.volume;if(n==null||r==null||!Number.isFinite(r))return [];let i=this.scene.volumeLayer,o=n.close>=n.open?i?.upColor??this.theme.upColor:i?.downColor??this.theme.downColor;return [{label:e.title,value:xd(r),color:o}]}updateLegendValues(){if(!this.inputsUI)return;let e=this.bars.length,t=new Map;if(e>0){let n=this.hoverLogical!=null?this.hoverLogical:e-1,r=this.dataWindowPricePane();for(let i of this.scene.indicators.values())t.set(i.id,this.dataWindowRowsFor(i,n,r).map(o=>({value:o.value,color:o.color})));}this.inputsUI.setPlotValues(t);}renderFrame(e){this.animator.active||(bs(e)?(this.computeScales(),this.paintData()):ac(e)&&this.paintedData&&(this.chrome.prepare(this.scene,this.coords,this.theme),this.chrome.render(this.scene,this.coords,this.theme,this.axisSurface())),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx()),!bs(e)&&this.paintedData&&this.repaintCursorLayers(),this.updateLegendValues());}repaintCursorLayers(){let e=this.scene.panes.get(pe);if(!e)return;let t=typeof performance<"u"?performance.now():Date.now();for(let n of this.extLayers)n.def.repaintOnCursor&&(n.instance.render(this.extLayerArgs(n.def.id,e.scale,e.bounds,t)),this.animZoom&&n.instance.animating?.()&&this.animator.start());}extLayerArgs(e,t,n,r){return {bars:this.scene.bars,data:this.scene.nativeData.get(e),settings:this.scene.nativeData.get(`${e}-settings`)??{},pending:this.scene.nativePending.get(e)??[],coords:this.coords,scale:t,bounds:n,theme:this.theme,priceStyle:this.scene.priceStyle,nowMs:r,cursor:this.lastPointer}}paintData(){this.stampScaleInvert(),this.backend.modelAlpha=this.modelAlpha,this.backend.candleBodyAlpha=this.candleBodyAlpha,this.backend.candleStructureAlpha=this.candleStructureAlpha,this.backend.gridAlpha=1;let e=1;this.backend.candleBodyScale=e;let t=this.scene.panes.get(pe);if(t){let o=this.nativeLayerPane("volume")??t;this.volumeRenderer.render({bars:this.scene.bars,data:this.scene.volumeLayer,visible:this.volumeActive&&!this.volumeHidden&&!o.collapsed,coords:this.coords,bounds:o.bounds,fillPane:o.kind!=="price"}),this.vpvrRenderer.render({bars:this.scene.bars,data:this.scene.vpvrLayer,visible:this.vpvrActive&&!this.vpvrHidden,coords:this.coords,scale:t.scale,bounds:t.bounds,theme:this.theme});let a=typeof performance<"u"?performance.now():Date.now(),l=null;for(let c of this.extLayers){let d=this.extLayerArgs(c.def.id,t.scale,t.bounds,a);c.instance.render(d),l=sd(l,c.instance.modulateBase?.(d)??null),this.animZoom&&c.instance.animating?.()&&this.animator.start();}l&&(l.candleBodyScale!=null&&(this.backend.candleBodyScale=zs(l.candleBodyScale)||.01),l.candleBodyAlpha!=null&&(this.backend.candleBodyAlpha=zs(l.candleBodyAlpha)*this.candleBodyAlpha),l.gridAlpha!=null&&(this.backend.gridAlpha=zs(l.gridAlpha)));}let n=this.bars.length-1,r=n>=0?this.bars[n]:void 0,i=!!r&&this.liveEaseTime===r.time&&(r.high!==this.liveEaseHigh||r.low!==this.liveEaseLow||r.close!==this.liveEaseClose);i&&r&&(this.bars[n]={...r,high:this.liveEaseHigh,low:this.liveEaseLow,close:this.liveEaseClose}),this.scene.drawingSlices=this.userDrawings?.prepareSlices(this.scene.orderedPanes().map(o=>o.id))??new Map,this.backend.render(this.scene,this.coords,this.theme),this.chrome.render(this.scene,this.coords,this.theme,this.axisSurface()),this.userDrawings?.render(),i&&r&&(this.bars[n]=r),this.paintedData=true;}drawingProjector(){return Jc(this.coords,e=>{let t=this.scene.panes.get(e);return t?{scale:t.scale,bounds:t.bounds,collapsed:t.collapsed}:null},e=>this.paneNodeAtY(e)?.id??null,(e,t)=>this.barsInTimeRange(e,t))}barsInTimeRange(e,t){let n=Math.min(e,t),r=Math.max(e,t),i=[];for(let o of this.bars)if(!(o.time<n)){if(o.time>r)break;i.push(o);}return i}get userDrawingsPort(){return this.userDrawings??void 0}focus(){this.dataCanvas?.focus({preventScroll:true});}setExternalCrosshair(e,t=null){let n=e==null?null:{time:e,price:t},r=this.externalCross;!n&&!r||n&&r&&r.time===n.time&&r.price===n.price||(this.externalCross=n,this.scheduler.invalidate(1));}externalCrossPx(){let e=this.externalCross;if(!e||this.coords.barCount===0)return null;let t=Math.floor(this.coords.timeToLogical(e.time));if(t<0||t>=this.coords.barCount)return null;let n=this.coords.logicalToX(t);if(!Number.isFinite(n)||n<0||n>this.coords.width)return null;let r=null;if(e.price!=null){let i=this.scene.orderedPanes().find(o=>o.kind==="price");i&&(r=this.coords.priceToY(e.price,i.scale,i.bounds),(!Number.isFinite(r)||r<i.bounds.top||r>i.bounds.top+i.bounds.height)&&(r=null));}return {x:n,y:r,time:this.coords.logicalToTime(t),price:r!=null?e.price:null}}setSnapMode(e){this.snapMode=e;}snapToCandle(e,t,n="strong",r){if(n==="off")return e;let i=this.bars.length;if(i===0)return e;let o=Math.max(0,Math.min(i-1,Math.round(this.coords.timeToLogical(e.time)))),a=this.bars[o];if(!a)return e;let l;if(t!==pe)l={time:a.time,price:e.price};else {let c=a.open;for(let d of [a.high,a.low,a.close])Math.abs(d-e.price)<Math.abs(c-e.price)&&(c=d);l={time:a.time,price:c};}if(n==="weak"&&r){let c=this.drawingProjector(),d=c.yOf(l.price,t);if(Math.hypot(c.xOf(l.time)-r.x,(d??r.y)-r.y)>Rb)return e}return l}computeScales(){let e=this.coords.barCount;if(e===0)return;let t=this.coords.visibleLogicalRange(),n=this.coords.visibleTimeRange(),r=Math.max(0,Math.floor(t.from)),i=Math.min(e-1,Math.ceil(t.to));if(i<r)return;this.scene.percentBaseline=this.bars[r]?.close??0;let o=this.scene.orderedPanes(),a=o.find(c=>c.kind==="price")??null;this.chrome.prepare(this.scene,this.coords,this.theme);let l=this.animator.active;for(let c of o){if(c.manualScale){c.scaleTarget=c.manualScale,c.scale={...c.manualScale},c.initialized=true;continue}let h=this.scene.indicatorsForPane(c.id).filter(f=>f.ownScale!==true),u=this.chrome.paneDrawingsRange(h,this.scene,c===a,t),p=this.userDrawings?.priceRangeForPane(c.id,n.from,n.to)??null;p&&(u=u?{min:Math.min(u.min,p.min),max:Math.max(u.max,p.max)}:p);let m=c.kind==="price"&&!this.scene.candlesHidden;if(c.scaleTarget=ks(h,this.bars,m,r,i,u,ds(this.scene,c),f=>this.scene.offsetOf(f)),c.percentBaseline=c.kind==="price"?this.bars[r]?.close??0:this.firstVisibleValue(h,r),c.axisFormat=void 0,this.volumeOwnsPane(c,h)){let f=this.maxVisibleVolume(r,i);f>0&&(c.scaleTarget={min:0,max:f/Is},c.axisFormat="volume");}if(c===a&&this.scene.tradeMarkers.visible&&c.bounds.height>0){let f=this.tradesScaleHints(t);if(f){let b=c.scaleTarget,g={...b,min:Math.min(b.min,f.min),max:Math.max(b.max,f.max)};c.scaleTarget=td(g,c.bounds.height,f.abovePx,f.belowPx);}}(!l||!c.initialized)&&(c.scale={...c.scaleTarget},c.initialized=true);for(let f of this.scene.ownScaleIndicatorsForPane(c.id)){let b=this.scene.ensureIndicatorScale(f.id,c.scaleTarget);if(b.manualScale){b.scaleTarget=b.manualScale,b.scale={...b.manualScale},b.initialized=true;continue}let g=this.chrome.paneDrawingsRange([f],this.scene,false,t);b.scaleTarget=ks([f],this.bars,false,r,i,g,false,v=>this.scene.offsetOf(v)),(!l||!b.initialized)&&(b.scale={...b.scaleTarget},b.initialized=true);}}}tradesScaleHints(e){let t=null,n={timeToLogical:r=>this.coords.timeToLogical(r),barAt:r=>{let i=this.bars[Math.round(r)];return i?{high:i.high,low:i.low}:null}};for(let r of this.scene.indicators.values()){if(!r.trades?.length)continue;let i=ql(r.trades,this.scene.tradeMarkers,n,e.from,e.to,this.scene.style.fontSize);i&&(t=t?{min:Math.min(t.min,i.min),max:Math.max(t.max,i.max),abovePx:Math.max(t.abovePx,i.abovePx),belowPx:Math.max(t.belowPx,i.belowPx)}:i);}return t}fitContent(){let e=this.coords.barCount,t=this.coords.width;if(e<=0||t<=0)return;this.animator?.stop(),this.panVelocity=0;for(let o of this.scene.panes.values())o.manualScale=null;for(let o of this.scene.indicatorScales.values())o.manualScale=null;let n=Math.min(e,200),r=6,i=this.clampViewport(t/((n+r)*this.coords.spacingScale),r);this.coords.setViewport(i),this.targetBarSpacing=i.barSpacing;}paneBoundsFor(e){let t=this.scene.panes.get(e);return {top:t?.bounds.top??0,height:t?.bounds.height??0,rightAxis:this.rightAxisW}}paneMasterTitle(e){let t=this.scene.orderedIndicatorsForPane(e);return (t.find(r=>r.ownScale!==true)??t[0])?.title||null}nativeLayerPane(e){for(let t of this.scene.indicators.values())if(t.native?.type===e)return this.scene.panes.get(t.paneId??pe)??null;return null}volumeOwnsPane(e,t){return e.kind==="price"||!this.volumeActive||this.volumeHidden||!this.scene.volumeLayer||this.nativeLayerPane("volume")!==e?false:t.every(n=>n.native?.type==="volume")}paneScaleInfos(){return this.scene.orderedPanes().map(e=>({id:e.id,kind:e.kind,top:e.bounds.top,height:e.bounds.height,mode:cs(this.scene,e),log:ds(this.scene,e),invert:hs(this.scene,e)}))}setPaneScaleMode(e,t){if(e===pe)this.scene.scaleMode=t;else {let n=this.scene.panes.get(e);if(!n)return;n.scaleMode=t;}this.scheduler?.invalidate(4);}setPaneLog(e,t){if(e===pe){this.scene.logScale=t;let n=this.scene.orderedPanes().find(r=>r.kind==="price");n&&(n.manualScale=null);}else {let n=this.scene.panes.get(e);if(!n)return;n.logScale=t,n.manualScale=null;}this.scheduler?.invalidate(4);}setPaneInvert(e,t){if(e===pe)this.scene.invertScale=t;else {let n=this.scene.panes.get(e);if(!n)return;n.invert=t;}this.scheduler?.invalidate(4);}stampScaleInvert(){for(let e of this.scene.panes.values()){let t=hs(this.scene,e);e.scale.invert=t,e.scaleTarget.invert=t,e.manualScale&&(e.manualScale.invert=t);for(let n of this.scene.ownScaleIndicatorsForPane(e.id)){let r=this.scene.indicatorScales.get(n.id);r&&(r.scale.invert=t,r.scaleTarget.invert=t,r.manualScale&&(r.manualScale.invert=t));}}}firstVisibleValue(e,t){for(let n of e){let r=this.scene.offsetOf(n.id);for(let i of n.series)if(le(i)){let o=i.points[t-r]?.value;if(o!=null&&Number.isFinite(o))return o}else if(i.kind==="candle"||i.kind==="bar"){let o=i.bars[t-r];if(o&&Number.isFinite(o.close))return o.close}}return 0}maxVisibleVolume(e,t){let n=0;for(let r=e;r<=t;r+=1){let i=this.bars[r]?.volume;i!=null&&i>n&&(n=i);}return n}syncTables(e){let t=e.tables??[],n=this.tableOverlays.get(e.id);if(t.length===0){n&&(n.destroy(),this.tableOverlays.delete(e.id));return}n||(n=new Ni(this.plot,this.theme,r=>this.paneBoundsFor(r)),n.setVisible(this.loadingEl===null),this.tableOverlays.set(e.id,n)),n.update(t);}repositionTables(){for(let e of this.tableOverlays.values())e.reposition();}layoutPanes(){let e=this.scene.orderedPanes(),t=this.coords.height;this.inputsUI?.setCollapsedPanes(this.collapsedMasterMap());let n=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null;if(n){let d=0;for(let h of e)h===n?h.bounds={top:0,height:t}:h.bounds={top:t,height:0},d+=h.bounds.height;this.inputsUI?.reposition(),this.paneControls?.reposition(),this.repositionScrollButton(),this.positionAttribution(),this.publishPricePaneBounds();return}let r=e.filter(d=>d.collapsed),i=e.filter(d=>!d.collapsed),o=r.length*bd,a=Math.max(0,t-o),l=i.reduce((d,h)=>d+(h.heightWeight||1),0)||1,c=0;for(let d of e){let h=d.collapsed?bd:a*(d.heightWeight||1)/l;d.bounds={top:c,height:h},c+=h;}this.inputsUI?.reposition(),this.paneControls?.reposition(),this.repositionScrollButton(),this.positionAttribution(),this.publishPricePaneBounds();}repositionScrollButton(){let e=this.coords.height;if(e<=0)return;let t=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null,n=t?[t]:this.scene.orderedPanes().filter(i=>!i.collapsed),r=n.length?Math.max(...n.map(i=>i.bounds.top+i.bounds.height)):e;this.scrollBtnBottomPx=Ns+Math.max(0,e-r),this.scrollBtnRightPx=this.rightAxisW+wd,this.scrollButton&&(this.scrollButton.style.bottom=`${this.scrollBtnBottomPx}px`,this.scrollButton.style.right=`${this.scrollBtnRightPx}px`);}collapsedMasterMap(){let e=new Map;for(let t of this.scene.panes.values()){if(!t.collapsed)continue;let n=this.scene.orderedIndicatorsForPane(t.id),r=new Set(this.scene.ownScaleIndicatorsForPane(t.id).map(o=>o.id)),i=n.find(o=>!r.has(o.id))??n[0];e.set(t.id,i?.id??null);}return e}setToolbarGutter(e){e!==this.toolbarGutter&&(this.toolbarGutter=e,this.publishGutters(),this.positionAttribution(),this.syncSize());}publishGutters(){this.mountContainer?.style.setProperty("--vela-toolbar-gutter",`${this.toolbarGutter}px`),this.mountContainer?.style.setProperty("--vela-scale-gutter",`${this.rightAxisW}px`);}publishPricePaneBounds(){if(!this.mountContainer)return;let e=this.coords.height+or,t=this.scene.panes.get(pe),n=t?t.bounds.top:0,r=t?t.bounds.height:this.coords.height,i=Math.max(0,e-(n+r));this.mountContainer.style.setProperty("--vela-price-pane-top",`${n}px`),this.mountContainer.style.setProperty("--vela-price-pane-bottom",`${i}px`);}buildAttributionEl(){return this.attributionHtml!==null?dd(document,this.attributionHtml,this.theme.background):hd(document,this.theme.background)}rebuildAttribution(){this.attributionEl&&(this.attributionEl.remove(),this.attributionEl=this.buildAttributionEl(),this.attributionEnabled||(this.attributionEl.style.display="none"),this.positionAttribution(),this.wrapper.appendChild(this.attributionEl));}positionAttribution(){if(!this.attributionEl)return;let e=this.coords?.height??0,t=this.maximizedPaneId?this.scene.panes.get(this.maximizedPaneId):null,n=t?[t]:this.scene.orderedPanes().filter(i=>!i.collapsed),r=e>0&&n.length?Math.max(...n.map(i=>i.bounds.top+i.bounds.height)):e;Object.assign(this.attributionEl.style,{left:`${(this.toolbarGutter||0)+12}px`,bottom:`${or+10+Math.max(0,e-r)}px`});}refreshAttributionColor(){this.attributionEl&&(this.attributionHtml!==null?this.attributionEl.style.color=Os(this.theme.background):Fs(this.attributionEl,this.theme.background));}syncSize(){let e=this.wrapper.clientWidth,t=this.wrapper.clientHeight;if(e<=0||t<=0)return;let n=window.devicePixelRatio||1;this.plot.style.left=`${this.toolbarGutter}px`;let r=Math.max(1,e-this.toolbarGutter),i=t;this.dataCanvas.width=Math.round(r*n),this.dataCanvas.height=Math.round(i*n),this.volumeCanvas.width=this.dataCanvas.width,this.volumeCanvas.height=this.dataCanvas.height;for(let o of this.extLayers)o.canvas.width=this.dataCanvas.width,o.canvas.height=this.dataCanvas.height;this.vpvrCanvas.width=this.dataCanvas.width,this.vpvrCanvas.height=this.dataCanvas.height,this.chromeCanvas.width=this.dataCanvas.width,this.chromeCanvas.height=this.dataCanvas.height,this.drawingsCanvas.width=this.dataCanvas.width,this.drawingsCanvas.height=this.dataCanvas.height,this.cursorCanvas.width=this.dataCanvas.width,this.cursorCanvas.height=this.dataCanvas.height,this.coords.setSize(Math.max(1,r-this.rightAxisW),Math.max(1,i-or),n),this.scene.crosshair=null,this.layoutPanes(),this.repositionTables(),this.userDrawings?.onResize(),!this.didInitialFit&&this.coords.barCount>0&&(this.fitContent(),this.didInitialFit=true),this.animator.active?(this.computeScales(),this.paintData(),this.crosshairLayer.render(this.scene,this.coords,this.theme,this.hoverSeparatorY,this.externalCrossPx())):this.scheduler.flushNow(4);}applyBackground(){this.wrapper.style.background=this.theme.background;}};function Yb(s,e){for(let t of s.series){let n=t.kind==="candle"||t.kind==="bar"?t.bars:le(t)?t.points:null;if(!n||n.length===0)continue;let r=0,i=n.length;for(;r<i;){let o=r+i>>1;n[o].time<e?r=o+1:i=o;}return r}return null}function Xb(s,e){if(e.kind==="value"){for(let t of e.series){let n=s.series.find(r=>r.id===t.seriesId);n&&(t.kind==="points"&&le(n)?n.points=t.points:t.kind==="bars"&&(n.kind==="candle"||n.kind==="bar")&&(n.bars=t.bars));}e.lines&&(s.lines=e.lines),e.boxes&&(s.boxes=e.boxes),e.labels&&(s.labels=e.labels),e.polylines&&(s.polylines=e.polylines),e.linefills&&(s.linefills=e.linefills),e.tables&&(s.tables=e.tables),e.trades&&(s.trades=e.trades);return}for(let t of e.removed){let n=s.series.findIndex(r=>r.id===t);n>=0&&s.series.splice(n,1);}for(let t of e.added)s.series.push(t);}function Sd(s,e){let t=Xi(s,e),n=r=>r<10?`0${r}`:String(r);return {date:`${t.getUTCFullYear()}-${n(t.getUTCMonth()+1)}-${n(t.getUTCDate())}`,time:`${n(t.getUTCHours())}:${n(t.getUTCMinutes())}`}}function Kb(s,e){let{date:t,time:n}=Sd(s,e);return `${t} ${n}`}function jb(s){if(!Array.isArray(s))return [];let e=[];for(let t of s){if(!t||typeof t!="object")continue;let n=t,r=Number(n.from),i=Number(n.to);!Number.isFinite(r)||!Number.isFinite(i)||i<=r||e.push({from:r,to:i,color:typeof n.color=="string"?n.color:"rgba(120,130,160,0.10)"});}return e.sort((t,n)=>t.from-n.from)}function zs(s){return Math.max(0,Math.min(1,s))}function qb(s){return typeof s=="string"&&tn().includes(s)}function yd(s){return s==="percent"||s==="indexed"?s:"price"}function xd(s){let e=Math.abs(s);return e>=1e9?`${(s/1e9).toFixed(2)}B`:e>=1e6?`${(s/1e6).toFixed(2)}M`:e>=1e3?`${(s/1e3).toFixed(2)}K`:s.toFixed(2)}function Zb(s){let e=[...s].sort((n,r)=>n.time-r.time),t=[];for(let n of e){let r=t[t.length-1];r&&r.time===n.time?t[t.length-1]=n:t.push(n);}return t}function $s(s,e){let t=(s.open+s.high+s.low+s.close)/4,n=e?(e.open+e.close)/2:(s.open+s.close)/2;return {time:s.time,open:n,high:Math.max(s.high,n,t),low:Math.min(s.low,n,t),close:t,...s.volume!=null?{volume:s.volume}:{}}}function Cd(s){let e=new Array(s.length),t;for(let n=0;n<s.length;n+=1)t=$s(s[n],t),e[n]=t;return e}var Jb={full:Cd,next:$s};function Td(){Wo({id:"heikinashi",label:"Heikin Ashi",barTransform:Jb});}var Ws=q,Us=X,Gs=20;function Qb(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Md(s,e){return typeof s=="string"&&s!==""?s:e}function Co(s){return {upColor:Md(s.upColor,Ws),downColor:Md(s.downColor,Us),heightFrac:Math.min(.5,Math.max(.05,Qb(s.heightPct,Gs)/100))}}var Ys=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(Co(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData(Co(e));}suspend(){}resume(){this.ctx.pushData(Co(this.inputs));}stop(){}},Ld={type:"volume",title:"Volume",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"upColor",title:"Up color",type:"color",defval:Ws},{key:"downColor",title:"Down color",type:"color",defval:Us},{key:"heightPct",title:"Height %",type:"int",defval:Gs,min:5,max:50,step:1,tooltip:"Pane height the tallest visible bar occupies"}],defaultInputs:()=>({upColor:Ws,downColor:Us,heightPct:Gs}),create:()=>new Ys};function Xs(){_t(Ld);}var js=24,qs=30,Zs=ve,Js=X,Qs=70;function Ks(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Pd(s,e){return typeof s=="string"&&s!==""?s:e}function To(s){return {rows:Math.round(Math.min(400,Math.max(2,Ks(s.rows,js)))),widthFrac:Math.min(.9,Math.max(.05,Ks(s.widthPct,qs)/100)),upColor:Pd(s.upColor,Zs),downColor:Pd(s.downColor,Js),showPoc:s.showPoc!==false,valueAreaFrac:Math.min(1,Math.max(0,Ks(s.valueAreaPct,Qs)/100))}}var ea=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(To(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData(To(e));}suspend(){}resume(){this.ctx.pushData(To(this.inputs));}stop(){}},Ed={type:"vpvr",title:"Visible Range Volume Profile",shortTitle:"VRVP",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"rows",title:"Rows",type:"int",defval:js,min:2,max:400,step:1},{key:"widthPct",title:"Width %",type:"int",defval:qs,min:5,max:90,step:1,tooltip:"Pane width the largest row occupies"},{key:"upColor",title:"Up color",type:"color",defval:Zs},{key:"downColor",title:"Down color",type:"color",defval:Js},{key:"showPoc",title:"Point of control",type:"bool",defval:true},{key:"valueAreaPct",title:"Value area %",type:"int",defval:Qs,min:0,max:100,step:1}],defaultInputs:()=>({rows:js,widthPct:qs,upColor:Zs,downColor:Js,showPoc:true,valueAreaPct:Qs}),create:()=>new ea};function ta(){_t(Ed);}var na=class{constructor(e,t={},n={}){Td(),Xs(),ta();let r=eg(e),i=Xt(t.theme),o=true,a=true;typeof t.animations=="boolean"?(o=t.animations,a=t.animations):t.animations&&(o=t.animations.zoom??true,a=t.animations.pan??true);let l={currentPriceLine:t.currentPriceLine??true,logScale:t.logScale??false,nativeBackend:t.nativeBackend??"auto",animZoom:o,animPan:a,glow:t.glow??0,upColor:t.upColor??q,downColor:t.downColor??X,priceStyle:t.priceStyle??"candles"},c=t.renderer??sr;if(typeof c!="function")throw new Error("[vela] options.renderer must be a renderer class, e.g. import { LwcRenderer } from 'vela/renderers/lwc'. The 'lwc'/'native' string options were removed.");let d=n.renderer??new c(l),h=n.engines??[],u=n.dataFeed??new Pt,p={market:{symbol:t.symbol,timeframe:t.timeframe,bars:t.bars,visibleRange:t.visibleRange,data:t.data},live:t.live??false,theme:i,defaultLanguage:t.defaultLanguage??h[0]?.language??"pine",drawings:t.drawings,volume:t.volume??true};this.rendererControl=new On(d),this.dataControl=new _n(u),this.orchestrator=new Ri(r,d,u,h,p,this.dataControl);let m=Go();Object.keys(m).length>0&&this.rendererControl.set(m),this.panesControl=new Di(this.orchestrator),this.drawingsControl=new Nn(this.orchestrator.drawings);}registerEngine(e,t){return this.orchestrator.registerEngine(e,t),this}addIndicator(e,t){return this.orchestrator.addIndicator(e,t)}addNativeIndicator(e,t){return this.orchestrator.addNativeIndicator(e,t)}availableNativeIndicators(){return this.orchestrator.availableNativeIndicators()}presentNativeIndicators(){return this.orchestrator.presentNativeIndicators()}indicators(){return this.orchestrator.listIndicators()}runScript(e,t){let n=this.addIndicator(e,t),r=new Set,i=()=>{try{n.remove();}catch{}};return new Promise(o=>{let a=false,l=this.on("script:run",d=>{if(d.id===n.id){if(a){for(let h of r)h(d);return}a=true,c(),o({ok:true,run:d,error:null,onUpdate:h=>(r.add(h),()=>r.delete(h)),remove:()=>{l(),r.clear(),i();}});}}),c=n.on("error",({error:d})=>{a||(a=true,l(),c(),i(),o({ok:false,run:null,error:d,onUpdate:()=>()=>{},remove:()=>{}}));});})}runIndicator(e,t){let n=this.addIndicator(e,t);return new Promise(r=>{let i=n.on("ready",()=>{i(),o(),r({ok:true,handle:n,error:null,context:null});}),o=n.on("error",({error:a})=>{i(),o(),n.context().catch(()=>null).then(l=>{try{n.remove();}catch{}r({ok:false,handle:null,error:a,context:l});});});})}setMarket(e){return this.orchestrator.setMarket(e)}get market(){return this.orchestrator.marketSnapshot()}ready(){return this.orchestrator.ready()}historyComplete(){return this.orchestrator.historyComplete()}inspect(){return this.orchestrator.inspect()}get renderer(){return this.rendererControl}get panes(){return this.panesControl}get data(){return this.dataControl}get drawings(){return this.drawingsControl}on(e,t){return this.orchestrator.events.on(e,t)}getVisibleRange(){return this.orchestrator.getVisibleRange()}setVisibleRange(e){return this.orchestrator.setVisibleRange(e),this}panBy(e){return this.orchestrator.panBy(e),this}setVisibleRangePreset(e){return this.orchestrator.setVisibleRangePreset(e),this}resize(){this.orchestrator.resize();}setTheme(e){return this.orchestrator.setTheme(Xt(e)),this}destroy(){this.orchestrator.destroy();}};function eg(s){if(typeof s!="string")return s;let e=document.querySelector(s);if(!e)throw new Error(`[vela] container not found for selector "${s}"`);return e}var ar=new Map,lr=new Map,cr=new Map;function tg(s){return lr.set(s.id,s),()=>{lr.get(s.id)===s&&lr.delete(s.id);}}function ng(s){lr.delete(s);}function rg(){return [...lr.values()]}var kd=100;function ig(s){return cr.set(s.id,s),()=>{cr.get(s.id)===s&&cr.delete(s.id);}}function og(s){cr.delete(s);}function sg(){return [...cr.values()].sort((s,e)=>(s.order??kd)-(e.order??kd))}function ag(s){return ar.set(s.id,s),()=>{ar.get(s.id)===s&&ar.delete(s.id);}}function lg(s){ar.delete(s);}function cg(s,e){let t=[...ar.values()].filter(n=>n.target===s);return t.sort((n,r)=>(n.order??0)-(r.order??0)),e?t.filter(n=>!n.when||n.when(e)):t}var dr=new Map;function dg(s){return dr.set(s.id,s),()=>{dr.get(s.id)===s&&dr.delete(s.id);}}function hg(s){dr.delete(s);}function ug(){return [...dr.values()].sort((s,e)=>(s.order??0)-(e.order??0))}var hr=new Map;function pg(s,e){return hr.set(s,e),()=>{hr.get(s)===e&&hr.delete(s);}}function mg(s){hr.delete(s);}function fg(s){return {...Object.fromEntries(hr),...s}}var Id=280,ra=200,Rd=640;function bg(s,e=ra,t=Rd){let n=Number.isFinite(e)&&e>0?e:ra,r=Number.isFinite(t)?Math.max(t,n):Number.POSITIVE_INFINITY;return Number.isFinite(s)?Math.round(Math.min(Math.max(s,n),r)):n}function Dd(s){let e=s.title.trim().toLowerCase().replace(/\s+/g,"-");return `${s.instanceId}:${s.kind}:${e}#${s.ordinal}`}var Ad="https://api.binance.com/api/v3",gg="https://api.binance.us/api/v3",ia="https://fapi.binance.com/fapi/v1",vg="wss://stream.binance.com:9443",yg="wss://stream.binance.us:9443",xg="wss://fstream.binance.com";var Od={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h",D:"1d",W:"1w",M:"1M"},Fd={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},wg=[1,3,5,15,30,60,120,240,360,480,720],Sg={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h"},Cg=["1","3","5","15","30","45","60","120","180","240","D","W","M"];function Bd(s){return Fd[s]??Fd[s.toLowerCase()]??s}function oa(s){let e=s.trim().toUpperCase();return e.endsWith(".P")?{apiSymbol:e.slice(0,-2),isFutures:true}:{apiSymbol:e,isFutures:false}}function Vd(s){return s.map(e=>({time:Number(e[0]),open:Number(e[1]),high:Number(e[2]),low:Number(e[3]),close:Number(e[4]),volume:Number(e[5])}))}function Tg(s){return {time:Number(s.t),open:Number(s.o),high:Number(s.h),low:Number(s.l),close:Number(s.c),volume:Number(s.v)}}function Mg(s){let e=new Map;for(let t of s)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function Lg(s,e){let t=new Map;for(let n of s){let r=Math.floor(n.time/e)*e,i=t.get(r);i?(i.high=Math.max(i.high,n.high),i.low=Math.min(i.low,n.low),i.close=n.close,i.volume=(i.volume??0)+(n.volume??0)):t.set(r,{time:r,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,r)=>n.time-r.time)}function Pg(s){return wg.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}var Mo=class{constructor(){this.spotBaseUrl=null;this.spotBaseProbe=null;this.symbolsPromise=null;}info(){return {name:"binance",displayName:"Binance",requiresApiKey:false,supportedTimeframes:Cg,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let{apiSymbol:r,isFutures:i}=oa(e),o=i?ia:await this.spotBase(),a=Bd(t),l=Od[a];if(l)return Mg(Vd(await this.fetchKlines(o,r,l,n)));let c=/^\d+$/.test(a)?parseInt(a,10):null,d=c!=null?Pg(c):null;if(c==null||d==null)return console.warn(`[vela] Binance: timeframe "${t}" is not supported and cannot be aggregated.`),[];let h=c/d,u={...n,limit:n.limit!=null?n.limit*h+h:void 0},p=Vd(await this.fetchKlines(o,r,Sg[d],u)),m=Lg(p,c*6e4);return n.limit!=null&&m.length>n.limit?m.slice(-n.limit):m}catch(r){return console.warn(`[vela] Binance: failed to fetch ${e} ${t} \u2014 ${r instanceof Error?r.message:String(r)}`),[]}}async getSymbolInfo(e){let{apiSymbol:t,isFutures:n}=oa(e),r=n?ia:await this.spotBase(),i=n?`${r}/exchangeInfo`:`${r}/exchangeInfo?symbol=${t}`,a=(await this.json(i).catch(()=>null))?.symbols??[],l=n?a.find(h=>h.symbol===t):a[0];if(!l)return;let c=l.filters?.find(h=>h.filterType==="PRICE_FILTER"),d=c?parseFloat(c.tickSize??"0.01"):.01;return {ticker:e,tickerid:`BINANCE:${e}`,prefix:"BINANCE",description:`${l.baseAsset} / ${l.quoteAsset}${n?" Perpetual":""}`,type:n?"futures":"crypto",basecurrency:l.baseAsset,currency:l.quoteAsset,mintick:d,pricescale:Math.round(1/d),timezone:"Etc/UTC",session:"24x7"}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=Promise.all([this.listSpot().catch(()=>[]),this.listFutures().catch(()=>[])]).then(([e,t])=>[...e,...t])),this.symbolsPromise}subscribe(e,t,n){let{apiSymbol:r,isFutures:i}=oa(e),o=Od[Bd(t)];return o&&typeof WebSocket<"u"?this.streamKlines(e,t,r,i,o,n):this.pollBars(e,t,n)}streamKlines(e,t,n,r,i,o){let a=false,l=null,c=null,d=null,h=null,u=`${n.toLowerCase()}@kline_${i}`,p=()=>{d&&(clearTimeout(d),d=null);},m=()=>{if(!(a||h)){p(),c&&(clearTimeout(c),c=null);try{l?.close();}catch{}l=null,console.warn(`[vela] Binance: ${e} ${t} stream delivered no data; falling back to polling.`),h=this.pollBars(e,t,o);}},f=async()=>{if(a)return;let b=r?xg:await this.spotWsBase();a||(l=new WebSocket(`${b}/ws/${u}`),d=setTimeout(m,15e3),l.onmessage=g=>{if(!(a||h))try{let v=JSON.parse(typeof g.data=="string"?g.data:"");v.k&&(p(),o(Tg(v.k)));}catch{}},l.onclose=()=>{!a&&!h&&(c=setTimeout(()=>{f();},2e3));},l.onerror=()=>{try{l?.close();}catch{}});};return f(),()=>{a=true,p(),c&&clearTimeout(c),h?.();try{l?.close();}catch{}}}async spotWsBase(){return (await this.spotBase()).includes("binance.us")?yg:vg}pollBars(e,t,n){let r=false,i=null,o=async()=>{if(!r){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}r||(i=setTimeout(()=>{o();},3e3));}};return i=setTimeout(()=>{o();},3e3),()=>{r=true,i&&clearTimeout(i);}}async listSpot(){let e=await this.spotBase();return ((await this.json(`${e}/exchangeInfo`)).symbols??[]).filter(n=>n.status==="TRADING").map(n=>({ticker:n.symbol,description:`${n.baseAsset} / ${n.quoteAsset}`,type:"crypto"}))}async listFutures(){return ((await this.json(`${ia}/exchangeInfo`)).symbols??[]).filter(t=>t.contractType==="PERPETUAL"&&t.status==="TRADING").map(t=>({ticker:`${t.symbol}.P`,description:`${t.baseAsset} / ${t.quoteAsset} Perpetual`,type:"futures"}))}async fetchKlines(e,t,n,r){if(r.from!=null)return this.paginateForward(e,t,n,r.from,r.to??Date.now(),r.limit);let i=r.limit??500;return i>1e3?this.paginateBackward(e,t,n,i,r.to):this.klinesChunk(e,{symbol:t,interval:n,limit:i,endTime:r.to})}async paginateForward(e,t,n,r,i,o){let a=[],l=r;for(;l<i;){let c=await this.klinesChunk(e,{symbol:t,interval:n,limit:1e3,startTime:l,endTime:i});if(c.length===0||(a.push(...c),l=Number(c[c.length-1][6])+1,c.length<1e3)||o&&a.length>=o)break}return o?a.slice(0,o):a}async paginateBackward(e,t,n,r,i){let o=[],a=r,l=i,c=Math.ceil(r/1e3)+5;for(;a>0&&c-- >0;){let d=Math.min(a,1e3),h=await this.klinesChunk(e,{symbol:t,interval:n,limit:d,endTime:l});if(h.length===0||(o=h.concat(o),a-=h.length,l=Number(h[0][0])-1,h.length<d))break}return o}async klinesChunk(e,t){let n=new URL(`${e}/klines`);n.searchParams.set("symbol",t.symbol),n.searchParams.set("interval",t.interval),t.limit&&n.searchParams.set("limit",String(Math.min(t.limit,1e3))),t.startTime!=null&&n.searchParams.set("startTime",String(t.startTime)),t.endTime!=null&&n.searchParams.set("endTime",String(t.endTime));let r=await this.json(n.toString());return Array.isArray(r)?r.length>0&&!Array.isArray(r[0])?[]:r:[]}spotBase(){return this.spotBaseUrl?Promise.resolve(this.spotBaseUrl):(this.spotBaseProbe||(this.spotBaseProbe=(async()=>{try{for(let e of [Ad,gg])try{if((await fetch(`${e}/ping`,{signal:AbortSignal.timeout(5e3)})).ok)return this.spotBaseUrl=e}catch{}return Ad}finally{this.spotBaseProbe=null;}})()),this.spotBaseProbe)}async json(e){let t=await fetch(e);if(!t.ok)throw new Error(`Binance HTTP ${t.status} for ${e}`);return t.json()}};var Eg="https://api.hyperliquid.xyz/info",kg="wss://api.hyperliquid.xyz/ws";var _d={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h",D:"1d",W:"1w",M:"1M"},Nd={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},Ig=[1,3,5,15,30,60,120,240,480,720],Rg={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h"},Dg=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],Hd={D:864e5,W:6048e5,M:2592e6};function Ag(s){if(Hd[s])return Hd[s];let e=parseInt(s,10);return Number.isFinite(e)&&e>0?e*6e4:36e5}function zd(s){return Nd[s]??Nd[s.toLowerCase()]??s}function sa(s){let e=s.trim();return e.includes("/")?e:e.toUpperCase()}function aa(s){return {time:Number(s.t),open:Number(s.o),high:Number(s.h),low:Number(s.l),close:Number(s.c),volume:Number(s.v)}}function Og(s){let e=new Map;for(let t of s)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function Fg(s,e){let t=new Map;for(let n of s){let r=Math.floor(n.time/e)*e,i=t.get(r);i?(i.high=Math.max(i.high,n.high),i.low=Math.min(i.low,n.low),i.close=n.close,i.volume=(i.volume??0)+(n.volume??0)):t.set(r,{time:r,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,r)=>n.time-r.time)}function Bg(s){return Ig.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}var Lo=class{constructor(){this.metaPromise=null;this.spotMetaPromise=null;this.symbolsPromise=null;}info(){return {name:"hyperliquid",displayName:"Hyperliquid",requiresApiKey:false,supportedTimeframes:Dg,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let r=sa(e),i=zd(t),o=_d[i];if(o)return Og((await this.fetchCandles(r,o,Ag(i),n)).map(aa));let a=/^\d+$/.test(i)?parseInt(i,10):null,l=a!=null?Bg(a):null;if(a==null||l==null)return console.warn(`[vela] Hyperliquid: timeframe "${t}" is not supported and cannot be aggregated.`),[];let c=a/l,d={...n,limit:n.limit!=null?n.limit*c+c:void 0},h=(await this.fetchCandles(r,Rg[l],l*6e4,d)).map(aa),u=Fg(h,a*6e4);return n.limit!=null&&u.length>n.limit?u.slice(-n.limit):u}catch(r){return console.warn(`[vela] Hyperliquid: failed to fetch ${e} ${t} \u2014 ${r instanceof Error?r.message:String(r)}`),[]}}async getSymbolInfo(e){let t=sa(e),r=(await this.fetchMeta().catch(()=>null))?.universe?.find(i=>i.name===t);if(r){let i=Wd(Math.max(0,6-(r.szDecimals??2)));return $d(e,t,"USD","futures",`${t} / USD Perpetual`,i)}if(t.includes("/")){let i=await this.fetchSpotMeta().catch(()=>null),o=i?.universe?.find(h=>h.name===t),a=o&&i?.tokens?i.tokens[o.tokens?.[0]??-1]:void 0,[l=t,c="USDC"]=t.split("/"),d=Wd(Math.max(0,8-(a?.szDecimals??2)));return $d(e,l,c,"crypto",`${l} / ${c}`,d)}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=Promise.all([this.listPerps().catch(()=>[]),this.listSpot().catch(()=>[])]).then(([e,t])=>[...e,...t])),this.symbolsPromise}subscribe(e,t,n){let r=sa(e),i=_d[zd(t)];return i&&typeof WebSocket<"u"?this.streamCandles(e,t,r,i,n):this.pollBars(e,t,n)}async listPerps(){return ((await this.fetchMeta()).universe??[]).filter(t=>!t.isDelisted).map(t=>({ticker:t.name,description:`${t.name} / USD Perpetual`,type:"futures"}))}async listSpot(){let e=await this.fetchSpotMeta(),t=e.tokens??[],n=r=>r!=null?t[r]?.name??null:null;return (e.universe??[]).map(r=>{let i=n(r.tokens?.[0]),o=n(r.tokens?.[1]),a=i&&o?`${i} / ${o}`:r.name;return {ticker:r.name,description:a,type:"crypto"}})}async fetchCandles(e,t,n,r){let i=r.to??Date.now(),o=r.from!=null?r.from:i-((r.limit??500)+2)*n,a=await this.candleSnapshot(e,t,o,i);return r.from==null&&r.limit!=null&&a.length>r.limit?a.slice(-r.limit):a}async candleSnapshot(e,t,n,r){let i=await this.post({type:"candleSnapshot",req:{coin:e,interval:t,startTime:Math.floor(n),endTime:Math.floor(r)}});return Array.isArray(i)?i:[]}streamCandles(e,t,n,r,i){let o=false,a=null,l=null,c=null,d=null,h=null,u=()=>{d&&(clearTimeout(d),d=null);},p=()=>{l&&(clearInterval(l),l=null);},m=()=>{if(!(o||h)){u(),p(),c&&(clearTimeout(c),c=null);try{a?.close();}catch{}a=null,console.warn(`[vela] Hyperliquid: ${e} ${t} stream delivered no data; falling back to polling.`),h=this.pollBars(e,t,i);}},f=()=>{o||h||(a=new WebSocket(kg),d=setTimeout(m,15e3),a.onopen=()=>{try{a?.send(JSON.stringify({method:"subscribe",subscription:{type:"candle",coin:n,interval:r}}));}catch{}l=setInterval(()=>{try{a?.send(JSON.stringify({method:"ping"}));}catch{}},3e4);},a.onmessage=b=>{if(!(o||h))try{let g=JSON.parse(typeof b.data=="string"?b.data:"");g.channel==="candle"&&g.data&&g.data.s===n&&(u(),i(aa(g.data)));}catch{}},a.onclose=()=>{p(),!o&&!h&&(c=setTimeout(f,2e3));},a.onerror=()=>{try{a?.close();}catch{}});};return f(),()=>{o=true,u(),p(),c&&clearTimeout(c),h?.();try{a?.close();}catch{}}}pollBars(e,t,n){let r=false,i=null,o=async()=>{if(!r){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}r||(i=setTimeout(()=>{o();},3e3));}};return i=setTimeout(()=>{o();},3e3),()=>{r=true,i&&clearTimeout(i);}}fetchMeta(){return this.metaPromise??(this.metaPromise=this.post({type:"meta"}).then(e=>e))}fetchSpotMeta(){return this.spotMetaPromise??(this.spotMetaPromise=this.post({type:"spotMeta"}).then(e=>e))}async post(e){let t=await fetch(Eg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`Hyperliquid HTTP ${t.status}`);return t.json()}};function $d(s,e,t,n,r,i){return {ticker:s,tickerid:`HYPERLIQUID:${s}`,prefix:"HYPERLIQUID",description:r,type:n,basecurrency:e,currency:t,mintick:i,pricescale:Math.round(1/i),timezone:"Etc/UTC",session:"24x7"}}function Wd(s){return Math.pow(10,-s)}var Vg={now:()=>Date.now(),delay:s=>new Promise(e=>setTimeout(e,s))},Po=class{constructor(e,t,n=Vg){this.maxConcurrent=e;this.minIntervalMs=t;this.clock=n;this.active=0;this.waiters=[];this.nextStartAt=0;this.pausedUntil=0;}async run(e){await this.acquire();try{return await this.waitForTurn(),await e()}finally{this.release();}}pauseFor(e){e>0&&(this.pausedUntil=Math.max(this.pausedUntil,this.clock.now()+e));}async waitForTurn(){for(;;){let e=this.clock.now(),t=Math.max(this.pausedUntil-e,this.nextStartAt-e);if(t<=0)break;await this.clock.delay(t);}this.nextStartAt=Math.max(this.clock.now(),this.nextStartAt)+this.minIntervalMs;}acquire(){return this.active<this.maxConcurrent?(this.active+=1,Promise.resolve()):new Promise(e=>{this.waiters.push(()=>{this.active+=1,e();});})}release(){this.active-=1;let e=this.waiters.shift();e&&e();}};var la="https://api.exchange.coinbase.com",_g="wss://ws-feed.exchange.coinbase.com",Ng={Accept:"application/json"},Hg=15e3,zg=2e3,$g=5e3,Eo=300,Wg=4,Ug=120,Gg=4,Yg=600,Xg=400;function Kg(s,e){let t=Number(s.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t*1e3:e}var Ud={1:60,5:300,15:900,60:3600,360:21600,D:86400},Gd={"1m":"1","3m":"3","5m":"5","15m":"15","30m":"30","45m":"45","1h":"60","2h":"120","3h":"180","4h":"240","6h":"360","8h":"480","12h":"720","1d":"D","1w":"W","1mo":"M","1D":"D","1W":"W","4H":"240",D:"D",W:"W",M:"M"},jg=[1,5,15,60,360,1440],qg={1:60,5:300,15:900,60:3600,360:21600,1440:86400},Zg=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],ca=864e5;function Yd(s){return Gd[s]??Gd[s.toLowerCase()]??s}function da(s){return s.trim().toUpperCase()}function Jg(s){return {time:Number(s[0])*1e3,open:Number(s[3]),high:Number(s[2]),low:Number(s[1]),close:Number(s[4]),volume:Number(s[5])}}function ha(s){let e=new Map;for(let t of s)e.set(t.time,t);return [...e.values()].sort((t,n)=>t.time-n.time)}function Qg(s,e){return Xd(s,t=>Math.floor(t/e)*e)}function ev(s,e){return Xd(s,e==="W"?tv:nv)}function Xd(s,e){let t=new Map;for(let n of s){let r=e(n.time),i=t.get(r);i?(i.high=Math.max(i.high,n.high),i.low=Math.min(i.low,n.low),i.close=n.close,i.volume=(i.volume??0)+(n.volume??0)):t.set(r,{time:r,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume??0});}return [...t.values()].sort((n,r)=>n.time-r.time)}function tv(s){let e=new Date(s),t=(e.getUTCDay()+6)%7;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()-t)}function nv(s){let e=new Date(s);return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)}function rv(s){return jg.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}function ua(s,e){return e!=null&&s.length>e?s.slice(-e):s}var ko=class{constructor(){this.symbolsPromise=null;this.gate=new Po(Wg,Ug);}info(){return {name:"coinbase",displayName:"Coinbase",requiresApiKey:false,supportedTimeframes:Zg,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let r=da(e),i=Yd(t),o=Ud[i];if(o)return ha(await this.fetchCandles(r,o,n));if(i==="W"||i==="M"){let u=i==="W"?7*ca:31*ca,p=n.from!=null?n:{...n,limit:n.limit!=null?Math.ceil(n.limit*u/ca)+31:void 0},m=await this.fetchCandles(r,86400,p);return ua(ev(m,i),n.limit)}let a=/^\d+$/.test(i)?parseInt(i,10):null,l=a!=null?rv(a):null;if(a==null||l==null)return console.warn(`[vela] Coinbase: timeframe "${t}" is not supported and cannot be aggregated.`),[];let c=a/l,d={...n,limit:n.limit!=null?n.limit*c+c:void 0},h=await this.fetchCandles(r,qg[l],d);return ua(Qg(h,a*6e4),n.limit)}catch(r){return console.warn(`[vela] Coinbase: failed to fetch ${e} ${t} \u2014 ${r instanceof Error?r.message:String(r)}`),[]}}async getSymbolInfo(e){let t=da(e),n=await this.json(`${la}/products/${t}`).catch(()=>null);if(!n||!n.id)return;let r=n.quote_increment!=null?parseFloat(n.quote_increment):.01,i=r>0?r:.01;return {ticker:e,tickerid:`COINBASE:${e}`,prefix:"COINBASE",description:`${n.base_currency} / ${n.quote_currency}`,type:"crypto",basecurrency:n.base_currency,currency:n.quote_currency,mintick:i,pricescale:Math.round(1/i),timezone:"Etc/UTC",session:"24x7"}}listSymbols(){return this.symbolsPromise||(this.symbolsPromise=this.fetchProducts().then(e=>e.filter(t=>t.status==="online"&&!t.trading_disabled).map(t=>({ticker:t.id,description:`${t.base_currency} / ${t.quote_currency}`,type:"crypto"}))).catch(()=>[])),this.symbolsPromise}subscribe(e,t,n){let r=Ud[Yd(t)];return r&&typeof WebSocket<"u"?this.streamTicker(e,t,r,n):this.pollBars(e,t,n)}async fetchProducts(){let e=await this.json(`${la}/products`);return Array.isArray(e)?e:[]}async fetchCandles(e,t,n){return n.from!=null?this.paginateForward(e,t,n.from,n.to??Date.now(),n.limit):this.paginateBackward(e,t,n.limit??500,n.to??Date.now())}async paginateBackward(e,t,n,r){let i=t*1e3,o=[],a=n,l=r,c=Math.ceil(n/Eo)+4;for(;a>0&&c-- >0;){let d=Math.min(a,Eo),h=l-d*i,u=await this.candlesChunk(e,t,h,l);if(u.length===0||(o=u.concat(o),a-=u.length,l=u[0].time-1,u.length<d))break}return ua(ha(o),n)}async paginateForward(e,t,n,r,i){let o=t*1e3,a=[],l=n,c=Math.ceil((r-n)/(Eo*o))+4;for(;l<r&&c-- >0;){let h=Math.min(l+Eo*o,r),u=await this.candlesChunk(e,t,l,h);if(u.length>0&&a.push(...u),l=h,i!=null&&a.length>=i)break}let d=ha(a);return i!=null?d.slice(0,i):d}async candlesChunk(e,t,n,r){let i=new URL(`${la}/products/${e}/candles`);i.searchParams.set("granularity",String(t)),i.searchParams.set("start",String(Math.floor(n/1e3))),i.searchParams.set("end",String(Math.floor(r/1e3)));let o=await this.json(i.toString());return !Array.isArray(o)||o.length>0&&!Array.isArray(o[0])?[]:o.map(Jg).sort((a,l)=>a.time-l.time)}streamTicker(e,t,n,r){let i=da(e),o=n*1e3,a=C=>Math.floor(C/o)*o,l=false,c=null,d=null,h=null,u=null,p=null,m=null,f=()=>{h&&(clearTimeout(h),h=null);},b=()=>{u&&(clearInterval(u),u=null);},g=()=>{m&&r({...m});},v=async C=>{try{let T=await this.getBars(e,t,{limit:2});if(l||T.length===0)return;C&&T.length>=2&&r(T[T.length-2]);let M=T[T.length-1];m=m&&m.time===M.time?{...M,high:Math.max(M.high,m.high),low:Math.min(M.low,m.low),close:m.close}:{...M},g();}catch{}},y=(C,T)=>{let M=Number(C);if(!Number.isFinite(M))return;let E=a(T);!m||E>m.time?(m={time:E,open:M,high:M,low:M,close:M,volume:0},g(),v(false)):E===m.time&&(m={...m,close:M,high:Math.max(m.high,M),low:Math.min(m.low,M)},g());},x=()=>{if(!(l||p)){f(),b(),d&&(clearTimeout(d),d=null);try{c?.close();}catch{}c=null,console.warn(`[vela] Coinbase: ${e} ${t} stream delivered no data; falling back to polling.`),p=this.pollBars(e,t,r);}},S=()=>{l||p||(c=new WebSocket(_g),h=setTimeout(x,Hg),c.onopen=()=>{try{c?.send(JSON.stringify({type:"subscribe",product_ids:[i],channels:["ticker"]}));}catch{}v(false),u=setInterval(()=>{v(false);},$g);},c.onmessage=C=>{if(!(l||p))try{let T=JSON.parse(typeof C.data=="string"?C.data:"");T.type==="ticker"&&T.product_id===i&&T.price!=null&&(f(),y(T.price,T.time?Date.parse(T.time):Date.now()));}catch{}},c.onclose=()=>{b(),!l&&!p&&(d=setTimeout(S,zg));},c.onerror=()=>{try{c?.close();}catch{}});};return S(),()=>{l=true,f(),b(),d&&clearTimeout(d),p?.();try{c?.close();}catch{}}}pollBars(e,t,n){let r=false,i=null,o=async()=>{if(!r){try{let a=await this.getBars(e,t,{limit:2});for(let l of a)n(l);}catch{}r||(i=setTimeout(()=>{o();},3e3));}};return i=setTimeout(()=>{o();},3e3),()=>{r=true,i&&clearTimeout(i);}}async json(e){return (await this.request(e)).json()}async request(e){for(let t=0;;t+=1){let n=await this.gate.run(()=>fetch(e,{headers:Ng}));if(n.status===429&&t<Gg){let r=Yg*2**t+Math.random()*Xg;this.gate.pauseFor(Math.max(Kg(n,0),r));continue}if(!n.ok)throw new Error(`Coinbase HTTP ${n.status} for ${e}`);return n}}};
311
+ exports.ACCENT=ve;exports.ACCENT_BRIGHT=fr;exports.BEARISH=X;exports.BULLISH=q;exports.BarStore=Ai;exports.BinanceProvider=Mo;exports.CATEGORICAL=ga;exports.CROSSHAIR=xa;exports.CachingDataFeed=Vn;exports.CoinbaseProvider=ko;exports.DARK_THEME=Be;exports.DEFAULT_PANEL_MAX_WIDTH=Rd;exports.DEFAULT_PANEL_MIN_WIDTH=ra;exports.DEFAULT_PANEL_WIDTH=Id;exports.DataControl=_n;exports.Drawing=B;exports.DrawingStore=Yt;exports.DrawingToolbar=rr;exports.DrawingsControl=Nn;exports.HIGHLIGHT=va;exports.HyperliquidProvider=Lo;exports.INFO=_e;exports.INVALID=gr;exports.LIGHT_THEME=An;exports.MARKER=ya;exports.MultiProviderFeed=Pt;exports.NEUTRAL=he;exports.NativeRenderer=sr;exports.RendererControl=On;exports.SERIES_LINE=gn;exports.SESSION_OFF=fv;exports.SESSION_POST=mv;exports.SESSION_PRE=pv;exports.SLATE=vr;exports.SLATE_DEEP=wa;exports.TRADE_EXIT=Ta;exports.TRADE_LONG=Sa;exports.TRADE_SHORT=Ca;exports.TypedEventBus=ct;exports.VALID=br;exports.Vela=na;exports.WARNING=bn;exports.buildColorPicker=Jn;exports.buildToolbar=kn;exports.categoricalColor=bv;exports.chartType=Ue;exports.chartTypes=Ge;exports.clampPanelWidth=bg;exports.combineColor=vc;exports.createDrawing=rt;exports.defaultToolbar=En;exports.deserializeDrawing=Fe;exports.drawingTypes=Mi;exports.getDrawingType=nt;exports.getNativeIndicator=fn;exports.iconMarkup=La;exports.legendActions=ug;exports.nativeIndicatorDescriptors=pr;exports.nativeIndicatorTypes=ma;exports.normalizeSettingsRow=ki;exports.registerChartType=Wo;exports.registerDefaultEngine=pg;exports.registerDrawingType=A;exports.registerIcon=D;exports.registerLegendAction=dg;exports.registerNativeIndicator=_t;exports.registerRendererDefaults=Op;exports.registerRendererLayer=Sb;exports.registerSidePanel=ig;exports.registerWidgetAction=ag;exports.registerWidgetAttachment=tg;exports.rendererDefaults=Go;exports.rendererLayers=As;exports.resolveEngines=fg;exports.resolveTheme=Xt;exports.settingsRowValueKeys=Rn;exports.sharedBarStore=Fn;exports.sidePanels=sg;exports.splitColor=cn;exports.stableSeriesId=Dd;exports.tickerModifierIds=Uo;exports.timeframeToMs=In;exports.unregisterChartType=Lp;exports.unregisterDefaultEngine=mg;exports.unregisterLegendAction=hg;exports.unregisterNativeIndicator=pa;exports.unregisterRendererDefaults=Fp;exports.unregisterRendererLayer=Cb;exports.unregisterSidePanel=og;exports.unregisterWidgetAction=lg;exports.unregisterWidgetAttachment=ng;exports.widgetActions=cg;exports.widgetAttachments=rg;return exports;})({});