@luxalgo/vela 0.6.0 → 0.6.1
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.
- package/dist/{DataProvider-DNx9ntBD.d.ts → DataProvider-BNKtYU5V.d.cts} +13 -3
- package/dist/{DataProvider-Ce6PuCzQ.d.cts → DataProvider-gJjN_0eh.d.ts} +13 -3
- package/dist/{chunk-CA3N3PYT.js → chunk-4MQEG67Z.js} +16 -12
- package/dist/{chunk-7ROONW6H.js → chunk-6LZJRO2S.js} +35 -7
- package/dist/{contributions-Dlc7ZWZz.d.cts → contributions-D64UA74H.d.cts} +2 -2
- package/dist/{contributions-DToMhiw3.d.ts → contributions-lPAgo9Cu.d.ts} +2 -2
- package/dist/{history-BZADxpKx.d.cts → history-CVoFDJ2D.d.ts} +21 -3
- package/dist/{history-BuHXJZJ2.d.ts → history-fSMXVLt1.d.cts} +21 -3
- package/dist/index.cjs +16 -12
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/{options-BlQ00Fju.d.cts → options-BqGeFHtp.d.cts} +15 -1
- package/dist/{options-BlQ00Fju.d.ts → options-BqGeFHtp.d.ts} +15 -1
- package/dist/{plugin-BNPLOQO1.d.cts → plugin-D5ni4WEJ.d.cts} +3 -3
- package/dist/{plugin-BqjEa5r3.d.ts → plugin-o5HJH46Z.d.ts} +3 -3
- package/dist/plugin.d.cts +4 -4
- package/dist/plugin.d.ts +4 -4
- package/dist/providers/binance.d.cts +2 -2
- package/dist/providers/binance.d.ts +2 -2
- package/dist/providers/coinbase.d.cts +2 -2
- package/dist/providers/coinbase.d.ts +2 -2
- package/dist/providers/hyperliquid.d.cts +2 -2
- package/dist/providers/hyperliquid.d.ts +2 -2
- package/dist/ui.d.cts +1 -1
- package/dist/ui.d.ts +1 -1
- package/dist/vela.global.js +16 -12
- package/dist/vela.global.min.js +2 -2
- package/dist/widget.cjs +92 -19
- package/dist/widget.d.cts +18 -6
- package/dist/widget.d.ts +18 -6
- package/dist/widget.js +47 -6
- package/dist/workspace.cjs +94 -18
- package/dist/workspace.d.cts +20 -5
- package/dist/workspace.d.ts +20 -5
- package/dist/workspace.js +48 -4
- package/package.json +1 -1
package/dist/vela.global.min.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
var Vela=(function(exports){'use strict';function ae(s){return s.kind!=="candle"&&s.kind!=="bar"&&s.kind!=="markers"}var ft=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 Tr=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 Pn=new Map;function Yt(s){Pn.set(s.type,s);}function Aa(s){Pn.delete(s);}function Mn(s){return Pn.get(s)}function Oa(){return [...Pn.keys()]}function Pr(){return [...Pn.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 Xt=class{constructor(e,t,n,r){this.controller=n;this.schema=[];this.visibleState=true;this.bus=new ft;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 Ah(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(Ah),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 Oh={"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-Oh[s],{from:Math.max(t,r),to:n}}var xe="#2962ff",Kt="#38c0fd",q="#089981",X="#f23645",pe="#787b86",_a="#e0b400",Ln="#ff9800",ze="#5b9cf6",Na="#ff5d00",Lr="#0ecb81",Er="#f6465d",cy="#f97316",dy="#0ea5e9",hy="#9ca3af",En="#3b82f6",Ha="#9aa0ad",za="#1e293b",kr="#475569",$a=xe,Wa=X,Ua="#d500f9",Va=[xe,q,X,Ln,"#7e57c2","#26a69a",ze,"#e573b5"];function uy(s){let e=0;for(let t=0;t<s.length;t++)e=e*31+s.charCodeAt(t)>>>0;return Va[e%Va.length]}var D=Kt;function jo(){return {lineColor:D,lineWidth:2,lineStyle:"solid"}}function $e(s=""){return {value:s,size:"normal",hAlign:"left",vAlign:"top"}}var Ir=class Ir{constructor(e){this.locked=false;this.visible=true;this.zIndex=0;this.id=e.id??`dw-${Ir.seq+=1}`,this.paneId=e.paneId,this.anchors=(e.anchors??[]).map(t=>({time:t.time,price:t.price})),this.style=e.style?{...e.style}:jo(),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=$e()),Ga(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){}};Ir.seq=0;var B=Ir;function Ga(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 qo=new Map;function R(s,e){qo.set(s,e);}function Dr(s){return qo.get(s)??null}function $(s){return qo.get(s)??""}function re(s,e){return $(s).replace("<svg ",`<svg width="${e}" height="${e}" `)}function Ya(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 Zo(s){return `<svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" stroke="none">${s}</svg>`}var _=Ya;R("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"/>'));R("style-bars",_('<path d="M4.5 2.5v11M2.5 5h2M4.5 11h2"/><path d="M11.5 2.5v11M9.5 4.5h2M11.5 10.5h2"/>'));R("style-line",_('<path d="M1.5 11.5 5.5 7l3 2.5 5-6"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("clock",_('<circle cx="8" cy="8" r="6.2"/><path d="M8 4.8V8l2.4 1.6"/>'));R("calendar",_('<rect x="2.2" y="3.2" width="11.6" height="10.6" rx="1.4"/><path d="M5.2 1.8v2.8M10.8 1.8v2.8M2.2 6.8h11.6"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("search",_('<circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3.5 3.5"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("market-closed",I('<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>'));R("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"/>'));R("chevron-right",_('<path d="m6 3.5 4.5 4.5L6 12.5"/>'));R("chevron-left",_('<path d="M10 3.5 5.5 8l4.5 4.5"/>'));R("chevron-down",_('<path d="M3.5 6 8 10.5 12.5 6"/>'));R("chevron-up",_('<path d="M3.5 10 8 5.5 12.5 10"/>'));R("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"/>'));R("chevrons-left",_('<path d="M12 3.5 7.5 8l4.5 4.5"/><path d="M7.5 3.5 3 8l4.5 4.5"/>'));R("check",_('<path d="m2.8 8.4 3.4 3.4 7-7.6"/>'));R("close",_('<path d="m3.8 3.8 8.4 8.4M12.2 3.8l-8.4 8.4"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("arrow-up",_('<path d="M8 13.2V3M4.2 6.8 8 3l3.8 3.8"/>'));R("arrow-down",_('<path d="M8 2.8V13M4.2 9.2 8 13l3.8-3.8"/>'));R("move-vertical",_('<path d="M8 2.5v11M5 5.5 8 2.5l3 3M5 10.5l3 3 3-3"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("collapse",_('<path d="M3 8h10"/>'));R("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"/>'));R("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"/>'));R("restore",_('<path d="M6.2 2.5v3.7H2.5M9.8 13.5V9.8h3.7M13.5 6.2H9.8V2.5M2.5 9.8h3.7v3.7"/>'));R("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"/>'));R("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"'));R("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"'));R("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"'));R("burger",_('<path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("cursor",I('<path d="M5 3l6 16 2-6 6-2z"/>','fill="currentColor" stroke="none"'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("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"/>'));R("type",I('<path d="M5 6V4.5h14V6"/><path d="M12 4.5v15"/><path d="M9.5 19.5h5"/>'));R("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"'));R("italic",I('<path d="M15 5h-5M14 19H9M14.5 5 10 19"/>','stroke-width="2.2"'));R("price-delta",I('<path d="M12 4v16"/><path d="M8 8l4-4 4 4"/><path d="M8 16l4 4 4-4"/>'));R("date-delta",I('<path d="M4 12h16"/><path d="M8 8l-4 4 4 4"/><path d="M16 8l4 4-4 4"/>'));R("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"/>'));R("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"/>'));R("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>');R("bands",I('<path d="M3 6h18"/><path d="M3 18h18"/><path d="M3 12h18" stroke-dasharray="3 3"/>'));R("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"/>'));R("sonic",I('<circle cx="15" cy="12" r="4"/><circle cx="12" cy="12" r="2.5"/><path d="M8 5v14"/>'));R("supersonic",I('<circle cx="16" cy="12" r="3.5"/><path d="M6 12 15 6M6 12 15 18"/>'));var ge=[{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:ge,group:"line"}],Z=[{path:"style.fillColor",label:"Fill color",kind:"color",group:"fill"}],Le=[{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:Le,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 jt(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 he(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 Re(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 Jo(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 ne(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 Rr=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 Ar=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 Or=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]=ne(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 ot=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 Fr=class extends ot{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]=ne(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 Br=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 Vr=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 _r=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 Nr=class extends ot{constructor(){super(...arguments);this.type="infoline";}};var Hr=class extends ot{constructor(){super(...arguments);this.type="trendangle";}};var zr=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&&he(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 Fh={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},st=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=Fh[this.text?.size??"normal"]??14,i=this.labelText().split(`
|
|
2
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&&he(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 We=class extends st{constructor(t){super(t);this.type="text";this.text||(this.text={...$e(),size:"large"});}schema(){return {fields:[...F],textIsContent:true}}};var bt=class extends st{constructor(t){super(t);this.type="note";this.text||(this.text=$e("Note"));}defaultLabel(){return "Note"}schema(){return {fields:[...O,...Z,...F],textIsContent:true}}};var gt=class extends st{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 Bh={tiny:10,small:12,normal:14,large:18,huge:24,auto:14},Te=class extends B{constructor(e){super(e),this.text||(this.text=$e(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=Bh[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&&he(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 Ae=class extends Te{constructor(){super(...arguments);this.type="callout";}};var vt=class extends Te{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 yt=class extends Te{constructor(){super(...arguments);this.type="comment";}defaultLabel(){return "Comment"}};var xt=class extends Te{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&&Re(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 $r=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 Wr=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 Ur=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 Vh=2;function Xa(){return {midColor:pe,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:Vh*h,r2:Math.max(0,Math.min(1,p*p)),n:e}}var Ue=class extends B{constructor(t){super(t);this.type="regressionchannel";this.cachedRange=null;this.reg||(this.reg=Xa());}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 Re(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={...Xa(),...t};}};var ja=`${ze}00`;function qa(){return {midColor:ze,midStyle:"solid",multiplier:1,upperColor:ja,upperStyle:"solid",lowerColor:ja,lowerStyle:"solid",bandFill:`${ze}33`}}function Za(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 wt=class extends B{constructor(t){super(t);this.type="anchoredvwap";this.cachedRange=null;this.cachedExtent=null;this.vwap||(this.vwap=qa());}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=Za(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?Re(t,n,this.bandPolygon(o))?true:Qo(t,n,o.mid,i)||Qo(t,n,o.upper,i)||Qo(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={...qa(),...t};}};function Qo(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 _h=`${q}66`,Nh=`${X}66`,Hh=`${q}BF`,zh=`${X}BF`;function Ja(){return {rows:24,valueAreaPct:70,widthPct:35,anchor:"left",upColor:_h,downColor:Nh,vaUpColor:Hh,vaDownColor:zh,showVah:true,vahColor:pe,vahStyle:"solid",showVal:true,valColor:pe,valStyle:"solid",showPoc:true,pocColor:void 0,pocStyle:"solid",showDevelopingPoc:false,developingPocColor:xe,developingPocStyle:"dotted",showDevelopingVa:false,developingVaColor:xe,developingVaStyle:"dotted"}}function $h(s,e){return s<0?0:s>=e?e-1:s}function Qa(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 el(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($h(Math.floor((l-e)/t),i));for(let l of a)s[l][o]+=r;}function tl(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 nl(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)el(a,n,o,p);let l=tl(a);if(!l)return null;let{poc:c,maxTotal:d}=l,{vaFrom:h,vaTo:u}=Qa(a,c,t);return {rows:a,rowH:o,min:n,maxTotal:d,poc:c,vaFrom:h,vaTo:u}}function rl(s,e,t,n){let r=nl(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){el(l,i,o,u);let p=tl(l);if(!p)continue;let{poc:m}=p,{vaFrom:f,vaTo:b}=Qa(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 Oe=class extends B{constructor(t){super(t);this.type="fixedrangevp";this.cachedRange=null;this.frvp||(this.frvp=Ja());}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=rl(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,w=C=>{let T=[];for(let P of C){let E=g(P.price);E!=null&&T.push([t.xOf(P.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:w(i.developingPoc),developingVaHigh:w(i.developingVaHigh),developingVaLow:w(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(Re(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:ge,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:ge,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:ge,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:ge,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:ge,group:"line"}]}}writeProps(){return {...this.frvp}}readProps(t){this.frvp={...Ja(),...t};}};var Gr=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:[ne(a[0],a[1],d,h,"right",m,f),ne(l[0],l[1],l[0]+u,l[1]+p,"right",m,f),ne(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 qt=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:[ne(o[0],o[1],c,d,"right",p,m),ne(a[0],a[1],a[0]+h,a[1]+u,"right",p,m),ne(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 Yr=class extends qt{constructor(){super(...arguments);this.type="schiffpitchfork";}medianStart(t,n){return {time:t.time,price:(t.price+n.price)/2}}};var Xr=class extends qt{constructor(){super(...arguments);this.type="modifiedschiffpitchfork";}medianStart(t,n){return {time:(t.time+n.time)/2,price:(t.price+n.price)/2}}};var Kr=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:[ne(h,u,h+p,u+m,"right",f,b),ne(c[0],c[1],c[0]+p,c[1]+m,"right",f,b),ne(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 jr=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 il=48,qr=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<=il;r+=1){let i=r/il*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:jt(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 Zr=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 Wh=512,at=class extends J{anchorSchema(){return {min:2,max:Wh,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 Jr=class extends at{constructor(){super(...arguments);this.type="polyline";}};var kn=class extends at{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}}},Qr=class extends kn{constructor(){super(...arguments);this.type="freehand";}};var Uh=[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Width",kind:"number",min:4,max:60,step:1,group:"line"}],ei=class extends kn{constructor(){super(...arguments);this.type="highlighter";}schema(){return {fields:Uh}}};var ti=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 ni=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 ri=class extends at{constructor(){super(...arguments);this.type="path";}};var ol=40,ii=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<=ol;v+=1){let y=v/ol*Math.PI,x=Math.cos(y),w=Math.sin(y);b.push([a+x*c+w*f*u,l+x*d+w*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 sl=40,oi=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<=sl;l+=1){let c=l/sl,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 Gh={head:11,headW:9,stemW:3.5,len:22},St=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}=Gh,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&&Re(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]}}},In=class extends St{constructor(){super(...arguments);this.type="arrowmarkup";}dir(){return "up"}},Dn=class extends St{constructor(){super(...arguments);this.type="arrowmarkdown";}dir(){return "down"}};var On=["\u2605","\u2606","\u25CF","\u25C6","\u25B2","\u25BC","\u27A4","\u2691","\u271A","\u2715","\u2764","\u2666"],si=["small","normal","large","huge"],al={small:16,normal:22,large:32,huge:44},Ct=class extends B{constructor(e){super(e),this.glyph||(this.glyph=this.defaultGlyph()),this.size||(this.size="normal");}sizePx(){return al[this.size]??al.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:On.map(e=>({value:e,label:e})),group:"line"},{path:"size",label:"Size",kind:"select",options:si.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);}},Rn=class extends Ct{constructor(){super(...arguments);this.type="flagmark";}defaultGlyph(){return "\u2691"}},An=class extends Ct{constructor(){super(...arguments);this.type="iconstamp";}defaultGlyph(){return "\u2605"}};var ll=s=>s==="small"||s==="normal"||s==="large"||s==="huge";function Yh(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(Yh).filter(n=>n!=null);t.length&&(this.levels=t);}ll(e.numbersSize)&&(this.numbersSize=e.numbersSize),ll(e.labelsSize)&&(this.labelsSize=e.labelsSize);}};var Zt=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 Tt=pe,Fe=X,Be=Ln,Pt="#4caf50",lt=q,Ge=ze,Mt="#9c27b0",Xh="#e91e63",es="#26a69a",Kh="#ab47bc",jh="#ef5350",cl="#ffb74d",qh="#38c0fd",ai="#b2b5be",Jt=[qh,Ge,lt,Pt,Be,Fe,Xh,Mt,Tt,es,Kh,jh];function dl(s){return Jt[(s%Jt.length+Jt.length)%Jt.length]}var Zh=[[0,Tt],[.125,Fe],[.236,Fe],[.25,Fe],[.382,Be],[.5,Pt],[.618,lt],[.75,Ge],[.786,Ge],[1,Tt],[1.272,Ge],[1.382,Be],[1.618,Fe],[2,Tt],[2.382,Be],[2.618,Be],[3,Tt],[4.236,Pt],[6.854,lt],[11.09,Ge]];function Jh(s,e=0){return Zh.find(([t])=>t===s)?.[1]??dl(e)}function Q(s){return s.map((e,t)=>{let n=typeof e=="number"?{ratio:e}:e;return {ratio:n.ratio,color:n.color??Jh(n.ratio,t),enabled:n.enabled!==false,...n.label?{label:n.label}:{}}})}function hl(s,e=s){return Array.from({length:s},(t,n)=>({ratio:n+1,color:dl(n),enabled:n<e,label:String(n+1)}))}var Qh=Q([0,.236,.382,.5,.618,.786,1]),li=class extends Zt{constructor(){super(...arguments);this.type="fibretracement";}defaultLevels(){return Qh}};var eu=Q([0,.382,.618,1,1.272,1.618,{ratio:2.618,color:Mt}]),ci=class extends Zt{constructor(){super(...arguments);this.type="fibextension";}defaultLevels(){return eu}};var tu=Q([0,.382,.5,.618,1,1.618,{ratio:2.618,color:Mt}]),di=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 tu}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 nu=Q([.236,.382,.5,.618,.786,1]),hi=class extends ee{constructor(){super(...arguments);this.type="fibfan";}defaultLevels(){return nu}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]=ne(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 ru=[0,1,2,3,5,8,13,21,34].map(s=>({ratio:s,color:D,enabled:true})),ui=class extends ee{constructor(){super(...arguments);this.type="fibtimezones";}defaultLevels(){return ru}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 iu=Q([0,.236,.382,.5,.618,.786,1,1.618,2.618]),pi=class extends ee{constructor(){super(...arguments);this.type="fibchannel";}defaultLevels(){return iu}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 ou=Q([0,.236,.382,.5,.618,.786,1]),mi=class extends ee{constructor(){super(...arguments);this.type="fibspeedfan";}defaultLevels(){return ou}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=ne(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,w=ne(a,i,y,x,h,u,p);m.push({color:f.color,label:f.label,x1:w[0],y1:w[1],x2:w[2],y2:w[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 su=Q([0,.382,{ratio:.5,enabled:false},.618,1,1.382,1.618,2,2.382,2.618,3]),fi=class extends ee{constructor(){super(...arguments);this.type="trendfibtime";}defaultLevels(){return su}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 au(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 Ee=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(au(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 lu=Q([.236,.382,.5,.618,.786,1,1.618,2.618]),bi=class extends Ee{constructor(){super(...arguments);this.type="fibcircles";}defaultLevels(){return lu}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 cu=Q([.236,.382,.5,.618,.786,1,1.618,2.618]),gi=class extends Ee{constructor(){super(...arguments);this.type="fibarcs";}defaultLevels(){return cu}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 du=Q([.236,.382,.5,.618,.786,1]),vi=class extends Ee{constructor(){super(...arguments);this.type="fibwedge";}defaultLevels(){return du}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 hu=1.6180339887,ul=Math.log(hu)/(Math.PI/2),uu=Math.PI/64,pu=Math.PI,mu=.5,Lt=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(mu/c)/ul,-8*Math.PI*2),u=[];for(let p=h;p<=pu;p+=uu){let m=c*Math.exp(ul*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&&jt(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 fu=Q([{ratio:.125,color:Fe,label:"1/8"},{ratio:.25,color:Be,label:"1/4"},{ratio:.333,color:cl,label:"1/3"},{ratio:.5,color:Pt,label:"1/2"},{ratio:1,color:ai,label:"1/1"},{ratio:2,color:lt,label:"2/1"},{ratio:3,color:Ge,label:"3/1"},{ratio:4,color:es,label:"4/1"},{ratio:8,color:Mt,label:"8/1"}]),yi=class extends ee{constructor(){super(...arguments);this.type="gannfan";}defaultLevels(){return fu}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]=ne(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 bu=Q([0,.25,.382,.5,.618,.75,1].map(s=>({ratio:s,label:String(s)}))),xi=class extends ee{constructor(){super(...arguments);this.type="gannbox";}defaultLevels(){return bu}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??Tt;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&&he(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 gu=Q([0,.25,.382,.5,.618,.75,1].map(s=>({ratio:s,label:String(s)}))),vu=[{label:"3x1",x:3,y:1,color:Fe},{label:"2x1",x:2,y:1,color:Be},{label:"1x1",x:1,y:1,color:ai},{label:"1x2",x:1,y:2,color:lt},{label:"1x3",x:1,y:3,color:Ge}],ts=[{k:.25,color:Fe},{k:.5,color:Be},{k:.75,color:Pt},{k:1,color:lt}],Et=class extends ee{constructor(){super(...arguments);this.type="gannsquare";}defaultLevels(){return gu}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 vu){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&&he(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 ns=[4,8,12,16,24,32,48,64],yu=24,xu=.75;function pl(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 ml(s){let e=[];for(let t=0;t<s;t+=1)pl(t,s)&&e.push(t);return e}var kt=class extends B{constructor(t){super(t);this.type="dedekind";this.maxCurvature===void 0&&(this.maxCurvature=yu);}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<xu)continue;let x=ml(g);if(x.length===0)continue;let w=Math.floor(h)-1,C=Math.ceil(u)+1;for(let T=w;T<=C;T+=1)for(let P of x){let E=P/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&&he(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 rs=[3,4,5,6,8,10,12],is=[1.5,2,2.5,3,4,5],wi=6,wu=2;function os(s=wi){return [...hl(Jt.length,s)]}function Su(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 Qt={path:"showRatios",label:"Show ratios",kind:"boolean",group:"behavior"},we=class extends B{constructor(e){super(e),this.waveCount===void 0&&(this.waveCount=wi),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,w=[];if(f<=1+1e-9){let C=-u,T=h;w.push([g-C*x,v-T*x,g+C*x,v+T*x]);}else {let C=Math.asin(1/f),T=Math.cos(C),P=Math.sin(C),E=(G,S,H)=>[G*T-S*H*P,G*H*P+S*T],[k,M]=E(h,u,1),[L,V]=E(h,u,-1);w.push([g,v,g+k*x,v+M*x]),w.push([g,v,g+L*x,v+V*x]);}return {c0x:l,c0y:c,R:d,fx:h,fy:u,noseX:g,noseY:v,circles:b,rays:w}}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"},Qt,...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(Su).filter(n=>n!=null);t.length&&(this.levels=t);}}},Fn=class extends we{constructor(){super(...arguments);this.type="sonic";}defaultLevels(){return os(wi)}machNumber(){return 1}},Bn=class extends we{constructor(t){super(t);this.type="supersonic";this.mach===void 0&&(this.mach=wu);}defaultLevels(){return os(wi)}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"},Qt,...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 fl=Q([.236,.382,.5,.618,.786,1,1.618,2.618,4.236,6.854,11.09]),Cu=2,Si=class extends we{constructor(){super(...arguments);this.type="goldensonic";}shouldSyncWaveCount(){return false}defaultLevels(){return fl}machNumber(){return 1}schema(){return {fields:[...O,Qt,...F]}}},Ci=class extends we{constructor(t){super(t);this.type="goldensupersonic";this.mach===void 0&&(this.mach=Cu);}shouldSyncWaveCount(){return false}defaultLevels(){return fl}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"},Qt,...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 se=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&&jt(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 Ti=class extends se{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 se{constructor(){super(...arguments);this.type="abcd";}vertexLabels(){return ["A","B","C","D"]}legRatios(){return true}};var Mi=class extends se{constructor(){super(...arguments);this.type="elliottimpulse";}vertexLabels(){return ["1","2","3","4","5"]}};var Li=class extends se{constructor(){super(...arguments);this.type="elliottcorrection";}vertexLabels(){return ["A","B","C"]}};var Ei=class extends se{constructor(){super(...arguments);this.type="headshoulders";}vertexLabels(){return ["","LS","","H","","RS",""]}necklineIndices(){return [2,4]}};var ve=class extends se{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 ki=class extends ve{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 Ii=class extends ve{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 Di=class extends ve{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 Ri=class extends ve{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 Ai=class extends ve{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 Tu={min:1.272,max:1.414},Pu={min:.74,max:.83},Oi=class extends ve{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(),Tu)&&this.inBand(this.cdOverXc(),Pu)}};function bl(s){return `${s>=0?"+":""}${s.toFixed(2)}`}function Vn(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 It=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 `${bl(n)} (${bl(r)}%)`}timeLabel(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return "";let r=Vn(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&&he(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:Le,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 Fi=class extends It{constructor(){super(...arguments);this.type="datepricerange";}};var Bi=[{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 $${Mu(this.dollarLoss())} \xB7 Size ${Lu(this.positionSize())}`}targetLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${gl(t.target)}`:"";return `Target +${this.rewardPct().toFixed(2)}%${n}`}stopLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${gl(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 vl(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 he(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:Bi,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:Le,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=Lr,ie.DEFAULT_LOSS_COLOR=Er;var Ve=ie;function Mu(s){if(!Number.isFinite(s))return "0";let e=Math.round(s*100)/100;return Number.isInteger(e)?String(e):e.toFixed(2)}function Lu(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 gl(s){return Number.isFinite(s)?Math.abs(s)>=1?s.toFixed(2):s.toPrecision(4).replace(/\.?0+$/,""):"0"}function vl(s){return Math.round(s*1e8)/1e8}var _n=new Map;function A(s){_n.set(s.type,s);}function ct(s){return _n.get(s)}function Vi(){return [..._n.values()]}function dt(s,e){let t=_n.get(s);if(!t)return null;let n={...t.defaultStyle,...e.style??{}};return t.create({...e,style:n})}function ss(s){let e=dt(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 _e(s){let e=_n.get(s.type);return e?e.create(s):null}var Eu=I('<line x1="4" y1="19" x2="20" y2="5"/>'),ku=I('<line x1="3" y1="12" x2="21" y2="12"/>');A({type:"trendline",group:"lines",label:"Trend Line",icon:Eu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Rr(s)});A({type:"hline",group:"lines",label:"Horizontal Line",icon:ku,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"dashed"},create:s=>new Ar(s)});var Iu=I('<line x1="3" y1="20" x2="21" y2="6"/><circle cx="3" cy="20" r="1.6" fill="currentColor"/>'),Du=I('<rect x="4" y="6" width="16" height="12" rx="1"/>'),Ru=I('<path d="M5 6h14M12 6v13"/>');A({type:"ray",group:"lines",label:"Ray",icon:Iu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Or(s)});var Au=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"/>'),Ou=I('<line x1="12" y1="3" x2="12" y2="21"/>'),Fu=I('<line x1="5" y1="12" x2="21" y2="12"/><circle cx="5" cy="12" r="1.6" fill="currentColor"/>'),Bu=I('<line x1="3" y1="12" x2="21" y2="12"/><line x1="12" y1="3" x2="12" y2="21"/>'),Vu=I('<path d="M4 20 20 4"/><rect x="9" y="9" width="9" height="6" rx="1"/>'),_u=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:Au,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Fr(s)});A({type:"vline",group:"lines",label:"Vertical Line",icon:Ou,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Br(s)});A({type:"hray",group:"lines",label:"Horizontal Ray",icon:Fu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Vr(s)});A({type:"crossline",group:"lines",label:"Cross Line",icon:Bu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new _r(s)});A({type:"infoline",group:"lines",label:"Info Line",icon:Vu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Nr(s)});A({type:"trendangle",group:"lines",label:"Trend Angle",icon:_u,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Hr(s)});A({type:"box",group:"shapes",label:"Rectangle",icon:Du,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}26`},create:s=>new zr(s)});A({type:"text",group:"annotations",label:"Text",icon:Ru,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new We(s)});var Nu=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:Nu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new Ae(s)});var Hu=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"/>'),zu=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"/>'),$u=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"/>'),Wu=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"/>'),Uu=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:Hu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new bt(s)});A({type:"pricenote",group:"annotations",label:"Price Note",icon:zu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new vt(s)});A({type:"comment",group:"annotations",label:"Comment",icon:$u,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new yt(s)});A({type:"pricelabel",group:"annotations",label:"Price Label",icon:Wu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new gt(s)});A({type:"signpost",group:"annotations",label:"Signpost",icon:Uu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new xt(s)});var Gu=I('<line x1="3" y1="16" x2="21" y2="8"/><line x1="3" y1="21" x2="21" y2="13"/>'),Yu=I('<line x1="3" y1="7" x2="21" y2="10"/><line x1="3" y1="18" x2="21" y2="14"/>'),Xu=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:Gu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new $r(s)});A({type:"disjointchannel",group:"channels",label:"Disjoint Channel",icon:Yu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new Wr(s)});var Ku=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:Ku,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new Ur(s)});var ju=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:ju,defaultStyle:{lineColor:pe,lineWidth:1,lineStyle:"solid"},create:s=>new Ue(s)});A({type:"pitchfork",group:"pitchforks",label:"Pitchfork",icon:Xu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Gr(s)});var qu=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"/>'),Zu=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"/>'),Ju=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:qu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Yr(s)});A({type:"modifiedschiffpitchfork",group:"pitchforks",label:"Modified Schiff Pitchfork",icon:Zu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Xr(s)});A({type:"insidepitchfork",group:"pitchforks",label:"Inside Pitchfork",icon:Ju,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Kr(s)});var Qu=I('<path d="M7 7h10v10"/><path d="M7 17 17 7"/>'),ep=I('<ellipse cx="12" cy="12" rx="9" ry="6"/>'),tp=I('<path d="M12 4 20 19 4 19Z"/>');A({type:"arrow",group:"shapes",label:"Arrow",icon:Qu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",arrowRight:true},create:s=>new jr(s)});A({type:"ellipse",group:"shapes",label:"Ellipse",icon:ep,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new qr(s)});A({type:"triangle",group:"shapes",label:"Triangle",icon:tp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new Zr(s)});var np=I('<polyline points="3 17 9 10 13 14 21 5"/>'),rp=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"/>'),ip=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:np,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Jr(s)});A({type:"freehand",group:"shapes",label:"Brush",icon:rp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Qr(s)});A({type:"highlighter",group:"shapes",label:"Highlighter",icon:ip,defaultStyle:{lineColor:`${Na}59`,lineWidth:14,lineStyle:"solid"},create:s=>new ei(s)});var op=I('<circle cx="12" cy="12" r="8"/>'),sp=I('<path d="M5 14 9.5 5 19 10 14.5 19 Z"/>'),ap=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"/>'),lp=I('<path d="M4 17a8 8 0 0 1 16 0"/><path d="M4 17 20 17"/>'),cp=I('<path d="M4 18Q12 1 20 14"/>'),dp=I('<path d="M12 5 12 19"/><path d="M6 11 12 5 18 11"/>'),hp=I('<path d="M12 5 12 19"/><path d="M6 13 12 19 18 13"/>');A({type:"circle",group:"shapes",label:"Circle",icon:op,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new ti(s)});A({type:"rotatedrect",group:"shapes",label:"Rotated Rectangle",icon:sp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}26`},create:s=>new ni(s)});A({type:"path",group:"shapes",label:"Path",icon:ap,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new ri(s)});A({type:"arc",group:"shapes",label:"Arc",icon:lp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}26`},create:s=>new ii(s)});A({type:"curve",group:"shapes",label:"Curve",icon:cp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new oi(s)});A({type:"arrowmarkup",group:"shapes",label:"Arrow Mark Up",icon:dp,defaultStyle:{lineColor:q,lineWidth:1,lineStyle:"solid"},create:s=>new In(s)});A({type:"arrowmarkdown",group:"shapes",label:"Arrow Mark Down",icon:hp,defaultStyle:{lineColor:X,lineWidth:1,lineStyle:"solid"},create:s=>new Dn(s)});var up=I('<path d="M6 21V4"/><path d="M6 5h11l-2.5 3.5L17 12H6" fill="currentColor" stroke="none"/>'),pp=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:up,defaultStyle:{lineColor:xe,lineWidth:1,lineStyle:"solid"},create:s=>new Rn(s)});A({type:"iconstamp",group:"stamps",label:"Icon",icon:pp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new An(s)});var mp=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"/>'),fp=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:mp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new li(s)});A({type:"fibextension",group:"fibonacci",label:"Fib Extension",icon:fp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new ci(s)});var bp=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:bp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new di(s)});var gp=I('<path d="M4 20 20 5M4 20 21 11M4 20 21 17M4 20 20 20"/>'),vp=I('<path d="M3 5v14M6 5v14M11 5v14M19 5v14"/>');A({type:"fibfan",group:"fibonacci",label:"Fib Fan",icon:gp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new hi(s)});A({type:"fibtimezones",group:"fibonacci",label:"Fib Time Zones",icon:vp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"dashed"},create:s=>new ui(s)});var yp=I('<path d="M3 18 18 9M5 21 20 12M6 13 21 4"/>'),xp=I('<path d="M4 4 20 20M4 4 20 12M4 4 12 20M4 4 20 4M4 4 4 20"/>'),wp=I('<path d="M3 19 9 8M9 8 12 5v14M14 5v14M18 5v14M21 5v14"/>');A({type:"fibchannel",group:"fibonacci",label:"Fib Channel",icon:yp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new pi(s)});A({type:"fibspeedfan",group:"fibonacci",label:"Fib Speed Resistance Fan",icon:xp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new mi(s)});A({type:"trendfibtime",group:"fibonacci",label:"Trend-Based Fib Time",icon:wp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"dashed"},create:s=>new fi(s)});var Sp=I('<circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="10"/>'),Cp=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"/>'),Tp=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"/>'),Pp=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:Sp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new bi(s)});A({type:"fibarcs",group:"fibonacci",label:"Fib Speed Resistance Arcs",icon:Cp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new gi(s)});A({type:"fibwedge",group:"fibonacci",label:"Fib Wedge",icon:Tp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new vi(s)});A({type:"fibspiral",group:"fibonacci",label:"Fib Spiral",icon:Pp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Lt(s)});var Mp=I('<path d="M4 20 20 20M4 20 20 13M4 20 20 6M4 20 15 4M4 20 9 4M4 20 4 4"/>'),Lp=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:Mp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new yi(s)});A({type:"gannbox",group:"fibonacci",label:"Gann Box",icon:Lp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new xi(s)});var Ep=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:Ep,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Et(s)});var kp=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:kp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new kt(s)});var Ip=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"/>'),Dp=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:Ip,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Fn(s)});A({type:"supersonic",group:"geometry",label:"Supersonic",icon:Dp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Bn(s)});var Rp=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"/>'),Ap=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:Rp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Si(s)});A({type:"goldensupersonic",group:"geometry",label:"Golden Supersonic",icon:Ap,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Ci(s)});var Op=I('<path d="M3 18 7 8 11 14 15 6 20 16"/>'),Fp=I('<path d="M4 17 9 7 14 15 20 5"/>'),Bp=I('<path d="M3 19 8 9 12 13 17 5 21 9"/>'),Vp=I('<path d="M4 7 11 16 20 9"/>'),_p=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:Op,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Ti(s)});A({type:"abcd",group:"patterns",label:"ABCD Pattern",icon:Fp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Pi(s)});A({type:"elliottimpulse",group:"patterns",label:"Elliott Impulse Wave (1-5)",icon:Bp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Mi(s)});A({type:"elliottcorrection",group:"patterns",label:"Elliott Correction Wave (ABC)",icon:Vp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Li(s)});A({type:"headshoulders",group:"patterns",label:"Head & Shoulders",icon:_p,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Ei(s)});var Np=I('<path d="M3 17 7 6 12 14 17 5 21 16"/><path d="M3 17 21 16" opacity="0.45"/>'),en={group:"patterns",icon:Np,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"}};A({type:"gartley",label:"Gartley",...en,create:s=>new ki(s)});A({type:"bat",label:"Bat",...en,create:s=>new Ii(s)});A({type:"butterfly",label:"Butterfly",...en,create:s=>new Di(s)});A({type:"crab",label:"Crab",...en,create:s=>new Ri(s)});A({type:"shark",label:"Shark",...en,create:s=>new Ai(s)});A({type:"cypher",label:"Cypher",...en,create:s=>new Oi(s)});var Hp=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:Hp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Fi(s)});var zp=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:zp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Ve(s)});var $p=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:$p,defaultStyle:{lineColor:ze,lineWidth:2,lineStyle:"solid"},create:s=>new wt(s)});var Wp=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:Wp,defaultStyle:{lineColor:q,lineWidth:1,lineStyle:"solid"},create:s=>new Oe(s)});var Up=["fibretracement","fibextension","fibextensiontrend","fibfan","fibtimezones","fibchannel","fibspeedfan","trendfibtime","fibcircles","fibarcs","fibwedge","fibspiral"],Gp=["gannfan","gannbox","gannsquare"],Yp=["dedekind","sonic","supersonic","goldensonic","goldensupersonic"],Xp=["xabcd","abcd","headshoulders"],Kp=["elliottimpulse","elliottcorrection"],jp=["gartley","bat","butterfly","crab","shark","cypher"],qp=["position","datepricerange"],Zp=["anchoredvwap","fixedrangevp"],Jp=["freehand","highlighter"],Qp=["arrow","arrowmarkup","arrowmarkdown"],em=["box","ellipse","triangle","polyline","circle","rotatedrect","path","arc","curve"],tm=["text","callout","note","pricenote","comment","pricelabel","signpost"],nm=["flagmark","iconstamp"],rm=[{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:Up},{label:"Gann",types:Gp},{label:"Geometry",types:Yp}]},{id:"patterns-waves-harmonics",label:"Patterns",sections:[{label:"Patterns",types:Xp},{label:"Elliott Waves",types:Kp},{label:"Harmonics",types:jp}]},{id:"measurements",label:"Measurements",sections:[{label:"Measurements",types:qp},{label:"Volume",types:Zp}]},{id:"brushes-arrows-shapes",label:"Shapes",sections:[{label:"Brushes",types:Jp},{label:"Arrows",types:Qp},{label:"Shapes",types:em}]},{id:"text",label:"Text",sections:[{label:"Text",types:tm}]},{id:"icons",label:"Icons",sections:[{label:"Icons",types:nm}]}];function im(s){let e=ct(s);return e?{type:e.type,label:e.label,icon:e.icon}:null}function om(s){let e=new Map;for(let t of Vi()){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 sm(s,e,t){return "registryGroup"in s?e.get(s.registryGroup)??[]:s.types.map(n=>t.get(n)).filter(n=>n!=null)}function yl(s){let e=om(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 rm){let i=[],o=[];for(let a of r.sections){let l=sm(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 am(s){let e=new Set;for(let t of s)ct(t)&&e.add(t);return yl(e)}function lm(s){let e=[];for(let t of s){let n=t.tools.map(im).filter(r=>r!=null);n.length>0&&e.push({id:t.id,label:t.label,tools:n});}return {groups:e}}function Nn(){return yl()}function Hn(s){if(s===false)return {definition:Nn(),visible:false};if(s===void 0||s===true)return {definition:Nn(),visible:true};let e=s.toolbar??true;return s.groups?{definition:lm(s.groups),visible:e}:s.tools?{definition:am(s.tools),visible:e}:{definition:Nn(),visible:e}}function Dt(s){let e=globalThis.structuredClone;return e?e(s):JSON.parse(JSON.stringify(s))}function cm(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 xl(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(cm)}}var tn=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=xl(e);this.byId.clear(),this.seq=0,this.zCounter=1;for(let n of t.drawings){let r=_e(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 _i=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=Dt(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(Dt(e));}undo(e){let t=this.undoStack.pop();return t?(this.redoStack.push(Dt(e)),t):null}redo(e){let t=this.redoStack.pop();return t?(this.undoStack.push(Dt(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 Ni=class{constructor(e,t,n){this.events=t;this.store=new tn;this.history=new _i;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}=Hn(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){ct(e)&&t!==this.favs.has(e)&&(t?this.favs.add(e):this.favs.delete(e),this.pushFavorites());}setFavorites(e){let t=e.filter(n=>ct(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(Hn(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=dt(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=>Dt(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=_e({...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=_e({...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 wl={D:864e5,W:6048e5,M:2592e6};function zn(s){let e=s.trim();if(wl[e])return wl[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 Ye=s=>s.trim().toLowerCase(),Rt=s=>s.trim().toUpperCase();function Xe(s){let e=s.trim(),t=/^(?:([A-Za-z0-9_.]+):)?(.+)$/.exec(e);if(!t)return {provider:null,ticker:e};let n=t[1]?Ye(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 Hi=class{constructor(){this.entries=new Map;this.changeListeners=new Set;this.waits=new Set;this.unresolvedCbs=new Set;}register(e,t){let n=Ye(e),r={name:n,provider:t,index:null,prefixIndex:null,byTicker: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=>Rt(n.ticker))),e.byTicker=new Map(t.map(n=>[Rt(n.ticker),n])),e.prefixIndex=new Map;for(let n of t)n.prefix&&e.prefixIndex.set(`${Ye(n.prefix)}:${Rt(n.ticker)}`,n);}}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(Ye(e)),this.notify(false);}has(e){return this.entries.has(Ye(e))}get(e){return this.entries.get(Ye(e))?.provider}names(){return [...this.entries.keys()]}parse(e){return Xe(e)}resolve(e,t={}){let{provider:n,ticker:r}=this.parse(e);if(n){if(this.entries.has(n))return {provider:n,ticker:r};let o=`${n}:${Rt(r)}`;for(let a of this.candidateOrder(t.default)){let l=this.entries.get(a).prefixIndex?.get(o);if(l)return {provider:a,ticker:l.ticker}}return null}let i=Rt(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=Ye(e);if(this.entries.has(n))return [n,...t.filter(r=>r!==n)]}return t}displayPrefixOf(e){return this.entries.get(e.provider)?.byTicker?.get(Rt(e.ticker))?.prefix??e.provider}canonicalSymbol(e){let t=this.entries.get(e.provider)?.byTicker?.get(Rt(e.ticker));return `${t?.prefix??e.provider}:${t?.ticker??e.ticker}`}symbolsOf(e){return e!=null?this.entries.get(Ye(e))?.descriptors??[]:[...this.entries.entries()].flatMap(([t,n])=>n.descriptors.map(r=>({...r,provider:t})))}infoOf(e){let t=Ye(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 zi(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 $n(s){if(s.kind==="heading"||s.kind==="header")return [];let e=zi(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 At(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 Wn=new Map;function as(s){Wn.set(s.id,s);}function hm(s){Wn.delete(s);}function Ke(s){return typeof s=="string"?Wn.get(s):void 0}function je(){return [...Wn.values()]}function ls(){return [...Wn.values()].filter(s=>s.tickerModifier??s.barTransform!=null).map(s=>s.id)}function $i(s){return Ke(s)?.barTransform??null}function Sl(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"&&!ls().includes(t)?{symbol:s,modifier:null,transform:null}:{symbol:s.slice(0,e),modifier:t,transform:$i(t)}}var Ne={background:"#151619",textColor:"#b2b5be",gridColor:"#20222c",borderColor:"#2a2b30",upColor:q,downColor:X,fontFamily:"sans-serif"},Un={background:"#ffffff",textColor:"#1e293b",gridColor:"#cccccc",borderColor:"#d4dae3",upColor:q,downColor:X,fontFamily:"sans-serif"};function nn(s){return !s||s==="dark"?Ne:s==="light"?Un:s}var um=150,pm=1e3,mm=300,fm=5e3,Cl=1e4,bm=1.5,Tl=5e3,Wi=class s{constructor(e,t,n,r,i,o){this.renderer=t;this.feed=n;this.config=i;this.dataControl=o;this.events=new ft;this.registry=new Tr;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(nn(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=$i(a),this.drawings=new Ni(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(),Ke(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=Sl(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});}},um);}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>fm;if(o&&this.feed.loadRange){let a=await this.feed.load({...n,bars:Math.min(r,Cl)});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:mm});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<=Tl||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:Xe(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=Cl,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||Mn("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=Ke(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=Ke(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=$i(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()*bm&&Date.now()-this.lastHealAt>Tl){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 zn(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 Xt(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 Xt(n.id,n.title,this);let r=Mn(e),i=this.registry.nextId("native"),o=r?.title??e,a=new Xt(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 gm();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,vm(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)ae(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)<pm||(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 gm(){return typeof requestAnimationFrame=="function"?new Promise(s=>requestAnimationFrame(()=>requestAnimationFrame(()=>s()))):new Promise(s=>setTimeout(s,0))}function vm(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(ae(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 Gn=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 rn=new Map;function ym(s){let e=Object.entries(s);for(let[t,n]of e)rn.set(t,n);return ()=>{for(let[t,n]of e)rn.get(t)===n&&rn.delete(t);}}function xm(...s){if(s.length===0)rn.clear();else for(let e of s)rn.delete(e);}function cs(){return Object.fromEntries(rn)}var Ui=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 Pl(s,e,t){return `${s}|${e}|${t}`}function wm(s){return s.split("|")[1]??""}var Gi=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=wm(t);n!==e&&!this.retained.has(n)&&(this.series.delete(t),this.coveredFrom.delete(t));}}clear(){this.series.clear(),this.coveredFrom.clear();}},Yn=new Gi;function Ml(s,e){let{provider:t,ticker:n}=Xe(s);return Pl(t??"",n,e)}var Xn=1e4,Sm=Xn+1,Kn=class{constructor(e,t=Yn){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=Ml(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,Yi(l));return Ll(c,l[l.length-1]).slice(-i)}let a=await this.inner.load(e);return this.store.merge(n,Yi(a)),a}async loadRange(e,t){if(!this.inner.loadRange)return this.inner.load(e);let n=Ml(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,Yi(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,Yi(l)),this.store.markCovered(n,c??t.from??l[0]?.time??0),l}async fetchRange(e,t){let n=zn(e.timeframe??"60"),r=Cm(t,n);if(r<=Sm){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:Xn;if(c<=0)break;let d=await this.inner.loadRange(e,{to:o,limit:Math.min(Xn,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-=Xn*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 Cm(s,e){if(s.limit!=null)return s.limit;if(s.from==null)return Xn;let t=Math.max(0,(s.to??Date.now())-s.from);return Math.ceil(t/e*1.1)+2}function Yi(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 Tm(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 Ot=class{constructor(e=Yn){this.registry=new Hi;this.primaryProvider=null;this.liveBars=[];this.symInfoCache=new Map;this.cache=new Kn(new us(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})}displayPrefix(e){let t=this.resolveSymbol(e);return t?this.registry.displayPrefixOf(t):null}canonicalSymbol(e){let t=this.resolveSymbol(e);return t?this.registry.canonicalSymbol(t):null}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(hs(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(Xi(e),{default:this.primaryProvider});return this.primaryProvider=t.provider,this.prefetchSymbolInfo(t),this.cache.load(ds(e,t))}symbolInfo(e){if(e.data&&e.data.length>0)return;let t=this.registry.resolve(Xi(e),{default:this.primaryProvider});return t?this.symInfoCache.get(hs(t)):void 0}prefetchSymbolInfo(e){let t=hs(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(Xi(e),{default:this.primaryProvider});return n?this.cache.loadRange(ds(e,n),t):[]}subscribe(e,t){if(e.data&&e.data.length>0)return this.synthesizeTicks(e,t);let n=this.registry.resolve(Xi(e),{default:this.primaryProvider});return n?this.cache.subscribe(ds(e,n),t):()=>{}}synthesizeTicks(e,t){if(this.liveBars.length===0)return ()=>{};let n=Tm(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 Xi(s){return s.symbol??""}function ds(s,e){return {...s,symbol:`${e.provider}:${e.ticker}`}}function hs(s){return `${s.provider}|${s.ticker}`}async function El(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 us=class{constructor(e){this.registry=e;}load(e){let{provider:t,ticker:n}=Xe(e.symbol??""),r=this.registry.get(t??"");return r?El(r,n,e.timeframe??"60",{limit:e.bars??500}):Promise.resolve([])}loadRange(e,t){let{provider:n,ticker:r}=Xe(e.symbol??""),i=this.registry.get(n??"");return i?El(i,r,e.timeframe??"60",t):Promise.resolve([])}subscribe(e,t){let{provider:n,ticker:r}=Xe(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 jn=class{constructor(e){this.registry=e instanceof Ot?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}displayPrefix(e){return this.registry?.displayPrefix(e)??null}canonicalSymbol(e){return this.registry?.canonicalSymbol(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 qn=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 Ki(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=Ki(s);return t?`rgba(${t.r},${t.g},${t.b},${e})`:s}function kl(s,e,t){let n=Ki(s),r=Ki(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 Se(s){let e=Ki(s);return e?.2126*e.r+.7152*e.g+.0722*e.b<128:true}var ji={"--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-z-popover":"6000","--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 qi(s){let e=Se(s.background),t=r=>e?`rgba(255,255,255,${r})`:W(s.textColor,r+.02),n=kl(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":xe,"--vela-accent-bright":Kt,"--vela-highlight":_a,"--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 ce(s,e){let t=n=>{for(let r in n)s.style.setProperty(r,n[r]);};t(ji),t(qi(e));}function Ft(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;"),ce(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 Il(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}}function ue(s,e,t=document){if(typeof document>"u")return;let n=t instanceof Document?t.head:t;if(t.getElementById?.(s)??n.querySelector(`#${CSS.escape(s)}`))return;let r=document.createElement("style");r.id=s,r.textContent=e,n.appendChild(r);}function on(s,e=document){let t=e.createElement("span");t.className="vela-icon",t.setAttribute("aria-hidden","true");let n=Dr(s);return n&&(t.innerHTML=n),t}function Dl(s={}){let e=s.checked??false,t=s.disabled??false;return {get checked(){return e},disabled:t,size:s.size??"md",tone:s.tone??"bright",setChecked(n){e=n;},toggle(){return t||(e=!e,s.onChange?.(e)),e}}}var Rl="vela-ui-switch",Al=`
|
|
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&&he(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 Ae=class extends Te{constructor(){super(...arguments);this.type="callout";}};var vt=class extends Te{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 yt=class extends Te{constructor(){super(...arguments);this.type="comment";}defaultLabel(){return "Comment"}};var xt=class extends Te{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&&Re(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 $r=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 Wr=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 Ur=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 Vh=2;function Xa(){return {midColor:pe,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:Vh*h,r2:Math.max(0,Math.min(1,p*p)),n:e}}var Ue=class extends B{constructor(t){super(t);this.type="regressionchannel";this.cachedRange=null;this.reg||(this.reg=Xa());}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 Re(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={...Xa(),...t};}};var ja=`${ze}00`;function qa(){return {midColor:ze,midStyle:"solid",multiplier:1,upperColor:ja,upperStyle:"solid",lowerColor:ja,lowerStyle:"solid",bandFill:`${ze}33`}}function Za(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 wt=class extends B{constructor(t){super(t);this.type="anchoredvwap";this.cachedRange=null;this.cachedExtent=null;this.vwap||(this.vwap=qa());}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=Za(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?Re(t,n,this.bandPolygon(o))?true:Qo(t,n,o.mid,i)||Qo(t,n,o.upper,i)||Qo(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={...qa(),...t};}};function Qo(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 _h=`${q}66`,Nh=`${X}66`,Hh=`${q}BF`,zh=`${X}BF`;function Ja(){return {rows:24,valueAreaPct:70,widthPct:35,anchor:"left",upColor:_h,downColor:Nh,vaUpColor:Hh,vaDownColor:zh,showVah:true,vahColor:pe,vahStyle:"solid",showVal:true,valColor:pe,valStyle:"solid",showPoc:true,pocColor:void 0,pocStyle:"solid",showDevelopingPoc:false,developingPocColor:xe,developingPocStyle:"dotted",showDevelopingVa:false,developingVaColor:xe,developingVaStyle:"dotted"}}function $h(s,e){return s<0?0:s>=e?e-1:s}function Qa(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 el(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($h(Math.floor((l-e)/t),i));for(let l of a)s[l][o]+=r;}function tl(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 nl(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)el(a,n,o,p);let l=tl(a);if(!l)return null;let{poc:c,maxTotal:d}=l,{vaFrom:h,vaTo:u}=Qa(a,c,t);return {rows:a,rowH:o,min:n,maxTotal:d,poc:c,vaFrom:h,vaTo:u}}function rl(s,e,t,n){let r=nl(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){el(l,i,o,u);let p=tl(l);if(!p)continue;let{poc:m}=p,{vaFrom:f,vaTo:b}=Qa(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 Oe=class extends B{constructor(t){super(t);this.type="fixedrangevp";this.cachedRange=null;this.frvp||(this.frvp=Ja());}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=rl(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,w=C=>{let T=[];for(let P of C){let E=g(P.price);E!=null&&T.push([t.xOf(P.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:w(i.developingPoc),developingVaHigh:w(i.developingVaHigh),developingVaLow:w(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(Re(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:ge,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:ge,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:ge,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:ge,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:ge,group:"line"}]}}writeProps(){return {...this.frvp}}readProps(t){this.frvp={...Ja(),...t};}};var Gr=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:[ne(a[0],a[1],d,h,"right",m,f),ne(l[0],l[1],l[0]+u,l[1]+p,"right",m,f),ne(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 qt=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:[ne(o[0],o[1],c,d,"right",p,m),ne(a[0],a[1],a[0]+h,a[1]+u,"right",p,m),ne(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 Yr=class extends qt{constructor(){super(...arguments);this.type="schiffpitchfork";}medianStart(t,n){return {time:t.time,price:(t.price+n.price)/2}}};var Xr=class extends qt{constructor(){super(...arguments);this.type="modifiedschiffpitchfork";}medianStart(t,n){return {time:(t.time+n.time)/2,price:(t.price+n.price)/2}}};var Kr=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:[ne(h,u,h+p,u+m,"right",f,b),ne(c[0],c[1],c[0]+p,c[1]+m,"right",f,b),ne(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 jr=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 il=48,qr=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<=il;r+=1){let i=r/il*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:jt(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 Zr=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 Wh=512,at=class extends J{anchorSchema(){return {min:2,max:Wh,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 Jr=class extends at{constructor(){super(...arguments);this.type="polyline";}};var kn=class extends at{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}}},Qr=class extends kn{constructor(){super(...arguments);this.type="freehand";}};var Uh=[{path:"style.lineColor",label:"Color",kind:"color",group:"line"},{path:"style.lineWidth",label:"Width",kind:"number",min:4,max:60,step:1,group:"line"}],ei=class extends kn{constructor(){super(...arguments);this.type="highlighter";}schema(){return {fields:Uh}}};var ti=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 ni=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 ri=class extends at{constructor(){super(...arguments);this.type="path";}};var ol=40,ii=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<=ol;v+=1){let y=v/ol*Math.PI,x=Math.cos(y),w=Math.sin(y);b.push([a+x*c+w*f*u,l+x*d+w*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 sl=40,oi=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<=sl;l+=1){let c=l/sl,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 Gh={head:11,headW:9,stemW:3.5,len:22},St=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}=Gh,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&&Re(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]}}},In=class extends St{constructor(){super(...arguments);this.type="arrowmarkup";}dir(){return "up"}},Dn=class extends St{constructor(){super(...arguments);this.type="arrowmarkdown";}dir(){return "down"}};var On=["\u2605","\u2606","\u25CF","\u25C6","\u25B2","\u25BC","\u27A4","\u2691","\u271A","\u2715","\u2764","\u2666"],si=["small","normal","large","huge"],al={small:16,normal:22,large:32,huge:44},Ct=class extends B{constructor(e){super(e),this.glyph||(this.glyph=this.defaultGlyph()),this.size||(this.size="normal");}sizePx(){return al[this.size]??al.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:On.map(e=>({value:e,label:e})),group:"line"},{path:"size",label:"Size",kind:"select",options:si.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);}},Rn=class extends Ct{constructor(){super(...arguments);this.type="flagmark";}defaultGlyph(){return "\u2691"}},An=class extends Ct{constructor(){super(...arguments);this.type="iconstamp";}defaultGlyph(){return "\u2605"}};var ll=s=>s==="small"||s==="normal"||s==="large"||s==="huge";function Yh(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(Yh).filter(n=>n!=null);t.length&&(this.levels=t);}ll(e.numbersSize)&&(this.numbersSize=e.numbersSize),ll(e.labelsSize)&&(this.labelsSize=e.labelsSize);}};var Zt=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 Tt=pe,Fe=X,Be=Ln,Pt="#4caf50",lt=q,Ge=ze,Mt="#9c27b0",Xh="#e91e63",es="#26a69a",Kh="#ab47bc",jh="#ef5350",cl="#ffb74d",qh="#38c0fd",ai="#b2b5be",Jt=[qh,Ge,lt,Pt,Be,Fe,Xh,Mt,Tt,es,Kh,jh];function dl(s){return Jt[(s%Jt.length+Jt.length)%Jt.length]}var Zh=[[0,Tt],[.125,Fe],[.236,Fe],[.25,Fe],[.382,Be],[.5,Pt],[.618,lt],[.75,Ge],[.786,Ge],[1,Tt],[1.272,Ge],[1.382,Be],[1.618,Fe],[2,Tt],[2.382,Be],[2.618,Be],[3,Tt],[4.236,Pt],[6.854,lt],[11.09,Ge]];function Jh(s,e=0){return Zh.find(([t])=>t===s)?.[1]??dl(e)}function Q(s){return s.map((e,t)=>{let n=typeof e=="number"?{ratio:e}:e;return {ratio:n.ratio,color:n.color??Jh(n.ratio,t),enabled:n.enabled!==false,...n.label?{label:n.label}:{}}})}function hl(s,e=s){return Array.from({length:s},(t,n)=>({ratio:n+1,color:dl(n),enabled:n<e,label:String(n+1)}))}var Qh=Q([0,.236,.382,.5,.618,.786,1]),li=class extends Zt{constructor(){super(...arguments);this.type="fibretracement";}defaultLevels(){return Qh}};var eu=Q([0,.382,.618,1,1.272,1.618,{ratio:2.618,color:Mt}]),ci=class extends Zt{constructor(){super(...arguments);this.type="fibextension";}defaultLevels(){return eu}};var tu=Q([0,.382,.5,.618,1,1.618,{ratio:2.618,color:Mt}]),di=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 tu}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 nu=Q([.236,.382,.5,.618,.786,1]),hi=class extends ee{constructor(){super(...arguments);this.type="fibfan";}defaultLevels(){return nu}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]=ne(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 ru=[0,1,2,3,5,8,13,21,34].map(s=>({ratio:s,color:D,enabled:true})),ui=class extends ee{constructor(){super(...arguments);this.type="fibtimezones";}defaultLevels(){return ru}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 iu=Q([0,.236,.382,.5,.618,.786,1,1.618,2.618]),pi=class extends ee{constructor(){super(...arguments);this.type="fibchannel";}defaultLevels(){return iu}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 ou=Q([0,.236,.382,.5,.618,.786,1]),mi=class extends ee{constructor(){super(...arguments);this.type="fibspeedfan";}defaultLevels(){return ou}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=ne(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,w=ne(a,i,y,x,h,u,p);m.push({color:f.color,label:f.label,x1:w[0],y1:w[1],x2:w[2],y2:w[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 su=Q([0,.382,{ratio:.5,enabled:false},.618,1,1.382,1.618,2,2.382,2.618,3]),fi=class extends ee{constructor(){super(...arguments);this.type="trendfibtime";}defaultLevels(){return su}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 au(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 Ee=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(au(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 lu=Q([.236,.382,.5,.618,.786,1,1.618,2.618]),bi=class extends Ee{constructor(){super(...arguments);this.type="fibcircles";}defaultLevels(){return lu}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 cu=Q([.236,.382,.5,.618,.786,1,1.618,2.618]),gi=class extends Ee{constructor(){super(...arguments);this.type="fibarcs";}defaultLevels(){return cu}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 du=Q([.236,.382,.5,.618,.786,1]),vi=class extends Ee{constructor(){super(...arguments);this.type="fibwedge";}defaultLevels(){return du}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 hu=1.6180339887,ul=Math.log(hu)/(Math.PI/2),uu=Math.PI/64,pu=Math.PI,mu=.5,Lt=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(mu/c)/ul,-8*Math.PI*2),u=[];for(let p=h;p<=pu;p+=uu){let m=c*Math.exp(ul*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&&jt(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 fu=Q([{ratio:.125,color:Fe,label:"1/8"},{ratio:.25,color:Be,label:"1/4"},{ratio:.333,color:cl,label:"1/3"},{ratio:.5,color:Pt,label:"1/2"},{ratio:1,color:ai,label:"1/1"},{ratio:2,color:lt,label:"2/1"},{ratio:3,color:Ge,label:"3/1"},{ratio:4,color:es,label:"4/1"},{ratio:8,color:Mt,label:"8/1"}]),yi=class extends ee{constructor(){super(...arguments);this.type="gannfan";}defaultLevels(){return fu}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]=ne(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 bu=Q([0,.25,.382,.5,.618,.75,1].map(s=>({ratio:s,label:String(s)}))),xi=class extends ee{constructor(){super(...arguments);this.type="gannbox";}defaultLevels(){return bu}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??Tt;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&&he(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 gu=Q([0,.25,.382,.5,.618,.75,1].map(s=>({ratio:s,label:String(s)}))),vu=[{label:"3x1",x:3,y:1,color:Fe},{label:"2x1",x:2,y:1,color:Be},{label:"1x1",x:1,y:1,color:ai},{label:"1x2",x:1,y:2,color:lt},{label:"1x3",x:1,y:3,color:Ge}],ts=[{k:.25,color:Fe},{k:.5,color:Be},{k:.75,color:Pt},{k:1,color:lt}],Et=class extends ee{constructor(){super(...arguments);this.type="gannsquare";}defaultLevels(){return gu}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 vu){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&&he(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 ns=[4,8,12,16,24,32,48,64],yu=24,xu=.75;function pl(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 ml(s){let e=[];for(let t=0;t<s;t+=1)pl(t,s)&&e.push(t);return e}var kt=class extends B{constructor(t){super(t);this.type="dedekind";this.maxCurvature===void 0&&(this.maxCurvature=yu);}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<xu)continue;let x=ml(g);if(x.length===0)continue;let w=Math.floor(h)-1,C=Math.ceil(u)+1;for(let T=w;T<=C;T+=1)for(let P of x){let E=P/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&&he(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 rs=[3,4,5,6,8,10,12],is=[1.5,2,2.5,3,4,5],wi=6,wu=2;function os(s=wi){return [...hl(Jt.length,s)]}function Su(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 Qt={path:"showRatios",label:"Show ratios",kind:"boolean",group:"behavior"},we=class extends B{constructor(e){super(e),this.waveCount===void 0&&(this.waveCount=wi),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,w=[];if(f<=1+1e-9){let C=-u,T=h;w.push([g-C*x,v-T*x,g+C*x,v+T*x]);}else {let C=Math.asin(1/f),T=Math.cos(C),P=Math.sin(C),E=(G,S,H)=>[G*T-S*H*P,G*H*P+S*T],[k,M]=E(h,u,1),[L,V]=E(h,u,-1);w.push([g,v,g+k*x,v+M*x]),w.push([g,v,g+L*x,v+V*x]);}return {c0x:l,c0y:c,R:d,fx:h,fy:u,noseX:g,noseY:v,circles:b,rays:w}}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"},Qt,...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(Su).filter(n=>n!=null);t.length&&(this.levels=t);}}},Fn=class extends we{constructor(){super(...arguments);this.type="sonic";}defaultLevels(){return os(wi)}machNumber(){return 1}},Bn=class extends we{constructor(t){super(t);this.type="supersonic";this.mach===void 0&&(this.mach=wu);}defaultLevels(){return os(wi)}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"},Qt,...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 fl=Q([.236,.382,.5,.618,.786,1,1.618,2.618,4.236,6.854,11.09]),Cu=2,Si=class extends we{constructor(){super(...arguments);this.type="goldensonic";}shouldSyncWaveCount(){return false}defaultLevels(){return fl}machNumber(){return 1}schema(){return {fields:[...O,Qt,...F]}}},Ci=class extends we{constructor(t){super(t);this.type="goldensupersonic";this.mach===void 0&&(this.mach=Cu);}shouldSyncWaveCount(){return false}defaultLevels(){return fl}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"},Qt,...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 se=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&&jt(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 Ti=class extends se{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 se{constructor(){super(...arguments);this.type="abcd";}vertexLabels(){return ["A","B","C","D"]}legRatios(){return true}};var Mi=class extends se{constructor(){super(...arguments);this.type="elliottimpulse";}vertexLabels(){return ["1","2","3","4","5"]}};var Li=class extends se{constructor(){super(...arguments);this.type="elliottcorrection";}vertexLabels(){return ["A","B","C"]}};var Ei=class extends se{constructor(){super(...arguments);this.type="headshoulders";}vertexLabels(){return ["","LS","","H","","RS",""]}necklineIndices(){return [2,4]}};var ve=class extends se{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 ki=class extends ve{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 Ii=class extends ve{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 Di=class extends ve{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 Ri=class extends ve{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 Ai=class extends ve{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 Tu={min:1.272,max:1.414},Pu={min:.74,max:.83},Oi=class extends ve{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(),Tu)&&this.inBand(this.cdOverXc(),Pu)}};function bl(s){return `${s>=0?"+":""}${s.toFixed(2)}`}function Vn(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 It=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 `${bl(n)} (${bl(r)}%)`}timeLabel(e){let t=this.anchors[0],n=this.anchors[1];if(!t||!n)return "";let r=Vn(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&&he(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:Le,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 Fi=class extends It{constructor(){super(...arguments);this.type="datepricerange";}};var Bi=[{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 $${Mu(this.dollarLoss())} \xB7 Size ${Lu(this.positionSize())}`}targetLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${gl(t.target)}`:"";return `Target +${this.rewardPct().toFixed(2)}%${n}`}stopLabel(){let t=this.prices(),n=this.showPrices&&t?` @ ${gl(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 vl(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 he(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:Bi,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:Le,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=Lr,ie.DEFAULT_LOSS_COLOR=Er;var Ve=ie;function Mu(s){if(!Number.isFinite(s))return "0";let e=Math.round(s*100)/100;return Number.isInteger(e)?String(e):e.toFixed(2)}function Lu(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 gl(s){return Number.isFinite(s)?Math.abs(s)>=1?s.toFixed(2):s.toPrecision(4).replace(/\.?0+$/,""):"0"}function vl(s){return Math.round(s*1e8)/1e8}var _n=new Map;function A(s){_n.set(s.type,s);}function ct(s){return _n.get(s)}function Vi(){return [..._n.values()]}function dt(s,e){let t=_n.get(s);if(!t)return null;let n={...t.defaultStyle,...e.style??{}};return t.create({...e,style:n})}function ss(s){let e=dt(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 _e(s){let e=_n.get(s.type);return e?e.create(s):null}var Eu=I('<line x1="4" y1="19" x2="20" y2="5"/>'),ku=I('<line x1="3" y1="12" x2="21" y2="12"/>');A({type:"trendline",group:"lines",label:"Trend Line",icon:Eu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Rr(s)});A({type:"hline",group:"lines",label:"Horizontal Line",icon:ku,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"dashed"},create:s=>new Ar(s)});var Iu=I('<line x1="3" y1="20" x2="21" y2="6"/><circle cx="3" cy="20" r="1.6" fill="currentColor"/>'),Du=I('<rect x="4" y="6" width="16" height="12" rx="1"/>'),Ru=I('<path d="M5 6h14M12 6v13"/>');A({type:"ray",group:"lines",label:"Ray",icon:Iu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Or(s)});var Au=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"/>'),Ou=I('<line x1="12" y1="3" x2="12" y2="21"/>'),Fu=I('<line x1="5" y1="12" x2="21" y2="12"/><circle cx="5" cy="12" r="1.6" fill="currentColor"/>'),Bu=I('<line x1="3" y1="12" x2="21" y2="12"/><line x1="12" y1="3" x2="12" y2="21"/>'),Vu=I('<path d="M4 20 20 4"/><rect x="9" y="9" width="9" height="6" rx="1"/>'),_u=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:Au,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Fr(s)});A({type:"vline",group:"lines",label:"Vertical Line",icon:Ou,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Br(s)});A({type:"hray",group:"lines",label:"Horizontal Ray",icon:Fu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Vr(s)});A({type:"crossline",group:"lines",label:"Cross Line",icon:Bu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new _r(s)});A({type:"infoline",group:"lines",label:"Info Line",icon:Vu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Nr(s)});A({type:"trendangle",group:"lines",label:"Trend Angle",icon:_u,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Hr(s)});A({type:"box",group:"shapes",label:"Rectangle",icon:Du,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}26`},create:s=>new zr(s)});A({type:"text",group:"annotations",label:"Text",icon:Ru,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new We(s)});var Nu=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:Nu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new Ae(s)});var Hu=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"/>'),zu=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"/>'),$u=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"/>'),Wu=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"/>'),Uu=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:Hu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new bt(s)});A({type:"pricenote",group:"annotations",label:"Price Note",icon:zu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new vt(s)});A({type:"comment",group:"annotations",label:"Comment",icon:$u,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new yt(s)});A({type:"pricelabel",group:"annotations",label:"Price Label",icon:Wu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new gt(s)});A({type:"signpost",group:"annotations",label:"Signpost",icon:Uu,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid",fillColor:`${D}d9`},create:s=>new xt(s)});var Gu=I('<line x1="3" y1="16" x2="21" y2="8"/><line x1="3" y1="21" x2="21" y2="13"/>'),Yu=I('<line x1="3" y1="7" x2="21" y2="10"/><line x1="3" y1="18" x2="21" y2="14"/>'),Xu=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:Gu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new $r(s)});A({type:"disjointchannel",group:"channels",label:"Disjoint Channel",icon:Yu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new Wr(s)});var Ku=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:Ku,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new Ur(s)});var ju=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:ju,defaultStyle:{lineColor:pe,lineWidth:1,lineStyle:"solid"},create:s=>new Ue(s)});A({type:"pitchfork",group:"pitchforks",label:"Pitchfork",icon:Xu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Gr(s)});var qu=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"/>'),Zu=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"/>'),Ju=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:qu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Yr(s)});A({type:"modifiedschiffpitchfork",group:"pitchforks",label:"Modified Schiff Pitchfork",icon:Zu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Xr(s)});A({type:"insidepitchfork",group:"pitchforks",label:"Inside Pitchfork",icon:Ju,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Kr(s)});var Qu=I('<path d="M7 7h10v10"/><path d="M7 17 17 7"/>'),ep=I('<ellipse cx="12" cy="12" rx="9" ry="6"/>'),tp=I('<path d="M12 4 20 19 4 19Z"/>');A({type:"arrow",group:"shapes",label:"Arrow",icon:Qu,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",arrowRight:true},create:s=>new jr(s)});A({type:"ellipse",group:"shapes",label:"Ellipse",icon:ep,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new qr(s)});A({type:"triangle",group:"shapes",label:"Triangle",icon:tp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new Zr(s)});var np=I('<polyline points="3 17 9 10 13 14 21 5"/>'),rp=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"/>'),ip=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:np,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Jr(s)});A({type:"freehand",group:"shapes",label:"Brush",icon:rp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Qr(s)});A({type:"highlighter",group:"shapes",label:"Highlighter",icon:ip,defaultStyle:{lineColor:`${Na}59`,lineWidth:14,lineStyle:"solid"},create:s=>new ei(s)});var op=I('<circle cx="12" cy="12" r="8"/>'),sp=I('<path d="M5 14 9.5 5 19 10 14.5 19 Z"/>'),ap=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"/>'),lp=I('<path d="M4 17a8 8 0 0 1 16 0"/><path d="M4 17 20 17"/>'),cp=I('<path d="M4 18Q12 1 20 14"/>'),dp=I('<path d="M12 5 12 19"/><path d="M6 11 12 5 18 11"/>'),hp=I('<path d="M12 5 12 19"/><path d="M6 13 12 19 18 13"/>');A({type:"circle",group:"shapes",label:"Circle",icon:op,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}1a`},create:s=>new ti(s)});A({type:"rotatedrect",group:"shapes",label:"Rotated Rectangle",icon:sp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}26`},create:s=>new ni(s)});A({type:"path",group:"shapes",label:"Path",icon:ap,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new ri(s)});A({type:"arc",group:"shapes",label:"Arc",icon:lp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid",fillColor:`${D}26`},create:s=>new ii(s)});A({type:"curve",group:"shapes",label:"Curve",icon:cp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new oi(s)});A({type:"arrowmarkup",group:"shapes",label:"Arrow Mark Up",icon:dp,defaultStyle:{lineColor:q,lineWidth:1,lineStyle:"solid"},create:s=>new In(s)});A({type:"arrowmarkdown",group:"shapes",label:"Arrow Mark Down",icon:hp,defaultStyle:{lineColor:X,lineWidth:1,lineStyle:"solid"},create:s=>new Dn(s)});var up=I('<path d="M6 21V4"/><path d="M6 5h11l-2.5 3.5L17 12H6" fill="currentColor" stroke="none"/>'),pp=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:up,defaultStyle:{lineColor:xe,lineWidth:1,lineStyle:"solid"},create:s=>new Rn(s)});A({type:"iconstamp",group:"stamps",label:"Icon",icon:pp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new An(s)});var mp=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"/>'),fp=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:mp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new li(s)});A({type:"fibextension",group:"fibonacci",label:"Fib Extension",icon:fp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new ci(s)});var bp=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:bp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new di(s)});var gp=I('<path d="M4 20 20 5M4 20 21 11M4 20 21 17M4 20 20 20"/>'),vp=I('<path d="M3 5v14M6 5v14M11 5v14M19 5v14"/>');A({type:"fibfan",group:"fibonacci",label:"Fib Fan",icon:gp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new hi(s)});A({type:"fibtimezones",group:"fibonacci",label:"Fib Time Zones",icon:vp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"dashed"},create:s=>new ui(s)});var yp=I('<path d="M3 18 18 9M5 21 20 12M6 13 21 4"/>'),xp=I('<path d="M4 4 20 20M4 4 20 12M4 4 12 20M4 4 20 4M4 4 4 20"/>'),wp=I('<path d="M3 19 9 8M9 8 12 5v14M14 5v14M18 5v14M21 5v14"/>');A({type:"fibchannel",group:"fibonacci",label:"Fib Channel",icon:yp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new pi(s)});A({type:"fibspeedfan",group:"fibonacci",label:"Fib Speed Resistance Fan",icon:xp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new mi(s)});A({type:"trendfibtime",group:"fibonacci",label:"Trend-Based Fib Time",icon:wp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"dashed"},create:s=>new fi(s)});var Sp=I('<circle cx="12" cy="12" r="3"/><circle cx="12" cy="12" r="6.5"/><circle cx="12" cy="12" r="10"/>'),Cp=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"/>'),Tp=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"/>'),Pp=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:Sp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new bi(s)});A({type:"fibarcs",group:"fibonacci",label:"Fib Speed Resistance Arcs",icon:Cp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new gi(s)});A({type:"fibwedge",group:"fibonacci",label:"Fib Wedge",icon:Tp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new vi(s)});A({type:"fibspiral",group:"fibonacci",label:"Fib Spiral",icon:Pp,defaultStyle:{lineColor:D,lineWidth:2,lineStyle:"solid"},create:s=>new Lt(s)});var Mp=I('<path d="M4 20 20 20M4 20 20 13M4 20 20 6M4 20 15 4M4 20 9 4M4 20 4 4"/>'),Lp=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:Mp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new yi(s)});A({type:"gannbox",group:"fibonacci",label:"Gann Box",icon:Lp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new xi(s)});var Ep=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:Ep,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Et(s)});var kp=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:kp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new kt(s)});var Ip=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"/>'),Dp=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:Ip,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Fn(s)});A({type:"supersonic",group:"geometry",label:"Supersonic",icon:Dp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Bn(s)});var Rp=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"/>'),Ap=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:Rp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Si(s)});A({type:"goldensupersonic",group:"geometry",label:"Golden Supersonic",icon:Ap,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Ci(s)});var Op=I('<path d="M3 18 7 8 11 14 15 6 20 16"/>'),Fp=I('<path d="M4 17 9 7 14 15 20 5"/>'),Bp=I('<path d="M3 19 8 9 12 13 17 5 21 9"/>'),Vp=I('<path d="M4 7 11 16 20 9"/>'),_p=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:Op,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Ti(s)});A({type:"abcd",group:"patterns",label:"ABCD Pattern",icon:Fp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Pi(s)});A({type:"elliottimpulse",group:"patterns",label:"Elliott Impulse Wave (1-5)",icon:Bp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Mi(s)});A({type:"elliottcorrection",group:"patterns",label:"Elliott Correction Wave (ABC)",icon:Vp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Li(s)});A({type:"headshoulders",group:"patterns",label:"Head & Shoulders",icon:_p,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Ei(s)});var Np=I('<path d="M3 17 7 6 12 14 17 5 21 16"/><path d="M3 17 21 16" opacity="0.45"/>'),en={group:"patterns",icon:Np,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"}};A({type:"gartley",label:"Gartley",...en,create:s=>new ki(s)});A({type:"bat",label:"Bat",...en,create:s=>new Ii(s)});A({type:"butterfly",label:"Butterfly",...en,create:s=>new Di(s)});A({type:"crab",label:"Crab",...en,create:s=>new Ri(s)});A({type:"shark",label:"Shark",...en,create:s=>new Ai(s)});A({type:"cypher",label:"Cypher",...en,create:s=>new Oi(s)});var Hp=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:Hp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Fi(s)});var zp=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:zp,defaultStyle:{lineColor:D,lineWidth:1,lineStyle:"solid"},create:s=>new Ve(s)});var $p=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:$p,defaultStyle:{lineColor:ze,lineWidth:2,lineStyle:"solid"},create:s=>new wt(s)});var Wp=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:Wp,defaultStyle:{lineColor:q,lineWidth:1,lineStyle:"solid"},create:s=>new Oe(s)});var Up=["fibretracement","fibextension","fibextensiontrend","fibfan","fibtimezones","fibchannel","fibspeedfan","trendfibtime","fibcircles","fibarcs","fibwedge","fibspiral"],Gp=["gannfan","gannbox","gannsquare"],Yp=["dedekind","sonic","supersonic","goldensonic","goldensupersonic"],Xp=["xabcd","abcd","headshoulders"],Kp=["elliottimpulse","elliottcorrection"],jp=["gartley","bat","butterfly","crab","shark","cypher"],qp=["position","datepricerange"],Zp=["anchoredvwap","fixedrangevp"],Jp=["freehand","highlighter"],Qp=["arrow","arrowmarkup","arrowmarkdown"],em=["box","ellipse","triangle","polyline","circle","rotatedrect","path","arc","curve"],tm=["text","callout","note","pricenote","comment","pricelabel","signpost"],nm=["flagmark","iconstamp"],rm=[{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:Up},{label:"Gann",types:Gp},{label:"Geometry",types:Yp}]},{id:"patterns-waves-harmonics",label:"Patterns",sections:[{label:"Patterns",types:Xp},{label:"Elliott Waves",types:Kp},{label:"Harmonics",types:jp}]},{id:"measurements",label:"Measurements",sections:[{label:"Measurements",types:qp},{label:"Volume",types:Zp}]},{id:"brushes-arrows-shapes",label:"Shapes",sections:[{label:"Brushes",types:Jp},{label:"Arrows",types:Qp},{label:"Shapes",types:em}]},{id:"text",label:"Text",sections:[{label:"Text",types:tm}]},{id:"icons",label:"Icons",sections:[{label:"Icons",types:nm}]}];function im(s){let e=ct(s);return e?{type:e.type,label:e.label,icon:e.icon}:null}function om(s){let e=new Map;for(let t of Vi()){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 sm(s,e,t){return "registryGroup"in s?e.get(s.registryGroup)??[]:s.types.map(n=>t.get(n)).filter(n=>n!=null)}function yl(s){let e=om(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 rm){let i=[],o=[];for(let a of r.sections){let l=sm(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 am(s){let e=new Set;for(let t of s)ct(t)&&e.add(t);return yl(e)}function lm(s){let e=[];for(let t of s){let n=t.tools.map(im).filter(r=>r!=null);n.length>0&&e.push({id:t.id,label:t.label,tools:n});}return {groups:e}}function Nn(){return yl()}function Hn(s){if(s===false)return {definition:Nn(),visible:false};if(s===void 0||s===true)return {definition:Nn(),visible:true};let e=s.toolbar??true;return s.groups?{definition:lm(s.groups),visible:e}:s.tools?{definition:am(s.tools),visible:e}:{definition:Nn(),visible:e}}function Dt(s){let e=globalThis.structuredClone;return e?e(s):JSON.parse(JSON.stringify(s))}function cm(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 xl(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(cm)}}var tn=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=xl(e);this.byId.clear(),this.seq=0,this.zCounter=1;for(let n of t.drawings){let r=_e(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 _i=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=Dt(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(Dt(e));}undo(e){let t=this.undoStack.pop();return t?(this.redoStack.push(Dt(e)),t):null}redo(e){let t=this.redoStack.pop();return t?(this.undoStack.push(Dt(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 Ni=class{constructor(e,t,n){this.events=t;this.store=new tn;this.history=new _i;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}=Hn(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){ct(e)&&t!==this.favs.has(e)&&(t?this.favs.add(e):this.favs.delete(e),this.pushFavorites());}setFavorites(e){let t=e.filter(n=>ct(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(Hn(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=dt(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=>Dt(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=_e({...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=_e({...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 wl={D:864e5,W:6048e5,M:2592e6};function zn(s){let e=s.trim();if(wl[e])return wl[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 Ye=s=>s.trim().toLowerCase(),Rt=s=>s.trim().toUpperCase();function Xe(s){let e=s.trim(),t=/^(?:([A-Za-z0-9_.]+):)?(.+)$/.exec(e);if(!t)return {provider:null,ticker:e};let n=t[1]?Ye(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 Hi=class{constructor(){this.entries=new Map;this.changeListeners=new Set;this.waits=new Set;this.unresolvedCbs=new Set;}register(e,t){let n=Ye(e),r={name:n,provider:t,index:null,prefixIndex:null,byTicker: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=>Rt(n.ticker))),e.byTicker=new Map(t.map(n=>[Rt(n.ticker),n])),e.prefixIndex=new Map;for(let n of t)n.prefix&&e.prefixIndex.set(`${Ye(n.prefix)}:${Rt(n.ticker)}`,n);}}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(Ye(e)),this.notify(false);}has(e){return this.entries.has(Ye(e))}get(e){return this.entries.get(Ye(e))?.provider}names(){return [...this.entries.keys()]}parse(e){return Xe(e)}resolve(e,t={}){let{provider:n,ticker:r}=this.parse(e);if(n){if(this.entries.has(n))return {provider:n,ticker:r};let o=`${n}:${Rt(r)}`;for(let a of this.candidateOrder(t.default)){let l=this.entries.get(a).prefixIndex?.get(o);if(l)return {provider:a,ticker:l.ticker}}return null}let i=Rt(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=Ye(e);if(this.entries.has(n))return [n,...t.filter(r=>r!==n)]}return t}displayPrefixOf(e){return this.entries.get(e.provider)?.byTicker?.get(Rt(e.ticker))?.prefix??e.provider}canonicalSymbol(e){let t=this.entries.get(e.provider)?.byTicker?.get(Rt(e.ticker));return `${t?.prefix??e.provider}:${t?.ticker??e.ticker}`}symbolsOf(e){return e!=null?this.entries.get(Ye(e))?.descriptors??[]:[...this.entries.entries()].flatMap(([t,n])=>n.descriptors.map(r=>({...r,provider:t})))}infoOf(e){let t=Ye(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 zi(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 $n(s){if(s.kind==="heading"||s.kind==="header")return [];let e=zi(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 At(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 Wn=new Map;function as(s){Wn.set(s.id,s);}function hm(s){Wn.delete(s);}function Ke(s){return typeof s=="string"?Wn.get(s):void 0}function je(){return [...Wn.values()]}function ls(){return [...Wn.values()].filter(s=>s.tickerModifier??s.barTransform!=null).map(s=>s.id)}function $i(s){return Ke(s)?.barTransform??null}function Sl(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"&&!ls().includes(t)?{symbol:s,modifier:null,transform:null}:{symbol:s.slice(0,e),modifier:t,transform:$i(t)}}var Ne={background:"#151619",textColor:"#b2b5be",gridColor:"#20222c",borderColor:"#2a2b30",upColor:q,downColor:X,fontFamily:"sans-serif"},Un={background:"#ffffff",textColor:"#1e293b",gridColor:"#cccccc",borderColor:"#d4dae3",upColor:q,downColor:X,fontFamily:"sans-serif"};function nn(s){return !s||s==="dark"?Ne:s==="light"?Un:s}var um=150,pm=1e3,mm=300,fm=5e3,Cl=1e4,bm=1.5,Tl=5e3,Wi=class s{constructor(e,t,n,r,i,o){this.renderer=t;this.feed=n;this.config=i;this.dataControl=o;this.events=new ft;this.registry=new Tr;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(nn(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=$i(a),this.drawings=new Ni(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(),Ke(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=Sl(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});}},um);}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>fm;if(o&&this.feed.loadRange){let a=await this.feed.load({...n,bars:Math.min(r,Cl)});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:mm});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<=Tl||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:Xe(e.symbol??"").provider??void 0,timeframe:e.timeframe,bars:e.bars,session:e.session,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.session!==void 0&&e.session!==t.session||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.session!==void 0&&(t.session=e.session),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=Cl,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||Mn("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=Ke(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=Ke(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=$i(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()*bm&&Date.now()-this.lastHealAt>Tl){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 zn(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 Xt(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 Xt(n.id,n.title,this);let r=Mn(e),i=this.registry.nextId("native"),o=r?.title??e,a=new Xt(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 gm();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,vm(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)ae(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)<pm||(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 gm(){return typeof requestAnimationFrame=="function"?new Promise(s=>requestAnimationFrame(()=>requestAnimationFrame(()=>s()))):new Promise(s=>setTimeout(s,0))}function vm(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(ae(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 Gn=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 rn=new Map;function ym(s){let e=Object.entries(s);for(let[t,n]of e)rn.set(t,n);return ()=>{for(let[t,n]of e)rn.get(t)===n&&rn.delete(t);}}function xm(...s){if(s.length===0)rn.clear();else for(let e of s)rn.delete(e);}function cs(){return Object.fromEntries(rn)}var Ui=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 Pl(s,e,t,n){return `${s}|${e}|${t}${n&&n!=="regular"?`|${n}`:""}`}function wm(s){return s.split("|")[1]??""}var Gi=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=wm(t);n!==e&&!this.retained.has(n)&&(this.series.delete(t),this.coveredFrom.delete(t));}}clear(){this.series.clear(),this.coveredFrom.clear();}},Yn=new Gi;function Ml(s,e,t){let{provider:n,ticker:r}=Xe(s);return Pl(n??"",r,e,t)}var Xn=1e4,Sm=Xn+1,Kn=class{constructor(e,t=Yn){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=Ml(t,e.timeframe??"60",e.session);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,Yi(l));return Ll(c,l[l.length-1]).slice(-i)}let a=await this.inner.load(e);return this.store.merge(n,Yi(a)),a}async loadRange(e,t){if(!this.inner.loadRange)return this.inner.load(e);let n=Ml(e.symbol??"TEST",e.timeframe??"60",e.session),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,Yi(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,Yi(l)),this.store.markCovered(n,c??t.from??l[0]?.time??0),l}async fetchRange(e,t){let n=zn(e.timeframe??"60"),r=Cm(t,n);if(r<=Sm){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:Xn;if(c<=0)break;let d=await this.inner.loadRange(e,{to:o,limit:Math.min(Xn,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-=Xn*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 Cm(s,e){if(s.limit!=null)return s.limit;if(s.from==null)return Xn;let t=Math.max(0,(s.to??Date.now())-s.from);return Math.ceil(t/e*1.1)+2}function Yi(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 Tm(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 Ot=class{constructor(e=Yn){this.registry=new Hi;this.primaryProvider=null;this.liveBars=[];this.symInfoCache=new Map;this.cache=new Kn(new us(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})}displayPrefix(e){let t=this.resolveSymbol(e);return t?this.registry.displayPrefixOf(t):null}canonicalSymbol(e){let t=this.resolveSymbol(e);return t?this.registry.canonicalSymbol(t):null}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(hs(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(Xi(e),{default:this.primaryProvider});return this.primaryProvider=t.provider,this.prefetchSymbolInfo(t),this.cache.load(ds(e,t))}symbolInfo(e){if(e.data&&e.data.length>0)return;let t=this.registry.resolve(Xi(e),{default:this.primaryProvider});return t?this.symInfoCache.get(hs(t)):void 0}prefetchSymbolInfo(e){let t=hs(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(Xi(e),{default:this.primaryProvider});return n?this.cache.loadRange(ds(e,n),t):[]}subscribe(e,t){if(e.data&&e.data.length>0)return this.synthesizeTicks(e,t);let n=this.registry.resolve(Xi(e),{default:this.primaryProvider});return n?this.cache.subscribe(ds(e,n),t):()=>{}}synthesizeTicks(e,t){if(this.liveBars.length===0)return ()=>{};let n=Tm(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 Xi(s){return s.symbol??""}function ds(s,e){return {...s,symbol:`${e.provider}:${e.ticker}`}}function hs(s){return `${s.provider}|${s.ticker}`}async function El(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 us=class{constructor(e){this.registry=e;}load(e){let{provider:t,ticker:n}=Xe(e.symbol??""),r=this.registry.get(t??"");return r?El(r,n,e.timeframe??"60",{limit:e.bars??500,session:e.session}):Promise.resolve([])}loadRange(e,t){let{provider:n,ticker:r}=Xe(e.symbol??""),i=this.registry.get(n??"");return i?El(i,r,e.timeframe??"60",{...t,session:e.session}):Promise.resolve([])}subscribe(e,t){let{provider:n,ticker:r}=Xe(e.symbol??""),i=this.registry.get(n??"");if(!i)return ()=>{};let o=e.timeframe??"60";if(i.subscribe)return i.subscribe(r,o,t,e.session?{session:e.session}:void 0);let a=false,l=null,c=async()=>{if(!a){try{let d=await i.getBars(r,o,{limit:2,session:e.session});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 jn=class{constructor(e){this.registry=e instanceof Ot?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}displayPrefix(e){return this.registry?.displayPrefix(e)??null}canonicalSymbol(e){return this.registry?.canonicalSymbol(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 qn=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 Ki(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=Ki(s);return t?`rgba(${t.r},${t.g},${t.b},${e})`:s}function kl(s,e,t){let n=Ki(s),r=Ki(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 Se(s){let e=Ki(s);return e?.2126*e.r+.7152*e.g+.0722*e.b<128:true}var ji={"--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-z-popover":"6000","--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 qi(s){let e=Se(s.background),t=r=>e?`rgba(255,255,255,${r})`:W(s.textColor,r+.02),n=kl(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":xe,"--vela-accent-bright":Kt,"--vela-highlight":_a,"--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 ce(s,e){let t=n=>{for(let r in n)s.style.setProperty(r,n[r]);};t(ji),t(qi(e));}function Ft(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;"),ce(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 Il(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}}function ue(s,e,t=document){if(typeof document>"u")return;let n=t instanceof Document?t.head:t;if(t.getElementById?.(s)??n.querySelector(`#${CSS.escape(s)}`))return;let r=document.createElement("style");r.id=s,r.textContent=e,n.appendChild(r);}function on(s,e=document){let t=e.createElement("span");t.className="vela-icon",t.setAttribute("aria-hidden","true");let n=Dr(s);return n&&(t.innerHTML=n),t}function Dl(s={}){let e=s.checked??false,t=s.disabled??false;return {get checked(){return e},disabled:t,size:s.size??"md",tone:s.tone??"bright",setChecked(n){e=n;},toggle(){return t||(e=!e,s.onChange?.(e)),e}}}var Rl="vela-ui-switch",Al=`
|
|
4
4
|
.vela-switch {
|
|
5
5
|
width: 20px;
|
|
6
6
|
height: 20px;
|
|
@@ -556,5 +556,5 @@ void main() {
|
|
|
556
556
|
[data-layout='mobile'] .vela-attribution .vela-attr-wordmark svg { height: 21px; }
|
|
557
557
|
[data-vela-layout='mobile'] .vela-attribution:hover .vela-attr-wordmark,
|
|
558
558
|
[data-layout='mobile'] .vela-attribution:hover .vela-attr-wordmark { transform: translateX(0); }
|
|
559
|
-
`;function Sg(s){let e=s.getElementById(Kd);e||(e=s.createElement("style"),e.id=Kd,s.head.appendChild(e)),e.textContent=wg;}function ea(s){return Se(s)?"#ffffff":"#000000"}function ta(s,e){let t=Se(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 jd(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=ea(t),n.innerHTML=e,n}function qd(s,e){Sg(s);let t=s.createElement("a");t.className="vela-attribution",t.href=xg,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"}),ta(t,e);let n=s.createElement("span");n.className="vela-attr-symbol",n.setAttribute("aria-hidden","true"),n.innerHTML=Yd;let r=s.createElement("span");return r.className="vela-attr-wordmark",r.innerHTML=Xd,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 Zd(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 na(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 Cg(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 _o(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||!Cg(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,na(s,p,m,u.width,u.height,Zd(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=Zd(h,p.width,p.height);Vo(h.backgroundColor)&&(s.globalAlpha=u,s.fillStyle=h.backgroundColor,na(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,na(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 Jd(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],w=x.volume;if(!(w!=null&&w>0))continue;let C=x.close>=x.open?"up":"down",T=x.high-x.low;if(T<=0){let k=ra(Math.floor((x.low-a)/d),c);h[k][C]+=w;continue}let P=ra(Math.floor((x.low-a)/d),c),E=ra(Math.floor((x.high-a)/d-1e-9),c);for(let k=P;k<=E;k+=1){let M=a+k*d,L=Math.min(x.high,M+d)-Math.max(x.low,M);L>0&&(h[k][C]+=w*L/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 ra(s,e){return s<0?0:s>=e?e-1:s}function Qd(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 No=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=Jd(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(),Qd(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 fe="price",Lg=8,Eg="rgba(0,0,0,0)",Ho=64,kg=56,th=26,gr=22,br=26,ia=24,Ig=5,Dg="0 2px 8px rgba(0,0,0,0.4)",Rg=12,sh=12,nh=Ho+sh,oa=gr+14,Ag=120,Og=2,rh=6,Fg=70,Tn=80,Bg=110,sa=90,Vg=130,_g=.02,Ng=.004,Hg=.2,zg=4,vr=class{constructor(e){this.capabilities=gc;this.surfaceBackground=Ne.background;this.surfaceTextColor=Ne.textColor;this.toolbarGutter=0;this.mountContainer=null;this.userDrawings=null;this.volumeRenderer=new Bo;this.extLayers=[];this.attributionEl=null;this.attributionEnabled=true;this.attributionHtml=null;this.vpvrRenderer=new No;this.resizeObserver=null;this.dprMedia=null;this.coords=new yo;this.scene=new uo;this.backendMode="auto";this.glowAmount=0;this.chrome=new Po;this.crosshairLayer=new Mo;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=Ho;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=oa;this.scrollBtnRightPx=nh;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-br/2,r=t.height-this.scrollBtnBottomPx-br/2,i=Math.hypot(e.clientX-t.left-n,e.clientY-t.top-r)<=Ag;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=Ps(e.priceStyle),this.scene.candleOverride=lo(e.priceStyle,this.scene.style.chartTypes)),this.theme=this.deriveTheme(Ne);}applyFeature(e,t){switch(e){case "logScale":if(t&&typeof t=="object"){let n=t;this.setPaneLog(n.pane??fe,!!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=Gg(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??fe,ih(n.mode));return}this.scene.scaleMode=ih(t);break;case "invertScale":if(t&&typeof t=="object"){let n=t;this.setPaneInvert(n.pane??fe,!!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(Yg(t)?t:"candles");break;case "priceBaseline":this.scene.baselineValue=t==null?null:Number(t);break;case "tradeMarkers":this.scene.tradeMarkers=Vc(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(fe);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:Ts,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??Eg}})(),baseline:(()=>{let r=e.baseline.topLineColor??pn,i=e.baseline.bottomLineColor??mn;return {topLineColor:r,bottomLineColor:i,topFillColor:e.baseline.topFillColor??W(r,Qe),topFillColor2:e.baseline.topFillColor2??W(r,et),bottomFillColor:e.baseline.bottomFillColor??W(i,Qe),bottomFillColor2:e.baseline.bottomFillColor2??W(i,et),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=kc(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&&Se(t.layout.textColor)===Se(t.layout.background)){let d=Se(t.layout.background)?Ne:Un;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=lo(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&&(ce(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 dr(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=re("gear",14),Object.assign(e.style,{position:"absolute",bottom:`${gr+10}px`,right:`${Ho+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 dr(this.dialogHost??this.plot,this.theme),this.settingsDialog.setLayoutMode(this.layoutMode)),this.toggleSettingsDialog(e);}syncThemeControl(){this.settingsDialog?.setThemeControl(Se(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(Ec(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:`${oa}px`,right:`${nh}px`,zIndex:"6",width:`${br}px`,height:`${br}px`,boxSizing:"border-box",display:"none",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:`${Ig}px`,border:`1px solid ${this.theme.borderColor}`,boxShadow:Dg,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 re("chevrons-right",Rg)}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(rh);}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"&&_o(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]")??[])_o(t,l,r);for(let l of i)l.getAttribute("data-vela-screenshot")!=="under"&&_o(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:Se(this.surfaceBackground)?Ne.borderColor:Un.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"}),ce(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=Qs().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(vo()),this.scene.ensurePane(fe,"price",0,3),this.scheduler=new xo(i=>this.renderFrame(i)),this.animator=new wo(i=>this.animTick(i)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.input=new So({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 Fo(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===fe?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=`${ia}px`,this.scrollButton.style.height=`${ia}px`)),this.keyboard=new Co({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 no(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 ro(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")&&vc()){let n=this.makeDataCanvas(),r=new go;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 cr;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 cr;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&&ce(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=Xg(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=Pe(this.liveEaseHigh,t.high,e,sa),i=Pe(this.liveEaseLow,t.low,e,sa),o=Pe(this.liveEaseClose,t.close,e,sa),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!==fe&&(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=Ho+kg*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=$g(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));}Wg(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=Ps(e),this.scene.candleOverride=lo(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"?ia:br;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=tt(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:tt(e),rightOffset:t};let i=Math.min(Og,n),o=this.coords.spacingScale,a=Math.min(1e3,r/(i*o)),l=Math.max(.5,Math.min(a,r/((n+rh)*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=tt(Pe(n,o,e,Fg)),r=this.anchoredRightOffset(n),i=true):n!==o&&(n=o,r=this.anchoredRightOffset(n));let a=_g/Math.max(1e-6,n*this.coords.spacingScale);if(Math.abs(this.panVelocity)>a&&(r+=this.panVelocity*e,this.panVelocity*=Math.exp(-e/Bg),Math.abs(this.panVelocity)<=a?this.panVelocity=0:i=true),this.scrollTargetRO!=null){let c=this.scrollTargetRO,d=Pe(r,c,e,Vg);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=Pe(Math.log(i.min),c,e,Tn),p=Pe(Math.log(i.max),d,e,Tn);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=Pe(i.min,r.min,e,Tn),l=Pe(i.max,r.max,e,Tn);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=Pe(i.min,r.min,e,Tn),l=Pe(i.max,r.max,e,Tn);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(ae(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,zd(n,Math.exp(e*Ng)));}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,$d(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)<=zg)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=Wd(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=tt(t.barSpacing*Math.exp(e*Hg));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(Ug(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?ah(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?ao(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?oh(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(ae(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:oh(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||(_s(e)?(this.computeScales(),this.paintData()):Jc(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()),!_s(e)&&this.paintedData&&this.repaintCursorLayers(),this.updateLegendValues());}repaintCursorLayers(){let e=this.scene.panes.get(fe);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(fe);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=Gd(l,c.instance.modulateBase?.(d)??null),this.animZoom&&c.instance.animating?.()&&this.animator.start();}l&&(l.candleBodyScale!=null&&(this.backend.candleBodyScale=aa(l.candleBodyScale)||.01),l.candleBodyAlpha!=null&&(this.backend.candleBodyAlpha=aa(l.candleBodyAlpha)*this.candleBodyAlpha),l.gridAlpha!=null&&(this.backend.gridAlpha=aa(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 Vd(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!==fe)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)>Lg)return e}return l}computeScales(){let e=this.coords.barCount;if(e===0)return;let t=this.coords.visibleLogicalRange(),n=Math.max(0,Math.floor(t.from)),r=Math.min(e-1,Math.ceil(t.to));if(r<n)return;this.scene.percentBaseline=this.bars[n]?.close??0;let i=this.scene.orderedPanes(),o=i.find(l=>l.kind==="price")??null;this.chrome.prepare(this.scene,this.coords,this.theme);let a=this.animator.active;for(let l of i){if(l.manualScale){l.scaleTarget=l.manualScale,l.scale={...l.manualScale},l.initialized=true;continue}let d=this.scene.indicatorsForPane(l.id).filter(p=>p.ownScale!==true),h=this.chrome.paneDrawingsRange(d,this.scene,l===o,t),u=l.kind==="price"&&!this.scene.candlesHidden;if(l.scaleTarget=js(d,this.bars,u,n,r,h,Rs(this.scene,l),p=>this.scene.offsetOf(p)),l.percentBaseline=l.kind==="price"?this.bars[n]?.close??0:this.firstVisibleValue(d,n),l.axisFormat=void 0,this.volumeOwnsPane(l,d)){let p=this.maxVisibleVolume(n,r);p>0&&(l.scaleTarget={min:0,max:p/qs},l.axisFormat="volume");}if(l===o&&this.scene.tradeMarkers.visible&&l.bounds.height>0){let p=this.tradesScaleHints(t);if(p){let m=l.scaleTarget,f={...m,min:Math.min(m.min,p.min),max:Math.max(m.max,p.max)};l.scaleTarget=Hd(f,l.bounds.height,p.abovePx,p.belowPx);}}(!a||!l.initialized)&&(l.scale={...l.scaleTarget},l.initialized=true);for(let p of this.scene.ownScaleIndicatorsForPane(l.id)){let m=this.scene.ensureIndicatorScale(p.id,l.scaleTarget);if(m.manualScale){m.scaleTarget=m.manualScale,m.scale={...m.manualScale},m.initialized=true;continue}let f=this.chrome.paneDrawingsRange([p],this.scene,false,t);m.scaleTarget=js([p],this.bars,false,n,r,f,false,b=>this.scene.offsetOf(b)),(!a||!m.initialized)&&(m.scale={...m.scaleTarget},m.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=zc(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??fe)??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:Ds(this.scene,e),log:Rs(this.scene,e),invert:As(this.scene,e)}))}setPaneScaleMode(e,t){if(e===fe)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===fe){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===fe)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=As(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(ae(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 io(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*th,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?th: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=oa+Math.max(0,e-r),this.scrollBtnRightPx=this.rightAxisW+sh,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+gr,t=this.scene.panes.get(fe),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?jd(document,this.attributionHtml,this.theme.background):qd(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:`${gr+10+Math.max(0,e-r)}px`});}refreshAttributionColor(){this.attributionEl&&(this.attributionHtml!==null?this.attributionEl.style.color=ea(this.theme.background):ta(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-gr),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 $g(s,e){for(let t of s.series){let n=t.kind==="candle"||t.kind==="bar"?t.bars:ae(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 Wg(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"&&ae(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 ah(s,e){let t=po(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 Ug(s,e){let{date:t,time:n}=ah(s,e);return `${t} ${n}`}function Gg(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 aa(s){return Math.max(0,Math.min(1,s))}function Yg(s){return typeof s=="string"&&fn().includes(s)}function ih(s){return s==="percent"||s==="indexed"?s:"price"}function oh(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 Xg(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 la(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 lh(s){let e=new Array(s.length),t;for(let n=0;n<s.length;n+=1)t=la(s[n],t),e[n]=t;return e}var Kg={full:lh,next:la};function ch(){as({id:"heikinashi",label:"Heikin Ashi",barTransform:Kg});}var ca=q,da=X,ha=20;function jg(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function dh(s,e){return typeof s=="string"&&s!==""?s:e}function zo(s){return {upColor:dh(s.upColor,ca),downColor:dh(s.downColor,da),heightFrac:Math.min(.5,Math.max(.05,jg(s.heightPct,ha)/100))}}var ua=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(zo(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData(zo(e));}suspend(){}resume(){this.ctx.pushData(zo(this.inputs));}stop(){}},hh={type:"volume",title:"Volume",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"upColor",title:"Up color",type:"color",defval:ca},{key:"downColor",title:"Down color",type:"color",defval:da},{key:"heightPct",title:"Height %",type:"int",defval:ha,min:5,max:50,step:1,tooltip:"Pane height the tallest visible bar occupies"}],defaultInputs:()=>({upColor:ca,downColor:da,heightPct:ha}),create:()=>new ua};function pa(){Yt(hh);}var fa=24,ba=30,ga=xe,va=X,ya=70;function ma(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function uh(s,e){return typeof s=="string"&&s!==""?s:e}function $o(s){return {rows:Math.round(Math.min(400,Math.max(2,ma(s.rows,fa)))),widthFrac:Math.min(.9,Math.max(.05,ma(s.widthPct,ba)/100)),upColor:uh(s.upColor,ga),downColor:uh(s.downColor,va),showPoc:s.showPoc!==false,valueAreaFrac:Math.min(1,Math.max(0,ma(s.valueAreaPct,ya)/100))}}var xa=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData($o(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData($o(e));}suspend(){}resume(){this.ctx.pushData($o(this.inputs));}stop(){}},ph={type:"vpvr",title:"Visible Range Volume Profile",shortTitle:"VRVP",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"rows",title:"Rows",type:"int",defval:fa,min:2,max:400,step:1},{key:"widthPct",title:"Width %",type:"int",defval:ba,min:5,max:90,step:1,tooltip:"Pane width the largest row occupies"},{key:"upColor",title:"Up color",type:"color",defval:ga},{key:"downColor",title:"Down color",type:"color",defval:va},{key:"showPoc",title:"Point of control",type:"bool",defval:true},{key:"valueAreaPct",title:"Value area %",type:"int",defval:ya,min:0,max:100,step:1}],defaultInputs:()=>({rows:fa,widthPct:ba,upColor:ga,downColor:va,showPoc:true,valueAreaPct:ya}),create:()=>new xa};function wa(){Yt(ph);}var Sa=class{constructor(e,t={},n={}){ch(),pa(),wa();let r=qg(e),i=nn(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??vr;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 Ot,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 Gn(d),this.dataControl=new jn(u),this.orchestrator=new Wi(r,d,u,h,p,this.dataControl);let m=cs();Object.keys(m).length>0&&this.rendererControl.set(m),this.panesControl=new Ui(this.orchestrator),this.drawingsControl=new qn(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(nn(e)),this}destroy(){this.orchestrator.destroy();}};function qg(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 yr=new Map,xr=new Map,wr=new Map;function Zg(s){return xr.set(s.id,s),()=>{xr.get(s.id)===s&&xr.delete(s.id);}}function Jg(s){xr.delete(s);}function Qg(){return [...xr.values()]}var mh=100;function ev(s){return wr.set(s.id,s),()=>{wr.get(s.id)===s&&wr.delete(s.id);}}function tv(s){wr.delete(s);}function nv(){return [...wr.values()].sort((s,e)=>(s.order??mh)-(e.order??mh))}function rv(s){return yr.set(s.id,s),()=>{yr.get(s.id)===s&&yr.delete(s.id);}}function iv(s){yr.delete(s);}function ov(s,e){let t=[...yr.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 Sr=new Map;function sv(s){return Sr.set(s.id,s),()=>{Sr.get(s.id)===s&&Sr.delete(s.id);}}function av(s){Sr.delete(s);}function lv(){return [...Sr.values()].sort((s,e)=>(s.order??0)-(e.order??0))}var Cr=new Map;function cv(s,e){return Cr.set(s,e),()=>{Cr.get(s)===e&&Cr.delete(s);}}function dv(s){Cr.delete(s);}function hv(s){return {...Object.fromEntries(Cr),...s}}var fh=280,Ca=200,bh=640;function uv(s,e=Ca,t=bh){let n=Number.isFinite(e)&&e>0?e:Ca,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 gh(s){let e=s.title.trim().toLowerCase().replace(/\s+/g,"-");return `${s.instanceId}:${s.kind}:${e}#${s.ordinal}`}var vh="https://api.binance.com/api/v3",pv="https://api.binance.us/api/v3",Ta="https://fapi.binance.com/fapi/v1",mv="wss://stream.binance.com:9443",fv="wss://stream.binance.us:9443",bv="wss://fstream.binance.com";var yh={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"},xh={"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"},gv=[1,3,5,15,30,60,120,240,360,480,720],vv={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h"},yv=["1","3","5","15","30","45","60","120","180","240","D","W","M"];function wh(s){return xh[s]??xh[s.toLowerCase()]??s}function Pa(s){let e=s.trim().toUpperCase();return e.endsWith(".P")?{apiSymbol:e.slice(0,-2),isFutures:true}:{apiSymbol:e,isFutures:false}}function Sh(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 xv(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 wv(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 Sv(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 Cv(s){return gv.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}var Wo=class{constructor(){this.spotBaseUrl=null;this.spotBaseProbe=null;this.symbolsPromise=null;}info(){return {name:"binance",displayName:"Binance",requiresApiKey:false,supportedTimeframes:yv,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let{apiSymbol:r,isFutures:i}=Pa(e),o=i?Ta:await this.spotBase(),a=wh(t),l=yh[a];if(l)return wv(Sh(await this.fetchKlines(o,r,l,n)));let c=/^\d+$/.test(a)?parseInt(a,10):null,d=c!=null?Cv(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=Sh(await this.fetchKlines(o,r,vv[d],u)),m=Sv(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}=Pa(e),r=n?Ta: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}=Pa(e),o=yh[wh(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?bv: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(xv(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")?fv:mv}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(`${Ta}/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 [vh,pv])try{if((await fetch(`${e}/ping`,{signal:AbortSignal.timeout(5e3)})).ok)return this.spotBaseUrl=e}catch{}return vh}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 Tv="https://api.hyperliquid.xyz/info",Pv="wss://api.hyperliquid.xyz/ws";var Ch={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"},Th={"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"},Mv=[1,3,5,15,30,60,120,240,480,720],Lv={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h"},Ev=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],Ph={D:864e5,W:6048e5,M:2592e6};function kv(s){if(Ph[s])return Ph[s];let e=parseInt(s,10);return Number.isFinite(e)&&e>0?e*6e4:36e5}function Mh(s){return Th[s]??Th[s.toLowerCase()]??s}function Ma(s){let e=s.trim();return e.includes("/")?e:e.toUpperCase()}function La(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 Iv(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 Dv(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 Rv(s){return Mv.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}var Uo=class{constructor(){this.metaPromise=null;this.spotMetaPromise=null;this.symbolsPromise=null;}info(){return {name:"hyperliquid",displayName:"Hyperliquid",requiresApiKey:false,supportedTimeframes:Ev,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let r=Ma(e),i=Mh(t),o=Ch[i];if(o)return Iv((await this.fetchCandles(r,o,kv(i),n)).map(La));let a=/^\d+$/.test(i)?parseInt(i,10):null,l=a!=null?Rv(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,Lv[l],l*6e4,d)).map(La),u=Dv(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=Ma(e),r=(await this.fetchMeta().catch(()=>null))?.universe?.find(i=>i.name===t);if(r){let i=Eh(Math.max(0,6-(r.szDecimals??2)));return Lh(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=Eh(Math.max(0,8-(a?.szDecimals??2)));return Lh(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=Ma(e),i=Ch[Mh(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(Pv),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(La(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(Tv,{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 Lh(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 Eh(s){return Math.pow(10,-s)}var Av={now:()=>Date.now(),delay:s=>new Promise(e=>setTimeout(e,s))},Go=class{constructor(e,t,n=Av){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 Ea="https://api.exchange.coinbase.com",Ov="wss://ws-feed.exchange.coinbase.com",Fv={Accept:"application/json"},Bv=15e3,Vv=2e3,_v=5e3,Yo=300,Nv=4,Hv=120,zv=4,$v=600,Wv=400;function Uv(s,e){let t=Number(s.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t*1e3:e}var kh={1:60,5:300,15:900,60:3600,360:21600,D:86400},Ih={"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"},Gv=[1,5,15,60,360,1440],Yv={1:60,5:300,15:900,60:3600,360:21600,1440:86400},Xv=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],ka=864e5;function Dh(s){return Ih[s]??Ih[s.toLowerCase()]??s}function Ia(s){return s.trim().toUpperCase()}function Kv(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 jv(s,e){return Rh(s,t=>Math.floor(t/e)*e)}function qv(s,e){return Rh(s,e==="W"?Zv:Jv)}function Rh(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 Zv(s){let e=new Date(s),t=(e.getUTCDay()+6)%7;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()-t)}function Jv(s){let e=new Date(s);return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)}function Qv(s){return Gv.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}function Ra(s,e){return e!=null&&s.length>e?s.slice(-e):s}var Xo=class{constructor(){this.symbolsPromise=null;this.gate=new Go(Nv,Hv);}info(){return {name:"coinbase",displayName:"Coinbase",requiresApiKey:false,supportedTimeframes:Xv,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let r=Ia(e),i=Dh(t),o=kh[i];if(o)return Da(await this.fetchCandles(r,o,n));if(i==="W"||i==="M"){let u=i==="W"?7*ka:31*ka,p=n.from!=null?n:{...n,limit:n.limit!=null?Math.ceil(n.limit*u/ka)+31:void 0},m=await this.fetchCandles(r,86400,p);return Ra(qv(m,i),n.limit)}let a=/^\d+$/.test(i)?parseInt(i,10):null,l=a!=null?Qv(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,Yv[l],d);return Ra(jv(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=Ia(e),n=await this.json(`${Ea}/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=kh[Dh(t)];return r&&typeof WebSocket<"u"?this.streamTicker(e,t,r,n):this.pollBars(e,t,n)}async fetchProducts(){let e=await this.json(`${Ea}/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/Yo)+4;for(;a>0&&c-- >0;){let d=Math.min(a,Yo),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 Ra(Da(o),n)}async paginateForward(e,t,n,r,i){let o=t*1e3,a=[],l=n,c=Math.ceil((r-n)/(Yo*o))+4;for(;l<r&&c-- >0;){let h=Math.min(l+Yo*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(`${Ea}/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(Kv).sort((a,l)=>a.time-l.time)}streamTicker(e,t,n,r){let i=Ia(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 P=T[T.length-1];m=m&&m.time===P.time?{...P,high:Math.max(P.high,m.high),low:Math.min(P.low,m.low),close:m.close}:{...P},g();}catch{}},y=(C,T)=>{let P=Number(C);if(!Number.isFinite(P))return;let E=a(T);!m||E>m.time?(m={time:E,open:P,high:P,low:P,close:P,volume:0},g(),v(false)):E===m.time&&(m={...m,close:P,high:Math.max(m.high,P),low:Math.min(m.low,P)},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);}},w=()=>{l||p||(c=new WebSocket(Ov),h=setTimeout(x,Bv),c.onopen=()=>{try{c?.send(JSON.stringify({type:"subscribe",product_ids:[i],channels:["ticker"]}));}catch{}v(false),u=setInterval(()=>{v(false);},_v);},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(w,Vv));},c.onerror=()=>{try{c?.close();}catch{}});};return w(),()=>{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:Fv}));if(n.status===429&&t<zv){let r=$v*2**t+Math.random()*Wv;this.gate.pauseFor(Math.max(Uv(n,0),r));continue}if(!n.ok)throw new Error(`Coinbase HTTP ${n.status} for ${e}`);return n}}};
|
|
559
|
+
`;function Sg(s){let e=s.getElementById(Kd);e||(e=s.createElement("style"),e.id=Kd,s.head.appendChild(e)),e.textContent=wg;}function ea(s){return Se(s)?"#ffffff":"#000000"}function ta(s,e){let t=Se(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 jd(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=ea(t),n.innerHTML=e,n}function qd(s,e){Sg(s);let t=s.createElement("a");t.className="vela-attribution",t.href=xg,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"}),ta(t,e);let n=s.createElement("span");n.className="vela-attr-symbol",n.setAttribute("aria-hidden","true"),n.innerHTML=Yd;let r=s.createElement("span");return r.className="vela-attr-wordmark",r.innerHTML=Xd,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 Zd(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 na(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 Cg(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 _o(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||!Cg(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,na(s,p,m,u.width,u.height,Zd(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=Zd(h,p.width,p.height);Vo(h.backgroundColor)&&(s.globalAlpha=u,s.fillStyle=h.backgroundColor,na(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,na(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 Jd(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],w=x.volume;if(!(w!=null&&w>0))continue;let C=x.close>=x.open?"up":"down",T=x.high-x.low;if(T<=0){let k=ra(Math.floor((x.low-a)/d),c);h[k][C]+=w;continue}let P=ra(Math.floor((x.low-a)/d),c),E=ra(Math.floor((x.high-a)/d-1e-9),c);for(let k=P;k<=E;k+=1){let M=a+k*d,L=Math.min(x.high,M+d)-Math.max(x.low,M);L>0&&(h[k][C]+=w*L/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 ra(s,e){return s<0?0:s>=e?e-1:s}function Qd(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 No=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=Jd(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(),Qd(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 fe="price",Lg=8,Eg="rgba(0,0,0,0)",Ho=64,kg=56,th=26,gr=22,br=26,ia=24,Ig=5,Dg="0 2px 8px rgba(0,0,0,0.4)",Rg=12,sh=12,nh=Ho+sh,oa=gr+14,Ag=120,Og=2,rh=6,Fg=70,Tn=80,Bg=110,sa=90,Vg=130,_g=.02,Ng=.004,Hg=.2,zg=4,vr=class{constructor(e){this.capabilities=gc;this.surfaceBackground=Ne.background;this.surfaceTextColor=Ne.textColor;this.toolbarGutter=0;this.mountContainer=null;this.userDrawings=null;this.volumeRenderer=new Bo;this.extLayers=[];this.attributionEl=null;this.attributionEnabled=true;this.attributionHtml=null;this.vpvrRenderer=new No;this.resizeObserver=null;this.dprMedia=null;this.coords=new yo;this.scene=new uo;this.backendMode="auto";this.glowAmount=0;this.chrome=new Po;this.crosshairLayer=new Mo;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=Ho;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=oa;this.scrollBtnRightPx=nh;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-br/2,r=t.height-this.scrollBtnBottomPx-br/2,i=Math.hypot(e.clientX-t.left-n,e.clientY-t.top-r)<=Ag;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=Ps(e.priceStyle),this.scene.candleOverride=lo(e.priceStyle,this.scene.style.chartTypes)),this.theme=this.deriveTheme(Ne);}applyFeature(e,t){switch(e){case "logScale":if(t&&typeof t=="object"){let n=t;this.setPaneLog(n.pane??fe,!!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=Gg(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??fe,ih(n.mode));return}this.scene.scaleMode=ih(t);break;case "invertScale":if(t&&typeof t=="object"){let n=t;this.setPaneInvert(n.pane??fe,!!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(Yg(t)?t:"candles");break;case "priceBaseline":this.scene.baselineValue=t==null?null:Number(t);break;case "tradeMarkers":this.scene.tradeMarkers=Vc(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(fe);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:Ts,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??Eg}})(),baseline:(()=>{let r=e.baseline.topLineColor??pn,i=e.baseline.bottomLineColor??mn;return {topLineColor:r,bottomLineColor:i,topFillColor:e.baseline.topFillColor??W(r,Qe),topFillColor2:e.baseline.topFillColor2??W(r,et),bottomFillColor:e.baseline.bottomFillColor??W(i,Qe),bottomFillColor2:e.baseline.bottomFillColor2??W(i,et),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=kc(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&&Se(t.layout.textColor)===Se(t.layout.background)){let d=Se(t.layout.background)?Ne:Un;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=lo(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&&(ce(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 dr(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=re("gear",14),Object.assign(e.style,{position:"absolute",bottom:`${gr+10}px`,right:`${Ho+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 dr(this.dialogHost??this.plot,this.theme),this.settingsDialog.setLayoutMode(this.layoutMode)),this.toggleSettingsDialog(e);}syncThemeControl(){this.settingsDialog?.setThemeControl(Se(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(Ec(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:`${oa}px`,right:`${nh}px`,zIndex:"6",width:`${br}px`,height:`${br}px`,boxSizing:"border-box",display:"none",alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:`${Ig}px`,border:`1px solid ${this.theme.borderColor}`,boxShadow:Dg,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 re("chevrons-right",Rg)}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(rh);}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"&&_o(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]")??[])_o(t,l,r);for(let l of i)l.getAttribute("data-vela-screenshot")!=="under"&&_o(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:Se(this.surfaceBackground)?Ne.borderColor:Un.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"}),ce(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=Qs().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(vo()),this.scene.ensurePane(fe,"price",0,3),this.scheduler=new xo(i=>this.renderFrame(i)),this.animator=new wo(i=>this.animTick(i)),this.targetBarSpacing=this.coords.getViewport().barSpacing,this.input=new So({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 Fo(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===fe?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=`${ia}px`,this.scrollButton.style.height=`${ia}px`)),this.keyboard=new Co({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 no(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 ro(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")&&vc()){let n=this.makeDataCanvas(),r=new go;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 cr;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 cr;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&&ce(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=Xg(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=Pe(this.liveEaseHigh,t.high,e,sa),i=Pe(this.liveEaseLow,t.low,e,sa),o=Pe(this.liveEaseClose,t.close,e,sa),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!==fe&&(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=Ho+kg*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=$g(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));}Wg(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=Ps(e),this.scene.candleOverride=lo(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"?ia:br;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=tt(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:tt(e),rightOffset:t};let i=Math.min(Og,n),o=this.coords.spacingScale,a=Math.min(1e3,r/(i*o)),l=Math.max(.5,Math.min(a,r/((n+rh)*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=tt(Pe(n,o,e,Fg)),r=this.anchoredRightOffset(n),i=true):n!==o&&(n=o,r=this.anchoredRightOffset(n));let a=_g/Math.max(1e-6,n*this.coords.spacingScale);if(Math.abs(this.panVelocity)>a&&(r+=this.panVelocity*e,this.panVelocity*=Math.exp(-e/Bg),Math.abs(this.panVelocity)<=a?this.panVelocity=0:i=true),this.scrollTargetRO!=null){let c=this.scrollTargetRO,d=Pe(r,c,e,Vg);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=Pe(Math.log(i.min),c,e,Tn),p=Pe(Math.log(i.max),d,e,Tn);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=Pe(i.min,r.min,e,Tn),l=Pe(i.max,r.max,e,Tn);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=Pe(i.min,r.min,e,Tn),l=Pe(i.max,r.max,e,Tn);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(ae(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,zd(n,Math.exp(e*Ng)));}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,$d(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)<=zg)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=Wd(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=tt(t.barSpacing*Math.exp(e*Hg));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(Ug(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?ah(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?ao(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?oh(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(ae(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:oh(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||(_s(e)?(this.computeScales(),this.paintData()):Jc(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()),!_s(e)&&this.paintedData&&this.repaintCursorLayers(),this.updateLegendValues());}repaintCursorLayers(){let e=this.scene.panes.get(fe);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(fe);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=Gd(l,c.instance.modulateBase?.(d)??null),this.animZoom&&c.instance.animating?.()&&this.animator.start();}l&&(l.candleBodyScale!=null&&(this.backend.candleBodyScale=aa(l.candleBodyScale)||.01),l.candleBodyAlpha!=null&&(this.backend.candleBodyAlpha=aa(l.candleBodyAlpha)*this.candleBodyAlpha),l.gridAlpha!=null&&(this.backend.gridAlpha=aa(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 Vd(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!==fe)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)>Lg)return e}return l}computeScales(){let e=this.coords.barCount;if(e===0)return;let t=this.coords.visibleLogicalRange(),n=Math.max(0,Math.floor(t.from)),r=Math.min(e-1,Math.ceil(t.to));if(r<n)return;this.scene.percentBaseline=this.bars[n]?.close??0;let i=this.scene.orderedPanes(),o=i.find(l=>l.kind==="price")??null;this.chrome.prepare(this.scene,this.coords,this.theme);let a=this.animator.active;for(let l of i){if(l.manualScale){l.scaleTarget=l.manualScale,l.scale={...l.manualScale},l.initialized=true;continue}let d=this.scene.indicatorsForPane(l.id).filter(p=>p.ownScale!==true),h=this.chrome.paneDrawingsRange(d,this.scene,l===o,t),u=l.kind==="price"&&!this.scene.candlesHidden;if(l.scaleTarget=js(d,this.bars,u,n,r,h,Rs(this.scene,l),p=>this.scene.offsetOf(p)),l.percentBaseline=l.kind==="price"?this.bars[n]?.close??0:this.firstVisibleValue(d,n),l.axisFormat=void 0,this.volumeOwnsPane(l,d)){let p=this.maxVisibleVolume(n,r);p>0&&(l.scaleTarget={min:0,max:p/qs},l.axisFormat="volume");}if(l===o&&this.scene.tradeMarkers.visible&&l.bounds.height>0){let p=this.tradesScaleHints(t);if(p){let m=l.scaleTarget,f={...m,min:Math.min(m.min,p.min),max:Math.max(m.max,p.max)};l.scaleTarget=Hd(f,l.bounds.height,p.abovePx,p.belowPx);}}(!a||!l.initialized)&&(l.scale={...l.scaleTarget},l.initialized=true);for(let p of this.scene.ownScaleIndicatorsForPane(l.id)){let m=this.scene.ensureIndicatorScale(p.id,l.scaleTarget);if(m.manualScale){m.scaleTarget=m.manualScale,m.scale={...m.manualScale},m.initialized=true;continue}let f=this.chrome.paneDrawingsRange([p],this.scene,false,t);m.scaleTarget=js([p],this.bars,false,n,r,f,false,b=>this.scene.offsetOf(b)),(!a||!m.initialized)&&(m.scale={...m.scaleTarget},m.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=zc(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??fe)??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:Ds(this.scene,e),log:Rs(this.scene,e),invert:As(this.scene,e)}))}setPaneScaleMode(e,t){if(e===fe)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===fe){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===fe)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=As(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(ae(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 io(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*th,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?th: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=oa+Math.max(0,e-r),this.scrollBtnRightPx=this.rightAxisW+sh,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+gr,t=this.scene.panes.get(fe),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?jd(document,this.attributionHtml,this.theme.background):qd(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:`${gr+10+Math.max(0,e-r)}px`});}refreshAttributionColor(){this.attributionEl&&(this.attributionHtml!==null?this.attributionEl.style.color=ea(this.theme.background):ta(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-gr),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 $g(s,e){for(let t of s.series){let n=t.kind==="candle"||t.kind==="bar"?t.bars:ae(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 Wg(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"&&ae(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 ah(s,e){let t=po(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 Ug(s,e){let{date:t,time:n}=ah(s,e);return `${t} ${n}`}function Gg(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 aa(s){return Math.max(0,Math.min(1,s))}function Yg(s){return typeof s=="string"&&fn().includes(s)}function ih(s){return s==="percent"||s==="indexed"?s:"price"}function oh(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 Xg(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 la(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 lh(s){let e=new Array(s.length),t;for(let n=0;n<s.length;n+=1)t=la(s[n],t),e[n]=t;return e}var Kg={full:lh,next:la};function ch(){as({id:"heikinashi",label:"Heikin Ashi",barTransform:Kg});}var ca=q,da=X,ha=20;function jg(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function dh(s,e){return typeof s=="string"&&s!==""?s:e}function zo(s){return {upColor:dh(s.upColor,ca),downColor:dh(s.downColor,da),heightFrac:Math.min(.5,Math.max(.05,jg(s.heightPct,ha)/100))}}var ua=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData(zo(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData(zo(e));}suspend(){}resume(){this.ctx.pushData(zo(this.inputs));}stop(){}},hh={type:"volume",title:"Volume",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"upColor",title:"Up color",type:"color",defval:ca},{key:"downColor",title:"Down color",type:"color",defval:da},{key:"heightPct",title:"Height %",type:"int",defval:ha,min:5,max:50,step:1,tooltip:"Pane height the tallest visible bar occupies"}],defaultInputs:()=>({upColor:ca,downColor:da,heightPct:ha}),create:()=>new ua};function pa(){Yt(hh);}var fa=24,ba=30,ga=xe,va=X,ya=70;function ma(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function uh(s,e){return typeof s=="string"&&s!==""?s:e}function $o(s){return {rows:Math.round(Math.min(400,Math.max(2,ma(s.rows,fa)))),widthFrac:Math.min(.9,Math.max(.05,ma(s.widthPct,ba)/100)),upColor:uh(s.upColor,ga),downColor:uh(s.downColor,va),showPoc:s.showPoc!==false,valueAreaFrac:Math.min(1,Math.max(0,ma(s.valueAreaPct,ya)/100))}}var xa=class{constructor(){this.inputs={};}start(e,t){this.ctx=e,this.inputs=t,e.emit({}),e.pushData($o(t));}onBars(){}onViewport(){}setInputs(e){this.inputs=e,this.ctx.pushData($o(e));}suspend(){}resume(){this.ctx.pushData($o(this.inputs));}stop(){}},ph={type:"vpvr",title:"Visible Range Volume Profile",shortTitle:"VRVP",paneHint:"price",overlay:true,inputsSchema:()=>[{key:"rows",title:"Rows",type:"int",defval:fa,min:2,max:400,step:1},{key:"widthPct",title:"Width %",type:"int",defval:ba,min:5,max:90,step:1,tooltip:"Pane width the largest row occupies"},{key:"upColor",title:"Up color",type:"color",defval:ga},{key:"downColor",title:"Down color",type:"color",defval:va},{key:"showPoc",title:"Point of control",type:"bool",defval:true},{key:"valueAreaPct",title:"Value area %",type:"int",defval:ya,min:0,max:100,step:1}],defaultInputs:()=>({rows:fa,widthPct:ba,upColor:ga,downColor:va,showPoc:true,valueAreaPct:ya}),create:()=>new xa};function wa(){Yt(ph);}var Sa=class{constructor(e,t={},n={}){ch(),pa(),wa();let r=qg(e),i=nn(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??vr;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 Ot,p={market:{symbol:t.symbol,timeframe:t.timeframe,bars:t.bars,session:t.session,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 Gn(d),this.dataControl=new jn(u),this.orchestrator=new Wi(r,d,u,h,p,this.dataControl);let m=cs();Object.keys(m).length>0&&this.rendererControl.set(m),this.panesControl=new Ui(this.orchestrator),this.drawingsControl=new qn(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(nn(e)),this}destroy(){this.orchestrator.destroy();}};function qg(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 yr=new Map,xr=new Map,wr=new Map;function Zg(s){return xr.set(s.id,s),()=>{xr.get(s.id)===s&&xr.delete(s.id);}}function Jg(s){xr.delete(s);}function Qg(){return [...xr.values()]}var mh=100;function ev(s){return wr.set(s.id,s),()=>{wr.get(s.id)===s&&wr.delete(s.id);}}function tv(s){wr.delete(s);}function nv(){return [...wr.values()].sort((s,e)=>(s.order??mh)-(e.order??mh))}function rv(s){return yr.set(s.id,s),()=>{yr.get(s.id)===s&&yr.delete(s.id);}}function iv(s){yr.delete(s);}function ov(s,e){let t=[...yr.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 Sr=new Map;function sv(s){return Sr.set(s.id,s),()=>{Sr.get(s.id)===s&&Sr.delete(s.id);}}function av(s){Sr.delete(s);}function lv(){return [...Sr.values()].sort((s,e)=>(s.order??0)-(e.order??0))}var Cr=new Map;function cv(s,e){return Cr.set(s,e),()=>{Cr.get(s)===e&&Cr.delete(s);}}function dv(s){Cr.delete(s);}function hv(s){return {...Object.fromEntries(Cr),...s}}var fh=280,Ca=200,bh=640;function uv(s,e=Ca,t=bh){let n=Number.isFinite(e)&&e>0?e:Ca,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 gh(s){let e=s.title.trim().toLowerCase().replace(/\s+/g,"-");return `${s.instanceId}:${s.kind}:${e}#${s.ordinal}`}var vh="https://api.binance.com/api/v3",pv="https://api.binance.us/api/v3",Ta="https://fapi.binance.com/fapi/v1",mv="wss://stream.binance.com:9443",fv="wss://stream.binance.us:9443",bv="wss://fstream.binance.com";var yh={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"},xh={"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"},gv=[1,3,5,15,30,60,120,240,360,480,720],vv={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",360:"6h",480:"8h",720:"12h"},yv=["1","3","5","15","30","45","60","120","180","240","D","W","M"];function wh(s){return xh[s]??xh[s.toLowerCase()]??s}function Pa(s){let e=s.trim().toUpperCase();return e.endsWith(".P")?{apiSymbol:e.slice(0,-2),isFutures:true}:{apiSymbol:e,isFutures:false}}function Sh(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 xv(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 wv(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 Sv(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 Cv(s){return gv.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}var Wo=class{constructor(){this.spotBaseUrl=null;this.spotBaseProbe=null;this.symbolsPromise=null;}info(){return {name:"binance",displayName:"Binance",requiresApiKey:false,supportedTimeframes:yv,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let{apiSymbol:r,isFutures:i}=Pa(e),o=i?Ta:await this.spotBase(),a=wh(t),l=yh[a];if(l)return wv(Sh(await this.fetchKlines(o,r,l,n)));let c=/^\d+$/.test(a)?parseInt(a,10):null,d=c!=null?Cv(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=Sh(await this.fetchKlines(o,r,vv[d],u)),m=Sv(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}=Pa(e),r=n?Ta: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}=Pa(e),o=yh[wh(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?bv: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(xv(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")?fv:mv}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(`${Ta}/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 [vh,pv])try{if((await fetch(`${e}/ping`,{signal:AbortSignal.timeout(5e3)})).ok)return this.spotBaseUrl=e}catch{}return vh}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 Tv="https://api.hyperliquid.xyz/info",Pv="wss://api.hyperliquid.xyz/ws";var Ch={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"},Th={"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"},Mv=[1,3,5,15,30,60,120,240,480,720],Lv={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",60:"1h",120:"2h",240:"4h",480:"8h",720:"12h"},Ev=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],Ph={D:864e5,W:6048e5,M:2592e6};function kv(s){if(Ph[s])return Ph[s];let e=parseInt(s,10);return Number.isFinite(e)&&e>0?e*6e4:36e5}function Mh(s){return Th[s]??Th[s.toLowerCase()]??s}function Ma(s){let e=s.trim();return e.includes("/")?e:e.toUpperCase()}function La(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 Iv(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 Dv(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 Rv(s){return Mv.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}var Uo=class{constructor(){this.metaPromise=null;this.spotMetaPromise=null;this.symbolsPromise=null;}info(){return {name:"hyperliquid",displayName:"Hyperliquid",requiresApiKey:false,supportedTimeframes:Ev,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let r=Ma(e),i=Mh(t),o=Ch[i];if(o)return Iv((await this.fetchCandles(r,o,kv(i),n)).map(La));let a=/^\d+$/.test(i)?parseInt(i,10):null,l=a!=null?Rv(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,Lv[l],l*6e4,d)).map(La),u=Dv(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=Ma(e),r=(await this.fetchMeta().catch(()=>null))?.universe?.find(i=>i.name===t);if(r){let i=Eh(Math.max(0,6-(r.szDecimals??2)));return Lh(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=Eh(Math.max(0,8-(a?.szDecimals??2)));return Lh(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=Ma(e),i=Ch[Mh(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(Pv),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(La(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(Tv,{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 Lh(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 Eh(s){return Math.pow(10,-s)}var Av={now:()=>Date.now(),delay:s=>new Promise(e=>setTimeout(e,s))},Go=class{constructor(e,t,n=Av){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 Ea="https://api.exchange.coinbase.com",Ov="wss://ws-feed.exchange.coinbase.com",Fv={Accept:"application/json"},Bv=15e3,Vv=2e3,_v=5e3,Yo=300,Nv=4,Hv=120,zv=4,$v=600,Wv=400;function Uv(s,e){let t=Number(s.headers.get("retry-after"));return Number.isFinite(t)&&t>0?t*1e3:e}var kh={1:60,5:300,15:900,60:3600,360:21600,D:86400},Ih={"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"},Gv=[1,5,15,60,360,1440],Yv={1:60,5:300,15:900,60:3600,360:21600,1440:86400},Xv=["1","3","5","15","30","45","60","120","180","240","360","480","720","D","W","M"],ka=864e5;function Dh(s){return Ih[s]??Ih[s.toLowerCase()]??s}function Ia(s){return s.trim().toUpperCase()}function Kv(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 jv(s,e){return Rh(s,t=>Math.floor(t/e)*e)}function qv(s,e){return Rh(s,e==="W"?Zv:Jv)}function Rh(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 Zv(s){let e=new Date(s),t=(e.getUTCDay()+6)%7;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()-t)}function Jv(s){let e=new Date(s);return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)}function Qv(s){return Gv.filter(e=>e<s&&s%e===0).sort((e,t)=>t-e)[0]??null}function Ra(s,e){return e!=null&&s.length>e?s.slice(-e):s}var Xo=class{constructor(){this.symbolsPromise=null;this.gate=new Go(Nv,Hv);}info(){return {name:"coinbase",displayName:"Coinbase",requiresApiKey:false,supportedTimeframes:Xv,capabilities:{enumerate:true,stream:true,symbolInfo:true}}}async getBars(e,t,n){try{let r=Ia(e),i=Dh(t),o=kh[i];if(o)return Da(await this.fetchCandles(r,o,n));if(i==="W"||i==="M"){let u=i==="W"?7*ka:31*ka,p=n.from!=null?n:{...n,limit:n.limit!=null?Math.ceil(n.limit*u/ka)+31:void 0},m=await this.fetchCandles(r,86400,p);return Ra(qv(m,i),n.limit)}let a=/^\d+$/.test(i)?parseInt(i,10):null,l=a!=null?Qv(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,Yv[l],d);return Ra(jv(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=Ia(e),n=await this.json(`${Ea}/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=kh[Dh(t)];return r&&typeof WebSocket<"u"?this.streamTicker(e,t,r,n):this.pollBars(e,t,n)}async fetchProducts(){let e=await this.json(`${Ea}/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/Yo)+4;for(;a>0&&c-- >0;){let d=Math.min(a,Yo),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 Ra(Da(o),n)}async paginateForward(e,t,n,r,i){let o=t*1e3,a=[],l=n,c=Math.ceil((r-n)/(Yo*o))+4;for(;l<r&&c-- >0;){let h=Math.min(l+Yo*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(`${Ea}/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(Kv).sort((a,l)=>a.time-l.time)}streamTicker(e,t,n,r){let i=Ia(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 P=T[T.length-1];m=m&&m.time===P.time?{...P,high:Math.max(P.high,m.high),low:Math.min(P.low,m.low),close:m.close}:{...P},g();}catch{}},y=(C,T)=>{let P=Number(C);if(!Number.isFinite(P))return;let E=a(T);!m||E>m.time?(m={time:E,open:P,high:P,low:P,close:P,volume:0},g(),v(false)):E===m.time&&(m={...m,close:P,high:Math.max(m.high,P),low:Math.min(m.low,P)},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);}},w=()=>{l||p||(c=new WebSocket(Ov),h=setTimeout(x,Bv),c.onopen=()=>{try{c?.send(JSON.stringify({type:"subscribe",product_ids:[i],channels:["ticker"]}));}catch{}v(false),u=setInterval(()=>{v(false);},_v);},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(w,Vv));},c.onerror=()=>{try{c?.close();}catch{}});};return w(),()=>{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:Fv}));if(n.status===429&&t<zv){let r=$v*2**t+Math.random()*Wv;this.gate.pauseFor(Math.max(Uv(n,0),r));continue}if(!n.ok)throw new Error(`Coinbase HTTP ${n.status} for ${e}`);return n}}};
|
|
560
560
|
exports.ACCENT=xe;exports.ACCENT_BRIGHT=Kt;exports.BEARISH=X;exports.BULLISH=q;exports.BarStore=Gi;exports.BinanceProvider=Wo;exports.CATEGORICAL=Va;exports.CROSSHAIR=Ha;exports.CachingDataFeed=Kn;exports.CoinbaseProvider=Xo;exports.DARK_THEME=Ne;exports.DEFAULT_PANEL_MAX_WIDTH=bh;exports.DEFAULT_PANEL_MIN_WIDTH=Ca;exports.DEFAULT_PANEL_WIDTH=fh;exports.DataControl=jn;exports.Drawing=B;exports.DrawingStore=tn;exports.DrawingToolbar=fr;exports.DrawingsControl=qn;exports.HIGHLIGHT=_a;exports.HyperliquidProvider=Uo;exports.INFO=ze;exports.INVALID=Er;exports.LIGHT_THEME=Un;exports.MARKER=Na;exports.MultiProviderFeed=Ot;exports.NEUTRAL=pe;exports.NativeRenderer=vr;exports.RendererControl=Gn;exports.SERIES_LINE=En;exports.SESSION_OFF=hy;exports.SESSION_POST=dy;exports.SESSION_PRE=cy;exports.SLATE=kr;exports.SLATE_DEEP=za;exports.TRADE_EXIT=Ua;exports.TRADE_LONG=$a;exports.TRADE_SHORT=Wa;exports.TypedEventBus=ft;exports.VALID=Lr;exports.Vela=Sa;exports.WARNING=Ln;exports.buildColorPicker=an;exports.buildToolbar=Hn;exports.categoricalColor=uy;exports.chartType=Ke;exports.chartTypes=je;exports.clampPanelWidth=uv;exports.combineColor=Qn;exports.createDrawing=dt;exports.defaultToolbar=Nn;exports.deserializeDrawing=_e;exports.drawingTypes=Vi;exports.getDrawingType=ct;exports.getNativeIndicator=Mn;exports.iconMarkup=Dr;exports.legendActions=lv;exports.nativeIndicatorDescriptors=Pr;exports.nativeIndicatorTypes=Oa;exports.normalizeSettingsRow=zi;exports.registerChartType=as;exports.registerDefaultEngine=cv;exports.registerDrawingType=A;exports.registerIcon=R;exports.registerLegendAction=sv;exports.registerNativeIndicator=Yt;exports.registerRendererDefaults=ym;exports.registerRendererLayer=vg;exports.registerSidePanel=ev;exports.registerWidgetAction=rv;exports.registerWidgetAttachment=Zg;exports.rendererDefaults=cs;exports.rendererLayers=Qs;exports.resolveEngines=hv;exports.resolveTheme=nn;exports.settingsRowValueKeys=$n;exports.sharedBarStore=Yn;exports.sidePanels=nv;exports.splitColor=Je;exports.stableSeriesId=gh;exports.tickerModifierIds=ls;exports.timeframeToMs=zn;exports.unregisterChartType=hm;exports.unregisterDefaultEngine=dv;exports.unregisterLegendAction=av;exports.unregisterNativeIndicator=Aa;exports.unregisterRendererDefaults=xm;exports.unregisterRendererLayer=yg;exports.unregisterSidePanel=tv;exports.unregisterWidgetAction=iv;exports.unregisterWidgetAttachment=Jg;exports.widgetActions=ov;exports.widgetAttachments=Qg;return exports;})({});
|